The Open Standard for Generative UI
OpenUI 1.0: docs (#1352)
Aditya-thesys0600740235e1
diff --git a/docs/components/diagram-kit.tsx b/docs/components/diagram-kit.tsxnew file mode 100644index 000000000..bc2cb1787--- /dev/null+++ b/docs/components/diagram-kit.tsx@@ -0,0 +1,424 @@+import type { LucideIcon } from "lucide-react";+import type { ReactNode } from "react";++// Shared drawing pieces for the OpenUI Lang docs diagrams. They follow the style of+// openui-flow-diagram.tsx: outlined boxes, lucide icons, uppercase mono arrow labels, and theme+// tokens so the same SVG works in light and dark mode.++export const labelClass =+ "fill-fd-foreground font-mono text-[13px] font-bold uppercase tracking-[0.1em]";++// For labels that are code, such as a function name, where uppercase would change the meaning.+const codeLabelClass = "fill-fd-foreground font-mono text-[13px] font-bold";++const boxClass = "fill-fd-background stroke-fd-foreground";+const highlightClass = "fill-[#eef1fb] stroke-fd-foreground dark:fill-[#1c2233]";++export function DiagramFrame({+ id,+ title,+ description,+ width,+ height,+ minWidth,+ children,+}: {+ id: string;+ title: string;+ description: string;+ width: number;+ height: number;+ /** Below this width the figure scrolls inside its container instead of shrinking further. */+ minWidth: number;+ children: ReactNode;+}) {+ return (+ <figure className="not-prose my-8 overflow-x-auto">+ <svg+ viewBox={`0 0 ${width} ${height}`}+ role="img"+ aria-labelledby={`${id}-title ${id}-description`}+ className="h-auto w-full text-fd-foreground"+ style={{ minWidth }}+ >+ <title id={`${id}-title`}>{title}</title>+ <desc id={`${id}-description`}>{description}</desc>+ <defs>+ <marker+ id={`${id}-arrow`}+ viewBox="0 0 10 10"+ refX="9"+ refY="5"+ markerWidth="11"+ markerHeight="11"+ markerUnits="userSpaceOnUse"+ orient="auto-start-reverse"+ >+ <path+ d="M1 1 L9 5 L1 9"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.6"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </marker>+ </defs>+ {children}+ </svg>+ </figure>+ );+}++export function Label({+ x,+ y,+ anchor = "middle",+ code,+ children,+}: {+ x: number;+ y: number;+ anchor?: "start" | "middle" | "end";+ code?: boolean;+ children: ReactNode;+}) {+ return (+ <text x={x} y={y} textAnchor={anchor} className={code ? codeLabelClass : labelClass}>+ {children}+ </text>+ );+}++export function Arrow({+ marker,+ x1,+ y1,+ x2,+ y2,+ dashed,+}: {+ marker: string;+ x1: number;+ y1: number;+ x2: number;+ y2: number;+ dashed?: boolean;+}) {+ return (+ <line+ x1={x1}+ y1={y1}+ x2={x2}+ y2={y2}+ stroke="currentColor"+ strokeWidth={1.6}+ strokeDasharray={dashed ? "5 5" : undefined}+ markerEnd={`url(#${marker}-arrow)`}+ />+ );+}++export function PathArrow({ marker, d, dashed }: { marker: string; d: string; dashed?: boolean }) {+ return (+ <path+ d={d}+ fill="none"+ stroke="currentColor"+ strokeWidth={1.6}+ strokeDasharray={dashed ? "5 5" : undefined}+ markerEnd={`url(#${marker}-arrow)`}+ />+ );+}++export type NodeProps = {+ x: number;+ y: number;+ width: number;+ height: number;+ icon: LucideIcon;+ title: string;+ lines?: string[];+ footer?: string;+ highlight?: boolean;+ /** Keep the title's case, for code such as `$days` or `parseMessage`. */+ codeTitle?: boolean;+};++/** A box with a centered icon, an uppercase title, and short lines of text. */+export function Node({+ x,+ y,+ width,+ height,+ icon: Icon,+ title,+ lines = [],+ footer,+ highlight,+ codeTitle,+}: NodeProps) {+ const center = x + width / 2;+ const contentHeight = 30 + 30 + lines.length * 22;+ const top = y + Math.max(14, (height - contentHeight - (footer ? 22 : 0)) / 2);+ const titleY = top + 52;+ return (+ <g>+ <rect+ x={x}+ y={y}+ width={width}+ height={height}+ rx={12}+ strokeWidth={1.75}+ className={highlight ? highlightClass : boxClass}+ />+ <Icon+ x={center - 14}+ y={top}+ width={28}+ height={28}+ strokeWidth={1.6}+ className="text-fd-foreground"+ aria-hidden="true"+ />+ <text+ x={center}+ y={titleY}+ textAnchor="middle"+ className={+ codeTitle+ ? "fill-fd-foreground font-mono text-[16px] font-bold"+ : "fill-fd-foreground font-mono text-[15px] font-bold uppercase tracking-[0.05em]"+ }+ >+ {title}+ </text>+ {lines.map((line, index) => (+ <text+ key={line}+ x={center}+ y={titleY + 26 + index * 22}+ textAnchor="middle"+ className="fill-fd-muted-foreground font-sans text-[15px]"+ >+ {line}+ </text>+ ))}+ {footer && (+ <text+ x={center}+ y={y + height - 14}+ textAnchor="middle"+ className="fill-fd-muted-foreground font-mono text-[11.5px] font-semibold uppercase tracking-[0.12em]"+ >+ {footer}+ </text>+ )}+ </g>+ );+}++export type CodeLine = { text: string; tag?: string };++/** A box with an icon and title on top and lines of code below. */+export function CodeNode({+ x,+ y,+ width,+ height,+ icon: Icon,+ title,+ code,+ highlight,+}: {+ x: number;+ y: number;+ width: number;+ height: number;+ icon: LucideIcon;+ title: string;+ code: (string | CodeLine)[];+ highlight?: boolean;+}) {+ return (+ <g>+ <rect+ x={x}+ y={y}+ width={width}+ height={height}+ rx={12}+ strokeWidth={1.75}+ className={highlight ? highlightClass : boxClass}+ />+ <Icon+ x={x + 16}+ y={y + 14}+ width={22}+ height={22}+ strokeWidth={1.6}+ className="text-fd-foreground"+ aria-hidden="true"+ />+ <text+ x={x + 48}+ y={y + 31}+ className="fill-fd-foreground font-mono text-[14px] font-bold uppercase tracking-[0.05em]"+ >+ {title}+ </text>+ <line+ x1={x}+ y1={y + 48}+ x2={x + width}+ y2={y + 48}+ strokeWidth={1}+ className="stroke-fd-muted-foreground/40"+ />+ {code.map((entry, index) => {+ const line = typeof entry === "string" ? { text: entry } : entry;+ const lineY = y + 74 + index * 24;+ return (+ <g key={`${index}-${line.text}`}>+ <text+ x={x + 16}+ y={lineY}+ xmlSpace="preserve"+ className="fill-fd-foreground font-mono text-[13.5px]"+ >+ {line.text}+ </text>+ {line.tag && (+ <text+ x={x + width - 16}+ y={lineY}+ textAnchor="end"+ className="fill-fd-muted-foreground font-mono text-[11.5px] font-bold uppercase tracking-[0.12em]"+ >+ {line.tag}+ </text>+ )}+ </g>+ );+ })}+ </g>+ );+}++export function Lane({+ x,+ y,+ width,+ height,+ title,+ tag,+ tagWidth = 150,+ tagRight,+}: {+ x: number;+ y: number;+ width: number;+ height: number;+ title: string;+ tag?: string;+ tagWidth?: number;+ /** Put the tag at the right end of the lane instead of after the title. */+ tagRight?: boolean;+}) {+ const titleWidth = title.length * 9.6;+ const tagX = tagRight ? x + width - 20 - tagWidth : x + 32 + titleWidth;+ return (+ <g>+ <rect+ x={x}+ y={y}+ width={width}+ height={height}+ rx={16}+ strokeWidth={1.25}+ strokeDasharray="6 6"+ className="fill-fd-muted/40 stroke-fd-muted-foreground/60"+ />+ <text x={x + 20} y={y + 32} className={labelClass}>+ {title}+ </text>+ {tag && (+ <g>+ <rect+ x={tagX}+ y={y + 14}+ width={tagWidth}+ height={26}+ rx={13}+ className="fill-fd-foreground"+ />+ <text+ x={tagX + tagWidth / 2}+ y={y + 32}+ textAnchor="middle"+ className="fill-fd-background font-mono text-[11.5px] font-bold uppercase tracking-[0.12em]"+ >+ {tag}+ </text>+ </g>+ )}+ </g>+ );+}++/** A short box with the icon on the left, a title, and one line of text. */+export function RowNode({+ x,+ y,+ width,+ height,+ icon: Icon,+ title,+ line,+ highlight,+}: {+ x: number;+ y: number;+ width: number;+ height: number;+ icon: LucideIcon;+ title: string;+ line: string;+ highlight?: boolean;+}) {+ const middle = y + height / 2;+ return (+ <g>+ <rect+ x={x}+ y={y}+ width={width}+ height={height}+ rx={12}+ strokeWidth={1.75}+ className={highlight ? highlightClass : boxClass}+ />+ <Icon+ x={x + 18}+ y={middle - 12}+ width={24}+ height={24}+ strokeWidth={1.6}+ className="text-fd-foreground"+ aria-hidden="true"+ />+ <text+ x={x + 58}+ y={middle - 4}+ className="fill-fd-foreground font-mono text-[14px] font-bold uppercase tracking-[0.05em]"+ >+ {title}+ </text>+ <text x={x + 58} y={middle + 17} className="fill-fd-muted-foreground font-sans text-[14px]">+ {line}+ </text>+ </g>+ );+}diff --git a/docs/components/openui-lang-diagrams.tsx b/docs/components/openui-lang-diagrams.tsxnew file mode 100644index 000000000..6af59e443--- /dev/null+++ b/docs/components/openui-lang-diagrams.tsx@@ -0,0 +1,592 @@+import {+ AppWindow,+ Bot,+ Cpu,+ Database,+ FileCode,+ FilePen,+ FileSearch,+ GitMerge,+ LayoutDashboard,+ LineChart,+ ListFilter,+ MessageSquare,+ Search,+ Server,+ Type,+ Variable,+ Wrench,+} from "lucide-react";+import {+ Arrow,+ CodeNode,+ DiagramFrame,+ Label,+ Lane,+ Node,+ PathArrow,+ RowNode,+} from "./diagram-kit";++/** openui-lang/index: message in, prompt to the model, OpenUI Lang streamed back and rendered. */+export function LangGlanceDiagram() {+ const m = "lang-glance";+ return (+ <DiagramFrame+ id={m}+ title="OpenUI Lang at a glance"+ description="Your frontend sends the user's message to your backend. Your backend adds the prompt generated from your component library and calls the model. The model writes OpenUI Lang, for example root = Stack([chart]). Your backend streams it to your frontend, where the Renderer turns each line into your components."+ width={1020}+ height={400}+ minWidth={640}+ >+ <Node+ x={10}+ y={30}+ width={230}+ height={210}+ icon={AppWindow}+ title="Your frontend"+ lines={["The Renderer turns", "each line into your", "components"]}+ />+ <Node+ x={395}+ y={30}+ width={230}+ height={210}+ icon={Server}+ title="Your backend"+ lines={["Adds the prompt", "made from your", "component library"]}+ />+ <Node+ x={780}+ y={30}+ width={230}+ height={210}+ icon={Bot}+ title="Model"+ lines={["Writes OpenUI Lang", "with your components"]}+ highlight+ />++ <Arrow marker={m} x1={244} y1={110} x2={389} y2={110} />+ <Label x={317} y={98}>+ Message+ </Label>+ <Arrow marker={m} x1={391} y1={160} x2={246} y2={160} />+ <Label x={317} y={182}>+ Stream+ </Label>++ <Arrow marker={m} x1={629} y1={110} x2={774} y2={110} />+ <Label x={702} y={98}>+ Prompt+ </Label>+ <Arrow marker={m} x1={776} y1={160} x2={631} y2={160} />+ <Label x={702} y={182}>+ OpenUI Lang+ </Label>++ <Arrow marker={m} x1={895} y1={244} x2={895} y2={266} dashed />+ <CodeNode+ x={720}+ y={270}+ width={290}+ height={120}+ icon={FileCode}+ title="Example output"+ code={["root = Stack([chart])", "chart = PieChart(...)"]}+ />+ </DiagramFrame>+ );+}++/** architecture: generate once with the model, then execute without it. */+export function GenerateExecuteDiagram() {+ const m = "generate-execute";+ const xs = [35, 295, 555, 815];+ const w = 180;+ return (+ <DiagramFrame+ id={m}+ title="Generate once, then execute"+ description="Generate runs once per request: the user's request goes to your backend, which sends the system prompt and tool specs to the model, and the model writes an OpenUI Lang program. Execute runs after generation, without the model: the Renderer parses the program and renders your components. When the user clicks or changes a $variable, the runtime calls your tools through the toolProvider and sends the rows back to the components."+ width={1020}+ height={520}+ minWidth={680}+ >+ <Lane+ x={10}+ y={10}+ width={1000}+ height={210}+ title="Generate"+ tag="Once per request"+ tagWidth={170}+ tagRight+ />+ <Node+ x={xs[0]}+ y={60}+ width={w}+ height={140}+ icon={MessageSquare}+ title="Request"+ lines={["The user asks", "for a UI"]}+ />+ <Node+ x={xs[1]}+ y={60}+ width={w}+ height={140}+ icon={Server}+ title="Your backend"+ lines={["System prompt", "and tool specs"]}+ />+ <Node+ x={xs[2]}+ y={60}+ width={w}+ height={140}+ icon={Bot}+ title="Model"+ lines={["Writes the", "program"]}+ />+ <Node+ x={xs[3]}+ y={60}+ width={w}+ height={140}+ icon={FileCode}+ title="OpenUI Lang"+ lines={["Layout, queries,", "and actions"]}+ highlight+ />+ {[0, 1, 2].map((i) => (+ <Arrow key={i} marker={m} x1={xs[i] + w + 4} y1={130} x2={xs[i + 1] - 6} y2={130} />+ ))}++ <PathArrow marker={m} d="M905 204 V250 H125 V331" />+ <Label x={515} y={242}>+ Program+ </Label>++ <Lane+ x={10}+ y={280}+ width={1000}+ height={230}+ title="Execute"+ tag="Every click, no model"+ tagWidth={200}+ tagRight+ />+ <Node+ x={xs[0]}+ y={335}+ width={w}+ height={140}+ icon={FileSearch}+ title="Renderer"+ lines={["Parses the", "program"]}+ />+ <Node+ x={xs[1]}+ y={335}+ width={w}+ height={140}+ icon={LayoutDashboard}+ title="Components"+ lines={["Your design", "system"]}+ />+ <Node+ x={xs[2]}+ y={335}+ width={w}+ height={140}+ icon={Cpu}+ title="Runtime"+ lines={["Runs queries", "and actions"]}+ />+ <Node+ x={xs[3]}+ y={335}+ width={w}+ height={140}+ icon={Wrench}+ title="Your tools"+ lines={["Function map", "or MCP"]}+ />++ <Arrow marker={m} x1={xs[0] + w + 4} y1={405} x2={xs[1] - 6} y2={405} />+ <Label x={xs[0] + w + 40} y={393}>+ Renders+ </Label>++ <Arrow marker={m} x1={xs[1] + w + 4} y1={385} x2={xs[2] - 6} y2={385} />+ <Label x={xs[1] + w + 40} y={373}>+ Clicks+ </Label>+ <Arrow marker={m} x1={xs[2] - 4} y1={425} x2={xs[1] + w + 6} y2={425} />+ <Label x={xs[1] + w + 40} y={447}>+ Data+ </Label>++ <Arrow marker={m} x1={xs[2] + w + 4} y1={385} x2={xs[3] - 6} y2={385} />+ <Label x={xs[2] + w + 40} y={373}>+ Call+ </Label>+ <Arrow marker={m} x1={xs[3] - 4} y1={425} x2={xs[2] + w + 6} y2={425} />+ <Label x={xs[2] + w + 40} y={447}>+ Rows+ </Label>+ </DiagramFrame>+ );+}++/** reactive-state: one $variable change updates everything that reads it. */+export function ReactivityDiagram() {+ const m = "reactivity";+ return (+ <DiagramFrame+ id={m}+ title="How a $variable change spreads"+ description="The user picks 30 days in a Select. The Select is bound to $days, which changes from 7 to 30. The TextContent that reads $days shows the new text. The Query that takes $days in its arguments fetches again with days 30, and the Chart that reads the Query's rows re-renders."+ width={1020}+ height={450}+ minWidth={640}+ >+ <Node+ x={30}+ y={20}+ width={260}+ height={150}+ icon={ListFilter}+ title="Select"+ lines={["The user picks", '"30 days"']}+ />+ <Node+ x={370}+ y={20}+ width={260}+ height={150}+ icon={Variable}+ title="$days"+ lines={['"7" → "30"']}+ codeTitle+ highlight+ />+ <Arrow marker={m} x1={294} y1={95} x2={364} y2={95} />+ <Label x={329} y={83}>+ Sets+ </Label>++ <Arrow marker={m} x1={500} y1={174} x2={500} y2={274} />+ <PathArrow marker={m} d="M500 222 H170 V274" />+ <Label x={335} y={212}>+ Re-evaluates+ </Label>+ <Label x={512} y={212} anchor="start">+ Re-fetches+ </Label>++ <Node+ x={30}+ y={280}+ width={280}+ height={150}+ icon={Type}+ title="TextContent"+ lines={['"Showing last', '30 days"']}+ />+ <Node+ x={360}+ y={280}+ width={280}+ height={150}+ icon={Search}+ title="Query"+ lines={["Fetches again with", '{days: "30"}']}+ />+ <Node+ x={690}+ y={280}+ width={280}+ height={150}+ icon={LineChart}+ title="Chart"+ lines={["Re-renders with", "the new rows"]}+ />+ <Arrow marker={m} x1={644} y1={355} x2={684} y2={355} />+ <Label x={665} y={343}>+ Rows+ </Label>+ </DiagramFrame>+ );+}++/** queries-mutations: a Query goes from the program through the runtime to your tools. */+export function QueryFlowDiagram() {+ const m = "query-flow";+ return (+ <DiagramFrame+ id={m}+ title="How a Query reaches your tools"+ description="The program declares tickets = Query(list_tickets). On load, or when an action runs it with @Run, the runtime evaluates the arguments and calls the tool through toolProvider. Your tools, a function map or an MCP server, return rows. The runtime passes the rows to the components that read them, such as a table and a chart."+ width={1020}+ height={460}+ minWidth={640}+ >+ <CodeNode+ x={10}+ y={30}+ width={300}+ height={160}+ icon={FileCode}+ title="OpenUI Lang"+ code={["tickets = Query(", ' "list_tickets",', " {}, {rows: []})"]}+ />+ <Arrow marker={m} x1={314} y1={110} x2={414} y2={110} />+ <Label x={364} y={84}>+ On load+ </Label>+ <Label x={364} y={100}>+ or @Run+ </Label>++ <Node+ x={420}+ y={30}+ width={180}+ height={160}+ icon={Cpu}+ title="Runtime"+ lines={["Evaluates the", "arguments"]}+ highlight+ />++ <Arrow marker={m} x1={604} y1={90} x2={804} y2={90} />+ <Label x={704} y={78} code>+ toolProvider+ </Label>+ <Arrow marker={m} x1={806} y1={140} x2={606} y2={140} />+ <Label x={704} y={162} code>+ {"{ rows: [...] }"}+ </Label>++ <Node+ x={810}+ y={30}+ width={200}+ height={160}+ icon={Wrench}+ title="Your tools"+ lines={["Function map", "or MCP server"]}+ />++ <Arrow marker={m} x1={510} y1={194} x2={510} y2={290} />+ <Label x={522} y={248} anchor="start">+ Rows+ </Label>++ <Node+ x={375}+ y={296}+ width={270}+ height={150}+ icon={LayoutDashboard}+ title="Your components"+ lines={["The table and chart", "re-render with the rows"]}+ />+ </DiagramFrame>+ );+}++/** message-protocol: how a stored message is written and read again. */+export function MessageProtocolDiagram() {+ const m = "message-protocol";+ return (+ <DiagramFrame+ id={m}+ title="Storing and reloading a message"+ description="Save: the model streams a response, your app wraps it with buildMessage into ]]>openui: marker lines, and stores it. Reload: your app reads the stored message with parseMessage. The content goes to the Renderer, the context goes to your app, for example to restore form values, and no marker lines go to the model."+ width={1020}+ height={540}+ minWidth={680}+ >+ <Lane x={10} y={10} width={1000} height={200} title="Save" />+ <Node+ x={40}+ y={55}+ width={220}+ height={135}+ icon={Bot}+ title="Model"+ lines={["Streams the", "response"]}+ />+ <Node+ x={400}+ y={55}+ width={220}+ height={135}+ icon={FilePen}+ title="buildMessage"+ lines={["Your app adds the", "]]>openui: lines"]}+ codeTitle+ highlight+ />+ <Node+ x={760}+ y={55}+ width={220}+ height={135}+ icon={Database}+ title="Storage"+ lines={["Your database"]}+ />+ <Arrow marker={m} x1={264} y1={122} x2={394} y2={122} />+ <Label x={329} y={110}>+ Text+ </Label>+ <Arrow marker={m} x1={624} y1={122} x2={754} y2={122} />+ <Label x={689} y={110}>+ Message+ </Label>++ <Lane x={10} y={240} width={1000} height={290} title="Reload" />+ <Node+ x={40}+ y={315}+ width={180}+ height={150}+ icon={Database}+ title="Storage"+ lines={["Stored message"]}+ />+ <Node+ x={300}+ y={315}+ width={200}+ height={150}+ icon={FileSearch}+ title="parseMessage"+ lines={["Your app splits", "the message"]}+ codeTitle+ highlight+ />+ <Arrow marker={m} x1={224} y1={390} x2={294} y2={390} />+ <Label x={259} y={378}>+ Load+ </Label>++ <RowNode+ x={680}+ y={278}+ width={310}+ height={64}+ icon={AppWindow}+ title="Renderer"+ line="Renders the content"+ />+ <RowNode+ x={680}+ y={358}+ width={310}+ height={64}+ icon={Server}+ title="Your app"+ line="Restores form values"+ />+ <RowNode+ x={680}+ y={438}+ width={310}+ height={64}+ icon={Bot}+ title="Model"+ line="Never sees the markers"+ />+ <Arrow marker={m} x1={504} y1={390} x2={674} y2={390} />+ <PathArrow marker={m} d="M560 390 V310 H674" />+ <PathArrow marker={m} d="M560 390 V470 H674" dashed />+ <Label x={620} y={302}>+ Content+ </Label>+ <Label x={620} y={382}>+ Context+ </Label>+ <Label x={620} y={462}>+ No markers+ </Label>+ </DiagramFrame>+ );+}++/** incremental-editing: the parser merges the model's patch into the previous program by name. */+export function IncrementalEditDiagram() {+ const m = "incremental-edit";+ return (+ <DiagramFrame+ id={m}+ title="Merging a patch by statement name"+ description="The previous program has root, header, tickets, and tbl. The model's patch redefines root to include chart and adds chart. mergeStatements merges them by name: root is replaced, header, tickets, and tbl are kept, and chart is added."+ width={1020}+ height={350}+ minWidth={680}+ >+ <CodeNode+ x={10}+ y={10}+ width={350}+ height={162}+ icon={FileCode}+ title="Previous program"+ code={[+ "root = Stack([header, tbl])",+ 'header = CardHeader("Tickets")',+ "tickets = Query(...)",+ "tbl = Table([...])",+ ]}+ />+ <CodeNode+ x={10}+ y={220}+ width={350}+ height={114}+ icon={Bot}+ title="Model patch"+ code={["root = Stack([header, chart, tbl])", "chart = PieChart(...)"]}+ highlight+ />+ <Node+ x={410}+ y={100}+ width={175}+ height={150}+ icon={GitMerge}+ title="mergeStatements"+ lines={["Merges", "by name"]}+ codeTitle+ />+ <PathArrow marker={m} d="M364 91 H385 V150 H404" />+ <PathArrow marker={m} d="M364 277 H385 V200 H404" />+ <Arrow marker={m} x1={589} y1={175} x2={614} y2={175} />++ <CodeNode+ x={620}+ y={82}+ width={390}+ height={186}+ icon={FileCode}+ title="Merged program"+ code={[+ { text: "root = Stack([header, chart, tbl])", tag: "Replaced" },+ { text: 'header = CardHeader("Tickets")', tag: "Kept" },+ { text: "tickets = Query(...)", tag: "Kept" },+ { text: "tbl = Table([...])", tag: "Kept" },+ { text: "chart = PieChart(...)", tag: "Added" },+ ]}+ />+ </DiagramFrame>+ );+}diff --git a/docs/components/overview-components/genui.ts b/docs/components/overview-components/genui.tsindex 45a049e74..9d5b2d405 100644--- a/docs/components/overview-components/genui.ts+++ b/docs/components/overview-components/genui.ts@@ -1,2 +1,9 @@-export const genuiOutput =- 'root = Stack([welcomeCard])\nwelcomeCard = MyCard([welcomeHeader, welcomeBody])\nwelcomeHeader = CardHeader("Welcome", "Get started with our platform")\nwelcomeBody = Stack([signupForm], "column", "m")\nsignupForm = Form("signup", [nameField, emailField], actions)\nnameField = FormControl("Name", Input("name", "Your name", "text", ["required", "minLength:2"]))\nemailField = FormControl("Email", Input("email", "[email protected]", "email", ["required", "email"]))\nactions = Buttons([signUpBtn, learnMoreBtn], "row")\nsignUpBtn = Button("Sign up", "submit:signup", "primary")\nlearnMoreBtn = Button("Learn more", "action:learn_more", "secondary")';+export const genuiOutput = `root = Stack([welcomeCard])+welcomeCard = Card([welcomeHeader, signupForm])+welcomeHeader = CardHeader("Welcome", "Get started with our platform")+signupForm = Form("signup", actions, [nameField, emailField])+nameField = FormControl("Name", Input("name", "Your name", "text", {required: true, minLength: 2}))+emailField = FormControl("Email", Input("email", "[email protected]", "email", {required: true, email: true}))+actions = Buttons([signUpBtn, learnMoreBtn], "row")+signUpBtn = Button("Sign up", @ToAssistant("Sign me up"), "primary")+learnMoreBtn = Button("Learn more", @ToAssistant("Tell me more about the platform"), "secondary")`;diff --git a/docs/components/overview-components/overview-page.tsx b/docs/components/overview-components/overview-page.tsxindex 9015f2402..417690dab 100644--- a/docs/components/overview-components/overview-page.tsx+++ b/docs/components/overview-components/overview-page.tsx@@ -120,7 +120,7 @@ export function OverviewPage() {className="h-full"title="Component Library Definition"code={`import { defineComponent, createLibrary } from '@openuidev/react-lang';-import { z } from 'zod';+import { z } from 'zod/v4';const MyCard = defineComponent({name: 'MyCard',@@ -195,8 +195,8 @@ export function AssistantMessage({ content, isStreaming }) {</div><p className="mb-4 text-sm text-slate-600 sm:mb-6 sm:text-base dark:text-slate-400">- Drop in <code>AgentInterface</code> — a production-ready artifact chat surface with thread- history, conversation starters, and streaming — or build custom UIs with headless hooks.+ Drop in <code>AgentInterface</code>, a production-ready artifact chat surface with thread+ history, conversation starters, and streaming, or build custom UIs with headless hooks.Fully themeable and accessible out of the box.</p>@@ -324,7 +324,7 @@ const llm = {title="Quick example"code={`import { createLibrary, defineComponent } from '@openuidev/react-lang';import { openuiLibrary } from '@openuidev/react-ui';-import { z } from 'zod';+import { z } from 'zod/v4';// Generate prompt with CLI: openui generate ./src/library.tsdiff --git a/docs/content/blog/oui-1.mdx b/docs/content/blog/oui-1.mdxindex 55b59fd42..96706fa90 100644--- a/docs/content/blog/oui-1.mdx+++ b/docs/content/blog/oui-1.mdx@@ -110,7 +110,7 @@ OUI-1 did more than bring us back to where we began. AppLess had relied on GemmaThree directions matter from here:- **Personal devices.** Run models like OUI-1 closer to the person, keeping more of their context on the device.-- **[OpenUI Lang 0.5](/docs/openui-lang/specification-v05).** Generate interfaces with their own state, queries and mutations, so the runtime—not the model—handles each interaction.+- **[OpenUI Lang 0.5](/docs/openui-lang/specification/v0.5).** Generate interfaces with their own state, queries and mutations, so the runtime handles each interaction, not the model.- **Lower latency.** Move toward reliable, locally generated interfaces that arrive in under a second.## Referencesdiff --git a/docs/content/docs/agent/reference/adapters-and-formats.mdx b/docs/content/docs/agent/reference/adapters-and-formats.mdxindex 67de8fae8..b70cfc6ed 100644--- a/docs/content/docs/agent/reference/adapters-and-formats.mdx+++ b/docs/content/docs/agent/reference/adapters-and-formats.mdx@@ -383,7 +383,7 @@ Wrapping Anthropic, or any provider with no bundled adapter? You have two paths:### `agUIAdapter````ts-import { agUIAdapter } from "@openuidev/react-ui";+import { agUIAdapter, fetchLLM } from "@openuidev/react-ui";const llm = fetchLLM({ url: "/api/chat", streamAdapter: agUIAdapter() });```@@ -394,7 +394,7 @@ const llm = fetchLLM({ url: "/api/chat", streamAdapter: agUIAdapter() });### `openAIAdapter````ts-import { openAIAdapter } from "@openuidev/react-ui";+import { fetchLLM, openAIAdapter, openAIMessageFormat } from "@openuidev/react-ui";const llm = fetchLLM({url: "/api/chat",@@ -410,7 +410,7 @@ const llm = fetchLLM({### `openAIReadableStreamAdapter````ts-import { openAIReadableStreamAdapter } from "@openuidev/react-ui";+import { fetchLLM, openAIMessageFormat, openAIReadableStreamAdapter } from "@openuidev/react-ui";const llm = fetchLLM({url: "/api/chat",@@ -431,7 +431,11 @@ const llm = fetchLLM({### `openAIResponsesAdapter````ts-import { openAIResponsesAdapter } from "@openuidev/react-ui";+import {+ fetchLLM,+ openAIConversationMessageFormat,+ openAIResponsesAdapter,+} from "@openuidev/react-ui";const llm = fetchLLM({url: "/api/chat",@@ -603,10 +607,7 @@ import { langGraphMessageFormat } from "@openuidev/react-ui";## Related<Cards>- <Card- title="AgentInterface props"- href="/docs/agent/reference/agentinterface-props"- >+ <Card title="AgentInterface props" href="/docs/agent/reference/agentinterface-props">Where llm and storage are passed.</Card><Card title="Conversations" href="/docs/agent/core-concepts/conversations">diff --git a/docs/content/docs/agent/reference/agentinterface-props.mdx b/docs/content/docs/agent/reference/agentinterface-props.mdxindex 8fb0a9a08..1c7adca5a 100644--- a/docs/content/docs/agent/reference/agentinterface-props.mdx+++ b/docs/content/docs/agent/reference/agentinterface-props.mdx@@ -1,32 +1,37 @@---title: "<AgentInterface> props"-description: Complete prop reference for AgentInterfaceProps — adapters, rendering, theme, branding, starters, routing, and children.+description: Every prop of AgentInterface, grouped by area (adapters, rendering, theme, branding, starters, routing, scrolling, and children).----`AgentInterface` from `@openuidev/react-ui` is the only chat component you mount. It owns the full layout — sidebar, thread list, composer, routing, and the workspace rail — and you configure all of it through `AgentInterfaceProps`. This page is the complete prop reference, grouped by what each prop controls, with links to the relevant concept and how-to pages for each area.+`AgentInterface` from `@openuidev/react-ui` is the only chat component you mount. It owns the layout: sidebar, thread list, composer, routing, and the workspace rail. You configure all of it through `AgentInterfaceProps`. This page lists every prop, grouped by what it controls.The only required prop is `llm`. Everything else is optional and falls back to a sensible default.## At a glance-| Prop | Type | Required | Default |-| ---------------------- | -------------------------------------------- | -------- | ------------------------------ |-| `llm` | `ChatLLM` | **Yes** | — |-| `storage` | `ChatStorage` | No | internal in-memory (ephemeral) |-| `artifactRenderers` | `ReadonlyArray<ArtifactRendererConfig<any>>` | No | none |-| `artifactCategories` | `ArtifactCategory[]` | No | none (single "Artifacts" item) |-| `componentLibrary` | `Library` | No | none (markdown rendering) |-| `components` | `AgentInterfaceComponents` | No | none |-| `theme` | `ThemeProps` | No | built-in theme |-| `disableThemeProvider` | `boolean` | No | `false` |-| `logoUrl` | `string` | No | none |-| `agentName` | `string` | No | none |-| `starters` | `ConversationStarterProps[]` | No | none |-| `starterVariant` | `"short" \| "long" \| "card"` | No | — |-| `path` | `string` | No | — (uncontrolled) |-| `defaultPath` | `string` | No | thread view (`undefined`) |-| `onNavigate` | `(next: string \| undefined) => void` | No | — (uncontrolled) |-| `children` | `ReactNode` | No | none |+| Prop | Type | Required | Default |+| ---------------------- | --------------------------------------------- | -------- | ------------------------------ |+| `llm` | `ChatLLM` | **Yes** | none |+| `storage` | `ChatStorage` | No | internal in-memory (ephemeral) |+| `artifactRenderers` | `ReadonlyArray<ArtifactRendererConfig<any>>` | No | none |+| `artifactCategories` | `ArtifactCategory[]` | No | none (single "Artifacts" item) |+| `artifactAutoOpen` | `boolean` | No | `true` |+| `componentLibrary` | `Library` | No | none (markdown rendering) |+| `onAction` | `(event: ActionEvent) => void` | No | none |+| `components` | `AgentInterfaceComponents` | No | none |+| `theme` | `ThemeProps` | No | built-in theme |+| `disableThemeProvider` | `boolean` | No | `false` |+| `logoUrl` | `string` | No | none |+| `agentName` | `string` | No | none |+| `labels` | `AgentInterfaceLabels` | No | built-in labels |+| `starters` | `ConversationStarterProps[]` | No | none |+| `starterVariant` | `"short" \| "long" \| "card"` | No | none |+| `path` | `string` | No | none (uncontrolled) |+| `defaultPath` | `string` | No | thread view (`undefined`) |+| `onNavigate` | `(next: string \| undefined) => void` | No | none (uncontrolled) |+| `scrollVariant` | `"always" \| "once" \| "user-message-anchor"` | No | `"user-message-anchor"` |+| `scrollOnLoad` | `boolean` | No | `true` |+| `children` | `ReactNode` | No | none |The rest of this page explains each group.@@ -36,12 +41,12 @@ These two props connect `AgentInterface` to your backend. They are independent c| Prop | Type | Required | Default | Description || --------- | ------------- | -------- | ------------------------------ | ----------------------------------------------------- |-| `llm` | `ChatLLM` | **Yes** | — | Sends messages to your backend and streams the reply. |+| `llm` | `ChatLLM` | **Yes** | none | Sends messages to your backend and streams the reply. || `storage` | `ChatStorage` | No | internal in-memory (ephemeral) | Persists thread history (and, optionally, artifacts). |-`llm` is a `ChatLLM` — usually built with `fetchLLM()`, which POSTs `{ threadId, messages }` to your route and parses the streamed response. See [Conversations](/docs/agent/core-concepts/conversations) for the model, and the [Adapters & formats reference](/docs/agent/reference/adapters-and-formats) for the full `ChatLLM` / `fetchLLM()` surface and the stream adapters that parse each provider's stream.+`llm` is a `ChatLLM`, usually built with `fetchLLM()`. `fetchLLM()` POSTs `{ threadId, messages }` to your route and parses the streamed response. See [Conversations](/docs/agent/core-concepts/conversations) for the model, and the [Adapters & formats reference](/docs/agent/reference/adapters-and-formats) for the full `ChatLLM` / `fetchLLM()` surface and the stream adapters that parse each provider's stream.-`storage` is a `ChatStorage` — `{ thread: ThreadStorage; artifact?: ArtifactStorage }`. Omit it and conversations live only in memory: a page refresh clears everything. Build one with `restStorage()`, or implement the interfaces yourself. The full adapter interfaces (`ChatLLM`, `ChatStorage`, `ThreadStorage`, `ArtifactStorage`, `fetchLLM`, `restStorage`) are in the [Adapters & formats reference](/docs/agent/reference/adapters-and-formats).+`storage` is a `ChatStorage`: `{ thread: ThreadStorage; artifact?: ArtifactStorage }`. Omit it and conversations live only in memory: a page refresh clears everything. Build one with `restStorage()`, or implement the interfaces yourself. The full adapter interfaces (`ChatLLM`, `ChatStorage`, `ThreadStorage`, `ArtifactStorage`, `fetchLLM`, `restStorage`) are in the [Adapters & formats reference](/docs/agent/reference/adapters-and-formats).<Callout type="info">The provider API call always happens on your server. `fetchLLM()` only ever talks to your own@@ -50,13 +55,15 @@ These two props connect `AgentInterface` to your backend. They are independent c## Rendering-These props control how the assistant's output is rendered — both durable artifacts such as dashboards and apps, and the inline message body.+These props control how the assistant's output renders: artifacts such as dashboards and apps, and the message body.| Prop | Type | Required | Default | Description || -------------------- | -------------------------------------------- | -------- | ------- | ------------------------------------------------------------------------------------- || `artifactRenderers` | `ReadonlyArray<ArtifactRendererConfig<any>>` | No | none | Renderers that display artifacts (from a tool call or from stored content). || `artifactCategories` | `ArtifactCategory[]` | No | none | User-defined groupings for the artifact browser and workspace rail. |-| `componentLibrary` | `Library` | No | none | Turns on Generative UI — rich interactive components rendered inline in chat. |+| `artifactAutoOpen` | `boolean` | No | `true` | Opens a new artifact in the workspace panel while it streams. At most one per reply. |+| `componentLibrary` | `Library` | No | none | Turns on Generative UI: components rendered inline in chat. |+| `onAction` | `(event: ActionEvent) => void` | No | none | Receives the Generative UI actions the chat does not handle, such as custom actions. || `components` | `AgentInterfaceComponents` | No | none | Replace assistant answers, user messages, and the turn's tool timeline independently. |### `artifactRenderers`@@ -79,7 +86,7 @@ const codeArtifact = defineArtifactRenderer({### `artifactCategories`-Categories are **user-defined organization** for the artifact browser — they are orthogonal to whether an artifact is static or live. Each is `{ name: string; filter: { type: string[] } }`. Without categories, the sidebar shows a single "Artifacts" item; with them, one item per category.+Categories group artifacts in the artifact browser. They do not depend on whether an artifact is static or live. Each is `{ name: string; filter: { type: string[] } }`. Without categories, the sidebar shows a single "Artifacts" item; with them, one item per category.```tsx<AgentInterface@@ -103,9 +110,27 @@ import { openuiLibrary } from "@openuidev/react-ui/genui-lib";<AgentInterface llm={llm} componentLibrary={openuiLibrary} />;```+### `onAction`++`AgentInterface` handles two actions of Generative UI components itself: `@ToAssistant` sends a new user message and `@OpenUrl` opens the link in a new tab. Those never reach `onAction`. `onAction` receives the other actions, such as the [custom actions](/docs/openui-lang/actions#custom-actions) your `componentLibrary` defines.++```tsx+<AgentInterface+ llm={llm}+ componentLibrary={library}+ onAction={(event) => {+ if (event.type === "CopyToClipboard") {+ void navigator.clipboard.writeText(String(event.params.text));+ }+ }}+/>+```++`onAction` is only called for messages that `AgentInterface` renders from `componentLibrary`. When you pass `components.AssistantMessage`, it is not called. Pass `onAction` to the `Renderer` in your component instead.+### `components`-Override the message components directly: `{ AssistantMessage?, ToolCallTimeline?, UserMessage? }`. Message rendering precedence is **`components` > `componentLibrary` > built-in default** — an explicit `components` entry always wins. See [Message rendering](/docs/agent/customize/message-rendering).+Override the message components directly: `{ AssistantMessage?, ToolCallTimeline?, UserMessage? }`. Message rendering precedence is **`components` > `componentLibrary` > built-in default**, so an explicit `components` entry always wins. See [Message rendering](/docs/agent/customize/message-rendering).## Theme@@ -118,10 +143,11 @@ Set `disableThemeProvider` to `true` when `AgentInterface` is mounted inside an## Branding-| Prop | Type | Required | Default | Description |-| ----------- | -------- | -------- | ------- | ------------------------------------------------------- |-| `logoUrl` | `string` | No | none | Logo shown in the sidebar header and the mobile header. |-| `agentName` | `string` | No | none | Agent name shown next to the logo. |+| Prop | Type | Required | Default | Description |+| ----------- | ---------------------- | -------- | --------------- | --------------------------------------------------------------------------------------------- |+| `logoUrl` | `string` | No | none | Logo shown in the sidebar header and the mobile header. |+| `agentName` | `string` | No | none | Agent name shown next to the logo. |+| `labels` | `AgentInterfaceLabels` | No | built-in labels | Text for the artifact browser and workspace: `{ defaultCategory?, workspaceToggle?, tabs? }`. |These feed the default `SidebarHeader` and `MobileHeader`. To go further, replace those slots. See [Sidebar](/docs/agent/customize/sidebar).@@ -132,9 +158,9 @@ Conversation starters are the suggested prompts shown on the welcome screen and| Prop | Type | Required | Default | Description || ---------------- | ----------------------------- | -------- | ------- | ---------------------------------------------- || `starters` | `ConversationStarterProps[]` | No | none | Suggested prompts to seed a conversation. |-| `starterVariant` | `"short" \| "long" \| "card"` | No | — | Layout variant for how starters are presented. |+| `starterVariant` | `"short" \| "long" \| "card"` | No | none | Layout variant for how starters are presented. |-Each starter is `{ displayText: string; prompt: string; icon?: ReactNode }` — `displayText` is the label on the suggestion chip and `prompt` is the message sent when it is clicked. These props set the defaults for the `Welcome` and `Composer` slots; either slot can also take its own `starters` / `starterVariant`. See [Welcome & starters](/docs/agent/customize/welcome-and-starters).+Each starter is `{ displayText: string; prompt: string; icon?: ReactNode }`. `displayText` is the label on the suggestion chip and `prompt` is the message sent when it is clicked. These props set the defaults for the `Welcome` and `Composer` slots; either slot can also take its own `starters` / `starterVariant`. See [Welcome & starters](/docs/agent/customize/welcome-and-starters).## Routing@@ -142,11 +168,11 @@ Each starter is `{ displayText: string; prompt: string; icon?: ReactNode }` —| Prop | Type | Required | Default | Description || ------------- | ------------------------------------- | -------- | ------------------------- | -------------------------------------------------------------- |-| `path` | `string` | No | — (uncontrolled) | Controlled current route. |+| `path` | `string` | No | none (uncontrolled) | Controlled current route. || `defaultPath` | `string` | No | thread view (`undefined`) | Uncontrolled initial route. |-| `onNavigate` | `(next: string \| undefined) => void` | No | — (uncontrolled) | Navigation callback; **its presence selects controlled mode**. |+| `onNavigate` | `(next: string \| undefined) => void` | No | none (uncontrolled) | Navigation callback; **its presence selects controlled mode**. |-Controlled mode is chosen by the **presence of `onNavigate`**, not by `path !== undefined` — because `undefined` is a meaningful path (the thread view). In controlled mode, drive `path` from your own router and update it inside `onNavigate`. In uncontrolled mode, set an initial route with `defaultPath` and let the component manage navigation internally.+Controlled mode is chosen by the **presence of `onNavigate`**, not by `path !== undefined`, because `undefined` is a valid path (the thread view). In controlled mode, drive `path` from your own router and update it inside `onNavigate`. In uncontrolled mode, set an initial route with `defaultPath` and let the component manage navigation internally.Controlled consumers must round-trip the reserved artifact-browser paths (`artifacts/{category}` and `artifacts/{category}/{id}`), which are matched before your own `AgentInterface.Route` entries. Read the current route and navigate from anywhere inside the component with the `useNav()` hook (from `@openuidev/react-ui`).@@ -158,13 +184,20 @@ Controlled consumers must round-trip the reserved artifact-browser paths (`artif<AgentInterface llm={llm} path={path} onNavigate={setPath} />;```+## Scrolling++| Prop | Type | Required | Default | Description |+| --------------- | --------------------------------------------- | -------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `scrollVariant` | `"always" \| "once" \| "user-message-anchor"` | No | `"user-message-anchor"` | `"user-message-anchor"` pins the latest user message to the top. `"always"` follows the reply to the bottom until the user scrolls up. `"once"` scrolls to the bottom once when a message is added. |+| `scrollOnLoad` | `boolean` | No | `true` | Scroll to the latest message when a thread loads or the user switches threads. |+## Children| Prop | Type | Required | Default | Description || ---------- | ----------- | -------- | ------- | -------------------------------------------- || `children` | `ReactNode` | No | none | Slots, primitives, Routes, and free content. |-`children` is where composition happens. Pass the compound statics on `AgentInterface` — slots (`AgentInterface.Sidebar`, `.Welcome`, `.Composer`, `.Workspace`, …), primitives (`AgentInterface.SidebarItem`, `.ThreadList`, `.Messages`, …), and `AgentInterface.Route` for multi-page content. Slots not provided fall back to their built-in defaults. See the [Components reference](/docs/agent/reference/components).+`children` is where composition happens. Pass the compound statics on `AgentInterface`: slots (`AgentInterface.Sidebar`, `.Welcome`, `.Composer`, `.Workspace`, and so on), primitives (`AgentInterface.SidebarItem`, `.ThreadList`, `.Messages`, and so on), and `AgentInterface.Route` for multi-page content. Slots not provided fall back to their built-in defaults. See the [Components reference](/docs/agent/reference/components).```tsx<AgentInterface llm={llm}>@@ -180,7 +213,7 @@ Controlled consumers must round-trip the reserved artifact-browser paths (`artif## Related references-- [Adapters & formats](/docs/agent/reference/adapters-and-formats) — `ChatLLM`, `ChatStorage`, `ThreadStorage`, `ArtifactStorage`, `fetchLLM`, `restStorage`, the stream adapters, and the message formats used to build `llm` and `storage`.-- [`defineArtifactRenderer`](/docs/agent/reference/define-artifact-renderer) — the shape of each `artifactRenderers` entry.-- [Hooks](/docs/agent/reference/hooks) — `useNav`, `useThread`, `useArtifactStorage`, and the rest.-- [Components](/docs/agent/reference/components) — the slots and primitives you pass as `children`.+- [Adapters & formats](/docs/agent/reference/adapters-and-formats): `ChatLLM`, `ChatStorage`, `ThreadStorage`, `ArtifactStorage`, `fetchLLM`, `restStorage`, the stream adapters, and the message formats used to build `llm` and `storage`.+- [`defineArtifactRenderer`](/docs/agent/reference/define-artifact-renderer): the shape of each `artifactRenderers` entry.+- [Hooks](/docs/agent/reference/hooks): `useNav`, `useThread`, `useArtifactStorage`, and the rest.+- [Components](/docs/agent/reference/components): the slots and primitives you pass as `children`.diff --git a/docs/content/docs/api-reference/angular-lang.mdx b/docs/content/docs/api-reference/angular-lang.mdxindex a253d6d47..b28158be8 100644--- a/docs/content/docs/api-reference/angular-lang.mdx+++ b/docs/content/docs/api-reference/angular-lang.mdx@@ -13,7 +13,14 @@ For a runnable chat integration with NG-ZORRO X, see the [Angular example](httpsnpm install @openuidev/angular-lang zod rxjs```-Version `0.3.0` requires `@angular/core` and `@angular/common` `^22.1.5`, RxJS `^7.8.2`, and Zod `^3.25.0 || ^4.0.0`. Use the `zod/v4` API when defining schemas. Your Angular application supplies its normal compiler and build tooling; the renderer does not require `zone.js` or `@angular/platform-browser-dynamic`.+Version `0.4.1` requires `@angular/core` and `@angular/common` `^22.1.5`, RxJS `^7.8.2`, and Zod `^3.25.0 || ^4.0.0`. Use the `zod/v4` API when defining schemas. Your Angular application supplies its normal compiler and build tooling; the renderer does not require `zone.js` or `@angular/platform-browser-dynamic`.++<Callout type="info">+ This renderer is on 0.4. Keep `@openuidev/lang-core` at `^0.4` with it. The OpenUI Lang 1.0+ features (single-step actions, custom functions, custom actions) need the [React+ renderer](/docs/api-reference/react-lang) for now. See [What's New in+ 1.0](/docs/openui-lang/whats-new#vue-svelte-and-angular).+</Callout>## Define a librarydiff --git a/docs/content/docs/api-reference/react-lang.mdx b/docs/content/docs/api-reference/react-lang.mdxindex 2f3552285..d35a718a9 100644--- a/docs/content/docs/api-reference/react-lang.mdx+++ b/docs/content/docs/api-reference/react-lang.mdx@@ -10,9 +10,15 @@ Use this package for OpenUI Lang authoring and rendering.```tsimport {defineComponent,+ defineFunction,+ defineAction,+ action,+ steps,createLibrary,Renderer,BuiltinActionType,+ buildMessage,+ parseMessage,createParser,createStreamingParser,} from "@openuidev/react-lang";@@ -47,7 +53,8 @@ interface DefinedComponent<T extends z.ZodObject<any> = z.ZodObject<any>> {Creates a `Library` from an array of defined components.```ts-function createLibrary(input: LibraryDefinition): Library;+/** The result has functions, actions, and extend set (Required<Library>). */+function createLibrary(input: LibraryDefinition): Required<Library>;```Core types:@@ -56,7 +63,13 @@ Core types:interface LibraryDefinition {components: DefinedComponent[];componentGroups?: ComponentGroup[];+ /** Custom functions, called as `@Name(...)` in programs. */+ functions?: DefinedFunction[];+ /** Custom action steps, used as `@Name(...)` in action props. */+ actions?: DefinedAction[];root?: string;+ /** Optional public id. `toSpec()` includes it. */+ id?: string;}interface ComponentGroup {@@ -68,11 +81,18 @@ interface ComponentGroup {interface Library {readonly components: Record<string, DefinedComponent>;readonly componentGroups: ComponentGroup[] | undefined;+ /** Optional, so a hand-built Library object still type-checks. createLibrary always sets it. */+ readonly functions?: Record<string, DefinedFunction>;+ /** Optional, like functions. */+ readonly actions?: Record<string, DefinedAction>;readonly root: string | undefined;+ readonly id: string | undefined;prompt(options?: PromptOptions): string;- toJSONSchema(): object;+ toJSONSchema(): LibraryJSONSchema;toSpec(): PromptSpec;+ /** Derive a new library. Optional, like functions. */+ extend?(extension: LibraryExtension): Required<Library>;}interface PromptOptions {@@ -86,26 +106,131 @@ interface PromptOptions {toolCalls?: boolean;/** Enable $variables, @Set, @Reset, built-in functions. Default: true if toolCalls. */bindings?: boolean;+ /** List the built-in functions (@Count, @Sum, ...). Default: true if toolCalls or bindings. */+ builtinFunctions?: boolean;}```+`createLibrary` throws when a function or action name is a built-in name, `Action`, `Query`, `Mutation`, or the name of a component, function, or action in the same library.++## `defineFunction(config)`++Defines a custom function, called as `@Name(...)` in programs. See [Functions](/docs/openui-lang/functions#custom-functions).++```ts+function defineFunction<+ T extends z.ZodObject,+ R extends z.ZodType | undefined = undefined,+>(config: {+ name: string;+ description: string;+ /** Key order is the positional order of the arguments. */+ params: T;+ /** Printed in the prompt signature and checked at runtime. */+ returns?: R;+ /** Receives one object keyed by the params names, with defaults applied. */+ fn: (args: z.infer<T>) => R extends z.ZodType ? z.infer<R> : unknown;+}): DefinedFunction<T, R>;+```++A call with an invalid required argument, an `fn` that throws, or a result that does not match `returns` evaluates to `null`. An invalid optional argument falls back to its default.++## `defineAction(config)`++Defines a custom action step. The renderer does not run it: it calls `onAction` with `{ type: name, params }`. A step with any invalid argument is a no-op. See [Actions](/docs/openui-lang/actions#custom-actions).++```ts+function defineAction<const N extends string, T extends z.ZodObject>(config: {+ name: N;+ description: string;+ /** Key order is the positional order of the arguments. */+ params: T;+}): DefinedAction<T, N>;++interface DefinedAction<T, N> {+ name: N;+ description: string;+ params: T;+ /** For slots that take only some actions: `z.union([copy.ref, steps.OpenUrl.ref])` */+ ref: ActionRef;+}+```++## `action()` and `steps`++`action()` returns the schema for an action prop, tagged `ActionExpression`. In the JSON Schema the prop is `{"$ref": "#/$defs/ActionExpression"}`.++```ts+props: z.object({ label: z.string(), action: action().optional() });+```++`steps.OpenUrl.ref` and `steps.ToAssistant.ref` name built-in steps in a restricted slot, together with the `.ref` of custom actions. Restricted slots shape the prompt and the JSON Schema only; the runtime accepts any step. See [Actions](/docs/openui-lang/actions#slots-that-take-only-some-actions).++## `library.extend(extension)`++Returns a new library with the additions. The base library is unchanged. See [Extending a library](/docs/openui-lang/defining-components#extending-a-library).++```ts+interface LibraryExtension {+ components?: {+ /** With slots ("Parent.prop", or "Parent" when it has one content slot), it joins those unions. */+ add?: (DefinedComponent | { component: DefinedComponent; slots: string[] })[];+ /** Replaces the component of the same name. Every parent points at the new one. */+ override?: DefinedComponent[];+ /** Drops it from the library, every parent union, and componentGroups. */+ remove?: string[];+ };+ functions?: { add?: DefinedFunction[] };+ actions?: { add?: DefinedAction[] };+}+```++`extend` throws when an added name exists, an overridden or removed name does not, a removal is the root or the only type of a slot, or a slot does not resolve to one content slot. The derived library has no `id`. Create it once at module scope, since parsers are cached per library object.++## `buildMessage(input)` and `parseMessage(raw, options?)`++Write and read a stored message with `]]>openui:` marker lines. See [Message Protocol](/docs/openui-lang/message-protocol).++```ts+function buildMessage(input: {+ content: string;+ /** A string is written as is, anything else as JSON. Omitted when null or undefined. */+ context?: unknown;+ attributes?: Record<string, string>;+ end?: boolean;+}): string;++function parseMessage(+ raw: string,+ options?: {+ /** Hold back a last line that may be a marker cut mid-stream. */ streaming?: boolean;+ },+): {+ content: string;+ /** Parsed JSON, else raw text. null when absent. */+ context: unknown;+ attributes: Record<string, string>;+ end: boolean;+};+```+## `<Renderer />`Parses OpenUI Lang text and renders nodes with your `Library`.```ts-interface RendererProps {+interface RendererProps<L extends Library = Library> {+ /** OpenUI Lang text, or a stored message with ]]>openui: marker lines. */response: string | null;- library: Library;+ library: L;isStreaming?: boolean;- onAction?: (event: ActionEvent) => void;+ /** Typed from the library: checking event.type narrows params for custom actions. */+ onAction?: (event: LibraryActionEvent<L>) => void;onStateUpdate?: (state: Record<string, unknown>) => void;initialState?: Record<string, any>;onParseResult?: (result: ParseResult | null) => void;toolProvider?:- | Record<string, (args: Record<string, unknown>) => Promise<unknown>>- | McpClientLike- | null;+ Record<string, (args: Record<string, unknown>) => Promise<unknown>> | McpClientLike | null;/** Custom loading indicator. Defaults to a spinner. */queryLoader?: React.ReactNode;children?: React.ReactNode;@@ -117,12 +242,12 @@ interface RendererProps {`Renderer` keeps query defaults or cached results visible while loading and after failures, and reports errors through `onError`. A spinner is shown while queries load; provide `queryLoader` to customize it. No error/retry view is shown by default. To customize loading feedback and opt into an error/retry presentation, use `Renderer.Root` with these slots:-| Slot | Purpose |-| --- | --- |-| `Renderer.Content` | Generated UI; accepts div props and stays mounted during query failures. |+| Slot | Purpose |+| ----------------------- | ------------------------------------------------------------------------------------------------------ |+| `Renderer.Content` | Generated UI; accepts div props and stays mounted during query failures. || `Renderer.QueryLoading` | Children shown while queries wait or fetch; omitted children use `queryLoader` or the default spinner. |-| `Renderer.QueryError` | Children shown when queries fail; renders nothing without children. |-| `Renderer.Retry` | A retry button; accepts standard button props. |+| `Renderer.QueryError` | Children shown when queries fail; renders nothing without children. |+| `Renderer.Retry` | A retry button; accepts standard button props. |Root accepts the same runtime props as Renderer and renders only its children. Put overlays in your own positioned container. Slots share context through wrappers and React portals. `useRendererQuery()` returns `{ isLoading, errors, retry, isRetrying }` within that root. `Renderer.Content` renders defaults or cached data while queries load and hides content on failure while preserving mounted state through retries.@@ -145,8 +270,8 @@ Root accepts the same runtime props as Renderer and renders only its children. PHandles `Query()` and `Mutation()` tool calls at runtime. The `toolProvider` prop accepts two forms:-- **Function map** — `Record<string, (args) => Promise<unknown>>` — the simplest option-- **MCP client** — any object implementing `callTool({ name, arguments })` (e.g. from `@modelcontextprotocol/sdk`)+- **Function map**: `Record<string, (args) => Promise<unknown>>`. The simplest option.+- **MCP client**: any object implementing `callTool({ name, arguments })` (e.g. from `@modelcontextprotocol/sdk`)The Renderer detects which form was passed and normalizes internally.@@ -162,7 +287,11 @@ interface OpenUIError {statementId?: string;component?: string;path?: string;+ /** Tool name for query and mutation errors. */+ toolName?: string;hint?: string;+ /** "warning" when the page still rendered; absent means error. */+ severity?: "warning";}class ToolNotFoundError extends Error {@@ -171,7 +300,7 @@ class ToolNotFoundError extends Error {}```-Error codes: `unknown-component`, `missing-required`, `null-required`, `inline-reserved`, `tool-not-found`, `parse-failed`, `parse-exception`, `runtime-error`, `render-error`.+Error codes: `unknown-component`, `missing-required`, `null-required`, `type-mismatch`, `excess-args`, `inline-reserved`, `unknown-function`, `no-root`, `tool-not-found`, `tool-error`, `mcp-error`, `parse-failed`, `parse-exception`, `runtime-error`, `render-error`.## Actions@@ -195,19 +324,23 @@ Action steps (runtime types from the evaluator):```tstype ActionStep =| { type: "run"; statementId: string; refType: "query" | "mutation" }- | { type: "continue_conversation"; message: string; context?: string }+ | { type: "continue_conversation"; message: string; context?: unknown }| { type: "open_url"; url: string }| { type: "set"; target: string; valueAST: ASTNode }- | { type: "reset"; targets: string[] };+ | { type: "reset"; targets: string[] }+ | { type: "custom_action"; name: string; params: Record<string, unknown> };```+Every step call evaluates to a plan, `{ steps: ActionStep[] }`. A step that cannot run gives a plan with no steps.+| Step type | Triggered by | Description || ------------------------- | --------------------- | ------------------------------------------------------------------ || `"run"` | `@Run(ref)` | Execute a Mutation or re-fetch a Query. `refType` indicates which. || `"set"` | `@Set($var, val)` | Change a `$variable`. `valueAST` is evaluated at click time. || `"reset"` | `@Reset($a, $b)` | Restore `$variables` to declared defaults. |-| `"continue_conversation"` | `@ToAssistant("msg")` | Send message to LLM. Optional `context`. |+| `"continue_conversation"` | `@ToAssistant("msg")` | Send message to LLM. Optional `context` of any type. || `"open_url"` | `@OpenUrl("url")` | Open URL in new tab. |+| `"custom_action"` | `@Name(...)` | A custom action. Reaches `onAction` as `{ type: name, params }`. |## Parser APIs@@ -224,19 +357,28 @@ interface LibraryJSONSchema {>;}-function createParser(schema: LibraryJSONSchema): Parser;-function createStreamingParser(schema: LibraryJSONSchema): StreamParser;+function createParser(schema: LibraryJSONSchema, rootName?: string): Parser;+function createStreamingParser(schema: LibraryJSONSchema, rootName?: string): StreamParser;interface Parser {parse(input: string): ParseResult;}interface StreamParser {- push(chunk: string): ParseResult;- getResult(): ParseResult;+ /** Pass complete once the stream has ended. */+ push(chunk: string, complete?: boolean): ParseResult;+ /** Set the full text so far. Only the new part is parsed. */+ set(fullText: string, complete?: boolean): ParseResult;+ getResult(complete?: boolean): ParseResult;}```+Pass the root component name as `rootName`, usually `library.root`. A program without a `root` statement then falls back to the first statement that calls that component. Without `rootName`, such a program reports `no-root` and has no root.++```ts+const parser = createParser(library.toJSONSchema(), library.root);+```+Core parsed types:```ts@@ -254,7 +396,11 @@ type ValidationErrorCode =| "missing-required"| "null-required"| "unknown-component"- | "inline-reserved";+ | "inline-reserved"+ | "excess-args"+ | "type-mismatch"+ | "unknown-function"+ | "no-root";interface ValidationError {code: ValidationErrorCode;@@ -262,15 +408,19 @@ interface ValidationError {path: string;message: string;statementId?: string;+ /** "warning" when the program still renders, e.g. a no-root fallback entry. */+ severity?: "warning";}interface ParseResult {root: ElementNode | null;+ /** Set when the entry picks a component at runtime (`root = $t ? A : B`). */+ rootExpression?: ASTNode;meta: {incomplete: boolean;/** References used but not yet defined (dropped as null in output). */unresolved: string[];- /** Value statements defined but not reachable from root. Excludes $state, Query, and Mutation. */+ /** Value statements defined but not reachable from the entry. Excludes $state, Query, and Mutation. Empty when there is no entry. */orphaned: string[];statementCount: number;/**@@ -308,8 +458,9 @@ function useRenderNode(): (value: unknown) => React.ReactNode;function useTriggerAction(): (userMessage: string,formName?: string,- action?: { type?: string; params?: Record<string, any> },-) => void;+ /** An evaluated action prop (ActionPlan), or a legacy { type, params } object. */+ action?: ActionPlan | { type?: string; params?: Record<string, any> },+) => void | Promise<void>;function useIsStreaming(): boolean;function useIsQueryLoading(): boolean;function useGetFieldValue(): (formName: string | undefined, name: string) => any;@@ -323,7 +474,7 @@ function useSetFieldValue(): (function useFormName(): string | undefined;function useSetDefaultValue(options: {formName?: string;- componentType: string;+ componentType?: string;name: string;existingValue: any;defaultValue: any;@@ -336,6 +487,7 @@ function useSetDefaultValue(options: {```tsinterface FormValidationContextValue {errors: Record<string, string | undefined>;+ getFieldError: (name: string) => string | undefined;validateField: (name: string, value: unknown, rules: ParsedRule[]) => boolean;registerField: (name: string, rules: ParsedRule[], getValue: () => unknown) => void;unregisterField: (name: string) => void;diff --git a/docs/content/docs/api-reference/react-ui.mdx b/docs/content/docs/api-reference/react-ui.mdxindex ab0ca6d31..3d5977c0c 100644--- a/docs/content/docs/api-reference/react-ui.mdx+++ b/docs/content/docs/api-reference/react-ui.mdx@@ -62,14 +62,14 @@ The layered variant requires browser support for [CSS cascade layers](https://de### `AgentInterface````tsx-import { AgentInterface, openAIAdapter, type ChatLLM } from "@openuidev/react-ui";+import { AgentInterface, fetchLLM, openAIAdapter, openAIMessageFormat } from "@openuidev/react-ui";import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";-const llm: ChatLLM = {- send: ({ messages, signal }) =>- fetch("/api/chat", { method: "POST", body: JSON.stringify({ messages }), signal }),- streamProtocol: openAIAdapter(),-};+const llm = fetchLLM({+ url: "/api/chat",+ streamAdapter: openAIAdapter(),+ messageFormat: openAIMessageFormat,+});<AgentInterface llm={llm} componentLibrary={openuiChatLibrary} />;```@@ -83,9 +83,11 @@ const llm: ChatLLM = {- `llm: ChatLLM` — required; `{ send({ threadId, messages, signal }), streamProtocol }`- `artifactRenderers?: ArtifactRendererConfig[]`- `artifactCategories?: ArtifactCategory[]`+ - `artifactAutoOpen?: boolean`- Shared UI props:- `componentLibrary?: Library` (from `@openuidev/react-lang`) — drives auto-GenUI rendering- - `components?: AgentInterfaceComponents` — `{ AssistantMessage?, UserMessage? }` overrides+ - `onAction?: (event: ActionEvent) => void`: actions the chat does not handle, such as custom actions+ - `components?: AgentInterfaceComponents`: `{ AssistantMessage?, UserMessage?, ToolCallTimeline? }` overrides- `logoUrl?: string`- `agentName?: string`- `labels?: AgentInterfaceLabels`@@ -93,6 +95,7 @@ const llm: ChatLLM = {- `starterVariant?: ConversationStarterVariant`- `scrollVariant?: ScrollVariant`- `scrollOnLoad?: boolean`+ - `path?: string`, `defaultPath?: string`, `onNavigate?: (next: string | undefined) => void`- Theme wrapper props:- `theme?: ThemeProps`- `disableThemeProvider?: boolean`diff --git a/docs/content/docs/api-reference/svelte-lang.mdx b/docs/content/docs/api-reference/svelte-lang.mdxindex d4110f58c..b44ca34b0 100644--- a/docs/content/docs/api-reference/svelte-lang.mdx+++ b/docs/content/docs/api-reference/svelte-lang.mdx@@ -13,7 +13,14 @@ For a runnable SvelteKit chat integration with the Vercel AI SDK, see the [Sveltnpm install @openuidev/svelte-lang zod```-Version `0.3.0` requires Svelte `>=5.0.0` and Zod `^3.25.0 || ^4.0.0`. Use the `zod/v4` API when defining schemas.+Version `0.4.1` requires Svelte `>=5.0.0` and Zod `^3.25.0 || ^4.0.0`. Use the `zod/v4` API when defining schemas.++<Callout type="info">+ This renderer is on 0.4. Keep `@openuidev/lang-core` at `^0.4` with it. The OpenUI Lang 1.0+ features (single-step actions, custom functions, custom actions) need the [React+ renderer](/docs/api-reference/react-lang) for now. See [What's New in+ 1.0](/docs/openui-lang/whats-new#vue-svelte-and-angular).+</Callout><Callout type="info">The Svelte renderer covers component rendering, simple actions, and form state. It does not yetdiff --git a/docs/content/docs/api-reference/vue-lang.mdx b/docs/content/docs/api-reference/vue-lang.mdxindex 75c4c129f..e5e465521 100644--- a/docs/content/docs/api-reference/vue-lang.mdx+++ b/docs/content/docs/api-reference/vue-lang.mdx@@ -13,7 +13,14 @@ For a runnable Nuxt chat integration with the Vercel AI SDK, see the [Vue examplnpm install @openuidev/vue-lang zod```-Version `0.3.0` requires Vue `>=3.5.0` and Zod `^3.25.0 || ^4.0.0`. Use the `zod/v4` API when defining schemas.+Version `0.4.1` requires Vue `>=3.5.0` and Zod `^3.25.0 || ^4.0.0`. Use the `zod/v4` API when defining schemas.++<Callout type="info">+ This renderer is on 0.4. Keep `@openuidev/lang-core` at `^0.4` with it. The OpenUI Lang 1.0+ features (single-step actions, custom functions, custom actions) need the [React+ renderer](/docs/api-reference/react-lang) for now. See [What's New in+ 1.0](/docs/openui-lang/whats-new#vue-svelte-and-angular).+</Callout>## Define a librarydiff --git a/docs/content/docs/build-agents/tools.mdx b/docs/content/docs/build-agents/tools.mdxindex 15a611606..4c6713b61 100644--- a/docs/content/docs/build-agents/tools.mdx+++ b/docs/content/docs/build-agents/tools.mdx@@ -49,9 +49,9 @@ $priority = "high"$title = ""tickets = Query("list_tickets", {priority: $priority}, {rows: []})createTicket = Mutation("create_ticket", {title: $title, priority: $priority})-filter = Select("priority", $priority, [SelectItem("high", "High"), SelectItem("low", "Low")])+filter = Select("priority", [SelectItem("high", "High"), SelectItem("low", "Low")], null, null, $priority)addBtn = Button("Add", Action([@Run(createTicket), @Run(tickets), @Reset($title)]))-form = Form("create", addBtn, [FormControl("Title", Input("title", $title))])+form = Form("create", Buttons([addBtn]), [FormControl("Title", Input("title", "Ticket title", "text", null, $title))])tbl = Table([Col("Title", tickets.rows.title), Col("Priority", tickets.rows.priority)])root = Stack([CardHeader("Tickets"), filter, form, tbl])```diff --git a/docs/content/docs/openui-lang/actions.mdx b/docs/content/docs/openui-lang/actions.mdxnew file mode 100644index 000000000..3f4e852cd--- /dev/null+++ b/docs/content/docs/openui-lang/actions.mdx@@ -0,0 +1,335 @@+---+title: Actions+description: Write one action or several in Action([...]), define custom actions, and handle them in your app.+---++Actions decide what happens when the user clicks. The model writes the action into a component's action prop, such as a button's. On click the renderer runs it, or hands it to your app as an event.++For example, an order card has an "Approve" button. The model writes `Action([@Run(approveOrder), @Run(orders), @ToAssistant("Order approved")])`. On click, the renderer runs the mutation, refreshes the order list, and sends a message to the model, in that order.++Each `@ToAssistant`, `@OpenUrl`, `@Set`, `@Reset`, `@Run`, or custom `@Name` call in an action prop is an action. `Action([...])` holds several actions that run in order. The API and the generated prompt call these steps (`ActionStep`, `{ steps: [...] }`). What your `onAction` handler receives is an event.++## One action needs no wrapper++```text+askBtn = Button("Explain this chart", @ToAssistant("Explain the revenue chart"))+docsBtn = Button("Docs", @OpenUrl("https://example.com/docs"))+```++`@ToAssistant("...")` here is the same as `Action([@ToAssistant("...")])`.++## Several actions in order++Put several actions in `Action([...])`. They run in order:++```text+saveBtn = Button("Save", Action([@Run(createTicket), @Run(tickets), @Reset($title)]))+```++`Action([...])` can be its own statement and be used in several places:++```text+onSave = Action([@Run(createTicket), @Run(tickets), @Reset($title)])+saveBtn = Button("Save", onSave)+```++## Built-in actions++| Action | What it does |+| :-------------------------------- | :----------------------------------------------------------------------------------------------------------------- |+| `@ToAssistant(message, context?)` | Sends a `continue_conversation` event with the message. `context` can be any value and reaches the host unchanged. |+| `@OpenUrl(url)` | Sends an `open_url` event with `params.url`. |+| `@Set($var, value)` | Sets a `$variable`. `value` is evaluated when the action runs. |+| `@Reset($a, $b, ...)` | Restores `$variables` to their declared defaults. |+| `@Run(ref)` | Runs a `Mutation` or fetches a `Query` again. A failed mutation stops the actions after it. |+| `@Name(...)` | A [custom action](#custom-actions) from your library. Sends an event with `type: "Name"`. |++The renderer runs `@Set`, `@Reset`, and `@Run` itself. `@ToAssistant`, `@OpenUrl`, and custom actions reach your app as events.++### Context for `@ToAssistant`++The second argument of `@ToAssistant` is optional context: a string, number, object, or array. The host receives it unchanged in `event.params.context`:++```text+approveBtn = Button("Approve", @ToAssistant("Approve this order", {orderId: 42}))+```++```ts+{+ type: "continue_conversation",+ humanFriendlyMessage: "Approve this order",+ params: { context: { orderId: 42 } },+ formState: { /* ... */ },+ formName: undefined,+}+```++With no context, or `null`, `params` is `{}`. The host decides how the context reaches the model. The chat in `@openuidev/react-ui` adds it to the stored user turn, after the form state. See [Message Protocol](/docs/openui-lang/message-protocol#the-react-ui-chat-format).++## Custom actions++The built-in actions send messages, open links, change state, and run tools. A custom action is one your app defines, such as copying text, adding an item to a cart, or opening a panel in your app. The model uses it like a built-in action. The renderer does not run it. It sends an event to your `onAction` handler, and your code does the work.++### Define an action++This file, `message.tsx`, defines a button, a custom action, the library, and the message component that handles the event:++```tsx+"use client";++import {+ action,+ createLibrary,+ defineAction,+ defineComponent,+ Renderer,+ useTriggerAction,+} from "@openuidev/react-lang";+import { z } from "zod/v4";++// 1. A component with an action prop.+const Button = defineComponent({+ name: "Button",+ description: "A clickable button",+ props: z.object({+ label: z.string(),+ action: action().optional(),+ }),+ component: ({ props }) => {+ const triggerAction = useTriggerAction();+ return (+ <button onClick={() => triggerAction(props.label, undefined, props.action)}>+ {props.label}+ </button>+ );+ },+});++// 2. The custom action.+export const copyToClipboard = defineAction({+ name: "CopyToClipboard",+ description: "Copies text to the clipboard",+ params: z.object({+ text: z.string(),+ format: z.enum(["plain", "markdown"]).default("plain"),+ }),+});++// 3. The library the model writes against.+export const library = createLibrary({+ root: "Button",+ components: [Button],+ actions: [copyToClipboard],+});++// 4. Your app handles the event.+export function Message({ response }: { response: string }) {+ return (+ <Renderer+ library={library}+ response={response}+ onAction={(event) => {+ if (event.type === "CopyToClipboard") {+ void navigator.clipboard.writeText(event.params.text);+ }+ }}+ />+ );+}+```++The model can now write:++```text+root = Button("Copy order ID", @CopyToClipboard("ORD-1042"))+```++The user sees a "Copy order ID" button. On click, the renderer sends a `CopyToClipboard` event to `onAction`, and your handler copies "ORD-1042". The `Button` in `@openuidev/react-ui` takes an action prop the same way.++### Fields++| Field | Description |+| :------------ | :--------------------------------------------------------------------------- |+| `name` | The name after `@` in programs, and the `type` of the event `onAction` gets. |+| `description` | Shown next to the signature in the prompt. |+| `params` | A `z.object(...)`. Key order is the positional order of the arguments. |++`defineAction` returns the definition with a `.ref`, used for [slots that take only some actions](#slots-that-take-only-some-actions).++### Using it in a program++A custom action works anywhere a built-in action does: alone, or with other actions in `Action([...])`:++```text+copyBtn = Button("Copy", @CopyToClipboard(order.id))+copyAndClose = Button("Copy and close", Action([@CopyToClipboard(order.id), @Set($open, false)]))+```++Arguments are positional, in the key order of `params`, and defaults apply. `@CopyToClipboard("ORD-1042")` delivers `{ text: "ORD-1042", format: "plain" }`.++### The event++```ts+{+ type: "CopyToClipboard",+ params: { text: "ORD-1042", format: "plain" },+ humanFriendlyMessage: "",+ formState: { /* the form's field values */ },+ formName: undefined, // the enclosing form, if any+}+```++`formState` and `formName` work as they do for the built-in events. See [Interactivity](/docs/openui-lang/interactivity#actionevent).++## Handling actions in your app++### Action props in your components++Use `action()` for a prop that takes an action, as the `Button` in [Define an action](#define-an-action) does: `action: action().optional()`.++At runtime the prop holds an evaluated plan, `{ steps: [...] }`, with one entry per action. Pass it to `triggerAction(label, formName, action)`, which runs the actions in order and sends events to `onAction`. When the prop is empty, `triggerAction(label)` sends a `continue_conversation` event with the label as the message.++### Slots that take only some actions++A prop can name the actions it accepts. Build it from the `.ref` of a custom action and the built-in action refs in `steps`:++```tsx+import { defineComponent, steps, useTriggerAction } from "@openuidev/react-lang";+import { z } from "zod/v4";+import { copyToClipboard } from "./message";++const ShareButton = defineComponent({+ name: "ShareButton",+ description: "Shares a link or copies it",+ props: z.object({+ label: z.string(),+ share: z.union([copyToClipboard.ref, steps.OpenUrl.ref]),+ }),+ component: ({ props }) => {+ const triggerAction = useTriggerAction();+ return (+ <button onClick={() => triggerAction(props.label, undefined, props.share)}>+ {props.label}+ </button>+ );+ },+});+```++<Callout type="warn">+ Restricted slots are not enforced yet. They shape the prompt and the JSON Schema only. At runtime+ the slot accepts any action or `Action([...])`, so `ShareButton("Ask", @ToAssistant("Hi"))` still+ sends a `continue_conversation` event.+</Callout>++### `onAction` on the `Renderer`++The `Message` component in [Define an action](#define-an-action) handles the custom action in `onAction`. `Renderer` types `onAction` from its `library`. When the library has custom actions, the event is a union on `type`, and checking `type` narrows `params`. Here `event.params` is `{ text: string; format: "plain" | "markdown" }`.++To type a handler outside the `Renderer`, use `LibraryActionEvent`:++```ts+import type { LibraryActionEvent } from "@openuidev/react-lang";++function handleAction(event: LibraryActionEvent<typeof library>) {+ if (event.type === "CopyToClipboard") {+ void navigator.clipboard.writeText(event.params.text);+ }+}+```++### `onAction` on `AgentInterface`++`AgentInterface` from `@openuidev/react-ui` handles `@ToAssistant` (it sends a new user message) and `@OpenUrl` (it opens the link in a new tab). Its `onAction` prop receives the events the chat does not handle, such as the events from your custom actions:++```tsx+import { AgentInterface } from "@openuidev/react-ui";++<AgentInterface+ llm={llm}+ componentLibrary={library}+ onAction={(event) => {+ if (event.type === "CopyToClipboard") {+ void navigator.clipboard.writeText(String(event.params.text));+ }+ }}+/>;+```++Here `onAction` takes a plain `ActionEvent`, so `params` is not typed from the library.++When you pass `components.AssistantMessage`, `AgentInterface` does not render the messages and does not call `onAction`. Pass `onAction` to the `Renderer` in your message component instead.++### Renderer support++Custom actions work in the React `Renderer` from `@openuidev/react-lang`. The Vue, Svelte, and Angular renderers are on 0.4 and do not support them yet.++## Complete example++An order card where one button approves the order and another copies its ID. It adds `copyToClipboard` from [Define an action](#define-an-action) to `openuiLibrary`. `sendMessage` stands for your chat's send function:++```tsx+"use client";++import { Renderer } from "@openuidev/react-lang";+import { openuiLibrary } from "@openuidev/react-ui";+import { copyToClipboard } from "./message";++const library = openuiLibrary.extend({ actions: { add: [copyToClipboard] } });++export function OrderMessage({+ response,+ sendMessage,+}: {+ response: string;+ sendMessage: (text: string) => void;+}) {+ return (+ <Renderer+ library={library}+ response={response}+ toolProvider={{+ approve_order: async (args) =>+ fetch("/api/orders/approve", { method: "POST", body: JSON.stringify(args) }).then((r) =>+ r.json(),+ ),+ }}+ onAction={(event) => {+ if (event.type === "CopyToClipboard") {+ void navigator.clipboard.writeText(event.params.text);+ }+ if (event.type === "continue_conversation") {+ sendMessage(event.humanFriendlyMessage);+ }+ }}+ />+ );+}+```++The model writes:++```text+root = Stack([card])+card = Card([CardHeader("Order ORD-1042", "3 items, $120"), status, buttons])+approveOrder = Mutation("approve_order", {orderId: "ORD-1042"})+status = approveOrder.status == "success" ? Callout("success", "Approved", "The order is approved.") : null+buttons = Buttons([approveBtn, copyBtn])+approveBtn = Button("Approve", Action([@Run(approveOrder), @ToAssistant("I approved order ORD-1042")]), "primary")+copyBtn = Button("Copy ID", @CopyToClipboard("ORD-1042"), "secondary")+```++The user sees an order card with two buttons. "Approve" runs the mutation, shows the "Approved" callout, and sends "I approved order ORD-1042" to the model. "Copy ID" copies "ORD-1042" through your handler. If `approve_order` fails, the message is not sent.++## When to use it++Use actions when:++- A click should send a follow-up to the model: `@ToAssistant`.+- A click should change the UI or the data without the model: `@Set`, `@Reset`, `@Run`.+- A click should do something only your app can do, such as copy text or open a panel: a custom action.++Do not use them when:++- The UI only needs to show or hide something based on input. Bind a `$variable` to the input instead. See [Reactive State](/docs/openui-lang/reactive-state).+- You need a value computed from data. Use a [function](/docs/openui-lang/functions).diff --git a/docs/content/docs/openui-lang/architecture.mdx b/docs/content/docs/openui-lang/architecture.mdxindex 6b633f8b1..0c4649891 100644--- a/docs/content/docs/openui-lang/architecture.mdx+++ b/docs/content/docs/openui-lang/architecture.mdx@@ -3,6 +3,7 @@ title: Architecturedescription: Build dashboards, CRUD interfaces, and monitoring tools. The LLM generates the UI once, then your app runs independently.---+import { GenerateExecuteDiagram } from "@/components/openui-lang-diagrams";import { GatewayCallout } from "./components/gateway-callout";## The problem today@@ -13,18 +14,15 @@ In most AI-powered applications, when a user interacts with a generated UI (filtOpenUI separates **generation** from **execution**. The LLM generates the interface once. After that, the UI runs on its own: fetching data, handling state, and responding to user actions without any LLM involvement.-<img- src="/images/openui-lang/architecture.png"- alt="Architecture diagram showing two phases: GENERATE (one-time) and EXECUTE (ongoing, no LLM)"-/>+<GenerateExecuteDiagram />### Generate-The user describes what they want. Your backend sends the request to an LLM along with a system prompt that includes your component library and tool descriptions. The LLM responds with openui-lang code, a compact declarative format that describes the UI layout, data sources, and interactions.+The user describes what they want. Your backend sends the request to an LLM along with a system prompt that includes your component library and tool descriptions. The LLM responds with OpenUI Lang, a compact format that describes the UI layout, data sources, and interactions.### Execute-The Renderer parses the generated code. When it encounters a `Query("list_tickets")`, the runtime calls your tool directly, no LLM roundtrip. When the user clicks a button that triggers `@Run(createResult)`, the runtime executes the mutation against your tool. When a `$variable` changes from a dropdown, all dependent queries re-fetch automatically.+The Renderer parses the generated code in the browser. When it reaches `Query("list_tickets")`, the runtime calls your tool through the `toolProvider`, with no LLM call. When the user clicks a button that runs `@Run(createResult)`, the runtime runs the mutation with your tool. When a dropdown changes a `$variable`, the runtime fetches every query that uses it again.The LLM generated the wiring. The runtime executes it.@@ -47,13 +45,13 @@ The LLM doesn't have to get it right the first time. With [incremental editing](Turn 1: Turn 2 (patch only):root = Stack([header, tbl]) root = Stack([header, chart, tbl]) ← updated-header = CardHeader("Tickets") chart = PieChart(["Open","Closed"], ← new-tickets = Query(...) [@Count(@Filter(..., "open")),-tbl = Table([...]) @Count(@Filter(..., "closed"))- ], "donut")- 20 lines, ~400 tokens 3 lines, ~60 tokens (85% fewer)+header = CardHeader("Tickets") chart = PieChart(...) ← new+tickets = Query(...)+tbl = Table([...])```+For example, a full program of 20 lines might take about 400 tokens. A patch of 2 or 3 lines might take about 60.+<videosrc="/videos/openui-lang/incremental-editing.mp4"autoPlay@@ -81,7 +79,7 @@ The Renderer accepts a `toolProvider` prop that tells the runtime how to call yo/>```-**[MCP](https://modelcontextprotocol.io/docs/getting-started/intro) client** for server-side tools:+**[MCP](https://modelcontextprotocol.io/docs/getting-started/intro) client** for tools that run on an MCP server:```tsximport { Client } from "@modelcontextprotocol/sdk/client/index.js";@@ -92,9 +90,9 @@ await client.connect(new StreamableHTTPClientTransport(new URL("/api/mcp")));<Renderer toolProvider={client} response={code} library={library} />;```-These examples are simplified for demonstration. In production, you'll need to handle authentication, error boundaries, and connection lifecycle.+These examples leave out authentication, error handling, and connection lifecycle. Production code needs them.-The [GitHub Demo](/demo/github) uses a function map where tools run entirely client-side, calling the GitHub API directly from the browser. Server-side applications can expose the same tool surface through MCP.+The `toolProvider` runs in the browser, next to the `Renderer`. The [GitHub Demo](/demo/github) uses a function map that calls the GitHub API from the browser. To keep data access on your server, point the functions at your API routes or connect an MCP client to your server.## A concrete example@@ -104,7 +102,9 @@ Here's the full flow for a ticket tracker: define tools, generate the prompt, re```ts// tools.ts-const tools: ToolSpec[] = [+import type { ToolSpec } from "@openuidev/lang-core";++export const tools: ToolSpec[] = [{name: "list_tickets",description: "List all tickets",@@ -139,24 +139,24 @@ const tools: ToolSpec[] = [### 2. Generate the prompt and call the LLM+The prompt must list your tools, so your backend builds it with `generateSystemPrompt` and calls the provider. Gateway builds its own prompt from `generateSystemPrompt({ cloud: true, library })` and accepts only `preamble`, `examples`, and `additionalRules`. It drops every other option, including `tools`. [System Prompts](/docs/openui-lang/system-prompts#where-the-prompt-is-built) lists them all.+```ts// route.tsimport OpenAI from "openai";import { generateSystemPrompt, type LibrarySpec } from "@openuidev/lang-core";import componentSpec from "./generated/component-spec.json";+import { tools } from "./tools";-const gateway = new OpenAI({- apiKey: process.env.THESYS_API_KEY,- baseURL: "https://api.thesys.dev/v1/embed",-});+const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });const systemPrompt = generateSystemPrompt({library: componentSpec as LibrarySpec,promptOptions: { tools, toolCalls: true, bindings: true },});-const completion = await gateway.chat.completions.create({- model: "openai/gpt-5",+const completion = await client.chat.completions.create({+ model: "gpt-5",stream: true,messages: [{ role: "system", content: systemPrompt },@@ -167,15 +167,18 @@ const completion = await gateway.chat.completions.create({### 3. Render the response+The `Renderer` runs in the browser, and so does the `toolProvider`. Each tool calls an API route that reads or writes your database on the server:+```tsx-// page.tsx+// page.tsx, a client component<Rendererlibrary={library}response={streamedText}isStreaming={isStreaming}toolProvider={{- list_tickets: async () => db.query("SELECT * FROM tickets"),- create_ticket: async (args) => db.query("INSERT INTO tickets ...", args),+ list_tickets: async () => fetch("/api/tickets").then((r) => r.json()),+ create_ticket: async (args) =>+ fetch("/api/tickets", { method: "POST", body: JSON.stringify(args) }).then((r) => r.json()),}}/>```@@ -183,19 +186,19 @@ const completion = await gateway.chat.completions.create({### What the LLM generates```text+root = Stack([CardHeader("Ticket Tracker"), form, tbl])$title = ""$priority = "medium"createResult = Mutation("create_ticket", {title: $title, priority: $priority})tickets = Query("list_tickets", {}, {rows: []})-submitBtn = Button("Create", Action([@Run(createResult), @Run(tickets), @Reset($title, $priority)]))-form = Form("create", submitBtn, [- FormControl("Title", Input("title", $title)),- FormControl("Priority", Select("priority", $priority, [+submitBtn = Button("Create", Action([@Run(createResult), @Run(tickets), @Reset($title, $priority)]), "primary")+form = Form("create", Buttons([submitBtn]), [+ FormControl("Title", Input("title", "Ticket title", "text", {required: true}, $title)),+ FormControl("Priority", Select("priority", [SelectItem("low", "Low"), SelectItem("medium", "Medium"), SelectItem("high", "High")- ]))+ ], null, null, $priority))])tbl = Table([Col("Title", tickets.rows.title), Col("Priority", tickets.rows.priority)])-root = Stack([CardHeader("Ticket Tracker"), form, tbl])```<video@@ -209,10 +212,10 @@ root = Stack([CardHeader("Ticket Tracker"), form, tbl])### What happens at runtime-1. `Query("list_tickets")` → runtime calls your tool → table fills with data-2. User types a title, picks a priority, clicks "Create"-3. `@Run(createResult)` → runtime calls `create_ticket` directly-4. `@Run(tickets)` → runtime re-fetches `list_tickets` → table updates-5. `@Reset($title, $priority)` → form clears+1. `Query("list_tickets")`: the runtime calls your tool and the table fills with data.+2. The user types a title, picks a priority, and clicks "Create".+3. `@Run(createResult)`: the runtime calls `create_ticket`.+4. `@Run(tickets)`: the runtime fetches `list_tickets` again and the table updates.+5. `@Reset($title, $priority)`: the form clears.-All without the LLM.+The LLM is not called for any of these.diff --git a/docs/content/docs/openui-lang/builtins.mdx b/docs/content/docs/openui-lang/builtins.mdxdeleted file mode 100644index 1d12afcda..000000000--- a/docs/content/docs/openui-lang/builtins.mdx+++ /dev/null@@ -1,86 +0,0 @@-----title: Built-in Functions-description: Transform, filter, and aggregate data with @-prefixed built-in functions.------Built-in functions start with `@` - this tells the LLM "this is a function, not a component."--Built-ins are included in the system prompt when `toolCalls` or `bindings` is enabled. They are primarily used with `Query` results for data transformation, filtering, and aggregation.--## Aggregation--| Function | What it does | Example |-| --------------- | --------------- | --------------------------------- |-| `@Count(array)` | Length of array | `@Count(tickets.rows)` → `42` |-| `@Sum(array)` | Sum of numbers | `@Sum(data.rows.amount)` → `1250` |-| `@Avg(array)` | Average | `@Avg(data.rows.score)` → `4.2` |-| `@Min(array)` | Smallest value | `@Min(data.rows.price)` → `9.99` |-| `@Max(array)` | Largest value | `@Max(data.rows.price)` → `99.99` |-| `@First(array)` | First element | `@First(data.rows)` |-| `@Last(array)` | Last element | `@Last(data.rows)` |--## Filtering & Sorting--| Function | What it does |-| ---------------------------------- | --------------------------------------------------------------------------------- |-| `@Filter(array, field, op, value)` | Keep items where field matches. Ops: `==`, `!=`, `>`, `<`, `>=`, `<=`, `contains` |-| `@Sort(array, field, direction?)` | Sort by field. Direction: `"asc"` (default) or `"desc"` |--Examples:--```text-openTickets = @Filter(tickets.rows, "status", "==", "open")-sorted = @Sort(tickets.rows, "created", "desc")-```--## Composing functions--Functions can be nested:--```text-openCount = @Count(@Filter(tickets.rows, "status", "==", "open"))-```--This is the main pattern for KPI cards:--```text-kpi = Card([- TextContent("Open Tickets", "small"),- TextContent("" + @Count(@Filter(data.rows, "status", "==", "open")), "large-heavy")-])-```--## Math--| Function | What it does |-| --------------------------- | ------------------------- |-| `@Round(number, decimals?)` | Round to N decimal places |-| `@Abs(number)` | Absolute value |-| `@Floor(number)` | Round down |-| `@Ceil(number)` | Round up |--## Iteration with @Each--Render a template for every item in an array:--```text-@Each(tickets.rows, "t", Tag(t.priority, null, "sm"))-```--The second argument (`"t"`) is the loop variable name. Use it inside the template.--## Action steps--These are used inside `Action([...])` to wire button clicks:--| Step | What it does |-| ---------------------- | -------------------------------------- |-| `@Run(ref)` | Execute a Mutation or re-fetch a Query |-| `@Set($var, value)` | Change a `$variable` |-| `@Reset($var1, $var2)` | Restore `$variables` to defaults |-| `@ToAssistant("msg")` | Send a message to the LLM |-| `@OpenUrl("url")` | Open a URL in a new tab |--```text-submitBtn = Button("Create", Action([@Run(mutation), @Run(query), @Reset($title)]))-```diff --git a/docs/content/docs/openui-lang/components/how-it-works.tsx b/docs/content/docs/openui-lang/components/how-it-works.tsxindex f15722386..05e04cd43 100644--- a/docs/content/docs/openui-lang/components/how-it-works.tsx+++ b/docs/content/docs/openui-lang/components/how-it-works.tsx@@ -10,7 +10,7 @@ const steps = [title: "Define Library",description: "Create your component library with Zod schemas and generate the system prompt",code: `import { defineComponent, createLibrary } from '@openuidev/react-lang';-import { z } from 'zod';+import { z } from 'zod/v4';const Card = defineComponent({name: 'Card',@@ -35,12 +35,12 @@ export const systemPrompt = library.prompt(); // Generated system promptwelcomeCard = Card([welcomeHeader, welcomeBody], "card")welcomeHeader = CardHeader("Welcome", "Get started with our platform")welcomeBody = Stack([signupForm], "column", "m")-signupForm = Form("signup", [nameField, emailField], actions)-nameField = FormControl("Name", Input("name", "Your name", "text", ["required", "minLength:2"]))-emailField = FormControl("Email", Input("email", "[email protected]", "email", ["required", "email"]))+signupForm = Form("signup", actions, [nameField, emailField])+nameField = FormControl("Name", Input("name", "Your name", "text", {required: true, minLength: 2}))+emailField = FormControl("Email", Input("email", "[email protected]", "email", {required: true, email: true}))actions = Buttons([signUpBtn, learnMoreBtn], "row")-signUpBtn = Button("Sign up", "submit:signup", "primary")-learnMoreBtn = Button("Learn more", "action:learn_more", "secondary")+signUpBtn = Button("Sign up", @ToAssistant("Sign me up"), "primary")+learnMoreBtn = Button("Learn more", @ToAssistant("Tell me more about the platform"), "secondary")`,},];diff --git a/docs/content/docs/openui-lang/components/lang-example.tsx b/docs/content/docs/openui-lang/components/lang-example.tsxindex 7ab270a76..3b2605bef 100644--- a/docs/content/docs/openui-lang/components/lang-example.tsx+++ b/docs/content/docs/openui-lang/components/lang-example.tsx@@ -12,18 +12,6 @@ import { genuiOutput } from "@/components/overview-components/genui";import { Renderer } from "@openuidev/react-lang";import { openuiLibrary } from "@openuidev/react-ui";-const renderableOutput = `root = Stack([welcomeCard])-welcomeCard = Card([welcomeHeader, welcomeBody])-welcomeHeader = CardHeader("Welcome", "Get started with our platform")-welcomeBody = Stack([signupForm], "column", "m")-signupForm = Form("signup", actions, [nameField, emailField])-nameField = FormControl("Name", Input("name", "Your name", "text", { required: true, minLength: 2 }))-emailField = FormControl("Email", Input("email", "[email protected]", "email", { required: true, email: true }))-actions = Buttons([signUpBtn, learnMoreBtn], "row")-signUpBtn = Button("Sign up", { type: "continue_conversation", context: "signup" }, "primary")-learnMoreBtn = Button("Learn more", { type: "continue_conversation", context: "learn_more" }, "secondary")-`;-export const LangExample = () => {return (<div className="grid gap-4 lg:grid-cols-2">@@ -49,7 +37,7 @@ export const LangExample = () => {className="h-full"title="Component Library Definition"code={`import { defineComponent, createLibrary } from '@openuidev/react-lang';-import { z } from 'zod';+import { z } from 'zod/v4';const MyCard = defineComponent({name: 'MyCard',@@ -91,13 +79,13 @@ export function AssistantMessage({ content, isStreaming }) {<div className="mb-3 text-sm font-medium">Generate System Prompt with CLI</div><CodeBlocktitle=""- code={`@openuidev/cli generate path/to/library.ts -o system-prompt.txt`}+ code={`npx @openuidev/cli@latest generate path/to/library.ts --out system-prompt.txt`}/><div className="my-3 text-sm font-medium">Send system prompt to the LLM</div><CodeBlocktitle=""code={`import fs from "fs";-const openuiSystemPrompt = fs.readFileSync("system-prompt.txt", "utf8");+const systemPrompt = fs.readFileSync("system-prompt.txt", "utf8");const completion = await client.chat.completions.create({model: "gpt-5.2",stream: true,@@ -115,7 +103,7 @@ const completion = await client.chat.completions.create({<span className="text-sm font-medium">Output Preview</span></div><div className="p-6">- <Renderer library={openuiLibrary} response={renderableOutput} isStreaming={false} />+ <Renderer library={openuiLibrary} response={genuiOutput} isStreaming={false} /></div></SimpleCard></div>diff --git a/docs/content/docs/openui-lang/defining-components.mdx b/docs/content/docs/openui-lang/defining-components.mdxindex 59373dea7..2d6449289 100644--- a/docs/content/docs/openui-lang/defining-components.mdx+++ b/docs/content/docs/openui-lang/defining-components.mdx@@ -86,29 +86,72 @@ const TabItemSchema = z.object({});```-## Naming reusable helper schemas+## Action props-Use `tagSchemaId(...)` when a prop uses a standalone helper schema and you want a readable name in generated prompt signatures instead of `any`.+Use `action()` for a prop that takes an action, such as a button's click behavior:```tsx-import { defineComponent, tagSchemaId } from "@openuidev/react-lang";+import { action, defineComponent, useTriggerAction } from "@openuidev/react-lang";import { z } from "zod/v4";-const ActionExpression = z.any();-tagSchemaId(ActionExpression, "ActionExpression");-const Button = defineComponent({name: "Button",description: "Triggers an action",props: z.object({label: z.string(),- action: ActionExpression.optional(),+ action: action().optional(),+ }),+ component: ({ props }) => {+ const triggerAction = useTriggerAction();+ return (+ <button onClick={() => triggerAction(props.label, undefined, props.action)}>+ {props.label}+ </button>+ );+ },+});+```++The prompt prints the prop as `action?: ActionExpression` and teaches the model the available actions. See [Actions](/docs/openui-lang/actions).++## Naming reusable helper schemas++Use `tagSchemaId(...)` when a prop uses a standalone helper schema and you want a readable name in generated prompt signatures.++```tsx+import { defineComponent, tagSchemaId } from "@openuidev/react-lang";+import { z } from "zod/v4";++const ValidationRules = z.record(z.string(), z.any());+tagSchemaId(ValidationRules, "ValidationRules");++const Input = defineComponent({+ name: "Input",+ description: "A text input",+ props: z.object({+ name: z.string(),+ rules: ValidationRules.optional(),}),- component: ({ props }) => <button>{props.label}</button>,+ component: ({ props }) => <input name={props.name} />,});```-Without `tagSchemaId(...)`, the generated prompt would fall back to `action?: any`. Components already get their names automatically through `defineComponent(...)`, so this is only needed for non-component helper schemas.+The prompt prints `rules?: ValidationRules` instead of `rules?: Record<string, any>`. The tag changes the prompt only, not the JSON Schema. Components already get their names automatically through `defineComponent(...)`, so this is only needed for non-component helper schemas.++## Functions and actions++A library can also add its own `@` functions and actions:++```ts+const library = createLibrary({+ root: "Stack",+ components: [Stack, Card, TextContent, Button],+ functions: [percent], // defineFunction(...)+ actions: [copyToClipboard], // defineAction(...)+});+```++See [Functions](/docs/openui-lang/functions) and [Actions](/docs/openui-lang/actions). To add to an existing library instead, see [Extending a library](#extending-a-library).## The `root` field@@ -128,6 +171,8 @@ This serves two purposes:The `root` must match the `name` of one of the components in your library. If omitted, the prompt uses "Root" as a placeholder.+The root component also decides the fallback when a program has no `root` statement. See [Entry Statement](/docs/openui-lang/specification#entry-statement).+For the built-in libraries: `openuiLibrary` uses `Stack` (flexible layout container), while `openuiChatLibrary` uses `Card` (vertical container optimized for chat responses).## Notes on schema metadata@@ -208,6 +253,27 @@ const prompt = library.prompt(options);See [System Prompts](/docs/openui-lang/system-prompts) for full details on prompt generation.+## Extending a library++`library.extend(...)` derives a new library from an existing one, such as `openuiChatLibrary` from `@openuidev/react-ui`. The base library is not changed.++```tsx+export const shopLibrary = openuiChatLibrary.extend({+ components: {+ add: [{ component: ProductCard, slots: ["Card.children"] }],+ override: [CodeBlock],+ remove: ["RadarChart"],+ },+ functions: { add: [formatCurrency] },+ actions: { add: [addToCart] },+});+```++- `add` takes new components. `slots` puts one in a parent's signature, as `"Parent.prop"`.+- The shorthand `"Card"` works when the parent has exactly one content slot.+- `override` replaces a component of the same name. `remove` drops it from the library and from every parent.+- Create the derived library once, at module scope. A new library on every render makes the `Renderer` parse again from the start.+## Best practices for LLM generationSince LLMs are the ones writing OpenUI Lang, component design choices directly affect generation quality.diff --git a/docs/content/docs/openui-lang/evolution-guide.mdx b/docs/content/docs/openui-lang/evolution-guide.mdxindex b7c6ad769..c4e92ffd9 100644--- a/docs/content/docs/openui-lang/evolution-guide.mdx+++ b/docs/content/docs/openui-lang/evolution-guide.mdx@@ -3,6 +3,10 @@ title: Evolution Guidedescription: How OpenUI Lang evolved from static UI generation to interactive, data-driven apps.---+## v0.5 → 1.0++1.0 lets a library grow with its own functions, actions, and `library.extend`, adds a message format for storing responses, and sets one rule for where a program starts. One action no longer needs `Action([...])`. See [What's New in 1.0](/docs/openui-lang/whats-new).+## v0.1 → v0.5OpenUI Lang started as a way to generate static UI from LLM output, a token-efficient alternative to JSON for rendering chat responses. v0.5 turns it into a language for building **standalone interactive apps** that run independently of the LLM.@@ -13,7 +17,7 @@ OpenUI Lang started as a way to generate static UI from LLM output, a token-effi| ------------------- | ----------------------------- | --------------------------------------------------------------- || **Purpose** | Generate UI responses in chat | Build interactive apps with live data || **Data** | Hardcoded in the output | Fetched from your tools via `Query` / `Mutation` |-| **State** | None - static render | Reactive `$variables` with two-way binding |+| **State** | None, static render | Reactive `$variables` with two-way binding || **Interactivity** | Send message back to LLM | Buttons call tools directly via `@Run`, update state via `@Set` || **LLM role** | Generates UI on every turn | Generates UI once, then gets out of the way || **Data transforms** | None | `@Count`, `@Filter`, `@Sort`, `@Each`, `@Sum`, etc. |@@ -35,11 +39,11 @@ Data is hardcoded. No interactivity beyond clicking a button to send a message b### v0.5: Interactive app with live data-The LLM generates code that **connects to your tools**. The runtime fetches data, handles user interactions, and updates the UI - all without going back to the LLM.+The LLM generates code that **connects to your tools**. The runtime fetches data, handles user interactions, and updates the UI without going back to the LLM.```text$days = "7"-filter = Select("days", $days, [SelectItem("7", "7 days"), SelectItem("30", "30 days")])+filter = Select("days", [SelectItem("7", "7 days"), SelectItem("30", "30 days")], null, null, $days)data = Query("analytics", {days: $days}, {rows: []})chart = LineChart(data.rows.day, [Series("Revenue", data.rows.revenue)])kpi = Card([TextContent("Total", "small"), TextContent("" + @Sum(data.rows.revenue), "large-heavy")])@@ -57,11 +61,11 @@ What's different:### Reactive state-Declare variables, bind them to inputs, reference them in expressions. Everything updates automatically.+Declare variables, bind them to inputs, and reference them in expressions. A change updates everything that reads them.```text$search = ""-searchBox = Input("search", $search, "Search...")+searchBox = Input("search", "Search...", "text", null, $search)filtered = @Filter(data.rows, "title", "contains", $search)```@@ -69,7 +73,7 @@ See [Reactive State](/docs/openui-lang/reactive-state).### Data fetching-`Query` reads data from your tools. `Mutation` writes. The runtime calls your MCP endpoint directly - no LLM involved.+`Query` reads data from your tools. `Mutation` writes. The runtime calls your MCP endpoint directly, without the LLM.```texttickets = Query("list_tickets", {}, {rows: []})@@ -87,11 +91,11 @@ openCount = @Count(@Filter(tickets.rows, "status", "==", "open"))sorted = @Sort(tickets.rows, "created", "desc")```-See [Built-in Functions](/docs/openui-lang/builtins).+See [Built-in functions](/docs/openui-lang/functions#built-in-functions).### Action composition-Buttons can run mutations, refresh queries, set state, and reset forms - all in a single action.+One button action can run mutations, refresh queries, set state, and reset forms.```textsubmitBtn = Button("Create", Action([@Run(createResult), @Run(tickets), @Set($success, true), @Reset($title)]))@@ -101,11 +105,11 @@ submitBtn = Button("Create", Action([@Run(createResult), @Run(tickets), @Set($suComponents can accept `$variables` as props for reactive binding. For example, a Modal's `open` prop or a Callout's `visible` prop can be bound to a `$variable`, and the component reads and writes the variable directly.-This is a library-level feature (component authors use `useStateField`), not a language change. The language just passes the `$variable` as a positional argument.+This is a library-level feature (component authors use `useStateField`), not a language change. The language passes the `$variable` as a positional argument.### Incremental editing-LLM outputs only changed statements. The parser merges by name - existing code stays intact.+LLM outputs only changed statements. The parser merges by name, so the rest of the code stays.See [Incremental Editing](/docs/openui-lang/incremental-editing).@@ -118,4 +122,4 @@ The core language is unchanged:- Forward references and streaming-first rendering- Component resolution and validation-v0.5 is a superset - all v0.1 code is valid v0.5 code.+v0.5 is a superset: all v0.1 code is valid v0.5 code.diff --git a/docs/content/docs/openui-lang/functions.mdx b/docs/content/docs/openui-lang/functions.mdxnew file mode 100644index 000000000..d65f76ec4--- /dev/null+++ b/docs/content/docs/openui-lang/functions.mdx@@ -0,0 +1,265 @@+---+title: Functions+description: Call built-in and custom @ functions, and define your own with defineFunction.+---++Functions compute values inside a program. The model writes the call, and the renderer runs the code on the client. The numbers come from your data, not from the model.++For example, a ticket dashboard shows "Open tickets: 12". The model writes `@Count(@Filter(tickets.rows, "status", "==", "open"))`. The renderer counts the rows when the query returns and counts again when the rows change. The model never sees the rows.++Function calls start with `@`. The `@` marks a call (function or action), not a component. OpenUI Lang has built-in functions. When they are not enough, such as for currency formatting or a calculation specific to your domain, a library adds its own ([custom functions](#custom-functions)).++## Calling a function++```text+openTickets = @Filter(tickets.rows, "status", "==", "open")+```++Arguments are positional, the same rule as component props. `null` in place of an optional argument skips it. Calls can be nested:++```text+openCount = @Count(@Filter(tickets.rows, "status", "==", "open"))+```++The `@` is required. `Count(x)` is not a function call.++### Invalid arguments++Built-ins convert their arguments instead of validating them. `@Sum(["1", 2])` gives `3`.++Custom function arguments go through the same checks as component props, so a mistake in one call does not break the page.++Literal arguments are checked when the program is parsed:++| Problem | Error code | Result |+| :------------------------------- | :------------------------------------ | :----------------------------------------------- |+| Wrong type for a required param | `type-mismatch` | The call evaluates to `null`. |+| Required param missing or `null` | `missing-required` or `null-required` | The call evaluates to `null`. |+| Wrong type for an optional param | `type-mismatch` | The argument is dropped and the default applies. |+| More arguments than params | `excess-args` | The extra arguments are dropped. The call runs. |++Arguments that are only known at runtime (a `$variable`, a reference, a query result, an expression) are checked when the call runs:++- A required argument that is `null` or missing, with no default, makes the call evaluate to `null` with no error. This covers an unset `$variable` or a query that has not returned yet.+- A required argument of the wrong type reports `runtime-error`, and the call evaluates to `null`.+- An optional argument of the wrong type reports `runtime-error`, and its default applies. The call runs.+- If the function throws, the call reports `runtime-error` (`@Percent threw: ...`) and evaluates to `null`.+- If the result does not match its `returns` schema, the call reports `runtime-error` and evaluates to `null`. Without `returns`, the result is used as is.++The React `Renderer` sends these errors to `onError` once the stream has ended.++Custom actions are stricter. Any invalid argument there, optional or not, makes the action a no-op.++### Unknown functions++A call to an `@Name` that is not a built-in function, an action, or a library function reports `unknown-function` and evaluates to `null`. The rest of the statement still renders:++```text+root = TextContent("Total: " + @Total(items))+```++If the library has no `Total` function, this renders "Total: ".++## Built-in functions++The system prompt lists the built-ins when `toolCalls` or `bindings` is enabled, or when you set the `builtinFunctions` prompt option. They are mostly used to filter, sort, and aggregate `Query` results.++### Aggregation++| Function | What it does | Example |+| --------------- | --------------- | --------------------------------- |+| `@Count(array)` | Length of array | `@Count(tickets.rows)` → `42` |+| `@Sum(array)` | Sum of numbers | `@Sum(data.rows.amount)` → `1250` |+| `@Avg(array)` | Average | `@Avg(data.rows.score)` → `4.2` |+| `@Min(array)` | Smallest value | `@Min(data.rows.price)` → `9.99` |+| `@Max(array)` | Largest value | `@Max(data.rows.price)` → `99.99` |+| `@First(array)` | First element | `@First(data.rows)` |+| `@Last(array)` | Last element | `@Last(data.rows)` |++### Filtering & Sorting++| Function | What it does |+| ---------------------------------- | --------------------------------------------------------------------------------- |+| `@Filter(array, field, op, value)` | Keep items where field matches. Ops: `==`, `!=`, `>`, `<`, `>=`, `<=`, `contains` |+| `@Sort(array, field, direction?)` | Sort by field. Direction: `"asc"` (default) or `"desc"` |++```text+sorted = @Sort(tickets.rows, "created", "desc")+```++Nesting `@Count` and `@Filter` is the main pattern for KPI cards:++```text+kpi = Card([+ TextContent("Open Tickets", "small"),+ TextContent("" + @Count(@Filter(data.rows, "status", "==", "open")), "large-heavy")+])+```++### Math++| Function | What it does |+| --------------------------- | ------------------------- |+| `@Round(number, decimals?)` | Round to N decimal places |+| `@Abs(number)` | Absolute value |+| `@Floor(number)` | Round down |+| `@Ceil(number)` | Round up |++### Iteration with @Each++Render a template for every item in an array:++```text+priorityTags = @Each(tickets.rows, "t", Tag(t.priority, null, "sm"))+```++The second argument (`"t"`) is the loop variable name. Use it inside the template.++### Actions are not functions++`@Run`, `@Set`, `@Reset`, `@ToAssistant`, and `@OpenUrl` are actions, not functions. A function computes a value for a prop. An action runs when the user clicks. See [Actions](/docs/openui-lang/actions).++### Built-in signatures++The built-in functions are defined with `defineFunction` inside `@openuidev/lang-core`, so their prompt lines are generated the same way as custom ones:++```text+@Sum(numbers: number[]) → number+@Round(number: number, decimals?: number) → number+@Filter(array: any[], field: string, operator: "==" | "!=" | ">" | "<" | ">=" | "<=" | "contains", value: any) → any[]+```++## Custom functions++A library can add its own functions next to the built-ins. The model calls them with an `@` prefix, like `@Count`, and the renderer runs your implementation on the client. Use them for what the built-ins do not cover, such as formatting and small domain calculations that the model should not do by hand.++### Define a function++```tsx+import { createLibrary, defineComponent, defineFunction } from "@openuidev/react-lang";+import { z } from "zod/v4";++const percent = defineFunction({+ name: "Percent",+ description: "Formats part / total as a percentage",+ params: z.object({+ part: z.number(),+ total: z.number().default(100),+ }),+ returns: z.string(),+ fn: ({ part, total }) => `${((part / total) * 100).toFixed(1)}%`,+});++const TextContent = defineComponent({+ name: "TextContent",+ description: "A line of text",+ props: z.object({ text: z.string() }),+ component: ({ props }) => <p>{props.text}</p>,+});++export const library = createLibrary({+ root: "TextContent",+ components: [TextContent],+ functions: [percent],+});+```++The model can now write:++```text+root = TextContent("Done: " + @Percent(42, 120))+```++This renders "Done: 35.0%".++To add a function to an existing library, such as `openuiLibrary` from `@openuidev/react-ui`, use [`library.extend`](/docs/openui-lang/defining-components#extending-a-library).++### Fields++| Field | Description |+| :------------ | :--------------------------------------------------------------------------------------------- |+| `name` | The name after `@` in programs. By convention, start it with an uppercase letter. |+| `description` | Shown next to the signature in the prompt. |+| `params` | A `z.object(...)`. Key order is the positional order of the arguments. |+| `returns` | Optional. A Zod schema for the result. It is printed in the prompt and checked at runtime. |+| `fn` | The implementation. It receives one object keyed by the `params` names, with defaults applied. |++`params` must be a `z.object(...)`. Anything else throws when you call `defineFunction`.++### What `fn` receives++Arguments map to `params` in key order. `fn` receives them as one object:++| Call | `fn` receives |+| :------------------- | :------------------------- |+| `@Percent(42, 120)` | `{ part: 42, total: 120 }` |+| `@Percent(42)` | `{ part: 42, total: 100 }` |+| `@Percent(42, null)` | `{ part: 42, total: 100 }` |++A missing optional argument, or `null` in its place, takes the param's default. An optional param with no default is left out of the object. Keep `fn` pure and synchronous; it can run many times.++## Using functions in your app++Pass the library to the `Renderer` from `@openuidev/react-lang`, or to `AgentInterface`. The renderer runs `fn` and sends errors to `onError`:++```tsx+<Renderer library={library} response={response} onError={(errors) => console.warn(errors)} />+```++The Vue, Svelte, and Angular renderers are on 0.4 and do not run custom functions yet. Parsers built from `library.toJSONSchema()`, including Autofix in `@openuidev/server`, accept the calls.++## Complete example++A sales summary where the renderer computes the percentages.++Your app adds the function to `openuiLibrary` and renders with the extended library:++```tsx+"use client";++import { defineFunction, Renderer } from "@openuidev/react-lang";+import { openuiLibrary } from "@openuidev/react-ui";+import { z } from "zod/v4";++const percent = defineFunction({+ name: "Percent",+ description: "Formats part / total as a percentage",+ params: z.object({ part: z.number(), total: z.number().default(100) }),+ returns: z.string(),+ fn: ({ part, total }) => `${((part / total) * 100).toFixed(1)}%`,+});++// Create the library once, at module scope.+const library = openuiLibrary.extend({ functions: { add: [percent] } });++export function Summary({ response }: { response: string }) {+ return <Renderer library={library} response={response} />;+}+```++The model writes:++```text+root = Stack([header, tbl, summary])+header = CardHeader("Q3 sales")+regions = ["North", "South", "West"]+sales = [42, 75, 120]+targets = [120, 100, 100]+tbl = Table([Col("Region", regions), Col("Sales", sales, "number"), Col("Target", targets, "number")])+summary = TextContent("North reached " + @Percent(42, 120) + " of its target. The team reached " + @Percent(@Sum(sales), @Sum(targets)) + ".")+```++The user sees a table with three regions and the line "North reached 35.0% of its target. The team reached 74.1%." The renderer computed both numbers. The model only wrote the calls.++## When to use it++Use functions when:++- A value is derived from data: counts, sums, averages, or a filtered list.+- The value depends on `Query` results or `$variables`, so it must update without the model.+- Your app formats values in a fixed way, such as currency or percentages. Add a custom function for it.++Do not use them when:++- The function would have side effects, such as writing data or opening a link. Use an [action](/docs/openui-lang/actions) instead.+- The work is slow or async. `fn` must be pure and synchronous. Use a `Query` for data from your backend.diff --git a/docs/content/docs/openui-lang/incremental-editing.mdx b/docs/content/docs/openui-lang/incremental-editing.mdxindex 49c2740b1..b71b68d01 100644--- a/docs/content/docs/openui-lang/incremental-editing.mdx+++ b/docs/content/docs/openui-lang/incremental-editing.mdx@@ -1,24 +1,15 @@---title: Incremental Editing-description: Edit existing UIs efficiently - the LLM patches only what changed, the parser merges it.+description: Edit an existing UI by sending only what changed. The model writes a patch, mergeStatements merges it by name.----When a user says "add a pie chart" to an existing dashboard, the LLM doesn't regenerate everything.-It outputs only the changed and new statements. The parser merges them into the existing code.+import { IncrementalEditDiagram } from "@/components/openui-lang-diagrams";-## How it works+Incremental editing lets the model change an existing UI without writing it again. The model writes only the statements that changed or are new. Your app merges them into the previous program by statement name.-```- Before (4 statements): After merge (5 statements):+For example, a user has a ticket dashboard and says "add a pie chart". The model does not regenerate the whole dashboard. It writes two lines: a new `root` that includes the chart, and the chart itself. The queries, state, and table from the first response stay as they were.- root = Stack([header, tbl]) root = Stack([header, chart, tbl]) ← replaced- header = CardHeader("Tickets") header = CardHeader("Tickets") ← kept- tickets = Query("list_tickets",...) tickets = Query("list_tickets",...) ← kept- tbl = Table([...]) tbl = Table([...]) ← kept- chart = PieChart(...) ← added-- LLM only output 2 lines (root + chart). Parser merged by name.-```+<IncrementalEditDiagram /><videosrc="/videos/openui-lang/incremental-editing.mp4"@@ -29,7 +20,9 @@ It outputs only the changed and new statements. The parser merges them into theclassName="w-full rounded-lg"/>-**Initial generation** - LLM outputs full code:+## How it works++**First response.** The model writes the full program:```textroot = Stack([header, tbl])@@ -38,56 +31,96 @@ tickets = Query("list_tickets", {}, {rows: []})tbl = Table([Col("Title", tickets.rows.title), Col("Status", tickets.rows.status)])```-**User says:** _"add a pie chart showing ticket status breakdown"_+**The user says:** _"add a pie chart showing ticket status breakdown"_-**LLM outputs only the patch:**+**The model writes only the patch:**```textroot = Stack([header, chart, tbl])-chart = PieChart(["Open", "Closed"], [- @Count(@Filter(tickets.rows, "status", "==", "open")),- @Count(@Filter(tickets.rows, "status", "==", "closed"))-], "donut")+chart = PieChart(["Open", "Closed"], [@Count(@Filter(tickets.rows, "status", "==", "open")), @Count(@Filter(tickets.rows, "status", "==", "closed"))], "donut")```-The parser merges by statement name:+`mergeStatements` merges by statement name:-- `root` is redefined → new definition wins (now includes `chart`)-- `chart` is new → added-- `header`, `tickets`, `tbl` → kept from original (not in the patch, so unchanged)+- `root` is in the patch, so the new definition replaces the old one. It now includes `chart`.+- `chart` is new, so it is added.+- `header`, `tickets`, and `tbl` are not in the patch, so they are kept.## Merge rules-- **Same name** → new definition replaces old-- **New name** → added to the program-- **Missing from patch** → kept from original (not deleted)-- **Explicit deletion** → remove a statement from the `root` children list, it becomes unreachable and gets garbage-collected+- **Same name:** the patch definition replaces the old one.+- **New name:** the statement is added to the program.+- **Not in the patch:** the statement is kept.+- **Removed from its parent:** when the model writes the parent again without a child, the child is no longer reachable from `root` and is dropped. `$variables` are always kept.+- **`name = null`:** the statement is deleted.-## Why this matters+## Why use it-- **Fewer tokens** - LLM outputs 2-3 lines instead of regenerating 20+-- **Faster** - less to stream, less to parse-- **Preserves context** - existing queries, state, and bindings stay intact-- **Works with streaming** - each patched line renders as it arrives+- **Fewer tokens.** The model writes 2 or 3 lines instead of the whole program.+- **Faster.** There is less to stream and less to parse.+- **State stays.** Existing queries, `$variables`, and bindings are not rebuilt.-Full regeneration: 20 statements, ~400 tokens, ~2s streaming.-Incremental patch: 2 statements, ~60 tokens, ~0.3s streaming.-Same result, up to **85% fewer tokens**.+For example, a dashboard of 20 statements might take about 400 tokens and 2 seconds to stream in full. A patch of 2 statements might take about 60 tokens and 0.3 seconds. The real numbers depend on the program and the model.## Enabling edit mode-Two flags control this behavior in your prompt config:+Two prompt options control this behavior. Pass them to `generateSystemPrompt` in your backend:```ts-const config: PromptSpec = {- ...componentSpec,- editMode: true, // LLM outputs patches instead of full regenerations- inlineMode: true, // LLM can mix text and code in the same response-};+import { generateSystemPrompt, type LibrarySpec } from "@openuidev/lang-core";+import librarySpec from "./generated/system-prompt.spec.json";++const systemPrompt = generateSystemPrompt({+ library: librarySpec as LibrarySpec,+ promptOptions: {+ editMode: true, // the model writes patches instead of full programs+ inlineMode: true, // the model can mix text and code in one response+ },+});```-**`editMode`** tells the LLM it can output partial patches. Without it, the LLM regenerates the entire UI on every turn, even for small changes. With it enabled, the LLM only outputs the statements that changed or were added.+**`editMode`** tells the model to write only the statements that changed or were added. Without it, the model writes the whole program on every turn, even for small changes.++**`inlineMode`** lets the model answer with text next to the code. The parser reads code from ` ```openui-lang ` fences and treats everything else as text. The model can say "I added a pie chart for the status breakdown" before the patch, so the user knows what changed.++Gateway builds its own prompt and drops `editMode` and `inlineMode`. Build the prompt in your backend to use edit mode. See [System Prompts](/docs/openui-lang/system-prompts).++## Complete example++Your backend builds the prompt with `editMode: true` as shown above and sends the full conversation, including the previous program, with each request. Your app keeps the current program and merges each new response into it:++```tsx+"use client";++import { mergeStatements, Renderer } from "@openuidev/react-lang";+import { openuiLibrary } from "@openuidev/react-ui";++export function Dashboard({+ previous,+ latest,+ isStreaming,+}: {+ previous: string; // the program shown before this turn+ latest: string; // the model's patch for this turn+ isStreaming: boolean;+}) {+ const program = isStreaming ? previous : mergeStatements(previous, latest);+ return <Renderer library={openuiLibrary} response={program} isStreaming={isStreaming} />;+}+```++The component merges after the stream ends. While the patch streams, `root` is half written, and `mergeStatements` would drop the statements it cannot reach yet. After the merge, store `program` as the new `previous` for the next turn.++The model writes the two-line patch from [How it works](#how-it-works). The user keeps seeing the same ticket table while the patch streams. When it ends, a donut chart appears between the header and the table, and the table keeps its data. The `list_tickets` query is not rebuilt.++## When to use it++Use incremental editing when:++- Users refine a generated UI over several turns: "add a filter", "rename the title", "remove the chart".+- Programs are long, so writing them again costs time and tokens.-**`inlineMode`** lets the LLM respond with explanation text alongside the code. The parser extracts code from fenced blocks (` ```openui-lang `) and ignores everything else. This way the LLM can say "I added a pie chart for the status breakdown" before the patch, which gives the user context about what changed.+Do not use it when:-Both flags are passed to `generateSystemPrompt()` via `promptOptions`. See [System Prompts](/docs/openui-lang/system-prompts) for the full reference.+- Each response is a new, unrelated UI, such as a chat that answers with a fresh card every turn.+- Your app does not keep the previous program. Without it, there is nothing to merge into.diff --git a/docs/content/docs/openui-lang/index.mdx b/docs/content/docs/openui-lang/index.mdxindex a47fe1de7..321868468 100644--- a/docs/content/docs/openui-lang/index.mdx+++ b/docs/content/docs/openui-lang/index.mdx@@ -5,6 +5,7 @@ description: A streaming-first language that models use to build interfaces from---import { StreamingComparison } from "@/app/docs/openui-lang/streaming-comparison";+import { LangGlanceDiagram } from "@/components/openui-lang-diagrams";import { GatewayCallout } from "./components/gateway-callout";OpenUI Lang is an open, compact language for describing interfaces with components your application controls. Models generate it efficiently, renderers can display it progressively, and applications can use it with any model provider, agent framework, or chat library.@@ -13,19 +14,19 @@ OpenUI Lang is an open, compact language for describing interfaces with componen## Architecture at a Glance-<img src="/images/openui-lang/openui-chart-flow.png" alt="Architecture diagram" />+<LangGlanceDiagram />-1. **System prompt includes OpenUI Lang spec**: Your backend appends the generated component library prompt alongside your system prompt, instructing the LLM to respond in OpenUI Lang instead of plain text or JSON.+1. **System prompt includes OpenUI Lang spec**: Your backend adds the prompt generated from your component library to your system prompt. It tells the LLM to respond in OpenUI Lang instead of plain text or JSON.2. **LLM generates OpenUI Lang**: Instead of returning markdown, the model outputs a compact, line-oriented syntax (e.g., `root = Stack([chart])`) constrained to your component library.-3. **Streaming render**: On the client, the `<Renderer />` component parses each line as it arrives and maps it to your React components in real-time. Structure renders first, then data fills in progressively.+3. **Streaming render**: On the client, the `<Renderer />` component parses each line as it arrives and maps it to your React components. Structure renders first, then data fills in.The result is a native UI dynamically composed by the AI, streamed efficiently, and rendered safely from your own components. For data-driven apps with live tools and reactive state, see [Architecture](/docs/openui-lang/architecture).## OpenUI Lang-OpenUI Lang is a compact, line-oriented language designed specifically for Large Language Models (LLMs) to generate user interfaces. It serves as a more efficient, predictable, and stream-friendly alternative to verbose formats like JSON. For the complete syntax reference, see the [Language Specification](/docs/openui-lang/specification-v05).+OpenUI Lang is a compact, line-oriented language designed specifically for Large Language Models (LLMs) to generate user interfaces. It uses fewer tokens than JSON and streams line by line. For the complete syntax reference, see the [Language Specification](/docs/openui-lang/specification).### Why a New Language?@@ -33,11 +34,11 @@ While JSON is a common data interchange format, it has significant drawbacks wheOpenUI Lang was created to solve these core issues:-- **Token Efficiency:** JSON is extremely verbose. Keys like `"component"`, `"props"`, and `"children"` are repeated for every single element, consuming a large number of tokens. This directly increases API costs and latency. OpenUI Lang uses a concise, positional syntax that drastically reduces the token count. Benchmarks show it is up to **[67% more token-efficient](/docs/openui-lang/benchmarks)** than JSON.+- **Token Efficiency:** JSON repeats keys like `"component"`, `"props"`, and `"children"` for every element. Each repeated key costs tokens, which adds cost and latency. OpenUI Lang uses positional arguments instead. In our [benchmarks](/docs/openui-lang/benchmarks) it uses up to 67% fewer tokens than JSON.-- **Streaming-First Design:** The language is line-oriented (`identifier = Expression`), making it trivial to parse and render progressively. As each line arrives from the model, a new piece of the UI can be rendered immediately. This provides a superior user experience with much better perceived performance compared to waiting for a complete JSON object to download and parse.+- **Streaming-First Design:** The language is line-oriented (`identifier = Expression`). The renderer can show each line as it arrives from the model. With JSON, the UI often waits until the object is complete enough to parse.-- **Robustness:** LLMs are unpredictable. They can hallucinate component names or produce invalid structures. OpenUI Lang validates output and drops invalid portions, rendering only what's valid.+- **Robustness:** LLMs can invent component names or produce invalid structures. The parser validates the output, drops the invalid parts, and the renderer shows the rest.<StreamingComparison />diff --git a/docs/content/docs/openui-lang/interactivity.mdx b/docs/content/docs/openui-lang/interactivity.mdxindex fde3708f9..8045a9d2a 100644--- a/docs/content/docs/openui-lang/interactivity.mdx+++ b/docs/content/docs/openui-lang/interactivity.mdx@@ -7,7 +7,7 @@ OpenUI components can be interactive. The `Renderer` manages form state automati## Actions-When a user clicks a button or follow-up, the component calls `triggerAction`. The `Renderer` wraps this into an `ActionEvent` and fires `onAction`.+When a user clicks a button or follow-up, the component calls `triggerAction`. The `Renderer` turns the click into an event, an `ActionEvent`, and passes it to `onAction`.```tsx<Renderer@@ -15,9 +15,9 @@ When a user clicks a button or follow-up, the component calls `triggerAction`. Tresponse={content}onAction={(event) => {if (event.type === "continue_conversation") {- // event.humanFriendlyMessage — button label or follow-up text- // event.formState — field values at time of click- // event.formName — scoping form name, if any+ // event.humanFriendlyMessage: button label or follow-up text+ // event.formState: field values at time of click+ // event.formName: scoping form name, if any}}}/>@@ -43,21 +43,26 @@ enum BuiltinActionType {}```-- `ContinueConversation`: sends the user's intent back to the LLM (`@ToAssistant`).-- `OpenUrl`: opens a URL in a new tab (`@OpenUrl`).+- `ContinueConversation`: sends the user's intent back to the LLM (`@ToAssistant`). The optional context from `@ToAssistant(message, context)` arrives unchanged in `params.context`, and can be any value.+- `OpenUrl`: opens a URL in a new tab (`@OpenUrl`). The URL is in `params.url`.-The following action steps are handled internally by the runtime (not dispatched to `onAction`):+A [custom action](/docs/openui-lang/actions#custom-actions) from your library arrives with its own name as `type` and its arguments in `params`. When the library has custom actions, `onAction` is typed from the library, and checking `event.type` narrows `event.params`.++The renderer runs these actions itself and does not send them to `onAction`:- `@Run(ref)`: executes a Mutation or re-fetches a Query- `@Set($var, value)`: changes a reactive `$variable`- `@Reset($var1, $var2)`: restores `$variables` to their declared defaults-In openui-lang, actions are composed with `Action([...])`:+In OpenUI Lang, one action can be passed on its own, and several actions go in `Action([...])`:```text+askBtn = Button("Tell me more", @ToAssistant("Tell me more about these tickets"))submitBtn = Button("Create", Action([@Run(createResult), @Run(tickets), @Reset($title)]))```+See [Actions](/docs/openui-lang/actions) for the full rules.+See [Reactive State](/docs/openui-lang/reactive-state) for `$variables` and [Queries & Mutations](/docs/openui-lang/queries-mutations) for `@Run`.### Inline mode@@ -85,13 +90,13 @@ const MyButton = defineComponent({});```-`triggerAction(userMessage, formName?, action?)` accepts optional second and third arguments.+`triggerAction(userMessage, formName?, action?)` accepts optional second and third arguments. To let the model choose what a component does on click, give it an `action()` prop and pass that prop as the third argument. See [Action props in your components](/docs/openui-lang/actions#action-props-in-your-components).---## Reactive state (`$variables`)-In openui-lang, `$variables` create reactive state that components can read and write. When the LLM generates `$days = "7"` and passes it to a Select, the runtime creates a two-way binding automatically.+In OpenUI Lang, `$variables` hold reactive state that components can read and write. When the model writes `$days = "7"` and passes it to a Select, the renderer keeps the Select and `$days` in sync.For component authors building custom libraries, the `useStateField` hook provides this binding:@@ -107,8 +112,8 @@ const MySelect = defineComponent({}),component: ({ props }) => {const field = useStateField(props.name, props.value);- // field.value — current value (reads from $variable or form state)- // field.setValue(val) — updates the $variable and triggers re-evaluation+ // field.value: current value (reads from $variable or form state)+ // field.setValue(val): updates the $variable and triggers re-evaluationreturn (<select value={field.value ?? ""} onChange={(e) => field.setValue(e.target.value)}>{/* ... */}diff --git a/docs/content/docs/openui-lang/message-protocol.mdx b/docs/content/docs/openui-lang/message-protocol.mdxnew file mode 100644index 000000000..c1c709cdc--- /dev/null+++ b/docs/content/docs/openui-lang/message-protocol.mdx@@ -0,0 +1,174 @@+---+title: Message Protocol+description: Store a response and show it again later, with form values kept, using buildMessage and parseMessage.+---++import { MessageProtocolDiagram } from "@/components/openui-lang-diagrams";++The message protocol lets your app store a model response and show it again later, with the user's form values kept. Without stored context, a reloaded chat has no form values to restore.++For example, a user fills half of a booking form in a chat and closes the tab. When the user opens the chat again, the form is back with the same dates and guest count. Your app stored the response and the form values together as one message.++Three parties handle a stored message:++- **Your app writes it.** `buildMessage` wraps the response text and the context, such as form values, in marker lines that start with `]]>openui:`.+- **The Renderer reads it.** Pass the stored message as `response`. The Renderer renders the content and ignores the context.+- **The model never sees the markers.** Before a stored message goes back to the model as history, your app strips the markers with `parseMessage`.++<MessageProtocolDiagram />++Both functions are exported from `@openuidev/react-lang` and `@openuidev/lang-core`.++## Write a message++```ts+import { buildMessage } from "@openuidev/react-lang";++const stored = buildMessage({+ content: responseText,+ context: { formState: { note: "rush" } },+ attributes: { library: "[email protected]" },+ end: true,+});+```++| Field | Description |+| :----------- | :------------------------------------------------------------------------------------------------------------------------ |+| `content` | The response text. |+| `context` | Optional. A string is written as is. Any other value is written as JSON. `null` or `undefined` writes no context section. |+| `attributes` | Optional. Written after `?` on the content line, encoded like `URLSearchParams` (`@` becomes `%40`). |+| `end` | Optional. `true` adds the `end` line. Set it when the stream has finished. |++What the context holds is up to your app. OpenUI does not require a shape.++## Read a message++```ts+import { parseMessage } from "@openuidev/react-lang";++const { content, context, attributes, end } = parseMessage(stored);+// content: "root = Card([title, saveBtn])\n..."+// context: { formState: { note: "rush" } }+// attributes: { library: "[email protected]" }+// end: true+```++| Field | Description |+| :----------- | :---------------------------------------------------------------------------------------------------------------------------- |+| `content` | The body of the content section. For text with no markers, the whole text. |+| `context` | The body of the context section, parsed as JSON. Raw text when it is not valid JSON. `null` when there is no context section. |+| `attributes` | The decoded attributes of the content line. |+| `end` | `true` when the message has an `end` line. |++`end` is absent when the host did not mark the stream as finished. A message without it still renders.++## Show a stored message again++The `Renderer` accepts a stored message as `response`. It removes the marker lines and renders the content:++```tsx+<Renderer library={library} response={stored} />+```++The `Renderer` does not read the context. To restore form values, read them yourself and pass them as `initialState`. To keep them up to date, write a new message from `onStateUpdate`:++```tsx+import { buildMessage, parseMessage, Renderer, type Library } from "@openuidev/react-lang";++type Context = { formState?: Record<string, unknown> } | null;++export function StoredMessage({+ stored,+ library,+ save,+}: {+ stored: string;+ library: Library;+ save: (message: string) => void;+}) {+ const { content, context, attributes } = parseMessage(stored);+ return (+ <Renderer+ library={library}+ response={stored}+ initialState={(context as Context)?.formState}+ onStateUpdate={(formState) =>+ save(buildMessage({ content, context: { formState }, attributes, end: true }))+ }+ />+ );+}+```++## Send history to the model++Strip the markers before a stored message goes back to the model. For an assistant turn, send `parseMessage(stored).content`. If your app sends context to the model (form values, click data), turn it into plain text in the user turn. The model must never see `]]>openui:` lines.++## Complete example++The `StoredMessage` component above is the whole client side. Your app also:++1. Saves each finished response: `save(buildMessage({ content: responseText, end: true }))`.+2. Renders it with `<StoredMessage stored={row.message} library={openuiLibrary} save={...} />`, where `save` writes the new message back to the same row.+3. Sends `parseMessage(row.message).content` as the assistant turn when it builds the history for the next request.++The user fills in a form, reloads the page, and sees the form with the same values. The model sees only the program, never a `]]>openui:` line.++## When to use it++Use the message format when:++- Your app stores chat history and shows generated UI again after a reload.+- Form values or click context should survive a reload.++Do not use it when:++- Responses are shown once and never stored. Pass the raw text to the `Renderer`.+- You use `AgentInterface` from `@openuidev/react-ui`. It already stores messages in this format. See [The react-ui chat format](#the-react-ui-chat-format).++## Format++A stored message is the response text with marker lines:++```text+]]>openui:content?library=support%401.2.0+root = Card([title, saveBtn])+title = TextContent("Order 42")+saveBtn = Button("Save", @ToAssistant("Save order", {orderId: 42}))+]]>openui:context+{"formState":{"note":"rush"}}+]]>openui:end+```++| Line | Meaning |+| :------------------ | :------------------------------------------------------------------------------------------- |+| `]]>openui:content` | Starts the content: the program, or prose with fenced programs. Attributes follow `?`. |+| `]]>openui:context` | Starts the context: data your app keeps with the message, such as form values. Usually JSON. |+| `]]>openui:end` | The stream finished. It is absent when the host did not mark the stream as finished. |++Reading rules:++- A `]]>openui:content` marker in the middle of a line is first moved onto its own line. Other markers count only at the start of a line, so `]]>openui:end` in the middle of a line is ordinary text.+- With several content sections, the last one wins. A context section before it is ignored.+- Text before the first marker is the content only when the message has no content marker.+- Unknown marker kinds are skipped together with their text.+- Plain text with no markers comes back unchanged as `content`, so older stored responses still read.++## While streaming++Pass `{ streaming: true }` while the response is still arriving:++```ts+const { content } = parseMessage(partialText, { streaming: true });+```++A last line that is, or could become, a marker line (for example `]]>open`) is then held back until its newline arrives, so a half-written marker never shows up as content.++## The react-ui chat format++`AgentInterface` in `@openuidev/react-ui` stores its messages in this format:++- An assistant message stores `[formState]` as its context once the user changes a field.+- A user turn created by `@ToAssistant` stores the message as content and an array as context: `["User clicked: <message>", formState, context]`. The second element is the form state. It is present when there is form state or a context, and is `{}` when there is only a context. The third element, the `@ToAssistant` context, is present only when one is given.++It still reads messages stored in the older `<content>...</content><context>...</context>` envelope.diff --git a/docs/content/docs/openui-lang/meta.json b/docs/content/docs/openui-lang/meta.jsonindex d3224b208..619337529 100644--- a/docs/content/docs/openui-lang/meta.json+++ b/docs/content/docs/openui-lang/meta.json@@ -4,6 +4,7 @@"pages": ["index","quickstart",+ "whats-new","---Core Concepts---","overview","defining-components",@@ -11,16 +12,16 @@"renderer","interactivity","reliability",- "---Building Apps---",- "architecture",+ "---Language Spec---","reactive-state",+ "functions",+ "actions","queries-mutations",- "incremental-editing",- "builtins","patterns",- "---Language Specification---",- "specification-v05",- "specification-v01",+ "incremental-editing",+ "message-protocol",+ "architecture",+ "specification","evolution-guide","---Advanced---","developer-tools",diff --git a/docs/content/docs/openui-lang/overview.mdx b/docs/content/docs/openui-lang/overview.mdxindex 7e7817f25..952a55945 100644--- a/docs/content/docs/openui-lang/overview.mdx+++ b/docs/content/docs/openui-lang/overview.mdx@@ -23,6 +23,8 @@ Four pieces make that flow work:<GatewayCallout description="For production, route generation through the Gateway to correct invalid OpenUI Lang while it streams and recover from provider failures." />+`@X(...)` is either a [function](/docs/openui-lang/functions), which computes a value, or an [action](/docs/openui-lang/actions), which runs on click. The name decides which. For example, `@Count(open)` in `TextContent("Open: " + @Count(open))` is a function, and `@ToAssistant("Explain this")` in `Button("Explain", @ToAssistant("Explain this"))` is an action.+## The core loop1. Define the components your application supports.diff --git a/docs/content/docs/openui-lang/patterns.mdx b/docs/content/docs/openui-lang/patterns.mdxindex ff027ca90..ceab3bdc0 100644--- a/docs/content/docs/openui-lang/patterns.mdx+++ b/docs/content/docs/openui-lang/patterns.mdx@@ -3,7 +3,7 @@ title: Patternsdescription: Complete examples showing how Query, $variables, @builtins, and actions compose together.----Real dashboards combine multiple features. These patterns show complete, copy-paste-ready openui-lang snippets using the built-in `openuiLibrary` components (Stack, Card, Table, etc.). The openui-lang code works the same with any custom library, just swap the component names to match your own definitions.+Real dashboards combine multiple features. These patterns show complete, copy-paste-ready openui-lang snippets using the built-in `openuiLibrary` components (Stack, Card, Table, etc.). The same code works with a custom library once the component names match your own definitions.## Searchable, sortable tablediff --git a/docs/content/docs/openui-lang/queries-mutations.mdx b/docs/content/docs/openui-lang/queries-mutations.mdxindex 31dc1e51b..373dfef5d 100644--- a/docs/content/docs/openui-lang/queries-mutations.mdx+++ b/docs/content/docs/openui-lang/queries-mutations.mdx@@ -1,16 +1,17 @@---title: Queries & Mutations-description: Fetch and write data from your tools - the LLM generates the wiring, the runtime executes it.+description: Fetch and write data from your tools. The model writes the wiring, the runtime runs it.----<img- src="/images/openui-lang/query-flow.png"- alt="Data flow: openui-lang code → Runtime → Your Tools → Live data back to components"-/>+import { QueryFlowDiagram } from "@/components/openui-lang-diagrams";++Queries and mutations connect a generated UI to your backend. The model writes which tool to call and where the result goes. The runtime calls your tools directly, without the model.++For example, a support agent asks for "a table of open tickets with a form to add one". The model writes one `Query` that lists tickets and one `Mutation` that creates a ticket. The table fills from your API, and each new ticket appears in it after the user submits the form. No click goes through the model.-OpenUI Lang connects to your backend through **tools**. A tool is any function your server-exposes (a database query, an API call, a calculation). The LLM generates `Query` and `Mutation`-statements that call these tools. The runtime executes them directly and feeds the results into your UI.+<QueryFlowDiagram />++A **tool** is any function your app exposes: a database query, an API call, or a calculation. The model generates `Query` and `Mutation` statements that call these tools. The runtime runs them and feeds the results into your UI.## Reading data with Query@@ -20,44 +21,44 @@ data = Query("list_tickets", {}, {rows: []})What each argument means:-1. `"list_tickets"` - the tool name (matches what your server exposes)-2. `{}` - arguments to pass to the tool-3. `{rows: []}` - default value (what renders before the tool responds)+1. `"list_tickets"`: the tool name. It matches a tool your `toolProvider` exposes.+2. `{}`: the arguments passed to the tool.+3. `{rows: []}`: the default value. The UI renders it until the tool responds.-The default value is important - it lets the UI render immediately while data loads.+The default value lets the UI render while the data loads.## Using Query results-Query results are just data. Access fields with dot notation:+Query results are data. Access fields with dot notation:```texttbl = Table([Col("Title", data.rows.title), Col("Status", data.rows.status)])chart = LineChart(data.rows.day, [Series("Views", data.rows.views)])```-`data.rows.title` extracts the `title` field from every row - like a column pluck.+`data.rows.title` takes the `title` field from every row, like a column pluck.### Reactive queries-Pass a `$variable` in the query args - the query re-runs when the variable changes:+Pass a `$variable` in the query arguments. The query runs again when the variable changes:```text$days = "7"data = Query("analytics", {days: $days}, {rows: []})-filter = Select("days", $days, [SelectItem("7", "7 days"), SelectItem("30", "30 days")])+filter = Select("days", [SelectItem("7", "7 days"), SelectItem("30", "30 days")], null, null, $days)```-User picks "30" → `$days` updates → Query re-fetches with `{days: "30"}` → chart updates.+The user picks "30", `$days` updates, the Query fetches again with `{days: "30"}`, and the chart updates.### Auto-refresh-Add a fourth argument for periodic refresh (in seconds):+A fourth argument sets a refresh interval in seconds:```texthealth = Query("get_server_health", {}, {cpu: 0, memory: 0}, 30)```-This re-fetches every 30 seconds - great for monitoring dashboards.+This fetches the data again every 30 seconds.## Writing data with Mutation@@ -65,37 +66,103 @@ This re-fetches every 30 seconds - great for monitoring dashboards.createResult = Mutation("create_ticket", {title: $title, priority: $priority})```-Mutations are NOT executed on page load. They only run when triggered by `@Run`:+A Mutation does not run when the page loads. It runs only when an action runs it with `@Run`:```textsubmitBtn = Button("Create", Action([@Run(createResult), @Run(tickets), @Reset($title)]))```-This button does three things in order:+This button runs three actions in order:++1. `@Run(createResult)` runs the mutation and creates the ticket.+2. `@Run(tickets)` fetches the tickets query again, so the table refreshes.+3. `@Reset($title)` clears the title field.-1. `@Run(createResult)` - executes the mutation (creates the ticket)-2. `@Run(tickets)` - re-fetches the tickets query (refreshes the table)-3. `@Reset($title)` - clears the form+If the mutation fails, the actions after it do not run.### Error handling-Check `result.status` for mutation feedback:+Check `result.status` to show feedback. Assign each check to a statement and place it in the layout:```text-createResult.status == "error" ? Callout("error", "Failed", createResult.error) : null-createResult.status == "success" ? Callout("success", "Created", "Ticket added.") : null+createError = createResult.status == "error" ? Callout("error", "Failed", createResult.error) : null+createDone = createResult.status == "success" ? Callout("success", "Created", "Ticket added.") : null```## How tools connect to the runtime-The Renderer accepts a `toolProvider` prop that handles tool execution. Pass a function map or an [MCP](https://modelcontextprotocol.io/docs/getting-started/intro) client:+The `Renderer` takes a `toolProvider` prop that runs the tools. Pass a function map or an [MCP](https://modelcontextprotocol.io/docs/getting-started/intro) client. The `Renderer` is a client component, so these functions run in the browser. Point them at your API routes:```tsx// Function map-<Renderer toolProvider={{- list_tickets: async (args) => fetch('/api/tickets').then(r => r.json()),-}} response={code} library={library} />+<Renderer+ toolProvider={{+ list_tickets: async () => fetch("/api/tickets").then((r) => r.json()),+ }}+ response={code}+ library={library}+/>// Or an MCP client<Renderer toolProvider={mcpClient} response={code} library={library} />```++## Complete example++A ticket tracker with a create form and a table.++Your app gives the renderer two tools. Each calls an API route on your server:++```tsx+"use client";++import { Renderer } from "@openuidev/react-lang";+import { openuiLibrary } from "@openuidev/react-ui";++export function Tickets({ response }: { response: string }) {+ return (+ <Renderer+ library={openuiLibrary}+ response={response}+ toolProvider={{+ list_tickets: async () => fetch("/api/tickets").then((r) => r.json()),+ create_ticket: async (args) =>+ fetch("/api/tickets", { method: "POST", body: JSON.stringify(args) }).then((r) =>+ r.json(),+ ),+ }}+ />+ );+}+```++The model writes:++```text+root = Stack([CardHeader("Tickets"), form, createError, tbl])+$title = ""+$priority = "medium"+tickets = Query("list_tickets", {}, {rows: []})+createResult = Mutation("create_ticket", {title: $title, priority: $priority})+form = Form("create", Buttons([submitBtn]), [titleField, priorityField])+titleField = FormControl("Title", Input("title", "Ticket title", "text", {required: true}, $title))+priorityField = FormControl("Priority", Select("priority", [SelectItem("low", "Low"), SelectItem("medium", "Medium"), SelectItem("high", "High")], null, null, $priority))+submitBtn = Button("Create", Action([@Run(createResult), @Run(tickets), @Reset($title, $priority)]), "primary")+createError = createResult.status == "error" ? Callout("error", "Could not create the ticket", createResult.error) : null+tbl = Table([Col("Title", tickets.rows.title), Col("Priority", tickets.rows.priority)])+```++The user sees a form and a table with the current tickets. The user types a title, picks a priority, and clicks "Create". The renderer calls `create_ticket`, then `list_tickets`, and the new ticket appears in the table. The form clears. If `create_ticket` fails, an error callout appears above the table.++## When to use it++Use queries and mutations when:++- The UI shows data that lives in your systems, such as tickets, orders, or metrics.+- The data changes after the response, and the UI should show the latest rows.+- The user creates, updates, or deletes records from the UI.++Do not use them when:++- The data is small and fixed when the model answers. The model can write the values into the program.+- The result needs the model to reason about it. Call the tool on your backend before the model answers, or use `@ToAssistant`.diff --git a/docs/content/docs/openui-lang/reactive-state.mdx b/docs/content/docs/openui-lang/reactive-state.mdxindex 6bbfe0375..5655e15f1 100644--- a/docs/content/docs/openui-lang/reactive-state.mdx+++ b/docs/content/docs/openui-lang/reactive-state.mdx@@ -1,8 +1,14 @@---title: Reactive State-description: Make your UI interactive with $variables that update automatically.+description: Keep UI state in $variables so the generated UI updates without another model call when the user changes something.---+import { ReactivityDiagram } from "@/components/openui-lang-diagrams";++Reactive state makes a generated UI interactive: filters, tabs, and inputs respond to the user without another model call. The model declares a `$variable` and uses it in several places. When the user changes it, the renderer updates every place that reads it.++For example, a dashboard has a date range picker, a heading, and a chart. The user picks "30 days". The heading changes to "Showing last 30 days" and the chart fetches 30 days of data. The model wrote that wiring once, in the first response.+<videosrc="/videos/openui-lang/reactive.mp4"autoPlay@@ -12,12 +18,9 @@ description: Make your UI interactive with $variables that update automatically.className="w-full rounded-lg"/>-Every UI needs state: which tab is selected, what the user typed, whether a modal is open.-In OpenUI Lang, state is declared with `$variables`.-## Declaring a variable-A `$variable` is a line that starts with `$`:+A `$variable` is a statement whose name starts with `$`:```text$days = "7"@@ -25,18 +28,19 @@ $title = ""$showEdit = false```-That's it. The value on the right is the default.+The value on the right is the default.## Binding to inputs-When you pass a `$variable` to an input component, it creates a two-way binding.-The user changes the input, the variable updates. The variable changes, the input updates.+When a `$variable` is passed to an input's `value` prop, the two stay in sync. When the user changes the input, the variable updates. When the variable changes, the input shows the new value.```text$days = "7"-filter = Select("days", $days, [SelectItem("7", "7 days"), SelectItem("30", "30 days")])+filter = Select("days", [SelectItem("7", "7 days"), SelectItem("30", "30 days")], null, null, $days)```+In `openuiLibrary`, `value` is the fifth argument of `Select` and `Input`, so the model writes `null` for the placeholder and rules it skips.+## Using variables in expressionsAny expression can read a `$variable`:@@ -46,18 +50,17 @@ title = TextContent("Showing last " + $days + " days")data = Query("analytics", {days: $days}, {rows: []})```-When `$days` changes (user picks "30" in the Select), the title updates and the Query-re-fetches with the new value. This happens automatically - no wiring needed.+When the user picks "30" in the Select, `$days` changes. The renderer updates the title and fetches the Query again with the new value.## Changing state from buttons-Use `@Set` inside an `Action` to change a variable when a button is clicked:+`@Set` is an action that sets a variable when the button is clicked:```text-btn = Button("Show 30 days", Action([@Set($days, "30")]))+btn = Button("Show 30 days", @Set($days, "30"))```-You can set multiple variables at once:+To set several variables, put several actions in `Action([...])`. They run in order:```textsaveBtn = Button("Save", Action([@Set($showEdit, false), @Set($saved, true)]))@@ -70,32 +73,92 @@ saveBtn = Button("Save", Action([@Set($showEdit, false), @Set($saved, true)]))```text$title = ""$priority = "medium"-resetBtn = Button("Clear", Action([@Reset($title, $priority)]))+resetBtn = Button("Clear", @Reset($title, $priority))```-After click: `$title` goes back to `""`, `$priority` goes back to `"medium"`.+After the click, `$title` is `""` again and `$priority` is `"medium"`.## Conditional rendering-Use ternary expressions to show/hide UI based on state:+A ternary shows or hides part of the UI based on state. The result must be assigned to a statement like any other expression:```text-$showEdit ? editForm : null-status == "error" ? Callout("error", "Failed", errorMsg) : null+$showHelp = false+helpBtn = Button("Help", @Set($showHelp, true))+help = $showHelp ? Callout("info", "Tip", "Pick a range to update the chart.") : null+root = Stack([helpBtn, help])```## How reactivity works-<img- src="/images/openui-lang/reactive.png"- alt="Reactivity chain: $days changes, Query re-fetches, TextContent re-evaluates, Chart re-renders"-/>+<ReactivityDiagram />++When a `$variable` changes, the renderer:++1. Updates every input bound to it.+2. Fetches every `Query` that uses it in its arguments again.+3. Re-evaluates every expression that reads it.+4. Re-renders the components whose props changed.++The model declares the variable and uses it. The renderer keeps everything in sync.++## Complete example++A usage dashboard where the date range drives the heading and the chart.++Your app renders the response with `openuiLibrary` and gives the renderer one tool:++```tsx+"use client";++import { Renderer } from "@openuidev/react-lang";+import { openuiLibrary } from "@openuidev/react-ui";++export function Dashboard({ response }: { response: string }) {+ return (+ <Renderer+ library={openuiLibrary}+ response={response}+ toolProvider={{+ get_usage: async ({ days }) => fetch(`/api/usage?days=${days}`).then((r) => r.json()),+ }}+ />+ );+}+```++The model writes:++```text+root = Stack([header, filter, summary, chart])+header = CardHeader("Usage")+$days = "7"+filter = FormControl("Date range", Select("days", [SelectItem("7", "7 days"), SelectItem("30", "30 days")], null, null, $days))+usage = Query("get_usage", {days: $days}, {rows: []})+summary = TextContent("Showing last " + $days + " days, " + @Sum(usage.rows.events) + " events")+chart = LineChart(usage.rows.day, [Series("Events", usage.rows.events)])+```++The user sees a "Usage" card with a date range picker set to "7 days", a summary line, and a line chart. When the user picks "30 days", the summary changes to "Showing last 30 days" and the renderer calls `get_usage` with `{ days: "30" }`. The chart redraws with the new rows. The model is not called again.++## What your component must do++The components in `openuiLibrary` already support `$variable` binding. A component in your own library supports it when it:++1. Marks the prop with `reactive(...)`, for example `value: reactive(z.string().optional())`.+2. Reads and writes the value through `useStateField(props.name, props.value)` instead of local React state.++`useStateField` returns `{ value, setValue }`. Calling `setValue` updates the `$variable`, and the renderer re-evaluates everything that reads it. See [Interactivity](/docs/openui-lang/interactivity#reactive-state-variables) for a full component.++## When to use it++Use reactive state when:-When a `$variable` changes:+- A filter, tab, or toggle should change what the UI shows.+- Form inputs feed a `Query` or `Mutation`.+- A button should open a modal or show a section.-1. All inputs bound to it update their display-2. All `Query` calls that reference it in their args re-fetch-3. All expressions that reference it re-evaluate-4. The UI re-renders with new values+Do not use it when:-No event listeners. No useEffect. No wiring. Just declare and reference.+- The change needs new reasoning or new layout from the model. Use `@ToAssistant` to send a message instead.+- The value never changes. Use a plain statement, such as `title = "Usage"`.diff --git a/docs/content/docs/openui-lang/renderer.mdx b/docs/content/docs/openui-lang/renderer.mdxindex d1e139ab1..91028fdc1 100644--- a/docs/content/docs/openui-lang/renderer.mdx+++ b/docs/content/docs/openui-lang/renderer.mdx@@ -24,26 +24,26 @@ export function AssistantMessage({## Props-| Prop | Type | Description |-| :-------------- | :--------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------- |-| `response` | `string \| null` | Raw OpenUI Lang response text. |-| `library` | `Library` | Library created by `createLibrary(...)`. |-| `isStreaming` | `boolean` | Indicates stream is in progress. |-| `onAction` | `(event: ActionEvent) => void` | Receives structured action events from interactive components. |-| `onStateUpdate` | `(state: Record<string, any>) => void` | Called on form field changes with the raw field state map. |-| `initialState` | `Record<string, any>` | Hydrates form state on load (e.g. from persisted message). |-| `onParseResult` | `(result: ParseResult \| null) => void` | Debug/inspect latest parse result. |-| `toolProvider` | `Record<string, (args: Record<string, unknown>) => Promise<unknown>> \| McpClientLike \| null` | Handles `Query()` / `Mutation()` tool calls. Pass a function map or an [MCP](https://modelcontextprotocol.io/docs/getting-started/intro) client. |-| `queryLoader` | `React.ReactNode` | Custom loading indicator; defaults to a spinner. |-| `children` | `React.ReactNode` | Optional Renderer slot composition; omit to keep content visible with a loading indicator. |-| `onError` | `(errors: OpenUIError[]) => void` | Structured, LLM-friendly errors from the parser and query system. Suitable for automated correction loops. Called with `[]` when resolved. |+| Prop | Type | Description |+| :-------------- | :--------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `response` | `string \| null` | Raw OpenUI Lang text, or a stored message. The Renderer renders its content and ignores the context. See [Message Protocol](/docs/openui-lang/message-protocol). |+| `library` | `Library` | Library created by `createLibrary(...)`. |+| `isStreaming` | `boolean` | Indicates stream is in progress. |+| `onAction` | `(event: LibraryActionEvent<L>) => void` | Receives structured action events from interactive components. Typed from the library's custom actions. |+| `onStateUpdate` | `(state: Record<string, any>) => void` | Called on form field changes with the raw field state map. |+| `initialState` | `Record<string, any>` | Hydrates form state on load (e.g. from persisted message). |+| `onParseResult` | `(result: ParseResult \| null) => void` | Debug/inspect latest parse result. |+| `toolProvider` | `Record<string, (args: Record<string, unknown>) => Promise<unknown>> \| McpClientLike \| null` | Handles `Query()` / `Mutation()` tool calls. Pass a function map or an [MCP](https://modelcontextprotocol.io/docs/getting-started/intro) client. |+| `queryLoader` | `React.ReactNode` | Custom loading indicator; defaults to a spinner. |+| `children` | `React.ReactNode` | Optional Renderer slot composition; omit to keep content visible with a loading indicator. |+| `onError` | `(errors: OpenUIError[]) => void` | Structured, LLM-friendly errors from the parser and query system. Suitable for automated correction loops. Called with `[]` when resolved. |## Connecting toolsFor UIs that use `Query()` and `Mutation()`, pass a `toolProvider`. Two options:```tsx-// Function map — tools are just async functions+// Function map: one async function per tool<RenderertoolProvider={{list_tickets: async (args) => fetch("/api/tickets").then((r) => r.json()),@@ -54,7 +54,7 @@ For UIs that use `Query()` and `Mutation()`, pass a `toolProvider`. Two options:response={code}/>;-// MCP client — pass a configured MCP client directly+// MCP client: pass a configured MCP client directlyimport { Client } from "@modelcontextprotocol/sdk/client/index.js";import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";@@ -90,18 +90,25 @@ These examples are simplified for demonstration. In production, you'll need to hError codes:-| Code | Source | Description |-| :------------------ | :------------- | :---------------------------------------------------------------------- |-| `unknown-component` | parser | Component name not in the library |-| `missing-required` | parser | Required prop not provided |-| `null-required` | parser | Required prop explicitly null |-| `excess-args` | parser | More positional args than schema params (extras dropped, still renders) |-| `inline-reserved` | parser | Query/Mutation used inline instead of top-level |-| `parse-failed` | parser | Response produced no renderable root |-| `parse-exception` | parser | Parser crashed on malformed input |-| `tool-not-found` | query/mutation | Tool name not found in toolProvider |-| `runtime-error` | runtime | Expression evaluation failed on a prop |-| `render-error` | runtime | React component threw during render |+| Code | Source | Description |+| :------------------ | :------------- | :------------------------------------------------------------------------------------------------- |+| `unknown-component` | parser | Component name not in the library |+| `missing-required` | parser | Required prop not provided |+| `null-required` | parser | Required prop explicitly null |+| `type-mismatch` | parser | Argument does not match the prop's type or enum |+| `excess-args` | parser | More positional args than schema params (extras dropped, still renders) |+| `inline-reserved` | parser | Query/Mutation used inline instead of top-level |+| `unknown-function` | parser | `@Name(...)` is not a built-in function, action, or library function |+| `no-root` | parser | No usable entry statement (see [Entry Statement](/docs/openui-lang/specification#entry-statement)) |+| `parse-failed` | parser | Response text produced no statements |+| `parse-exception` | parser | Parser crashed on malformed input |+| `tool-not-found` | query/mutation | Tool name not found in toolProvider |+| `tool-error` | query/mutation | The tool call failed |+| `mcp-error` | query/mutation | The MCP tool returned an error |+| `runtime-error` | runtime | Expression evaluation or a library function call failed on a prop |+| `render-error` | runtime | React component threw during render |++An error with `severity: "warning"` did not stop the page from rendering, for example a `no-root` fallback entry. Skip warnings when you send errors back to the LLM.If no `onError` callback is provided, errors are logged to `console.warn` instead of being silently swallowed.@@ -110,7 +117,7 @@ If no `onError` callback is provided, errors are logged to `console.warn` instea- Parser re-runs as chunks arrive.- Forward references resolve when their statements arrive.- Unresolved references and invalid components are dropped from arrays (not left as null holes).-- `meta.orphaned` lists defined-but-unreachable statements on every chunk — useful for real-time debugging.+- `meta.orphaned` lists defined but unreachable statements on every chunk. Use it to debug while streaming.- There is no `nodePlaceholder` prop in the current renderer API.## Actions@@ -121,8 +128,8 @@ If no `onError` callback is provided, errors are logged to `console.warn` instearesponse={content}onAction={(event) => {if (event.type === "continue_conversation") {- // event.humanFriendlyMessage — display label- // event.formState — raw field values at time of action+ // event.humanFriendlyMessage: display label+ // event.formState: raw field values at time of action}}}/>diff --git a/docs/content/docs/openui-lang/specification/index.mdx b/docs/content/docs/openui-lang/specification/index.mdxnew file mode 100644index 000000000..3a3d53bb8--- /dev/null+++ b/docs/content/docs/openui-lang/specification/index.mdx@@ -0,0 +1,173 @@+---+title: Specification+description: Language specification for OpenUI Lang 1.0. The entry rule, @-calls, action expressions, stored messages, and error codes.+---++OpenUI Lang 1.0 extends the [v0.5 specification](/docs/openui-lang/specification/v0.5). The statement syntax is unchanged. 1.0 adds one expression form, a lone action without an `Action([...])` wrapper. It also adds a clear entry rule, custom functions and actions, a format for stored messages, and new error codes. See [What's New in 1.0](/docs/openui-lang/whats-new) for upgrade notes.++## Syntax Overview++A program is a list of **assignment statements**, one per line:++```text+identifier = Expression+```++The statement kinds are the same as in v0.5: component or value statements, `$variable` declarations, and `Query` or `Mutation` statements. 1.0 adds these expression forms:++| Form | Syntax | Example |+| --------------- | ------------------- | -------------------------------------- |+| Function call | `@Name(args)` | `@Percent(done, total)` |+| Action | `@Name(args)` | `@ToAssistant("Tell me more")` |+| Several actions | `Action([actions])` | `Action([@Run(save), @Reset($title)])` |++All other expressions and operators work as in v0.5.++## Core Rules++1. **One statement per line:** `identifier = Expression`+2. **Entry:** the statement named `root`. See [Entry Statement](#entry-statement).+3. **Positional arguments:** mapped to props, function params, and action params by Zod key order. `null` skips an optional argument.+4. **Forward references allowed:** a statement can use a name defined later.+5. **`@` is required** for functions and actions. `Count(x)` is not a call. Only `Action([...])` works without the `@`.+6. **Last definition wins:** if two statements share a name, the later one is used.++## Entry Statement++The entry is the statement named `root`. Its value must be a component: a call, a reference to one, or an expression that gives one.++```text+$compact = false+root = $compact ? compactView : fullView+compactView = TextContent("3 open")+fullView = Card([TextContent("3 open tickets")])+```++With no `root` statement, the first statement that calls the library's root component is the entry, wherever it is. It renders, with a `no-root` warning:++```text+title = TextContent("Orders")+page = Card([title])+```++In every other case nothing renders. The parser reports `no-root` on every parse. Renderers, such as the React `Renderer`, hold errors back until the stream ends, so a missing entry is not shown as an error while streaming.++The fallback needs the root component name. The `Renderer` takes it from the library. A parser on the server needs it as the second argument: `createParser(library.toJSONSchema(), library.root)`.++## Function Calls++`@Name(args)` calls a built-in function or a custom function from the library. The built-ins are the same as in v0.5. Built-ins are looked up first, and a library cannot reuse the name of a built-in function or action.++Custom function arguments are checked like component props:++- A literal argument with the wrong type, or a required one that is missing or `null`, makes the call `null`. The error is `type-mismatch`, `missing-required`, or `null-required`.+- A wrong optional argument is dropped and its default applies. Extra arguments report `excess-args` and are dropped.+- A required argument that is `null` at runtime, such as an unset `$variable`, makes the call `null` with no error.+- A wrong runtime type, a function that throws, or a result that does not match `returns` reports `runtime-error`. The call is `null`.++Custom functions must be pure and synchronous. The client may call them any number of times, in any order.++A call to an `@Name` that is not a built-in function, an action, or a library function reports `unknown-function` and evaluates to `null`. The rest of the statement still renders:++```text+root = Card([total])+total = TextContent("Total: " + @Total(items))+```++See [Functions](/docs/openui-lang/functions).++## Action Expressions++One action needs no wrapper. Several actions go in `Action([...])` and run in order:++```text+askBtn = Button("Tell me more", @ToAssistant("Tell me more about this order"))+saveBtn = Button("Save", Action([@Run(save), @Run(orders), @Reset($note)]))+```++`@ToAssistant("Hi")` is the same as `Action([@ToAssistant("Hi")])`. A nested `Action([...])` is flattened. A plain list of actions, such as `[@Set($a, 1), @ToAssistant("Hi")]`, is not an action. It is plain data, with no error.++### Built-in actions++| Action | Description |+| --------------------------------- | ------------------------------------------------------------------------ |+| `@ToAssistant(message, context?)` | Send a `continue_conversation` event. `context` can be any value |+| `@OpenUrl(url)` | Send an `open_url` event |+| `@Set($var, value)` | Set a `$variable`. `value` is evaluated when the action runs |+| `@Reset($var1, $var2)` | Restore `$variables` to declared defaults |+| `@Run(ref)` | Run a Mutation or re-fetch a Query. A mutation that fails stops the rest |+| `@Name(args)` | A custom action. Sends an event with `type: "Name"` and `params` |++The `context` of `@ToAssistant` reaches the host unchanged in `params.context`:++```text+approveBtn = Button("Approve", @ToAssistant("Approve this order", {orderId: 42}))+```++Each event carries the form state as of when its action runs.++### Invalid actions++An action with invalid arguments is skipped and the rest still run. A mutation that runs and fails stops the rest. A custom action with any invalid argument, required or optional, is a no-op. It does not fall back to a default.++Only an `@Name(...)` call written in the program creates a custom action. An object, a `$variable`, or a query row shaped like an action never reaches the host as one.++### Restricted action slots++A prop can accept only some actions. The prompt prints it with the action names:++```text+ShareButton(label: string, share: @CopyToClipboard | @OpenUrl)+```++In the JSON Schema, the prop is an `anyOf` of `$ref`s to the action names. A prop that takes any action is `{"$ref": "#/$defs/ActionExpression"}`. In 1.0 the restriction shapes the prompt and the schema only. At runtime the slot accepts any action.++See [Actions](/docs/openui-lang/actions).++## Stored Messages++A host stores a response as text, with marker lines that start with `]]>openui:`. The model never writes or sees them.++```text+]]>openui:content?library=support%401.2.0+root = Card([title])+title = TextContent("Order 42")+]]>openui:context+{"formState":{"note":"rush"}}+]]>openui:end+```++| Line | Meaning |+| ------------------- | -------------------------------------------------- |+| `]]>openui:content` | Starts the program, or prose with fenced programs |+| `]]>openui:context` | Starts host data, such as form state. Usually JSON |+| `]]>openui:end` | The stream finished |++A `]]>openui:content` marker in the middle of a line is first moved onto its own line. Other markers count only at the start of a line. With several `content` sections, the last one wins. Text with no markers is the content. `end` is absent when the host did not mark the stream as finished. A message without it still renders. See [Message Protocol](/docs/openui-lang/message-protocol).++## Error Codes++| Code | Meaning | Result |+| ------------------- | -------------------------------------------------------- | ----------------------------------- |+| `unknown-component` | Component not in the library | Component dropped |+| `missing-required` | Required prop or param missing | Default if any, else dropped |+| `null-required` | Required prop or param is `null` | Same as `missing-required` |+| `type-mismatch` | Wrong type, enum value, or data in a component-only slot | Default if any, else dropped |+| `excess-args` | More arguments than props or params | Extras dropped, still renders |+| `inline-reserved` | `Query` or `Mutation` used inline | Evaluates to nothing |+| `unknown-function` | `@Name` is not a built-in, action, or library function | Call is `null`, statement kept |+| `no-root` | No usable entry | Warning with the fallback, or fatal |+| `parse-failed` | Text with no statements | Fatal |+| `runtime-error` | Evaluation or a function call failed | The prop or call is `null` |++`unknown-function` and `no-root` are new in 1.0. Query, mutation, and render errors are as in the [Renderer](/docs/openui-lang/renderer) docs.++An error with `severity: "warning"` did not stop the page from rendering. Today that is the `no-root` fallback. Skip warnings when you send errors back to the model.++## Prompt Feature Flags++The flags are the same as in v0.5, plus `builtinFunctions`. It lists the built-in functions in a library without `toolCalls` or `bindings`. A library's own functions and actions are always listed. See [System Prompts](/docs/openui-lang/system-prompts).++## Streaming++Forward references and hoisting work as in v0.5. When the stream ends, the result equals a parse of the full text: statements, entry, errors, and state defaults.diff --git a/docs/content/docs/openui-lang/specification/meta.json b/docs/content/docs/openui-lang/specification/meta.jsonnew file mode 100644index 000000000..0447a67e7--- /dev/null+++ b/docs/content/docs/openui-lang/specification/meta.json@@ -0,0 +1,5 @@+{+ "title": "Specification",+ "defaultOpen": false,+ "pages": ["index", "v0.5", "v0.1"]+}diff --git a/docs/content/docs/openui-lang/specification-v01.mdx b/docs/content/docs/openui-lang/specification/v0.1.mdxsimilarity index 97%rename from docs/content/docs/openui-lang/specification-v01.mdxrename to docs/content/docs/openui-lang/specification/v0.1.mdxindex b38bd3d2a..21aafe3c5 100644--- a/docs/content/docs/openui-lang/specification-v01.mdx+++ b/docs/content/docs/openui-lang/specification/v0.1.mdx@@ -5,8 +5,8 @@ description: The original OpenUI Lang specification for declarative UI generatio<Callout type="info">This is the **v0.1** specification, the original language for generating static UI from LLM- output. For the latest version with reactive state, data queries, and interactive apps, see- [v0.5](/docs/openui-lang/specification-v05).+ output, kept as it was released. For the current version, see the+ [Specification](/docs/openui-lang/specification).</Callout>OpenUI Lang is the output format the LLM generates. It is a compact, declarative, line-oriented DSL designed specifically for streaming and token efficiency.diff --git a/docs/content/docs/openui-lang/specification-v05.mdx b/docs/content/docs/openui-lang/specification/v0.5.mdxsimilarity index 93%rename from docs/content/docs/openui-lang/specification-v05.mdxrename to docs/content/docs/openui-lang/specification/v0.5.mdxindex fba640e74..fe43b50d4 100644--- a/docs/content/docs/openui-lang/specification-v05.mdx+++ b/docs/content/docs/openui-lang/specification/v0.5.mdx@@ -1,9 +1,14 @@----title: v0.5 (Latest)+title: v0.5description: Full language specification for OpenUI Lang v0.5 - reactive state, queries, mutations, and built-in functions.----OpenUI Lang v0.5 extends the [v0.1 specification](/docs/openui-lang/specification-v01) with reactive state, data fetching, and built-in functions. See the [Evolution Guide](/docs/openui-lang/evolution-guide) to understand how the language evolved from static UI generation to interactive apps.+<Callout type="info">+ This is the **v0.5** specification, kept as it was released. For the current version, see the+ [Specification](/docs/openui-lang/specification).+</Callout>++OpenUI Lang v0.5 extends the [v0.1 specification](/docs/openui-lang/specification/v0.1) with reactive state, data fetching, and built-in functions. See the [Evolution Guide](/docs/openui-lang/evolution-guide) to understand how the language evolved from static UI generation to interactive apps.## Syntax Overview@@ -150,7 +155,7 @@ Steps execute in order. If `@Run(mutation)` fails, remaining steps are skipped.## Component Resolution-Positional arguments map to named props via Zod schema key order. See [v0.1 spec](/docs/openui-lang/specification-v01#component-resolution) for the full mapping logic.+Positional arguments map to named props via Zod schema key order. See [v0.1 spec](/docs/openui-lang/specification/v0.1#component-resolution) for the full mapping logic.## Prompt Feature Flags@@ -165,4 +170,4 @@ The system prompt is generated with feature flags that control which language fe## Streaming & Hoisting-Forward references are allowed. See [v0.1 spec](/docs/openui-lang/specification-v01#streaming--hoisting) for details.+Forward references are allowed. See [v0.1 spec](/docs/openui-lang/specification/v0.1#streaming--hoisting) for details.diff --git a/docs/content/docs/openui-lang/syntax.mdx b/docs/content/docs/openui-lang/syntax.mdxindex 0c860164c..411702b89 100644--- a/docs/content/docs/openui-lang/syntax.mdx+++ b/docs/content/docs/openui-lang/syntax.mdx@@ -14,12 +14,12 @@ Example:```textroot = Stack([title, form])title = TextContent("Sign up", "large-heavy")-form = Form("signup", [nameField, emailField], actions)-nameField = FormControl("Name", Input("name", "Your name", "text", ["required"]))-emailField = FormControl("Email", Input("email", "[email protected]", "email", ["required", "email"]))+form = Form("signup", actions, [nameField, emailField])+nameField = FormControl("Name", Input("name", "Your name", "text", {required: true}))+emailField = FormControl("Email", Input("email", "[email protected]", "email", {required: true, email: true}))actions = Buttons([submitBtn, cancelBtn], "row")-submitBtn = Button("Submit", "submit:signup", "primary")-cancelBtn = Button("Cancel", "action:cancel", "secondary")+submitBtn = Button("Submit", @ToAssistant("Sign me up"), "primary")+cancelBtn = Button("Cancel", @ToAssistant("Cancel sign up"), "secondary")```## Supported expression types@@ -37,7 +37,7 @@ cancelBtn = Button("Cancel", "action:cancel", "secondary")## Rules-- First statement is the entry point.+- `root` is the entry point. Without it, the first statement that calls the root component is used.- For OpenUI library prompts, start with `root = Stack(...)`.- Arguments are positional, based on Zod key order.- Optional args can be omitted from the end.@@ -45,22 +45,24 @@ cancelBtn = Button("Cancel", "action:cancel", "secondary")## Common default-library signatures+These are the signatures in `openuiLibrary` from `@openuidev/react-ui`.+| Component | Signature || ------------- | --------------------------------------------------------------------- || `Stack` | `Stack(children, direction?, gap?, align?, justify?, wrap?)` || `Card` | `Card(children, variant?, direction?, gap?, align?, justify?, wrap?)` || `TextContent` | `TextContent(text, size?)` |-| `Form` | `Form(name, fields, buttons)` |+| `Form` | `Form(name, buttons, fields?)` || `FormControl` | `FormControl(label, input, hint?)` |-| `Input` | `Input(name, placeholder?, type?, rules?)` |-| `Select` | `Select(name, items, placeholder?, rules?)` |-| `Button` | `Button(label, action, variant?, type?, size?)` |+| `Input` | `Input(name, placeholder?, type?, rules?, value?)` |+| `Select` | `Select(name, items, placeholder?, rules?, value?, size?)` |+| `Button` | `Button(label, action?, variant?, type?, size?)` || `Buttons` | `Buttons(buttons, direction?)` || `Tabs` | `Tabs(items)` || `TabItem` | `TabItem(value, trigger, content)` || `Table` | `Table(columns)` || `Col` | `Col(label, data, type?)` |-| `BarChart` | `BarChart(labels, series, variant?, xLabel?, yLabel?)` |+| `BarChart` | `BarChart(labels, series, variant?, xLabel?, yLabel?, height?)` |For full generated signatures, inspect:diff --git a/docs/content/docs/openui-lang/system-prompts.mdx b/docs/content/docs/openui-lang/system-prompts.mdxindex 87794fcd8..e4a2f3be3 100644--- a/docs/content/docs/openui-lang/system-prompts.mdx+++ b/docs/content/docs/openui-lang/system-prompts.mdx@@ -5,6 +5,18 @@ description: Generate and customize prompt instructions from your OpenUI libraryThe system prompt tells the LLM how to output valid OpenUI Lang. Generate a serialized library spec at build time, then pass that spec to `generateSystemPrompt` in your backend.+## Where the prompt is built++| Where | Use it when | Code |+| :----------- | :------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------------- |+| CLI | The prompt is the same for every request. | `npx @openuidev/cli@latest generate ./src/library.ts --out system-prompt.txt`, then send the file's text. |+| Your backend | The prompt needs tools, `editMode`, `inlineMode`, or other per-request options. | `generateSystemPrompt({ library: librarySpec, promptOptions })` |+| Gateway | Your backend calls models through Gateway. Gateway builds the prompt. | `generateSystemPrompt({ cloud: true, library: librarySpec })` |++Gateway accepts only `preamble`, `examples`, and `additionalRules` in `promptOptions`. It drops every other option: `tools`, `toolExamples`, `toolCalls`, `bindings`, `builtinFunctions`, `editMode`, and `inlineMode`. For `Query`, `Mutation`, or edit mode, build the prompt in your backend.++The sections below cover each path.+## 1. CLI (recommended for most setups)`openui generate` emits two outputs from the same library: a prebuilt prompt and a serialized library spec. Use the **spec** with `generateSystemPrompt`; retain the prompt only for static or legacy integrations.@@ -49,7 +61,7 @@ The CLI auto-detects exported `PromptOptions` (examples, rules) alongside your l## 2. `generateSystemPrompt` (recommended backend integration)-For backends that need dynamic prompts — different tools, preambles, or feature flags per request — use `generateSystemPrompt` from `@openuidev/lang-core`. It has no React dependency, so it works in any Node, Edge, or serverless backend. Import the spec emitted by the command above and build the prompt at runtime:+For backends that build the prompt per request, with different tools, preambles, or feature flags, use `generateSystemPrompt` from `@openuidev/lang-core`. It has no React dependency, so it works in any Node, Edge, or serverless backend. Import the spec emitted by the command above and build the prompt at runtime:```tsimport { generateSystemPrompt, type LibrarySpec } from "@openuidev/lang-core";@@ -59,7 +71,7 @@ const systemPrompt = generateSystemPrompt({library: librarySpec as LibrarySpec,promptOptions: {- // Tool descriptions — so the LLM knows what tools exist+ // Tool descriptions, so the LLM knows what tools existtools: myToolSpecs,// Examples showing how to use your tools with Query/Mutation@@ -78,16 +90,17 @@ const systemPrompt = generateSystemPrompt({});```-| Flag | What it enables | Default |-| ------------ | ----------------------------------------------------------------------------- | ----------------------------- |-| `toolCalls` | `Query()`, `Mutation()`, `@Run`, built-in functions, tool workflow rules | `true` if `tools` provided |-| `bindings` | `$variables`, `@Set`, `@Reset`, built-in functions, reactive filters | `true` if `toolCalls` is true |-| `editMode` | Incremental editing - LLM outputs only changed statements | `false` |-| `inlineMode` | Text + fenced code responses - LLM can answer questions without generating UI | `false` |+| Flag | What it enables | Default |+| ------------------ | -------------------------------------------------------------------------------------- | ----------------------------------- |+| `toolCalls` | `Query()`, `Mutation()`, `@Run`, built-in functions, tool workflow rules | `true` if `tools` provided |+| `bindings` | `$variables`, `@Set`, `@Reset`, built-in functions, reactive filters | `true` if `toolCalls` is true |+| `editMode` | Incremental editing: the LLM outputs only changed statements | `false` |+| `inlineMode` | Text and fenced code: the LLM can answer without generating UI | `false` |+| `builtinFunctions` | Lists the built-in functions (`@Count`, `@Sum`, ...) without `toolCalls` or `bindings` | `true` if `toolCalls` or `bindings` |### Gateway and Autofix-Pass `cloud: true` with the generated library specification to emit a configuration block for Gateway or Autofix. Gateway uses it to assemble the system prompt; Autofix uses it to validate and repair generated OpenUI Lang against your component library. The option name is retained for compatibility.+Pass `cloud: true` with the generated library specification to emit a configuration block for Gateway or Autofix. Gateway uses it to build the system prompt. Autofix uses it to validate and repair generated OpenUI Lang against your component library. The option name is kept for compatibility.For Gateway requests, `instructions` adds extra prose after the configuration block.@@ -101,7 +114,7 @@ const instructions = generateSystemPrompt({});```-Add Gateway-compatible prompt options when needed:+Gateway accepts `preamble`, `examples`, and `additionalRules`:```tsconst instructions = generateSystemPrompt({@@ -113,7 +126,7 @@ const instructions = generateSystemPrompt({See the [Generative UI Quickstart](/docs/gateway/generate-openui-lang) for the Gateway workflow, or the [Autofix API](/docs/autofix) to repair output from your existing model integration.-Built-in functions (`@Count`, `@Filter`, `@Sort`, `@Each`, etc.) are automatically included when either `toolCalls` or `bindings` is enabled. For static UI libraries without data fetching, they are omitted to keep the prompt concise.+The prompt lists the built-in functions (`@Count`, `@Filter`, `@Sort`, `@Each`, and the rest) when either `toolCalls` or `bindings` is enabled. For static UI libraries without data fetching, they are omitted to keep the prompt concise. Set `builtinFunctions: true` to include them anyway. A library's own [custom functions](/docs/openui-lang/functions#custom-functions) are always listed.### `library.prompt()` (frontend shorthand)@@ -133,7 +146,9 @@ The generated prompt includes:- Syntax rules and expression types- Component signatures (from your registered components)-- Built-in function reference (`@Count`, `@Filter`, `@Sort`, etc.) — only when `toolCalls` or `bindings` enabled+- Built-in function reference (`@Count`, `@Filter`, `@Sort`, etc.), only when `toolCalls`, `bindings`, or `builtinFunctions` is enabled+- Your [custom functions](/docs/openui-lang/functions#custom-functions), when the library has any+- The Action section with the available actions, including your [custom actions](/docs/openui-lang/actions#custom-actions), when a component has an action prop or the library has custom actions- Query/Mutation/Action workflow (if `toolCalls` enabled)- `$variable` and reactive binding rules (if `bindings` enabled)- Tool descriptions and tool examples (if `tools` provided)diff --git a/docs/content/docs/openui-lang/troubleshooting.mdx b/docs/content/docs/openui-lang/troubleshooting.mdxindex 40fe8370d..9de61a01e 100644--- a/docs/content/docs/openui-lang/troubleshooting.mdx+++ b/docs/content/docs/openui-lang/troubleshooting.mdx@@ -17,13 +17,19 @@ If you want one import path that works across `[email protected]` and `zod@4`, prefer `### Why does a prop show up as `any` in the generated prompt?-`defineComponent(...)` automatically names component schemas, but standalone helper schemas do not get a friendly prompt name by default. Tag those helper schemas explicitly.+`defineComponent(...)` names component schemas, but a standalone helper schema has no prompt name by default. For an action prop, use `action()`. It prints as `ActionExpression` in the prompt:```ts-const ActionExpression = z.any();-tagSchemaId(ActionExpression, "ActionExpression");+import { action } from "@openuidev/react-lang";++props: z.object({+ label: z.string(),+ action: action().optional(),+});```+For other helper schemas, name them with `tagSchemaId(schema, "Name")`. See [Naming reusable helper schemas](/docs/openui-lang/defining-components#naming-reusable-helper-schemas).+This only affects prompt signatures. Validation behavior stays the same.## LLM Output Issues@@ -35,7 +41,7 @@ Providing more arguments than the schema defines causes the extra arguments to b```text// Schema: z.object({ title: z.string(), subtitle: z.string() })-// Wrong — 3 args for a 2-prop schema+// Wrong: 3 args for a 2-prop schemah1 = Header("Title", "Sub", "extra")// Correct@@ -47,10 +53,10 @@ h1 = Header("Title", "Sub")The LLM may invent component names that are not in the library. The parser drops any statement that references an unknown component.```text-// Wrong — "Paragraph" is not registered+// Wrong: "Paragraph" is not registeredtext = Paragraph("Hello world")-// Correct — use the registered name+// Correct: use the registered nametext = TextContent("Hello world")```@@ -80,15 +86,21 @@ count = Count(items)count = @Count(items)```+The reverse also fails: components are called without `@`. `@Card(...)` reports `unknown-function` and evaluates to null.++### Why does nothing render?++Check `onError` for `no-root`. A response without a `root` statement renders only when one of its statements calls the library's root component. See [Entry Statement](/docs/openui-lang/specification#entry-statement).+### Query or Mutation used inline`Query` and `Mutation` must be top-level statements, not inside component arguments.```text-// Wrong — Query inside Table+// Wrong: Query inside Tabletbl = Table([Col("Title", Query("list", {}).rows.title)])-// Correct — Query as a separate statement+// Correct: Query as a separate statementdata = Query("list", {}, {rows: []})tbl = Table([Col("Title", data.rows.title)])```@@ -115,7 +127,7 @@ Use the `onError` callback. It receives structured errors from the parser, runti/>```-If you don't provide `onError`, errors are logged to `console.warn` automatically.+Without `onError`, the Renderer logs errors to `console.warn`.For LLM self-correction loops, format the errors and send them back:@@ -136,7 +148,10 @@ Error codes:- `null-required`: required prop explicitly set to null- `inline-reserved`: Query/Mutation used inline instead of top-level- `tool-not-found`: tool name not found in toolProvider (hint lists available tools)-- `parse-failed`: response produced no renderable root+- `type-mismatch`: argument does not match the prop's type or enum+- `unknown-function`: `@Name(...)` is not a built-in function, action, or library function (the call evaluates to null)+- `no-root`: no usable entry statement; with `severity: "warning"` the page still rendered from a fallback entry (see [Entry Statement](/docs/openui-lang/specification#entry-statement))+- `parse-failed`: response text produced no statements- `parse-exception`: parser crashed on malformed input- `runtime-error`: expression evaluation failed on a prop (falls back to raw value)- `render-error`: React component threw during render (falls back to last good state)diff --git a/docs/content/docs/openui-lang/whats-new.mdx b/docs/content/docs/openui-lang/whats-new.mdxnew file mode 100644index 000000000..217edb1b0--- /dev/null+++ b/docs/content/docs/openui-lang/whats-new.mdx@@ -0,0 +1,124 @@+---+title: What's New in 1.0+description: Custom functions and actions, actions without a wrapper, library.extend, and the message format.+---++OpenUI Lang 1.0 adds ways for a library to grow (custom functions, custom actions, `library.extend`) and a message format for storing responses. It also makes actions shorter to write.++## Custom functions++A library can add its own `@` functions with `defineFunction`. The model calls them like the built-ins, and the client runs them.++```ts+const percent = defineFunction({+ name: "Percent",+ description: "Formats part / total as a percentage",+ params: z.object({ part: z.number(), total: z.number().default(100) }),+ returns: z.string(),+ fn: ({ part, total }) => `${((part / total) * 100).toFixed(1)}%`,+});++const library = createLibrary({ root: "Card", components, functions: [percent] });+```++```text+share = TextContent("Share: " + @Percent(done, total))+```++Arguments are checked like component props, and a failed call evaluates to `null` instead of breaking the page. The built-in functions are now defined the same way, so their prompt lines carry types, for example `@Sum(numbers: number[]) → number`. See [Functions](/docs/openui-lang/functions#custom-functions).++## Custom actions++A library can add its own actions with `defineAction`. The model uses them like `@OpenUrl`, and your `onAction` handler receives them with typed `params`.++```text+copyBtn = Button("Copy", @CopyToClipboard(order.id))+```++```tsx+<Renderer+ library={library}+ response={response}+ onAction={(event) => {+ if (event.type === "CopyToClipboard") void navigator.clipboard.writeText(event.params.text);+ }}+/>+```++`AgentInterface` takes an `onAction` prop for the same purpose. See [Actions](/docs/openui-lang/actions#custom-actions).++## One action needs no wrapper++One action no longer needs `Action([...])`:++```text+askBtn = Button("Tell me more", @ToAssistant("Tell me more about this order"))+saveBtn = Button("Save", Action([@Run(save), @Run(orders), @Reset($note)]))+```++Several actions still go in `Action([...])`. The prompt teaches both forms. See [Actions](/docs/openui-lang/actions).++## Context for `@ToAssistant`++The second argument of `@ToAssistant` can be any value, and the host receives it unchanged in `event.params.context`:++```text+approveBtn = Button("Approve", @ToAssistant("Approve this order", {orderId: 42}))+```++## Action props++- `action()` returns the schema for an action prop: `action: action().optional()`. It replaces `tagSchemaId(z.any(), "ActionExpression")`.+- In the JSON Schema, an action prop is `{"$ref": "#/$defs/ActionExpression"}`, like a component slot.+- A prop can name the actions it takes, for example `z.union([copyToClipboard.ref, steps.OpenUrl.ref])`, printed as `@CopyToClipboard | @OpenUrl`. This shapes the prompt and the JSON Schema only. The runtime does not enforce it yet.++See [Actions](/docs/openui-lang/actions#action-props-in-your-components).++## `library.extend`++Derive a library from an existing one. Add, override, or remove components, and add functions and actions:++```ts+const shopLibrary = openuiChatLibrary.extend({+ components: {+ add: [{ component: ProductCard, slots: ["Card"] }],+ override: [CodeBlock],+ remove: ["RadarChart"],+ },+ functions: { add: [formatCurrency] },+ actions: { add: [addToCart] },+});+```++The derived library has no `id`. Create it once at module scope. See [Extending a library](/docs/openui-lang/defining-components#extending-a-library).++## Entry rule++The entry is the statement named `root`. Without one, the first statement that calls the library's root component is used, with a `no-root` warning. See [Entry Statement](/docs/openui-lang/specification#entry-statement).++On the server, pass the root component name to the parser so this fallback works:++```ts+const parser = createParser(library.toJSONSchema(), library.root);+```++`createStreamingParser` takes the same second argument. Without it, a program with no `root` statement reports `no-root` and renders nothing.++## Message format++`buildMessage` and `parseMessage` read and write responses wrapped in `]]>openui:` marker lines, with optional context such as form values. The `Renderer` accepts a stored message as `response`.++```text+]]>openui:content+root = Card([title])+title = TextContent("Order 42")+]]>openui:context+{"formState":{"note":"rush"}}+]]>openui:end+```++See [Message Protocol](/docs/openui-lang/message-protocol).++## Vue, Svelte, and Angular++`@openuidev/vue-lang`, `@openuidev/svelte-lang`, and `@openuidev/angular-lang` stay on 0.4. Keep `@openuidev/lang-core` at `^0.4` with them. The 1.0 language features (actions without a wrapper, custom functions, custom actions) need the React renderer for now.