- Accordion
- Attachment
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Card
- Checkbox
- Code Block
- Collapsible
- Dialog
- Dropdown Menu
- Empty
- Field
- Hover Card
- Input
- Input Group
- Input OTP
- Item
- Label
- Marker
- Message
- Number Flow
- Pagination
- Popover
- Progress
- Radio Group
- Select
- Slider
- Sonner
- Spinner
- Switch
- Tooltip
- Separator
- Sheet
- Tabs
- Textarea
- Toggle
- Toggle Group
- Trace
@frakment/ai is Frakment's deterministic chat engine — a createChat() builder that scripts transcripts, streams them as AI SDK v7 UIMessageChunks, and lets you test chat UIs without calling a model.
Installation
$ bun add @frakment/ai$ npm install @frakment/ai$ pnpm add @frakment/ai$ yarn add @frakment/ai
The engine ships as an npm package. Components that use it list it as a dependency, so npx frakment add message-animated installs it for you automatically.
Quick start
import { createChat, getMessageText } from "@frakment/ai";
const chat = createChat()
.user("Hello")
.sleep(500)
.assistant("Hi! How can I help?")
.user("What's the weather?")
.assistant("It's sunny and 72°F.");
const initialMessages = chat.get(0); // UIMessage[]
const transport = chat.transport({ delayMs: 20 });
const nextMessage = chat.next(messages); // UIMessage | nullWire it to useChat from @ai-sdk/react:
import { useChat } from "@ai-sdk/react";
const { messages, sendMessage, status } = useChat({
messages: initialMessages,
transport,
});createChat(options?)
Returns a chainable Chat object.
| Prop | Type | Default | Description |
|---|---|---|---|
messageIdPrefix | string | — | Prefix for generated message IDs. |
toolCallIdPrefix | string | — | Prefix for tool call IDs. |
sourceIdPrefix | string | — | Prefix for source citation IDs. |
approvalIdPrefix | string | — | Prefix for approval request IDs. |
now | Datestring | — | Fixed clock for message metadata. |
messages | UIMessage[] | — | Hydrate the builder from an existing transcript. |
Chat methods
| Prop | Type | Default | Description |
|---|---|---|---|
.user(text?, options?) | Chat | — | Script a user turn (instant text). |
.assistant(input?, options?) | Chat | — | Script an assistant turn. String streams word-by-word; callback gets full DSL. |
.error(errorText?) | Chat | — | Script an assistant turn that streams a single error chunk. |
.sleep(delayMs) | Chat | — | Delay the next turn's stream. |
.get(count?) | UIMessage[] | — | Returns deep-cloned messages. Stops at the first continuation turn. |
.next(messages) | UIMessagenull | — | Returns the next queued user message after the given transcript. |
.transport(options?) | ChatTransport | — | Creates an AI SDK v7 transport that streams assistant responses. |
chat.transport(options?)
| Prop | Type | Default | Description |
|---|---|---|---|
delayMs | number | — | Delay between text deltas (ms). Set to 0 to disable. |
fallback | stringPART[](ctx) => void | — | Response when the transcript runs past the end of the script. |
The returned object implements the AI SDK v7 ChatTransport<UIMessage> interface — sendMessages() streams UIMessageChunk[], reconnectToStream() returns null (no server).
Assistant callback DSL
Pass a callback to .assistant() for full control over parts and timing. The callback receives a writer — a fluent DSL that appends events to the turn.
chat.assistant(({ writer }) => {
writer
.reasoning("Let me think...")
.sleep(300)
.text("Here's the answer:")
.text("42", { mode: "instant" });
});Writer methods
| Prop | Type | Default | Description |
|---|---|---|---|
.text(text?, { mode?, delayMs? }) | EventWriter | — | Append text. mode: "instant" emits one chunk instead of word-by-word. |
.reasoning(text?, opts?) | EventWriter | — | Append a reasoning part. |
.sleep(delayMs) | EventWriter | — | Insert a delay between events. |
.data({ type, id?, data }) | EventWriter | — | Append a data part. type: "data-<name>". |
.error(errorText?) | EventWriter | — | Stream an error chunk and end the turn. |
.tool(name, options?) | ToolHandle | — | Append a tool call. Returns a handle for output/error/denied. |
.sourceUrl(overrides?) | EventWriter | — | Append a URL source citation. |
.sourceDocument(overrides?) | EventWriter | — | Append a document source citation. |
.file(overrides?) | EventWriter | — | Append a file attachment. |
.reasoningFile(overrides?) | EventWriter | — | Append a reasoning file. |
.custom(kind?) | EventWriter | — | Append a custom part. |
.stepStart() | EventWriter | — | Mark the start of a new step. |
Tools
chat.assistant(({ writer }) => {
writer
.text("Searching...")
.tool("web_search", {
input: { query: "Next.js 16 release notes" },
output: { results: [...] },
title: "Web search",
})
.text("Found the answer.")
})writer.tool() returns a ToolHandle for streaming multi-step tools:
const handle = writer.tool("long_task", { input: { jobId: 123 } });
handle
.sleep(500)
.output({ progress: 30 }, { preliminary: true })
.sleep(500)
.output({ result: "done" }); // final output| Prop | Type | Default | Description |
|---|---|---|---|
.sleep(ms) | ToolHandle | — | Delay before the next event. |
.output(value, { preliminary? }) | ToolHandle | — | Stream an output. preliminary: true keeps the call open. |
.error(text?) | ToolHandle | — | Stream a tool error. |
.denied() | ToolHandle | — | Mark the tool call as denied by the user. |
Human-in-the-loop approvals
Set needsApproval: true to pause the turn. The follow-up .assistant(callback) becomes a continuation turn — it materializes only when a real transcript arrives, and receives { toolCall, toolCalls, messages } in its context.
chat
.user("Send an email to the team.")
.assistant(({ writer }) => {
writer.text("I'll send it, but I need your approval first.");
writer.tool("send_email", {
input: { to: "team@company.com", subject: "Update" },
needsApproval: true,
});
})
.assistant(({ writer, toolCall }) => {
if (toolCall?.approved) {
writer.text("Email sent.");
} else {
writer.text("Email was not sent.");
}
});A continuation turn has no materialized message until a live transcript
arrives. chat.get(count) stops before the first continuation turn, and
chat.next(messages) matches by message ID (fallback: role + text).
Helper functions
getMessageText(message)
Extracts the concatenated text parts from a UIMessage. Returns "" if no text parts exist.
import { getMessageText } from "@frakment/ai";
const text = getMessageText(messages[0]);getToolCalls(message)
Extracts tool call descriptors from a UIMessage. Each descriptor: { toolCallId, name, dynamic, input, output, errorText, state, approval? }.
Architecture
@frakment/ai is split into focused modules:
| File | Purpose |
|---|---|
types.ts | Public + internal TypeScript interfaces |
ids.ts | ID generator with reserve/next semantics |
utils.ts | assertNever, abortableSleep, deepClone, splitWords, stripDataPrefix, devWarn |
payloads.ts | File / reasoning / source / custom payload factory |
envelope.ts | materializeParts, eventsFromParts, eventsToEnvelope |
stream.ts | streamFromEnvelope — ReadableStream<UIMessageChunk> |
writer.ts | EventWriter + ToolHandle DSL |
builder.ts | ChatBuilder — core methods, continuation, transport |
adapter.ts | getMessageText, getToolCalls, FrameworkAdapter |
index.ts | Barrel export + createChat factory |
Behavior
@frakment/ai is a first-party chat engine, written to match the API contract that chat builders rely on. Every data-* attribute, ARIA role, timing constant, chunk encoding, and continuation semantic follows the same shape — swapping between @frakment/ai and other chat engines requires no consumer code changes.