Build AI workflows with blocks. Get streaming, state, retries, and type safety for free.
import { defineFlow, generator, handler, sequencer } from "@flow-state-dev/core";
const chat = generator({
name: "chat",
model: "openai/gpt-6-luna",
prompt: "You are a helpful assistant.",
inputSchema: z.object({ message: z.string() }),
history: true,
user: (input) => input.message,
});
const trackUsage = handler({
name: "track-usage",
sessionStateSchema: z.object({ messageCount: z.number().default(0) }),
execute: async (input, ctx) => {
await ctx.session.incState({ messageCount: 1 });
return input;
},
});
const pipeline = sequencer({ name: "chat-pipeline" })
.step(chat)
.step(trackUsage);
export default defineFlow({
kind: "my-app",
actions: {
chat: { block: pipeline, userMessage: (i) => i.message },
},
session: { stateSchema: z.object({ messageCount: z.number().default(0) }) },
})();That's a streaming chat with conversation history, session state, and atomic counters. No transport wiring. No SSE plumbing. No retry logic. The framework handles all of it.
Five block kinds. Infinite compositions.
| Block | What it does |
|---|---|
| handler | Pure logic — validate, transform, mutate state, implement tools |
| generator | Call an LLM with managed tool loops, streaming, and structured output repair |
| sequencer | Compose blocks into pipelines with .step(), .parallel(), .rescue(), .forEach(), and 10 more DSL methods |
| router | Dispatch to different pipelines at runtime based on input or state |
Any block or sequence of blocks can be used as a tool. A single tool call can trigger an entire multi-step pipeline — your AI's tools can be as sophisticated as any other part of your workflow.
Scoped state that scales. Four isolation levels — request, session, user, org — each with atomic operations (patchState, incState, pushState, atomicState). Every block declares only the state fields it needs. Type-safe all the way down.
Resumable streaming out of the box. Items stream over SSE as blocks execute. Disconnect mid-response? Reconnect with a sequence cursor and pick up exactly where you left off. No data loss. No duplicate events.
Resources: hybrid memory and filesystem. Each resource combines rich text content with structured atomic state — like files that carry metadata. An artifact can hold a document's full text alongside its title, tags, and timestamps. Scoped to sessions, users, or orgs. Projections derive client-safe views from state and resources, giving the frontend exactly the shape it needs without manual data wiring.
First-class error handling. Retry policies per block. Type-based rescue routing. Non-aborting work queues for side-chain operations. Normalized error model with codes, scopes, and retry signals.
Full-stack type safety. Define a schema once in Zod. It validates at runtime, infers at compile time, and flows from server blocks through the client SDK to React hooks. One type system, zero glue code.
Flows are full APIs. Register a flow and you get action execution, session management, SSE streaming, and state snapshots — zero route wiring:
Server — Three lines to a complete API:
const registry = createFlowRegistry();
registry.register(myFlow);
export const { GET, POST, DELETE } = createFlowApiRouter({ registry });Client — Connect from anywhere, framework handles SSE and state sync:
const fsd = createClient({ baseUrl: "http://localhost:3000", userId: "user_1" });
await fsd.flow("my-app").send("chat", { message: "Hello" });React — Hooks that wire streaming, items, and clientData to your UI:
<FlowProvider flowKind="my-app" userId="user_1">
<ChatUI />
</FlowProvider>
function ChatUI() {
const flow = useFlow({ autoCreateSession: true });
const session = useSession(flow.activeSessionId);
return (
<>
{session.items.map(item => <ItemRenderer key={item.id} item={item} />)}
<button onClick={() => session.sendAction("chat", { message: "Hi" })}>
Send
</button>
</>
);
}Testing — Deterministic tests with generator mocks, no real LLM calls:
import { testBlock, testItems } from "@flow-state-dev/testing";
const result = await testBlock(pipeline, {
input: { message: "Hello" },
session: { state: { messageCount: 0 } },
generators: { "chat": mockGenerator({ script: [{ text: "Hi there!" }] }) },
});
const items = testItems(result.items);
expect(items.messages()).toHaveLength(1);
expect(result.output).toBeDefined();Built for an ecosystem. Blocks and flows are portable. Share a tool block, a validation handler, or a complete agentic flow across projects. The uniform block contract means community blocks compose with yours out of the box.
- You're building AI-powered features and tired of reinventing orchestration, streaming, and state management every time.
- You want composable primitives, not a rigid agent framework that prescribes how you structure your AI.
- You want tools that can be as powerful as your workflows — multi-step pipelines, not just function wrappers.
- You want your AI to have a real workspace: persistent resources with rich content and typed state, not just chat history.
- You care about execution semantics — retry, rescue, lifecycle hooks — being explicit and testable, not hidden in application glue.
- You want one coherent stack across server, client, React, CLI, and tests.
| Package | Purpose |
|---|---|
@flow-state-dev/core |
Block builders, flow definitions, type contracts, item taxonomy |
@flow-state-dev/engine |
Execution runtime, stores, SSE streaming, HTTP routes |
@flow-state-dev/client |
Isomorphic API client — actions, sessions, streams |
@flow-state-dev/react |
React hooks and renderers |
@flow-state-dev/testing |
Test harnesses and generator mocks |
@flow-state-dev/fsdev |
Terminal interface (fsdev run, fsdev dev) |
@flow-state-dev/devtool |
Pre-built DevTool assets for fsdev dev |
apps/devtool |
DevTool source app |
If you have a project of your own, ask a coding assistant to run the install-fsd skill, or follow Existing project by hand.
If you are contributing to this repository, clone it and install from the root:
# Prerequisites: Node.js >=22, pnpm@10.4.1
pnpm install
pnpm typecheck
pnpm testTwo directories, different purposes:
apps/*— full reference applications we maintain, test against, and use for day-to-day feature work. Larger in scope; multiple flows; polished UI.examples/*— minimal, focused, pedagogical. Each example fits in a single README section.
apps/kitchen-sink — Reference app. Hosts the chat-agent flow (handler + generator + router + sequencer, resources, clientData, capabilities, tool-use) and everything the framework can do in a full Next.js UI.
examples/hello-chat — Minimal chat flow. Generator + handler + sequencer in ~50 lines. Start here.
The framework ships as six packages with strict dependency boundaries:
core ← engine ← testing
core ← client ← react ← apps/devtool
enginenever depends onclientorreactreactwrapsclient— no transport logic in the UI layerapps/devtooluses only public APIs
Request lifecycle:
POST /api/flows/{kind}/actions/{action}
→ 202 Accepted (async execution)
→ SSE stream: items, content deltas, status events
→ request.completed
→ Client refetches state snapshot
Resume after disconnect: Last-Event-ID or starting_after query param replays events from the sequence cursor.
Architecture (docs/architecture/):
- Overview — System architecture, data flow, core abstractions
- Blocks — Handler, generator, evaluator, sequencer, router deep dive
- Flows and Actions — defineFlow, actions, lifecycle hooks
- State and Scopes — Four scopes, atomic ops, CAS concurrency
- Streaming — Item/content model, SSE protocol, resume semantics
- Execution and Errors — Retry, rescue, work queue
- Resources and Client Data — Typed data containers and derived client views
- Sequencer DSL — Full method reference
- Server and Client — Routes, transport, React hooks
Contributing (docs/contributing/):
- Best Practices — Implementation standards
- Architecture Reference — Locked contracts
- Development Setup — Monorepo workflow
- Wave Process — Wave execution protocol
Phase 1 (Foundation) — Waves 1.a through 1.m are complete. Core contracts, block builders, server runtime, client transport, React bindings, testing utilities, the CLI and the devtool are all implemented and tested. Remaining: 1.n, cross-package validation.
- See
AGENTS.mdfor the process protocol - See
docs/contributing/for standards and setup - Keep implementation standards in
docs/contributing/best-practices.md - See
CONTRIBUTING.mdfor contribution guidelines - See
CODE_OF_CONDUCT.mdfor community standards
We're grateful to the sponsors who support the development of @flow-state-dev.
Neon — Serverless Postgres with branching, autoscaling, and scale-to-zero.
MIT — see LICENSE for details. Copyright (c) 2026 Fixpoint Labs.