diff --git a/README.md b/README.md
index 523a44a746..02731a88b6 100644
--- a/README.md
+++ b/README.md
@@ -1,140 +1,210 @@
-# flow-state-dev
-`@flow-state-dev` is a block-based AI workflow framework focused on typed flows, resumable streaming, and predictable execution behavior.
-
-This repository is the active implementation workspace for Phase 1.
-
-## Why this project exists
-
-Building AI features often means stitching together orchestration, retries, streaming, state, and UI glue in app-specific ways.
-`@flow-state-dev` aims to make those concerns first-class framework primitives so teams can ship faster with less runtime drift.
-
-## Why this repo may be worth your time
-
-- You want a framework that doesn't prebake the patterns that you use to implement agentic systems, but instead the primitives that allow you to build your own.
-- You want a typed flow model, not ad-hoc handler chains.
-- You want advanced state and memory management for your agentic workflows and agents.
-- You care about execution semantics (retry, rescue, lifecycle) being explicit and testable.
-- You want item-first streaming with replay/resume, not one-off transport wiring.
-- You want one stack across server, client, React UI, CLI, and tests.
-
-## Current maturity (Phase 1)
-
-- Core contracts and block builders are implemented.
-- Server execution, stores, and streaming runtime are implemented.
-- Client transport/session/SSE APIs are implemented and tested.
-- React hook wrappers, renderer registry, and item render helpers are implemented and tested.
-- Testing package APIs are implemented and validated.
-- Canonical Wave K example flows are implemented in:
- - `examples/hello-chat/src/flows/hello-chat/flow.ts`
- - `examples/kitchen-sink/src/flows/kitchen-sink/flow.ts`
-- CLI/devtool packages remain in active implementation.
-
-This is an implementation-phase repository, not a polished production release yet.
-
-## Core concepts
-
-- **Flow**: declared via `defineFlow`, with flow-level `actions`.
-- **Block kinds**: exactly `handler`, `generator`, `sequencer`, `router`.
-- **Generator**: loop-capable runtime unit with framework-managed execution.
-- **Scopes**: request/session/user/project state + resource updates.
-- **Execution entrypoint**: blocks execute via framework-owned `block.run(...)`.
-- **Streaming model**: item/content lifecycle events with sequence-based replay.
-- **Execution model**: normalized errors, retry policy, rescue routing, work convergence.
-
-## Package map
-
-- `@flow-state-dev/core`: builders, contracts, item/event taxonomy.
-- `@flow-state-dev/server`: action runtime, stores, SSE streaming, orchestration.
-- `@flow-state-dev/client`: isomorphic action/session/stream API client.
-- `@flow-state-dev/react`: hooks and render/runtime bindings.
-- `@flow-state-dev/testing`: flow/block/runtime test harnesses.
-- `@flow-state-dev/cli`: `fsdev` CLI for running/inspecting flows.
-- `apps/devtool`: first-party inspector app using public framework APIs.
-- `examples/hello-chat`: minimal canonical chat flow example.
-- `examples/kitchen-sink`: comprehensive canonical feature-reference flow example.
-
-## Repository layout
-
-```text
-packages/
- core/ # Isomorphic builders, type contracts, item taxonomy
- server/ # Action runtime, stores, SSE streaming
- client/ # Isomorphic HTTP/SSE transport client
- react/ # React hooks, renderers, context providers
- testing/ # Test harnesses for blocks, flows, generators
- cli/ # fsdev CLI for running/inspecting flows
-apps/
- devtool/ # First-party inspector app
- docs/ # Docusaurus documentation site
-examples/
- hello-chat/ # Minimal canonical chat flow
- kitchen-sink/ # Comprehensive feature-reference flow
-docs/
- architecture/ # Framework developer reference (9 topic docs)
- contributing/ # Standards, setup, process docs
- internal/ # Wave plans, journals, changelogs
+# @flow-state-dev
+
+**Build AI workflows with blocks. Get streaming, state, retries, and type safety for free.**
+
+```ts
+import { defineFlow, generator, handler, sequencer } from "@flow-state-dev/core";
+
+const chat = generator({
+ name: "chat",
+ model: "gpt-5-mini",
+ prompt: "You are a helpful assistant.",
+ inputSchema: z.object({ message: z.string() }),
+ history: (_input, ctx) => ctx.session.items.llm(),
+ 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" })
+ .then(chat)
+ .then(trackUsage);
+
+export default defineFlow({
+ kind: "my-app",
+ actions: {
+ chat: { block: pipeline, userMessage: (i) => i.message },
+ },
+ session: { stateSchema: z.object({ messageCount: z.number().default(0) }) },
+})({ id: "default" });
```
-## Quick start
+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.
+
+## What you get
+
+**Four block primitives. 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 `.then()`, `.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, project — 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 projects. 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.
+
+## The developer experience
+
+**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:
+
+```ts
+const registry = createFlowRegistry();
+registry.register(myFlow);
+export const { GET, POST, DELETE } = createFlowApiRouter({ registry });
+```
+
+**Client** — Connect from anywhere, framework handles SSE and state sync:
+
+```ts
+const client = createClient({ flowKind: "my-app", userId: "user_1" });
+await client.sendAction("chat", { message: "Hello" });
+```
+
+**React** — Hooks that wire streaming, items, and projections to your UI:
+
+```tsx
+
+
+
+
+function ChatUI() {
+ const flow = useFlow({ autoCreateSession: true });
+ const session = useSession(flow.activeSessionId);
+
+ return (
+ <>
+ {session.items.map(item => )}
+
+ >
+ );
+}
+```
+
+**Testing** — Deterministic tests with generator mocks, no real LLM calls:
-### Prerequisites
+```ts
+import { testBlock, testItems } from "@flow-state-dev/testing";
-- Node.js `>=18` (Node 20+ recommended)
-- `pnpm@10.4.1`
+const result = await testBlock(pipeline, {
+ input: { message: "Hello" },
+ session: { state: { messageCount: 0 } },
+ generators: { "chat": mockGenerator({ script: [{ text: "Hi there!" }] }) },
+});
-### Setup
+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.
+
+## When this framework is for you
+
+- 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.
+
+## Packages
+
+| Package | Purpose |
+|---------|---------|
+| [`@flow-state-dev/core`](packages/core) | Block builders, flow definitions, type contracts, item taxonomy |
+| [`@flow-state-dev/server`](packages/server) | Execution runtime, stores, SSE streaming, HTTP routes |
+| [`@flow-state-dev/client`](packages/client) | Isomorphic API client — actions, sessions, streams |
+| [`@flow-state-dev/react`](packages/react) | React hooks and renderers |
+| [`@flow-state-dev/testing`](packages/testing) | Test harnesses and generator mocks |
+| [`@flow-state-dev/cli`](packages/cli) | Terminal interface (`fsdev`) |
+| [`apps/devtool`](apps/devtool) | First-party flow inspector |
+
+## Quick start
```bash
+# Prerequisites: Node.js >=18, pnpm@10.4.1
pnpm install
pnpm typecheck
pnpm test
```
-### Common commands
+## Examples
+
+**[hello-chat](examples/hello-chat)** — Minimal chat flow. Generator + handler + sequencer in ~50 lines. Start here.
-- Run all tests: `pnpm test`
-- Run all typechecks: `pnpm typecheck`
-- Watch tests: `pnpm test:watch`
-- Test one package: `pnpm --filter @flow-state-dev/server test`
-- Typecheck one package: `pnpm --filter @flow-state-dev/core typecheck`
+**[kitchen-sink](examples/kitchen-sink)** — Everything the framework can do. Router-based dispatch, handler-backed tools, session resources with projections, rescue boundaries, and a full Next.js UI.
-## Start here (new contributors)
+## Architecture
-1. Read architecture overview: `docs/architecture/overview.md`
-2. Browse topic docs: `docs/architecture/` (blocks, flows, state, streaming, etc.)
-3. Review current progress: `changelog.md`
-4. Review standards: `docs/contributing/best-practices.md`
-5. For canonical edge cases: `../preperation/architecture/`
+The framework ships as six packages with strict dependency boundaries:
-## Documentation map
+```
+core ← server ← testing
+core ← client ← react ← apps/devtool
+```
-**Architecture reference** (`docs/architecture/`):
-- [Overview](docs/architecture/overview.md) — package structure, core abstractions, data flow
-- [Blocks](docs/architecture/blocks.md) — handler, generator, sequencer, router
-- [Flows and Actions](docs/architecture/flows-and-actions.md) — defineFlow, actions, lifecycle
-- [State and Scopes](docs/architecture/state-and-scopes.md) — 4 scopes, state ops, CAS
-- [Streaming](docs/architecture/streaming.md) — item/content model, SSE protocol, resume
-- [Execution and Errors](docs/architecture/execution-and-errors.md) — retry, rescue, work queue
-- [Resources and Projections](docs/architecture/resources-and-projections.md) — typed data management
-- [Sequencer DSL](docs/architecture/sequencer-dsl.md) — full method reference
-- [Server and Client](docs/architecture/server-and-client.md) — routes, transport, React hooks
+- `server` never depends on `client` or `react`
+- `react` wraps `client` — no transport logic in the UI layer
+- `apps/devtool` uses 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.
+
+## Documentation
+
+**Architecture** (`docs/architecture/`):
+- [Overview](docs/architecture/overview.md) — System architecture, data flow, core abstractions
+- [Blocks](docs/architecture/blocks.md) — Handler, generator, sequencer, router deep dive
+- [Flows and Actions](docs/architecture/flows-and-actions.md) — defineFlow, actions, lifecycle hooks
+- [State and Scopes](docs/architecture/state-and-scopes.md) — Four scopes, atomic ops, CAS concurrency
+- [Streaming](docs/architecture/streaming.md) — Item/content model, SSE protocol, resume semantics
+- [Execution and Errors](docs/architecture/execution-and-errors.md) — Retry, rescue, work queue
+- [Resources and Projections](docs/architecture/resources-and-projections.md) — Typed data containers and derived views
+- [Sequencer DSL](docs/architecture/sequencer-dsl.md) — Full method reference
+- [Server and Client](docs/architecture/server-and-client.md) — Routes, transport, React hooks
**Contributing** (`docs/contributing/`):
-- [Best Practices](docs/contributing/best-practices.md) — implementation standards (BP-001–BP-009)
-- [Architecture Reference](docs/contributing/architecture-reference.md) — locked contracts quick reference
-- [Development Setup](docs/contributing/development-setup.md) — monorepo setup and workflow
-- [Wave Process](docs/contributing/wave-process.md) — wave execution protocol
-
-**Other**:
-- Canonical architecture (authoritative for edge cases): `../preperation/architecture/`
-- Package READMEs: `packages/*/README.md`
-- Example READMEs: `examples/*/README.md`
-- Changelog: `changelog.md`
-- Agent protocol: `AGENTS.md`
-
-## Contributing notes
-
-- Keep onboarding-relevant changes reflected in this README.
-- Keep implementation standards in `docs/contributing/best-practices.md`.
-- Keep wave/process protocol in `AGENTS.md` (not in README).
-- See `AGENTS.md` for the full documentation maintenance protocol.
+- [Best Practices](docs/contributing/best-practices.md) — Implementation standards
+- [Architecture Reference](docs/contributing/architecture-reference.md) — Locked contracts
+- [Development Setup](docs/contributing/development-setup.md) — Monorepo workflow
+- [Wave Process](docs/contributing/wave-process.md) — Wave execution protocol
+
+## Current status
+
+Phase 1 (Foundation) — Waves 1.a through 1.k are complete. Core contracts, block builders, server runtime, client transport, React bindings, and testing utilities are all implemented and tested. CLI and devtool are in active development.
+
+## Contributing
+
+- See [`AGENTS.md`](AGENTS.md) for the process protocol
+- See [`docs/contributing/`](docs/contributing/) for standards and setup
+- Keep implementation standards in `docs/contributing/best-practices.md`
diff --git a/apps/docs/blog/2026-02-26-welcome.md b/apps/docs/blog/2026-02-26-welcome.md
index e3abd4e404..105588ec76 100644
--- a/apps/docs/blog/2026-02-26-welcome.md
+++ b/apps/docs/blog/2026-02-26-welcome.md
@@ -1,14 +1,74 @@
---
slug: welcome
-title: Welcome to Flow State Dev
+title: "We Don't Know What the Best AI Agents Look Like Yet"
authors: [flowstatedev]
tags: [announcement]
---
-Flow State Dev is a block-based AI workflow framework for TypeScript.
+Most AI frameworks start from the same premise: here's how agents work, here's the pattern, fill in the blanks. ReAct loops. Tool-calling chains. RAG pipelines. These are well-understood patterns, and there are plenty of good frameworks for executing them.
+
+We're building something different. **flow-state.dev** exists because we believe the most powerful AI agent architectures haven't been discovered yet — and the only way to find them is to give developers the right primitives to explore.
-We're building a framework that makes AI workflow concerns — orchestration, retries, streaming, state, and UI rendering — first-class primitives so teams can ship faster with less runtime drift.
+## The frontier is wide open
+
+We're still in the early days of what AI agents can do. The patterns that dominate today — single-agent loops, linear chains, fixed tool sets — are starting points, not endpoints. The teams pushing boundaries are the ones experimenting with novel architectures: agents that spawn sub-agents with their own tool pipelines, workflows where a single tool call triggers a multi-step research process, systems where AI has a persistent workspace it can read, write, and organize across conversations.
+
+But experimenting is hard when your framework assumes you already know the shape of your solution. Most tools lock you into their mental model. You can configure what they anticipated. Everything else is a workaround.
+
+## Primitives, not patterns
+
+**flow-state.dev** takes a different approach. Instead of prescribing agent architectures, we give you four composable primitives — **handler**, **generator**, **sequencer**, **router** — and a powerful composition system. That's it. Every AI workflow you can imagine reduces to combinations of these four blocks.
+
+The constraint is liberating. Want an agent whose tools are themselves multi-step pipelines? Compose a sequencer, pass it as a tool. Want a router that dispatches to entirely different agent architectures based on runtime state? That's just a router block with sequencer routes. Want to give your AI a persistent workspace with rich documents and structured metadata it can manipulate across sessions? That's resources — hybrid memory that combines text content with atomic state.
+
+```ts
+// A tool that's a full research pipeline — not just a function wrapper
+const deepResearch = sequencer({ name: "deep-research" })
+ .then(searchIndex)
+ .then(rankResults)
+ .then(summarize);
+
+// An agent whose tools are as sophisticated as the agent itself
+const agent = generator({
+ name: "agent",
+ model: "gpt-5-mini",
+ tools: [deepResearch, readDoc, writeDoc],
+ // ...
+});
+```
+
+We didn't design this to make existing patterns easier to implement (though it does). We designed it so you can explore patterns that don't have names yet.
+
+## Built to build together
+
+Exploring new boundaries alone is slow. The real acceleration happens when discoveries compound — when one team's novel tool pipeline becomes another team's building block, when an agent architecture that works brilliantly in one domain gets adapted to another.
+
+That's why **flow-state.dev** is built for an ecosystem from day one. Every block has the same contract: typed input, typed output, declared state dependencies. A handler, a sequencer pipeline, an entire agent flow — each is a portable unit that composes with anything else. Connectors bridge incompatible types with a single function. No wrappers. No adapters. No inheritance hierarchies.
+
+When someone discovers a powerful new pattern — a novel retrieval strategy, an innovative agent coordination mechanism, a breakthrough in structured output handling — they can package it as blocks and share it. And those blocks compose with yours immediately, because the contracts are universal.
+
+## Solid ground for bold experiments
+
+Exploring new frontiers requires solid infrastructure underneath. You shouldn't have to reinvent streaming, state management, and error handling every time you want to try a new agent architecture. So we made these framework-level concerns:
+
+- **Resumable SSE streaming** with sequence-number cursors — disconnect mid-experiment and pick up exactly where you left off
+- **Scoped state** at four isolation levels with atomic operations — your agent's workspace is reliable even under concurrent access
+- **Resources** that combine rich text with structured state — give your AI a real workspace, not just a chat log
+- **Type safety from schema to screen** — one Zod schema flows from server blocks through client SDK to React hooks
+- **Deterministic testing** — mock generators, seed state, assert on items and state changes without real LLM calls
+
+The framework handles execution semantics — retry, rescue, lifecycle hooks, streaming — so you can focus entirely on the architecture of your AI. Every experiment runs on battle-tested infrastructure.
+
+## Where we are
+
+Phase 1 (Foundation) is largely complete: core contracts, block builders, server runtime with stores and streaming, client transport, React hooks and renderers, and a testing package with deterministic generator mocks. CLI and devtool are in active development.
+
+## Come build with us
+
+We're not here to tell you how AI agents should work. We're here to give you the tools to figure that out — and to make it easy to share what you discover.
+
+The best agent architectures of 2027 probably don't look like anything we'd design today. But they'll be built from composable primitives, on solid infrastructure, by developers who had the freedom to experiment.
-Stay tuned for updates as we progress through our roadmap.
+[Get started](/docs/getting-started/quick-start) and see what you can build.
diff --git a/apps/docs/blog/authors.yml b/apps/docs/blog/authors.yml
index 6257947039..cbc680a75d 100644
--- a/apps/docs/blog/authors.yml
+++ b/apps/docs/blog/authors.yml
@@ -1,3 +1,3 @@
flowstatedev:
- name: Flow State Dev Team
+ name: flow-state.dev team
url: https://github.com/flow-state-dev
diff --git a/apps/docs/docs/concepts/actions.md b/apps/docs/docs/concepts/actions.md
index fc6eaf7f99..c6c1d2518a 100644
--- a/apps/docs/docs/concepts/actions.md
+++ b/apps/docs/docs/concepts/actions.md
@@ -4,11 +4,11 @@ sidebar_position: 3
# Actions
-Actions are the entry points into a flow. When a client wants to do something — send a message, reset state, trigger processing — it invokes an action.
+Actions are how the outside world talks to your flow. When a client sends a message, resets state, or triggers any processing — it invokes an action. Actions are the flow's public API: named entry points with validated input and a block to execute.
-## Defining Actions
+## Defining actions
-Actions are defined inside `defineFlow`:
+Actions live inside `defineFlow`:
```ts
const myFlow = defineFlow({
@@ -23,28 +23,32 @@ const myFlow = defineFlow({
inputSchema: z.object({}),
block: resetHandler,
},
+ saveArtifact: {
+ inputSchema: artifactInputSchema,
+ block: updateArtifact,
+ },
},
});
```
Each action has:
-- **`inputSchema`** — Zod schema for validating action input
-- **`block`** — The block (or pipeline) to execute
-- **`userMessage`** (optional) — Extracts a user message string from the input, emitted as a `message` item before block execution
+- **`inputSchema`** — Zod schema that validates every incoming request. Invalid input is rejected before any block runs.
+- **`block`** — The block (or pipeline) to execute. This is where the work happens.
+- **`userMessage`** (optional) — Extracts a display string from the input. The framework emits it as a user-role `message` item before execution begins, so the conversation history shows what the user said.
-## Invoking Actions
+## Invoking actions
-### From the client
+### From the client SDK
```ts
import { createClient } from "@flow-state-dev/client";
-const client = createClient({ flowKind: "my-app", userId: "devuser" });
+const client = createClient({ flowKind: "my-app", userId: "user_1" });
-// Dynamic action name
+// New session (auto-created)
await client.sendAction("chat", { message: "Hello!" });
-// With an existing session
+// Existing session
await client.sendAction("chat", { message: "Hello!" }, { sessionId: "sess_123" });
```
@@ -52,14 +56,10 @@ await client.sendAction("chat", { message: "Hello!" }, { sessionId: "sess_123" }
```tsx
const session = useSession(sessionId);
-
-// Primary pattern — via useSession
await session.sendAction("chat", { message: "Hello!" });
```
-### HTTP API
-
-Actions are exposed at:
+### Over HTTP
```
POST /api/flows/:kind/actions/:action # New session
@@ -72,41 +72,39 @@ The server returns `202 Accepted` immediately with a `requestId`. Execution happ
GET /api/flows/:kind/requests/:requestId/stream
```
-## Execution Flow
+## How an action executes
```
Client Server
- │ │
- ├─ POST /actions/chat ──────►│
- │ { input, userId } ├─ validate input
- │ ├─ resolve/create session
- │◄── 202 { requestId } ──────┤
- │ ├─ execute block (async)
- ├─ GET /requests/:id/stream ►│
- │◄── SSE events ─────────────┤ item.added, content.delta, ...
- │◄── request.completed ──────┤
- │ │
+ | |
+ |-- POST /actions/chat ------>|
+ | { input, userId } |-- validate input
+ | |-- resolve/create session
+ |<-- 202 { requestId } ------|
+ | |-- execute block (async)
+ |-- GET /requests/:id/stream->|
+ |<-- SSE events --------------| item.added, content.delta, ...
+ |<-- request.completed -------|
+ | |
```
-## Action Lifecycle
-
-1. **Validate** — Input is checked against `inputSchema`
-2. **Session** — Resolved from `sessionId` or created new
-3. **User message** — `userMessage(input)` emitted if defined
-4. **Execute** — Block runs asynchronously
-5. **Complete or Error** — Lifecycle hooks fire, stream closes
+Step by step:
+1. **Validate** — Input is checked against `inputSchema`. Bad input returns 400.
+2. **Session** — Resolved from `sessionId` or created new.
+3. **User message** — If `userMessage` is defined, a user-role message item is emitted to the stream.
+4. **Execute** — The root block runs asynchronously. Items stream to the client as they're produced.
+5. **Complete** — Lifecycle hooks fire. The stream emits `request.completed` (or `request.failed`).
-## Typed Actions
+## Typed actions
-For compile-time type safety, use `createTypedClient`:
+For compile-time type safety, use `createTypedClient` — it generates action methods from your flow definition:
```ts
import { createTypedClient } from "@flow-state-dev/client";
-const client = createTypedClient({ flow: myFlow, userId: "devuser" });
+const client = createTypedClient({ flow: myFlow, userId: "user_1" });
-// Type-safe action methods
-await client.actions.chat({ message: "Hello!" });
-// TypeScript error: Property 'invalid' does not exist
-await client.actions.invalid({ message: "Hello!" });
+await client.actions.chat({ message: "Hello!" }); // Type-checked
+await client.actions.reset({}); // Type-checked
+await client.actions.invalid({ message: "Hello!" }); // TypeScript error
```
diff --git a/apps/docs/docs/concepts/blocks.md b/apps/docs/docs/concepts/blocks.md
index ead1fc13d8..96327d2134 100644
--- a/apps/docs/docs/concepts/blocks.md
+++ b/apps/docs/docs/concepts/blocks.md
@@ -4,13 +4,15 @@ sidebar_position: 1
# Blocks
-Blocks are the runtime units of Flow State Dev. Every piece of work — calling an LLM, validating input, transforming data, choosing a path — is a block.
+Everything in flow-state.dev is a block. Every LLM call, every data transform, every branching decision, every multi-step pipeline — it's all composed from four block kinds. No more, no less.
-## Four Block Kinds
+This constraint is the point. Four primitives that compose freely means you can build any AI workflow without inventing new abstractions.
-### Handler
+## The four kinds
-Synchronous logic blocks for validation, state updates, and transformations.
+### Handler — pure logic
+
+Handlers do the work that isn't AI: validate input, transform data, update state, implement tool logic. They take input, run `execute`, and return output.
```ts
import { handler } from "@flow-state-dev/core";
@@ -22,115 +24,346 @@ const counter = handler({
outputSchema: z.string(),
sessionStateSchema: z.object({ count: z.number().default(0) }),
execute: async (input, ctx) => {
- await ctx.session.patchState({ count: (ctx.session.state.count ?? 0) + 1 });
+ await ctx.session.incState({ count: 1 });
return input;
},
});
```
-### Generator
+Handlers are **silent by default** — they don't emit anything to the client unless you explicitly call `ctx.emitMessage()` or `ctx.emitComponent()`. This gives you precise control over what the user sees.
+
+### Generator — the AI block
-LLM-calling blocks with tool loops, structured output, and streaming.
+Generators call LLMs. But unlike a raw API call, the framework manages everything around it: prompt assembly, conversation history, tool execution loops, streaming, structured output with schema repair.
```ts
import { generator } from "@flow-state-dev/core";
import { z } from "zod";
-const chatGen = generator({
- name: "chat",
+const agent = generator({
+ name: "agent",
model: "gpt-5-mini",
prompt: "You are a helpful assistant.",
inputSchema: z.object({ message: z.string() }),
- outputSchema: z.object({ response: z.string() }),
+ history: (_input, ctx) => ctx.session.items.llm(),
user: (input) => input.message,
- tools: [searchTool, calculatorTool],
+ tools: [searchTool, createArtifactTool],
+ emit: { reasoning: true, messages: true },
});
```
-Generators handle:
-- Prompt assembly (system, context, history, user messages)
-- Tool execution loops (call tools, feed results back, repeat)
-- Structured output with schema repair
-- Streaming content deltas to the client
+What the framework handles for you:
+- **Prompt assembly** from four slots: system prompt, context entries, conversation history, and user message
+- **Tool execution loops** — tools are blocks, auto-compiled to provider-native format (see below)
+- **Streaming** — content deltas flow to the client as they're generated
+- **Structured output repair** — if the LLM returns invalid JSON, the framework can auto-retry or route to a rescue block
-### Sequencer
+#### Any block can be a tool
-Pipeline composition using a fluent DSL for chaining, branching, parallelism, and error recovery.
+Any block or sequence of blocks can be used as a tool. A generator's `tools` array accepts handlers, sequencers, routers — anything with the block contract. That means a single tool call can trigger an entire multi-step pipeline:
```ts
-import { sequencer } from "@flow-state-dev/core";
+// A simple handler as a tool
+const readDoc = handler({
+ name: "read-doc",
+ inputSchema: z.object({ docId: z.string() }),
+ outputSchema: z.string(),
+ execute: async (input, ctx) => {
+ const doc = ctx.session.resources.get("docs")?.state.byId[input.docId];
+ return doc?.content ?? "Document not found.";
+ },
+});
-const pipeline = sequencer({
- name: "chat-pipeline",
- inputSchema: z.object({ message: z.string() }),
-})
+// A full pipeline as a tool — search, rank, summarize
+const deepResearch = sequencer({ name: "deep-research" })
+ .then(searchIndex)
+ .then(rankResults)
+ .then(summarize);
+
+// Both work as tools — the framework compiles them for the LLM
+const agent = generator({
+ name: "agent",
+ tools: [readDoc, deepResearch],
+ // ...
+});
+```
+
+When the LLM calls `deep-research`, the framework runs the full sequencer pipeline, collects the output, and feeds it back as the tool result — all within the generator's tool loop. Your tools can be as sophisticated as any other part of your workflow.
+
+### Sequencer — the composition engine
+
+Sequencers compose blocks into pipelines using a fluent DSL with 15 chainable methods. Each step's output feeds into the next step's input, with full type inference through the chain.
+
+#### Sequential steps
+
+The basics — chain blocks in order, conditionally skip steps, or transform values inline:
+
+```ts
+const pipeline = sequencer({ name: "pipeline", inputSchema })
+ .then(analyzeInput) // always runs
+ .thenIf((result) => result.needsContext, enrichWithContext) // conditional
+ .map((result) => ({ ...result, timestamp: Date.now() })) // inline transform
+ .then(agent);
+```
+
+#### Parallel execution
+
+Run multiple blocks concurrently with a single step. Output is an object keyed by step name:
+
+```ts
+const enriched = sequencer({ name: "enrich" })
+ .then(parseQuery)
+ .parallel({
+ web: searchWeb,
+ docs: searchInternalDocs,
+ memory: { connector: (input) => input.userId, block: searchUserHistory },
+ }, { maxConcurrency: 3 })
+ // output: { web: WebResults, docs: DocResults, memory: HistoryResults }
+ .then(mergeResults);
+```
+
+#### Collection processing
+
+Process arrays concurrently with `forEach`. Supports dynamic block selection per item:
+
+```ts
+pipeline
+ .forEach(processChunk, { maxConcurrency: 5 }) // static block
+ .forEach((input) => input.urls, fetchUrl, { maxConcurrency: 10 }) // extract array first
+ .forEach((item, index) => item.type === "pdf" ? parsePdf : parseText); // dynamic block
+```
+
+#### Loops
+
+Three loop constructs — each with built-in guards to prevent infinite loops:
+
+```ts
+pipeline
+ // Loop until condition is true (checked after each iteration)
+ .doUntil((result) => result.confidence > 0.9, refineBlock)
+
+ // Loop while condition is true (checked after each iteration)
+ .doWhile((result) => result.remaining > 0, processNextBatch)
+
+ // Jump back to a named step — requires explicit max iterations
+ .then(generateBlock)
.then(validateBlock)
- .then(chatGen)
- .tap(analyticsBlock)
- .rescue([
- { when: [NetworkError], block: retryBlock },
- ]);
+ .loopBack("generate-block", {
+ when: (result) => !result.isValid,
+ maxIterations: 3,
+ });
+```
+
+#### Background work
+
+Queue non-blocking tasks that run alongside the main pipeline. The main chain continues immediately — background failures emit `step_error` items but never abort the pipeline:
+
+```ts
+pipeline
+ .then(coreLogic)
+ .work(logAnalytics) // fire and forget
+ .work((output) => output.metrics, reportMetrics) // with connector
+ .then(moreWork)
+ .waitForWork({ timeoutMs: 5000 }); // optionally converge later
+```
+
+#### Branching
+
+Route to different blocks based on runtime conditions. First matching branch wins:
+
+```ts
+pipeline.branch({
+ urgent: [
+ (input) => input,
+ (input) => input.priority === "critical",
+ urgentPipeline,
+ ],
+ standard: [
+ (input) => input,
+ (input) => input.priority === "normal",
+ standardPipeline,
+ ],
+ fallback: [
+ (input) => input,
+ () => true, // catch-all
+ defaultPipeline,
+ ],
+});
+```
+
+#### Side effects
+
+Run blocks or functions for observation without changing the payload:
+
+```ts
+pipeline
+ .tap(auditLogBlock) // block side effect
+ .tap((value, ctx) => console.log("checkpoint", value)) // inline side effect
+ .tapIf((value) => value.score < 0.5, alertBlock); // conditional side effect
```
-See [Sequencer Patterns](/docs/guides/sequencer-patterns) for composition recipes.
+#### Error recovery
+
+Catch errors from prior steps and route to recovery blocks by error type:
+
+```ts
+pipeline.rescue([
+ { when: [RateLimitError], block: retryWithBackoff },
+ { when: [ModelError], block: fallbackModel },
+ { block: genericRecovery }, // catch-all
+]);
+```
-### Router
+#### Putting it all together
-Runtime block selection based on input or state.
+These compose into sophisticated workflows that would be painful to build from scratch:
+
+```ts
+const researchAgent = sequencer({ name: "research-agent" })
+ .then(parseQuery)
+ .parallel({
+ web: searchWeb,
+ docs: searchDocs,
+ memory: searchMemory,
+ })
+ .then(mergeAndRank)
+ .doUntil((r) => r.confidence > 0.9, refineResults)
+ .work(logAnalytics)
+ .then(synthesize)
+ .tapIf((r) => r.citations.length > 5, notifyReviewer)
+ .rescue([{ when: [SearchError], block: fallbackSearch }]);
+```
+
+That's a parallel search across three sources, iterative refinement until confidence is high, background analytics, synthesis, conditional notification, and error recovery — all as a single composable block that can be nested inside other sequencers, used as a generator tool, or registered as a flow action.
+
+### Router — runtime dispatch
+
+Routers inspect input or state and pick which block (or pipeline) to run next. Routes are declared statically so the framework can validate them, but selection happens at runtime.
```ts
import { router } from "@flow-state-dev/core";
const modeRouter = router({
name: "mode-router",
- inputSchema: z.object({ message: z.string(), mode: z.string() }),
- routes: {
- chat: chatPipeline,
- agent: agentPipeline,
- search: searchPipeline,
- },
- execute: async (input, ctx) => {
- return input.mode; // returns the route key
+ inputSchema,
+ outputSchema: z.string(),
+ sessionStateSchema: z.object({ mode: modeSchema }),
+ routes: [chatPipeline, planPipeline, reviewPipeline],
+ execute: (input, ctx) => {
+ const mode = ctx.session.state.mode;
+ if (mode === "plan") return planPipeline;
+ if (mode === "review") return reviewPipeline;
+ return chatPipeline;
},
});
```
-## Block Context
+## The block context
-Every block receives a `BlockContext` with access to scopes and framework services:
+Every block's `execute` function receives a context object with access to scoped state, resources, and framework services:
```ts
execute: async (input, ctx) => {
- // Scope access
- ctx.session.state; // Read session state
- await ctx.session.patchState({...}); // Update state
+ // Read and write scoped state
+ const mode = ctx.session.state.mode;
+ await ctx.session.patchState({ mode: "agent" });
+
+ // Access resources
+ const plan = ctx.session.resources.get("plan");
+ await ctx.session.resources.plan.patchState({ status: "active" });
- // Resources
- ctx.session.resources.plan.state; // Read resource
- await ctx.session.resources.plan.patchState({...});
+ // Emit items to the client
+ await ctx.emitMessage("Processing your request...");
+ await ctx.emitComponent("progress-bar", { percent: 50 });
- // Framework services
- ctx.resolveModel(modelId); // Resolve AI model
- ctx.emit(item); // Emit stream item
+ // Resolve AI models
+ const model = ctx.resolveModel("gpt-5-mini");
}
```
-## Blocks Are Composable
+## Blocks are composable
-Any block can be used wherever a block is expected. A sequencer is a block. A router is a block. This means you can nest them freely:
+A sequencer is a block. A router is a block. This means you can nest them freely — a sequencer can contain routers, a router can dispatch to sequencers, sequencers can nest inside sequencers:
```ts
-const innerPipeline = sequencer({ name: "inner", ... })
+const innerPipeline = sequencer({ name: "inner" })
.then(blockA)
.then(blockB);
-const outerPipeline = sequencer({ name: "outer", ... })
- .then(innerPipeline) // Sequencer inside sequencer
+const outerPipeline = sequencer({ name: "outer" })
+ .then(innerPipeline) // Sequencer inside sequencer
+ .then(modeRouter) // Router inside sequencer
.then(blockC);
```
-## Key Rules
+## Connecting blocks with different shapes
+
+An immediate question: if blocks have typed inputs and outputs, how do they fit together when their types don't match? The answer is **connectors** — lightweight functions that transform one block's output into the next block's input.
+
+### Sequencer connectors
+
+The most common pattern. Pass a transform function before the block in any sequencer method:
+
+```ts
+const pipeline = sequencer({ name: "pipeline", inputSchema })
+ // Block A outputs { text: string, metadata: {...} }
+ // Block B expects { query: string }
+ .then(blockA)
+ .then(
+ (output) => ({ query: output.text }), // Connector: reshape the data
+ blockB
+ );
+```
+
+Connectors receive the previous step's output and the block context, and return the shape the next block expects. They work across the entire sequencer DSL:
+
+```ts
+pipeline
+ .then((output) => ({ query: output.text }), searchBlock) // then
+ .thenIf(needsReview, (output) => output.results, reviewBlock) // thenIf
+ .parallel({ // parallel
+ summary: summaryBlock,
+ tags: { connector: (output) => output.text, block: tagBlock },
+ })
+ .forEach((output) => output.items, processBlock) // forEach
+```
+
+The type system tracks these transformations — TypeScript knows the connector's return type must match the next block's input schema.
+
+### Block-level connections
+
+You can also attach transforms directly to a block with `connectInput` and `connectOutput`. This is useful when you want a block to always accept a different input shape:
+
+```ts
+// Create an adapted version of searchBlock that accepts a string
+const searchFromText = searchBlock.connectInput(
+ (text: string) => ({ query: text, limit: 10 })
+);
+
+// Now it fits directly in the pipeline without a sequencer connector
+pipeline.then(searchFromText);
+```
+
+### Why this matters for portability
+
+Connectors are how blocks from different packages work together. A community search block expects `{ query: string, limit: number }`. Your pipeline produces `{ text: string, metadata: object }`. A one-line connector bridges the gap — no wrapper blocks, no adapters, no type gymnastics:
+
+```ts
+pipeline.then(
+ (output) => ({ query: output.text, limit: 5 }),
+ communitySearchBlock
+);
+```
+
+## Blocks are portable
+
+Because every block has the same contract — typed input, typed output, declared state dependencies — blocks are inherently shareable. A handler that validates email addresses, a sequencer that does multi-step research, a generator pre-configured for code review — each can be packaged independently and composed into any flow.
+
+Connectors make this practical: when types don't align, a simple transform function bridges the gap. No wrapper blocks, no inheritance hierarchies. The framework's four-primitive constraint and partial state schemas mean blocks don't leak assumptions about the flows they live in.
+
+## Key rules
-- **Execute via `block.run()`** — Never call `block.config.execute` directly. The framework manages validation, retry, and lifecycle through `block.run()`.
-- **Schemas define the contract** — `inputSchema` and `outputSchema` are validated at runtime. Trust the types.
-- **Names must be unique** — Each block within a flow needs a unique `name` for provenance tracking and debugging.
+- **Always use `block.run()`** — never call `block.config.execute` directly. The framework manages validation, retry, lifecycle, and streaming through `block.run()`.
+- **Schemas are contracts** — `inputSchema` and `outputSchema` are validated at runtime. TypeScript catches mismatches at compile time.
+- **Names must be unique** — within a flow, each block needs a unique `name` for provenance tracking and debugging.
+- **Partial state schemas** — each block declares only the state fields it touches, not the full flow-level schema. This keeps blocks reusable.
diff --git a/apps/docs/docs/concepts/flows.md b/apps/docs/docs/concepts/flows.md
index ffbbae3236..300a23ba29 100644
--- a/apps/docs/docs/concepts/flows.md
+++ b/apps/docs/docs/concepts/flows.md
@@ -4,17 +4,19 @@ sidebar_position: 2
# Flows
-A **flow** is the top-level unit in Flow State Dev. It declares what actions are available, what state is managed, and how blocks execute.
+A flow is the top-level unit — the thing you register with the server and clients connect to. It ties together your blocks, actions, state, resources, and projections into a single, deployable definition.
-## Defining a Flow
+Think of a flow as the complete specification of an AI-powered feature: what actions users can trigger, what state is tracked, and what data is exposed to the frontend.
+
+## Defining a flow
```ts
-import { defineFlow, sequencer, generator } from "@flow-state-dev/core";
+import { defineFlow } from "@flow-state-dev/core";
import { z } from "zod";
const chatFlow = defineFlow({
- kind: "my-chat", // Unique identifier
- requireUser: true, // Require userId on requests
+ kind: "my-chat", // Unique identifier — becomes the URL path
+ requireUser: true, // Require userId on every request
actions: {
chat: {
@@ -22,35 +24,54 @@ const chatFlow = defineFlow({
block: chatPipeline,
userMessage: (input) => input.message,
},
+ reset: {
+ inputSchema: z.object({}),
+ block: resetHandler,
+ },
},
session: {
stateSchema: z.object({
messageCount: z.number().default(0),
}),
+ resources: {
+ artifacts: { stateSchema: artifactSchema, writable: true },
+ },
+ projections: {
+ messageCount: {
+ client: true,
+ compute: (ctx) => ctx.session.state.messageCount ?? 0,
+ },
+ },
+ },
+
+ user: {
+ stateSchema: z.object({
+ preferences: z.object({ theme: z.string().default("light") }).default({}),
+ }),
},
});
export default chatFlow({ id: "default" });
```
-## Flow Type vs Flow Instance
+## FlowType vs FlowInstance
-`defineFlow()` returns a **FlowType** — a factory function. Calling it with `{ id }` creates a **FlowInstance**:
+`defineFlow()` returns a **FlowType** — a factory. Calling it with `{ id }` creates a **FlowInstance** — the thing you actually register with the server:
```ts
-// FlowType — the factory
+// FlowType — the blueprint
const chatFlow = defineFlow({ kind: "my-chat", ... });
-// FlowInstance — what you register with the server
+// FlowInstance — what you register and deploy
export default chatFlow({ id: "default" });
```
-This separation lets you create multiple instances of the same flow type with different configurations.
+This separation lets you create multiple instances of the same flow type with different configurations if needed.
-## Actions
+## Actions — the flow's public API
-Actions are the entry points into a flow. Each action defines its input schema, the block to execute, and optional lifecycle hooks.
+Each action is an entry point that maps a name to an input schema and a root block. Clients call actions by name — that's the only way to trigger execution.
```ts
actions: {
@@ -59,11 +80,10 @@ actions: {
block: chatPipeline,
userMessage: (input) => input.message,
- // Lifecycle hooks
- onCompleted: async (result, ctx) => { /* ... */ },
- onErrored: async (error, ctx) => { /* ... */ },
+ // Lifecycle hooks — observe, don't control
+ onCompleted: async (result, ctx) => { /* succeeded */ },
+ onErrored: async (error, ctx) => { /* failed */ },
},
-
reset: {
inputSchema: z.object({}),
block: resetHandler,
@@ -71,16 +91,18 @@ actions: {
},
```
-When an action is executed:
+When an action executes:
1. Input is validated against `inputSchema`
2. Session is resolved or created
-3. `userMessage` is emitted as a user message item (if defined)
-4. The block executes asynchronously
+3. `userMessage(input)` emits a user message item (if defined)
+4. The root block executes asynchronously
5. Lifecycle hooks fire on completion or error
-## Session Configuration
+See [Actions](/docs/concepts/actions) for the full picture.
-Flows declare session-level state, resources, and projections:
+## Session configuration
+
+Sessions carry state, resources, and projections that persist across requests in a conversation:
```ts
session: {
@@ -110,12 +132,12 @@ session: {
See [State](/docs/concepts/state) for details on scopes, resources, and projections.
-## Lifecycle Hooks
+## Lifecycle hooks
-Both actions and requests support lifecycle hooks:
+Observe execution at both the action and request level:
```ts
-// Action-level hooks
+// Action-level
actions: {
chat: {
onCompleted: async (result, ctx) => { /* action succeeded */ },
@@ -123,17 +145,19 @@ actions: {
},
},
-// Request-level hooks
+// Request-level
request: {
onStarted: async (ctx) => { /* request began */ },
onCompleted: async (ctx) => { /* request succeeded */ },
onErrored: async (error, ctx) => { /* request failed */ },
- onFinished: async (ctx) => { /* always fires */ },
+ onFinished: async (ctx) => { /* always fires, success or failure */ },
onStepErrored: async (error, ctx) => { /* non-terminal step failure */ },
},
```
-## Flow Registration
+Hooks are **observational** — they run after the fact and can't modify the result. The past-tense naming (`onCompleted`, not `onComplete`) makes this intent clear.
+
+## Registration
Flows are registered with a server registry to be served via HTTP:
@@ -147,4 +171,4 @@ registry.register(agentFlow);
const router = createFlowApiRouter({ registry });
```
-The registry discovers flows by `kind` and routes requests to the right flow instance.
+The registry discovers flows by `kind` and routes requests automatically. Multiple flows can coexist in the same server.
diff --git a/apps/docs/docs/concepts/state.md b/apps/docs/docs/concepts/state.md
index 50ee942634..951c6ca0ef 100644
--- a/apps/docs/docs/concepts/state.md
+++ b/apps/docs/docs/concepts/state.md
@@ -4,43 +4,43 @@ sidebar_position: 4
# State Management
-Flow State Dev provides structured state management across four scope levels with typed operations, resources, and projections.
+State in AI applications is messy. Conversation history, user preferences, shared configuration, intermediate processing data — all at different lifetimes, all needing different isolation guarantees. flow-state.dev gives you four scoped levels with typed operations, resources for structured data, and projections to control exactly what the client can see.
## Scopes
State is organized into four hierarchical scopes:
-| Scope | Lifetime | Use For |
+| Scope | Lifetime | Example |
|-------|----------|---------|
-| **Request** | Single action execution | Temporary processing data |
-| **Session** | Across requests in a conversation | Chat history, current mode, plan state |
-| **User** | Across sessions for a user | Preferences, accumulated knowledge |
+| **Request** | Single action execution | Temporary processing data, intermediate results |
+| **Session** | Across requests in a conversation | Chat history, current mode, plan state, counters |
+| **User** | Across sessions for a user | Preferences, accumulated knowledge, model choices |
| **Project** | Across users in a project | Shared configuration, global data |
-Each scope has its own state, resources, and projections.
+Each scope has its own state, resources, and projections. Most of your state lives at the session level.
-## State Operations
+## State operations
-State is managed through scope handles in `BlockContext`:
+Every scope provides the same set of atomic operations via the block context:
```ts
execute: async (input, ctx) => {
- // Read state
+ // Read state — always available, always typed
const mode = ctx.session.state.mode;
- // Patch state (merge fields)
+ // Patch — merge fields into existing state
await ctx.session.patchState({ mode: "agent" });
- // Replace state entirely
+ // Replace — overwrite the entire state
await ctx.session.setState({ mode: "chat", count: 0 });
- // Increment numeric fields
+ // Increment — atomic numeric increment
await ctx.session.incState({ messageCount: 1 });
- // Push to array fields
+ // Push — append to array fields
await ctx.session.pushState({ history: newEntry });
- // Functional update
+ // Functional update — read-modify-write with CAS safety
await ctx.session.updateState((current) => ({
...current,
processedAt: Date.now(),
@@ -48,11 +48,11 @@ execute: async (input, ctx) => {
}
```
-All state operations use **CAS (Compare-and-Swap)** semantics — concurrent updates are retried automatically to prevent lost writes.
+All operations use **CAS (Compare-and-Swap)** semantics — if two blocks try to update the same state concurrently, one will automatically retry. No lost writes.
-## Defining State Schemas
+## Defining state schemas
-State schemas are declared in the flow definition:
+State schemas are declared at the flow level:
```ts
const myFlow = defineFlow({
@@ -67,23 +67,117 @@ const myFlow = defineFlow({
stateSchema: z.object({
preferences: z.object({
theme: z.enum(["light", "dark"]).default("dark"),
+ preferredModel: z.string().default("gpt-5-mini"),
}).default({}),
}),
},
});
```
-## Resources
+**Partial schemas** are the key pattern: each block declares only the state fields it needs, not the full flow-level schema. A counter block that only touches `messageCount` doesn't need to know about `mode`:
-Resources are named, schema-typed data containers attached to a scope. They're ideal for structured data that needs independent lifecycle from the main state:
+```ts
+const counter = handler({
+ name: "counter",
+ sessionStateSchema: z.object({ messageCount: z.number().default(0) }),
+ execute: async (input, ctx) => {
+ // ctx.session.state is typed as { messageCount: number } — inferred from the schema
+ await ctx.session.incState({ messageCount: 1 });
+ return input;
+ },
+});
+```
+
+Note that `ctx.session.state` is fully typed here — the framework infers types directly from your Zod schemas. You write a schema once and the input, output, state, and resources are all strongly typed throughout your `execute` function with no manual type annotations. See [Type System](/docs/concepts/type-system) for more on how this works across blocks, sequencers, and flows.
+
+This keeps blocks reusable and self-documenting about their dependencies.
+
+## State bubbling
+
+Here's the powerful part: you don't have to define every state field at the flow level. When a flow is constructed, block-level state declarations **bubble up** and merge into the flow's combined schema automatically.
+
+Say you have two blocks, each declaring the session state they need:
+
+```ts
+const counter = handler({
+ name: "counter",
+ sessionStateSchema: z.object({ messageCount: z.number().default(0) }),
+ execute: async (input, ctx) => {
+ await ctx.session.incState({ messageCount: 1 });
+ return input;
+ },
+});
+
+const modeSwitch = handler({
+ name: "mode-switch",
+ sessionStateSchema: z.object({ mode: z.enum(["chat", "agent"]).default("chat") }),
+ execute: async (input, ctx) => {
+ await ctx.session.patchState({ mode: "agent" });
+ return input;
+ },
+});
+```
+
+When these blocks are composed into a flow, their state declarations are collected and merged. The flow ends up with a combined session state of `{ messageCount: number, mode: "chat" | "agent" }` — without you having to repeat those fields in a flow-level `stateSchema`.
+
+You *can* still define a flow-level schema if you want one clean place to see everything:
+
+```ts
+defineFlow({
+ kind: "my-app",
+ session: {
+ stateSchema: z.object({
+ messageCount: z.number().default(0),
+ mode: z.enum(["chat", "agent"]).default("chat"),
+ }),
+ },
+ // ...
+});
+```
+
+But you don't have to. The flow-level schema only needs to define fields that aren't already declared by blocks — or fields that the flow configuration itself references (like in projections).
+
+### Why this matters
+
+The point is **blocks shouldn't depend on flows**. A counter block that needs `messageCount` declares it on itself. A mode-switching block declares `mode`. Neither needs to know about the other's state. Neither is coupled to a specific flow definition.
+
+This is what makes blocks truly portable:
+
+```ts
+// These blocks work in any flow — they bring their own state requirements
+import { counter } from "@shared/blocks";
+import { modeSwitch } from "@shared/blocks";
+
+const pipeline = sequencer({ name: "chat" })
+ .then(counter) // bubbles up { messageCount }
+ .then(modeSwitch) // bubbles up { mode }
+ .then(agent);
+```
+
+### Conflicts
+
+If two blocks declare the same field with incompatible types, the framework catches it as a type error during flow construction. This means schema conflicts surface early — at build time, not at runtime.
+
+For shared blocks used across codebases, the recommended practice is to namespace state fields (e.g., `analytics_eventCount` instead of `count`) to avoid collisions. Within a single codebase, consistent naming conventions are usually enough.
+
+## Resources — hybrid memory and filesystem
+
+Resources are more than key-value stores. Each resource combines **rich text content** with **structured atomic state** — think of them as files that carry metadata. This hybrid model gives your AI a persistent, typed workspace.
+
+Consider an artifacts resource: each artifact has a `content` field (the "file" — a document, code snippet, plan, or any rich text) alongside structured fields like `title`, `tags`, and `updatedAt` (the "metadata"). Both live in the same typed container with the same atomic operations:
```ts
session: {
resources: {
- plan: {
+ artifacts: {
stateSchema: z.object({
- steps: z.array(z.string()).default([]),
- status: z.enum(["draft", "active", "complete"]).default("draft"),
+ byId: z.record(z.object({
+ title: z.string(),
+ content: z.string(), // The "file" — rich text content
+ tags: z.array(z.string()), // Structured metadata
+ updatedAt: z.number(), // Structured metadata
+ })).default({}),
+ order: z.array(z.string()).default([]),
}),
writable: true,
},
@@ -91,51 +185,80 @@ session: {
}
```
-Access resources through scope handles:
+Access resources through scope handles — they have the same atomic operations as state:
```ts
-const plan = ctx.session.resources.plan;
-const steps = plan.state.steps;
-
-await plan.patchState({ status: "active" });
+const artifacts = ctx.session.resources.get("artifacts");
+
+// Read content and metadata together
+const doc = artifacts.state.byId["design-doc"];
+console.log(doc.content); // The full document text
+console.log(doc.tags); // ["architecture", "v2"]
+
+// Write with atomic state operations
+await artifacts.patchState({
+ byId: {
+ "design-doc": {
+ title: "Design Doc v2",
+ content: "# Architecture\n\nThe system is composed of...",
+ tags: ["architecture", "v2"],
+ updatedAt: Date.now(),
+ },
+ },
+ order: [...artifacts.state.order, "design-doc"],
+});
```
+Resources are scoped — session-level resources persist across requests in a conversation, user-level resources persist across sessions, project-level resources are shared across users. This gives you a natural hierarchy: scratch artifacts in a session, personal notes per user, shared knowledge bases per project.
+
## Projections
-Projections are derived views computed from state and resources. They're the **only way** to expose values to the client:
+Projections are derived views computed from state and resources. They're the **only way** to expose data to clients:
```ts
session: {
projections: {
- activePlan: {
- client: true, // Visible to the client
- compute: (ctx) => ctx.session.resources.plan?.state ?? null,
+ artifactsList: {
+ client: true, // Visible to the frontend
+ compute: (ctx) => {
+ const artifacts = ctx.session.resources.get("artifacts")?.state;
+ return artifacts?.order.map(id => ({
+ id,
+ title: artifacts.byId[id]?.title ?? "Untitled",
+ })) ?? [];
+ },
+ },
+ messageCount: {
+ client: true,
+ compute: (ctx) => ctx.session.state.messageCount ?? 0,
},
- messageCount: (ctx) => ctx.session.state.messageCount ?? 0,
},
}
```
-On the client side, read projections via `useProjections`:
+On the client, read projections via `useProjections`:
```tsx
const projections = useProjections(session, {
- session: ["activePlan", "messageCount"],
+ session: ["artifactsList", "messageCount"],
+ user: ["preferences"],
});
-// projections.session.activePlan → { steps: [...], status: "active" }
+// projections.session?.artifactsList → [{ id: "doc-1", title: "Design Doc" }]
```
-## Client Visibility
+## Why projections matter
-The client reads state through projections, not raw state. The state snapshot endpoint returns projections grouped by scope:
+Raw state never reaches the client. The state snapshot endpoint returns projections grouped by scope:
```json
{
"projections": {
- "session": { "activePlan": [...], "messageCount": 5 },
+ "session": { "artifactsList": [...], "messageCount": 5 },
"user": { "preferences": { "theme": "dark" } }
}
}
```
-During streaming, `state_change` and `resource_change` events signal that projections may be stale — the client refetches on `request.completed`.
+This is a deliberate architectural choice. Internal state — intermediate processing data, raw resource contents, block-specific fields — stays on the server. You decide exactly what the client sees by writing `compute` functions. Security by architecture, not by convention.
+
+During streaming, `state_change` and `resource_change` events signal that projections may be stale — the client refetches the authoritative snapshot on `request.completed`.
diff --git a/apps/docs/docs/concepts/streaming.md b/apps/docs/docs/concepts/streaming.md
index 746f2bda6e..354564459c 100644
--- a/apps/docs/docs/concepts/streaming.md
+++ b/apps/docs/docs/concepts/streaming.md
@@ -1,25 +1,25 @@
---
-sidebar_position: 5
+sidebar_position: 6
---
# Streaming
-Flow State Dev uses an **item-first streaming model** over Server-Sent Events (SSE). Instead of streaming raw text, the framework streams structured items — messages, tool calls, state changes, components — that clients render as they arrive.
+Most frameworks bolt streaming on as an afterthought — raw text over a WebSocket, maybe some SSE. flow-state.dev makes streaming structural. Instead of raw text, the framework streams **typed items**: messages, tool calls, state changes, reasoning, custom components. Each item has a lifecycle and a sequence number, so clients can disconnect and resume without losing a single event.
-## How Streaming Works
+## How it works
-When an action executes, the server creates a request stream. The client connects to it via SSE:
+When a client invokes an action, the server starts executing blocks and streaming results immediately:
```
-POST /api/flows/:kind/actions/:action → 202 { requestId }
-GET /api/flows/:kind/requests/:requestId/stream → SSE events
+POST /api/flows/:kind/actions/:action --> 202 { requestId }
+GET /api/flows/:kind/requests/:requestId/stream --> SSE events
```
-Events flow in real-time as blocks execute:
+Events flow in real time as blocks execute:
```
event: item.added
-data: { "item": { "type": "message", "role": "assistant", ... } }
+data: { "item": { "type": "message", "role": "assistant", "status": "in_progress" } }
event: content.delta
data: { "itemId": "msg_1", "delta": { "text": "Hello" } }
@@ -27,30 +27,37 @@ data: { "itemId": "msg_1", "delta": { "text": "Hello" } }
event: content.delta
data: { "itemId": "msg_1", "delta": { "text": " there!" } }
-event: request.status
+event: item.done
+data: { "item": { "type": "message", "role": "assistant", "status": "completed" } }
+
+event: request.completed
data: { "status": "completed" }
```
-## Item Types
+The client assembles content progressively from deltas. Text appears token by token. When the request completes, the client refetches the state snapshot for the authoritative final state.
+
+## Item types
+
+Every streamed event is a typed item. This means the client always knows what it's rendering:
-| Type | What It Is |
+| Type | What it is |
|------|-----------|
| `message` | Chat message (user or assistant) with content parts |
-| `reasoning` | Model reasoning/thinking (often hidden from end users) |
+| `reasoning` | Model reasoning/thinking tokens |
| `block_output` | Structured output from any block |
-| `component` | Custom UI component with props |
-| `container` | Groups child items for UI layout |
+| `component` | Custom UI component with typed props |
+| `container` | Groups child items for visual layout |
| `tool_call` | Tool invocation with arguments |
| `tool_result` | Tool execution result |
| `state_change` | State mutation notification |
| `resource_change` | Resource mutation notification |
| `step_error` | Non-terminal error in a pipeline step |
| `error` | Terminal request error |
-| `status` | Request lifecycle status |
+| `status` | Transient progress updates |
-## Content Model
+## Content model
-Message and reasoning items have a **content array** of typed parts:
+Message and reasoning items have a **content array** with typed parts:
```ts
{
@@ -63,45 +70,55 @@ Message and reasoning items have a **content array** of typed parts:
}
```
-Content is streamed via `content.delta` events — the client assembles the full content progressively.
+Content is assembled progressively from `content.delta` events — the framework handles buffering and assembly so you don't have to.
-## Resume and Replay
+## Resume and replay
-Every stream event has a **sequence number**. Clients can resume from where they left off:
+This is where flow-state.dev's streaming really shines. Every event has a **sequence number**. When a client disconnects — network blip, tab backgrounded, mobile app suspended — it can resume from exactly where it left off:
```
GET /api/flows/:kind/requests/:requestId/stream
Last-Event-ID: 42
```
-The server replays all events after sequence 42, then switches to live streaming. This makes reconnection seamless — no lost data.
+The server replays all events after sequence 42, then switches to live streaming. No data loss. No duplicate events. No application-level retry logic needed.
+
+You can also use the `starting_after` query parameter:
+
+```
+GET /api/flows/:kind/requests/:requestId/stream?starting_after=42
+```
-## Item Visibility
+## Item audiences
-Items have a `visibility` field:
+Not all items go everywhere. The framework uses type-based audience routing — each item type has a fixed audience:
-| Visibility | Meaning |
-|------------|---------|
-| `ui` | Shown to the user in the UI |
-| `internal` | Available in stream but not rendered by default |
-| `devtool` | Only visible in developer tools |
+| Audience | Item types |
+|----------|-----------|
+| **Client** | `message`, `reasoning`, `component`, `container`, `status`, `state_change`, `resource_change`, `error`, `step_error` |
+| **LLM** | `message`, `reasoning`, `context`, `block_output` |
+| **Internal** | `block_output` (devtools only unless it's a tool call) |
-Transient items (like in-progress content) are replaced by their final versions when the block completes.
+Generators access LLM-audience items via `session.items.llm()` — the framework automatically filters to items the model should see (messages, reasoning, context) and excludes UI-only items (status, components).
-## React Integration
+## React integration
-On the React side, streaming is automatic through hooks:
+On the React side, streaming is automatic. The `useSession` hook connects to the SSE stream, processes events, and updates items reactively:
```tsx
const session = useSession(sessionId);
-// session.items — all items from the current session
-// session.isStreaming — true while a request is active
-// session.messages — filtered to message items only
-
+// Items update in real time as the stream delivers them
{session.items.map((item) => (
))}
+
+// Filtered views
+{session.messages.map(...)} // Only message items
+{session.blockOutputs.map(...)} // Only block outputs
+
+// Status
+{session.isStreaming && }
```
-The `useSession` hook connects to the SSE stream, processes events, and updates items reactively. No manual stream management needed.
+No manual stream management. No event listeners. No reconnection logic. The hooks handle all of it.
diff --git a/apps/docs/docs/concepts/testing.md b/apps/docs/docs/concepts/testing.md
index c0d6098997..683b7e5f52 100644
--- a/apps/docs/docs/concepts/testing.md
+++ b/apps/docs/docs/concepts/testing.md
@@ -1,14 +1,14 @@
---
-sidebar_position: 6
+sidebar_position: 7
---
# Testing
-Flow State Dev includes a dedicated testing package with deterministic test harnesses for blocks, flows, and generators.
+LLMs aren't deterministic. But your tests should be. flow-state.dev ships a dedicated testing package that lets you write fully deterministic tests for blocks, pipelines, and complete flows — no real LLM calls, no network, no flaky tests.
-## Test Harnesses
+## Test harnesses
-### Testing a Block
+### Testing a block
```ts
import { handler } from "@flow-state-dev/core";
@@ -31,7 +31,7 @@ expect(result.output).toEqual({ counted: true });
expect(result.session.state.count).toBe(1);
```
-### Testing a Flow
+### Testing a flow end-to-end
```ts
import { testFlow } from "@flow-state-dev/testing";
@@ -47,12 +47,12 @@ const result = await testFlow({
},
});
-expect(result.items).toContainEqual(
- expect.objectContaining({ type: "message" })
-);
+const items = testItems(result.items);
+expect(items.messages()).not.toHaveLength(0);
+expect(result.status).toBe("completed");
```
-### Testing a Sequencer
+### Testing a sequencer
```ts
import { testSequencer } from "@flow-state-dev/testing";
@@ -66,36 +66,53 @@ const result = await testSequencer(pipeline, {
});
```
-## Mocking Generators
+## Mocking generators
-Generators call LLMs, which aren't deterministic. The testing package provides scripted mocks:
+The testing package replaces real LLM calls with scripted responses. You control exactly what the generator returns:
```ts
import { mockGenerator } from "@flow-state-dev/testing";
+// Simple: just the output
const mock = mockGenerator({
name: "chat-gen",
output: { response: "Mocked response" },
+});
+
+// With items: control what gets emitted to the stream
+const mock = mockGenerator({
+ name: "chat-gen",
+ output: "Mocked response",
items: [
{ type: "message", role: "assistant", content: [{ type: "text", text: "Mocked response" }] },
],
});
+
+// Scripted sequence: different responses for successive calls
+const mock = mockGenerator({
+ name: "chat-gen",
+ script: [
+ { text: "First response" },
+ { text: "Second response" },
+ ],
+});
```
-In test harnesses, mock generators by name:
+In test harnesses, pass mocks by generator name:
```ts
-const result = await testBlock(myBlock, {
+const result = await testBlock(myPipeline, {
input: { message: "hello" },
generators: {
- "chat-gen": { output: { response: "Mocked!" } },
+ "chat-gen": { output: "Mocked!" },
+ "summary-gen": { output: "Brief summary." },
},
});
```
-## Seeding State
+## Seeding state and resources
-All test harnesses support seeding scope state and resources:
+All test harnesses support seeding scoped state and resources to set up the scenario you want to test:
```ts
const result = await testFlow({
@@ -105,7 +122,7 @@ const result = await testFlow({
userId: "testuser",
seed: {
session: {
- state: { mode: "agent" },
+ state: { mode: "agent", messageCount: 5 },
resources: {
plan: { steps: ["step1"], status: "active" },
},
@@ -114,27 +131,30 @@ const result = await testFlow({
state: { preferredModel: "gpt-4o-mini" },
},
},
+ generators: {
+ "agent-gen": { output: "Done!" },
+ },
});
```
-## Item Assertions
+## Item assertions
-Use `testItems` for assertions on emitted items:
+Use `testItems` for expressive assertions on emitted items:
```ts
import { testItems } from "@flow-state-dev/testing";
const items = testItems(result.items);
-// Check item types
expect(items.messages()).toHaveLength(2);
expect(items.blockOutputs()).toHaveLength(1);
-expect(items.ofType("tool_call")).toHaveLength(3);
+expect(items.byType("tool_call")).toHaveLength(3);
+expect(items.byType("state_change")).not.toHaveLength(0);
```
-## Key Principles
+## What makes this different
-- **Deterministic** — Generator mocks ensure reproducible tests
-- **Isolated** — Each test harness creates an isolated runtime context with in-memory stores
-- **Framework-contract focused** — Test harnesses validate the same contracts the runtime enforces
-- **No network required** — Everything runs in-process with mocked LLM responses
+- **Deterministic** — Generator mocks produce the same output every time. No flaky tests from LLM variance.
+- **Isolated** — Each test harness creates a fresh runtime context with in-memory stores. No shared state between tests.
+- **Full-contract testing** — Test harnesses enforce the same validation, lifecycle, and execution contracts as the production runtime. If it passes in tests, it'll behave the same way in production.
+- **No network** — Everything runs in-process. No HTTP servers, no SSE connections, no external dependencies.
diff --git a/apps/docs/docs/concepts/type-system.md b/apps/docs/docs/concepts/type-system.md
new file mode 100644
index 0000000000..577a0504d1
--- /dev/null
+++ b/apps/docs/docs/concepts/type-system.md
@@ -0,0 +1,231 @@
+---
+sidebar_position: 5
+---
+
+# Type System
+
+Most TypeScript frameworks ask you to manage types alongside your code — writing interfaces, casting generics, wiring type parameters through layers. flow-state.dev takes a different approach: **you write a Zod schema, and the framework infers everything from it.** Input types, output types, state types, resource types, context types — all derived automatically, all the way through.
+
+The goal is to minimize type gymnastics. Your code should be easy to read and reason about, not cluttered with manual type annotations.
+
+## Schema in, types out
+
+When you provide a schema to a block, the framework uses `z.infer<>` to extract TypeScript types and thread them through the entire API surface:
+
+```ts
+const processOrder = handler({
+ name: "process-order",
+ inputSchema: z.object({ orderId: z.string(), quantity: z.number() }),
+ outputSchema: z.object({ total: z.number(), confirmed: z.boolean() }),
+ sessionStateSchema: z.object({ orderCount: z.number().default(0) }),
+
+ execute: async (input, ctx) => {
+ // input is typed as { orderId: string; quantity: number }
+ // ctx.session.state is typed as { orderCount: number }
+ await ctx.session.incState({ orderCount: 1 });
+
+ // Return type must match outputSchema — { total: number; confirmed: boolean }
+ return { total: input.quantity * 9.99, confirmed: true };
+ },
+});
+```
+
+You didn't write a single type annotation. The Zod schemas are the single source of truth — they define the runtime validation AND the compile-time types. If you return the wrong shape from `execute`, TypeScript catches it. If you access a state field that doesn't exist, TypeScript catches it.
+
+## Types flow through sequencers
+
+The sequencer DSL tracks types through the chain. Each `.then()` captures the output schema of the current step and threads it as the input type of the next:
+
+```ts
+const pipeline = sequencer({ name: "pipeline" })
+ .then(parseInput) // output: { query: string, filters: Filter[] }
+ .then(searchDocs) // input: ↑ that type. output: SearchResult[]
+ .then(rankResults) // input: SearchResult[]. output: RankedResult[]
+ .map((results) => // results is typed as RankedResult[]
+ results.slice(0, 10)
+ );
+// pipeline output type: RankedResult[]
+```
+
+If `searchDocs` expects a different input shape than what `parseInput` produces, TypeScript flags it immediately. The fix is a connector — a one-line transform function between steps:
+
+```ts
+.then(
+ (output) => ({ query: output.query, limit: 10 }), // connector
+ searchDocs
+)
+```
+
+The connector's return type must match `searchDocs`'s input schema. TypeScript enforces this at compile time.
+
+## Parallel steps produce typed objects
+
+When you use `.parallel()`, the output is a typed object with a key for each named step:
+
+```ts
+const enriched = sequencer({ name: "enrich" })
+ .then(parseQuery)
+ .parallel({
+ web: searchWeb, // output: WebResult[]
+ docs: searchDocs, // output: DocResult[]
+ memory: searchMemory, // output: MemoryResult[]
+ })
+ // output type: { web: WebResult[], docs: DocResult[], memory: MemoryResult[] }
+ .then((results) => {
+ // results.web, results.docs, results.memory — all typed
+ return merge(results.web, results.docs, results.memory);
+ });
+```
+
+## State and resources are typed per-block
+
+Each block declares only the state it needs, and the context is typed accordingly. A block that declares `sessionStateSchema` gets a `ctx.session.state` typed to exactly those fields — nothing more:
+
+```ts
+const analytics = handler({
+ name: "analytics",
+ sessionStateSchema: z.object({
+ eventCount: z.number().default(0),
+ lastEventAt: z.number().optional(),
+ }),
+ execute: async (input, ctx) => {
+ ctx.session.state.eventCount; // number — typed
+ ctx.session.state.lastEventAt; // number | undefined — typed
+ ctx.session.state.somethingElse; // TypeScript error — not in schema
+
+ await ctx.session.patchState({ lastEventAt: Date.now() });
+ return input;
+ },
+});
+```
+
+The same applies to resources. Declare a resource schema and `ctx.session.resources` is typed with the correct handles:
+
+```ts
+const docReader = handler({
+ name: "doc-reader",
+ sessionResourceSchemas: z.object({
+ documents: z.object({
+ stateSchema: z.object({
+ byId: z.record(z.object({ title: z.string(), content: z.string() })),
+ }),
+ }),
+ }),
+ execute: async (input, ctx) => {
+ // ctx.session.resources.documents.state.byId — fully typed
+ const doc = ctx.session.resources.documents.state.byId["doc-1"];
+ return doc.content; // string
+ },
+});
+```
+
+## Generators infer tool types
+
+When you pass blocks as tools to a generator, the framework compiles their schemas into the model's tool format automatically. The tool's `inputSchema` becomes the function parameters the model sees, and the `outputSchema` types the result fed back into the conversation:
+
+```ts
+const search = handler({
+ name: "search",
+ inputSchema: z.object({ query: z.string(), limit: z.number().default(5) }),
+ outputSchema: z.array(z.object({ title: z.string(), url: z.string() })),
+ execute: async (input) => { /* ... */ },
+});
+
+const agent = generator({
+ name: "agent",
+ tools: [search], // schema is compiled to model tool format automatically
+ // ...
+});
+```
+
+No manual tool definition objects. No duplicating parameter schemas. The block IS the tool.
+
+## Flow-level inference
+
+At the flow level, `defineFlow` infers state types from scope configurations and makes them available to projections:
+
+```ts
+const myFlow = defineFlow({
+ kind: "my-app",
+ session: {
+ stateSchema: z.object({ mode: z.string(), count: z.number() }),
+ resources: {
+ docs: { stateSchema: z.object({ byId: z.record(docSchema) }) },
+ },
+ projections: {
+ summary: {
+ client: true,
+ compute: (ctx) => {
+ // ctx.session.state — typed as { mode: string; count: number }
+ // ctx.session.resources.docs.state.byId — typed as Record
+ return { mode: ctx.session.state.mode, docCount: Object.keys(ctx.session.resources.docs.state.byId).length };
+ },
+ },
+ },
+ },
+ // ...
+});
+```
+
+## What you don't have to write
+
+Here's what the framework infers so you don't have to:
+
+| You provide | Framework infers |
+|-------------|-----------------|
+| `inputSchema` | `execute(input)` parameter type |
+| `outputSchema` | `execute()` return type |
+| `sessionStateSchema` | `ctx.session.state` type |
+| `userStateSchema` | `ctx.user.state` type |
+| `sessionResourceSchemas` | `ctx.session.resources.*` handle types |
+| Block in `.then()` | Next step's input type |
+| Block in `tools` | Model tool parameters and result type |
+| Scope `stateSchema` in flow | Projection `compute(ctx)` types |
+
+The pattern is always the same: **Zod schema in, TypeScript types out.** One source of truth. No drift between runtime validation and compile-time checking.
+
+## Extracting types when you need them
+
+In most cases you never need to think about types — you write schemas, and `execute` just works. But sometimes you need a block's inferred type outside of the block itself — maybe for a utility function, a shared interface, or a connector. The framework exports type helpers so you never have to manage types manually:
+
+```ts
+import { type BlockInput, type BlockOutput, type StateOf } from "@flow-state-dev/core";
+
+const search = handler({
+ name: "search",
+ inputSchema: z.object({ query: z.string(), limit: z.number() }),
+ outputSchema: z.array(z.object({ title: z.string(), url: z.string() })),
+ sessionStateSchema: z.object({ searchCount: z.number().default(0) }),
+ execute: async (input, ctx) => { /* ... */ },
+});
+
+// Extract types directly from the block — no duplication
+type SearchInput = BlockInput; // { query: string; limit: number }
+type SearchOutput = BlockOutput; // { title: string; url: string }[]
+```
+
+For state and resource schemas:
+
+```ts
+import { type StateOf, type ContextOf } from "@flow-state-dev/core";
+
+const docResource = defineResource({
+ stateSchema: z.object({
+ byId: z.record(z.object({ title: z.string(), content: z.string() })),
+ }),
+});
+
+type DocState = StateOf; // { byId: Record }
+```
+
+### Available type helpers
+
+| Helper | Extracts |
+|--------|----------|
+| `BlockInput` | Inferred input type from `inputSchema` |
+| `BlockOutput` | Inferred output type from `outputSchema` |
+| `StateOf` | State type from a schema, resource, or scope config |
+| `ContextOf` | Context handle type for a scope or resource |
+| `ResourceContext` | Resource context type |
+
+These all use `typeof` on your existing definitions — the block or resource is the single source of truth, and you derive types from it rather than maintaining them separately.
diff --git a/apps/docs/docs/getting-started/installation.md b/apps/docs/docs/getting-started/installation.md
index 9f208cc7b6..83fcbb352d 100644
--- a/apps/docs/docs/getting-started/installation.md
+++ b/apps/docs/docs/getting-started/installation.md
@@ -6,7 +6,7 @@ sidebar_position: 2
## Packages
-Flow State Dev is distributed as separate packages. Install what you need:
+flow-state.dev is distributed as separate packages. Install what you need:
```bash
# Core (required) — block builders, flow definitions, types
@@ -44,7 +44,7 @@ The `react` package depends on `client` internally — you don't need to install
## TypeScript
-Flow State Dev is written in TypeScript and ships type definitions. For best results:
+flow-state.dev is written in TypeScript and ships type definitions. For best results:
- TypeScript `^5.7`
- Enable `strict` mode in your `tsconfig.json`
diff --git a/apps/docs/docs/getting-started/project-structure.md b/apps/docs/docs/getting-started/project-structure.md
index c0a677db0c..4c4df6b984 100644
--- a/apps/docs/docs/getting-started/project-structure.md
+++ b/apps/docs/docs/getting-started/project-structure.md
@@ -4,7 +4,7 @@ sidebar_position: 3
# Project Structure
-How to organize your Flow State Dev project.
+How to organize your flow-state.dev project.
## Recommended Layout
diff --git a/apps/docs/docs/getting-started/quick-start.md b/apps/docs/docs/getting-started/quick-start.md
index 6ca0b9015e..82260a38b2 100644
--- a/apps/docs/docs/getting-started/quick-start.md
+++ b/apps/docs/docs/getting-started/quick-start.md
@@ -4,69 +4,80 @@ sidebar_position: 1
# Quick Start
-Build your first flow in 5 minutes. This guide walks you through defining a simple chat flow, setting up the server, and connecting a React frontend.
+Build a streaming chat app in 5 minutes. By the end, you'll have an LLM-powered chat with conversation history, session state, and a React UI — all type-safe, all streaming.
## Prerequisites
- Node.js >= 18 (Node 20+ recommended)
- pnpm (or npm/yarn)
-## 1. Install Packages
+## 1. Install packages
```bash
pnpm add @flow-state-dev/core @flow-state-dev/server @flow-state-dev/client @flow-state-dev/react zod
```
-## 2. Define a Flow
+## 2. Define your flow
-Create a file for your flow definition:
+This is where you describe what your AI does. A generator calls the LLM. A handler tracks state. A sequencer wires them together. `defineFlow` makes it deployable.
```ts title="src/flows/hello-chat/flow.ts"
-import { defineFlow, generator, sequencer } from "@flow-state-dev/core";
+import { defineFlow, generator, handler, sequencer } from "@flow-state-dev/core";
import { z } from "zod";
-// Define a generator block for LLM interaction
+const inputSchema = z.object({ message: z.string() });
+
+// Generator: calls the LLM with conversation history
const chatGen = generator({
name: "chat",
model: "gpt-5-mini",
prompt: "You are a helpful assistant.",
- inputSchema: z.object({ message: z.string() }),
+ inputSchema,
+ history: (_input, ctx) => ctx.session.items.llm(),
user: (input) => input.message,
});
-// Create a pipeline
-const pipeline = sequencer({
- name: "chat-pipeline",
- inputSchema: z.object({ message: z.string() }),
-}).then(chatGen);
+// Handler: increments a message counter after each exchange
+const counter = handler({
+ name: "counter",
+ inputSchema: z.string(),
+ outputSchema: z.string(),
+ sessionStateSchema: z.object({ messageCount: z.number().default(0) }),
+ execute: async (input, ctx) => {
+ await ctx.session.incState({ messageCount: 1 });
+ return input;
+ },
+});
-// Define and export the flow
+// Pipeline: generator → counter
+const pipeline = sequencer({ name: "chat-pipeline", inputSchema })
+ .then(chatGen)
+ .then(counter);
+
+// Flow definition
const chatFlow = defineFlow({
kind: "hello-chat",
+ requireUser: true,
actions: {
chat: {
- inputSchema: z.object({ message: z.string() }),
+ inputSchema,
block: pipeline,
userMessage: (input) => input.message,
},
},
session: {
- stateSchema: z.object({}),
+ stateSchema: z.object({ messageCount: z.number().default(0) }),
},
});
export default chatFlow({ id: "default" });
```
-**What's happening here:**
-- `generator` creates an LLM-calling block with a prompt and input schema
-- `sequencer` chains blocks into a pipeline
-- `defineFlow` declares the flow with its actions and session config
-- The final `chatFlow({ id: "default" })` creates a flow instance
+**What's happening:** The generator handles the LLM call — prompt assembly, streaming, conversation history. The handler is a pure function that bumps a counter. The sequencer pipes the generator's output into the handler. `defineFlow` wraps it all with actions, session state, and lifecycle management.
-## 3. Set Up the Server
+## 3. Set up the server
-Create an API route that registers your flow and handles requests:
+One catch-all route gives you a complete API with SSE streaming:
```ts title="app/api/flows/[...path]/route.ts"
import { createFlowRegistry, createFlowApiRouter } from "@flow-state-dev/server";
@@ -82,9 +93,11 @@ export const POST = router.POST;
export const DELETE = router.DELETE;
```
-This gives you a full REST API with SSE streaming at `/api/flows/`.
+That's it. You now have action execution, session management, SSE streaming with resume, and state snapshots at `/api/flows/`.
+
+## 4. Connect the React frontend
-## 4. Connect the React Frontend
+The hooks handle streaming, reconnection, and state sync. You just render:
```tsx title="src/app/page.tsx"
import { FlowProvider, ItemRenderer, useFlow, useSession } from "@flow-state-dev/react";
@@ -117,7 +130,7 @@ function ChatUI() {
>
@@ -125,27 +138,25 @@ function ChatUI() {
}
```
-**What's happening here:**
-- `FlowProvider` sets up the flow context with `flowKind` and `userId`
-- `useFlow` manages session lifecycle (creates one automatically)
-- `useSession` provides items, streaming status, and `sendAction`
-- `ItemRenderer` renders each streamed item using registered renderers
+**What's happening:** `FlowProvider` sets up the flow context. `useFlow` creates a session automatically. `useSession` gives you live-updating items, streaming status, and `sendAction`. `ItemRenderer` renders each streamed item. The framework handles SSE connection, reconnection, and state sync behind the scenes.
-## 5. Run It
+## 5. Run it
```bash
pnpm dev
```
-Open your browser and start chatting. The framework handles:
-- Action dispatch and validation
-- SSE streaming with automatic reconnection
-- Session state persistence
+Open your browser and start chatting. The framework is handling:
+- Input validation against your Zod schema
+- Action dispatch and async block execution
+- SSE streaming with automatic reconnection and resume
+- Session state persistence across requests
+- Conversation history assembly for the LLM
- Item rendering in the UI
-## Next Steps
+## Next steps
-- [Installation](/docs/getting-started/installation) — Package options and configuration
-- [Project Structure](/docs/getting-started/project-structure) — How to organize your flow project
-- [Concepts: Blocks](/docs/concepts/blocks) — Deep dive into the four block kinds
-- [Guide: Building a Chat App](/docs/guides/building-a-chat-app) — Complete walkthrough with state, tools, and UI
+- **[Installation](/docs/getting-started/installation)** — Package options, peer dependencies, TypeScript config
+- **[Project Structure](/docs/getting-started/project-structure)** — How to organize flows, blocks, and tools
+- **[Blocks](/docs/concepts/blocks)** — Deep dive into handler, generator, sequencer, and router
+- **[Building a Chat App](/docs/guides/building-a-chat-app)** — Full walkthrough with state, projections, tools, and tests
diff --git a/apps/docs/docs/guides/building-a-chat-app.md b/apps/docs/docs/guides/building-a-chat-app.md
index 247b0ef728..3695b61493 100644
--- a/apps/docs/docs/guides/building-a-chat-app.md
+++ b/apps/docs/docs/guides/building-a-chat-app.md
@@ -4,19 +4,20 @@ sidebar_position: 1
# Building a Chat App
-This guide walks you through building a complete chat application with Flow State Dev — from flow definition to React UI.
+This guide walks you through building a complete chat application — from blocks to React UI to deterministic tests. Along the way, you'll see how conversation history, session state, projections, and streaming fit together.
-## What We're Building
+## What we're building
-A chat app with:
-- LLM-powered responses via a generator block
-- Message counting via a handler block
-- Session state persistence
-- Streaming responses in a React UI
+A chat app where:
+- An LLM generates responses via a generator block
+- A handler tracks message count in session state
+- A projection exposes the count to the React UI
+- Items stream to the frontend in real time
+- Tests run deterministically with mocked generators
-## 1. Define the Blocks
+## 1. Define the blocks
-### Generator Block
+### The generator — talks to the LLM
```ts title="src/flows/hello-chat/blocks/chat-gen.ts"
import { generator } from "@flow-state-dev/core";
@@ -27,11 +28,14 @@ export const chatGen = generator({
model: "gpt-5-mini",
prompt: "You are a helpful assistant. Be concise and friendly.",
inputSchema: z.object({ message: z.string() }),
+ history: (_input, ctx) => ctx.session.items.llm(),
user: (input) => input.message,
});
```
-### Counter Handler
+The `history` slot loads prior conversation from persisted request items. `session.items.llm()` returns completed messages in `{role, content}` format — the framework handles filtering and formatting. The `user` slot extracts the current message from input.
+
+### The handler — tracks usage
```ts title="src/flows/hello-chat/blocks/counter.ts"
import { handler } from "@flow-state-dev/core";
@@ -49,7 +53,9 @@ export const counter = handler({
});
```
-## 2. Compose the Pipeline
+Notice the **partial state schema** — this handler only declares `messageCount`. It doesn't need to know about any other session state fields. `incState` is an atomic increment — safe even under concurrent requests.
+
+## 2. Compose the pipeline and flow
```ts title="src/flows/hello-chat/flow.ts"
import { defineFlow, sequencer } from "@flow-state-dev/core";
@@ -57,10 +63,9 @@ import { z } from "zod";
import { chatGen } from "./blocks/chat-gen";
import { counter } from "./blocks/counter";
-const pipeline = sequencer({
- name: "chat-pipeline",
- inputSchema: z.object({ message: z.string() }),
-})
+const inputSchema = z.object({ message: z.string() });
+
+const pipeline = sequencer({ name: "chat-pipeline", inputSchema })
.then(chatGen)
.then(counter);
@@ -70,7 +75,7 @@ const chatFlow = defineFlow({
actions: {
chat: {
- inputSchema: z.object({ message: z.string() }),
+ inputSchema,
block: pipeline,
userMessage: (input) => input.message,
},
@@ -93,12 +98,12 @@ const chatFlow = defineFlow({
export default chatFlow({ id: "default" });
```
-**What this does:**
-- The sequencer chains `chatGen` → `counter`, so every chat message gets an LLM response and increments the count
-- `userMessage: (input) => input.message` emits the user's input as a visible message item
-- The `messageCount` projection exposes the count to the React UI
+Key details:
+- The sequencer chains `chatGen` then `counter` — every message gets an LLM response and increments the count
+- `userMessage: (input) => input.message` tells the framework to emit a user-role message item before execution, so the conversation stream shows what the user said
+- The `messageCount` projection exposes the count to the React UI — this is the *only* way the client sees this value
-## 3. Set Up the Server
+## 3. Set up the server
```ts title="app/api/flows/[...path]/route.ts"
import { createFlowRegistry, createFlowApiRouter } from "@flow-state-dev/server";
@@ -114,6 +119,8 @@ export const POST = router.POST;
export const DELETE = router.DELETE;
```
+Three lines of setup. You now have action execution, session management, SSE streaming, and state snapshots.
+
## 4. Build the React UI
```tsx title="src/components/ChatApp.tsx"
@@ -157,7 +164,7 @@ function ChatUI() {
@@ -173,7 +180,7 @@ function ChatUI() {
autoComplete="off"
/>
@@ -181,13 +188,20 @@ function ChatUI() {
}
```
-## 5. Test It
+What each hook does:
+- `useFlow({ autoCreateSession: true })` — creates a session on mount, tracks the active session ID
+- `useSession(id, { items: { visibility: "ui" } })` — connects to the SSE stream, delivers items in real time, provides `sendAction` and `isStreaming`
+- `useProjections(session, { session: ["messageCount"] })` — reads the `messageCount` projection from the latest state snapshot
+
+## 5. Write tests
+
+No real LLM calls. No network. Deterministic results:
```ts title="src/flows/hello-chat/__tests__/flow.test.ts"
import { testFlow } from "@flow-state-dev/testing";
import chatFlow from "../flow";
-test("chat action increments message count", async () => {
+test("chat action streams a response and increments count", async () => {
const result = await testFlow({
flow: chatFlow,
action: "chat",
@@ -198,15 +212,43 @@ test("chat action increments message count", async () => {
},
});
- expect(result.session.state.messageCount).toBe(1);
+ // User message was emitted
expect(result.items).toContainEqual(
expect.objectContaining({ type: "message", role: "user" })
);
+
+ // Assistant message was emitted
+ expect(result.items).toContainEqual(
+ expect.objectContaining({ type: "message", role: "assistant" })
+ );
+
+ // State was updated
+ expect(result.session.state.messageCount).toBe(1);
+});
+
+test("message count accumulates across requests", async () => {
+ const result = await testFlow({
+ flow: chatFlow,
+ action: "chat",
+ input: { message: "Second message" },
+ userId: "testuser",
+ seed: {
+ session: { state: { messageCount: 3 } },
+ },
+ generators: {
+ chat: { output: "Response" },
+ },
+ });
+
+ expect(result.session.state.messageCount).toBe(4);
});
```
-## Next Steps
+The test harness creates an isolated runtime with in-memory stores, mocks the generator, and executes the full action pipeline — validation, session resolution, block execution, state persistence, lifecycle hooks. Same contracts as production.
+
+## Next steps
-- Add [custom renderers](/docs/guides/react-integration) for message styling
-- Add tools to the generator for [function calling](/docs/concepts/blocks#generator)
-- Use [sequencer patterns](/docs/guides/sequencer-patterns) for branching and error recovery
+- Add **[custom renderers](/docs/guides/react-integration)** to style messages, reasoning, and components
+- Add **tools** to the generator for [function calling](/docs/concepts/blocks#generator--the-ai-block) (search, create artifacts, etc.)
+- Use **[sequencer patterns](/docs/guides/sequencer-patterns)** for conditional logic, parallelism, and error recovery
+- Add **resources and projections** for richer state — see the [kitchen-sink example](https://github.com/flow-state-dev/flow-state-dev) for a full demonstration
diff --git a/apps/docs/docs/guides/react-integration.md b/apps/docs/docs/guides/react-integration.md
index 1e7f00d117..9db63c71e9 100644
--- a/apps/docs/docs/guides/react-integration.md
+++ b/apps/docs/docs/guides/react-integration.md
@@ -4,7 +4,7 @@ sidebar_position: 3
# React Integration
-How to use Flow State Dev's React bindings to build interactive UIs.
+How to use flow-state.dev's React bindings to build interactive UIs.
## FlowProvider
diff --git a/apps/docs/docs/guides/server-setup.md b/apps/docs/docs/guides/server-setup.md
index 79c7708727..e5f7b1ab0b 100644
--- a/apps/docs/docs/guides/server-setup.md
+++ b/apps/docs/docs/guides/server-setup.md
@@ -4,7 +4,7 @@ sidebar_position: 2
# Server Setup
-How to configure the Flow State Dev server runtime in your application.
+How to configure the flow-state.dev server runtime in your application.
## Basic Setup
diff --git a/apps/docs/docs/intro.md b/apps/docs/docs/intro.md
index f219f75699..a98f32cb78 100644
--- a/apps/docs/docs/intro.md
+++ b/apps/docs/docs/intro.md
@@ -3,45 +3,110 @@ sidebar_position: 1
slug: /intro
---
-# Introduction
+# Why flow-state.dev?
-Flow State Dev is a block-based AI workflow framework for TypeScript. It gives you typed building blocks for AI interactions, composable pipelines, resumable streaming, and scoped state management — all with one type system from server to UI.
+Every AI feature needs the same infrastructure: call an LLM, stream the response, manage state across turns, handle errors gracefully, sync everything to the UI. Teams rebuild this from scratch every time — ad-hoc orchestration, hand-rolled SSE, application-specific retry logic, state scattered across closures and databases.
-## Why Flow State Dev?
+flow-state.dev makes these concerns **framework primitives**. You write the logic that matters. The framework handles everything else.
-Building AI features typically means stitching together orchestration, retries, streaming, state, and UI rendering in application-specific ways. Flow State Dev makes these concerns first-class framework primitives:
+## What it looks like
-- **Typed blocks** — Define handlers, generators, sequencers, and routers with input/output schemas that are validated at runtime and inferred at compile time.
-- **Composable flows** — Chain blocks into pipelines with branching, parallelism, error recovery, and background work using a fluent DSL.
-- **Resumable streaming** — Item-first SSE streaming with sequence-number replay. Clients reconnect mid-stream without losing data.
-- **Scoped state** — Four scope levels (request, session, user, project) with typed state operations, resources, and projections.
-- **Full-stack TypeScript** — One type system across server execution, client transport, and React UI. Schemas defined once, validated everywhere.
+```ts
+import { defineFlow, generator, handler, sequencer } from "@flow-state-dev/core";
-## How It Works
+const chat = generator({
+ name: "chat",
+ model: "gpt-5-mini",
+ prompt: "You are a helpful assistant.",
+ history: (_input, ctx) => ctx.session.items.llm(),
+ user: (input) => input.message,
+ tools: [searchDocs, createArtifact],
+});
-A **flow** is the top-level unit. It declares **actions** (entry points) that execute **blocks** (the runtime units). Blocks come in four kinds:
+const pipeline = sequencer({ name: "pipeline" })
+ .then(chat)
+ .then(trackUsage)
+ .rescue([{ when: [ModelError], block: fallback }]);
-| Block | Purpose |
-|-------|---------|
-| **Handler** | Synchronous logic — validation, state updates, transformations |
-| **Generator** | LLM calls with tool loops, structured output, and streaming |
-| **Sequencer** | Pipeline composition — chaining, branching, parallelism |
-| **Router** | Runtime block selection based on input or state |
+export default defineFlow({
+ kind: "my-app",
+ actions: { chat: { block: pipeline, userMessage: (i) => i.message } },
+ session: { stateSchema, resources, projections },
+})({ id: "default" });
+```
-Blocks compose into pipelines via the **sequencer DSL**. Pipelines execute on the **server**, stream results to the **client** via SSE, and render in **React** through hooks and renderers.
+That gives you: streaming over SSE with resume, conversation history, tool loops, atomic state operations, typed projections to the client, error recovery, and lifecycle hooks. From that one definition.
-## Package Overview
+## What you get
-| Package | Purpose |
-|---------|---------|
-| `@flow-state-dev/core` | Block builders, flow definitions, type contracts |
-| `@flow-state-dev/server` | Action runtime, stores, SSE streaming |
-| `@flow-state-dev/client` | HTTP/SSE transport client (no React dependency) |
-| `@flow-state-dev/react` | React hooks, renderers, context providers |
-| `@flow-state-dev/testing` | Test harnesses for blocks, flows, generators |
+### Four block primitives
-## Next Steps
+Every piece of logic — calling an LLM, validating input, choosing a path, composing a pipeline — is one of exactly four block kinds:
-- [Quick Start](/docs/getting-started/quick-start) — Build your first flow in 5 minutes
-- [Concepts](/docs/concepts/blocks) — Understand the core abstractions
-- [Guides](/docs/guides/building-a-chat-app) — Build a complete chat application
+| Block | What it does | When to reach for it |
+|-------|-------------|---------------------|
+| **Handler** | Pure logic: validate, transform, mutate state | Data processing, state updates, tool implementations |
+| **Generator** | LLM calls with managed tool loops and streaming | Chat, extraction, any AI generation |
+| **Sequencer** | Compose blocks into pipelines | Multi-step workflows with branching, parallelism, error recovery |
+| **Router** | Dispatch to different pipelines at runtime | Mode switching, intent routing, conditional flows |
+
+All blocks share the same contract: `block.run(input, ctx)`. Any block composes with any other block — and any block or sequence of blocks can be used as a tool. That means a single tool call can trigger a handler, a multi-step sequencer pipeline, or even a router that dispatches to different strategies. Your AI's tools can be as simple or as sophisticated as any other part of your workflow.
+
+### Flows are full APIs
+
+Define a flow, register it with the server, and you have a complete REST API — action execution, session management, SSE streaming, state snapshots — with zero route wiring. Every flow you register becomes instantly callable from any client:
+
+```
+POST /api/flows/my-app/actions/chat → Execute an action
+GET /api/flows/my-app/requests/:id/stream → Stream results via SSE
+GET /api/flows/sessions/:id/state → State snapshot with projections
+```
+
+Multiple flows can coexist in the same server. Each one is self-contained with its own actions, state, and resources.
+
+### Resumable streaming
+
+Items stream over SSE as blocks execute — messages, reasoning, tool calls, state changes, custom components. Every event has a sequence number. Disconnect mid-response? Reconnect with a cursor and pick up exactly where you left off. No data loss. No duplicates. No manual SSE plumbing.
+
+### Scoped state that scales
+
+Four isolation levels with atomic operations:
+
+| Scope | Lifetime | Example |
+|-------|----------|---------|
+| **Request** | Single action execution | Temporary processing data |
+| **Session** | Across requests in a conversation | Chat history, mode, counters |
+| **User** | Across sessions for a user | Preferences, accumulated knowledge |
+| **Project** | Shared across users | Configuration, global data |
+
+Each block declares only the state fields it needs via partial schemas. A counter block doesn't need to know about a preferences block's state.
+
+### Resources: hybrid memory and filesystem
+
+**Resources** are more than key-value stores. Each resource combines rich text content with structured atomic state — like a file that carries metadata. An artifact resource can hold a document's full text alongside its title, tags, and timestamps, all in one typed container with atomic operations. Scoped to sessions, users, or projects, resources give your AI a persistent, typed workspace.
+
+**Projections** are derived views computed from state and resources, and the *only* way to expose data to clients. You can't accidentally leak internal state because projections are the sole data gateway.
+
+### Built for an ecosystem
+
+Blocks and flows are portable by design. A tool block, a validation handler, a complete agentic workflow — each is a self-contained unit with typed inputs, outputs, and declared state dependencies. Share them across projects or publish them as packages. The uniform block contract means community blocks compose with yours without adapters or glue code.
+
+### Full-stack type safety
+
+Define a Zod schema once. 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. No code generation step.
+
+## The full stack
+
+| Package | What it does |
+|---------|-------------|
+| [`@flow-state-dev/core`](/docs/api/core) | Block builders, flow definitions, type contracts |
+| [`@flow-state-dev/server`](/docs/api/server) | Execution runtime, stores, SSE streaming, HTTP routes |
+| [`@flow-state-dev/client`](/docs/api/client) | Isomorphic API client — works in Node, browser, edge |
+| [`@flow-state-dev/react`](/docs/api/react) | React hooks and renderers — wraps client, no transport logic |
+| [`@flow-state-dev/testing`](/docs/api/testing) | Deterministic test harnesses with generator mocks |
+
+## Next steps
+
+- **[Quick Start](/docs/getting-started/quick-start)** — Build a streaming chat app in 5 minutes
+- **[Blocks](/docs/concepts/blocks)** — Deep dive into the four primitives
+- **[Building a Chat App](/docs/guides/building-a-chat-app)** — Complete walkthrough from blocks to React UI to tests
diff --git a/apps/docs/docusaurus.config.ts b/apps/docs/docusaurus.config.ts
index f09ec556a3..7d51ed82d1 100644
--- a/apps/docs/docusaurus.config.ts
+++ b/apps/docs/docusaurus.config.ts
@@ -3,11 +3,11 @@ import type { Config } from "@docusaurus/types";
import type * as Preset from "@docusaurus/preset-classic";
const config: Config = {
- title: "Flow State Dev",
- tagline: "Block-based AI workflow framework for TypeScript",
+ title: "flow-state.dev",
+ tagline: "Composable AI workflows for TypeScript. Blocks in. Streaming out.",
favicon: "img/favicon.ico",
- url: "https://flowstatedev.com",
+ url: "https://flow-state.dev",
baseUrl: "/",
organizationName: "flow-state-dev",
@@ -49,7 +49,7 @@ const config: Config = {
themeConfig: {
navbar: {
- title: "Flow State Dev",
+ title: "flow-state.dev",
items: [
{
type: "docSidebar",
@@ -101,7 +101,7 @@ const config: Config = {
],
},
],
- copyright: `Copyright ${new Date().getFullYear()} Flow State Dev. Built with Docusaurus.`,
+ copyright: `Copyright ${new Date().getFullYear()} Fixpoint Labs, LLC. Built with Docusaurus.`,
},
prism: {
theme: prismThemes.github,
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index 8538f76b74..56a43c53e2 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -20,6 +20,7 @@ const sidebars: SidebarsConfig = {
"concepts/flows",
"concepts/actions",
"concepts/state",
+ "concepts/type-system",
"concepts/streaming",
"concepts/testing",
],
diff --git a/apps/docs/src/css/custom.css b/apps/docs/src/css/custom.css
index 93042edb50..0a079ca266 100644
--- a/apps/docs/src/css/custom.css
+++ b/apps/docs/src/css/custom.css
@@ -18,5 +18,19 @@
--ifm-color-primary-light: #a5b4fc;
--ifm-color-primary-lighter: #c7d2fe;
--ifm-color-primary-lightest: #e0e7ff;
+ --ifm-background-color: #0a0a0f;
+ --ifm-background-surface-color: #111118;
+ --ifm-navbar-background-color: rgba(10, 10, 15, 0.8);
+ --ifm-footer-background-color: #06060a;
--docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.3);
}
+
+[data-theme="dark"] .navbar {
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+}
+
+[data-theme="dark"] .footer {
+ border-top: 1px solid rgba(255, 255, 255, 0.06);
+}
diff --git a/apps/docs/src/pages/index.module.css b/apps/docs/src/pages/index.module.css
index 8eed17f32e..01afdf03b7 100644
--- a/apps/docs/src/pages/index.module.css
+++ b/apps/docs/src/pages/index.module.css
@@ -1,32 +1,520 @@
+/* ── Hero ── */
+
.heroBanner {
- padding: 4rem 0;
- text-align: center;
position: relative;
+ padding: 8rem 2rem 6rem;
+ text-align: center;
overflow: hidden;
+ background: radial-gradient(
+ ellipse 80% 60% at 50% -10%,
+ rgba(99, 102, 241, 0.15) 0%,
+ transparent 70%
+ ),
+ var(--ifm-background-color);
+}
+
+.heroBanner::before {
+ content: "";
+ position: absolute;
+ inset: 0;
+ background: radial-gradient(
+ circle at 30% 80%,
+ rgba(129, 140, 248, 0.06) 0%,
+ transparent 50%
+ );
+ pointer-events: none;
+}
+
+.heroTitle {
+ font-size: 3.5rem;
+ font-weight: 700;
+ letter-spacing: -0.035em;
+ line-height: 1.1;
+ margin-bottom: 1.5rem;
+ background: linear-gradient(
+ 135deg,
+ #fff 0%,
+ rgba(255, 255, 255, 0.7) 100%
+ );
+ -webkit-background-clip: text;
+ -webkit-text-fill-color: transparent;
+ background-clip: text;
+}
+
+[data-theme="light"] .heroTitle {
+ background: linear-gradient(
+ 135deg,
+ #1a1a2e 0%,
+ #3730a3 100%
+ );
+ -webkit-background-clip: text;
+ background-clip: text;
}
+.heroSubtitle {
+ font-size: 1.15rem;
+ max-width: 560px;
+ margin: 0 auto 2.5rem;
+ color: rgba(255, 255, 255, 0.55);
+ line-height: 1.7;
+ font-weight: 400;
+}
+
+[data-theme="light"] .heroSubtitle {
+ color: var(--ifm-color-emphasis-600);
+}
+
+.brandName {
+ font-family: var(--ifm-font-family-monospace);
+ font-weight: 600;
+ color: var(--ifm-color-primary-light);
+ letter-spacing: -0.01em;
+}
+
+/* ── Buttons ── */
+
.buttons {
display: flex;
align-items: center;
justify-content: center;
- margin-top: 1.5rem;
+ gap: 0.75rem;
+ flex-wrap: wrap;
+}
+
+.primaryBtn,
+.secondaryBtn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0.7rem 1.75rem;
+ border-radius: 9999px;
+ font-size: 0.925rem;
+ font-weight: 600;
+ text-decoration: none;
+ transition: all 0.2s ease;
+ cursor: pointer;
+ border: none;
+}
+
+.primaryBtn {
+ background: var(--ifm-color-primary);
+ color: #fff;
+ box-shadow: 0 0 24px rgba(99, 102, 241, 0.25);
+}
+
+.primaryBtn:hover {
+ background: var(--ifm-color-primary-dark);
+ box-shadow: 0 0 32px rgba(99, 102, 241, 0.4);
+ color: #fff;
+ text-decoration: none;
+ transform: translateY(-1px);
+}
+
+.secondaryBtn {
+ background: rgba(255, 255, 255, 0.06);
+ color: rgba(255, 255, 255, 0.8);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+}
+
+.secondaryBtn:hover {
+ background: rgba(255, 255, 255, 0.1);
+ color: #fff;
+ text-decoration: none;
+ transform: translateY(-1px);
+}
+
+[data-theme="light"] .secondaryBtn {
+ background: rgba(0, 0, 0, 0.04);
+ color: var(--ifm-color-emphasis-700);
+ border: 1px solid rgba(0, 0, 0, 0.12);
+}
+
+[data-theme="light"] .secondaryBtn:hover {
+ background: rgba(0, 0, 0, 0.08);
+ color: var(--ifm-color-emphasis-900);
}
+/* ── Features ── */
+
.features {
+ padding: 5rem 2rem;
+ position: relative;
+}
+
+.features::before {
+ content: "";
+ position: absolute;
+ top: 0;
+ left: 50%;
+ transform: translateX(-50%);
+ width: min(100%, 800px);
+ height: 1px;
+ background: linear-gradient(
+ 90deg,
+ transparent 0%,
+ rgba(255, 255, 255, 0.08) 50%,
+ transparent 100%
+ );
+}
+
+[data-theme="light"] .features::before {
+ background: linear-gradient(
+ 90deg,
+ transparent 0%,
+ rgba(0, 0, 0, 0.08) 50%,
+ transparent 100%
+ );
+}
+
+.featureGrid {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 1.25rem;
+ max-width: 1100px;
+ margin: 0 auto;
+}
+
+.featureCard {
+ padding: 1.75rem;
+ border-radius: 16px;
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ transition: all 0.25s ease;
+}
+
+.featureCard:hover {
+ background: rgba(255, 255, 255, 0.05);
+ border-color: rgba(129, 140, 248, 0.2);
+ transform: translateY(-2px);
+}
+
+[data-theme="light"] .featureCard {
+ background: rgba(0, 0, 0, 0.02);
+ border-color: rgba(0, 0, 0, 0.08);
+}
+
+[data-theme="light"] .featureCard:hover {
+ background: rgba(0, 0, 0, 0.04);
+ border-color: var(--ifm-color-primary-lighter);
+}
+
+.featureTitle {
+ font-size: 1.05rem;
+ font-weight: 600;
+ margin-bottom: 0.6rem;
+ color: var(--ifm-color-primary-light);
+}
+
+[data-theme="light"] .featureTitle {
+ color: var(--ifm-color-primary-dark);
+}
+
+.featureDesc {
+ font-size: 0.9rem;
+ line-height: 1.6;
+ color: rgba(255, 255, 255, 0.5);
+ margin: 0;
+}
+
+[data-theme="light"] .featureDesc {
+ color: var(--ifm-color-emphasis-600);
+}
+
+/* ── Code Showcase ── */
+
+.codeShowcase {
+ padding: 4rem 2rem 5rem;
+ position: relative;
+}
+
+.codeShowcase::before {
+ content: "";
+ position: absolute;
+ top: 0;
+ left: 50%;
+ transform: translateX(-50%);
+ width: min(100%, 800px);
+ height: 1px;
+ background: linear-gradient(
+ 90deg,
+ transparent 0%,
+ rgba(255, 255, 255, 0.08) 50%,
+ transparent 100%
+ );
+}
+
+[data-theme="light"] .codeShowcase::before {
+ background: linear-gradient(
+ 90deg,
+ transparent 0%,
+ rgba(0, 0, 0, 0.08) 50%,
+ transparent 100%
+ );
+}
+
+.sectionTitle {
+ font-size: 2rem;
+ font-weight: 700;
+ letter-spacing: -0.02em;
+ text-align: center;
+ margin-bottom: 0.5rem;
+}
+
+.sectionSubtext {
+ text-align: center;
+ color: rgba(255, 255, 255, 0.45);
+ max-width: 520px;
+ margin: 0 auto 2.5rem;
+ font-size: 0.95rem;
+ line-height: 1.6;
+}
+
+[data-theme="light"] .sectionSubtext {
+ color: var(--ifm-color-emphasis-500);
+}
+
+.tabBar {
display: flex;
- align-items: center;
- padding: 2rem 0;
+ justify-content: center;
+ gap: 0.25rem;
+ margin-bottom: 1.5rem;
+ padding: 0.25rem;
+ background: rgba(255, 255, 255, 0.04);
+ border-radius: 12px;
+ width: fit-content;
+ margin-left: auto;
+ margin-right: auto;
+ border: 1px solid rgba(255, 255, 255, 0.06);
}
-.codePreview {
- padding: 2rem 0 4rem;
+[data-theme="light"] .tabBar {
+ background: rgba(0, 0, 0, 0.04);
+ border-color: rgba(0, 0, 0, 0.08);
}
-.codeBlock {
- background: var(--ifm-code-background);
- border-radius: var(--ifm-code-border-radius);
- padding: 1.5rem;
+.tab {
+ padding: 0.5rem 1.25rem;
+ border-radius: 9px;
font-size: 0.875rem;
+ font-weight: 500;
+ cursor: pointer;
+ border: none;
+ background: transparent;
+ color: rgba(255, 255, 255, 0.45);
+ transition: all 0.2s ease;
+}
+
+.tab:hover {
+ color: rgba(255, 255, 255, 0.7);
+}
+
+[data-theme="light"] .tab {
+ color: var(--ifm-color-emphasis-500);
+}
+
+[data-theme="light"] .tab:hover {
+ color: var(--ifm-color-emphasis-700);
+}
+
+.tabActive {
+ background: var(--ifm-color-primary);
+ color: #fff !important;
+ box-shadow: 0 2px 8px rgba(99, 102, 241, 0.3);
+}
+
+[data-theme="light"] .tabActive {
+ color: #fff !important;
+}
+
+.codeWrapper {
+ max-width: 800px;
+ margin: 0 auto;
+ border-radius: 12px;
+ overflow: hidden;
+}
+
+.codeWrapper pre {
+ border-radius: 12px !important;
+ border: 1px solid rgba(255, 255, 255, 0.06) !important;
+}
+
+[data-theme="light"] .codeWrapper pre {
+ border-color: rgba(0, 0, 0, 0.08) !important;
+}
+
+.codeCaption {
+ text-align: center;
+ margin-top: 1rem;
+ font-size: 0.85rem;
+ color: rgba(255, 255, 255, 0.35);
+}
+
+[data-theme="light"] .codeCaption {
+ color: var(--ifm-color-emphasis-400);
+}
+
+/* ── CTA ── */
+
+.ctaSection {
+ padding: 5rem 2rem;
+ text-align: center;
+ position: relative;
+}
+
+.ctaSection::before {
+ content: "";
+ position: absolute;
+ top: 0;
+ left: 50%;
+ transform: translateX(-50%);
+ width: min(100%, 800px);
+ height: 1px;
+ background: linear-gradient(
+ 90deg,
+ transparent 0%,
+ rgba(255, 255, 255, 0.08) 50%,
+ transparent 100%
+ );
+}
+
+[data-theme="light"] .ctaSection::before {
+ background: linear-gradient(
+ 90deg,
+ transparent 0%,
+ rgba(0, 0, 0, 0.08) 50%,
+ transparent 100%
+ );
+}
+
+.ctaTitle {
+ font-size: 2rem;
+ font-weight: 700;
+ letter-spacing: -0.02em;
+ margin-bottom: 0.75rem;
+}
+
+.ctaSubtext {
+ color: rgba(255, 255, 255, 0.45);
+ max-width: 440px;
+ margin: 0 auto 2rem;
+ font-size: 0.95rem;
line-height: 1.6;
- overflow-x: auto;
+}
+
+[data-theme="light"] .ctaSubtext {
+ color: var(--ifm-color-emphasis-500);
+}
+
+/* ── Responsive ── */
+
+@media (max-width: 996px) {
+ .featureGrid {
+ grid-template-columns: repeat(2, 1fr);
+ }
+}
+
+@media (max-width: 768px) {
+ .heroBanner {
+ padding: 5rem 1.5rem 4rem;
+ }
+
+ .heroTitle {
+ font-size: 2rem;
+ letter-spacing: -0.03em;
+ }
+
+ .heroSubtitle {
+ font-size: 1rem;
+ margin-bottom: 2rem;
+ }
+
+ .buttons {
+ flex-direction: column;
+ gap: 0.6rem;
+ }
+
+ .primaryBtn,
+ .secondaryBtn {
+ width: 100%;
+ max-width: 280px;
+ }
+
+ .features {
+ padding: 3rem 1.5rem;
+ }
+
+ .featureGrid {
+ grid-template-columns: 1fr;
+ gap: 1rem;
+ }
+
+ .featureCard {
+ padding: 1.5rem;
+ }
+
+ .codeShowcase {
+ padding: 3rem 1rem 4rem;
+ }
+
+ .sectionTitle {
+ font-size: 1.6rem;
+ }
+
+ .tabBar {
+ width: 100%;
+ max-width: 360px;
+ }
+
+ .tab {
+ padding: 0.45rem 0.9rem;
+ font-size: 0.8rem;
+ }
+
+ .ctaSection {
+ padding: 3.5rem 1.5rem;
+ }
+
+ .ctaTitle {
+ font-size: 1.6rem;
+ }
+}
+
+@media (max-width: 480px) {
+ .heroBanner {
+ padding: 4rem 1.25rem 3rem;
+ }
+
+ .heroTitle {
+ font-size: 1.7rem;
+ }
+
+ .heroSubtitle {
+ font-size: 0.925rem;
+ }
+
+ .featureCard {
+ padding: 1.25rem;
+ }
+
+ .featureTitle {
+ font-size: 0.95rem;
+ }
+
+ .featureDesc {
+ font-size: 0.85rem;
+ }
+
+ .codeShowcase {
+ padding: 2.5rem 0.75rem 3rem;
+ }
+
+ .tabBar {
+ gap: 0.15rem;
+ padding: 0.2rem;
+ }
+
+ .tab {
+ padding: 0.4rem 0.7rem;
+ font-size: 0.75rem;
+ }
}
diff --git a/apps/docs/src/pages/index.tsx b/apps/docs/src/pages/index.tsx
index aa33c6dc36..363bbb129a 100644
--- a/apps/docs/src/pages/index.tsx
+++ b/apps/docs/src/pages/index.tsx
@@ -1,145 +1,339 @@
-import clsx from "clsx";
+import { useState } from "react";
import Link from "@docusaurus/Link";
-import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import Layout from "@theme/Layout";
import Heading from "@theme/Heading";
+import CodeBlock from "@theme/CodeBlock";
import styles from "./index.module.css";
-function HomepageHeader() {
- const { siteConfig } = useDocusaurusContext();
+/* ── Code examples ── */
+
+const defineExample = `import { defineFlow, generator, sequencer } from "@flow-state-dev/core";
+// Reusable blocks — yours, your team's, or from the ecosystem
+import { searchWeb, searchInternalDocs, searchMemory } from "@research/blocks";
+import { mergeAndRank, refineResults } from "@research/ranking";
+import { gatherEvidence, scoreFindings } from "@research/analysis";
+import { logAnalytics, fallbackSearch } from "@infra/blocks";
+
+// A tool that's a full pipeline — parallel search, iterative refinement, recovery
+const deepResearch = sequencer({ name: "deep-research" })
+ .then(parseQuery)
+ .parallel({ // fan out to three sources at once
+ web: searchWeb,
+ docs: searchInternalDocs,
+ memory: searchMemory,
+ }, { maxConcurrency: 3 })
+ .then(mergeAndRank)
+ .doUntil( // loop until quality threshold met
+ (result) => result.confidence > 0.9,
+ refineResults
+ )
+ .work(logAnalytics) // async — doesn't block the pipeline
+ .rescue([{ when: [SearchError], block: fallbackSearch }]);
+
+// Sequencer that analyzes and emits a component item to the UI
+const analyze = sequencer({ name: "analyze" })
+ .then(gatherEvidence)
+ .then(scoreFindings)
+ .tap((report, ctx) => { // emit without changing the payload
+ ctx.emitComponent("report-card", {
+ title: report.title,
+ findings: report.findings,
+ confidence: report.score,
+ }).done();
+ });
+
+const agent = generator({
+ name: "agent",
+ model: "gpt-5-mini",
+ prompt: "You are a research assistant.",
+ // Blocks can declare only the state they need
+ sessionStateSchema: z.object({ researchCount: z.number().default(0) }),
+ history: (_input, ctx) => ctx.session.items.llm(),
+ user: (input) => input.message,
+ tools: [deepResearch, analyze, readDoc, writeDoc],
+});
+
+export default defineFlow({
+ kind: "research-assistant",
+ actions: {
+ chat: {
+ inputSchema: z.object({ message: z.string() }),
+ block: agent,
+ userMessage: (i) => i.message,
+ },
+ },
+ session: {
+ stateSchema,
+ resources: { docs: docResource },
+ projections: {
+ docList: { client: true, compute: (ctx) => /* derived view */ },
+ },
+ },
+})({ id: "default" });`;
+
+const serveExample = `import { createFlowRegistry, createFlowApiRouter } from "@flow-state-dev/server";
+import researchFlow from "./flows/research-assistant";
+import chatFlow from "./flows/chat";
+
+const registry = createFlowRegistry();
+registry.register(researchFlow);
+registry.register(chatFlow);
+
+export const { GET, POST, DELETE } = createFlowApiRouter({ registry });
+// POST /api/flows/research-assistant/actions/chat
+// GET /api/flows/research-assistant/requests/:id/stream
+// GET /api/flows/sessions/:id/state`;
+
+const renderExample = `// Register component renderers — the UI counterpart to ctx.emitComponent()
+function ReportCard({ item }: { item: ComponentItem }) {
+ const { title, findings, confidence } = item.data;
return (
-
-
-
- {siteConfig.title}
-
-
{siteConfig.tagline}
-
-
- Get Started
-
-
- Learn More
-
-
-
-
+
+
{title}
+
{findings.map(f =>
{f}
)}
+
+
);
}
+function App() {
+ return (
+
+
+
+ );
+}
+
+function ResearchApp() {
+ const flow = useFlow({ autoCreateSession: true });
+ const session = useSession(flow.activeSessionId);
+
+ return (
+ <>
+ {/* ItemRenderer resolves component items to registered renderers */}
+ {session.items.map(item => )}
+
+
+ >
+ );
+}`;
+
+const testExample = `const result = await testFlow({
+ flow: researchFlow,
+ action: "chat",
+ input: { message: "Summarize the design doc" },
+ userId: "testuser",
+ seed: {
+ session: {
+ resources: {
+ docs: { byId: { "design-doc": { title: "Design", content: "..." } } },
+ },
+ },
+ },
+ generators: {
+ agent: mockGenerator({ script: [{ text: "The design doc covers..." }] }),
+ },
+});
+
+const items = testItems(result.items);
+expect(items.messages()).not.toHaveLength(0);
+expect(items.components("report-card")).not.toHaveLength(0);`;
+
+/* ── Data ── */
+
+type CodeTab = {
+ label: string;
+ caption: string;
+ code: string;
+ language: string;
+};
+
+const codeTabs: CodeTab[] = [
+ {
+ label: "Define",
+ caption: "Compose blocks into flows with typed state, resources, and projections.",
+ code: defineExample,
+ language: "ts",
+ },
+ {
+ label: "Serve",
+ caption: "Register flows and get a full REST + SSE API. No route wiring.",
+ code: serveExample,
+ language: "ts",
+ },
+ {
+ label: "Render",
+ caption: "Register component renderers. ItemRenderer resolves them from the stream.",
+ code: renderExample,
+ language: "tsx",
+ },
+ {
+ label: "Test",
+ caption: "Deterministic tests with mock generators. No LLM calls needed.",
+ code: testExample,
+ language: "ts",
+ },
+];
+
type FeatureItem = {
title: string;
description: string;
};
-const FeatureList: FeatureItem[] = [
+const features: FeatureItem[] = [
+ {
+ title: "Four primitives. Compose freely.",
+ description:
+ "Handler, generator, sequencer, router. The sequencer DSL alone gives you parallel steps, forEach, doUntil/doWhile loops, background work, branching, error recovery, and more.",
+ },
{
- title: "Typed Blocks, Composable Flows",
+ title: "Flows are full APIs.",
description:
- "Define handlers, generators, sequencers, and routers as typed building blocks. Compose them into flows with a fluent DSL that catches errors at build time.",
+ "Define a flow and you have REST endpoints, SSE streaming, session management, and state snapshots. No route wiring.",
},
{
- title: "Resumable Streaming",
+ title: "Hybrid memory + filesystem.",
description:
- "Item-first streaming with sequence-number replay. Clients reconnect mid-stream without losing data. SSE protocol with content deltas, tool calls, and status events.",
+ "Resources combine rich text with structured state — like files that carry metadata. Scoped to sessions, users, or projects.",
},
{
- title: "Scoped State Management",
+ title: "Built for an ecosystem.",
description:
- "Four scope levels — request, session, user, project — with CAS-based state operations. Resources and projections provide typed data management with client visibility control.",
+ "Blocks are portable. Share a tool, a handler, or an entire flow. Community blocks compose with yours out of the box.",
},
{
- title: "Full-Stack TypeScript",
+ title: "Streaming that just works.",
description:
- "One type system from server execution through client transport to React UI. Schemas defined once, validated everywhere. No glue code between layers.",
+ "Messages, components, status updates — all stream over SSE as blocks execute. Disconnect mid-response? Reconnect with a sequence cursor.",
+ },
+ {
+ title: "Type-safe, end to end.",
+ description:
+ "One Zod schema flows from server blocks through client SDK to React hooks. No glue code. No type drift.",
},
];
-function Feature({ title, description }: FeatureItem) {
+/* ── Components ── */
+
+function Hero() {
return (
-
-
- {title}
-
{description}
+
+
+
+ Stop wiring. Start building.
+
+
+ flow-state.dev gives you
+ composable primitives for AI orchestration, streaming, state, and
+ error handling — so you can explore new patterns instead of
+ reinventing infrastructure.
+
+ Get a streaming AI app running in minutes. Then push it somewhere no framework has gone before.
+
+
+
+ Quick Start
+
+
+ Read the Manifesto
+
);
}
+/* ── Page ── */
+
export default function Home(): React.ReactElement {
- const { siteConfig } = useDocusaurusContext();
return (
-
-
+
+
-
-
+
+
+
);
diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md
index 95ffcf24d9..fa0de655a1 100644
--- a/docs/architecture/overview.md
+++ b/docs/architecture/overview.md
@@ -1,12 +1,42 @@
# Architecture Overview
-`@flow-state-dev` is a block-based AI workflow framework. You define **flows** composed of **blocks**, and the framework handles execution, streaming, state persistence, retries, and client rendering.
+`@flow-state-dev` gives you four composable block primitives — **handler**, **generator**, **sequencer**, **router** — and a runtime that handles execution, streaming, state persistence, retries, and client rendering so you don't have to.
+
+You define flows composed of blocks. The framework does the rest.
This document provides the system-level view. For deep dives into each subsystem, see the companion docs linked throughout.
-## Package Structure
+## The idea in 30 seconds
-The framework ships as six packages plus one first-party app:
+Every AI feature needs the same infrastructure: call an LLM, stream the response, manage state, handle errors, sync with the UI. Teams rebuild this for every project. `@flow-state-dev` makes these concerns framework primitives.
+
+```ts
+// Define blocks
+const chat = generator({ name: "chat", model: "gpt-5-mini", prompt: "..." });
+const track = handler({ name: "track", execute: async (input, ctx) => {
+ await ctx.session.incState({ count: 1 });
+ return input;
+}});
+
+// Compose into a pipeline
+const pipeline = sequencer({ name: "pipeline" })
+ .then(chat)
+ .then(track)
+ .rescue([{ when: [Error], block: fallback }]);
+
+// Expose as a flow
+export default defineFlow({
+ kind: "my-app",
+ actions: { chat: { block: pipeline } },
+ session: { stateSchema },
+})({ id: "default" });
+```
+
+The framework gives you: SSE streaming with resume, atomic state operations, retry policies, rescue boundaries, lifecycle hooks, typed client SDK, React hooks — all from this definition.
+
+## Package structure
+
+Six packages with strict dependency boundaries:
```
@flow-state-dev/core Isomorphic builders, type contracts, item taxonomy
@@ -18,7 +48,7 @@ The framework ships as six packages plus one first-party app:
apps/devtool First-party inspector app
```
-## Dependency Graph
+## Dependency graph
```
core ─────────────────────────────────┐
@@ -36,29 +66,29 @@ core ─────────────────────────
└── client
```
-**Boundary rules:**
-- `server` never depends on `react` or `client`
-- `client` never depends on `server` or `react`
-- `react` has no transport logic — it wraps `client`
+**Boundary rules (locked):**
+- `server` never depends on `react` or `client` — server knows nothing about transport consumers
+- `client` never depends on `server` or `react` — works in any JavaScript environment
+- `react` has no transport logic — it wraps `client` with hooks and renderers
- `cli` uses `server` + `testing`, never `react` or `client`
- `apps/devtool` uses only public APIs from `client` and `react`
-## Core Abstractions
+## Core abstractions
-### Blocks
+### Blocks — the four primitives
-Four block kinds compose all framework behavior:
+Every piece of logic in the framework is one of exactly four block kinds:
-| Kind | Purpose | Example |
-|------|---------|---------|
-| **handler** | Synchronous logic: `input → execute → output` | Validate input, transform data, update state |
-| **generator** | LLM call with framework-managed tool loop | Chat completion, structured extraction, agent tool use |
-| **sequencer** | Fluent DSL composing blocks into pipelines | `then`, `parallel`, `forEach`, `rescue`, `work` |
-| **router** | Runtime block selection | Route to different pipelines based on input/state |
+| Kind | What it does | When to use it |
+|------|-------------|----------------|
+| **handler** | `input → execute → output` | Validation, data transforms, state mutations, tool implementations |
+| **generator** | LLM call with framework-managed tool loop | Chat, structured extraction, agent tool use, any AI generation |
+| **sequencer** | Fluent DSL composing blocks into pipelines | Building multi-step workflows with branching, parallelism, error recovery |
+| **router** | Runtime block selection based on input or state | Dispatching to different pipelines based on mode, intent, or conditions |
-All blocks share the same execution contract: `block.run(input, ctx)`. See [Blocks](./blocks.md).
+All blocks share the same execution contract: `block.run(input, ctx)`. This uniformity means any block can be composed with any other block. See [Blocks](./blocks.md).
-### Flows
+### Flows — the entry point
A flow ties blocks to **actions** (entry points), **scopes** (state containers), and **lifecycle hooks**:
@@ -69,36 +99,46 @@ const myFlow = defineFlow({
actions: {
chat: { inputSchema, block: chatPipeline, userMessage: (i) => i.message }
},
- session: { stateSchema }
+ session: { stateSchema, resources: { ... }, projections: { ... } },
+ user: { stateSchema, projections: { ... } },
});
```
-See [Flows and Actions](./flows-and-actions.md).
+Actions are the flow's public API. Clients call them by name. Each action maps to a root block that the framework executes. See [Flows and Actions](./flows-and-actions.md).
-### Scopes
+### Scopes — state that scales
-Four nested state scopes with typed operations:
+Four nested state scopes, each with typed atomic operations:
```
request → session → user → project
+(one run) (conversation) (across sessions) (shared across users)
```
-Each scope provides atomic state operations (`patchState`, `incState`, `pushState`, etc.) with CAS-based concurrency. See [State and Scopes](./state-and-scopes.md).
+Each scope provides `patchState`, `setState`, `incState`, `pushState`, `atomicState`, and more — all CAS-guarded for concurrency safety. Blocks declare only the state fields they need via partial schemas, so a counter block doesn't need to know about a preferences block's state. See [State and Scopes](./state-and-scopes.md).
-### Streaming
+### Streaming — resilient by default
-SSE-based item/content streaming model:
+SSE-based item/content streaming with built-in resume:
-- Items have types (`message`, `reasoning`, `component`, `status`, `error`, etc.)
-- Content streams within items via delta events
-- Sequence-number cursors enable replay/resume
-- Item types determine audience routing (client, LLM, devtools)
+- **Items** have types (`message`, `reasoning`, `component`, `status`, `error`, etc.) and lifecycle states (`in_progress` → `completed`)
+- **Content** streams within items via delta events — text appears token-by-token
+- **Sequence-number cursors** enable replay after disconnect — no data loss, no duplicates
+- **Item types determine audience routing** — some items go to the UI, some to the LLM context, some to devtools
See [Streaming](./streaming.md).
-## Data Flow
+### Resources and projections — data with policy
+
+**Resources** are named, typed state containers scoped to sessions, users, or projects. Think of them as structured data stores that blocks can read and write.
+
+**Projections** are derived views computed from state and resources — and the *only* way to expose data to clients. This is a deliberate architectural choice: you can't accidentally leak internal state because projections are the sole data gateway.
+
+See [Resources and Projections](./resources-and-projections.md).
+
+## Data flow
-A typical request flows through the system like this:
+A typical request flows through the system:
```
Client Server Store
@@ -123,12 +163,12 @@ Client Server Store
```
Key points:
-1. POST returns `202 Accepted` immediately — execution is async
-2. Items stream live via SSE as blocks execute
-3. Client refetches state snapshot on `request.completed` (correctness path)
-4. Resume after disconnect uses `Last-Event-ID` or `starting_after` query param
+1. **Async by design** — POST returns `202 Accepted` immediately. Execution happens in the background.
+2. **Live streaming** — Items stream via SSE as blocks execute. The client sees results as they're produced.
+3. **Correctness path** — Client refetches the state snapshot on `request.completed` to get the authoritative final state.
+4. **Resilient resume** — Reconnect after disconnect using `Last-Event-ID` or `starting_after` query param. The server replays missed events from the sequence cursor.
-## Locked Contracts (Phase 1)
+## Locked contracts (Phase 1)
These decisions are canonical and cannot change without architecture review:
@@ -141,6 +181,6 @@ These decisions are canonical and cannot change without architecture review:
- Generator provider: Vercel AI SDK in Phase 1
- Observational hooks: past tense (`onStarted`, `onCompleted`, `onErrored`, `onFinished`)
-## Canonical Authority
+## Canonical authority
For edge cases and detailed contracts, the canonical specs in `../preperation/architecture/` are authoritative. The docs in this directory are adapted summaries — when in doubt, check the source spec.
diff --git a/packages/client/README.md b/packages/client/README.md
index 71e2d14b71..399adefe81 100644
--- a/packages/client/README.md
+++ b/packages/client/README.md
@@ -1,95 +1,100 @@
# @flow-state-dev/client
-Isomorphic transport/API client for Flow State Dev.
+**Connect to flows from anywhere. Actions, sessions, streaming — no framework lock-in on the client side.**
-`@flow-state-dev/client` owns framework network access:
-- action execution
-- session CRUD + session request listing
-- session state snapshots (scope state + scope-grouped projections + optional items)
-- request/user SSE consumption
+Works in Node, the browser, edge runtimes. No React dependency. No DOM dependency. Just HTTP and SSE.
-No React or DOM dependency.
-
-## Public API
+```ts
+import { createClient } from "@flow-state-dev/client";
-- `createClient(options)`
-- `createTypedClient(options)`
-- `createSessionClient(options)`
-- `createSSEClient(options)`
-- `createUserSSEClient(options)`
-- `ClientHttpError`
+const client = createClient({ flowKind: "my-app", userId: "user_1" });
-## `createClient` vs `createTypedClient`
+// Send an action and get back a request ID
+const { requestId } = await client.sendAction("chat", { message: "Hello" });
-`createClient`:
-- dynamic action names (`sendAction("run", input)`)
-- best for tooling and generic UIs
+// Or use a typed client for compile-time action safety
+const typed = createTypedClient({ flow: myFlowDefinition, userId: "user_1" });
+await typed.actions.chat({ message: "Hello" });
+```
-`createTypedClient`:
-- flow-bound action methods (`actions.run(input)`)
-- best when a flow definition is available at compile time
+## Streaming
-## Usage
+Subscribe to a request's SSE stream with typed event handlers:
```ts
-import { createClient } from "@flow-state-dev/client";
+import { createSSEClient } from "@flow-state-dev/client";
-const client = createClient({
- flowKind: "demo",
- userId: "devuser",
+const stream = createSSEClient({
+ url: `/api/flows/my-app/requests/${requestId}/stream`,
+ onItemAdded: (event) => {
+ // New item appeared (message, reasoning, component, etc.)
+ },
+ onContentDelta: (event) => {
+ // Text chunk arrived — append to the current item's content
+ },
+ onRequestStatus: (event) => {
+ if (event.status === "completed") {
+ // Refetch state snapshot for the authoritative final state
+ }
+ },
});
-
-await client.sendAction("run", { value: "hello" }, { sessionId: "sess_1" });
```
-Typed client:
+Resume after disconnect — pass a sequence cursor and the server replays missed events:
```ts
-import { createTypedClient } from "@flow-state-dev/client";
-
-const typed = createTypedClient({ flow, userId: "devuser" });
-await typed.actions.run({ value: "hello" });
+const stream = createSSEClient({
+ url: `/api/flows/my-app/requests/${requestId}/stream?starting_after=${lastSeq}`,
+ // ...handlers
+});
```
-Snapshot API with query controls:
+## Session management
```ts
-const sessions = createSessionClient();
+import { createSessionClient } from "@flow-state-dev/client";
+
+const sessions = createSessionClient({ baseUrl: "/api" });
+// State snapshot with projections and items
const snapshot = await sessions.getSessionState("sess_1", {
includeItems: true,
- projections: ["session.artifactsList", "user.topics"],
+ projections: ["session.artifactsList", "user.preferences"],
});
```
-### SSE Stream Client
+## `createClient` vs `createTypedClient`
-```ts
-import { createSSEClient } from "@flow-state-dev/client";
+| | `createClient` | `createTypedClient` |
+|--|----------------|---------------------|
+| Action calls | `sendAction("chat", input)` | `actions.chat(input)` |
+| Type safety | Runtime only | Compile-time + runtime |
+| Best for | Generic UIs, devtools | App code with known flow definitions |
-const stream = createSSEClient({
- url: `/api/flows/my-flow/requests/${requestId}/stream`,
- onItemAdded: (event) => { /* handle new item */ },
- onContentDelta: (event) => { /* handle text chunk */ },
- onRequestStatus: (event) => {
- if (event.status === "completed") { /* refetch state */ }
- },
-});
-```
+## Public API
+
+- `createClient(options)` — Dynamic action client
+- `createTypedClient(options)` — Flow-bound typed client
+- `createSessionClient(options)` — Session CRUD and state snapshots
+- `createSSEClient(options)` — Request stream consumer
+- `createUserSSEClient(options)` — User-level stream consumer
+- `ClientHttpError` — Typed HTTP error class
## Notes
-- `userId` is required for Phase 1 action/session calls.
-- Request stream resume supports both `Last-Event-ID` and `starting_after`.
-- When both resume inputs are supplied, `starting_after` takes precedence.
+- `userId` is required for Phase 1 action/session calls
+- Stream resume supports both `Last-Event-ID` header and `starting_after` query param
+- When both are supplied, `starting_after` takes precedence
-## Architecture Reference
+## Scripts
-- [Server and Client](../../docs/architecture/server-and-client.md) — routes, transport, React hooks contract
-- [Streaming](../../docs/architecture/streaming.md) — item/content model, SSE protocol, resume
+```bash
+pnpm --filter @flow-state-dev/client build
+pnpm --filter @flow-state-dev/client typecheck
+pnpm --filter @flow-state-dev/client test
+```
-## Scripts
+## Architecture reference
-- `pnpm --filter @flow-state-dev/client build`
-- `pnpm --filter @flow-state-dev/client typecheck`
-- `pnpm --filter @flow-state-dev/client test`
+- [Server and Client](../../docs/architecture/server-and-client.md) — Routes, transport, React hooks contract
+- [Streaming](../../docs/architecture/streaming.md) — Item/content model, SSE protocol, resume semantics
diff --git a/packages/core/README.md b/packages/core/README.md
index 5c10f402a4..5d0cfb2a67 100644
--- a/packages/core/README.md
+++ b/packages/core/README.md
@@ -1,95 +1,121 @@
# @flow-state-dev/core
-Isomorphic builders, type contracts, and item taxonomy for Flow State Dev.
+**The building blocks. Define handlers, generators, sequencers, routers, and flows — all with end-to-end type safety.**
-This is the foundation package — every other package depends on it. It defines the block builders, flow model, type system, and item/event taxonomy used across the framework.
+This is the foundation package. Every other package depends on it. It's isomorphic — runs in Node, the browser, edge runtimes, anywhere JavaScript runs.
-## What This Package Is For
-
-Use `@flow-state-dev/core` to:
-- Define blocks (`handler`, `generator`, `sequencer`, `router`)
-- Define flows (`defineFlow`)
-- Define resources and projections (`defineResource`, `defineProjection`)
-- Import shared types and item definitions
-
-This package is **isomorphic** — no platform-specific code (Node, browser, etc.).
-
-## Quick Start
+## What you can build
```ts
-import { defineFlow, generator, handler, sequencer } from "@flow-state-dev/core";
+import { defineFlow, generator, handler, sequencer, router } from "@flow-state-dev/core";
import { z } from "zod";
+```
-// Define a generator block
-const chatGen = generator({
- name: "chat",
+**A generator that calls an LLM with tools, history, and streaming:**
+
+```ts
+const agent = generator({
+ name: "agent",
model: "gpt-5-mini",
prompt: "You are a helpful assistant.",
inputSchema: z.object({ message: z.string() }),
+ history: (_input, ctx) => ctx.session.items.llm(),
user: (input) => input.message,
+ tools: [readDoc, writeDoc],
+ emit: { reasoning: true, messages: true },
});
+```
+
+**A handler that validates and transforms:**
-// Define a handler block
+```ts
const counter = handler({
name: "counter",
- inputSchema: z.string(),
- outputSchema: z.string(),
sessionStateSchema: z.object({ count: z.number().default(0) }),
execute: async (input, ctx) => {
- await ctx.session.patchState({ count: (ctx.session.state.count ?? 0) + 1 });
+ await ctx.session.incState({ count: 1 });
return input;
},
});
+```
-// Compose into a pipeline
-const pipeline = sequencer({ name: "chat-pipeline", inputSchema: z.object({ message: z.string() }) })
- .then(chatGen)
- .then(counter);
+**A sequencer that composes them into a pipeline with error recovery:**
-// Define the flow
-const flow = defineFlow({
- kind: "my-chat",
+```ts
+const pipeline = sequencer({ name: "chat-pipeline", inputSchema })
+ .then(analyzeInput)
+ .thenIf((result) => result.needsContext, enrichWithContext)
+ .then(agent)
+ .then(counter)
+ .rescue([{ when: [ModelError], block: fallback }]);
+```
+
+**A router that dispatches to different pipelines at runtime:**
+
+```ts
+const dispatch = router({
+ name: "mode-router",
+ routes: [chatPipeline, planPipeline, reviewPipeline],
+ execute: (input, ctx) => {
+ const mode = ctx.session.state.mode;
+ if (mode === "plan") return planPipeline;
+ if (mode === "review") return reviewPipeline;
+ return chatPipeline;
+ },
+});
+```
+
+**A flow that ties it all together:**
+
+```ts
+export default defineFlow({
+ kind: "my-app",
requireUser: true,
actions: {
chat: {
inputSchema: z.object({ message: z.string() }),
- block: pipeline,
+ block: dispatch,
userMessage: (input) => input.message,
},
},
session: {
- stateSchema: z.object({ count: z.number().default(0) }),
+ stateSchema: z.object({ mode: z.string().default("chat"), count: z.number().default(0) }),
+ resources: { artifacts: { stateSchema: artifactSchema, writable: true } },
+ projections: {
+ artifactsList: {
+ client: true,
+ compute: (ctx) => /* derive list from resource state */,
+ },
+ },
},
-});
-
-export default flow({ id: "default" });
+})({ id: "default" });
```
## Exports
### Main (`@flow-state-dev/core`)
-**Block Builders:**
-- `handler(config)` — Synchronous logic block
-- `generator(config)` — LLM call with tool loop
-- `sequencer(config)` — Fluent composition DSL
-- `router(config)` — Runtime block selection
+**Block builders:**
+- `handler(config)` — Synchronous/async logic block
+- `generator(config)` — LLM call with framework-managed tool loop, streaming, and structured output repair
+- `sequencer(config)` — Fluent composition DSL (14 methods: `then`, `thenIf`, `parallel`, `forEach`, `doUntil`, `doWhile`, `map`, `tap`, `tapIf`, `rescue`, `branch`, `work`, `waitForWork`, `loopBack`)
+- `router(config)` — Runtime block selection from declared routes
**Flow:**
-- `defineFlow(definition)` — Create a flow type
+- `defineFlow(definition)` — Create a flow type with actions, scopes, resources, and projections
-**Resources & Projections:**
+**Resources and projections:**
- `defineResource(config)` — Portable resource definition
- `defineProjection(config)` — Portable projection definition
-- `resource(uri, opts?)` — Resource slot reference for generators
-- `projection(uri, opts?)` — Projection slot reference
-- `projectionText(uri, opts?)` — Text projection reference
-- `projectionData(uri, opts?)` — Data projection reference
-- `projectionMessages(uri, opts?)` — Message projection reference
+- `resource(uri)` — Resource slot reference for generators
+- `projection(uri)` — Projection slot reference
+- `projectionText(uri)` — Text projection for LLM context
+- `projectionData(uri)` — Structured data projection
+- `projectionMessages(uri)` — Message-pair projection
Inline flow projections infer resource state types from scope `resources` automatically. For portable projections (`defineProjection`), provide `sessionResourceSchemas`, `userResourceSchemas`, or `projectResourceSchemas` (as Zod schemas, `defineResource(...)` values, or maps of either) when you need typed resource access inside `compute`.
-**Type Helpers:**
+**Type helpers:**
- `StateOf` — Extract state type from schema or resource
- `ContextOf` — Get context handle type for scope/resource
- `ResourceContext` — Resource context type
@@ -97,27 +123,36 @@ Inline flow projections infer resource state types from scope `resources` automa
### Types (`@flow-state-dev/core/types`)
-Block, flow, resource, scope, streaming, and model type definitions. Use this subpath for type-only imports in client/react code.
+Block, flow, resource, scope, streaming, and model type definitions. Use this subpath for type-only imports.
### Items (`@flow-state-dev/core/items`)
-Canonical output item unions, content types, and stream event helpers. Use this subpath for item-related type imports.
+Output item unions, content types, and stream event helpers. Item types: `message`, `reasoning`, `component`, `context`, `status`, `state_change`, `resource_change`, `block_output`, `error`, `step_error`.
+
+## Key design decisions
+
+**Partial state schemas.** Each block declares only the state fields it touches. A counter block doesn't need to know about a preferences block's state. This keeps blocks reusable and self-documenting about their dependencies.
+
+**Silent by default.** Blocks emit nothing to the client unless they explicitly call `ctx.emitMessage()`, `ctx.emitComponent()`, or `ctx.emitStatus()`. Generators are the exception — they auto-emit messages and reasoning. This gives you precise control over what the user sees.
+
+**Projections as data policy.** Projections are the *only* way to expose data to clients. Internal state, resources, and intermediate values stay server-side unless you deliberately project them. Security by architecture, not by convention.
## Dependencies
-- `zod` ^3.24.1 — Schema validation
+- `zod` ^3.24.1
## Scripts
-- `pnpm --filter @flow-state-dev/core build`
-- `pnpm --filter @flow-state-dev/core typecheck`
-- `pnpm --filter @flow-state-dev/core test`
+```bash
+pnpm --filter @flow-state-dev/core build
+pnpm --filter @flow-state-dev/core typecheck
+pnpm --filter @flow-state-dev/core test
+```
-## Architecture Reference
+## Architecture reference
-See `docs/architecture/` for detailed documentation:
-- [Blocks](../../docs/architecture/blocks.md)
-- [Flows and Actions](../../docs/architecture/flows-and-actions.md)
-- [Sequencer DSL](../../docs/architecture/sequencer-dsl.md)
-- [State and Scopes](../../docs/architecture/state-and-scopes.md)
-- [Resources and Projections](../../docs/architecture/resources-and-projections.md)
+- [Blocks](../../docs/architecture/blocks.md) — Deep dive into all four block kinds
+- [Flows and Actions](../../docs/architecture/flows-and-actions.md) — defineFlow, actions, lifecycle hooks
+- [Sequencer DSL](../../docs/architecture/sequencer-dsl.md) — Full method reference for the composition DSL
+- [State and Scopes](../../docs/architecture/state-and-scopes.md) — Scoped state, atomic operations, CAS
+- [Resources and Projections](../../docs/architecture/resources-and-projections.md) — Data containers and derived views
diff --git a/packages/react/README.md b/packages/react/README.md
index 5b746e7366..fef0b62b92 100644
--- a/packages/react/README.md
+++ b/packages/react/README.md
@@ -1,175 +1,165 @@
# @flow-state-dev/react
-React bindings for Flow State Dev.
-
-`@flow-state-dev/react` is a UI-layer package:
-- wraps `@flow-state-dev/client` transport APIs with React hooks
-- provides renderer/context helpers for `fsd:block_output` items
-- keeps transport logic out of React components
-
-## Install
-
-```bash
-pnpm add @flow-state-dev/react
-```
-
-Peer dependency: `react ^18.0.0 || ^19.0.0`
-
-## Quick Start
+**React hooks and renderers for Flow State Dev. Wire AI workflows to your UI in minutes.**
```tsx
-import {
- FlowProvider,
- ItemRenderer,
- useFlow,
- useProjections,
- useSession,
-} from "@flow-state-dev/react";
+import { FlowProvider, useFlow, useSession, ItemRenderer } from "@flow-state-dev/react";
function App() {
return (
-
-
+
+
);
}
-function AgentUI() {
+function Chat() {
const flow = useFlow({ autoCreateSession: true });
- const session = useSession(flow.activeSessionId, {
- items: { visibility: "ui" },
- });
-
- const projections = useProjections(session, {
- session: ["artifactsList", "planStatus"],
- });
+ const session = useSession(flow.activeSessionId);
return (