Skip to content

The Open Standard for Generative UI

Add Autofix helpers to `@openuidev/server` (#1194)

AB68c928010638
diff --git a/.changeset/autofix-stream-pipeline.md b/.changeset/autofix-stream-pipeline.md
new file mode 100644
index 000000000..4ab0e53f3
--- /dev/null
+++ b/.changeset/autofix-stream-pipeline.md
@@ -0,0 +1,16 @@
+---
+"@openuidev/server": minor
+---
+
+Add `createAutofix` from `@openuidev/server/openai` for Chat Completions and
+`@openuidev/server/vercel` for Vercel AI SDK UI message streams.
+Both expose `fix({ generation, messages, signal })` for completed text.
+Streaming uses `chat.completions({ stream, messages, signal })` for Chat Completions,
+`responses()` for OpenAI Responses (not yet supported), and `ai({ stream, messages, signal })`
+for Vercel AI SDK UI message streams. Validate locally and call Autofix only for invalid UI.
+Streaming appends the complete corrected program as native text deltas before completion,
+preserving tool calls and metadata. A closed ```openui-lang fence is held back so the
+repair is inserted inside that same fence. The Vercel AI SDK 7 helper accepts
+`toUIMessageStream({ stream: result.stream })` output and returns AI SDK UI message SSE.
+`@openuidev/server/openai` also exports `storeChatCompletionHistory` and
+`chatCompletionMessagesToItems` (moved off the package root).
diff --git a/docs/content/docs/api-reference/index.mdx b/docs/content/docs/api-reference/index.mdx
index 69937eed7..0ccbd36de 100644
--- a/docs/content/docs/api-reference/index.mdx
+++ b/docs/content/docs/api-reference/index.mdx
@@ -17,6 +17,8 @@ The OpenUI SDK is split into packages that build on each other:
- **`@openuidev/langchain`** — LangChain and LangGraph integration primitives for transforming protocol-v2 agent streams into AG-UI events and relaying them to an OpenUI frontend over Web-standard Server-Sent Events.
+- **`@openuidev/server`** — Server utilities for OpenUI Gateway. Repair invalid OpenUI Lang with Autofix, and persist a completed turn as Conversations API items. Import from `/openai` or `/vercel`.
+
- **`@openuidev/react-email`** — Pre-built email component library and prompt options for model-generated emails that can be rendered to HTML with React Email.
- **`@openuidev/vue-lang`** — Vue 3 bindings for defining model-renderable components, generating prompts from those definitions, and rendering streamed OpenUI Lang in Vue apps.
@@ -41,6 +43,7 @@ The OpenUI SDK is split into packages that build on each other:
| A ready-made React chat surface | [`@openuidev/react-ui`](/docs/api-reference/react-ui) |
| OpenUI tool rendering in an assistant-ui application | [`@openuidev/assistant-ui`](/docs/api-reference/assistant-ui) |
| A LangChain or LangGraph agent connected to an OpenUI frontend | [`@openuidev/langchain`](/docs/api-reference/langchain) |
+| Autofix or conversation history on the Gateway | [`@openuidev/server`](/docs/api-reference/server) |
| Model-generated emails | [`@openuidev/react-email`](/docs/api-reference/react-email) |
| Vue integration | [`@openuidev/vue-lang`](https://github.com/thesysdev/openui/tree/main/packages/vue-lang) |
| Svelte integration | [`@openuidev/svelte-lang`](https://github.com/thesysdev/openui/tree/main/packages/svelte-lang) |
@@ -78,6 +81,10 @@ The OpenUI SDK is split into packages that build on each other:
LangGraph stream transformation, stateless run helpers, and AG-UI SSE relay APIs for OpenUI
frontends.
</Card>
+ <Card title="@openuidev/server" href="/docs/api-reference/server">
+ Autofix helpers for Chat Completions and the Vercel AI SDK, plus conversation history
+ persistence.
+ </Card>
<Card title="@openuidev/react-email" href="/docs/api-reference/react-email">
API reference for the pre-built email templates library and prompt options.
</Card>
diff --git a/docs/content/docs/api-reference/meta.json b/docs/content/docs/api-reference/meta.json
index 6bd4c992b..8ad4c9cf7 100644
--- a/docs/content/docs/api-reference/meta.json
+++ b/docs/content/docs/api-reference/meta.json
@@ -8,6 +8,7 @@
"react-ui",
"assistant-ui",
"langchain",
+ "server",
"react-email",
"devtools",
"cli",
diff --git a/docs/content/docs/api-reference/server.mdx b/docs/content/docs/api-reference/server.mdx
new file mode 100644
index 000000000..8a7144857
--- /dev/null
+++ b/docs/content/docs/api-reference/server.mdx
@@ -0,0 +1,332 @@
+---
+title: "@openuidev/server"
+description: API reference for Autofix helpers and conversation history persistence on the OpenUI Gateway.
+---
+
+Server utilities for OpenUI Gateway. Validate and repair model-generated OpenUI Lang, and persist a completed turn as Conversations API items.
+Import from the subpath that matches your SDK. The helpers call [Autofix HTTP API](/docs/gateway/api/autofix).
+
+## Install
+
+```bash tab="pnpm" tab-group="pkg"
+pnpm add @openuidev/server
+```
+
+```bash tab="bun" tab-group="pkg"
+bun add @openuidev/server
+```
+
+```bash tab="yarn" tab-group="pkg"
+yarn add @openuidev/server
+```
+
+```bash tab="npm" tab-group="pkg"
+npm install @openuidev/server
+```
+
+## Import paths
+
+| Import from | Autofix | History helpers |
+| :------------------------- | :----------------------------------------- | :------------------------------------------------------------ |
+| `@openuidev/server/openai` | `completions.fix` and `completions.stream` | `storeChatCompletionHistory`, `chatCompletionMessagesToItems` |
+| `@openuidev/server/vercel` | `ai.fix` and `ai.stream` | — |
+
+Pair each Autofix stream with the matching frontend adapter: `openAIAdapter()` or `useChat`.
+
+## `createAutofix(options)`
+
+Use the spec from `openui generate --spec` for the same library as your renderer, including its `schema`.
+
+```ts tab="OpenAI" tab-group="autofix-sdk"
+import { createAutofix } from "@openuidev/server/openai";
+import library from "./openui.spec.json";
+
+const autofix = createAutofix({
+ apiKey: process.env.THESYS_API_KEY!,
+ library,
+});
+```
+
+```ts tab="Vercel AI SDK" tab-group="autofix-sdk"
+import { createAutofix } from "@openuidev/server/vercel";
+import library from "./openui.spec.json";
+
+const autofix = createAutofix({
+ apiKey: process.env.THESYS_API_KEY!,
+ library,
+});
+```
+
+```ts tab="Non-streaming" tab-group="autofix-sdk"
+import { createAutofix } from "@openuidev/server/openai";
+// import { createAutofix } from "@openuidev/server/vercel";
+import library from "./openui.spec.json";
+
+const autofix = createAutofix({
+ apiKey: process.env.THESYS_API_KEY!,
+ library,
+});
+```
+
+```ts
+function createAutofix(options: {
+ apiKey: string;
+ library: LibrarySpec & { schema: LibraryJSONSchema };
+ apiBaseUrl?: string; // defaults to https://api.thesys.dev
+ fetch?: typeof globalThis.fetch;
+}): Autofix;
+```
+
+From `@openuidev/server/openai`, `Autofix` is `{ completions: { fix, stream } }`. From `@openuidev/server/vercel`, it is `{ ai: { fix, stream } }`.
+
+## `fix(input)`
+
+Validate completed OpenUI text. Valid output is returned as-is. Invalid output is sent to `POST /v1/autofix`.
+
+```ts tab="OpenAI" tab-group="autofix-sdk"
+const result = await autofix.completions.fix({ generation, messages, signal });
+
+if (result.content !== null) {
+ // already_valid or fixed — use result.content
+} else {
+ // fix_failed — choose a fallback
+ console.warn(result.unfixedErrors);
+}
+```
+
+```ts tab="Vercel AI SDK" tab-group="autofix-sdk"
+const result = await autofix.ai.fix({ generation, messages, signal });
+
+if (result.content !== null) {
+ // already_valid or fixed — use result.content
+} else {
+ // fix_failed — choose a fallback
+ console.warn(result.unfixedErrors);
+}
+```
+
+```ts tab="Non-streaming" tab-group="autofix-sdk"
+const result = await autofix.completions.fix({ generation, messages, signal });
+// const result = await autofix.ai.fix({ generation, messages, signal });
+
+if (result.content !== null) {
+ // already_valid or fixed — use result.content
+} else {
+ // fix_failed — choose a fallback
+ console.warn(result.unfixedErrors);
+}
+```
+
+```ts
+function fix(input: {
+ generation: string;
+ messages?: ChatCompletionMessageParam[];
+ signal?: AbortSignal;
+}): Promise<AutofixResult>;
+```
+
+`generation` is the completed OpenUI text. Optional `messages` is the conversation before that generation. On `fixed`, `content` is the program the Autofix API returned.
+
+```ts
+type AutofixResult = {
+ original: string;
+ fixedErrors: AutofixDiagnostic[];
+ unfixedErrors: AutofixDiagnostic[];
+} & (
+ { status: "already_valid" | "fixed"; content: string } | { status: "fix_failed"; content: null }
+);
+
+interface AutofixDiagnostic {
+ code: string;
+ message: string;
+ component?: string;
+ path?: string;
+ statementId?: string;
+}
+```
+
+## `stream(input)`
+
+Wrap a native SDK stream. The helper forwards provider events and inserts a repair before the stream completes when the finished UI is invalid.
+
+```ts
+function stream(input: {
+ stream: AsyncIterable<Chunk> & { controller?: AbortController };
+ messages?: ChatCompletionMessageParam[];
+ signal?: AbortSignal;
+}): AutofixStream<Chunk>;
+```
+
+Use `autofix.completions.stream()` with a native Chat Completions stream, or `autofix.ai.stream()` with `toUIMessageStream({ stream: result.stream })` — not the raw `result.stream`.
+
+```ts
+interface AutofixStream<T> {
+ chunks: AsyncIterable<T>;
+ toResponse(): Response;
+ result: Promise<AutofixResult | null>;
+}
+```
+
+Use either `chunks` or `toResponse()` once. `result` settles after that consumer finishes. Persist `result.content` when it is a string — that is the Autofix program, not the joined stream text. `result` is `null` when Autofix did not run.
+
+```ts title="app/api/chat/route.ts" tab="OpenAI" tab-group="autofix-sdk"
+import OpenAI from "openai";
+import { createAutofix } from "@openuidev/server/openai";
+import library from "./openui.spec.json";
+
+const model = new OpenAI();
+const autofix = createAutofix({
+ apiKey: process.env.THESYS_API_KEY!,
+ library,
+});
+
+export async function POST(request: Request) {
+ const { messages } = await request.json();
+ const source = await model.chat.completions.create(
+ { model: "openai/gpt-5.5", messages, stream: true },
+ { signal: request.signal },
+ );
+
+ return autofix.completions
+ .stream({ stream: source, messages, signal: request.signal })
+ .toResponse();
+}
+```
+
+```ts title="app/api/chat/route.ts" tab="Vercel AI SDK" tab-group="autofix-sdk"
+import { streamText, toUIMessageStream } from "ai";
+import { createAutofix } from "@openuidev/server/vercel";
+import library from "./openui.spec.json";
+
+const autofix = createAutofix({
+ apiKey: process.env.THESYS_API_KEY!,
+ library,
+});
+
+const result = streamText({
+ model: "openai/gpt-5.5",
+ system: systemPrompt,
+ prompt: "Show a greeting card",
+ abortSignal: signal,
+});
+
+return autofix.ai
+ .stream({
+ stream: toUIMessageStream({ stream: result.stream }),
+ signal,
+ })
+ .toResponse();
+```
+
+```ts title="server.ts" tab="Non-streaming" tab-group="autofix-sdk"
+const result = await autofix.completions.fix({ generation, messages, signal });
+// const result = await autofix.ai.fix({ generation, messages, signal });
+
+if (result.content !== null) {
+ // already_valid or fixed — use result.content
+} else {
+ console.warn(result.unfixedErrors);
+}
+```
+
+```ts tab="OpenAI" tab-group="autofix-sdk"
+const output = autofix.completions.stream({ stream: source, messages, signal });
+
+for await (const chunk of output.chunks) {
+ // Native SDK events, including any appended correction
+}
+
+const settled = await output.result;
+if (settled?.content) {
+ // Persist settled.content
+}
+```
+
+```ts tab="Vercel AI SDK" tab-group="autofix-sdk"
+const output = autofix.ai.stream({
+ stream: toUIMessageStream({ stream: result.stream }),
+ signal,
+});
+
+for await (const chunk of output.chunks) {
+ // Native SDK events, including any appended correction
+}
+
+const settled = await output.result;
+if (settled?.content) {
+ // Persist settled.content
+}
+```
+
+```ts tab="Non-streaming" tab-group="autofix-sdk"
+if (result.content) {
+ // Persist result.content
+}
+```
+
+A failed repair on a stream throws with `code: "fix_failed"`. Use `fix()` on the same helper when you already have completed text.
+
+### Stream errors
+
+Thrown errors include a `code` string:
+
+| `code` | When |
+| :--------------------- | :------------------------------------------------- |
+| `invalid_library` | `library.schema` is missing |
+| `generation_too_large` | Generation exceeds 100,000 characters |
+| `http_error` | Autofix HTTP request failed (`status` is set) |
+| `invalid_response` | Autofix response could not be read |
+| `stream_consumed` | `chunks` or `toResponse()` was used more than once |
+| `fix_failed` | Streamed generation could not be repaired |
+
+## Conversation history
+
+Persist only the new turn — not the full `messages` array — or items will be duplicated. Use the master API key. System and developer messages are skipped.
+
+### `storeChatCompletionHistory(options)`
+
+```ts
+import { storeChatCompletionHistory } from "@openuidev/server/openai";
+
+await storeChatCompletionHistory({
+ apiKey: process.env.THESYS_API_KEY!,
+ conversationId: threadId,
+ messages: [
+ { role: "user", content: lastUserText },
+ { role: "assistant", content: assistantText },
+ ],
+});
+```
+
+```ts
+function storeChatCompletionHistory(options: {
+ apiKey: string;
+ conversationId: string;
+ messages: ChatCompletionMessageParam[];
+ apiBaseUrl?: string;
+ fetch?: typeof fetch;
+}): Promise<ConversationItemList>;
+```
+
+### `chatCompletionMessagesToItems(messages)`
+
+Convert Chat Completions messages to Conversations API items without posting.
+
+```ts
+import { chatCompletionMessagesToItems } from "@openuidev/server/openai";
+
+chatCompletionMessagesToItems([
+ { role: "user", content: "hello" },
+ { role: "assistant", content: "hi" },
+]);
+```
+
+## Exports
+
+| Entry point | Export | Description |
+| :------------------------- | :---------------------------------- | :----------------------------------------------------- |
+| `@openuidev/server/openai` | `createAutofix` | Chat Completions Autofix: `completions.fix` / `stream` |
+| `@openuidev/server/openai` | `storeChatCompletionHistory` | Persist a Chat Completions turn |
+| `@openuidev/server/openai` | `chatCompletionMessagesToItems` | Convert messages to Conversations API items |
+| `@openuidev/server/openai` | `StoreChatCompletionHistoryOptions` | History helper configuration |
+| `@openuidev/server/vercel` | `createAutofix` | Vercel AI SDK Autofix: `ai.fix` / `ai.stream` |
diff --git a/docs/content/docs/gateway/api/autofix.mdx b/docs/content/docs/gateway/api/autofix.mdx
index 744d1e1e2..e847e27bb 100644
--- a/docs/content/docs/gateway/api/autofix.mdx
+++ b/docs/content/docs/gateway/api/autofix.mdx
@@ -20,14 +20,120 @@ flowchart LR
`}
/>
-## Detect an invalid generation
+## Use the server package
-Parse the generation with `@openuidev/lang-core` before you call the API. It is the same check the API runs first, so a generation that passes here would come back as `already_valid`. Skip the call when nothing is wrong.
+Import `createAutofix` from `@openuidev/server/openai` for Chat Completions or `@openuidev/server/vercel` for the Vercel AI SDK. Use the spec from `openui generate --spec` for the same library as your renderer. Keep the API key on the server.
+
+```ts title="lib/autofix.ts" tab="OpenAI" tab-group="autofix-sdk"
+import { createAutofix } from "@openuidev/server/openai";
+import library from "./openui.spec.json";
+
+export const autofix = createAutofix({
+ apiKey: process.env.THESYS_API_KEY!,
+ library,
+});
+```
+
+```ts title="lib/autofix.ts" tab="Vercel AI SDK" tab-group="autofix-sdk"
+import { createAutofix } from "@openuidev/server/vercel";
+import library from "./openui.spec.json";
+
+export const autofix = createAutofix({
+ apiKey: process.env.THESYS_API_KEY!,
+ library,
+});
+```
+
+```ts title="lib/autofix.ts" tab="Non-streaming" tab-group="autofix-sdk"
+import { createAutofix } from "@openuidev/server/openai";
+// import { createAutofix } from "@openuidev/server/vercel";
+import library from "./openui.spec.json";
+
+export const autofix = createAutofix({
+ apiKey: process.env.THESYS_API_KEY!,
+ library,
+});
+```
+
+```ts title="app/api/chat/route.ts" tab="OpenAI" tab-group="autofix-sdk"
+import OpenAI from "openai";
+import { autofix } from "../../../lib/autofix";
+
+const model = new OpenAI();
+
+export async function POST(request: Request) {
+ const { messages } = await request.json();
+ const source = await model.chat.completions.create(
+ { model: "openai/gpt-5.5", messages, stream: true },
+ { signal: request.signal },
+ );
+
+ return autofix.completions
+ .stream({ stream: source, messages, signal: request.signal })
+ .toResponse();
+}
+```
+
+```ts title="app/api/chat/route.ts" tab="Vercel AI SDK" tab-group="autofix-sdk"
+import { streamText, toUIMessageStream } from "ai";
+import { autofix } from "../../../lib/autofix";
+
+export async function POST(request: Request) {
+ const { messages } = await request.json();
+ const result = streamText({
+ model: "openai/gpt-5.5",
+ system: systemPrompt, // Generated from the same OpenUI component library.
+ messages,
+ abortSignal: request.signal,
+ });
+
+ return autofix.ai
+ .stream({
+ stream: toUIMessageStream({ stream: result.stream }),
+ signal: request.signal,
+ })
+ .toResponse();
+}
+```
+
+```ts title="server.ts" tab="Non-streaming" tab-group="autofix-sdk"
+import { autofix } from "./lib/autofix";
+
+const result = await autofix.completions.fix({ generation, messages, signal });
+// const result = await autofix.ai.fix({ generation, messages, signal });
+
+if (result.status === "fix_failed") {
+ console.warn(result.unfixedErrors);
+} else {
+ // Render or persist result.content.
+}
+```
+
+OpenAI: return SSE for the frontend `openAIAdapter()`.
+
+Vercel: pass `toUIMessageStream({ stream: result.stream })`. `toResponse()` is the UI message SSE protocol used by `useChat`.
+
+Non-streaming: `generation` is the completed OpenUI text. Optional `messages` is the conversation before that generation. Use `completions.fix` or `ai.fix` to match the import.
+
+### Consume the stream
+
+Use either `chunks` or `toResponse()` once. `result` settles after that consumer finishes.
+
+| Member | Purpose |
+| -------------- | ----------------------------------------------------------------------- |
+| `chunks` | Native SDK events, including any correction. |
+| `toResponse()` | SSE `Response` for the matching frontend. |
+| `result` | Settled Autofix result. Persist `content` when present, not joined text. |
+
+`result` is `null` when Autofix did not run. A failed repair throws with `code: "fix_failed"`. Use `fix()` on the same helper when you already have completed text.
+
+## Call the API directly
+
+Parse first, and only call Autofix when the generation is invalid.
```ts title="lib/detect.ts"
import type { ParseResult } from "@openuidev/lang-core";
-/** The API's own rule: a generation renders only when all five hold. */
export function isValid({ root, meta }: ParseResult): boolean {
return (
!meta.incomplete &&
@@ -55,7 +161,7 @@ export async function generate(messages: OpenAI.ChatCompletionMessageParam[]) {
let generation = "";
let result = parser.getResult();
- const stream = await model.chat.completions.create({ model: "gpt-5", messages, stream: true });
+ const stream = await model.chat.completions.create({ model: "gpt-5.5", messages, stream: true });
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content ?? "";
if (!delta) continue;
@@ -159,11 +265,11 @@ export async function autofix(messages: Message[], generation: string) {
## Request
-| Field | Type | Required | Purpose |
-| ---------- | ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Field | Type | Required | Purpose |
+| ---------- | ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `messages` | array | Yes | The conversation, in the OpenAI chat message shape. The first message is a `system` turn that carries your library as the `]]>openui:config` block that `generateSystemPrompt({ cloud: true, library })` writes; it is read as the library, not as conversation. The last turn must be an `assistant` turn whose text is the generation to fix, up to 100,000 characters. The turns in between are the context: only the text of `user`, `assistant`, `system`, and `developer` turns is read, and tool turns and non-text parts are dropped. |
-| `model` | string | No | Accepted so that an SDK client can name a model, and ignored. The answer always reports `openui/autofix`. |
-| `stream` | bool | No | Streaming is not supported. A fix has nothing to send until it is finished, so `stream: true` is a `400`. |
+| `model` | string | No | Accepted so that an SDK client can name a model, and ignored. The answer always reports `openui/autofix`. |
+| `stream` | bool | No | Streaming is not supported. A fix has nothing to send until it is finished, so `stream: true` is a `400`. |
The other OpenAI fields, such as `temperature` and `tools`, are ignored.
@@ -171,11 +277,11 @@ The other OpenAI fields, such as `temperature` and `tools`, are ignored.
The answer is a chat completion. `choices[0].message.content` holds the complete generation, not a patch: replace the model output with it and render it. `fix_summary.status` says what happened.
-| `status` | `content` | Errors | Charged |
-| --------------- | ------------------------ | ----------------------------------------------------- | ------- |
-| `already_valid` | The input, unchanged | `fixed_errors` is empty | No |
-| `fixed` | The corrected generation | `fixed_errors` lists what was wrong and is now fixed | Yes |
-| `fix_failed` | `null` | `unfixed_errors` lists what is still wrong | Yes |
+| `status` | `content` | Errors | Charged |
+| --------------- | ------------------------ | ---------------------------------------------------- | ------- |
+| `already_valid` | The input, unchanged | `fixed_errors` is empty | No |
+| `fixed` | The corrected generation | `fixed_errors` lists what was wrong and is now fixed | Yes |
+| `fix_failed` | `null` | `unfixed_errors` lists what is still wrong | Yes |
`fixed_errors` and `unfixed_errors` are always present, and one of them is usually empty.
@@ -291,12 +397,12 @@ Each call that runs a fix is charged a flat price from your credits. A generatio
The endpoint returns the same error shape as the Chat Completions and Responses APIs.
-| Status | Type | When |
-| ------ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------ |
+| Status | Type | When |
+| ------ | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400` | `invalid_request_error` | The first message is not a library turn, or its block is malformed; the last turn is not an assistant turn with a generation; a limit is passed; or `stream` is `true`. |
-| `401` | `authentication_error` | The API key is missing or invalid. |
-| `429` | `rate_limit_error` | The organization has no credits, or billing is suspended. |
-| `500` | `internal_server_error` | The fixing model could not be reached. Nothing is charged. |
+| `401` | `authentication_error` | The API key is missing or invalid. |
+| `429` | `rate_limit_error` | The organization has no credits, or billing is suspended. |
+| `500` | `internal_server_error` | The fixing model could not be reached. Nothing is charged. |
## Observability
diff --git a/packages/server/README.md b/packages/server/README.md
index 10cd058d3..0663cbec5 100644
--- a/packages/server/README.md
+++ b/packages/server/README.md
@@ -2,14 +2,114 @@
Server utilities for OpenUI & OpenUI Gateway.
-```bash
-npm install @openuidev/server
+**Links:** [Package docs](https://openui.com/docs/api-reference/server) | [Autofix API](https://openui.com/docs/gateway/api/autofix) | [GitHub repo](https://github.com/thesysdev/openui)
+
+## Autofix
+
+Prefer this package over calling the endpoint yourself. Import `createAutofix` from `@openuidev/server/openai` for Chat Completions or `@openuidev/server/vercel` for the Vercel AI SDK. Use the spec from `openui generate --spec` for the same library as your renderer. Keep the API key on the server.
+
+### Configure once
+
+```ts
+import { createAutofix } from "@openuidev/server/openai";
+import library from "./openui.spec.json";
+
+export const autofix = createAutofix({
+ apiKey: process.env.THESYS_API_KEY!,
+ library,
+});
+```
+
+### Fix a completed generation
+
+```ts
+import { autofix } from "./lib/autofix";
+
+const result = await autofix.completions.fix({ generation, messages, signal });
+
+if (result.status === "fix_failed") {
+ console.warn(result.unfixedErrors);
+} else {
+ // Render or persist result.content.
+}
+```
+
+`generation` is the completed OpenUI text. Optional `messages` is the conversation before that generation.
+
+### Wrap a Chat Completions stream
+
+```ts
+import OpenAI from "openai";
+import { autofix } from "../../../lib/autofix";
+
+const model = new OpenAI();
+
+export async function POST(request: Request) {
+ const { messages } = await request.json();
+ const source = await model.chat.completions.create(
+ { model: "openai/gpt-5.5", messages, stream: true },
+ { signal: request.signal },
+ );
+
+ return autofix.completions
+ .stream({ stream: source, messages, signal: request.signal })
+ .toResponse();
+}
+```
+
+Return SSE for the frontend `openAIAdapter()`. `autofix.responses` is not supported yet.
+
+### Wrap a Vercel AI SDK stream
+
+```ts
+import { streamText, toUIMessageStream } from "ai";
+import { createAutofix } from "@openuidev/server/vercel";
+import library from "./openui.spec.json";
+
+const autofix = createAutofix({
+ apiKey: process.env.THESYS_API_KEY!,
+ library,
+});
+
+const result = streamText({
+ model: "openai/gpt-5.5",
+ system: systemPrompt, // Generated from the same OpenUI component library.
+ prompt: "Show a greeting card",
+ abortSignal: signal,
+});
+
+return autofix.ai
+ .stream({
+ stream: toUIMessageStream({ stream: result.stream }),
+ signal,
+ })
+ .toResponse();
```
-Persist a Chat Completions turn as Conversations API items. Chat Completions has no `conversation` + `store: true`. Use the master API key (Cloud rejects frontend tokens on create). Pass only the new turn — last user message plus the assembled assistant reply — not the client’s full `messages` array.
+Pass `toUIMessageStream({ stream: result.stream })`. `toResponse()` is the UI message SSE protocol used by `useChat`.
+
+### Consume the stream
+
+Use either `chunks` or `toResponse()` once. `result` settles after that consumer finishes.
+
+| Member | Purpose |
+| -------------- | ------------------------------------------------------------------------ |
+| `chunks` | Native SDK events, including any correction. |
+| `toResponse()` | SSE `Response` for the matching frontend. |
+| `result` | Settled Autofix result. Persist `content` when present, not joined text. |
+
+`result` is `null` when Autofix did not run. A failed repair throws with `code: "fix_failed"`. Use `fix()` on the same helper when you already have completed text.
+
+`apiBaseUrl` overrides the Gateway origin. `fetch` supports custom transports or mocks.
+
+## Conversation history
+
+Persist a Chat Completions turn as Conversations API items. Pass only the new turn —
+last user message plus the assembled assistant reply — not the full `messages` array.
+Use the master API key.
```ts
-import { storeChatCompletionHistory } from "@openuidev/server";
+import { storeChatCompletionHistory } from "@openuidev/server/openai";
await storeChatCompletionHistory({
apiKey: process.env.THESYS_API_KEY!,
@@ -24,7 +124,7 @@ await storeChatCompletionHistory({
Convert without posting:
```ts
-import { chatCompletionMessagesToItems } from "@openuidev/server";
+import { chatCompletionMessagesToItems } from "@openuidev/server/openai";
chatCompletionMessagesToItems([
{ role: "user", content: "hello" },
diff --git a/packages/server/package.json b/packages/server/package.json
index 78474c25c..c853a54ed 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -25,6 +25,26 @@
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
+ },
+ "./openai": {
+ "import": {
+ "types": "./dist/openai/index.d.mts",
+ "default": "./dist/openai/index.mjs"
+ },
+ "require": {
+ "types": "./dist/openai/index.d.cts",
+ "default": "./dist/openai/index.cjs"
+ }
+ },
+ "./vercel": {
+ "import": {
+ "types": "./dist/vercel/index.d.mts",
+ "default": "./dist/vercel/index.mjs"
+ },
+ "require": {
+ "types": "./dist/vercel/index.d.cts",
+ "default": "./dist/vercel/index.cjs"
+ }
}
},
"scripts": {
@@ -56,9 +76,23 @@
"url": "https://github.com/thesysdev/openui/issues"
},
"author": "[email protected]",
+ "dependencies": {
+ "@openuidev/lang-core": "workspace:^"
+ },
"devDependencies": {
- "openai": "^6.22.0",
+ "ai": "^7.0.10",
+ "openai": "^7.20.0",
"tsdown": "^0.21.7",
"vitest": "^4.1.0"
+ },
+ "typesVersions": {
+ "*": {
+ "openai": [
+ "dist/openai/index.d.cts"
+ ],
+ "vercel": [
+ "dist/vercel/index.d.cts"
+ ]
+ }
}
}
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 872127586..cb0ff5c3b 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -1,5 +1 @@
-export {
- chatCompletionMessagesToItems,
- storeChatCompletionHistory,
-} from "./store-chat-completion-history";
-export type { StoreChatCompletionHistoryOptions } from "./types";
+export {};
diff --git a/packages/server/src/openai/adapter.ts b/packages/server/src/openai/adapter.ts
new file mode 100644
index 000000000..b7925beab
--- /dev/null
+++ b/packages/server/src/openai/adapter.ts
@@ -0,0 +1,129 @@
+import type { ChatCompletionChunk } from "openai/resources/chat/completions";
+import { MAX_AUTOFIX_GENERATION_LENGTH, type StreamAdapter } from "../shared/types";
+import { isUIOutput, splitClosedFence, unwrapOpenUIFence } from "../shared/utils";
+
+/** Create a correction or stop chunk with the original completion's routing fields. */
+export function correctionChunk(
+ template: ChatCompletionChunk,
+ index: number,
+ content: string | null,
+): ChatCompletionChunk {
+ return {
+ id: template.id,
+ object: template.object,
+ created: template.created,
+ model: template.model,
+ ...(template.service_tier !== undefined && { service_tier: template.service_tier }),
+ choices: [
+ {
+ index,
+ delta: content === null ? {} : { content },
+ finish_reason: content === null ? "stop" : null,
+ },
+ ],
+ };
+}
+
+type Held = { id: string; index: number; repair: boolean };
+
+/** Preserve Chat Completions chunks and repair text before a successful final choice closes. */
+export const openAIAdapter: StreamAdapter<ChatCompletionChunk> = {
+ protocol: "openai-chat-completions",
+ // Track text within each choice and wait for the finish reason before attempting repair.
+ async *transform(source, fix) {
+ const texts = new Map<string, string | null>();
+ const closings = new Map<string, string>();
+ const hasTools = new Set<string>();
+ const failed = new Set<string>();
+ const done = new Set<string>();
+
+ // Release deferred endings, optionally inserting a repair before a held closing fence.
+ async function* release(
+ template: ChatCompletionChunk,
+ held: Held[],
+ ): AsyncGenerator<ChatCompletionChunk> {
+ for (const { id, index, repair } of held) {
+ const text = texts.get(id);
+ // Repair only a successful final-choice UI generation.
+ if (repair && text != null && isUIOutput(text)) {
+ const result = await fix(text);
+ // Only append when Autofix actually changed the text.
+ if (result.status === "fixed") {
+ yield correctionChunk(template, index, `\n${unwrapOpenUIFence(result.content)}\n`);
+ }
+ }
+ const closing = closings.get(id);
+ // Emit the held fence closer after any repair.
+ if (closing) yield correctionChunk(template, index, closing);
+ done.add(id);
+ texts.delete(id);
+ closings.delete(id);
+ yield correctionChunk(template, index, null);
+ }
+ }
+
+ for await (const chunk of source) {
+ const held: Held[] = [];
+ const choices = chunk.choices.map((choice) => {
+ const id = JSON.stringify([chunk.id, choice.index]);
+ // Already finished this choice; pass through.
+ if (done.has(id)) return choice;
+ // Start accumulating this text part.
+ if (!texts.has(id)) texts.set(id, "");
+
+ // Tools mean this choice is not the final UI answer.
+ if (choice.delta.tool_calls?.length || choice.delta.function_call) hasTools.add(id);
+ // Failed choice; release without repair.
+ if (choice.delta.refusal != null) failed.add(id);
+
+ const previous = texts.get(id);
+ const incoming = choice.delta.content ?? "";
+ // Accumulate text and maybe hold a closing fence.
+ if (previous != null) {
+ const combined = previous + incoming;
+ // Too large to send to Autofix; stop holding.
+ if (combined.length > MAX_AUTOFIX_GENERATION_LENGTH) {
+ texts.set(id, null);
+ const closing = closings.get(id);
+ closings.delete(id);
+ if (closing) {
+ choice = { ...choice, delta: { ...choice.delta, content: closing + incoming } };
+ }
+ } else {
+ texts.set(id, combined);
+ const split = splitClosedFence(combined);
+ // Hold the closing fence so a later repair stays inside it.
+ if (split) {
+ closings.set(id, split.closing);
+ const emit = split.body.slice(previous.length);
+ // Always strip the closer from this delta; it is re-emitted in release.
+ choice = { ...choice, delta: { ...choice.delta, content: emit } };
+ } else {
+ closings.delete(id);
+ }
+ }
+ }
+
+ // Mid-stream; nothing to repair yet.
+ if (!choice.finish_reason) return choice;
+ const text = texts.get(id);
+ const repair =
+ choice.finish_reason === "stop" &&
+ !hasTools.has(id) &&
+ !failed.has(id) &&
+ text != null &&
+ isUIOutput(text);
+ // Hold endings until repair and/or the closer are emitted.
+ if (repair || closings.has(id)) {
+ held.push({ id, index: choice.index, repair });
+ return { ...choice, finish_reason: null };
+ }
+ done.add(id);
+ return choice;
+ });
+
+ yield { ...chunk, choices };
+ yield* release(chunk, held);
+ }
+ },
+};
diff --git a/packages/server/src/openai/index.ts b/packages/server/src/openai/index.ts
new file mode 100644
index 000000000..4fe533b43
--- /dev/null
+++ b/packages/server/src/openai/index.ts
@@ -0,0 +1,16 @@
+import { createAutofix as createAutofixPipeline } from "../shared/create-autofix";
+import type { AutofixOptions } from "../shared/types";
+import { openAIAdapter } from "./adapter";
+
+export {
+ chatCompletionMessagesToItems,
+ storeChatCompletionHistory,
+} from "./store-conversation-items";
+export type { StoreChatCompletionHistoryOptions } from "./types";
+
+// Create validation and repair helpers for OpenAI Chat Completions and Responses.
+export function createAutofix(options: AutofixOptions) {
+ return {
+ completions: createAutofixPipeline(options, openAIAdapter),
+ };
+}
diff --git a/packages/server/src/store-chat-completion-history.test.ts b/packages/server/src/openai/store-conversation-items.test.ts
similarity index 99%
rename from packages/server/src/store-chat-completion-history.test.ts
rename to packages/server/src/openai/store-conversation-items.test.ts
index 0c0a7ef1b..4bd236a80 100644
--- a/packages/server/src/store-chat-completion-history.test.ts
+++ b/packages/server/src/openai/store-conversation-items.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest";
import {
chatCompletionMessagesToItems,
storeChatCompletionHistory,
-} from "./store-chat-completion-history";
+} from "./store-conversation-items";
describe("chatCompletionMessagesToItems", () => {
it("maps user and assistant text into Conversations message items", () => {
diff --git a/packages/server/src/store-chat-completion-history.ts b/packages/server/src/openai/store-conversation-items.ts
similarity index 97%
rename from packages/server/src/store-chat-completion-history.ts
rename to packages/server/src/openai/store-conversation-items.ts
index 0f963e4f1..5315b1880 100644
--- a/packages/server/src/store-chat-completion-history.ts
+++ b/packages/server/src/openai/store-conversation-items.ts
@@ -11,9 +11,8 @@ import type {
ResponseInputItem,
ResponseInputMessageContentList,
} from "openai/resources/responses/responses";
-import type { StoreChatCompletionHistoryOptions } from "./types";
-
-const THESYS_API_BASE_URL = "https://api.thesys.dev";
+import { THESYS_API_BASE_URL } from "../shared/constants.js";
+import type { StoreChatCompletionHistoryOptions } from "./types.js";
function userContentOf(
content: ChatCompletionUserMessageParam["content"],
diff --git a/packages/server/src/types.ts b/packages/server/src/openai/types.ts
similarity index 100%
rename from packages/server/src/types.ts
rename to packages/server/src/openai/types.ts
diff --git a/packages/server/src/shared/constants.ts b/packages/server/src/shared/constants.ts
new file mode 100644
index 000000000..76507cd35
--- /dev/null
+++ b/packages/server/src/shared/constants.ts
@@ -0,0 +1 @@
+export const THESYS_API_BASE_URL = "https://api.thesys.dev";
diff --git a/packages/server/src/shared/create-autofix.ts b/packages/server/src/shared/create-autofix.ts
new file mode 100644
index 000000000..ba96d23b4
--- /dev/null
+++ b/packages/server/src/shared/create-autofix.ts
@@ -0,0 +1,43 @@
+import { createParser } from "@openuidev/lang-core";
+import { THESYS_API_BASE_URL } from "./constants";
+import { fixGeneration } from "./fix";
+import { createAutofixStream } from "./stream";
+import type {
+ AutofixInput,
+ AutofixOptions,
+ AutofixResult,
+ AutofixStream,
+ AutofixStreamInput,
+ StreamAdapter,
+} from "./types";
+import { AutofixError } from "./types";
+
+/** Create helpers to validate and repair complete or streamed model output. */
+export function createAutofix<Chunk>(
+ options: AutofixOptions,
+ adapter: StreamAdapter<Chunk>,
+): {
+ fix(input: AutofixInput): Promise<AutofixResult>;
+ stream(input: AutofixStreamInput<Chunk>): AutofixStream<Chunk>;
+} {
+ const { library } = options;
+ if (!library?.schema)
+ throw new AutofixError("A library spec with schema is required", "invalid_library");
+ const parser = createParser(library.schema, library.root);
+ const endpoint = `${(options.apiBaseUrl ?? THESYS_API_BASE_URL).replace(/\/+$/, "")}/v1/autofix`;
+ const fetchFn = options.fetch ?? globalThis.fetch;
+
+ const fix = fixGeneration.bind(null, {
+ library,
+ apiKey: options.apiKey,
+ parser,
+ endpoint,
+ fetchFn,
+ });
+
+ return {
+ fix,
+ // Wrap model emissions with validation and repair before the stream finishes.
+ stream: (input: AutofixStreamInput<Chunk>) => createAutofixStream(input, fix, adapter),
+ };
+}
diff --git a/packages/server/src/shared/fix.ts b/packages/server/src/shared/fix.ts
new file mode 100644
index 000000000..8de81eb44
--- /dev/null
+++ b/packages/server/src/shared/fix.ts
@@ -0,0 +1,74 @@
+import { generateSystemPrompt, type Parser } from "@openuidev/lang-core";
+import type { AutofixInput, AutofixOptions, AutofixResult } from "./types";
+import { AutofixError, MAX_AUTOFIX_GENERATION_LENGTH } from "./types";
+import { errorsOf, readCompletion, repairContext } from "./utils";
+
+// Return valid programs unchanged and send invalid programs to the Autofix API.
+export async function fixGeneration(
+ {
+ library,
+ apiKey,
+ parser,
+ endpoint,
+ fetchFn,
+ }: Pick<AutofixOptions, "library" | "apiKey"> & {
+ parser: Parser;
+ endpoint: string;
+ fetchFn: typeof globalThis.fetch;
+ },
+ { generation, messages = [], signal }: AutofixInput,
+): Promise<AutofixResult> {
+ signal?.throwIfAborted();
+ if (generation.length > MAX_AUTOFIX_GENERATION_LENGTH) {
+ throw new AutofixError("Generation exceeds 100,000 characters", "generation_too_large");
+ }
+ const initialErrors = errorsOf(parser.parse(generation));
+ if (initialErrors.length === 0) {
+ return {
+ status: "already_valid",
+ original: generation,
+ content: generation,
+ fixedErrors: [],
+ unfixedErrors: [],
+ };
+ }
+
+ const response = await fetchFn(endpoint, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
+ body: JSON.stringify({
+ messages: [
+ { role: "system", content: generateSystemPrompt({ cloud: true, library }) },
+ ...repairContext(messages),
+ { role: "assistant", content: generation },
+ ],
+ }),
+ signal,
+ });
+ signal?.throwIfAborted();
+ if (!response.ok) {
+ throw new AutofixError(
+ `Autofix request failed: HTTP ${response.status}`,
+ "http_error",
+ response.status,
+ );
+ }
+ let body: unknown;
+ try {
+ body = await response.json();
+ } catch (error) {
+ signal?.throwIfAborted();
+ throw new AutofixError(`Could not read Autofix response: ${String(error)}`, "invalid_response");
+ }
+ signal?.throwIfAborted();
+ const completion = readCompletion(body);
+ if (completion.status === "fix_failed") {
+ return { ...completion, status: "fix_failed", content: null, original: generation };
+ }
+ return {
+ ...completion,
+ status: completion.status,
+ original: generation,
+ content: completion.content!,
+ };
+}
diff --git a/packages/server/src/shared/sse.ts b/packages/server/src/shared/sse.ts
new file mode 100644
index 000000000..99ae50eee
--- /dev/null
+++ b/packages/server/src/shared/sse.ts
@@ -0,0 +1,42 @@
+import type { StreamAdapter } from "./types";
+
+// Convert a supported event stream to SSE without changing its event objects.
+export function toSSE<T>(
+ chunks: AsyncIterable<T>,
+ protocol: StreamAdapter<unknown>["protocol"],
+ cancel: (reason?: unknown) => void,
+): Response {
+ const iterator = chunks[Symbol.asyncIterator]();
+ const encoder = new TextEncoder();
+ return new Response(
+ new ReadableStream<Uint8Array>({
+ // Pull and frame one native event at a time, respecting consumer backpressure.
+ async pull(controller) {
+ try {
+ const next = await iterator.next();
+ if (next.done) {
+ controller.enqueue(encoder.encode("data: [DONE]\n\n"));
+ controller.close();
+ } else {
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(next.value)}\n\n`));
+ }
+ } catch (error) {
+ controller.error(error);
+ }
+ },
+ // Stop upstream work when the HTTP consumer disconnects.
+ cancel(reason) {
+ cancel(reason);
+ void iterator.return?.().catch(() => {});
+ },
+ }),
+ {
+ headers: {
+ "Content-Type": "text/event-stream",
+ "Cache-Control": "no-cache",
+ "X-Accel-Buffering": "no",
+ ...(protocol === "vercel-ai" && { "x-vercel-ai-ui-message-stream": "v1" }),
+ },
+ },
+ );
+}
diff --git a/packages/server/src/shared/stream.ts b/packages/server/src/shared/stream.ts
new file mode 100644
index 000000000..0b779dacd
--- /dev/null
+++ b/packages/server/src/shared/stream.ts
@@ -0,0 +1,127 @@
+import { toSSE } from "./sse";
+import type {
+ AutofixInput,
+ AutofixResult,
+ AutofixStream,
+ AutofixStreamInput,
+ StreamAdapter,
+} from "./types";
+import { AutofixError } from "./types";
+
+// Stop waiting on cancellation even when an upstream iterator or request is stalled.
+async function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
+ signal.throwIfAborted();
+ let abort!: () => void;
+ const cancelled = new Promise<never>((_, reject) => {
+ abort = () => reject(signal.reason);
+ signal.addEventListener("abort", abort, { once: true });
+ });
+ try {
+ return await Promise.race([promise, cancelled]);
+ } finally {
+ signal.removeEventListener("abort", abort);
+ }
+}
+
+// Bind the shared fix function to an adapter and expose native chunks or HTTP streaming.
+export function createAutofixStream<Chunk>(
+ input: AutofixStreamInput<Chunk>,
+ fix: (input: AutofixInput) => Promise<AutofixResult>,
+ adapter: StreamAdapter<Chunk>,
+): AutofixStream<Chunk> {
+ const controller = new AbortController();
+ let consumed = false;
+ let last: AutofixResult | null = null;
+ let settle!: (value: AutofixResult | null) => void;
+ let fail!: (reason: unknown) => void;
+ let settled = false;
+ const result = new Promise<AutofixResult | null>((resolve, reject) => {
+ settle = resolve;
+ fail = reject;
+ });
+ // Ignore rejection unless the caller awaits result.
+ result.catch(() => {});
+
+ const resolveOnce = (value: AutofixResult | null) => {
+ // result settles only once.
+ if (settled) return;
+ settled = true;
+ settle(value);
+ };
+ const rejectOnce = (reason: unknown) => {
+ // result settles only once.
+ if (settled) return;
+ settled = true;
+ fail(reason);
+ };
+
+ // Stop both repair work and the upstream SDK stream.
+ const cancel = (reason?: unknown) => {
+ controller.abort(reason ?? new DOMException("Stream consumer stopped", "AbortError"));
+ input.stream.controller?.abort();
+ };
+
+ const chunks: AsyncIterable<Chunk> = {
+ // Consume the selected adapter once and clean up when iteration ends early.
+ async *[Symbol.asyncIterator]() {
+ // chunks and toResponse() share this iterator.
+ if (consumed)
+ throw new AutofixError("Autofix stream can only be consumed once", "stream_consumed");
+ consumed = true;
+ const signal = controller.signal;
+ // Forward the caller's cancellation to the upstream stream and Autofix request.
+ const forwardAbort = () => cancel(input.signal?.reason);
+ // The request may already be cancelled before iteration starts.
+ if (input.signal?.aborted) forwardAbort();
+ else input.signal?.addEventListener("abort", forwardAbort, { once: true });
+
+ const iterator = adapter.transform(input.stream, async (generation) => {
+ const next = await fix({ generation, messages: input.messages, signal });
+ signal.throwIfAborted();
+ last = next;
+ // Surface a failed repair as a stream error with the Autofix payload.
+ if (next.status === "fix_failed") {
+ throw new AutofixError(
+ "Could not repair the streamed generation",
+ "fix_failed",
+ undefined,
+ next,
+ );
+ }
+ return next;
+ });
+
+ let ended = false;
+ try {
+ while (true) {
+ const next = await abortable(iterator.next(), signal);
+ signal.throwIfAborted();
+ // Adapter finished; settle with the last Autofix result or null.
+ if (next.done) {
+ ended = true;
+ break;
+ }
+ yield next.value;
+ }
+ resolveOnce(last);
+ } catch (error) {
+ rejectOnce(error);
+ throw error;
+ } finally {
+ input.signal?.removeEventListener("abort", forwardAbort);
+ // Early stop: cancel upstream work and reject result.
+ if (!ended) {
+ cancel();
+ void iterator.return(undefined).catch(() => {});
+ rejectOnce(signal.reason ?? new DOMException("Stream consumer stopped", "AbortError"));
+ }
+ }
+ },
+ };
+ return {
+ chunks,
+ result,
+ // Serialize the native events in the selected protocol's SSE format.
+ toResponse: () => toSSE(chunks, adapter.protocol, cancel),
+ };
+}
diff --git a/packages/server/src/shared/types.ts b/packages/server/src/shared/types.ts
new file mode 100644
index 000000000..9758c41b6
--- /dev/null
+++ b/packages/server/src/shared/types.ts
@@ -0,0 +1,80 @@
+import type { LibraryJSONSchema, LibrarySpec } from "@openuidev/lang-core";
+import type { ChatCompletionMessageParam } from "openai/resources/chat/completions";
+
+export const MAX_AUTOFIX_GENERATION_LENGTH = 100_000;
+
+export interface AutofixOptions {
+ apiKey: string;
+ /** The same generated library spec used by the renderer. Schema is required for local checks. */
+ library: LibrarySpec & { schema: LibraryJSONSchema };
+ /** Origin of the Gateway; defaults to https://api.thesys.dev. */
+ apiBaseUrl?: string;
+ fetch?: typeof globalThis.fetch;
+}
+
+export interface AutofixDiagnostic {
+ code: string;
+ message: string;
+ component?: string;
+ path?: string;
+ statementId?: string;
+}
+
+export type AutofixResult = {
+ original: string;
+ fixedErrors: AutofixDiagnostic[];
+ unfixedErrors: AutofixDiagnostic[];
+} & (
+ { status: "already_valid" | "fixed"; content: string } | { status: "fix_failed"; content: null }
+);
+
+export interface BaseAutofixInput {
+ /** Context before the generated assistant message. The wrapper appends that message itself. */
+ messages?: ChatCompletionMessageParam[];
+ signal?: AbortSignal;
+}
+
+export interface AutofixInput extends BaseAutofixInput {
+ generation: string;
+}
+
+export type StreamSource<T> = AsyncIterable<T> & { controller?: AbortController };
+
+export interface AutofixStreamInput<Chunk> extends BaseAutofixInput {
+ /** Native SDK events for the selected import path. */
+ stream: StreamSource<Chunk>;
+}
+
+/** Wrap provider events with validation and repair while preserving the selected output protocol. */
+export interface StreamAdapter<Chunk> {
+ /** SSE format for emitted events; transform must produce chunks compatible with this protocol. */
+ protocol: "openai-chat-completions" | "vercel-ai";
+ /** Forward events and use fix to validate completed UI before emitting its completion marker. */
+ transform(
+ source: StreamSource<Chunk>,
+ fix: (generation: string) => Promise<AutofixResult>,
+ ): AsyncGenerator<Chunk>;
+}
+
+export interface AutofixStream<T> {
+ /** Single consumer. Preserves provider chunks and appends the corrected program before UI completion. */
+ chunks: AsyncIterable<T>;
+ /** Alternative to consuming chunks: SSE in the selected adapter's protocol. */
+ toResponse(): Response;
+ /** Settles after chunks or toResponse() finish. Null when Autofix did not run. Persist content, not joined deltas. */
+ result: Promise<AutofixResult | null>;
+}
+
+/** Stream and request failures throw; exhausted repairs include their diagnostics. */
+export class AutofixError extends Error {
+ // Attach a code and optional HTTP status or repair result to the error.
+ constructor(
+ message: string,
+ readonly code: string,
+ readonly status?: number,
+ readonly result?: AutofixResult,
+ ) {
+ super(message);
+ this.name = "AutofixError";
+ }
+}
diff --git a/packages/server/src/shared/utils.ts b/packages/server/src/shared/utils.ts
new file mode 100644
index 000000000..a6169b5c1
--- /dev/null
+++ b/packages/server/src/shared/utils.ts
@@ -0,0 +1,147 @@
+import type { ParseResult } from "@openuidev/lang-core";
+import type { AutofixDiagnostic, AutofixResult, BaseAutofixInput } from "./types";
+import { AutofixError } from "./types";
+
+// Collect parser errors, missing references, and incomplete output into diagnostics.
+export function errorsOf({ root, meta }: ParseResult): AutofixDiagnostic[] {
+ return [
+ ...meta.errors,
+ ...meta.unresolved.map((name) => ({
+ code: "unresolved",
+ statementId: name,
+ message: `Reference "${name}" is not defined`,
+ })),
+ ...meta.orphaned.map((name) => ({
+ code: "orphaned",
+ statementId: name,
+ message: `Statement "${name}" is not reachable from root`,
+ })),
+ ...(meta.incomplete ? [{ code: "incomplete", message: "Generation ends mid-statement" }] : []),
+ ...(root === null ? [{ code: "missing-root", message: "No root element" }] : []),
+ ];
+}
+
+// Check whether a value is a non-null object rather than an array.
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+
+// Check API diagnostics and extract their supported fields.
+function readDiagnostics(value: unknown): AutofixDiagnostic[] {
+ if (!Array.isArray(value))
+ throw new AutofixError("Malformed Autofix diagnostics", "invalid_response");
+ return value.map((entry: unknown) => {
+ if (
+ !isRecord(entry) ||
+ typeof entry["code"] !== "string" ||
+ typeof entry["message"] !== "string"
+ ) {
+ throw new AutofixError("Malformed Autofix diagnostic", "invalid_response");
+ }
+ return {
+ code: entry["code"],
+ message: entry["message"],
+ ...(typeof entry["component"] === "string" && { component: entry["component"] }),
+ ...(typeof entry["path"] === "string" && { path: entry["path"] }),
+ ...(typeof entry["statementId"] === "string" && { statementId: entry["statementId"] }),
+ };
+ });
+}
+
+// Read the API response into the package's result shape without reparsing the program.
+export function readCompletion(body: unknown): Omit<AutofixResult, "original"> {
+ if (!isRecord(body) || !isRecord(body["fix_summary"])) {
+ throw new AutofixError("Missing Autofix summary", "invalid_response");
+ }
+ const summary = body["fix_summary"];
+ const status = summary["status"];
+ if (status !== "fixed" && status !== "already_valid" && status !== "fix_failed") {
+ throw new AutofixError("Unknown Autofix status", "invalid_response");
+ }
+ const choices = body["choices"];
+ const choice: unknown = Array.isArray(choices) ? choices[0] : undefined;
+ const message = isRecord(choice) ? choice["message"] : undefined;
+ const content = isRecord(message) ? message["content"] : undefined;
+ if (
+ (status === "fix_failed" && content !== null) ||
+ (status !== "fix_failed" && typeof content !== "string")
+ ) {
+ throw new AutofixError("Malformed Autofix content", "invalid_response");
+ }
+ return {
+ status,
+ content: content as string | null,
+ fixedErrors: readDiagnostics(summary["fixed_errors"]),
+ unfixedErrors: readDiagnostics(summary["unfixed_errors"]),
+ };
+}
+
+/** Keep recent text context within the endpoint's limit of 20 messages and 8,000 characters. */
+export function repairContext(messages: NonNullable<BaseAutofixInput["messages"]>) {
+ const context: { role: "user" | "assistant" | "system" | "developer"; content: string }[] = [];
+ let remaining = 8_000;
+ for (let i = messages.length - 1; i >= 0 && context.length < 20 && remaining > 0; i--) {
+ const message = messages[i]!;
+ if (!["user", "assistant", "system", "developer"].includes(message.role)) continue;
+ const text =
+ typeof message.content === "string"
+ ? message.content
+ : (message.content ?? []).map((part) => (part.type === "text" ? part.text : "")).join("\n");
+ if (!text) continue;
+ const content = text.slice(-remaining);
+ context.unshift({ role: message.role as (typeof context)[number]["role"], content });
+ remaining -= content.length;
+ }
+ return context;
+}
+
+const OPENUI_FENCE = /```openui(?:-lang)?\s*\n/;
+const ROOT_ASSIGN = /(^|\n)\s*root\s*=/;
+const CONTENT_OPEN = "]]>openui:content";
+const CONTENT_END = "]]>openui:end";
+const FENCE_CLOSE = "```";
+const FENCE_CLOSE_WITH_END = "```\n]]>openui:end";
+
+/** OpenUI Lang is a Cloud content marker, a fenced ```openui block, or an unfenced `root =` program. */
+export function isUIOutput(text: string): boolean {
+ return text.includes(CONTENT_OPEN) || text.search(OPENUI_FENCE) >= 0 || ROOT_ASSIGN.test(text);
+}
+
+/** Split a closed OpenUI block from its closer (```, or ``` plus ]]>openui:end). */
+export function splitClosedFence(text: string): { body: string; closing: string } | null {
+ const fence = text.search(OPENUI_FENCE);
+ const content = text.indexOf(CONTENT_OPEN);
+ const open = fence >= 0 ? fence : content;
+ if (open < 0) return null;
+ const afterOpenNl = text.indexOf("\n", open);
+ if (afterOpenNl < 0) return null;
+ const from = afterOpenNl + 1;
+ // Prefer the Cloud closer so a later repair stays inside ]]>openui:content … end.
+ if (content >= 0) {
+ const closeWithEnd = text.indexOf(FENCE_CLOSE_WITH_END, from);
+ if (closeWithEnd >= 0)
+ return { body: text.slice(0, closeWithEnd), closing: text.slice(closeWithEnd) };
+ const closeEnd = text.indexOf(CONTENT_END, from);
+ if (closeEnd >= 0) return { body: text.slice(0, closeEnd), closing: text.slice(closeEnd) };
+ // Fence is open but ]]>openui:end has not arrived; hold a bare ``` if present.
+ if (fence < 0) return null;
+ }
+ const close = text.indexOf(FENCE_CLOSE, from);
+ if (close < 0) return null;
+ return { body: text.slice(0, close), closing: text.slice(close) };
+}
+
+/** Inner OpenUI program, without a wrapping markdown fence or Cloud markers. */
+export function unwrapOpenUIFence(text: string): string {
+ const fence = text.search(OPENUI_FENCE);
+ if (fence >= 0) {
+ const start = text.indexOf("\n", fence) + 1;
+ const close = text.indexOf("```", start);
+ return (close < 0 ? text.slice(start) : text.slice(start, close)).trim();
+ }
+ const content = text.indexOf(CONTENT_OPEN);
+ if (content < 0) return text;
+ const start = text.indexOf("\n", content) + 1;
+ const close = text.indexOf(CONTENT_END, start);
+ return (close < 0 ? text.slice(start) : text.slice(start, close)).trim();
+}
diff --git a/packages/server/src/vercel/adapter.ts b/packages/server/src/vercel/adapter.ts
new file mode 100644
index 000000000..cdd0c9e59
--- /dev/null
+++ b/packages/server/src/vercel/adapter.ts
@@ -0,0 +1,105 @@
+import type { UIMessageChunk } from "ai";
+import { MAX_AUTOFIX_GENERATION_LENGTH, type StreamAdapter } from "../shared/types";
+import { isUIOutput, splitClosedFence, unwrapOpenUIFence } from "../shared/utils";
+
+/** Preserve AI SDK UI message chunks and repair text before a successful final step closes. */
+export const vercelAIAdapter: StreamAdapter<UIMessageChunk> = {
+ protocol: "vercel-ai",
+ // Track text within each step and wait for the finish reason before attempting repair.
+ async *transform(source, fix) {
+ const texts = new Map<string, string | null>();
+ const closings = new Map<string, string>();
+ let held: UIMessageChunk[] = [];
+ let hasTools = false;
+ let failed = false;
+
+ // Release deferred endings, optionally inserting a repair before a held closing fence.
+ async function* release(repair = false): AsyncGenerator<UIMessageChunk> {
+ for (const event of held) {
+ // Insert repair and closer just before the text part ends.
+ if (event.type === "text-end") {
+ const text = texts.get(event.id);
+ // Repair only a successful final-step UI generation.
+ if (repair && text != null && isUIOutput(text)) {
+ const result = await fix(text);
+ // Only append when Autofix actually changed the text.
+ if (result.status === "fixed") {
+ yield {
+ type: "text-delta",
+ id: event.id,
+ delta: `\n${unwrapOpenUIFence(result.content)}\n`,
+ };
+ }
+ }
+ const closing = closings.get(event.id);
+ // Emit the held fence closer after any repair.
+ if (closing) yield { type: "text-delta", id: event.id, delta: closing };
+ }
+ yield event;
+ }
+ held = [];
+ texts.clear();
+ closings.clear();
+ }
+
+ for await (const event of source) {
+ // New step; the previous one was not the final answer.
+ if (event.type === "start" || event.type === "start-step") {
+ yield* release();
+ hasTools = false;
+ // A new run resets the failure flag.
+ if (event.type === "start") failed = false;
+ }
+ // Start accumulating this text part.
+ if (event.type === "text-start") {
+ texts.set(event.id, "");
+ closings.delete(event.id);
+ }
+ // Accumulate text and maybe hold a closing fence.
+ if (event.type === "text-delta") {
+ const previous = texts.get(event.id);
+ // Still tracking this text part.
+ if (previous != null) {
+ const combined = previous + event.delta;
+ // Too large to send to Autofix; stop holding.
+ if (combined.length > MAX_AUTOFIX_GENERATION_LENGTH) {
+ texts.set(event.id, null);
+ const closing = closings.get(event.id);
+ closings.delete(event.id);
+ yield closing ? { ...event, delta: closing + event.delta } : event;
+ continue;
+ }
+ texts.set(event.id, combined);
+ const split = splitClosedFence(combined);
+ // Hold the closing fence so a later repair stays inside it.
+ if (split) {
+ closings.set(event.id, split.closing);
+ const emit = split.body.slice(previous.length);
+ // Emit the body slice if anything remains after holding the closer.
+ if (emit) yield { ...event, delta: emit };
+ continue;
+ }
+ }
+ }
+ // Tools mean this step is not the final UI answer.
+ if (event.type.startsWith("tool-")) hasTools = true;
+ // Failed run; flush held events without repair.
+ if (event.type === "error" || event.type === "abort") {
+ failed = true;
+ yield* release();
+ }
+ // Hold endings until the stream finishes.
+ if (event.type === "text-end" || event.type === "finish-step") {
+ held.push(event);
+ continue;
+ }
+ // Stream done; repair only on a clean stop without tools or errors.
+ if (event.type === "finish") {
+ yield* release(event.finishReason === "stop" && !failed && !hasTools);
+ }
+ yield event;
+ }
+ // EOF without a successful finish preserves events without attempting repair.
+ yield* release();
+ },
+};
diff --git a/packages/server/src/vercel/index.ts b/packages/server/src/vercel/index.ts
new file mode 100644
index 000000000..b9c8ae26c
--- /dev/null
+++ b/packages/server/src/vercel/index.ts
@@ -0,0 +1,10 @@
+import { createAutofix as createAutofixPipeline } from "../shared/create-autofix";
+import type { AutofixOptions } from "../shared/types";
+import { vercelAIAdapter } from "./adapter";
+
+// Create validation and repair helpers for Vercel AI SDK UI message streams.
+export function createAutofix(options: AutofixOptions) {
+ return {
+ ai: createAutofixPipeline(options, vercelAIAdapter),
+ };
+}
diff --git a/packages/server/tsdown.config.ts b/packages/server/tsdown.config.ts
index bd5f1a3e1..1ba4a4023 100644
--- a/packages/server/tsdown.config.ts
+++ b/packages/server/tsdown.config.ts
@@ -1,14 +1,33 @@
-import { defineConfig } from "tsdown";
+import { defineConfig, type UserConfig } from "tsdown";
-export default defineConfig({
- entry: ["src/index.ts"],
+// One outDir per entry so each folder's index.ts emits dist/<name>/index.d.ts.
+const shared: UserConfig = {
format: ["esm", "cjs"],
dts: true,
sourcemap: true,
target: "es2022",
- outDir: "dist",
- clean: true,
deps: {
neverBundle: [/^(?![./]|[A-Za-z]:[/\\])/],
},
-});
+};
+
+export default defineConfig([
+ {
+ ...shared,
+ entry: { index: "src/index.ts" },
+ outDir: "dist",
+ clean: true,
+ },
+ {
+ ...shared,
+ entry: { index: "src/openai/index.ts" },
+ outDir: "dist/openai",
+ clean: false,
+ },
+ {
+ ...shared,
+ entry: { index: "src/vercel/index.ts" },
+ outDir: "dist/vercel",
+ clean: false,
+ },
+]);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index eaf52e435..8f787ae9b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -879,10 +879,17 @@ importers:
packages/server:
+ dependencies:
+ '@openuidev/lang-core':
+ specifier: workspace:^
+ version: link:../lang-core
devDependencies:
+ ai:
+ specifier: ^7.0.10
+ version: 7.0.10([email protected])
openai:
- specifier: ^6.22.0
+ specifier: ^7.20.0
tsdown:
specifier: ^0.21.7
@@ -978,16 +985,32 @@ packages:
peerDependencies:
zod: ^3.25.76 || ^4.1.8
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-esHzojMp+LllqOnEu6sYa6NKOmPcE5UObPV61LE6L2QAzCH6WHMgTS+Q/HF5HU3lVUWsHtkDzN7TNqMfv/ecCg==}
+ engines: {node: '>=22'}
+ peerDependencies:
+ zod: ^3.25.76 || ^4.1.8
+
'@ai-sdk/[email protected]':
resolution: {integrity: sha512-OL5IrpUm9Y8Dwy+w/vvFwPotS6m52O9W0op2oXgXdCROMJIBalBI0oro6OIBYkPxvm5Xg02GSkoQN25RlR0bnw==}
engines: {node: '>=18'}
peerDependencies:
zod: ^3.25.76 || ^4.1.8
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-El0JOXXGcHFe6+owJ1UV0VgB9XtdivP8vcZni+rUIt6lt+cBHCnUdddaA6LE2avJGJ5AD0uXSY+uAvRL2tSvgw==}
+ engines: {node: '>=22'}
+ peerDependencies:
+ zod: ^3.25.76 || ^4.1.8
+
'@ai-sdk/[email protected]':
resolution: {integrity: sha512-5X1k57JBJ4H7H1QjX7CnJYAB1I19r/trVZTMcSms7/kLNZ8RaU4Nt2agcwZzv82Hfx6Q7/TOLU7agAKeFfc8cA==}
engines: {node: '>=18'}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-6p3C/vGqVIjcptBu1DnVd/BZJ2wWmV9TUv9192vT6ZvT9KNED8EwRTqyqFpoQZKgSbMDSvBSq3dqR524Nt/Crw==}
+ engines: {node: '>=22'}
+
resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}
engines: {node: '>=10'}
@@ -5860,6 +5883,9 @@ packages:
'@webcontainer/[email protected]':
resolution: {integrity: sha512-6aN99yL695Hi9SuIk1oC88l9o0gmxL1nGWWQ/kNy81HigJ0FoaoTXpytCj6ItzgyCEwA9kF1wixsTuv5cjsgng==}
+ '@workflow/[email protected]':
+ resolution: {integrity: sha512-pav4F2BoirECWR7Nf1TKt+2eETcBj7jj4cBefQ8VXQCA6NPkaKeLfj/zMgi+3zYV5ZIBT4GuUiphsj0/b9hPQQ==}
+
resolution: {integrity: sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==}
@@ -5894,6 +5920,12 @@ packages:
peerDependencies:
zod: ^3.25.76 || ^4.1.8
+ resolution: {integrity: sha512-qfrNXGNlSBZJgB4rM1AkcMUnM776+SEgp4jUToQWPX+nOOdk04Bzbta+G84NEDmxs87ojkqTn+MWVfeXvPg4Dg==}
+ engines: {node: '>=22'}
+ peerDependencies:
+ zod: ^3.25.76 || ^4.1.8
+
resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==}
peerDependencies:
@@ -9109,6 +9141,30 @@ packages:
zod:
optional: true
+ resolution: {integrity: sha512-5x5ru4cKEvEqHqYZbdIbT57OE7KqmP9YYxZiUKuKng016grOHXqom1vmu34MTPPW30q+lcP9RhxAbaRse+Xlcw==}
+ engines: {node: '>=22.0.0'}
+ peerDependencies:
+ '@aws-sdk/credential-provider-node': '>=3.972.0 <4'
+ '@smithy/hash-node': '>=4.3.0 <5'
+ '@smithy/signature-v4': '>=5.4.0 <6'
+ undici: '>=5 <9'
+ ws: ^8.21.0
+ zod: ^3.25 || ^4.0
+ peerDependenciesMeta:
+ '@aws-sdk/credential-provider-node':
+ optional: true
+ '@smithy/hash-node':
+ optional: true
+ '@smithy/signature-v4':
+ optional: true
+ undici:
+ optional: true
+ ws:
+ optional: true
+ zod:
+ optional: true
+
resolution: {integrity: sha512-QSw0BA08piujetEwfZsHoTrDpMEha7GDZDicQqVwX4u0ChCjefvjDB++TZ8BTg76UpwhzIQgdvvfgfl3HpCSAw==}
@@ -11091,6 +11147,13 @@ snapshots:
'@vercel/oidc': 3.2.0
zod: 4.4.3
+ dependencies:
+ '@ai-sdk/provider': 4.0.1
+ '@ai-sdk/provider-utils': 5.0.3([email protected])
+ '@vercel/oidc': 3.2.0
+ zod: 4.4.3
+
dependencies:
'@ai-sdk/provider': 3.0.14
@@ -11098,10 +11161,22 @@ snapshots:
eventsource-parser: 3.1.0
zod: 4.4.3
+ dependencies:
+ '@ai-sdk/provider': 4.0.1
+ '@standard-schema/spec': 1.1.0
+ '@workflow/serde': 4.1.0
+ eventsource-parser: 3.1.0
+ zod: 4.4.3
+
'@ai-sdk/[email protected]':
dependencies:
json-schema: 0.4.0
+ '@ai-sdk/[email protected]':
+ dependencies:
+ json-schema: 0.4.0
+
'@alloc/[email protected]': {}
'@ampproject/[email protected]':
@@ -16098,6 +16173,8 @@ snapshots:
'@webcontainer/[email protected]': {}
+ '@workflow/[email protected]': {}
+
'@xtuc/[email protected]': {}
'@xtuc/[email protected]': {}
@@ -16125,6 +16202,13 @@ snapshots:
'@opentelemetry/api': 1.9.1
zod: 4.4.3
+ dependencies:
+ '@ai-sdk/gateway': 4.0.8([email protected])
+ '@ai-sdk/provider': 4.0.1
+ '@ai-sdk/provider-utils': 5.0.3([email protected])
+ zod: 4.4.3
+
optionalDependencies:
ajv: 8.20.0
@@ -19800,6 +19884,13 @@ snapshots:
ws: 8.21.1
zod: 4.4.3
+ optionalDependencies:
+ '@aws-sdk/credential-provider-node': 3.972.73
+ '@smithy/signature-v4': 5.6.11
+ ws: 8.21.1
+ zod: 4.4.3
+
dependencies:
jose: 6.2.4