# AI & Skills
# AI & Skills [#ai--skills]
Feed RilayKit docs to AI agents directly, or install the RilayKit skill for context-aware assistance.
## LLM-Ready Documentation [#llm-ready-documentation]
| Endpoint | Description |
| ---------------------------------- | ----------------------------------------------- |
| [`/llms.txt`](/llms.txt) | Index of all pages with titles and descriptions |
| [`/llms-full.txt`](/llms-full.txt) | Complete documentation as plain markdown |
Use these with any AI tool that supports `llms.txt`.
## Install the RilayKit Skill [#install-the-rilaykit-skill]
The skill gives coding agents deep knowledge of the framework: builder patterns, validation, conditions, hooks, and real-world patterns. It uses progressive disclosure — only the relevant reference loads into context when needed.
```bash
npx skills add andyoucreate/rilaykit -a claude-code
```
```bash
npx skills add andyoucreate/rilaykit --all
```
```bash
npx skills add andyoucreate/rilaykit -g --all
```
## What's Included [#whats-included]
Three reference files cover the API:
| Reference | Coverage |
| --------- | ----------------------------------------------------------------------------------- |
| Core | `ril` instance, component registry, Standard Schema validation, `when()` conditions |
| Forms | Form builder, row layouts, components, field/form/condition hooks |
| Workflow | Flow builder, navigation, step data helpers, persistence, analytics |
## Supported Agents [#supported-agents]
Works with any agent in the [skills.sh](https://skills.sh) ecosystem: Claude Code, Cursor, Windsurf, OpenCode, and 40+ more.
## Verify Installation [#verify-installation]
Ask your agent:
```
How do I create a multi-step workflow with conditional steps using RilayKit?
```
It should reference the `@rilaykit/workflow` builder API with `when()` conditions — not generic form library patterns.
# API Reference
# API Reference [#api-reference]
Package mains are React-free (RSC/server-safe): import builders, validators, and schema compilers from `@rilaykit/core`, `@rilaykit/forms`, `@rilaykit/workflow`, `@rilaykit/agent` (or the all-in-one `rilaykit`). Import components and hooks from the matching `/react` entry.
***
## @rilaykit/core [#rilaykitcore]
Catalog (`ril`), validators, conditions, effects, and error classes shared by all packages.
### ril [#ril]
The immutable catalog: registered components, tools, and parts. Every mutation returns a **new instance**.
```ts
import { ril } from '@rilaykit/core';
import { z } from 'zod';
const catalog = ril.create()
.component('email', {
description: 'Email input',
propsSchema: z.object({ label: z.string() }),
renderer: (ctx) => (
ctx.field?.onChange(e.target.value)}
onBlur={ctx.field?.onBlur}
/>
),
})
.tool('lookup_company', {
description: 'Fetch company data by SIREN',
inputSchema: z.object({ siren: z.string() }),
})
.part('text', { renderer: ({ part }) =>
{(part as { text: string }).text}
});
```
| Method | Returns | Description |
| ----------------------------------------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ril.create()` | `ril` | New empty catalog |
| `.component(type, entry)` | new instance | Register a component (`entry`: `name?`, `description?`, `propsSchema?`, `propsJsonSchema?`, `renderer?`, `defaultProps?`, `validation?`, `meta?`, `replace?`) |
| `.tool(name, entry)` | new instance | Register a tool (`description?`, `inputSchema?`, `inputJsonSchema?`, `renderer?`, `meta?`, `replace?`) |
| `.part(type, entry)` | new instance | Register a message-part renderer (`renderer` required) |
| `.use(plugin)` | new instance | Apply a `RilayPlugin` (`(r) => r.component(...)...`) |
| `.renderers({ components?, tools?, parts? })` | new instance | Attach renderers to already-registered entries |
| `.getComponent(id)` / `.getTool(name)` / `.getPart(type)` | entry or `undefined` | Lookup |
| `.getAllComponents()` / `.getAllTools()` / `.getAllParts()` | arrays | Enumerate |
| `.hasComponent(id)` | `boolean` | Existence check |
| `.validateProps(type, props)` | `PropsValidationResult` | Check props against the component's `propsSchema` |
| `.validate()` / `.validateAsync()` | `string[]` / `Promise` | Configuration validation |
| `.getStats()` | `{ total, components, tools, parts }` | Counts |
| `.clone()` / `.removeComponent(id)` / `.clear()` | new instance | Immutability utilities |
Registering an existing key throws `DuplicateError` unless the entry sets `replace: true`.
### ComponentRenderContext [#componentrendercontext]
Passed to every component renderer:
```ts
interface ComponentRenderContext> {
readonly id: string;
readonly props: TProps;
readonly field?: FieldBinding; // value, onChange, onBlur, error?, disabled?, isValidating?, touched?
readonly conditions?: FieldConditions; // visible, disabled, required, readonly
readonly children?: React.ReactNode;
readonly meta?: Record;
}
```
`field.error` and `conditions.{required,disabled,readonly}` carry what WCAG-AA rendering needs (`aria-invalid`, `role="alert"`, ARIA attributes); `field.touched` gates error display.
### Validators [#validators]
All built-ins implement [Standard Schema](https://standardschema.dev) (`StandardSchemaV1`) and mix freely with Zod, Valibot, ArkType, etc.
```ts
import {
required, email, url, minLength, maxLength,
pattern, number, min, max, custom, async, combine,
} from '@rilaykit/core';
```
| Validator | Signature |
| ------------------------- | ------------------------------------------------------- |
| `required` | `required(msg?)` |
| `email` | `email(msg?)` |
| `url` | `url(msg?)` |
| `minLength` / `maxLength` | `minLength(min, msg?)` / `maxLength(max, msg?)` |
| `pattern` | `pattern(regex, msg?)` |
| `number` | `number(msg?)` |
| `min` / `max` | `min(val, msg?)` / `max(val, msg?)` |
| `custom` | `custom(fn, msg?)` — sync `(value: T) => boolean` |
| `async` | `async(fn, msg?)` — `(value: T) => Promise` |
| `combine` | `combine(...schemas)` — merge Standard Schemas |
### Conditional Logic [#conditional-logic]
`when(field)` returns a `ConditionBuilder`:
```ts
import { when } from '@rilaykit/core';
when('role').equals('admin').or(when('permissions').contains('write'))
when('address.country').equals('FR') // nested paths work
```
**Operators**: `.equals()`, `.notEquals()`, `.greaterThan()`, `.lessThan()`, `.greaterThanOrEqual()`, `.lessThanOrEqual()`, `.contains()`, `.notContains()`, `.in()`, `.notIn()`, `.matches()`, `.exists()`, `.notExists()`.
**Combinators**: `.and(condition)`, `.or(condition)`. **Terminals**: `.build()` → `ConditionConfig`, `.evaluate(data)` → `boolean`.
A field with only `conditions.required` (no `validation` block) is enforced: submit blocks while the condition holds and the field is empty.
### Field Effects [#field-effects]
`onChange(fieldId, handler)` declares reactive field-to-field logic — `fieldId` is the field being **watched**, not the field the effect is declared on.
```ts
import { onChange } from '@rilaykit/core';
onChange('country', async (value, { setValue, setProps }) => {
setValue('city', '');
setProps('city', { options: await fetchCities(value) });
});
```
| Context method | Description |
| -------------------------- | ------------------------------------ |
| `setValue(fieldId, value)` | Set another field's value (cascades) |
| `setProps(fieldId, props)` | Merge dynamic props into a field |
| `getValues()` | Snapshot of all form values |
| `getFieldValue(fieldId)` | One field's current value |
Protections: cascade depth cap (10), cycle detection, async abort (only the latest handler wins). Effects run regardless of field visibility; a repeatable-template effect watching a global field fans out per live row with row-scoped `setValue`/`getFieldValue`.
### Errors and Constants [#errors-and-constants]
```ts
import { RilayError, ValidationError, DuplicateError, NotFoundError } from '@rilaykit/core';
```
`RilayError` carries `code: RilayErrorCode` and `meta?`. Subclasses: `ValidationError` (`VALIDATION`), `DuplicateError` (`DUPLICATE`), `NotFoundError` (`NOT_FOUND`), `InvalidSchemaError` (`INVALID_SCHEMA`), `ConfigurationError` (`CONFIGURATION`), `MaxDepthExceededError` (`MAX_DEPTH`).
`FORM_LEVEL_ERROR_KEY` (`'__form__'`) and `FORM_LEVEL_ERROR_CODE` (`'FORM_LEVEL'`) are the reserved bucket/code of the path-keyed error map (see `useFormErrors`).
***
## @rilaykit/forms [#rilaykitforms]
Builder and schema compiler from `@rilaykit/forms`; components and hooks from `@rilaykit/forms/react`.
### Components [#components]
```tsx
import { Form } from '@rilaykit/forms/react';
```
#### `Form` [#form]
Compound root (`Form.Body`, `Form.Field`, `Form.Submit`, `Form.List`). Wraps `FormProvider`.
| Prop | Type | Description |
| -------------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------- |
| `of` | `FormConfiguration \| form` | Built configuration or builder (auto-built) |
| `defaults?` | `Record` | Initial values. Live upgrade channel: changing it re-seeds **untouched** fields; edited fields are immune |
| `onSubmit?` | `(data) => void \| Promise` | Receives only visible fields' values |
| `onFieldChange?` | `(fieldId, value, formData) => void` | Per-change callback |
| `onFieldsRemove?` | `(fieldIds, formData) => void` | Fired when repeatable-row removal deletes keys |
| `onRepeatableOrderChange?` | `(order) => void` | Live row-order mirror |
| `defaultRepeatableOrder?` | `Record` | Row order to restore |
| `instanceId?` | `string` | Owner identity; same config + different `instanceId` = different form |
| `conditionValues?` | `Record` | Read-only extra values conditions may reference (cross-step) |
| `className?` | `string` | CSS class |
#### `Form.Body` / `Form.Field` / `Form.Submit` / `Form.List` [#formbody--formfield--formsubmit--formlist]
| Component | Props |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Form.Body` | `children?: ({ rows }) => ReactNode`, `className?` — renders all visible rows by default |
| `Form.Field` | `id`, `config?`, `disabled?`, `overrides?` (extra props merged in), `forceVisible?`, `className?` |
| `Form.Submit` | `children?: ReactNode \| (({ submitting, submit }) => ReactNode)`, `className?` |
| `Form.List` | `id`, `children?: (ctx: FormListContext) => ReactNode`, `className?` — `ctx`: `items`, `add()`, `remove(key)`, `move(from, to)`, `canAdd`, `canRemove` |
`FormProvider` is the lower-level provider (`formConfig`, `defaultValues`, same callbacks); `useForm()` reads its context: `formConfig`, `conditionsHelpers`, `validateField`, `validateForm`, `validateFormLevel`, `submit`.
### form (FormBuilder) [#form-formbuilder]
```ts
import { form } from '@rilaykit/forms';
const contact = form.create(catalog, 'contact') // formId optional
.add({ id: 'email', type: 'email', props: { label: 'Email' } })
.add( // multiple fields in one call = one row
{ id: 'firstName', type: 'input', props: { label: 'First' } },
{ id: 'lastName', type: 'input', props: { label: 'Last' } },
)
.setValidation({
mode: 'onTouched', // when a field FIRST validates (default)
reValidateMode: 'onChange', // re-validation after an error (default)
validate: z.object({ password: z.string().min(8), confirmPassword: z.string() })
.refine((d) => d.password === d.confirmPassword, {
message: "Passwords don't match",
path: ['confirmPassword'], // routed to that field's errors
}),
});
```
| Method | Description |
| --------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| `.add(...fields)` / `.add([fields])` | Add fields; one call = one row |
| `.addSeparateRows(fields)` | Each field on its own row |
| `.addRepeatable(id, (r) => r.add(...).min(n).max(n).defaultValue(v))` | Repeatable group (strictly one level — no nesting) |
| `.setValidation(config)` | Form-level `FormValidationConfig`: `validate?`, `mode?`, `reValidateMode?` |
| `.setSubmitOptions(options)` | Default submit options |
| `.addFieldValidation(fieldId, config)` | Attach validation after creation |
| `.addFieldConditions(fieldId, conditions)` | Attach `ConditionalBehavior` (`visible?`, `disabled?`, `required?`, `readonly?`) |
| `.updateField(fieldId, updates)` / `.removeField(fieldId)` | Mutate fields |
| `.getField(id)` / `.getFields()` / `.getRows()` | Read back |
| `.setId(id)` / `.clear()` / `.clone(newId?)` | Utilities |
| `.validate()` | Structural issues as `string[]` |
| `.build()` | `FormConfiguration`; throws on invalid |
| `.toJSON()` / `.fromJSON(json)` / `.getStats()` | Serialization, stats |
**Validation timing** — form-level, two-phase (mirrors React Hook Form):
* `mode`: `'onSubmit' | 'onBlur' | 'onChange' | 'onTouched' | 'all'` — when a field first validates. Default `'onTouched'` (first blur, then live). RHF's own default is `onSubmit`; RilayKit keeps its historical behavior.
* `reValidateMode`: `'onChange' | 'onBlur' | 'onSubmit'` — re-validation once a field has errored. Default `'onChange'` (errors clear live).
* Per field: `validation: { validate, debounceMs }`. `debounceMs` defers change-triggered async validation only; blur and submit always validate immediately.
* Submit always validates and marks errored fields `touched`, so touched-gated renderers show submit errors, and they clear live.
**Error routing** — cross-field issues from `setValidation`'s `validate` are written to the store by `issue.path`: a path naming a known field attaches to that field (tagged `FORM_LEVEL_ERROR_CODE`); empty or unmatched paths land in the `__form__` bucket read by `useFormErrors()`. Form-level rules re-run on the same `mode`/`reValidateMode` cadence and on repeatable row add/remove/move.
### Hooks [#hooks]
All from `@rilaykit/forms/react`, Zustand-backed: field-level hooks re-render only when their field changes (a keystroke re-renders only the typed field).
| Field hook | Returns |
| ---------------------------------- | ---------------------------------------------------------------------- |
| `useFieldValue(fieldId)` | `T` |
| `useFieldErrors(fieldId)` | `FieldError[]` (includes routed cross-field issues) |
| `useFieldTouched(fieldId)` | `boolean` |
| `useFieldValidationState(fieldId)` | `'idle' \| 'validating' \| 'valid' \| 'invalid'` |
| `useFieldConditions(fieldId)` | `{ visible, disabled, required, readonly }` |
| `useFieldState(fieldId)` | `{ value, errors, validationState, touched, dirty }` |
| `useFieldProps(fieldId)` | `Record` |
| `useFieldActions(fieldId)` | `{ setValue, setTouched, setErrors, clearErrors, setValidationState }` |
| Form hook | Returns |
| ----------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `useFormErrors()` | `FieldError[]` — the `__form__` bucket; use for a form-level error banner (`aria-live`) |
| `useFormValues()` | `Record` |
| `useFormSubmitting()` / `useFormValid()` / `useFormDirty()` | `boolean` (`isValid` counts the whole map, `__form__` included) |
| `useFormSubmitState()` | `{ isSubmitting, isValid, isDirty }` |
| `useFormActions()` | `{ setValue, setTouched, setErrors, setSubmitting, reset, setFieldConditions }` |
| `useRepeatableKeys(repeatableId)` | `string[]` — live row keys |
| `useFormStoreApi()` | Store ref for imperative `getState()` reads |
| `useForm()` | Form context (config, validation, `submit`) |
`reset(values?, repeatableOrder?)` restores defaults or explicit values; the second argument restores repeatable row order.
### Server-Driven Forms (JSON schemas) [#server-driven-forms-json-schemas]
```ts
import { compileForm, fromSchema, validateSchema, isFormSchema } from '@rilaykit/forms';
const { formConfig, defaultValues } = compileForm(schema, catalog, { bindings });
```
| Export | Description |
| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `compileForm(schema, catalog, options?)` | Compile a `FormSchema` → `{ formConfig, defaultValues? }`. `options.bindings` resolves custom validator/effect string references; `options` can also enable per-field props validation |
| `fromSchema(schema, catalog, registry?)` | Same result, registry-style signature |
| `validateSchema(schema, catalog, registry?)` | Throws `SchemaValidationError` (with pathed `issues[]`) on invalid structure |
| `isFormSchema(value)` | Type guard |
```ts
interface FormSchema {
readonly version?: 1;
readonly id: string;
readonly defaultValues?: Record;
readonly fields?: FormSchemaField[]; // flat layout
readonly rows?: FormSchemaRow[]; // row-based layout (incl. repeatables)
readonly validation?: FormSchemaValidationConfig; // { rules?, mode?, reValidateMode? }
readonly submitOptions?: SubmitOptions;
}
interface FormSchemaField {
readonly id: string;
readonly type: string;
readonly props?: Record;
readonly validation?: { rules?: ValidationDescriptor | ValidationDescriptor[]; debounceMs?: number };
readonly conditions?: ConditionalBehavior;
readonly effects?: FieldSchemaEffect[];
}
// rules: 'required' | 'email' | 'url' | 'number' (shortcuts)
// or { type: string; message?: string; params?: Record }
interface SchemaRegistry { // alias: Bindings
readonly validators?: Record;
readonly effects?: Record;
}
```
***
## @rilaykit/workflow [#rilaykitworkflow]
Builder and flow-schema compiler from `@rilaykit/workflow`; components and hooks from `@rilaykit/workflow/react`.
### Components [#components-1]
```tsx
import { Flow } from '@rilaykit/workflow/react';
save(data, meta)}>
```
#### `Flow` [#flow]
Compound root (`Flow.Body`, `Flow.Progress`, `Flow.Next`, `Flow.Back`, `Flow.Skip`). Wraps `WorkflowProvider`.
| Prop | Type | Description |
| --------------- | --------------------------------------------------------------- | ------------------------------------------- |
| `of` | `WorkflowConfig \| flow` | Built configuration or builder (auto-built) |
| `defaults?` | `Record` | Initial data |
| `defaultStep?` | `string` | Step ID to start on |
| `onStepChange?` | `(from: number, to: number, context) => void` | Step transition callback |
| `onComplete?` | `(data, meta: WorkflowCompletionMeta) => void \| Promise` | See below |
| `className?` | `string` | CSS class |
**Completion**: `data` is a pure projection — only answered visible steps; a skipped or never-visible step is absent (no `{}` placeholder). `meta` (`{ visitedSteps, skippedSteps, passedSteps }`, `string[]` in insertion order, exported from `@rilaykit/workflow/react`) is additive: `onComplete(data)` callers keep working. `visitedSteps` records steps navigated *to*; the entry step is not included.
| Component | Props |
| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Flow.Body` | `stepId?` (render only for that step), `children?: ReactNode \| (({ step }) => ReactNode)` — falls back to the step's `renderer`, then `` |
| `Flow.Progress` | `children?: (ctx: FlowStepsContext) => ReactNode` (`{ steps, currentIndex, goTo }`), `className?` |
| `Flow.Next` / `Flow.Back` / `Flow.Skip` | `children?: ReactNode \| ((ctx: FlowNavContext) => ReactNode)` (`{ go, canGo, submitting, isLastStep, step }`), `className?` |
`useFlow()` returns the full `WorkflowContextValue`: workflow state, `currentStep`, navigation (`goToStep`, `goNext`, `goPrevious`, `skipStep`, `canGoNext`, …), data actions (`setValue`, `setStepData`, `resetWorkflow`), submission (`submitWorkflow`, `canSubmit`), and persistence (`persistNow`, `isPersisting`, `persistenceError`).
### flow (FlowBuilder) [#flow-flowbuilder]
```ts
import { flow } from '@rilaykit/workflow';
const onboarding = flow.create(catalog, 'onboarding', 'User Onboarding')
.step({
id: 'basics',
title: 'Basics',
formConfig: basicsForm,
after: async (step) => {
const company = await fetchCompany(step.data.siren);
step.next.prefill({ companyName: company.name });
},
})
.step([
{ title: 'Company', formConfig: companyForm },
{ title: 'Review', formConfig: reviewForm, allowSkip: true },
]);
```
**StepDefinition**: `id?`, `title`, `description?`, `formConfig` (built config or builder), `allowSkip?` (boolean or predicate on workflow data), `renderer?`, `conditions?` (`{ visible?, skippable? }`), `metadata?`, `after?`.
**`after(step)`** runs after successful validation, before navigating. `StepContext`:
| Member | Description |
| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `step.data` | The step's validated data |
| `step.next.prefill(fields)` | Write fields into the next **visible** step (a conditionally hidden step never swallows the prefill). Overwrite-always and re-runs on every forward transition — guard on the value for seed-if-empty |
| `step.workflow.get(stepId)` / `step.workflow.all()` | Other steps' data |
| `step.meta`, `step.isFirst`, `step.isLast` | Metadata and position |
The legacy `onAfterValidation(stepData, helper, context)` signature still works but is deprecated — use `after`.
| Method | Description |
| ------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `.step(def)` / `.step([defs])` (alias `.addStep`) | Add steps |
| `.configure({ analytics?, persistence? })` | `analytics: WorkflowAnalytics`; `persistence: { adapter, options?, userId? }` |
| `.use(plugin)` / `.removePlugin(name)` | Plugins (dependencies validated on install) |
| `.updateStep(id, updates)` / `.removeStep(id)` | Mutate steps |
| `.addStepConditions(id, { visible?, skippable? })` | Conditions after creation |
| `.getStep(id)` / `.getSteps()` / `.clearSteps()` | Read back / reset |
| `.clone(newId?, newName?)` / `.validate()` / `.build()` | Utilities; `.build()` throws on invalid |
| `.toJSON()` / `.fromJSON(json)` / `.getStats()` | Serialization, stats |
Skip semantics: a step is re-skippable after navigating back onto it; a step later completed stops counting as skipped. `onStepSkip(stepId, reason)` currently always reports `'user_skip'`.
### Hooks [#hooks-1]
From `@rilaykit/workflow/react`.
| Hook | Returns |
| -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `useFlow()` | Full workflow context (see above) |
| `useFlowStepIndex()` | `number` |
| `useFlowTransitioning()` / `useFlowInitializing()` / `useFlowSubmitting()` | `boolean` |
| `useFlowData()` | All data across steps |
| `useStepData()` / `useStepDataById(stepId)` | Current / specific step data |
| `useVisitedSteps()` / `usePassedSteps()` / `useSkippedSteps()` | `Set` |
| `useIsStepVisited(id)` / `useIsStepPassed(id)` / `useIsStepSkipped(id)` | `boolean` |
| `useFlowNavigationState()` | `{ currentStepIndex, isTransitioning, isSubmitting }` |
| `useFlowSubmitState()` | `{ isSubmitting, isTransitioning, isInitializing }` |
| `useFlowActions()` | Store actions: `setCurrentStep`, `setStepData`, `setAllData`, `setFieldValue`, `setSubmitting`, `setTransitioning`, `setInitializing`, `markStepVisited/Passed/Skipped`, `reset`, `loadPersistedState` |
| `useFlowSteps()` | `{ steps, currentIndex, goTo }` (drives `Flow.Progress`) |
| `useStepMetadata()` | `current`, `getByStepId`, `getByStepIndex`, `hasCurrentKey`, `getCurrentValue`, `getAllStepsMetadata`, `findStepsByMetadata` |
| `useFlowStoreApi()` | Store ref for imperative reads |
### Persistence [#persistence]
Configured via `.configure({ persistence: { adapter, options?, userId? } })`.
* Values survive save→load byte-faithfully: `Date`, `NaN`, `±Infinity`, `-0`, `BigInt` are tag-encoded; legacy plain-JSON blobs still load.
* A pending debounced autosave is flushed on unmount; completion clears persisted data and a late in-flight save cannot resurrect it.
* Corrupted blobs degrade to a fresh start (`LOAD_FAILED` on `persistenceError`); out-of-range step indexes clamp; resume into a now-hidden step relocates forward to the next visible step.
### Analytics [#analytics]
Every workflow error path routes through `analytics.onError(error, context)` and the monitoring adapter: step-transition failures, `after` throws, submission throws, and persistence save/load/remove failures (`WorkflowPersistenceError`). A validation error blocking Next is **not** an error path. The last step fires no `onStepComplete` — completion is carried by `onWorkflowComplete(id, duration, data)` with the same projected data as `onComplete`.
### Flow Schemas [#flow-schemas]
```ts
import { compileFlow, validateFlowSchema, isFlowSchema } from '@rilaykit/workflow';
const { workflowConfig } = compileFlow(schema, catalog, { bindings });
```
`validateFlowSchema` reports pathed issues; `SchemaValidationError` is re-exported from `@rilaykit/workflow` for flow-schema failures.
***
## @rilaykit/agent [#rilaykitagent]
AI-agent integration (re-exported by `rilaykit`). Mains are React-free. See the [AI guide](/docs/ai) for the full walkthrough.
| Export | Entry | Description |
| ------------------------------------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `manifest(catalog)` | main | Markdown catalog manifest for the system prompt |
| `uiTools()` | main | Registers `show_form` / `show_flow` / `show_component` (schema-only tools, no `execute`) |
| `parsePartialJson(text)` | main | Streaming-tolerant JSON parsing |
| `Part`, `isTextPart`, `isToolPart`, `isDataPart` | main | Normalized message-part model |
| `Catalog`, `Parts`, `Part`, `ShowForm`, `ShowFlow`, `ShowComponent` | `/react` | HITL rendering components |
| `tools(catalog)`, `toParts(message)` | `rilaykit/ai-sdk` | Vercel AI SDK adapter — `tools()` is assignable to `ToolSet` with no cast; `toParts` maps `UIMessage` parts (all four tool states, `dynamic-tool`, `data-*`) |
| `tools(catalog)`, `toParts(message)` | `rilaykit/anthropic` | Anthropic SDK adapter — `Anthropic.Tool[]`-compatible, maps `text` / `tool_use` blocks |
Tool JSON schemas come from the Standard Schema's `~standard.jsonSchema.output` or a manual `inputJsonSchema`; a tool with neither is dropped and logged. Hosts must register a `.part('text', …)` renderer — there is no default. `show_form` resolves `{ status: 'submitted', values }` or `{ status: 'cancelled' }` exactly once per `toolCallId`.
***
## Types [#types]
### Validation [#validation]
```ts
interface FieldError {
readonly message: string;
readonly code?: string;
readonly path?: string;
}
interface ValidationResult {
readonly isValid: boolean;
readonly errors: FieldError[];
readonly value?: any;
}
type ValidationState = 'idle' | 'validating' | 'valid' | 'invalid';
interface FieldValidationConfig {
readonly validate?: StandardSchema | StandardSchema[];
readonly debounceMs?: number; // async cost control; blur/submit validate immediately
}
type FormValidationMode = 'onSubmit' | 'onBlur' | 'onChange' | 'onTouched' | 'all';
type FormReValidateMode = 'onChange' | 'onBlur' | 'onSubmit';
interface FormValidationConfig = Record> {
readonly validate?: StandardSchema | StandardSchema[];
readonly mode?: FormValidationMode; // default 'onTouched'
readonly reValidateMode?: FormReValidateMode; // default 'onChange'
readonly validateOnStepChange?: boolean;
}
```
### Conditions [#conditions]
```ts
interface ConditionConfig {
field: string;
operator: ConditionOperator;
value?: ConditionValue;
conditions?: ConditionConfig[];
logicalOperator?: 'and' | 'or';
}
type ConditionValue =
| string | number | boolean | null | undefined
| RegExp | Array;
interface ConditionalBehavior {
readonly visible?: ConditionConfig;
readonly disabled?: ConditionConfig;
readonly required?: ConditionConfig;
readonly readonly?: ConditionConfig;
}
interface StepConditionalBehavior {
readonly visible?: ConditionConfig;
readonly skippable?: ConditionConfig;
}
```
### Workflow [#workflow]
```ts
interface WorkflowCompletionMeta {
readonly visitedSteps: string[];
readonly skippedSteps: string[];
readonly passedSteps: string[];
}
interface WorkflowAnalytics {
readonly onWorkflowStart?: (workflowId: string, context: WorkflowContext) => void;
readonly onWorkflowComplete?: (workflowId: string, duration: number, data: any) => void;
readonly onWorkflowAbandon?: (workflowId: string, currentStep: string, data: any) => void;
readonly onStepStart?: (stepId: string, timestamp: number, context: WorkflowContext) => void;
readonly onStepComplete?: (stepId: string, duration: number, data: any, context: WorkflowContext) => void;
readonly onStepSkip?: (stepId: string, reason: string, context: WorkflowContext) => void;
readonly onError?: (error: Error, context: WorkflowContext) => void;
}
interface WorkflowPlugin {
readonly name: string;
readonly version?: string;
readonly install: (workflow: any) => void;
readonly dependencies?: string[];
}
```
For `MonitoringConfig` and the monitoring pipeline, see the [monitoring docs](/docs/monitoring).
# Examples Gallery
# Examples Gallery [#examples-gallery]
Copy-paste examples covering common setups. For full production scenarios (SaaS onboarding, KYC verification, dynamic pricing), see the [Real-World Examples](/docs/guides/real-world-examples) guide.
## Simple Contact Form [#simple-contact-form]
Register a renderer, build a form, render it.
```tsx title="ContactForm.tsx"
import { ril, required, email, minLength } from 'rilaykit';
import type { ComponentRenderContext } from 'rilaykit';
import { Form } from 'rilaykit/react';
interface InputProps {
label: string;
type?: string;
placeholder?: string;
}
function Input({ id, props, field }: ComponentRenderContext) {
return (
);
}
```
## 3. Register Components [#3-register-components]
```tsx title="lib/rilay.ts"
import { ril } from 'rilaykit';
import { Input } from '../components/Input';
export const rilay = ril.create().component('input', { renderer: Input });
```
## 4. Build the Form [#4-build-the-form]
```tsx title="forms/login.ts"
import { email, required } from 'rilaykit';
import { rilay } from '../lib/rilay';
export const loginForm = rilay.form('login')
.add({
id: 'email',
type: 'input',
props: { label: 'Email', type: 'email' },
validation: { validate: [required(), email()] },
})
.add({
id: 'password',
type: 'input',
props: { label: 'Password', type: 'password' },
validation: { validate: [required()] },
})
.build();
```
By default fields validate on first blur, then re-validate on every keystroke. Tune with `.setValidation({ mode, reValidateMode })`.
## 5. Render It [#5-render-it]
Components and hooks import from `rilaykit/react`:
```tsx title="components/LoginForm.tsx"
import { Form, FormField } from 'rilaykit/react';
import { loginForm } from '../forms/login';
export function LoginForm() {
return (
);
}
```
Done — mount `` anywhere.
## Common Patterns [#common-patterns]
### Multiple Input Types [#multiple-input-types]
```tsx
export const rilay = ril.create()
.component('input', { renderer: Input })
.component('textarea', { renderer: TextareaInput })
.component('select', { renderer: SelectInput });
```
### Validation with Zod [#validation-with-zod]
Any Standard Schema library works directly — no adapter:
```tsx
import { z } from 'zod';
const userForm = rilay.form('user')
.add({
id: 'email',
type: 'input',
validation: { validate: z.string().email() },
});
```
### Conditional Fields [#conditional-fields]
```tsx
import { when } from 'rilaykit';
const accountForm = rilay.form('account')
.add({
id: 'accountType',
type: 'select',
props: { options: [{ value: 'business', label: 'Business' }] },
})
.add({
id: 'companyName',
type: 'input',
conditions: { visible: when('accountType').equals('business') },
});
```
### Cross-Field Validation [#cross-field-validation]
Form-level rules run on the same cadence as field validation. An issue whose `path` names a field attaches to that field; pathless issues land in the `__form__` bucket, read via `useFormErrors()`:
```tsx
import { z } from 'zod';
const signupForm = rilay.form('signup')
.add({ id: 'password', type: 'input', props: { label: 'Password', type: 'password' } })
.add({ id: 'confirmPassword', type: 'input', props: { label: 'Confirm', type: 'password' } })
.setValidation({
validate: z
.object({ password: z.string(), confirmPassword: z.string() })
.refine((d) => d.password === d.confirmPassword, {
message: 'Passwords do not match',
path: ['confirmPassword'],
}),
})
.build();
```
## What's Next? [#whats-next]
* [Your First Form](/getting-started/your-first-form) — step-by-step tutorial
* [Validation](/core-concepts/validation) — timing modes, Standard Schema, async
* [Advanced Forms](/forms/advanced-forms) — conditions, effects, repeatables
* [Workflows](/workflow/building-workflows) — multi-step flows and wizards
* [Examples](/examples) — real-world patterns
* [Discord](https://discord.gg/rilay) — get help from the community
# Roadmap
# Roadmap [#roadmap]
Public roadmap, organized by phase. Priorities may shift with community feedback. Code samples in unshipped phases are proposals, not final APIs.
Want to influence the roadmap? [Open a discussion](https://github.com/andyoucreate/rilaykit/discussions) or upvote existing proposals.
***
## Phase 5 — AI-Assisted Form Filling [#phase-5--ai-assisted-form-filling]
**Status:** Next up
The foundation shipped: `@rilaykit/agent` lets an LLM *render* forms and flows as chat tools (`show_form`, `show_flow`, `show_component`) with AI SDK and Anthropic adapters. Next: letting an LLM *fill* an existing form from unstructured text. Since RilayKit forms are data, the AI knows every field's type, constraints, and validation rules.
### `useAIFormFill()` — Text-to-Form Mapping [#useaiformfill--text-to-form-mapping]
```tsx
const { fillFromText, isProcessing } = useAIFormFill(formConfig, {
provider: 'openai', // or 'anthropic', 'custom'
});
await fillFromText(
"My name is Karl, I live in Paris, my email is karl@example.com"
);
// → setValue('name', 'Karl')
// → setValue('city', 'Paris')
// → setValue('email', 'karl@example.com')
```
Unlocks paste-to-fill from emails or transcripts, voice-to-form via speech-to-text, and bulk import from unstructured sources.
Opt-in and provider-agnostic — RilayKit will not bundle an AI SDK.
***
## Phase 2 — Data Transform Pipeline [#phase-2--data-transform-pipeline]
**Status:** Planned
Declarative transforms around submission — sanitization, field exclusion, reshaping — without `onSubmit` boilerplate.
### `transform()` — Pre/Post Submission Hooks [#transform--prepost-submission-hooks]
```tsx
form.create(r, 'register')
.add(/* fields */)
.transform({
before: (data) => ({
...data,
email: data.email.trim().toLowerCase(),
}),
after: (data) => omit(data, ['confirmPassword', 'acceptTerms']),
})
.build();
```
***
## Phase 3 — Cross-Step Workflow Validation [#phase-3--cross-step-workflow-validation]
**Status:** Planned
Form-level cross-field validation already shipped (`setValidation({ validate })`, path-routed errors, `useFormErrors()`), but each workflow step still validates independently. This phase adds rules that span steps, reusing the same path-keyed error routing.
### `crossValidate()` — Multi-Step Validation Rules [#crossvalidate--multi-step-validation-rules]
```tsx
flow.create(r, 'checkout', 'Checkout')
.step({ id: 'shipping', title: 'Shipping', formConfig: shippingForm })
.step({ id: 'billing', title: 'Billing', formConfig: billingForm })
.crossValidate({
validate: (allData) => {
const errors: Record = {};
if (allData.billing.sameAsShipping && !allData.shipping.address) {
errors['shipping.address'] = 'Required when "same as shipping" is checked';
}
return errors;
},
trigger: 'before-complete' // or 'on-step-leave'
})
.build();
```
***
## Phase 6 — DevTools [#phase-6--devtools]
**Status:** Planned
A visual inspector panel (similar to React Query DevTools) surfacing form and workflow state in real time.
### `` — Visual Inspector [#rilaydevtools---visual-inspector]
```tsx
{process.env.NODE_ENV === 'development' && }
```
**Planned capabilities:**
* **Field Inspector** — live values, errors, touched state, active conditions
* **Condition Graph** — which fields affect which conditions
* **Validation Timeline** — validation runs with timing and results
* **Workflow Navigator** — step state, visited/passed steps, accumulated data
* **Performance Panel** — render counts and hotspots, powered by the existing monitoring system in `@rilaykit/core`
***
## Phase 7 — Plugin System [#phase-7--plugin-system]
**Status:** Exploring
A public plugin API for extending form and workflow behavior. The `WorkflowPlugin` type already exists internally — this phase promotes and documents it.
### `createPlugin()` — Lifecycle Hooks [#createplugin--lifecycle-hooks]
```tsx
import { createPlugin } from 'rilaykit';
const autosavePlugin = createPlugin({
id: 'autosave',
onFieldChange: debounce(async (fieldId, value, { allValues }) => {
await saveDraft(allValues);
}, 1000),
onStepComplete: (stepId, stepData) => {
analytics.track('step_completed', { stepId });
},
});
flow.create(r, 'onboarding', 'Onboarding')
.configure({ plugins: [autosavePlugin] })
.build();
```
Community plugin ideas: autosave, analytics, A/B testing, feature flags, undo/redo.
***
## Completed [#completed]
Shipped in the current release:
| Feature | Package | Status |
| ------------------------------------------------------------------------------------------------- | ------------------------------------ | ------- |
| Immutable component registry | `@rilaykit/core` | Shipped |
| Standard Schema validation (Zod, Valibot, Yup, ArkType) | `@rilaykit/core` | Shipped |
| Declarative conditions with `when()` builder | `@rilaykit/core` | Shipped |
| Performance monitoring & adapters | `@rilaykit/core` | Shipped |
| Form builder with type-safe field config | `@rilaykit/forms` | Shipped |
| Granular Zustand store selectors | `@rilaykit/forms` | Shipped |
| Repeatable fields with min/max | `@rilaykit/forms` | Shipped |
| Async field validation with `debounceMs` | `@rilaykit/forms` | Shipped |
| Validation timing — `mode` / `reValidateMode` (RHF model) | `@rilaykit/forms` | Shipped |
| Path-keyed error map + `useFormErrors()` form-level bucket | `@rilaykit/forms` | Shipped |
| Multi-step workflow builder | `@rilaykit/workflow` | Shipped |
| Step navigation with validation guards | `@rilaykit/workflow` | Shipped |
| Workflow persistence (LocalStorage, type-faithful serialization) | `@rilaykit/workflow` | Shipped |
| Completion meta — `onComplete(data, meta)` with visited/skipped/passed steps | `@rilaykit/workflow` | Shipped |
| Workflow analytics hooks | `@rilaykit/workflow` | Shipped |
| Step conditions (visible, skippable) | `@rilaykit/workflow` | Shipped |
| All-in-one `rilaykit` package with `.form()` / `.flow()` | `rilaykit` | Shipped |
| Field effects with `onChange()` — cascades, dynamic props, calculated fields | `@rilaykit/core` + `@rilaykit/forms` | Shipped |
| `useFieldProps` hook for dynamic field props | `@rilaykit/forms` | Shipped |
| Server-driven forms — `fromSchema()`, `compileForm`, `validateSchema`, `isFormSchema` | `@rilaykit/forms` | Shipped |
| Server-driven flows — `compileFlow` | `@rilaykit/workflow` | Shipped |
| Agent chat tools — `show_form` / `show_flow` / `show_component` with human-in-the-loop resolution | `@rilaykit/agent` | Shipped |
| `manifest()` — catalog to Markdown for system prompts | `@rilaykit/agent` | Shipped |
| AI SDK & Anthropic adapters (`rilaykit/ai-sdk`, `rilaykit/anthropic`) | `rilaykit` | Shipped |
| RSC-safe isomorphic entries (React-free mains, `/react` client entries) | all packages | Shipped |
# What's New
# What's New [#whats-new]
P3 ships the agent package, an honest forms API, and reliability work across the stack.
## Agent package [#agent-package]
`@rilaykit/agent` (re-exported by `rilaykit`) lets a model emit real RilayKit forms and flows as tool calls, and lets your users answer them — human-in-the-loop, typed end to end.
* `manifest(catalog)` renders your catalog as Markdown for the system prompt.
* `uiTools()` registers `show_form` / `show_flow` / `show_component` — schema-only tools, no `execute`.
* Adapters: `rilaykit/ai-sdk` and `rilaykit/anthropic`. `tools(catalog)` is assignable to the SDK's tool type with no cast; `toParts(message)` maps real message parts, all tool states covered. Verified against `ai@5.0.215` and `@anthropic-ai/sdk@0.112.1`.
* Standard Schema is vendor-neutral: zod, valibot, arktype. Tool JSON schema comes from `~standard.jsonSchema.output` or a manual `inputJsonSchema`; a tool with neither is dropped and logged.
* Mains are React-free (RSC/server-safe). Components and hooks come from `/react`.
```tsx
// server
import { manifest } from 'rilaykit';
import { tools } from 'rilaykit/ai-sdk';
streamText({ model, system: manifest(catalog), tools: tools(catalog) });
// client — show_form resolves { status: 'submitted', values } exactly once
addToolResult(output)} />
```
Built-in `ShowFlow` renders binding-free schemas (built-in validators, conditions, repeatables). For custom logic or persistence, plug a host renderer via `.renderers({ tools: {…} })`. Hosts must register `.part('text', …)` — there is no default text renderer.
## Honest API refactor [#honest-api-refactor]
### Two-phase validation timing [#two-phase-validation-timing]
Per-field timing flags are gone. One form-level call controls when a field first validates and how it re-validates after an error:
```ts
form.setValidation({ mode: 'onTouched', reValidateMode: 'onChange' });
```
| Option | Values | Default |
| ---------------- | -------------------------------------------------------------- | ------------- |
| `mode` | `'onSubmit' \| 'onBlur' \| 'onChange' \| 'onTouched' \| 'all'` | `'onTouched'` |
| `reValidateMode` | `'onChange' \| 'onBlur' \| 'onSubmit'` | `'onChange'` |
Default behavior: validate on first blur, then live. Submit always validates and marks errored fields `touched`. Per-field `debounceMs` stays for async cost control; blur and submit always validate immediately.
### Path-keyed error map [#path-keyed-error-map]
Cross-field issues now route by `issue.path`: a path naming a known field attaches to that field; empty or unmatched paths land in the reserved `__form__` bucket. The new `useFormErrors()` hook (from `rilaykit/react`) returns that bucket — use it for a form-level error banner. `isValid` counts the whole map. Form-level rules re-run on the same `mode`/`reValidateMode` cadence as fields, and on repeatable row add/remove/move — cross-field errors appear and clear live, no resubmit.
### Completion payload projection [#completion-payload-projection]
`onComplete(data, meta)` — `data` contains only answered visible steps. A skipped or never-visible step is absent, not an `{}` placeholder. The new `meta` argument carries `{ visitedSteps, skippedSteps, passedSteps }`. Additive: existing `onComplete(data)` callers keep working.
## Reliability & performance [#reliability--performance]
| Area | Change |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Persistence | `Date`, `NaN`, `±Infinity`, `-0`, `BigInt` survive save→load byte-faithfully; a pending debounced autosave is flushed on unmount; completion clears persisted data; corrupted blobs degrade to a fresh start (`LOAD_FAILED` on `persistenceError`). |
| Observability | Every workflow error path routes through `trackError` → both `analytics.onError(error, workflowContext)` and the monitoring adapter: step transitions, `onAfterValidation` throws, submission throws, persistence failures. |
| Render isolation | A keystroke re-renders only the typed field — O(1) even at 200 fields with conditionals. Appending a repeatable row does not re-render surviving rows. |
## Breaking changes [#breaking-changes]
| Removed | Replacement |
| ----------------------------------------------------------- | ------------------------- |
| Per-field `validateOnChange` / `validateOnBlur` | Form-level `mode` |
| Form-level `validateOnSubmit` | `mode` + `reValidateMode` |
| `next.skip()` / `workflow.goto()` (never-implemented stubs) | — |
Migration — per-field `validate` is unchanged; only the timing flags move:
```diff
- .validation({ validateOnChange: true, validateOnBlur: true, validate: schema })
+ .validation({ validate: schema })
+ form.setValidation({ mode: 'onChange', reValidateMode: 'onChange' });
```
# Why RilayKit
## The Problem [#the-problem]
Forms in React are usually built imperatively: JSX mixed with state management, validation scattered across components, nothing serializable, and every multi-step flow a hand-rolled state machine. UI and business logic end up coupled, every form is a one-off, and type safety is bolted on.
RilayKit treats forms as data structures instead of UI trees.
## Schema-First: Forms as Data [#schema-first-forms-as-data]
Form configurations are plain, serializable objects. You describe what a form contains; the library handles rendering and behavior.
```tsx
import { ril, required, email } from '@rilaykit/core';
import { form } from '@rilaykit/forms';
const rilay = ril.create()
.component('input', { renderer: YourInputComponent });
const onboardingForm = form.create(rilay, 'onboarding')
.add({
id: 'email',
type: 'input',
props: { label: 'Email' },
validation: { validate: [required(), email()] },
});
// A form config is just data -- serialize it, store it, version it
const json = onboardingForm.toJSON();
```
Because a form is data, it is introspectable (iterate fields, read rules), serializable (store in a database, send over the network), clonable (`form.clone()` for A/B variants or per-tenant customization), and generatable from a server, CMS, or visual editor.
## Component Registry: Define Once, Use Everywhere [#component-registry-define-once-use-everywhere]
Components are registered once on the `ril` instance; every form uses them. The same schema renders with completely different design systems:
```tsx
// Design system A
const rilayMaterial = ril.create()
.component('input', { renderer: MaterialInput });
// Design system B
const rilayShadcn = ril.create()
.component('input', { renderer: ShadcnInput });
// Same form definition works with both
const loginForm = form.create(rilayMaterial, 'login')
.add({ id: 'email', type: 'input', props: { label: 'Email' } });
```
Your UI components stay in your design system. RilayKit handles state, validation, conditions, and rendering orchestration -- no imposed styling, no vendor lock-in on the visual layer.
## Type Propagation: Safety Without Boilerplate [#type-propagation-safety-without-boilerplate]
`.component('input', { renderer: MyInput })` captures `MyInput`'s exact props interface. Every later `.add({ type: 'input', props })` gets autocompletion and compile-time checking. You never write type annotations for forms -- types flow from component definitions through the builder chain.
```tsx
const rilay = ril.create()
.component('text', { renderer: TextInput }) // captures TextInputProps
.component('select', { renderer: SelectInput }); // captures SelectProps
form.create(rilay, 'example')
.add({
id: 'country',
type: 'select', // 'type' narrowed to 'text' | 'select'
props: {
label: 'Country',
options: [{ value: 'us', label: 'US' }], // required by SelectProps
},
});
```
## Universal Validation [#universal-validation]
A single `validation.validate` field accepts built-in validators, custom functions, and any [Standard Schema](https://standardschema.dev) library (Zod, Valibot, ArkType, ...) -- mixed in the same array, no adapters:
```tsx
import { z } from 'zod';
import { required, custom } from '@rilaykit/core';
.add({
id: 'email',
type: 'input',
props: { label: 'Email' },
validation: {
validate: [
required('Email is required'),
z.string().email('Invalid format'),
custom((value) => !value.endsWith('.test'), 'No test domains'),
],
},
})
```
Validation timing is configured once at the form level with `.setValidation({ mode, reValidateMode })` -- the same two-phase model as React Hook Form (`mode` for first validation, `reValidateMode` once a field has errored).
## Declarative Conditions [#declarative-conditions]
Conditional logic is declared with `when()` -- no `useEffect`, no manual subscriptions:
```tsx
import { when } from '@rilaykit/core';
.add({
id: 'companyName',
type: 'input',
props: { label: 'Company Name' },
conditions: {
visible: when('accountType').equals('business'),
required: when('accountType').equals('business'),
},
})
```
Conditions drive visibility, required, disabled, and readonly state. They compose with `.and()` / `.or()`, support dot-notation paths, and offer operators from `equals` through `greaterThanOrEqual`, `contains`, `in`, `matches`, and `exists`. A field hidden by a condition skips validation automatically.
## Real Workflow Engine [#real-workflow-engine]
`@rilaykit/workflow` is a workflow engine on the same schema-first foundation, not a wizard with hidden divs:
```tsx
import { flow, LocalStorageAdapter } from '@rilaykit/workflow';
const onboarding = flow.create(rilay, 'onboarding', 'User Onboarding')
.step({ id: 'account', title: 'Create Account', formConfig: accountForm })
.step({ id: 'profile', title: 'Your Profile', formConfig: profileForm, allowSkip: true })
.configure({
persistence: {
adapter: new LocalStorageAdapter({ maxAge: 7 * 24 * 60 * 60 * 1000 }),
options: { autoPersist: true, debounceMs: 500 },
},
analytics: {
onStepComplete: (stepId, duration) => trackEvent('step_complete', { stepId, duration }),
onWorkflowComplete: (id, duration) => trackEvent('workflow_complete', { id, duration }),
},
});
```
The engine provides step navigation with guards and step-level validation, persistence through an adapter interface (localStorage or any backend), analytics callbacks, a plugin system (`.use(plugin)`), and cross-step conditions via `when('stepId.fieldId')`. On completion, `onComplete(data, meta)` receives only the answered visible steps, plus `meta.visitedSteps` / `skippedSteps` / `passedSteps`.
## Agent-Ready [#agent-ready]
Because forms and flows are data, `@rilaykit/agent` can hand them to an LLM: `manifest(catalog)` documents your catalog in the system prompt, `uiTools()` exposes `show_form` / `show_flow` / `show_component` as schema-only tools, and adapters for the Vercel AI SDK (`rilaykit/ai-sdk`) and Anthropic (`rilaykit/anthropic`) plug into real chat loops. The model asks; the user answers through your validated, type-safe form.
## Who Is RilayKit For? [#who-is-rilaykit-for]
Teams building complex user-facing flows (SaaS onboarding, KYC, insurance claims, multi-step checkout), products with multiple design systems that share form logic, and developers who want multi-step workflows without hand-rolling state machines. MIT licensed, free, open source.
Head to the [installation guide](/getting-started/installation) to set up RilayKit, or jump to the [quickstart](/quickstart) to build your first form.
# Advanced Forms
Beyond one-time configuration, the form builder can inspect, modify, clone, and serialize form definitions.
## Dynamic Form Management [#dynamic-form-management]
Modify a form configuration after creation:
| Method | Description |
| -------------------------------- | ------------------------------------------------ |
| `.updateField(fieldId, updates)` | Modifies an existing field's configuration |
| `.removeField(fieldId)` | Removes a field |
| `.getField(fieldId)` | Returns a field's configuration, or `undefined` |
| `.getFields()` | Returns a flat array of all field configurations |
| `.getRows()` | Returns all row configurations |
| `.clear()` | Removes all fields and rows |
```tsx
import { rilay } from '@/lib/rilay';
import { form } from '@rilaykit/forms';
const myDynamicForm = form.create(rilay, 'dynamic-form')
.add({ id: 'username', type: 'text', props: { label: 'Username' } });
if (shouldAddEmail) {
myDynamicForm.add({ id: 'email', type: 'email', props: { label: 'Email' } });
}
myDynamicForm.updateField('username', {
props: { label: 'Please enter your desired username' }
});
const formConfig = myDynamicForm.build();
```
Builder methods mutate the builder instance. To create variations, use `.clone()` first.
## Cloning [#cloning]
`.clone(newFormId?)` deep-copies the builder so variations don't affect the original.
```tsx
const baseForm = form.create(rilay, 'base-form')
.add({ id: 'name', type: 'text', props: { label: 'Name' } });
const adminForm = baseForm.clone('admin-form')
.add({ id: 'adminNotes', type: 'textarea', props: { label: 'Admin Notes' } });
// baseForm is unaffected
```
## Serialization (JSON Import/Export) [#serialization-json-importexport]
`.toJSON()` exports the form structure as a JSON-serializable object; `.fromJSON(json)` populates a builder from one. Use this to store definitions in a database, drive a visual form builder, or send structures over the network.
```tsx
const originalForm = form.create(rilay, 'question-form')
.add({ id: 'question', type: 'text', props: { label: 'Your Question' } });
const jsonString = JSON.stringify(originalForm.toJSON());
// Later, or in another environment
const rehydratedForm = form.create(rilay).fromJSON(JSON.parse(jsonString));
const formConfig = rehydratedForm.build();
```
`fromJSON` replaces the content of an existing builder — call it on a freshly created builder to avoid mutating a shared instance.
## Introspection [#introspection]
`.getStats()` returns a structural overview, useful for debugging:
```ts
const stats = myFormBuilder.getStats();
/*
{
totalFields: 5,
totalRows: 4,
averageFieldsPerRow: 1.25,
maxFieldsInRow: 2,
minFieldsInRow: 1,
totalRepeatables: 0,
totalRepeatableFields: 0
}
*/
```
# Building Forms
`rilay.form(id)` (or `form.create(rilay, id)` with modular packages) returns a form builder wired to your component registry. This page covers adding fields, submit options, and field effects — it assumes a configured `rilay` instance ([Your First Form](/docs/getting-started/your-first-form)).
## Adding Fields [#adding-fields]
`.add()` is polymorphic:
* `.add(field)` — one field on its own row
* `.add(field1, field2)` — multiple fields on the same row
* `.add([field1, field2])` — equivalent array syntax
```tsx
import { rilay } from '@/lib/rilay';
const registrationForm = rilay
.form('registration')
// Two fields on the same row
.add(
{ id: 'firstName', type: 'text', props: { label: 'First Name' } },
{ id: 'lastName', type: 'text', props: { label: 'Last Name' } }
)
// One field on its own row
.add({ id: 'email', type: 'email', props: { label: 'Email Address' } });
```
`type` must exist in your component registry. `addSeparateRows([...])` places each field of an array on its own row.
## Field Configuration [#field-configuration]
```ts
interface FieldConfig {
id?: string; // Auto-generated ('field-1', 'field-2', …) if omitted
type: string; // Component type from your registry
props?: Record; // Passed to your component renderer
validation?: FieldValidationConfig; // { validate?, debounceMs? } — see Validation
conditions?: ConditionalBehavior; // visible/required/disabled/readonly — see Conditions
effects?: FieldEffect[]; // Reactive side effects (below)
}
```
## When to use `.build()` [#when-to-use-build]
`
```
### `` [#formsubmit]
Renders a `