For the complete documentation index, see llms.txt. Markdown variants are available by appending .md to any URL or sending an Accept: text/markdown header. An agent skill is available at /.well-known/agent-skills/site-skill.md.
FrakmentFrakment

AI Helpers

Deterministic chat engine for building AI interfaces without a model.

@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

$ npm install @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

chat.ts
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 | null

Wire it to useChat from @ai-sdk/react:

tsx
import { useChat } from "@ai-sdk/react";
 
const { messages, sendMessage, status } = useChat({
  messages: initialMessages,
  transport,
});

createChat(options?)

Returns a chainable Chat object.

PropTypeDefaultDescription
messageIdPrefixstring—Prefix for generated message IDs.
toolCallIdPrefixstring—Prefix for tool call IDs.
sourceIdPrefixstring—Prefix for source citation IDs.
approvalIdPrefixstring—Prefix for approval request IDs.
now
Datestring
—Fixed clock for message metadata.
messagesUIMessage[]—Hydrate the builder from an existing transcript.

Chat methods

PropTypeDefaultDescription
.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?)

PropTypeDefaultDescription
delayMsnumber—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.

tsx
chat.assistant(({ writer }) => {
  writer
    .reasoning("Let me think...")
    .sleep(300)
    .text("Here's the answer:")
    .text("42", { mode: "instant" });
});

Writer methods

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

tsx
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:

tsx
const handle = writer.tool("long_task", { input: { jobId: 123 } });
handle
  .sleep(500)
  .output({ progress: 30 }, { preliminary: true })
  .sleep(500)
  .output({ result: "done" }); // final output
PropTypeDefaultDescription
.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.

tsx
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.");
    }
  });

Helper functions

getMessageText(message)

Extracts the concatenated text parts from a UIMessage. Returns "" if no text parts exist.

ts
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:

FilePurpose
types.tsPublic + internal TypeScript interfaces
ids.tsID generator with reserve/next semantics
utils.tsassertNever, abortableSleep, deepClone, splitWords, stripDataPrefix, devWarn
payloads.tsFile / reasoning / source / custom payload factory
envelope.tsmaterializeParts, eventsFromParts, eventsToEnvelope
stream.tsstreamFromEnvelope — ReadableStream<UIMessageChunk>
writer.tsEventWriter + ToolHandle DSL
builder.tsChatBuilder — core methods, continuation, transport
adapter.tsgetMessageText, getToolCalls, FrameworkAdapter
index.tsBarrel 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.