Skip to main content

@flow-state-dev/core

Namespaces​

Classes​

DispatchRefusedError​

Thrown by a dispatcher block when the seam refuses. Carries the address and the refusal by name so a .rescue() can branch on it.

Extends​

  • Error

Constructors​

Constructor​
new DispatchRefusedError(
blockName,
address,
refused,
detail
): DispatchRefusedError;
Parameters​
blockName​

string

address​

DispatchAddress

refused​

DispatchRefusal

detail​

string

Returns​

DispatchRefusedError

Overrides​

Error.constructor

Properties​

address​
readonly address: DispatchAddress;
blockName​
readonly blockName: string;
cause?​
cause?: unknown;
Inherited from​

Error.cause

code​
readonly code: "dispatch-refused" = "dispatch-refused";
detail​
readonly detail: string;
message​
message: string;
Inherited from​

Error.message

name​
name: string;
Inherited from​

Error.name

refused​
readonly refused: DispatchRefusal;
stack?​
stack?: string;
Inherited from​

Error.stack


FlowConfigRefusalError​

What a refused config bag throws: the same message as before, plus the issues as data. Its name stays "Error", so nothing that reads the error as text sees a difference.

Extends​

  • Error

Constructors​

Constructor​
new FlowConfigRefusalError(message, issues): FlowConfigRefusalError;
Parameters​
message​

string

issues​

readonly FlowConfigIssue[]

Returns​

FlowConfigRefusalError

Overrides​

Error.constructor

Properties​

cause?​
cause?: unknown;
Inherited from​

Error.cause

issues​
readonly issues: readonly FlowConfigIssue[];

Every reason the bag was refused. Never empty.

message​
message: string;
Inherited from​

Error.message

name​
name: string;
Inherited from​

Error.name

stack?​
stack?: string;
Inherited from​

Error.stack


FlowError​

Author-throwable runtime error. Carries an optional machine-readable code, a retryable flag (default false), arbitrary structured details, and an optional underlying cause.

Extends​

  • Error

Extended by​

Constructors​

Constructor​
new FlowError(message, options?): FlowError;
Parameters​
message​

string

options?​

FlowErrorOptions

Returns​

FlowError

Overrides​

Error.constructor

Properties​

blockInstanceId?​
readonly blockInstanceId?: string;
blockName?​
readonly blockName?: string;
cause?​
readonly cause?: unknown;
Overrides​

Error.cause

code?​
readonly code?: string;
details?​
readonly details?: Record<string, unknown>;
message​
message: string;
Inherited from​

Error.message

name​
name: string;
Inherited from​

Error.name

retryable​
readonly retryable: boolean;
scope?​
readonly scope?: FlowErrorScope;
stack?​
stack?: string;
Inherited from​

Error.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


OutputValidationError​

Author-throwable runtime error. Carries an optional machine-readable code, a retryable flag (default false), arbitrary structured details, and an optional underlying cause.

Extends​

Constructors​

Constructor​
new OutputValidationError(
message,
details,
cause?
): OutputValidationError;
Parameters​
message​

string

details​

OutputValidationDetails

cause?​

unknown

Returns​

OutputValidationError

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: OutputValidationDetails;
Overrides​

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


RecordedValueOmittedError​

Fatal, non-retryable resume error: the request needs a value its record holds only as a placeholder. Running the block again could repeat its side effects, so the request fails, naming the block. The fix is in the block: return less from it (paths and sizes, ids, a reference), or move bulk data between steps through a sequencer's .map.

Extends​

Constructors​

Constructor​
new RecordedValueOmittedError(blockName, omitted): RecordedValueOmittedError;
Parameters​
blockName​

string

omitted​

Pick<OmittedValue, "bytes">

Returns​

RecordedValueOmittedError

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: RecordedValueOmittedDetails;
Overrides​

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


RouteUnavailableError​

Fatal, non-retryable resume error: the recorded router decision cannot be honored on continuation. See RouteUnavailableDetails for which of the two causes (re-decision drift vs. removed route) applies.

Extends​

Constructors​

Constructor​
new RouteUnavailableError(details): RouteUnavailableError;
Parameters​
details​

RouteUnavailableDetails

Returns​

RouteUnavailableError

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: RouteUnavailableDetails;
Overrides​

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


SequencerOutputSchemaError​

Thrown by the sequencer runtime when the composed output fails the declared outputSchema. rawOutput is the actual (typed JS) value that failed — unlike OutputValidationError, which carries raw LLM text.

Extends​

Constructors​

Constructor​
new SequencerOutputSchemaError(
message,
details,
cause?
): SequencerOutputSchemaError;
Parameters​
message​

string

details​

SequencerOutputSchemaErrorDetails

cause?​

unknown

Returns​

SequencerOutputSchemaError

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: SequencerOutputSchemaErrorDetails;
Overrides​

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


SequencerSchemaMismatchError​

Thrown by SequencerDefinition.validate() when the declared outputSchema and the chain's inferred output schema disagree structurally (top-level kind, object key set, one level of value kinds, or array element kind).

Extends​

Constructors​

Constructor​
new SequencerSchemaMismatchError(message, details): SequencerSchemaMismatchError;
Parameters​
message​

string

details​

SequencerSchemaMismatchErrorDetails

Returns​

SequencerSchemaMismatchError

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: SequencerSchemaMismatchErrorDetails;
Overrides​

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


StrictSchemaError​

Author-throwable runtime error. Carries an optional machine-readable code, a retryable flag (default false), arbitrary structured details, and an optional underlying cause.

Extends​

Constructors​

Constructor​
new StrictSchemaError(violations, label?): StrictSchemaError;
Parameters​
violations​

StrictViolation[]

label?​

string

Returns​

StrictSchemaError

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: object;
violations​
violations: StrictViolation[];
Overrides​

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

Accessors​

violations​
Get Signature​
get violations(): StrictViolation[];

The strict-mode incompatibilities found, each with its path and reason. Delegates to details.violations so the data has a single home.

Returns​

StrictViolation[]

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


VoiceError​

Discriminated voice error. Thrown by VoiceProvider method implementations and createCompositeVoiceProvider.

Extends​

  • Error

Constructors​

Constructor​
new VoiceError(options): VoiceError;
Parameters​
options​

VoiceErrorOptions

Returns​

VoiceError

Overrides​

Error.constructor

Properties​

cause?​
cause?: unknown;
Inherited from​

Error.cause

kind​
readonly kind: VoiceErrorKind;
message​
message: string;
Inherited from​

Error.message

name​
name: string;
Inherited from​

Error.name

provider​
readonly provider: string;
retryable​
readonly retryable: boolean;
stack?​
stack?: string;
Inherited from​

Error.stack

status?​
readonly status?: number;

Interfaces​

ActionMcpConfig​

Per-action overrides for MCP exposure. The flow-level mcp.enabled decides participation; per-action enabled: false opts an action out of exposure, and name overrides the auto-derived tool name.

Properties​

enabled?​
enabled?: boolean;

If false, the action is excluded from MCP exposure even when its flow has mcp.enabled: true. Default: true (action is exposed when its flow exposes it).

name?​
name?: string;

Optional override for the MCP tool name. When omitted, the tool name is derived deterministically from the action key (recordPayment → record_payment). Names must match the MCP charset [A-Za-z0-9_.-]{1,128}.

session?​
session?:
| string
| {
fromInput: string;
};

How the MCP adapter derives the dispatch sessionId for this action. MCP is sessionless — by default every tools/call runs in a fresh one-off session the adapter makes (oneOffSessionId()). This directive lets a specific action reuse or hand out a session id, so a client can group related calls together.

  • Omitted (default): stateless — every tools/call runs in a fresh one-off session.
  • string: a template for a freshly minted id. Only the FIRST * is replaced by a random token ("conv_*" → "conv_1784…_a1b2"; extra * stay literal); with no * the token is appended. Use to hand the caller a reusable id whose prefix names the concept (e.g. a "conversation").
  • { fromInput: <field> }: use the string value at input.<field> as the sessionId, so a caller-supplied id groups calls into one session.

Security: fromInput reads model-supplied input as a flow session key (not the protocol Mcp-Session-Id, and never an auth/routing decision — the principal still comes from resolvePrincipal). Because the id is a bare, caller-controlled session key, { fromInput } is safe only under a single server-trusted principal until caller-supplied keys are namespaced by principal: in a multi-user flow a caller could name another user's session id (the framework's user-binding check blocks the run, but bound the field length in your schema and namespace keys before exposing this to mutually-distrusting users). See the MCP server docs.


BlockContext​

Type Parameters​

TRequestState​

TRequestState extends object = Record<string, unknown>

TSessionState​

TSessionState extends object = Record<string, unknown>

TUserState​

TUserState extends object = Record<string, unknown>

TOrgState​

TOrgState extends object = Record<string, unknown>

TResources​

TResources extends Record<string, AnyResourceRef> = Record<string, AnyResourceRef>

TSequencerState​

TSequencerState extends object = Record<string, unknown>

TParentInput​

TParentInput = unknown

TTargets​

TTargets extends Record<string, ZodTypeAny> | undefined = Record<string, ZodTypeAny>

TCapabilities​

TCapabilities extends Record<string, Record<string, (...args) => any>> = { }

TSelfState​

TSelfState extends object = Record<string, unknown>

TParentState​

TParentState extends object = Record<string, unknown>

TFlowConfig​

TFlowConfig extends object = Readonly<Record<string, unknown>>

Properties​

attempt?​
attempt?: number;

0-indexed retry attempt for the currently-executing block. Starts at 0 for the initial invocation and increments per retry. Handlers can use this to drive idempotent behavior (see runOnce).

cap​
cap: TCapabilities;

Capability helper functions, keyed by capability name. Each capability's fns(ctx) result is memoized on first access.

emit​
emit: object;

Namespaced emission API for client-visible items.

ctx.emit.trace.* is reserved for framework auto-emitters of the four trace item types and rarely called by user code.

data​
data: (dataType, value, options?) => void;

Emit a data item: structured content at this point in the conversation. Code reads it back by dataType; a client draws it only when it registers a renderer for that dataType (generative UI is a dataType with a renderer).

Defaults to transient: false (persisted). Reaches the client and not model history unless itemVisibility says otherwise; an enclosing generator's visibility is not inherited.

A stable key gives the keyed-snapshot (upsert) semantics: one entry per (requestId, key), value replaced on each emission. See apps/docs/docs/streaming/emitting-items.md for the transient × key matrix.

Parameters​
dataType​

string

value​

Record<string, unknown>

options?​

EmitDataOptions

Returns​

void

message​
message: {
(text, options?): void;
(content, options?): void;
};

Emit a chat message item.

Defaults to transient: false (persisted) regardless of the producing block's transient flag. Pass { transient: true } to opt in to a stream-only message.

See apps/docs/docs/streaming/emitting-items.md for the transient × key matrix.

Call Signature​
(text, options?): void;
Parameters​
text​

string

options?​

EmitMessageOptions

Returns​

void

Call Signature​
(content, options?): void;
Parameters​
content​

Content[]

options?​

EmitMessageOptions

Returns​

void

status​
status: (message, options?) => void;

Update the request-scoped status slot. Rendered by clients as a single in-flight indicator ("what is happening right now").

  • message as a string (including "") sets the slot; dedupe suppresses re-emission when the value is unchanged.
  • message as undefined preserves the slot value — useful when updating only blocked / sideChainTasks signals.

Defaults to transient: true (live-only) — statuses are naturally ephemeral. Pass { transient: false } to persist a status item.

Parameters​
message​

string | undefined

options?​
blocked?​

boolean

sideChainTasks?​

number

transient?​

boolean

Returns​

void

flow​
flow: FlowContextView<TFlowConfig>;

The flow copy this block is running in, narrowed to its create-time config bag — ctx.flow.config and nothing else.

ctx.settings is the whole process, one shape for every flow in it; this is the per-copy sibling: two registered copies of one definition read different values here. Fixed when the copy was created and frozen for its life — anything a block would WRITE belongs in instance-isolated state, not here.

Typed from this block's own flowConfigSchema, which also makes the flow refuse when it cannot supply what the block declared. A block that declares nothing reads an open read-only record and parses for itself.

idempotencyKey?​
idempotencyKey?: string;

Stable idempotency key for the currently-executing block. Derived from ${requestId}:${blockPath} and intentionally excludes attempt so the value is identical across retries of the same logical step within a request. Suitable for passing directly to external APIs that accept an idempotency key (e.g. Stripe's Idempotency-Key header).

Cross-request de-dup is out of scope: retryRequest creates a new request ID and therefore a new key. Use a user-controlled external key if cross-request idempotency is required.

org?​
org?: OrgScopeHandle<TOrgState>;
parent?​
parent?: object & Partial<StateRef<TParentState>>;

The immediate parent block in the execution chain, if any. Provides the parent's name, kind, and the input it was called with. Useful when a nested block (e.g. a step inside a sequencer, a tool block inside a generator, or a route inside a router) needs the original input that triggered its parent.

When this block declares parentStateSchema and the parent has its own stateSchema, ctx.parent also carries the parent's state operations — a child writes its owner's state without naming it (e.g. a generator's activation tool writing ctx.parent.pushState(...)). Absent (guard with ?.) when the parent declares no own state.

Type Declaration​
input​
input: TParentInput;
kind​
kind: BlockKind;
name​
name: string;
request​
request: RequestScopeHandle<TRequestState>;
requestRuntime?​
requestRuntime?: object;

Runtime metadata for the current request. Available during server-side execution; undefined in test harnesses or static analysis contexts. Blocks can use this to access client-supplied metadata (e.g., voice settings) passed through sendAction.

metadata?​
metadata?: Record<string, unknown>;
resolveModel​
resolveModel: ModelResolver;
resources​
resources: ResourceRegistry<TResources>;

Flat resource registry — every resource declared by this block, the flow it lives in, or any capability it uses, accessible by its accessor key. The resource's intrinsic scope (set on defineResource) routes reads/writes to the right storage layer; consumers don't need to know which scope a resource lives in. Replaces the legacy per-scope ctx.session.resources.* / ctx.user.resources.* / ctx.org.resources.* accessors.

response​
response: ResponseEmitterHandle;
self?​
self?: StateRef<TSelfState>;

This block's own request-scoped state, if it declared stateSchema. Undefined when the block declares no own state. Namespaced by the block itself, so a field can be named freely with no cross-block collision worry. Read anywhere; write is meaningful for blocks with an execute (handlers, sequencer callbacks) — generators read it in config functions.

Routers should treat ctx.self as read-only in their selector: a durable router's execute re-runs on resume (see execution-and-errors.md's suspendable-router purity contract), so a preceding .tap(handler) should perform the write instead.

sequencer?​
sequencer?: StateRef<TSequencerState>;
session​
session: SessionScopeHandle<TSessionState>;
settings​
settings: FlowStateSettings;

Instance-level settings declared on createFlowState({ settings }). Read-only. Typed via declaration merging into FlowStateSettings.

signal​
signal: AbortSignal;
suspendForUser​
suspendForUser: SuspendForUser;

Stop the request until the user answers: an approval, a review or an input. Returns the answer, or { cancelled: true } when the task was cancelled while it waited; at a review's or an input's deadline it throws SuspensionTimeoutError, and an approval reads as a no. A stop with no deadline takes the host's setting for a user's stop, else waits until answered, stopped or cancelled. Needs durable execution, as suspend does. See types/suspend-for-user.ts.

targets​
targets: InferTargetStatesFromSchemas<TTargets>;
tokenCounter?​
tokenCounter?: TokenCounter;

The flow's token counter: defineFlow({ tokenCounter }), else core's estimateTokenCounter. The same counter the engine packs history with, so a block that budgets tokens counts them the way the flow does. Absent outside an engine run (a mock context); fall back to estimateTokenCounter.

user​
user: UserScopeHandle<TUserState>;
view?​
view?: ViewRunContext;

In a view's run, the change it may answer for and the call that answers for just those rows (ctx.view.partial). Absent outside a view.

Methods​

getBlockOutput()​
getBlockOutput<TBlock>(block): BlockOutput<TBlock> | undefined;
Type Parameters​
TBlock​

TBlock extends BlockDefinition<ZodTypeAny, ZodTypeAny, any, any>

Parameters​
block​

TBlock

Returns​

BlockOutput<TBlock> | undefined

getBlockResult()​
getBlockResult<TBlock>(block): BlockResult<BlockOutput<TBlock>>;
Type Parameters​
TBlock​

TBlock extends BlockDefinition<ZodTypeAny, ZodTypeAny, any, any>

Parameters​
block​

TBlock

Returns​

BlockResult<BlockOutput<TBlock>>

getTarget()​
getTarget<TState>(name): StateRef<TState> | undefined;
Type Parameters​
TState​

TState extends object = Record<string, unknown>

Parameters​
name​

string

Returns​

StateRef<TState> | undefined

runOnce()?​
runOnce?<T>(key, fn): Promise<T>;

Execute fn once per (requestId, userKey) and memoize the result on the request store. Subsequent calls — whether triggered by a block retry or a re-entry within the same request — return the persisted value without re-executing fn. The user-supplied key is the dedup unit, namespaced under the current request.

Concurrent in-process calls with the same key share a single inflight promise so the wrapped side effect cannot fire twice in a race.

Scope is per-request: a fresh requestId (including the one created by a retryRequest recovery dispatch) starts with an empty key space. Results must be JSON-serializable; non-serializable values throw.

Type Parameters​
T​

T

Parameters​
key​

string

fn​

() => Promise<T>

Returns​

Promise<T>

saveCheckpoint()?​
saveCheckpoint?(): Promise<void>;

Manually save a checkpoint at the current execution point. Normally checkpoints are automatic at sequencer step boundaries; this is for blocks that perform expensive work within a single step and want finer-grained recovery.

Only available in durable contexts.

Returns​

Promise<void>

suspend()?​
suspend?(options): Promise<unknown>;

Suspend execution and wait for external input. On first call, throws a SuspensionError that the sequencer catches at the step boundary. On resume, returns the resume data instead of throwing.

Only callable inside a block that runs within a durable sequencer. Throws if called outside a durable context.

Parameters​
options​

SuspendOptions

Returns​

Promise<unknown>

wasRescued()​
wasRescued(target): boolean;

Returns whether target — a prior block in the current sequencer scope — recovered an error through its own .rescue() handler during its execution. The flag is set on the block that owns the .rescue() (e.g. a sub-sequencer wrapping a risky step), so query that block, not the inner step that threw. target is a block name or definition (resolved via block.name).

Scope and resolution match getBlockResult: only blocks that ran as prior siblings in the current sequencer run are visible, and under .loopBack the most recent (current-iteration) run of a named block is consulted.

Returns false when the block ran without rescuing, was never dispatched (e.g. skipped by .stepIf), is not found in the current scope, or when called outside a sequencer. Never throws.

Parameters​
target​

| string | BlockDefinition<any, any, any, any>

Returns​

boolean


BlockDefinition​

Public block surface — what user code holds and passes around.

Deliberately omits the dispatch entry point. Substrate code (executor, sequencer, router, generator tool loop, CLI) sees the runtime view via BlockRuntime and uses asRuntime() to recover it at the boundary. Removing run from the public type makes block.run(input, ctx) from inside a handler's execute a TypeScript error — handlers never call blocks, enforced at the type system instead of at convention.

Extended by​

Type Parameters​

TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

TOutputSchema​

TOutputSchema extends ZodTypeAny = ZodTypeAny

TInput​

TInput = z.infer<TInputSchema>

TOutput​

TOutput = z.infer<TOutputSchema>

Properties​

childBlocks?​
childBlocks?: readonly BlockDefinition<any, any, any, any>[];

Every block this block statically composes: a sequencer's step/tap/branch children and its chain-level rescue handlers, a router's routes, a rescue handler installed on any block.

Exists so the block graph is walkable at definition time. A SequencerOperation is {name, run} — the child it dispatches is captured inside a closure and retained nowhere else — so before this field the sequencer edge was opaque and a traversal from an action root could not see past the first .step(). Since a task board's drain is a sequencer, that made "every reachable detached board resolves to a binding" not merely unchecked but uncomputable. defineFlow walks this to assert it.

Retained for structure only — nothing executes through it. Dispatch still runs the operation closures.

config​
config: BlockConfig<TInputSchema, TOutputSchema, TInput, TOutput>;
declaredResources?​
declaredResources?: DeclaredResources;
description?​
description?: string;
dispatch?​
dispatch?: DispatchAddress;

The address this block dispatches to, when it is a dispatcher.

Stamped by dispatcher() (and by the task board on its dispatch block) and carried across every rebuild path, so defineFlow can walk the graph and refuse an address that resolves no entry, and a board can read which of its assignees dispatch without running anything. undefined on every block that dispatches nothing, which is every block that computes.

inputSchema​
inputSchema: TInputSchema;
kind​
kind: BlockKind;
name​
name: string;
outputSchema​
outputSchema: TOutputSchema;
ownDeclaredResources?​
ownDeclaredResources?: DeclaredResources;

This block's OWN declared resources: its own resources config plus its own capability-injected resources, EXCLUDING resources that bubble up from descendant/child blocks. Where declaredResources is the bubble-up (this block + all descendants), ownDeclaredResources is the strict subset this block itself contributes. For leaf blocks (handler/generator) the two are identical; for composites (sequencer/router) it omits children's declarations so the block-dispatch prefetch hook can load only this block's own declarations without re-loading children's.

staticTools?​
staticTools?: readonly BlockDefinition<any, any, any, any>[];

A generator's authored static tools array, kept for the definition-time walk. generator() rewrites config.tools into one async resolver when a capability contributes tools, which hides the authored array from a walk that reads config.tools; this field keeps the tool edge walkable either way. Absent when tools was omitted or authored as a function.

Retained for structure only — the model is offered what config.tools resolves to.

transient​
transient: boolean;

Methods​

as()​
as(options): BlockDefinition<TInputSchema, TOutputSchema, TInput, TOutput>;

Return a copy of this block under a new name, a new description, or both. Everything else is the same block: schemas, connectors, resources, capabilities, rescue handlers and the model-output mapper ride the copy.

The new name is the copy's only name: the model calls it by that name, and its items, trace rows, errors and resume points carry it. The original block is not changed. An omitted option keeps the original's value; a blank name is refused when the copy is built.

Unlike asTool, .as() adds nothing at run time — no wrapper and no extra tool_output. The two stack: block.as({ name }).asTool() shows a tool pill under the new name, while block.asTool().as({ name }) renames only the wrapper and the pill keeps the original name.

Returns a plain block definition, so on a sequencer finish adding steps first and rename last.

Known limitation: a copy of a dispatcher() block still names its dispatches and dispatch refusals with the original name.

Parameters​
options​

BlockAsOptions

Returns​

BlockDefinition<TInputSchema, TOutputSchema, TInput, TOutput>

asTool()​
asTool(opts?): BlockDefinition<TInputSchema, TOutputSchema, TInput, TOutput>;

Wrap this block so that, when executed inside a sequencer step, it emits a tool_output item with the same envelope and lifecycle the AI SDK tool-loop wrapper produces inside generators. The wrapped block runs normally and returns its typed output unchanged.

Use this when a tool has been moved out of an LLM-driven loop into a deterministic prefetch (e.g. inside a .parallel({...}) step) and the transcript should keep showing it as a tool pill.

Attribution (itemVisibility, agentName) is supplied via opts; when omitted the fields are not stamped on the emitted item.

Parameters​
opts?​

AsToolOpts

Returns​

BlockDefinition<TInputSchema, TOutputSchema, TInput, TOutput>

connectInput()​
connectInput<TFrom>(mapper): BlockDefinition<ZodTypeAny, TOutputSchema>;
Type Parameters​
TFrom​

TFrom

Parameters​
mapper​

ConnectorFn<TFrom, TInput>

Returns​

BlockDefinition<ZodTypeAny, TOutputSchema>

connectOutput()​
connectOutput<TTo>(mapper): BlockDefinition<TInputSchema, ZodTypeAny>;
Type Parameters​
TTo​

TTo

Parameters​
mapper​

(output, ctx) => TTo | Promise<TTo>

Returns​

BlockDefinition<TInputSchema, ZodTypeAny>

mapModelOutput()​
mapModelOutput(mapper): BlockDefinition<TInputSchema, TOutputSchema>;

Declare a separate, model-visible representation of this block's output for use when the block is installed as a tool on a generator. The mapper fires only at the AI SDK bridge boundary, producing the string the LLM observes on its next turn.

The structured TOutput continues to flow through the block graph unchanged: tool_output items, downstream sequencer steps, devtool, tests, and replay all see the original value. Both TInputSchema and TOutputSchema are preserved.

The mapper is a property of the block definition. When the block is used as a regular sequencer step (not via tools: [...]), the mapper is silently inert.

The mapper is expected to be deterministic: history replay re-runs it rather than persisting its string output. A non-deterministic formatter would produce different strings between original turn and replay.

Parameters​
mapper​

(output, ctx) => string | Promise<string>

Returns​

BlockDefinition<TInputSchema, TOutputSchema>

rescue()​
rescue(handlers): BlockDefinition<TInputSchema, TOutputSchema, TInput, TOutput>;

Return a copy of this block that recovers from its own failures. If the block throws a non-SuspensionError, the first handler whose when matches runs — receiving the thrown error, with the same scoped context the block executed in (so it can read sequencer state) — and its output is returned in place of the throw. The enclosing sequencer chain, forEach fan-out, parallel branch, or router route therefore continues to the next step. ctx.wasRescued(block) reports true afterwards.

Available on every block kind. A leaf step recovers and the chain continues; a whole sequencer recovers as a unit (the steps after the failure have already unwound) — the same behavior as SequencerDefinition.rescue(), which is the chain-level spelling.

Parameters​
handlers​

RescueHandlerSpec[]

Returns​

BlockDefinition<TInputSchema, TOutputSchema, TInput, TOutput>


CachingConfig​

Normalized caching config carried on a generator block and passed through the ModelCallOptions to the AI SDK adapter. Every field is optional so users can override just the axis they care about; defaults are documented in @flow-state-dev/core DEFAULT_CACHING_CONFIG.

Properties​

breakpoints?​
breakpoints?: CachingBreakpointMode;

auto — adapter decides breakpoint placement. manual — adapter passes user-supplied cacheControl through untouched. Default auto.

enabled?​
enabled?: boolean;

Emit cache markers at all. Default true.

ttl?​
ttl?: CachingTtl;

Ephemeral tier for Anthropic markers. Default 5m.


CompositeVoiceProviderConfig​

Slot configuration for createCompositeVoiceProvider.

Properties​

listVoices?​
listVoices?: VoiceProvider;

Provider that owns the listVoices ability.

speak?​
speak?: VoiceProvider;

Provider that owns the speak ability.

speakStream?​
speakStream?: VoiceProvider;

Provider that owns the speakStream ability. If omitted, the speak provider is used when it advertises speakStream; otherwise streaming is unavailable.

transcribe?​
transcribe?: VoiceProvider;

Provider that owns the transcribe ability.


ConcurrencyKeyContext​

Minimal, serializable view of a dispatch passed to a custom ConcurrencyKey function. Carries only the request-derived coordinates a key derivation could reasonably need — not the full envelope — so a custom key stays a pure function of dispatch identity.

Properties​

actionName​
actionName: string;
flowKind​
flowKind: string;
metadata?​
metadata?: Record<string, unknown>;
orgId?​
orgId?: string;
sessionId​
sessionId: string;

The run's session: every dispatch names one, a one-off run's included.

source?​
source?: string;
tenantId?​
tenantId?: string;
userId​
userId: string;

ConfiguredCapability​

The branded capability type returned by defineCapability().

At runtime, the presets property from CapabilityConfig is replaced by a builder method. The raw preset data is still accessible internally via __presetDefs. DefinedCapability doesn't extend CapabilityConfig directly because the presets property changes from data to a method.

Extends​

  • DefinedCapability<TName, TFns, TPresetNames, TPresets, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema>

Type Parameters​

TName​

TName extends string = string

TFns​

TFns extends Record<string, (...args) => any> = Record<string, (...args) => any>

TPresetNames​

TPresetNames extends string = string

TPresets​

TPresets extends Record<string, PresetDef | string[]> = Record<string, PresetDef>

TSessionStateSchema​

TSessionStateSchema extends ZodTypeAny | undefined = undefined

TResources​

TResources extends | Record<string, DeclaredResourceEntry> | undefined = undefined

TTargetSchemas​

TTargetSchemas extends Record<string, ZodTypeAny> | undefined = undefined

TSequencerStateSchema​

TSequencerStateSchema extends ZodTypeAny | undefined = undefined

TOwnStateSchema​

TOwnStateSchema extends ZodTypeAny | undefined = undefined

Properties​

__brand​
readonly __brand: "Capability";

Brand — set by defineCapability() to identify capability objects.

Inherited from​

DefinedCapability.__brand

__configInType?​
readonly __configInType?: unknown;

Type-only carrier for the .config() argument type. Set by defineCapability to z.input of the config schema (or the explicit schemaless type), or never when the capability declares no config. Holds no runtime value.

Inherited from​

DefinedCapability.__configInType

__presetDefs?​
readonly __presetDefs?: TPresets & object;

Raw preset definitions. Set internally by defineCapability().

Type Declaration​
default?​
default?: string[];
Inherited from​

DefinedCapability.__presetDefs

__presetOverrides​
readonly __presetOverrides: PresetOverrides<TPresetNames, TPresets>;
fns?​
fns?: (ctx) => TFns;
Parameters​
ctx​

BlockContext

Returns​

TFns

Inherited from​

DefinedCapability.fns

itemVisibility?​
itemVisibility?:
| ItemVisibility
| readonly ItemVisibility[];

Allowlist of block itemVisibility this capability attaches to. See CapabilityConfig.itemVisibility.

Inherited from​

DefinedCapability.itemVisibility

name​
readonly name: TName;
Inherited from​

DefinedCapability.name

orgStateSchema?​
orgStateSchema?: ZodTypeAny;
Inherited from​

DefinedCapability.orgStateSchema

requestStateSchema?​
requestStateSchema?: ZodTypeAny;
Inherited from​

DefinedCapability.requestStateSchema

resources?​
resources?: TResources extends Record<string, DeclaredResourceEntry> ? TResources : Record<string, DeclaredResourceEntry>;
Inherited from​

DefinedCapability.resources

resourcesType?​
readonly resourcesType?: unknown;
Inherited from​

DefinedCapability.resourcesType

sequencerStateSchema?​
sequencerStateSchema?: TSequencerStateSchema extends ZodTypeAny ? TSequencerStateSchema : ZodTypeAny;
Inherited from​

DefinedCapability.sequencerStateSchema

sequencerStateType?​
readonly sequencerStateType?: unknown;
Inherited from​

DefinedCapability.sequencerStateType

sessionStateSchema?​
sessionStateSchema?: TSessionStateSchema extends ZodTypeAny ? TSessionStateSchema : ZodTypeAny;
Inherited from​

DefinedCapability.sessionStateSchema

sessionStateType?​
readonly sessionStateType?: unknown;

Type-only escape hatch carriers. These fields hold no runtime value; InferCapability* utilities read them via infer to override the type derived from the corresponding schema. Useful when the schema infers to a shape that's too loose for consumer ctx (e.g. z.record(z.any())).

Inherited from​

DefinedCapability.sessionStateType

stateSchema?​
stateSchema?: TOwnStateSchema extends ZodTypeAny ? TOwnStateSchema : ZodTypeAny;

Own-state contribution — see PresetDef.stateSchema.

Inherited from​

DefinedCapability.stateSchema

stateSchemaType?​
readonly stateSchemaType?: unknown;
Inherited from​

DefinedCapability.stateSchemaType

targetStateSchemas?​
targetStateSchemas?: TTargetSchemas extends Record<string, ZodTypeAny> ? TTargetSchemas : Record<string, ZodTypeAny>;
Inherited from​

DefinedCapability.targetStateSchemas

targetStatesType?​
readonly targetStatesType?: unknown;
Inherited from​

DefinedCapability.targetStatesType

userStateSchema?​
userStateSchema?: ZodTypeAny;
Inherited from​

DefinedCapability.userStateSchema

uses?​
uses?: UsesSlot;
Inherited from​

DefinedCapability.uses

Methods​

config()​
config<Self>(this, value): ConfiguredCapability<TName, TFns, TPresetNames, TPresets, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema> & PreserveCarriers<Self>;

Apply typed open configuration declared via defineCapability({ config }). Returns a new configured reference (does not mutate the original), one hop from the base so diamond dedup still works. Composes with .presets() in either order. A compile error on a capability that declares no config (__configInType is never).

Type Parameters​
Self​

Self

Parameters​
this​

Self

value​

ConfigArgOf<Self>

Returns​

ConfiguredCapability<TName, TFns, TPresetNames, TPresets, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema> & PreserveCarriers<Self>

Inherited from​

DefinedCapability.config

presets()​
presets<Self>(this, overrides): ConfiguredCapability<TName, TFns, TPresetNames, TPresets, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema> & PreserveCarriers<Self>;

Configure which presets are active. Returns a new capability reference with the overrides recorded (does not mutate the original). Uses Object.create() to preserve base reference identity for diamond dedup.

Polymorphic over this so escape-hatch carriers (and any .config() argument type) survive the chain — .presets().config() keeps both.

Type Parameters​
Self​

Self

Parameters​
this​

Self

overrides​

PresetOverrides<TPresetNames, TPresets>

Returns​

ConfiguredCapability<TName, TFns, TPresetNames, TPresets, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema> & PreserveCarriers<Self>

Inherited from​

DefinedCapability.presets

with()​
with<Self>(this, bag): ConfiguredCapability<TName, TFns, TPresetNames, TPresets, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema> & PreserveCarriers<Self>;

Normalized consumer builder — collapses .config() and .presets() into one flat call. Preset-named keys become preset overrides; the rest become the config value. .with({ allowed, dynamicActivation: true }) is exactly .config({ allowed }).presets({ dynamicActivation: true }).

The argument is the config input intersected with the (all-optional) preset overrides. When the capability declares no config, the config half collapses away, so .with() accepts preset overrides alone; when it declares no presets, the preset half is empty, so .with() accepts the config value alone (including a scalar/array config, routed wholesale at runtime). Composes with .config()/.presets() and preserves escape-hatch carriers.

Type Parameters​
Self​

Self

Parameters​
this​

Self

bag​

WithArg<Self, TPresetNames, TPresets>

Returns​

ConfiguredCapability<TName, TFns, TPresetNames, TPresets, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema> & PreserveCarriers<Self>

Inherited from​

DefinedCapability.with


CostEstimate​

Properties​

byModel​
readonly byModel: Record<string, number>;
totalUSD​
readonly totalUSD: number;

CostEstimator​

Methods​

estimate()​
estimate(usage, model): number;
Parameters​
usage​

ModelUsageEntry

model​

string

Returns​

number


CreateModelResolverOptions​

Options for createModelResolver.

Properties​

defaultModel?​
defaultModel?: string;

Required when CreateModelResolverOptions.intents is non-empty. The model string returned when an intent has no available candidate, an unknown intent is referenced, or an intent's list is empty. Must be a valid model string (provider/model or name:model — never intent/*).

env?​
env?: Record<string, string | undefined>;

Optional env-var source for intent overrides. Defaults to process.env. Tests and library callers can pass an explicit object to avoid mutating the global environment.

Reads at construction time only — never per-call. See the Env-var overrides section in the package README for the variable naming convention.

gateways?​
gateways?: Record<string, unknown>;

Gateway instances or configurations. Keys are gateway names (e.g., "vercel", "openrouter"), and each key is a route name for name:model strings ("vercel:openai/gpt-6.1-sol"). A key may not also be a key of providers. Pass a pre-created instance for bundled environments (Next.js): gateways: { vercel: createGateway({ apiKey }) } Or a config object for auto-detection: gateways: { vercel: { type: "vercel", apiKey: "..." } }

intentDefaults?​
intentDefaults?: Record<string, IntentDefaults>;

Optional per-intent defaults. Keys must match a key in intents. When a candidate from intents[name] wins resolution, the resolver applies intentDefaults[name] to the request before the generator's own providerOptions overrides it.

Construction throws if a key in intentDefaults is not also present in intents. Applies only on successful candidate resolution — when an intent falls through to defaultModel, no intent defaults apply (defaultModel has no associated intent context).

intents?​
intents?: Record<string, string[]>;

Map of intent name → ordered candidate model strings.

keys?​
keys?: Partial<Record<string, string>>;

Explicit API keys. Overrides env var detection.

providerPreference?​
providerPreference?: ProviderPreference;

Default provider preference applied to intent resolution. See ProviderPreference. Stable-reorders each intent's candidate list by provider bucket before availability filtering — preferred providers first (in the order given), remaining models after in their original order. Omit to preserve the intent author's ordering.

providers?​
providers?: Record<string, unknown>;

AI SDK provider instances. Keys are provider prefixes used in model strings, both name/model and the pinned name:model ("triage:native"). A key may not also be a key of gateways, nor vercel or openrouter. If omitted, auto-creates providers from env vars.

retryPolicy?​
retryPolicy?: ModelRetryPolicy;

Retry policy for fallback arrays and intents.


CreateToolCacheCapabilityOptions​

Properties​

defaultScope?​
defaultScope?: "request" | "session" | "run";

Default scope for entries that don't specify one. Default "run".

defaultTtl?​
defaultTtl?: number;

Default TTL (ms) for entries that don't specify one. Default 5 minutes.

maxEntries?​
maxEntries?: number;

Max entries before LRU eviction. Default 5000.

name?​
name?: string;

Override the capability name. Defaults to "toolCache". The Task Board wiring passes a board-scoped name (e.g. toolCache_<boardName>) so multiple boards in one flow don't collide.


DefinedCapability​

The branded capability type returned by defineCapability().

At runtime, the presets property from CapabilityConfig is replaced by a builder method. The raw preset data is still accessible internally via __presetDefs. DefinedCapability doesn't extend CapabilityConfig directly because the presets property changes from data to a method.

Extended by​

Type Parameters​

TName​

TName extends string = string

TFns​

TFns extends Record<string, (...args) => any> = Record<string, (...args) => any>

TPresetNames​

TPresetNames extends string = string

TPresets​

TPresets extends Record<string, PresetDef | string[]> = Record<string, PresetDef>

TSessionStateSchema​

TSessionStateSchema extends ZodTypeAny | undefined = undefined

TResources​

TResources extends | Record<string, DeclaredResourceEntry> | undefined = undefined

TTargetSchemas​

TTargetSchemas extends Record<string, ZodTypeAny> | undefined = undefined

TSequencerStateSchema​

TSequencerStateSchema extends ZodTypeAny | undefined = undefined

TOwnStateSchema​

TOwnStateSchema extends ZodTypeAny | undefined = undefined

Properties​

__brand​
readonly __brand: "Capability";

Brand — set by defineCapability() to identify capability objects.

__configInType?​
readonly __configInType?: unknown;

Type-only carrier for the .config() argument type. Set by defineCapability to z.input of the config schema (or the explicit schemaless type), or never when the capability declares no config. Holds no runtime value.

__presetDefs?​
readonly __presetDefs?: TPresets & object;

Raw preset definitions. Set internally by defineCapability().

Type Declaration​
default?​
default?: string[];
fns?​
fns?: (ctx) => TFns;
Parameters​
ctx​

BlockContext

Returns​

TFns

itemVisibility?​
itemVisibility?:
| ItemVisibility
| readonly ItemVisibility[];

Allowlist of block itemVisibility this capability attaches to. See CapabilityConfig.itemVisibility.

name​
readonly name: TName;
orgStateSchema?​
orgStateSchema?: ZodTypeAny;
requestStateSchema?​
requestStateSchema?: ZodTypeAny;
resources?​
resources?: TResources extends Record<string, DeclaredResourceEntry> ? TResources : Record<string, DeclaredResourceEntry>;
resourcesType?​
readonly resourcesType?: unknown;
sequencerStateSchema?​
sequencerStateSchema?: TSequencerStateSchema extends ZodTypeAny ? TSequencerStateSchema : ZodTypeAny;
sequencerStateType?​
readonly sequencerStateType?: unknown;
sessionStateSchema?​
sessionStateSchema?: TSessionStateSchema extends ZodTypeAny ? TSessionStateSchema : ZodTypeAny;
sessionStateType?​
readonly sessionStateType?: unknown;

Type-only escape hatch carriers. These fields hold no runtime value; InferCapability* utilities read them via infer to override the type derived from the corresponding schema. Useful when the schema infers to a shape that's too loose for consumer ctx (e.g. z.record(z.any())).

stateSchema?​
stateSchema?: TOwnStateSchema extends ZodTypeAny ? TOwnStateSchema : ZodTypeAny;

Own-state contribution — see PresetDef.stateSchema.

stateSchemaType?​
readonly stateSchemaType?: unknown;
targetStateSchemas?​
targetStateSchemas?: TTargetSchemas extends Record<string, ZodTypeAny> ? TTargetSchemas : Record<string, ZodTypeAny>;
targetStatesType?​
readonly targetStatesType?: unknown;
userStateSchema?​
userStateSchema?: ZodTypeAny;
uses?​
uses?: UsesSlot;

Methods​

config()​
config<Self>(this, value): ConfiguredCapability<TName, TFns, TPresetNames, TPresets, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema> & PreserveCarriers<Self>;

Apply typed open configuration declared via defineCapability({ config }). Returns a new configured reference (does not mutate the original), one hop from the base so diamond dedup still works. Composes with .presets() in either order. A compile error on a capability that declares no config (__configInType is never).

Type Parameters​
Self​

Self

Parameters​
this​

Self

value​

ConfigArgOf<Self>

Returns​

ConfiguredCapability<TName, TFns, TPresetNames, TPresets, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema> & PreserveCarriers<Self>

presets()​
presets<Self>(this, overrides): ConfiguredCapability<TName, TFns, TPresetNames, TPresets, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema> & PreserveCarriers<Self>;

Configure which presets are active. Returns a new capability reference with the overrides recorded (does not mutate the original). Uses Object.create() to preserve base reference identity for diamond dedup.

Polymorphic over this so escape-hatch carriers (and any .config() argument type) survive the chain — .presets().config() keeps both.

Type Parameters​
Self​

Self

Parameters​
this​

Self

overrides​

PresetOverrides<TPresetNames, TPresets>

Returns​

ConfiguredCapability<TName, TFns, TPresetNames, TPresets, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema> & PreserveCarriers<Self>

with()​
with<Self>(this, bag): ConfiguredCapability<TName, TFns, TPresetNames, TPresets, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema> & PreserveCarriers<Self>;

Normalized consumer builder — collapses .config() and .presets() into one flat call. Preset-named keys become preset overrides; the rest become the config value. .with({ allowed, dynamicActivation: true }) is exactly .config({ allowed }).presets({ dynamicActivation: true }).

The argument is the config input intersected with the (all-optional) preset overrides. When the capability declares no config, the config half collapses away, so .with() accepts preset overrides alone; when it declares no presets, the preset half is empty, so .with() accepts the config value alone (including a scalar/array config, routed wholesale at runtime). Composes with .config()/.presets() and preserves escape-hatch carriers.

Type Parameters​
Self​

Self

Parameters​
this​

Self

bag​

WithArg<Self, TPresetNames, TPresets>

Returns​

ConfiguredCapability<TName, TFns, TPresetNames, TPresets, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema> & PreserveCarriers<Self>


EvaluationModel​

An AI SDK evaluation model: what a provider's evaluationModel(id) returns (for example openai.evaluationModel("gpt-6-luna"), or Jev's typeSafeAi.evaluationModel("jev-latest")).

Kept structural and opaque on purpose: FSD checks only what it needs to tell an evaluation model from a text model and to report its identity. The call contract (doEvaluate) is the SDK's.

Properties​

modelId​
readonly modelId: string;

Model id, e.g. "gpt-6-luna" or "jev-latest".

provider​
readonly provider: string;

Provider id reported by the model, e.g. "openai.evaluation".

specificationVersion​
readonly specificationVersion: string;
supportedQuestionTypes​
readonly supportedQuestionTypes: readonly EvaluationQuestionType[];

The question types this model answers.

Methods​

doEvaluate()​
doEvaluate(options): PromiseLike<unknown>;

The SDK's evaluation call. Invoked only through experimental_evaluate.

Parameters​
options​

never

Returns​

PromiseLike<unknown>


EvaluatorConfig​

Config for evaluator. Scope schemas, resources, uses, connectInput and the shared block fields work as on a handler, and they type the ctx the questions and state callbacks receive the way they type a handler's execute. There is no retry: an evaluator makes one call per run.

The type parameters after TQuestions mirror HandlerConfig's; they are inferred from the declarations, not written by hand.

Extends​

  • Omit<BlockConfig<TInputSchema, ZodTypeAny, TInput, EvaluatorOutput<TQuestions>>, | "execute" | "outputSchema" | "retry" | "validateChunk" | "cacheable" | "stateSchema" | "flowConfigSchema">

Type Parameters​

TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

TInput​

TInput = z.infer<TInputSchema>

TQuestions​

TQuestions extends EvaluatorQuestions = EvaluatorQuestions

TRequestStateSchema​

TRequestStateSchema extends ZodTypeAny | undefined = undefined

TSessionStateSchema​

TSessionStateSchema extends ZodTypeAny | undefined = undefined

TUserStateSchema​

TUserStateSchema extends ZodTypeAny | undefined = undefined

TOrgStateSchema​

TOrgStateSchema extends ZodTypeAny | undefined = undefined

TSequencerStateSchema​

TSequencerStateSchema extends ZodTypeAny | undefined = undefined

TParentInputSchema​

TParentInputSchema extends ZodTypeAny | undefined = undefined

TResourceDefs​

TResourceDefs extends | Record<string, DeclaredResourceEntry> | undefined = undefined

TTargetSchemas​

TTargetSchemas extends Record<string, ZodTypeAny> | undefined = undefined

TUses​

TUses extends readonly UsesEntry[] = readonly []

TRequestState​

TRequestState extends object = InferStateFromSchema<TRequestStateSchema>

TSessionState​

TSessionState extends object = Prettify<InferStateFromSchema<TSessionStateSchema> & InferCapabilitySessionState<TUses>>

TUserState​

TUserState extends object = InferStateFromSchema<TUserStateSchema>

TOrgState​

TOrgState extends object = InferStateFromSchema<TOrgStateSchema>

TSequencerState​

TSequencerState extends object = Prettify<InferStateFromSchema<TSequencerStateSchema> & InferCapabilitySequencerState<TUses>>

TParentInput​

TParentInput = TParentInputSchema extends ZodTypeAny ? z.infer<TParentInputSchema> : unknown

TResources​

TResources extends Record<string, AnyResourceRef> = Prettify<InferBlockResources<undefined, TResourceDefs> & InferCapabilityResources<TUses>>

TMergedTargetSchemas​

TMergedTargetSchemas extends Record<string, ZodTypeAny> | undefined = MergeTargetSchemas<TTargetSchemas, TUses>

TCapabilities​

TCapabilities extends Record<string, Record<string, (...args) => any>> = InferCapabilities<TUses>

TStateSchema​

TStateSchema extends ZodTypeAny | undefined = undefined

TParentStateSchema​

TParentStateSchema extends ZodTypeAny | undefined = undefined

TSelfState​

TSelfState extends object = Prettify<InferStateFromSchema<TStateSchema> & InferCapabilityOwnState<TUses>>

TParentState​

TParentState extends object = InferStateFromSchema<TParentStateSchema>

TFlowConfigSchema​

TFlowConfigSchema extends ZodTypeAny | undefined = undefined

TFlowConfig​

TFlowConfig extends object = InferFlowConfigFromSchema<TFlowConfigSchema>

Properties​

activeStatusMessage?​
activeStatusMessage?: string | ((input, ctx) => string);

Active status message for this block — declarative sugar for ctx.emit.status() at block start. A static string is emitted once when the block enters execution; a function receives (input, ctx) and its return value is emitted. Use direct ctx.emit.status() only when a block needs to update status mid-execution (e.g. per-file progress).

Inherited from​

Omit.activeStatusMessage

connectInput?​
connectInput?: ConnectorFn<unknown, TInput>;
Overrides​

Omit.connectInput

container?​
container?: object;
component?​
component?: string;
label?​
label?: string | ((input) => string);
metadata?​
metadata?:
| Record<string, unknown>
| ((input) => Record<string, unknown>);
Inherited from​

Omit.container

description?​
description?: string;
Inherited from​

Omit.description

flowConfigSchema?​
flowConfigSchema?: TFlowConfigSchema;

What this block requires of the flow that installs it; types ctx.flow.config.

inputSchema?​
inputSchema?: TInputSchema;
Inherited from​

Omit.inputSchema

model​
model: string | EvaluationModel;

Which model answers: a model string (resolved through the app's model setup) or an evaluation model instance, e.g. openai.evaluationModel("gpt-6-luna"). Intents, fallback arrays and selectModel are refused.

name​
name: string;
Inherited from​

Omit.name

onCompleted?​
onCompleted?: (output, ctx) => void | Promise<void>;
Parameters​
output​

EvaluatorOutput

ctx​

BlockContext

Returns​

void | Promise<void>

Inherited from​

Omit.onCompleted

onErrored?​
onErrored?: (error, ctx) => void | Promise<void>;
Parameters​
error​

Error

ctx​

BlockContext

Returns​

void | Promise<void>

Inherited from​

Omit.onErrored

orgStateSchema?​
orgStateSchema?: TOrgStateSchema;
parentInputSchema?​
parentInputSchema?: TParentInputSchema;
parentStateSchema?​
parentStateSchema?: TParentStateSchema;

Expected shape of the immediate parent's own state.

questions​
questions: EvaluatorQuestionsSlot<TInput, TQuestions, BlockContext<TRequestState, TSessionState, TUserState, TOrgState, TResources, TSequencerState, TParentInput, TMergedTargetSchemas, TCapabilities, TSelfState, TParentState, TFlowConfig>>;

The questions. Ids become the keys of answers.

requestStateSchema?​
requestStateSchema?: TRequestStateSchema;
rescue?​
rescue?: RescueHandlerSpec[];

Per-block rescue handlers. When this block's execution throws a non-SuspensionError, the first handler whose when matches runs with the block's own scoped context — so it can read sequencer state — and its output replaces the throw, letting the enclosing chain / fan-out continue. Set via block.rescue([...]). Sequencers handle their own chain-level rescue in the operation loop and do not use this field.

Inherited from​

Omit.rescue

resources?​
resources?: TResourceDefs;
sequencerStateSchema?​
sequencerStateSchema?: TSequencerStateSchema;
sessionStateSchema?​
sessionStateSchema?: TSessionStateSchema;
state?​
state?: (input, ctx) =>
| EvaluationInput
| Promise<EvaluationInput>;

What the model evaluates: a string, an array or a plain object. Defaults to the block's input.

Parameters​
input​

TInput

ctx​

BlockContext<TRequestState, TSessionState, TUserState, TOrgState, TResources, TSequencerState, TParentInput, TMergedTargetSchemas, TCapabilities, TSelfState, TParentState, TFlowConfig>

Returns​

| EvaluationInput | Promise<EvaluationInput>

stateSchema?​
stateSchema?: TStateSchema;

This block's own request-scoped state, exposed via ctx.self.

targetStateSchemas?​
targetStateSchemas?: TTargetSchemas;
transient?​
transient?: boolean;
Inherited from​

Omit.transient

userStateSchema?​
userStateSchema?: TUserStateSchema;
uses?​
uses?: TUses;

Capabilities to install: resources, state and helpers. Capabilities cannot supply an evaluator's model, tools or context.


FlowStateSettings​

Instance-level settings, read inside blocks via ctx.settings.

Empty by default and framework-provided — users declaration-merge their own keys in their project, exactly as Vite's ImportMetaEnv works:

declare module "@flow-state-dev/core" {
interface FlowStateSettings {
sandbox: { type: "local" | "vercel" | "memory" };
}
}

The runtime value is supplied by createFlowState({ settings }) and threaded onto every BlockContext. The FlowState<TSettings> generic and this interface are kept in sync by the same declaration merge.


GeneratorCompletedMeta​

Runtime metadata passed as the third argument to a generator block's onCompleted. Carries framework-resolved data that is not part of the block's output — currently the identity of the model that produced the output. Typed per block kind: only generators receive this shape, so other kinds' onCompleted signatures stay free of generator-only fields.

Properties​

model​
model: ModelIdentity;

Resolved identity of the model that produced this generator's output. Always populated on the success path — the generator seeds actual before invoking the model, so onCompleted (which fires only after a successful execute) always sees at least { actual }.


GeneratorConfig​

Extends​

  • Omit<BlockConfig<TInputSchema, TOutputSchema, TInput, TOutput>, "execute" | "onCompleted" | "stateSchema" | "flowConfigSchema">

Type Parameters​

TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

TOutputSchema​

TOutputSchema extends ZodTypeAny = ZodTypeAny

TInput​

TInput = z.infer<TInputSchema>

TOutput​

TOutput = z.infer<TOutputSchema>

TRequestStateSchema​

TRequestStateSchema extends ZodTypeAny | undefined = undefined

TSessionStateSchema​

TSessionStateSchema extends ZodTypeAny | undefined = undefined

TUserStateSchema​

TUserStateSchema extends ZodTypeAny | undefined = undefined

TOrgStateSchema​

TOrgStateSchema extends ZodTypeAny | undefined = undefined

TSequencerStateSchema​

TSequencerStateSchema extends ZodTypeAny | undefined = undefined

TResourceDefs​

TResourceDefs extends | Record<string, DeclaredResourceEntry> | undefined = undefined

TTargetSchemas​

TTargetSchemas extends Record<string, ZodTypeAny> | undefined = undefined

TUses​

TUses extends readonly UsesEntry[] = readonly []

TRequestState​

TRequestState extends object = InferStateFromSchema<TRequestStateSchema>

TSessionState​

TSessionState extends object = Prettify<InferStateFromSchema<TSessionStateSchema> & InferCapabilitySessionState<TUses>>

TUserState​

TUserState extends object = InferStateFromSchema<TUserStateSchema>

TOrgState​

TOrgState extends object = InferStateFromSchema<TOrgStateSchema>

TSequencerState​

TSequencerState extends object = Prettify<InferStateFromSchema<TSequencerStateSchema> & InferCapabilitySequencerState<TUses>>

TResources​

TResources extends Record<string, AnyResourceRef> = Prettify<InferBlockResources<undefined, TResourceDefs> & InferCapabilityResources<TUses>>

TMergedTargetSchemas​

TMergedTargetSchemas extends Record<string, ZodTypeAny> | undefined = MergeTargetSchemas<TTargetSchemas, TUses>

TCapabilities​

TCapabilities extends Record<string, Record<string, (...args) => any>> = InferCapabilities<TUses>

TStateSchema​

TStateSchema extends ZodTypeAny | undefined = undefined

TParentStateSchema​

TParentStateSchema extends ZodTypeAny | undefined = undefined

TSelfState​

TSelfState extends object = Prettify<InferStateFromSchema<TStateSchema> & InferCapabilityOwnState<TUses>>

TParentState​

TParentState extends object = InferStateFromSchema<TParentStateSchema>

TFlowConfigSchema​

TFlowConfigSchema extends ZodTypeAny | undefined = undefined

TFlowConfig​

TFlowConfig extends object = InferFlowConfigFromSchema<TFlowConfigSchema>

TCtx​

TCtx = BlockContext<TRequestState, TSessionState, TUserState, TOrgState, TResources, TSequencerState, unknown, TMergedTargetSchemas, TCapabilities, TSelfState, TParentState, TFlowConfig>

Properties​

activeStatusMessage?​
activeStatusMessage?: string | ((input, ctx) => string);

Active status message for this block — declarative sugar for ctx.emit.status() at block start. A static string is emitted once when the block enters execution; a function receives (input, ctx) and its return value is emitted. Use direct ctx.emit.status() only when a block needs to update status mid-execution (e.g. per-file progress).

Inherited from​

Omit.activeStatusMessage

agentName?​
agentName?: string;

Stable name of the producing agent. Defaults to the block's name when itemVisibility is set and agentName is omitted. Generators that share an agentName collaborate (same logical agent across instances); distinct names stay isolated. Items emitted by the generator are stamped with this name.

cacheable?​
cacheable?: true | BlockCacheableConfig;

Opt-in tool-result memoization. When set, and when this block is installed as a tool on a generator, the framework caches the tool's output keyed on (toolName, canonicalize(args), scope) and serves repeat calls from the cache. Errors are never cached. Identical concurrent calls within a request are coalesced (single-flight).

Pass true for cache-everything defaults, or an object to tune TTL, scope, key derivation, and a cacheIf predicate.

No effect when the block is used outside a generator's tool slot.

Inherited from​

Omit.cacheable

caching?​
caching?: ResolvableCachingConfig<TInput, TCtx>;

Prompt caching config. Defaults to { enabled: true, breakpoints: 'auto', ttl: '5m' }. In auto mode the adapter places a cache breakpoint at the end of the system prefix on Anthropic-flavored providers (Anthropic, OpenRouter) when the cacheable prefix is large enough to activate, and opts the Vercel AI Gateway into automatic marking (caching: 'auto'). Other providers (OpenAI, Google, DeepSeek) cache implicitly and are left untouched. Set { enabled: false } to disable, or { breakpoints: 'manual' } to take full control of cacheControl placement via user-supplied provider options.

connectInput?​
connectInput?: ConnectorFn<unknown, TInput>;
Overrides​

Omit.connectInput

container?​
container?: object;
component?​
component?: string;
label?​
label?: string | ((input) => string);
metadata?​
metadata?:
| Record<string, unknown>
| ((input) => Record<string, unknown>);
Inherited from​

Omit.container

context?​
context?: GeneratorSlot<NoInfer<TInput>, TCtx>;
describeTools?​
describeTools?: boolean;

When true (default), auto-inject tool name+description pairs into the system context.

description?​
description?: string;
Inherited from​

Omit.description

flowConfigSchema?​
flowConfigSchema?: TFlowConfigSchema;

What this block requires of whatever flow installs it. Types ctx.flow.config off this schema, and makes the flow refuse when it cannot supply a bag that satisfies it. Names no flow, so the block stays portable. See BlockConfig.flowConfigSchema.

flowTools?​
flowTools?: ToolsConfig;
history?​
history?: GeneratorHistoryConfig<NoInfer<TInput>, TCtx>;
inputSchema?​
inputSchema?: TInputSchema;
Inherited from​

Omit.inputSchema

itemVisibility?​
itemVisibility?: ItemVisibility;

Transport and memory visibility stamped on every conversational item this generator auto-emits.

  • { client: true, history: true } — user-facing agent (primary).
  • { client: true, history: false } — observable work (sub-agent).
  • { client: false, history: true } — private/injected context.
  • { client: false, history: false } — trace (devtool only).
  • unset (default): no auto-emission. Only the generator's typed block_trace output flows to parents via graph edges.

There is no position-inferred default — every generator declares its own visibility explicitly. Pattern factories set visibility on their internal generators.

loop?​
loop?: GeneratorLoopConfig<TInput, TCtx>;
maxIterations?​
maxIterations?: number;
maxTokens?​
maxTokens?: number;
model?​
model?: ResolvableModel<NoInfer<TInput>, TCtx>;

Model selection. Optional when a capability in uses contributes a model (see PresetDef.model); a block-level setting always wins over the capability's. Missing on both is a runtime error at construction.

name​
name: string;
Inherited from​

Omit.name

onCompleted?​
onCompleted?: (output, ctx, meta) => void | Promise<void>;
Parameters​
output​

TOutput

ctx​

TCtx

meta​

GeneratorCompletedMeta

Returns​

void | Promise<void>

onErrored?​
onErrored?: (error, ctx) => void | Promise<void>;
Parameters​
error​

Error

ctx​

BlockContext

Returns​

void | Promise<void>

Inherited from​

Omit.onErrored

orgStateSchema?​
orgStateSchema?: TOrgStateSchema;
outputSchema?​
outputSchema?: TOutputSchema;
Inherited from​

Omit.outputSchema

parentStateSchema?​
parentStateSchema?: TParentStateSchema;

Expected shape of the immediate parent's own state.

prompt​
prompt:
| PromptFile
| PromptSlot<NoInfer<TInput>, TCtx>;

Prompt slot. Accepts an inline string, a resolver function, an array of those, a branded PromptFile slot (pf.prompt), or a whole PromptFile (prompt: loadPromptFile(...)). Passing the PromptFile directly expands its user / caching / maxTokens / temperature / name / description into this config — any sibling field set explicitly here wins, matching ...definePromptFile(pf), <overrides>.

providerOptions?​
providerOptions?: ResolvableProviderOptions<TInput, TCtx>;
providerTools?​
providerTools?: ProviderTool[];

Provider-defined tools passed through to the AI SDK without block compilation.

repair?​
repair?: GeneratorRepairConfig;
repairOutput?​
repairOutput?: (candidate, error, state, ctx) => unknown;
Parameters​
candidate​

unknown

error​

Error

state​

GeneratorLoopState<TInput>

ctx​

TCtx

Returns​

unknown

requestStateSchema?​
requestStateSchema?: TRequestStateSchema;
rescue?​
rescue?: RescueHandlerSpec[];

Per-block rescue handlers. When this block's execution throws a non-SuspensionError, the first handler whose when matches runs with the block's own scoped context — so it can read sequencer state — and its output replaces the throw, letting the enclosing chain / fan-out continue. Set via block.rescue([...]). Sequencers handle their own chain-level rescue in the operation loop and do not use this field.

Inherited from​

Omit.rescue

resources?​
resources?: TResourceDefs;

Flat resource declaration. See HandlerConfig.resources.

retry?​
retry?: RetryPolicy;
Overrides​

Omit.retry

search?: boolean | GeneratorSearchConfig;

Enable provider-native web search. When true, uses defaults. When an object, maps normalized config to the provider's native search tool. The provider is detected at execution time from the resolved model.

sequencerStateSchema?​
sequencerStateSchema?: TSequencerStateSchema;
sessionStateSchema?​
sessionStateSchema?: TSessionStateSchema;
stateSchema?​
stateSchema?: TStateSchema;

This generator's own request-scoped state. Exposed via ctx.self in context/prompt/tool-loop callbacks — a generator can accumulate across its own tool loop (e.g. what it has loaded so far).

targetStateSchemas?​
targetStateSchemas?: TTargetSchemas;
tools?​
tools?:
| GeneratorTool[]
| ((input, ctx) => MaybePromise<GeneratorTool[]>);
transient?​
transient?: boolean;
Inherited from​

Omit.transient

user?​
user?:
| TypedUserSlotFn<TInput, TCtx>
| GeneratorSlotStatic
| GeneratorSlotStatic[];

Typed user slot: accepts a function over TInput, a static string, or other non-function slot entries.

userStateSchema?​
userStateSchema?: TUserStateSchema;
uses?​
uses?: TUses;

Capabilities to install. Merges resources, state schemas, targets, and any active preset surfaces into this block's config.

validateChunk?​
validateChunk?: (input, ctx) =>
| ChunkValidation
| Promise<ChunkValidation>;
Parameters​
input​

TInput

ctx​

BlockContext

Returns​

| ChunkValidation | Promise<ChunkValidation>

Inherited from​

Omit.validateChunk


GeneratorLoopConfig​

Type Parameters​

TInput​

TInput = unknown

TCtx​

TCtx = BlockContext

Properties​

answerOnLastStep?​
answerOnLastStep?: boolean;

The loop's last step offers the model no framework tools, so a model still looking things up when its steps run out answers in text with what it found, rather than ending on a tool call with nothing said. Off by default: without it, the last step offers every tool, as the others do.

maxIterations?​
maxIterations?: number;
runTools?​
runTools?: boolean;

GeneratorLoopState​

Type Parameters​

TInput​

TInput = unknown

Properties​

input​
input: TInput;
iteration​
iteration: number;
lastCandidate?​
lastCandidate?: unknown;
messages​
messages: unknown[];
model​
model: string;
prompt​
prompt: string;
toolResults​
toolResults: GeneratorToolResult[];

GeneratorModel​

Properties​

modelId​
modelId: string;

Methods​

generate()​
generate(options): Promise<GeneratorModelResult>;

SDK-driven multi-step generation: one call runs the model's internal tool loop to completion (bounded by maxSteps), auto-executing any tool that carries an execute closure. Used by the generator block for models that do not implement generateStep.

Parameters​
options​

GeneratorModelLoopOptions

Returns​

Promise<GeneratorModelResult>

generateStep()?​
generateStep?(options): Promise<GeneratorModelResult>;

Single-step generation for the framework-owned tool loop. One call is exactly one provider model call — no internal multi-step iteration, no maxSteps, no prepareStep (the framework owns loop policy and per-step reshaping). The model never executes framework tools: callers pass tools WITHOUT execute, and the step's requested tool calls are returned on the result's toolCalls for the caller to run itself. A returned steps array, when present, has at most one entry.

OPTIONAL: models that omit it (hand-rolled test mocks, the public mockGenerator, third-party adapters, and createFallbackModel groups) fall back to the SDK-driven multi-step path via generate. The framework-owned loop — and suspension support built on it in a later change — requires step-capable models; the AI SDK adapter implements it. A fallback model group deliberately does NOT, so one candidate owns the whole loop rather than switching candidates mid-loop (see createFallbackModel).

Parameters​
options​

GeneratorModelCallOptions

Returns​

Promise<GeneratorModelResult>

resolveSearchTool()?​
resolveSearchTool?(config):
| {
name: string;
tool: unknown;
}
| undefined;

Resolves a provider-native search tool from normalized config. Returns undefined if the provider does not support search tools. Implemented by the AI SDK adapter based on provider detection.

Parameters​
config​

GeneratorSearchConfig

Returns​

| { name: string; tool: unknown; } | undefined

stream()?​
stream?(options): AsyncIterable<GeneratorModelStreamChunk>;

SDK-driven multi-step streaming counterpart to generate: the model runs the whole tool loop internally and yields deltas across all steps, terminating with a finish chunk carrying the full result.

Parameters​
options​

GeneratorModelLoopOptions

Returns​

AsyncIterable<GeneratorModelStreamChunk>

streamStep()?​
streamStep?(options): AsyncIterable<GeneratorModelStreamChunk>;

Single-step streaming counterpart to generateStep: one call is one provider model call that keeps yielding deltas within the step (text, reasoning, tool-call argument fragments, sources) and terminates with a finish chunk whose fullResult carries the step's assistant turn. Framework tools are passed without execute and are never run by the model — the framework executes them between steps.

OPTIONAL, with the same fallback semantics as generateStep: models without it stream via the SDK-driven multi-step stream.

Parameters​
options​

GeneratorModelCallOptions

Returns​

AsyncIterable<GeneratorModelStreamChunk>


GeneratorRepairConfig​

Properties​

coerce?​
coerce?:
| boolean
| {
model?: ResolvableModel<unknown, BlockContext<Record<string, unknown>, Record<string, unknown>, Record<string, unknown>, Record<string, unknown>, Record<string, AnyResourceRef>, Record<string, unknown>, unknown, Record<string, ZodTypeAny>, {
}, Record<string, unknown>, Record<string, unknown>, Readonly<Record<string, unknown>>>>;
};

LLM coercion repair. When the deterministic repair pass can't recover the model's structured output (e.g. it returned the right data under the wrong field names), make one model call that reshapes the raw output to the schema, preserving content. Runs only in auto mode and only on the path that would otherwise throw.

Default: enabled, using intent/utility. Set false to disable. Pass { model } to override the coercion model (any ResolvableModel, e.g. a concrete model id or a GeneratorModel instance).

maxAttempts?​
maxAttempts?: number;
mode?​
mode?: GeneratorRepairMode;

GeneratorToolResult​

Properties​

error?​
error?: Error;
input​
input: unknown;
output?​
output?: unknown;
toolCallId?​
toolCallId?: string;
toolName​
toolName: string;

InstanceOwnerPin​

Security pin for one registered flow instance: the organization that owns it and, optionally, the user.

{ orgId, userId? }, handed to register(flow, { pin }) by the code that registers the instance, from a record it trusts. It is never parsed from the instance's address. A caller outside the pin cannot see or run the instance. Absent means the instance is shared: an app flow, a kind.

Properties​

orgId​
orgId: string;

The organization that owns the instance.

userId?​
userId?: string;

The user that owns the instance. Absent means every member of orgId may see it.


IntentDefaults​

Per-intent defaults applied when a candidate from that intent wins resolution. The resolved candidate's provider is used to filter providerOptions — keys for other providers are dropped silently (matches the Vercel AI SDK's per-provider namespace behavior).

Call-site providerOptions (passed by a generator at execution time) always wins on key collisions. Nested provider-namespace objects are deep-merged.

Captured at resolver construction time — the resolved fallback model is immutable. Mutations to intentDefaults after createModelResolver has been called do not affect already-resolved intents (intents are cached by (name, normalizedPreference)).

Open shape so future fields (reasoning, caching, etc.) can be added without a breaking change.

Properties​

providerOptions?​
providerOptions?: Record<string, Record<string, unknown>>;

Per-provider options merged into the request when a candidate from the intent's list wins. Only the resolved provider's sub-object is kept; others are dropped.


InternalDispatcherConfig​

An internal dispatcher: sends this request's authority to flow.internal.actions[action].

Type Parameters​

TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

Properties​

action​
action: string;

The entry name — resolves flow.internal.actions[action] on the flow InternalDispatcherConfig.flowKind names. Verified at defineFlow for a same-flow address, at the seam for a cross-flow one.

description?​
description?: string;
flowKind?​
flowKind?: string;

The other flow instance this dispatcher sends to — its exact id: a singleton's kind, or a collection member's explicit id. Omit for the sending instance's own entry, which is the ordinary case. A collection's bare kind names no instance and refuses flow-not-found; an explicit value equal to the sender's own id is the sender.

A cross-flow dispatch is fire-and-forget in the same sense a same-flow one is — it starts a request over there and returns the handle, it does not wait for a result. Getting one back is the same three-request shape it is within a flow: the recipient replies with a { from: true } dispatcher of its own, pointed back at flowKind: <the sender's flow>.

defineFlow cannot check this address — it holds one flow's entry maps and this names another's. The check runs at the seam instead, against what the process actually registered, and refuses by name: flow-not-found for an unregistered flow, no-entry for a flow that declares no such entry. Both reach this block as a thrown DispatchRefusedError.

inputSchema?​
inputSchema?: TInputSchema;

What this block accepts. Defaults to z.unknown().

name​
name: string;
payload?​
payload?: (input, ctx) => unknown;

The entry's input, computed from this block's input. Defaults to the input itself. Validated on arrival by the entry's own schema.

Parameters​
input​

TypeOf<TInputSchema>

ctx​

BlockContext

Returns​

unknown

session​
session: DispatcherSession<TypeOf<TInputSchema>>;

Which session the dispatch runs in.

transient?​
transient?: boolean;

Hide this block's trace from clients. Default: false.

type?​
type?: "internal";

Discriminant. Omit it — internal is the default. A board's dispatcher is one whose session is a task policy; do not set type there.

wait?​
wait?: boolean;

Wait for the request this dispatch starts, and output how it ended (DispatchWaitResult) instead of the handle. Default: false. Bounded by the host's default wait deadline, at which the output is running and nothing is stopped.


KeyedSlot​

A slot that holds entries by key. Each contributor gives a record of entries, or entries (one, or an array) that each carry a string id, which is then the key. Two contributors giving one key is refused, naming both.

Type Parameters​

T​

T = unknown

Properties​

kind​
readonly kind: "keyed";
schema​
readonly schema: ZodType<T, ZodTypeDef, unknown>;

Every entry contributed is checked against it.


KitDefinition​

The definition defineKit takes.

Type Parameters​

Name​

Name extends string = string

ConfigSchema​

ConfigSchema extends z.ZodTypeAny | undefined = z.ZodTypeAny | undefined

Slots​

Slots extends Record<string, SlotDeclaration> = Record<string, SlotDeclaration>

Folder​

Folder = unknown

Properties​

config?​
readonly config?: ConfigSchema;

The schema the factory checks its config against. Omitted: the kit takes none.

contributes?​
readonly contributes?: (input) => Readonly<Record<string, unknown>>;

What this kit puts in the slots of the kits it requires, by slot key: { [workforce.slots.workerFlows]: { coder: coderFlow(config) } } for a keyed slot (or entries carrying an id), an entry or an array of them for a list slot.

Runs after every kit that requires this one has contributed, so slots holds this kit's own slots fully filled, the app's fill included.

Parameters​
input​
config​

ConfigOutput<ConfigSchema>

slots​

{ readonly [K in string | number | symbol]: SlotValue<Slots[K]> }

Returns​

Readonly<Record<string, unknown>>

directory?​
readonly directory?: object;

The folder this kit owns in the app. path is its default, read against the app's root; an app overrides it with directory in the kit's config, read against the working directory. read is the kit's reader, and runs on the server at start-up.

path​
readonly path: string;
read​
readonly read: (folder, input) => Folder | Promise<Folder>;
Parameters​
folder​

KitFolder

input​
config​

ConfigOutput<ConfigSchema>

Returns​

Folder | Promise<Folder>

install​
readonly install: (input) =>
| KitInstallation
| Promise<KitInstallation>;

Builds the flows the kit serves, from its config, its folder and its slots.

Parameters​
input​

KitInstallInput<ConfigOutput<ConfigSchema>, Folder, Slots>

Returns​

| KitInstallation | Promise<KitInstallation>

name​
readonly name: Name;

The kit's name: lowercase letters, digits and single hyphens, unique in an app.

requires?​
readonly requires?: readonly AnyKitFactory[];

The kits this one installs after, and may fill the slots of (directly or through another).

slots?​
readonly slots?: Slots;

The slots this kit declares, by name. Only a kit that requires it can fill them.


KitFolder​

The folder a kit owns, as its reader sees it.

Every entry in it is used or refused: the reader claims what it consumed, and anything left unclaimed (except the names that never mean anything, such as .DS_Store) stops the app starting, each named. The engine builds this; a kit's reader only reads path and calls claim.

Properties​

path​
readonly path: string;

The folder's absolute path.

Methods​

claim()​
claim(relativePath): void;

Mark a file or directory as used, by its slash-separated path relative to the folder ("teams", "teams/eng/team.md"). Claiming a directory claims everything under it; "." claims the whole folder. A symlink is refused wherever it is, claimed or not.

Parameters​
relativePath​

string

Returns​

void


KitInstallation​

What an install returns: the flows the kit serves.

Properties​

flows​
readonly flows: readonly FlowInstance<any, any>[];

KitInstallInput​

What a kit's install is handed.

Type Parameters​

Config​

Config

Folder​

Folder

Slots​

Slots

Properties​

config​
readonly config: Config;

The kit's config, as its schema parsed it.

folder​
readonly folder: Folder;

What the kit's directory.read returned; undefined when it owns no folder.

slots​
readonly slots: { readonly [K in string | number | symbol]: SlotValue<Slots[K]> };

Each declared slot's merged entries.


KitInstance​

One installed kit, as createFlowState({ kits }) takes it: a factory called with its config.

Properties​

config​
readonly config: unknown;

The config, as the kit's schema parsed it.

definition​
readonly definition: KitDefinition<string, any, any, any>;

The definition the factory was made from.

directory​
readonly directory: string | undefined;

The folder path the app gave in config, read against the working directory; undefined for the kit's default.

kitName​
readonly kitName: string;

The kit's name.

withheld​
readonly withheld: readonly KitWithheld[];

What this instance's contributions are withheld from: a whole slot, or one key of a keyed slot.

Methods​

without()​
without(slot, key?): KitInstance;

The same kit with its contribution to slot dropped, or only the entry under key when the slot is keyed (harnesses().without(workforce.slots.workerFlows, "coder")).

Parameters​
slot​

SlotKey

key?​

string

Returns​

KitInstance


KitWithheld​

One contribution an app dropped from a kit: a slot, or one key in it.

Properties​

key?​
readonly key?: string;

Set when only this entry of a keyed slot is dropped.

slot​
readonly slot: string;

ListSlot​

A slot that holds a list. Contributions append in install order (each kit's requires first, ties in the app's listed order), the app's last.

Type Parameters​

T​

T = unknown

Properties​

kind​
readonly kind: "list";
schema​
readonly schema: ZodType<T, ZodTypeDef, unknown>;

Every entry contributed is checked against it.


ListVoicesCapable​

VoiceProvider narrowed to require listVoices.

Extends​

Properties​

abilities​
readonly abilities: VoiceAbilities;
Inherited from​

VoiceProvider.abilities

defaultModels?​
readonly defaultModels?: object;

Provider-suggested default model ids per ability. Routers/pipelines fall back to these when the caller doesn't specify a model in SpeakOptions.model / TranscribeOptions.model.

speak?​
speak?: string;
transcribe?​
transcribe?: string;
Inherited from​

VoiceProvider.defaultModels

id​
readonly id: string;

Stable identifier for telemetry/registry use.

Inherited from​

VoiceProvider.id

providerName​
readonly providerName: string;

Short provider name (e.g. "openai", "elevenlabs", "composite").

Inherited from​

VoiceProvider.providerName

Methods​

listVoices()​
listVoices(): Promise<VoiceInfo[]>;
Returns​

Promise<VoiceInfo[]>

Overrides​

VoiceProvider.listVoices

speak()?​
speak?(options): Promise<SpeakResult>;
Parameters​
options​

SpeakOptions

Returns​

Promise<SpeakResult>

Inherited from​

VoiceProvider.speak

speakStream()?​
speakStream?(options): AsyncIterable<SpeakChunk>;
Parameters​
options​

SpeakOptions

Returns​

AsyncIterable<SpeakChunk>

Inherited from​

VoiceProvider.speakStream

transcribe()?​
transcribe?(options): Promise<TranscribeResult>;
Parameters​
options​

TranscribeOptions

Returns​

Promise<TranscribeResult>

Inherited from​

VoiceProvider.transcribe


MakeSchemaStrictOptions​

Options for makeSchemaStrict.

Properties​

label?​
label?: string;

Label prefixed onto a thrown error's message (e.g. a generator name).

requireTextOrObjectRoot?​
requireTextOrObjectRoot?: boolean;

When true (with validate), also require the schema's ROOT to be something a model call can carry: a bare z.string() (sent as plain text) or an object (sent as a structured-output root). Defaults to false.

Off by default because generator() accepts any root and fails at the provider; a caller that wants the failure before the call — an agent materializer deciding what an author may declare — opts in. The predicate is output-root.ts, the same one the generator routes on, so opting in cannot disagree with what actually gets sent.

validate?​
validate?: boolean;

When true, after building the strict schema, walk it and throw a StrictSchemaError if any construct OpenAI strict mode rejects survives (a reachable z.record, or a non-literal z.union). Defaults to false — transform only, no validation.


McpConfig​

Per-flow MCP exposure config. Opt-in: a flow must set enabled: true for the MCP transport adapter to mount routes for it. Per-action inclusion is controlled on each action via action.mcp.enabled. The runtime under host.dispatch is identical between MCP and HTTP requests.

Properties​

enabled?​
enabled?: boolean;

Master enable. Default: false.

exposeResources?​
exposeResources?: boolean;

If true (default), exposes flow-scoped resources via MCP resources/list + resources/read, honoring the existing client.content.read permission. If false, no resources are exposed.


ModelIdentity​

Identity of a model that actually executed a generator call. Surfaced on generator-emitted items and on BlockTraceItem so consumers can answer "which model produced this?" without consulting internal/debug surfaces.

actual is always populated. requested and gateway appear only when meaningful (intent fallback, gateway-routed call, provider substitution).

Properties​

actual​
actual: string;

The concrete model that actually executed the call. Prefers the provider-reported model id (e.g. gpt-5.5-2025-04-12); falls back to the framework's winning candidate string (e.g. openai/gpt-6.1-sol) when the provider doesn't report one.

gateway?​
gateway?: string;

The gateway that routed the call, when one was used.

requested?​
requested?: string;

What the caller requested, when different from actual. Populated for intent strings (intent/chat), for non-first candidates inside a fallback chain, and when the provider reports a different model id than the framework requested. Omitted when equal to actual.


ModelLookupEntry​

Properties​

charsPerToken​
charsPerToken: number;

Estimated characters per token for the model family.

keyword​
keyword: string;

Substring matched against the model ID — first match wins.

pricing?​
pricing?: object;

USD per 1M tokens.

cacheCreationPer1M?​
cacheCreationPer1M?: number;
cacheReadPer1M?​
cacheReadPer1M?: number;
completionPer1M​
completionPer1M: number;
promptPer1M​
promptPer1M: number;

ModelUsageEntry​

Properties​

cacheCreationTokens​
cacheCreationTokens: number;
cacheReadTokens​
cacheReadTokens: number;
completion​
completion: number;
prompt​
prompt: number;
total​
total: number;

ProjectedReactiveBindings​

Per-reactive-kind bindings for a projected collection. Only the three state kinds are available: a read-only projected collection has no content-write seam, so contentUpdated is omitted — it could be declared but would never fire. Change-awareness itself (path B) lands in a later PR; the config field is authored now so the backing contract is stable.

Type Parameters​

TState​

TState extends JsonObject = JsonObject

Properties​

created?​
created?: ReactiveBinding<TState>;

Runs when the app reports a record was created.

deleted?​
deleted?: ReactiveBinding<TState>;

Runs when the app reports a record was deleted.

stateUpdated?​
stateUpdated?: ReactiveBinding<TState>;

Runs when the app reports a record's state was updated.


ReactiveBindings​

Per-reactive-kind bindings, as passed to reactTo.

Type Parameters​

TState​

TState extends JsonObject = JsonObject

Properties​

contentUpdated?​
contentUpdated?: ReactiveContentBinding;

Runs after an instance/resource's content body is written.

created?​
created?: ReactiveBinding<TState>;

Runs when an instance/resource is created.

deleted?​
deleted?: ReactiveBinding<TState>;

Runs when an instance/resource is deleted (including eviction).

stateUpdated?​
stateUpdated?: ReactiveBinding<TState>;

Runs when an instance/resource's structured state is updated.


ResolveModelCallOptions​

Per-call options for the ModelResolver callable. Currently only carries preferProvider — a provider preference that overrides any resolver-level default for this single resolution. Used to plumb a selectModel-collected preference through to intent resolution.

Properties​

preferProvider?​
preferProvider?: string | string[];

Preferred provider(s). Overrides resolver-level providerPreference.


ResourceChange​

The payload handed to a reactive block when its bound state mutation fires. state is the post-mutation state (null on delete); prevState is the pre-mutation state (null on create). evicted distinguishes a capacity-driven removal from an explicit delete.

Type Parameters​

TState​

TState extends JsonObject = JsonObject

Properties​

evicted​
evicted: boolean;

true only when kind === "deleted" AND it was a capacity eviction (LRU/oldest); false otherwise.

key​
key: string;

Collection instance key, or the single resource's ref name.

kind​
kind: ResourceChangeKind;

Which state mutation produced this change.

prevState​
prevState: TState | null;

Pre-mutation state; null for "created"; present for stateUpdated/deleted.

ref​
ref: string;

Full storage path, e.g. "artifacts/memo-1".

state​
state: TState | null;

Post-mutation state; null for "deleted".


ResourceCollectionRef​

Runtime ref for accessing a collection's dynamic resource instances.

All read methods (get/getOptional/list/count) are async regardless of prefetchMode — the server implementation resolves immediately for eager collections and performs a load for lazy ones, but callers always await. Mutation methods (create/getOrCreate/upsert/delete) were already async and are unchanged.

ResourceRef.state is a synchronous getter on the ref itself — do NOT await it.

Type Parameters​

TState​

TState extends JsonObject = JsonObject

TScope​

TScope extends ScopeType = ScopeType

Properties​

config​
config: Readonly<ResourceCollectionConfig>;

The collection's config.

pattern​
pattern: string;

The collection's declared pattern.

scope​
scope: TScope;

Scope this collection is registered in: its declaration's, when the declaration names one literally.

Methods​

count()​
count(): Promise<number>;

Current instance count.

Returns​

Promise<number>

create()​
create(
key,
initial?,
options?
): Promise<ResourceRef<TState>>;

Create a new instance.

Default behavior: throws if already exists, or if creating would exceed maxInstances (subject to the configured eviction policy).

With { replace: true }: overwrites the instance if it exists (setState semantics — Zod .default(null) fills nullable fields the caller doesn't supply); creates it if missing. Use for setup/reset paths that want a known initial state regardless of whether the instance was present before. On a writable: false collection, replacing an existing instance throws the same read-only error as setState; a missing key still creates.

Parameters​
key​

string | Record<string, string>

initial?​

Partial<TState>

options?​
replace?​

boolean

Returns​

Promise<ResourceRef<TState>>

delete()​
delete(key): Promise<void>;

Delete an instance. No-op if the instance does not exist. Throws the same read-only error as setState when the collection is writable: false.

Parameters​
key​

string | Record<string, string>

Returns​

Promise<void>

findBy()​
findBy(index, value): Promise<ResourceRef<TState>[]>;

The instances whose declared index index has value, in key order. Reads the same rows list() does and passes the same owner fence. On a store that keeps index entries (SQLite, Postgres) it reads the index, plus one row read per hit; elsewhere it scans the collection. Every hit is checked against its row, so a row whose value changed is never returned. Equality only. Throws when the collection declares no index named index.

Parameters​
index​

string

value​

ResourceIndexValue

Returns​

Promise<ResourceRef<TState>[]>

get()​
get(key): Promise<ResourceRef<TState>>;

Get an existing instance. Rejects if not found.

Parameters​
key​

string | Record<string, string>

Returns​

Promise<ResourceRef<TState>>

getOptional()​
getOptional(key): Promise<ResourceRef<TState> | undefined>;

Get an existing instance, or undefined if not found.

Parameters​
key​

string | Record<string, string>

Returns​

Promise<ResourceRef<TState> | undefined>

getOrCreate()​
getOrCreate(key, initial?): Promise<ResourceRef<TState>>;

Get or create — returns existing if present, creates if not.

Parameters​
key​

string | Record<string, string>

initial?​

Partial<TState>

Returns​

Promise<ResourceRef<TState>>

list()​
list(prefix?): Promise<ResourceRef<TState>[]>;

List all instances, optionally filtered by prefix.

Parameters​
prefix?​

string

Returns​

Promise<ResourceRef<TState>[]>

upsert()​
upsert(
key,
update,
createOnly?
): Promise<ResourceRef<TState>>;

Upsert — patch the existing instance with update if it exists, otherwise create with { ...createOnly, ...update } (the create-only extras provide the fields you only need to supply at creation time — update wins on overlapping keys).

Fires onInstanceUpdated on the patch branch, onInstanceCreated on the create branch. The create branch honors maxInstances + eviction like create().

Use for incremental-update paths that need to handle the first-touch case in a single call.

Parameters​
key​

string | Record<string, string>

update​

Partial<TState>

createOnly?​

Partial<TState>

Returns​

Promise<ResourceRef<TState>>


ResourceContentChange​

The payload handed to a reactive block when a resource's content body is written (writeContent). Deliberately minimal: bodies are not inlined — the block readContent()s the fresh body, and reads state (unchanged by a content write) from ctx.resources if it needs it.

Properties​

key​
key: string;

Collection instance key, or the single resource's ref name.

kind​
kind: "contentUpdated";

Always "contentUpdated" — the discriminant against ResourceChange.

ref​
ref: string;

Full storage path, e.g. "artifacts/memo-1".


RouterConfig​

Extends​

  • Omit<BlockConfig<TInputSchema, TOutputSchema, TInput, TOutput>, "execute" | "stateSchema" | "flowConfigSchema">

Type Parameters​

TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

TOutputSchema​

TOutputSchema extends ZodTypeAny = ZodTypeAny

TInput​

TInput = z.infer<TInputSchema>

TOutput​

TOutput = z.infer<TOutputSchema>

TRequestStateSchema​

TRequestStateSchema extends ZodTypeAny | undefined = undefined

TSessionStateSchema​

TSessionStateSchema extends ZodTypeAny | undefined = undefined

TUserStateSchema​

TUserStateSchema extends ZodTypeAny | undefined = undefined

TOrgStateSchema​

TOrgStateSchema extends ZodTypeAny | undefined = undefined

TSequencerStateSchema​

TSequencerStateSchema extends ZodTypeAny | undefined = undefined

TResourceDefs​

TResourceDefs extends | Record<string, DeclaredResourceEntry> | undefined = undefined

TTargetSchemas​

TTargetSchemas extends Record<string, ZodTypeAny> | undefined = undefined

TUses​

TUses extends readonly UsesEntry[] = readonly []

TRequestState​

TRequestState extends object = InferStateFromSchema<TRequestStateSchema>

TSessionState​

TSessionState extends object = Prettify<InferStateFromSchema<TSessionStateSchema> & InferCapabilitySessionState<TUses>>

TUserState​

TUserState extends object = InferStateFromSchema<TUserStateSchema>

TOrgState​

TOrgState extends object = InferStateFromSchema<TOrgStateSchema>

TSequencerState​

TSequencerState extends object = Prettify<InferStateFromSchema<TSequencerStateSchema> & InferCapabilitySequencerState<TUses>>

TResources​

TResources extends Record<string, AnyResourceRef> = Prettify<InferBlockResources<undefined, TResourceDefs> & InferCapabilityResources<TUses>>

TMergedTargetSchemas​

TMergedTargetSchemas extends Record<string, ZodTypeAny> | undefined = MergeTargetSchemas<TTargetSchemas, TUses>

TCapabilities​

TCapabilities extends Record<string, Record<string, (...args) => any>> = InferCapabilities<TUses>

TStateSchema​

TStateSchema extends ZodTypeAny | undefined = undefined

TParentStateSchema​

TParentStateSchema extends ZodTypeAny | undefined = undefined

TSelfState​

TSelfState extends object = Prettify<InferStateFromSchema<TStateSchema> & InferCapabilityOwnState<TUses>>

TParentState​

TParentState extends object = InferStateFromSchema<TParentStateSchema>

TFlowConfigSchema​

TFlowConfigSchema extends ZodTypeAny | undefined = undefined

TFlowConfig​

TFlowConfig extends object = InferFlowConfigFromSchema<TFlowConfigSchema>

Properties​

activeStatusMessage?​
activeStatusMessage?: string | ((input, ctx) => string);

Active status message for this block — declarative sugar for ctx.emit.status() at block start. A static string is emitted once when the block enters execution; a function receives (input, ctx) and its return value is emitted. Use direct ctx.emit.status() only when a block needs to update status mid-execution (e.g. per-file progress).

Inherited from​

Omit.activeStatusMessage

cacheable?​
cacheable?: true | BlockCacheableConfig;

Opt-in tool-result memoization. When set, and when this block is installed as a tool on a generator, the framework caches the tool's output keyed on (toolName, canonicalize(args), scope) and serves repeat calls from the cache. Errors are never cached. Identical concurrent calls within a request are coalesced (single-flight).

Pass true for cache-everything defaults, or an object to tune TTL, scope, key derivation, and a cacheIf predicate.

No effect when the block is used outside a generator's tool slot.

Inherited from​

Omit.cacheable

connectInput?​
connectInput?: ConnectorFn<unknown, TInput>;
Overrides​

Omit.connectInput

container?​
container?: object;
component?​
component?: string;
label?​
label?: string | ((input) => string);
metadata?​
metadata?:
| Record<string, unknown>
| ((input) => Record<string, unknown>);
Overrides​

Omit.container

description?​
description?: string;
Inherited from​

Omit.description

execute​
execute: (input, ctx) =>
| BlockDefinition<TInputSchema, TOutputSchema, TypeOf<TInputSchema>, TypeOf<TOutputSchema>>
| Promise<BlockDefinition<TInputSchema, TOutputSchema, TypeOf<TInputSchema>, TypeOf<TOutputSchema>>>;
Parameters​
input​

TInput

ctx​

BlockContext<TRequestState, TSessionState, TUserState, TOrgState, TResources, TSequencerState, unknown, TMergedTargetSchemas, TCapabilities, TSelfState, TParentState, TFlowConfig>

Returns​

| BlockDefinition<TInputSchema, TOutputSchema, TypeOf<TInputSchema>, TypeOf<TOutputSchema>> | Promise<BlockDefinition<TInputSchema, TOutputSchema, TypeOf<TInputSchema>, TypeOf<TOutputSchema>>>

flowConfigSchema?​
flowConfigSchema?: TFlowConfigSchema;

What this block requires of whatever flow installs it. Types ctx.flow.config off this schema, and makes the flow refuse when it cannot supply a bag that satisfies it. Names no flow, so the block stays portable. See BlockConfig.flowConfigSchema.

inputSchema?​
inputSchema?: TInputSchema;
Inherited from​

Omit.inputSchema

name​
name: string;
Inherited from​

Omit.name

onCompleted?​
onCompleted?: (output, ctx) => void | Promise<void>;
Parameters​
output​

TOutput

ctx​

BlockContext

Returns​

void | Promise<void>

Inherited from​

Omit.onCompleted

onErrored?​
onErrored?: (error, ctx) => void | Promise<void>;
Parameters​
error​

Error

ctx​

BlockContext

Returns​

void | Promise<void>

Inherited from​

Omit.onErrored

orgStateSchema?​
orgStateSchema?: TOrgStateSchema;
outputSchema?​
outputSchema?: TOutputSchema;
Inherited from​

Omit.outputSchema

parentStateSchema?​
parentStateSchema?: TParentStateSchema;

Expected shape of the immediate parent's own state.

requestStateSchema?​
requestStateSchema?: TRequestStateSchema;
rescue?​
rescue?: RescueHandlerSpec[];

Per-block rescue handlers. When this block's execution throws a non-SuspensionError, the first handler whose when matches runs with the block's own scoped context — so it can read sequencer state — and its output replaces the throw, letting the enclosing chain / fan-out continue. Set via block.rescue([...]). Sequencers handle their own chain-level rescue in the operation loop and do not use this field.

Inherited from​

Omit.rescue

resources?​
resources?: TResourceDefs;

Flat resource declaration. See HandlerConfig.resources.

retry?​
retry?: RetryPolicy;
Inherited from​

Omit.retry

routes​
routes: BlockDefinition<TInputSchema, TOutputSchema, TypeOf<TInputSchema>, TypeOf<TOutputSchema>>[];
sequencerStateSchema?​
sequencerStateSchema?: TSequencerStateSchema;
sessionStateSchema?​
sessionStateSchema?: TSessionStateSchema;
stateSchema?​
stateSchema?: TStateSchema;

This router's own request-scoped state. Read-only in execute — see ctx.self purity note above.

targetStateSchemas?​
targetStateSchemas?: TTargetSchemas;
transient?​
transient?: boolean;
Inherited from​

Omit.transient

userStateSchema?​
userStateSchema?: TUserStateSchema;
uses?​
uses?: TUses;

Capabilities to install. Merges resources, state schemas, targets, and any active preset surfaces into this block's config.

validateChunk?​
validateChunk?: (input, ctx) =>
| ChunkValidation
| Promise<ChunkValidation>;
Parameters​
input​

TInput

ctx​

BlockContext

Returns​

| ChunkValidation | Promise<ChunkValidation>

Inherited from​

Omit.validateChunk

validateRoute?​
validateRoute?: (candidate, routes, input, ctx) => boolean | Promise<boolean>;
Parameters​
candidate​

BlockDefinition<TInputSchema, TOutputSchema>

routes​

BlockDefinition<TInputSchema, TOutputSchema, TypeOf<TInputSchema>, TypeOf<TOutputSchema>>[]

input​

TInput

ctx​

BlockContext<TRequestState, TSessionState, TUserState, TOrgState, TResources, TSequencerState, unknown, TMergedTargetSchemas, TCapabilities, TSelfState, TParentState, TFlowConfig>

Returns​

boolean | Promise<boolean>


ScopeStateOps​

Scope-level state-mutation surface. Every method's resolved boolean is true when the write produced a real state change and false when the proposed update was structurally equal to the current state — in which case the framework suppresses the persist call and the corresponding state_change SSE emit. Existing callers that ignore the return value remain source-compatible.

Type Parameters​

TState​

TState extends object

Methods​

atomicState()​
atomicState(mutator): Promise<boolean>;
Parameters​
mutator​

(state) => Partial<TState>

Returns​

Promise<boolean>

deleteStateRecord()​
deleteStateRecord(field, key): Promise<boolean>;
Parameters​
field​

string

key​

string

Returns​

Promise<boolean>

incState()​
incState(increments): Promise<boolean>;
Parameters​
increments​

Record<string, number>

Returns​

Promise<boolean>

patchState()​
Call Signature​
patchState(updates): Promise<boolean>;
Parameters​
updates​

Partial<TState>

Returns​

Promise<boolean>

Call Signature​
patchState<TKey>(key, updater): Promise<boolean>;
Type Parameters​
TKey​

TKey extends string | number | symbol

Parameters​
key​

TKey

updater​

(current) => TState[TKey]

Returns​

Promise<boolean>

pushState()​
pushState(field, value): Promise<boolean>;
Parameters​
field​

string

value​

unknown

Returns​

Promise<boolean>

setState()​
setState(nextState): Promise<boolean>;
Parameters​
nextState​

TState

Returns​

Promise<boolean>

setStateRecord()​
setStateRecord(
field,
key,
value
): Promise<boolean>;
Parameters​
field​

string

key​

string

value​

unknown

Returns​

Promise<boolean>


SequencerDefinition​

Sequencer DSL definition. Types flow through the chain via schema inference:

  • TInput/TOutput are runtime value types (e.g., number, string)
  • Types are inferred from Zod schemas on BlockDefinition via z.infer<>
  • Connectors and conditions receive properly typed values from the previous step

The sequencer extends BlockDefinition<any, any> at the boundary for structural compatibility.

Extends​

Type Parameters​

TInput​

TInput

TOutput​

TOutput

TStateSchema​

TStateSchema extends ZodTypeAny | undefined = undefined

TFlowConfigSchema​

TFlowConfigSchema extends ZodTypeAny | undefined = undefined

Properties​

childBlocks?​
childBlocks?: readonly BlockDefinition<any, any, any, any>[];

Every block this block statically composes: a sequencer's step/tap/branch children and its chain-level rescue handlers, a router's routes, a rescue handler installed on any block.

Exists so the block graph is walkable at definition time. A SequencerOperation is {name, run} — the child it dispatches is captured inside a closure and retained nowhere else — so before this field the sequencer edge was opaque and a traversal from an action root could not see past the first .step(). Since a task board's drain is a sequencer, that made "every reachable detached board resolves to a binding" not merely unchecked but uncomputable. defineFlow walks this to assert it.

Retained for structure only — nothing executes through it. Dispatch still runs the operation closures.

Inherited from​

BlockDefinition.childBlocks

config​
config: BlockConfig<any, any, any, any>;
Inherited from​

BlockDefinition.config

declaredResources?​
declaredResources?: DeclaredResources;
Inherited from​

BlockDefinition.declaredResources

description?​
description?: string;
Inherited from​

BlockDefinition.description

dispatch?​
dispatch?: DispatchAddress;

The address this block dispatches to, when it is a dispatcher.

Stamped by dispatcher() (and by the task board on its dispatch block) and carried across every rebuild path, so defineFlow can walk the graph and refuse an address that resolves no entry, and a board can read which of its assignees dispatch without running anything. undefined on every block that dispatches nothing, which is every block that computes.

Inherited from​

BlockDefinition.dispatch

inputSchema​
inputSchema: any;
Inherited from​

BlockDefinition.inputSchema

kind​
kind: BlockKind;
Inherited from​

BlockDefinition.kind

name​
name: string;
Inherited from​

BlockDefinition.name

outputSchema​
outputSchema: any;
Inherited from​

BlockDefinition.outputSchema

ownDeclaredResources?​
ownDeclaredResources?: DeclaredResources;

This block's OWN declared resources: its own resources config plus its own capability-injected resources, EXCLUDING resources that bubble up from descendant/child blocks. Where declaredResources is the bubble-up (this block + all descendants), ownDeclaredResources is the strict subset this block itself contributes. For leaf blocks (handler/generator) the two are identical; for composites (sequencer/router) it omits children's declarations so the block-dispatch prefetch hook can load only this block's own declarations without re-loading children's.

Inherited from​

BlockDefinition.ownDeclaredResources

staticTools?​
staticTools?: readonly BlockDefinition<any, any, any, any>[];

A generator's authored static tools array, kept for the definition-time walk. generator() rewrites config.tools into one async resolver when a capability contributes tools, which hides the authored array from a walk that reads config.tools; this field keeps the tool edge walkable either way. Absent when tools was omitted or authored as a function.

Retained for structure only — the model is offered what config.tools resolves to.

Inherited from​

BlockDefinition.staticTools

transient​
transient: boolean;
Inherited from​

BlockDefinition.transient

Methods​

as()​
as(options): BlockDefinition<any, any, any, any>;

Return a copy of this block under a new name, a new description, or both. Everything else is the same block: schemas, connectors, resources, capabilities, rescue handlers and the model-output mapper ride the copy.

The new name is the copy's only name: the model calls it by that name, and its items, trace rows, errors and resume points carry it. The original block is not changed. An omitted option keeps the original's value; a blank name is refused when the copy is built.

Unlike asTool, .as() adds nothing at run time — no wrapper and no extra tool_output. The two stack: block.as({ name }).asTool() shows a tool pill under the new name, while block.asTool().as({ name }) renames only the wrapper and the pill keeps the original name.

Returns a plain block definition, so on a sequencer finish adding steps first and rename last.

Known limitation: a copy of a dispatcher() block still names its dispatches and dispatch refusals with the original name.

Parameters​
options​

BlockAsOptions

Returns​

BlockDefinition<any, any, any, any>

Inherited from​

BlockDefinition.as

asTool()​
asTool(opts?): BlockDefinition<any, any, any, any>;

Wrap this block so that, when executed inside a sequencer step, it emits a tool_output item with the same envelope and lifecycle the AI SDK tool-loop wrapper produces inside generators. The wrapped block runs normally and returns its typed output unchanged.

Use this when a tool has been moved out of an LLM-driven loop into a deterministic prefetch (e.g. inside a .parallel({...}) step) and the transcript should keep showing it as a tool pill.

Attribution (itemVisibility, agentName) is supplied via opts; when omitted the fields are not stamped on the emitted item.

Parameters​
opts?​

AsToolOpts

Returns​

BlockDefinition<any, any, any, any>

Inherited from​

BlockDefinition.asTool

branch()​
branch<TBranches>(branches): SequencerDefinition<TInput, BranchStepOutput<TBranches[keyof TBranches]>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TBranches​

TBranches extends Record<string, BranchStep<TOutput, TStateSchema, TFlowConfigSchema>>

Parameters​
branches​

TBranches

Returns​

SequencerDefinition<TInput, BranchStepOutput<TBranches[keyof TBranches]>, TStateSchema, TFlowConfigSchema>

connectInput()​
connectInput<TFrom>(mapper): SequencerDefinition<TFrom, TOutput, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TFrom​

TFrom

Parameters​
mapper​

ConnectorFn<TFrom, TInput>

Returns​

SequencerDefinition<TFrom, TOutput, TStateSchema, TFlowConfigSchema>

Overrides​

BlockDefinition.connectInput

connectOutput()​
connectOutput<TTo>(mapper): BlockDefinition<any, ZodTypeAny>;
Type Parameters​
TTo​

TTo

Parameters​
mapper​

(output, ctx) => TTo | Promise<TTo>

Returns​

BlockDefinition<any, ZodTypeAny>

Inherited from​

BlockDefinition.connectOutput

doUntil()​
Call Signature​
doUntil<TOutSchema>(condition, block): SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TOutSchema​

TOutSchema extends ZodTypeAny

Parameters​
condition​

(value, ctx) => boolean | Promise<boolean>

block​

BlockDefinition<any, TOutSchema>

Returns​

SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>

Call Signature​
doUntil<TStepIn, TOutSchema>(
condition,
connector,
block
): SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TStepIn​

TStepIn

TOutSchema​

TOutSchema extends ZodTypeAny

Parameters​
condition​

(value, ctx) => boolean | Promise<boolean>

connector​

ConnectorFn<TOutput, TStepIn>

block​

BlockDefinition<any, TOutSchema>

Returns​

SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>

doWhile()​
Call Signature​
doWhile<TOutSchema>(condition, block): SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TOutSchema​

TOutSchema extends ZodTypeAny

Parameters​
condition​

(value, ctx) => boolean | Promise<boolean>

block​

BlockDefinition<any, TOutSchema>

Returns​

SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>

Call Signature​
doWhile<TStepIn, TOutSchema>(
condition,
connector,
block
): SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TStepIn​

TStepIn

TOutSchema​

TOutSchema extends ZodTypeAny

Parameters​
condition​

(value, ctx) => boolean | Promise<boolean>

connector​

ConnectorFn<TOutput, TStepIn>

block​

BlockDefinition<any, TOutSchema>

Returns​

SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>

exitIf()​
exitIf(condition): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;

Exit the sequencer chain early if condition returns true. Current value becomes the sequencer output.

Parameters​
condition​

(value, ctx) => boolean | Promise<boolean>

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

forEach()​
Call Signature​
forEach<TOutSchema>(blockOrFactory, options?): SequencerDefinition<TInput, TypeOf<TOutSchema>[], TStateSchema, TFlowConfigSchema>;
Type Parameters​
TOutSchema​

TOutSchema extends ZodTypeAny

Parameters​
blockOrFactory​

| BlockDefinition<any, TOutSchema, any, TypeOf<TOutSchema>> | ((item, index, ctx) => BlockDefinition<any, TOutSchema>)

options?​

IterationOptions

Returns​

SequencerDefinition<TInput, TypeOf<TOutSchema>[], TStateSchema, TFlowConfigSchema>

Call Signature​
forEach<TStepIn, TOutSchema>(
connector,
blockOrFactory,
options?
): SequencerDefinition<TInput, TypeOf<TOutSchema>[], TStateSchema, TFlowConfigSchema>;
Type Parameters​
TStepIn​

TStepIn

TOutSchema​

TOutSchema extends ZodTypeAny

Parameters​
connector​

ConnectorFn<TOutput, TStepIn[]>

blockOrFactory​

| BlockDefinition<any, TOutSchema, any, TypeOf<TOutSchema>> | ((item, index, ctx) => BlockDefinition<any, TOutSchema>)

options?​

IterationOptions

Returns​

SequencerDefinition<TInput, TypeOf<TOutSchema>[], TStateSchema, TFlowConfigSchema>

forEachSideChain()​
Call Signature​
forEachSideChain(blockOrFactory, options?): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;
Parameters​
blockOrFactory​

| BlockDefinition<any, any, any, any> | ((item, index, ctx) => BlockDefinition<any, any>)

options?​

SideChainIterationOptions

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

Call Signature​
forEachSideChain<TStepIn>(
connector,
blockOrFactory,
options?
): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TStepIn​

TStepIn

Parameters​
connector​

ConnectorFn<TOutput, TStepIn[]>

blockOrFactory​

| BlockDefinition<any, any, any, any> | ((item, index, ctx) => BlockDefinition<any, any>)

options?​

SideChainIterationOptions

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

loopBack()​
loopBack(targetStepName, options): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;
Parameters​
targetStepName​

string

options​
maxIterations​

number

when?​

(value, ctx) => boolean | Promise<boolean>

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

map()​
map<TNext>(mapper): SequencerDefinition<TInput, TNext, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TNext​

TNext

Parameters​
mapper​

(input, ctx) => TNext | Promise<TNext>

Returns​

SequencerDefinition<TInput, TNext, TStateSchema, TFlowConfigSchema>

mapModelOutput()​
mapModelOutput(mapper): BlockDefinition<any, any>;

Declare a separate, model-visible representation of this block's output for use when the block is installed as a tool on a generator. The mapper fires only at the AI SDK bridge boundary, producing the string the LLM observes on its next turn.

The structured TOutput continues to flow through the block graph unchanged: tool_output items, downstream sequencer steps, devtool, tests, and replay all see the original value. Both TInputSchema and TOutputSchema are preserved.

The mapper is a property of the block definition. When the block is used as a regular sequencer step (not via tools: [...]), the mapper is silently inert.

The mapper is expected to be deterministic: history replay re-runs it rather than persisting its string output. A non-deterministic formatter would produce different strings between original turn and replay.

Parameters​
mapper​

(output, ctx) => string | Promise<string>

Returns​

BlockDefinition<any, any>

Inherited from​

BlockDefinition.mapModelOutput

parallel()​
parallel<TSteps>(steps, options?): SequencerDefinition<TInput, { [K in string | number | symbol]: ParallelStepOutput<TSteps[K]> }, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TSteps​

TSteps extends Record<string, ParallelStep<TOutput>>

Parameters​
steps​

TSteps

options?​
maxConcurrency?​

number

Returns​

SequencerDefinition<TInput, { [K in string | number | symbol]: ParallelStepOutput<TSteps[K]> }, TStateSchema, TFlowConfigSchema>

race()​
race(blocks, options?): SequencerDefinition<TInput, unknown, TStateSchema, TFlowConfigSchema>;

Run blocks concurrently, return the first successful result, abort the rest. Throws AggregateError if all fail.

Parameters​
blocks​

BlockDefinition<any, any, any, any>[]

options?​
maxConcurrency?​

number

Returns​

SequencerDefinition<TInput, unknown, TStateSchema, TFlowConfigSchema>

rescue()​
rescue(handlers): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;

Return a copy of this block that recovers from its own failures. If the block throws a non-SuspensionError, the first handler whose when matches runs — receiving the thrown error, with the same scoped context the block executed in (so it can read sequencer state) — and its output is returned in place of the throw. The enclosing sequencer chain, forEach fan-out, parallel branch, or router route therefore continues to the next step. ctx.wasRescued(block) reports true afterwards.

Available on every block kind. A leaf step recovers and the chain continues; a whole sequencer recovers as a unit (the steps after the failure have already unwound) — the same behavior as SequencerDefinition.rescue(), which is the chain-level spelling.

Parameters​
handlers​

RescueHandlerSpec[]

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

Overrides​

BlockDefinition.rescue

sideChain()​
Call Signature​
sideChain(block, options?): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;
Parameters​
block​

BlockDefinition<any, any>

options?​
name?​

string

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

Call Signature​
sideChain<TStepIn>(
connector,
block,
options?
): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TStepIn​

TStepIn

Parameters​
connector​

ConnectorFn<TOutput, TStepIn>

block​

BlockDefinition<any, any>

options?​
name?​

string

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

sideChainIf()​
Call Signature​
sideChainIf(
condition,
block,
options?
): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;

Conditional variant of .sideChain() — dispatches a fire-and-forget sidechain only when the condition is truthy. Complete no-op when falsy (no items, no trace).

The condition is evaluated once per execution before dispatching. The function form receives the running step value first and the BlockContext second — matching .stepIf and .tapIf — so authors can gate dispatch on either the upstream output or live session/request state.

Parameters​
condition​

boolean | ((value, ctx) => boolean | Promise<boolean>)

block​

BlockDefinition<any, any>

options?​
name?​

string

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

Call Signature​
sideChainIf<TStepIn>(
condition,
connector,
block,
options?
): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TStepIn​

TStepIn

Parameters​
condition​

boolean | ((value, ctx) => boolean | Promise<boolean>)

connector​

ConnectorFn<TOutput, TStepIn>

block​

BlockDefinition<any, any>

options?​
name?​

string

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

step()​
Call Signature​
step<TOutSchema>(block): SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TOutSchema​

TOutSchema extends ZodTypeAny

Parameters​
block​

BlockDefinition<any, TOutSchema>

Returns​

SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>

Call Signature​
step<TOutSchema>(block, options): SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TOutSchema​

TOutSchema extends ZodTypeAny

Parameters​
block​

BlockDefinition<any, TOutSchema>

options​

StepOptions

Returns​

SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>

Call Signature​
step<TFactory, TOutputSchema>(factory, config): SequencerDefinition<TInput, TypeOf<TOutputSchema>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TFactory​

TFactory extends InlineBlockFactory

TOutputSchema​

TOutputSchema extends ZodTypeAny

Parameters​
factory​

TFactory

config​

InlineConfig<TFactory, TOutput, TOutputSchema, TStateSchema, TFlowConfigSchema>

Returns​

SequencerDefinition<TInput, TypeOf<TOutputSchema>, TStateSchema, TFlowConfigSchema>

Call Signature​
step<TStepIn, TOutSchema>(connector, block): SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TStepIn​

TStepIn

TOutSchema​

TOutSchema extends ZodTypeAny

Parameters​
connector​

ConnectorFn<TOutput, TStepIn>

block​

BlockDefinition<any, TOutSchema>

Returns​

SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>

Call Signature​
step<TStepIn, TOutSchema>(
connector,
block,
options
): SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TStepIn​

TStepIn

TOutSchema​

TOutSchema extends ZodTypeAny

Parameters​
connector​

ConnectorFn<TOutput, TStepIn>

block​

BlockDefinition<any, TOutSchema>

options​

StepOptions

Returns​

SequencerDefinition<TInput, TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>

stepAll()​
stepAll<TSteps>(steps, options?): SequencerDefinition<TInput, { [K in string | number | symbol]: ParallelStepOutput<TSteps[K]> }, TStateSchema, TFlowConfigSchema>;

Run an array of blocks concurrently with the same input, collect all results as an ordered array. Like Promise.all.

Type Parameters​
TSteps​

TSteps extends ParallelStep<TOutput>[]

Parameters​
steps​

[...TSteps[]]

options?​
maxConcurrency?​

number

Returns​

SequencerDefinition<TInput, { [K in string | number | symbol]: ParallelStepOutput<TSteps[K]> }, TStateSchema, TFlowConfigSchema>

stepAny()​
stepAny(blocks): SequencerDefinition<TInput, unknown, TStateSchema, TFlowConfigSchema>;

Try blocks sequentially in order. Return the first successful result; skip remaining blocks. Throws AggregateError if all fail.

Parameters​
blocks​

BlockDefinition<any, any, any, any>[]

Returns​

SequencerDefinition<TInput, unknown, TStateSchema, TFlowConfigSchema>

stepIf()​
Call Signature​
stepIf<TOutSchema>(condition, block): SequencerDefinition<TInput, TOutput | TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TOutSchema​

TOutSchema extends ZodTypeAny

Parameters​
condition​

(input, ctx) => boolean | Promise<boolean>

block​

BlockDefinition<any, TOutSchema>

Returns​

SequencerDefinition<TInput, TOutput | TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>

Call Signature​
stepIf<TOutSchema>(
condition,
block,
options
): SequencerDefinition<TInput, TOutput | TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TOutSchema​

TOutSchema extends ZodTypeAny

Parameters​
condition​

(input, ctx) => boolean | Promise<boolean>

block​

BlockDefinition<any, TOutSchema>

options​

StepOptions

Returns​

SequencerDefinition<TInput, TOutput | TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>

Call Signature​
stepIf<TFactory, TOutputSchema>(
condition,
factory,
config
): SequencerDefinition<TInput, TOutput | TypeOf<TOutputSchema>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TFactory​

TFactory extends InlineBlockFactory

TOutputSchema​

TOutputSchema extends ZodTypeAny

Parameters​
condition​

(input, ctx) => boolean | Promise<boolean>

factory​

TFactory

config​

InlineConfig<TFactory, TOutput, TOutputSchema, TStateSchema, TFlowConfigSchema>

Returns​

SequencerDefinition<TInput, TOutput | TypeOf<TOutputSchema>, TStateSchema, TFlowConfigSchema>

Call Signature​
stepIf<TStepIn, TOutSchema>(
condition,
connector,
block
): SequencerDefinition<TInput, TOutput | TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TStepIn​

TStepIn

TOutSchema​

TOutSchema extends ZodTypeAny

Parameters​
condition​

(input, ctx) => boolean | Promise<boolean>

connector​

ConnectorFn<TOutput, TStepIn>

block​

BlockDefinition<any, TOutSchema>

Returns​

SequencerDefinition<TInput, TOutput | TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>

Call Signature​
stepIf<TStepIn, TOutSchema>(
condition,
connector,
block,
options
): SequencerDefinition<TInput, TOutput | TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TStepIn​

TStepIn

TOutSchema​

TOutSchema extends ZodTypeAny

Parameters​
condition​

(input, ctx) => boolean | Promise<boolean>

connector​

ConnectorFn<TOutput, TStepIn>

block​

BlockDefinition<any, TOutSchema>

options​

StepOptions

Returns​

SequencerDefinition<TInput, TOutput | TypeOf<TOutSchema>, TStateSchema, TFlowConfigSchema>

tap()​
Call Signature​
tap(blockOrFn): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;
Parameters​
blockOrFn​

| BlockDefinition<any, any, any, any> | ((value, ctx) => void | Promise<void>)

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

Call Signature​
tap<TFactory>(factory, config): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TFactory​

TFactory extends InlineBlockFactory

Parameters​
factory​

TFactory

config​

InlineTapConfig<TFactory, TOutput, TStateSchema, TFlowConfigSchema>

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

Call Signature​
tap<TStepIn>(connector, block): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TStepIn​

TStepIn

Parameters​
connector​

ConnectorFn<TOutput, TStepIn>

block​

BlockDefinition<any, any>

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

tapIf()​
Call Signature​
tapIf(condition, blockOrFn): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;
Parameters​
condition​

(value, ctx) => boolean | Promise<boolean>

blockOrFn​

| BlockDefinition<any, any, any, any> | ((value, ctx) => void | Promise<void>)

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

Call Signature​
tapIf<TStepIn>(
condition,
connector,
block
): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;
Type Parameters​
TStepIn​

TStepIn

Parameters​
condition​

(value, ctx) => boolean | Promise<boolean>

connector​

ConnectorFn<TOutput, TStepIn>

block​

BlockDefinition<any, any>

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

throwIf()​
throwIf(condition, error): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;

Throw an error if condition returns true — a guard primitive for halting the chain when an invariant fails. The error is supplied as either a static Error or a factory (value, ctx) => Error so the message can carry runtime context. Pairs with .rescue([{ when: [...] }]) when a typed early-stop pattern is wanted.

Parameters​
condition​

(value, ctx) => boolean | Promise<boolean>

error​

Error | ((value, ctx) => Error | Promise<Error>)

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>

validate()​
validate(): void;

Build-time conformance check between the sequencer's declared outputSchema (from config) and the chain's tracked schema (inferred from the final step). Throws SequencerSchemaMismatchError when structurally incompatible. No-op when either schema is undefined.

Conservative — checks top-level kind, object key sets, array element kinds, and one level of object-value kinds. Does NOT verify deep schema equivalence, refinements, brands, or union-variant shapes.

Returns void. Call as a terminal assertion (typically at end of build or in a setup test) — DSL operations added after .validate() are NOT covered by the check.

Returns​

void

waitForCondition()​
waitForCondition(predicate, options): SequencerDefinition<TInput, {
timedOut: boolean;
}, TStateSchema, TFlowConfigSchema>;

Suspend the chain until predicate over the request's item stream returns true, or until timeoutMs elapses (whichever comes first).

Evaluation: once synchronously at entry against the items already emitted on the response (no subscription if it returns true). That entry check sees what getItems() retains: every non-transient item, but only the most recent maxBufferSize (default 10,000) done transient ones, such as resource_change. Otherwise the runtime subscribes to subsequent item lifecycle events and re-runs the predicate on each — exactly once per event. On timeout or parent abort the subscription is torn down.

Output: { timedOut: false } when the predicate became true, { timedOut: true } when the timer fired first. Parent abort also resolves with { timedOut: false } — timedOut is strictly a timer signal, not a cancellation signal. Callers that need to distinguish "condition met" from "request cancelled" should check ctx.signal.aborted on the next step (the sequencer kernel also short-circuits between steps on an aborted signal). If the predicate itself throws the error propagates after teardown.

wakeOn is an optional cheap pre-filter on item events. When provided, the predicate is only re-evaluated for items the filter matches. Use to reduce wake-cost in high-fanout patterns (e.g. a task-board worker that only cares about task-change items, not resource_change churn from sibling workers). The filter does NOT affect the initial on-entry predicate evaluation; that always runs once before any subscription.

Parameters​
predicate​

(items) => boolean

options​
timeoutMs​

number

wakeOn?​

(item, kind) => boolean

Returns​

SequencerDefinition<TInput, { timedOut: boolean; }, TStateSchema, TFlowConfigSchema>

waitForSideChain()​
waitForSideChain(options?): SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>;
Parameters​
options?​
failOnError?​

boolean

timeoutMs?​

number

Returns​

SequencerDefinition<TInput, TOutput, TStateSchema, TFlowConfigSchema>


SpeakCapable​

VoiceProvider narrowed to require speak.

Extends​

Properties​

abilities​
readonly abilities: VoiceAbilities;
Inherited from​

VoiceProvider.abilities

defaultModels?​
readonly defaultModels?: object;

Provider-suggested default model ids per ability. Routers/pipelines fall back to these when the caller doesn't specify a model in SpeakOptions.model / TranscribeOptions.model.

speak?​
speak?: string;
transcribe?​
transcribe?: string;
Inherited from​

VoiceProvider.defaultModels

id​
readonly id: string;

Stable identifier for telemetry/registry use.

Inherited from​

VoiceProvider.id

providerName​
readonly providerName: string;

Short provider name (e.g. "openai", "elevenlabs", "composite").

Inherited from​

VoiceProvider.providerName

Methods​

listVoices()?​
listVoices?(): Promise<VoiceInfo[]>;
Returns​

Promise<VoiceInfo[]>

Inherited from​

VoiceProvider.listVoices

speak()​
speak(options): Promise<SpeakResult>;
Parameters​
options​

SpeakOptions

Returns​

Promise<SpeakResult>

Overrides​

VoiceProvider.speak

speakStream()?​
speakStream?(options): AsyncIterable<SpeakChunk>;
Parameters​
options​

SpeakOptions

Returns​

AsyncIterable<SpeakChunk>

Inherited from​

VoiceProvider.speakStream

transcribe()?​
transcribe?(options): Promise<TranscribeResult>;
Parameters​
options​

TranscribeOptions

Returns​

Promise<TranscribeResult>

Inherited from​

VoiceProvider.transcribe


SpeakOptions​

Arguments to VoiceProvider.speak and VoiceProvider.speakStream.

Properties​

model?​
model?: string;

Override the provider's default speak model.

outputFormat?​
outputFormat?: string;

Requested audio container/codec (e.g. "mp3", "wav", "pcm16").

providerOptions?​
providerOptions?: Record<string, unknown>;

Escape hatch for provider-specific options not covered by this interface.

signal?​
signal?: AbortSignal;

Abort signal forwarded to the underlying transport.

speed?​
speed?: number;

Speech speed multiplier (1.0 = normal). Provider may clamp.

text​
text: string;

Text to synthesize.

voice?​
voice?: string;

Provider-specific voice id. If omitted, the provider's default voice is used.


SpeakResult​

Result of a batch VoiceProvider.speak call.

Properties​

audio​
audio: Uint8Array;
mediaType​
mediaType: string;

MIME media type of audio (e.g. "audio/mpeg").


SpeakStreamCapable​

VoiceProvider narrowed to require speakStream.

Extends​

Properties​

abilities​
readonly abilities: VoiceAbilities;
Inherited from​

VoiceProvider.abilities

defaultModels?​
readonly defaultModels?: object;

Provider-suggested default model ids per ability. Routers/pipelines fall back to these when the caller doesn't specify a model in SpeakOptions.model / TranscribeOptions.model.

speak?​
speak?: string;
transcribe?​
transcribe?: string;
Inherited from​

VoiceProvider.defaultModels

id​
readonly id: string;

Stable identifier for telemetry/registry use.

Inherited from​

VoiceProvider.id

providerName​
readonly providerName: string;

Short provider name (e.g. "openai", "elevenlabs", "composite").

Inherited from​

VoiceProvider.providerName

Methods​

listVoices()?​
listVoices?(): Promise<VoiceInfo[]>;
Returns​

Promise<VoiceInfo[]>

Inherited from​

VoiceProvider.listVoices

speak()?​
speak?(options): Promise<SpeakResult>;
Parameters​
options​

SpeakOptions

Returns​

Promise<SpeakResult>

Inherited from​

VoiceProvider.speak

speakStream()​
speakStream(options): AsyncIterable<SpeakChunk>;
Parameters​
options​

SpeakOptions

Returns​

AsyncIterable<SpeakChunk>

Overrides​

VoiceProvider.speakStream

transcribe()?​
transcribe?(options): Promise<TranscribeResult>;
Parameters​
options​

TranscribeOptions

Returns​

Promise<TranscribeResult>

Inherited from​

VoiceProvider.transcribe


StrictViolation​

One strict-mode incompatibility, tagged with a JSON-path-ish location.

Properties​

path​
path: string;

Location of the offending node, e.g. $.metrics, $.items[], $.result|0.

reason​
reason: string;

Human-readable reason the construct fails strict mode.

typeName​
typeName: string;

Zod type name that triggered the violation, e.g. "ZodRecord".


TaskDispatcherConfig​

A task dispatcher: a board's dispatcher that hands its assignee's rows off to flow.task.actions[action]. TPayload is the worker input a key policy reads — a task board's TaskWorkerInput.

Type Parameters​

TPayload​

TPayload = unknown

Properties​

action​
action: string | TaskEntryChoice;

The entry name — resolves flow.task.actions[action]. Verified at defineFlow for a same-flow address, at the seam for a cross-flow one.

Or { among, by }, chosen per row: by is handed the row's assignee, id and input and answers one of the names in among. Every name in among is verified exactly as a string action is; an answer outside it refuses the dispatch no-entry. See TaskEntryChoice.

description?​
description?: string;
flowKind?​
flowKind?: string | TaskFlowTarget;

The other flow this dispatcher dispatches to. Omit for this flow's own task entry. Same skip as an internal cross-flow address: defineFlow cannot see the other flow's map, so the seam resolves it.

Or a function, looked up once per task: (task, ctx) => flowId, handed the row's assignee, id and input. Use it when which flow serves a task is known only when the task is handed over (a flow registered after start, say). Answering undefined refuses the dispatch flow-not-found, naming the assignee. See TaskFlowTarget.

name​
name: string;
session​
session: TaskSessionPolicy<TPayload>;

Which child session each row runs in. See TaskSessionPolicy.

state?​
state?:
| Readonly<Record<string, unknown>>
| TaskStateTarget;

The initial session state each row's child session is created with: a fixed object, or (task, ctx) => object, looked up per task and handed the row's assignee, id and input. The target flow's stateSchema parses it and its session.createCheck judges it. A child that already exists keeps its own. See TaskStateTarget.

transient?​
transient?: boolean;

Hide this block's trace from clients. Default: false.

type?​
type?: "task";

Discriminant. Omit it — a "per-task" / "per-worker" / { key } session already makes it a task dispatcher. The board reads dispatch.type === "task" off the block; callers do not set this.

wait?​
wait?: boolean;

Whether the board's drain waits on each row it hands over. Unset follows the board's mode: a plan board waits on every row, a delegation board on none. A board refuses a dispatcher that contradicts its mode.


TokenCounter​

Methods​

count()​
count(text, model): Promise<number>;
Parameters​
text​

string

model​

string

Returns​

Promise<number>

countMessages()​
countMessages(messages, model): Promise<number>;
Parameters​
messages​

LLMMessage[]

model​

string

Returns​

Promise<number>


TokenLedger​

Properties​

byModel​
readonly byModel: Record<string, ModelUsageEntry>;
remaining​
readonly remaining: number;
totalConsumed​
readonly totalConsumed: number;

ToolCacheEntry​

One cached tool-call entry.

Properties​

output​
output: unknown;

The tool's resolved output. Cached verbatim.

sourceTask?​
sourceTask?: object;

Attribution back to the task whose original call populated this entry, when the call ran inside a Task Board worker. A later cache-hit emit uses this to stamp sourceTask on its tool_output item.

collectionId​
collectionId: string;
taskId​
taskId: string;
storedAt​
storedAt: number;

Wall-clock millis (Date.now()) when the entry was written.

toolName​
toolName: string;

Name of the tool that produced the entry — used for invalidate-by-prefix.

ttl?​
ttl?: number;

Resolved TTL applied to this entry, in ms. undefined falls back to the store's default.


ToolCacheStore​

Store accessor surface. The substrate's compileToolsWithExecute (in generator.ts) only calls get and set on the resolved store; the additional delete / invalidate / size methods exist so the capability accessor can expose invalidation and stats to consumer blocks.

Properties​

defaultScope?​
defaultScope?: "request" | "session" | "run";
defaultTtl?​
defaultTtl?: number;

Methods​

delete()​
delete(key): void;
Parameters​
key​

string

Returns​

void

get()​
get(key): ToolCacheEntry | undefined;
Parameters​
key​

string

Returns​

ToolCacheEntry | undefined

invalidate()​
invalidate(keyOrPrefix): number;
Parameters​
keyOrPrefix​

string

Returns​

number

set()​
set(key, entry): void;
Parameters​
key​

string

entry​

ToolCacheEntry

Returns​

void

size()​
size(): number;
Returns​

number


TranscribeCapable​

VoiceProvider narrowed to require transcribe.

Extends​

Properties​

abilities​
readonly abilities: VoiceAbilities;
Inherited from​

VoiceProvider.abilities

defaultModels?​
readonly defaultModels?: object;

Provider-suggested default model ids per ability. Routers/pipelines fall back to these when the caller doesn't specify a model in SpeakOptions.model / TranscribeOptions.model.

speak?​
speak?: string;
transcribe?​
transcribe?: string;
Inherited from​

VoiceProvider.defaultModels

id​
readonly id: string;

Stable identifier for telemetry/registry use.

Inherited from​

VoiceProvider.id

providerName​
readonly providerName: string;

Short provider name (e.g. "openai", "elevenlabs", "composite").

Inherited from​

VoiceProvider.providerName

Methods​

listVoices()?​
listVoices?(): Promise<VoiceInfo[]>;
Returns​

Promise<VoiceInfo[]>

Inherited from​

VoiceProvider.listVoices

speak()?​
speak?(options): Promise<SpeakResult>;
Parameters​
options​

SpeakOptions

Returns​

Promise<SpeakResult>

Inherited from​

VoiceProvider.speak

speakStream()?​
speakStream?(options): AsyncIterable<SpeakChunk>;
Parameters​
options​

SpeakOptions

Returns​

AsyncIterable<SpeakChunk>

Inherited from​

VoiceProvider.speakStream

transcribe()​
transcribe(options): Promise<TranscribeResult>;
Parameters​
options​

TranscribeOptions

Returns​

Promise<TranscribeResult>

Overrides​

VoiceProvider.transcribe


TranscribeOptions​

Arguments to VoiceProvider.transcribe.

Properties​

audio​
audio: Uint8Array<ArrayBufferLike> | Blob;
language?​
language?: string;

BCP-47 language hint (e.g. "en", "es-MX").

mediaType?​
mediaType?: string;

MIME media type of audio. Some providers infer; declaring is safer.

model?​
model?: string;

Override the provider's default transcribe model.

providerOptions?​
providerOptions?: Record<string, unknown>;

Escape hatch for provider-specific options not covered by this interface.

signal?​
signal?: AbortSignal;

Abort signal forwarded to the underlying transport.


TranscribeResult​

Result of a VoiceProvider.transcribe call.

Properties​

language?​
language?: string;

BCP-47 language detected (or echoed from TranscribeOptions.language).

text​
text: string;

ViewRunContext​

What a view's block sees of its run, as ctx.view: set on every block of a view's run, child blocks included, and absent anywhere else.

Properties​

changed?​
readonly changed?: ViewChange;

The change this run may answer for, or undefined on a whole run (a first read, a connect, a notice with no ids, a view with no key).

Methods​

partial()​
partial<TEntries>(entries, options?): TEntries;

Answer for just some rows: entries are placed by key over the rows the screen holds (a key it holds is replaced in place), and removed keys are dropped. A key the screen doesn't hold makes it read the view whole: only a whole run says where a new row goes. Return what this returns. Opt-in: a view that never calls it answers whole. Answer whole whenever a change could move a row: a partial answer never reorders rows.

Type Parameters​
TEntries​

TEntries extends readonly unknown[]

Parameters​
entries​

TEntries

options?​
removed?​

readonly string[]

Returns​

TEntries

Throws​

When the run has no changed, or the view declares no key.


VoiceAbilities​

Per-ability flags declared by a provider. A true flag guarantees the corresponding method is present and callable; a false flag means the method is absent (and the narrowing type guards will return false).

Properties​

listVoices​
readonly listVoices: boolean;
speak​
readonly speak: boolean;
speakStream​
readonly speakStream: boolean;
transcribe​
readonly transcribe: boolean;

VoiceErrorOptions​

Constructor options for VoiceError. Mirrors FlowErrorOptions's shape.

Properties​

cause?​
cause?: unknown;

Underlying error, forwarded via the standard Error.cause mechanism.

kind​
kind: VoiceErrorKind;

Discriminator for downstream branching and retry classification.

message​
message: string;

Human-readable description.

provider​
provider: string;

Provider name (providerName from the underlying VoiceProvider).

retryable?​
retryable?: boolean;

Whether a retry could succeed. Omit to use the default for kind: rate_limit, provider_unavailable, and network default to true; all others default to false.

status?​
status?: number;

Optional transport-layer status code (e.g. HTTP 401 / 429 / 503).


VoiceInfo​

One entry in the provider's voice catalog. Returned by VoiceProvider.listVoices.

Properties​

accent?​
accent?: string;

Accent label, if the catalog declares one (e.g. "british", "southern").

age?​
age?: string;

Age label, if the catalog declares one (e.g. "young", "middle-aged").

gender?​
gender?: string;

Gender label, if the catalog declares one (e.g. "female", "male", "neutral").

id​
id: string;

Provider-specific voice id used as SpeakOptions.voice.

language?​
language?: string;

BCP-47 language tag, if the catalog declares one.

name​
name: string;

Human-readable label.

previewUrl?​
previewUrl?: string;

URL to a short audio preview, if the catalog provides one.

provider​
provider: string;

providerName of the owning provider.

raw?​
raw?: unknown;

Raw provider payload, for callers that want to surface custom fields.

supportedModels?​
supportedModels?: string[];

Speak models the voice is known to work with, if the catalog declares it.


VoiceProvider​

The canonical voice contract. All four methods are optional at the type level; presence is governed by abilities. Provider authors must keep the two in sync — declaring abilities.speak: true without implementing speak is a contract violation that the type guards trust (callers will see a native TypeError when they invoke a missing method).

Extended by​

Properties​

abilities​
readonly abilities: VoiceAbilities;
defaultModels?​
readonly defaultModels?: object;

Provider-suggested default model ids per ability. Routers/pipelines fall back to these when the caller doesn't specify a model in SpeakOptions.model / TranscribeOptions.model.

speak?​
speak?: string;
transcribe?​
transcribe?: string;
id​
readonly id: string;

Stable identifier for telemetry/registry use.

providerName​
readonly providerName: string;

Short provider name (e.g. "openai", "elevenlabs", "composite").

Methods​

listVoices()?​
listVoices?(): Promise<VoiceInfo[]>;
Returns​

Promise<VoiceInfo[]>

speak()?​
speak?(options): Promise<SpeakResult>;
Parameters​
options​

SpeakOptions

Returns​

Promise<SpeakResult>

speakStream()?​
speakStream?(options): AsyncIterable<SpeakChunk>;
Parameters​
options​

SpeakOptions

Returns​

AsyncIterable<SpeakChunk>

transcribe()?​
transcribe?(options): Promise<TranscribeResult>;
Parameters​
options​

TranscribeOptions

Returns​

Promise<TranscribeResult>


WebhookBindingsConfig​

A provider whose events each run one handler, matched by event type.

Properties​

on​
on: Record<string, WebhookEventBinding>;

Declarative event → handler map. Each key is matched by exact string equality against the host provider's extracted eventType. Keys are opaque strings — a typo simply never matches.

service?​
service?: undefined;

WebhookEventBinding​

A webhook event binding — an action in webhook form. It extends the shared ActionCore (the handler block plus execution policy like durable and tokenBudget) with the webhook-specific event mapping. Because it carries the core inline, the handler needs no entry in flow.actions: it is reached only through a verified webhook, never the public action endpoint or MCP.

input and sessionId may return a value or a Promise — the adapter awaits before constructing the dispatch envelope. when is synchronous: the adapter evaluates it in the hot path before any async work so the no-match case stays cheap.

Extends​

Properties​

autoResume?​
autoResume?: boolean;

Whether a request on this entry becomes its session's auto-resume target (latestRequestId): the request a client attaching to the session finds and reattaches to. Set false on a control action sent beside a running request, such as a line handed into it, so a client that reloads still finds the running request rather than the control. Default: true.

Inherited from​

ActionCore.autoResume

block​
block: BlockDefinition;
Inherited from​

ActionCore.block

concurrency?​
concurrency?: ConcurrencyConfig;

What happens when a dispatch arrives on this entry while another request on the same key (default: session) is already in flight. Overrides the flow-level default on request.concurrency. Resolution is per-entry-wins: entry.concurrency ?? flow.request?.concurrency ?? "allow", and every dispatch type gets the same ladder — a task or internal entry declares its policy exactly as a caller action does. Default when unset everywhere: "allow".

Inherited from​

ActionCore.concurrency

durable?​
durable?: boolean;

When true, this action is treated as durable at completion: its suspension records and lease are cleared when it completes. Suspending and crash recovery don't depend on it: they need a host with durable execution (on by default wherever stores persist), and sequencers checkpoint unless they set durable: false. Default: false.

Inherited from​

ActionCore.durable

input​
input: (event) => unknown;

Map the inbound event to the handler's input. May return a value or a Promise. The result is validated against the binding's inputSchema (falling back to block.inputSchema) by the runtime, the same way HTTP request bodies are.

Parameters​
event​

WebhookInboundEvent

Returns​

unknown

inputSchema?​
inputSchema?: ZodTypeAny;

Optional override for action-level input validation. Defaults to block.inputSchema — the block already validates its own input, so the action layer only needs an explicit schema when it should diverge from the block (MCP tool surface with richer .describe(), narrower public contract, escape hatches like z.unknown()).

Inherited from​

ActionCore.inputSchema

onCompleted?​
onCompleted?: BlockDefinition<any, any, any, any>;
Inherited from​

ActionCore.onCompleted

onErrored?​
onErrored?: BlockDefinition<any, any, any, any>;
Inherited from​

ActionCore.onErrored

sessionId?​
sessionId?: (event) => string | Promise<string> | undefined;

Derive the session id from the event. May return a value or a Promise. When omitted (or it resolves to undefined or ""), the webhook route makes a fresh one-off session id (oneOffSessionId()) before it dispatches — a webhook has no thread to key on.

Parameters​
event​

WebhookInboundEvent

Returns​

string | Promise<string> | undefined

taskOf?​
taskOf?: (input) => string | undefined;

Names the task this request is for, read from the action's input. When it returns an id, the runtime stamps it as OutputItem.taskId on the userMessage echo and on every item the request emits, unless a nearer scope marks another task with ctx._markTaskScope. Trace items stay unstamped. Returning undefined (or an empty string) stamps nothing.

The id is a label: it attributes items to a task's view and never routes, admits or authorizes. A reader that starts deciding by taskId checks it.

Parameters​
input​

any

Returns​

string | undefined

Inherited from​

ActionCore.taskOf

tokenBudget?​
tokenBudget?: object;
maxTotalTokens​
maxTotalTokens: number;
onExceeded?​
onExceeded?: "error" | "stop" | "warn";
warnAt?​
warnAt?: number;
Inherited from​

ActionCore.tokenBudget

userMessage?​
userMessage?: (input) => string | UserMessageEcho;

The request's input as a user message item, written when the request starts: the text alone, or the text with metadata the item carries for a client to read (say, to draw a message the flow was handed, not one a person typed, as something other than the person's line). The metadata is never sent to a model.

Parameters​
input​

any

Returns​

string | UserMessageEcho

Inherited from​

ActionCore.userMessage

when?​
when?: (event) => boolean;

Synchronous predicate. When provided and falsy for an event, the binding does not match and no handler runs. Use it to narrow a coarse event type to a sub-action, e.g. when: (e) => e.payload.action === "opened".

Parameters​
event​

WebhookInboundEvent

Returns​

boolean


WebhookInboundEvent​

The normalized inbound webhook event handed to a flow's webhook bindings. The adapter builds it after verifying the signature and parsing the body.

Type Parameters​

TPayload​

TPayload = unknown

Properties​

deliveryId?​
deliveryId?: string;

Stable per-delivery id from the host provider's deliveryId extractor, if configured.

eventType​
eventType: string | null;

Discriminator produced by the host provider's eventType extractor, or null.

headers​
headers: Headers;

Raw request headers.

payload​
payload: TPayload;

Parsed request body. unknown by default; narrow via defineWebhookBinding<T>().

provider​
provider: string;

Provider key — the :provider URL segment and webhooks map key (e.g. "stripe").

rawBody​
rawBody: Uint8Array;

Exact request bytes, preserved for advanced re-verification.


WebhookServiceConfig​

A provider whose events go to the sessions that follow them, through a service flow: the transport verifies, parses and reads the delivery id as for a binding, then service.normalize maps the delivery to zero or more normalized events and the host routes each through the flow's internal service.entry as the service (service:<provider>), firing each owner run it names. The 202 is sent once every run is durably recorded. A flow gets it from its provider's service flow factory (githubServiceFlow), not by hand. Never both on and service.

Properties​

on?​
on?: undefined;
service​
service: WebhookServiceRoute;

WebhookServiceRoute​

What a service route runs: the delivery's normalize, and the internal entry each event is routed through.

Properties​

entry​
readonly entry: string;

The flow's internal action that routes one normalized event.

Methods​

normalize()​
normalize(event, at): readonly object[];

The delivery as zero or more normalized events. Pure: the same delivery maps to the same events, so a redelivery names the same objects at the same versions. received is when the transport took it, in ms.

Parameters​
event​

WebhookInboundEvent

at​
received​

number

Returns​

readonly object[]

Type Aliases​

ActionConfig​

type ActionConfig<TBlock> = ActionCore<TBlock> & object;

A caller-addressed action: the shared ActionCore plus the exposure metadata for the client-facing HTTP and MCP surfaces, where a caller names the action and a principal is authorized per request. Lives in FlowDefinition.actions — the flow's public entries. Every other entry type (internal.actions, task.actions, and the webhook / schedule bindings) carries the same core on its own map and never enters this one.

Type Parameters​

TBlock​

TBlock extends BlockDefinition = BlockDefinition

Type Declaration​

description?​
description?: string;

Human-readable description. Required when the action is exposed via MCP — the text becomes the LLM-facing tool description and must communicate (1) what the tool does, (2) when to use it vs. siblings, (3) preconditions and side effects, (4) what each argument means. Used by the devtool for tooltips even when MCP is not enabled.

Defaults to block.description: defineFlow resolves it once, so every consumer reads the one value. Set it when a public MCP tool needs wording of its own.

mcp?​
mcp?: ActionMcpConfig;

Per-action MCP overrides.


ActionCore​

type ActionCore<TBlock> = object;

The shared core of an action: the executable unit (a block) plus its execution policy, independent of how the action is addressed or authenticated. Every form of action builds on this core — the caller-addressed ActionConfig (HTTP/MCP) and event-addressed transport bindings such as WebhookEventBinding — so the runtime dispatches, runs, and records them all the same way. Generalizing the core is what lets a webhook handler be a first-class action without living in flow.actions.

Extended by​

Type Parameters​

TBlock​

TBlock extends BlockDefinition = BlockDefinition

Properties​

autoResume?​
autoResume?: boolean;

Whether a request on this entry becomes its session's auto-resume target (latestRequestId): the request a client attaching to the session finds and reattaches to. Set false on a control action sent beside a running request, such as a line handed into it, so a client that reloads still finds the running request rather than the control. Default: true.

block​
block: TBlock;
concurrency?​
concurrency?: ConcurrencyConfig;

What happens when a dispatch arrives on this entry while another request on the same key (default: session) is already in flight. Overrides the flow-level default on request.concurrency. Resolution is per-entry-wins: entry.concurrency ?? flow.request?.concurrency ?? "allow", and every dispatch type gets the same ladder — a task or internal entry declares its policy exactly as a caller action does. Default when unset everywhere: "allow".

durable?​
durable?: boolean;

When true, this action is treated as durable at completion: its suspension records and lease are cleared when it completes. Suspending and crash recovery don't depend on it: they need a host with durable execution (on by default wherever stores persist), and sequencers checkpoint unless they set durable: false. Default: false.

inputSchema?​
inputSchema?: TBlock["inputSchema"];

Optional override for action-level input validation. Defaults to block.inputSchema — the block already validates its own input, so the action layer only needs an explicit schema when it should diverge from the block (MCP tool surface with richer .describe(), narrower public contract, escape hatches like z.unknown()).

onCompleted?​
onCompleted?: BlockDefinition<any, any>;
onErrored?​
onErrored?: BlockDefinition<any, any>;
taskOf?​
taskOf?: (input) => string | undefined;

Names the task this request is for, read from the action's input. When it returns an id, the runtime stamps it as OutputItem.taskId on the userMessage echo and on every item the request emits, unless a nearer scope marks another task with ctx._markTaskScope. Trace items stay unstamped. Returning undefined (or an empty string) stamps nothing.

The id is a label: it attributes items to a task's view and never routes, admits or authorizes. A reader that starts deciding by taskId checks it.

Parameters​
input​

TBlock["inputSchema"]["_output"]

Returns​

string | undefined

tokenBudget?​
tokenBudget?: object;
maxTotalTokens​
maxTotalTokens: number;
onExceeded?​
onExceeded?: "error" | "stop" | "warn";
warnAt?​
warnAt?: number;
userMessage?​
userMessage?: (input) => string | UserMessageEcho;

The request's input as a user message item, written when the request starts: the text alone, or the text with metadata the item carries for a client to read (say, to draw a message the flow was handed, not one a person typed, as something other than the person's line). The metadata is never sent to a model.

Parameters​
input​

TBlock["inputSchema"]["_output"]

Returns​

string | UserMessageEcho


ActionEntry​

type ActionEntry<TBlock> = TBlock | ActionConfig<TBlock>;

What an author writes for an entry: the block alone, or the object form when the entry sets anything beyond its block (userMessage, mcp, concurrency, a description that differs from the block's, …). defineFlow turns a bare block into { block }, so an instance only ever carries the object form.

Type Parameters​

TBlock​

TBlock extends BlockDefinition = BlockDefinition


AnyKitFactory​

type AnyKitFactory = object;

Any kit factory, for requires.

Properties​

kitName​
readonly kitName: string;
slots​
readonly slots: Readonly<Record<string, string>>;

BlockDispatchType​

type BlockDispatchType = "internal" | "task";

The types a block may dispatch — the ones whose trust a running request can supply itself. See the module header for why the others are excluded.


BlockInput​

type BlockInput<T> = T extends object ? V : never;

Extract the inferred input value type from a BlockDefinition.

Type Parameters​

T​

T


BlockKind​

type BlockKind = "handler" | "generator" | "evaluator" | "sequencer" | "router";

The five block kinds. handler runs code, generator asks a model to write, evaluator asks an evaluation model typed questions, and sequencer and router compose other blocks.


BlockManifestSource​

type BlockManifestSource = ManifestSource<BlockContext>;

A manifest source bound to the block context its entries reads.


BlockOutput​

type BlockOutput<T> = T extends object ? V : never;

Extract the inferred output value type from a BlockDefinition.

Type Parameters​

T​

T


BlockResult​

type BlockResult<TOutput> =
| {
status: "not_started";
}
| {
status: "running";
}
| {
output: TOutput;
status: "completed";
}
| {
error: Error;
status: "failed";
};

Type Parameters​

TOutput​

TOutput


BooleanAnswer​

type BooleanAnswer = object;

The answer to a boolean question.

Properties​

confidence?​
confidence?: number;

The model's own reported confidence in this answer, when it gave one.

probability​
probability: number;

The model's estimate that the answer is yes: P(true). It is an answer, not the model's confidence in it.

type​
type: "boolean";

BooleanQuestion​

type BooleanQuestion = object;

A yes/no question, answered as P(true).

Properties​

criteria?​
readonly criteria?: object;

Optional descriptions of what true and false mean.

false?​
readonly false?: EvaluationInput | null;
true?​
readonly true?: EvaluationInput | null;
instructions​
readonly instructions: EvaluationInput;
type​
readonly type: "boolean";

BranchStep​

type BranchStep<TInput, TStateSchema, TFlowConfigSchema> = readonly [connector: ConnectorFn<TInput, any>, condition: (input, ctx) => boolean | Promise<boolean>, block: BlockDefinition<any, any>];

Type Parameters​

TInput​

TInput

TStateSchema​

TStateSchema extends ZodTypeAny | undefined = undefined

TFlowConfigSchema​

TFlowConfigSchema extends ZodTypeAny | undefined = undefined


BranchStepOutput​

type BranchStepOutput<TStep> = TStep extends readonly [ConnectorFn<any, any>, (input, ctx) => boolean | Promise<boolean>, {
outputSchema: {
_output: infer V;
};
}] ? V : never;

Type Parameters​

TStep​

TStep


CachingBreakpointMode​

type CachingBreakpointMode = "auto" | "manual";

Where the adapter places cache breakpoints on Anthropic-flavored calls.


CachingTtl​

type CachingTtl = "5m" | "1h";

Cache tier. Anthropic currently exposes 5m and 1h ephemeral tiers.


CapabilityPresetCtx​

type CapabilityPresetCtx<TSessionState> = BlockContext<Record<string, unknown>, [TSessionState] extends [object] ? TSessionState : Record<string, unknown>>;

The ctx a preset callback receives: the consuming block's BlockContext, which is what the runtime passes it (collectOwnPresets). Session state is typed from the capability's sessionStateSchema; a capability that declares none reads it as any, since the block supplies the shape.

Being a BlockContext, it passes to any helper that takes one, and a key BlockContext does not declare is a compile error rather than any.

Type Parameters​

TSessionState​

TSessionState = any


CapabilityRef​

type CapabilityRef = DefinedCapability<any, any, any, any, any, any, any, any, any>;

Accepted in block-level and capability-level uses arrays.


ChoiceAnswer​

type ChoiceAnswer<TOption> = object;

The answer to a choice question. confidence is present only when the model reported one; the evaluator never supplies it.

Type Parameters​

TOption​

TOption extends string = string

Properties​

choice​
choice: TOption;

One of the question's option keys.

confidence?​
confidence?: number;

The model's own reported confidence in this answer, when it gave one.

probabilities?​
probabilities?: Record<TOption, number>;

Distribution over the option keys, when the model returned one.

type​
type: "choice";

ChoiceQuestion​

type ChoiceQuestion<TOption> = object;

A multiple-choice question. TOption is the union of option keys.

Type Parameters​

TOption​

TOption extends string = string

Properties​

criteria​
readonly criteria: Readonly<Record<TOption, EvaluationInput | null>>;

Option key → description (null for no description).

instructions​
readonly instructions: EvaluationInput;
type​
readonly type: "choice";

ClientDataOf​

type ClientDataOf<T> = T extends DefinedResourceCollection<any, infer C> ? C : T extends DefinedResource<any, infer C> ? C : never;

Extracts the projected client-data output type from a defined resource or collection. Resolves to the client projection's shape — Pick/Omit/computed-return/identity — so consumers derive the client type from the definition instead of hand-mirroring it. never for anything that isn't a defined resource/collection.

Type Parameters​

T​

T


CollectionHookContext​

type CollectionHookContext = object;

Context provided to per-instance lifecycle hooks.

Properties​

cell​
cell: string;

The storage cell this instance is persisted under: the exact scope key the engine writes the instance at. Resolved per instance key, so when a narrower overlapping collection owns the key, it is that collection's cell even if a broader handle did the write. It differs from scopeId whenever storage is partitioned below the bare identity — a flow-isolated collection (<id>:<flow>), an owner-pinned instance's per-(org, user) cell (<user>:~org:<org>), or an identity whose id needs escaping. Two instances with the same key are the same row exactly when they share a cell, so a hook mirroring rows elsewhere (a schedule index) keys on cell + key. Opaque: store and compare it, never parse it.

log​
log: (message) => void;

Log a message associated with this hook invocation.

Parameters​
message​

string

Returns​

void

orgId​
orgId: string;

The organization the execution that fired this hook was admitted under. Server-derived, never the caller's — a hook that persists a binding for later trusted use (a dynamic schedule's target organization) takes it from here rather than from the state it was handed, which the caller wrote.

scopeId​
scopeId: string;

The identifier of the concrete scope instance the hook fired in: userId for scope:"user", orgId for scope:"org", sessionId for scope:"session". Lets hooks correlate collection mutations back to the entity that owns them. Not where the row is stored — see cell for that.

scopeType​
scopeType: ScopeType;

The scope type this collection belongs to (session, user, org).


ConcurrencyConfig​

type ConcurrencyConfig =
| ImplementedConcurrencyPolicy
| {
key?: ConcurrencyKey;
policy: ImplementedConcurrencyPolicy;
};

Concurrency policy as declared on a flow. The string shorthand uses the default key ("session"); the object form overrides the key.

The debounce object shape ({ policy: "debounce"; windowMs; maxWaitMs? }) is reserved for the fast-follow and is rejected by validation in v1.


ConcurrencyKey​

type ConcurrencyKey = "session" | "user" | "none" | ((ctx) => string | undefined);

What the policy keys on. Preset names resolve from the dispatch envelope; a function returns a custom key (or undefined to opt this dispatch out of arbitration entirely).

  • "session" (default): the tenant-namespaced session id. Every dispatch names one, so a one-off run arbitrates on its own one-off session.
  • "user": the tenant-namespaced user id.
  • "none": disable arbitration for this action.
  • a function: returns a custom key string, or undefined for no arbitration (e.g. a webhook delivery id pulled from metadata).

ConcurrencyPolicyName​

type ConcurrencyPolicyName = "allow" | "queue" | "reject" | "hold" | "defer" | "debounce" | "restart";

All policy names. debounce (collapse-a-burst) and restart (cancel-in-flight) are reserved: they parse into the type so the follow-up work is additive, but validateConcurrencyConfig rejects them in v1.

  • allow (default): run concurrently. Today's behavior, fully backward compatible.
  • queue: serialize requests on the key in arrival order (FIFO). One runs to completion before the next starts.
  • reject: while one request holds the key, drop a competing one (the caller gets a 409-shaped error naming the in-flight request).
  • hold: run at once, as allow does, and occupy the key while running. Never waits and is never refused, but a defer, queue, or reject request on the key sees it. For a turn that follow-up work must not overlap, such as a reply in a conversation.
  • defer: wait until no request holds or waits on the key, then run and occupy it. Several deferred requests run one at a time. The wait has no budget: it ends when the requests ahead settle, or, on a shared lease backend, when a crashed process's place expires.

ConfigArgOf​

type ConfigArgOf<Self> = Self extends object ? [I] extends [never] ? never : I : never;

The .config() argument type, read from the receiver's __configInType carrier. Resolves to never when the capability declares no config, so .config() is a compile error on a config-less capability.

Type Parameters​

Self​

Self


ContextFunction​

type ContextFunction = (input, ctx) => string;

The function signature returned by contextFn. Compatible with generator context slots — receives the block input and ctx, returns a string.

Parameters​

input​

unknown

ctx​

BlockContext

Returns​

string


ContextObject​

type ContextObject<TInput, TCtx> = object;

Object-form context: keys become XML tag names. Values may be strings, nested ContextObjects (recursive), functions resolved at render time, heterogeneous arrays of those (strings, functions, nested objects mixed), or null/undefined placeholders that reserve insertion order but emit nothing if no contributor fills them.

Authored keys may be camelCase, snake_case, or kebab-case — all normalize to kebab-case before aggregation, so contributions to the same key from different sources collapse into a single tag.

Type Parameters​

TInput​

TInput = unknown

TCtx​

TCtx = BlockContext

Index Signature​

[tagName: string]:
| string
| ContextObject<TInput, TCtx>
| ContextValueFn<TInput, TCtx>
| (
| string
| ContextObject<TInput, TCtx>
| ContextValueFn<TInput, TCtx>
| null
| undefined)[]
| null
| undefined

Example​

generator({
prompt: "You are a research assistant.",
context: {
documents: [docA, docB],
userPreferences: () => loadPrefs(),
memory: { shortTerm: items, longTerm: () => loadLongTerm() },
skills: [catalogContext, activeContext],
},
})

ContextOf​

type ContextOf<T, TKind, _TResources> = TKind extends "resource" ? ResourceContext<AsStateObject<StateOf<T>>> : TKind extends "session" ? SessionScopeHandle<AsStateObject<StateOf<T>>> : TKind extends "request" ? RequestScopeHandle<AsStateObject<StateOf<T>>> : TKind extends "user" ? UserScopeHandle<AsStateObject<StateOf<T>>> : OrgScopeHandle<AsStateObject<StateOf<T>>>;

Type Parameters​

T​

T

TKind​

TKind extends "resource" | "request" | "session" | "user" | "org" = "resource"

_TResources​

_TResources extends Record<string, ResourceRef<any>> = Record<string, ResourceRef<any>>


DeclaredResources​

type DeclaredResources = Record<string, DeclaredResourceEntry>;

Flat resource declaration: accessor key → resource definition. The resource's intrinsic scope (and flowIsolation) determines its storage placement; the accessor key is what consumers reach for via ctx.resources.<key>. The two are independent — multiple accessor keys can point at the same (scope, ref) only if the storage keys do not collide (see flow-build collision detection).


DefinedProjectedResourceCollection​

type DefinedProjectedResourceCollection<TState, TStateSchema, TClient> = DefinedResourceCollection<TState, TClient> & ProjectedCollectionBrand<TStateSchema>;

The definition returned by defineProjectedResourceCollection — a DefinedResourceCollection intersected with the projected brand, so the inference conditionals (which test & { projected: true } first) resolve it to the read-only ref.

Type Parameters​

TState​

TState extends JsonObject = JsonObject

TStateSchema​

TStateSchema extends ZodTypeAny = ZodTypeAny

TClient​

TClient = JsonValue


DefinedResource​

type DefinedResource<TState, TClient> = ResourceConfig & object;

Branded definition returned by defineResource(). Carries the resolved state type and intrinsic scope/flowIsolation stamps used by the framework to derive storage keys and detect cross-flow collisions. ClientType is the projected client-data shape derived from the client config — a pure type-level brand (runtime clientData stays JsonValue). Extract it with ClientDataOf<typeof resource>.

Type Parameters​

TState​

TState extends JsonObject = JsonObject

TClient​

TClient = JsonValue

Type Declaration​

ClientType​
ClientType: TClient;
ContextType​
ContextType: ResourceContext<TState>;
StateType​
StateType: TState;

DefinedResourceCollection​

type DefinedResourceCollection<TState, TClient> = ResourceCollectionConfig & object;

Branded type returned by defineResourceCollection(). Carries phantom StateType for downstream type inference, and ClientType — the projected client-data shape derived from the client config (expose/exclude/data/identity). ClientType is a pure type-level brand; the runtime clientData payload stays JsonValue. Extract it with ClientDataOf<typeof collection>. The prefetchMode config field still exists (it controls server-side loading behaviour), but it no longer affects the ref's read-method signatures — both eager and lazy collections expose the same async ResourceCollectionRef interface.

Type Parameters​

TState​

TState extends JsonObject = JsonObject

TClient​

TClient = JsonValue

Type Declaration​

__brand​
readonly __brand: "ResourceCollection";
ClientType​
ClientType: TClient;
StateType​
StateType: TState;

DispatchAddress​

type DispatchAddress =
| {
action: string;
flowKind?: string;
type: "internal";
}
| {
action: string | TaskEntryChoice;
flowKind?: string | TaskFlowTarget;
session: TaskSessionPolicy<any>;
state?: | Readonly<Record<string, unknown>>
| TaskStateTarget;
type: "task";
wait?: boolean;
};

Where a dispatcher sends. (type, action) is static by construction: it is what the block declares, so its reachable entries are declared rather than computed at run time. An internal action chosen from data is a router over declared dispatchers, not a dynamic address. A task address may choose its entry per row (TaskEntryChoice), but only among declared ones: every name it can answer is listed on the address and verified like a string action. Its flowKind may be a TaskFlowTarget: the entry is still declared, and only which flow serves it is looked up when a task is handed over. Such a target is cross-flow, so nothing at definition time can list the flows it reaches.

defineFlow verifies the same-flow pair. A cross-flow address is equally static and equally declared — it is simply verified one layer later, by the seam, against the flow the running process registered under that kind.

A task address also carries the dispatcher's session policy — declared once on the dispatcher and read by the board that holds it, so the board can list statically which of its assignees dispatch and where their rows land.

Union Members​

Type Literal​
{
action: string;
flowKind?: string;
type: "internal";
}
action​
readonly action: string;

The entry name — flow.internal.actions[action].

flowKind?​
readonly flowKind?: string;

The flow the entry lives on, when it is not this one. Absent is same-flow, which is the whole of what defineFlow can check.

A cross-flow address is declared exactly like a same-flow one — a string on the block, resolved by the walk it is reachable from — but the flow it names is registered independently of this one, so nothing at definition time can read its entry map. The check moves to the seam, where it stays a named refusal: flow-not-found when this process has no such flow, no-entry when the flow has no such entry. Never a retry, a queue, or a fall through to this flow's own map.

type​
readonly type: "internal";

Type Literal​
{
action: string | TaskEntryChoice;
flowKind?: string | TaskFlowTarget;
session: TaskSessionPolicy<any>;
state?: | Readonly<Record<string, unknown>>
| TaskStateTarget;
type: "task";
wait?: boolean;
}
action​
readonly action: string | TaskEntryChoice;

The entry name — flow.task.actions[action] — or a choice among declared entry names, made per row (see TaskEntryChoice).

flowKind?​
readonly flowKind?: string | TaskFlowTarget;

The flow the entry lives on, when it is not this one. Same skip as an internal cross-flow address: defineFlow cannot see the other flow's map, so the seam resolves it. A function is looked up per task (see TaskFlowTarget) and is always cross-flow.

session​
readonly session: TaskSessionPolicy<any>;
state?​
readonly state?:
| Readonly<Record<string, unknown>>
| TaskStateTarget;

The initial state each task's child session is created with: a fixed object, or looked up per task (see TaskStateTarget). A child that already exists keeps its own.

type​
readonly type: "task";
wait?​
readonly wait?: boolean;

Whether the board's drain waits on a row it hands over. Absent follows the board's mode: a plan board waits, a delegation board doesn't. A board refuses one that contradicts its mode.


DispatcherConfig​

type DispatcherConfig<TInputSchema, TPayload> =
| InternalDispatcherConfig<TInputSchema>
| TaskDispatcherConfig<TPayload>;

Either dispatcher config; session (and an explicit type) discriminates.

Type Parameters​

TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

TPayload​

TPayload = unknown


DispatcherSession​

type DispatcherSession<TInput> =
| {
key: (input, ctx) => string;
state?: | Readonly<Record<string, unknown>>
| ((input, ctx) => Readonly<Record<string, unknown>>);
}
| {
id: (input, ctx) => string;
}
| {
from: true;
};

Which session an internal dispatch runs in, computed from the dispatcher's input.

  • key — a child of the running session, derived from the returned key. Minted on first use, adopted after: the same key from the same parent lands on the same child, so a retry re-enters the work it started. Use a value that names the unit of work — a document id, an issue key. Add state for the child's initial session state: the target flow's stateSchema parses it and its session.createCheck judges it. A child that already exists keeps its own.
  • id — an existing session. Delivered into it when it exists and belongs to this principal on this flow; refused by name otherwise. Never created.
  • from: true — the seam-stamped sender. The block names no session id; the runtime delivers into metadata.dispatch.from.sessionId. Use this to reply, not { id: (input) => input.replyTo }.

Type Parameters​

TInput​

TInput


DispatchHandle​

type DispatchHandle = z.infer<typeof dispatchHandleSchema>;

DispatchOutcome​

type DispatchOutcome =
| {
adopted: boolean;
ok: true;
requestId: string;
sessionId: string;
}
| {
detail: string;
ok: false;
refused: DispatchRefusal;
};

Outcome of a dispatch. adopted says whether the child session already existed.

Union Members​

Type Literal​
{
adopted: boolean;
ok: true;
requestId: string;
sessionId: string;
}

Type Literal​
{
detail: string;
ok: false;
refused: DispatchRefusal;
}
detail​
readonly detail: string;

Operator-facing detail. Not a stable contract; branch on refused.

ok​
readonly ok: false;
refused​
readonly refused: DispatchRefusal;

DispatchRefusal​

type DispatchRefusal =
| "no-entry"
| "flow-not-found"
| "session-not-found"
| "session-not-addressable"
| "key-occupied"
| "create-refused"
| "no-dispatch-operation"
| "dispatch-rejected"
| "external-flow-runner"
| "no-sender";

Why a dispatch was refused. A name the caller can branch on rather than a message it has to parse. Every refusal is decided before anything is dispatched, so a refused caller still owns whatever it was handing over.


DispatchSpec​

type DispatchSpec = object;

What a dispatcher hands the seam. Every field is computed by the block that dispatches.

Properties​

action​
readonly action: string;
flowKind?​
readonly flowKind?: string;

The flow instance the entry lives on — its exact id — when it is not the sending request's own.

from​
readonly from: string;

The dispatching block's name. Provenance only — never resolved.

payload​
readonly payload: unknown;

The entry's input. Validated by the entry's own schema on arrival.

provenance?​
readonly provenance?: Readonly<Record<string, unknown>>;

Server-derived facts stamped onto the child request's record beside the address — a board puts its task id here. Never a caller's bag: it lands on the wire as server truth, so only put here what the runtime produced.

session​
readonly session: SessionTarget;
type​
readonly type: BlockDispatchType;
waits?​
readonly waits?: boolean;

The sending request parks on the dispatched request at once, waiting for it (dispatcher({ wait: true })). The seam stamps the child with who waits on it, from the sender's own server-derived facts, so the child's wait depth counts its sender before the sender's park is written.


DispatchType​

type DispatchType = "public" | "webhook" | "schedule" | "task" | "internal";

The kinds of dispatch a flow can receive. Each resolves one map on the flow.


DispatchWaitResult​

type DispatchWaitResult = z.infer<typeof dispatchWaitResultSchema>;

EntryCoordinate​

type EntryCoordinate = object;

The protocol coordinate a webhook or schedule dispatch carries. Stamped by the adapter into the namespaced metadata slot the engine reads it back from; absent for the three types whose name is the whole address.

Properties​

schedule?​
readonly schedule?: object;
scheduleId?​
readonly scheduleId?: string;
webhook?​
readonly webhook?: object;
eventType?​
readonly eventType?: string | null;
provider?​
readonly provider?: string;

EntryMaps​

type EntryMaps<TEntry> = object;

The five maps, generic over the entry value so a narrowed view (the concurrency arbiter reads only concurrency) resolves through the same function as a full FlowInstance.

Type Parameters​

TEntry​

TEntry

Properties​

actions​
readonly actions: Record<string, TEntry>;
internal?​
readonly internal?: object;
actions?​
readonly actions?: Record<string, TEntry>;
schedules?​
readonly schedules?: object;
static?​
readonly static?: Record<string, TEntry>;
task?​
readonly task?: object;
actions?​
readonly actions?: Record<string, TEntry>;
webhooks?​
readonly webhooks?: Record<string,
| {
on?: Record<string, TEntry>;
}
| undefined>;

EvaluationInput​

type EvaluationInput = string | JsonObject | JsonValue[];

Text or structured JSON an evaluation model reads: the evaluated state, a question's instructions, or an option's description.


EvaluationQuestionType​

type EvaluationQuestionType = "choice" | "score" | "boolean";

The question types an evaluation model can be asked.


EvaluatorAnswer​

type EvaluatorAnswer<TQuestion> = TQuestion extends ChoiceQuestion<infer TOption> ? ChoiceAnswer<TOption> : TQuestion extends ScoreQuestion ? ScoreAnswer : BooleanAnswer;

The answer type for one question, typed by that question.

Type Parameters​

TQuestion​

TQuestion extends EvaluatorQuestion = EvaluatorQuestion


EvaluatorAnswers​

type EvaluatorAnswers<TQuestions> = { [TId in keyof TQuestions]: EvaluatorAnswer<TQuestions[TId]> };

Answers for a whole question set, keyed by question id.

Type Parameters​

TQuestions​

TQuestions extends EvaluatorQuestions = EvaluatorQuestions


EvaluatorDefinition​

type EvaluatorDefinition<TInputSchema, TInput, TQuestions> = BlockDefinition<TInputSchema, EvaluatorOutputSchema<TQuestions>, TInput, EvaluatorOutput<TQuestions>>;

The block an evaluator call returns.

Type Parameters​

TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

TInput​

TInput = z.infer<TInputSchema>

TQuestions​

TQuestions extends EvaluatorQuestions = EvaluatorQuestions


EvaluatorOutput​

type EvaluatorOutput<TQuestions> = object;

An evaluator block's output.

Type Parameters​

TQuestions​

TQuestions extends EvaluatorQuestions = EvaluatorQuestions

Properties​

answers​
answers: EvaluatorAnswers<TQuestions>;

EvaluatorOutputSchema​

type EvaluatorOutputSchema<TQuestions> = z.ZodType<EvaluatorOutput<TQuestions>>;

The output schema type an evaluator carries, so BlockOutput<typeof block> and sequencer steps see typed answers. At runtime the output is not re-validated: the SDK has already checked every answer against its question.

Type Parameters​

TQuestions​

TQuestions extends EvaluatorQuestions = EvaluatorQuestions


EvaluatorQuestion​

type EvaluatorQuestion =
| ChoiceQuestion<string>
| ScoreQuestion
| BooleanQuestion;

Any one evaluator question.


EvaluatorQuestions​

type EvaluatorQuestions = Record<string, EvaluatorQuestion>;

A question set: question id → question. Ids become the keys of answers.


EvaluatorQuestionsSlot​

type EvaluatorQuestionsSlot<TInput, TQuestions, TContext> =
| TQuestions
| ((input, ctx) => TQuestions | Promise<TQuestions>);

A static question set, or one computed per execution from the input and context.

Type Parameters​

TInput​

TInput

TQuestions​

TQuestions extends EvaluatorQuestions

TContext​

TContext = BlockContext


EvictionPolicy​

type EvictionPolicy = "none" | "lru" | "oldest";

FacetedClientConfig​

type FacetedClientConfig<TStateSchema, TEvaluator> = CollectionClientConfig<StateFor<TStateSchema, TEvaluator>>;

The client visibility config a faceted collection accepts.

Type Parameters​

TStateSchema​

TStateSchema extends z.AnyZodObject = z.AnyZodObject

TEvaluator​

TEvaluator extends AnyEvaluatorBlock = AnyEvaluatorBlock


FacetedCollection​

type FacetedCollection<TName, TState, TFacets, TClientData> = object;

What defineFacetedCollection returns.

Type Parameters​

TName​

TName extends string

TState​

TState extends JsonObject

TFacets​

TFacets

TClientData​

TClientData = TState

Properties​

collection​
collection: DefinedResourceCollection<TState, TClientData>;

The collection. Declare it on your own blocks under name. Carries the client projection.

reindex​
reindex: BlockDefinition<ZodType<FacetReindexInput>, ZodType<FacetReindexOutput>>;

Classifies rows without facets (every row with force) through the same path as a write.

resources​
resources: { [K in TName]: DefinedResourceCollection<TState, TClientData> } & DeclaredResources;

Pass to defineFlow({ resources }): the collection under name, plus every resource the evaluator declares.

search​
search: BlockDefinition<ZodType<FacetSearchInput<TFacets>>, ZodType<FacetSearchOutput>>;

Filters stored facets and returns matching keys. Runs no model. Usable as an agent's tool.


FacetedCollectionConfig​

type FacetedCollectionConfig<TName, TStateSchema, TEvaluator, TClient> = Omit<ResourceCollectionConfig, "stateSchema" | "reactTo" | "client" | "writable"> & object;

Config for defineFacetedCollection.

Type Parameters​

TName​

TName extends string = string

TStateSchema​

TStateSchema extends z.AnyZodObject = z.AnyZodObject

TEvaluator​

TEvaluator extends AnyEvaluatorBlock = AnyEvaluatorBlock

TClient​

TClient extends | FacetedClientConfig<TStateSchema, TEvaluator> | undefined = | FacetedClientConfig<TStateSchema, TEvaluator> | undefined

Type Declaration​

client?​
client?: TClient;

Client visibility. Reads and deletes are allowed; content.create and content.update are refused, because a client body edit runs no reaction and would leave facets describing text the row no longer has.

evaluator​
evaluator: TEvaluator;

The evaluator block that classifies each body. Its questions must be a fixed object: they type the stored facets and the search's options. It receives the body as its input.

name​
name: TName;

The accessor the collection is registered under. The returned resources registers it under this name; the search, reindex and the reaction read it from here.

reactTo?​
reactTo?: Omit<ReactiveBindings<AsStateObject<FacetedState<z.infer<TStateSchema>, FacetsOf<TEvaluator>>>>, "contentUpdated">;

The app's own created / stateUpdated / deleted bindings. contentUpdated is the definer's.

stateSchema​
stateSchema: TStateSchema;

The app's own fields. facets and indexedAs are added.

writable?​
writable?: true;

Must stay writable: indexing writes facets and indexedAs on every body write, so writable: false is refused.


FacetedState​

type FacetedState<TState, TFacets> = TState & object;

The stored state of a faceted collection instance: the app's own fields, plus facets (null until classified, and whenever a classification failed or was superseded) and indexedAs.

Type Parameters​

TState​

TState

TFacets​

TFacets

Type Declaration​

facets​
facets: TFacets | null;
indexedAs​
indexedAs: string | null;

FacetReindexInput​

type FacetReindexInput = object;

What reindex takes: force reclassifies every row with a body.

Properties​

force?​
force?: boolean;

FacetReindexOutput​

type FacetReindexOutput = object;

What reindex returns: reindexed holds the keys whose body it classified, and failed the keys whose classification failed (they keep no facets and are not retried). A row a newer write rewrote mid-reindex is in neither: that write indexes it.

Properties​

failed​
failed: string[];
reindexed​
reindexed: string[];

FacetSearchInput​

type FacetSearchInput<TFacets> = { [K in ChoiceIdsOf<TFacets>]?: TFacets[K] extends ChoiceAnswer<infer O> ? O : never } & object;

What a facet search takes: one optional value per choice question (its option keys), plus an optional minConfidence in [0, 1].

Type Parameters​

TFacets​

TFacets

Type Declaration​

minConfidence?​
minConfidence?: number;

FacetSearchOutput​

type FacetSearchOutput = object;

What a facet search returns: the matching instance keys.

Properties​

keys​
keys: string[];

FacetsOf​

type FacetsOf<TEvaluator> = BlockOutput<TEvaluator> extends object ? A : never;

The answers an evaluator block returns, keyed by question id: what facets stores.

Type Parameters​

TEvaluator​

TEvaluator


FactoryConfig​

type FactoryConfig<TFactory> = TFactory extends (config) => any ? C : never;

Extracts the config parameter type from a block factory function.

Type Parameters​

TFactory​

TFactory


FlowCardinality​

type FlowCardinality = "singleton" | "collection";

How many registered instances a flow definition supports.

  • "singleton" (default) — one instance per kind. Its id is its kind, so the addresses an application already uses (/api/flows/<kind>/…, fsdev run <kind>) keep resolving unchanged.
  • "collection" — several named copies of one definition. Every instance must be created with an explicit id, and that id is the only address it answers to; the bare kind never selects a member, even when only one is registered.

Declared on the definition only. It is the flow's identity policy, not a per-instance choice: a hand-built singleton of a collection kind would turn the bare kind into an accidental address for the whole collection.


FlowConfigInput​

type FlowConfigInput<TConfigSchema> = TConfigSchema extends ZodTypeAny ? TConfigSchema["_input"] : never;

What a caller may hand a flow factory as config — the INPUT side of the declared schema, so a key with a .default() may be omitted.

never when the definition declares no configSchema: a copy may only carry settings the definition declared, and that is decidable here.

Type Parameters​

TConfigSchema​

TConfigSchema extends ZodTypeAny | undefined


FlowConfigIssue​

type FlowConfigIssue = object;

One reason a config bag was refused, as data: what the refusal's message renders, path by path, so a caller can read it without parsing the message.

Properties​

code​
code: string;

Zod's issue code ("unrecognized_keys" names one undeclared key, at its own path), or the framework's: "no_config_schema" (the flow declares none) and "block_contributes" (a block's flowConfigSchema would change the bag at this path).

message​
message: string;

The issue's own message.

path​
path: FlowConfigPath;

Where in the bag. [] is the whole bag.


FlowConfigPath​

type FlowConfigPath = readonly (string | number)[];

A path in a config bag, as segments. [] is the whole bag.


FlowConfigValue​

type FlowConfigValue<TConfigSchema> = TConfigSchema extends ZodTypeAny ? Readonly<TConfigSchema["_output"]> : Readonly<Record<string, unknown>>;

The parsed, frozen bag a copy carries — the OUTPUT side of the declared schema, so defaults are present. An open read-only record for a flow that declares no schema, which reads {} at run time.

Type Parameters​

TConfigSchema​

TConfigSchema extends ZodTypeAny | undefined


FlowContextView​

type FlowContextView<TConfig> = object;

The one member of the running flow instance a block may read: the copy's create-time config bag.

A block context deliberately does not carry the flow instance. Reaching the whole instance would put a block's hands on the action, task and internal maps, and every claim and dispatch gate built onto them could then be stepped around. So the boundary is a shape rather than an absence — this view names config and nothing else, and the type-test in test/block-context-boundary.type-test.ts keeps the rest closed.

Named once and referred to by BlockContext, the block builders and that type-test, so widening the boundary later is one edit in one place.

This is a compile-time contract, not runtime enforcement. The engine builds one context object carrying the whole FlowInstance under flow; only the public type is narrowed. So a block that casts — (ctx as any).flow.actions — reaches every member this view leaves out, and nothing stops it at run time. That is the accepted shape: a block author already owns the process their flow runs in, so the boundary exists to prevent the accident and the drift, not the determined author.

It is a real guardrail rather than decoration — reaching past it takes a deliberate cast that shows up in review, and the type-test fails CI if the declared surface widens by accident. Just do not cite it as proof that a block cannot reach the flow's action, task or internal maps.

Type Parameters​

TConfig​

TConfig extends object = Readonly<Record<string, unknown>>

Properties​

config​
readonly config: TConfig;

The settings this copy of the flow was created with — parsed against the flow's configSchema and frozen at the mint. {} for a flow that declares none. Shallowly frozen: a nested object is not deep-frozen.


FlowDefinition​

type FlowDefinition<TActions, TSession, TRequest, TUser, TOrg, TResources, TConfigSchema> = object;

Type Parameters​

TActions​

TActions extends Record<string, ActionEntry> = Record<string, ActionEntry>

TSession​

TSession extends SessionConfig | undefined = SessionConfig | undefined

TRequest​

TRequest extends RequestConfig | undefined = RequestConfig | undefined

TUser​

TUser extends UserConfig | undefined = UserConfig | undefined

TOrg​

TOrg extends OrgConfig | undefined = OrgConfig | undefined

TResources​

TResources extends Record<string, DeclaredResourceEntry> = Record<string, DeclaredResourceEntry>

TConfigSchema​

TConfigSchema extends ZodTypeAny | undefined = undefined

Properties​

actions​
actions: TActions;

The flow's public entries — what a caller may name over HTTP, MCP or voice, each authorized per request. The public API of the flow. Each is a block, or { block, ... } when the entry sets more than its block.

authentication?​
authentication?: AuthenticationConfig;

Per-flow authentication hook. The framework owns the resolution contract (call resolvePrincipal, apply defaultUserId, enforce requireUser); the host owns credential verification. See AuthenticationConfig.

cardinality?​
cardinality?: FlowCardinality;

Instance cardinality — see FlowCardinality. Omitted means "singleton". Definition-only: rejectDefinitionOnlyOptions refuses it as an instance option.

configSchema?​
configSchema?: TConfigSchema;

What a copy of this flow may be created WITH — the shape of the bag flow({ config }) carries, parsed and frozen at that call.

Must be a plain z.object({ ... }): the framework closes it before parsing, so a key nobody declared is an error rather than a silently stripped one. A union, an intersection or an object wrapped in .refine() is refused where it is declared — a rule spanning two settings belongs in the block that reads them.

Definition-only in the way cardinality is: passing it as an instance option throws by name rather than being accepted and ignored.

Anything the copy is GIVEN goes here. Anything the copy LEARNS goes in its own instance-isolated state — the bag is frozen for the copy's life.

This option alone is the instance bag. BlockConfig.flowConfigSchema is the other half, and it buys something different: block PORTABILITY — a block that declares what it needs of any flow installing it, checked at each. That second half is what costs the TFlowConfigSchema generic on every block kind and through the sequencer DSL. A reader working out which lines exist for which reason can use that split: the bag is this option, the factory's config, and the parse; everything threading a schema through a block builder is portability.

costEstimator?​
costEstimator?: CostEstimator;
description?​
description?: string;

What the flow is for, in a sentence a person reads beside its name in a flow list (the developer tool shows it on an empty session list). Display only; it goes out on the flow list.

internal?​
internal?: TypedEntries<InternalEntry | BlockDefinition>;

The flow's internal entries — internal: { actions: { wake: { block } } } — reachable only by an internal dispatch from a dispatcher() block running in one of this flow's own requests. Nothing a caller can name resolves here: the map is the boundary, and a dispatch addressed to a type never falls through to another type's map.

Use it for work a request starts for itself or a sibling session — a background job in a child session, a wake sent to a coordinator, a follow-up delivered into a session that already exists.

isolateOrgState?​
isolateOrgState?: boolean;

Org-scope equivalent of isolateUserState. Default: false.

isolateUserState?​
isolateUserState?: boolean;

Isolation for the user scope. Two roles:

  • keys the scope's state record (ctx.user.state) — the user's cell in the org, {userId}:~org:{orgId}, when false, and that cell plus :{instance id} when true; and
  • the default flowIsolation for user-scoped resources that don't declare their own.

The namespace is the registered instance, not the kind: a singleton's id is its kind, so its cell is unchanged, but two copies of a collection definition isolate from each other as well as from other flows. Renaming an instance therefore moves where its isolated data lives.

Resources key per resource: a resource's own flowIsolation always wins over this default, in both directions. Default: false (resources are shared across flows under the same userId).

kind​
kind: string;
mcp?​
mcp?: McpConfig;

Per-flow MCP exposure config. When mcp.enabled === true, the @flow-state-dev/mcp adapter mounts POST /api/flows/:kind/mcp for this flow and translates exposed actions into MCP tools.

org?​
org?: TOrg;
request?​
request?: TRequest;
requireUser?​
requireUser?: boolean;

Top-level shorthand for authentication.requireUser. When both are set, authentication.requireUser wins. Default: true.

resources?​
resources?: TResources;

Flow-level resource declarations. Single flat map, accessor key → resource definition. Resources are routed to the right storage layer via their intrinsic scope (set on defineResource); cross-flow sharing is controlled by flowIsolation on the resource. Replaces the legacy session.resources / user.resources / org.resources.

resourceVisibility?​
resourceVisibility?: ResourceVisibilityRule;

Which of the flow's resources the model's resource tools reach on each turn: listing, search, reading and writing through core's resource tools and the discovery door. Omitted, every resource is reachable as its own llmReadable and llmWritable flags allow. A resource the rule hides answers exactly like one that isn't registered. Definition-only.

schedules?​
schedules?: SchedulesConfig;

Per-flow scheduled-action config. When set, the router's built-in scheduled endpoint answers POST /api/flows/:kind/schedules/:scheduleId/dispatch for this flow (with no schedules, it answers as for an unknown flow). Static entries are validated at registration; dynamic entries returned by resolve are validated at dispatch.

session?​
session?: TSession;
task?​
task?: TypedEntries<TaskEntry | BlockDefinition>;

The flow's task entries — task: { actions: { implement: { block } } } — where a task board dispatches a claimed row to run in a session of its own. Declared like actions and reached only by a task dispatch from a dispatcher({ type: "task", action: "implement" }) in the workers of a board the flow reaches. defineFlow puts each entry behind that board's claim gate and refuses an entry no board addresses.

tokenCounter?​
tokenCounter?: TokenCounter;
tools?​
tools?: ToolsConfig;
user?​
user?: TUser;
views?​
views?: Record<string, ViewDefinition>;

The flow's views: blocks a screen watches, each with a scope (session, or user / org with no session) and, for a list, a row key. Declared with defineView. A view writes nothing and calls no model; each run's answer names the change topics its reads fall under.

voice?​
voice?: VoiceConfig;
webhooks?​
webhooks?: WebhookConfig;

Per-flow webhook-transport subscriptions. When set, the @flow-state-dev/engine webhook adapter mounts POST /api/flows/:kind/webhooks/:provider and routes verified inbound events to the named actions. The flow declares routing only; the host supplies signature verification and payload mechanics at adapter mount.


FlowErrorOptions​

type FlowErrorOptions = object;

Options accepted by FlowError. The author-facing surface is the narrow { code, retryable, details, cause } shape; blockName, blockInstanceId, and scope are populated by the runtime when normalizing errors.

Properties​

blockInstanceId?​
blockInstanceId?: string;
blockName?​
blockName?: string;
cause?​
cause?: unknown;
code?​
code?: string;
details?​
details?: Record<string, unknown>;
retryable?​
retryable?: boolean;
scope?​
scope?: FlowErrorScope;

FlowErrorScope​

type FlowErrorScope = "request" | "sideChain" | "resource" | "block";

Conceptual location of a failure for downstream classification.


FlowInstance​

type FlowInstance<TActions, TSession, TRequest, TUser, TOrg, TResources, TConfigSchema> = object;

Type Parameters​

TActions​

TActions extends Record<string, ActionConfig> = Record<string, ActionConfig>

TSession​

TSession extends SessionConfig | undefined = SessionConfig | undefined

TRequest​

TRequest extends RequestConfig | undefined = RequestConfig | undefined

TUser​

TUser extends UserConfig | undefined = UserConfig | undefined

TOrg​

TOrg extends OrgConfig | undefined = OrgConfig | undefined

TResources​

TResources extends Record<string, DeclaredResourceEntry> = Record<string, DeclaredResourceEntry>

TConfigSchema​

TConfigSchema extends ZodTypeAny | undefined = undefined

Properties​

actions​
actions: TActions;
authentication?​
authentication?: AuthenticationConfig;
cardinality​
cardinality: FlowCardinality;

Normalized from the definition; see FlowCardinality.

config​
config: FlowConfigValue<TConfigSchema>;

This copy's create-time settings, parsed against the definition's configSchema and frozen. Never absent — a flow that declares no schema carries a frozen empty object, so a block always reads a value.

Blocks read it as ctx.flow.config. Normalized, never persisted, never on the wire, and no part of any storage key.

costEstimator?​
costEstimator?: CostEstimator;
description?​
description?: string;

See FlowDefinition.description. Absent when the definition has none.

flowLevelResourceKeys​
flowLevelResourceKeys: ReadonlySet<string>;

Accessor keys declared in the flow's OWN resources map passed to defineFlow, captured before block-tree/capability resources bubble up and merge into resources. The block-dispatch prefetch hook uses this to distinguish flow-level declarations (no per-block load trigger) from block-level ones.

id​
id: string;

The instance's global address. For a singleton this equals kind; for a collection member it is the explicit id the factory was called with. The flow registry indexes every registered instance by this value alone.

internal?​
internal?: TypedEntries<InternalEntry>;

See FlowDefinition.internal. Absent when the flow declares none.

isolateOrgState​
isolateOrgState: boolean;
isolateUserState​
isolateUserState: boolean;
kind​
kind: string;
mcp?​
mcp?: McpConfig;
org?​
org?: TOrg;
ownerPin?​
ownerPin?: InstanceOwnerPin;

Owner pin for an owner-pinned instance. Absent on shared flows. See InstanceOwnerPin.

request?​
request?: TRequest;
requireUser​
requireUser: boolean;
resources?​
resources?: TResources;
resourceVisibility?​
resourceVisibility?: ResourceVisibilityRule;

See FlowDefinition.resourceVisibility.

schedules?​
schedules?: SchedulesConfig;
scopeStateSchemas?​
scopeStateSchemas?: object;

Internal, read by the engine: the schema each scope's reads fill missing defaults from. The flow's own stateSchema merged, at defineFlow, with every scope-state schema its reachable blocks and their capabilities declare; a scope nothing declares is absent. Writes still validate against the flow's own stateSchema. Absent on an instance not built by defineFlow, whose reads fall back to its own stateSchema.

org?​
readonly org?: ZodTypeAny;
session?​
readonly session?: ZodTypeAny;
user?​
readonly user?: ZodTypeAny;
session?​
session?: TSession;
task?​
task?: TypedEntries<TaskEntry>;

See FlowDefinition.task. Absent when the flow declares none. Every entry here is the declared entry rebuilt behind its board's claim gate, so a task dispatch can only ever reach the worker through that gate.

tokenCounter?​
tokenCounter?: TokenCounter;
tools?​
tools?: ToolsConfig;
user?​
user?: TUser;
views?​
views?: Record<string, ViewDefinition>;

See FlowDefinition.views. Absent when the flow declares none.

voice?​
voice?: VoiceConfig;
webhooks?​
webhooks?: WebhookConfig;

FlowInstanceOptions​

type FlowInstanceOptions<TActions, TSession, TRequest, TUser, TOrg, TResources, TConfigSchema> = object;

Type Parameters​

TActions​

TActions extends Record<string, ActionConfig> = Record<string, ActionConfig>

TSession​

TSession extends SessionConfig | undefined = SessionConfig | undefined

TRequest​

TRequest extends RequestConfig | undefined = RequestConfig | undefined

TUser​

TUser extends UserConfig | undefined = UserConfig | undefined

TOrg​

TOrg extends OrgConfig | undefined = OrgConfig | undefined

TResources​

TResources extends Record<string, DeclaredResourceEntry> = Record<string, DeclaredResourceEntry>

TConfigSchema​

TConfigSchema extends ZodTypeAny | undefined = undefined

Properties​

actions?​
actions?: { [K in keyof TActions]?: TActions[K] | TActions[K]["block"] } & Record<string, ActionEntry>;

Per-instance action overrides, merged over the definition's. Each is a block, or { block, ... }. An existing action's override is typed off that action (TActions[K]), so it keeps the block's input type the client was typed with; a new name takes any entry.

authentication?​
authentication?: AuthenticationConfig;
config?​
config?: FlowConfigInput<TConfigSchema>;

The settings this copy is created with, parsed against the definition's configSchema and frozen. Omitting it is not a way around the schema: the schema parses {}, so its defaults apply and a required field refuses.

costEstimator?​
costEstimator?: CostEstimator;
id?​
id?: string;
isolateOrgState?​
isolateOrgState?: boolean;
isolateUserState?​
isolateUserState?: boolean;
kind?​
kind?: string;
org?​
org?: TOrg;
ownerPin?​
ownerPin?: InstanceOwnerPin;

Owner pin for this instance. Omitted, the instance stays shared. The registry's register(flow, { pin }) is authoritative; this field is how a reload hands the pin to that call. See InstanceOwnerPin.

request?​
request?: TRequest;
requireUser?​
requireUser?: boolean;
resources?​
resources?: TResources;
session?​
session?: TSession;
tokenCounter?​
tokenCounter?: TokenCounter;
tools?​
tools?: ToolsConfig;
user?​
user?: TUser;
voice?​
voice?: VoiceConfig;

FlowType()​

type FlowType<TActions, TSession, TRequest, TUser, TOrg, TResources, TConfigSchema> = FlowInstance<TActions, TSession, TRequest, TUser, TOrg, TResources, TConfigSchema>;

Type Parameters​

TActions​

TActions extends Record<string, ActionConfig> = Record<string, ActionConfig>

TSession​

TSession extends SessionConfig | undefined = SessionConfig | undefined

TRequest​

TRequest extends RequestConfig | undefined = RequestConfig | undefined

TUser​

TUser extends UserConfig | undefined = UserConfig | undefined

TOrg​

TOrg extends OrgConfig | undefined = OrgConfig | undefined

TResources​

TResources extends Record<string, DeclaredResourceEntry> = Record<string, DeclaredResourceEntry>

TConfigSchema​

TConfigSchema extends ZodTypeAny | undefined = undefined

type FlowType(options?): FlowInstance<TActions, TSession, TRequest, TUser, TOrg, TResources, TConfigSchema>;

Parameters​

options?​

FlowInstanceOptions<TActions, TSession, TRequest, TUser, TOrg, TResources, TConfigSchema>

Returns​

FlowInstance<TActions, TSession, TRequest, TUser, TOrg, TResources, TConfigSchema>

Properties​

actions​
actions: TActions;
authentication?​
authentication?: AuthenticationConfig;
cardinality​
cardinality: FlowCardinality;

Mirror of FlowInstance.cardinality.

config​
config: FlowConfigValue<TConfigSchema>;

What a copy of this flow would carry if nobody supplied a bag — the definition's configSchema parsed against {}, so a blueprint and a bagless mint agree exactly, defaults included. The frozen empty object when that parse fails, in which case requiresConfig is true.

flowLevelResourceKeys​
flowLevelResourceKeys: ReadonlySet<string>;

Mirror of FlowInstance.flowLevelResourceKeys.

internal?​
internal?: TypedEntries<InternalEntry>;

Mirror of FlowInstance.internal.

isolateOrgState​
isolateOrgState: boolean;
isolateUserState​
isolateUserState: boolean;
kind​
kind: string;
mcp?​
mcp?: McpConfig;
org?​
org?: TOrg;
request?​
request?: TRequest;
requiresConfig​
requiresConfig: boolean;

True when this flow cannot run on the bag it would have if nobody supplied one: its configSchema does not parse {}, or the value that parse produced does not satisfy a block that declared flowConfigSchema.

A declaration-derived flag — the registry reads it and refuses a blueprint handed over in place of an instance, rather than behaving differently. The framework never reads INSIDE the bag.

requireUser​
requireUser: boolean;
resources?​
resources?: TResources;
schedules?​
schedules?: SchedulesConfig;
scopeStateSchemas?​
scopeStateSchemas?: FlowInstance["scopeStateSchemas"];

Mirror of FlowInstance.scopeStateSchemas.

session?​
session?: TSession;
task?​
task?: TypedEntries<TaskEntry>;

Mirror of FlowInstance.task.

tools?​
tools?: ToolsConfig;
user?​
user?: TUser;
views?​
views?: Record<string, ViewDefinition>;

See FlowDefinition.views. Absent when the flow declares none.

voice?​
voice?: VoiceConfig;
webhooks?​
webhooks?: WebhookConfig;

GeneratorHistoryConfig​

type GeneratorHistoryConfig<TInput, TCtx> =
| true
| ItemQuery
| GeneratorSlot<TInput, TCtx>;

History slot config with shorthands:

  • true — auto-fetch session history with defaults
  • ItemQuery object — auto-fetch with options (e.g. { limit: 8 })
  • GeneratorSlot — custom function or static messages (full control)

Type Parameters​

TInput​

TInput = unknown

TCtx​

TCtx = BlockContext


GeneratorModelCallOptions​

type GeneratorModelCallOptions = object;

Options common to every GeneratorModel call — single-step and multi-step alike. One call's worth of request configuration: the conversation, the tool dictionary, output/token/abort/provider knobs.

Properties​

caching?​
caching?: CachingConfig;

Prompt-cache config. When set, the AI SDK adapter stamps provider- specific cache markers (e.g. Anthropic cacheControl) on the request before dispatch. Omitted or undefined uses framework defaults (auto breakpoints, 5m TTL, enabled).

maxTokens?​
maxTokens?: number;
messages​
messages: unknown[];
outputSchema?​
outputSchema?: ZodTypeAny;
providerOptions?​
providerOptions?: Record<string, unknown>;
providerTools?​
providerTools?: ProviderTool[];
signal?​
signal?: AbortSignal;
tools?​
tools?: GeneratorModelTool[];

GeneratorModelLoopOptions​

type GeneratorModelLoopOptions = GeneratorModelCallOptions & object;

Options for the SDK-driven multi-step methods (generate / stream). Extends the per-call options with the loop policy the model implementation runs internally: maxSteps bounds the tool loop and prepareStep lets the caller reshape each step's request before dispatch.

Type Declaration​

maxSteps?​
maxSteps?: number;
prepareStep?​
prepareStep?: PrepareStepFn;

GeneratorModelResult​

type GeneratorModelResult = object;

Properties​

finishReason?​
finishReason?: string;
providerMetadata?​
providerMetadata?: Record<string, Record<string, unknown>>;
resolvedIdentity?​
resolvedIdentity?: ModelIdentity;

Resolved identity of the model that produced this result. Internal carrier threaded from wrapAiSdkModel / createFallbackModel up to the generator block, which stamps the public model: ModelIdentity field on emitted items and on BlockTraceItem.

responseMessages?​
responseMessages?: unknown[];

The final step's RAW provider/SDK response messages (AI SDK v7 response.messages): the assistant turn exactly as the provider produced it, including reasoning/thinking parts and their provider-specific payloads (e.g. Anthropic thinking signatures) that the normalized fields above cannot carry. In-memory live-fidelity carrier for the framework-owned step loop: when a generateStep / streamStep result carries it, the loop appends the assistant portion of these messages verbatim for the step's turn instead of reconstructing an assistant message, so reasoning-model tool loops round-trip their thinking blocks. Never persisted; adapters may omit it (the loop falls back to constructed messages). Tool names inside these messages are the model-facing aliases, untranslated.

sources?​
sources?: GeneratorModelSource[];

Sources from provider-native tools (e.g., web search results).

steps?​
steps?: GeneratorStepResult[];
structuredOutput?​
structuredOutput?: unknown;
text?​
text?: string;
toolCalls?​
toolCalls?: GeneratorModelToolCall[];
usage?​
usage?: GeneratorModelUsage;

GeneratorModelSource​

type GeneratorModelSource = object;

Properties​

id​
id: string;
providerMetadata?​
providerMetadata?: Record<string, Record<string, unknown>>;
sourceType​
sourceType: "url";
title?​
title?: string;
type​
type: "source";
url​
url: string;

GeneratorModelTool​

type GeneratorModelTool = object;

Properties​

description?​
description?: string;
execute?​
execute?: (args, options?) => Promise<unknown>;
Parameters​
args​

unknown

options?​
toolCallId?​

string

Returns​

Promise<unknown>

name​
name: string;
parameters?​
parameters?: ZodTypeAny;
toModelOutput?​
toModelOutput?: (output) => string | Promise<string>;

Optional mapper from the structured tool output to the string the model sees on its next turn. Forwarded to the AI SDK as toModelOutput. When omitted, the AI SDK uses the structured output verbatim. Sourced from a block's mapModelOutput declaration.

Parameters​
output​

unknown

Returns​

string | Promise<string>


GeneratorModelToolCall​

type GeneratorModelToolCall = object;

Properties​

args​
args: unknown;
providerExecuted?​
providerExecuted?: boolean;

True when the provider executed this tool call server-side (e.g. a provider-native web search / other providerTools), rather than the model requesting a framework tool for the caller to run. The framework-owned step loop uses this to skip provider-executed calls (their results are already in the raw response) instead of mistaking them for hallucinated unknown tools. Absent/false for ordinary model-requested framework tool calls.

toolCallId​
toolCallId: string;
toolName​
toolName: string;

GeneratorModelUsage​

type GeneratorModelUsage = object;

Properties​

cacheCreationInputTokens?​
cacheCreationInputTokens?: number;

Tokens billed at the cache write rate (~1.25x input). Populated when a prompt-cache-enabled request creates a new cache entry.

cacheReadInputTokens?​
cacheReadInputTokens?: number;

Tokens billed at the cache read rate (~0.1x input). Populated when a prompt-cache-enabled request hits an existing cache entry.

completionTokens​
completionTokens: number;
promptTokens​
promptTokens: number;
totalTokens​
totalTokens: number;

GeneratorRepairMode​

type GeneratorRepairMode = "auto" | "rescue" | "fail";

GeneratorSearchConfig​

type GeneratorSearchConfig = object;

Properties​

allowedDomains?​
allowedDomains?: string[];

Only search these domains. Maps to Anthropic/OpenAI allowedDomains.

blockedDomains?​
blockedDomains?: string[];

Never search these domains. Maps to Anthropic blockedDomains.

maxUses?​
maxUses?: number;

Max number of search invocations per generation. Maps to Anthropic maxUses.

searchDepth?​
searchDepth?: "low" | "medium" | "high";

Search depth / context size. Maps to OpenAI searchContextSize.

userLocation?​
userLocation?: object;

Approximate user location for geo-relevant results.

city?​
city?: string;
country?​
country?: string;
region?​
region?: string;
timezone?​
timezone?: string;
type​
type: "approximate";

GeneratorSlot​

type GeneratorSlot<TInput, TCtx> =
| GeneratorSlotEntry<TInput, TCtx>
| GeneratorSlotEntry<TInput, TCtx>[];

Type Parameters​

TInput​

TInput = unknown

TCtx​

TCtx = BlockContext


GeneratorSlotEntry​

type GeneratorSlotEntry<TInput, TCtx> =
| string
| ContextObject<TInput, TCtx>
| ContextObject<TInput, TCtx>[]
| GeneratorSlotReference<TInput, TCtx>;

Type Parameters​

TInput​

TInput = unknown

TCtx​

TCtx = BlockContext


GeneratorSlotReference​

type GeneratorSlotReference<TInput, TCtx> = (input, ctx) => unknown | Promise<unknown>;

Type Parameters​

TInput​

TInput = unknown

TCtx​

TCtx = BlockContext

Parameters​

input​

TInput

ctx​

TCtx

Returns​

unknown | Promise<unknown>


GeneratorTool​

type GeneratorTool = BlockDefinition<any, any>;

HistoryTurn​

type HistoryTurn = object;

One past turn of a session, as items.turns() lists it: the request that is the turn, when it started, whether it has settled, and the messages the model would read for it.

Properties​

messages​
messages: LLMMessage[];
requestId​
requestId: string;
settled​
settled: boolean;

Whether the turn has finished for good. A turn still running, suspended on a gate, or interrupted and parked to run again has not, and items.turns() gives it no messages: what it says is not final until it settles. A session's history read (RequestSessions.history) lists a turn waiting on a call with what it has settled so far, as a model reads it, and settled: false.

startedAtMs​
startedAtMs: number;

InferCapabilities​

type InferCapabilities<TUses> = [Extract<TUses[number], CapabilityRef>] extends [never] ? object : Prettify<UnionToIntersection<InferCapabilityEntry<Extract<TUses[number], CapabilityRef>>>> extends infer T ? T extends Record<string, Record<string, (...args) => any>> ? T : object : object;

Infer the ctx.cap type from a uses array. Maps each capability's name → fns return type, then intersects.

Type Parameters​

TUses​

TUses extends readonly UsesEntry[]


InferFlowConfigFromSchema​

type InferFlowConfigFromSchema<TSchema> = TSchema extends ZodTypeAny ? z.infer<TSchema> extends object ? Readonly<z.infer<TSchema>> : Readonly<Record<string, unknown>> : Readonly<Record<string, unknown>>;

A block's view of the config bag: the shape it declared with flowConfigSchema, or an open read-only record for a block that declared nothing — the honest type for a block that never said what it wanted.

Type Parameters​

TSchema​

TSchema extends ZodTypeAny | undefined


InlineBlockFactory​

type InlineBlockFactory = (config) => BlockDefinition<any, any>;

Factory function type — matches handler(), generator(), router().

Parameters​

config​

any

Returns​

BlockDefinition<any, any>


InlineConfig​

type InlineConfig<TFactory, TInput, TOutputSchema, TStateSchema, TFlowConfigSchema, TOutput> = Omit<FactoryConfig<TFactory>, "inputSchema" | "name" | "outputSchema" | "execute"> & object;

Transforms a factory's config for inline use in a sequencer chain.

  • Omits inputSchema (auto-injected from previous step's outputSchema)
  • Makes name optional (auto-generated if omitted)
  • Overrides execute to receive TInput (the chain's current output type)

Type Parameters​

TFactory​

TFactory

TInput​

TInput

TOutputSchema​

TOutputSchema extends ZodTypeAny

TStateSchema​

TStateSchema extends ZodTypeAny | undefined = undefined

TFlowConfigSchema​

TFlowConfigSchema extends ZodTypeAny | undefined = undefined

TOutput​

TOutput = z.infer<TOutputSchema>

Type Declaration​

execute?​
execute?: (input, ctx) => TOutput | Promise<TOutput>;
Parameters​
input​

TInput

ctx​

SequencerCtx<TStateSchema, TFlowConfigSchema>

Returns​

TOutput | Promise<TOutput>

name?​
name?: string;
outputSchema​
outputSchema: TOutputSchema;

InlineTapConfig​

type InlineTapConfig<TFactory, TInput, TStateSchema, TFlowConfigSchema> = Omit<FactoryConfig<TFactory>, "inputSchema" | "name" | "outputSchema" | "execute"> & object;

Inline config for tap (output discarded, outputSchema optional).

Type Parameters​

TFactory​

TFactory

TInput​

TInput

TStateSchema​

TStateSchema extends ZodTypeAny | undefined = undefined

TFlowConfigSchema​

TFlowConfigSchema extends ZodTypeAny | undefined = undefined

Type Declaration​

execute?​
execute?: (input, ctx) => unknown | Promise<unknown>;
Parameters​
input​

TInput

ctx​

SequencerCtx<TStateSchema, TFlowConfigSchema>

Returns​

unknown | Promise<unknown>

name?​
name?: string;
outputSchema?​
outputSchema?: ZodTypeAny;

InstructionsSlot​

type InstructionsSlot<TInput> = string | ((input, ctx) => MaybePromise<string>);

Instructions slot accepted by pattern factories — static string or context-aware function returning a prompt string.

Type Parameters​

TInput​

TInput = unknown


InternalEntry​

type InternalEntry = ActionCore & object;

An internal entry: a block plus execution policy, reachable only by an internal dispatch from a dispatcher() in a running request of this flow. No HTTP or MCP caller can name it — the map it lives in is the boundary.

Type Declaration​

service?​
readonly service?: InternalServiceRoute;

The entry is a service flow's routing entry: an internal dispatch to it starts no request as its sender. The host routes the payload (a SubscriptionEvent) through it as the service, service:<provider>, in the sender's organization (routeServiceEvent), stamps the event's sender with the dispatching session and its owner with the sender's user and tenant, and fires only the owner runs of that user in that tenant. The session target is not read. Set by a service flow factory (internalServiceFlow), not by hand.


ItemVisibility​

type ItemVisibility = object;

Resolved visibility of an item: whether it should be sent to the client and whether it should be included in LLM conversation history.

Properties​

client​
client: boolean;
history​
history: boolean;

JsonObject​

type JsonObject = object;

Index Signature​

[key: string]: JsonValue

JsonPrimitive​

type JsonPrimitive = string | number | boolean | null;

JsonValue​

type JsonValue =
| JsonPrimitive
| JsonObject
| JsonValue[];

KeyedTaskSessionPolicy​

type KeyedTaskSessionPolicy<TPayload> = Exclude<TaskSessionPolicy<TPayload>, {
by: unknown;
}>;

The session policies that always derive a keyed child: every policy but { by }.

Type Parameters​

TPayload​

TPayload = unknown


KitFactory​

type KitFactory<Name, ConfigSchema, Slots> = ((...config) => KitInstance) & object;

A kit's factory: call it with the kit's config to install it. The config may also carry directory, the app's path for the kit's folder, read against the working directory; a kit that owns no folder refuses it.

Type Parameters​

Name​

Name extends string = string

ConfigSchema​

ConfigSchema extends z.ZodTypeAny | undefined = z.ZodTypeAny | undefined

Slots​

Slots extends Record<string, SlotDeclaration> = Record<string, SlotDeclaration>

Type Declaration​

kitName​
readonly kitName: Name;

The kit's name.

slots​
readonly slots: { readonly [K in keyof Slots]: SlotKey<Slots[K]> };

The key a contribution to each of this kit's slots goes under.


ManifestDomain​

type ManifestDomain = typeof MANIFEST_DOMAINS[number];

One of the three pinned discovery domains.


ManifestEntry​

type ManifestEntry = object;

One thing an agent could plan against.

purpose is the field the choice actually gets made on, so it is required and worth writing well — an entry reading "does engineering things" will not get picked over one that says what it does. contract is the optional deeper half (how to work with this thing), withheld from a thin read so a catalog stays cheap on every call.

An entry says a thing was registered or declared. It does not promise the thing is open, running or still there; a caller confirms that the same way it would without a catalog.

Properties​

contract?​
contract?: string;

Optional hint at how to work with it. Returned only on a detailed read.

id​
id: string;

Stable identifier the caller uses to act on this thing.

kind​
kind: string;

What kind of thing this is within its domain — "worker", "resource", …

purpose​
purpose: string;

One line saying what it is for. What an agent chooses on.


ManifestRegistry​

type ManifestRegistry = object;

The sources one scope carries. Immutable — everything it holds was named at construction, so "what is in scope" is a fact about the declaration site and not about call order.

Methods​

domains()​
domains(): ("resources" | "workers" | "skills")[];

Domains this scope carries, in the canonical domain order.

Returns​

("resources" | "workers" | "skills")[]

source()​
source(domain): BlockManifestSource | undefined;

This scope's source for domain, or undefined when it carries none. An absent source is an ordinary state, not an error: a scope with no resources source registered yet simply has nothing to say about resources.

Parameters​
domain​

"resources" | "workers" | "skills"

Returns​

BlockManifestSource | undefined


ManifestSource​

type ManifestSource<TCtx> = object;

A projection of one domain's existing reader into manifest entries.

entries is computed at call time from the caller's context — a source holds no state and caches nothing, so what an agent reads is what the domain's reader says at the moment it asks.

Generic over the context type: this layer is zero-dependency and node-free, so it does not know BlockContext. core binds it.

A source does not know how many tools sit in front of it. Whether the door is one tool taking a domain or a family of per-domain tools is a decision above this type, and either answer reads the same source.

Type Parameters​

TCtx​

TCtx = unknown

Properties​

domain​
domain: ManifestDomain;

The single domain this source answers for.

entries​
entries: (ctx) =>
| ManifestEntry[]
| Promise<ManifestEntry[]>;

Project this domain's reader into entries. Called on every read.

Parameters​
ctx​

TCtx

Returns​

| ManifestEntry[] | Promise<ManifestEntry[]>

origin?​
origin?: string;

Where this source was registered from, e.g. "createWorkforceCapability". Used to name both sites when two sources claim one domain.


MaybePromise​

type MaybePromise<T> = T | Promise<T>;

Type Parameters​

T​

T


ModelResolver​

type ModelResolver = ((modelId, blockName?, options?) => GeneratorModel) & object;

Type Declaration​

prepareMessages()?​
prepareMessages?(messages, target?): Promise<unknown[]>;

Turns the person's files on a call's user lines, held as references (FileContent whose data is fsd-blob:<id>), into the parts a model takes, with the bytes inline. The engine's run sets it; a generator calls it on the messages of every model call, at the call, so what a run records (a trace, a tool loop's prelude) keeps the references and never the bytes. Optional: without it the messages go as they are.

target.accepts is what the call's model reads as files, from its provider (providerAttachmentAccepts): a PDF goes as a file where it is listed and as its text where it isn't; a text-like file always goes as text. A call that names no target reads images and PDFs.

Parameters​
messages​

unknown[]

target?​
accepts​

AttachmentAccepts

Returns​

Promise<unknown[]>

providerOf()?​
providerOf?(modelId): string;

The provider a model string's call reaches, classified against this resolver's own providers and gateways maps: "anthropic" for "vercel:anthropic/claude-sonnet-5.5", "triage" for "triage:native". Returns "unknown" when the string names no provider. Optional: a generator's model-array fallback uses it to label each entry, and falls back to extractProviderName's config-free guess when it is absent.

Parameters​
modelId​

string

Returns​

string

resolveEvaluationModel()?​
resolveEvaluationModel?(modelId, blockName?):
| EvaluationModel
| Promise<EvaluationModel>;

Resolves a model string to an evaluation model, for evaluator blocks. Optional: a resolver without it serves generators unchanged, and an evaluator whose model is a string refuses to run on it (before any provider call), naming this hook. An evaluator given an evaluation model instance never consults the resolver.

Return the evaluation model, or throw to refuse the string. The framework never substitutes another resolver when this is absent. createModelResolver implements it with the same direct-then-gateway precedence as generator strings.

Parameters​
modelId​

string

blockName?​

string

Returns​

| EvaluationModel | Promise<EvaluationModel>

resolveId()​
resolveId(modelId, options?): string;

Returns the primary underlying model string for any model reference. For intents, returns the first available provider/model string (applying the resolver's provider preference and any call-site override). For direct model strings, returns the input as-is. A name:model string is returned as-is when its route is registered, and throws the same "Unknown route" error resolving it would when it is not.

Parameters​
modelId​

string

options?​
preferProvider?​

string | string[]

Returns​

string

Example​
resolver.resolveId("intent/chat")
// → "anthropic/claude-sonnet-5-5"
resolver.resolveId("intent/chat", { preferProvider: "openai" })
// → "openai/gpt-6.1-sol" (reorders the intent before walking it)
resolver.resolveId("anthropic/claude-sonnet-5-5")
// → "anthropic/claude-sonnet-5-5"

ModelRule​

type ModelRule<TInput, TCtx> =
| PreferProviderRule<TInput, TCtx>
| WhenRule<TInput, TCtx>;

Union of all rule kinds.

Type Parameters​

TInput​

TInput = unknown

TCtx​

TCtx = AnyBlockContext


ModelSelection​

type ModelSelection =
| string
| string[]
| {
model: string | string[];
preferProvider?: ProviderPreference;
};

Final return shape of the selectModel callable. May be a bare model id (or array of ids) when no preference was collected, or an object carrying both the model and a preferProvider value when one was.


NormalizedActions​

type NormalizedActions<TActions> = { [K in keyof TActions]: NormalizedEntry<TActions[K]> };

An actions map as defineFlow publishes it: each bare block as { block }.

Type Parameters​

TActions​

TActions extends Record<string, ActionEntry>


OrgScopeHandle​

type OrgScopeHandle<TState> = object & ScopeStateOps<TState>;

Type Parameters​

TState​

TState extends object = Record<string, unknown>

Type Declaration​

identity​
identity: ScopeIdentity;
state​
state: Readonly<TState>;

OutputValidationDetails​

type OutputValidationDetails = object & Record<string, unknown>;

Type Declaration​

issues​
issues: ZodIssue[];
phase​
phase: "stream" | "final";
rawOutput​
rawOutput: string;

ParallelStep​

type ParallelStep<TCurrent> =
| BlockDefinition<any, any>
| {
block: BlockDefinition<any, any>;
connector: ConnectorFn<TCurrent, unknown>;
};

Type Parameters​

TCurrent​

TCurrent


ParallelStepOutput​

type ParallelStepOutput<TStep> = TStep extends object ? V : TStep extends object ? V : never;

Type Parameters​

TStep​

TStep


PreferProviderRule​

type PreferProviderRule<TInput, TCtx> = object;

Returns a provider-preference value (provider name or ordered list of provider names). The first non-null result is collected into the ModelSelection's preferProvider field. Evaluation does not short-circuit — when rules below still execute.

Type Parameters​

TInput​

TInput = unknown

TCtx​

TCtx = AnyBlockContext

Properties​

preferProvider​
preferProvider: (input, ctx) => MaybePromise<string | string[] | undefined | null>;
Parameters​
input​

TInput

ctx​

TCtx

Returns​

MaybePromise<string | string[] | undefined | null>


PrepareStepFn​

type PrepareStepFn = (stepInfo) => Promise<PrepareStepResult | undefined | void>;

Parameters​

stepInfo​
messages​

unknown[]

stepNumber​

number

steps​

GeneratorStepResult[]

Returns​

Promise<PrepareStepResult | undefined | void>


PrepareStepResult​

type PrepareStepResult = object;

Callback invoked before each step of the AI SDK's multi-step tool loop. Returns updated system/messages/activeTools for the step, or undefined to keep defaults.

Properties​

activeTools?​
activeTools?: string[];

Tool names to enable for this step (filters the compiled tool set).

messages?​
messages?: unknown[];
modelId?​
modelId?: string;

Switch to a different model for this step. The model ID string is re-resolved through the model resolver at the AI SDK adapter layer. Only effective when the GeneratorModel was created via createAiSdkModelResolver (not wrapAiSdkModel).

system?​
system?: unknown;

PresetContextEntry​

type PresetContextEntry<TSessionState> =
| string
| ContextObject<any, CapabilityPresetCtx<TSessionState>>
| ((input, ctx) => MaybePromise<
| string
| ContextObject<any, CapabilityPresetCtx<TSessionState>>
| null
| undefined>);

Context entry within a preset. Capabilities may contribute static strings, static object-form context (keys become XML tag names — see ContextObject in @flow-state-dev/core), or a function that receives (input, ctx) and resolves to one of those shapes (or null/undefined to contribute nothing).

Type Parameters​

TSessionState​

TSessionState = any


PresetDef​

type PresetDef<TSessionState> = object;

A preset definition — a partial block config. TSessionState flows from the capability's sessionStateSchema so preset callbacks get typed ctx.

Type Parameters​

TSessionState​

TSessionState = any

Properties​

caching?​
caching?: ResolvableCachingConfig<any, CapabilityPresetCtx<TSessionState>>;
context?​
context?:
| PresetContextEntry<TSessionState>
| PresetContextEntry<TSessionState>[];
controlTools?​
controlTools?:
| GeneratorTool[]
| ((ctx) =>
| GeneratorTool[]
| Promise<GeneratorTool[]>);

Tools that are NOT subject to a consuming block's tools: fence.

A block's declared tools: is the complete and exclusive set of catalog tools the model may call. Anything a capability contributes through tools above is a catalog grant and is fenced out unless the block named it.

controlTools is the other kind: a framework control the block reached for by composing this capability at all. The composition is the declaration, so there is nothing for the fence to check — and no way for the block to re-declare it, since a control is usually built inside the capability and never exported for a tools: list to name.

Use it only for tools whose presence is already implied by the block's own configuration — the skills loader its config switched on, the delegation board a skill it holds asked for. A capability that grants access to something the block did not ask for (memory recall, MCP, resource tools) belongs in tools, where the fence can see it.

A capability may declare both: createSkillsLibrary registers the app catalog through tools and its own loader through controlTools.

history?​
history?:
| ItemQuery
| ((ctx) => MaybePromise<ItemQuery>);

A query added to every ctx.session.items.history() read of the generator that installs the capability, whether through the history option's default or a history function of its own. The read's own keys win over it; among capabilities, later keys win. Generator only.

A history summary uses it to read only the turns after its mark ({ afterRequestId }). A function is resolved on every run.

model?​
model?: ResolvableModel<any, CapabilityPresetCtx<TSessionState>>;
orgStateSchema?​
orgStateSchema?: ZodTypeAny;
providerOptions?​
providerOptions?: ResolvableProviderOptions<any, CapabilityPresetCtx<TSessionState>>;
requestStateSchema?​
requestStateSchema?: ZodTypeAny;
resources?​
resources?: Record<string, DeclaredResourceEntry>;
sequencerStateSchema?​
sequencerStateSchema?: ZodTypeAny;
sessionStateSchema?​
sessionStateSchema?: ZodTypeAny;
stateSchema?​
stateSchema?: ZodTypeAny;

Own-state — this block's ctx.self container. Valid on any block kind, since any block can hold its own request-scoped state. Merged with the block's own stateSchema (and any sibling capability's own-state contribution) with explicit duplicate-field collision detection — see mergeCapabilityOwnStateWithBlock in capability/merge.ts.

targetStateSchemas?​
targetStateSchemas?: Record<string, ZodTypeAny>;
tools?​
tools?:
| GeneratorTool[]
| ((ctx) =>
| GeneratorTool[]
| Promise<GeneratorTool[]>);
userStateSchema?​
userStateSchema?: ZodTypeAny;

PresetOverrides​

type PresetOverrides<TNames, TPresets> = { [K in TNames]?: boolean | (K extends keyof TPresets ? TPresets[K] extends PresetDef ? PresetOverrideFn<TPresets[K]> : never : never) };

Type Parameters​

TNames​

TNames extends string

TPresets​

TPresets extends Record<string, PresetDef | string[]>


ProjectedRecordHit​

type ProjectedRecordHit<TState> = object;

One hit returned by a projected collection's search. key is the within-scope row key/path — the framework normalizes it through the collection pattern (resolveCollectionKey) to the canonical storage path before building URIs or emitting change events.

Ranking is the hook's RETURN ORDER (the framework preserves it); the snippet is derived framework-side from rendered content. App-supplied score / snippet overrides are deferred until a consumer needs them — they land with semantic-search ranking, where an app score is no longer redundant with hook order. Re-add the two optional fields here + prefer them in searchProjectedRecords when that consumer arrives.

Type Parameters​

TState​

TState extends JsonObject = JsonObject

Properties​

key​
key: string;

Within-scope key/path; normalized through the pattern → instance path/uri.

state​
state: TState;

The record state (validated through stateSchema before any consumer sees it).


ProjectedResourceCollectionConfig​

type ProjectedResourceCollectionConfig<TStateSchema> = object;

Config for defineProjectedResourceCollection. read / search are first-class required members — the config is the backing. There is no writable / llmWritable / edges / prefetchMode / maxInstances / eviction: read-only, lazy, and unbounded are structural, not flags.

Type Parameters​

TStateSchema​

TStateSchema extends ZodTypeAny = ZodTypeAny

Properties​

client?​
client?: CollectionClientConfig<z.infer<TStateSchema>>;

The COLLECTION client config (per-item state + content). Its content.create / update / delete flags are rejected at build time — a projected collection is read-only.

contentTemplate?​
contentTemplate?:
| ResourceTemplate
| string
| AnchoredPath;

A role-tagged Markdown template rendered against each record's state.

contentTemplateRef?​
contentTemplateRef?: string;

Path of another resource whose raw content is a template for each instance.

llmReadable?​
llmReadable?: boolean;

Gate the read/search tools (default off).

metadata?​
metadata?: Record<string, unknown>;
pattern​
pattern: string;

WILDCARD-ONLY pattern: "positions/*" or "positions/**". Parameterized [name] patterns are rejected at build time — they need an object key, incompatible with the string hit key a projected read / search returns.

reactTo?​
reactTo?: ProjectedReactiveBindings<z.infer<TStateSchema>>;

created / stateUpdated / deleted only — no content-write seam exists.

scope​
scope: ResourceScope;

session | user | org — routes scopeId into the read/search context.

stateSchema​
stateSchema: TStateSchema;

The shape of one record (every instance shares it).

Methods​

read()​
read(args): Promise<TypeOf<TStateSchema> | null>;

Resolve one record by its within-scope key. null = no such record. REQUIRED.

Parameters​
args​
ctx​

ProjectedResourceContext

key​

string

Returns​

Promise<TypeOf<TStateSchema> | null>

search()​
search(args): Promise<ResourceSearchResult<TypeOf<TStateSchema>>>;

Resolve a filtered/searched page, pushing the query DOWN to the app engine (never enumerate-in-memory). REQUIRED. list, searchResources, and the read tool's discovery route here; globResources / grepResourceContent do NOT (they skip projected collections — a lexical search can't honor their deterministic contract).

Parameters​
args​
ctx​

ProjectedResourceContext

query​

ResourceQuery

Returns​

Promise<ResourceSearchResult<TypeOf<TStateSchema>>>


ProjectedResourceContext​

type ProjectedResourceContext = object;

Trusted, server-derived context handed to read / search (never caller-controllable). The framework populates every field from a trusted source (the loaded session / scope identity), so the hook can safely scope its own query to the same owner/tenant namespace the framework uses.

Properties​

flowKind​
flowKind: string;

The flow kind this read runs under.

orgId?​
orgId?: string;
scope​
scope: ResourceScope;

session | user | org — never the transient "request" scope.

scopeId​
scopeId: string;

The resolved sessionId / userId / orgId for scope.

signal?​
signal?: AbortSignal;

Request abort propagation — the hook should honor it.

tenantId?​
tenantId?: string;

Trusted tenant coordinate (ScopeIdentity) for multi-tenant queries.

userId​
userId: string;

Always populated — the server-derived owner. Never caller input.


PromptSlot​

type PromptSlot<TInput, TCtx> =
| PromptSlotEntry<TInput, TCtx>
| PromptSlotEntry<TInput, TCtx>[];

Prompt slot — accepts a single entry or an array. Array entries are resolved individually (functions called with input+ctx), nulls filtered, then joined with newlines. This lets patterns compose prompts declaratively:

prompt: [instructions, basePrompt]

Type Parameters​

TInput​

TInput = unknown

TCtx​

TCtx = BlockContext


ProviderPreference​

type ProviderPreference = string | string[];

Brand preference axis: a provider name ("anthropic") or an ordered list of provider names (["anthropic", "google"]). Orthogonal to the intent axis — the intent defines the candidate pool; preference reorders it.


ProviderTool​

type ProviderTool = object;

Opaque wrapper for a Vercel AI SDK provider-defined tool. Passed through to the AI SDK without compilation — the provider executes it server-side.

Use the providerTool() factory to create instances.

Properties​

__providerTool​
readonly __providerTool: true;
name​
readonly name: string;

Display name for observability (item stream, devtool).

tool​
readonly tool: unknown;

The raw AI SDK tool object to pass through.


ReactiveBinding​

type ReactiveBinding<TState> =
| BlockDefinition<any, any>
| {
block: BlockDefinition<any, any>;
when?: (change) => boolean;
};

An author's binding for one state kind: either a bare block, or a block paired with an optional when gate that skips dispatch when it returns false.

Type Parameters​

TState​

TState extends JsonObject = JsonObject

Union Members​

BlockDefinition<any, any>


Type Literal​
{
block: BlockDefinition<any, any>;
when?: (change) => boolean;
}
block​
block: BlockDefinition<any, any>;
when?​
when?: (change) => boolean;

Optional gate; skip dispatch when it returns false.

Parameters​
change​

ResourceChange<TState>

Returns​

boolean


ReactiveContentBinding​

type ReactiveContentBinding =
| BlockDefinition<any, any>
| {
block: BlockDefinition<any, any>;
when?: (change) => boolean;
};

An author's binding for the content kind. Same shape as ReactiveBinding, but its when gate receives a ResourceContentChange (key/ref only — no state to gate on; gate on state inside the block).

Union Members​

BlockDefinition<any, any>


Type Literal​
{
block: BlockDefinition<any, any>;
when?: (change) => boolean;
}
block​
block: BlockDefinition<any, any>;
when?​
when?: (change) => boolean;

Optional gate; skip dispatch when it returns false.

Parameters​
change​

ResourceContentChange

Returns​

boolean


RecordedValueOmittedDetails​

type RecordedValueOmittedDetails = object;

Structured details carried by RecordedValueOmittedError.

Properties​

blockName​
blockName: string;

The block (or tool) whose recorded value was left out.

bytes​
bytes: number | null;

Its serialized size in bytes, or null when it could not be serialized.


RequestScopeHandle​

type RequestScopeHandle<TState> = object & ScopeStateOps<TState>;

Type Parameters​

TState​

TState extends object = Record<string, unknown>

Type Declaration​

attachments​
attachments: ReadonlyArray<FileContent>;

The files the person's message carried, in the order attached, as references (FileContent whose data is fsd-blob:<id>). Empty when it carried none. A block that hands files on itself (a harness turn) reads them here; they never appear in the block's input.

costEstimate​
costEstimate: CostEstimate;
identity​
identity: ScopeIdentity;
incarnation​
incarnation: string;

Which request this is, among every request that has held its id.

Stamped once when this request is first recorded; one request, one value for its whole life. A retry, a resume in another process, or a queued run picking up the record its host wrote all read the same value.

A request id can be chosen by the caller, and once a request's record is deleted (session retention, for one) the same id can name a new request, from the same user or another one. identity.id alone cannot tell the two apart; this can. Anything keyed on a request id that outlives the request (a scratch directory, a cache) must key on this too, or the next request under that id inherits it.

Opaque: compare it for equality, never parse it.

state​
state: Readonly<TState>;
tokenUsage​
tokenUsage: TokenLedger;

ResourceChangeKind​

type ResourceChangeKind = "created" | "stateUpdated" | "deleted";

The kind of structured-state mutation that produced a ResourceChange. stateUpdated (formerly updated) names the axis that changed, keeping it parallel to the content axis's contentUpdated.


ResourceCollectionConfig​

type ResourceCollectionConfig<TState> = object;

Type Parameters​

TState​

TState extends JsonObject = JsonObject

Properties​

canWrite?​
canWrite?: CollectionCanWrite<TState>;

The default write flow's rule for one entry, run after the schema and owner checks; false refuses the write. Requires runBy: "default". Required for an org collection on the default write flow: without it every member of the org could write every entry. Declare canWrite: () => true when that is what you want.

client?​
client?: CollectionClientConfig<TState>;

Client visibility configuration. Omit to keep the collection invisible to clients.

contentTemplate?​
contentTemplate?:
| ResourceTemplate
| string
| AnchoredPath;

A role-tagged Markdown template applied to each instance. Accepts a parsed ResourceTemplate or a file path resolved at server startup — bare string from the working directory, AnchoredPath relative to the declaring module first.

contentTemplateRef?​
contentTemplateRef?: string;

Path of another resource whose raw content is a template for each instance.

edges?​
edges?: boolean | EdgeSlotConfig;

Declare a typed-edge graph on each instance of this collection. true = defaults; object = curated vocabulary / size cap. Attaches an .edges API to each live instance ref backed by that instance's own state. defineResourceCollection injects an edges field into the instance stateSchema (the same way defineResource does for single resources), so callers do not declare it themselves.

eviction?​
eviction?: EvictionPolicy;
flowIsolation?​
flowIsolation?: boolean;

Cross-flow sharing intent. Default false. Same semantics as ResourceConfig.flowIsolation. Rejected at session scope.

indexes?​
indexes?: Record<string, ResourceIndexDeclaration<TState>>;

Fields this collection's rows can be looked up by with findBy(name, value). Each entry is an index function of the row's key and state (version 1), or { version, value }. The function must answer from key and state alone. Bump version when it changes what it returns for existing rows: the next lookup in each scope rebuilds the index from the rows, as the first lookup after the index is added does. Names must be non-empty and must not contain @.

llmReadable?​
llmReadable?: boolean;

Expose this collection's instance content to the LLM via the generic content tools (readResourceContentTool), content search (grepResourceContent / searchResources), and instance state via resourceTools()'s readResource, which also leaves out secret fields. Collection-wide — applies to every instance, the same way client is declared once at the collection level. Default false: a collection that doesn't opt in stays invisible to those tools.

llmWritable?​
llmWritable?: boolean;

Allow the LLM to overwrite instance content via writeResourceContentTool. Collection-wide. Default false. Independent of llmReadable, matching the single-resource contract (the write tool gates on llmWritable alone).

maxInstances?​
maxInstances?: number;
onInstanceCreated?​
onInstanceCreated?: (key, state, ctx) => void | Promise<void>;

Fires when a specific instance is created (e.g., files/utils.ts).

Parameters​
key​

string

state​

JsonObject

ctx​

CollectionHookContext

Returns​

void | Promise<void>

onInstanceDeleted?​
onInstanceDeleted?: (key, ctx) => void | Promise<void>;

Fires when a specific instance is deleted (including eviction).

Parameters​
key​

string

ctx​

CollectionHookContext

Returns​

void | Promise<void>

onInstanceUpdated?​
onInstanceUpdated?: (key, state, prevState, ctx) => void | Promise<void>;

Fires when a specific instance's state is updated.

Parameters​
key​

string

state​

JsonObject

prevState​

JsonObject

ctx​

CollectionHookContext

Returns​

void | Promise<void>

ownerPrivate?​
ownerPrivate?: object;

Make each row readable and writable only by the user it belongs to. param names the pattern parameter that holds the owner; key it with ownerSegment(userId). A row is served only to the user its owner segment names, and no other collection in the app reads or writes it. The pattern must declare param exactly once and must not use **, and the collection has no browser read.

param​
param: string;
ownerWrites?​
ownerWrites?: object;

Make each row readable by everyone the scope serves and writable only by the user it belongs to. param names the pattern parameter that holds the owner; key it with ownerSegment(userId). Every read path serves the row, the browser routes included. A create, update or delete is refused unless the session's user is the one the owner segment names, and no other collection in the app reads or writes the rows. The pattern must declare param exactly once and must not use **. Not with ownerPrivate, and not with an eviction policy other than "none".

param​
param: string;
pattern​
pattern: string;

Glob-style pattern: files/*, files/**, or [topic]/observations.

prefetchMode?​
prefetchMode?: "eager" | "lazy";

When this collection's instances are loaded relative to a request. 'eager' (default when omitted) loads the full instance set when the scope's resource registry is constructed, giving the collection ref synchronous get/list/count. 'lazy' defers loading: the ref's read methods become async and the collection holds only a partial cache. Because a lazy collection never sees its full set, it cannot support a non-'none' eviction policy — defineResourceCollection throws on that combination.

prefetchWindow?​
prefetchWindow?: number;

Number of items to inline in the snapshot's prefetched window for this collection. Default 0 (lazy — clients fetch items via the list endpoint or useResourceCollectionList). Items are selected in lexicographic storage-key order, not by recency. Per-item clientData is included only when client.state.read is also true; otherwise prefetched entries carry just the topic.

reactTo?​
reactTo?: ReactiveBindings<TState>;

Bind blocks to this collection's instance mutations. Each present entry names a block — bare, or { block, when } with an optional gate — that the server dispatcher runs when that mutation fires. The state kinds (created / stateUpdated / deleted) get a ResourceChange payload; contentUpdated (a content-body write) gets a ResourceContentChange. Coexists with the onInstance* callbacks above and supersedes them for the block case: prefer reactTo when the reaction is itself a block to run, not just a side effect.

runBy?​
runBy?: ResourceRunBy;

The flow a client's write of this user or org collection's entries runs through: "default" (the framework's default write flow) or { flow }. Omit it and a client can't write an entry. User or org scope only, not with flowIsolation: true, and with client.state.read: true, since a client writes an entry at the version it read. With "default", no computed client.data, no writable: false and no eviction.

scope​
scope: ScopeType;

Intrinsic scope this collection lives in. Required for new collections — mirrors defineResource({ scope }).

secret?​
secret?: ReadonlyArray<keyof TState & string>;

State fields that never leave the server. Every read the engine serves omits them: the client snapshot, the list and get-state routes, live deltas, and the debug routes, which otherwise return full state. A client.data function sees the full state, but a secret field in what it returns is dropped. Blocks on the server read them through the handle. A field named here cannot also be named in client.expose.

sharedToLineage?​
sharedToLineage?: boolean;

Give this session-scoped collection ONE identity across the whole session lineage. Same semantics as ResourceConfig.sharedToLineage, applied to every instance: a session and the background child sessions it spawns resolve the collection against the lineage root, so they read and write one instance set. Session-scope only; rejected at user/org scope.

stampOrgId?​
stampOrgId?: boolean;

Record which organization created each instance. When true, create (and the create branch of getOrCreate / upsert) writes the organization the execution was admitted under into the new instance's orgId field when the caller's initial state names none — so the stored row carries a server-derived org without the caller passing one. A create whose initial state names a different orgId than the execution's throws; restating the execution's own is accepted. On an update (every instance write, and create(..., { replace: true }) of a live instance) the stored orgId stands: omitting it keeps it, restating it is accepted, and naming another throws without writing. A row with no stored orgId stays without one unless the update names the executing run's own; any other throws. The stateSchema must declare orgId, or the parse strips it. Default false.

stateSchema​
stateSchema: ZodTypeAny;
wakeEntry?​
wakeEntry?: string;

The internal entry a write from another session starts a turn of, in the session written (ctx.resources.at({ session })). The turn is a wake on that session and entry, so writes that land before it runs fold into one turn: the entry reads what changed, not one event, and settles its wake (requestHost.wakes) as every wake's entry does. Absent, a write from another session is heard on the change bus and starts no turn. A write from the session itself never starts one; reactTo answers those. Session-scope only.

writable?​
writable?: boolean;

Allow blocks to mutate instance state (patchState / setState / updateState / upsert patch) and instance content (writeContent), and to overwrite or remove an existing instance (create with { replace: true }, delete). Collection-wide. Default true when omitted — same as a single resource. Set false to refuse those writes. create / getOrCreate of a key that does not exist stay open.


ResourceContext​

type ResourceContext<TState> = object;

Type Parameters​

TState​

TState extends JsonObject = JsonObject

Properties​

edges?​
edges?: ResourceEdgeApi;

Typed-edge graph API — present at runtime only when the resource declared edges. Consumers that declared edges access it via ctx.edges!.

state​
state: Readonly<TState>;

Methods​

incState()​
incState(increments): Promise<void>;

Add to number-valued state fields in one guarded write.

Parameters​
increments​

ResourceIncrements<TState>

Returns​

Promise<void>

See​

ResourceRef.incState for the atomicity and refusal contract.

patchState()​
patchState(updates): Promise<void>;
Parameters​
updates​

Partial<TState>

Returns​

Promise<void>

pushState()​
pushState<K>(field, value): Promise<void>;

Append one value to an array-valued state field in one guarded write.

Type Parameters​
K​

K extends string

Parameters​
field​

K

value​

ResourceArrayElement<TState[K]>

Returns​

Promise<void>

See​

ResourceRef.pushState for the atomicity and refusal contract.

setState()​
setState(nextState): Promise<void>;
Parameters​
nextState​

TState

Returns​

Promise<void>

updateState()​
updateState(updater): Promise<void>;
Parameters​
updater​

(state) => TState | Promise<TState>

Returns​

Promise<void>


ResourceIndexDeclaration​

type ResourceIndexDeclaration<TState> =
| ResourceIndexFunction<TState>
| {
value: ResourceIndexFunction<TState>;
version: number;
};

One declared index: a function (version 1), or { version, value }. Bump version when the function changes what it returns for existing rows; the next lookup in each scope then rebuilds the index from the rows.

Type Parameters​

TState​

TState extends JsonObject = JsonObject


ResourceIndexFunction​

type ResourceIndexFunction<TState> = (key, state) =>
| ResourceIndexValue
| null
| undefined
| ReadonlyArray<ResourceIndexValue | null | undefined>;

An index function. Sees the row's storage key and its state only, and must answer from them alone: one that reads the clock or other rows drifts, and a lookup can filter a stale entry but never recover a missing one. Returns a value, an array of values (the row is found by each), or null / undefined when the row has no value for this index.

Type Parameters​

TState​

TState extends JsonObject = JsonObject

Parameters​

key​

string

state​

TState

Returns​

| ResourceIndexValue | null | undefined | ReadonlyArray<ResourceIndexValue | null | undefined>


ResourceIndexValue​

type ResourceIndexValue = string | number | boolean;

A value a row can be found by: equality on a string, number or boolean.


ResourceQuery​

type ResourceQuery = object;

Minimal portable query pushed down to a projected collection's search. The app engine runs it (never enumerate-in-memory). Deliberately closed this slice; a richer filter AST and semantic search extend this type later.

Properties​

cursor?​
cursor?: string;

Opaque pagination cursor, echoed back by the app from a prior page.

filter?​
filter?: Record<string, JsonValue>;

Equality map — the only structured predicate this slice.

limit?​
limit?: number;

Page size hint.

prefix?​
prefix?: string;

Path-boundary prefix — same semantics as the store-backed search tools.

search?​
search?: string;

Free-text relevance (lexical now; semantic later). Maps to searchResources' query.


ResourceSearchResult​

type ResourceSearchResult<TState> = object;

A page of hits plus the app's opaque cursor for the next page.

Type Parameters​

TState​

TState extends JsonObject = JsonObject

Properties​

hits​
hits: ProjectedRecordHit<TState>[];
nextCursor?​
nextCursor?: string;

Omit when the result set is exhausted.


ResourceVisibility​

type ResourceVisibility = "visible" | "read-only" | "hidden";

What the model's resource tools may do with one resource on this turn:

  • "visible": everything its own flags allow;
  • "read-only": list, search and read it, but not write it. A write is refused exactly as for a resource that isn't llmWritable;
  • "hidden": nothing. It answers exactly like a resource that isn't registered: absent from every listing, and "not found" when named.

ResourceVisibilityRule​

type ResourceVisibilityRule = (ctx, resource) => ResourceVisibility;

The rule. Called with the running block's context, on every listing and lookup, so it must be synchronous and cheap. Derive the answer from data the server wrote on this turn, never from the turn's input.

Parameters​

ctx​

BlockContext

resource​

ResourceVisibilityTarget

Returns​

ResourceVisibility


ResourceVisibilityTarget​

type ResourceVisibilityTarget = object;

One resource as the rule sees it: the key the flow registers it under, and its handle.

Properties​

name​
readonly name: string;

The key in the flow's resources map (ctx.resources[name]).

ref​
readonly ref: AnyResourceRef;

The resource or collection's handle on this turn.


ResumeAction​

type ResumeAction = "approve" | "reject" | "submit" | "skip";

The resolution actions a resumer can send to the resume endpoint. approve and reject are the original binary outcomes; submit carries a validated payload (a question answer, a form, a selection); skip declines an optional step so the run continues with a default. A leaf type so the item taxonomy (SuspensionItem.allow) can reference it without depending on core.


RouteUnavailableDetails​

type RouteUnavailableDetails = object;

Structured details carried by RouteUnavailableError.

Properties​

recordedRoute​
recordedRoute: string;

The route name persisted in the request's router_decision item.

recordedRouteDeclared​
recordedRouteDeclared: boolean;

Whether the recorded route still appears in the router's route table.

reselectedRoute​
reselectedRoute: string;

The route the re-run selector picked on resume.

routerName​
routerName: string;

ScheduleConfig​

type ScheduleConfig = ActionCore & object;

Single scheduled-action declaration — an action in scheduled form. It extends the shared ActionCore (the handler block plus execution policy like durable and tokenBudget) with the schedule-specific cron mapping. Because it carries the core inline, the handler needs no entry in flow.actions: a fired schedule reaches it only through the dispatch endpoint, never the public action surface or MCP.

Static entries live in SchedulesConfig.static and are validated at registration time; the dispatch resolves them through resolveActionCore via the metadata.schedule.scheduleId coordinate. Dynamic entries are produced by the resolver hook and validated at dispatch time (failures map to 400 invalid_schedule); their core is carried inline on the dispatch envelope because no static coordinate can reach it — so durable dynamic schedules are not crash-recoverable (a documented non-goal).

Type Declaration​

cron​
cron: string;

POSIX 5-field cron expression: minute hour dom month dow. Validated via cron-parser. Display-only — the framework does not run the schedule; the host's scheduler does.

description?​
description?: string;

Optional human description, surfaced in DevTool and the listing endpoint. Free text.

enabled?​
enabled?: boolean;

Whether the schedule is enabled. Default true. Disabled schedules appear in the listing endpoint (so operators can see them) but the dispatch endpoint short-circuits with 404. Mostly useful for static; dynamic resolvers can simply return null for disabled records.

input?​
input?: unknown | ScheduleInputFn;

Input passed to the handler. Either a static value (validated against the binding's effective input schema at registration for static schedules; deferred to runtime for dynamic) or a function called server-side at dispatch time.

onOverlap?​
onOverlap?: "skip" | "allow";

Behavior when a previous invocation of this schedule id is still in flight.

  • "skip" (default): adapter responds 200 with { status: "skipped" }, no runAction call.
  • "allow": dispatch proceeds; concurrent invocations are permitted.

"queue" is reserved as a future enum value but not implemented in v1 (it requires durable queueing).

principal?​
principal?: object;

The principal the action runs as — the target, not the dispatch caller. For static framework-level schedules this is typically a system principal ({ userId: "system" }). For dynamic per-user schedules this is the owning user's principal (the resolver pulls it from the persisted schedule record).

If omitted, the adapter falls back to the gateway principal established by the dispatch endpoint's host.resolvePrincipal call. Static schedules typically rely on the fallback; dynamic schedules almost always set this explicitly.

The organization may be omitted while the user is named, and then it alone falls back to the gateway's. That is for a STATIC schedule, whose principal is trusted config written in the flow definition. A dynamic schedule must not reach that fallback — a stored schedule fires into the organization that created it, not into whichever one happens to be firing the beat — so its resolver refuses to build a config without the stored organization.

principal.orgId?​
orgId?: string;
principal.userId​
userId: string;
session?​
session?: "per-fire" | "per-schedule";

Where this schedule's fires run.

  • "per-fire" (default): each fire is a one-off run in a session of its own.
  • "per-schedule": every fire runs in one session, kept for this schedule. The framework derives its id from the org and user the fire runs as, the flow instance and the schedule id, and reserves its prefix: only a scheduled dispatch may create the session or run in it, while its owner can still list and read it. The flow's session.retention caps its history.

A preset, not an id: a schedule can't name the session it fires into.

timezone?​
timezone?: string;

Optional IANA timezone identifier (e.g., "America/New_York"). Opaque metadata — the host's scheduler does the time-zone math. Default: "UTC".


ScheduleInputContext​

type ScheduleInputContext = object;

Context passed to a ScheduleInputFn at dispatch time. Captures the resolved schedule's identity, the nominal fire time supplied by the host scheduler (or now() if absent), and the effective principal the action will run as.

Properties​

cron​
cron: string;

Cron expression as configured.

flowKind​
flowKind: string;

The flow kind.

nominalFireTime​
nominalFireTime: string;

ISO-8601 fire time supplied by the host scheduler in the dispatch body, or now() if absent.

origin​
origin: "static" | "dynamic";

"static" or "dynamic" — useful for input functions that branch on origin.

principal​
principal: ResolvedPrincipal;

Effective principal for this dispatch (the schedule's principal, falling back to the gateway principal).

scheduleId​
scheduleId: string;

ScheduleInputFn​

type ScheduleInputFn = (ctx) => unknown | Promise<unknown>;

Input function called server-side at dispatch time.

Parameters​

ctx​

ScheduleInputContext

Returns​

unknown | Promise<unknown>


ScheduleResolutionContext​

type ScheduleResolutionContext = object;

Context passed to SchedulesConfig.resolve when the dispatch endpoint needs to look up a schedule that is not in static. Carries the raw dispatch URL id, the flow kind, the dispatch caller's gateway principal (typically a system user), the underlying HTTP request, and the host's store registry for resolvers that read directly from a store.

Properties​

flowKind​
flowKind: string;
gatewayPrincipal​
gatewayPrincipal: ResolvedPrincipal;

Principal of the dispatch caller, established by gateway auth (the shared scheduler secret typically yields a system principal). Non-authoritative for the scheduled action itself — that comes from the resolved ScheduleConfig.principal. Provided here for resolvers that need to authorize the lookup against the caller.

ownerPin?​
ownerPin?: InstanceOwnerPin;

The owner pin of the registered instance this dispatch addresses, when that instance is pinned to an owner; absent for every other flow. Taken from the registry, never from the request. It chooses no storage key: user-scoped storage is keyed by the organization the schedule id names (see resolveUserStorageKey in @flow-state-dev/engine). A resolver uses it only to refuse an id naming another organization than the pin's, or another user than a user-owned pin's. Removed with owner pins.

request​
request: Request;

Adapter-provided raw HTTP request (body, headers).

stores​
stores: ScheduleResolutionStores;

The host's store registry. Typed structurally so this contract can live in core; resolvers receive the full StoreRegistry at runtime.

Methods​

userStorageKey()​
userStorageKey(userId, orgId): string;

The storage key of userId's cell in orgId, for data no flow isolates: where a user-scoped resource collection that declares no flowIsolation (a schedule collection) keeps its rows. Supplied by the dispatch endpoint, which owns the engine's key derivation, so a resolver reads a user's row without depending on the engine.

Parameters​
userId​

string

orgId​

string

Returns​

string


ScheduleResolutionStores​

type ScheduleResolutionStores = object;

Subset of StoreRegistry exposed to dynamic resolvers. Defined structurally in core so defineFlow can reference the resolver shape without depending on @flow-state-dev/engine (which owns the full StoreRegistry type). Resolvers receive the host's full StoreRegistry at runtime — this type only narrows what the contract guarantees.

Properties​

content​
readonly content: object;

Content store — an instance's content body (writeContent), which is separate from its state. Key shape is (scopeType, scopeId, resourceKey).

get()​
get(
scopeType,
scopeId,
resourceKey
): Promise<string | undefined>;
Parameters​
scopeType​

"session" | "user" | "org"

scopeId​

string

resourceKey​

string

Returns​

Promise<string | undefined>

resourceState​
readonly resourceState: object;

Resource state store — where a resource collection's create / setState / patchState persist each instance's state, so the canonical entry point for resolvers backed by one. Key shape is (scopeType, scopeId, resourceKey); a missing (or deleted) instance reads as undefined.

get()​
get(
scopeType,
scopeId,
resourceKey
): Promise<
| {
state: Record<string, unknown>;
}
| undefined>;
Parameters​
scopeType​

"session" | "user" | "org"

scopeId​

string

resourceKey​

string

Returns​

Promise< | { state: Record<string, unknown>; } | undefined>


SchedulesConfig​

type SchedulesConfig = object;

Per-flow scheduled-actions configuration. static covers the framework cron-job case; resolve is the dynamic case (per-user, per-record, agent-created). The dispatch handler tries static[id] first and falls back to resolve(id, ctx).

Properties​

index?​
index?: ScheduleDueSource;

The schedule index this flow's dynamic schedules are mirrored into (@flow-state-dev/scheduled's ScheduleIndex). The app's schedule tick claims due entries from it and dispatches them to this flow, so the flow's schedules fire with no cron of the host's own. One index serves one flow. Typed structurally so this contract can live in core.

resolve?​
resolve?: (scheduleId, ctx) =>
| Promise<ScheduleConfig | null>
| ScheduleConfig
| null;

Dynamic resolver. Called when static[id] is absent. Receives the raw schedule id from the dispatch URL plus context (flow kind, the adapter's resolved gateway principal, request, and host stores). Return null to 404 the dispatch.

Implementations typically read from a host-owned store keyed by schedule id and return the persisted schedule definition.

Parameters​
scheduleId​

string

ctx​

ScheduleResolutionContext

Returns​

| Promise<ScheduleConfig | null> | ScheduleConfig | null

static?​
static?: Record<string, ScheduleConfig>;

Statically declared schedules, looked up by id first.


ScoreAnswer​

type ScoreAnswer = object;

The answer to a score question.

Properties​

confidence?​
confidence?: number;

The model's own reported confidence in this answer, when it gave one.

probabilities?​
probabilities?: Record<string, number>;

Distribution keyed by level index ("0", "1", …), when returned.

score​
score: number;

Position in [0, levels - 1]. May be fractional.

type​
type: "score";

ScoreQuestion​

type ScoreQuestion = object;

An ordered-scale question. Levels are indexed from 0.

Properties​

criteria​
readonly criteria: readonly (EvaluationInput | null)[];

At least two ordered level descriptions (null for no description).

instructions​
readonly instructions: EvaluationInput;
type​
readonly type: "score";

SequencerConfig​

type SequencerConfig<TInputSchema, TInput, TStateSchema, TFlowConfigSchema> = object;

Type Parameters​

TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

TInput​

TInput = z.infer<TInputSchema>

TStateSchema​

TStateSchema extends ZodTypeAny | undefined = undefined

TFlowConfigSchema​

TFlowConfigSchema extends ZodTypeAny | undefined = undefined

Properties​

activeStatusMessage?​
activeStatusMessage?: string | ((input, ctx) => string);

Active status message for this sequencer — declarative sugar for ctx.emit.status() at sequencer start. A static string is emitted once when the sequencer enters execution; a function receives (input, ctx) and its return value is emitted.

container?​
container?: object;
component?​
component?: string;
label?​
label?: string | ((input) => string);
metadata?​
metadata?:
| Record<string, unknown>
| ((input) => Record<string, unknown>);
description?​
description?: string;
durable?​
durable?: boolean;

When true (default), the sequencer's state is checkpointed to stores.checkpoints at every step boundary. The Phase 2 resume runtime reads the latest checkpoint to pick up after an interrupted request. Set false to opt out — typically for tests or single-shot ephemeral sequencers where persistence is unwanted overhead.

Latest-only semantics: storage is constant per sequencer regardless of step count. See SequencerCheckpoint.

flowConfigSchema?​
flowConfigSchema?: TFlowConfigSchema;

What this sequencer requires of whatever flow installs it. Types ctx.flow.config in every DSL callback — connectors, taps, conditions — and makes the flow refuse when it cannot supply a bag that satisfies it. See BlockConfig.flowConfigSchema.

inputSchema?​
inputSchema?: TInputSchema;
name​
name: string;
outputSchema?​
outputSchema?: ZodTypeAny;
stateSchema?​
stateSchema?: TStateSchema;

This sequencer's own request-scoped state (an alias: also exposed as ctx.self within its own DSL callbacks, in addition to ctx.sequencer).

transient?​
transient?: boolean;
uses?​
uses?: readonly UsesEntry[];

Capabilities to install. Merges resources, state schemas, targets, and any active preset surfaces into this sequencer's config.


SequencerOutputSchemaErrorDetails​

type SequencerOutputSchemaErrorDetails = object & Record<string, unknown>;

Structured payload attached to a runtime sequencer-output validation failure.

Type Declaration​

issues​
issues: ZodIssue[];
lastStepName​
lastStepName: string | undefined;
rawOutput​
rawOutput: unknown;
sequencerName​
sequencerName: string;

SequencerSchemaMismatchErrorDetails​

type SequencerSchemaMismatchErrorDetails = object & Record<string, unknown>;

Structured payload attached to a build-time .validate() structural mismatch.

Type Declaration​

declaredKind​
declaredKind: string;
inferredKind​
inferredKind: string | undefined;
reason​
reason: string;
sequencerName​
sequencerName: string;

SessionHistoryWindow​

type SessionHistoryWindow = object;

The history window this request loaded (session.historyWindow), read-only.

Properties​

startRequestId?​
readonly startRequestId?: string;

The first turn the window holds, when earlier turns have fallen out of it. Absent while every earlier turn is still in the window. The request record carries the same mark as historyStart.

turns​
readonly turns: number;

How many past turns the window holds.


SessionScopeHandle​

type SessionScopeHandle<TState> = object & ScopeStateOps<TState>;

Session scope handle — exposes per-session state and metadata. Resources have been lifted to the flat ctx.resources registry; a resource's intrinsic scope routes its storage to the session record for session-scoped definitions.

Type Parameters​

TState​

TState extends object = Record<string, unknown>

Type Declaration​

identity​
identity: ScopeIdentity;
items​
items: SessionItemViews;
lineageId?​
readonly lineageId?: string;

The lineage id minted when this session's record was created. A session deleted and created again under the same id gets a new one, so identity.id plus this names one incarnation of the session.

metadata​
metadata: Readonly<SessionMetadata>;
state​
state: Readonly<TState>;
window?​
readonly window?: SessionHistoryWindow;

The history window this request loaded. Absent on a context that loads no history (a test double, for one).

appendJournal()​
appendJournal(entry): Promise<void>;
Parameters​
entry​

JournalEntryInput

Returns​

Promise<void>

getJournal()​
getJournal(options?): Promise<JournalEntry[]>;
Parameters​
options?​
limit?​

number

offset?​

number

Returns​

Promise<JournalEntry[]>

setMetadata()​
setMetadata(input): Promise<void>;
Parameters​
input​

SessionMetadataInput

Returns​

Promise<void>

stopRequest()​
stopRequest(requestId): Promise<StopRequestOutcome>;

Stop another request running in this session, by its id.

The same stop the abort route records for a client, reached from a block: the request ends aborted. Only a request of this session can be stopped; any other id answers "not-in-this-session".

Parameters​
requestId​

string

Returns​

Promise<StopRequestOutcome>


SessionTarget​

type SessionTarget =
| {
key: string;
state?: Readonly<Record<string, unknown>>;
}
| {
id: string;
state?: Readonly<Record<string, unknown>>;
}
| {
from: true;
};

Which session a dispatch runs in.

  • key — a child of the running session, derived from this key together with the running request's tenant, principal, session and lineage. Minted on first use and adopted after, so the same key from the same parent always lands on the same child: a retry re-enters the child it already started.
  • id — an existing session. Delivered into it when it exists and is this principal's on this flow; refused by name otherwise. Never created — an unknown id is a typo, a stale reference, or a hallucinated value, and auto-creating turns all three into work nobody is watching. Unless it carries state: then a session absent at that id is created there, as a session of its own (no parent), from that state, judged by the target flow's session.createCheck with via: "dispatch" exactly as a key child is. The block computed the id and the state, so the create check is what decides whether that id is this principal's to create.
  • from — the seam-stamped sender. The runtime reads metadata.dispatch.from.sessionId through readDispatchStamp and delivers into that session as an id would. The author names no session. A request that was not dispatched has no sender (no-sender).

Union Members​

Type Literal​
{
key: string;
state?: Readonly<Record<string, unknown>>;
}
key​
readonly key: string;
state?​
readonly state?: Readonly<Record<string, unknown>>;

The child's initial session state, read only when the child is created: a child that already exists keeps its own. The target flow's stateSchema parses it and its session.createCheck judges it. Computed by the dispatching block's own code, never taken from a caller's input.


Type Literal​
{
id: string;
state?: Readonly<Record<string, unknown>>;
}
id​
readonly id: string;
state?​
readonly state?: Readonly<Record<string, unknown>>;

Initial state, read only when this id is created (see id above). From the dispatching block's code, never a caller's input.


Type Literal​
{
from: true;
}

SlotDeclaration​

type SlotDeclaration<T> = KeyedSlot<T> | ListSlot<T>;

A slot a kit declares: keyed or list.

Type Parameters​

T​

T = unknown


SlotKey​

type SlotKey<S> = string & object;

The key a contribution to one slot goes under: <kit>.<slot>, read from the owning kit's factory (workforce.slots.workerFlows) rather than spelled.

Type Parameters​

S​

S extends SlotDeclaration = SlotDeclaration

Type Declaration​

__slot?​
readonly __slot?: S;

SlotValue​

type SlotValue<S> = S extends KeyedSlot<infer T> ? Readonly<Record<string, T>> : S extends ListSlot<infer T> ? readonly T[] : never;

What a kit's install receives for one slot: the merged entries.

Type Parameters​

S​

S


SpeakChunk​

type SpeakChunk = object;

A chunk yielded by VoiceProvider.speakStream. Discriminated by kind so future variants (markers, viseme frames, etc.) can be added without breaking existing consumers. M1 ships only the "audio" variant.

Properties​

bytes​
bytes: Uint8Array;
isLast?​
isLast?: boolean;

Set on the final chunk so consumers can flush without waiting for return.

kind​
kind: "audio";
mediaType​
mediaType: string;

MIME media type of bytes. Stable across the stream.


StateOf​

type StateOf<T> = T extends object ? S["_output"] : T extends ZodTypeAny ? T["_output"] : never;

Type Parameters​

T​

T


StepOptions​

type StepOptions = object;

Per-step dispatch options for .step().

Deliberately tiny. This is not a general escape hatch for per-step config — both members carry something a step's dispatch owns and the block itself cannot see: the signal it runs under, and the moment its dispatch ends.

Properties​

abortSignal?​
abortSignal?: (ctx) => AbortSignal | undefined;

An additional abort signal this step runs under, resolved per execution from the running context.

Composed with the request's signal, never a replacement for it: the step aborts when either fires, so a caller cannot accidentally make a step outlive a cancelled request. Return undefined and the step runs exactly as it would without the option.

The resolver runs once per dispatch, immediately before the child is invoked, so it can read state a preceding step wrote.

Parameters​
ctx​

BlockContext

Returns​

AbortSignal | undefined

onSettled?​
onSettled?: (ctx, outcome) => void;

Called once when this step's dispatch leaves, by every path — it returned, it threw, or it suspended — and told which of the three it was.

Suspension is the one that needs a seam at all. .rescue() is deliberately not run for a SuspensionError (suspension is control flow, not a failure), and a suspended request does not abort its signal either, so a step that parks on ctx.suspend() passes through no handler a caller can compose. Anything a preceding step started and this step's completion was supposed to stop — a timer, a lease renewal, a subscription — outlives the request without this.

Why the outcome is part of the contract. A caller that releases on every exit alike releases too early on the two exits that are not suspension: "returned" and "threw" both pass to a downstream step (a recorder, a .rescue() handler) that still has work to do, and this hook fires before that step runs. A lease renewal stopped here has stopped before the write it was protecting. So the useful shape is usually "release only on "suspended", and let the downstream handler release the rest".

Runs in a finally and cannot change the step's outcome — a throw from it is caught, logged and discarded, so a cleanup bug cannot turn a suspension into a crash. It is for releasing what the dispatch was holding, not for recovery; throwing here is still a caller bug, it just is not the step's problem.

Must be synchronous. The return type is void, and TypeScript lets an async function satisfy that — so an async hook type-checks, is never awaited, and its release has not happened when the step settles (a rejection from one surfaces as an unhandled rejection, not as an error here). Awaiting it is deliberately not offered: it would move when the step settles, and when is the whole point of this hook.

Not called when nothing was dispatched, which is two situations, not one: a .stepIf() whose condition was false, and a step whose child is injected from the resume replay log instead of executed. The second matters because a durable request can re-enter many times, and a hook that fired on every re-entry would run non-idempotent cleanup — releasing a semaphore, decrementing a refcount — once per resume for work that ran once.

Parameters​
ctx​

BlockContext

outcome​

StepOutcome

Returns​

void


StepOutcome​

type StepOutcome = "returned" | "threw" | "suspended";

How a step's dispatch left.

"suspended" is separated from "threw" even though both arrive as a throw, because they are opposite situations for a caller holding a resource: a suspension has no downstream handler at all, and a genuine failure has one (.rescue()) that is about to run.


StopRequestOutcome​

type StopRequestOutcome =
| "stopped"
| "already-finished"
| "already-resolved"
| "not-in-this-session";

What SessionScopeHandle.stopRequest came to.

  • "stopped": the stop is recorded on the request. A request running in this process has its signal fired now; one running in another process is stopped on that process's next heartbeat, as an abort is. A request a crash or restart left interrupted, behind no gate, is ended aborted now, so nothing continues it.
  • "already-finished": the request had already ended; nothing was written.
  • "already-resolved": the request was parked, but what it waited on was resolved first (an answer won the race), so it is running again. Nothing was written; a second stop reaches the running turn.
  • "not-in-this-session": no request under that id belongs to this session (another session's, another tenant's, or none at all). Nothing was written, and the answer does not say which.

SuspendForUserKind​

type SuspendForUserKind = "approval" | "review" | "input";

What a suspension for a user asks for (ctx.suspendForUser):

  • approval: a yes or a no. At a deadline, a no.
  • review: a verdict on work the user looks at.
  • input: an answer the code reads on its next line.

Never a question: a question with a task holds its task instead.


TaskBinding​

type TaskBinding = object;

What a task board binds onto the dispatch it installs at a task dispatcher: which board it is, and the claim gate every entry the dispatcher addresses must run behind.

The gate needs the board's ledger, which lives outside core, so the board supplies it and defineFlow applies it: for every reachable task dispatcher the walk finds, the target entry is rebuilt as gate(entry). That is what lets an author declare a task entry as a plain block — the same shape as an action — and still never have it reached without the row re-read, the claim verified, the task scope marked and the ticket re-minted first.

Properties​

boardId​
readonly boardId: string;
gate​
readonly gate: (entry, target) => ActionCore;

Wrap an entry in this board's claim gate. The second argument is the entry's name on the flow.

Parameters​
entry​

ActionCore

target​

string

Returns​

ActionCore

requiresInternal?​
readonly requiresInternal?: readonly string[];

Internal entries the flow holding this board must declare (a board that hands rows out is heard back on onTaskSettled). defineFlow refuses a flow that reaches the board and lacks one, by name.

viaEntrySource?​
readonly viaEntrySource?: boolean;

The board hands its rows to an entry that declares where it takes tasks from (TaskEntry.from) through that entry's own gate, which reads the row off this board's ledger by id (a worker's step filed session: "new", handed to its own work entry). Without it, an entry with from that this board also dispatches to is refused. An entry without from still runs behind this board's gate, and a flow that declares no such entry is not refused: it files no row for it, and a dispatch to it is refused no-entry.


TaskDispatchInput​

type TaskDispatchInput = z.infer<typeof taskDispatchInputSchema>;

TaskEntry​

type TaskEntry = ActionCore & object;

A task entry: the block a board drain hands a claimed row to, in a session of its own. Declared on the flow like any other entry — task: { actions: { implement: { block } } } — and reached only through a task dispatch from a dispatcher({ type: "task" }) in a board's workers. defineFlow wraps the entry in that board's claim gate (see TaskBinding), so the block receives the packed worker input the row was claimed with, never the envelope, and never runs against a row nothing verified.

Type Declaration​

from?​
readonly from?: TaskBinding;

Where this entry takes tasks from when no board in this flow dispatches to it: a binding whose gate reads each task off the ledger its dispatch names, so one entry serves tasks from many ledgers, including ones made after the flow was defined. defineFlow applies this gate exactly as it applies a board's, so the entry still never runs against a row nothing verified. An entry a board in this flow also dispatches to is refused: one entry runs behind one gate.

gatedBy?​
readonly gatedBy?: TaskBinding;

The binding whose gate fronts this entry, set by defineFlow when it applies the gate. Read by the run-time routability check on a carried core: a task dispatcher produced at dispatch time must be held by the same board, or its rows would be claimed on one ledger and refused at another board's gate after the dispatch was accepted.


TaskEntryChoice​

type TaskEntryChoice = object;

A task address's entry, chosen per row: by answers, for each row, one of the entry names listed in among. Every listed name is declared and verified like a string action (defineFlow for this flow, the seam for another), so the entries a board's rows can land on are still declared, not computed. An answer outside among is refused before anything is dispatched.

Properties​

among​
readonly among: readonly string[];
by​
readonly by: (task, ctx) => string | Promise<string>;
Parameters​
task​

TaskTargetQuery

ctx​

BlockContext

Returns​

string | Promise<string>


TaskFlowTarget​

type TaskFlowTarget = (task, ctx) => string | undefined | Promise<string | undefined>;

A task dispatcher's flow, looked up per task: the id of the flow instance the entry lives on, or undefined when nothing answers for this task (the dispatch is then refused flow-not-found, naming the assignee). Resolved once per dispatch, before anything is dispatched.

Parameters​

task​

TaskTargetQuery

ctx​

BlockContext

Returns​

string | undefined | Promise<string | undefined>


TaskSessionChoice​

type TaskSessionChoice =
| {
key: string;
}
| {
id: string;
};

What a { by } session policy answers for one row: a child key, minted on first use and adopted after exactly as a { key } policy's is, or the id of an existing session to deliver into (the SessionTarget { id }).


TaskSessionPolicy​

type TaskSessionPolicy<TPayload> =
| "per-task"
| "per-worker"
| {
key: (task, ctx) => string;
}
| {
by: (task, ctx) =>
| TaskSessionChoice
| Promise<TaskSessionChoice>;
};

Which session a task dispatch runs in, decided per row.

  • "per-task" — one child per row, keyed on the task id (a follow-up row, whose payload names followUpOf, on the task it follows). Rows are independent: a checkout per issue.
  • "per-worker" — one child per assignee, shared by every row routed to it. The worker remembers what it already did.
  • { key } — keyed on what the function returns, read from the worker input the row was packed into. One issue across several phases, or a key shared across assignees.
  • { by } — chosen per row (see TaskSessionChoice): a keyed child, as { key } makes, or an existing session by id. One board can then send some rows to a child of their own and others into a session that is already running. An id is delivered into, never created, and refused by name when it is missing or not this principal's on this flow, so an id read off a row cannot reach a session the claimer could not.

The presets frame the board id into the key, so two boards' children stay apart even when their task ids coincide; a custom key is used as returned.

Type Parameters​

TPayload​

TPayload = unknown


TaskStateTarget​

type TaskStateTarget = (task, ctx) =>
| Readonly<Record<string, unknown>>
| Promise<Readonly<Record<string, unknown>>>;

A task dispatcher's child-session initial state, looked up per task: what the target flow's stateSchema parses and its session.createCheck judges when the task's child session is created. Handed the same server-derived task a per-task flow target is (assignee, id, input), because the state names who runs the row. Resolved once per dispatch, before anything is dispatched.

Parameters​

task​

TaskTargetQuery

ctx​

BlockContext

Returns​

| Readonly<Record<string, unknown>> | Promise<Readonly<Record<string, unknown>>>


TaskTargetQuery​

type TaskTargetQuery = object;

The task a task dispatcher's per-task target is asked about: who the row is assigned to, which row, and the worker input it was claimed with. All of it comes off the claim the board minted, never from a caller.

Properties​

assignee​
readonly assignee: string;

The row's assignee, the name the board routed it by.

filedBy?​
readonly filedBy?: string;

The user whose request filed the row, as the ledger recorded it when the row was added. Supplied by a board's hand-over, which reads it off the row it claimed; absent when the ledger recorded none, or when a bare dispatcher is run with an envelope (which carries no filer).

input​
readonly input: unknown;

The packed worker input the row was claimed with.

taskId​
readonly taskId: string;

ToolCacheAccessor​

type ToolCacheAccessor = object & Record<string, (...args) => any>;

Surface a consumer block can call via ctx.cap.toolCache.*.

Type Declaration​

invalidate​
invalidate: (keyOrPrefix) => number;
Parameters​
keyOrPrefix​

string

Returns​

number

stats​
stats: () => object;
Returns​

object

entries​
entries: number;
store​
store: () => ToolCacheStore;
Returns​

ToolCacheStore


ToolLifecycleEvent​

type ToolLifecycleEvent = object;

Properties​

cached?​
cached?: boolean;

True when the tool's result was served from the per-tool memoization cache rather than executed against the upstream. Observers fire on the cache-hit path with the same onToolStarted / onToolCompleted ordering as a normal call so consumers can attribute downstream side-effects either way. onToolErrored never fires on the cache path — errors are never cached.

error?​
error?: Error;
input​
input: unknown;
output?​
output?: unknown;
toolName​
toolName: string;

ToolsConfig​

type ToolsConfig = object;

Properties​

defaults?​
defaults?: object;
retry?​
retry?: RetryPolicy;
timeoutMs?​
timeoutMs?: number;
onToolCompleted?​
onToolCompleted?:
| HookHandler<ToolLifecycleEvent>
| BlockDefinition<any, any>;
onToolErrored?​
onToolErrored?:
| HookHandler<ToolLifecycleEvent>
| BlockDefinition<any, any>;
onToolStarted?​
onToolStarted?:
| HookHandler<ToolLifecycleEvent>
| BlockDefinition<any, any>;

ToolsSlot​

type ToolsSlot =
| GeneratorTool[]
| ((ctx) => MaybePromise<GeneratorTool[]>);

Tools slot accepted by generators and pattern factories — static array or context-aware function.


TopicOptions​

type TopicOptions = object;

Narrow a topic to one resource under its scope.

Properties​

resource?​
resource?: string;

TracingLevel​

type TracingLevel = "verbose" | "normal" | "minimal";

TTSConfig​

type TTSConfig = object;

TTS configuration on VoiceConfig.

Properties​

model?​
model?: string;

Speak model id. Provider-specific; if omitted, the provider's default is used.

speed?​
speed?: number;
voice?​
voice?: string;

UserMessageEcho​

type UserMessageEcho = object;

What an action's userMessage may return beside plain text: the text, the item's metadata, and files the flow hands the line.

Properties​

attachments?​
readonly attachments?: ReadonlyArray<FileContent>;

Files the line carries that the flow kept itself, in reference form (FileContent whose data is fsd-blob:<id>), such as a task's brief files read off its row. Written as file parts after the person's own files, so a model reads them as part of the line. Read off server-written state, never off the action's input: a reference from input is a claim the action route never checked. A run reads only files its session or its person's own scope owns, so any other reference reads nothing.

metadata?​
readonly metadata?: Record<string, unknown>;
text​
readonly text: string;

UserScopeHandle​

type UserScopeHandle<TState> = object & ScopeStateOps<TState>;

Type Parameters​

TState​

TState extends object = Record<string, unknown>

Type Declaration​

identity​
identity: ScopeIdentity;
state​
state: Readonly<TState>;

UsesEntry​

type UsesEntry =
| CapabilityRef
| ((ctx) => readonly CapabilityRef[]);

A single entry in a uses array — either a static capability reference or a function that resolves capabilities at runtime based on context.

Dynamic entries contribute context, tools and control tools only. Resources must be declared statically (on the capability's required surface or elsewhere) because they need to exist before block execution.


UsesSlot​

type UsesSlot = readonly UsesEntry[];

The uses slot on blocks and capabilities. Accepts a readonly array of static capability refs and/or dynamic resolver functions.


ViewChange​

type ViewChange = object;

The change a view's run is asked to answer for: the notice that woke its watcher, with the ids it named. Ids are the publisher's (a task on a board notice, an entry's storage key on a resource notice), never row keys: only the view knows which of its rows an id touches.

Properties​

ids​
readonly ids: readonly string[];
kind​
readonly kind: ChangeKind;
topic​
readonly topic: WireTopic;

ViewConfig​

type ViewConfig<TBlock, TScope> = object;

What an author writes for defineView.

Type Parameters​

TBlock​

TBlock extends BlockDefinition = BlockDefinition

TScope​

TScope extends ViewScope = ViewScope

Properties​

block​
block: TBlock;

The block that computes the answer. It must declare an outputSchema.

description?​
description?: string;

Human-readable description, for tooling. Defaults to block.description.

inputSchema?​
inputSchema?: TBlock["inputSchema"];

Overrides block.inputSchema for the view's input, as on an action.

scope​
scope: TScope;

Where the view runs. "user" and "org" run with no session: the caller's user and org come from the verified principal, and a block that reaches for ctx.session is refused with NoSessionError.

Methods​

key()?​
key?(entry): string;

The row's key, for a view whose answer is a list. With it the answer must be an array whose rows have distinct string keys, and a screen keeps rows by key.

Method syntax on purpose: its parameter is checked bivariantly, so a view with no list (whose entry is never) is still a ViewDefinition under strictFunctionTypes. An author's key is still typed by the entry.

Parameters​
entry​

ViewElement<TBlock>

Returns​

string


ViewDefinition​

type ViewDefinition<TBlock, TScope> = Readonly<ViewConfig<TBlock, TScope>> & object;

A view as defineView returns it. Install it in a flow's views.

Type Parameters​

TBlock​

TBlock extends BlockDefinition = BlockDefinition

TScope​

TScope extends ViewScope = ViewScope

Type Declaration​

kind​
readonly kind: "view";

ViewElement​

type ViewElement<TBlock> = BlockOutput<TBlock> extends readonly infer TElement[] ? TElement : never;

The element type of a block whose output is a list, else never.

Type Parameters​

TBlock​

TBlock extends BlockDefinition


ViewHearing​

type ViewHearing = object;

Which notices under one of a view answer's topics may change what its run read. A watcher reads again on a notice its topic covers whose kind is listed and, for a resource notice that names a path, whose path falls at or under one of paths (mayHold). A resource notice that names no path always reads. A resync is not decided here: the watcher reads on it before this rule runs.

  • state, on a user or org topic: the scope's state was read.
  • state, on a session topic: the session's state was read.
  • items, request, run and state, on a session topic: the session itself was read (its items, metadata or history).
  • resource, with paths: a resource was read, at its storage key or a collection's root.
  • board, on a session topic narrowed to a board: a task board was read through its task collection, whose every write publishes its board notice there. Its ledger's own resource notices are not heard.
  • board, with partitions: a partitioned board was read at those partitions, so a board notice that names another partition can't change it (hearsNotice).

Properties​

kinds​
readonly kinds: readonly ChangeKind[];
partitions?​
readonly partitions?: readonly string[];

The partitions of a partitioned board the run read, as opaque keys (WireNotice.partition), its empty ones included. Absent: the board was read whole, or by a server from before partitions, and every board notice under the topic is heard.

paths?​
readonly paths?: readonly string[];
topic​
readonly topic: WireTopic;

ViewInput​

type ViewInput<TView> = SchemaInput<TView["block"]["inputSchema"]>;

The input a caller sends to a view, before its schema applies defaults or transforms.

Type Parameters​

TView​

TView extends object


ViewOutput​

type ViewOutput<TView> = BlockOutput<TView["block"]>;

The answer a view computes: its block's output type. Never unknown.

Type Parameters​

TView​

TView extends object


ViewScope​

type ViewScope = "session" | "user" | "org";

Where a view runs: on a session, or at the caller's user or org scope with no session.


VoiceConfig​

type VoiceConfig = object;

Voice configuration on a flow.

Properties​

provider?​
provider?: VoiceProvider;

Provider that owns the flow's voice surfaces. Consumed server-side by the router and TTS pipeline.

tts?​
tts?: TTSConfig;

VoiceErrorKind​

type VoiceErrorKind =
| "auth"
| "rate_limit"
| "not_found"
| "invalid_input"
| "format_unsupported"
| "provider_unavailable"
| "network"
| "aborted"
| "unknown";

Discriminator for VoiceError. The taxonomy is provider-agnostic: every voice provider implementation classifies its underlying failures into one of these kinds before rethrowing.


WebhookConfig​

type WebhookConfig = Record<string, WebhookSubscriptionConfig>;

Per-flow webhook configuration. Carried on FlowDefinition.webhooks, keyed by provider — the :provider URL segment the adapter mounts.


WebhookSubscriptionConfig​

type WebhookSubscriptionConfig =
| WebhookBindingsConfig
| WebhookServiceConfig;

Per-provider declaration on the flow. Pure routing — no secrets, no crypto. Verification and payload mechanics live on the host's WebhookProviderDefinition, keyed by the same provider name.


WhenRule​

type WhenRule<TInput, TCtx> = object;

Returns a boolean condition. When true, replaces the model with use.

Type Parameters​

TInput​

TInput = unknown

TCtx​

TCtx = AnyBlockContext

Properties​

use​
use: string | string[];
when​
when: (input, ctx) => MaybePromise<boolean>;
Parameters​
input​

TInput

ctx​

TCtx

Returns​

MaybePromise<boolean>


WireTopic​

type WireTopic =
| {
id: string;
resource?: string;
scope: "session";
}
| {
resource?: string;
scope: "user" | "org";
};

A topic as a client names it: a scope, the session's id for a session, and optionally one resource under the scope. No user, org or tenant id.


WithArg​

type WithArg<Self, TNames, TPresets> = [NonNullable<ConfigArgOf<Self>>] extends [never] ? PresetOverrides<TNames, TPresets> : NonNullable<ConfigArgOf<Self>> extends readonly unknown[] ? NonNullable<ConfigArgOf<Self>> : NonNullable<ConfigArgOf<Self>> extends object ? NonNullable<ConfigArgOf<Self>> & PresetOverrides<TNames, TPresets> : NonNullable<ConfigArgOf<Self>>;

The .with() argument type. Cases, in order:

  • No config (config half is never, nullish stripped): just the all-optional preset overrides.
  • Array or scalar config: that value unchanged — a non-object config is routed wholesale at runtime and can't share a bag with preset keys, so the preset overrides are not intersected (which would collapse to never).
  • Object config: the config input intersected with the preset overrides, the flat mixed bag.

Type Parameters​

Self​

Self

TNames​

TNames extends string

TPresets​

TPresets extends Record<string, PresetDef | string[]>

Variables​

DEFAULT_MODEL_LOOKUP​

const DEFAULT_MODEL_LOOKUP: ModelLookupEntry[];

DEFAULT_ORG_ID​

const DEFAULT_ORG_ID: "__fsd_default_org__" = "__fsd_default_org__";

The organization every unauthenticated single-organization deployment runs under.

Organization identity is never optional: a session, request or dispatched child always carries one. An app that configures no resolvePrincipal has no verified organization to carry, so the framework supplies this one and the existing org scope works without an app-level wrapper.

It is a development and system-wiring identity, not a security boundary. The spelling is deliberately unusable as a customer id so it cannot overlap with a real organization, and a configured resolver returning it is refused — an authenticated app must name its own organization.

Once written it is stored identity: changing this value after records exist requires the offline migration in the persistence guide.


DISPATCH_TYPES​

const DISPATCH_TYPES: readonly DispatchType[];

Every dispatch type, for validation and iteration.


dispatchHandleSchema​

const dispatchHandleSchema: z.ZodObject<{
adopted: z.ZodBoolean;
requestId: z.ZodString;
sessionId: z.ZodString;
}, "strip", ZodTypeAny, {
adopted: boolean;
requestId: string;
sessionId: string;
}, {
adopted: boolean;
requestId: string;
sessionId: string;
}>;

What a dispatcher returns: enough to find the work it started.


dispatchWaitResultSchema​

const dispatchWaitResultSchema: z.ZodObject<{
error: z.ZodOptional<z.ZodString>;
output: z.ZodOptional<z.ZodUnknown>;
requestId: z.ZodString;
status: z.ZodEnum<["completed", "failed", "running"]>;
}, "strip", ZodTypeAny, {
error?: string;
output?: unknown;
requestId: string;
status: "completed" | "failed" | "running";
}, {
error?: string;
output?: unknown;
requestId: string;
status: "completed" | "failed" | "running";
}>;

What a dispatcher with wait: true outputs: how the request it started ended, or that it was still running at the deadline.


estimateTokenCounter​

const estimateTokenCounter: TokenCounter;

MANIFEST_DOMAINS​

const MANIFEST_DOMAINS: readonly ["workers", "skills", "resources"];

The domains the door answers for, in the order a caller sees them.

Pinned and model-facing: these strings appear in a tool argument and in a worker's own file, so renaming one breaks prompts and files on disk. Three — a generator already gets its tool list from its provider, and what another worker can do belongs on that worker's entry.


RECORDED_VALUE_OMITTED​

const RECORDED_VALUE_OMITTED: "RECORDED_VALUE_OMITTED" = "RECORDED_VALUE_OMITTED";

The error code a resumed request fails with when it meets a placeholder.


slot​

const slot: object;

The two slot shapes, each with the schema its entries are checked against.

Type Declaration​

keyed​
readonly keyed: <T>(schema) => KeyedSlot<T>;

A slot of entries by key; a key given twice is refused, naming both contributors.

Type Parameters​
T​

T

Parameters​
schema​

z.ZodType<T, z.ZodTypeDef, unknown>

Returns​

KeyedSlot<T>

list​
readonly list: <T>(schema) => ListSlot<T>;

A slot of entries in a list, appended in install order, the app's last.

Type Parameters​
T​

T

Parameters​
schema​

z.ZodType<T, z.ZodTypeDef, unknown>

Returns​

ListSlot<T>


SUSPENSION_SKIPPED​

const SUSPENSION_SKIPPED: unique symbol;

Returned by ctx.suspend() when a human skips an optional suspension (resumed with action: "skip"). Distinct from reject, which throws SuspensionRejectedError and aborts the flow: a skip is normal control flow, so a flow author branches on it (if (r === SUSPENSION_SKIPPED) useDefault()). The symbol never crosses the serialization boundary — only the string resolution: "skipped" is ever persisted; the sentinel is reconstructed on both the live continuation and the replay path.


taskDispatchInputSchema​

const taskDispatchInputSchema: z.ZodObject<{
assignee: z.ZodString;
attempt: z.ZodNumber;
boardId: z.ZodString;
createdAt: z.ZodNumber;
incarnationId: z.ZodOptional<z.ZodString>;
partition: z.ZodOptional<z.ZodString>;
payload: z.ZodUnknown;
taskId: z.ZodString;
turn: z.ZodOptional<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
assignee: string;
attempt: number;
boardId: string;
createdAt: number;
incarnationId?: string;
partition?: string;
payload?: unknown;
taskId: string;
turn?: number;
}, {
assignee: string;
attempt: number;
boardId: string;
createdAt: number;
incarnationId?: string;
partition?: string;
payload?: unknown;
taskId: string;
turn?: number;
}>;

What a task dispatch carries: the claim's identity and the worker's input.

Every field is server-derived at dispatch — the board supplies them from the ticket it minted off the row it claimed. attempt, createdAt and incarnationId say which claim this dispatch believes it is running; assignee names the assignee the board routed the row to. The entry's gate decides whether all of that is still true: verified, never trusted.


topic​

const topic: object;

The wire topic constructors. topic.session(id) watches one session, topic.user() the caller's own user scope and topic.org() the caller's organization. Each takes an optional { resource } to watch one resource under the scope.

Type Declaration​

org​
readonly org: (options?) => WireTopic;
Parameters​
options?​

TopicOptions

Returns​

WireTopic

session​
readonly session: (id, options?) => WireTopic;
Parameters​
id​

string

options?​

TopicOptions

Returns​

WireTopic

user​
readonly user: (options?) => WireTopic;
Parameters​
options?​

TopicOptions

Returns​

WireTopic

Functions​

__resetDeprecationWarningsForTests()​

function __resetDeprecationWarningsForTests(): void;

Test-only: forget all claimed keys so a fresh process can be simulated.

Returns​

void


assertStrictCompatible()​

function assertStrictCompatible(
schema,
label?,
options?
): void;

Throw a StrictSchemaError if schema, after the strict transform, still contains a construct OpenAI strict structured-output mode rejects. A no-op on a compatible schema. label (e.g. a generator name) is prefixed onto the thrown message.

Authors can call this in a test, but generators call it automatically at definition (see generator()), so a bad output schema fails at import. The error's violations carry the offending path and Zod type for each issue.

Parameters​

schema​

ZodTypeAny

label?​

string

options?​

Pick<MakeSchemaStrictOptions, "requireTextOrObjectRoot">

Returns​

void


bindTaskDispatcher()​

function bindTaskDispatcher(block, binding): void;

Bind a board's claim gate to the block that dispatches its tasks. Substrate- facing; called by taskBoard() on the dispatch it installs at each dispatcher({ type: "task" }), after markDispatcher has stamped the address the binding is keyed by.

Parameters​

block​

BlockDefinition<any, any>

binding​

TaskBinding

Returns​

void

Throws​

when the block carries no task address, or is already bound to a different board — one dispatch serves one board, or the walk could not say whose gate the entry gets.


bindToolCacheStore()​

function bindToolCacheStore(ctx, store): void;

Bind a cache store onto a context so any cacheable tool that runs under that subtree resolves to it. Used by taskBoard's outer sequencer to scope the store to a single board run; consumers can also call it directly to share a store across blocks without going through the capability path.

Parameters​

ctx​

BlockContext

store​

ToolCacheStore

Returns​

void


boolean()​

function boolean(instructions, criteria?): BooleanQuestion;

A yes/no question. The answer's probability is the model's estimate that the answer is yes.

Parameters​

instructions​

EvaluationInput

What to decide.

criteria?​

Optional descriptions of what true and false mean.

false?​

EvaluationInput | null

true?​

EvaluationInput | null

Returns​

BooleanQuestion


canListVoices()​

function canListVoices(p): p is ListVoicesCapable;

Narrows to ListVoicesCapable when the provider advertises listVoices.

Parameters​

p​

VoiceProvider

Returns​

p is ListVoicesCapable


canonicalizeToolArgs()​

function canonicalizeToolArgs(value): string;

Canonicalize a value into a deterministic JSON string. Recursively sorts object keys so two calls whose arg objects differ only in key order produce the same cache key. Throws a clear error when the value contains non-JSON-serializable types (functions, symbols, BigInt, class instances with custom toJSON, etc.) — silent fallback would cause cache poisoning.

undefined is treated as omitted (matches JSON.stringify). Tools that distinguish "key not present" from "key present with undefined" should supply their own keyFn.

Parameters​

value​

unknown

Returns​

string


canSpeak()​

function canSpeak(p): p is SpeakCapable;

Narrows to SpeakCapable when the provider advertises speak.

Parameters​

p​

VoiceProvider

Returns​

p is SpeakCapable


canSpeakStream()​

function canSpeakStream(p): p is SpeakStreamCapable;

Narrows to SpeakStreamCapable when the provider advertises speakStream.

Parameters​

p​

VoiceProvider

Returns​

p is SpeakStreamCapable


canTranscribe()​

function canTranscribe(p): p is TranscribeCapable;

Narrows to TranscribeCapable when the provider advertises transcribe.

Parameters​

p​

VoiceProvider

Returns​

p is TranscribeCapable


choice()​

function choice<TOptions>(instructions, options): ChoiceQuestion<Extract<keyof TOptions, string>>;

A multiple-choice question. The option keys become the answer's type: choice("Which team?", { billing: "…", technical: "…" }) answers with choice: "billing" | "technical".

Type Parameters​

TOptions​

TOptions extends Record<string, EvaluationInput | null>

Parameters​

instructions​

EvaluationInput

What to decide.

options​

TOptions

Option key → description (null for none). At least one.

Returns​

ChoiceQuestion<Extract<keyof TOptions, string>>


collapseToCanonicalLog()​

function collapseToCanonicalLog<T>(items): T[];

Collapse a request's physical item log to its canonical view.

Three superseding rules, all keyed by the logical block path:

  1. Resume re-run emissions. For every suspension that has a matching suspension_resume (a resolved cycle), the block at that suspension's logical path re-ran on continuation. Its run-1 emissions are exactly the items it owns at an itemIndex below the suspension's — drop them; the re-emitted run-2 copies (after the resume) survive. suspension and suspension_resume items are never dropped (they are the audit trail the history must preserve). Across N cycles the latest resolved suspension per logical path wins, so intermediate-cycle emissions collapse too.
  2. Superseded traces. Among block_trace items sharing a logical path, keep only the canonical one — the completed trace with the highest itemIndex (or, absent any completed, the highest-index trace) — and drop the run-1 partial(s).
  3. Crash-recovery re-run emissions. The continue path (crash recovery) re-runs the interrupted in-flight block with NO suspension / suspension_resume marker, so Rule 1 never fires for it — its run-1 emissions would otherwise survive next to the re-emitted run-2 copies. A re-run is visible as more than one block_trace on a logical path; the canonical (latest) trace's itemIndex is the start of the surviving run (traces reserve their index at block start). Use it as the supersession boundary, merged with Rule 1's so the later boundary wins. A block that ran once (one trace) — including a completed block injected from the log on replay — has no boundary and is left untouched.
  4. Generator tool-call de-duplication. A generator that suspends inside its tool loop re-runs on resume, setting a Rule-1/3 boundary on the generator's own logical path. But a tool_output carries its parent generator's blockInstanceId as provenance, so a completed sibling tool call that settled on run 1 (below the boundary) would be dropped even though resume never re-runs it — it is injected from the log, not re-emitted, so no run-2 copy replaces it. Losing it would make a post-resume GET/useSession incomplete. Tool calls are memoized per toolCall.callId, so tool_outputs are collapsed by (logical path + callId) instead of by the generator's re-run boundary: the canonical one per callId is the completed (or highest-index) record — the run-2 approved result supersedes its run-1 failed(SUSPENSION) gate record for the same callId, while a completed sibling with no run-2 copy survives. tool_output is therefore exempt from the Rule-1/3 boundary. Non-generator (.asTool()) outputs have unique synthesized callIds, so this is a no-op for them.

Order and identity of the surviving items are preserved. A request that never suspended is returned unchanged (no resolved suspensions, no duplicate traces).

Type Parameters​

T​

T extends RuntimeItem

Parameters​

items​

readonly T[]

Returns​

T[]


composeSideChainSignal()​

function composeSideChainSignal(ctx, extra): AbortSignal | undefined;

The background signal a subtree's .sideChain() dispatches should read, once extra has been composed into it.

.sideChain() / .sideChainIf() / .forEachSideChain() deliberately do NOT run under ctx.signal — they substitute the request's background signal so a task tree survives transport teardown. That substitution is right about the transport signal and wrong about everything else composed on top: a caller that added a signal to this subtree via .step(block, { abortSignal }) has that signal silently dropped the moment the subtree dispatches background work, which is precisely where the un-cancelled work goes on costing money.

Composing rather than substituting keeps both promises: the task still outlives a disconnected client, and it still stops when the caller's signal fires.

Returns undefined when the request installed no background signal (unit contexts). That case must stay untouched — there, sideChainTaskCtx runs the task on ctx.signal, which already carries extra, and installing one here would substitute extra for the request signal instead of adding to it.

Parameters​

ctx​

BlockContext

extra​

AbortSignal

Returns​

AbortSignal | undefined


containsSecret()​

function containsSecret(text): boolean;

Whether text carries something shaped like an API key or bearer token, by the same shapes redactSecrets removes. For a write that must refuse a credential rather than store it.

Parameters​

text​

string

Returns​

boolean


contextFn()​

Call Signature​

function contextFn<TSession>(schemas, fn): ContextFunction;

Creates a typed context function for use in generator context slots.

The schemas parameter acts as a type carrier — it declares which scope state types the callback expects, enabling TypeScript inference without any runtime schema validation. The actual state values are read from BlockContext scope handles at execution time.

The returned function fits anywhere a GeneratorSlotEntry does. Two common shapes:

  • Array form: context: [researchCtx] — the function's string return becomes a system message of its own.
  • Object form: context: { research: researchCtx } — the function's return is wrapped in <research>...</research> and aggregates with any other contributions to the research key from capabilities or other slots. See ContextObject for the full object-form contract.
Type Parameters​
TSession​

TSession extends ZodTypeAny

Parameters​
schemas​
session​

TSession

fn​

(scopes, ctx) => string

Returns​

ContextFunction

Example​
import { contextFn } from "@flow-state-dev/core";
import { list } from "@flow-state-dev/core/prompt";

const researchCtx = contextFn(
{ session: sessionStateSchema },
({ session }) => list(session.coveredTopics)
);

// Object form — wrapped under <research> and aggregated cross-source.
generator({
name: "researcher",
context: { research: researchCtx },
// ...
});

Call Signature​

function contextFn<TSession, TUser>(schemas, fn): ContextFunction;

Creates a typed context function for use in generator context slots.

The schemas parameter acts as a type carrier — it declares which scope state types the callback expects, enabling TypeScript inference without any runtime schema validation. The actual state values are read from BlockContext scope handles at execution time.

The returned function fits anywhere a GeneratorSlotEntry does. Two common shapes:

  • Array form: context: [researchCtx] — the function's string return becomes a system message of its own.
  • Object form: context: { research: researchCtx } — the function's return is wrapped in <research>...</research> and aggregates with any other contributions to the research key from capabilities or other slots. See ContextObject for the full object-form contract.
Type Parameters​
TSession​

TSession extends ZodTypeAny

TUser​

TUser extends ZodTypeAny

Parameters​
schemas​
session​

TSession

user​

TUser

fn​

(scopes, ctx) => string

Returns​

ContextFunction

Example​
import { contextFn } from "@flow-state-dev/core";
import { list } from "@flow-state-dev/core/prompt";

const researchCtx = contextFn(
{ session: sessionStateSchema },
({ session }) => list(session.coveredTopics)
);

// Object form — wrapped under <research> and aggregated cross-source.
generator({
name: "researcher",
context: { research: researchCtx },
// ...
});

Call Signature​

function contextFn<TSession, TUser, TOrg>(schemas, fn): ContextFunction;

Creates a typed context function for use in generator context slots.

The schemas parameter acts as a type carrier — it declares which scope state types the callback expects, enabling TypeScript inference without any runtime schema validation. The actual state values are read from BlockContext scope handles at execution time.

The returned function fits anywhere a GeneratorSlotEntry does. Two common shapes:

  • Array form: context: [researchCtx] — the function's string return becomes a system message of its own.
  • Object form: context: { research: researchCtx } — the function's return is wrapped in <research>...</research> and aggregates with any other contributions to the research key from capabilities or other slots. See ContextObject for the full object-form contract.
Type Parameters​
TSession​

TSession extends ZodTypeAny

TUser​

TUser extends ZodTypeAny

TOrg​

TOrg extends ZodTypeAny

Parameters​
schemas​
org​

TOrg

session​

TSession

user​

TUser

fn​

(scopes, ctx) => string

Returns​

ContextFunction

Example​
import { contextFn } from "@flow-state-dev/core";
import { list } from "@flow-state-dev/core/prompt";

const researchCtx = contextFn(
{ session: sessionStateSchema },
({ session }) => list(session.coveredTopics)
);

// Object form — wrapped under <research> and aggregated cross-source.
generator({
name: "researcher",
context: { research: researchCtx },
// ...
});

createCompositeVoiceProvider()​

function createCompositeVoiceProvider(config): VoiceProvider;

Build a synthetic provider that delegates each ability to a different underlying provider. The returned abilities reflect what the underlying providers actually advertise — declaring a slot whose provider doesn't support that ability yields a false flag rather than a runtime failure.

Composite-only invariants:

  • providerName is "composite".
  • id is "composite:speak=<id>|stream=<id>|tx=<id>|voices=<id>", stable across processes. Empty slots render as -; underlying-provider ids are percent-escaped on | and = so the format stays unambiguous.
  • Methods are present only when the corresponding ability is true, so the narrowing guards (canSpeak etc.) work transparently.
  • With no slots set, every ability is false. A method call reached via a bad cast throws VoiceError({ kind: "invalid_input" }).

Parameters​

config​

CompositeVoiceProviderConfig

Returns​

VoiceProvider


createEstimateTokenCounter()​

function createEstimateTokenCounter(lookup?): TokenCounter;

Parameters​

lookup?​

ModelLookupEntry[]

Returns​

TokenCounter


createInMemoryToolCacheStore()​

function createInMemoryToolCacheStore(opts?): ToolCacheStore;

Create a fresh store without going through the capability path.

Parameters​

opts?​
defaultScope?​

"request" | "session" | "run"

defaultTtl?​

number

maxEntries?​

number

Returns​

ToolCacheStore


createManifestRegistry()​

function createManifestRegistry(sources): ManifestRegistry;

Build the registry for one scope from the sources it declares.

Parameters​

sources​

readonly BlockManifestSource[]

Returns​

ManifestRegistry

Throws​

when two sources claim the same domain, naming both sites.


createModelResolver()​

function createModelResolver(options?): ModelResolver;

Creates a unified model resolver that auto-detects providers from env vars and resolves model strings.

Supports:

  • "provider/model" — the provider directly, else a configured gateway (e.g., "openai/gpt-6.1-sol")
  • "name:model" — a named route, pinned: a gateway ("vercel:openai/gpt-6.1-sol") or a provider ("openai:gpt-6.1-sol", "triage:native"). Never falls through.
  • "intent/name" — resolve a configured intent to a fallback model (e.g., "intent/chat")

Any other shape (a three-part slash string, say) throws as an invalid format: at construction for config strings, on first resolve for any other.

Parameters​

options?​

CreateModelResolverOptions

Returns​

ModelResolver


createTiktokenCounter()​

function createTiktokenCounter(tiktoken): TokenCounter;

Parameters​

tiktoken​

TiktokenModule

Returns​

TokenCounter


createToolCacheCapability()​

function createToolCacheCapability(options?): DefinedCapability<string, ToolCacheAccessor, never, Record<string, PresetDef<any>>, undefined, undefined, undefined, undefined, undefined> & object;

Build a tool-cache capability. Each consumer block that installs it (or each board that auto-installs it) gets a request-scoped store exposed on the active context. The substrate's caching path inside compileToolsWithExecute reads through ctx._resolveToolCacheStore — that slot is populated for any block that lists the capability in its uses chain.

Parameters​

options?​

CreateToolCacheCapabilityOptions

Returns​

DefinedCapability<string, ToolCacheAccessor, never, Record<string, PresetDef<any>>, undefined, undefined, undefined, undefined, undefined> & object


defineCapability()​

function defineCapability<TName, TFns, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TPresetKeys, TSessionStateType, TResourcesType, TTargetStatesType, TSequencerStateType, TConfigSchema, TConfigExplicit, TOwnStateSchema, TOwnStateType>(config): DefinedCapability<TName, TFns, TPresetKeys, Record<string, PresetDef>, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema> & object;

Type Parameters​

TName​

TName extends string

TFns​

TFns extends Record<string, (...args) => any> = Record<string, never>

TSessionStateSchema​

TSessionStateSchema extends ZodTypeAny | undefined = undefined

TResources​

TResources extends | Record<string, DeclaredResourceEntry> | undefined = undefined

TTargetSchemas​

TTargetSchemas extends Record<string, ZodTypeAny> | undefined = undefined

TSequencerStateSchema​

TSequencerStateSchema extends ZodTypeAny | undefined = undefined

TPresetKeys​

TPresetKeys extends string = never

TSessionStateType​

TSessionStateType = unknown

TResourcesType​

TResourcesType = unknown

TTargetStatesType​

TTargetStatesType = unknown

TSequencerStateType​

TSequencerStateType = unknown

TConfigSchema​

TConfigSchema extends ZodTypeAny | undefined = undefined

TConfigExplicit​

TConfigExplicit = never

TOwnStateSchema​

TOwnStateSchema extends ZodTypeAny | undefined = undefined

TOwnStateType​

TOwnStateType = unknown

Parameters​

config​

Omit<CapabilityConfig<TName, TFns, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema>, "config"> & object

Returns​

DefinedCapability<TName, TFns, TPresetKeys, Record<string, PresetDef>, TSessionStateSchema, TResources, TTargetSchemas, TSequencerStateSchema, TOwnStateSchema> & object


defineFacetedCollection()​

function defineFacetedCollection<TName, TStateSchema, TEvaluator, TClient>(config): FacetedCollection<TName, AsStateObject<FacetedState<TypeOf<TStateSchema>, FacetsOf<TEvaluator>>>, FacetsOf<TEvaluator>, ProjectedClient<AsStateObject<FacetedState<TypeOf<TStateSchema>, FacetsOf<TEvaluator>>>, TClient>>;

Define a resource collection whose bodies are classified once, on write, by evaluator, storing its answers as facets. Returns the collection, a search over stored answers (optional minConfidence, no model call), a reindex for rows without facets (force for all), and the resources to register on the flow.

Type Parameters​

TName​

TName extends string

TStateSchema​

TStateSchema extends AnyZodObject

TEvaluator​

TEvaluator extends AnyEvaluatorBlock

TClient​

TClient extends | FacetedClientConfig<TStateSchema, TEvaluator> | undefined = undefined

Parameters​

config​

FacetedCollectionConfig<TName, TStateSchema, TEvaluator, TClient>

Returns​

FacetedCollection<TName, AsStateObject<FacetedState<TypeOf<TStateSchema>, FacetsOf<TEvaluator>>>, FacetsOf<TEvaluator>, ProjectedClient<AsStateObject<FacetedState<TypeOf<TStateSchema>, FacetsOf<TEvaluator>>>, TClient>>

Example​

const tickets = defineFacetedCollection({
name: "tickets",
pattern: "tickets/*",
scope: "user",
stateSchema: z.object({ title: z.string() }),
evaluator: triage,
});
defineFlow({
kind: "support",
resources: tickets.resources,
actions: { search: { block: tickets.search }, reindex: { block: tickets.reindex } },
});

defineFlow()​

function defineFlow<TActions, TSession, TRequest, TUser, TOrg, TResources, TConfigSchema>(definition): FlowType<NormalizedActions<TActions>, TSession, TRequest, TUser, TOrg, TResources, TConfigSchema>;

Type Parameters​

TActions​

TActions extends Record<string, ActionEntry>

TSession​

TSession extends SessionConfig | undefined = SessionConfig | undefined

TRequest​

TRequest extends RequestConfig | undefined = RequestConfig | undefined

TUser​

TUser extends UserConfig | undefined = UserConfig | undefined

TOrg​

TOrg extends OrgConfig | undefined = OrgConfig | undefined

TResources​

TResources extends Record<string, DeclaredResourceEntry> = Record<string, DeclaredResourceEntry>

TConfigSchema​

TConfigSchema extends ZodTypeAny | undefined = undefined

Parameters​

definition​

FlowDefinition<TActions, TSession, TRequest, TUser, TOrg, TResources, TConfigSchema>

Returns​

FlowType<NormalizedActions<TActions>, TSession, TRequest, TUser, TOrg, TResources, TConfigSchema>


defineKit()​

function defineKit<Name, ConfigSchema, Slots, Folder>(definition): KitFactory<Name, ConfigSchema, Slots>;

Define a kit. Returns its factory: the app calls it with the kit's config and lists the result in createFlowState({ kits }), in any order.

Throws when the name breaks the naming rule (it is half of every slot key, joined with a .), and, from the factory, when the config fails the kit's schema or names a directory for a kit that owns no folder.

Type Parameters​

Name​

Name extends string

ConfigSchema​

ConfigSchema extends ZodTypeAny | undefined = undefined

Slots​

Slots extends Record<string, SlotDeclaration<unknown>> = { }

Folder​

Folder = undefined

Parameters​

definition​

KitDefinition<Name, ConfigSchema, Slots, Folder>

Returns​

KitFactory<Name, ConfigSchema, Slots>


defineProjectedResourceCollection()​

function defineProjectedResourceCollection<TStateSchema, TConfig>(config): DefinedProjectedResourceCollection<AsStateObject<TConfig["stateSchema"]["_output"]>, TConfig["stateSchema"], ProjectedClient<AsStateObject<TConfig["stateSchema"]["_output"]>, TConfig["client"]>>;

Define a read-only collection whose instances are resolved from an app-owned store. Shares the collection runtime core; read-only and lazy by type.

Type Parameters​

TStateSchema​

TStateSchema extends ZodTypeAny

TConfig​

TConfig extends ProjectedResourceCollectionConfig<TStateSchema> & object

Parameters​

config​

TConfig

Returns​

DefinedProjectedResourceCollection<AsStateObject<TConfig["stateSchema"]["_output"]>, TConfig["stateSchema"], ProjectedClient<AsStateObject<TConfig["stateSchema"]["_output"]>, TConfig["client"]>>


defineResource()​

function defineResource<TStateSchema, TConfig>(config): TConfig & ResourceConfig<JsonObject> & object;

Type Parameters​

TStateSchema​

TStateSchema extends ZodTypeAny

TConfig​

TConfig extends ResourceConfig<AsStateObject<TStateSchema["_output"]>> & object

Parameters​

config​

TConfig

Returns​

TConfig & ResourceConfig<JsonObject> & object


defineResourceCollection()​

function defineResourceCollection<TStateSchema, TConfig>(config): TConfig & ResourceCollectionConfig<JsonObject> & object;

Type Parameters​

TStateSchema​

TStateSchema extends ZodTypeAny

TConfig​

TConfig extends ResourceCollectionConfig<AsStateObject<TStateSchema["_output"]>> & object

Parameters​

config​

TConfig

Returns​

TConfig & ResourceCollectionConfig<JsonObject> & object


defineScheduleBinding()​

function defineScheduleBinding(binding): ScheduleConfig;

Construct a ScheduleConfig — the schedule sibling of defineWebhookBinding. The schedule binding carries the shared ActionCore (handler block plus execution policy) inline alongside the cron mapping. Compile-time convenience only: the runtime is a single passthrough. Use it for inline static entries (schedules.static[id] = defineScheduleBinding({…})) or the value a dynamic resolve() returns.

Parameters​

binding​

ScheduleConfig

Returns​

ScheduleConfig


defineView()​

function defineView<TBlock, TScope>(config): ViewDefinition<TBlock, TScope>;

Declare a view. Refuses, at definition time, a scope that isn't "session", "user" or "org", a missing block, a block with no output schema (its answer would be untyped on the client), and a key that isn't a function.

Type Parameters​

TBlock​

TBlock extends BlockDefinition<ZodTypeAny, ZodTypeAny, any, any>

TScope​

TScope extends ViewScope

Parameters​

config​

ViewConfig<TBlock, TScope>

Returns​

ViewDefinition<TBlock, TScope>

Example​

export const roster = defineView({
scope: "user",
key: (row) => row.id,
block: rosterBlock,
});
defineFlow({ kind: "workforce-roster", views: { roster } });

defineWebhookBinding()​

function defineWebhookBinding<TPayload>(binding): WebhookEventBinding;

Construct a WebhookEventBinding whose handlers receive an event with a typed payload instead of unknown. Place the result directly in a flow's webhooks[provider].on map. Compile-time convenience only — the runtime is a single passthrough. (The cast bridges the function-parameter variance that prevents a typed binding from being assignable directly.)

Type Parameters​

TPayload​

TPayload = unknown

Parameters​

binding​

ActionCore & object

Returns​

WebhookEventBinding


discoveryTools()​

function discoveryTools(registry): object;

Build the discovery door over the sources a scope carries.

Returns one tool:

  • discover({ domain?, detail? }) — with no domain, every domain the scope carries; with one, just that domain. A domain name that is not one of the three returns the known names rather than throwing, so the next call can succeed.

One tool taking a domain, rather than a listWorkers / listSkills family: it keeps the shared shape real in the surface a model sees, and detail turns "how much does an entry say" into a per-call choice. Going from one tool to four later is additive; going from four to one would break prompts.

Parameters​

registry​

ManifestRegistry

Returns​

object

discover​
discover: BlockDefinition<ZodObject<{
detail: ZodDefault<ZodEnum<["thin", "full"]>>;
domain: ZodDefault<ZodNullable<ZodString>>;
}, "strip", ZodTypeAny, {
detail: "thin" | "full";
domain: string | null;
}, {
detail?: "thin" | "full";
domain?: string | null;
}>, ZodObject<{
domains: ZodArray<ZodObject<{
domain: ZodString;
entries: ZodArray<ZodObject<{
contract: ZodOptional<...>;
id: ZodString;
kind: ZodString;
purpose: ZodString;
}, "strip", ZodTypeAny, {
contract?: ... | ...;
id: string;
kind: string;
purpose: string;
}, {
contract?: ... | ...;
id: string;
kind: string;
purpose: string;
}>, "many">;
problem: ZodOptional<ZodString>;
}, "strip", ZodTypeAny, {
domain: string;
entries: object[];
problem?: string;
}, {
domain: string;
entries: object[];
problem?: string;
}>, "many">;
problem: ZodOptional<ZodString>;
}, "strip", ZodTypeAny, {
domains: object[];
problem?: string;
}, {
domains: object[];
problem?: string;
}>, {
detail: "thin" | "full";
domain: string | null;
},
| {
domains: never[];
problem: string;
}
| {
domains: object[];
problem?: undefined;
}>;

dispatcher()​

Call Signature​

function dispatcher<TInputSchema>(config): BlockDefinition<TInputSchema, ZodObject<{
error: ZodOptional<ZodString>;
output: ZodOptional<ZodUnknown>;
requestId: ZodString;
status: ZodEnum<["completed", "failed", "running"]>;
}, "strip", ZodTypeAny, {
error?: string;
output?: unknown;
requestId: string;
status: "completed" | "failed" | "running";
}, {
error?: string;
output?: unknown;
requestId: string;
status: "completed" | "failed" | "running";
}>>;

Build a dispatcher block. See the module header.

The first signature takes an internal dispatcher that declares its inputSchema, ahead of the task one, so the session callbacks (key, state, id) are typed with that schema's input. TypeScript types a callback against the first signature it tries, and a task config's (task: unknown) would otherwise stick.

Type Parameters​
TInputSchema​

TInputSchema extends ZodTypeAny

Parameters​
config​

InternalDispatcherConfig<TInputSchema> & object

Returns​

BlockDefinition<TInputSchema, ZodObject<{ error: ZodOptional<ZodString>; output: ZodOptional<ZodUnknown>; requestId: ZodString; status: ZodEnum<["completed", "failed", "running"]>; }, "strip", ZodTypeAny, { error?: string; output?: unknown; requestId: string; status: "completed" | "failed" | "running"; }, { error?: string; output?: unknown; requestId: string; status: "completed" | "failed" | "running"; }>>

Call Signature​

function dispatcher<TInputSchema>(config): BlockDefinition<TInputSchema, ZodObject<{
adopted: ZodBoolean;
requestId: ZodString;
sessionId: ZodString;
}, "strip", ZodTypeAny, {
adopted: boolean;
requestId: string;
sessionId: string;
}, {
adopted: boolean;
requestId: string;
sessionId: string;
}>>;

Build a dispatcher block. See the module header.

The first signature takes an internal dispatcher that declares its inputSchema, ahead of the task one, so the session callbacks (key, state, id) are typed with that schema's input. TypeScript types a callback against the first signature it tries, and a task config's (task: unknown) would otherwise stick.

Type Parameters​
TInputSchema​

TInputSchema extends ZodTypeAny

Parameters​
config​

InternalDispatcherConfig<TInputSchema> & object

Returns​

BlockDefinition<TInputSchema, ZodObject<{ adopted: ZodBoolean; requestId: ZodString; sessionId: ZodString; }, "strip", ZodTypeAny, { adopted: boolean; requestId: string; sessionId: string; }, { adopted: boolean; requestId: string; sessionId: string; }>>

Call Signature​

function dispatcher<TPayload>(config): BlockDefinition<ZodObject<{
assignee: ZodString;
attempt: ZodNumber;
boardId: ZodString;
createdAt: ZodNumber;
incarnationId: ZodOptional<ZodString>;
partition: ZodOptional<ZodString>;
payload: ZodUnknown;
taskId: ZodString;
turn: ZodOptional<ZodNumber>;
}, "strip", ZodTypeAny, {
assignee: string;
attempt: number;
boardId: string;
createdAt: number;
incarnationId?: string;
partition?: string;
payload?: unknown;
taskId: string;
turn?: number;
}, {
assignee: string;
attempt: number;
boardId: string;
createdAt: number;
incarnationId?: string;
partition?: string;
payload?: unknown;
taskId: string;
turn?: number;
}>, ZodObject<{
adopted: ZodBoolean;
requestId: ZodString;
sessionId: ZodString;
}, "strip", ZodTypeAny, {
adopted: boolean;
requestId: string;
sessionId: string;
}, {
adopted: boolean;
requestId: string;
sessionId: string;
}>>;

Build a dispatcher block. See the module header.

The first signature takes an internal dispatcher that declares its inputSchema, ahead of the task one, so the session callbacks (key, state, id) are typed with that schema's input. TypeScript types a callback against the first signature it tries, and a task config's (task: unknown) would otherwise stick.

Type Parameters​
TPayload​

TPayload = unknown

Parameters​
config​

TaskDispatcherConfig<TPayload>

Returns​

BlockDefinition<ZodObject<{ assignee: ZodString; attempt: ZodNumber; boardId: ZodString; createdAt: ZodNumber; incarnationId: ZodOptional<ZodString>; partition: ZodOptional<ZodString>; payload: ZodUnknown; taskId: ZodString; turn: ZodOptional<ZodNumber>; }, "strip", ZodTypeAny, { assignee: string; attempt: number; boardId: string; createdAt: number; incarnationId?: string; partition?: string; payload?: unknown; taskId: string; turn?: number; }, { assignee: string; attempt: number; boardId: string; createdAt: number; incarnationId?: string; partition?: string; payload?: unknown; taskId: string; turn?: number; }>, ZodObject<{ adopted: ZodBoolean; requestId: ZodString; sessionId: ZodString; }, "strip", ZodTypeAny, { adopted: boolean; requestId: string; sessionId: string; }, { adopted: boolean; requestId: string; sessionId: string; }>>

Call Signature​

function dispatcher<TInputSchema>(config): BlockDefinition<TInputSchema, ZodObject<{
error: ZodOptional<ZodString>;
output: ZodOptional<ZodUnknown>;
requestId: ZodString;
status: ZodEnum<["completed", "failed", "running"]>;
}, "strip", ZodTypeAny, {
error?: string;
output?: unknown;
requestId: string;
status: "completed" | "failed" | "running";
}, {
error?: string;
output?: unknown;
requestId: string;
status: "completed" | "failed" | "running";
}>>;

Build a dispatcher block. See the module header.

The first signature takes an internal dispatcher that declares its inputSchema, ahead of the task one, so the session callbacks (key, state, id) are typed with that schema's input. TypeScript types a callback against the first signature it tries, and a task config's (task: unknown) would otherwise stick.

Type Parameters​
TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

Parameters​
config​

InternalDispatcherConfig<TInputSchema> & object

Returns​

BlockDefinition<TInputSchema, ZodObject<{ error: ZodOptional<ZodString>; output: ZodOptional<ZodUnknown>; requestId: ZodString; status: ZodEnum<["completed", "failed", "running"]>; }, "strip", ZodTypeAny, { error?: string; output?: unknown; requestId: string; status: "completed" | "failed" | "running"; }, { error?: string; output?: unknown; requestId: string; status: "completed" | "failed" | "running"; }>>

Call Signature​

function dispatcher<TInputSchema>(config): BlockDefinition<TInputSchema, ZodObject<{
adopted: ZodBoolean;
requestId: ZodString;
sessionId: ZodString;
}, "strip", ZodTypeAny, {
adopted: boolean;
requestId: string;
sessionId: string;
}, {
adopted: boolean;
requestId: string;
sessionId: string;
}>>;

Build a dispatcher block. See the module header.

The first signature takes an internal dispatcher that declares its inputSchema, ahead of the task one, so the session callbacks (key, state, id) are typed with that schema's input. TypeScript types a callback against the first signature it tries, and a task config's (task: unknown) would otherwise stick.

Type Parameters​
TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

Parameters​
config​

InternalDispatcherConfig<TInputSchema>

Returns​

BlockDefinition<TInputSchema, ZodObject<{ adopted: ZodBoolean; requestId: ZodString; sessionId: ZodString; }, "strip", ZodTypeAny, { adopted: boolean; requestId: string; sessionId: string; }, { adopted: boolean; requestId: string; sessionId: string; }>>


evaluator()​

function evaluator<TInputSchema, TInput, TQuestions, TRequestStateSchema, TSessionStateSchema, TUserStateSchema, TOrgStateSchema, TSequencerStateSchema, TParentInputSchema, TResourceDefs, TTargetSchemas, TUses, TRequestState, TSessionState, TUserState, TOrgState, TSequencerState, TParentInput, TResources, TMergedTargetSchemas, TCapabilities, TStateSchema, TParentStateSchema, TSelfState, TParentState, TFlowConfigSchema, TFlowConfig>(config): EvaluatorDefinition<TInputSchema, TInput, TQuestions>;

Build an evaluator block: it asks an evaluation model typed questions about one state and returns { answers }, one answer per question id, typed by its question. An answer carries confidence only when the model reported one.

One provider call per run. No retry, no fallback, no gating: branch on the answers in a router or a sequencer step. A failed call fails the block like any other; .rescue in a sequencer recovers with a substitute block.

Type Parameters​

TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

TInput​

TInput = TypeOf<TInputSchema>

TQuestions​

TQuestions extends EvaluatorQuestions = EvaluatorQuestions

TRequestStateSchema​

TRequestStateSchema extends ZodTypeAny | undefined = undefined

TSessionStateSchema​

TSessionStateSchema extends ZodTypeAny | undefined = undefined

TUserStateSchema​

TUserStateSchema extends ZodTypeAny | undefined = undefined

TOrgStateSchema​

TOrgStateSchema extends ZodTypeAny | undefined = undefined

TSequencerStateSchema​

TSequencerStateSchema extends ZodTypeAny | undefined = undefined

TParentInputSchema​

TParentInputSchema extends ZodTypeAny | undefined = undefined

TResourceDefs​

TResourceDefs extends | Record<string, DeclaredResourceEntry> | undefined = undefined

TTargetSchemas​

TTargetSchemas extends Record<string, ZodTypeAny> | undefined = undefined

TUses​

TUses extends readonly UsesEntry[] = readonly []

TRequestState​

TRequestState extends object = InferStateFromSchema<TRequestStateSchema>

TSessionState​

TSessionState extends object = { [K in string | number | symbol]: (InferStateFromSchema<TSessionStateSchema> & InferCapabilitySessionState<TUses>)[K] }

TUserState​

TUserState extends object = InferStateFromSchema<TUserStateSchema>

TOrgState​

TOrgState extends object = InferStateFromSchema<TOrgStateSchema>

TSequencerState​

TSequencerState extends object = { [K in string | number | symbol]: (InferStateFromSchema<TSequencerStateSchema> & InferCapabilitySequencerState<TUses>)[K] }

TParentInput​

TParentInput = TParentInputSchema extends ZodTypeAny ? TypeOf<TParentInputSchema> : unknown

TResources​

TResources extends Record<string, AnyResourceRef> = { [K in string | number | symbol]: (InferBlockResources<undefined, TResourceDefs> & InferCapabilityResources<TUses>)[K] }

TMergedTargetSchemas​

TMergedTargetSchemas extends Record<string, ZodTypeAny> | undefined = MergeTargetSchemas<TTargetSchemas, TUses>

TCapabilities​

TCapabilities extends Record<string, Record<string, (...args) => any>> = InferCapabilities<TUses>

TStateSchema​

TStateSchema extends ZodTypeAny | undefined = undefined

TParentStateSchema​

TParentStateSchema extends ZodTypeAny | undefined = undefined

TSelfState​

TSelfState extends object = { [K in string | number | symbol]: (InferStateFromSchema<TStateSchema> & InferCapabilityOwnState<TUses>)[K] }

TParentState​

TParentState extends object = InferStateFromSchema<TParentStateSchema>

TFlowConfigSchema​

TFlowConfigSchema extends ZodTypeAny | undefined = undefined

TFlowConfig​

TFlowConfig extends object = InferFlowConfigFromSchema<TFlowConfigSchema>

Parameters​

config​

EvaluatorConfig<TInputSchema, TInput, TQuestions, TRequestStateSchema, TSessionStateSchema, TUserStateSchema, TOrgStateSchema, TSequencerStateSchema, TParentInputSchema, TResourceDefs, TTargetSchemas, TUses, TRequestState, TSessionState, TUserState, TOrgState, TSequencerState, TParentInput, TResources, TMergedTargetSchemas, TCapabilities, TStateSchema, TParentStateSchema, TSelfState, TParentState, TFlowConfigSchema, TFlowConfig>

Returns​

EvaluatorDefinition<TInputSchema, TInput, TQuestions>

Example​

const triage = evaluator({
name: "triage",
model: "typesafe-ai/jev",
state: (input: { message: string }) => input.message,
questions: {
team: choice("Which team should handle this?", {
billing: "Payments and refunds",
technical: "Bugs and outages",
}),
urgent: boolean("Does this need someone now?"),
},
});

findModelEntry()​

function findModelEntry(model, lookup?): ModelLookupEntry | undefined;

Parameters​

model​

string

lookup?​

ModelLookupEntry[]

Returns​

ModelLookupEntry | undefined


firstInProcess()​

function firstInProcess(key): boolean;

true the first time key is claimed in this process, false every time after. Survives module re-evaluation, so a boot diagnostic guarded by it prints once per server start rather than once per hot reload.

Unlike warnOnceDev, this is NOT dev-only and does NOT honour FSD_QUIET_WARNINGS: it only answers "first time?", and the caller decides what to print and when.

Namespace the key by package ("workforce/...", "engine/..."): every caller in the process shares one set.

Parameters​

key​

string

Returns​

boolean


formatScheduleId()​

function formatScheduleId(
orgId,
userId,
key
): string;

The dispatch id of a dynamic schedule: <orgId>/<userId>/<key>, each part URL-encoded so an org or user id containing / round-trips. The engine's schedule tick dispatches by it, and @flow-state-dev/scheduled's defaultParseScheduleId reads it back.

Put it on a dispatch URL as one more encoded path segment, since the router decodes each segment once: /api/flows/<kind>/schedules/${encodeURIComponent(formatScheduleId(...))}/dispatch.

Parameters​

orgId​

string

userId​

string

key​

string

Returns​

string


generator()​

function generator<TInputSchema, TOutputSchema, TInput, TOutput, TRequestStateSchema, TSessionStateSchema, TUserStateSchema, TOrgStateSchema, TSequencerStateSchema, TResourceDefs, TTargetSchemas, TUses, TRequestState, TSessionState, TUserState, TOrgState, TSequencerState, TResources, TMergedTargetSchemas, TCapabilities, TStateSchema, TParentStateSchema, TSelfState, TParentState, TFlowConfigSchema, TFlowConfig, TCtx>(config): BlockDefinition<TInputSchema, TOutputSchema, TInput, TOutput>;

Type Parameters​

TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

TOutputSchema​

TOutputSchema extends ZodTypeAny = ZodTypeAny

TInput​

TInput = TypeOf<TInputSchema>

TOutput​

TOutput = TypeOf<TOutputSchema>

TRequestStateSchema​

TRequestStateSchema extends ZodTypeAny | undefined = undefined

TSessionStateSchema​

TSessionStateSchema extends ZodTypeAny | undefined = undefined

TUserStateSchema​

TUserStateSchema extends ZodTypeAny | undefined = undefined

TOrgStateSchema​

TOrgStateSchema extends ZodTypeAny | undefined = undefined

TSequencerStateSchema​

TSequencerStateSchema extends ZodTypeAny | undefined = undefined

TResourceDefs​

TResourceDefs extends | Record<string, DeclaredResourceEntry> | undefined = undefined

TTargetSchemas​

TTargetSchemas extends Record<string, ZodTypeAny> | undefined = undefined

TUses​

TUses extends readonly UsesEntry[] = readonly []

TRequestState​

TRequestState extends object = InferStateFromSchema<TRequestStateSchema>

TSessionState​

TSessionState extends object = { [K in string | number | symbol]: (InferStateFromSchema<TSessionStateSchema> & InferCapabilitySessionState<TUses>)[K] }

TUserState​

TUserState extends object = InferStateFromSchema<TUserStateSchema>

TOrgState​

TOrgState extends object = InferStateFromSchema<TOrgStateSchema>

TSequencerState​

TSequencerState extends object = { [K in string | number | symbol]: (InferStateFromSchema<TSequencerStateSchema> & InferCapabilitySequencerState<TUses>)[K] }

TResources​

TResources extends Record<string, AnyResourceRef> = { [K in string | number | symbol]: (InferBlockResources<undefined, TResourceDefs> & InferCapabilityResources<TUses>)[K] }

TMergedTargetSchemas​

TMergedTargetSchemas extends Record<string, ZodTypeAny> | undefined = MergeTargetSchemas<TTargetSchemas, TUses>

TCapabilities​

TCapabilities extends Record<string, Record<string, (...args) => any>> = InferCapabilities<TUses>

TStateSchema​

TStateSchema extends ZodTypeAny | undefined = undefined

TParentStateSchema​

TParentStateSchema extends ZodTypeAny | undefined = undefined

TSelfState​

TSelfState extends object = { [K in string | number | symbol]: (InferStateFromSchema<TStateSchema> & InferCapabilityOwnState<TUses>)[K] }

TParentState​

TParentState extends object = InferStateFromSchema<TParentStateSchema>

TFlowConfigSchema​

TFlowConfigSchema extends ZodTypeAny | undefined = undefined

TFlowConfig​

TFlowConfig extends object = InferFlowConfigFromSchema<TFlowConfigSchema>

TCtx​

TCtx = BlockContext<TRequestState, TSessionState, TUserState, TOrgState, TResources, TSequencerState, unknown, TMergedTargetSchemas, TCapabilities, TSelfState, TParentState, TFlowConfig>

Parameters​

config​

GeneratorConfig<TInputSchema, TOutputSchema, TInput, TOutput, TRequestStateSchema, TSessionStateSchema, TUserStateSchema, TOrgStateSchema, TSequencerStateSchema, TResourceDefs, TTargetSchemas, TUses, TRequestState, TSessionState, TUserState, TOrgState, TSequencerState, TResources, TMergedTargetSchemas, TCapabilities, TStateSchema, TParentStateSchema, TSelfState, TParentState, TFlowConfigSchema, TFlowConfig, TCtx>

Returns​

BlockDefinition<TInputSchema, TOutputSchema, TInput, TOutput>


isAbortLike()​

function isAbortLike(err): boolean;

True if the root error in the cause chain looks like an AbortError — by name, DOMException code, or Node's ABORT_ERR code. Calls rootCause first, so a wrapper that loses e.name is transparent as long as the innermost cause is the abort. An AbortError that is not at the root of the chain is not detected.

Parameters​

err​

unknown

Returns​

boolean


isDefinedResourceCollection()​

function isDefinedResourceCollection(value): value is DefinedResourceCollection<JsonObject, JsonValue>;

Parameters​

value​

unknown

Returns​

value is DefinedResourceCollection<JsonObject, JsonValue>


isValidOrgId()​

function isValidOrgId(value): value is string;

Whether value is usable as an organization id.

Organization ids are opaque strings: not empty, not whitespace-only, and well-formed Unicode (see below). A whitespace-only id is rejected rather than trimmed, and a valid id is never rewritten — the framework stores exactly what the trusted source supplied, so a stored id and the identity that produced it compare equal.

An id holding a lone UTF-16 surrogate is refused too: it has no UTF-8 form, so anything that encodes the id (a storage key, an address) would map it onto U+FFFD and give two distinct ids one encoding.

The one definition both the host's principal normalization and trusted direct execution validate against, so the two cannot drift.

Parameters​

value​

unknown

Returns​

value is string


lifecycleSchema()​

function lifecycleSchema<S>(statuses): object;

Returns { status, startedAt, completedAt, errorMessage } to spread into a resource stateSchema. status is a required enum over the caller's statuses; the timestamp/error fields are nullable ISO-string slots defaulting to null.

Type Parameters​

S​

S extends readonly [string, string]

Parameters​

statuses​

S

Returns​

object

completedAt​
completedAt: ZodDefault<ZodNullable<ZodString>>;
errorMessage​
errorMessage: ZodDefault<ZodNullable<ZodString>>;
startedAt​
startedAt: ZodDefault<ZodNullable<ZodString>>;
status​
status: ZodEnum<Writeable<S>>;

Example​

stateSchema: z.object({
...lifecycleSchema(["pending", "writing", "published"]),
title: z.string(),
})

makeSchemaStrict()​

function makeSchemaStrict(schema, options?): ZodTypeAny;

Parameters​

schema​

ZodTypeAny

options?​

MakeSchemaStrictOptions

Returns​

ZodTypeAny


mapLimit()​

function mapLimit<TInput, TOutput>(
values,
maxConcurrency,
mapper
): Promise<TOutput[]>;

Run mapper over values with at most maxConcurrency calls in flight at once, preserving input order in the result.

maxConcurrency of undefined (or any value ≥ values.length) runs every item concurrently; values below 1 are clamped to 1. An empty input resolves to [] without invoking mapper. The first rejecting mapper call rejects the returned promise; any mapper calls already in flight on other workers run to completion (their results and errors are dropped), so callers using this for side-effecting work should not assume those operations were cancelled.

Type Parameters​

TInput​

TInput

TOutput​

TOutput

Parameters​

values​

readonly TInput[]

maxConcurrency​

number | undefined

mapper​

(value, index) => Promise<TOutput>

Returns​

Promise<TOutput[]>


markDispatcher()​

function markDispatcher<TBlock>(block, address): TBlock;

Stamp a block with the address it dispatches to, so defineFlow can verify the target resolves and a board can see the dispatch statically.

Assigns in place: the caller owns the block it just built, and every rebuild path (connectInput, .rescue(), asTool) forwards definition.dispatch.

Type Parameters​

TBlock​

TBlock extends object

Parameters​

block​

TBlock

address​

DispatchAddress

Returns​

TBlock


modelPricingEstimator()​

function modelPricingEstimator(lookup?): CostEstimator;

Parameters​

lookup?​

ModelLookupEntry[]

Returns​

CostEstimator


ownerSegment()​

function ownerSegment(userId): string;

The key segment that marks a row as userId's: ~ plus encodeUserSegment.

An owner-keyed collection (ownerPrivate: { param } or ownerWrites: { param }) keys each row with this at its owner parameter: an owner-private one serves the row only to that user, an owner-writes one lets only that user write it. A key's first segment beginning ~ is its owner in every app, so no other collection reads or writes a key carrying one. The escaped id holds no ~ and no /, so the segment is one segment with one marker.

Parameters​

userId​

string

Returns​

string


providerTool()​

function providerTool(name, tool): ProviderTool;

Wraps a Vercel AI SDK provider-defined tool for use in a generator's providerTools array. The tool is passed through to the AI SDK without compilation — the provider executes it server-side.

Parameters​

name​

string

tool​

unknown

Returns​

ProviderTool

Example​

import { anthropic } from '@ai-sdk/anthropic';
import { providerTool } from '@flow-state-dev/core';

generator({
providerTools: [
providerTool('webSearch', anthropic.tools.webSearch_20250305({ maxUses: 3 }))
],
})

readResourceContentTool()​

function readResourceContentTool(): BlockDefinition<ZodObject<{
uri: ZodOptional<ZodString>;
}, "strip", ZodTypeAny, {
uri?: string;
}, {
uri?: string;
}>, ZodObject<{
content: ZodOptional<ZodNullable<ZodString>>;
uri: ZodOptional<ZodString>;
uris: ZodOptional<ZodArray<ZodString, "many">>;
}, "strip", ZodTypeAny, {
content?: string | null;
uri?: string;
uris?: string[];
}, {
content?: string | null;
uri?: string;
uris?: string[];
}>, {
uri?: string;
},
| {
content?: undefined;
uri?: undefined;
uris: string[];
}
| {
content: string | null;
uri: string;
uris?: undefined;
}>;

Tool block for reading rendered resource content, keyed by scope-qualified uri.

Input uri is optional:

  • omitted: returns the uris of every readable resource (static + collection instance)
  • provided: returns rendered content for that uri

Returns​

BlockDefinition<ZodObject<{ uri: ZodOptional<ZodString>; }, "strip", ZodTypeAny, { uri?: string; }, { uri?: string; }>, ZodObject<{ content: ZodOptional<ZodNullable<ZodString>>; uri: ZodOptional<ZodString>; uris: ZodOptional<ZodArray<ZodString, "many">>; }, "strip", ZodTypeAny, { content?: string | null; uri?: string; uris?: string[]; }, { content?: string | null; uri?: string; uris?: string[]; }>, { uri?: string; }, | { content?: undefined; uri?: undefined; uris: string[]; } | { content: string | null; uri: string; uris?: undefined; }>


resolveEntry()​

function resolveEntry<TEntry>(
flow,
type,
name,
coordinate?
): TEntry | undefined;

Resolve the entry a dispatch is addressed to, or undefined when its type's map declares none. Never consults another type's map.

Type Parameters​

TEntry​

TEntry

Parameters​

flow​

EntryMaps<TEntry>

type​

DispatchType

name​

string

coordinate?​

EntryCoordinate

Returns​

TEntry | undefined


resolveResourceByPath()​

function resolveResourceByPath(path, ctx): Promise<ResourceRef<any> | undefined>;

Unified path lookup spanning single resources and collection instances. Tries single resources by ResourceRef.path, then collections via the same matcher as the CRUD tools (matchCollectionKey, + nsRef.get(key)). Returns a ResourceRef (collection instances are themselves ResourceRefs, so readContent() is uniform). Returns undefined on a miss.

Parameters​

path​

string

ctx​

BlockContext

Returns​

Promise<ResourceRef<any> | undefined>


resolveResourceByUri()​

function resolveResourceByUri(uri, ctx): Promise<ResourceRef<any> | undefined>;

Resolve a scope-qualified resource uri (${scope}/${path}) to its ResourceRef — static resource or collection instance, uniformly. Unlike resolveResourceByPath, the uri is unique across scopes, so resolution is unambiguous even when two collections share a pattern in different scopes. Resolves the target directly — statics by uri, then a single getOptional on the one collection whose scope+pattern matches — so reading one resource never lists (and so never bulk-loads) unrelated collections. Returns undefined on a miss.

Parameters​

uri​

string

ctx​

BlockContext

Returns​

Promise<ResourceRef<any> | undefined>


resolveTaskFlowKind()​

function resolveTaskFlowKind(
blockName,
address,
task,
ctx
): Promise<string | undefined>;

The flow a task dispatch goes to: the address's string as declared, or its per-task target's answer for this task. undefined is same-flow for a string-less address.

Parameters​

blockName​

string

address​
action​

string | TaskEntryChoice

The entry name — flow.task.actions[action] — or a choice among declared entry names, made per row (see TaskEntryChoice).

flowKind?​

string | TaskFlowTarget

The flow the entry lives on, when it is not this one. Same skip as an internal cross-flow address: defineFlow cannot see the other flow's map, so the seam resolves it. A function is looked up per task (see TaskFlowTarget) and is always cross-flow.

session​

TaskSessionPolicy<any>

state?​

| Readonly<Record<string, unknown>> | TaskStateTarget

The initial state each task's child session is created with: a fixed object, or looked up per task (see TaskStateTarget). A child that already exists keeps its own.

type​

"task"

wait?​

boolean

Whether the board's drain waits on a row it hands over. Absent follows the board's mode: a plan board waits, a delegation board doesn't. A board refuses one that contradicts its mode.

task​

TaskTargetQuery

ctx​

BlockContext

Returns​

Promise<string | undefined>

Throws​

flow-not-found, naming the assignee, when a per-task target answers nothing or an empty id. Decided before anything is dispatched, like every refusal.


resolveTaskState()​

function resolveTaskState(
blockName,
address,
task,
ctx
): Promise<Readonly<Record<string, unknown>> | undefined>;

The initial state a task dispatch creates its child session with: the address's object as declared, or its per-task target's answer for this task. undefined when the address declares none.

Parameters​

blockName​

string

address​
action​

string | TaskEntryChoice

The entry name — flow.task.actions[action] — or a choice among declared entry names, made per row (see TaskEntryChoice).

flowKind?​

string | TaskFlowTarget

The flow the entry lives on, when it is not this one. Same skip as an internal cross-flow address: defineFlow cannot see the other flow's map, so the seam resolves it. A function is looked up per task (see TaskFlowTarget) and is always cross-flow.

session​

TaskSessionPolicy<any>

state?​

| Readonly<Record<string, unknown>> | TaskStateTarget

The initial state each task's child session is created with: a fixed object, or looked up per task (see TaskStateTarget). A child that already exists keeps its own.

type​

"task"

wait?​

boolean

Whether the board's drain waits on a row it hands over. Absent follows the board's mode: a plan board waits, a delegation board doesn't. A board refuses one that contradicts its mode.

task​

TaskTargetQuery

ctx​

BlockContext

Returns​

Promise<Readonly<Record<string, unknown>> | undefined>

Throws​

when the answer is not a plain object.


resourceChangeSchema()​

function resourceChangeSchema(stateSchema): ZodType<ResourceChange<JsonObject>>;

Build a Zod schema matching ResourceChange<TState>, suitable as a reactive block's inputSchema. stateSchema is the resource's own state schema; state/prevState are its nullable form.

This is an INPUT schema — the OpenAI strict-output rules (which only apply to generator OUTPUT schemas) do not apply, so the schema is returned as-is without makeSchemaStrict.

Parameters​

stateSchema​

ZodTypeAny

Returns​

ZodType<ResourceChange<JsonObject>>


resourceContentChangeSchema()​

function resourceContentChangeSchema(): ZodType<ResourceContentChange>;

Build a Zod schema matching ResourceContentChange, suitable as a reactTo.contentUpdated block's inputSchema. Takes no state schema — a content change carries only identity. An INPUT schema, so the strict-output rules do not apply.

Returns​

ZodType<ResourceContentChange>


resourceSearchTools()​

function resourceSearchTools(): object;

Resource navigation tool blocks for the LLM tool surface — the Glob/Grep/Search trio over resources. Returns handler blocks that work across all registered static resources and collections:

  • globResources({ pattern?, limit? }) — match the within-scope path against a glob (concepts/**, **/react*); a null pattern lists every READABLE resource. No content is read, but the llmReadable gate applies. Subsumes prefix-listing.
  • grepResourceContent({ pattern, prefix?, maxResults? }) — regex / substring search over llmReadable content bodies, returning matching lines.
  • searchResources({ query, prefix?, limit? }) — term-frequency ranked search over llmReadable content bodies (lexical, not semantic).

All three return the scope-qualified uri of each match — the unique handle the content tools accept.

Returns​

object

globResources​
globResources: BlockDefinition<ZodObject<{
limit: ZodDefault<ZodNumber>;
pattern: ZodDefault<ZodNullable<ZodString>>;
}, "strip", ZodTypeAny, {
limit: number;
pattern: string | null;
}, {
limit?: number;
pattern?: string | null;
}>, ZodObject<{
uris: ZodArray<ZodString, "many">;
}, "strip", ZodTypeAny, {
uris: string[];
}, {
uris: string[];
}>, {
limit: number;
pattern: string | null;
}, {
uris: string[];
}>;
grepResourceContent​
grepResourceContent: BlockDefinition<ZodObject<{
maxResults: ZodDefault<ZodNumber>;
pattern: ZodString;
prefix: ZodDefault<ZodNullable<ZodString>>;
}, "strip", ZodTypeAny, {
maxResults: number;
pattern: string;
prefix: string | null;
}, {
maxResults?: number;
pattern: string;
prefix?: string | null;
}>, ZodObject<{
matches: ZodArray<ZodObject<{
line: ZodNumber;
snippet: ZodString;
uri: ZodString;
}, "strip", ZodTypeAny, {
line: number;
snippet: string;
uri: string;
}, {
line: number;
snippet: string;
uri: string;
}>, "many">;
}, "strip", ZodTypeAny, {
matches: object[];
}, {
matches: object[];
}>, {
maxResults: number;
pattern: string;
prefix: string | null;
}, {
matches: object[];
}>;
searchResources​
searchResources: BlockDefinition<ZodObject<{
cursor: ZodDefault<ZodNullable<ZodString>>;
limit: ZodDefault<ZodNumber>;
prefix: ZodDefault<ZodNullable<ZodString>>;
query: ZodString;
}, "strip", ZodTypeAny, {
cursor: string | null;
limit: number;
prefix: string | null;
query: string;
}, {
cursor?: string | null;
limit?: number;
prefix?: string | null;
query: string;
}>, ZodObject<{
nextCursor: ZodOptional<ZodString>;
results: ZodArray<ZodObject<{
score: ZodNumber;
snippet: ZodString;
uri: ZodString;
}, "strip", ZodTypeAny, {
score: number;
snippet: string;
uri: string;
}, {
score: number;
snippet: string;
uri: string;
}>, "many">;
}, "strip", ZodTypeAny, {
nextCursor?: string;
results: object[];
}, {
nextCursor?: string;
results: object[];
}>, {
cursor: string | null;
limit: number;
prefix: string | null;
query: string;
},
| {
nextCursor?: undefined;
results: object[];
}
| {
nextCursor: string;
results: object[];
}>;

resourcesManifestSource()​

function resourcesManifestSource(): BlockManifestSource;

The resources domain, projected on demand from collectReadableResources plus the readable projected collections that helper does not reach.

Returns​

BlockManifestSource


resourceTools()​

function resourceTools(): object;

Generic resource CRUD tool blocks for LLM tool surface. Returns handler blocks that work across all registered collections.

Provides 4 tools, each acting on a path the caller already names:

  • createResource({ path, state? }) — Create a new resource instance
  • readResource({ path }) — Read a resource instance, in a collection that opted in with llmReadable, without the fields its secret names
  • updateResource({ path, state? }) — Update a resource instance
  • deleteResource({ path }) — Delete a resource instance

listResources was removed. It enumerated every collection's full stored state through collectCollections, ignoring the llmReadable gate this module defines two functions below — so a collection nobody marked readable was dumped to the model anyway. Enumeration is now the discovery door's job (discoveryTools), which answers from collectReadableResources and returns a planning contract rather than raw state.

Returns​

object

createResource​
createResource: BlockDefinition<ZodObject<{
path: ZodString;
state: ZodOptional<ZodRecord<ZodString, ZodUnknown>>;
}, "strip", ZodTypeAny, {
path: string;
state?: Record<string, unknown>;
}, {
path: string;
state?: Record<string, unknown>;
}>, ZodObject<{
ok: ZodLiteral<true>;
path: ZodString;
}, "strip", ZodTypeAny, {
ok: true;
path: string;
}, {
ok: true;
path: string;
}>, {
path: string;
state?: Record<string, unknown>;
}, {
ok: true;
path: string;
}>;
deleteResource​
deleteResource: BlockDefinition<ZodObject<{
path: ZodString;
}, "strip", ZodTypeAny, {
path: string;
}, {
path: string;
}>, ZodObject<{
ok: ZodLiteral<true>;
path: ZodString;
}, "strip", ZodTypeAny, {
ok: true;
path: string;
}, {
ok: true;
path: string;
}>, {
path: string;
}, {
ok: true;
path: string;
}>;
readResource​
readResource: BlockDefinition<ZodObject<{
path: ZodString;
}, "strip", ZodTypeAny, {
path: string;
}, {
path: string;
}>, ZodObject<{
path: ZodString;
state: ZodRecord<ZodString, ZodUnknown>;
}, "strip", ZodTypeAny, {
path: string;
state: Record<string, unknown>;
}, {
path: string;
state: Record<string, unknown>;
}>, {
path: string;
}, {
path: string;
state: JsonObject;
}>;
updateResource​
updateResource: BlockDefinition<ZodObject<{
path: ZodString;
state: ZodRecord<ZodString, ZodUnknown>;
}, "strip", ZodTypeAny, {
path: string;
state: Record<string, unknown>;
}, {
path: string;
state: Record<string, unknown>;
}>, ZodObject<{
ok: ZodLiteral<true>;
path: ZodString;
}, "strip", ZodTypeAny, {
ok: true;
path: string;
}, {
ok: true;
path: string;
}>, {
path: string;
state: Record<string, unknown>;
}, {
ok: true;
path: string;
}>;

router()​

function router<TInputSchema, TOutputSchema, TInput, TOutput, TRequestStateSchema, TSessionStateSchema, TUserStateSchema, TOrgStateSchema, TSequencerStateSchema, TResourceDefs, TTargetSchemas, TUses, TRequestState, TSessionState, TUserState, TOrgState, TSequencerState, TResources, TMergedTargetSchemas, TCapabilities, TStateSchema, TParentStateSchema, TSelfState, TParentState, TFlowConfigSchema, TFlowConfig>(config): BlockDefinition<TInputSchema, TOutputSchema, TInput, TOutput>;

Type Parameters​

TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

TOutputSchema​

TOutputSchema extends ZodTypeAny = ZodTypeAny

TInput​

TInput = TypeOf<TInputSchema>

TOutput​

TOutput = TypeOf<TOutputSchema>

TRequestStateSchema​

TRequestStateSchema extends ZodTypeAny | undefined = undefined

TSessionStateSchema​

TSessionStateSchema extends ZodTypeAny | undefined = undefined

TUserStateSchema​

TUserStateSchema extends ZodTypeAny | undefined = undefined

TOrgStateSchema​

TOrgStateSchema extends ZodTypeAny | undefined = undefined

TSequencerStateSchema​

TSequencerStateSchema extends ZodTypeAny | undefined = undefined

TResourceDefs​

TResourceDefs extends | Record<string, DeclaredResourceEntry> | undefined = undefined

TTargetSchemas​

TTargetSchemas extends Record<string, ZodTypeAny> | undefined = undefined

TUses​

TUses extends readonly UsesEntry[] = readonly []

TRequestState​

TRequestState extends object = InferStateFromSchema<TRequestStateSchema>

TSessionState​

TSessionState extends object = { [K in string | number | symbol]: (InferStateFromSchema<TSessionStateSchema> & InferCapabilitySessionState<TUses>)[K] }

TUserState​

TUserState extends object = InferStateFromSchema<TUserStateSchema>

TOrgState​

TOrgState extends object = InferStateFromSchema<TOrgStateSchema>

TSequencerState​

TSequencerState extends object = { [K in string | number | symbol]: (InferStateFromSchema<TSequencerStateSchema> & InferCapabilitySequencerState<TUses>)[K] }

TResources​

TResources extends Record<string, AnyResourceRef> = { [K in string | number | symbol]: (InferBlockResources<undefined, TResourceDefs> & InferCapabilityResources<TUses>)[K] }

TMergedTargetSchemas​

TMergedTargetSchemas extends Record<string, ZodTypeAny> | undefined = MergeTargetSchemas<TTargetSchemas, TUses>

TCapabilities​

TCapabilities extends Record<string, Record<string, (...args) => any>> = InferCapabilities<TUses>

TStateSchema​

TStateSchema extends ZodTypeAny | undefined = undefined

TParentStateSchema​

TParentStateSchema extends ZodTypeAny | undefined = undefined

TSelfState​

TSelfState extends object = { [K in string | number | symbol]: (InferStateFromSchema<TStateSchema> & InferCapabilityOwnState<TUses>)[K] }

TParentState​

TParentState extends object = InferStateFromSchema<TParentStateSchema>

TFlowConfigSchema​

TFlowConfigSchema extends ZodTypeAny | undefined = undefined

TFlowConfig​

TFlowConfig extends object = InferFlowConfigFromSchema<TFlowConfigSchema>

Parameters​

config​

RouterConfig<TInputSchema, TOutputSchema, TInput, TOutput, TRequestStateSchema, TSessionStateSchema, TUserStateSchema, TOrgStateSchema, TSequencerStateSchema, TResourceDefs, TTargetSchemas, TUses, TRequestState, TSessionState, TUserState, TOrgState, TSequencerState, TResources, TMergedTargetSchemas, TCapabilities, TStateSchema, TParentStateSchema, TSelfState, TParentState, TFlowConfigSchema, TFlowConfig>

Returns​

BlockDefinition<TInputSchema, TOutputSchema, TInput, TOutput>


score()​

function score(instructions, levels): ScoreQuestion;

An ordered-scale question. The answer's score is a position between the first level (0) and the last.

Parameters​

instructions​

EvaluationInput

What to rate.

levels​

readonly (EvaluationInput | null)[]

At least two ordered level descriptions (null for none).

Returns​

ScoreQuestion


selectModel()​

function selectModel<TInput, TCtx>(defaultModel, rules): (input, ctx) => Promise<ModelSelection>;

Creates a ResolvableModel function from declarative rules.

Evaluation order:

  1. All rules walked in order; first non-null preferProvider is collected.
  2. First truthy when rule replaces the model with its use value.
  3. Default — used when no when rule matches.

If a preferProvider was collected, the return is { model, preferProvider }. Otherwise the bare model (string or array) is returned for backward compatibility with the generator block.

Type Parameters​

TInput​

TInput = unknown

TCtx​

TCtx extends BlockContext<Record<string, unknown>, Record<string, unknown>, Record<string, unknown>, Record<string, unknown>, Record<string, AnyResourceRef>, Record<string, unknown>, unknown, Record<string, ZodTypeAny>, { }, Record<string, unknown>, Record<string, unknown>, Readonly<Record<string, unknown>>> = AnyBlockContext

Parameters​

defaultModel​

string | string[]

rules​

| ModelRule<TInput, TCtx> | ModelRule<TInput, TCtx>[]

Returns​

(input, ctx) => Promise<ModelSelection>

Example​

model: selectModel("intent/chat", [
{ preferProvider: (_input, ctx) => ctx.user?.state.preferredProvider },
{ when: (_input, ctx) => ctx.session.state.thinkingStyle === "chain-of-thought",
use: "intent/reason" },
])

sequencer()​

function sequencer<TInputSchema, TStateSchema, TInput, TFlowConfigSchema>(config): SequencerDefinition<TInput, TInput, TStateSchema, TFlowConfigSchema>;

Type Parameters​

TInputSchema​

TInputSchema extends ZodTypeAny = ZodTypeAny

TStateSchema​

TStateSchema extends ZodTypeAny | undefined = undefined

TInput​

TInput = TypeOf<TInputSchema>

TFlowConfigSchema​

TFlowConfigSchema extends ZodTypeAny | undefined = undefined

Parameters​

config​

SequencerConfig<TInputSchema, TInput, TStateSchema, TFlowConfigSchema>

Returns​

SequencerDefinition<TInput, TInput, TStateSchema, TFlowConfigSchema>


taskBindingOf()​

function taskBindingOf(block): TaskBinding | undefined;

The board binding on a task dispatcher, or undefined when no board holds it.

Parameters​

block​

BlockDefinition<any, any>

Returns​

TaskBinding | undefined


taskSessionKeyFor()​

function taskSessionKeyFor(
blockName,
policy,
envelope,
ctx
): string;

The child-session key a task dispatch runs under, for one envelope and one policy. Shared by dispatcher() and the board's dispatch so both derive the same child for the same row.

Parameters​

blockName​

string

policy​

KeyedTaskSessionPolicy<any>

envelope​
assignee​

string

attempt​

number

boardId​

string

createdAt​

number

incarnationId?​

string

partition?​

string

payload?​

unknown

taskId​

string

turn?​

number

ctx​

BlockContext

Returns​

string

Throws​

when a key policy returns something other than a non-empty string — the key names the child session, so an empty one is a computed refusal.


transientSlot()​

function transientSlot<T>(schema): T;

Mark a Zod schema field as a transient sequencer-state slot. Returns the same schema instance with the marker stamped on it.

Type Parameters​

T​

T extends ZodTypeAny

Parameters​

schema​

T

Returns​

T


validateConcurrencyConfig()​

function validateConcurrencyConfig(where, config): void;

Validate a flow/action concurrency config at definition time. Mirrors validateScheduleConfig's shape: throws a plain Error (callers translate to a build-time failure) when the policy is reserved (debounce / restart) or unknown. A no-op when config is absent — the default allow applies.

where names the offending site (e.g. flow "x" action "y" or flow "x" request default) so the error points the author at the exact config to fix.

Parameters​

where​

string

config​

ConcurrencyConfig | undefined

Returns​

void


whenAnyItem()​

function whenAnyItem(predicate): (items) => boolean;

True if at least one item in the stream satisfies predicate. The generic escape hatch for cases where the more specific helpers don't fit.

Parameters​

predicate​

(item) => boolean

Returns​

(items) => boolean


whenResourceChanged()​

function whenResourceChanged(criteria): (items) => boolean;

True if any item in the stream is a resource_change whose scope and resourcePath match exactly. When changeType is supplied, the change kind ("created", "updated", "deleted") must also match.

Used to suspend a sequencer until a specific resource mutation reaches the request stream — for example, waiting for a worker pattern to write its artifact before the supervisor reads it. resource_change items are transient, so a wait's entry check sees only the most recent maxBufferSize (default 10,000) of those already done.

Parameters​

criteria​
changeType?​

"created" | "updated" | "deleted"

path​

string

scope​

"request" | "session" | "user" | "org"

Returns​

(items) => boolean


whenResourceMatching()​

function whenResourceMatching(criteria): (items) => boolean;

True if any resource_change item's resourcePath matches pattern under the given scope. pattern supports * (single path segment) and ** (any number of segments). Use this when the path is templated — e.g., artifacts/* or workers/**/done. Like whenResourceChanged, a wait's entry check sees only the most recent maxBufferSize done changes.

Parameters​

criteria​
pattern​

string

scope​

"request" | "session" | "user" | "org"

Returns​

(items) => boolean


writeResourceContentTool()​

function writeResourceContentTool(): BlockDefinition<ZodObject<{
content: ZodString;
uri: ZodString;
}, "strip", ZodTypeAny, {
content: string;
uri: string;
}, {
content: string;
uri: string;
}>, ZodObject<{
ok: ZodLiteral<true>;
uri: ZodString;
}, "strip", ZodTypeAny, {
ok: true;
uri: string;
}, {
ok: true;
uri: string;
}>, {
content: string;
uri: string;
}, {
ok: true;
uri: string;
}>;

Tool block for overwriting resource content when llmWritable is enabled, keyed by scope-qualified uri.

Returns​

BlockDefinition<ZodObject<{ content: ZodString; uri: ZodString; }, "strip", ZodTypeAny, { content: string; uri: string; }, { content: string; uri: string; }>, ZodObject<{ ok: ZodLiteral<true>; uri: ZodString; }, "strip", ZodTypeAny, { ok: true; uri: string; }, { ok: true; uri: string; }>, { content: string; uri: string; }, { ok: true; uri: string; }>

References​

handler​

Re-exports handler


HandlerConfig​

Re-exports HandlerConfig


SuspendOptions​

Re-exports SuspendOptions


SuspensionError​

Re-exports SuspensionError


SuspensionRejectedError​

Re-exports SuspensionRejectedError


SuspensionTimeoutError​

Re-exports SuspensionTimeoutError