The Open Standard for Generative UI
Add openui-lang v0.5: parser, runtime, Query, $bindings (#385)
Aditya-thesys7c4e68e8a859
diff --git a/.gitignore b/.gitignoreindex f1718dadf..ba9580689 100644--- a/.gitignore+++ b/.gitignore@@ -31,6 +31,11 @@ CLAUDE.local.mdnode_modules.pnpm-store/+# Environment+.env+.env.local+.env*.local+# Build outputdist.next@@ -45,4 +50,4 @@ typingsclean-install.shlint-fix.sh-draft/\ No newline at end of file+draft/diff --git a/docs/app/(home)/components/Button/Button.tsx b/docs/app/(home)/components/Button/Button.tsxindex 18779c396..3653a5613 100644--- a/docs/app/(home)/components/Button/Button.tsx+++ b/docs/app/(home)/components/Button/Button.tsx@@ -2,13 +2,7 @@import { Check, Copy } from "lucide-react";import Link from "next/link";-import {- useEffect,- useRef,- useState,- type ButtonHTMLAttributes,- type ReactNode,-} from "react";+import { useEffect, useRef, useState, type ButtonHTMLAttributes, type ReactNode } from "react";import styles from "./Button.module.css";type ButtonType = ButtonHTMLAttributes<HTMLButtonElement>["type"];@@ -38,20 +32,16 @@ function CopyStatusIcon({return (<span className={[styles.copyIconFrame, frameClassName].filter(Boolean).join(" ")}><span- className={[- styles.iconLayer,- copied ? styles.iconHidden : styles.iconVisible,- className,- ].filter(Boolean).join(" ")}+ className={[styles.iconLayer, copied ? styles.iconHidden : styles.iconVisible, className]+ .filter(Boolean)+ .join(" ")}><CopyIcon color={color} /></span><span- className={[- styles.iconLayer,- copied ? styles.iconVisible : styles.iconHidden,- className,- ].filter(Boolean).join(" ")}+ className={[styles.iconLayer, copied ? styles.iconVisible : styles.iconHidden, className]+ .filter(Boolean)+ .join(" ")}><CheckIcon color={color} /></span>@@ -110,11 +100,7 @@ export function ClipboardCommandButton({const icon = (<span className={iconContainerClassName || undefined}>- <CopyStatusIcon- copied={copied}- frameClassName={iconFrameClassName}- color={copyIconColor}- />+ <CopyStatusIcon copied={copied} frameClassName={iconFrameClassName} color={copyIconColor} /></span>);@@ -155,12 +141,7 @@ export function PillLink({if (external) {return (- <a- href={href}- target="_blank"- rel="noopener noreferrer"- className={className}- >+ <a href={href} target="_blank" rel="noopener noreferrer" className={className}>{content}</a>);diff --git a/docs/app/(home)/components/FeatureList/FeatureList.module.css b/docs/app/(home)/components/FeatureList/FeatureList.module.cssindex 88e8ed1e4..b433438dd 100644--- a/docs/app/(home)/components/FeatureList/FeatureList.module.css+++ b/docs/app/(home)/components/FeatureList/FeatureList.module.css@@ -5,14 +5,15 @@flex-shrink: 0;align-items: center;justify-content: center;- border: 1px solid var(--home-border-default);- border-radius: var(--home-radius-pill);- background: var(--home-color-surface);+ border: 1px solid var(--openui-border-interactive);+ border-radius: var(--openui-radius-full);+ background: var(--openui-foreground);}.featureIconSvg {height: 18px;width: 18px;+ color: var(--openui-text-neutral-primary);}.desktopList {@@ -44,17 +45,17 @@}.desktopTitle {- color: #000;+ color: var(--openui-text-neutral-primary);}.desktopDescription {text-align: right;- color: var(--home-color-text-muted);+ color: var(--openui-text-neutral-secondary);}.mobileRow {display: flex;- align-items: center;+ align-items: flex-start;gap: 0.375rem;padding-block: 1rem;}@@ -75,12 +76,12 @@.mobileTitle {font-weight: 500;line-height: 1.25;- color: #000;+ color: var(--openui-text-neutral-primary);}.mobileDescription {line-height: 1.4;- color: var(--home-color-text-muted);+ color: var(--openui-text-neutral-secondary);}.divider {@@ -90,11 +91,11 @@}.desktopDivider {- background: var(--home-border-default);+ background: var(--openui-border-interactive);}.mobileDivider {- background: var(--home-color-surface-muted);+ background: var(--openui-highlight-strong);}@media (min-width: 1024px) {diff --git a/docs/app/(home)/components/FeatureList/FeatureList.tsx b/docs/app/(home)/components/FeatureList/FeatureList.tsxindex 5040a3079..1af38c8cf 100644--- a/docs/app/(home)/components/FeatureList/FeatureList.tsx+++ b/docs/app/(home)/components/FeatureList/FeatureList.tsx@@ -19,7 +19,7 @@ function FeatureIcon({ path, index }: { path: string; index: number }) {<div className={styles.featureIcon}><svg className={styles.featureIconSvg} fill="none" viewBox="0 0 18 18"><g clipPath={`url(#${clipId})`}>- <path d={path} fill="black" />+ <path d={path} fill="currentColor" /></g><defs><clipPath id={clipId}>@@ -31,13 +31,7 @@ function FeatureIcon({ path, index }: { path: string; index: number }) {);}-function DesktopFeatureRow({- item,- index,-}: {- item: FeatureListItem;- index: number;-}) {+function DesktopFeatureRow({ item, index }: { item: FeatureListItem; index: number }) {return (<div className={styles.desktopRow}><div className={styles.desktopRowLead}>diff --git a/docs/app/(home)/components/StackChip/StackChip.module.css b/docs/app/(home)/components/StackChip/StackChip.module.cssnew file mode 100644index 000000000..c74fa6daf--- /dev/null+++ b/docs/app/(home)/components/StackChip/StackChip.module.css@@ -0,0 +1,134 @@+.chip {+ display: inline-flex;+ min-height: 2.875rem;+ align-items: center;+ gap: 0.625rem;+ padding: 12px 24px 12px 12px;+ border: 1px solid var(--openui-border-default);+ border-radius: var(--openui-radius-full);+ background: var(--openui-foreground);+}++.chipBlurred {+ opacity: 0.52;+ filter: blur(2px);+ pointer-events: none;+ user-select: none;+ -webkit-mask-image: linear-gradient(90deg, #000 45%, rgb(0 0 0 / 0.08) 100%);+ mask-image: linear-gradient(90deg, #000 45%, rgb(0 0 0 / 0.08) 100%);+}++.badge {+ display: flex;+ height: 1.625rem;+ width: 1.625rem;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;+ overflow: hidden;+ border-radius: var(--openui-radius-full);+}++.badgeOpenUi {+ background: var(--openui-highlight-strong);+ color: var(--openui-text-neutral-primary);+}++.badgeWhite {+ background: var(--openui-text-white);+}++.badgeBlack {+ background: var(--openui-text-black);+}++.badgeAnthropic {+ background: #d4a574;+}++.badgeMistral {+ background: #ff7000;+}++.badgeDeepSeek {+ background: #4d6bfe;+}++.badgeLangChain {+ background: #1c3144;+}++.badgeCrewAi {+ background: #ff4b4b;+}++.badgeGoogle {+ background: #4285f4;+}++.badgeMaterial {+ background: #a485ff;+}++.badgeDaisyUi {+ background: #f472b6;+}++.badgeBaseUi {+ background: var(--openui-highlight-strong);+}++.badgeMore {+ background: var(--openui-highlight-subtle);+}++.badgeWithBorder {+ border: 1px solid var(--openui-border-interactive);+}++.badgeImage,+.iconSvg {+ display: block;+ height: 1rem;+ width: 1rem;+ object-fit: contain;+}++.mascotSvg {+ display: block;+ height: 1rem;+ width: 1rem;+ transform: rotate(-16.49deg);+}++.moreIcon {+ font-family: "Inter", sans-serif;+ font-size: 1rem;+ font-weight: 600;+ line-height: 1;+ color: var(--openui-text-neutral-tertiary);+}++.badgeText {+ font-family: "Inter", sans-serif;+ font-size: 0.75rem;+ font-weight: 700;+ line-height: 1;+ color: var(--openui-text-neutral-primary);+}++.chipLabel {+ font-family: "Inter", sans-serif;+ font-size: 0.95rem;+ font-weight: 500;+ line-height: 1;+ white-space: nowrap;+ color: var(--openui-text-neutral-primary);+}++@media (min-width: 1024px) {+ .chip {+ min-height: 3rem;+ padding-inline: 1rem;+ }+}diff --git a/docs/app/(home)/components/StackChip/StackChip.tsx b/docs/app/(home)/components/StackChip/StackChip.tsxnew file mode 100644index 000000000..a6c469a02--- /dev/null+++ b/docs/app/(home)/components/StackChip/StackChip.tsx@@ -0,0 +1,149 @@+import mascotSvgPaths from "@/imports/svg-10waxq0xyc";+import { useId } from "react";+import styles from "./StackChip.module.css";++interface StackChipBase {+ name: string;+ badgeClassName?: string;+ isBlurred?: boolean;+}++interface ImageStackChip extends StackChipBase {+ iconKind: "image";+ slug?: string;+ localSrc?: string;+ iconColor: string;+}++interface VectorStackChip extends StackChipBase {+ iconKind: "vector";+ iconViewBox: string;+ iconPath: string;+ iconFill: string;+ clipId?: string;+ clipSize?: string;+}++interface MascotStackChip extends StackChipBase {+ iconKind: "mascot";+}++interface TextStackChip extends StackChipBase {+ iconKind: "text";+ iconText: string;+}++interface MoreStackChip extends StackChipBase {+ iconKind: "more";+}++export type StackChipItem =+ | ImageStackChip+ | VectorStackChip+ | MascotStackChip+ | TextStackChip+ | MoreStackChip;++function ChipIcon({ item }: { item: StackChipItem }) {+ const iconId = useId();++ switch (item.iconKind) {+ case "image": {+ const imgSrc = item.localSrc ?? `https://cdn.simpleicons.org/${item.slug}/${item.iconColor}`;+ return (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={imgSrc} alt="" width={16} height={16} className={styles.badgeImage} />+ );+ }+ case "vector": {+ const clipPathId = item.clipId ? `${item.clipId}-${iconId}` : undefined;++ return clipPathId ? (+ <svg className={styles.iconSvg} fill="none" viewBox={item.iconViewBox} aria-hidden="true">+ <g clipPath={`url(#${clipPathId})`}>+ <path d={item.iconPath} fill={item.iconFill} />+ </g>+ <defs>+ <clipPath id={clipPathId}>+ <rect fill="white" height={item.clipSize} width={item.clipSize} />+ </clipPath>+ </defs>+ </svg>+ ) : (+ <svg className={styles.iconSvg} fill="none" viewBox={item.iconViewBox} aria-hidden="true">+ <path d={item.iconPath} fill={item.iconFill} />+ </svg>+ );+ }+ case "mascot":+ return (+ <svg+ className={styles.mascotSvg}+ fill="none"+ viewBox="0 0 37.6937 30.558"+ aria-hidden="true"+ >+ <path+ d={mascotSvgPaths.p581fa00}+ fill="currentColor"+ stroke="currentColor"+ strokeWidth="0.346875"+ />+ <path d={mascotSvgPaths.p3ea20780} fill="currentColor" />+ <path+ d={mascotSvgPaths.pf52e280}+ fill="currentColor"+ stroke="currentColor"+ strokeWidth="0.346875"+ />+ <path+ d={mascotSvgPaths.pa685a00}+ fill="currentColor"+ stroke="currentColor"+ strokeWidth="0.346875"+ />+ <path d={mascotSvgPaths.p371d6000} fill="currentColor" />+ <path d={mascotSvgPaths.p1cace000} fill="currentColor" />+ <path+ d={mascotSvgPaths.p1d3dca00}+ fill="currentColor"+ stroke="currentColor"+ strokeWidth="0.346875"+ />+ <path+ d={mascotSvgPaths.p11103600}+ fill="currentColor"+ stroke="currentColor"+ strokeWidth="0.346875"+ />+ </svg>+ );+ case "text":+ return (+ <span className={styles.badgeText} aria-hidden="true">+ {item.iconText}+ </span>+ );+ case "more":+ return (+ <span className={styles.moreIcon} aria-hidden="true">+ ++ </span>+ );+ }+}++export function StackChip({ item }: { item: StackChipItem }) {+ const chipClassName = item.isBlurred ? `${styles.chip} ${styles.chipBlurred}` : styles.chip;++ return (+ <div className={chipClassName} aria-hidden={item.isBlurred || undefined}>+ <div className={`${styles.badge} ${item.badgeClassName ?? ""}`.trim()}>+ <ChipIcon item={item} />+ </div>+ <span className={styles.chipLabel}>{item.name}</span>+ </div>+ );+}++export { styles as stackChipStyles };diff --git a/docs/app/(home)/components/StepsAccordion/StepsAccordion.module.css b/docs/app/(home)/components/StepsAccordion/StepsAccordion.module.cssindex e73b176b8..dd0a62eaa 100644--- a/docs/app/(home)/components/StepsAccordion/StepsAccordion.module.css+++ b/docs/app/(home)/components/StepsAccordion/StepsAccordion.module.css@@ -1,8 +1,8 @@.card {- border: 1px solid var(--home-border-subtle);+ border: 1px solid var(--openui-border-interactive);border-radius: 18px;- background: var(--home-color-surface);- box-shadow: var(--home-shadow-elevated);+ background: var(--openui-foreground);+ box-shadow: var(--openui-shadow-l);}.desktopSteps {@@ -22,18 +22,18 @@flex-shrink: 0;align-items: center;justify-content: center;- border: 1px solid var(--home-border-default);- border-radius: var(--home-radius-pill);+ border: 1px solid var(--openui-border-interactive);+ border-radius: var(--openui-radius-full);}.stepBadgeActive {- background: var(--home-color-surface-inverse);- color: #fff;+ background: var(--openui-inverted-background);+ color: var(--openui-text-accent-primary);}.stepBadgeInactive {- background: var(--home-color-surface);- color: var(--home-color-text-primary);+ background: var(--openui-foreground);+ color: var(--openui-text-neutral-primary);}.stepBadgeLabel {@@ -46,7 +46,7 @@.divider {height: 1px;width: 100%;- background: var(--home-color-surface-muted);+ background: var(--openui-highlight-strong);}.stepDetails {@@ -59,7 +59,7 @@font-family: "Inter Display", sans-serif;font-size: 18px;line-height: 1.2;- color: var(--home-color-text-muted);+ color: var(--openui-text-neutral-secondary);}.stepDetailsTitle {@@ -131,7 +131,7 @@font-size: 24px;font-weight: 500;line-height: 1.25;- color: #000;+ color: var(--openui-text-neutral-primary);}.desktopStepPreview {@@ -158,7 +158,7 @@font-size: 16px;font-weight: 500;line-height: 1.25;- color: #000;+ color: var(--openui-text-neutral-primary);}.mobileStepPanel {diff --git a/docs/app/(home)/components/TweetWall/TweetWall.module.css b/docs/app/(home)/components/TweetWall/TweetWall.module.cssnew file mode 100644index 000000000..cc0d9ac3d--- /dev/null+++ b/docs/app/(home)/components/TweetWall/TweetWall.module.css@@ -0,0 +1,117 @@+.root {+ --tweet-wall-height: 48rem;+ position: relative;+ width: 100%;+ height: var(--tweet-wall-height);+ min-height: var(--tweet-wall-height);+ overflow: hidden;+ --tweet-wall-mask: linear-gradient(+ to bottom,+ transparent 0,+ #000 4.5rem,+ #000 calc(100% - 4.5rem),+ transparent 100%+ );+ -webkit-mask-image: var(--tweet-wall-mask);+ mask-image: var(--tweet-wall-mask);+}++.columns {+ display: flex;+ gap: 1rem;+ align-items: stretch;+ justify-content: center;+ height: var(--tweet-wall-height);+ padding-block: 0.25rem;+}++.columnViewport {+ position: relative;+ flex: 1 1 0;+ min-width: 0;+ overflow: hidden;+}++.columnTrack {+ display: flex;+ flex-direction: column;+ gap: 1rem;+ width: 100%;+ will-change: transform;+ transform: translate3d(0, var(--loop-start, 0px), 0);+ animation-name: tweetWallLoop;+ animation-duration: var(--loop-duration, 32s);+ animation-timing-function: linear;+ animation-iteration-count: infinite;+ animation-fill-mode: both;+ animation-play-state: paused;+}++.embedSlot {+ width: 100%;+ flex-shrink: 0;+ display: flex;+ justify-content: center;+ min-height: 12rem;+ border-radius: 16px;+ overflow: hidden;+}++.embedSlot[data-embedded="pending"] {+ background: var(--openui-foreground);+ border: 1px solid var(--openui-border-default);+ box-shadow: var(--openui-shadow-m);+}++.embedSlot[data-embedded="error"] {+ min-height: 0;+}++.embedSlot :global(iframe) {+ width: 100% !important;+ max-width: 100% !important;+ border-radius: 12px !important;+}++.rootReady .columnTrack {+ animation-play-state: running;+}++/* --- Reduced motion --- */++.staticGrid {+ display: grid;+ gap: 1rem;+ grid-template-columns: 1fr;+ padding-block: 0.5rem;+}++.staticCell {+ min-width: 0;+}++@media (min-width: 640px) {+ .staticGrid {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ }+}++@media (min-width: 1024px) {+ .columns {+ gap: 1.25rem;+ }++ .staticGrid {+ grid-template-columns: repeat(3, minmax(0, 1fr));+ }+}++@keyframes tweetWallLoop {+ from {+ transform: translate3d(0, var(--loop-start, 0px), 0);+ }++ to {+ transform: translate3d(0, calc(var(--loop-start, 0px) - var(--loop-distance, 0px)), 0);+ }+}diff --git a/docs/app/(home)/components/TweetWall/TweetWall.tsx b/docs/app/(home)/components/TweetWall/TweetWall.tsxnew file mode 100644index 000000000..5e5ba4a0b--- /dev/null+++ b/docs/app/(home)/components/TweetWall/TweetWall.tsx@@ -0,0 +1,230 @@+"use client";++import Script from "next/script";+import { useEffect, useLayoutEffect, useRef, useState } from "react";+import { HOME_TWEETS, type HomeTweetEmbed } from "../../data/home-tweet-embeds";+import styles from "./TweetWall.module.css";++const MARQUEE_COPIES = 2;+const DESKTOP_COLUMN_COUNT = 3;+const MOBILE_COLUMN_COUNT = 1;+const MOBILE_COLUMN_DURATION = 40;+const COLUMN_DURATIONS = [30, 36, 30] as const;+const COLUMN_PHASES = [0, 0.28, 0.14] as const;+const EMBED_WIDTH = 360;++function loadTwitterWidgets(root: HTMLElement | null) {+ if (!root) return;+ window.twttr?.widgets?.load(root);+}++function splitIntoColumns(items: HomeTweetEmbed[], columnCount: number): HomeTweetEmbed[][] {+ const cols: HomeTweetEmbed[][] = Array.from({ length: columnCount }, () => []);+ items.forEach((item, i) => {+ cols[i % columnCount]!.push(item);+ });+ return cols;+}++function TweetEmbed({+ tweetId,+ conversation = "none",+}: {+ tweetId: string;+ conversation?: "all" | "none";+}) {+ return (+ <div className={styles.embedSlot} data-tweet-id={tweetId} data-conversation={conversation} />+ );+}++export function TweetWall() {+ const rootRef = useRef<HTMLDivElement>(null);+ const columnTracksRef = useRef<(HTMLDivElement | null)[]>([]);++ const [scriptReady, setScriptReady] = useState(false);+ const [prefersReducedMotion, setPrefersReducedMotion] = useState(false);+ const [columnCount, setColumnCount] = useState(DESKTOP_COLUMN_COUNT);+ const [isWallReady, setIsWallReady] = useState(false);+ const embedTheme = "light";++ useEffect(() => {+ const mqReduce = window.matchMedia("(prefers-reduced-motion: reduce)");+ const mqDesktop = window.matchMedia("(min-width: 900px)");++ const updateReduce = () => setPrefersReducedMotion(mqReduce.matches);+ const updateColumns = () => {+ setColumnCount(mqDesktop.matches ? DESKTOP_COLUMN_COUNT : MOBILE_COLUMN_COUNT);+ };++ updateReduce();+ updateColumns();++ mqReduce.addEventListener("change", updateReduce);+ mqDesktop.addEventListener("change", updateColumns);++ return () => {+ mqReduce.removeEventListener("change", updateReduce);+ mqDesktop.removeEventListener("change", updateColumns);+ };+ }, []);++ const columns = splitIntoColumns(HOME_TWEETS, columnCount);++ useEffect(() => {+ if (window.twttr?.widgets?.createTweet) {+ setScriptReady(true);+ }+ }, []);++ useEffect(() => {+ if (!scriptReady || !rootRef.current) return;++ let cancelled = false;+ const widgets = window.twttr?.widgets;+ if (!widgets?.createTweet) return;+ const createTweet = widgets.createTweet;++ const slots = Array.from(rootRef.current.querySelectorAll<HTMLElement>("[data-tweet-id]"));+ const shouldRehydrate = slots.some(+ (slot) => slot.dataset.embedded !== "true" || slot.dataset.theme !== embedTheme,+ );++ if (!shouldRehydrate) {+ setIsWallReady(true);+ return;+ }++ setIsWallReady(false);++ async function hydrateEmbeds() {+ await Promise.allSettled(+ slots.map(async (slot) => {+ const needsThemeRefresh = slot.dataset.theme !== embedTheme;+ const alreadyEmbedded = slot.dataset.embedded === "true";+ if (alreadyEmbedded && !needsThemeRefresh) return;++ const tweetId = slot.dataset.tweetId;+ if (!tweetId) return;++ slot.dataset.embedded = "pending";+ slot.dataset.theme = embedTheme;+ slot.innerHTML = "";++ try {+ await createTweet(tweetId, slot, {+ align: "center",+ conversation: slot.dataset.conversation === "all" ? "all" : "none",+ dnt: true,+ theme: embedTheme,+ width: EMBED_WIDTH,+ });+ slot.dataset.embedded = "true";+ } catch {+ slot.dataset.embedded = "error";+ }+ }),+ );++ if (cancelled) return;+ requestAnimationFrame(() => {+ requestAnimationFrame(() => {+ if (!cancelled) {+ loadTwitterWidgets(rootRef.current);+ setIsWallReady(true);+ }+ });+ });+ }++ void hydrateEmbeds();++ return () => {+ cancelled = true;+ };+ }, [columnCount, embedTheme, prefersReducedMotion, scriptReady]);++ useLayoutEffect(() => {+ if (prefersReducedMotion || !scriptReady) return;++ const observers = columnTracksRef.current.slice(0, columnCount).map((track, index) => {+ if (!track) return null;++ const updateMetrics = () => {+ const singleHeight = track.scrollHeight / MARQUEE_COPIES;+ if (singleHeight <= 0) return;+ const duration =+ columnCount === MOBILE_COLUMN_COUNT+ ? MOBILE_COLUMN_DURATION+ : (COLUMN_DURATIONS[index] ?? 32);++ track.style.setProperty("--loop-distance", `${singleHeight}px`);+ track.style.setProperty("--loop-duration", `${duration}s`);+ track.style.setProperty(+ "--loop-start",+ `${-(singleHeight * (COLUMN_PHASES[index] ?? 0))}px`,+ );+ };++ updateMetrics();++ const observer = new ResizeObserver(updateMetrics);+ observer.observe(track);+ return observer;+ });++ return () => {+ observers.forEach((observer) => observer?.disconnect());+ };+ }, [columnCount, prefersReducedMotion, scriptReady]);++ const staticGrid = (+ <div className={styles.staticGrid} role="list" aria-label="What people are saying on X">+ {HOME_TWEETS.map((tweet, index) => (+ <div key={`static-${index}`} className={styles.staticCell} role="listitem">+ <TweetEmbed tweetId={tweet.id} conversation={tweet.conversation} />+ </div>+ ))}+ </div>+ );++ return (+ <>+ <Script+ id="twitter-widgets-js"+ src="https://platform.twitter.com/widgets.js"+ strategy="lazyOnload"+ onLoad={() => setScriptReady(true)}+ />++ <div ref={rootRef} className={`${styles.root} ${isWallReady ? styles.rootReady : ""}`}>+ {prefersReducedMotion ? (+ staticGrid+ ) : (+ <div className={styles.columns} role="region" aria-label="Scrolling posts from X">+ {columns.map((colHtml, colIndex) => (+ <div key={colIndex} className={styles.columnViewport}>+ <div+ ref={(el) => {+ columnTracksRef.current[colIndex] = el;+ }}+ className={styles.columnTrack}+ >+ {Array.from({ length: MARQUEE_COPIES }).flatMap((_, copy) =>+ colHtml.map((tweet, rowIndex) => (+ <TweetEmbed+ key={`c${colIndex}-r${rowIndex}-copy${copy}`}+ tweetId={tweet.id}+ conversation={tweet.conversation}+ />+ )),+ )}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ </>+ );+}diff --git a/docs/app/(home)/data/home-tweet-embeds.ts b/docs/app/(home)/data/home-tweet-embeds.tsnew file mode 100644index 000000000..da5ef88f0--- /dev/null+++ b/docs/app/(home)/data/home-tweet-embeds.ts@@ -0,0 +1,17 @@+export type HomeTweetEmbed = {+ id: string;+ conversation?: "all" | "none";+};++/** Official X tweet IDs used to render real embeds via widgets.createTweet(). */+export const HOME_TWEETS: HomeTweetEmbed[] = [+ { id: "2031845364286783776", conversation: "none" },+ { id: "2031989015147397122", conversation: "none" },+ { id: "2031891607394664677", conversation: "none" },+ { id: "2034082798051443052", conversation: "none" },+ { id: "2034668122691735612", conversation: "none" },+ { id: "2034668644115107891", conversation: "none" },+ { id: "2039548793960681815", conversation: "none" },+ { id: "2032387346616758375", conversation: "none" },+ { id: "2034284259805176222", conversation: "none" },+];diff --git a/docs/app/(home)/globals.css b/docs/app/(home)/globals.cssindex 4a06e60bc..5bc59cf8d 100644--- a/docs/app/(home)/globals.css+++ b/docs/app/(home)/globals.css@@ -1,20 +1,20 @@.homeTheme {- --home-color-text-primary: #000;- --home-color-text-inverse: #fff;- --home-color-text-muted: rgb(0 0 0 / 40%);- --home-color-text-subtle: rgb(0 0 0 / 30%);- --home-color-text-secondary: rgb(0 0 0 / 60%);- --home-color-surface: #fff;- --home-color-surface-inverse: #000;- --home-color-surface-soft: rgb(0 0 0 / 5%);- --home-color-surface-muted: rgb(0 0 0 / 8%);- --home-color-surface-subtle: rgb(0 0 0 / 4%);- --home-border-soft: rgb(0 0 0 / 6%);- --home-border-subtle: rgb(0 0 0 / 8%);- --home-border-default: rgb(0 0 0 / 10%);- --home-shadow-elevated: 0 1px 3px 0 rgb(22 34 51 / 8%), 0 12px 24px 0 rgb(22 34 51 / 4%);- --home-shadow-soft-card: 0 1px 2px 0 rgb(22 34 51 / 4%), 0 8px 16px 0 rgb(22 34 51 / 4%);- --home-shadow-panel: 0 10px 20px rgb(0 0 0 / 10%);+ --home-color-text-primary: var(--text-neutral-primary);+ --home-color-text-inverse: var(--text-accent-primary);+ --home-color-text-muted: var(--text-neutral-secondary);+ --home-color-text-subtle: var(--text-neutral-tertiary);+ --home-color-text-secondary: var(--text-neutral-secondary);+ --home-color-surface: var(--foreground);+ --home-color-surface-inverse: var(--inverted-background);+ --home-color-surface-soft: var(--highlight);+ --home-color-surface-muted: var(--highlight-strong);+ --home-color-surface-subtle: var(--highlight-subtle);+ --home-border-soft: var(--border-default);+ --home-border-subtle: var(--border-interactive);+ --home-border-default: var(--border-interactive);+ --home-shadow-elevated: var(--shadow-l);+ --home-shadow-soft-card: var(--shadow-m);+ --home-shadow-panel: var(--shadow-xl);--home-radius-pill: 999px;--home-pill-padding-inline: 1.25rem;--home-section-padding-inline: 1.25rem;diff --git a/docs/app/(home)/layout.tsx b/docs/app/(home)/layout.tsxindex 9fa9c2bc7..6b9ff9f04 100644--- a/docs/app/(home)/layout.tsx+++ b/docs/app/(home)/layout.tsx@@ -1,11 +1,11 @@-import "./globals.css";+import { WebsiteThemeProvider } from "@/components/website-theme-provider";import { Navbar } from "./sections/Navbar/Navbar";export default function Layout({ children }: { children: React.ReactNode }) {return (- <div className="homeTheme">+ <WebsiteThemeProvider forcedTheme="light"><Navbar />{children}- </div>+ </WebsiteThemeProvider>);}diff --git a/docs/app/(home)/page.module.css b/docs/app/(home)/page.module.cssindex 70fa2ab41..7535425e6 100644--- a/docs/app/(home)/page.module.css+++ b/docs/app/(home)/page.module.css@@ -3,12 +3,17 @@min-height: 100vh;width: 100%;overflow-x: clip;- background: #fff;+ background: var(--openui-foreground);+}++.heroShell {+ background: var(--openui-foreground);}.contentSection {position: relative;margin-top: 4rem;+ background: var(--openui-background);}.contentShell {@@ -16,13 +21,7 @@flex-direction: column;gap: 7.5rem;padding-block: 5rem;- background: rgb(0 0 0 / 4%);-}--.compatibilityStack {- display: flex;- flex-direction: column;- gap: 2rem;+ background: var(--openui-background);}@media (min-width: 768px) {@@ -35,8 +34,4 @@.contentSection {margin-top: 6rem;}-- .compatibilityStack {- gap: 2.5rem;- }}diff --git a/docs/app/(home)/page.tsx b/docs/app/(home)/page.tsxindex 5c8dc74b7..01b668ad2 100644--- a/docs/app/(home)/page.tsx+++ b/docs/app/(home)/page.tsx@@ -1,4 +1,4 @@-import { BuildChatSection } from "./sections/BuildChatSection/BuildChatSection";+import styles from "./page.module.css";import { CompatibilitySection } from "./sections/CompatibilitySection/CompatibilitySection";import { FeaturesSection } from "./sections/FeaturesSection/FeaturesSection";import { Footer } from "./sections/Footer/Footer";@@ -7,25 +7,23 @@ import { HeroSection } from "./sections/HeroSection/HeroSection";import { PossibilitiesSection } from "./sections/PossibilitiesSection/PossibilitiesSection";import { ShiroMascot } from "./sections/ShiroMascot/ShiroMascot";import { StepsSection } from "./sections/StepsSection/StepsSection";-import { UILibrariesSection } from "./sections/UILibrariesSection/UILibrariesSection";-import styles from "./page.module.css";+import { TweetWallSection } from "./sections/TweetWallSection/TweetWallSection";export default function HomePage() {return (<div className={styles.page}>- <HeroSection />- <ShiroMascot />- <StepsSection />+ <div className={styles.heroShell}>+ <HeroSection />+ <ShiroMascot />+ <StepsSection />+ </div><div className={styles.contentSection}><GradientDivider direction="down" /><div className={styles.contentShell}><PossibilitiesSection />- <div className={styles.compatibilityStack}>- <UILibrariesSection />- <CompatibilitySection />- </div>+ <CompatibilitySection /><FeaturesSection />- <BuildChatSection />+ <TweetWallSection /></div><GradientDivider direction="up" /></div>diff --git a/docs/app/(home)/sections/BuildChatSection/BuildChatSection.module.css b/docs/app/(home)/sections/BuildChatSection/BuildChatSection.module.cssindex a4f9a3a51..b77083c56 100644--- a/docs/app/(home)/sections/BuildChatSection/BuildChatSection.module.css+++ b/docs/app/(home)/sections/BuildChatSection/BuildChatSection.module.css@@ -1,6 +1,6 @@.section {width: 100%;- padding-inline: var(--home-section-padding-inline);+ padding-inline: 1.25rem;}.container {@@ -12,16 +12,16 @@position: relative;overflow: hidden;border-radius: 32px;- background: var(--home-color-surface);+ background: var(--openui-foreground);}.overlay {position: absolute;inset: 0;pointer-events: none;- border: 1px solid var(--home-border-default);+ border: 1px solid var(--openui-border-interactive);border-radius: 32px;- box-shadow: var(--home-shadow-elevated);+ box-shadow: var(--openui-shadow-l);}.content {@@ -50,7 +50,7 @@font-size: 32px;font-weight: 600;line-height: 1.2;- color: var(--home-color-text-primary);+ color: var(--openui-text-neutral-primary);margin: auto;text-align: center;}@@ -63,7 +63,7 @@font-family: "Inter Display", sans-serif;font-size: 18px;line-height: 1.4;- color: var(--home-color-text-muted);+ color: var(--openui-text-neutral-secondary);}.ctaWrap {@@ -82,10 +82,10 @@justify-content: center;gap: 0.625rem;height: 3rem;- padding-inline: var(--home-pill-padding-inline);+ padding-inline: 1.25rem;border: 0;border-radius: 999px;- background: var(--home-color-surface-inverse);+ background: var(--openui-inverted-background);cursor: pointer;transition: transform 0.2s ease;}@@ -102,40 +102,26 @@font-size: 12px;font-weight: 400;line-height: 1.5rem;- color: var(--home-color-text-inverse);-}--.mediaColumn {- width: 100%;- flex-shrink: 0;-}--.dashboardImage {- width: 100%;- height: auto;- border-radius: 12px;- object-fit: contain;+ color: var(--openui-text-accent-primary);}@media (min-width: 1024px) {- .content {- flex-direction: row;- gap: 0;+ .section {+ padding-inline: 2rem;}.copyColumn {min-height: 0;- padding:16px;+ padding: 16px;}-.title {max-width: 430px;font-family: "Inter", sans-serif;font-size: 36px;font-weight: 600;line-height: 1.2;- color: var(--home-color-text-primary);+ color: var(--openui-text-neutral-primary);margin: 4px 0 0 4px;text-align: left;}@@ -154,8 +140,4 @@.ctaLabel {font-size: 16px;}-- .mediaColumn {- width: 600px;- }}diff --git a/docs/app/(home)/sections/BuildChatSection/BuildChatSection.tsx b/docs/app/(home)/sections/BuildChatSection/BuildChatSection.tsxindex fb3a6f652..9fe17319b 100644--- a/docs/app/(home)/sections/BuildChatSection/BuildChatSection.tsx+++ b/docs/app/(home)/sections/BuildChatSection/BuildChatSection.tsx@@ -1,7 +1,5 @@"use client";-import dashboardImg from "@/public/images/home/d67b5e94653944c1d0d4998c6b169c37f98060ad.png";-import Image from "next/image";import { ClipboardCommandButton } from "../../components/Button/Button";import styles from "./BuildChatSection.module.css";@@ -21,25 +19,12 @@ function CtaButton() {className={styles.ctaButton}iconPosition="start">- <span className={styles.ctaLabel}>- npx @openuidev/cli@latest create- </span>+ <span className={styles.ctaLabel}>npx @openuidev/cli@latest create</span></ClipboardCommandButton></div>);}-function DashboardIllustration() {- return (- <Image- src={dashboardImg}- alt="AI chat dashboard illustration"- className={styles.dashboardImage}- placeholder="blur"- />- );-}-// ---------------------------------------------------------------------------// Main component// ---------------------------------------------------------------------------@@ -49,22 +34,15 @@ export function BuildChatSection() {<div className={styles.section}><div className={styles.container}><div className={styles.card}>- {/* Border + shadow overlay */}<div aria-hidden="true" className={styles.overlay} /><div className={styles.content}>- {/* Left: text content */}<div className={styles.copyColumn}><div className={styles.copyStack}><SectionTitle /></div><CtaButton /></div>-- {/* Right: illustration */}- <div className={styles.mediaColumn}>- <DashboardIllustration />- </div></div></div></div>diff --git a/docs/app/(home)/sections/CompatibilitySection/CompatibilitySection.module.css b/docs/app/(home)/sections/CompatibilitySection/CompatibilitySection.module.cssindex ae04d9414..12c1b5b35 100644--- a/docs/app/(home)/sections/CompatibilitySection/CompatibilitySection.module.css+++ b/docs/app/(home)/sections/CompatibilitySection/CompatibilitySection.module.css@@ -1,133 +1,123 @@.section {width: 100%;- padding-inline: var(--home-section-padding-inline);+ padding-inline: 1.25rem;}.container {- max-width: 75rem;+ max-width: 84rem;margin-inline: auto;}.stack {display: flex;flex-direction: column;- gap: 1rem;+ gap: 2.75rem;+ align-items: center;}-.row {+.header {display: flex;- flex-direction: column;- gap: 0.75rem;+ justify-content: center;+ width: 100%;}-.label {- flex-shrink: 0;- font-family: "Inter", sans-serif;- font-size: 13px;- font-weight: 500;- line-height: 1;- letter-spacing: 0.08em;- text-transform: uppercase;- color: var(--home-color-text-subtle);+.title {+ margin: 0;+ text-align: center;+ font-size: 2.5rem;+ font-weight: 600;+ line-height: 1.2;+ letter-spacing: -2px;+ color: var(--openui-text-neutral-primary);}-.chips {+.rows {display: flex;- flex-wrap: wrap;- align-items: center;- gap: 0.5rem;+ width: 100%;+ max-width: 100%;+ flex-direction: column;+ gap: 2rem;+ align-items: stretch;}-.chip {+.row {display: flex;- align-items: center;- gap: 0.375rem;- padding: 0.375rem 0.625rem;- border: 1px solid var(--home-border-subtle);- border-radius: var(--home-radius-pill);- background: var(--home-color-surface);- box-shadow: 0 2px 8px -2px rgb(22 34 51 / 8%);+ width: 100%;+ flex-direction: column;+ gap: 1.125rem;}-.badge {- display: flex;- height: 1.375rem;- width: 1.375rem;+.label {flex-shrink: 0;- align-items: center;- justify-content: center;- overflow: hidden;- border-radius: 5px;-}--.badgeWhite {- background: var(--home-color-surface);-}--.badgeBlack {- background: var(--home-color-surface-inverse);-}--.badgeAnthropic {- background: #d4a574;-}--.badgeMistral {- background: #ff7000;+ font-family: "Inter", sans-serif;+ font-size: 1rem;+ font-weight: 600;+ line-height: 1.1;+ color: var(--openui-text-neutral-primary);}-.badgeLangChain {- background: #1c3144;+.chipsViewport {+ width: 100%;+ overflow: hidden;}-.badgeCrewAi {- background: #ff4b4b;+.chips {+ display: flex;+ width: max-content;+ flex-direction: column;+ align-items: flex-start;+ gap: 1rem;}-.badgeGoogle {- background: #4285f4;+.chipRow {+ display: flex;+ width: max-content;+ flex-wrap: nowrap;+ align-items: center;+ gap: 1rem;}-.badgeWithBorder {- border: 1px solid var(--home-border-default);-}+@media (min-width: 1024px) {+ .section {+ padding-inline: 2rem;+ }-.badgeImage {- height: 0.875rem;- width: 0.875rem;- object-fit: contain;-}+ .stack {+ gap: 2.5rem;+ }-.chipLabel,-.more {- font-family: "Inter", sans-serif;- font-size: 13px;- line-height: 1;- white-space: nowrap;- color: var(--home-color-text-secondary);-}+ .rows {+ gap: 1.5rem;+ }-.chipLabel {- font-weight: 500;-}+ .row {+ flex-direction: row;+ align-items: center;+ justify-content: center;+ gap: 1.5rem;+ }-.more {- margin-left: 0.25rem;- color: var(--home-color-text-subtle);-}+ .row:nth-child(2) {+ flex-direction: row-reverse;+ }-.divider {- height: 1px;- background: rgb(0 0 0 / 6%);-}+ .label {+ font-size: 1.125rem;+ white-space: nowrap;+ }-@media (min-width: 1024px) {- .stack {- gap: 1.25rem;+ .chipsViewport {+ width: auto;+ overflow: visible;}- .row {+ .chips {+ width: auto;flex-direction: row;align-items: center;}++ .chipRow {+ display: contents;+ }}diff --git a/docs/app/(home)/sections/CompatibilitySection/CompatibilitySection.tsx b/docs/app/(home)/sections/CompatibilitySection/CompatibilitySection.tsxindex 571b1c8a4..bb49a9d33 100644--- a/docs/app/(home)/sections/CompatibilitySection/CompatibilitySection.tsx+++ b/docs/app/(home)/sections/CompatibilitySection/CompatibilitySection.tsx@@ -1,121 +1,208 @@-// ----------------------------------------------------------------------------// Data-// ----------------------------------------------------------------------------+import svgPaths from "@/imports/svg-urruvoh2be";+import {+ StackChip,+ stackChipStyles,+ type StackChipItem,+} from "../../components/StackChip/StackChip";import styles from "./CompatibilitySection.module.css";-interface CompatibilityItem {- name: string;- slug?: string;- localSrc?: string;- iconColor: string;- badgeClassName?: string;+interface StackRow {+ label: string;+ items: StackChipItem[];}-const LLMS: CompatibilityItem[] = [- {- name: "OpenAI",- localSrc: "/brand-icons/openai.svg",- iconColor: "000000",- badgeClassName: `${styles.badgeWhite} ${styles.badgeWithBorder}`,- },- { name: "Anthropic", slug: "anthropic", iconColor: "ffffff", badgeClassName: styles.badgeAnthropic },+function splitItemsIntoRows(items: StackChipItem[], rowCount: number): StackChipItem[][] {+ const itemsPerRow = Math.ceil(items.length / rowCount);++ return Array.from({ length: rowCount }, (_, rowIndex) =>+ items.slice(rowIndex * itemsPerRow, (rowIndex + 1) * itemsPerRow),+ ).filter((row) => row.length > 0);+}++function createMoreChip(): StackChipItem {+ return {+ name: "+ more",+ iconKind: "more",+ badgeClassName: stackChipStyles.badgeMore,+ isBlurred: true,+ };+}++const STACK_ROWS: StackRow[] = [{- name: "Gemini",- slug: "googlegemini",- iconColor: "000000",- badgeClassName: `${styles.badgeWhite} ${styles.badgeWithBorder}`,+ label: "All LLMs",+ items: [+ {+ name: "OpenAI",+ iconKind: "image",+ localSrc: "/brand-icons/openai.svg",+ iconColor: "000000",+ badgeClassName: `${stackChipStyles.badgeWhite} ${stackChipStyles.badgeWithBorder}`,+ },+ {+ name: "Anthropic",+ iconKind: "image",+ slug: "anthropic",+ iconColor: "ffffff",+ badgeClassName: stackChipStyles.badgeAnthropic,+ },+ {+ name: "Gemini",+ iconKind: "image",+ slug: "googlegemini",+ iconColor: "000000",+ badgeClassName: `${stackChipStyles.badgeWhite} ${stackChipStyles.badgeWithBorder}`,+ },+ {+ name: "Mistral",+ iconKind: "image",+ slug: "mistralai",+ iconColor: "ffffff",+ badgeClassName: stackChipStyles.badgeMistral,+ },+ {+ name: "xAI",+ iconKind: "image",+ slug: "xai",+ iconColor: "ffffff",+ badgeClassName: stackChipStyles.badgeBlack,+ },+ {+ name: "DeepSeek",+ iconKind: "image",+ slug: "deepseek",+ iconColor: "ffffff",+ badgeClassName: stackChipStyles.badgeDeepSeek,+ },+ createMoreChip(),+ ],},- { name: "Mistral", slug: "mistralai", iconColor: "ffffff", badgeClassName: styles.badgeMistral },-];--const FRAMEWORKS: CompatibilityItem[] = [- { name: "Vercel AI SDK", slug: "vercel", iconColor: "ffffff", badgeClassName: styles.badgeBlack },- { name: "LangChain", slug: "langchain", iconColor: "ffffff", badgeClassName: styles.badgeLangChain },- { name: "CrewAI", slug: "crewai", iconColor: "ffffff", badgeClassName: styles.badgeCrewAi },{- name: "OpenAI Agents SDK",- localSrc: "/brand-icons/openai.svg",- iconColor: "000000",- badgeClassName: `${styles.badgeWhite} ${styles.badgeWithBorder}`,+ label: "Any UI Library",+ items: [+ {+ name: "OpenUI Design system",+ iconKind: "mascot",+ badgeClassName: stackChipStyles.badgeOpenUi,+ },+ {+ name: "ShadCN",+ iconKind: "vector",+ badgeClassName: stackChipStyles.badgeBlack,+ iconViewBox: "0 0 24 24",+ iconPath: svgPaths.p46a4800,+ iconFill: "white",+ clipId: "clip_shadcn",+ clipSize: "24",+ },+ {+ name: "Material Design system",+ iconKind: "vector",+ badgeClassName: stackChipStyles.badgeMaterial,+ iconViewBox: "0 0 30 30",+ iconPath: svgPaths.p3a7bdd80,+ iconFill: "white",+ clipId: "clip_material",+ clipSize: "30",+ },+ {+ name: "DaisyUI",+ iconKind: "text",+ iconText: "D",+ badgeClassName: stackChipStyles.badgeDaisyUi,+ },+ {+ name: "Base UI",+ iconKind: "text",+ iconText: "B",+ badgeClassName: stackChipStyles.badgeBaseUi,+ },+ createMoreChip(),+ ],},{- name: "Anthropic Agents SDK",- slug: "anthropic",- iconColor: "ffffff",- badgeClassName: styles.badgeAnthropic,+ label: "Any Framework",+ items: [+ {+ name: "Vercel AI SDK",+ iconKind: "image",+ slug: "vercel",+ iconColor: "ffffff",+ badgeClassName: stackChipStyles.badgeBlack,+ },+ {+ name: "LangChain",+ iconKind: "image",+ slug: "langchain",+ iconColor: "ffffff",+ badgeClassName: stackChipStyles.badgeLangChain,+ },+ {+ name: "CrewAI",+ iconKind: "image",+ slug: "crewai",+ iconColor: "ffffff",+ badgeClassName: stackChipStyles.badgeCrewAi,+ },+ {+ name: "OpenAI Agents SDK",+ iconKind: "image",+ localSrc: "/brand-icons/openai.svg",+ iconColor: "000000",+ badgeClassName: `${stackChipStyles.badgeWhite} ${stackChipStyles.badgeWithBorder}`,+ },+ {+ name: "Anthropic Agents SDK",+ iconKind: "image",+ slug: "anthropic",+ iconColor: "ffffff",+ badgeClassName: stackChipStyles.badgeAnthropic,+ },+ createMoreChip(),+ ],},- { name: "Google ADK", slug: "google", iconColor: "ffffff", badgeClassName: styles.badgeGoogle },];-// ----------------------------------------------------------------------------// Chip-// -----------------------------------------------------------------------------function Chip({ item }: { item: CompatibilityItem }) {- const imgSrc = item.localSrc ?? `https://cdn.simpleicons.org/${item.slug}/${item.iconColor}`;- return (- <div className={styles.chip}>- <div className={`${styles.badge} ${item.badgeClassName ?? ""}`.trim()}>- {/* eslint-disable-next-line @next/next/no-img-element */}- <img- src={imgSrc}- alt={item.name}- width={14}- height={14}- className={styles.badgeImage}- />- </div>- <span className={styles.chipLabel}>- {item.name}- </span>- </div>- );-}--// ----------------------------------------------------------------------------// Main component-// ----------------------------------------------------------------------------export function CompatibilitySection() {return (- <div className={styles.section}>+ <section className={styles.section} aria-labelledby="favorite-stack-title"><div className={styles.container}><div className={styles.stack}>- {/* LLMs row */}- <div className={styles.row}>- <span className={styles.label}>- Any LLM- </span>- <div className={styles.chips}>- {LLMS.map((item) => (- <Chip key={item.name} item={item} />- ))}- <span className={styles.more}>- + more- </span>- </div>- </div>+ <header className={styles.header}>+ <h2 id="favorite-stack-title" className={styles.title}>+ Works effortlessly+ <br />+ with your favorite stack.+ </h2>+ </header>- {/* Divider */}- <div className={styles.divider} />+ <div className={styles.rows}>+ {STACK_ROWS.map((row) => {+ const chipRows = splitItemsIntoRows(row.items, 2);- {/* Frameworks row */}- <div className={styles.row}>- <span className={styles.label}>- Any Framework- </span>- <div className={styles.chips}>- {FRAMEWORKS.map((item) => (- <Chip key={item.name} item={item} />- ))}- <span className={styles.more}>- + more- </span>- </div>+ return (+ <div key={row.label} className={styles.row}>+ <span className={styles.label}>{row.label}</span>+ <div className={styles.chipsViewport}>+ <div className={styles.chips}>+ {chipRows.map((chipRow, rowIndex) => (+ <div key={`${row.label}-row-${rowIndex}`} className={styles.chipRow}>+ {chipRow.map((item, itemIndex) => (+ <StackChip+ key={`${row.label}-${item.name}-${rowIndex}-${itemIndex}`}+ item={item}+ />+ ))}+ </div>+ ))}+ </div>+ </div>+ </div>+ );+ })}</div></div></div>- </div>+ </section>);}diff --git a/docs/app/(home)/sections/FeaturesSection/FeaturesSection.module.css b/docs/app/(home)/sections/FeaturesSection/FeaturesSection.module.cssindex 75e3fa67c..d424dc0e7 100644--- a/docs/app/(home)/sections/FeaturesSection/FeaturesSection.module.css+++ b/docs/app/(home)/sections/FeaturesSection/FeaturesSection.module.css@@ -1,6 +1,6 @@.section {width: 100%;- padding-inline: var(--home-section-padding-inline);+ padding-inline: 1.25rem;}.container {@@ -27,11 +27,11 @@align-items: center;justify-content: center;padding-inline: 1rem;- border: 1.25px solid var(--home-border-subtle);- border-radius: var(--home-radius-pill);- background: var(--home-color-surface);- box-shadow: var(--home-shadow-elevated);- color: var(--home-color-text-primary);+ border: 1.25px solid var(--openui-border-interactive);+ border-radius: var(--openui-radius-full);+ background: var(--openui-foreground);+ box-shadow: var(--openui-shadow-l);+ color: var(--openui-text-neutral-primary);cursor: pointer;transition:transform 0.2s ease,@@ -56,6 +56,10 @@}@media (min-width: 1024px) {+ .section {+ padding-inline: 2rem;+ }+.ctaWrap {margin-top: 5rem;}diff --git a/docs/app/(home)/sections/FeaturesSection/FeaturesSection.tsx b/docs/app/(home)/sections/FeaturesSection/FeaturesSection.tsxindex e8f273b5e..d3c7b9724 100644--- a/docs/app/(home)/sections/FeaturesSection/FeaturesSection.tsx+++ b/docs/app/(home)/sections/FeaturesSection/FeaturesSection.tsx@@ -12,7 +12,7 @@ import styles from "./FeaturesSection.module.css";const FEATURES: FeatureListItem[] = [{title: "Performance Optimized",- description: "Up to 3.0x faster rendering than json-render",+ description: "3x faster rendering than json-render",iconPath: svgPaths.p7658f00,},{@@ -21,23 +21,23 @@ const FEATURES: FeatureListItem[] = [iconPath: svgPaths.p2a8ddd80,},{- title: "Native Types",- description: "Performant and memory safe",+ title: "Live data",+ description: "Query your tools and MCP servers at runtime",iconPath: svgPaths.p10e86100,},{title: "Works across platforms",- description: "JS Runtime. Native support for iOS & Android coming soon",+ description: "React, React Native, Vue, etc",iconPath: svgPaths.p2cbb5d00,},{- title: "Streaming Native",- description: "Streaming and partial responses",+ title: "Native Streaming",+ description: "UI renders in real time",iconPath: svgPaths.p33780400,},{title: "Interactive",- description: "Handles inputs and interactive flows",+ description: "Reactive state, inputs, and tool-connected actions",iconPath: svgPaths.p17c7f700,},{diff --git a/docs/app/(home)/sections/Footer/Footer.module.css b/docs/app/(home)/sections/Footer/Footer.module.cssindex 20bb4e943..3f4e01dc4 100644--- a/docs/app/(home)/sections/Footer/Footer.module.css+++ b/docs/app/(home)/sections/Footer/Footer.module.css@@ -11,7 +11,7 @@.handcraftedSection {width: 100%;- padding-inline: var(--home-section-padding-inline);+ padding-inline: 1.25rem;}.handcraftedContainer {@@ -29,6 +29,7 @@height: 96px;width: 96px;flex-shrink: 0;+ color: var(--openui-text-neutral-primary);}.handcraftedMascot {@@ -37,12 +38,16 @@display: block;}+.handcraftedMascotDark {+ inset: 0;+}+.handcraftedCopy {text-align: center;font-family: var(--font-geist-mono);font-size: 18px;line-height: 1.2;- color: var(--home-color-text-primary);+ color: var(--openui-text-neutral-primary);margin-top: 12px;}@@ -53,8 +58,8 @@}.contentSection {- padding: 60px var(--home-section-padding-inline) 1rem;- background: var(--home-color-surface);+ padding: 60px 1.25rem 1rem;+ background: var(--openui-foreground);}.contentContainer {@@ -77,12 +82,13 @@position: relative;height: 3rem;width: 124px;+ color: var(--openui-text-neutral-primary);}.bottomBar {margin-top: 2.5rem;padding-block: 1rem;- border-top: 1px solid rgb(0 0 0 / 4%);+ border-top: 1px solid var(--openui-border-default);}.desktopBottomBar {@@ -94,7 +100,7 @@font-family: "Inter", sans-serif;font-size: 15px;line-height: 1.5;- color: var(--home-color-text-muted);+ color: var(--openui-text-neutral-secondary);}.desktopMetaLeft {@@ -122,6 +128,7 @@position: relative;height: 1.5rem;width: 1.5rem;+ color: var(--openui-text-neutral-tertiary);}.socialIconWrap {@@ -157,7 +164,7 @@font-family: "Inter", sans-serif;font-size: 12px;line-height: 1.5;- color: var(--home-color-text-muted);+ color: var(--openui-text-neutral-secondary);}@keyframes handcraftedCursorBlink {@@ -173,7 +180,13 @@}@media (min-width: 1024px) {+ .handcraftedSection {+ padding-inline: 2rem;+ }+ .contentSection {+ padding-inline: 2rem;+ }.desktopLogoRow {display: flex;flex-direction: column;diff --git a/docs/app/(home)/sections/Footer/Footer.tsx b/docs/app/(home)/sections/Footer/Footer.tsxindex d86a8af2d..727642e2a 100644--- a/docs/app/(home)/sections/Footer/Footer.tsx+++ b/docs/app/(home)/sections/Footer/Footer.tsx@@ -1,6 +1,8 @@"use client";+import mascotDarkSvgPaths from "@/imports/svg-mascot-dark";import svgPaths from "@/imports/svg-urruvoh2be";import mascotSvgPaths from "@/imports/svg-xeurqn3j1r";+import { useId } from "react";import styles from "./Footer.module.css";// ---------------------------------------------------------------------------@@ -56,20 +58,23 @@ const SOCIAL_LINKS: SocialLink[] = [// ---------------------------------------------------------------------------function SocialIcon({ link }: { link: SocialLink }) {- const svgContent = link.clipId ? (+ const uniqueId = useId();+ const clipPathId = link.clipId ? `${link.clipId}-${uniqueId}` : undefined;++ const svgContent = clipPathId ? (<svg className={styles.absoluteSvg} fill="none" viewBox={link.viewBox}>- <g clipPath={`url(#${link.clipId})`}>- <path d={link.path} fill="black" fillOpacity="0.4" />+ <g clipPath={`url(#${clipPathId})`}>+ <path d={link.path} fill="currentColor" /></g><defs>- <clipPath id={link.clipId}>+ <clipPath id={clipPathId}><rect fill="white" height={link.clipSize!.height} width={link.clipSize!.width} /></clipPath></defs></svg>) : (<svg className={styles.absoluteSvg} fill="none" viewBox={link.viewBox}>- <path d={link.path} fill="black" fillOpacity="0.4" />+ <path d={link.path} fill="currentColor" /></svg>);@@ -106,43 +111,97 @@ function ThesysLogo() {return (<div className={styles.logoWrap}><svg className={styles.absoluteSvg} fill="none" viewBox="0 0 123.871 49.5484">- <path d={svgPaths.p16775200} fill="black" />- <path clipRule="evenodd" d={svgPaths.p29abae30} fill="black" fillRule="evenodd" />- <path d={svgPaths.p318aaf80} fill="black" />- <path d={svgPaths.p3f22cf00} fill="black" />- <path d={svgPaths.p27013980} fill="black" />- <path d={svgPaths.p21b7f300} fill="black" />+ <path d={svgPaths.p16775200} fill="currentColor" />+ <path clipRule="evenodd" d={svgPaths.p29abae30} fill="currentColor" fillRule="evenodd" />+ <path d={svgPaths.p318aaf80} fill="currentColor" />+ <path d={svgPaths.p3f22cf00} fill="currentColor" />+ <path d={svgPaths.p27013980} fill="currentColor" />+ <path d={svgPaths.p21b7f300} fill="currentColor" /></svg></div>);}+function HandcraftedMascot({ isDark }: { isDark: boolean }) {+ if (isDark) {+ return (+ <svg+ className={`${styles.handcraftedMascot} ${styles.handcraftedMascotDark}`.trim()}+ fill="none"+ preserveAspectRatio="xMidYMid meet"+ viewBox="0 0 33 32"+ >+ <path d={mascotDarkSvgPaths.pBody} fill="white" />+ <path d={mascotDarkSvgPaths.pOutline} fill="#464646" stroke="#464646" strokeWidth="0.3" />+ <path d={mascotDarkSvgPaths.pMouth} fill="#464646" />+ <path d={mascotDarkSvgPaths.pEarLeft} fill="#464646" stroke="#464646" strokeWidth="0.3" />+ <path d={mascotDarkSvgPaths.pEarRight} fill="#464646" stroke="#464646" strokeWidth="0.3" />+ <path d={mascotDarkSvgPaths.pEyeLeft} fill="#464646" />+ <path d={mascotDarkSvgPaths.pEyeRight} fill="#464646" />+ <path d={mascotDarkSvgPaths.pHornLeft} fill="#464646" stroke="#464646" strokeWidth="0.3" />+ <path d={mascotDarkSvgPaths.pHornRight} fill="#464646" stroke="#464646" strokeWidth="0.3" />+ </svg>+ );+ }++ return (+ <svg+ className={styles.handcraftedMascot}+ fill="none"+ preserveAspectRatio="xMidYMid meet"+ viewBox="0 0 141.2 114.2"+ >+ <path+ d={mascotSvgPaths.p395b3c00}+ fill="currentColor"+ stroke="currentColor"+ strokeWidth="0.6"+ />+ <path d={mascotSvgPaths.p3b251e80} fill="currentColor" />+ <path+ d={mascotSvgPaths.p2718bc80}+ fill="currentColor"+ stroke="currentColor"+ strokeWidth="0.6"+ />+ <path+ d={mascotSvgPaths.p37ab5b0}+ fill="currentColor"+ stroke="currentColor"+ strokeWidth="0.6"+ />+ <path d={mascotSvgPaths.p2ac89300} fill="currentColor" />+ <path d={mascotSvgPaths.p2b8b4380} fill="currentColor" />+ <path+ d={mascotSvgPaths.p15c14e00}+ fill="currentColor"+ stroke="currentColor"+ strokeWidth="0.6"+ />+ <path+ d={mascotSvgPaths.p4076200}+ fill="currentColor"+ stroke="currentColor"+ strokeWidth="0.6"+ />+ </svg>+ );+}+// ---------------------------------------------------------------------------// Main component// ---------------------------------------------------------------------------export function Footer() {+ const isDark = false;+return (<footer className={styles.footer}>{/* Handcrafted */}<div className={styles.handcraftedSection}><div className={styles.handcraftedContainer}><div className={styles.mascotWrap}>- <svg- className={styles.handcraftedMascot}- fill="none"- preserveAspectRatio="xMidYMid meet"- viewBox="0 0 141.2 114.2"- >- <path d={mascotSvgPaths.p395b3c00} fill="black" stroke="black" strokeWidth="0.6" />- <path d={mascotSvgPaths.p3b251e80} fill="black" />- <path d={mascotSvgPaths.p2718bc80} fill="black" stroke="black" strokeWidth="0.6" />- <path d={mascotSvgPaths.p37ab5b0} fill="black" stroke="black" strokeWidth="0.6" />- <path d={mascotSvgPaths.p2ac89300} fill="black" />- <path d={mascotSvgPaths.p2b8b4380} fill="black" />- <path d={mascotSvgPaths.p15c14e00} fill="black" stroke="black" strokeWidth="0.6" />- <path d={mascotSvgPaths.p4076200} fill="black" stroke="black" strokeWidth="0.6" />- </svg>+ <HandcraftedMascot isDark={isDark} /></div><p className={styles.handcraftedCopy}>Handcrafted with a lot of love@@ -168,9 +227,7 @@ export function Footer() {{/* Bottom bar */}<div className={styles.bottomBar}><div className={styles.desktopBottomBar}>- <p className={styles.desktopMetaLeft}>- 355 Bryant St, San Francisco, CA 94107- </p>+ <p className={styles.desktopMetaLeft}>355 Bryant St, San Francisco, CA 94107</p><SocialIcons /><p className={styles.desktopMetaRight}>© {new Date().getFullYear()} Thesys Inc. All Rights Reserved@@ -183,9 +240,7 @@ export function Footer() {<p className={styles.mobileMetaText}>© {new Date().getFullYear()} Thesys Inc. All Rights Reserved</p>- <p className={styles.mobileMetaText}>- 355 Bryant St, San Francisco, CA 94107- </p>+ <p className={styles.mobileMetaText}>355 Bryant St, San Francisco, CA 94107</p></div></div></div>diff --git a/docs/app/(home)/sections/GradientDivider/GradientDivider.module.css b/docs/app/(home)/sections/GradientDivider/GradientDivider.module.cssindex 231e1e927..5897c6cb6 100644--- a/docs/app/(home)/sections/GradientDivider/GradientDivider.module.css+++ b/docs/app/(home)/sections/GradientDivider/GradientDivider.module.css@@ -4,12 +4,13 @@flex-direction: column;gap: 2px;transform: rotate(180deg);+ background: var(--openui-foreground);}.bar {width: 100%;flex-shrink: 0;- background: rgb(0 0 0 / 4%);+ background: var(--openui-background);}.barHeight60 {diff --git a/docs/app/(home)/sections/GradientDivider/GradientDivider.tsx b/docs/app/(home)/sections/GradientDivider/GradientDivider.tsxindex b28070648..98421a5e6 100644--- a/docs/app/(home)/sections/GradientDivider/GradientDivider.tsx+++ b/docs/app/(home)/sections/GradientDivider/GradientDivider.tsx@@ -22,10 +22,7 @@ export function GradientDivider({ direction = "down" }: { direction?: "down" | "return (<div className={styles.divider}>{bars.map((barClassName) => (- <div- key={barClassName}- className={`${styles.bar} ${barClassName}`.trim()}- />+ <div key={barClassName} className={`${styles.bar} ${barClassName}`.trim()} />))}</div>);diff --git a/docs/app/(home)/sections/HeroSection/HeroSection.module.css b/docs/app/(home)/sections/HeroSection/HeroSection.module.cssindex 62d489b81..cc19ab10b 100644--- a/docs/app/(home)/sections/HeroSection/HeroSection.module.css+++ b/docs/app/(home)/sections/HeroSection/HeroSection.module.css@@ -11,10 +11,10 @@gap: 0.625rem;padding-left: 1.25rem;padding-right: 0.5rem;- border: 1px solid var(--home-border-soft);- border-radius: var(--home-radius-pill);- background: var(--home-color-surface);- box-shadow: var(--home-shadow-elevated);+ border: 1px solid var(--openui-border-default);+ border-radius: var(--openui-radius-full);+ background: var(--openui-foreground);+ box-shadow: var(--openui-shadow-l);cursor: pointer;transition:transform 0.2s ease,@@ -27,7 +27,7 @@}.desktopPlaygroundButton:hover {- background: var(--home-color-surface-soft);+ background: var(--openui-highlight);}.npmDesktopLabel,@@ -48,7 +48,7 @@display: none;font-family: var(--font-geist-mono);white-space: nowrap;- color: var(--home-color-text-primary);+ color: var(--openui-text-neutral-primary);}.npmMobileLabel {@@ -70,7 +70,7 @@font-family: var(--font-geist-mono);white-space: nowrap;padding-right: 2rem;- color: var(--home-color-text-primary);+ color: var(--openui-text-neutral-primary);}.npmIconBadge {@@ -81,7 +81,7 @@align-items: center;justify-content: center;border-radius: 999px;- background: var(--home-color-surface-inverse);+ background: var(--openui-inverted-background);}.desktopPlaygroundButton,@@ -96,16 +96,17 @@}.desktopPlaygroundButton {- padding-inline: var(--home-pill-padding-inline);- color: var(--home-color-text-primary);+ padding-inline: 1.25rem;+ color: var(--openui-text-neutral-primary);transition: background-color 0.2s ease;}.mobilePlaygroundButton {flex-shrink: 0;- padding-inline: var(--home-pill-padding-inline);+ padding-inline: 1.25rem;border-radius: 100px;- background: var(--home-color-surface-inverse);+ background: var(--openui-inverted-background);+ color: var(--openui-text-accent-primary);transition: background-color 0.2s ease;}@@ -115,21 +116,7 @@.mobilePlaygroundLabel {white-space: nowrap;- color: var(--home-color-text-inverse);-}--.mobilePlaygroundArrow {- color: var(--home-color-text-inverse);- font-size: 20px;- line-height: 1;-}--.mobileMascotSvg {- position: absolute;- inset: 9.29% 0 10% 0;- display: block;- width: 100%;- height: 80.71%;+ color: var(--openui-text-accent-primary);}.desktopHero {@@ -137,57 +124,61 @@}.desktopHeroInner {- position: relative;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 1.5rem;max-width: 75rem;margin-inline: auto;}-.desktopHeroSpacer {- display: block;- width: 100%;- height: auto;- visibility: hidden;-}--.heroLayerMotion {- position: absolute;- inset: 0;-}--.heroLayerMotion,-.desktopCtaLayer {- will-change: transform, opacity;-}--.fillSvg {+.desktopHeroLockup {+ display: flex;+ align-items: center;+ justify-content: center;+ flex-direction: column;+ gap: 1rem;width: 100%;- height: 100%;-}--.desktopCtaLayer {- position: absolute;- left: 50%;- top: 71.19%;+ text-align: left;}.desktopCtaStack {- position: relative;display: flex;flex-direction: column;align-items: center;gap: 1rem;- padding-top: 3.5rem;- transform: translateX(-50%);+}++.desktopTitle {+ margin: 0;+ font-family: "Inter Display", sans-serif;+ font-size: 10rem;+ font-weight: 600;+ line-height: 1;+ letter-spacing: -3px;+ color: var(--openui-text-neutral-primary);+}++.desktopSubtitle {+ margin: 0;+ font-family: "Inter Display", sans-serif;+ font-size: 1.75rem;+ font-weight: 500;+ line-height: 1.25;+ margin-left: 32px;+ margin-top: -12px;+ color: var(--openui-text-neutral-secondary);}.mobileHero {position: relative;overflow: hidden;+ padding-top: 2rem;}.mobileHeroIntro {position: relative;- padding: 32px var(--home-section-padding-inline) var(--home-section-padding-inline);+ padding: 24px 1.25rem 0;}.mobileHeroStack {@@ -197,61 +188,121 @@margin-inline: auto;flex-direction: column;align-items: center;- gap: 1.25rem;- padding-block: 2.5rem;+ gap: 0.875rem;+ padding: 1rem 0 0.5rem;}.mobileBrandGroup {display: flex;flex-direction: column;align-items: center;- gap: 0rem;+ gap: 0;}-.mobileGithubBanner {+.heroBanner {display: inline-flex;align-items: center;justify-content: center;- gap: 0.5rem;+ gap: 0.75rem;min-height: 2.5rem;- padding-inline: 1rem;- border-radius: var(--home-radius-pill);- background: var(--home-color-surface-soft);- color: var(--home-color-text-primary);- text-decoration: none;+ padding: 0.875rem 1rem 0.875rem 1rem;+ border-radius: var(--openui-radius-full);+ background: var(--openui-highlight-strong);+ color: var(--openui-text-neutral-primary);font-family: "Inter Display", sans-serif;font-size: 16px;font-weight: 500;line-height: 1.5rem;transition: background-color 0.2s ease;+ text-align: center;+ margin-bottom: 24px;}-.mobileGithubBanner:hover {- background: var(--home-color-surface-muted);+.heroBannerDesktop {+ display: none;+}++.heroBannerMobile {+ display: inline-flex;+ text-decoration: none;+}++.heroBanner:hover {+ background: var(--openui-highlight-strong);+}++.heroBannerLabel {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ color: inherit;+ text-decoration: none;+}++.heroBannerActions {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;}-.mobileGithubBannerLead {+.heroBannerButton {display: inline-flex;align-items: center;justify-content: center;+ min-height: 2rem;+ padding-inline: 1rem;+ border-radius: var(--openui-radius-full);+ background: var(--openui-foreground);+ color: var(--openui-text-neutral-primary);+ text-decoration: none;+ font-size: 14px;+ font-weight: 500;+ line-height: 1.25rem;+ border: 1px solid var(--openui-border-default);+ transition:+ border-color 0.2s ease,+}++.heroBannerButton:hover {+ border: 1px solid var(--openui-border-interactive);+}++.heroBannerButtonPrimary {+ background: var(--openui-inverted-background);+ color: var(--openui-text-accent-primary);+}++.heroBannerButtonPrimary:hover {+ background: rgb(0 0 0 / 85%);+}++.heroBannerLead {+ display: inline-flex;+ align-items: center;gap: 0.375rem;+ min-width: 0;}-.mobileGithubBannerIcon {+.heroBannerIcon {display: inline-flex;align-items: center;justify-content: center;+ flex-shrink: 0;}-.mobileGithubBannerArrow {+.mobileGithubButton {+ min-height: 3rem;+ padding-inline: 1.25rem;+ border-radius: 100px;font-size: 18px;- line-height: 1;+ line-height: 1.5rem;}-.mobileMascotWrap {- position: relative;- height: 120px;- width: 120px;+.mobileCtaArrow {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ color: currentColor;flex-shrink: 0;}@@ -261,7 +312,7 @@font-size: 80px;font-weight: 600;line-height: 1.25;- color: var(--home-color-text-primary);+ color: var(--openui-text-neutral-primary);}.mobileSubtitle {@@ -270,7 +321,7 @@font-size: 22px;font-weight: 500;line-height: 1.2;- color: var(--home-color-text-muted);+ color: var(--openui-text-neutral-secondary);}.mobileCtaStack {@@ -278,64 +329,65 @@display: flex;flex-direction: column;align-items: center;- gap: 0.75rem;- padding: 1.25rem 2.5rem 5rem;+ margin-top: 32px;+ gap: 1rem;+ padding: 0.5rem 2.5rem 4rem;}.mobileCtaButtonWidth {width: 320px;max-width: 100%;+ justify-content: space-between;}.mobileIllustrationViewport {position: relative;- left: 50%;- width: 100vw;- transform: translateX(-50%);-}--.mobileIllustrationFallback {- aspect-ratio: 16 / 9;-}--.previewScaleContainer {- position: absolute;- inset: 0;+ width: 100%;+ max-width: 402px;+ margin-inline: auto;+ overflow: hidden;+ -webkit-mask-image: linear-gradient(to bottom, #000 0%, #000 78%, transparent 100%);+ mask-image: linear-gradient(to bottom, #000 0%, #000 78%, transparent 100%);}-.previewScaleFrame {- position: absolute;- left: 50%;- width: 1600px;- height: 518px;- transform: translateX(-50%) scale(var(--preview-scale, 1));- transform-origin: top center;+.mobileIllustrationImage {+ display: block;+ width: 100%;+ height: auto;}.previewSection {width: 100%;overflow: hidden;margin-top: 2rem;+ padding-inline: 1rem;}.previewDesktopOnly {display: none;+ width: 100%;justify-content: center;- overflow: hidden;}.previewFrame {position: relative;- width: calc(100% + 240px);- max-width: 100vw;- aspect-ratio: 1600 / 518;- margin-inline: -120px;+ width: 100%;+ max-width: 75rem;+ margin-inline: auto;overflow: hidden;+ -webkit-mask-image: linear-gradient(to bottom, #000 0%, #000 78%, transparent 100%);+ mask-image: linear-gradient(to bottom, #000 0%, #000 78%, transparent 100%);+}++.previewImage {+ display: block;+ width: 100%;+ height: auto;}.taglineSection {margin-top: 1.25rem;- padding-inline: var(--home-section-padding-inline);+ padding-inline: 1.25rem;}.taglineContainer {@@ -349,7 +401,7 @@font-size: 22px;font-weight: 500;line-height: 1.4;- color: var(--home-color-text-muted);+ color: var(--openui-text-neutral-secondary);}.taglineBreak {@@ -381,11 +433,31 @@position: relative;width: 100%;overflow: hidden;- padding: 5.5rem var(--home-section-padding-inline) 5.5rem;+ padding: 8rem 2rem 0rem 2rem;+ }++ .heroBanner {+ align-items: center;+ gap: 1rem;+ padding: 0.5rem 0.75rem 0.5rem 1rem;+ }++ .heroBannerDesktop {+ display: inline-flex;+ }++ .heroBannerMobile {+ display: none;+ }++ .heroBannerActions {+ flex-direction: row;+ align-items: center;}.previewSection {margin-top: 2.5rem;+ padding-inline: 2rem;}.previewDesktopOnly {@@ -394,7 +466,7 @@.taglineSection {margin-top: 2.5rem;- padding: 2.5rem var(--home-section-padding-inline) 0;+ padding: 2.5rem 2rem 0;}.tagline {@@ -404,4 +476,4 @@.taglineBreak {display: inline;}-}\ No newline at end of file+}diff --git a/docs/app/(home)/sections/HeroSection/HeroSection.tsx b/docs/app/(home)/sections/HeroSection/HeroSection.tsxindex bf47ab6b2..8b2a52e6b 100644--- a/docs/app/(home)/sections/HeroSection/HeroSection.tsx+++ b/docs/app/(home)/sections/HeroSection/HeroSection.tsx@@ -1,22 +1,39 @@"use client";import { GitHubIcon } from "@/components/brand-logo";-import HeroPreviewFrame from "@/imports/Frame2147239423";-import svgMascotPaths from "@/imports/svg-148i9mcxjn";-import svgHeroPaths from "@/imports/svg-a5kdrdeeao";-import { lazy, Suspense, useEffect, useRef, useState } from "react";+import { ArrowRight } from "lucide-react";+import Link from "next/link";import { ClipboardCommandButton, PillLink } from "../../components/Button/Button";import styles from "./HeroSection.module.css";-const LazyMobileActionFigure = lazy(() => import("@/imports/MobileActionFigure"));-// CTAsconst primaryCTA = "npx @openuidev/cli@latest create";const secondaryCTA = "Try Playground";+const architectureHref = "/docs/openui-lang/how-it-works";+const DESKTOP_HERO_IMAGE = {+ light: "/homepage/hero-web.png",+ dark: "/homepage/hero-web-dark.png",+ width: 2040,+ height: 704,+} as const;+const MOBILE_HERO_IMAGE = {+ light: "/homepage/mobile-hero.png",+ dark: "/homepage/mobile-hero-dark.png",+ width: 804,+ height: 880,+} as const;++type HeroTheme = "light" | "dark";// ---------------------------------------------------------------------------// Buttons// ---------------------------------------------------------------------------+function TrailingArrow() {+ return (+ <ArrowRight aria-hidden="true" className={styles.mobileCtaArrow} size={18} strokeWidth={2} />+ );+}+function NpmButton({ className = "" }: { className?: string }) {return (<ClipboardCommandButton@@ -25,18 +42,11 @@ function NpmButton({ className = "" }: { className?: string }) {iconContainerClassName={styles.npmIconBadge}copyIconColor="white">- <span className={styles.npmDesktopLabel}>- {primaryCTA}- </span>+ <span className={styles.npmDesktopLabel}>{primaryCTA}</span><span className={styles.npmMobileLabel}><span className={styles.npmTicker}>- <span className={styles.npmTickerText}>- {primaryCTA}- </span>- <span- aria-hidden="true"- className={styles.npmTickerText}- >+ <span className={styles.npmTickerText}>{primaryCTA}</span>+ <span aria-hidden="true" className={styles.npmTickerText}>{primaryCTA}</span></span>@@ -50,7 +60,7 @@ function DesktopPlaygroundButton({ className = "" }: { className?: string }) {<PillLinkhref="/playground"className={`${styles.desktopPlaygroundButton} ${className}`.trim()}- arrow={<span aria-hidden="true">→</span>}+ arrow={<TrailingArrow />}><span>{secondaryCTA}</span></PillLink>@@ -62,49 +72,50 @@ function MobilePlaygroundButton({ className = "" }: { className?: string }) {<PillLinkhref="/playground"className={`${styles.mobilePlaygroundButton} ${className}`.trim()}- arrow={- <span aria-hidden="true" className={styles.mobilePlaygroundArrow}>- →- </span>- }+ arrow={<TrailingArrow />}><span className={styles.mobilePlaygroundLabel}>{secondaryCTA}</span></PillLink>);}-// ----------------------------------------------------------------------------// Mascot SVG (mobile hero)-// -----------------------------------------------------------------------------const MASCOT_STROKED_PATHS = [- svgMascotPaths.p75ec1f0,- svgMascotPaths.p3d8f4800,- svgMascotPaths.p186ed000,- svgMascotPaths.p5c95b80,- svgMascotPaths.p2d8cb380,-] as const;--const MASCOT_FILLED_PATHS = [- svgMascotPaths.p6bfe080,- svgMascotPaths.pe416040,- svgMascotPaths.p34c31400,-] as const;+function AnnouncementBanner({ className = "" }: { className?: string }) {+ return (+ <>+ <div className={`${styles.heroBanner} ${styles.heroBannerDesktop} ${className}`.trim()}>+ <span className={styles.heroBannerLabel}>We're introducing OpenUI Lang v0.5</span>+ <div className={styles.heroBannerActions}>+ <Link href="/demo/github" target="_blank" className={`${styles.heroBannerButton} ${styles.heroBannerButtonPrimary}`}>+ <span>Try now</span>+ </Link>+ <Link href={architectureHref} className={styles.heroBannerButton}>+ <span>Read more</span>+ </Link>+ </div>+ </div>+ <Link href={architectureHref} className={`${styles.heroBanner} ${styles.heroBannerMobile} ${className}`.trim()}>+ <span className={styles.heroBannerLabel}>We're introducing OpenUI Lang v0.5</span>+ </Link>+ </>+ );+}-function MascotSvg() {+function GitHubBanner({ className = "" }: { className?: string }) {return (- <svg- className={styles.mobileMascotSvg}- fill="none"- viewBox="0 0 107.917 87.2814"+ <a+ href="https://github.com/thesysdev/openui"+ target="_blank"+ rel="noopener noreferrer"+ className={`${styles.heroBanner} ${styles.mobileGithubButton} ${className}`.trim()}>- {MASCOT_STROKED_PATHS.map((d) => (- <path key={d.slice(0, 20)} d={d} fill="black" stroke="black" strokeWidth="0.458571" />- ))}- {MASCOT_FILLED_PATHS.map((d) => (- <path key={d.slice(0, 20)} d={d} fill="black" />- ))}- </svg>+ <span className={styles.heroBannerLead}>+ <span aria-hidden="true" className={styles.heroBannerIcon}>+ <GitHubIcon />+ </span>+ <span>Star us on Github</span>+ </span>+ <TrailingArrow />+ </a>);}@@ -116,40 +127,19 @@ function DesktopHero() {return (<div className={styles.desktopHero}><div className={styles.desktopHeroInner}>- {/* Invisible spacer for aspect ratio */}- <svg- className={styles.desktopHeroSpacer}- fill="none"- viewBox="0 0 1600 376"- aria-hidden="true"- >- <rect width="1600" height="376" />- </svg>-- {/* Title */}- <div className={styles.heroLayerMotion}>- <svg className={styles.fillSvg} fill="none" viewBox="0 0 1600 376">- <path d={svgHeroPaths.pb12f700} fill="black" />- </svg>+ <div className={styles.desktopHeroLockup}>+ <AnnouncementBanner />+ <h1 className={styles.desktopTitle}>OpenUI</h1>+ <p className={styles.desktopSubtitle}>+ The Open Standard+ <br />+ for Generative UI+ </p></div>- {/* Subtitle */}- <div className={styles.heroLayerMotion}>- <svg className={styles.fillSvg} fill="none" viewBox="0 0 1600 376">- <g transform="translate(180 0)">- <g transform="translate(880 75) scale(1.5) translate(-980 -108)">- <path d={svgHeroPaths.p38a6ed80} fill="black" fillOpacity="0.4" />- </g>- </g>- </svg>- </div>-- {/* CTA buttons */}- <div className={styles.desktopCtaLayer}>- <div className={styles.desktopCtaStack}>- <NpmButton />- <DesktopPlaygroundButton />- </div>+ <div className={styles.desktopCtaStack}>+ <NpmButton />+ <DesktopPlaygroundButton /></div></div></div>@@ -160,37 +150,17 @@ function DesktopHero() {// Mobile hero// ----------------------------------------------------------------------------function MobileHero() {+function MobileHero({ theme }: { theme: HeroTheme }) {+ const mobileHeroImage = theme === "dark" ? MOBILE_HERO_IMAGE.dark : MOBILE_HERO_IMAGE.light;+return (<div className={styles.mobileHero}><div className={styles.mobileHeroIntro}><div className={styles.mobileHeroStack}>- <a- href="https://github.com/thesysdev/openui"- target="_blank"- rel="noopener noreferrer"- className={styles.mobileGithubBanner}- >- <span className={styles.mobileGithubBannerLead}>- <span aria-hidden="true" className={styles.mobileGithubBannerIcon}>- <GitHubIcon />- </span>- <span>Star us on Github</span>- </span>- <span aria-hidden="true" className={styles.mobileGithubBannerArrow}>- →- </span>- </a>+ <AnnouncementBanner /><div className={styles.mobileBrandGroup}>- <div className={styles.mobileMascotWrap}>- <MascotSvg />- </div>-- {/* Title */}- <p className={styles.mobileTitle}>- OpenUI- </p>+ <p className={styles.mobileTitle}>OpenUI</p></div>{/* Subtitle */}@@ -204,62 +174,49 @@ function MobileHero() {{/* CTA buttons */}<div className={styles.mobileCtaStack}>- <MobilePlaygroundButton className={styles.mobileCtaButtonWidth} /><NpmButton className={styles.mobileCtaButtonWidth} />+ <MobilePlaygroundButton className={styles.mobileCtaButtonWidth} />+ <GitHubBanner className={styles.mobileCtaButtonWidth} /></div>- {/* Full-width hero illustration */}+ {/* Mobile hero image */}<div className={styles.mobileIllustrationViewport}>- <Suspense fallback={<div className={styles.mobileIllustrationFallback} />}>- <LazyMobileActionFigure />- </Suspense>+ <img+ src={mobileHeroImage}+ alt="OpenUI mobile hero preview"+ width={MOBILE_HERO_IMAGE.width}+ height={MOBILE_HERO_IMAGE.height}+ className={styles.mobileIllustrationImage}+ loading="eager"+ decoding="async"+ fetchPriority="high"+ /></div></div>);}// ----------------------------------------------------------------------------// Desktop preview frame (ResizeObserver-scaled)+// Desktop preview image// ----------------------------------------------------------------------------const PREVIEW_NATIVE_WIDTH = 1600;-const PREVIEW_SCALE_MULTIPLIER = 1.25;+function PreviewImage({ theme }: { theme: HeroTheme }) {+ const desktopHeroImage = theme === "dark" ? DESKTOP_HERO_IMAGE.dark : DESKTOP_HERO_IMAGE.light;-function ScaledPreview() {- const containerRef = useRef<HTMLDivElement>(null);- const frameRef = useRef<HTMLDivElement>(null);- const [scale, setScale] = useState(1);-- useEffect(() => {- const el = containerRef.current;- if (!el) return;- const observer = new ResizeObserver(([entry]) => {- setScale(entry.contentRect.width / PREVIEW_NATIVE_WIDTH);- });- observer.observe(el);- return () => observer.disconnect();- }, []);-- useEffect(() => {- if (!frameRef.current) return;- frameRef.current.style.setProperty("--preview-scale", String(scale * PREVIEW_SCALE_MULTIPLIER));- }, [scale]);-- return (- <div ref={containerRef} className={styles.previewScaleContainer}>- <div ref={frameRef} className={styles.previewScaleFrame}>- <HeroPreviewFrame />- </div>- </div>- );-}--function PreviewImage() {return (<div className={styles.previewSection}><div className={styles.previewDesktopOnly}><div className={styles.previewFrame}>- <ScaledPreview />+ <img+ src={desktopHeroImage}+ alt="OpenUI desktop hero preview"+ width={DESKTOP_HERO_IMAGE.width}+ height={DESKTOP_HERO_IMAGE.height}+ className={styles.previewImage}+ loading="eager"+ decoding="async"+ fetchPriority="high"+ /></div></div></div>@@ -288,11 +245,13 @@ function Tagline() {// ---------------------------------------------------------------------------export function HeroSection() {+ const theme: HeroTheme = "light";+return (<section className={styles.section}><DesktopHero />- <MobileHero />- <PreviewImage />+ <MobileHero theme={theme} />+ <PreviewImage theme={theme} /><Tagline /></section>);diff --git a/docs/app/(home)/sections/Navbar/Navbar.module.css b/docs/app/(home)/sections/Navbar/Navbar.module.cssindex 61625def5..7e0b2894d 100644--- a/docs/app/(home)/sections/Navbar/Navbar.module.css+++ b/docs/app/(home)/sections/Navbar/Navbar.module.css@@ -3,63 +3,17 @@top: 0;z-index: 50;width: 100%;- padding: 0.75rem 1rem;- background: #fff;- transition: border-color 0.2s ease;+ --site-primary-nav-color: var(--home-color-text-primary);+ --site-primary-nav-hover-bg: var(--home-color-surface-soft);}-.navScrolled {- border-bottom: 1px solid var(--home-border-default);-}--.navInner {- display: flex;- max-width: 75rem;- margin-inline: auto;- align-items: center;- justify-content: space-between;-}--.logoCluster {- display: flex;- align-items: center;- gap: 0.5rem;-}--.logoDivider {- height: 1rem;- width: 1px;- background: var(--home-border-default);-}--.desktopTabs,-.desktopGithub {+.desktopActions {display: none;}-.desktopTabs {- align-items: center;+.desktopActions {gap: 0.5rem;-}--.desktopTabLink {- display: flex;- height: 2rem;align-items: center;- padding-inline: 0.5rem;- border-radius: 0.375rem;- color: #000;- text-decoration: none;- transition: background-color 0.2s ease;- font-family: "Inter Display", sans-serif;- font-size: 15px;- line-height: 1.5rem;-}--.desktopTabLink:hover,-.mobileTrayLink:hover,-.mobileMenuButton:hover {- background: rgb(0 0 0 / 5%);}.chevronIcon,@@ -81,6 +35,11 @@transition: background-color 0.2s ease;}+.mobileTrayLink:hover,+.mobileMenuButton:hover {+ background: var(--home-color-surface-soft);+}+.mobileBackdrop {position: absolute;top: 100%;@@ -104,10 +63,10 @@.mobileTray {pointer-events: auto;- border-top: 1px solid rgb(0 0 0 / 5%);+ border-top: 1px solid var(--home-border-soft);border-bottom-left-radius: 18px;border-bottom-right-radius: 18px;- background: #fff;+ background: var(--home-color-surface);box-shadow: var(--home-shadow-panel);}@@ -123,7 +82,7 @@.mobileTrayDivider {height: 1px;margin-inline: 0.75rem;- background: rgb(0 0 0 / 5%);+ background: var(--home-border-soft);}.mobileTrayLink {@@ -134,7 +93,7 @@gap: 0.25rem;padding-inline: 0.75rem;border-radius: 0.375rem;- color: #000;+ color: var(--home-color-text-primary);text-align: left;text-decoration: none;transition: background-color 0.2s ease;@@ -160,7 +119,7 @@padding-right: 0.5rem;border: 0;border-radius: 999px;- background: #fff;+ background: var(--home-color-surface);cursor: pointer;transform: scale(1.17);}@@ -180,12 +139,7 @@}@media (min-width: 1024px) {- .nav {- padding: 0.75rem 2rem;- }-- .desktopTabs,- .desktopGithub {+ .desktopActions {display: flex;}diff --git a/docs/app/(home)/sections/Navbar/Navbar.tsx b/docs/app/(home)/sections/Navbar/Navbar.tsxindex 625658596..ec2367df1 100644--- a/docs/app/(home)/sections/Navbar/Navbar.tsx+++ b/docs/app/(home)/sections/Navbar/Navbar.tsx@@ -1,187 +1,7 @@"use client";-import {- GitHubIcon,- GitHubStarButton,- OpenUILogo,- StarCountBadge,- ThesysLogo,- useGitHubStarCount,-} from "@/components/brand-logo";-import { AnimatePresence, motion } from "motion/react";-import { useCallback, useEffect, useState } from "react";-import styles from "./Navbar.module.css";--// ----------------------------------------------------------------------------// Constants-// -----------------------------------------------------------------------------const NAV_TABS = ["OpenUI Lang", "Playground", "API Reference", "Blog"] as const;-const TAB_URLS: Record<string, string> = {- "OpenUI Lang": "/docs/openui-lang",- Playground: "/playground",- "API Reference": "/docs/api-reference",- Components: "/docs/components",- Blog: "/blog",-};--// Sub-components-// -----------------------------------------------------------------------------function DesktopNavTabs() {- return (- <div className={styles.desktopTabs}>- {NAV_TABS.map((tab) => (- <a- key={tab}- href={TAB_URLS[tab]}- className={styles.desktopTabLink}- >- {tab}- </a>- ))}- </div>- );-}--function HamburgerIcon({ isOpen }: { isOpen: boolean }) {- return (- <svg- className={styles.hamburgerIcon}- fill="none"- viewBox="0 0 24 24"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- >- {isOpen ? (- <>- <path d="M18 6L6 18" />- <path d="M6 6l12 12" />- </>- ) : (- <>- <path d="M3 12h18" />- <path d="M3 6h18" />- <path d="M3 18h18" />- </>- )}- </svg>- );-}--function MobileMenu({ starCount, onClose }: { starCount: number | null; onClose: () => void }) {- return (- <>- {/* Backdrop overlay — below navbar (absolute top-full), covers rest of viewport */}- <motion.div- className={styles.mobileBackdrop}- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- exit={{ opacity: 0 }}- transition={{ duration: 0.2 }}- onClick={onClose}- />-- {/* Tray + floating GitHub button */}- <motion.div- className={styles.mobileTrayWrap}- initial={{ opacity: 0, y: -8 }}- animate={{ opacity: 1, y: 0 }}- exit={{ opacity: 0, y: -8 }}- transition={{ duration: 0.2 }}- >- {/* Tray */}- <div className={styles.mobileTray}>- <div className={styles.mobileTrayInner}>- {NAV_TABS.map((tab, index) => (- <div key={tab}>- {index > 0 && <div className={styles.mobileTrayDivider} />}- <a- href={TAB_URLS[tab]}- className={styles.mobileTrayLink}- >- {tab}- </a>- </div>- ))}- </div>- </div>-- {/* GitHub button — centered, 80px below tray, scaled up 140% */}- <div className={styles.mobileGithubButtonWrap}>- <a- href="https://github.com/thesysdev/openui"- target="_blank"- rel="noopener noreferrer"- className={styles.mobileGithubButton}- >- <div aria-hidden="true" className={styles.mobileGithubButtonOverlay} />- <GitHubIcon />- <StarCountBadge count={starCount} isHighlighted={false} />- </a>- </div>- </motion.div>- </>- );-}--// ----------------------------------------------------------------------------// Main component-// ---------------------------------------------------------------------------+import { SiteMarketingHeader } from "@/components/site-marketing-header";export function Navbar() {- const [isLogoHovered, setIsLogoHovered] = useState(false);- const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);- const [isScrolled, setIsScrolled] = useState(false);- const starCount = useGitHubStarCount("thesysdev/openui");-- useEffect(() => {- const handleScroll = () => {- setIsScrolled(window.scrollY > 0);- };- window.addEventListener("scroll", handleScroll, { passive: true });- handleScroll();- return () => window.removeEventListener("scroll", handleScroll);- }, []);-- const toggleMobileMenu = useCallback(() => {- setIsMobileMenuOpen((prev) => !prev);- }, []);-- return (- <nav className={`${styles.nav} ${isScrolled ? styles.navScrolled : ""}`.trim()}>- <div className={styles.navInner}>- {/* Left: Logos */}- <div className={styles.logoCluster}>- <ThesysLogo isHovered={isLogoHovered} onHoverChange={setIsLogoHovered} />- <div className={styles.logoDivider} />- <OpenUILogo />- </div>-- {/* Center: Nav tabs (desktop only) */}- <DesktopNavTabs />-- {/* Right: GitHub button (desktop only) */}- <div className={styles.desktopGithub}>- <GitHubStarButton repo="thesysdev/openui" isScrolled={isScrolled} />- </div>-- {/* Right: Hamburger (mobile only) */}- <button- className={styles.mobileMenuButton}- onClick={toggleMobileMenu}- aria-label="Toggle menu"- >- <HamburgerIcon isOpen={isMobileMenuOpen} />- </button>- </div>-- {/* Mobile dropdown menu */}- <AnimatePresence>- {isMobileMenuOpen && <MobileMenu starCount={starCount} onClose={toggleMobileMenu} />}- </AnimatePresence>- </nav>- );+ return <SiteMarketingHeader borderMode="scroll" themeToggle={null} brandVariant="light" />;}diff --git a/docs/app/(home)/sections/PossibilitiesSection/PossibilitiesSection.module.css b/docs/app/(home)/sections/PossibilitiesSection/PossibilitiesSection.module.cssindex 8de47f2de..49c722470 100644--- a/docs/app/(home)/sections/PossibilitiesSection/PossibilitiesSection.module.css+++ b/docs/app/(home)/sections/PossibilitiesSection/PossibilitiesSection.module.css@@ -5,51 +5,79 @@.headerContainer {max-width: 75rem;margin-inline: auto;- padding-inline: var(--home-section-padding-inline);+ padding-inline: 1.25rem;}.header {+ display: flex;+ justify-content: center;+ width: 100%;margin-bottom: 2rem;}.title {- max-width: 673px;- font-family: "Inter", sans-serif;- font-size: 22px;+ margin: 0;+ text-align: center;+ font-size: 2.5rem;font-weight: 600;- line-height: 1.25;- color: #000;+ line-height: 1.2;+ letter-spacing: -2px;+ color: var(--openui-text-neutral-primary);+}++.cardsContainer {+ max-width: 80rem;+ margin-inline: auto;}-.trackViewport {+.mobileCarouselViewport {overflow: hidden;- margin-block: -2rem;- padding-block: 2rem;+ padding-inline: 1.25rem;}-.track {+.mobileCarouselTrack {display: flex;width: max-content;gap: 1rem;- padding-left: 1rem;- user-select: none;will-change: transform;}-.trackIdle {- cursor: grab;-}--.trackDragging {- cursor: grabbing;+.cardsGrid {+ display: none;}.card {position: relative;- width: 240px;- flex-shrink: 0;- border-radius: 14px;- background: #fff;+ width: 100%;+ max-width: calc((100vw - 3.5rem) / 1.5);+ flex: 0 0 calc((100vw - 3.5rem) / 1.5);+ border-radius: var(--openui-radius-4xl);+ background: var(--openui-foreground);+}++.cardLink {+ display: block;+ color: inherit;+ text-decoration: none;+ cursor: pointer;+ transition:+ transform 160ms ease,+ box-shadow 160ms ease;+}++.cardLink:hover {+ transform: translateY(-2px);+}++.cardLink:focus-visible {+ outline: 2px solid var(--openui-border-accent);+ outline-offset: 4px;+}++.cardLink:hover .cardOverlay,+.cardLink:focus-visible .cardOverlay {+ border-color: var(--openui-border-accent);+ box-shadow: var(--openui-shadow-l);}.cardInner {@@ -60,20 +88,15 @@border-radius: inherit;}-.cardImage,-.cardImagePlaceholder {- width: 100%;- aspect-ratio: 5 / 4;- border-top-left-radius: 14px;- border-top-right-radius: 14px;-}-.cardImage {+ display: block;+ width: 100%;+ aspect-ratio: 1 / 1;+ border-top-left-radius: inherit;+ border-top-right-radius: inherit;object-fit: cover;-}--.cardImagePlaceholder {- background: rgb(0 0 0 / 4%);+ -webkit-mask-image: linear-gradient(to bottom, #000 0%, #000 82%, transparent 100%);+ mask-image: linear-gradient(to bottom, #000 0%, #000 82%, transparent 100%);}.cardBody {@@ -86,34 +109,42 @@font-size: 14px;font-weight: 500;line-height: 1.4;- color: #000;+ color: var(--openui-text-neutral-primary);}.cardOverlay {position: absolute;inset: 0;pointer-events: none;- border: 1px solid var(--home-border-soft);- border-radius: 14px;- box-shadow:- 0 1px 2px 0 rgb(22 34 51 / 4%),- 0 8px 16px 0 rgb(22 34 51 / 4%);+ border: 1px solid var(--openui-border-default);+ border-radius: inherit;+ box-shadow: var(--openui-shadow-m);}@media (min-width: 1024px) {- .title {- font-size: 32px;+ .headerContainer {+ padding-inline: 2rem;}- .card {- width: 300px;- border-radius: 18px;+ .mobileCarouselViewport {+ display: none;+ }++ .cardsGrid {+ display: grid;+ grid-template-columns: repeat(4, minmax(0, 1fr));+ max-width: none;+ margin-inline: 0;+ gap: 1.25rem;+ }++ .cardsContainer {+ padding-inline: 2rem;}- .cardImage,- .cardImagePlaceholder {- border-top-left-radius: 16px;- border-top-right-radius: 16px;+ .card {+ max-width: none;+ flex: initial;}.cardBody {@@ -122,10 +153,6 @@.cardTitle {font-family: "Inter Display", sans-serif;- font-size: 22px;- }-- .cardOverlay {- border-radius: 18px;+ font-size: 18px;}}diff --git a/docs/app/(home)/sections/PossibilitiesSection/PossibilitiesSection.tsx b/docs/app/(home)/sections/PossibilitiesSection/PossibilitiesSection.tsxindex 9d3a1cffd..0c9f20b1e 100644--- a/docs/app/(home)/sections/PossibilitiesSection/PossibilitiesSection.tsx+++ b/docs/app/(home)/sections/PossibilitiesSection/PossibilitiesSection.tsx@@ -1,175 +1,182 @@"use client";-import { useCallback, useEffect, useRef, useState } from "react";+import { useEffect, useRef } from "react";import styles from "./PossibilitiesSection.module.css";-const listCardImg = "/images/home/0ea99cfd72e99c55c9511d4e0c3fbb08d37fbafd.png";-const chartsCardImg = "/images/home/9fbf5ad1316183d81279510b9fceb2bd1b538523.png";-const formsCardImg = "/images/home/8ae798233176b4d64e44605bb283d7a9886fed7a.png";-const cardsCardImg = "/images/home/f380a0bc9e6bc51606848a52165d0b85e68cdc94.png";-const tablesCardImg = "/images/home/6529ac618f10178dc5029ec6ecc15836aebf61d3.png";+const bottomTraysLightImg = "/homepage/tray-light.png";+const bottomTraysDarkImg = "/homepage/tray-dark.png";// ---------------------------------------------------------------------------// Data// ----------------------------------------------------------------------------const CARD_TITLES = ["Charts", "Forms", "Cards", "Tables", "List"] as const;-const MARQUEE_COPIES = 3;-const SCROLL_SPEED = 0.5; // px per frame+type CardImageSet = {+ title: string;+ lightImage: string;+ darkImage: string;+ href?: string;+};++const MOBILE_CAROUSEL_COPIES = 3;+const MOBILE_SCROLL_SPEED = 0.35;++const CARDS: readonly CardImageSet[] = [+ {+ title: "Conversational Apps",+ lightImage: "/homepage/conversational-apps-light.png",+ darkImage: "/homepage/conversational-apps-dark.png",+ href: "https://github.com/thesysdev/openui/tree/main/examples/openui-chat",+ },+ {+ title: "Dashboards & Web-apps",+ lightImage: "/homepage/dashboard-light.png",+ darkImage: "/homepage/dashboard-dark.png",+ },+ {+ title: "Mobile Apps",+ lightImage: "/homepage/mobile-light.png",+ darkImage: "/homepage/mobile-dark.png",+ href: "https://github.com/thesysdev/openui/tree/main/examples/openui-react-native",+ },+ {+ title: "Bottom trays",+ lightImage: bottomTraysLightImg,+ darkImage: bottomTraysDarkImg,+ },+];++const MOBILE_CAROUSEL_CARDS = Array.from({ length: MOBILE_CAROUSEL_COPIES }, (_, copyIndex) =>+ CARDS.map((card) => ({+ ...card,+ key: `${card.title}-${copyIndex}`,+ })),+).flat();// ---------------------------------------------------------------------------// Sub-components// ----------------------------------------------------------------------------const IMAGE_MAP: Record<string, string> = {- List: listCardImg,- Charts: chartsCardImg,- Forms: formsCardImg,- Cards: cardsCardImg,- Tables: tablesCardImg,-};--function Card({ title }: { title: string }) {- const img = IMAGE_MAP[title];- return (- <div className={styles.card}>+function Card({ title, image, href }: { title: string; image: string; href?: string }) {+ const content = (+ <><div className={styles.cardInner}>- {img ? (- <img- src={img}- alt={`${title} illustration`}- className={styles.cardImage}- draggable={false}- />- ) : (- <div className={styles.cardImagePlaceholder} />- )}+ <img+ src={image}+ alt={`${title} illustration`}+ className={styles.cardImage}+ draggable={false}+ /><div className={styles.cardBody}>- <p className={styles.cardTitle}>- {title}- </p>+ <p className={styles.cardTitle}>{title}</p></div></div><div className={styles.cardOverlay} />- </div>+ </>);-}-// Pre-build the repeated card list so it's not re-created on every render-const MARQUEE_CARDS = Array.from({ length: MARQUEE_COPIES }, (_, copy) =>- CARD_TITLES.map((title) => ({ title, key: `${title}-${copy}` })),-).flat();+ if (!href) {+ return <div className={styles.card}>{content}</div>;+ }++ return (+ <a+ href={href}+ target="_blank"+ rel="noreferrer"+ aria-label={`Open ${title} example on GitHub`}+ className={`${styles.card} ${styles.cardLink}`}+ >+ {content}+ </a>+ );+}// ---------------------------------------------------------------------------// Main component// ---------------------------------------------------------------------------export function PossibilitiesSection() {- const scrollRef = useRef<HTMLDivElement>(null);- const offsetRef = useRef(0);- const rafRef = useRef(0);- const isPausedRef = useRef(false);- const isDraggingRef = useRef(false);- const dragStartXRef = useRef(0);- const dragStartOffsetRef = useRef(0);+ const mobileTrackRef = useRef<HTMLDivElement>(null);- const [isDragging, setIsDragging] = useState(false);-- // Auto-scroll loopuseEffect(() => {- const el = scrollRef.current;- if (!el) return;-- const singleSetWidth = () => el.scrollWidth / MARQUEE_COPIES;-- function tick() {- if (!isPausedRef.current && !isDraggingRef.current) {- offsetRef.current -= SCROLL_SPEED;+ const track = mobileTrackRef.current;+ if (!track) return;++ const mobileMediaQuery = window.matchMedia("(max-width: 1023px)");+ let frameId = 0;+ let offset = 0;++ const resetTrack = () => {+ offset = 0;+ track.style.transform = "translateX(0px)";+ };++ const tick = () => {+ if (mobileMediaQuery.matches) {+ const loopWidth = track.scrollWidth / MOBILE_CAROUSEL_COPIES;++ if (loopWidth > 0) {+ offset -= MOBILE_SCROLL_SPEED;+ if (offset <= -loopWidth) {+ offset += loopWidth;+ }++ track.style.transform = `translateX(${offset}px)`;+ }+ } else if (offset !== 0) {+ resetTrack();}- const totalWidth = singleSetWidth();- if (totalWidth > 0) {- // Seamless wrap in both directions- if (offsetRef.current < -totalWidth) offsetRef.current += totalWidth;- if (offsetRef.current > 0) offsetRef.current -= totalWidth;- }-- el!.style.transform = `translateX(${offsetRef.current}px)`;- rafRef.current = requestAnimationFrame(tick);- }-- rafRef.current = requestAnimationFrame(tick);- return () => cancelAnimationFrame(rafRef.current);- }, []);-- // Drag handlers- const handlePointerDown = useCallback((e: React.PointerEvent) => {- const el = scrollRef.current;- if (!el) return;-- isDraggingRef.current = true;- setIsDragging(true);- el.setPointerCapture(e.pointerId);- dragStartXRef.current = e.clientX;- dragStartOffsetRef.current = offsetRef.current;- }, []);+ frameId = window.requestAnimationFrame(tick);+ };- const handlePointerMove = useCallback((e: React.PointerEvent) => {- if (!isDraggingRef.current) return;- offsetRef.current = dragStartOffsetRef.current + (e.clientX - dragStartXRef.current);- }, []);-- const handlePointerUp = useCallback((e: React.PointerEvent) => {- const el = scrollRef.current;- if (!isDraggingRef.current || !el) return;+ const handleViewportChange = () => {+ resetTrack();+ };- el.releasePointerCapture(e.pointerId);- isDraggingRef.current = false;- setIsDragging(false);+ mobileMediaQuery.addEventListener("change", handleViewportChange);+ frameId = window.requestAnimationFrame(tick);- // Normalize offset for seamless loop- const totalWidth = el.scrollWidth / MARQUEE_COPIES;- if (totalWidth > 0) {- while (offsetRef.current > 0) offsetRef.current -= totalWidth;- while (offsetRef.current < -totalWidth) offsetRef.current += totalWidth;- }- }, []);-- const pauseScroll = useCallback(() => {- isPausedRef.current = true;- }, []);- const resumeScroll = useCallback(() => {- isPausedRef.current = false;+ return () => {+ window.cancelAnimationFrame(frameId);+ mobileMediaQuery.removeEventListener("change", handleViewportChange);+ track.style.transform = "";+ };}, []);return (- <div className={styles.section}>- {/* Header */}+ <section className={styles.section}><div className={styles.headerContainer}><div className={styles.header}>- <h2 className={styles.title}>- Endless possibilities. Built in realtime.- </h2>+ <h2 className={styles.title}>Endless possibilities. Built in realtime.</h2></div></div>- {/* Marquee track */}- <div className={styles.trackViewport}>- <div- ref={scrollRef}- className={`${styles.track} ${isDragging ? styles.trackDragging : styles.trackIdle}`}- onMouseEnter={pauseScroll}- onMouseLeave={resumeScroll}- onPointerDown={handlePointerDown}- onPointerMove={handlePointerMove}- onPointerUp={handlePointerUp}- onPointerCancel={handlePointerUp}- >- {MARQUEE_CARDS.map(({ title, key }) => (- <Card key={key} title={title} />+ <div className={styles.cardsContainer}>+ <div className={styles.mobileCarouselViewport}>+ <div ref={mobileTrackRef} className={styles.mobileCarouselTrack}>+ {MOBILE_CAROUSEL_CARDS.map((card) => (+ <Card+ key={card.key}+ title={card.title}+ image={card.lightImage}+ href={card.href}+ />+ ))}+ </div>+ </div>++ <div className={styles.cardsGrid}>+ {CARDS.map((card) => (+ <Card+ key={card.title}+ title={card.title}+ image={card.lightImage}+ href={card.href}+ />))}</div></div>- </div>+ </section>);}diff --git a/docs/app/(home)/sections/ShiroMascot/ShiroMascot.module.css b/docs/app/(home)/sections/ShiroMascot/ShiroMascot.module.cssindex 81a054514..c296cb30f 100644--- a/docs/app/(home)/sections/ShiroMascot/ShiroMascot.module.css+++ b/docs/app/(home)/sections/ShiroMascot/ShiroMascot.module.css@@ -19,6 +19,7 @@left: 8%;width: 83.84%;height: 115.47%;+ color: var(--openui-text-neutral-primary);}@media (min-width: 1024px) {diff --git a/docs/app/(home)/sections/ShiroMascot/ShiroMascot.tsx b/docs/app/(home)/sections/ShiroMascot/ShiroMascot.tsxindex 9e44a08e4..4e52b6bf2 100644--- a/docs/app/(home)/sections/ShiroMascot/ShiroMascot.tsx+++ b/docs/app/(home)/sections/ShiroMascot/ShiroMascot.tsx@@ -5,19 +5,15 @@ export function ShiroMascot() {return (<div className={styles.root}><div className={styles.figure}>- <svg- className={styles.svg}- fill="none"- viewBox="0 0 111.502 100.458"- >- <path d={svgPaths.p1ea82800} fill="black" />- <path d={svgPaths.p372c6800} fill="black" />- <path d={svgPaths.p183f7dc0} fill="black" />- <path d={svgPaths.p1fe91040} fill="black" />- <path d={svgPaths.p1abf95f0} fill="black" />- <path d={svgPaths.p256a8280} fill="black" />- <path d={svgPaths.p2fe128c0} fill="black" />- <path d={svgPaths.p1fb75100} fill="black" />+ <svg className={styles.svg} fill="none" viewBox="0 0 111.502 100.458">+ <path d={svgPaths.p1ea82800} fill="currentColor" />+ <path d={svgPaths.p372c6800} fill="currentColor" />+ <path d={svgPaths.p183f7dc0} fill="currentColor" />+ <path d={svgPaths.p1fe91040} fill="currentColor" />+ <path d={svgPaths.p1abf95f0} fill="currentColor" />+ <path d={svgPaths.p256a8280} fill="currentColor" />+ <path d={svgPaths.p2fe128c0} fill="currentColor" />+ <path d={svgPaths.p1fb75100} fill="currentColor" /></svg></div></div>diff --git a/docs/app/(home)/sections/StepsSection/StepsSection.module.css b/docs/app/(home)/sections/StepsSection/StepsSection.module.cssindex fe0ef96ce..ae7db869f 100644--- a/docs/app/(home)/sections/StepsSection/StepsSection.module.css+++ b/docs/app/(home)/sections/StepsSection/StepsSection.module.css@@ -1,6 +1,6 @@.section {width: 100%;- padding-inline: var(--home-section-padding-inline);+ padding-inline: 1.25rem;}.container {@@ -8,3 +8,8 @@margin-inline: auto;}+@media (min-width: 1024px) {+ .section {+ padding-inline: 2rem;+ }+}diff --git a/docs/app/(home)/sections/StepsSection/StepsSection.tsx b/docs/app/(home)/sections/StepsSection/StepsSection.tsxindex 20998b2a2..a07aba37d 100644--- a/docs/app/(home)/sections/StepsSection/StepsSection.tsx+++ b/docs/app/(home)/sections/StepsSection/StepsSection.tsx@@ -4,7 +4,10 @@ import LlmRespondsInOpenUiLang from "@/imports/LlmRespondsInOpenUiLang";import OpenUiGeneratesSchema from "@/imports/OpenUiGeneratesSchema";import OpenUiRendererRendersIt from "@/imports/OpenUiRendererRendersIt-43-427";import YouRegisterComponents from "@/imports/YouRegisterComponents-43-365";-import { StepsAccordion, type StepsAccordionItem } from "../../components/StepsAccordion/StepsAccordion";+import {+ StepsAccordion,+ type StepsAccordionItem,+} from "../../components/StepsAccordion/StepsAccordion";import styles from "./StepsSection.module.css";// ---------------------------------------------------------------------------diff --git a/docs/app/(home)/sections/TweetWallSection/TweetWallSection.module.css b/docs/app/(home)/sections/TweetWallSection/TweetWallSection.module.cssnew file mode 100644index 000000000..81b6ba7c1--- /dev/null+++ b/docs/app/(home)/sections/TweetWallSection/TweetWallSection.module.css@@ -0,0 +1,12 @@+.section {+ width: min(100%, 1200px);+ margin-inline: auto;+ padding-inline: 1.25rem;+ box-sizing: border-box;+}++@media (min-width: 1024px) {+ .section {+ padding-inline: 2rem;+ }+}diff --git a/docs/app/(home)/sections/TweetWallSection/TweetWallSection.tsx b/docs/app/(home)/sections/TweetWallSection/TweetWallSection.tsxnew file mode 100644index 000000000..3b4a23a72--- /dev/null+++ b/docs/app/(home)/sections/TweetWallSection/TweetWallSection.tsx@@ -0,0 +1,11 @@+import { TweetWall } from "../../components/TweetWall/TweetWall";+import styles from "./TweetWallSection.module.css";++/** Full-width social proof — not wrapped in the BuildChat card; sits on the home content band. */+export function TweetWallSection() {+ return (+ <section className={styles.section} aria-label="What people are saying on X">+ <TweetWall />+ </section>+ );+}diff --git a/docs/app/(home)/sections/UILibrariesSection/UILibrariesSection.module.css b/docs/app/(home)/sections/UILibrariesSection/UILibrariesSection.module.cssindex 99e6f36d0..6196b5f2e 100644--- a/docs/app/(home)/sections/UILibrariesSection/UILibrariesSection.module.css+++ b/docs/app/(home)/sections/UILibrariesSection/UILibrariesSection.module.css@@ -1,6 +1,6 @@.section {width: 100%;- padding-inline: var(--home-section-padding-inline);+ padding-inline: 1.25rem;}.container {@@ -17,7 +17,7 @@font-size: 22px;font-weight: 600;line-height: 1.25;- color: #000;+ color: var(--openui-text-neutral-primary);}.mobileOnly {@@ -39,9 +39,9 @@display: flex;flex: 1;height: 3.5rem;- border: 1px solid var(--home-border-default);+ border: 1px solid var(--openui-border-interactive);border-radius: 14px;- background: var(--home-color-surface);+ background: var(--openui-foreground);box-shadow: 0 4px 10px -4px rgb(22 34 51 / 5%);}@@ -65,7 +65,7 @@}.iconBadgeOpenUi {- background: var(--home-color-surface-muted);+ background: var(--openui-highlight-strong);}.iconBadgeShadcn {@@ -130,10 +130,14 @@font-size: 16px;font-weight: 500;line-height: 1.4;- color: #000;+ color: var(--openui-text-neutral-primary);}@media (min-width: 1024px) {+ .section {+ padding-inline: 2rem;+ }+.header {margin-bottom: 2rem;}diff --git a/docs/app/(home)/sections/UILibrariesSection/UILibrariesSection.tsx b/docs/app/(home)/sections/UILibrariesSection/UILibrariesSection.tsxindex 096513d80..1522d6ac7 100644--- a/docs/app/(home)/sections/UILibrariesSection/UILibrariesSection.tsx+++ b/docs/app/(home)/sections/UILibrariesSection/UILibrariesSection.tsx@@ -145,9 +145,7 @@ function LibraryCard({ lib }: { lib: UILibrary }) {</div>{/* Name */}- <span className={styles.name}>- {displayName}- </span>+ <span className={styles.name}>{displayName}</span></div></div>);diff --git a/docs/app/api/demo/github/stream/route.ts b/docs/app/api/demo/github/stream/route.tsnew file mode 100644index 000000000..ac4ca6092--- /dev/null+++ b/docs/app/api/demo/github/stream/route.ts@@ -0,0 +1,102 @@+import { BASE_URL } from "@/lib/source";+import { generatePrompt, type PromptSpec } from "@openuidev/lang-core";+import { readFileSync } from "fs";+import { type NextRequest } from "next/server";+import { join } from "path";+import {+ GITHUB_ADDITIONAL_RULES,+ GITHUB_PREAMBLE,+ GITHUB_TOOL_EXAMPLES,+} from "../../../../demo/github/github/prompt-config";+import { GITHUB_TOOL_SPECS } from "../../../../demo/github/github/types";++const MODEL = "openai/gpt-5.4-mini";++// ── Component spec from generated JSON ────────────────────────────────────++const componentSpec = JSON.parse(+ readFileSync(join(process.cwd(), "generated/playground-component-spec.json"), "utf-8"),+) as PromptSpec;++// ── GitHub system prompt ──────────────────────────────────────────────────++function buildGitHubPrompt(): string {+ return generatePrompt({+ ...componentSpec,+ tools: GITHUB_TOOL_SPECS,+ toolExamples: GITHUB_TOOL_EXAMPLES,+ additionalRules: GITHUB_ADDITIONAL_RULES,+ preamble: GITHUB_PREAMBLE,+ editMode: true,+ inlineMode: true,+ toolCalls: true,+ bindings: true,+ });+}++let cachedPrompt: string | null = null;+function getPrompt(): string {+ if (!cachedPrompt) cachedPrompt = buildGitHubPrompt();+ return cachedPrompt;+}++// ── Route handler ──────────────────────────────────────────────────────────++export async function POST(req: NextRequest) {+ const { prompt, messages } = await req.json();++ const systemPrompt = getPrompt();++ const chatMessages: Array<{ role: string; content: string }> = [+ { role: "system", content: systemPrompt },+ ];+ if (messages && Array.isArray(messages)) {+ for (const m of messages) {+ chatMessages.push({ role: m.role, content: m.content });+ }+ }+ chatMessages.push({ role: "user", content: prompt });++ const apiKey = process.env.OPENROUTER_API_KEY;+ if (!apiKey) {+ return Response.json(+ { error: { message: "OPENROUTER_API_KEY not configured" } },+ { status: 500 },+ );+ }++ const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {+ method: "POST",+ headers: {+ Authorization: `Bearer ${apiKey}`,+ "Content-Type": "application/json",+ "HTTP-Referer": `${BASE_URL}/demo/github`,+ "X-Title": "OpenUI GitHub Demo",+ },+ body: JSON.stringify({+ model: MODEL,+ stream: true,+ messages: chatMessages,+ }),+ signal: req.signal,+ });++ if (!res.ok) {+ const err = await res.json().catch(() => ({}));+ return Response.json(+ {+ error: (err as { error?: { message?: string } }).error ?? {+ message: `OpenRouter error ${res.status}`,+ },+ },+ { status: res.status },+ );+ }++ return new Response(res.body, {+ headers: {+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache",+ },+ });+}diff --git a/docs/app/blog/[slug]/page.tsx b/docs/app/blog/[slug]/page.tsxindex 24eb99d99..f5aad0d95 100644--- a/docs/app/blog/[slug]/page.tsx+++ b/docs/app/blog/[slug]/page.tsx@@ -1,8 +1,8 @@import { PillLink } from "@/app/(home)/components/Button/Button";import { blog } from "@/lib/source";import { getMDXComponents } from "@/mdx-components";-import { TOCProvider, TOCScrollArea } from "fumadocs-ui/components/toc/index";import { TOCItems } from "fumadocs-ui/components/toc/default";+import { TOCProvider, TOCScrollArea } from "fumadocs-ui/components/toc/index";import type { Metadata } from "next";import { notFound } from "next/navigation";@@ -14,9 +14,7 @@ function BlogGithubIcon() {);}-export default async function BlogPostPage(props: {- params: Promise<{ slug: string }>;-}) {+export default async function BlogPostPage(props: { params: Promise<{ slug: string }> }) {const params = await props.params;const page = blog.getPage([params.slug]);@@ -28,9 +26,7 @@ export default async function BlogPostPage(props: {<main className="mx-auto flex w-full max-w-[1200px] gap-4 px-4 pt-16 pb-40 lg:gap-28 lg:pr-8 min-[1249px]:pl-0 min-[1024px]:max-[1248px]:pl-8"><aside className="hidden w-56 shrink-0 lg:block"><div className="sticky top-24">- <p className="mb-3 text-sm font-medium text-fd-foreground">- On this page- </p>+ <p className="mb-3 text-sm font-medium text-fd-foreground">On this page</p><TOCScrollArea className="max-h-[calc(100vh-8rem)]"><TOCItems /></TOCScrollArea>@@ -39,9 +35,7 @@ export default async function BlogPostPage(props: {<div className="min-w-0 flex-1"><h1 className="mb-2 text-3xl font-bold">{page.data.title}</h1>- <p className="mb-4 text-fd-muted-foreground">- {page.data.description}- </p>+ <p className="mb-4 text-fd-muted-foreground">{page.data.description}</p><div className="flex items-center gap-3 border-b pb-6 text-sm text-fd-muted-foreground"><span>{page.data.author}</span><span>·</span>diff --git a/docs/app/blog/components/BlogNavbar.module.css b/docs/app/blog/components/BlogNavbar.module.cssnew file mode 100644index 000000000..0366dac6f--- /dev/null+++ b/docs/app/blog/components/BlogNavbar.module.css@@ -0,0 +1,150 @@+.nav {+ position: sticky;+ top: 0;+ z-index: 50;+ width: 100%;+ --home-color-surface: var(--blog-nav-bg);+ --site-primary-nav-color: var(--blog-nav-text);+ --site-primary-nav-hover-bg: var(--blog-nav-hover);+}++.desktopActions {+ display: none;+ align-items: center;+ gap: 0.5rem;+}++.hamburgerIcon {+ width: 1.25rem;+ height: 1.25rem;+}++.mobileMenuButton {+ display: flex;+ width: 2.5rem;+ height: 2.5rem;+ align-items: center;+ justify-content: center;+ border: 0;+ border-radius: 0.5rem;+ background: transparent;+ color: var(--blog-nav-text);+ cursor: pointer;+ transition: background-color 0.2s ease;+}++.mobileMenuButton:hover,+.mobileTrayLink:hover {+ background: var(--blog-nav-hover);+}++.mobileBackdrop {+ position: absolute;+ top: 100%;+ left: 0;+ right: 0;+ z-index: 40;+ height: 100vh;+ cursor: pointer;+ background: rgb(0 0 0 / 60%);+ backdrop-filter: blur(12px);+}++.mobileTrayWrap {+ position: absolute;+ top: 100%;+ left: 0;+ right: 0;+ z-index: 50;+ pointer-events: none;+}++.mobileTray {+ pointer-events: auto;+ border-top: 1px solid var(--blog-nav-border);+ border-bottom-left-radius: 18px;+ border-bottom-right-radius: 18px;+ background: var(--blog-nav-bg);+ box-shadow: 0 10px 20px rgb(0 0 0 / 10%);+}++.mobileTrayInner {+ display: flex;+ width: 100%;+ max-width: 1480px;+ margin-inline: auto;+ flex-direction: column;+ gap: 0;+ padding: 0.75rem 1rem 1.25rem;+}++.mobileTrayDivider {+ height: 1px;+ margin-inline: 0.75rem;+ background: var(--blog-nav-border);+}++.mobileTrayLink {+ display: flex;+ width: 100%;+ height: 3.5rem;+ align-items: center;+ gap: 0.25rem;+ padding-inline: 0.75rem;+ border-radius: 0.375rem;+ color: var(--blog-nav-text);+ text-align: left;+ text-decoration: none;+ transition: background-color 0.2s ease;+ font-family: "Inter", sans-serif;+ font-size: 18px;+ line-height: 1.5rem;+}++.mobileGithubButtonWrap {+ display: flex;+ justify-content: center;+ padding-top: 80px;+ pointer-events: auto;+}++.mobileGithubButton {+ position: relative;+ display: flex;+ height: 38px;+ align-items: center;+ gap: 0.375rem;+ padding-left: 0.75rem;+ padding-right: 0.5rem;+ border: 0;+ border-radius: 999px;+ background: var(--blog-nav-bg);+ cursor: pointer;+ transform: scale(1.17);+}++.mobileGithubButton:hover .mobileGithubButtonOverlay {+ box-shadow: none;+}++.mobileGithubButtonOverlay {+ position: absolute;+ inset: 0;+ pointer-events: none;+ border: 1px solid var(--blog-nav-border);+ border-radius: 999px;+ box-shadow: var(--mobile-github-button-shadow, none);+ transition: box-shadow 0.2s ease;+}++@media (min-width: 1024px) {+ .desktopActions {+ display: flex;+ }++ .mobileMenuButton,+ .mobileBackdrop,+ .mobileTrayWrap {+ display: none;+ }+}diff --git a/docs/app/blog/components/BlogNavbar.tsx b/docs/app/blog/components/BlogNavbar.tsxindex e677dcfb6..7252cc17e 100644--- a/docs/app/blog/components/BlogNavbar.tsx+++ b/docs/app/blog/components/BlogNavbar.tsx@@ -1,199 +1,7 @@"use client";-import {- GitHubIcon,- GitHubStarButton,- OpenUILogo,- StarCountBadge,- ThesysLogo,- useGitHubStarCount,-} from "@/components/brand-logo";-import { ThemeToggle } from "@/components/theme-toggle";-import { AnimatePresence, motion } from "motion/react";-import { useTheme } from "next-themes";-import { useCallback, useEffect, useState, type CSSProperties } from "react";--const BUTTON_SHADOW = "0px 1px 3px 0px rgba(22,34,51,0.08), 0px 12px 24px 0px rgba(22,34,51,0.04)";--const NAV_TABS = ["OpenUI Lang", "Playground", "API Reference", "Blog"] as const;-const TAB_URLS: Record<string, string> = {- "OpenUI Lang": "/docs/openui-lang",- Playground: "/playground",- "API Reference": "/docs/api-reference",- Blog: "/blog",-};--function DesktopNavTabs() {- return (- <div className="hidden lg:flex items-center gap-2">- {NAV_TABS.map((tab) => (- <a- key={tab}- href={TAB_URLS[tab]}- className="flex h-8 items-center px-2 rounded-md text-[var(--blog-nav-text)] no-underline transition-colors duration-200 font-['Inter_Display',sans-serif] text-[15px] leading-6 hover:bg-[var(--blog-nav-hover)]"- >- {tab}- </a>- ))}- </div>- );-}--function HamburgerIcon({ isOpen }: { isOpen: boolean }) {- return (- <svg- className="size-5"- fill="none"- viewBox="0 0 24 24"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- >- {isOpen ? (- <>- <path d="M18 6L6 18" />- <path d="M6 6l12 12" />- </>- ) : (- <>- <path d="M3 12h18" />- <path d="M3 6h18" />- <path d="M3 18h18" />- </>- )}- </svg>- );-}--function MobileMenu({ starCount, onClose }: { starCount: number | null; onClose: () => void }) {- const mobileGithubStyle = {- "--mobile-github-button-shadow": BUTTON_SHADOW,- } as CSSProperties;-- return (- <>- <motion.div- className="absolute top-full left-0 right-0 z-40 h-screen cursor-pointer bg-black/60 backdrop-blur-[12px]"- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- exit={{ opacity: 0 }}- transition={{ duration: 0.2 }}- onClick={onClose}- />- <motion.div- className="absolute top-full left-0 right-0 z-50 pointer-events-none lg:hidden"- initial={{ opacity: 0, y: -8 }}- animate={{ opacity: 1, y: 0 }}- exit={{ opacity: 0, y: -8 }}- transition={{ duration: 0.2 }}- >- <div className="pointer-events-auto border-t border-[var(--blog-nav-border)] rounded-b-[18px] bg-[var(--blog-nav-bg)] shadow-[0_10px_20px_rgb(0_0_0/0.1)]">- <div className="flex max-w-[75rem] mx-auto flex-col gap-0 pt-3 px-[1.75rem] pb-5">- {NAV_TABS.map((tab, index) => (- <div key={tab}>- {index > 0 && <div className="h-px mx-3 bg-[var(--blog-nav-border)]" />}- <a- href={TAB_URLS[tab]}- className="flex w-full h-14 items-center gap-1 px-3 rounded-md text-[var(--blog-nav-text)] text-left no-underline transition-colors duration-200 font-['Inter',sans-serif] text-lg leading-6 hover:bg-[var(--blog-nav-hover)]"- >- {tab}- </a>- </div>- ))}- </div>- </div>- <div className="flex justify-center pt-20 pointer-events-auto">- <a- href="https://github.com/thesysdev/openui"- target="_blank"- rel="noopener noreferrer"- className="group relative flex h-[38px] items-center gap-1.5 pl-3 pr-2 border-0 rounded-full bg-[var(--blog-nav-bg)] cursor-pointer scale-[1.17]"- >- <div- aria-hidden="true"- className="absolute inset-0 pointer-events-none border border-[var(--blog-nav-border)] rounded-full shadow-[var(--mobile-github-button-shadow,none)] transition-shadow duration-200 group-hover:shadow-none"- style={mobileGithubStyle}- />- <GitHubIcon />- <StarCountBadge count={starCount} isHighlighted={false} />- </a>- </div>- </motion.div>- </>- );-}+import { SiteMarketingHeader } from "@/components/site-marketing-header";export function BlogNavbar() {- const [isLogoHovered, setIsLogoHovered] = useState(false);- const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);- const [isScrolled, setIsScrolled] = useState(false);- const starCount = useGitHubStarCount("thesysdev/openui");- const { resolvedTheme } = useTheme();- const [mounted, setMounted] = useState(false);-- useEffect(() => {- setMounted(true);- }, []);-- useEffect(() => {- const handleScroll = () => setIsScrolled(window.scrollY > 0);- window.addEventListener("scroll", handleScroll, { passive: true });- handleScroll();- return () => window.removeEventListener("scroll", handleScroll);- }, []);-- const toggleMobileMenu = useCallback(() => {- setIsMobileMenuOpen((prev) => !prev);- }, []);-- const isDark = mounted && resolvedTheme === "dark";- const logoVariant = isDark ? "dark" : "light";- const borderColor = isDark ? "rgba(255,255,255,0.1)" : "rgba(0,0,0,0.1)";-- const navStyle = {- "--blog-nav-bg": isDark ? "#0b0b0f" : "#fff",- "--blog-nav-text": isDark ? "#e2e1e6" : "#000",- "--blog-nav-border": isDark ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.1)",- "--blog-nav-hover": isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.05)",- borderBottom: `1px solid ${isScrolled ? borderColor : "transparent"}`,- } as CSSProperties;-- return (- <nav- className="sticky top-0 z-50 w-full px-4 py-3 bg-[var(--blog-nav-bg)] transition-[border-color] duration-200 ease-in-out md:px-8"- style={navStyle}- >- <div className="flex max-w-[75rem] mx-auto items-center justify-between">- <div className="flex items-center gap-2">- <ThesysLogo- isHovered={isLogoHovered}- onHoverChange={setIsLogoHovered}- variant={logoVariant}- />- <div className="h-4 w-px bg-[var(--blog-nav-border)]" />- <OpenUILogo variant={logoVariant} />- </div>-- <DesktopNavTabs />-- <div className="hidden lg:flex items-center gap-2">- <ThemeToggle />- <GitHubStarButton repo="thesysdev/openui" isScrolled={isScrolled} />- </div>-- <button- className="flex size-10 items-center justify-center border-0 rounded-lg bg-transparent text-[var(--blog-nav-text)] cursor-pointer transition-colors duration-200 hover:bg-[var(--blog-nav-hover)] lg:hidden"- onClick={toggleMobileMenu}- aria-label="Toggle menu"- >- <HamburgerIcon isOpen={isMobileMenuOpen} />- </button>- </div>-- <AnimatePresence>- {isMobileMenuOpen && <MobileMenu starCount={starCount} onClose={toggleMobileMenu} />}- </AnimatePresence>- </nav>- );+ return <SiteMarketingHeader borderMode="scroll" />;}diff --git a/docs/app/blog/layout.tsx b/docs/app/blog/layout.tsxindex a19a904d7..a1e2b67fc 100644--- a/docs/app/blog/layout.tsx+++ b/docs/app/blog/layout.tsx@@ -1,10 +1,11 @@+import { WebsiteThemeProvider } from "@/components/website-theme-provider";import { BlogNavbar } from "./components/BlogNavbar";export default function BlogLayout({ children }: { children: React.ReactNode }) {return (- <>+ <WebsiteThemeProvider><BlogNavbar />{children}- </>+ </WebsiteThemeProvider>);}diff --git a/docs/app/components/components/AppThemeProvider/AppThemeProvider.tsx b/docs/app/components/components/AppThemeProvider/AppThemeProvider.tsxindex bb71bf74e..1d1f19390 100644--- a/docs/app/components/components/AppThemeProvider/AppThemeProvider.tsx+++ b/docs/app/components/components/AppThemeProvider/AppThemeProvider.tsx@@ -1,238 +1,10 @@"use client";+import { fontOverrides, legacyVarCss, swatchVarCss } from "@/shared/theme/openuiThemeBridge";import type { ThemeMode } from "@components/types";-import { ThemeProvider, swatchTokens } from "@openuidev/react-ui/ThemeProvider";+import { ThemeProvider } from "@openuidev/react-ui/ThemeProvider";import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react";-const FONT_FAMILY = 'var(--font-inter), "Inter", "Segoe UI", Arial, sans-serif';--const fontOverrides = {- fontBody: FONT_FAMILY,- fontHeading: FONT_FAMILY,- fontLabel: FONT_FAMILY,- fontNumbers: FONT_FAMILY,-};--const ALIASES: Record<string, string> = {- "--background": "var(--openui-background)",- "--foreground": "var(--openui-foreground)",- "--openui-background": "var(--background)",- "--openui-foreground": "var(--foreground)",- "--popover-background": "var(--openui-popover-background)",- "--sunk-light": "var(--openui-sunk-light)",- "--sunk": "var(--openui-sunk)",- "--sunk-deep": "var(--openui-sunk-deep)",- "--elevated-light": "var(--openui-elevated-light)",- "--elevated": "var(--openui-elevated)",- "--elevated-strong": "var(--openui-elevated-strong)",- "--elevated-intense": "var(--openui-elevated-intense)",- "--overlay": "var(--openui-overlay)",- "--highlight-subtle": "var(--openui-highlight-subtle)",- "--highlight": "var(--openui-highlight)",- "--highlight-strong": "var(--openui-highlight-strong)",- "--highlight-intense": "var(--openui-highlight-intense)",- "--inverted-background": "var(--openui-inverted-background)",- "--info-background": "var(--openui-info-background)",- "--success-background": "var(--openui-success-background)",- "--alert-background": "var(--openui-alert-background)",- "--danger-background": "var(--openui-danger-background)",- "--purple-background": "var(--openui-purple-background)",- "--pink-background": "var(--openui-pink-background)",- "--text-neutral-primary": "var(--openui-text-neutral-primary)",- "--text-neutral-secondary": "var(--openui-text-neutral-secondary)",- "--text-neutral-tertiary": "var(--openui-text-neutral-tertiary)",- "--text-neutral-link": "var(--openui-text-neutral-link)",- "--text-brand": "var(--openui-text-brand)",- "--text-white": "var(--openui-text-white)",- "--text-black": "var(--openui-text-black)",- "--text-accent-primary": "var(--openui-text-accent-primary)",- "--text-accent-secondary": "var(--openui-text-accent-secondary)",- "--text-accent-tertiary": "var(--openui-text-accent-tertiary)",- "--text-success-primary": "var(--openui-text-success-primary)",- "--text-success-inverted": "var(--openui-text-success-inverted)",- "--text-alert-primary": "var(--openui-text-alert-primary)",- "--text-alert-inverted": "var(--openui-text-alert-inverted)",- "--text-danger-primary": "var(--openui-text-danger-primary)",- "--text-danger-secondary": "var(--openui-text-danger-secondary)",- "--text-danger-tertiary": "var(--openui-text-danger-tertiary)",- "--text-danger-inverted-primary": "var(--openui-text-danger-inverted-primary)",- "--text-danger-inverted-secondary": "var(--openui-text-danger-inverted-secondary)",- "--text-danger-inverted-tertiary": "var(--openui-text-danger-inverted-tertiary)",- "--text-info-primary": "var(--openui-text-info-primary)",- "--text-info-inverted": "var(--openui-text-info-inverted)",- "--text-pink-primary": "var(--openui-text-pink-primary)",- "--text-pink-inverted": "var(--openui-text-pink-inverted)",- "--text-purple-primary": "var(--openui-text-purple-primary)",- "--text-purple-inverted": "var(--openui-text-purple-inverted)",- "--interactive-accent-default": "var(--openui-interactive-accent-default)",- "--interactive-brand-default": "var(--openui-interactive-accent-default)",- "--interactive-accent-hover": "var(--openui-interactive-accent-hover)",- "--interactive-accent-disabled": "var(--openui-interactive-accent-disabled)",- "--interactive-accent-pressed": "var(--openui-interactive-accent-pressed)",- "--interactive-destructive-default": "var(--openui-interactive-destructive-default)",- "--interactive-destructive-hover": "var(--openui-interactive-destructive-hover)",- "--interactive-destructive-disabled": "var(--openui-interactive-destructive-disabled)",- "--interactive-destructive-pressed": "var(--openui-interactive-destructive-pressed)",- "--interactive-destructive-accent-default":- "var(--openui-interactive-destructive-accent-default)",- "--interactive-destructive-accent-hover": "var(--openui-interactive-destructive-accent-hover)",- "--interactive-destructive-accent-pressed":- "var(--openui-interactive-destructive-accent-pressed)",- "--interactive-destructive-accent-disabled":- "var(--openui-interactive-destructive-accent-disabled)",- "--border-default": "var(--openui-border-default)",- "--border-interactive": "var(--openui-border-interactive)",- "--border-interactive-emphasis": "var(--openui-border-interactive-emphasis)",- "--border-interactive-selected": "var(--openui-border-interactive-selected)",- "--border-interactive-elements-selected": "var(--openui-border-interactive-selected)",- "--border-accent": "var(--openui-border-accent)",- "--border-accent-emphasis": "var(--openui-border-accent-emphasis)",- "--border-info": "var(--openui-border-info)",- "--border-info-emphasis": "var(--openui-border-info-emphasis)",- "--border-alert": "var(--openui-border-alert)",- "--border-alert-emphasis": "var(--openui-border-alert-emphasis)",- "--border-success": "var(--openui-border-success)",- "--border-success-emphasis": "var(--openui-border-success-emphasis)",- "--border-danger": "var(--openui-border-danger)",- "--border-danger-emphasis": "var(--openui-border-danger-emphasis)",- "--space-000": "var(--openui-space-000)",- "--space-3xs": "var(--openui-space-3xs)",- "--space-2xs": "var(--openui-space-2xs)",- "--space-xs": "var(--openui-space-xs)",- "--space-s": "var(--openui-space-s)",- "--space-s-m": "var(--openui-space-s-m)",- "--space-m": "var(--openui-space-m)",- "--space-m-l": "var(--openui-space-m-l)",- "--space-l": "var(--openui-space-l)",- "--space-xl": "var(--openui-space-xl)",- "--space-2xl": "var(--openui-space-2xl)",- "--space-3xl": "var(--openui-space-3xl)",- "--space-0": "var(--space-000)",- "--space-1": "var(--space-3xs)",- "--space-2": "var(--space-2xs)",- "--space-3": "var(--space-xs)",- "--space-4": "var(--space-s)",- "--space-5": "var(--space-s-m)",- "--space-6": "var(--space-m)",- "--space-8": "var(--space-m-l)",- "--space-10": "var(--space-l)",- "--space-12": "var(--space-xl)",- "--space-16": "var(--space-2xl)",- "--radius-none": "var(--openui-radius-none)",- "--radius-3xs": "var(--openui-radius-3xs)",- "--radius-2xs": "var(--openui-radius-2xs)",- "--radius-xs": "var(--openui-radius-xs)",- "--radius-s": "var(--openui-radius-s)",- "--radius-m": "var(--openui-radius-m)",- "--radius-l": "var(--openui-radius-l)",- "--radius-xl": "var(--openui-radius-xl)",- "--radius-2xl": "var(--openui-radius-2xl)",- "--radius-3xl": "var(--openui-radius-3xl)",- "--radius-4xl": "var(--openui-radius-4xl)",- "--radius-5xl": "var(--openui-radius-5xl)",- "--radius-6xl": "var(--openui-radius-6xl)",- "--radius-7xl": "var(--openui-radius-7xl)",- "--radius-8xl": "var(--openui-radius-8xl)",- "--radius-9xl": "var(--openui-radius-9xl)",- "--radius-full": "var(--openui-radius-full)",- "--shadow-none": "var(--openui-shadow-0)",- "--shadow-s": "var(--openui-shadow-s)",- "--shadow-m": "var(--openui-shadow-m)",- "--shadow-l": "var(--openui-shadow-l)",- "--shadow-xl": "var(--openui-shadow-xl)",- "--shadow-2xl": "var(--openui-shadow-2xl)",- "--shadow-3xl": "var(--openui-shadow-3xl)",- "--font-body": "var(--openui-font-body)",- "--font-code": "var(--openui-font-code)",- "--font-heading": "var(--openui-font-heading)",- "--font-label": "var(--openui-font-label)",- "--font-numbers": "var(--openui-font-numbers)",- "--text-body-xs": "var(--openui-text-body-xs)",- "--text-body-xs-letter-spacing": "var(--openui-text-body-xs-letter-spacing)",- "--text-body-xs-heavy": "var(--openui-text-body-xs-heavy)",- "--text-body-xs-heavy-letter-spacing": "var(--openui-text-body-xs-heavy-letter-spacing)",- "--text-body-sm": "var(--openui-text-body-sm)",- "--text-body-sm-letter-spacing": "var(--openui-text-body-sm-letter-spacing)",- "--text-body-sm-heavy": "var(--openui-text-body-sm-heavy)",- "--text-body-sm-heavy-letter-spacing": "var(--openui-text-body-sm-heavy-letter-spacing)",- "--text-body-default": "var(--openui-text-body-default)",- "--text-body-default-letter-spacing": "var(--openui-text-body-default-letter-spacing)",- "--text-body-default-heavy": "var(--openui-text-body-default-heavy)",- "--text-body-default-heavy-letter-spacing":- "var(--openui-text-body-default-heavy-letter-spacing)",- "--text-body-lg": "var(--openui-text-body-lg)",- "--text-body-lg-letter-spacing": "var(--openui-text-body-lg-letter-spacing)",- "--text-body-lg-heavy": "var(--openui-text-body-lg-heavy)",- "--text-body-lg-heavy-letter-spacing": "var(--openui-text-body-lg-heavy-letter-spacing)",- "--text-heading-xs": "var(--openui-text-heading-xs)",- "--text-heading-xs-letter-spacing": "var(--openui-text-heading-xs-letter-spacing)",- "--text-heading-sm": "var(--openui-text-heading-sm)",- "--text-heading-sm-letter-spacing": "var(--openui-text-heading-sm-letter-spacing)",- "--text-heading-md": "var(--openui-text-heading-md)",- "--text-heading-md-letter-spacing": "var(--openui-text-heading-md-letter-spacing)",- "--text-heading-lg": "var(--openui-text-heading-lg)",- "--text-heading-lg-letter-spacing": "var(--openui-text-heading-lg-letter-spacing)",- "--text-heading-xl": "var(--openui-text-heading-xl)",- "--text-heading-xl-letter-spacing": "var(--openui-text-heading-xl-letter-spacing)",- "--text-label-xs": "var(--openui-text-label-xs)",- "--text-label-xs-letter-spacing": "var(--openui-text-label-xs-letter-spacing)",- "--text-label-xs-heavy": "var(--openui-text-label-xs-heavy)",- "--text-label-xs-heavy-letter-spacing": "var(--openui-text-label-xs-heavy-letter-spacing)",- "--text-label-sm": "var(--openui-text-label-sm)",- "--text-label-sm-letter-spacing": "var(--openui-text-label-sm-letter-spacing)",- "--text-label-sm-heavy": "var(--openui-text-label-sm-heavy)",- "--text-label-sm-heavy-letter-spacing": "var(--openui-text-label-sm-heavy-letter-spacing)",- "--text-label-default": "var(--openui-text-label-default)",- "--text-label-default-letter-spacing": "var(--openui-text-label-default-letter-spacing)",- "--text-label-default-heavy": "var(--openui-text-label-default-heavy)",- "--text-label-default-heavy-letter-spacing":- "var(--openui-text-label-default-heavy-letter-spacing)",- "--text-label-lg": "var(--openui-text-label-lg)",- "--text-label-lg-letter-spacing": "var(--openui-text-label-lg-letter-spacing)",- "--text-label-lg-heavy": "var(--openui-text-label-lg-heavy)",- "--text-label-lg-heavy-letter-spacing": "var(--openui-text-label-lg-heavy-letter-spacing)",- "--text-numbers-xs": "var(--openui-text-numbers-xs)",- "--text-numbers-xs-letter-spacing": "var(--openui-text-numbers-xs-letter-spacing)",- "--text-numbers-xs-heavy": "var(--openui-text-numbers-xs-heavy)",- "--text-numbers-xs-heavy-letter-spacing": "var(--openui-text-numbers-xs-heavy-letter-spacing)",- "--text-numbers-sm": "var(--openui-text-numbers-sm)",- "--text-numbers-sm-letter-spacing": "var(--openui-text-numbers-sm-letter-spacing)",- "--text-numbers-sm-heavy": "var(--openui-text-numbers-sm-heavy)",- "--text-numbers-sm-heavy-letter-spacing": "var(--openui-text-numbers-sm-heavy-letter-spacing)",- "--text-numbers-default": "var(--openui-text-numbers-default)",- "--text-numbers-default-letter-spacing": "var(--openui-text-numbers-default-letter-spacing)",- "--text-numbers-default-heavy": "var(--openui-text-numbers-default-heavy)",- "--text-numbers-default-heavy-letter-spacing":- "var(--openui-text-numbers-default-heavy-letter-spacing)",- "--text-numbers-lg": "var(--openui-text-numbers-lg)",- "--text-numbers-lg-letter-spacing": "var(--openui-text-numbers-lg-letter-spacing)",- "--text-numbers-lg-heavy": "var(--openui-text-numbers-lg-heavy)",- "--text-numbers-lg-heavy-letter-spacing": "var(--openui-text-numbers-lg-heavy-letter-spacing)",- "--text-code-sm": "var(--openui-text-code-sm)",- "--text-code-sm-letter-spacing": "var(--openui-text-code-sm-letter-spacing)",- "--text-code-sm-heavy": "var(--openui-text-code-sm-heavy)",- "--text-code-sm-heavy-letter-spacing": "var(--openui-text-code-sm-heavy-letter-spacing)",- "--text-code-default": "var(--openui-text-code-default)",- "--text-code-default-letter-spacing": "var(--openui-text-code-default-letter-spacing)",- "--text-code-default-heavy": "var(--openui-text-code-default-heavy)",- "--text-code-default-heavy-letter-spacing":- "var(--openui-text-code-default-heavy-letter-spacing)",- "--motion-duration-fast": "120ms",- "--motion-duration-default": "200ms",- "--motion-duration-slow": "320ms",- "--motion-duration-slower": "480ms",- "--motion-ease-standard": "cubic-bezier(0.2, 0, 0, 1)",- "--motion-ease-emphasized": "cubic-bezier(0.2, 0, 0, 1.2)",-};--const legacyVarCss = Object.entries(ALIASES)- .map(([name, value]) => `${name}: ${value};`)- .join("\n");--const swatchVarCss = Object.entries(swatchTokens)- .map(([name, value]) => `--swatch-${name}: ${value};`)- .join("\n");-interface AppThemeProviderProps {children: ReactNode;}diff --git a/docs/app/demo/github/bookmarks/store.ts b/docs/app/demo/github/bookmarks/store.tsnew file mode 100644index 000000000..769fc9dbb--- /dev/null+++ b/docs/app/demo/github/bookmarks/store.ts@@ -0,0 +1,47 @@+import type { Bookmark } from "../github/types";++function storageKey(username: string): string {+ return `openui-gh-bookmarks-${username}`;+}++export function getBookmarks(username: string): Bookmark[] {+ if (typeof window === "undefined") return [];+ try {+ const raw = localStorage.getItem(storageKey(username));+ return raw ? JSON.parse(raw) : [];+ } catch {+ return [];+ }+}++export function saveBookmark(+ username: string,+ repo: string,+ note?: string,+ tag?: string,+): Bookmark {+ const bookmarks = getBookmarks(username);+ const existing = bookmarks.findIndex((b) => b.repo === repo);+ const bookmark: Bookmark = {+ repo,+ note: note ?? "",+ tag: tag ?? "important",+ created_at: new Date().toISOString(),+ };++ if (existing >= 0) {+ bookmarks[existing] = bookmark;+ } else {+ bookmarks.unshift(bookmark);+ }++ localStorage.setItem(storageKey(username), JSON.stringify(bookmarks));+ return bookmark;+}++export function deleteBookmark(username: string, repo: string): { success: boolean } {+ const bookmarks = getBookmarks(username);+ const filtered = bookmarks.filter((b) => b.repo !== repo);+ localStorage.setItem(storageKey(username), JSON.stringify(filtered));+ return { success: true };+}diff --git a/docs/app/demo/github/components/ConversationPanel/ConversationPanel.css b/docs/app/demo/github/components/ConversationPanel/ConversationPanel.cssnew file mode 100644index 000000000..ec411e06f--- /dev/null+++ b/docs/app/demo/github/components/ConversationPanel/ConversationPanel.css@@ -0,0 +1,321 @@+.conv-panel {+ display: flex;+ flex-direction: column;+ width: 360px;+ min-width: 360px;+ border-left: 1px solid var(--openui-border-default);+ background: var(--openui-background);+}++.conv-header {+ padding: var(--openui-space-m) var(--openui-space-m-l);+ border-bottom: 1px solid var(--openui-border-default);+ font-size: 13px;+ font-weight: 600;+ color: var(--openui-text-neutral-primary);+ font-family: var(--openui-font-body);+ display: flex;+ align-items: center;+ justify-content: space-between;+}++.conv-collapse-btn {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 24px;+ height: 24px;+ background: transparent;+ border: none;+ border-radius: var(--openui-radius-s);+ color: var(--openui-text-neutral-tertiary);+ cursor: pointer;+ transition:+ background-color 0.15s,+ color 0.15s;+}++.conv-collapse-btn:hover {+ background: var(--openui-highlight);+ color: var(--openui-text-neutral-primary);+}++/* Collapsed state */+.conv-collapsed {+ display: flex;+ flex-direction: column;+ align-items: center;+ padding: var(--openui-space-m) var(--openui-space-xs);+ border-left: 1px solid var(--openui-border-default);+ background: var(--openui-background);+}++.conv-expand-btn {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--openui-space-s);+ padding: var(--openui-space-s);+ background: transparent;+ border: none;+ border-radius: var(--openui-radius-m);+ color: var(--openui-text-neutral-tertiary);+ cursor: pointer;+ transition:+ background-color 0.15s,+ color 0.15s;+}++.conv-expand-btn:hover {+ background: var(--openui-highlight);+ color: var(--openui-text-neutral-primary);+}++.conv-badge {+ font-size: 10px;+ font-weight: 600;+ background: var(--openui-interactive-accent-default);+ color: var(--openui-text-accent-primary);+ border-radius: var(--openui-radius-full);+ min-width: 18px;+ height: 18px;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 0 4px;+ font-family: var(--openui-font-body);+}++.conv-messages {+ flex: 1;+ overflow: auto;+ padding: var(--openui-space-m) var(--openui-space-m-l);+}++.conv-msg {+ margin-bottom: var(--openui-space-m);+}++/* User message */+.conv-user-bubble {+ background: var(--openui-chat-user-response-bg);+ color: var(--openui-chat-user-response-text);+ padding: var(--openui-space-s) var(--openui-space-m);+ border-radius: var(--openui-radius-l);+ font-size: 13px;+ line-height: 1.4;+ margin-left: 40px;+ box-shadow: var(--openui-shadow-s);+ font-family: var(--openui-font-body);+}++/* Assistant message */+.conv-assistant {+ margin-right: var(--openui-space-xl);+}++.conv-assistant-bubble {+ background: var(--openui-chat-assistant-response-bg);+ border: 1px solid var(--openui-border-default);+ padding: var(--openui-space-s) var(--openui-space-m);+ border-radius: var(--openui-radius-l);+ font-size: 13px;+ line-height: 1.5;+ color: var(--openui-chat-assistant-response-text);+ font-family: var(--openui-font-body);+}++/* Tool call badges */+.conv-tools-badge {+ padding: var(--openui-space-xs) var(--openui-space-s-m);+ border-radius: var(--openui-radius-m);+ margin-bottom: var(--openui-space-xs);+ font-size: 11px;+ font-family: var(--openui-font-body);+}++.conv-tools-runtime {+ background: var(--openui-success-background);+ border: 1px solid var(--openui-border-success);+}++.conv-tools-live {+ background: var(--openui-highlight-subtle);+ border: 1px solid var(--openui-border-default);+}++.conv-tools-label {+ color: var(--openui-text-success-primary);+ font-weight: 600;+ margin-bottom: 3px;+ display: flex;+ align-items: center;+ gap: var(--openui-space-2xs);+}++.conv-tools-label-text {+ color: var(--openui-text-neutral-secondary);+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ font-size: 10px;+}++.conv-tools-list {+ display: flex;+ flex-wrap: wrap;+ gap: 3px;+ align-items: center;+}++.conv-tool-chip {+ padding: 1px var(--openui-space-xs);+ border-radius: var(--openui-radius-xs);+ font-size: 10px;+ font-family: var(--openui-font-code);+}++.conv-tool-done {+ background: var(--openui-success-background);+ color: var(--openui-text-success-primary);+}++.conv-tool-pending {+ background: var(--openui-alert-background);+ color: var(--openui-text-alert-primary);+}++.conv-tool-error {+ background: var(--openui-danger-background);+ color: var(--openui-text-danger-primary);+}++/* Code badge */+.conv-code-badge {+ display: inline-flex;+ align-items: center;+ gap: var(--openui-space-2xs);+ padding: var(--openui-space-3xs) var(--openui-space-s);+ border-radius: var(--openui-radius-m);+ font-size: 11px;+ background: var(--openui-success-background);+ color: var(--openui-text-success-primary);+ margin-top: var(--openui-space-2xs);+ font-family: var(--openui-font-body);+}++.conv-code-updating {+ background: var(--openui-purple-background);+ color: var(--openui-text-purple-primary);+}++/* Thinking state */+.conv-thinking {+ background: var(--openui-chat-assistant-response-bg);+ border: 1px solid var(--openui-border-default);+ padding: var(--openui-space-s) var(--openui-space-m);+ border-radius: var(--openui-radius-l);+ font-size: 13px;+ color: var(--openui-text-neutral-secondary);+ font-family: var(--openui-font-body);+}++.conv-empty {+ font-size: 12px;+ color: var(--openui-text-neutral-tertiary);+ font-style: italic;+}++/* Input area */+.conv-input-area {+ padding: var(--openui-space-m) var(--openui-space-m-l);+ border-top: 1px solid var(--openui-border-default);+ background: var(--openui-foreground);+}++.conv-input-row {+ display: flex;+ gap: var(--openui-space-s);+}++.conv-input {+ flex: 1;+ padding: var(--openui-space-s) var(--openui-space-m);+ border: 1px solid var(--openui-border-default);+ border-radius: var(--openui-radius-m);+ font-size: 13px;+ outline: none;+ background: var(--openui-sunk);+ color: var(--openui-text-neutral-primary);+ font-family: var(--openui-font-body);+ transition:+ border-color 0.15s,+ box-shadow 0.15s;+}++.conv-input:focus-visible {+ border-color: var(--openui-border-interactive-emphasis);+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--openui-border-accent-emphasis) 22%, transparent);+}++.openui-icon-button.conv-send-btn,+.openui-icon-button.conv-stop-btn {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 36px;+ height: 36px;+ border: none;+ border-radius: var(--openui-radius-m);+ cursor: pointer;+ transition:+ background-color 0.15s,+ color 0.15s,+ border-color 0.15s;+}++.openui-icon-button.conv-send-btn:focus-visible,+.openui-icon-button.conv-stop-btn:focus-visible {+ outline: 2px solid var(--openui-border-accent);+ outline-offset: 2px;+}++.openui-icon-button.conv-send-btn {+ background: var(--openui-interactive-accent-default);+ color: var(--openui-text-accent-primary);+}++.openui-icon-button.conv-send-btn:hover:not(:disabled) {+ background: var(--openui-interactive-accent-hover);+}++.openui-icon-button.conv-send-btn:disabled {+ opacity: 0.4;+ cursor: not-allowed;+}++.openui-icon-button.conv-stop-btn {+ background: var(--openui-highlight-subtle);+ color: var(--openui-text-neutral-secondary);+ border: 1px solid var(--openui-border-default);+}++.openui-icon-button.conv-stop-btn:hover:not(:disabled) {+ background: var(--openui-highlight);+ color: var(--openui-text-neutral-primary);+ border-color: var(--openui-border-interactive);+}++@media (max-width: 768px) {+ .conv-panel {+ width: 100%;+ min-width: 0;+ border-left: none;+ border-top: 1px solid var(--openui-border-default);+ max-height: 300px;+ }++ .conv-collapsed {+ display: none;+ }+}diff --git a/docs/app/demo/github/components/ConversationPanel/ConversationPanel.tsx b/docs/app/demo/github/components/ConversationPanel/ConversationPanel.tsxnew file mode 100644index 000000000..bc9578b40--- /dev/null+++ b/docs/app/demo/github/components/ConversationPanel/ConversationPanel.tsx@@ -0,0 +1,198 @@+"use client";++import { IconButton } from "@openuidev/react-ui";+import { ChevronRight, MessageSquare, Send, Square } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import type { ChatMessage, ToolCallEntry } from "../../constants";+import "./ConversationPanel.css";++type ConversationPanelProps = {+ messages: ChatMessage[];+ streamingText: string;+ isStreaming: boolean;+ elapsed: number | null;+ toolCalls: ToolCallEntry[];+ onSend: (text: string) => void;+ onStop: () => void;+ hasDashboard: boolean;+ responseHasCode: boolean;+};++export function ConversationPanel({+ messages,+ streamingText,+ isStreaming,+ elapsed,+ toolCalls,+ onSend,+ onStop,+ hasDashboard,+ responseHasCode,+}: ConversationPanelProps) {+ const [input, setInput] = useState("");+ const [collapsed, setCollapsed] = useState(false);+ const inputRef = useRef<HTMLInputElement>(null);+ const scrollRef = useRef<HTMLDivElement>(null);++ const canSend = input.trim().length > 0 && !isStreaming;++ useEffect(() => {+ scrollRef.current?.scrollIntoView({ behavior: "smooth" });+ }, [messages, streamingText]);++ useEffect(() => {+ if (!isStreaming) inputRef.current?.focus();+ }, [isStreaming]);++ const handleSend = () => {+ if (!canSend) return;+ onSend(input.trim());+ setInput("");+ };++ const pendingTools = toolCalls.filter((t) => t.status === "pending");++ if (collapsed) {+ return (+ <div className="conv-collapsed">+ <button+ className="conv-expand-btn"+ onClick={() => setCollapsed(false)}+ title="Expand conversation"+ >+ <MessageSquare size={16} />+ {messages.length > 0 && <span className="conv-badge">{messages.length}</span>}+ </button>+ </div>+ );+ }++ return (+ <div className="conv-panel">+ <div className="conv-header">+ <span>Conversation</span>+ <button className="conv-collapse-btn" onClick={() => setCollapsed(true)} title="Collapse">+ <ChevronRight size={16} />+ </button>+ </div>++ <div className="conv-messages">+ {messages.map((msg, i) => (+ <div key={i} className="conv-msg">+ {msg.role === "user" ? (+ <div className="conv-user-bubble">{msg.content}</div>+ ) : (+ <div className="conv-assistant">+ {/* Runtime tool call badges */}+ {msg.runtimeTools && msg.runtimeTools.length > 0 && (+ <div className="conv-tools-badge conv-tools-runtime">+ <div className="conv-tools-label">+ <span>⚡</span> Live data fetched+ </div>+ <div className="conv-tools-list">+ {msg.runtimeTools.map((tc, j) => (+ <span key={j} className={`conv-tool-chip conv-tool-${tc.status}`}>+ {tc.status === "done" ? "✓" : tc.status === "error" ? "✗" : "⏳"}{" "}+ {tc.tool}+ </span>+ ))}+ </div>+ </div>+ )}++ {/* Text response */}+ {msg.text && <div className="conv-assistant-bubble">{msg.text}</div>}++ {/* Dashboard updated badge */}+ {msg.hasCode && <span className="conv-code-badge">✓ dashboard updated</span>}++ {/* Empty response */}+ {!msg.text && !msg.hasCode && !msg.runtimeTools?.length && (+ <div className="conv-empty">(empty response)</div>+ )}+ </div>+ )}+ </div>+ ))}++ {/* Streaming indicator */}+ {isStreaming && (+ <div className="conv-msg">+ <div className="conv-assistant">+ {/* Live runtime tool calls */}+ {toolCalls.length > 0 && (+ <div className="conv-tools-badge conv-tools-live">+ <div className="conv-tools-list">+ <span className="conv-tools-label-text">+ {pendingTools.length > 0 ? "Fetching" : "Loaded"}+ </span>+ {toolCalls.map((tc, j) => (+ <span key={j} className={`conv-tool-chip conv-tool-${tc.status}`}>+ {tc.status === "pending" ? "⏳" : "✓"} {tc.tool}+ </span>+ ))}+ </div>+ </div>+ )}++ {/* Streaming text or thinking indicator */}+ {streamingText ? (+ <div className="conv-assistant-bubble">{streamingText}</div>+ ) : (+ <div className="conv-thinking">+ {elapsed+ ? `${(elapsed / 1000).toFixed(1)}s — ${responseHasCode ? "writing code..." : "thinking..."}`+ : "thinking..."}+ </div>+ )}++ {/* Dashboard updating indicator */}+ {responseHasCode && (+ <span className="conv-code-badge conv-code-updating">⟳ updating dashboard...</span>+ )}+ </div>+ </div>+ )}++ <div ref={scrollRef} />+ </div>++ {/* Input */}+ <div className="conv-input-area">+ <div className="conv-input-row">+ <input+ ref={inputRef}+ className="conv-input"+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && canSend) handleSend();+ }}+ placeholder={hasDashboard ? "Edit or ask..." : "Describe a dashboard..."}+ disabled={isStreaming}+ />+ {isStreaming ? (+ <IconButton+ className="conv-stop-btn"+ icon={<Square size={12} fill="currentColor" />}+ variant="tertiary"+ size="medium"+ onClick={onStop}+ aria-label="Stop generation"+ />+ ) : (+ <IconButton+ className="conv-send-btn"+ icon={<Send size={14} />}+ variant="primary"+ size="medium"+ onClick={handleSend}+ disabled={!canSend}+ aria-label="Send message"+ />+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/docs/app/demo/github/components/GitHubConnect/GitHubConnect.css b/docs/app/demo/github/components/GitHubConnect/GitHubConnect.cssnew file mode 100644index 000000000..69b934127--- /dev/null+++ b/docs/app/demo/github/components/GitHubConnect/GitHubConnect.css@@ -0,0 +1,393 @@+.gh-connect {+ --gh-chip-font: var(--openui-text-label-sm);+ --gh-chip-font-heavy: var(--openui-text-label-sm-heavy);+ width: min(100%, 1120px);+ margin: 0 auto;+ padding: clamp(40px, 8vh, 88px) var(--openui-space-xl) clamp(48px, 8vh, 88px);+ display: flex;+ justify-content: center;+}++.gh-builder {+ width: min(100%, 980px);+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--openui-space-3xl);+}++.gh-builder-copy {+ display: flex;+ max-width: 900px;+ flex-direction: column;+ align-items: center;+ gap: var(--openui-space-s);+ text-align: center;+}++.gh-builder-title {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--openui-space-s);+ margin: 0;+ color: var(--openui-text-neutral-primary);+ font-family: var(--openui-font-body);+ font-size: 32px;+ font-weight: 500;+ line-height: 1.4;+ text-wrap: balance;+ letter-spacing: -0.02em;+}++.gh-builder-inline {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: center;+ gap: var(--openui-space-m);+}++.gh-builder-inline-single {+ width: 100%;+}++.gh-inline-copy {+ color: var(--openui-text-neutral-secondary);+}++.gh-inline-input,+.gh-inline-select-wrap {+ position: relative;+ display: inline-flex;+ max-width: 100%;+ align-items: center;+ justify-content: center;+ gap: var(--openui-space-s);+ padding: 0 0 var(--openui-space-s);+ border-bottom: 1px solid var(--openui-border-interactive);+ transition:+ border-color 0.15s ease,+ color 0.15s ease;+}++.gh-inline-input:focus-within,+.gh-inline-select-wrap:focus-within {+ border-bottom-color: var(--openui-border-interactive-emphasis);+}++.gh-inline-input {+ width: fit-content;+}++.gh-inline-input-with-avatar {+ padding-left: var(--openui-space-s);+}++.gh-inline-inputControl {+ display: inline-grid;+ min-width: 1ch;+ max-width: min(14ch, 32vw);+}++.gh-inline-inputSizer,+.gh-inline-input-field {+ grid-area: 1 / 1;+}++.gh-inline-inputSizer {+ visibility: hidden;+ white-space: pre;+ font: inherit;+ line-height: inherit;+}++.gh-inline-avatar {+ width: 28px;+ height: 28px;+ flex-shrink: 0;+ border-radius: var(--openui-radius-full);+}++.gh-inline-input-field {+ width: 100%;+ min-width: 0;+ padding: 0;+ border: none;+ background: transparent;+ color: var(--openui-text-neutral-primary);+ font: inherit;+ line-height: inherit;+ text-align: center;+ outline: none;+}++.gh-inline-input-field::placeholder {+ color: var(--openui-text-neutral-tertiary);+}++.gh-inline-select-dropdown {+ width: fit-content;+ min-width: 0;+ max-width: min(22ch, 48vw);+}++.gh-error {+ color: var(--openui-text-danger-primary);+ font: var(--openui-text-label-sm);+ letter-spacing: var(--openui-text-label-sm-letter-spacing);+ text-align: center;+}++.gh-reset-button:focus-visible,+.gh-generate-button:focus-visible,+.gh-inline-input-field:focus-visible,+.gh-inline-selectButton:focus-visible,+.gh-dropdownOption:focus-visible {+ outline: 2px solid var(--openui-border-accent);+ outline-offset: 3px;+}++.gh-inline-selectButton {+ display: inline-flex;+ width: fit-content;+ max-width: 100%;+ min-width: 0;+ align-items: center;+ justify-content: center;+ gap: var(--openui-space-s);+ padding: 0;+ border: none;+ background: transparent;+ color: var(--openui-text-neutral-tertiary);+ cursor: pointer;+ font: inherit;+ line-height: inherit;+}++.gh-inline-selectButton-filled {+ color: var(--openui-text-neutral-primary);+}++.gh-inline-selectValue {+ display: inline-flex;+ min-width: 0;+ align-items: center;+ gap: var(--openui-space-s);+ white-space: nowrap;+}++.gh-inline-selectLeading {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ flex-shrink: 0;+}++.gh-inline-selectText {+ display: inline-flex;+ min-width: 0;+ align-items: baseline;+ gap: var(--openui-space-xs);+}++.gh-inline-selectPlaceholder {+ color: var(--openui-text-neutral-tertiary);+}++.gh-inline-selectLabel {+ color: inherit;+}++.gh-inline-selectDescription {+ color: var(--openui-text-neutral-tertiary);+ font: var(--openui-text-body-sm);+ letter-spacing: var(--openui-text-body-sm-letter-spacing);+}++.gh-inline-selectChevron {+ flex-shrink: 0;+ color: var(--openui-text-neutral-tertiary);+ transition: transform 0.15s ease;+}++.gh-inline-selectChevron-open {+ transform: rotate(180deg);+}++.gh-dropdownMenu {+ position: absolute;+ top: calc(100% + var(--openui-space-s));+ left: 50%;+ z-index: 20;+ width: max-content;+ min-width: min(360px, 88vw);+ max-width: min(420px, 92vw);+ padding: var(--openui-space-s);+ border: 1px solid var(--openui-border-default);+ border-radius: calc(var(--openui-radius-3xl) + 6px);+ background: var(--openui-foreground);+ box-shadow: var(--openui-shadow-xl);+ transform: translateX(-50%);+}++.gh-dropdownOption {+ display: flex;+ width: 100%;+ align-items: center;+ justify-content: space-between;+ gap: var(--openui-space-s);+ padding: var(--openui-space-s) var(--openui-space-m);+ border: none;+ border-radius: var(--openui-radius-2xl);+ background: transparent;+ color: var(--openui-text-neutral-primary);+ cursor: pointer;+ text-align: left;+ transition: background-color 0.15s ease;+}++.gh-dropdownOption:hover,+.gh-dropdownOption-selected {+ background: var(--openui-highlight-subtle);+}++.gh-dropdownOptionContent {+ display: inline-flex;+ min-width: 0;+ align-items: center;+ gap: var(--openui-space-s);+}++.gh-dropdownOptionLeading {+ display: inline-flex;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;+}++.gh-dropdownOptionCopy {+ display: flex;+ min-width: 0;+ flex-direction: column;+ gap: 2px;+}++.gh-dropdownOptionLabel {+ color: var(--openui-text-neutral-primary);+ font: var(--openui-text-body-default-heavy);+ letter-spacing: var(--openui-text-body-default-heavy-letter-spacing);+}++.gh-dropdownOptionDescription {+ color: var(--openui-text-neutral-secondary);+ font: var(--openui-text-body-sm);+ letter-spacing: var(--openui-text-body-sm-letter-spacing);+}++.gh-dropdownOptionCheck {+ flex-shrink: 0;+ color: var(--openui-text-neutral-secondary);+}++.gh-dropdown-avatar {+ width: 28px;+ height: 28px;+ border-radius: var(--openui-radius-full);+}++.gh-dropdown-icon {+ display: inline-flex;+ width: 24px;+ height: 24px;+ align-items: center;+ justify-content: center;+ border-radius: var(--openui-radius-full);+ background: var(--openui-highlight-subtle);+ font-size: 14px;+ line-height: 1;+}++.gh-start-actions {+ display: flex;+ justify-content: center;+ align-items: center;+ gap: var(--openui-space-s);+ width: auto;+}++.gh-reset-button,+.gh-generate-button {+ width: fit-content;+ min-width: 0;+}++.gh-visually-hidden {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+}++@media (max-width: 900px) {+ .gh-builder-title {+ font-size: clamp(34px, 7vw, 48px);+ }++ .gh-inline-inputControl {+ max-width: min(12ch, 36vw);+ }++ .gh-inline-select-dropdown {+ max-width: min(20ch, 60vw);+ }+}++@media (max-width: 768px) {+ .gh-connect {+ padding: var(--openui-space-2xl) var(--openui-space-m-l) var(--openui-space-2xl);+ }++ .gh-builder {+ gap: var(--openui-space-m-l);+ }++ .gh-builder-title {+ gap: var(--openui-space-xs);+ font-size:28px;+ line-height: 1.4;+ letter-spacing: -0.02em;+ }++ .gh-builder-inline {+ flex-direction: column;+ gap: var(--openui-space-xs);+ }++ .gh-inline-copy {+ font: var(--openui-text-body-sm);+ letter-spacing: var(--openui-text-body-sm-letter-spacing);+ }++ .gh-inline-inputControl {+ max-width: min(12ch, 68vw);+ }++ .gh-inline-select-dropdown {+ max-width: min(18ch, 72vw);+ }++ .gh-dropdownMenu {+ min-width: min(280px, 82vw);+ max-width: min(320px, 86vw);+ }++ .gh-start-actions {+ flex-wrap: nowrap;+ }+}diff --git a/docs/app/demo/github/components/GitHubConnect/GitHubConnect.tsx b/docs/app/demo/github/components/GitHubConnect/GitHubConnect.tsxnew file mode 100644index 000000000..ba59c7200--- /dev/null+++ b/docs/app/demo/github/components/GitHubConnect/GitHubConnect.tsx@@ -0,0 +1,380 @@+"use client";++import { Button } from "@openuidev/react-ui";+import { Check, ChevronDown } from "lucide-react";+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type FormEvent,+ type ReactNode,+} from "react";+import { GITHUB_STARTERS } from "../../constants";+import "./GitHubConnect.css";++type GitHubConnectProps = {+ onConnectAndPrompt: (username: string, prompt: string) => void;+};++const DEMO_USERS = [+ { username: "torvalds", label: "Linus Torvalds" },+ { username: "yyx990803", label: "Evan You" },+ { username: "gaearon", label: "Dan Abramov" },+ { username: "rauchg", label: "Guillermo Rauch" },+];++type DropdownOption = {+ value: string;+ label: string;+ description?: string;+ leading?: ReactNode;+};++const DEVELOPER_OPTIONS: DropdownOption[] = DEMO_USERS.map((user) => ({+ value: user.username,+ label: user.label,+ description: `@${user.username}`,+ leading: (+ <img+ src={`https://github.com/${user.username}.png?size=40`}+ alt=""+ className="gh-dropdown-avatar"+ />+ ),+}));++const FOCUS_AREA_OPTIONS: DropdownOption[] = GITHUB_STARTERS.map((starter) => ({+ value: starter.prompt,+ label: starter.label,+ leading: <span className="gh-dropdown-icon">{starter.icon}</span>,+}));++function getRandomStarterPrompt() {+ const idx = Math.floor(Math.random() * GITHUB_STARTERS.length);+ return GITHUB_STARTERS[idx].prompt;+}++type InlineDropdownProps = {+ id: string;+ ariaLabel: string;+ placeholder: string;+ options: DropdownOption[];+ value: string | null;+ onChange: (value: string) => void;+ showSelectedDescription?: boolean;+};++function InlineDropdown({+ id,+ ariaLabel,+ placeholder,+ options,+ value,+ onChange,+ showSelectedDescription = false,+}: InlineDropdownProps) {+ const [isOpen, setIsOpen] = useState(false);+ const containerRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ if (!isOpen) return;++ const handlePointerDown = (event: PointerEvent) => {+ if (!containerRef.current?.contains(event.target as Node)) {+ setIsOpen(false);+ }+ };++ const handleEscape = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ setIsOpen(false);+ }+ };++ window.addEventListener("pointerdown", handlePointerDown);+ window.addEventListener("keydown", handleEscape);++ return () => {+ window.removeEventListener("pointerdown", handlePointerDown);+ window.removeEventListener("keydown", handleEscape);+ };+ }, [isOpen]);++ const selectedOption = options.find((option) => option.value === value) ?? null;++ return (+ <div+ ref={containerRef}+ className={`gh-inline-select-wrap gh-inline-select-dropdown ${isOpen ? "gh-inline-select-wrap-open" : ""}`}+ >+ <button+ id={id}+ type="button"+ className={`gh-inline-selectButton ${selectedOption ? "gh-inline-selectButton-filled" : ""}`}+ aria-label={ariaLabel}+ aria-haspopup="listbox"+ aria-expanded={isOpen}+ onClick={() => setIsOpen((prev) => !prev)}+ >+ {selectedOption ? (+ <span className="gh-inline-selectValue">+ {selectedOption.leading && (+ <span className="gh-inline-selectLeading" aria-hidden="true">+ {selectedOption.leading}+ </span>+ )}+ <span className="gh-inline-selectText">+ <span className="gh-inline-selectLabel">{selectedOption.label}</span>+ {showSelectedDescription && selectedOption.description && (+ <span className="gh-inline-selectDescription">{selectedOption.description}</span>+ )}+ </span>+ </span>+ ) : (+ <span className="gh-inline-selectPlaceholder">{placeholder}</span>+ )}+ <ChevronDown+ aria-hidden="true"+ size={18}+ className={`gh-inline-selectChevron ${isOpen ? "gh-inline-selectChevron-open" : ""}`}+ />+ </button>++ {isOpen && (+ <div className="gh-dropdownMenu" role="listbox" aria-labelledby={id}>+ {options.map((option) => {+ const isSelected = option.value === value;++ return (+ <button+ key={option.value}+ type="button"+ className={`gh-dropdownOption ${isSelected ? "gh-dropdownOption-selected" : ""}`}+ role="option"+ aria-selected={isSelected}+ onClick={() => {+ onChange(option.value);+ setIsOpen(false);+ }}+ >+ <span className="gh-dropdownOptionContent">+ {option.leading && <span className="gh-dropdownOptionLeading">{option.leading}</span>}+ <span className="gh-dropdownOptionCopy">+ <span className="gh-dropdownOptionLabel">{option.label}</span>+ {option.description && (+ <span className="gh-dropdownOptionDescription">{option.description}</span>+ )}+ </span>+ </span>+ {isSelected && <Check size={16} className="gh-dropdownOptionCheck" aria-hidden="true" />}+ </button>+ );+ })}+ </div>+ )}+ </div>+ );+}++export function GitHubConnect({ onConnectAndPrompt }: GitHubConnectProps) {+ const initialGithubPrompt = useMemo(() => getRandomStarterPrompt(), []);+ const [username, setUsername] = useState("");+ const [selectedDeveloperUsername, setSelectedDeveloperUsername] = useState<string | null>(null);+ const [avatarUrl, setAvatarUrl] = useState<string | null>(null);+ const [error, setError] = useState("");+ const [defaultGithubPrompt, setDefaultGithubPrompt] = useState(initialGithubPrompt);+ const [selectedGithubPrompt, setSelectedGithubPrompt] = useState(initialGithubPrompt);+ const inputRef = useRef<HTMLInputElement>(null);+ const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined);++ useEffect(() => {+ inputRef.current?.focus();+ }, []);++ useEffect(() => {+ if (debounceRef.current) clearTimeout(debounceRef.current);++ if (!username.trim() || username.trim().length < 2) {+ return;+ }++ debounceRef.current = setTimeout(() => {+ const url = `https://github.com/${username.trim()}.png?size=64`;+ const img = new window.Image();+ img.onload = () => setAvatarUrl(url);+ img.onerror = () => setAvatarUrl(null);+ img.src = url;+ }, 250);++ return () => {+ if (debounceRef.current) clearTimeout(debounceRef.current);+ };+ }, [username]);++ const validate = useCallback((name: string): boolean => {+ const trimmed = name.trim();+ if (!trimmed) {+ setError("Enter a GitHub username");+ return false;+ }+ if (!/^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(trimmed)) {+ setError("Invalid username format");+ return false;+ }+ if (trimmed.length > 39) {+ setError("Username too long");+ return false;+ }+ setError("");+ return true;+ }, []);++ const handlePopularDeveloperSelect = useCallback(+ (nextUsername: string) => {+ setSelectedDeveloperUsername(nextUsername);+ setUsername("");+ setAvatarUrl(null);+ setError("");+ },+ [],+ );++ const trimmedUsername = username.trim();+ const effectiveUsername = trimmedUsername || selectedDeveloperUsername || "";+ const hasValidUsername =+ effectiveUsername.length > 0 &&+ effectiveUsername.length <= 39 &&+ /^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(effectiveUsername);+ const canStart = selectedGithubPrompt !== null && hasValidUsername;+ const canReset = Boolean(+ trimmedUsername || selectedDeveloperUsername || error || selectedGithubPrompt !== defaultGithubPrompt,+ );++ const handleReset = useCallback(() => {+ const nextDefaultPrompt = getRandomStarterPrompt();+ setUsername("");+ setSelectedDeveloperUsername(null);+ setAvatarUrl(null);+ setError("");+ setDefaultGithubPrompt(nextDefaultPrompt);+ setSelectedGithubPrompt(nextDefaultPrompt);+ inputRef.current?.focus();+ }, []);++ const [validating, setValidating] = useState(false);++ const handleStartGenerating = async () => {+ if (!selectedGithubPrompt) return;+ if (!validate(effectiveUsername)) return;++ setValidating(true);+ try {+ const res = await fetch(`https://api.github.com/users/${effectiveUsername}`);+ if (!res.ok) {+ setError("GitHub user not found");+ setValidating(false);+ return;+ }+ } catch {+ setError("Could not verify username");+ setValidating(false);+ return;+ }+ setValidating(false);++ onConnectAndPrompt(effectiveUsername, selectedGithubPrompt);+ };++ const handleSubmit = (event: FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ void handleStartGenerating();+ };++ return (+ <div className="gh-connect">+ <form className="gh-builder" onSubmit={handleSubmit}>+ <div className="gh-builder-copy">+ <h1 className="gh-builder-title">+ <span>Create an interactive GitHub dashboard for</span>+ <span className="gh-builder-inline">+ <label className="gh-visually-hidden" htmlFor="gh-username-input">+ GitHub username+ </label>+ <span className={`gh-inline-input ${avatarUrl ? "gh-inline-input-with-avatar" : ""}`}>+ {avatarUrl && <img src={avatarUrl} alt="" className="gh-inline-avatar" />}+ <span className="gh-inline-inputControl">+ <span aria-hidden="true" className="gh-inline-inputSizer">+ {username || "your username"}+ </span>+ <input+ id="gh-username-input"+ ref={inputRef}+ className="gh-inline-input-field"+ value={username}+ onChange={(e) => {+ setSelectedDeveloperUsername(null);+ setUsername(e.target.value);+ setAvatarUrl(null);+ setError("");+ }}+ placeholder="username"+ autoComplete="off"+ spellCheck={false}+ />+ </span>+ </span>+ <span className="gh-inline-copy">or</span>+ <label className="gh-visually-hidden" htmlFor="gh-developer-select">+ Popular developer+ </label>+ <InlineDropdown+ id="gh-developer-select"+ ariaLabel="Select a developer"+ placeholder="select a developer"+ options={DEVELOPER_OPTIONS}+ value={selectedDeveloperUsername}+ onChange={handlePopularDeveloperSelect}+ />+ </span>+ <span>that focuses on</span>+ <span className="gh-builder-inline gh-builder-inline-single">+ <label className="gh-visually-hidden" htmlFor="gh-focus-area-select">+ Focus area+ </label>+ <InlineDropdown+ id="gh-focus-area-select"+ ariaLabel="Select a focus area"+ placeholder="focus area"+ options={FOCUS_AREA_OPTIONS}+ value={selectedGithubPrompt}+ onChange={(nextPrompt) => {+ setSelectedGithubPrompt(nextPrompt);+ setError("");+ }}+ />+ </span>+ </h1>+ </div>++ {error && <div className="gh-error">{error}</div>}++ <div className="gh-start-actions">+ <Button+ className="gh-reset-button"+ variant="secondary"+ type="button"+ onClick={handleReset}+ disabled={!canReset}+ >+ Reset+ </Button>+ <Button className="gh-generate-button" type="submit" disabled={!canStart || validating}>+ {validating ? "Verifying..." : "Generate"}+ </Button>+ </div>+ </form>+ </div>+ );+}diff --git a/docs/app/demo/github/components/Header/Header.css b/docs/app/demo/github/components/Header/Header.cssnew file mode 100644index 000000000..0e0497a13--- /dev/null+++ b/docs/app/demo/github/components/Header/Header.css@@ -0,0 +1,54 @@+.openui-icon-button.header-btn,+.header-btn {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 6px 10px;+ background: transparent;+ border: none;+ border-radius: 6px;+ color: var(--openui-text-neutral-secondary);+ font-family: var(--openui-font-body);+ font-size: 13px;+ cursor: pointer;+ text-decoration: none;+ transition:+ background 0.15s,+ color 0.15s;+ white-space: nowrap;+}++.openui-icon-button.header-btn:hover:not(:disabled),+.header-btn:hover {+ background: var(--openui-highlight);+ color: var(--openui-text-neutral-primary);+}++.header-btn svg {+ flex-shrink: 0;+}++.openui-icon-button.header-icon-btn,+.header-icon-btn {+ padding: 6px;+ border-radius: 6px;+}++@media (max-width: 1023px) {+ .header-btn {+ padding: 6px 8px;+ font-size: 12px;+ }+}++@media (max-width: 767px) {+ .header-btn {+ gap: 0;+ min-width: 32px;+ padding: 6px;+ }++ .header-btn span {+ display: none;+ }+}diff --git a/docs/app/demo/github/components/Header/Header.tsx b/docs/app/demo/github/components/Header/Header.tsxnew file mode 100644index 000000000..e189b20da--- /dev/null+++ b/docs/app/demo/github/components/Header/Header.tsx@@ -0,0 +1,24 @@+import { SiteMarketingHeader } from "@/components/site-marketing-header";+import type { Theme } from "../../constants";+import "./Header.css";++type HeaderProps = {+ theme: Theme;+ onThemeToggle: () => void;+ borderMode?: "always" | "scroll";+};++export function Header({ theme, onThemeToggle, borderMode = "always" }: HeaderProps) {+ const themeLabel = { system: "System", light: "Light", dark: "Dark" }[theme];++ return (+ <SiteMarketingHeader+ borderMode={borderMode}+ themeToggle={{+ onToggle: onThemeToggle,+ title: `Theme: ${themeLabel}`,+ ariaLabel: `Switch theme (current: ${themeLabel})`,+ }}+ />+ );+}diff --git a/docs/app/demo/github/components/Modal/Modal.css b/docs/app/demo/github/components/Modal/Modal.cssnew file mode 100644index 000000000..89026479b--- /dev/null+++ b/docs/app/demo/github/components/Modal/Modal.css@@ -0,0 +1,84 @@+.modal-overlay {+ position: fixed;+ inset: 0;+ z-index: 200;+ background: var(--openui-overlay);+ backdrop-filter: blur(4px);+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 24px;+ animation: modal-overlay-in 0.15s ease;+}++@keyframes modal-overlay-in {+ from {+ opacity: 0;+ }+ to {+ opacity: 1;+ }+}++.modal-container {+ background: var(--openui-foreground);+ border: 1px solid var(--openui-border-interactive);+ border-radius: 16px;+ box-shadow: var(--openui-shadow-2xl);+ width: min(1400px, 95vw);+ height: 95vh;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ animation: modal-container-in 0.2s ease;+}++@keyframes modal-container-in {+ from {+ opacity: 0;+ transform: translateY(12px) scale(0.98);+ }+ to {+ opacity: 1;+ transform: translateY(0) scale(1);+ }+}++.modal-container-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 10px 16px;+ background: var(--openui-highlight-subtle);+ border-bottom: 1px solid var(--openui-border-default);+ flex-shrink: 0;+}++.modal-container-body {+ flex: 1;+ overflow: auto;+}++/* ─── Mobile ─────────────────────────────────────────────────────────────────── */+@media (max-width: 768px) {+ .modal-overlay {+ padding: 0;+ align-items: flex-end;+ }++ .modal-container {+ width: 100vw;+ height: 95dvh;+ border-radius: 16px 16px 0 0;+ animation: modal-container-mobile-in 0.35s cubic-bezier(0.22, 1, 0.36, 1);+ }+}++@keyframes modal-container-mobile-in {+ from {+ transform: translateY(100%);+ }+ to {+ transform: translateY(0);+ }+}diff --git a/docs/app/demo/github/components/Modal/Modal.tsx b/docs/app/demo/github/components/Modal/Modal.tsxnew file mode 100644index 000000000..47b5d784d--- /dev/null+++ b/docs/app/demo/github/components/Modal/Modal.tsx@@ -0,0 +1,56 @@+import { IconButton } from "@openuidev/react-ui";+import { X } from "lucide-react";+import type { ReactNode } from "react";+import { useCallback, useEffect } from "react";+import "./Modal.css";++type ModalProps = {+ title: string;+ titleAdornment?: ReactNode;+ onClose?: () => void;+ children: ReactNode;+ className?: string;+};++export function Modal({ title, titleAdornment, onClose, children, className }: ModalProps) {+ const handleKey = useCallback(+ (e: KeyboardEvent) => {+ if (e.key === "Escape") onClose?.();+ },+ [onClose],+ );++ useEffect(() => {+ if (!onClose) return;+ document.addEventListener("keydown", handleKey);+ return () => document.removeEventListener("keydown", handleKey);+ }, [onClose, handleKey]);++ return (+ <div className="modal-overlay" onClick={onClose}>+ <div+ className={`modal-container${className ? ` ${className}` : ""}`}+ onClick={(e) => e.stopPropagation()}+ >+ <div className="modal-container-header">+ <div className="panel-title-group">+ <span className="panel-title">{title}</span>+ {titleAdornment}+ </div>+ {onClose && (+ <IconButton+ className="panel-icon-btn"+ icon={<X size={16} />}+ variant="tertiary"+ size="extra-small"+ onClick={onClose}+ title="Close"+ aria-label="Close modal"+ />+ )}+ </div>+ <div className="modal-container-body">{children}</div>+ </div>+ </div>+ );+}diff --git a/docs/app/demo/github/components/PreviewPanel/PreviewPanel.css b/docs/app/demo/github/components/PreviewPanel/PreviewPanel.cssnew file mode 100644index 000000000..7445d8926--- /dev/null+++ b/docs/app/demo/github/components/PreviewPanel/PreviewPanel.css@@ -0,0 +1,32 @@+@keyframes preview-spin {+ to {+ transform: rotate(360deg);+ }+}++.panel-title-group {+ display: flex;+ align-items: center;+ gap: var(--openui-space-s);+}++.preview-spinner {+ animation: preview-spin 1s linear infinite;+ color: var(--openui-text-purple-primary);+ flex-shrink: 0;+}++.preview-body {+ flex: 1;+ overflow: auto;+ display: flex;+ align-items: center;+ justify-content: center;+ background: var(--openui-highlight-subtle);+}++.preview-content {+ width: 100%;+ padding: var(--openui-space-m-l);+ align-self: flex-start;+}diff --git a/docs/app/demo/github/components/PreviewPanel/PreviewPanel.tsx b/docs/app/demo/github/components/PreviewPanel/PreviewPanel.tsxnew file mode 100644index 000000000..78bfbf79c--- /dev/null+++ b/docs/app/demo/github/components/PreviewPanel/PreviewPanel.tsx@@ -0,0 +1,86 @@+import type { ActionEvent, ParseResult } from "@openuidev/react-lang";+import { Renderer } from "@openuidev/react-lang";+import { IconButton, openuiLibrary, ThemeProvider } from "@openuidev/react-ui";+import { Loader2, Maximize2, Monitor } from "lucide-react";+import { useCallback, useState } from "react";+import { Modal } from "../Modal/Modal";+import "./PreviewPanel.css";++type PreviewPanelProps = {+ code: string;+ isStreaming: boolean;+ onParseResult?: (result: ParseResult | null) => void;+ mode: "light" | "dark";+ toolProvider?: Record<string, (args: Record<string, unknown>) => Promise<unknown>> | null;+ onAction?: (event: ActionEvent) => void;+};++export function PreviewPanel({+ code,+ isStreaming,+ onParseResult,+ mode,+ toolProvider,+ onAction,+}: PreviewPanelProps) {+ const [isModalOpen, setIsModalOpen] = useState(false);++ const closeModal = useCallback(() => setIsModalOpen(false), []);++ const previewContent = code ? (+ <div className="preview-content">+ <ThemeProvider mode={mode}>+ <Renderer+ response={code}+ library={openuiLibrary}+ isStreaming={isStreaming}+ onParseResult={onParseResult}+ toolProvider={toolProvider}+ onAction={onAction}+ />+ </ThemeProvider>+ </div>+ ) : (+ <div className="empty-state">+ <div className="empty-state-icon">+ <Monitor size={28} />+ </div>+ <p className="empty-state-text">Rendered UI will appear here</p>+ </div>+ );++ return (+ <>+ <div className="panel">+ <div className="panel-header">+ <div className="panel-title-group">+ <span className="panel-title">Preview</span>+ {isStreaming && <Loader2 size={14} className="preview-spinner" />}+ </div>+ <div className="panel-actions">+ <IconButton+ className="panel-icon-btn"+ icon={<Maximize2 size={14} />}+ variant="tertiary"+ size="extra-small"+ onClick={() => setIsModalOpen(true)}+ title="Open fullscreen preview"+ aria-label="Open fullscreen preview"+ />+ </div>+ </div>+ <div className="preview-body">{previewContent}</div>+ </div>++ {isModalOpen && (+ <Modal+ title="Preview"+ titleAdornment={isStreaming ? <Loader2 size={14} className="preview-spinner" /> : null}+ onClose={closeModal}+ >+ {previewContent}+ </Modal>+ )}+ </>+ );+}diff --git a/docs/app/demo/github/constants.ts b/docs/app/demo/github/constants.tsnew file mode 100644index 000000000..f5f3222ac--- /dev/null+++ b/docs/app/demo/github/constants.ts@@ -0,0 +1,49 @@+export type Theme = "system" | "light" | "dark";+export type Status = "idle" | "streaming" | "done" | "error";++export const GITHUB_STARTERS = [+ {+ label: "Profile Dashboard",+ prompt:+ "Build a profile dashboard with KPIs, language breakdown chart, and top repos table with sorting and language filter",+ icon: "📊",+ },+ {+ label: "Coding Patterns",+ prompt:+ "Analyze my coding patterns — show activity breakdown, language distribution, and a recent events timeline",+ icon: "🔥",+ },+ {+ label: "Star History",+ prompt: "Show star history charts for my most popular repos with a comparison view",+ icon: "⭐",+ },+ {+ label: "Repo Organizer",+ prompt:+ "Build a repo organizer with bookmarks, tags, search, and language filter. Include a bookmark form in a modal.",+ icon: "🗂️",+ },+ {+ label: "Open Source Impact",+ prompt:+ "Show my open source impact — follower stats, total stars, top repos by forks, language expertise breakdown, and community reach",+ icon: "🌍",+ },+];++// ── Chat message types (shared between page + ConversationPanel) ──────────++export type ToolCallEntry = {+ tool: string;+ status: "pending" | "done" | "error";+};++export interface ChatMessage {+ role: "user" | "assistant";+ content: string;+ text?: string;+ hasCode: boolean;+ runtimeTools?: ToolCallEntry[];+}diff --git a/docs/app/demo/github/github/prompt-config.ts b/docs/app/demo/github/github/prompt-config.tsnew file mode 100644index 000000000..d30f3b988--- /dev/null+++ b/docs/app/demo/github/github/prompt-config.ts@@ -0,0 +1,85 @@+// Server-safe — no React, no browser APIs.+// Used by the stream route to build the GitHub-specific system prompt.++export const GITHUB_PREAMBLE = `You are an AI assistant that builds GitHub profile dashboards using openui-lang, a declarative UI language.++The user has connected their GitHub profile. All data comes from real GitHub API tools via Query().+The username is already set — do NOT include username in Query args.++Build rich, visually impressive dashboards with:+- Multiple KPI cards showing live computed stats+- Charts (PieChart for languages, BarChart for comparisons, LineChart for trends)+- Tables with sorting and filtering via $variables+- Interactive controls (Select dropdowns, search Input) wired to $variables++After the openui-lang code block, write a brief friendly message describing what you built and suggesting what the user could iterate on next. Keep it conversational, like you're talking to the user. For example: "Here's your dashboard with KPIs and language breakdown. You could try adding a search filter to the repos table, or ask me to add an activity timeline chart."`;++export const GITHUB_TOOL_EXAMPLES: string[] = [+ `Example — GitHub Profile Dashboard (PREFERRED pattern):+root = Stack([header, kpiRow, chartsRow, repoSection])+header = CardHeader("GitHub Dashboard", "Your developer profile at a glance")+$sortBy = "stars"+$language = "all"+profile = Query("get_profile", {}, {login: "", name: "", bio: "", avatar_url: "", public_repos: 0, followers: 0, following: 0, created_at: ""})+repos = Query("get_repos", {sort: $sortBy, language: $language}, {rows: []})+languages = Query("get_languages", {}, {rows: []})+events = Query("get_events", {}, {rows: [], summary: {total: 0, push: 0, pr: 0, issues: 0, reviews: 0}})+kpiRow = Stack([reposKpi, starsKpi, followersKpi, activityKpi], "row", "m", "stretch", "start", true)+reposKpi = Card([TextContent("Repositories", "small"), TextContent("" + profile.public_repos, "large-heavy")])+starsKpi = Card([TextContent("Total Stars", "small"), TextContent("" + @Sum(repos.rows.stars), "large-heavy")])+followersKpi = Card([TextContent("Followers", "small"), TextContent("" + profile.followers, "large-heavy")])+activityKpi = Card([TextContent("Recent Events", "small"), TextContent("" + events.summary.total, "large-heavy")])+chartsRow = Stack([langCard, activityCard], "row", "m")+langCard = Card([CardHeader("Languages", "By bytes of code"), PieChart(languages.rows.language, languages.rows.bytes, "donut")])+activityCard = Card([CardHeader("Activity Mix"), BarChart(["Push", "PR", "Issues", "Reviews"], [Series("Events", [events.summary.push, events.summary.pr, events.summary.issues, events.summary.reviews])])])+repoSection = Card([CardHeader("Repositories"), controls, repoTable])+controls = Stack([langFilter, sortFilter, refreshBtn], "row", "m", "end")+langFilter = FormControl("Language", Select("language", [SelectItem("all", "All"), SelectItem("TypeScript", "TypeScript"), SelectItem("Python", "Python"), SelectItem("JavaScript", "JavaScript"), SelectItem("C", "C"), SelectItem("Go", "Go"), SelectItem("Rust", "Rust")], null, null, $language))+sortFilter = FormControl("Sort", Select("sortBy", [SelectItem("stars", "Stars"), SelectItem("forks", "Forks"), SelectItem("updated", "Recent")], null, null, $sortBy))+refreshBtn = Button("Refresh", Action([@Run(repos), @Run(languages), @Run(events)]), "secondary")+sorted = @Sort(repos.rows, $sortBy, "desc")+repoTable = Table([Col("Name", sorted.name), Col("Language", @Each(sorted, "r", Tag(r.language, null, "sm", r.language == "TypeScript" ? "info" : r.language == "Python" ? "success" : "neutral"))), Col("Stars", sorted.stars, "number"), Col("Forks", sorted.forks, "number")])`,++ `Example — Repo Organizer with Bookmarks (CRUD pattern):+root = Stack([header, kpiRow, tabs, bookmarkModal])+header = CardHeader("Repo Organizer", "Bookmark and tag your repositories")+$showBookmark = false+$bookmarkRepo = ""+$bookmarkNote = ""+$bookmarkTag = "important"+$search = ""+repos = Query("get_repos", {sort: "stars"}, {rows: []})+bookmarks = Query("get_bookmarks", {}, {rows: []})+languages = Query("get_languages", {}, {rows: []})+saveResult = Mutation("save_bookmark", {repo: $bookmarkRepo, note: $bookmarkNote, tag: $bookmarkTag})+deleteResult = Mutation("delete_bookmark", {repo: $bookmarkRepo})+kpiRow = Stack([Card([TextContent("Repos", "small"), TextContent("" + @Count(repos.rows), "large-heavy")]), Card([TextContent("Bookmarked", "small"), TextContent("" + @Count(bookmarks.rows), "large-heavy")]), Card([TextContent("Stars", "small"), TextContent("" + @Sum(repos.rows.stars), "large-heavy")])], "row", "m", "stretch", "start", true)+tabs = Tabs([reposTab, bookmarksTab, insightsTab])+reposTab = TabItem("repos", "Repos", [searchField, repoTable])+searchField = FormControl("Search", Input("search", "Filter repos...", "text", null, $search))+filtered = @Filter(repos.rows, "name", "contains", $search)+repoTable = Table([Col("Repo", filtered.name), Col("Stars", filtered.stars, "number"), Col("Language", @Each(filtered, "r", Tag(r.language, null, "sm"))), Col("Actions", @Each(filtered, "r", Button("Bookmark", Action([@Set($bookmarkRepo, r.name), @Set($showBookmark, true)]), "secondary", "normal", "small")))])+bookmarksTab = TabItem("bookmarks", "Bookmarks", [bookmarkTable])+bookmarkTable = @Count(bookmarks.rows) > 0 ? Table([Col("Repo", bookmarks.rows.repo), Col("Tag", @Each(bookmarks.rows, "b", Tag(b.tag, null, "sm", b.tag == "important" ? "danger" : b.tag == "favorite" ? "success" : "info"))), Col("Note", bookmarks.rows.note), Col("Remove", @Each(bookmarks.rows, "b", Button("Delete", Action([@Set($bookmarkRepo, b.repo), @Run(deleteResult), @Run(bookmarks)]), "secondary", "destructive", "small")))]) : TextContent("No bookmarks yet. Go to Repos tab and bookmark some!")+insightsTab = TabItem("insights", "Insights", [Card([CardHeader("Language Breakdown"), PieChart(languages.rows.language, languages.rows.bytes, "donut")])])+bmBtns = Buttons([Button("Save", Action([@Run(saveResult), @Run(bookmarks), @Set($showBookmark, false), @Reset($bookmarkNote, $bookmarkTag)]), "primary"), Button("Cancel", Action([@Set($showBookmark, false)]), "secondary")])+bmForm = Form("bookmark", bmBtns, [FormControl("Repo", Input("bm_repo", "", "text", null, $bookmarkRepo)), FormControl("Tag", Select("bm_tag", [SelectItem("important", "Important"), SelectItem("review", "To Review"), SelectItem("learning", "Learning"), SelectItem("favorite", "Favorite")], null, null, $bookmarkTag)), FormControl("Note", TextArea("bm_note", "Why bookmark this?", 3, null, $bookmarkNote))])+bookmarkModal = Modal("Bookmark Repository", $showBookmark, [bmForm])`,+];++export const GITHUB_ADDITIONAL_RULES: string[] = [+ "The user's GitHub username is already connected — do NOT ask for it or include username in Query() args",+ "get_repos returns: rows[].{name, full_name, description, language, stars, forks, size, open_issues, updated_at, html_url}",+ "get_profile returns: {login, name, bio, avatar_url, public_repos, followers, following, created_at}",+ "get_languages returns: rows[].{language, bytes, repos_count} sorted by bytes descending",+ "get_events returns: {rows[].{type, repo, date}, summary.{total, push, pr, issues, reviews}}. Event types: Push, PullRequest, Issues, Create, Watch, Fork",+ 'get_commit_activity({repo}) returns: rows[].{week, total} — 52 weeks. Needs repo name, e.g. {repo: "linux"}',+ "get_star_history({repo}) returns: rows[].{starred_at, cumulative} for LineChart. Needs repo name.",+ "get_contributors({repo}) returns: rows[].{login, avatar_url, total_commits}. Needs repo name.",+ "Bookmark tools: save_bookmark({repo, note?, tag?}), get_bookmarks({}), delete_bookmark({repo}). Use Mutation + @Run pattern.",+ "For dashboards, ALWAYS include: 3+ KPI cards with @Sum/@Count, 2+ chart types, 1 data table, 1+ interactive filter ($variable + Select)",+ "Use @Sum(repos.rows.stars), @Count(repos.rows), @Avg, @Round on Query results for KPIs — NEVER hardcode numbers",+ "Use PieChart for language breakdowns (donut variant), BarChart for comparisons, LineChart for trends over time",+ "Rate limit: 60 req/hr per visitor. Prefer get_repos (1 API call) over per-repo endpoints (get_commit_activity, get_star_history, get_contributors)",+ "Per-repo tools (get_commit_activity, get_star_history, get_contributors) are expensive — only use when the user specifically asks about a specific repo",+];diff --git a/docs/app/demo/github/github/tools.ts b/docs/app/demo/github/github/tools.tsnew file mode 100644index 000000000..009859a62--- /dev/null+++ b/docs/app/demo/github/github/tools.ts@@ -0,0 +1,425 @@+import { Octokit } from "octokit";+import { deleteBookmark, getBookmarks, saveBookmark } from "../bookmarks/store";+import type {+ CommitWeek,+ ContributorRow,+ EventRow,+ LanguageRow,+ RepoRow,+ StarPoint,+} from "./types";++// ── Cache ──────────────────────────────────────────────────────────────────++const cache = new Map<string, { data: unknown; ts: number }>();+const CACHE_TTL = 5 * 60 * 1000; // 5 minutes++function cached<T>(key: string, fn: () => Promise<T>): Promise<T> {+ const now = Date.now();+ const entry = cache.get(key);+ if (entry && now - entry.ts < CACHE_TTL) return Promise.resolve(entry.data as T);++ // Evict expired entries occasionally+ if (cache.size > 50) {+ for (const [k, v] of cache) {+ if (now - v.ts >= CACHE_TTL) cache.delete(k);+ }+ }++ return fn().then((data) => {+ cache.set(key, { data, ts: now });+ return data;+ });+}++/** Clear all cached data (call when switching users) */+export function clearCache() {+ cache.clear();+}++// ── Rate limit tracking ────────────────────────────────────────────────────++let rateLimitRemaining = 60;+let rateLimitReset = 0;++export function getRateLimit() {+ return { remaining: rateLimitRemaining, reset: rateLimitReset };+}++function checkRateLimit(): string | null {+ if (rateLimitRemaining <= 0 && Date.now() / 1000 < rateLimitReset) {+ const mins = Math.ceil((rateLimitReset - Date.now() / 1000) / 60);+ return `GitHub API rate limit exceeded. Try again in ${mins} minute${mins > 1 ? "s" : ""}.`;+ }+ return null;+}++function updateRateLimit(response: any) {+ const h = response?.headers;+ if (!h) return;+ const remaining = h["x-ratelimit-remaining"];+ const reset = h["x-ratelimit-reset"];+ if (remaining != null) {+ const n = parseInt(String(remaining), 10);+ if (!isNaN(n)) rateLimitRemaining = n;+ }+ if (reset != null) {+ const n = parseInt(String(reset), 10);+ if (!isNaN(n)) rateLimitReset = n;+ }+}++// ── Retry for 202 (computing) ──────────────────────────────────────────────++async function fetchWithRetry(+ octokit: Octokit,+ route: string,+ params: Record<string, unknown>,+ retries = 3,+): Promise<unknown> {+ for (let i = 0; i < retries; i++) {+ const res = await octokit.request(route, params);+ updateRateLimit(res);+ if (res.status !== 202) return res.data;+ // GitHub is computing stats — wait and retry+ await new Promise((r) => setTimeout(r, 1500));+ }+ return { error: "GitHub is still computing stats. Try again in a moment." };+}++// ── Tool implementations ───────────────────────────────────────────────────++export function createGitHubToolProvider(+ username: string,+): Record<string, (args: Record<string, unknown>) => Promise<unknown>> {+ const octokit = new Octokit();++ // Shared repo data — fetched once, used by get_repos + get_languages+ let repoCache: RepoRow[] | null = null;++ async function fetchRepos(): Promise<RepoRow[]> {+ if (repoCache) return repoCache;++ const limitErr = checkRateLimit();+ if (limitErr) throw new Error(limitErr);++ const res = await octokit.rest.repos.listForUser({+ username,+ per_page: 100,+ sort: "pushed",+ });+ updateRateLimit(res);++ repoCache = res.data.map((r) => ({+ name: r.name,+ full_name: r.full_name,+ description: r.description ?? "",+ language: r.language ?? "",+ stars: r.stargazers_count ?? 0,+ forks: r.forks_count ?? 0,+ size: r.size ?? 0,+ open_issues: r.open_issues_count ?? 0,+ updated_at: r.updated_at?.slice(0, 10) ?? "",+ html_url: r.html_url ?? "",+ }));+ return repoCache;+ }++ return {+ // ── Profile ──────────────────────────────────────────────────────────++ get_profile: () =>+ cached(`profile:${username}`, async () => {+ const empty = {+ login: "",+ name: "",+ bio: "",+ avatar_url: "",+ public_repos: 0,+ followers: 0,+ following: 0,+ created_at: "",+ };+ const limitErr = checkRateLimit();+ if (limitErr) return { ...empty, error: limitErr };++ try {+ const res = await octokit.rest.users.getByUsername({ username });+ updateRateLimit(res);+ const u = res.data;+ return {+ login: u.login,+ name: u.name ?? u.login,+ bio: u.bio ?? "",+ avatar_url: u.avatar_url,+ public_repos: u.public_repos,+ followers: u.followers,+ following: u.following,+ created_at: u.created_at?.slice(0, 10) ?? "",+ };+ } catch (err: any) {+ if (err.status === 404) return { ...empty, error: `User "${username}" not found` };+ return { ...empty, error: err.message ?? "Failed to fetch profile" };+ }+ }),++ // ── Repos ────────────────────────────────────────────────────────────++ get_repos: (args) =>+ cached(`repos:${username}:${JSON.stringify(args)}`, async () => {+ try {+ let rows = await fetchRepos();++ // Client-side language filter+ const lang = args.language as string | undefined;+ if (lang && lang !== "all" && lang !== "") {+ rows = rows.filter((r) => r.language.toLowerCase() === lang.toLowerCase());+ }++ // Client-side sort+ const sort = (args.sort as string) ?? "stars";+ const sortKey =+ sort === "forks"+ ? "forks"+ : sort === "updated"+ ? "updated_at"+ : sort === "created"+ ? "updated_at"+ : "stars";+ rows = [...rows].sort((a, b) => {+ const av = (a as any)[sortKey];+ const bv = (b as any)[sortKey];+ if (typeof av === "string") return bv.localeCompare(av);+ return bv - av;+ });++ return { rows };+ } catch (err: any) {+ return { error: err.message, rows: [] };+ }+ }),++ // ── Languages (aggregated) ───────────────────────────────────────────++ get_languages: () =>+ cached(`languages:${username}`, async () => {+ try {+ const repos = await fetchRepos();++ // Quick aggregation from repo language field+ const langMap = new Map<string, { bytes: number; count: number }>();+ for (const r of repos) {+ if (!r.language) continue;+ const entry = langMap.get(r.language) ?? { bytes: 0, count: 0 };+ entry.bytes += r.size * 1024; // size is in KB, convert to bytes approx+ entry.count += 1;+ langMap.set(r.language, entry);+ }++ // Fetch detailed language bytes for top 5 repos (by stars)+ const topRepos = [...repos].sort((a, b) => b.stars - a.stars).slice(0, 5);++ const limitErr = checkRateLimit();+ if (!limitErr) {+ for (const repo of topRepos) {+ try {+ const res = await octokit.rest.repos.listLanguages({+ owner: username,+ repo: repo.name,+ });+ updateRateLimit(res);+ for (const [lang, bytes] of Object.entries(res.data)) {+ const entry = langMap.get(lang) ?? { bytes: 0, count: 0 };+ entry.bytes = Math.max(entry.bytes, bytes as number);+ if (!langMap.has(lang)) entry.count = 1;+ langMap.set(lang, entry);+ }+ } catch {+ // Skip individual repo failures+ }+ }+ }++ const rows: LanguageRow[] = [...langMap.entries()]+ .map(([language, { bytes, count }]) => ({+ language,+ bytes,+ repos_count: count,+ }))+ .sort((a, b) => b.bytes - a.bytes);++ return { rows };+ } catch (err: any) {+ return { error: err.message, rows: [] };+ }+ }),++ // ── Events ───────────────────────────────────────────────────────────++ get_events: () =>+ cached(`events:${username}`, async () => {+ const limitErr = checkRateLimit();+ if (limitErr)+ return {+ error: limitErr,+ rows: [],+ summary: { total: 0, push: 0, pr: 0, issues: 0, reviews: 0 },+ };++ try {+ const res = await octokit.rest.activity.listPublicEventsForUser({+ username,+ per_page: 100,+ });+ updateRateLimit(res);++ const rows: EventRow[] = res.data.map((e) => ({+ type: e.type?.replace("Event", "") ?? "Unknown",+ repo: (e.repo as any)?.name?.split("/")[1] ?? e.repo?.name ?? "",+ date: e.created_at?.slice(0, 10) ?? "",+ count: 1,+ }));++ // Build summary+ const summary = { total: rows.length, push: 0, pr: 0, issues: 0, reviews: 0 };+ for (const r of rows) {+ if (r.type === "Push") summary.push++;+ else if (r.type === "PullRequest") summary.pr++;+ else if (r.type === "Issues") summary.issues++;+ else if (r.type === "PullRequestReview") summary.reviews++;+ }++ return { rows, summary };+ } catch (err: any) {+ return {+ error: err.message,+ rows: [],+ summary: { total: 0, push: 0, pr: 0, issues: 0, reviews: 0 },+ };+ }+ }),++ // ── Commit Activity (per repo) ───────────────────────────────────────++ get_commit_activity: (args) =>+ cached(`commits:${username}:${args.repo}`, async () => {+ const repo = args.repo as string;+ if (!repo) return { error: "repo argument is required", rows: [] };++ const limitErr = checkRateLimit();+ if (limitErr) return { error: limitErr, rows: [] };++ try {+ const data = await fetchWithRetry(+ octokit,+ "GET /repos/{owner}/{repo}/stats/commit_activity",+ { owner: username, repo },+ );++ if (!Array.isArray(data)) return data; // error object++ const rows: CommitWeek[] = data.map((w: { week: number; total: number }) => ({+ week: new Date(w.week * 1000).toISOString().slice(0, 10),+ total: w.total,+ }));++ return { rows };+ } catch (err: any) {+ return { error: err.message, rows: [] };+ }+ }),++ // ── Star History (per repo) ──────────────────────────────────────────++ get_star_history: (args) =>+ cached(`stars:${username}:${args.repo}`, async () => {+ const repo = args.repo as string;+ if (!repo) return { error: "repo argument is required", rows: [] };++ const limitErr = checkRateLimit();+ if (limitErr) return { error: limitErr, rows: [] };++ try {+ const res = await octokit.request("GET /repos/{owner}/{repo}/stargazers", {+ owner: username,+ repo,+ per_page: 100,+ headers: { accept: "application/vnd.github.star+json" },+ });+ updateRateLimit(res);++ const stargazers = res.data as Array<{+ starred_at: string;+ user: { login: string };+ }>;++ const rows: StarPoint[] = stargazers.map((s, i) => ({+ starred_at: s.starred_at.slice(0, 10),+ cumulative: i + 1,+ }));++ return { rows };+ } catch (err: any) {+ return { error: err.message, rows: [] };+ }+ }),++ // ── Contributors (per repo) ──────────────────────────────────────────++ get_contributors: (args) =>+ cached(`contrib:${username}:${args.repo}`, async () => {+ const repo = args.repo as string;+ if (!repo) return { error: "repo argument is required", rows: [] };++ const limitErr = checkRateLimit();+ if (limitErr) return { error: limitErr, rows: [] };++ try {+ const data = await fetchWithRetry(+ octokit,+ "GET /repos/{owner}/{repo}/stats/contributors",+ { owner: username, repo },+ );++ if (!Array.isArray(data)) return data;++ const rows: ContributorRow[] = data+ .map((c: any) => ({+ login: c.author?.login ?? "unknown",+ avatar_url: c.author?.avatar_url ?? "",+ total_commits: c.total ?? 0,+ }))+ .sort((a: ContributorRow, b: ContributorRow) => b.total_commits - a.total_commits)+ .slice(0, 20);++ return { rows };+ } catch (err: any) {+ return { error: err.message, rows: [] };+ }+ }),++ // ── Bookmarks (localStorage) ─────────────────────────────────────────++ save_bookmark: async (args) => {+ const repo = args.repo as string;+ if (!repo) return { error: "repo argument is required" };+ const bookmark = saveBookmark(+ username,+ repo,+ args.note as string | undefined,+ args.tag as string | undefined,+ );+ return { success: true, bookmark };+ },++ get_bookmarks: async () => {+ return { rows: getBookmarks(username) };+ },++ delete_bookmark: async (args) => {+ const repo = args.repo as string;+ if (!repo) return { error: "repo argument is required" };+ return deleteBookmark(username, repo);+ },+ };+}diff --git a/docs/app/demo/github/github/types.ts b/docs/app/demo/github/github/types.tsnew file mode 100644index 000000000..46153e335--- /dev/null+++ b/docs/app/demo/github/github/types.ts@@ -0,0 +1,347 @@+import type { ToolSpec } from "@openuidev/lang-core";++// ── Transformed GitHub data interfaces ────────────────────────────────────++export interface GitHubProfile {+ login: string;+ name: string;+ bio: string;+ avatar_url: string;+ public_repos: number;+ followers: number;+ following: number;+ created_at: string;+}++export interface RepoRow {+ name: string;+ full_name: string;+ description: string;+ language: string;+ stars: number;+ forks: number;+ size: number;+ open_issues: number;+ updated_at: string;+ html_url: string;+}++export interface LanguageRow {+ language: string;+ bytes: number;+ repos_count: number;+}++export interface EventRow {+ type: string;+ repo: string;+ date: string;+ count: number;+}++export interface CommitWeek {+ week: string;+ total: number;+}++export interface StarPoint {+ starred_at: string;+ cumulative: number;+}++export interface ContributorRow {+ login: string;+ avatar_url: string;+ total_commits: number;+}++export interface Bookmark {+ repo: string;+ note: string;+ tag: string;+ created_at: string;+}++// ── ToolSpec definitions for system prompt ──────────────────────────────++export const GITHUB_TOOL_SPECS: ToolSpec[] = [+ {+ name: "get_profile",+ description:+ "Get the connected GitHub user's profile — name, bio, avatar, follower/following counts, public repo count, join date",+ inputSchema: { type: "object", properties: {} },+ outputSchema: {+ type: "object",+ properties: {+ login: { type: "string" },+ name: { type: "string" },+ bio: { type: "string" },+ avatar_url: { type: "string" },+ public_repos: { type: "integer" },+ followers: { type: "integer" },+ following: { type: "integer" },+ created_at: { type: "string" },+ },+ },+ annotations: { readOnlyHint: true },+ },+ {+ name: "get_repos",+ description:+ "List the user's public repositories with stars, forks, language, size, open issues. Supports sorting and language filtering.",+ inputSchema: {+ type: "object",+ properties: {+ sort: {+ type: "string",+ enum: ["stars", "forks", "updated", "created"],+ description: "Sort field (default: stars)",+ },+ language: {+ type: "string",+ description: "Filter by programming language (e.g. 'TypeScript'). Omit or empty for all.",+ },+ },+ },+ outputSchema: {+ type: "object",+ properties: {+ rows: {+ type: "array",+ items: {+ type: "object",+ properties: {+ name: { type: "string" },+ full_name: { type: "string" },+ description: { type: "string" },+ language: { type: "string" },+ stars: { type: "integer" },+ forks: { type: "integer" },+ size: { type: "integer" },+ open_issues: { type: "integer" },+ updated_at: { type: "string" },+ html_url: { type: "string" },+ },+ },+ },+ },+ },+ annotations: { readOnlyHint: true },+ },+ {+ name: "get_languages",+ description:+ "Get aggregated language breakdown across all repos — language name, bytes of code, number of repos using it. Sorted by bytes descending.",+ inputSchema: { type: "object", properties: {} },+ outputSchema: {+ type: "object",+ properties: {+ rows: {+ type: "array",+ items: {+ type: "object",+ properties: {+ language: { type: "string" },+ bytes: { type: "integer" },+ repos_count: { type: "integer" },+ },+ },+ },+ },+ },+ annotations: { readOnlyHint: true },+ },+ {+ name: "get_events",+ description:+ "Get the user's recent public events (pushes, PRs, issues, reviews, forks, stars) from the last 30 days. Returns event rows + summary counts.",+ inputSchema: { type: "object", properties: {} },+ outputSchema: {+ type: "object",+ properties: {+ rows: {+ type: "array",+ items: {+ type: "object",+ properties: {+ type: { type: "string" },+ repo: { type: "string" },+ date: { type: "string" },+ count: { type: "integer" },+ },+ },+ },+ summary: {+ type: "object",+ properties: {+ total: { type: "integer" },+ push: { type: "integer" },+ pr: { type: "integer" },+ issues: { type: "integer" },+ reviews: { type: "integer" },+ },+ },+ },+ },+ annotations: { readOnlyHint: true },+ },+ {+ name: "get_commit_activity",+ description: "Get weekly commit counts for a specific repo over the past year (52 weeks).",+ inputSchema: {+ type: "object",+ properties: {+ repo: {+ type: "string",+ description:+ 'Repository name (just the name, not full path — e.g. "linux" not "torvalds/linux")',+ },+ },+ required: ["repo"],+ },+ outputSchema: {+ type: "object",+ properties: {+ rows: {+ type: "array",+ items: {+ type: "object",+ properties: {+ week: { type: "string" },+ total: { type: "integer" },+ },+ },+ },+ },+ },+ annotations: { readOnlyHint: true },+ },+ {+ name: "get_star_history",+ description:+ "Get star history for a repo — who starred it and when, with cumulative count for charting.",+ inputSchema: {+ type: "object",+ properties: {+ repo: {+ type: "string",+ description: "Repository name (e.g. 'linux')",+ },+ },+ required: ["repo"],+ },+ outputSchema: {+ type: "object",+ properties: {+ rows: {+ type: "array",+ items: {+ type: "object",+ properties: {+ starred_at: { type: "string" },+ cumulative: { type: "integer" },+ },+ },+ },+ },+ },+ annotations: { readOnlyHint: true },+ },+ {+ name: "get_contributors",+ description: "Get contributor stats for a repo — login, avatar, total commits.",+ inputSchema: {+ type: "object",+ properties: {+ repo: {+ type: "string",+ description: "Repository name (e.g. 'linux')",+ },+ },+ required: ["repo"],+ },+ outputSchema: {+ type: "object",+ properties: {+ rows: {+ type: "array",+ items: {+ type: "object",+ properties: {+ login: { type: "string" },+ avatar_url: { type: "string" },+ total_commits: { type: "integer" },+ },+ },+ },+ },+ },+ annotations: { readOnlyHint: true },+ },+ {+ name: "save_bookmark",+ description:+ "Save a repository bookmark with a note and tag. Upserts — saving the same repo updates it.",+ inputSchema: {+ type: "object",+ properties: {+ repo: { type: "string", description: "Repository name to bookmark" },+ note: { type: "string", description: "User note about the repo" },+ tag: {+ type: "string",+ enum: ["important", "review", "learning", "favorite"],+ description: "Tag category",+ },+ },+ required: ["repo"],+ },+ outputSchema: {+ type: "object",+ properties: {+ success: { type: "boolean" },+ },+ },+ annotations: { readOnlyHint: false },+ },+ {+ name: "get_bookmarks",+ description: "Get all saved bookmarks for the current user.",+ inputSchema: { type: "object", properties: {} },+ outputSchema: {+ type: "object",+ properties: {+ rows: {+ type: "array",+ items: {+ type: "object",+ properties: {+ repo: { type: "string" },+ note: { type: "string" },+ tag: { type: "string" },+ created_at: { type: "string" },+ },+ },+ },+ },+ },+ annotations: { readOnlyHint: true },+ },+ {+ name: "delete_bookmark",+ description: "Delete a bookmark by repo name.",+ inputSchema: {+ type: "object",+ properties: {+ repo: { type: "string", description: "Repository name to remove" },+ },+ required: ["repo"],+ },+ outputSchema: {+ type: "object",+ properties: {+ success: { type: "boolean" },+ },+ },+ annotations: { readOnlyHint: false, destructiveHint: true },+ },+];diff --git a/docs/app/demo/github/layout.css b/docs/app/demo/github/layout.cssnew file mode 100644index 000000000..9be46683a--- /dev/null+++ b/docs/app/demo/github/layout.css@@ -0,0 +1,618 @@+/* Scope playground resets so they do not leak into other routes after navigation.+ Use `:where()` to keep specificity at zero and avoid overriding react-ui classes. */+:where(.app, .app *, .app *::before, .app *::after) {+ box-sizing: border-box;+ margin: 0;+ padding: 0;+}++/* ─── Global ────────────────────────────────────────────────────────────────── */+.app {+ font-family: var(--openui-font-body);+ background-color: var(--openui-foreground);+ color: var(--openui-text-neutral-primary);+ -webkit-font-smoothing: antialiased;+ -moz-osx-font-smoothing: grayscale;+ transition:+ background-color 0.2s ease,+ color 0.2s ease;+}++/* ─── Scrollbar ─────────────────────────────────────────────────────────────── */+.app::-webkit-scrollbar,+.app ::-webkit-scrollbar {+ width: 6px;+ height: 6px;+}+.app::-webkit-scrollbar-track,+.app ::-webkit-scrollbar-track {+ background: transparent;+}+.app::-webkit-scrollbar-thumb,+.app ::-webkit-scrollbar-thumb {+ background: var(--openui-text-neutral-tertiary);+ border-radius: 3px;+}++/* ─── App Layout ────────────────────────────────────────────────────────────── */+.app {+ --playground-focus-ring: color-mix(+ in srgb,+ var(--openui-border-accent-emphasis) 24%,+ transparent+ );+ --playground-code-background: var(--openui-inverted-background);+ --playground-code-foreground: var(--openui-text-accent-primary);+ display: flex;+ flex-direction: column;+ height: 100vh;+ background: var(--openui-foreground);+}++.app-body {+ display: flex;+ flex: 1;+ min-height: 0;+ overflow: hidden;+}++.app-body-home {+ overflow-y: auto;+}++.content-wrapper {+ flex: 1;+ display: flex;+ flex-direction: column;+ padding: var(--openui-space-2xl) var(--openui-space-xl);+ overflow: hidden;+ min-width: 0;+}++.content-wrapper-home {+ justify-content: center;+ padding: 0;+ overflow: visible;+}++/* ─── Split Screen ──────────────────────────────────────────────────────────── */+.split-screen {+ display: grid;+ grid-template-columns: 2fr 3fr;+ gap: 16px;+ flex: 1;+ min-height: 0;+ overflow: hidden;+}++/* ─── Shared Panel ──────────────────────────────────────────────────────────── */+.panel {+ display: flex;+ flex-direction: column;+ border: 1px solid var(--openui-border-default);+ border-radius: var(--openui-radius-xl);+ overflow: hidden;+ background: var(--openui-foreground);+ min-height: 0;+}++.panel-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: var(--openui-space-s-m) var(--openui-space-m-l);+ background: var(--openui-highlight-subtle);+ border-bottom: 1px solid var(--openui-border-default);+ flex-shrink: 0;+}++.panel-title {+ font-size: 12px;+ font-weight: 600;+ color: var(--openui-text-neutral-secondary);+ letter-spacing: 0.04em;+ text-transform: uppercase;+}++.panel-actions {+ display: flex;+ align-items: center;+ gap: var(--openui-space-2xs);+}++.openui-icon-button.panel-icon-btn {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 28px;+ height: 28px;+ background: transparent;+ border: none;+ border-radius: var(--openui-radius-s);+ color: var(--openui-text-neutral-tertiary);+ cursor: pointer;+ transition:+ background-color 0.15s,+ color 0.15s;+}++.openui-icon-button.panel-icon-btn:hover:not(:disabled) {+ background-color: var(--openui-highlight);+ color: var(--openui-text-neutral-primary);+}++.openui-icon-button.panel-icon-btn:focus-visible,+.openui-button-base.send-btn:focus-visible,+.openui-button-base.stop-btn:focus-visible,+.openui-button-base.chip:focus-visible,+.openui-button-base.dashboard-source-toggle:focus-visible,+.openui-button-base.gh-connected-change:focus-visible {+ outline: 2px solid var(--openui-border-accent);+ outline-offset: 2px;+}++/* ─── Shared Empty State ────────────────────────────────────────────────────── */+.empty-state {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: var(--openui-space-s);+ padding: var(--openui-space-2xl) var(--openui-space-xl);+ text-align: center;+ color: var(--openui-text-neutral-tertiary);+ height: 100%;+}++.empty-state-icon {+ opacity: 0.3;+ margin-bottom: 4px;+}++.empty-state-text {+ font-size: 13px;+ line-height: 1.5;+}++/* ─── Prompt Section ────────────────────────────────────────────────────────── */+.prompt-section {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--openui-space-m-l);+ padding: var(--openui-space-3xl) 0 var(--openui-space-2xl);+}++.prompt-heading {+ font-size: 28px;+ font-weight: 600;+ letter-spacing: -0.03em;+ color: var(--openui-text-neutral-primary);+ text-align: center;+}++.prompt-container {+ width: 100%;+ max-width: 760px;+ background: var(--openui-foreground);+ border: 1px solid var(--openui-border-interactive);+ border-radius: var(--openui-radius-2xl);+ display: flex;+ flex-direction: column;+ transition: border-color 0.15s;+ box-shadow: var(--openui-shadow-m);+}++.prompt-container:focus-within {+ border-color: var(--openui-border-accent-emphasis);+ box-shadow: 0 0 0 3px var(--playground-focus-ring);+}++.prompt-textarea {+ width: 100%;+ padding: var(--openui-space-m-l) var(--openui-space-m-l) 0;+ background: transparent;+ border: none;+ outline: none;+ resize: none;+ font-family: var(--openui-font-body);+ font-size: 15px;+ line-height: 1.5;+ color: var(--openui-text-neutral-primary);+ min-height: 64px;+ max-height: 240px;+ overflow-y: auto;+}++.prompt-textarea::placeholder {+ color: var(--openui-text-neutral-tertiary);+}++.prompt-textarea:disabled {+ opacity: 0.4;+ cursor: not-allowed;+}++.prompt-actions {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: var(--openui-space-s-m) var(--openui-space-m);+ gap: var(--openui-space-s);+}++.model-select {+ background: var(--openui-highlight-subtle);+ border: 1px solid var(--openui-border-default);+ border-radius: var(--openui-radius-m);+ color: var(--openui-text-neutral-secondary);+ font-family: var(--openui-font-body);+ font-size: 12px;+ font-weight: 500;+ padding: 5px 8px;+ cursor: pointer;+ outline: none;+ transition: border-color 0.15s;+ appearance: none;+ -webkit-appearance: none;+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' stroke='%23999' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round' fill='none'/%3E%3C/svg%3E");+ background-repeat: no-repeat;+ background-position: right 8px center;+ padding-right: 24px;+}++.model-select:focus {+ border-color: var(--openui-border-interactive);+}++.model-select:disabled {+ opacity: 0.4;+ cursor: not-allowed;+}++.openui-button-base.send-btn {+ display: flex;+ align-items: center;+ gap: var(--openui-space-xs);+ padding: var(--openui-space-xs) var(--openui-space-m);+ background: var(--openui-interactive-accent-default);+ color: var(--openui-text-accent-primary);+ border: none;+ border-radius: var(--openui-radius-m);+ font-family: var(--openui-font-body);+ font-size: 13px;+ font-weight: 500;+ cursor: pointer;+ transition:+ background 0.15s,+ opacity 0.15s;+ flex-shrink: 0;+}++.openui-button-base.send-btn:hover:not(:disabled) {+ background: var(--openui-interactive-accent-hover);+}++.openui-button-base.send-btn:disabled {+ opacity: 0.35;+ cursor: not-allowed;+}++.openui-button-base.stop-btn {+ display: flex;+ align-items: center;+ gap: var(--openui-space-xs);+ padding: var(--openui-space-xs) var(--openui-space-m);+ background: transparent;+ color: var(--openui-text-neutral-secondary);+ border: 1px solid var(--openui-border-interactive);+ border-radius: var(--openui-radius-m);+ font-family: var(--openui-font-body);+ font-size: 13px;+ font-weight: 500;+ cursor: pointer;+ transition:+ background 0.15s,+ color 0.15s,+ border-color 0.15s;+ flex-shrink: 0;+}++.openui-button-base.stop-btn:hover:not(:disabled) {+ background-color: var(--openui-highlight);+ color: var(--openui-text-neutral-primary);+ border-color: var(--openui-border-interactive-emphasis);+}++/* ─── Chips ─────────────────────────────────────────────────────────────────── */+.chips-row {+ display: flex;+ flex-wrap: wrap;+ gap: var(--openui-space-s);+ justify-content: center;+ max-width: 760px;+ width: 100%;+}++.openui-button-base.chip {+ padding: var(--openui-space-s-m) var(--openui-space-m-l);+ background: var(--openui-highlight-subtle);+ border: 1px solid var(--openui-border-interactive);+ border-radius: var(--openui-radius-full);+ color: var(--openui-text-neutral-primary);+ font-size: 13px;+ cursor: pointer;+ transition:+ background 0.15s,+ color 0.15s,+ border-color 0.15s;+ white-space: nowrap;+ flex-shrink: 0;+}++.openui-button-base.chip:hover:not(:disabled),+.openui-button-base.chip:active:not(:disabled) {+ background-color: var(--openui-highlight);+ color: var(--openui-text-neutral-primary);+ border-color: var(--openui-border-interactive);+}++.openui-button-base.chip-selected,+.openui-button-base.chip-selected:hover:not(:disabled),+.openui-button-base.chip-selected:active:not(:disabled) {+ border-color: var(--openui-border-interactive-selected);+}++.openui-button-base.chip:disabled {+ opacity: 0.4;+ cursor: not-allowed;+}++/* ─── Error Banner ──────────────────────────────────────────────────────────── */+.error-banner {+ margin: 0 0 var(--openui-space-m-l);+ padding: var(--openui-space-m) var(--openui-space-m-l);+ background: var(--openui-danger-background);+ border: 1px solid var(--openui-border-danger);+ border-radius: var(--openui-radius-m);+ font-size: 13px;+ color: var(--openui-text-danger-primary);+ line-height: 1.5;+}++/* ─── Artifact Layout (GitHub connected mode) ──────────────────────────────── */+.artifact-layout {+ display: flex;+ flex: 1;+ min-height: 0;+ overflow: hidden;+}++.dashboard-area {+ flex: 1;+ overflow: auto;+ padding: var(--openui-space-m-l) var(--openui-space-xl);+ min-width: 0;+}++.dashboard-renderer {+ min-height: 200px;+}++.dashboard-renderer .panel {+ border-radius: var(--openui-radius-xl);+ box-shadow: var(--openui-shadow-s);+}++.dashboard-meta {+ display: flex;+ gap: var(--openui-space-m);+ margin-bottom: var(--openui-space-s);+ font-size: 12px;+ color: var(--openui-text-neutral-tertiary);+ align-items: center;+}++.dashboard-elapsed {+ font-family: var(--openui-font-code);+}++.openui-button-base.dashboard-source-toggle {+ display: flex;+ align-items: center;+ gap: var(--openui-space-2xs);+ padding: var(--openui-space-2xs) var(--openui-space-s);+ background: var(--openui-highlight-subtle);+ border: 1px solid var(--openui-border-default);+ border-radius: var(--openui-radius-full);+ cursor: pointer;+ color: var(--openui-text-neutral-secondary);+ font-size: 12px;+ font-family: var(--openui-font-body);+ transition:+ background-color 0.15s,+ border-color 0.15s,+ color 0.15s;+}++.openui-button-base.dashboard-source-toggle:hover:not(:disabled) {+ background: var(--openui-highlight);+ border-color: var(--openui-border-interactive);+ color: var(--openui-text-neutral-primary);+}++.dashboard-source {+ background: var(--playground-code-background);+ color: var(--playground-code-foreground);+ padding: var(--openui-space-m);+ border: 1px solid var(--openui-border-default);+ border-radius: var(--openui-radius-m);+ font-size: 11px;+ font-family: var(--openui-font-code);+ overflow: auto;+ white-space: pre-wrap;+ max-height: 250px;+ line-height: 1.4;+ margin-bottom: var(--openui-space-m);+}++.dashboard-loading {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: 60px var(--openui-space-xl);+ color: var(--openui-text-neutral-tertiary);+ gap: var(--openui-space-xs);+}++.dashboard-loading-text {+ font-size: 14px;+}++.dashboard-loading-timer {+ font-size: 12px;+ font-family: var(--openui-font-code);+}++/* Connected user bar */+.gh-connected-bar {+ display: flex;+ align-items: center;+ gap: var(--openui-space-s);+ padding: var(--openui-space-s) var(--openui-space-m);+ margin-bottom: var(--openui-space-m);+ border: 1px solid var(--openui-border-default);+ border-radius: var(--openui-radius-m);+ background: var(--openui-highlight-subtle);+ font-size: 13px;+ color: var(--openui-text-neutral-secondary);+ font-family: var(--openui-font-body);+}++.gh-connected-avatar {+ width: 20px;+ height: 20px;+ border-radius: 50%;+}++.openui-button-base.gh-connected-change {+ margin-left: auto;+ background: transparent;+ border: none;+ color: var(--openui-text-neutral-tertiary);+ font-size: 12px;+ cursor: pointer;+ padding: var(--openui-space-2xs) var(--openui-space-xs);+ border-radius: var(--openui-radius-s);+ font-family: var(--openui-font-body);+ box-shadow: none;+ transition:+ color 0.15s,+ background-color 0.15s;+}++.openui-button-base.gh-connected-change:hover:not(:disabled) {+ color: var(--openui-text-neutral-primary);+ background: var(--openui-highlight);+}++/* GitHub starters welcome (inside artifact layout) */+.gh-starters-welcome {+ max-width: 600px;+ margin: var(--openui-space-3xl) auto;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--openui-space-xl);+}++.gh-welcome-text {+ display: flex;+ align-items: center;+ gap: var(--openui-space-s);+ font-size: 15px;+ color: var(--openui-text-neutral-secondary);+ font-family: var(--openui-font-body);+ text-align: center;+ flex-wrap: wrap;+ justify-content: center;+}++.gh-welcome-avatar {+ display: flex;+ align-items: center;+}++.gh-welcome-avatar-image {+ width: 24px;+ height: 24px;+ border-radius: var(--openui-radius-full);+}++.gh-starters-grid-compact {+ width: min(100%, 600px);+}++/* ─── Responsive ────────────────────────────────────────────────────────────── */+@media (max-width: 768px) {+ .app {+ height: 100dvh;+ overflow: hidden;+ }++ .app-body {+ flex-direction: column;+ overflow-y: auto;+ overflow-x: hidden;+ }++ .content-wrapper {+ flex: none;+ overflow: visible;+ padding: 20px var(--openui-space-m-l) var(--openui-space-2xl);+ }++ .content-wrapper-home {+ padding: 0;+ }++ .split-screen {+ display: flex;+ flex-direction: column;+ gap: 12px;+ overflow: visible;+ min-height: 0;+ }++ .panel {+ height: 380px;+ flex-shrink: 0;+ }++ .prompt-section {+ padding: 24px 0 20px;+ gap: 12px;+ }++ .prompt-heading {+ font-size: 20px;+ }++ .chips-row {+ gap: 6px;+ }++ .chip {+ font-size: 12px;+ padding: 5px 12px;+ }++ .artifact-layout {+ flex-direction: column;+ }++ .dashboard-area {+ padding: var(--openui-space-m) var(--openui-space-m-l);+ }+}diff --git a/docs/app/demo/github/layout.tsx b/docs/app/demo/github/layout.tsxnew file mode 100644index 000000000..39f12f65d--- /dev/null+++ b/docs/app/demo/github/layout.tsx@@ -0,0 +1,7 @@+import { WebsiteThemeProvider } from "@/components/website-theme-provider";+import type { ReactNode } from "react";+import "./layout.css";++export default function DemoGitHubLayout({ children }: { children: ReactNode }) {+ return <WebsiteThemeProvider>{children}</WebsiteThemeProvider>;+}diff --git a/docs/app/demo/github/page.tsx b/docs/app/demo/github/page.tsxnew file mode 100644index 000000000..082bac644--- /dev/null+++ b/docs/app/demo/github/page.tsx@@ -0,0 +1,537 @@+"use client";++import { mergeStatements } from "@openuidev/react-lang";+import { Button } from "@openuidev/react-ui";+import { Code2 } from "lucide-react";+import { useTheme } from "next-themes";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { ConversationPanel } from "./components/ConversationPanel/ConversationPanel";+import { GitHubConnect } from "./components/GitHubConnect/GitHubConnect";+import { Header } from "./components/Header/Header";+import { PreviewPanel } from "./components/PreviewPanel/PreviewPanel";+import {+ GITHUB_STARTERS,+ type ChatMessage,+ type Status,+ type Theme,+ type ToolCallEntry,+} from "./constants";+import { clearCache, createGitHubToolProvider } from "./github/tools";++// ── Helpers ─────────────────────────────────────────────────────────────────++function extractCodeOnly(response: string): string | null {+ const fenceRegex = /```[\w-]*\n([\s\S]*?)```/g;+ const blocks: string[] = [];+ let match;+ while ((match = fenceRegex.exec(response)) !== null) {+ blocks.push(match[1].trim());+ }+ if (blocks.length > 0) return blocks.join("\n");++ const unclosedMatch = response.match(/```[\w-]*\n([\s\S]*)$/);+ if (unclosedMatch) return unclosedMatch[1].trim() || null;++ if (isPureCode(response)) return response;+ return null;+}++function extractText(response: string): string {+ const withoutFences = response.replace(/```[\w-]*\n[\s\S]*?```/g, "").trim();+ const withoutUnclosed = withoutFences.replace(/```[\w-]*\n[\s\S]*$/g, "").trim();+ if (withoutUnclosed && isPureCode(withoutUnclosed)) return "";+ return withoutUnclosed;+}++function responseHasCode(response: string): boolean {+ if (/```[\w-]*\n/.test(response)) return true;+ const trimmed = response.trim();+ if (/^[a-zA-Z_$][\w$]*\s*=\s*/.test(trimmed)) return true;+ return false;+}++function isPureCode(response: string): boolean {+ const trimmed = response.trim();+ if (/```/.test(trimmed)) return false;+ const lines = trimmed.split("\n").filter((l) => l.trim());+ if (lines.length === 0) return false;+ const stmtPattern = /^[a-zA-Z_$][\w$]*\s*=/;+ const stmtCount = lines.filter((l) => stmtPattern.test(l.trim())).length;+ return stmtCount / lines.length > 0.7;+}++// ── Tool call tracking wrapper ───────────────────────────────────────────++type ToolCallListener = (calls: ToolCallEntry[]) => void;++function wrapToolProvider(+ inner: Record<string, (args: Record<string, unknown>) => Promise<unknown>>,+ listener: ToolCallListener,+): Record<string, (args: Record<string, unknown>) => Promise<unknown>> {+ const activeCalls: ToolCallEntry[] = [];+ const wrapped: Record<string, (args: Record<string, unknown>) => Promise<unknown>> = {};++ for (const [name, fn] of Object.entries(inner)) {+ wrapped[name] = async (args) => {+ const entry: ToolCallEntry = { tool: name, status: "pending" };+ activeCalls.push(entry);+ listener([...activeCalls]);+ try {+ const data = await fn(args);+ entry.status = "done";+ listener([...activeCalls]);+ return data;+ } catch {+ entry.status = "error";+ listener([...activeCalls]);+ return null;+ }+ };+ }++ return wrapped;+}++// ── SSE streaming ────────────────────────────────────────────────────────++async function streamChat(+ body: Record<string, unknown>,+ onChunk: (text: string) => void,+ onDone: () => void,+ signal?: AbortSignal,+ onFirstChunk?: () => void,+) {+ const res = await fetch("/api/demo/github/stream", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ signal,+ });++ if (!res.ok) {+ const err = await res.json().catch(() => ({}));+ onChunk(+ `Error: ${(err as { error?: { message?: string } }).error?.message ?? `Server error ${res.status}`}`,+ );+ onDone();+ return;+ }++ const reader = res.body!.getReader();+ const decoder = new TextDecoder();+ let firstChunkFired = false;++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ const raw = decoder.decode(value, { stream: true });+ for (const line of raw.split("\n")) {+ const trimmed = line.trim();+ if (!trimmed.startsWith("data:")) continue;+ const data = trimmed.slice(5).trim();+ if (data === "[DONE]") {+ onDone();+ return;+ }+ try {+ const parsed = JSON.parse(data) as {+ choices: Array<{ delta: { content?: string } }>;+ };+ const content = parsed.choices[0]?.delta?.content;+ if (content) {+ if (!firstChunkFired) {+ firstChunkFired = true;+ onFirstChunk?.();+ }+ onChunk(content);+ }+ } catch {+ // skip malformed chunks+ }+ }+ }+ onDone();+}++// ── Main Page ────────────────────────────────────────────────────────────++export default function GitHubDemoPage() {+ // Theme+ const { theme, setTheme, resolvedTheme } = useTheme();++ // GitHub connection+ const [githubUsername, setGithubUsername] = useState<string | null>(null);+ const [toolProvider, setToolProvider] = useState<Record<+ string,+ (args: Record<string, unknown>) => Promise<unknown>+ > | null>(null);++ // Dashboard state+ const [dashboardCode, setDashboardCode] = useState<string | null>(null);+ const [showSource, setShowSource] = useState(false);+ const [parsedJson, setParsedJson] = useState<string | null>(null);++ // Conversation+ const [conversation, setConversation] = useState<ChatMessage[]>([]);+ const [streamingText, setStreamingText] = useState("");+ const [toolCalls, setToolCalls] = useState<ToolCallEntry[]>([]);+ const [streamResponseHasCode, setStreamResponseHasCode] = useState(false);++ // Streaming+ const [status, setStatus] = useState<Status>("idle");+ const [startTime, setStartTime] = useState<number | null>(null);+ const [elapsed, setElapsed] = useState<number | null>(null);+ const [errorMsg, setErrorMsg] = useState("");++ const abortRef = useRef<AbortController | null>(null);+ const responseRef = useRef("");+ const pendingPromptRef = useRef<string | null>(null);++ const isStreaming = status === "streaming";+ const hasDashboard = dashboardCode !== null;+ const isGitHub = githubUsername !== null;+ const isHomeState = !isGitHub && !hasDashboard && conversation.length === 0;++ // Theme+ const currentTheme = useMemo<Theme>(() => {+ if (theme === "light" || theme === "dark" || theme === "system") {+ return theme;+ }+ return "system";+ }, [theme]);++ const resolvedMode = resolvedTheme === "dark" ? "dark" : "light";++ const cycleTheme = () =>+ setTheme(currentTheme === "system" ? "light" : currentTheme === "light" ? "dark" : "system");++ // Timer+ useEffect(() => {+ if (!isStreaming || !startTime) return;+ const iv = setInterval(() => setElapsed(Date.now() - startTime), 100);+ return () => clearInterval(iv);+ }, [isStreaming, startTime]);++ // ── GitHub connect ───────────────────────────────────────────────────++ const handleConnect = useCallback((username: string) => {+ const rawTools = createGitHubToolProvider(username);+ const wrapped = wrapToolProvider(rawTools, (calls) => {+ setToolCalls([...calls]);+ setConversation((prev) => {+ if (prev.length === 0) return prev;+ const last = prev[prev.length - 1];+ if (last.role !== "assistant") return prev;+ return [...prev.slice(0, -1), { ...last, runtimeTools: [...calls] }];+ });+ });+ setGithubUsername(username);+ setToolProvider(wrapped);+ }, []);++ const handleDisconnect = () => {+ abortRef.current?.abort();+ abortRef.current = null;+ clearCache();+ setGithubUsername(null);+ setToolProvider(null);+ setDashboardCode(null);+ setConversation([]);+ setStatus("idle");+ setStreamingText("");+ setToolCalls([]);+ setStreamResponseHasCode(false);+ setElapsed(null);+ setShowSource(false);+ setParsedJson(null);+ setErrorMsg("");+ };++ // ── Send message ─────────────────────────────────────────────────────++ const send = useCallback(+ async (text: string) => {+ if (!text.trim() || isStreaming) return;+ const trimmed = text.trim();++ setStatus("streaming");+ setStartTime(null);+ setElapsed(null);+ setErrorMsg("");+ responseRef.current = "";+ setStreamingText("");+ setToolCalls([]);+ setStreamResponseHasCode(false);+ let streamStartTime: number | null = null;++ const userMsg: ChatMessage = {+ role: "user",+ content: trimmed,+ hasCode: false,+ };+ const updated = [...conversation, userMsg];+ setConversation(updated);+ const existingCode = dashboardCode;++ // Build API messages+ const apiMessages = updated.map((m, i) => {+ if (m.role === "user" && i === updated.length - 1 && existingCode) {+ return {+ role: m.role,+ content: `${m.content}\n\n<current-dashboard>\n${existingCode}\n</current-dashboard>`,+ };+ }+ return { role: m.role, content: m.content };+ });++ const controller = new AbortController();+ abortRef.current = controller;++ try {+ await streamChat(+ {+ prompt: trimmed,+ messages: apiMessages.slice(0, -1),+ },+ (chunk) => {+ responseRef.current += chunk;+ const raw = responseRef.current;+ setStreamingText(extractText(raw) || "");+ setStreamResponseHasCode(responseHasCode(raw));+ if (existingCode) {+ setDashboardCode(existingCode + "\n" + raw);+ } else {+ setDashboardCode(raw);+ }+ },+ () => {+ setStatus("done");+ abortRef.current = null;+ setStreamingText("");+ setStreamResponseHasCode(false);+ if (streamStartTime) setElapsed(Date.now() - streamStartTime);++ const raw = responseRef.current;+ const hasCode = responseHasCode(raw);+ const pureCode = isPureCode(raw);+ const text = pureCode ? undefined : extractText(raw) || undefined;++ const assistantMsg: ChatMessage = {+ role: "assistant",+ content: raw,+ text,+ hasCode,+ runtimeTools: toolCalls.length > 0 ? [...toolCalls] : undefined,+ };+ setConversation((prev) => [...prev, assistantMsg]);++ if (hasCode) {+ const newCode = pureCode ? raw : extractCodeOnly(raw);+ if (newCode) {+ const merged = existingCode ? mergeStatements(existingCode, newCode) : newCode;+ setDashboardCode(merged);+ }+ }+ },+ controller.signal,+ () => {+ streamStartTime = Date.now();+ setStartTime(streamStartTime);+ },+ );+ } catch (err: unknown) {+ if (err instanceof Error && err.name === "AbortError") {+ setStreamResponseHasCode(false);+ setStatus("idle");+ return;+ }+ setErrorMsg(err instanceof Error ? err.message : "Unknown error");+ setStreamResponseHasCode(false);+ setStatus("error");+ }+ },+ [isStreaming, conversation, dashboardCode, toolCalls],+ );++ // Process pending prompt after GitHub connect+ useEffect(() => {+ if (githubUsername && toolProvider && pendingPromptRef.current) {+ const p = pendingPromptRef.current;+ pendingPromptRef.current = null;+ send(p);+ }+ }, [githubUsername, toolProvider, send]);++ const handleStop = () => {+ abortRef.current?.abort();+ setStreamResponseHasCode(false);+ setStatus("idle");+ };++ const handleConnectAndPrompt = useCallback(+ (username: string, promptText: string) => {+ pendingPromptRef.current = promptText;+ handleConnect(username);+ },+ [handleConnect],+ );++ // ── Render ─────────────────────────────────────────────────────────────++ const showConversation = conversation.length > 0 || isStreaming;++ return (+ <div className={`app ${isHomeState ? "app-home" : "app-artifact"}`}>+ <Header+ theme={currentTheme}+ onThemeToggle={cycleTheme}+ borderMode={isHomeState ? "scroll" : "always"}+ />++ <div className={`app-body ${isHomeState ? "app-body-home" : ""}`}>+ {/* Phase 1: Connect Screen */}+ {isHomeState && (+ <div className="content-wrapper content-wrapper-home">+ <GitHubConnect onConnectAndPrompt={handleConnectAndPrompt} />+ </div>+ )}++ {/* Phase 2: Artifact Layout */}+ {(isGitHub || hasDashboard || conversation.length > 0) && (+ <div className="artifact-layout">+ {/* Left: Dashboard */}+ <div className="dashboard-area">+ {/* Connected user bar */}+ {isGitHub && (hasDashboard || conversation.length > 0) && (+ <div className="gh-connected-bar">+ <img+ src={`https://github.com/${githubUsername}.png?size=32`}+ alt=""+ className="gh-connected-avatar"+ />+ <span>@{githubUsername}</span>+ <Button+ className="gh-connected-change"+ variant="tertiary"+ size="extra-small"+ onClick={handleDisconnect}+ >+ Change+ </Button>+ </div>+ )}++ {/* GitHub starters (before first generation) */}+ {isGitHub && !hasDashboard && conversation.length === 0 && (+ <div className="gh-starters-welcome">+ <div className="gh-welcome-text">+ <span className="gh-welcome-avatar">+ <img+ src={`https://github.com/${githubUsername}.png?size=32`}+ alt=""+ className="gh-welcome-avatar-image"+ />+ </span>+ Connected as <strong>@{githubUsername}</strong>. What do you want to build?+ </div>+ <div className="gh-starters-grid gh-starters-grid-compact">+ {GITHUB_STARTERS.map((s) => (+ <Button+ key={s.prompt}+ className="gh-starter-card"+ variant="tertiary"+ size="large"+ onClick={() => send(s.prompt)}+ disabled={isStreaming}+ >+ <span className="gh-starter-icon">{s.icon}</span>+ <div className="gh-starter-label">{s.label}</div>+ <div className="gh-starter-desc">+ {s.prompt.length > 60 ? s.prompt.slice(0, 60) + "..." : s.prompt}+ </div>+ </Button>+ ))}+ </div>+ </div>+ )}++ {/* Meta + source toggle */}+ {hasDashboard && !isStreaming && (+ <div className="dashboard-meta">+ {elapsed && (+ <span className="dashboard-elapsed">{(elapsed / 1000).toFixed(1)}s</span>+ )}+ <Button+ className="dashboard-source-toggle"+ variant="tertiary"+ size="extra-small"+ onClick={() => setShowSource(!showSource)}+ >+ <Code2 size={12} />+ {showSource ? "Hide code" : "View code"}+ </Button>+ </div>+ )}++ {/* Source code view */}+ {hasDashboard && showSource && (+ <pre className="dashboard-source">{dashboardCode}</pre>+ )}++ {/* Dashboard renderer */}+ {hasDashboard && (+ <div className="dashboard-renderer">+ <PreviewPanel+ code={dashboardCode!}+ isStreaming={isStreaming}+ onParseResult={(r) => setParsedJson(r ? JSON.stringify(r, null, 2) : null)}+ mode={resolvedMode}+ toolProvider={toolProvider}+ onAction={(event) => {+ if (event.type === "continue_conversation") {+ const text =+ (typeof event.params?.context === "string" ? event.params.context : "") ||+ event.humanFriendlyMessage ||+ "";+ if (text) send(text);+ }+ }}+ />+ </div>+ )}++ {/* Streaming placeholder */}+ {isStreaming && !hasDashboard && (+ <div className="dashboard-loading">+ <div className="dashboard-loading-text">Generating dashboard...</div>+ {elapsed && (+ <div className="dashboard-loading-timer">{(elapsed / 1000).toFixed(1)}s</div>+ )}+ </div>+ )}+ </div>++ {/* Right: Conversation Panel */}+ {showConversation && (+ <ConversationPanel+ messages={conversation}+ streamingText={streamingText}+ isStreaming={isStreaming}+ elapsed={elapsed}+ toolCalls={toolCalls}+ onSend={send}+ onStop={handleStop}+ hasDashboard={hasDashboard}+ responseHasCode={streamResponseHasCode}+ />+ )}+ </div>+ )}+ </div>++ {/* Error banner */}+ {status === "error" && errorMsg && <div className="error-banner">{errorMsg}</div>}+ </div>+ );+}diff --git a/docs/app/docs/chat/page.tsx b/docs/app/docs/chat/page.tsxindex 274a931a7..86243152e 100644--- a/docs/app/docs/chat/page.tsx+++ b/docs/app/docs/chat/page.tsx@@ -1,6 +1,11 @@import { Button } from "@/components/button";-import { HeroBadge } from "@/components/hero-badge";-import { CodeBlock, FeatureCard, FeatureCards } from "@/components/overview-components";+import {+ CodeBlock,+ FeatureCard,+ FeatureCards,+ Separator,+ SimpleCard,+} from "@/components/overview-components";import {Code2,Database,@@ -8,9 +13,9 @@ import {Maximize2,MessageCircle,MessageSquare,- Palette,PanelRightOpen,Zap,+ type LucideIcon,} from "lucide-react";import Link from "next/link";@@ -40,112 +45,147 @@ function CustomChat() {);}`;+const layoutOptions = [+ {+ icon: <PanelRightOpen />,+ title: "Copilot",+ description: "A sidebar assistant that lives alongside your main application content.",+ href: "/docs/chat/copilot",+ },+ {+ icon: <Maximize2 />,+ title: "Full Screen",+ description: "A standalone, immersive chat page similar to ChatGPT or Claude.",+ href: "/docs/chat/fullscreen",+ },+ {+ icon: <MessageCircle />,+ title: "Bottom Tray",+ description: "A floating support-style widget that expands from the bottom corner.",+ href: "/docs/chat/bottom-tray",+ },+] as const;++const capabilities = [+ {+ icon: <MessageSquare />,+ title: "Streaming Native",+ description: "Handles text deltas, optimistic updates, loading states, and partial responses.",+ },+ {+ icon: <Database />,+ title: "Thread Persistence",+ description: "Save and restore conversation history with straightforward API contracts.",+ },+ {+ icon: <Zap />,+ title: "Composable State",+ description: "Use the same primitives across prebuilt layouts and fully custom chat surfaces.",+ },+] as const;++function SectionHeader({+ icon: Icon,+ title,+ description,+}: {+ icon: LucideIcon;+ title: string;+ description: string;+}) {+ return (+ <div className="mb-6 flex items-start gap-3 sm:mb-8 sm:gap-4">+ <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-fd-muted sm:size-12">+ <Icon className="size-5 text-fd-foreground sm:size-6" />+ </div>+ <div>+ <h2 className="mb-1 text-2xl font-bold sm:mb-2 sm:text-3xl">{title}</h2>+ <p className="text-sm text-fd-muted-foreground sm:text-base">{description}</p>+ </div>+ </div>+ );+}+export default function ChatOverviewPage() {return (- <div className="max-w-5xl mx-auto py-10 px-6 space-y-20">- {/* --- Hero Section --- */}- <section className="space-y-6 text-center md:text-left">- <HeroBadge icon="MessageSquare" text="Generative UI Chat" />- <h1 className="text-4xl md:text-5xl font-extrabold tracking-tight text-slate-900 dark:text-white">- OpenUI{" "}- <span className="text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-indigo-600">- Chat SDK- </span>- </h1>- <p className="text-xl text-slate-600 dark:text-slate-400 max-w-2xl leading-relaxed">- A complete framework for building AI interfaces. Use our{" "}- <strong>pre-built layouts</strong> for speed, or our <strong>headless hooks</strong> for- total control.+ <div className="mx-auto max-w-4xl px-3 py-8 font-sans text-slate-900 sm:px-4 sm:py-12 lg:px-8 dark:text-slate-100">+ <section className="mb-12 space-y-6 sm:mb-16">+ <h1 className="docs-page-title max-w-3xl">OpenUI Chat SDK</h1>+ <p className="max-w-2xl text-base leading-7 text-fd-muted-foreground sm:text-lg">+ Production-ready chat UI for AI agents. Start with prebuilt layouts for fast integration,+ then drop down to headless hooks when you need full control over behavior and rendering.</p>-- <div className="flex flex-wrap gap-4 pt-2 justify-center md:justify-start">+ <div className="flex flex-wrap gap-3"><Button href="/docs/chat/installation" text="Installation" variant="primary" /><Button href="/docs/chat/copilot" text="Explore Layouts" variant="secondary" /></div></section>- {/* --- Layouts Showcase --- */}+ <Separator className="my-8 sm:my-12" />+<section>- <div className="flex items-center gap-2 mb-8">- <Layout className="text-fd-foreground" />- <h2 className="text-2xl font-bold">Batteries-Included Layouts</h2>- </div>+ <SectionHeader+ icon={Layout}+ title="Batteries-Included Layouts"+ description="Choose the surface that matches your product and customize from there."+ /><FeatureCards>- <FeatureCard- icon={<PanelRightOpen />}- title="Copilot"- description="A sidebar assistant that lives alongside your main application content."- href="/docs/chat/copilot"- />- <FeatureCard- icon={<Maximize2 />}- title="Full Screen"- description="A standalone, immersive chat page similar to ChatGPT or Claude."- href="/docs/chat/fullscreen"- />- <FeatureCard- icon={<MessageCircle />}- title="Bottom Tray"- description="A floating support-style widget that expands from the bottom corner."- href="/docs/chat/bottom-tray"- />+ {layoutOptions.map((item) => (+ <FeatureCard+ key={item.href}+ icon={item.icon}+ title={item.title}+ description={item.description}+ href={item.href}+ />+ ))}</FeatureCards></section>- {/* --- Headless / Features Split --- */}- <section className="grid lg:grid-cols-2 gap-12 items-start">- {/* Left: Core Features */}+ <Separator className="my-8 sm:my-12" />++ <section className="grid gap-10 lg:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)] lg:items-start"><div className="space-y-8">- <div className="flex items-center gap-2">- <Zap className="text-fd-foreground" />- <h2 className="text-2xl font-bold">Core Capabilities</h2>- </div>+ <SectionHeader+ icon={Zap}+ title="Core Capabilities"+ description="The SDK handles the stateful parts so you can focus on UX, product logic, and polish."+ /><FeatureCards direction="horizontal">- <FeatureCard- direction="horizontal"- icon={<MessageSquare />}- title="Streaming Native"- description="Handles text deltas, optimistic updates, and loading states automatically."- />- <FeatureCard- direction="horizontal"- icon={<Database />}- title="Thread Persistence"- description="Built-in support for saving and loading conversation history via simple API contracts."- />- <FeatureCard- direction="horizontal"- icon={<Palette />}- title="Theming"- description="Customize every color, radius, and font using CSS variables or Tailwind."- />+ {capabilities.map((item) => (+ <FeatureCard+ key={item.title}+ direction="horizontal"+ icon={item.icon}+ title={item.title}+ description={item.description}+ />+ ))}</FeatureCards></div>- {/* Right: Headless Code Snippet */}<div className="space-y-6">- <div className="flex items-center gap-2">- <Code2 className="text-fd-foreground" />- <h2 className="text-2xl font-bold">Go Headless</h2>- </div>-- <p className="text-slate-600 dark:text-slate-400">- Need full control? Use the `useChat` hook to build your own UI while we handle the- state.- </p>-- <CodeBlock code={headlessCode} title="CustomChat.tsx" />+ <SectionHeader+ icon={Code2}+ title="Go Headless"+ description="Use the same chat primitives without the prebuilt layouts when you need a fully custom surface."+ />- <div className="text-right">+ <SimpleCard className="space-y-4 p-4 sm:p-5">+ <p className="text-sm leading-6 text-fd-muted-foreground">+ The `useChat` hook gives you message state, append helpers, and loading semantics+ without locking you into a specific UI.+ </p>+ <CodeBlock code={headlessCode} title="CustomChat.tsx" /><Linkhref="/docs/chat/headless-intro"- className="text-sm font-medium text-blue-600 hover:underline"+ className="inline-flex items-center text-sm font-medium text-fd-foreground transition-colors hover:text-fd-muted-foreground">- Read the Headless Guide →+ Read the Headless Guide</Link>- </div>+ </SimpleCard></div></section></div>diff --git a/docs/app/docs/layout.tsx b/docs/app/docs/layout.tsxindex 3b549bd93..b17771b80 100644--- a/docs/app/docs/layout.tsx+++ b/docs/app/docs/layout.tsx@@ -1,6 +1,11 @@import { DocsRouteLayout } from "@/components/docs-route-layout";+import { WebsiteThemeProvider } from "@/components/website-theme-provider";import { source } from "@/lib/source";export default function Layout({ children }: LayoutProps<"/docs">) {- return <DocsRouteLayout tree={source.getPageTree()}>{children}</DocsRouteLayout>;+ return (+ <WebsiteThemeProvider>+ <DocsRouteLayout tree={source.getPageTree()}>{children}</DocsRouteLayout>+ </WebsiteThemeProvider>+ );}diff --git a/docs/app/global.css b/docs/app/global.cssindex c0a86bb87..347cdca1d 100644--- a/docs/app/global.css+++ b/docs/app/global.css@@ -5,62 +5,149 @@@import "../shared/design-system/styles/variables/index.css";@import "@openuidev/react-ui/styles/index.css";-@media (prefers-color-scheme: light) {- :root {- --color-fd-background: hsl(0, 0%, 100%);- }+body {+ --color-fd-background: var(--openui-background);+ --color-fd-foreground: var(--openui-text-neutral-primary);+ --color-fd-muted: var(--openui-highlight-subtle);+ --color-fd-muted-foreground: var(--openui-text-neutral-secondary);+ --color-fd-popover: var(--openui-popover-background);+ --color-fd-card: var(--openui-foreground);+ --color-fd-secondary: var(--openui-highlight);+ --color-fd-border: var(--openui-border-default);+ --color-fd-accent: var(--openui-highlight);+ --color-fd-accent-foreground: var(--openui-text-neutral-primary);+ --color-fd-ring: var(--openui-border-accent-emphasis);++ --color-doc-surface: var(--openui-foreground);+ --color-doc-surface-raised: var(--openui-popover-background);+ --color-doc-surface-sunken: var(--openui-sunk);+ --color-doc-border: var(--openui-border-default);+ --color-doc-code-bg: var(--openui-sunk-light);+ color: var(--openui-text-neutral-primary);+ background: var(--openui-background);+ font-family: var(--openui-font-body);+}++#nd-docs-layout {+ --color-fd-background: var(--openui-foreground);+ --color-doc-surface: var(--openui-foreground);+ /* 4rem top bar + 0.5rem gap above tabs + ~2.5rem tabs row — keep in sync with `.tabsBar` padding */+ --fd-banner-height: calc(4rem + 0.5rem + 2.5rem) !important;+ --fd-layout-width: 1560px !important;+ width: 100%;+ min-height: calc(100dvh - (4rem + 0.5rem + 2.5rem)) !important;+ padding-top: calc(4rem + 0.5rem + 2.5rem) !important;+ background: var(--openui-foreground);}-.light {- --color-fd-background: hsl(0, 0%, 100%);- --color-doc-surface: #f8f8fa;- --color-doc-surface-raised: #ffffff;- --color-doc-surface-sunken: #f0f0f4;- --color-doc-border: rgba(0, 0, 0, 0.08);- --color-doc-code-bg: #f4f4f8;+/* Override Fumadocs `max-w-[900px]` on `<article id="nd-page">` */+#nd-page {+ max-width: 800px !important;}-.dark {- --color-fd-background: #0b0b0f;- --color-fd-foreground: #e2e1e6;- --color-fd-muted: #141418;- --color-fd-popover: #131317;- --color-fd-card: #111115;- --color-fd-secondary: #141418;-- /* Doc component surface tokens */- --color-doc-surface: #111115;- --color-doc-surface-raised: #16161b;- --color-doc-surface-sunken: #0e0e12;- --color-doc-border: rgba(255, 255, 255, 0.08);- --color-doc-code-bg: #0d0d11;+#nd-page > h1,+#nd-page .docs-page-title,+.docs-page-title {+ font-size: 36px !important;+ line-height: 1.1 !important;+ font-weight: 600 !important;+ letter-spacing: -0.03em;}-#nd-docs-layout {- --fd-banner-height: 104px !important;- min-height: calc(100dvh - 104px) !important;- padding-top: 104px !important;+#nd-page[data-full="true"],+#nd-page[data-full=""] {+ max-width: 1168px !important;}-#nd-docs-layout:not(:has(#nd-sidebar)) {+/*+ * Sidebar width: set on `#nd-docs-layout` so `--fd-sidebar-col` matches.+ *+ * Fumadocs uses `minmax(min-content, 1fr)` for the outer columns. With the sidebar spanning cols 1–2+ * and content aligned with `items-end`, track 1’s min-content can resolve to 0, so the first `1fr`+ * collapses and the last `1fr` takes all free space — the shell looks “stuck left”. Use+ * `minmax(0, 1fr)` for those tracks so left/right gutters stay symmetric and the 1560px shell centers.+ *+ * Must set full `grid-template` (not columns alone) so row/area definitions stay intact.+ */+@media (min-width: 768px) {+ #nd-docs-layout:has([data-sidebar-placeholder]) {+ --fd-sidebar-width: 240px !important;++ grid-template:+ "sidebar sidebar header toc toc"+ "sidebar sidebar toc-popover toc toc"+ "sidebar sidebar main toc toc" 1fr+ /+ minmax(0, 1fr)+ var(--fd-sidebar-col)+ minmax(0, calc(var(--fd-layout-width, 97rem) - var(--fd-sidebar-width) - var(--fd-toc-width)))+ var(--fd-toc-width)+ minmax(0, 1fr) !important;+ }+}++/* Pages with no docs sidebar tree (no placeholder) — keep layout vars consistent */+#nd-docs-layout:not(:has([data-sidebar-placeholder])) {--fd-sidebar-width: 0px !important;--fd-toc-width: 0px !important;}#nd-sidebar {background-color: transparent !important;+ border-right: none !important;+ border-inline-end: none !important;+ border-inline-end-width: 0 !important;}-.docs-nav-sidebar-toggle {- display: none;+#nd-sidebar > .flex.flex-col.gap-3.p-4.pb-2,+#nd-sidebar-mobile > .flex.flex-col.gap-3.p-4.pb-2 {+ padding: 2rem 0 0.5rem 1rem !important;}-@media (max-width: 767px) {- .docs-nav-sidebar-toggle {- display: flex;+/* Sidebar page-tree scroll viewport */+#nd-sidebar [data-radix-scroll-area-viewport].p-4,+#nd-sidebar-mobile [data-radix-scroll-area-viewport].p-4 {+ padding: 1rem 0 1rem 1rem !important;+}++@media (min-width: 1560px) {+ #nd-sidebar > .flex.flex-col.gap-3.p-4.pb-2,+ #nd-sidebar-mobile > .flex.flex-col.gap-3.p-4.pb-2 {+ padding-left: 0 !important;+ }++ #nd-sidebar [data-radix-scroll-area-viewport].p-4,+ #nd-sidebar-mobile [data-radix-scroll-area-viewport].p-4 {+ padding-left: 0 !important;}+}++/* Page tree: primary text on links; tertiary on section titles (folders w/o link row, separators) */+#nd-sidebar [data-radix-scroll-area-viewport] a,+#nd-sidebar-mobile [data-radix-scroll-area-viewport] a {+ color: var(--openui-text-neutral-primary) !important;+}- .docs-nav-tabs {- display: none !important;+#nd-sidebar [data-radix-scroll-area-viewport] a:hover,+#nd-sidebar [data-radix-scroll-area-viewport] a[data-active="true"],+#nd-sidebar-mobile [data-radix-scroll-area-viewport] a:hover,+#nd-sidebar-mobile [data-radix-scroll-area-viewport] a[data-active="true"] {+ color: var(--openui-text-neutral-primary) !important;+}++#nd-sidebar [data-radix-scroll-area-viewport] button.w-full,+#nd-sidebar [data-radix-scroll-area-viewport] div.w-full.rounded-lg.text-start,+#nd-sidebar [data-radix-scroll-area-viewport] p.inline-flex.items-center.gap-2,+#nd-sidebar-mobile [data-radix-scroll-area-viewport] button.w-full,+#nd-sidebar-mobile [data-radix-scroll-area-viewport] div.w-full.rounded-lg.text-start,+#nd-sidebar-mobile [data-radix-scroll-area-viewport] p.inline-flex.items-center.gap-2 {+ color: var(--openui-text-neutral-tertiary) !important;+}++@media (max-width: 767px) {+ #nd-docs-layout {+ --fd-banner-height: 4rem !important;+ min-height: calc(100dvh - 4rem) !important;+ padding-top: 4rem !important;}}diff --git a/docs/app/layout.tsx b/docs/app/layout.tsxindex 4fc85b4f0..bcd8cf474 100644--- a/docs/app/layout.tsx+++ b/docs/app/layout.tsx@@ -87,14 +87,10 @@ export const metadata: Metadata = {export default function Layout({ children }: LayoutProps<"/">) {return (- <html- lang="en"- className={`${inter.className} ${geistMono.variable}`}- suppressHydrationWarning- >+ <html lang="en" className={`${inter.className} ${geistMono.variable}`} suppressHydrationWarning><body className="flex flex-col min-h-screen"><PHProvider>- <RootProvider>{children}</RootProvider>+ <RootProvider theme={{ defaultTheme: "light" }}>{children}</RootProvider></PHProvider></body><Scriptdiff --git a/docs/app/playground/components/CodePanel/CodePanel.css b/docs/app/playground/components/CodePanel/CodePanel.cssindex ebc736fa8..133d946b0 100644--- a/docs/app/playground/components/CodePanel/CodePanel.css+++ b/docs/app/playground/components/CodePanel/CodePanel.css@@ -1,6 +1,6 @@.code-panel .panel-header {- background: #0f0f0f;- border-bottom: 1px solid rgba(255, 255, 255, 0.06);+ background: var(--code-bg);+ border-bottom: 1px solid var(--code-border);}/* ─── Tabs ───────────────────────────────────────────────────────────────────── */@@ -20,7 +20,7 @@font-weight: 600;letter-spacing: 0.03em;text-transform: uppercase;- color: rgba(255, 255, 255, 0.3);+ color: var(--code-text-tertiary);cursor: pointer;transition:background 0.15s,@@ -28,13 +28,13 @@}.code-tab:hover {- color: rgba(255, 255, 255, 0.6);- background: rgba(255, 255, 255, 0.05);+ color: var(--code-text-secondary);+ background: var(--code-hover);}.code-tab.active {- color: rgba(255, 255, 255, 0.85);- background: rgba(255, 255, 255, 0.1);+ color: var(--code-text);+ background: var(--code-hover-strong);}/* ─── Token Count Badge (on tabs) ───────────────────────────────────────────── */@@ -44,8 +44,8 @@margin-left: 5px;padding: 1px 5px;border-radius: 4px;- background: rgba(255, 255, 255, 0.07);- color: rgba(255, 255, 255, 0.35);+ background: var(--code-hover);+ color: var(--code-text-tertiary);font-size: 10px;font-weight: 500;letter-spacing: 0;@@ -55,24 +55,24 @@}.code-tab.active .token-count {- background: rgba(255, 255, 255, 0.12);- color: rgba(255, 255, 255, 0.55);+ background: var(--code-hover-strong);+ color: var(--code-text-secondary);}/* ─── Tooltip ────────────────────────────────────────────────────────────────── */-[data-tooltip] {+.code-panel [data-tooltip] {position: relative;}-[data-tooltip]::after {+.code-panel [data-tooltip]::after {content: attr(data-tooltip);position: absolute;top: calc(100% + 6px);left: 50%;transform: translateX(-50%);- background: #1e1e1e;- border: 1px solid rgba(255, 255, 255, 0.12);- color: rgba(255, 255, 255, 0.75);+ background: color-mix(in srgb, var(--code-bg) 88%, var(--openui-foreground));+ border: 1px solid var(--code-border);+ color: var(--code-text-secondary);font-size: 11px;font-weight: 400;font-family: var(--font-sans);@@ -84,11 +84,11 @@pointer-events: none;opacity: 0;transition: opacity 0.15s;- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);+ box-shadow: var(--openui-shadow-l);z-index: 100;}-[data-tooltip]:hover::after {+.code-panel [data-tooltip]:hover::after {opacity: 1;}@@ -99,9 +99,9 @@gap: 4px;padding: 2px 7px;border-radius: 20px;- background: rgba(74, 222, 128, 0.12);- border: 1px solid rgba(74, 222, 128, 0.25);- color: #4ade80;+ background: var(--playground-success-tint);+ border: 1px solid var(--playground-success-border);+ color: var(--playground-success-text);font-size: 10px;font-weight: 600;letter-spacing: 0.02em;@@ -110,20 +110,20 @@}.code-panel .panel-title {- color: rgba(255, 255, 255, 0.4);+ color: var(--code-text-secondary);}.code-panel .panel-icon-btn {- color: rgba(255, 255, 255, 0.3);+ color: var(--code-text-tertiary);}.code-panel .panel-icon-btn:hover {- background: rgba(255, 255, 255, 0.07);- color: rgba(255, 255, 255, 0.8);+ background: var(--code-hover);+ color: var(--code-text);}.code-panel .empty-state {- color: rgba(255, 255, 255, 0.2);+ color: var(--code-text-tertiary);}.code-body {@@ -154,12 +154,12 @@}.status-dot.streaming {- background: #4ade80;+ background: var(--openui-border-success-emphasis);animation: pulse 1s ease-in-out infinite;}.status-dot.error {- background: #f87171;+ background: var(--openui-border-danger-emphasis);}@keyframes pulse {diff --git a/docs/app/playground/components/Header/Header.css b/docs/app/playground/components/Header/Header.cssdeleted file mode 100644index 19a4cd9a0..000000000--- a/docs/app/playground/components/Header/Header.css+++ /dev/null@@ -1,75 +0,0 @@-.header {- position: sticky;- top: 0;- z-index: 50;- background-color: var(--header-bg);- border-bottom: 1px solid var(--header-border);- backdrop-filter: blur(12px);-}--.header-inner {- display: grid;- grid-template-columns: 1fr auto 1fr;- align-items: center;- gap: 16px;- padding: 0 16px 0 24px;- margin: 0 auto;- height: 56px;-}--.header-title {- font-size: 13px;- font-weight: 500;- color: rgba(0, 0, 0, 0.4);- letter-spacing: 0.02em;- text-transform: uppercase;- justify-self: center;- white-space: nowrap;-}--.header-left {- display: flex;- align-items: center;- gap: 10px;-}--.header-right {- display: flex;- align-items: center;- gap: 4px;- justify-self: end;- padding-right: 24px;-}--.header-btn {- display: flex;- align-items: center;- gap: 6px;- padding: 6px 10px;- background: transparent;- border: none;- border-radius: 6px;- color: rgba(0, 0, 0, 0.55);- font-family: var(--font-sans);- font-size: 13px;- cursor: pointer;- text-decoration: none;- transition:- background 0.15s,- color 0.15s;- white-space: nowrap;-}--.header-btn:hover {- background: rgba(0, 0, 0, 0.06);- color: #0a0a0a;-}--.header-btn svg {- flex-shrink: 0;-}--.header-icon-btn {- padding: 6px;- border-radius: 6px;-}diff --git a/docs/app/playground/components/Header/Header.tsx b/docs/app/playground/components/Header/Header.tsxindex d0515f425..7143d381e 100644--- a/docs/app/playground/components/Header/Header.tsx+++ b/docs/app/playground/components/Header/Header.tsx@@ -1,14 +1,5 @@-import { OpenUILogo, ThesysLogo } from "@/components/brand-logo";-import { BookOpen, Github, KeyRound, Monitor, Moon, Sun } from "lucide-react";-import { useState } from "react";+import { SiteMarketingHeader } from "@/components/site-marketing-header";import { Theme } from "../../constants";-import "./Header.css";--function ThemeIcon({ theme }: { theme: Theme }) {- if (theme === "light") return <Sun size={15} />;- if (theme === "dark") return <Moon size={15} />;- return <Monitor size={15} />;-}type HeaderProps = {theme: Theme;@@ -18,56 +9,19 @@ type HeaderProps = {};export function Header({ theme, onThemeToggle, hasApiKey, onChangeKey }: HeaderProps) {+ void hasApiKey;+ void onChangeKey;+const themeLabel = { system: "System", light: "Light", dark: "Dark" }[theme];- const [isLogoHovered, setIsLogoHovered] = useState(false);return (- <header className="header">- <div className="header-inner">- <div className="header-left">- <ThesysLogo isHovered={isLogoHovered} onHoverChange={setIsLogoHovered} />- <div className="h-4 w-px bg-black/10" />- <OpenUILogo />- </div>-- <span className="header-title">Playground</span>-- <div className="header-right">- <a- className="header-btn"- href="https://github.com/thesysdev/openui"- target="_blank"- rel="noreferrer"- >- <Github size={14} />- GitHub- </a>- <a className="header-btn" href="/docs" target="_blank" rel="noreferrer">- <BookOpen size={14} />- Docs- </a>-- <button- className="header-btn header-icon-btn"- onClick={onThemeToggle}- title={`Theme: ${themeLabel}`}- aria-label={`Switch theme (current: ${themeLabel})`}- >- <ThemeIcon theme={theme} />- </button>-- {hasApiKey && (- <button- className="header-btn header-icon-btn"- onClick={onChangeKey}- title="Change API Key"- aria-label="Change API Key"- >- <KeyRound size={15} />- </button>- )}- </div>- </div>- </header>+ <SiteMarketingHeader+ borderMode="always"+ themeToggle={{+ onToggle: onThemeToggle,+ title: `Theme: ${themeLabel}`,+ ariaLabel: `Switch theme (current: ${themeLabel})`,+ }}+ />);}diff --git a/docs/app/playground/components/PreviewPanel/PreviewPanel.css b/docs/app/playground/components/PreviewPanel/PreviewPanel.cssindex 10099a124..d5214fbee 100644--- a/docs/app/playground/components/PreviewPanel/PreviewPanel.css+++ b/docs/app/playground/components/PreviewPanel/PreviewPanel.css@@ -12,7 +12,7 @@.preview-spinner {animation: preview-spin 1s linear infinite;- color: #6366f1;+ color: var(--openui-interactive-accent-default);flex-shrink: 0;}diff --git a/docs/app/playground/layout.css b/docs/app/playground/layout.cssindex 237e15dfe..f4e298d8b 100644--- a/docs/app/playground/layout.css+++ b/docs/app/playground/layout.css@@ -1,163 +1,89 @@-/* ─── Reset & Base ─────────────────────────────────────────────────────────── */-*,-*::before,-*::after {+/* Scope playground resets so they do not leak into other routes after navigation.+ Use `:where()` to keep specificity at zero and avoid overriding shared docs styles. */+:where(.app, .app *, .app *::before, .app *::after) {box-sizing: border-box;margin: 0;padding: 0;}-/* ─── Theme Tokens ─────────────────────────────────────────────────────────── */-:root {- --header-bg: #ffffff;- --header-text: #0a0a0a;- --header-border: rgba(0, 0, 0, 0.08);-- --page-bg: #ffffff;- --surface: #f5f5f5;- --surface-hover: #ebebeb;- --border: rgba(0, 0, 0, 0.1);- --border-strong: rgba(0, 0, 0, 0.2);-- --text-primary: #0a0a0a;- --text-secondary: rgba(0, 0, 0, 0.5);- --text-tertiary: rgba(0, 0, 0, 0.35);-- --btn-primary-bg: #0a0a0a;- --btn-primary-text: #ffffff;- --btn-primary-hover: #1a1a1a;-- --btn-ghost-hover: rgba(0, 0, 0, 0.06);-- --input-bg: #ffffff;- --input-border: rgba(0, 0, 0, 0.15);- --input-focus-ring: rgba(0, 0, 0, 0.9);-- --chip-bg: rgba(0, 0, 0, 0.05);- --chip-hover: rgba(0, 0, 0, 0.1);- --chip-border: rgba(0, 0, 0, 0.1);-- --code-bg: #0d0d0d;- --code-text: #e5e5e5;-- --panel-header-bg: #f0f0f0;- --panel-header-border: rgba(0, 0, 0, 0.08);-- --modal-backdrop: rgba(0, 0, 0, 0.5);- --modal-bg: #ffffff;- --modal-border: rgba(0, 0, 0, 0.12);- --modal-shadow: 0 24px 64px rgba(0, 0, 0, 0.15);-- --scrollbar-thumb: rgba(0, 0, 0, 0.2);-- --font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;- --font-mono: "SF Mono", "Fira Code", "Cascadia Code", Consolas, monospace;-}--@media (prefers-color-scheme: dark) {- :root:not([data-theme="light"]) {- --page-bg: #0a0a0a;- --surface: #111111;- --surface-hover: #1a1a1a;- --border: rgba(255, 255, 255, 0.08);- --border-strong: rgba(255, 255, 255, 0.15);-- --text-primary: #ffffff;- --text-secondary: rgba(255, 255, 255, 0.5);- --text-tertiary: rgba(255, 255, 255, 0.3);-- --btn-primary-bg: #ffffff;- --btn-primary-text: #0a0a0a;- --btn-primary-hover: #e5e5e5;-- --btn-ghost-hover: rgba(255, 255, 255, 0.07);-- --input-bg: #111111;- --input-border: rgba(255, 255, 255, 0.12);- --input-focus-ring: rgba(255, 255, 255, 0.9);-- --chip-bg: rgba(255, 255, 255, 0.05);- --chip-hover: rgba(255, 255, 255, 0.09);- --chip-border: rgba(255, 255, 255, 0.1);-- --panel-header-bg: #0f0f0f;- --panel-header-border: rgba(255, 255, 255, 0.06);-- --modal-backdrop: rgba(0, 0, 0, 0.7);- --modal-bg: #111111;- --modal-border: rgba(255, 255, 255, 0.1);- --modal-shadow: 0 24px 64px rgba(0, 0, 0, 0.5);-- --scrollbar-thumb: rgba(255, 255, 255, 0.15);- }-}--:root[data-theme="dark"] {- --page-bg: #0a0a0a;- --surface: #111111;- --surface-hover: #1a1a1a;- --border: rgba(255, 255, 255, 0.08);- --border-strong: rgba(255, 255, 255, 0.15);-- --text-primary: #ffffff;- --text-secondary: rgba(255, 255, 255, 0.5);- --text-tertiary: rgba(255, 255, 255, 0.3);-- --btn-primary-bg: #ffffff;- --btn-primary-text: #0a0a0a;- --btn-primary-hover: #e5e5e5;-- --btn-ghost-hover: rgba(255, 255, 255, 0.07);-- --input-bg: #111111;- --input-border: rgba(255, 255, 255, 0.12);- --input-focus-ring: rgba(255, 255, 255, 0.9);-- --chip-bg: rgba(255, 255, 255, 0.05);- --chip-hover: rgba(255, 255, 255, 0.09);- --chip-border: rgba(255, 255, 255, 0.1);-- --panel-header-bg: #0f0f0f;- --panel-header-border: rgba(255, 255, 255, 0.06);-- --modal-backdrop: rgba(0, 0, 0, 0.7);- --modal-bg: #111111;- --modal-border: rgba(255, 255, 255, 0.1);- --modal-shadow: 0 24px 64px rgba(0, 0, 0, 0.5);-- --scrollbar-thumb: rgba(255, 255, 255, 0.15);-}--/* ─── Global ────────────────────────────────────────────────────────────────── */-body {- font-family: var(--font-sans);- background-color: var(--page-bg);- color: var(--text-primary);- -webkit-font-smoothing: antialiased;- -moz-osx-font-smoothing: grayscale;- transition:- background-color 0.2s ease,- color 0.2s ease;-}-/* ─── Scrollbar ─────────────────────────────────────────────────────────────── */-::-webkit-scrollbar {+.app::-webkit-scrollbar,+.app ::-webkit-scrollbar {width: 6px;height: 6px;}-::-webkit-scrollbar-track {+.app::-webkit-scrollbar-track,+.app ::-webkit-scrollbar-track {background: transparent;}-::-webkit-scrollbar-thumb {+.app::-webkit-scrollbar-thumb,+.app ::-webkit-scrollbar-thumb {background: var(--scrollbar-thumb);border-radius: 3px;}/* ─── App Layout ────────────────────────────────────────────────────────────── */.app {+ --page-bg: var(--openui-foreground);+ --surface: var(--openui-foreground);+ --surface-hover: var(--openui-highlight);+ --border: var(--openui-border-default);+ --border-strong: var(--openui-border-interactive);+ --text-primary: var(--openui-text-neutral-primary);+ --text-secondary: var(--openui-text-neutral-secondary);+ --text-tertiary: var(--openui-text-neutral-tertiary);+ --btn-primary-bg: var(--openui-interactive-accent-default);+ --btn-primary-text: var(--openui-text-accent-primary);+ --btn-primary-hover: var(--openui-interactive-accent-hover);+ --btn-ghost-hover: var(--openui-highlight);+ --input-bg: var(--openui-foreground);+ --input-border: var(--openui-border-interactive);+ --input-focus-ring: var(--openui-border-accent-emphasis);+ --chip-bg: var(--openui-highlight-subtle);+ --chip-hover: var(--openui-highlight);+ --chip-border: var(--openui-border-default);+ --code-bg: var(--openui-inverted-background);+ --code-text: var(--openui-text-accent-primary);+ --code-text-secondary: var(--openui-text-accent-secondary);+ --code-text-tertiary: var(--openui-text-accent-tertiary);+ --code-hover: color-mix(in srgb, var(--openui-text-accent-primary) 8%, transparent);+ --code-hover-strong: color-mix(in srgb, var(--openui-text-accent-primary) 14%, transparent);+ --code-border: color-mix(in srgb, var(--openui-text-accent-primary) 12%, transparent);+ --panel-header-bg: var(--openui-highlight-subtle);+ --panel-header-border: var(--openui-border-default);+ --modal-backdrop: var(--openui-overlay);+ --modal-bg: var(--openui-foreground);+ --modal-border: var(--openui-border-default);+ --modal-shadow: var(--openui-shadow-xl);+ --scrollbar-thumb: var(--openui-text-neutral-tertiary);+ --font-sans: var(--openui-font-body);+ --font-mono: var(--openui-font-code);+ --playground-focus-ring: color-mix(in srgb, var(--openui-border-accent-emphasis) 24%, transparent);+ --playground-success-tint: color-mix(in srgb, var(--openui-success-background) 16%, transparent);+ --playground-success-border: color-mix(+ in srgb,+ var(--openui-border-success-emphasis) 36%,+ transparent+ );+ --playground-success-text: var(--openui-text-success-primary);+ --playground-danger-tint: color-mix(in srgb, var(--openui-danger-background) 14%, transparent);+ --playground-danger-border: color-mix(+ in srgb,+ var(--openui-border-danger-emphasis) 36%,+ transparent+ );+ --playground-danger-text: var(--openui-text-danger-primary);display: flex;flex-direction: column;height: 100vh;+ font-family: var(--font-sans);+ background-color: var(--page-bg);+ color: var(--text-primary);+ -webkit-font-smoothing: antialiased;+ -moz-osx-font-smoothing: grayscale;+ transition:+ background-color 0.2s ease,+ color 0.2s ease;}.app-body {@@ -291,22 +217,12 @@ body {display: flex;flex-direction: column;transition: border-color 0.15s;- box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);+ box-shadow: var(--openui-shadow-m);}.prompt-container:focus-within {border-color: var(--input-focus-ring);- box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.08);-}--:root[data-theme="dark"] .prompt-container:focus-within {- box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.08);-}--@media (prefers-color-scheme: dark) {- :root:not([data-theme="light"]) .prompt-container:focus-within {- box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.08);- }+ box-shadow: 0 0 0 3px var(--playground-focus-ring);}.prompt-textarea {@@ -363,7 +279,7 @@ body {}.model-select:focus {- border-color: var(--border-strong);+ border-color: var(--openui-border-interactive-emphasis);}.model-select:disabled {@@ -422,7 +338,7 @@ body {.stop-btn:hover {background: var(--btn-ghost-hover);color: var(--text-primary);- border-color: var(--text-primary);+ border-color: var(--openui-border-interactive-emphasis);}/* ─── Chips ─────────────────────────────────────────────────────────────────── */@@ -455,7 +371,7 @@ body {.chip:hover {background: var(--chip-hover);color: var(--text-primary);- border-color: var(--border-strong);+ border-color: var(--openui-border-interactive);transform: translateY(-1px);}@@ -469,11 +385,11 @@ body {.error-banner {margin: 0 0 16px;padding: 12px 16px;- background: rgba(248, 113, 113, 0.1);- border: 1px solid rgba(248, 113, 113, 0.2);+ background: var(--playground-danger-tint);+ border: 1px solid var(--playground-danger-border);border-radius: 8px;font-size: 13px;- color: #f87171;+ color: var(--playground-danger-text);line-height: 1.5;}diff --git a/docs/app/playground/layout.tsx b/docs/app/playground/layout.tsxindex 28bbf38e2..dc4dfe4b9 100644--- a/docs/app/playground/layout.tsx+++ b/docs/app/playground/layout.tsx@@ -1,6 +1,7 @@+import { WebsiteThemeProvider } from "@/components/website-theme-provider";import type { ReactNode } from "react";import "./layout.css";export default function PlaygroundLayout({ children }: { children: ReactNode }) {- return <>{children}</>;+ return <WebsiteThemeProvider>{children}</WebsiteThemeProvider>;}diff --git a/docs/app/playground/page.tsx b/docs/app/playground/page.tsxindex 73825d071..5d65ea64c 100644--- a/docs/app/playground/page.tsx+++ b/docs/app/playground/page.tsx@@ -1,14 +1,15 @@"use client";import { Send, Square } from "lucide-react";-import { useCallback, useEffect, useRef, useState } from "react";+import { useTheme } from "next-themes";+import { useCallback, useRef, useState } from "react";import { CodePanel } from "./components/CodePanel/CodePanel";import { Header } from "./components/Header/Header";import { PreviewPanel } from "./components/PreviewPanel/PreviewPanel";import { MODELS, STARTER_PROMPTS, type Model, type Status, type Theme } from "./constants";export default function PlaygroundPage() {- const [theme, setTheme] = useState<Theme>("system");+ const { theme, setTheme } = useTheme();const [prompt, setPrompt] = useState("");const [model, setModel] = useState<Model>("anthropic/claude-sonnet-4.6");const [code, setCode] = useState("");@@ -19,17 +20,11 @@ export default function PlaygroundPage() {const textareaRef = useRef<HTMLTextAreaElement>(null);const abortRef = useRef<AbortController | null>(null);- useEffect(() => {- const el = document.documentElement;- if (theme === "system") {- el.removeAttribute("data-theme");- } else {- el.setAttribute("data-theme", theme);- }- }, [theme]);+ const currentTheme: Theme =+ theme === "light" || theme === "dark" || theme === "system" ? theme : "system";const cycleTheme = () => {- setTheme((t) => (t === "system" ? "light" : t === "light" ? "dark" : "system"));+ setTheme(currentTheme === "system" ? "light" : currentTheme === "light" ? "dark" : "system");};const handlePromptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {@@ -124,7 +119,12 @@ export default function PlaygroundPage() {return (<div className="app">- <Header theme={theme} onThemeToggle={cycleTheme} hasApiKey={false} onChangeKey={() => {}} />+ <Header+ theme={currentTheme}+ onThemeToggle={cycleTheme}+ hasApiKey={false}+ onChangeKey={() => {}}+ /><div className="app-body"><div className="content-wrapper">@@ -192,7 +192,7 @@ export default function PlaygroundPage() {code={code}isStreaming={status === "streaming"}onParseResult={(r) => setParsedJson(r ? JSON.stringify(r, null, 2) : null)}- theme={theme}+ theme={currentTheme}/></div></div>diff --git a/docs/components/brand-logo.module.css b/docs/components/brand-logo.module.cssnew file mode 100644index 000000000..b61f0fad8--- /dev/null+++ b/docs/components/brand-logo.module.css@@ -0,0 +1,96 @@+.githubButton {+ position: relative;+ display: inline-flex;+ flex: none;+ align-items: center;+ gap: 0.375rem;+ min-inline-size: max-content;+ height: 2.5rem;+ padding-left: 0.625rem;+ padding-right: 0.375rem;+ border-radius: 999px;+ background: #fff;+ color: var(--openui-text-black);+ text-decoration: none;+ white-space: nowrap;+ transition: transform 0.2s ease;+}++.githubButton:hover {+ transform: scale(0.995);+}++.githubButtonOverlay {+ position: absolute;+ inset: 0;+ pointer-events: none;+ border: 1px solid rgb(0 0 0 / 6%);+ border-radius: 999px;+ box-shadow:+ 0 1px 3px 0 rgb(22 34 51 / 8%),+ 0 12px 24px 0 rgb(22 34 51 / 4%);+}++.githubButtonOverlayFlat {+ box-shadow: none;+}++.githubIcon {+ position: relative;+ flex: 0 0 auto;+ width: 1.25rem;+ height: 1.25rem;+ overflow: clip;+}++.githubIconInner {+ position: absolute;+ inset: 1.67% 1.67% 4.05% 1.67%;+}++.starBadge {+ display: inline-flex;+ flex: 0 0 auto;+ align-items: center;+ justify-content: center;+ min-inline-size: 3.5rem;+ height: 1.75rem;+ padding-inline: 0.5rem;+ border-radius: 999px;+ background: rgb(0 0 0 / 6%);+ transition: background-color 0.2s ease;+}++.starBadgeHighlighted {+ background: #000;+}++.starCount {+ color: #000;+ font-family: inherit;+ font-size: 0.9375rem;+ font-weight: 500;+ line-height: 1.5rem;+ font-variant-numeric: tabular-nums;+ transition:+ color 0.2s ease,+ opacity 0.2s ease;+}++.starCountHighlighted {+ color: #fff;+}++.starCountValue {+ display: inline-block;+ min-inline-size: 4ch;+ text-align: center;+}++.starCountHidden {+ opacity: 0;+}++.starCountVisible {+ opacity: 1;+}diff --git a/docs/components/brand-logo.tsx b/docs/components/brand-logo.tsxindex ab148f66f..86f7526f5 100644--- a/docs/components/brand-logo.tsx+++ b/docs/components/brand-logo.tsx@@ -6,9 +6,9 @@ import svgPaths from "@/imports/svg-urruvoh2be";import { AnimatePresence, motion } from "motion/react";import Link from "next/link";import { useEffect, useState } from "react";+import styles from "./brand-logo.module.css";const COUNT_UP_DURATION = 1500;-const BUTTON_SHADOW = "0px 1px 3px 0px rgba(22,34,51,0.08), 0px 12px 24px 0px rgba(22,34,51,0.04)";const LOGO_SPRING = { type: "spring", stiffness: 400, damping: 15 } as const;const LOGO_COLOR_TRANSITION = { duration: 0.25 } as const;@@ -16,6 +16,10 @@ const GLOW_TRANSITION = { duration: 0.2 } as const;export type LogoVariant = "light" | "dark";+function cx(...classNames: Array<string | false | null | undefined>) {+ return classNames.filter(Boolean).join(" ");+}+export function ThesysLogo({isHovered,onHoverChange,@@ -210,15 +214,15 @@ export function useGitHubStarCount(repo: string) {export function GitHubIcon() {return (- <div className="overflow-clip relative shrink-0 size-5">- <div className="absolute inset-[1.67%_1.67%_4.05%_1.67%]">+ <div className={styles.githubIcon}>+ <div className={styles.githubIconInner}><svgclassName="absolute block size-full"fill="none"preserveAspectRatio="none"viewBox="0 0 19.3333 18.8561">- <path d={svgPaths.p294daf00} fill="black" stroke="black" />+ <path d={svgPaths.p294daf00} fill="currentColor" stroke="currentColor" /></svg></div></div>@@ -233,16 +237,19 @@ export function StarCountBadge({isHighlighted: boolean;}) {return (- <div- className="rounded-full h-7 min-w-14 flex items-center justify-center px-2 transition-colors duration-200"- style={{ backgroundColor: isHighlighted ? "black" : "rgba(0,0,0,0.06)" }}- >+ <div className={cx(styles.starBadge, isHighlighted && styles.starBadgeHighlighted)}><span- className="font-['Inter',sans-serif] font-medium text-[15px] leading-6 tabular-nums transition-[color,opacity] duration-200"- style={{ color: isHighlighted ? "white" : "black" }}+ className={cx(styles.starCount, isHighlighted && styles.starCountHighlighted)}aria-hidden={count === null}>- <span className={count === null ? "opacity-0" : "opacity-100"}>{count ?? "0000"}</span>+ <span+ className={cx(+ styles.starCountValue,+ count === null ? styles.starCountHidden : styles.starCountVisible,+ )}+ >+ {count ?? "0000"}+ </span></span></div>);@@ -267,14 +274,16 @@ export function GitHubStarButton({href={`https://github.com/${repo}`}target="_blank"rel="noopener noreferrer"- className="bg-white flex items-center gap-1.5 h-10 pl-2.5 pr-1.5 rounded-full relative cursor-pointer transition-all duration-200 hover:scale-[0.995] no-underline"+ className={styles.githubButton}onMouseEnter={() => setIsHovered(true)}onMouseLeave={() => setIsHovered(false)}><divaria-hidden="true"- className="absolute inset-0 pointer-events-none rounded-full border border-black/6"- style={{ boxShadow: isScrolled || isHovered ? "none" : BUTTON_SHADOW }}+ className={cx(+ styles.githubButtonOverlay,+ (isScrolled || isHovered) && styles.githubButtonOverlayFlat,+ )}/><GitHubIcon /><StarCountBadge count={starCount} isHighlighted={isHovered} />diff --git a/docs/components/button.tsx b/docs/components/button.tsxindex d614acb82..2fc0f330d 100644--- a/docs/components/button.tsx+++ b/docs/components/button.tsx@@ -9,17 +9,14 @@ interface ButtonProps {}export function Button({ href, text, size = "lg", variant = "primary" }: ButtonProps) {- const sizeClasses = size === "lg" ? "px-6 py-3 text-base font-medium" : "";-+ const sizeClasses = size === "lg" ? "openui-button-base-large" : "";const variantClasses =- variant === "primary"- ? "text-white bg-slate-900 rounded-lg hover:bg-slate-800 transition-colors dark:bg-white dark:text-slate-900 dark:hover:bg-slate-100"- : "text-slate-700 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 transition-colors dark:bg-[var(--color-doc-surface)] dark:text-slate-300 dark:border-[var(--color-doc-border)] dark:hover:bg-[var(--color-doc-surface-raised)]";+ variant === "primary" ? "openui-button-base-primary" : "openui-button-base-secondary";return (<Linkhref={href}- className={`inline-flex items-center no-underline ${sizeClasses} ${variantClasses}`}+ className={`openui-button-base no-underline ${sizeClasses} ${variantClasses}`}>{text}{variant === "primary" && <ArrowRight className="ml-2 h-4 w-4" />}diff --git a/docs/components/docs-navbar.module.css b/docs/components/docs-navbar.module.cssnew file mode 100644index 000000000..9c1872ab7--- /dev/null+++ b/docs/components/docs-navbar.module.css@@ -0,0 +1,220 @@+.header {+ position: fixed;+ inset-inline: 0;+ top: 0;+ z-index: 40;+ width: 100%;+}++.topBar {+ width: 100%;+}++.tabsBar {+ width: 100%;+ padding-top: 0.5rem;+ background-color: color-mix(in srgb, var(--color-fd-background) 80%, transparent);+ backdrop-filter: blur(24px);+}++.tabsInner {+ width: 100%;+ max-width: calc(1560px + 2rem);+ min-height: 2.5rem;+ margin-inline: auto;+ padding-inline: 1rem;+ box-sizing: border-box;+}++.sidebarToggle {+ display: none;+ align-items: center;+ justify-content: center;+ width: 2.25rem;+ height: 2.25rem;+ margin-right: 0.75rem;+ border: none;+ border-radius: 0.5rem;+ background: transparent;+ color: var(--openui-text-neutral-secondary);+ cursor: pointer;+ transition:+ color 0.15s ease,+ background-color 0.15s ease;+}++.sidebarToggle:hover {+ color: var(--openui-text-neutral-primary);+ background: var(--openui-highlight);+}++.actions {+ display: none;+ align-items: center;+ gap: 0.75rem;+}++.searchCenter {+ display: none;+ align-items: center;+ justify-content: center;+}++.actionButtons {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}++.searchButton {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ width: 16rem;+ height: 2.25rem;+ padding-left: 0.875rem;+ padding-right: 0.625rem;+ border: 1px solid var(--openui-border-default);+ border-radius: 0.5rem;+ background: var(--color-fd-background);+ color: var(--openui-text-neutral-secondary);+ cursor: pointer;+ transition:+ border-color 0.15s ease,+ color 0.15s ease,+ background-color 0.15s ease;+}++.searchButton:hover {+ border-color: var(--openui-border-accent-emphasis);+}++.searchButton:focus-visible,+.iconLink:focus-visible,+.sidebarToggle:focus-visible {+ outline: 2px solid var(--openui-border-accent-emphasis);+ outline-offset: 2px;+}++.searchIcon {+ flex-shrink: 0;+}++.searchLabel {+ flex: 1;+ font-size: 0.875rem;+ text-align: left;+}++.searchShortcut {+ display: none;+ align-items: center;+ gap: 0.125rem;+ padding: 0.125rem 0.375rem;+ border: 1px solid var(--openui-border-default);+ border-radius: 0.25rem;+ color: var(--openui-text-neutral-secondary);+ font-size: 11px;+ font-weight: 500;+ line-height: 1;+}++.iconLink {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 2.25rem;+ height: 2.25rem;+ border-radius: 0.5rem;+ color: var(--openui-text-neutral-secondary);+ text-decoration: none;+ transition:+ color 0.15s ease,+ background-color 0.15s ease;+}++.iconLink:hover {+ color: var(--openui-text-neutral-primary);+ background: var(--openui-highlight);+}++.tabsNav {+ width: 100%;+ min-height: 2.5rem;+ display: flex;+ align-items: stretch;+ gap: 1.125rem;+ border-bottom: 1px solid var(--openui-border-default);+ overflow-x: auto;+ scrollbar-width: none;+}++.tabsNav::-webkit-scrollbar {+ display: none;+}++.tabLink {+ position: relative;+ display: inline-flex;+ align-items: center;+ flex-shrink: 0;+ min-height: 2.5rem;+ padding: 0.5rem 0;+ color: var(--openui-text-neutral-secondary);+ text-decoration: none;+ white-space: nowrap;+ font-size: 1rem;+ font-weight: 400;+ line-height: 1.5rem;+}++.tabLink:hover {+ color: var(--openui-text-neutral-primary);+}++.tabLink::after {+ content: "";+ position: absolute;+ right: 0;+ bottom: -1px;+ left: 0;+ height: 1.5px;+ background: transparent;+}++.tabLinkActive {+ color: var(--openui-text-neutral-primary);+ font-weight: 600;+}++.tabLinkActive::after {+ background: var(--openui-border-interactive-selected);+}++.tabLink:focus-visible {+ outline: 2px solid var(--openui-border-accent-emphasis);+ outline-offset: 2px;+}++@media (min-width: 640px) {+ .searchShortcut {+ display: inline-flex;+ }+}++@media (min-width: 768px) {+ .searchCenter,+ .actions {+ display: flex;+ }+}++@media (max-width: 767px) {+ .sidebarToggle {+ display: flex;+ }++ .tabsBar {+ display: none;+ }+}diff --git a/docs/components/docs-navbar.tsx b/docs/components/docs-navbar.tsxindex b8f9dd332..0e5e862cf 100644--- a/docs/components/docs-navbar.tsx+++ b/docs/components/docs-navbar.tsx@@ -6,19 +6,28 @@ import { useSearchContext } from "fumadocs-ui/contexts/search";import { useTheme } from "next-themes";import Link from "next/link";import { usePathname } from "next/navigation";-import { useEffect, useState } from "react";-import { GitHubStarButton, OpenUILogo, ThesysLogo } from "./brand-logo";+import { useEffect, useMemo, useState } from "react";+import { GitHubStarButton } from "./brand-logo";+import styles from "./docs-navbar.module.css";+import { SiteHeaderFrame } from "./site-header";import { ThemeToggle } from "./theme-toggle";const tabs = [{ title: "OpenUI", url: "/docs/openui-lang" },{ title: "Chat", url: "/docs/chat" },{ title: "API Reference", url: "/docs/api-reference" },-];+] as const;++function activeTabUrl(pathname: string): string {+ const sorted = [...tabs].sort((a, b) => b.url.length - a.url.length);+ return (+ sorted.find((t) => pathname === t.url || pathname.startsWith(`${t.url}/`))?.url ?? tabs[0].url+ );+}function SearchBar() {const { setOpenSearch } = useSearchContext();- const [isMac, setIsMac] = useState(+ const [isMac] = useState(() => typeof navigator !== "undefined" && /mac/i.test(navigator.userAgent),);@@ -38,7 +47,7 @@ function SearchBar() {type="button"onClick={() => setOpenSearch(true)}aria-label="Search documentation"- className="flex items-center gap-2.5 h-9 pl-3.5 pr-2.5 rounded-lg border border-fd-border bg-fd-background text-fd-muted-foreground cursor-pointer w-64 hover:border-fd-ring transition-colors"+ className={styles.searchButton}><svgwidth="14"@@ -49,13 +58,13 @@ function SearchBar() {strokeWidth="2"strokeLinecap="round"strokeLinejoin="round"- className="shrink-0"+ className={styles.searchIcon}><circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" /></svg>- <span className="text-sm flex-1 text-left">Search...</span>- <kbd className="hidden sm:flex items-center gap-0.5 text-[11px] font-medium text-fd-muted-foreground border border-fd-border rounded px-1.5 py-0.5 leading-none">+ <span className={styles.searchLabel}>Search...</span>+ <kbd className={styles.searchShortcut}>{isMac ? "⌘" : "Ctrl"}<span>K</span></kbd>@@ -65,91 +74,84 @@ function SearchBar() {export function DocsNavbar({ showSidebarToggle = false }: { showSidebarToggle?: boolean }) {const pathname = usePathname();- const [isThesysHovered, setIsThesysHovered] = useState(false);const { resolvedTheme } = useTheme();- const [mounted, setMounted] = useState(false);- useEffect(() => {- setMounted(true);- }, []);- const logoVariant = mounted && resolvedTheme === "dark" ? "dark" : "light";+ const logoVariant = resolvedTheme === "dark" ? "dark" : "light";- return (- <header className="fixed top-0 inset-x-0 z-40 w-full border-b border-fd-border bg-fd-background/80 backdrop-blur-xl">- {/* Top row: logo left, actions right */}- <div className="flex items-center h-16 max-w-388 mx-auto px-3 md:px-8">- {showSidebarToggle && (- <SidebarTrigger className="docs-nav-sidebar-toggle flex items-center justify-center size-9 rounded-lg text-fd-muted-foreground bg-transparent border-none cursor-pointer mr-3">- <svg- width="20"- height="20"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- >- <line x1="3" y1="6" x2="21" y2="6" />- <line x1="3" y1="12" x2="21" y2="12" />- <line x1="3" y1="18" x2="21" y2="18" />- </svg>- </SidebarTrigger>- )}+ const tabValue = useMemo(() => activeTabUrl(pathname), [pathname]);- {/* Brand */}- <div className="flex items-center gap-2.5 shrink-0">- <ThesysLogo- isHovered={isThesysHovered}- onHoverChange={setIsThesysHovered}- variant={logoVariant}- />- <span className="text-fd-muted-foreground text-[15px] select-none px-0.5">|</span>- <OpenUILogo variant={logoVariant} />- </div>-- {/* Actions */}- <div className="hidden md:flex items-center gap-3 ml-auto shrink-0">- <SearchBar />- <div className="flex items-center gap-2">- {/* Discord */}- <Link- href={siteConfig.discordUrl}- target="_blank"- rel="noopener noreferrer"- className="flex items-center justify-center size-9 rounded-lg text-fd-muted-foreground no-underline hover:text-fd-foreground hover:bg-fd-accent transition-colors"- aria-label="Discord"- >- <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">- <path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028 14.09 14.09 0 0 0 1.226-1.994.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z" />- </svg>- </Link>- {/* Theme toggle */}- <ThemeToggle />- <GitHubStarButton repo="thesysdev/openui" />- </div>- </div>+ return (+ <header className={styles.header}>+ <div className={styles.topBar}>+ <SiteHeaderFrame+ variant="docs"+ borderColor="var(--openui-border-default)"+ dividerColor="var(--openui-border-default)"+ brandVariant={logoVariant}+ center={+ <div className={styles.searchCenter}>+ <SearchBar />+ </div>+ }+ leading={+ showSidebarToggle ? (+ <SidebarTrigger className={styles.sidebarToggle}>+ <svg+ width="20"+ height="20"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <line x1="3" y1="6" x2="21" y2="6" />+ <line x1="3" y1="12" x2="21" y2="12" />+ <line x1="3" y1="18" x2="21" y2="18" />+ </svg>+ </SidebarTrigger>+ ) : null+ }+ end={+ <div className={styles.actions}>+ <div className={styles.actionButtons}>+ <Link+ href={siteConfig.discordUrl}+ target="_blank"+ rel="noopener noreferrer"+ className={styles.iconLink}+ aria-label="Discord"+ >+ <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">+ <path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028 14.09 14.09 0 0 0 1.226-1.994.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z" />+ </svg>+ </Link>+ <ThemeToggle />+ <GitHubStarButton repo="thesysdev/openui" />+ </div>+ </div>+ }+ /></div>+ <div className={styles.tabsBar}>+ <div className={styles.tabsInner}>+ <nav className={styles.tabsNav} aria-label="Documentation sections">+ {tabs.map((tab) => {+ const isActive = tab.url === tabValue;- {/* Bottom row: tabs */}- <div className="max-w-388 mx-auto px-8">- <nav className="docs-nav-tabs flex items-center overflow-x-auto">- {tabs.map((tab) => {- const isActive = pathname.startsWith(tab.url);- return (- <Link- key={tab.url}- href={tab.url}- className={`flex items-center px-4 py-2.5 text-sm font-medium whitespace-nowrap no-underline transition-colors duration-150 border-b-2 -mb-px ${- isActive- ? "text-fd-foreground border-fd-primary"- : "text-fd-muted-foreground border-transparent hover:text-fd-foreground"- }`}- >- {tab.title}- </Link>- );- })}- </nav>+ return (+ <Link+ key={tab.url}+ href={tab.url}+ className={`${styles.tabLink} ${isActive ? styles.tabLinkActive : ""}`.trim()}+ aria-current={isActive ? "page" : undefined}+ >+ {tab.title}+ </Link>+ );+ })}+ </nav>+ </div></div></header>);diff --git a/docs/components/docs-route-layout.tsx b/docs/components/docs-route-layout.tsxindex e2269a913..008d6912a 100644--- a/docs/components/docs-route-layout.tsx+++ b/docs/components/docs-route-layout.tsx@@ -50,12 +50,7 @@ export function DocsRouteLayout({ tree, children }: DocsRouteLayoutProps) {collapsible: false,banner: (<div className="flex flex-col mb-2">- <SidebarBannerLink- href="/playground"- label="Playground"- external- icon={<Play />}- />+ <SidebarBannerLink href="/playground" label="Playground" external icon={<Play />} /><SidebarBannerLinkhref={siteConfig.discordUrl}label="Discord"@@ -66,11 +61,7 @@ export function DocsRouteLayout({ tree, children }: DocsRouteLayoutProps) {</svg>}/>- <SidebarBannerLink- href="/docs/mcp"- label="Docs MCP"- icon={<Plug />}- />+ <SidebarBannerLink href="/docs/mcp" label="Docs MCP" icon={<Plug />} /></div>),}}diff --git a/docs/components/hero-badge.tsx b/docs/components/hero-badge.tsxindex e02f0263a..48716d3af 100644--- a/docs/components/hero-badge.tsx+++ b/docs/components/hero-badge.tsx@@ -12,7 +12,7 @@ export function HeroBadge({ icon, text }: HeroBadgeProps) {)[icon];return (- <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 text-sm font-medium">+ <div className="inline-flex items-center gap-2 rounded-full bg-fd-muted px-3 py-1 text-sm font-medium text-fd-foreground">{IconComponent && <IconComponent size={14} />}<span>{text}</span></div>diff --git a/docs/components/site-header.module.css b/docs/components/site-header.module.cssnew file mode 100644index 000000000..afab120b0--- /dev/null+++ b/docs/components/site-header.module.css@@ -0,0 +1,105 @@+.surface {+ --site-header-max-width: 1560px;+ --site-header-padding-inline: 1rem;+ --site-header-row-min-height: 4rem;+ --site-header-bottom-min-height: 2.5rem;+ width: 100%;+ transition:+ border-color 0.2s ease,+ background-color 0.2s ease,+ box-shadow 0.2s ease,+ backdrop-filter 0.2s ease;+}++.homeSurface {+ background: var(--openui-foreground);+}++.docsSurface {+ background-color: color-mix(in srgb, var(--color-fd-background) 80%, transparent);+ backdrop-filter: blur(24px);+}++.bordered {+ border-bottom: 1px solid var(--site-header-border-color);+}++.frame {+ padding-inline: var(--site-header-padding-inline);+}++.row {+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);+ align-items: center;+ column-gap: 1rem;+ min-height: var(--site-header-row-min-height);+ max-width: var(--site-header-max-width);+ margin-inline: auto;+}++.start {+ display: flex;+ align-items: center;+ justify-self: start;+ min-width: 0;+ grid-column: 1;+}++.leading {+ display: flex;+ align-items: center;+ flex-shrink: 0;+}++.brand {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ flex-shrink: 0;+}++.brandDivider {+ width: 1px;+ height: 1rem;+ background: var(--site-header-divider-color);+}++.center {+ display: flex;+ align-items: center;+ justify-content: center;+ min-width: 0;+ grid-column: 2;+}++.right {+ display: flex;+ align-items: center;+ justify-self: end;+ min-width: 0;+ grid-column: 3;+}++.end {+ display: flex;+ align-items: center;+ flex-shrink: 0;+}++.mobileEnd {+ display: flex;+ align-items: center;+ flex-shrink: 0;+}++.bottom {+ overflow: hidden;+ padding-inline: var(--site-header-padding-inline);+}++.bottomInner {+ max-width: var(--site-header-max-width);+ min-height: var(--site-header-bottom-min-height);+ margin-inline: auto;+}diff --git a/docs/components/site-header.tsx b/docs/components/site-header.tsxnew file mode 100644index 000000000..ecd1fb2ac--- /dev/null+++ b/docs/components/site-header.tsx@@ -0,0 +1,82 @@+"use client";++import { useState, type CSSProperties, type ReactNode } from "react";+import { OpenUILogo, ThesysLogo, type LogoVariant } from "./brand-logo";+import styles from "./site-header.module.css";++function joinClasses(...classNames: Array<string | false | null | undefined>) {+ return classNames.filter(Boolean).join(" ");+}++export function SiteHeaderBrand({ variant = "light" }: { variant?: LogoVariant }) {+ const [isHovered, setIsHovered] = useState(false);++ return (+ <div className={styles.brand}>+ <ThesysLogo isHovered={isHovered} onHoverChange={setIsHovered} variant={variant} />+ <span aria-hidden="true" className={styles.brandDivider} />+ <OpenUILogo variant={variant} />+ </div>+ );+}++type SiteHeaderFrameProps = {+ variant: "home" | "docs";+ bordered?: boolean;+ borderColor: string;+ dividerColor: string;+ brandVariant?: LogoVariant;+ leading?: ReactNode;+ center?: ReactNode;+ end?: ReactNode;+ mobileEnd?: ReactNode;+ bottom?: ReactNode;+};++export function SiteHeaderFrame({+ variant,+ bordered = false,+ borderColor,+ dividerColor,+ brandVariant = "light",+ leading,+ center,+ end,+ mobileEnd,+ bottom,+}: SiteHeaderFrameProps) {+ return (+ <div+ className={joinClasses(+ styles.surface,+ variant === "home" ? styles.homeSurface : styles.docsSurface,+ bordered && styles.bordered,+ )}+ style={+ {+ "--site-header-border-color": borderColor,+ "--site-header-divider-color": dividerColor,+ } as CSSProperties+ }+ >+ <div className={styles.frame}>+ <div className={styles.row}>+ <div className={styles.start}>+ {leading ? <div className={styles.leading}>{leading}</div> : null}+ <SiteHeaderBrand variant={brandVariant} />+ </div>+ {center ? <div className={styles.center}>{center}</div> : null}+ <div className={styles.right}>+ {end ? <div className={styles.end}>{end}</div> : null}+ {mobileEnd ? <div className={styles.mobileEnd}>{mobileEnd}</div> : null}+ </div>+ </div>+ </div>+ {bottom ? (+ <div className={styles.bottom}>+ <div className={styles.bottomInner}>{bottom}</div>+ </div>+ ) : null}+ </div>+ );+}diff --git a/docs/components/site-marketing-header.module.css b/docs/components/site-marketing-header.module.cssnew file mode 100644index 000000000..67caff41f--- /dev/null+++ b/docs/components/site-marketing-header.module.css@@ -0,0 +1,145 @@+.nav {+ position: sticky;+ top: 0;+ z-index: 50;+ width: 100%;+}++.desktopActions {+ display: none;+ align-items: center;+ gap: 0.5rem;+}++.hamburgerIcon {+ width: 1.25rem;+ height: 1.25rem;+}++.mobileMenuButton {+ display: flex;+ width: 2.5rem;+ height: 2.5rem;+ align-items: center;+ justify-content: center;+ border: 0;+ border-radius: 0.5rem;+ background: transparent;+ color: var(--openui-text-neutral-primary);+ cursor: pointer;+ transition: background-color 0.2s ease;+}++.mobileMenuButton:hover,+.mobileTrayLink:hover {+ background: var(--openui-highlight);+}++.mobileBackdrop {+ position: absolute;+ top: 100%;+ left: 0;+ right: 0;+ z-index: 40;+ height: 100vh;+ cursor: pointer;+ background: rgb(0 0 0 / 60%);+ backdrop-filter: blur(12px);+}++.mobileTrayWrap {+ position: absolute;+ top: 100%;+ left: 0;+ right: 0;+ z-index: 50;+ pointer-events: none;+}++.mobileTray {+ pointer-events: auto;+ border-top: 1px solid var(--openui-border-default);+ border-bottom-left-radius: 18px;+ border-bottom-right-radius: 18px;+ background: var(--openui-foreground);+ box-shadow: var(--openui-shadow-xl);+}++.mobileTrayInner {+ display: flex;+ max-width: 75rem;+ margin-inline: auto;+ flex-direction: column;+ gap: 0;+ padding: 0.75rem 1.75rem 1.25rem;+}++.mobileTrayDivider {+ height: 1px;+ margin-inline: 0.75rem;+ background: var(--openui-border-default);+}++.mobileTrayLink {+ display: flex;+ width: 100%;+ height: 3.5rem;+ align-items: center;+ gap: 0.25rem;+ padding-inline: 0.75rem;+ border-radius: 0.375rem;+ color: var(--openui-text-neutral-primary);+ text-align: left;+ text-decoration: none;+ transition: background-color 0.2s ease;+ font: var(--openui-text-body-lg);+ letter-spacing: var(--openui-text-body-lg-letter-spacing);+}++.mobileGithubButtonWrap {+ display: flex;+ justify-content: center;+ padding-top: 80px;+ pointer-events: auto;+}++.mobileGithubButton {+ position: relative;+ display: flex;+ height: 38px;+ align-items: center;+ gap: 0.375rem;+ padding-left: 0.75rem;+ padding-right: 0.5rem;+ border: 0;+ border-radius: 999px;+ background: var(--openui-foreground);+ cursor: pointer;+ transform: scale(1.17);+}++.mobileGithubButton:hover .mobileGithubButtonOverlay {+ box-shadow: none;+}++.mobileGithubButtonOverlay {+ position: absolute;+ inset: 0;+ pointer-events: none;+ border: 1px solid var(--openui-border-interactive);+ border-radius: 999px;+ box-shadow: var(--mobile-github-button-shadow, none);+ transition: box-shadow 0.2s ease;+}++@media (min-width: 1024px) {+ .desktopActions {+ display: flex;+ }++ .mobileMenuButton,+ .mobileBackdrop,+ .mobileTrayWrap {+ display: none;+ }+}diff --git a/docs/components/site-marketing-header.tsx b/docs/components/site-marketing-header.tsxnew file mode 100644index 000000000..665ad2a51--- /dev/null+++ b/docs/components/site-marketing-header.tsx@@ -0,0 +1,186 @@+"use client";++import {+ GitHubIcon,+ GitHubStarButton,+ type LogoVariant,+ StarCountBadge,+ useGitHubStarCount,+} from "@/components/brand-logo";+import { SiteHeaderFrame } from "@/components/site-header";+import { PRIMARY_SITE_NAV_ITEMS, SitePrimaryNav } from "@/components/site-primary-nav";+import { ThemeToggle } from "@/components/theme-toggle";+import { AnimatePresence, motion } from "motion/react";+import { useTheme } from "next-themes";+import Link from "next/link";+import { useCallback, useEffect, useState, type CSSProperties, type ReactNode } from "react";+import styles from "./site-marketing-header.module.css";++const BUTTON_SHADOW = "0px 1px 3px 0px rgba(22,34,51,0.08), 0px 12px 24px 0px rgba(22,34,51,0.04)";++type ThemeToggleConfig = {+ onToggle?: () => void;+ title?: string;+ ariaLabel?: string;+};++type SiteMarketingHeaderProps = {+ borderMode?: "always" | "scroll";+ extraActions?: ReactNode;+ themeToggle?: ThemeToggleConfig | null;+ brandVariant?: LogoVariant;+};++function HamburgerIcon({ isOpen }: { isOpen: boolean }) {+ return (+ <svg+ className={styles.hamburgerIcon}+ fill="none"+ viewBox="0 0 24 24"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ {isOpen ? (+ <>+ <path d="M18 6L6 18" />+ <path d="M6 6l12 12" />+ </>+ ) : (+ <>+ <path d="M3 12h18" />+ <path d="M3 6h18" />+ <path d="M3 18h18" />+ </>+ )}+ </svg>+ );+}++function MobileMenu({ starCount, onClose }: { starCount: number | null; onClose: () => void }) {+ const mobileGithubStyle = {+ "--mobile-github-button-shadow": BUTTON_SHADOW,+ } as CSSProperties;++ return (+ <>+ <motion.div+ className={styles.mobileBackdrop}+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ transition={{ duration: 0.2 }}+ onClick={onClose}+ />+ <motion.div+ className={styles.mobileTrayWrap}+ initial={{ opacity: 0, y: -8 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: -8 }}+ transition={{ duration: 0.2 }}+ >+ <div className={styles.mobileTray}>+ <div className={styles.mobileTrayInner}>+ {PRIMARY_SITE_NAV_ITEMS.map((item, index) => (+ <div key={item.href}>+ {index > 0 && <div className={styles.mobileTrayDivider} />}+ <Link href={item.href} className={styles.mobileTrayLink}>+ {item.title}+ </Link>+ </div>+ ))}+ </div>+ </div>+ <div className={styles.mobileGithubButtonWrap}>+ <a+ href="https://github.com/thesysdev/openui"+ target="_blank"+ rel="noopener noreferrer"+ className={styles.mobileGithubButton}+ >+ <div+ aria-hidden="true"+ className={styles.mobileGithubButtonOverlay}+ style={mobileGithubStyle}+ />+ <GitHubIcon />+ <StarCountBadge count={starCount} isHighlighted={false} />+ </a>+ </div>+ </motion.div>+ </>+ );+}++export function SiteMarketingHeader({+ borderMode = "scroll",+ extraActions,+ themeToggle,+ brandVariant,+}: SiteMarketingHeaderProps) {+ const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);+ const [isScrolled, setIsScrolled] = useState(borderMode === "always");+ const starCount = useGitHubStarCount("thesysdev/openui");+ const { resolvedTheme } = useTheme();+ const resolvedBrandVariant = brandVariant ?? (resolvedTheme === "dark" ? "dark" : "light");++ useEffect(() => {+ if (borderMode === "always") {+ setIsScrolled(true);+ return;+ }++ const handleScroll = () => {+ setIsScrolled(window.scrollY > 0);+ };++ window.addEventListener("scroll", handleScroll, { passive: true });+ handleScroll();+ return () => window.removeEventListener("scroll", handleScroll);+ }, [borderMode]);++ const toggleMobileMenu = useCallback(() => {+ setIsMobileMenuOpen((prev) => !prev);+ }, []);++ const isBordered = borderMode === "always" || isScrolled;++ return (+ <nav className={styles.nav}>+ <SiteHeaderFrame+ variant="home"+ bordered={isBordered}+ borderColor="var(--openui-border-interactive)"+ dividerColor="var(--openui-border-interactive)"+ brandVariant={resolvedBrandVariant}+ center={<SitePrimaryNav />}+ end={+ <div className={styles.desktopActions}>+ {themeToggle !== null && (+ <ThemeToggle+ onToggle={themeToggle?.onToggle}+ title={themeToggle?.title}+ ariaLabel={themeToggle?.ariaLabel}+ />+ )}+ {extraActions}+ <GitHubStarButton repo="thesysdev/openui" isScrolled={isBordered} />+ </div>+ }+ mobileEnd={+ <button+ className={styles.mobileMenuButton}+ onClick={toggleMobileMenu}+ aria-label="Toggle menu"+ >+ <HamburgerIcon isOpen={isMobileMenuOpen} />+ </button>+ }+ />+ <AnimatePresence>+ {isMobileMenuOpen && <MobileMenu starCount={starCount} onClose={toggleMobileMenu} />}+ </AnimatePresence>+ </nav>+ );+}diff --git a/docs/components/site-primary-nav.module.css b/docs/components/site-primary-nav.module.cssnew file mode 100644index 000000000..fe7e02ad8--- /dev/null+++ b/docs/components/site-primary-nav.module.css@@ -0,0 +1,36 @@+.nav {+ display: none;+ align-items: center;+ gap: 0.5rem;+}++.link {+ display: flex;+ align-items: center;+ height: 2rem;+ padding-inline: 0.5rem;+ border-radius: 0.375rem;+ color: var(--openui-text-neutral-primary);+ text-decoration: none;+ white-space: nowrap;+ font-family: "Inter Display", sans-serif;+ font-size: 15px;+ line-height: 1.5rem;+ transition:+ background-color 0.2s ease,+ color 0.2s ease;+}++.link:hover {+ background: var(--openui-highlight-strong);+}++.linkActive {+ background: var(--openui-highlight-strong);+}++@media (min-width: 1024px) {+ .nav {+ display: flex;+ }+}diff --git a/docs/components/site-primary-nav.tsx b/docs/components/site-primary-nav.tsxnew file mode 100644index 000000000..0d95a6ebc--- /dev/null+++ b/docs/components/site-primary-nav.tsx@@ -0,0 +1,35 @@+"use client";++import Link from "next/link";+import { usePathname } from "next/navigation";+import styles from "./site-primary-nav.module.css";++export const PRIMARY_SITE_NAV_ITEMS = [+ { title: "Docs", href: "/docs", newTab: false },+ { title: "Playground", href: "/playground", newTab: false },+ { title: "Demo", href: "/demo/github", newTab: true },+ { title: "Blogs", href: "/blog", newTab: false },+] as const;++export function SitePrimaryNav() {+ const pathname = usePathname();++ return (+ <nav className={styles.nav}>+ {PRIMARY_SITE_NAV_ITEMS.map((item) => {+ const isActive = pathname.startsWith(item.href);++ return (+ <Link+ key={item.href}+ href={item.href}+ className={`${styles.link} ${isActive ? styles.linkActive : ""}`.trim()}+ {...(item.newTab ? { target: "_blank", rel: "noopener noreferrer" } : {})}+ >+ {item.title}+ </Link>+ );+ })}+ </nav>+ );+}diff --git a/docs/components/theme-toggle.module.css b/docs/components/theme-toggle.module.cssnew file mode 100644index 000000000..2e051ae4d--- /dev/null+++ b/docs/components/theme-toggle.module.css@@ -0,0 +1,32 @@+.button {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 2.25rem;+ height: 2.25rem;+ padding: 0;+ border: 0;+ border-radius: 999px;+ background: transparent;+ color: var(--openui-text-neutral-primary);+ cursor: pointer;+ transition:+ background-color 0.15s ease,+ color 0.15s ease;+}++.button:hover {+ background: var(--openui-highlight-strong);+ color: var(--openui-text-neutral-primary);+}++.button:focus-visible {+ outline: 2px solid var(--openui-border-accent-emphasis);+ outline-offset: 2px;+}++.icon {+ width: 1.25rem;+ height: 1.25rem;+ flex-shrink: 0;+}diff --git a/docs/components/theme-toggle.tsx b/docs/components/theme-toggle.tsxindex c60581c90..ddbf4a359 100644--- a/docs/components/theme-toggle.tsx+++ b/docs/components/theme-toggle.tsx@@ -1,45 +1,50 @@"use client";import { cn } from "@/lib/cn";-import { Moon, Sun } from "lucide-react";import { useTheme } from "next-themes";-import { useEffect, useState } from "react";+import styles from "./theme-toggle.module.css";-export function ThemeToggle({ className }: { className?: string }) {- const { setTheme, resolvedTheme } = useTheme();- const [mounted, setMounted] = useState(false);+type ThemeToggleProps = {+ className?: string;+ onToggle?: () => void;+ title?: string;+ ariaLabel?: string;+};- useEffect(() => {- setMounted(true);- }, []);+function ThemeToggleIcon() {+ return (+ <svg+ className={styles.icon}+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ aria-hidden="true"+ >+ <path+ d="M12 2.25C10.0716 2.25 8.18657 2.82183 6.58319 3.89317C4.97982 4.96452 3.73013 6.48726 2.99218 8.26884C2.25422 10.0504 2.06114 12.0108 2.43735 13.9021C2.81355 15.7934 3.74215 17.5307 5.10571 18.8943C6.46928 20.2579 8.20656 21.1865 10.0979 21.5627C11.9892 21.9389 13.9496 21.7458 15.7312 21.0078C17.5127 20.2699 19.0355 19.0202 20.1068 17.4168C21.1782 15.8134 21.75 13.9284 21.75 12C21.7473 9.41498 20.7192 6.93661 18.8913 5.10872C17.0634 3.28084 14.585 2.25273 12 2.25ZM3.75 12C3.75249 9.81273 4.62248 7.71575 6.16911 6.16911C7.71575 4.62247 9.81273 3.75248 12 3.75V20.25C9.81273 20.2475 7.71575 19.3775 6.16911 17.8309C4.62248 16.2843 3.75249 14.1873 3.75 12Z"+ fill="currentColor"+ />+ </svg>+ );+}- const value = mounted ? resolvedTheme : null;+export function ThemeToggle({ className, onToggle, title, ariaLabel }: ThemeToggleProps) {+ const { setTheme, resolvedTheme } = useTheme();+ const nextTheme = resolvedTheme === "dark" ? "light" : "dark";+ const defaultLabel = `Switch to ${nextTheme} mode`;return (<button- className={cn(- "inline-flex items-center rounded-full border p-0.5 *:rounded-full cursor-pointer",- className,- )}- aria-label="Toggle Theme"- onClick={() => setTheme(value === "light" ? "dark" : "light")}+ type="button"+ className={cn(styles.button, className)}+ aria-label={ariaLabel ?? defaultLabel}+ title={title ?? ariaLabel ?? defaultLabel}+ onClick={onToggle ?? (() => setTheme(nextTheme))}data-theme-toggle="">- {(["light", "dark"] as const).map((key) => {- const Icon = key === "light" ? Sun : Moon;- return (- <Icon- key={key}- fill="currentColor"- className={cn(- "size-5 p-1",- value === key- ? "bg-fd-accent text-fd-accent-foreground rounded-full"- : "text-fd-muted-foreground",- )}- />- );- })}+ <ThemeToggleIcon /></button>);}diff --git a/docs/components/website-theme-provider.tsx b/docs/components/website-theme-provider.tsxnew file mode 100644index 000000000..7c82a09ff--- /dev/null+++ b/docs/components/website-theme-provider.tsx@@ -0,0 +1,70 @@+"use client";++import { ThemeProvider } from "@openuidev/react-ui/ThemeProvider";+import { useTheme } from "next-themes";+import { useEffect, type ReactNode } from "react";++const FONT_FAMILY = 'var(--font-inter), "Inter", "Segoe UI", Arial, sans-serif';+const FONT_CODE = 'var(--font-geist-mono), "SFMono-Regular", Menlo, monospace';++const fontOverrides = {+ fontBody: FONT_FAMILY,+ fontCode: FONT_CODE,+ fontHeading: FONT_FAMILY,+ fontLabel: FONT_FAMILY,+ fontNumbers: FONT_FAMILY,+};++type WebsiteThemeProviderProps = {+ children: ReactNode;+ forcedTheme?: "light" | "dark";+};++function WebsiteThemeBridge({+ children,+ forcedTheme,+}: {+ children: ReactNode;+ forcedTheme?: "light" | "dark";+}) {+ const { resolvedTheme } = useTheme();+ const mode = forcedTheme ?? (resolvedTheme === "dark" ? "dark" : "light");++ useEffect(() => {+ const root = document.documentElement;+ const body = document.body;+ const previousRootTheme = root.getAttribute("data-theme");+ const previousBodyTheme = body.getAttribute("data-theme");+ const previousColorScheme = root.style.colorScheme;++ root.setAttribute("data-theme", mode);+ body.setAttribute("data-theme", mode);+ root.style.colorScheme = mode;++ return () => {+ if (previousRootTheme === null) {+ root.removeAttribute("data-theme");+ } else {+ root.setAttribute("data-theme", previousRootTheme);+ }++ if (previousBodyTheme === null) {+ body.removeAttribute("data-theme");+ } else {+ body.setAttribute("data-theme", previousBodyTheme);+ }++ root.style.colorScheme = previousColorScheme;+ };+ }, [mode]);++ return (+ <ThemeProvider mode={mode} lightTheme={fontOverrides}>+ {children}+ </ThemeProvider>+ );+}++export function WebsiteThemeProvider({ children, forcedTheme }: WebsiteThemeProviderProps) {+ return <WebsiteThemeBridge forcedTheme={forcedTheme}>{children}</WebsiteThemeBridge>;+}diff --git a/docs/content/blog/rust-wasm-parser.mdx b/docs/content/blog/rust-wasm-parser.mdxindex 357b57370..cdc73d339 100644--- a/docs/content/blog/rust-wasm-parser.mdx+++ b/docs/content/blog/rust-wasm-parser.mdx@@ -62,11 +62,11 @@ Compare that to the JSON approach: `serde_json::to_string()` runs in pure Rust w### Benchmark: JSON string vs direct JsValue (1000 runs, µs per call)-| Fixture | JSON round-trip | serde-wasm-bindgen | Change |-|---|---|---|---|-| simple-table | 20.5 | 22.5 | -9% slower |-| contact-form | 61.4 | 79.4 | -29% slower |-| dashboard | 57.9 | 74.0 | -28% slower |+| Fixture | JSON round-trip | serde-wasm-bindgen | Change |+| ------------ | --------------- | ------------------ | ----------- |+| simple-table | 20.5 | 22.5 | -9% slower |+| contact-form | 61.4 | 79.4 | -29% slower |+| dashboard | 57.9 | 74.0 | -28% slower |We reverted this change immediately.@@ -81,17 +81,18 @@ We ported the full parser pipeline to TypeScript. Same six-stage architecture, s**How it was run:** 30 warm-up iterations to stabilise JIT, then 1000 timed iterations using `performance.now()` (µs precision). The median is reported. Fixtures are real LLM-generated component trees serialised in each format's real streaming syntax.**Fixtures:**+- `simple-table` — root + one Table with 3 columns and 5 rows (~180 chars)- `contact-form` — root + form layout with 6 input fields + submit button (~400 chars)- `dashboard` — root + sidebar nav + 3 metric cards + chart + data table (~950 chars)### Results: One-Shot Parse (median µs, 1000 runs)-| Fixture | TypeScript | WASM | Speedup |-|---|---|---|---|-| simple-table | 9.3 | 20.5 | **2.2x** |-| contact-form | 13.4 | 61.4 | **4.6x** |-| dashboard | 19.4 | 57.9 | **3.0x** |+| Fixture | TypeScript | WASM | Speedup |+| ------------ | ---------- | ---- | -------- |+| simple-table | 9.3 | 20.5 | **2.2x** |+| contact-form | 13.4 | 61.4 | **4.6x** |+| dashboard | 19.4 | 57.9 | **3.0x** |## The Algorithmic Problem: O(N²) Streaming@@ -131,11 +132,11 @@ Completed statements are never re-parsed. Only the trailing in-progress statemen### Results: Full-Stream Total Parse Cost (median µs across all chunks)-| Fixture | Naïve TS (re-parse every chunk) | Incremental TS (cache completed) | Speedup |-|---|---|---|---|-| simple-table | 69 | 77 | none (single statement, no cache benefit) |-| contact-form | 316 | 122 | **2.6x** |-| dashboard | 840 | 255 | **3.3x** |+| Fixture | Naïve TS (re-parse every chunk) | Incremental TS (cache completed) | Speedup |+| ------------ | ------------------------------- | -------------------------------- | ----------------------------------------- |+| simple-table | 69 | 77 | none (single statement, no cache benefit) |+| contact-form | 316 | 122 | **2.6x** |+| dashboard | 840 | 255 | **3.3x** |The `simple-table` fixture is a single statement — there's nothing to cache, so both approaches are equivalent. The benefit scales with the number of statements because more of the document gets cached and skipped on each chunk.@@ -148,12 +149,12 @@ The one-shot table shows 13.4µs for `contact-form`; the streaming table shows 3## Summary-| Approach | Per-call cost | Full-stream total | Notes |-|---|---|---|---|-| WASM + JSON round-trip | 20-61µs | baseline | Copy overhead each call |-| WASM + serde-wasm-bindgen | 22-79µs | +9-29% slower | Hundreds of internal boundary crossings |-| TypeScript (naïve re-parse) | 9-19µs | 69-840µs | No boundary, but O(N²) streaming |-| TypeScript (incremental) | 9-19µs | 69-255µs | No boundary + O(N) streaming |+| Approach | Per-call cost | Full-stream total | Notes |+| --------------------------- | ------------- | ----------------- | --------------------------------------- |+| WASM + JSON round-trip | 20-61µs | baseline | Copy overhead each call |+| WASM + serde-wasm-bindgen | 22-79µs | +9-29% slower | Hundreds of internal boundary crossings |+| TypeScript (naïve re-parse) | 9-19µs | 69-840µs | No boundary, but O(N²) streaming |+| TypeScript (incremental) | 9-19µs | 69-255µs | No boundary + O(N) streaming |**End result: 2.2-4.6x faster per call and 2.6-3.3x lower total streaming cost.**@@ -172,15 +173,15 @@ This experience sharpened our thinking on the right use cases for WASM:## Key Takeaways1. **Profile where time is actually spent before choosing the implementation language.**- For us, the cost was never in the computation - it was always in data transfer across the WASM-JS boundary.+ For us, the cost was never in the computation - it was always in data transfer across the WASM-JS boundary.2. **"Direct object passing" through `serde-wasm-bindgen` is not cheaper.**- Constructing a JS object field-by-field from Rust involves more boundary crossings than a single JSON string transfer, not fewer.- The boundary crossings happen inside the single FFI call, invisibly.+ Constructing a JS object field-by-field from Rust involves more boundary crossings than a single JSON string transfer, not fewer.+ The boundary crossings happen inside the single FFI call, invisibly.3. **Algorithmic complexity improvements dominate language-level optimisations.**- Going from O(N²) to O(N) in the streaming case had a larger practical impact than switching from WASM to TypeScript.+ Going from O(N²) to O(N) in the streaming case had a larger practical impact than switching from WASM to TypeScript.4. **WASM and JS do not share a heap.**- WASM has a flat linear memory (`WebAssembly.Memory`) that JS can read as raw bytes, but those bytes are Rust's internal layout - pointers, enum discriminants, alignment padding - completely opaque to the JS runtime.- Conversion is always required and always costs something.+ WASM has a flat linear memory (`WebAssembly.Memory`) that JS can read as raw bytes, but those bytes are Rust's internal layout - pointers, enum discriminants, alignment padding - completely opaque to the JS runtime.+ Conversion is always required and always costs something.diff --git a/docs/content/docs/api-reference/cli.mdx b/docs/content/docs/api-reference/cli.mdxindex 3d1d250a1..82199ba5f 100644--- a/docs/content/docs/api-reference/cli.mdx+++ b/docs/content/docs/api-reference/cli.mdx@@ -28,12 +28,12 @@ openui create [options]**Options**-| Flag | Description |-|---|---|-| `-n, --name <string>` | Project name (directory to create) |-| `--skill` | Install the OpenUI agent skill for AI coding assistants |-| `--no-skill` | Skip installing the OpenUI agent skill |-| `--no-interactive` | Fail instead of prompting for missing input |+| Flag | Description |+| --------------------- | ------------------------------------------------------- |+| `-n, --name <string>` | Project name (directory to create) |+| `--skill` | Install the OpenUI agent skill for AI coding assistants |+| `--no-skill` | Skip installing the OpenUI agent skill |+| `--no-interactive` | Fail instead of prompting for missing input |When run interactively (default), the CLI prompts for any missing options. Pass `--no-interactive` in CI or scripted environments to surface missing required flags as errors instead.@@ -78,19 +78,19 @@ openui generate [entry] [options]**Arguments**-| Argument | Description |-|---|---|+| Argument | Description |+| --------- | ----------------------------------------------------------------------- || `[entry]` | Path to a `.ts`, `.tsx`, `.js`, or `.jsx` file that exports a `Library` |**Options**-| Flag | Description |-|---|---|-| `-o, --out <file>` | Write output to a file instead of stdout |-| `--json-schema` | Output JSON schema instead of a system prompt |-| `--export <name>` | Name of the export to use (auto-detected by default) |+| Flag | Description |+| ------------------------- | -------------------------------------------------------------------- |+| `-o, --out <file>` | Write output to a file instead of stdout |+| `--json-schema` | Output JSON schema instead of a system prompt |+| `--export <name>` | Name of the export to use (auto-detected by default) || `--prompt-options <name>` | Name of the `PromptOptions` export to use (auto-detected by default) |-| `--no-interactive` | Fail instead of prompting for missing `entry` |+| `--no-interactive` | Fail instead of prompting for missing `entry` |**Examples**diff --git a/docs/content/docs/api-reference/index.mdx b/docs/content/docs/api-reference/index.mdxindex 3d1e3f0a9..c1d615ef1 100644--- a/docs/content/docs/api-reference/index.mdx+++ b/docs/content/docs/api-reference/index.mdx@@ -34,7 +34,7 @@ The OpenUI SDK is split into packages that build on each other:API reference for the pre-built email templates library and prompt options.</Card><Card title="@openuidev/cli" href="/docs/api-reference/cli">- openui create (scaffold a Next.js app) and openui generate (system prompt / JSON schema from- a library definition).+ openui create (scaffold a Next.js app) and openui generate (system prompt / JSON schema from a+ library definition).</Card></Cards>diff --git a/docs/content/docs/api-reference/react-email.mdx b/docs/content/docs/api-reference/react-email.mdxindex 9941757c1..858ae55b3 100644--- a/docs/content/docs/api-reference/react-email.mdx+++ b/docs/content/docs/api-reference/react-email.mdx@@ -52,7 +52,7 @@ const html = await render(## Exports-| Export | Type | Description |-| :--- | :--- | :--- |-| `emailLibrary` | `Library` | Ready-to-use library with all 44 email components |-| `emailPromptOptions` | `PromptOptions` | Examples + rules for `emailLibrary.prompt()` |+| Export | Type | Description |+| :------------------- | :-------------- | :------------------------------------------------ |+| `emailLibrary` | `Library` | Ready-to-use library with all 44 email components |+| `emailPromptOptions` | `PromptOptions` | Examples + rules for `emailLibrary.prompt()` |diff --git a/docs/content/docs/api-reference/react-lang.mdx b/docs/content/docs/api-reference/react-lang.mdxindex 0069c127d..3cfcb7d44 100644--- a/docs/content/docs/api-reference/react-lang.mdx+++ b/docs/content/docs/api-reference/react-lang.mdx@@ -72,12 +72,18 @@ interface Library {prompt(options?: PromptOptions): string;toJSONSchema(): object;+ toSpec(): PromptSpec;}interface PromptOptions {preamble?: string;additionalRules?: string[];examples?: string[];+ toolExamples?: string[];+ editMode?: boolean;+ inlineMode?: boolean;+ toolCalls?: boolean;+ bindings?: boolean;}```@@ -91,12 +97,50 @@ interface RendererProps {library: Library;isStreaming?: boolean;onAction?: (event: ActionEvent) => void;- onStateUpdate?: (state: Record<string, any>) => 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;+ queryLoader?: React.ReactNode;+ onError?: (errors: OpenUIError[]) => void;}```+## Tool Provider++Handles `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`)++The Renderer detects which form was passed and normalizes internally.++## Error types++```ts+type OpenUIErrorSource = "parser" | "runtime" | "query" | "mutation";++interface OpenUIError {+ source: OpenUIErrorSource;+ code: string;+ message: string;+ statementId?: string;+ component?: string;+ path?: string;+ hint?: string;+}++class ToolNotFoundError extends Error {+ toolName: string;+ availableTools: string[];+}+```++Error codes: `unknown-component`, `missing-required`, `null-required`, `inline-reserved`, `tool-not-found`, `parse-failed`, `parse-exception`, `runtime-error`, `render-error`.+## Actions```ts@@ -114,6 +158,25 @@ interface ActionEvent {}```+Action steps (runtime types from the evaluator):++```ts+type ActionStep =+ | { type: "run"; statementId: string; refType: "query" | "mutation" }+ | { type: "continue_conversation"; message: string; context?: string }+ | { type: "open_url"; url: string }+ | { type: "set"; target: string; valueAST: ASTNode }+ | { type: "reset"; targets: string[] };+```++| 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`. |+| `"open_url"` | `@OpenUrl("url")` | Open URL in new tab. |+## Parser APIsBoth `createParser` and `createStreamingParser` accept a `LibraryJSONSchema` (from `library.toJSONSchema()`).@@ -153,48 +216,51 @@ interface ElementNode {}/**- * Validation error codes for schema-related issues.- *- * - missing-required — required prop absent with no default- * - null-required — required prop explicitly null with no default- * - unknown-component — PascalCase name not in the library schema- * - excess-args — more positional args than the schema defines+ * Parser-level validation errors (schema mismatches).*/type ValidationErrorCode =| "missing-required"| "null-required"| "unknown-component"- | "excess-args";+ | "inline-reserved";-/**- * Structured error from the parser.- * Use `type` to distinguish error categories and `code` to filter- * or categorize errors on the consumer side.- */-type OpenUIError = {- type: "validation";+interface ValidationError {code: ValidationErrorCode;component: string;- /** JSON Pointer path within props, e.g. "/title". Empty string for structural errors. */path: string;message: string;-};+ statementId?: string;+}interface ParseResult {root: ElementNode | null;meta: {incomplete: boolean;- /** Identifiers referenced but not yet defined. Check after streaming completes. */unresolved: string[];statementCount: number;- errors: OpenUIError[];+ errors: ValidationError[];};+ /** Extracted Query() statements with tool name, args AST, defaults AST */+ queryStatements: QueryStatementInfo[];+ /** Extracted Mutation() statements with tool name, args AST */+ mutationStatements: MutationStatementInfo[];+ /** Declared $variables with their default values */+ stateDeclarations: Record<string, unknown>;}```## Context hooks (inside renderer components)```ts+// Reactive state binding — preferred for form inputs and $variable-bound components+function useStateField(+ name: string,+ value?: unknown,+): {+ value: unknown;+ setValue: (value: unknown) => void;+};+function useRenderNode(): (value: unknown) => React.ReactNode;function useTriggerAction(): (userMessage: string,diff --git a/docs/content/docs/api-reference/react-ui.mdx b/docs/content/docs/api-reference/react-ui.mdxindex b6cdf360d..d181ed509 100644--- a/docs/content/docs/api-reference/react-ui.mdx+++ b/docs/content/docs/api-reference/react-ui.mdx@@ -119,7 +119,9 @@ import {**`openuiChatLibrary`** — Root is `Card` (vertical, no layout params). Includes chat-specific components: `FollowUpBlock`, `ListBlock`, `SectionBlock`. Does not include `Stack`. Use with `FullScreen` / `BottomTray` / `Copilot` chat interfaces.-**`openuiLibrary`** — Root is `Stack`. Full layout suite with `Stack`, `Tabs`, `Carousel`, `Accordion`, etc. Use with the standalone `Renderer` or any non-chat layout (e.g., playground, embedded widgets).+**`openuiLibrary`** — Root is `Stack`. Full layout suite with `Stack`, `Tabs`, `Carousel`, `Accordion`, `Modal`, etc. Use with the standalone `Renderer` or any non-chat layout (e.g., playground, embedded widgets, dashboards).++**`openuiPromptOptions`** — includes examples and additional rules for the general-purpose library. Does not include `toolExamples` — pass those in your app-level `PromptSpec` alongside tool descriptions.Generate the system prompt at build time with the CLI:diff --git a/docs/content/docs/chat/artifacts.mdx b/docs/content/docs/chat/artifacts.mdxindex 0c0b91741..0114d01f9 100644--- a/docs/content/docs/chat/artifacts.mdx+++ b/docs/content/docs/chat/artifacts.mdx@@ -45,19 +45,19 @@ An artifact component has two parts:import { Artifact } from "@openuidev/react-ui";Artifact({- title, // string | (props) => string- preview, // (props, controls) => ReactNode- panel, // (props, controls) => ReactNode- panelProps, // optional — className, errorFallback, header+ title, // string | (props) => string+ preview, // (props, controls) => ReactNode+ panel, // (props, controls) => ReactNode+ panelProps, // optional — className, errorFallback, header});```-| Option | Type | Description |-|--------|------|-------------|-| `title` | `string \| (props: P) => string` | Panel header title. Static string or derived from props. |-| `preview` | `(props: P, controls: ArtifactControls) => ReactNode` | Inline preview rendered in the chat message. |-| `panel` | `(props: P, controls: ArtifactControls) => ReactNode` | Content rendered inside the side panel. |-| `panelProps` | `{ className?, errorFallback?, header? }` | Optional overrides forwarded to `ArtifactPanel`. |+| Option | Type | Description |+| ------------ | ----------------------------------------------------- | -------------------------------------------------------- |+| `title` | `string \| (props: P) => string` | Panel header title. Static string or derived from props. |+| `preview` | `(props: P, controls: ArtifactControls) => ReactNode` | Inline preview rendered in the chat message. |+| `panel` | `(props: P, controls: ArtifactControls) => ReactNode` | Content rendered inside the side panel. |+| `panelProps` | `{ className?, errorFallback?, header? }` | Optional overrides forwarded to `ArtifactPanel`. |Both `preview` and `panel` receive the full Zod-inferred props as the first argument and `ArtifactControls` as the second.@@ -67,9 +67,9 @@ The controls object passed to `preview` and `panel` render functions.```tsinterface ArtifactControls {- isActive: boolean; // whether this artifact's panel is currently open- open: () => void; // activate this artifact- close: () => void; // deactivate this artifact+ isActive: boolean; // whether this artifact's panel is currently open+ open: () => void; // activate this artifact+ close: () => void; // deactivate this artifacttoggle: () => void; // toggle open/close}```diff --git a/docs/content/docs/openui-lang/builtins.mdx b/docs/content/docs/openui-lang/builtins.mdxnew file mode 100644index 000000000..37d76a377--- /dev/null+++ b/docs/content/docs/openui-lang/builtins.mdx@@ -0,0 +1,84 @@+---+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."++## 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/defining-components.mdx b/docs/content/docs/openui-lang/defining-components.mdxindex 26467e382..6ad862d65 100644--- a/docs/content/docs/openui-lang/defining-components.mdx+++ b/docs/content/docs/openui-lang/defining-components.mdx@@ -97,8 +97,8 @@ const library = createLibrary({This serves two purposes:-1. **Constrains the LLM** — the model always wraps its output in a known top-level component, making output predictable.-2. **Enables streaming** — because the root statement comes first, the UI shell renders immediately while child components stream in.+1. **Constrains the LLM**: the model always wraps its output in a known top-level component, making output predictable.+2. **Enables streaming**: because the root statement comes first, the UI shell renders immediately while child components stream in.The `root` must match the `name` of one of the components in your library. If omitted, the prompt uses "Root" as a placeholder.@@ -131,7 +131,7 @@ Groups also let you co-locate related components so the LLM understands which co### Adding group notes-Each group can include a `notes` array — these strings are appended directly after the group's component signatures in the generated prompt. Use notes to give the LLM usage hints and constraints:+Each group can include a `notes` array. These strings are appended directly after the group's component signatures in the generated prompt. Use notes to give the LLM usage hints and constraints:```tscomponentGroups: [@@ -194,7 +194,7 @@ Deeply nested object props burn tokens and increase error rates. Prefer multiple### Order Zod keys deliberately-Required props first, optional props last. The most important or distinctive prop should be position 0 — the LLM sees it first during generation.+Required props first, optional props last. The most important or distinctive prop should be position 0, since the LLM sees it first during generation.### Use descriptive component names@@ -215,14 +215,3 @@ One or two concrete examples dramatically improve output quality, especially for### Use `componentGroups` with notesGroup related components and add notes like "Use BarChart for comparisons, LineChart for trends" to guide the LLM's choices. See [Grouping components](#grouping-components-in-prompt-output) above.--## Next Steps--<Cards>- <Card title="System Prompts" href="/docs/openui-lang/system-prompts">- Generate instructions from your library.- </Card>- <Card title="Renderer" href="/docs/openui-lang/renderer">- Parse and render model output.- </Card>-</Cards>diff --git a/docs/content/docs/openui-lang/evolution-guide.mdx b/docs/content/docs/openui-lang/evolution-guide.mdxnew file mode 100644index 000000000..b7c6ad769--- /dev/null+++ b/docs/content/docs/openui-lang/evolution-guide.mdx@@ -0,0 +1,121 @@+---+title: Evolution Guide+description: How OpenUI Lang evolved from static UI generation to interactive, data-driven apps.+---++## v0.1 → v0.5++OpenUI 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.++## The shift++| | v0.1 | v0.5 |+| ------------------- | ----------------------------- | --------------------------------------------------------------- |+| **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 |+| **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. |+| **Components** | Layout + content | + `Modal`, auto-dismiss `Callout` |++## From chat response to standalone app++### v0.1: Static UI generation++The LLM generates a component tree. It renders once. User wants changes? Ask the LLM again.++```text+root = Stack([header, chart])+header = CardHeader("Q4 Revenue")+chart = BarChart(["Oct", "Nov", "Dec"], [Series("Revenue", [120, 150, 180])])+```++Data is hardcoded. No interactivity beyond clicking a button to send a message back to the LLM.++### 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.++```text+$days = "7"+filter = Select("days", $days, [SelectItem("7", "7 days"), SelectItem("30", "30 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")])+root = Stack([CardHeader("Revenue Dashboard"), filter, Stack([kpi], "row"), chart])+```++What's different:++- `$days` is reactive state - user changes the Select, chart updates+- `Query("analytics", {days: $days})` fetches live data from your MCP tools+- `@Sum(data.rows.revenue)` computes the KPI from live data+- No LLM roundtrip when the user changes the filter++## What v0.5 adds++### Reactive state++Declare variables, bind them to inputs, reference them in expressions. Everything updates automatically.++```text+$search = ""+searchBox = Input("search", $search, "Search...")+filtered = @Filter(data.rows, "title", "contains", $search)+```++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.++```text+tickets = Query("list_tickets", {}, {rows: []})+createResult = Mutation("create_ticket", {title: $title})+```++See [Queries & Mutations](/docs/openui-lang/queries-mutations).++### Built-in functions++`@`-prefixed functions for transforming data inline: `@Count`, `@Filter`, `@Sort`, `@Sum`, `@Each`, `@Round`, and more.++```text+openCount = @Count(@Filter(tickets.rows, "status", "==", "open"))+sorted = @Sort(tickets.rows, "created", "desc")+```++See [Built-in Functions](/docs/openui-lang/builtins).++### Action composition++Buttons can run mutations, refresh queries, set state, and reset forms - all in a single action.++```text+submitBtn = Button("Create", Action([@Run(createResult), @Run(tickets), @Set($success, true), @Reset($title)]))+```++### Reactive component props (`$binding`)++Components 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.++### Incremental editing++LLM outputs only changed statements. The parser merges by name - existing code stays intact.++See [Incremental Editing](/docs/openui-lang/incremental-editing).++## What stayed the same++The core language is unchanged:++- Line-oriented assignment syntax: `identifier = Expression`+- Positional arguments mapped by Zod schema key order+- Forward references and streaming-first rendering+- Component resolution and validation++v0.5 is a superset - all v0.1 code is valid v0.5 code.diff --git a/docs/content/docs/openui-lang/examples/dashboard.mdx b/docs/content/docs/openui-lang/examples/dashboard.mdxnew file mode 100644index 000000000..375ca4336--- /dev/null+++ b/docs/content/docs/openui-lang/examples/dashboard.mdx@@ -0,0 +1,93 @@+---+title: Dashboard App+description: A data-driven dashboard with tools, MCP, and interactive charts built with OpenUI.+---++A full dashboard app that connects to backend tools via MCP. The LLM generates interactive UIs with KPI cards, charts, tables, and forms. After generation, the runtime calls your tools directly without the LLM.++[View source on GitHub →](https://github.com/thesysdev/openui/tree/main/examples/openui-dashboard)++<video+ src="/videos/openui-lang/dashboard.mp4"+ autoPlay+ loop+ muted+ playsInline+ className="w-full rounded-lg"+/>++## How it works++The app has three layers:++1. **Tools** (`src/tools.ts`): A shared registry of tool definitions with Zod input schemas, output schemas, and execute functions. Includes PostHog analytics queries, server health, ticket CRUD, and more.++2. **MCP server** (`src/app/api/mcp/route.ts`): Registers all tools from the shared registry as MCP endpoints. The Renderer's MCP client calls these at runtime.++3. **Chat + prompt** (`src/app/api/chat/route.ts`): Converts the same tool definitions into `ToolSpec[]` for prompt generation, then streams LLM responses with OpenAI function calling.++```+ tools.ts (shared source of truth)+ │+ ├──▶ /api/mcp (MCP server, runtime tool execution)+ │+ └──▶ /api/chat (prompt generation + LLM streaming)+```++## Key files++**`src/tools.ts`** defines each tool once:++```ts+export const tools: ToolDef[] = [+ {+ name: "get_usage_metrics",+ description: "Get usage metrics for the specified date range",+ inputSchema: { days: z.string().optional() },+ outputSchema: z.object({+ totalEvents: z.number(),+ data: z.array(z.object({ day: z.string(), events: z.number() })),+ }),+ execute: async (args) => getUsageMetrics(args),+ },+ // ... more tools+];+```++**`src/prompt-config.ts`** configures the prompt with tool examples and PostHog-specific instructions:++```ts+export const promptSpec: PromptSpec = {+ ...componentSpec,+ editMode: true,+ inlineMode: true,+ toolExamples: [/* PostHog dashboard example, server health example, CRUD example */],+ additionalRules: ["For analytics, prefer posthog_query with HogQL SQL", ...],+};+```++**`src/app/dashboard/page.tsx`** renders the UI with an MCP client as the tool provider:++```tsx+const client = new Client({ name: "openui-dashboard", version: "1.0.0" });+await client.connect(new StreamableHTTPClientTransport(new URL("/api/mcp")));++<Renderer+ toolProvider={client}+ library={openuiLibrary}+ response={streamedCode}+ isStreaming={isStreaming}+/>;+```++## Try it++```bash+git clone https://github.com/thesysdev/openui.git+cd openui/examples/openui-dashboard+pnpm install+echo "OPENAI_API_KEY=sk-your-key" > .env.local+pnpm dev+```++Ask it to build a PostHog analytics dashboard, a ticket tracker, or a server monitoring view.diff --git a/docs/content/docs/openui-lang/examples/react-native.mdx b/docs/content/docs/openui-lang/examples/react-native.mdxindex 71c9d6270..8daf08453 100644--- a/docs/content/docs/openui-lang/examples/react-native.mdx+++ b/docs/content/docs/openui-lang/examples/react-native.mdx@@ -29,18 +29,16 @@ Three things differ from a web OpenUI Lang integration:There is no DOM, no HTML, no CSS. Components use `Text`, `View`, `StyleSheet` from `react-native`, and `react-native-svg` for charts:```tsx-component: ({ props }) => (- <RNText style={styles.textBody}>{props.content}</RNText>-)+component: ({ props }) => <RNText style={styles.textBody}>{props.content}</RNText>;```### 2. Two mirror libraries`@openuidev/cli` runs in Node.js to generate the system prompt, but it can't import React Native. This will be fixed in future versions of the CLI. The solution is two files with identical schemas — one with real renderers for the app, one with null renderers for the backend:-| File | Purpose |-| ---- | ------- |-| `chat-app/library.tsx` | Real React Native renderers — what runs on device |+| File | Purpose |+| ------------------------ | ------------------------------------------------------------------------- |+| `chat-app/library.tsx` | Real React Native renderers — what runs on device || `backend/src/library.ts` | Null renderers (`() => null`) — used only to generate `system-prompt.txt` |Keep these in sync: same component names, same prop schemas, same root component.diff --git a/docs/content/docs/openui-lang/examples/shadcn-chat.mdx b/docs/content/docs/openui-lang/examples/shadcn-chat.mdxindex b4b63f9a0..2165869fc 100644--- a/docs/content/docs/openui-lang/examples/shadcn-chat.mdx+++ b/docs/content/docs/openui-lang/examples/shadcn-chat.mdx@@ -61,7 +61,6 @@ Swap `shadcnChatLibrary` for a library built on any other design system — MateSee [Defining Components](/docs/openui-lang/defining-components) for the full `defineComponent` API.-## Architecture```diff --git a/docs/content/docs/openui-lang/examples/vercel-ai-chat.mdx b/docs/content/docs/openui-lang/examples/vercel-ai-chat.mdxindex 54bd8506e..ce0979372 100644--- a/docs/content/docs/openui-lang/examples/vercel-ai-chat.mdx+++ b/docs/content/docs/openui-lang/examples/vercel-ai-chat.mdx@@ -63,7 +63,7 @@ const { messages, sendMessage, status, stop } = useChat({library={openuiChatLibrary}isStreaming={isStreaming}onAction={handleAction}-/>+/>;```- `response` — the accumulated text the LLM has streamed so far; `<Renderer />` parses it progressively as tokens arrivediff --git a/docs/content/docs/openui-lang/how-it-works.mdx b/docs/content/docs/openui-lang/how-it-works.mdxnew file mode 100644index 000000000..36d6f1e54--- /dev/null+++ b/docs/content/docs/openui-lang/how-it-works.mdx@@ -0,0 +1,210 @@+---+title: Architecture+description: Build dashboards, CRUD interfaces, and monitoring tools. The LLM generates the UI once, then your app runs independently.+---++## The problem today++In most AI-powered applications, when a user interacts with a generated UI (filtering data, submitting a form, refreshing a view), the request goes back through the LLM. The model re-processes the context, calls tools, and regenerates the response. Every click costs tokens. Every interaction adds latency.++## How OpenUI changes this++OpenUI 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)"+/>++### 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.++### 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 LLM generated the wiring. The runtime executes it.++## What this enables++- **Reactive dashboards** with date range filters, auto-refresh, and live KPIs computed from query results+- **CRUD interfaces** with create forms, edit modals, tables with search and sort+- **Monitoring tools** with periodic refresh, server health metrics, and error rate tracking+- **Any tool-connected UI.** If you can expose it as a tool (via [MCP](https://modelcontextprotocol.io/docs/getting-started/intro) or function map), the LLM can wire it into a UI++Try it live: [Open the GitHub Demo](/demo/github)++## Iterate and refine++The LLM doesn't have to get it right the first time. With [incremental editing](/docs/openui-lang/incremental-editing), the user says "add a pie chart" and the LLM outputs only the 2-3 changed statements and the parser merges them into the existing code. Existing queries, state, and bindings stay intact.++```+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)+```++<video+ src="/videos/openui-lang/incremental-editing.mp4"+ autoPlay+ loop+ muted+ playsInline+ className="w-full rounded-lg"+/>++## Connecting tools++The Renderer accepts a `toolProvider` prop that tells the runtime how to call your tools. Two options:++**Function map**, a plain object of async functions:++```tsx+<Renderer+ toolProvider={{+ list_tickets: async (args) => fetch("/api/tickets").then((r) => r.json()),+ create_ticket: async (args) =>+ fetch("/api/tickets", { method: "POST", body: JSON.stringify(args) }).then((r) => r.json()),+ }}+ response={code}+ library={library}+/>+```++**[MCP](https://modelcontextprotocol.io/docs/getting-started/intro) client** for server-side tools:++```tsx+import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";++const client = new Client({ name: "my-app", version: "1.0.0" });+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.++The [GitHub Demo](/demo/github) uses a function map where tools run entirely client-side, calling the GitHub API directly from the browser. The [Dashboard example](https://github.com/thesysdev/openui/tree/main/examples/openui-dashboard) uses MCP with server-side tools.++## A concrete example++Here's the full flow for a ticket tracker: define tools, generate the prompt, render the output.++### 1. Define your tools++```ts+// tools.ts+const tools: ToolSpec[] = [+ {+ name: "list_tickets",+ description: "List all tickets",+ inputSchema: { type: "object", properties: {} },+ outputSchema: {+ type: "object",+ properties: {+ rows: {+ type: "array",+ items: {+ type: "object",+ properties: { title: { type: "string" }, priority: { type: "string" } },+ },+ },+ },+ },+ },+ {+ name: "create_ticket",+ description: "Create a new ticket",+ inputSchema: {+ type: "object",+ properties: {+ title: { type: "string" },+ priority: { type: "string" },+ },+ },+ outputSchema: { type: "object", properties: { success: { type: "boolean" } } },+ },+];+```++### 2. Generate the prompt and call the LLM++```ts+// route.ts+import { generatePrompt } from "@openuidev/lang-core";+import componentSpec from "./generated/component-spec.json";++const systemPrompt = generatePrompt({+ ...componentSpec,+ tools,+ toolCalls: true,+ bindings: true,+});++const completion = await openai.chat.completions.create({+ model: "gpt-5.4-mini",+ stream: true,+ messages: [+ { role: "system", content: systemPrompt },+ { role: "user", content: "Build a ticket tracker with a create form and table" },+ ],+});+```++### 3. Render the response++```tsx+// page.tsx+<Renderer+ library={library}+ response={streamedText}+ isStreaming={isStreaming}+ toolProvider={{+ list_tickets: async () => db.query("SELECT * FROM tickets"),+ create_ticket: async (args) => db.query("INSERT INTO tickets ...", args),+ }}+/>+```++### What the LLM generates++```text+$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, [+ SelectItem("low", "Low"), SelectItem("medium", "Medium"), SelectItem("high", "High")+ ]))+])+tbl = Table([Col("Title", tickets.rows.title), Col("Priority", tickets.rows.priority)])+root = Stack([CardHeader("Ticket Tracker"), form, tbl])+```++<video+ src="/videos/openui-lang/ticket-tracker.mp4"+ autoPlay+ loop+ muted+ playsInline+ className="w-full rounded-lg"+/>++### 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++All without the LLM.diff --git a/docs/content/docs/openui-lang/incremental-editing.mdx b/docs/content/docs/openui-lang/incremental-editing.mdxnew file mode 100644index 000000000..ab1b490e5--- /dev/null+++ b/docs/content/docs/openui-lang/incremental-editing.mdx@@ -0,0 +1,93 @@+---+title: Incremental Editing+description: Edit existing UIs efficiently - the LLM patches only what changed, the parser merges it.+---++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.++## How it works++```+ Before (4 statements): After merge (5 statements):++ 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.+```++<video+ src="/videos/openui-lang/incremental-editing.mp4"+ autoPlay+ loop+ muted+ playsInline+ className="w-full rounded-lg"+/>++**Initial generation** - LLM outputs full code:++```text+root = Stack([header, tbl])+header = CardHeader("Tickets")+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"_++**LLM outputs only the patch:**++```text+root = Stack([header, chart, tbl])+chart = PieChart(["Open", "Closed"], [+ @Count(@Filter(tickets.rows, "status", "==", "open")),+ @Count(@Filter(tickets.rows, "status", "==", "closed"))+], "donut")+```++The parser 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)++## 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++## Why this matters++- **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++Full regeneration: 20 statements, ~400 tokens, ~2s streaming.+Incremental patch: 2 statements, ~60 tokens, ~0.3s streaming.+Same result, up to **85% fewer tokens**.++## Enabling edit mode++Two flags control this behavior in your prompt config:++```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+};+```++**`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.++**`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.++Both flags are passed to `generatePrompt()` via your `PromptSpec`. See [System Prompts](/docs/openui-lang/system-prompts) for the full reference.diff --git a/docs/content/docs/openui-lang/index.mdx b/docs/content/docs/openui-lang/index.mdxindex 8d90e47d4..11b656cf8 100644--- a/docs/content/docs/openui-lang/index.mdx+++ b/docs/content/docs/openui-lang/index.mdx@@ -5,7 +5,7 @@ title: Introductionimport { StreamingComparison } from "@/app/docs/openui-lang/streaming-comparison";import { TryItOut } from "./components/try-it-out";-OpenUI is a full-stack Generative UI framework — a compact streaming-first language, a React runtime with built-in component libraries, and ready-to-use chat interfaces — that is up to **[67% more token-efficient](/docs/openui-lang/benchmarks)** than JSON.+OpenUI is a full-stack Generative UI framework (a compact streaming-first language, a React runtime with built-in component libraries, and ready-to-use chat interfaces) that is up to **[67% more token-efficient](/docs/openui-lang/benchmarks)** than JSON. Generate anything from rich chat responses to [fully interactive dashboards](/docs/openui-lang/how-it-works).## What is Generative UI?@@ -16,11 +16,11 @@ Generative UI fundamentally changes this relationship. Instead of merely providi<TryItOut />## 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).+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).### Why a New Language?-While JSON is a common data interchange format, it has significant drawbacks when streamed directly from an LLM for UI generation. And there are mutliple implementations around it, like Vercel [JSON-Render](https://json-render.dev/) and [A2UI](https://a2ui.org/).+While JSON is a common data interchange format, it has significant drawbacks when streamed directly from an LLM for UI generation. And there are multiple implementations around it, like Vercel [JSON-Render](https://json-render.dev/) and [A2UI](https://a2ui.org/).OpenUI Lang was created to solve these core issues:@@ -28,20 +28,32 @@ OpenUI Lang was created to solve these core issues:- **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.-- **Robustness:** The LLMs are unpredictable. They can hallucinate component names, produce invalid structures. OpenUI Lang is designed to be robust against this by validating the output and drops the invalid portion of response from rendering.+- **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.<StreamingComparison />-## How It Works+## Architecture at a Glance<img src="/images/openui-lang/openui-chart-flow.png" alt="Architecture diagram" />-The key difference from a standard chat app is what happens at the LLM and rendering layers:+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 appends the generated component library prompt alongside your system prompt, instructing 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.-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 in real-time — structure first, then data fills in progressively.+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/how-it-works).-The result is a native UI — like the "Total expenses" card and interactive pie chart above — dynamically composed by the AI, streamed efficiently, and rendered safely from your own components.+## What can you build?++<Cards>+ <Card title="Chat" href="/docs/chat">+ Conversational AI with generative UI responses, thread history, and prebuilt layouts.+ </Card>+ <Card title="Dashboards & Apps" href="/docs/openui-lang/how-it-works">+ Data-driven dashboards, CRUD interfaces, and monitoring tools, powered by live data from your+ tools.+ </Card>+</Cards>++Want to try it? [Open the Playground](/playground) or follow the [Quick Start](/docs/openui-lang/quickstart).diff --git a/docs/content/docs/openui-lang/interactivity.mdx b/docs/content/docs/openui-lang/interactivity.mdxindex 795781a48..fde3708f9 100644--- a/docs/content/docs/openui-lang/interactivity.mdx+++ b/docs/content/docs/openui-lang/interactivity.mdx@@ -36,14 +36,38 @@ When a user clicks a button or follow-up, the component calls `triggerAction`. T### Built-in action types```ts+// Dispatched via onAction callbackenum BuiltinActionType {ContinueConversation = "continue_conversation",OpenUrl = "open_url",}```-- `ContinueConversation` — sends the user's intent back to the LLM.-- `OpenUrl` — opens a URL in a new tab. Expects `params.url`.+- `ContinueConversation`: sends the user's intent back to the LLM (`@ToAssistant`).+- `OpenUrl`: opens a URL in a new tab (`@OpenUrl`).++The following action steps are handled internally by the runtime (not dispatched 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([...])`:++```text+submitBtn = Button("Create", Action([@Run(createResult), @Run(tickets), @Reset($title)]))+```++See [Reactive State](/docs/openui-lang/reactive-state) for `$variables` and [Queries & Mutations](/docs/openui-lang/queries-mutations) for `@Run`.++### Inline mode++When `inlineMode` is enabled in the prompt config, the LLM can respond with either:++- **Code** (fenced in triple backticks), for creating or changing the UI+- **Text only**, for answering questions without modifying the UI++The parser extracts code from fences automatically. Text outside fences is shown as chat.### Using `triggerAction` in components@@ -61,13 +85,48 @@ const MyButton = defineComponent({});```-`triggerAction(userMessage, formName?, action?)` — the second and third arguments are optional.+`triggerAction(userMessage, formName?, action?)` accepts optional second and third arguments.++---++## 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.++For component authors building custom libraries, the `useStateField` hook provides this binding:++```tsx+import { useStateField, reactive } from "@openuidev/react-lang";++const MySelect = defineComponent({+ name: "MySelect",+ props: z.object({+ name: z.string(),+ value: reactive(z.string().optional()), // reactive() marks this prop as accepting $variable binding+ items: z.array(SelectItem.ref),+ }),+ 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+ return (+ <select value={field.value ?? ""} onChange={(e) => field.setValue(e.target.value)}>+ {/* ... */}+ </select>+ );+ },+});+```++`useStateField` unifies form state and reactive `$variable` binding. When the prop is a `$variable`, `setValue` updates the store and triggers all dependent queries and expressions to re-evaluate.++See [Reactive State](/docs/openui-lang/reactive-state) for the language-level documentation.---## Form state-The `Renderer` tracks field values automatically. Components use `useSetFieldValue` and `useGetFieldValue` to read and write state.+The `Renderer` tracks field values automatically. Components use `useStateField` (preferred) or the lower-level `useSetFieldValue` and `useGetFieldValue` to read and write state.### Persistence@@ -85,18 +144,19 @@ Use `onStateUpdate` to persist field state (e.g. to a message in your thread sto/>```-`onStateUpdate` fires on every field change. The state format is opaque — persist and hydrate it as-is.+`onStateUpdate` fires on every field change. The state format is opaque, so persist and hydrate it as-is.### Field hooksUse these inside `defineComponent` renderers:-| Hook | Signature | Description |-| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------- |-| `useGetFieldValue` | `(formName: string \| undefined, name: string) => any` | Read a field's current value. |-| `useSetFieldValue` | `(formName: string \| undefined, componentType: string \| undefined, name: string, value: any, shouldTriggerSaveCallback?: boolean) => void` | Write a field value. |-| `useFormName` | `() => string \| undefined` | Get the enclosing form's name. |-| `useSetDefaultValue` | `(options: { formName?, componentType, name, existingValue, defaultValue, shouldTriggerSaveCallback? }) => void` | Set a default if no value exists. |+| Hook | Signature | Description |+| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------- |+| `useStateField` | `(name: string, value?: unknown) => { value: unknown, setValue: (v: unknown) => void }` | **Preferred.** Unified form state + reactive `$variable` binding. |+| `useGetFieldValue` | `(formName: string \| undefined, name: string) => any` | Read a field's current value. |+| `useSetFieldValue` | `(formName: string \| undefined, componentType: string \| undefined, name: string, value: any, shouldTriggerSaveCallback?: boolean) => void` | Write a field value. |+| `useFormName` | `() => string \| undefined` | Get the enclosing form's name. |+| `useSetDefaultValue` | `(options: { formName?, componentType, name, existingValue, defaultValue, shouldTriggerSaveCallback? }) => void` | Set a default if no value exists. |---@@ -118,14 +178,3 @@ interface FormValidationContextValue {Built-in validators include `required`, `minLength`, `maxLength`, `min`, `max`, `pattern`, and `email`. Custom validators can be added via `builtInValidators`.-----## Next Steps--<Cards>- <Card title="Renderer" href="/docs/openui-lang/renderer">- Full Renderer props reference.- </Card>- <Card title="API Reference" href="/docs/api-reference/react-lang">- Complete react-lang API.- </Card>-</Cards>diff --git a/docs/content/docs/openui-lang/meta.json b/docs/content/docs/openui-lang/meta.jsonindex d456c99e4..a8e048ed4 100644--- a/docs/content/docs/openui-lang/meta.json+++ b/docs/content/docs/openui-lang/meta.json@@ -10,11 +10,22 @@"system-prompts","renderer","interactivity",- "troubleshooting",+ "---Building Apps---",+ "how-it-works",+ "reactive-state",+ "queries-mutations",+ "incremental-editing",+ "builtins",+ "patterns",+ "---Language Specification---",+ "specification-v01",+ "specification-v05",+ "evolution-guide","---Advanced---",- "specification","benchmarks",+ "troubleshooting","---Examples---",+ "examples/dashboard","examples/shadcn-chat","examples/react-native","examples/vercel-ai-chat",diff --git a/docs/content/docs/openui-lang/overview.mdx b/docs/content/docs/openui-lang/overview.mdxindex 98a32c6fe..f1bd067b0 100644--- a/docs/content/docs/openui-lang/overview.mdx+++ b/docs/content/docs/openui-lang/overview.mdx@@ -7,13 +7,13 @@ import { LangExample } from "./components/lang-example";OpenUI is built around four core building blocks that work together to turn LLM output into rendered UI:-- **Library** — A collection of components defined with Zod schemas and React renderers. The library is the contract between your app and the AI — it defines what components the LLM can use and how they render.+- **Library**: A collection of components defined with Zod schemas and React renderers. The library is the contract between your app and the AI, defining what components the LLM can use and how they render.-- **Prompt Generator** — Converts your library into a system prompt that instructs the LLM to output valid OpenUI Lang. Includes syntax rules, component signatures, streaming guidelines, and your custom examples/rules.+- **Prompt Generator**: Converts your library into a system prompt that instructs the LLM to output valid OpenUI Lang. Includes syntax rules, component signatures, streaming guidelines, and your custom examples/rules.-- **Parser** — Parses OpenUI Lang text (line-by-line, streaming-compatible) into a typed element tree. Validates against your library's JSON Schema and gracefully handles partial/invalid output.+- **Parser**: Parses OpenUI Lang text (line-by-line, streaming-compatible) into a typed element tree. Validates against your library's JSON Schema and gracefully handles partial/invalid output.-- **Renderer** — The `<Renderer />` React component takes parsed output and maps each element to your library's React components, rendering the UI progressively as the stream arrives.+- **Renderer**: The `<Renderer />` React component takes parsed output and maps each element to your library's React components, rendering the UI progressively as the stream arrives.## Built-in Component Libraries@@ -36,7 +36,7 @@ const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);### Chat-optimized library (`openuiChatLibrary`)-Root component is `Card` (vertical container, no layout params). Adds chat-specific components like `FollowUpBlock`, `ListBlock`, and `SectionBlock`. Does not include `Stack` — responses are always single-card, vertically stacked.+Root component is `Card` (vertical container, no layout params). Adds chat-specific components like `FollowUpBlock`, `ListBlock`, and `SectionBlock`. Does not include `Stack`; responses are always single-card, vertically stacked.```tsimport { openuiChatLibrary, openuiChatPromptOptions } from "@openuidev/react-ui/genui-lib";@@ -79,20 +79,3 @@ const myLibrary = createLibrary({## Usage Example<LangExample />--## Next Steps--<Cards>- <Card title="Defining Components" href="/docs/openui-lang/defining-components">- Create custom components with Zod schemas and React renderers.- </Card>- <Card title="System Prompts" href="/docs/openui-lang/system-prompts">- Generate and customize LLM instructions from your library.- </Card>- <Card title="The Renderer" href="/docs/openui-lang/renderer">- Parse and render streamed OpenUI Lang in React.- </Card>- <Card title="Chat Integration" href="/docs/chat">- Build AI chat interfaces with prebuilt layouts.- </Card>-</Cards>diff --git a/docs/content/docs/openui-lang/patterns.mdx b/docs/content/docs/openui-lang/patterns.mdxnew file mode 100644index 000000000..ff027ca90--- /dev/null+++ b/docs/content/docs/openui-lang/patterns.mdx@@ -0,0 +1,142 @@+---+title: Patterns+description: 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.++## Searchable, sortable table++A text input filters rows, a dropdown sorts them. Both are reactive.++```text+$search = ""+$sortBy = "stars"+data = Query("get_repos", {}, {rows: []})+filtered = @Filter(data.rows, "name", "contains", $search)+sorted = @Sort(filtered, $sortBy, "desc")+searchBox = FormControl("Search", Input("search", "Filter repos...", "text", null, $search))+sortSelect = FormControl("Sort by", Select("sortBy", [SelectItem("stars", "Stars"), SelectItem("forks", "Forks"), SelectItem("updated", "Recent")], null, null, $sortBy))+controls = Stack([searchBox, sortSelect], "row", "m")+tbl = Table([Col("Name", sorted.name), Col("Stars", sorted.stars, "number"), Col("Forks", sorted.forks, "number")])+emptyState = @Count(filtered) > 0 ? tbl : TextContent("No results match your search.")+root = Stack([CardHeader("Repositories"), controls, emptyState])+```++What's happening:++- `$search` binds to the Input. User types, `@Filter` re-evaluates, table updates.+- `$sortBy` binds to the Select. User picks a field, `@Sort` re-evaluates.+- `@Count(filtered) > 0` shows an empty state when nothing matches.++## CRUD with edit modal++Create tickets with a form, edit them in a modal, refresh the table after each action.++```text+$title = ""+$priority = "medium"+$showEdit = false+$editId = ""+$editTitle = ""+$editPriority = "medium"+createResult = Mutation("create_ticket", {title: $title, priority: $priority})+updateResult = Mutation("update_ticket", {id: $editId, title: $editTitle, priority: $editPriority})+tickets = Query("list_tickets", {}, {rows: []})+createBtn = Button("Create", Action([@Run(createResult), @Run(tickets), @Reset($title, $priority)]))+createForm = Form("create", createBtn, [+ 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", @Each(tickets.rows, "t", Tag(t.priority, null, "sm", t.priority == "high" ? "danger" : "neutral"))),+ Col("Edit", @Each(tickets.rows, "t", Button("Edit", Action([@Set($editId, t.id), @Set($editTitle, t.title), @Set($editPriority, t.priority), @Set($showEdit, true)]), "secondary", "normal", "small")))+])+saveBtn = Button("Save", Action([@Run(updateResult), @Run(tickets), @Set($showEdit, false)]), "primary")+cancelBtn = Button("Cancel", Action([@Set($showEdit, false)]), "secondary")+editForm = Form("edit", Buttons([saveBtn, cancelBtn]), [+ FormControl("Title", Input("editTitle", "", "text", {required: true}, $editTitle)),+ FormControl("Priority", Select("editPriority", [SelectItem("low", "Low"), SelectItem("medium", "Medium"), SelectItem("high", "High")], null, null, $editPriority))+])+editModal = Modal("Edit Ticket", $showEdit, [editForm])+root = Stack([CardHeader("Tickets"), createForm, tbl, editModal])+```++What's happening:++- Create form uses `Mutation` + `@Run` + `@Reset` to create and clear.+- Edit button uses `@Set` to populate modal fields and open it.+- Save button runs the update mutation, refreshes the query, and closes the modal.+- `@Each` renders per-row Tag colors and Edit buttons.++## Dashboard with KPI cards++Aggregate query results into KPI cards using `@Count`, `@Sum`, and `@Filter`.++```text+$days = "7"+data = Query("get_usage_metrics", {days: $days}, {totalEvents: 0, totalUsers: 0, data: []})+filter = FormControl("Date Range", Select("days", [SelectItem("7", "7 days"), SelectItem("14", "14 days"), SelectItem("30", "30 days")], null, null, $days))+kpiRow = Stack([+ Card([TextContent("Events", "small"), TextContent("" + data.totalEvents, "large-heavy")]),+ Card([TextContent("Users", "small"), TextContent("" + data.totalUsers, "large-heavy")]),+ Card([TextContent("Avg/Day", "small"), TextContent("" + @Round(@Avg(data.data.events), 0), "large-heavy")])+], "row", "m", "stretch", "start", true)+chart = Card([CardHeader("Daily Trend"), LineChart(data.data.day, [Series("Events", data.data.events), Series("Users", data.data.users)])])+root = Stack([CardHeader("Analytics"), filter, kpiRow, chart])+```++What's happening:++- One `$days` variable drives the Query args. Changing the Select re-fetches everything.+- KPIs use direct field access (`data.totalEvents`) and computed values (`@Round(@Avg(...))`).+- The chart uses array pluck (`data.data.day`) to extract columns from the query result.++## Auto-refresh monitoring++The 4th argument to `Query` sets a refresh interval in seconds.++```text+health = Query("get_server_health", {}, {cpu: 0, memory: 0, latencyP95: 0, errorRate: 0, timeseries: []}, 30)+kpiRow = Stack([+ Card([TextContent("CPU", "small"), TextContent("" + @Round(health.cpu, 1) + "%", "large-heavy")]),+ Card([TextContent("Memory", "small"), TextContent("" + @Round(health.memory, 1) + "%", "large-heavy")]),+ Card([TextContent("P95 Latency", "small"), TextContent("" + health.latencyP95 + "ms", "large-heavy")]),+ Card([TextContent("Error Rate", "small"), TextContent("" + @Round(health.errorRate, 2) + "%", "large-heavy")])+], "row", "m", "stretch", "start", true)+chart = Card([CardHeader("24h Trend"), LineChart(health.timeseries.time, [Series("CPU", health.timeseries.cpu), Series("Memory", health.timeseries.memory)])])+refreshBtn = Button("Refresh Now", Action([@Run(health)]), "secondary")+root = Stack([CardHeader("Server Health"), refreshBtn, kpiRow, chart])+```++What's happening:++- `Query(..., 30)` re-fetches every 30 seconds automatically.+- `@Run(health)` on the button triggers an immediate manual refresh.+- KPIs use `@Round` for clean number formatting.++## Shared filter across tabs++One `$days` variable works across all tab content because tabs share the same reactive scope.++```text+$days = "7"+filter = FormControl("Date Range", Select("days", [SelectItem("7", "7 days"), SelectItem("14", "14 days"), SelectItem("30", "30 days")], null, null, $days))+usage = Query("get_usage_metrics", {days: $days}, {data: []})+endpoints = Query("get_top_endpoints", {days: $days}, {endpoints: []})+overviewTab = TabItem("overview", "Overview", [+ LineChart(usage.data.day, [Series("Events", usage.data.events)])+])+endpointsTab = TabItem("endpoints", "Top Endpoints", [+ Table([Col("Path", endpoints.endpoints.path), Col("Requests", endpoints.endpoints.requests, "number"), Col("Latency", endpoints.endpoints.avgLatency, "number")])+])+tabs = Tabs([overviewTab, endpointsTab])+root = Stack([CardHeader("Dashboard"), filter, tabs])+```++What's happening:++- Both `usage` and `endpoints` queries reference `$days` in their args.+- Changing the filter re-fetches both queries, updating both tabs.+- Each tab renders different data but shares the same reactive variable.diff --git a/docs/content/docs/openui-lang/queries-mutations.mdx b/docs/content/docs/openui-lang/queries-mutations.mdxnew file mode 100644index 000000000..31dc1e51b--- /dev/null+++ b/docs/content/docs/openui-lang/queries-mutations.mdx@@ -0,0 +1,101 @@+---+title: Queries & Mutations+description: Fetch and write data from your tools - the LLM generates the wiring, the runtime executes it.+---++<img+ src="/images/openui-lang/query-flow.png"+ alt="Data flow: openui-lang code → Runtime → Your Tools → Live data back to components"+/>++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.++## Reading data with Query++```text+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)++The default value is important - it lets the UI render immediately while data loads.++## Using Query results++Query results are just data. Access fields with dot notation:++```text+tbl = 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.++### Reactive queries++Pass a `$variable` in the query args - the query re-runs 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")])+```++User picks "30" → `$days` updates → Query re-fetches with `{days: "30"}` → chart updates.++### Auto-refresh++Add a fourth argument for periodic refresh (in seconds):++```text+health = Query("get_server_health", {}, {cpu: 0, memory: 0}, 30)+```++This re-fetches every 30 seconds - great for monitoring dashboards.++## Writing data with Mutation++```text+createResult = Mutation("create_ticket", {title: $title, priority: $priority})+```++Mutations are NOT executed on page load. They only run when triggered by `@Run`:++```text+submitBtn = Button("Create", Action([@Run(createResult), @Run(tickets), @Reset($title)]))+```++This button does three things in order:++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++### Error handling++Check `result.status` for mutation feedback:++```text+createResult.status == "error" ? Callout("error", "Failed", createResult.error) : null+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:++```tsx+// Function map+<Renderer toolProvider={{+ list_tickets: async (args) => fetch('/api/tickets').then(r => r.json()),+}} response={code} library={library} />++// Or an MCP client+<Renderer toolProvider={mcpClient} response={code} library={library} />+```diff --git a/docs/content/docs/openui-lang/quickstart.mdx b/docs/content/docs/openui-lang/quickstart.mdxindex fc19f1c02..11ae7f6aa 100644--- a/docs/content/docs/openui-lang/quickstart.mdx+++ b/docs/content/docs/openui-lang/quickstart.mdx@@ -1,9 +1,18 @@---title: Quick Start-description: Bootstrap a Generative UI chat app in under a minute.+description: Bootstrap a GenUI chat app in under a minute.----## Bootstrap a GenUI Chat app+<video+ src="/videos/openui-lang/chat-quickstart.mp4"+ autoPlay+ loop+ muted+ playsInline+ className="w-full rounded-lg"+/>++## Create the app```bashnpx @openuidev/cli@latest create --name genui-chat-app@@ -39,9 +48,9 @@ src/system-prompt.txt # Auto-generated at build time via `openui generate````-- **`page.tsx`** — Renders the `FullScreen` chat layout with `openuiChatLibrary` for Generative UI rendering and `openAIAdapter()` for streaming.-- **`route.ts`** — A backend API route that sends the system prompt to the LLM and streams the response back.-- **`library.ts`** — Your component library entrypoint. The `openui generate` CLI reads this file to produce the system prompt.+- **`page.tsx`**: Renders the `FullScreen` chat layout with `openuiChatLibrary` for Generative UI rendering and `openAIAdapter()` for streaming.+- **`route.ts`**: A backend API route that sends the system prompt to the LLM and streams the response back.+- **`library.ts`**: Your component library entrypoint. The `openui generate` CLI reads this file to produce the system prompt.The `dev` and `build` scripts automatically regenerate the system prompt before starting:@@ -49,17 +58,3 @@ The `dev` and `build` scripts automatically regenerate the system prompt before"generate:prompt": "openui generate src/library.ts --out src/generated/system-prompt.txt","dev": "pnpm generate:prompt && next dev"```--## Next Steps--<Cards>- <Card title="Overview" href="/docs/openui-lang/overview">- Understand the key building blocks and built-in component libraries.- </Card>- <Card title="Defining Components" href="/docs/openui-lang/defining-components">- Create your own custom component library.- </Card>- <Card title="Chat Quick Start" href="/docs/chat/quick-start">- Explore chat-specific layouts and configurations.- </Card>-</Cards>diff --git a/docs/content/docs/openui-lang/reactive-state.mdx b/docs/content/docs/openui-lang/reactive-state.mdxnew file mode 100644index 000000000..6bbfe0375--- /dev/null+++ b/docs/content/docs/openui-lang/reactive-state.mdx@@ -0,0 +1,101 @@+---+title: Reactive State+description: Make your UI interactive with $variables that update automatically.+---++<video+ src="/videos/openui-lang/reactive.mp4"+ autoPlay+ loop+ muted+ playsInline+ 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 `$`:++```text+$days = "7"+$title = ""+$showEdit = false+```++That's it. 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.++```text+$days = "7"+filter = Select("days", $days, [SelectItem("7", "7 days"), SelectItem("30", "30 days")])+```++## Using variables in expressions++Any expression can read a `$variable`:++```text+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.++## Changing state from buttons++Use `@Set` inside an `Action` to change a variable when a button is clicked:++```text+btn = Button("Show 30 days", Action([@Set($days, "30")]))+```++You can set multiple variables at once:++```text+saveBtn = Button("Save", Action([@Set($showEdit, false), @Set($saved, true)]))+```++## Resetting to defaults++`@Reset` restores variables to their declared defaults:++```text+$title = ""+$priority = "medium"+resetBtn = Button("Clear", Action([@Reset($title, $priority)]))+```++After click: `$title` goes back to `""`, `$priority` goes back to `"medium"`.++## Conditional rendering++Use ternary expressions to show/hide UI based on state:++```text+$showEdit ? editForm : null+status == "error" ? Callout("error", "Failed", errorMsg) : null+```++## How reactivity works++<img+ src="/images/openui-lang/reactive.png"+ alt="Reactivity chain: $days changes, Query re-fetches, TextContent re-evaluates, Chart re-renders"+/>++When a `$variable` changes:++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++No event listeners. No useEffect. No wiring. Just declare and reference.diff --git a/docs/content/docs/openui-lang/renderer.mdx b/docs/content/docs/openui-lang/renderer.mdxindex 58adcadba..b2c23e3af 100644--- a/docs/content/docs/openui-lang/renderer.mdx+++ b/docs/content/docs/openui-lang/renderer.mdx@@ -24,15 +24,84 @@ 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. |+| 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 shown while queries are fetching. Defaults to a spinner. |+| `onError` | `(errors: OpenUIError[]) => void` | Structured, LLM-friendly errors from the parser and query system. Suitable for automated correction loops. Called with `[]` when resolved. |++## Connecting tools++For UIs that use `Query()` and `Mutation()`, pass a `toolProvider`. Two options:++```tsx+// Function map — tools are just async functions+<Renderer+ toolProvider={{+ list_tickets: async (args) => fetch("/api/tickets").then((r) => r.json()),+ create_ticket: async (args) =>+ fetch("/api/tickets", { method: "POST", body: JSON.stringify(args) }).then((r) => r.json()),+ }}+ library={library}+ response={code}+/>;++// MCP client — pass a configured MCP client directly+import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";++const client = new Client({ name: "my-app", version: "1.0.0" });+await client.connect(new StreamableHTTPClientTransport(new URL("/api/mcp")));+<Renderer toolProvider={client} library={library} response={code} />;+```++These examples are simplified for demonstration. In production, you'll need to handle authentication, error boundaries, and connection lifecycle.++## Error handling++`onError` receives structured errors suitable for sending back to the LLM for correction:++```tsx+<Renderer+ library={library}+ response={code}+ toolProvider={mcp}+ onError={(errors) => {+ if (!errors.length) return;+ const msg = errors+ .map(+ (e) =>+ `[${e.source}] ${e.statementId ? `"${e.statementId}": ` : ""}${e.message}${e.hint ? `\nHint: ${e.hint}` : ""}`,+ )+ .join("\n\n");+ // Send back to LLM for self-correction+ sendToLLM(`Fix these errors:\n\n${msg}`);+ }}+/>+```++Error 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 |+| `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 |++If no `onError` callback is provided, errors are logged to `console.warn` instead of being silently swallowed.## Streaming behavior@@ -58,8 +127,9 @@ export function AssistantMessage({## Hooks for component authors-Use these inside components defined with `defineComponent(...)`:+Use these inside components defined with `defineComponent(...)`. See [Reactive State](/docs/openui-lang/reactive-state) for how `$variables` work in the language.+- `useStateField(name, value?)` - reactive `$variable` binding (preferred for inputs)- `useIsStreaming()`- `useTriggerAction()`- `useRenderNode()`@@ -78,14 +148,3 @@ const Dashboard = defineComponent({component: ({ props, renderNode }) => <div>{renderNode(props.cards)}</div>,});```--## Next Steps--<Cards>- <Card title="Language Specification" href="/docs/openui-lang/specification">- Grammar and parser semantics.- </Card>- <Card title="Benchmarks" href="/docs/openui-lang/benchmarks">- Token and latency comparison.- </Card>-</Cards>diff --git a/docs/content/docs/openui-lang/specification.mdx b/docs/content/docs/openui-lang/specification-v01.mdxsimilarity index 92%rename from docs/content/docs/openui-lang/specification.mdxrename to docs/content/docs/openui-lang/specification-v01.mdxindex e24a7bd74..b38bd3d2a 100644--- a/docs/content/docs/openui-lang/specification.mdx+++ b/docs/content/docs/openui-lang/specification-v01.mdx@@ -1,8 +1,14 @@----title: Language Specification-description: Grammar, resolution, and parser semantics for OpenUI Lang.+title: v0.1+description: The original OpenUI Lang specification for declarative UI generation in chat responses.---+<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).+</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.While you rarely write this language manually, understanding the syntax is helpful for debugging raw LLM outputs or building custom parsers.diff --git a/docs/content/docs/openui-lang/specification-v05.mdx b/docs/content/docs/openui-lang/specification-v05.mdxnew file mode 100644index 000000000..fba640e74--- /dev/null+++ b/docs/content/docs/openui-lang/specification-v05.mdx@@ -0,0 +1,168 @@+---+title: v0.5 (Latest)+description: 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.++## Syntax Overview++The language consists of **assignment statements** - one per line.++```text+identifier = Expression+```++Three types of statements:++| Statement | Syntax | Example |+| ----------------- | -------------------------------------------- | -------------------------------------- |+| Component | `name = Component(args...)` | `header = CardHeader("Title")` |+| State declaration | `$name = defaultValue` | `$days = "7"` |+| Data statement | `name = Query(...)` / `name = Mutation(...)` | `data = Query("tool", {}, {rows: []})` |++## Expressions & Types++| Type | Syntax | Example |+| -------------- | ------------------- | ----------------------------- |+| Component call | `Type(arg1, arg2)` | `Header("Title", "Subtitle")` |+| Built-in call | `@Name(args)` | `@Count(data.rows)` |+| String | `"text"` | `"Hello"` |+| Number | `123`, `12.5`, `-5` | `42` |+| Boolean | `true` / `false` | `true` |+| Null | `null` | `null` |+| Array | `[a, b, c]` | `["Jan", "Feb"]` |+| Object | `{key: val}` | `{sql: "SELECT *"}` |+| Reference | `identifier` | `myHeader` |+| State ref | `$identifier` | `$days` |+| Member access | `a.b.c` | `data.rows.title` |+| Ternary | `cond ? a : b` | `$show ? form : null` |+| Binary ops | `a + b`, `a == b` | `"" + $days + " days"` |++### Operators++| Category | Operators |+| ---------- | -------------------------------- |+| Arithmetic | `+`, `-`, `*`, `/`, `%` |+| Comparison | `==`, `!=`, `>`, `<`, `>=`, `<=` |+| Logical | `&&`, `\|\|` |+| Unary | `!`, `-` |++### Member access and array pluck++`data.rows.title` on an array extracts the `title` field from every element - column pluck.++```text+data = Query("list", {}, {rows: []})+tbl = Table([Col("Title", data.rows.title)]) // plucks title from each row+kpi = TextContent("" + data.total) // access a single field+```++## Core Rules++1. **One statement per line:** `identifier = Expression`+2. **Root entry point:** `root = Root([children])`. If missing, nothing renders. The root component name comes from your library definition.+3. **Top-down generation:** Layout → Components → Data for progressive streaming.+4. **Positional arguments:** Mapped to props by Zod schema key order.+5. **Forward references allowed:** `root = Stack([chart])` can appear before `chart = ...` is defined.+6. **Positional only:** Write `Stack([children], "row", "l")` NOT `Stack([children], direction: "row", gap: "l")`.++## Reactive State (`$variables`)++Declare with `$name = default`:++```text+$days = "7"+$title = ""+$showEdit = false+```++Two-way binding: passing `$days` to `Select("days", $days, [...])` binds the variable to the input. User changes → variable updates → all expressions referencing it re-evaluate.++## Built-in Functions++All built-in functions use the `@` prefix. Using bare names (`Count(...)`) is **not supported** - only `@Count(...)`.++### Data builtins++| Function | Signature |+| --------- | ------------------------------------------------------------------------------------------------------------ |+| `@Count` | `@Count(array) → number` |+| `@Sum` | `@Sum(numbers[]) → number` |+| `@Avg` | `@Avg(numbers[]) → number` |+| `@Min` | `@Min(numbers[]) → number` |+| `@Max` | `@Max(numbers[]) → number` |+| `@First` | `@First(array) → element` |+| `@Last` | `@Last(array) → element` |+| `@Filter` | `@Filter(array, field, op, value) → filtered array`. Operators: `==`, `!=`, `>`, `<`, `>=`, `<=`, `contains` |+| `@Sort` | `@Sort(array, field, direction?) → sorted array` |+| `@Round` | `@Round(number, decimals?) → number` |+| `@Abs` | `@Abs(number) → number` |+| `@Floor` | `@Floor(number) → number` |+| `@Ceil` | `@Ceil(number) → number` |++### Iteration++`@Each(array, varName, template)` - render template for each element. Loop variable is only available inline.++### Action steps (inside `Action([...])`)++| Step | Description |+| ---------------------- | ----------------------------------------- |+| `@Run(ref)` | Execute a Mutation or re-fetch a Query |+| `@Set($var, value)` | Set a `$variable` to a value |+| `@Reset($var1, $var2)` | Restore `$variables` to declared defaults |+| `@ToAssistant("msg")` | Send message to the LLM |+| `@OpenUrl("url")` | Open URL in new tab |++## Query and Mutation++### Query (read data)++```text+data = Query("tool_name", {arg: value}, {rows: []}, 30)+```++| Position | Type | Description |+| -------- | ----------------- | -------------------------------------- |+| 1 | string | Tool name |+| 2 | object | Arguments (can reference `$variables`) |+| 3 | object | Defaults (renders before data arrives) |+| 4 | number (optional) | Refresh interval in seconds |++Queries execute on load. When `$variables` in args change, the query re-fetches automatically.++### Mutation (write data)++```text+result = Mutation("tool_name", {title: $title})+```++Mutations do NOT execute on load. Triggered via `@Run(result)` inside an `Action`.++### Action composition++```text+submitBtn = Button("Create", Action([@Run(mutation), @Run(query), @Reset($title)]))+```++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.++## Prompt Feature Flags++The system prompt is generated with feature flags that control which language features the LLM is instructed to use. See [System Prompts](/docs/openui-lang/system-prompts) for configuration.++| Flag | What it enables | Default |+| ------------ | ------------------------------------------------------------------- | ----------------------------- |+| `toolCalls` | `Query()`, `Mutation()`, `@Run`, tool workflow rules | `true` if `tools` provided |+| `bindings` | `$variables`, `@Set`, `@Reset`, reactive filters | `true` if `toolCalls` is true |+| `editMode` | Incremental editing (LLM outputs only changed statements) | `false` |+| `inlineMode` | Text + fenced code responses (LLM can answer without generating UI) | `false` |++## Streaming & Hoisting++Forward references are allowed. See [v0.1 spec](/docs/openui-lang/specification-v01#streaming--hoisting) for details.diff --git a/docs/content/docs/openui-lang/system-prompts.mdx b/docs/content/docs/openui-lang/system-prompts.mdxindex ecc0b365b..ea5a67c69 100644--- a/docs/content/docs/openui-lang/system-prompts.mdx+++ b/docs/content/docs/openui-lang/system-prompts.mdx@@ -3,9 +3,9 @@ title: System Promptsdescription: Generate and customize prompt instructions from your OpenUI library.----`library.prompt(...)` generates the instruction text your model needs to output valid OpenUI Lang. You can generate it programmatically or with the CLI.+The system prompt tells the LLM how to output valid OpenUI Lang. There are two ways to generate it.-## Generate with the CLI+## 1. CLI (recommended for most setups)The fastest way to generate a system prompt — works with any backend language:@@ -19,7 +19,7 @@ Write to a file:npx @openuidev/cli@latest generate ./src/library.ts --out system-prompt.txt```-Generate JSON Schema instead:+Generate the component spec as JSON (for use with `generatePrompt`):```bashnpx @openuidev/cli@latest generate ./src/library.ts --json-schema@@ -27,58 +27,94 @@ npx @openuidev/cli@latest generate ./src/library.ts --json-schemaThe CLI auto-detects exported `PromptOptions` (examples, rules) alongside your library. Use `--prompt-options <name>` to pick a specific export.-## Generate programmatically+## 2. `generatePrompt` (programmatic)-```ts-import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui";+For backends that need dynamic prompts - different tools, preambles, or feature flags per request - use `generatePrompt` from `@openuidev/lang-core`. This has no React dependency, so it works in any Node/Edge/serverless backend.-const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);+First, generate the component spec JSON via the CLI:++```bash+npx @openuidev/cli generate ./src/library.ts --json-schema --out generated/component-spec.json```-## Prompt options+Then build the prompt at runtime:```ts-import type { PromptOptions } from "@openuidev/react-lang";+import { generatePrompt, type PromptSpec } from "@openuidev/lang-core";+import componentSpec from "./generated/component-spec.json";++const systemPrompt = generatePrompt({+ ...componentSpec,-const options: PromptOptions = {- preamble: "You are an assistant that outputs only OpenUI Lang.",- additionalRules: ["Always produce actionable controls for forms.", "Prefer concise layouts."],- examples: [`root = Stack([title])\ntitle = TextContent("Hello")`],-};+ // Tool descriptions — so the LLM knows what tools exist+ tools: myToolSpecs,-const prompt = openuiLibrary.prompt(options);+ // Examples showing how to use your tools with Query/Mutation+ toolExamples: [`tickets = Query("list_tickets", {}, {rows: []})\n...`],++ // Feature flags+ toolCalls: true, // Enable Query(), Mutation(), @Run (default: true if tools provided)+ bindings: true, // Enable $variables, @Set, @Reset (default: true if toolCalls)+ editMode: true, // Enable incremental editing (LLM outputs patches, not full regen)+ inlineMode: true, // Enable text + code responses (LLM can answer questions without code)++ // Custom instructions+ preamble: "You build dashboards using openui-lang.",+ additionalRules: ['Use @Reset after form submit, not @Set($var, "")'],+});```-## What gets generated+| Flag | What it enables | Default |+| ------------ | ----------------------------------------------------------------------------- | ----------------------------- |+| `toolCalls` | `Query()`, `Mutation()`, `@Run`, tool workflow rules | `true` if `tools` provided |+| `bindings` | `$variables`, `@Set`, `@Reset`, 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` |-The generated prompt includes:+### `library.prompt()` (frontend shorthand)++If you're generating prompts client-side or in a Next.js route that already imports your library:-- syntax rules-- component signatures (from your registered components)-- hoisting/streaming rules-- important output constraints-- your optional examples/rules+```ts+import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui";++const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);+```-## Important behavior notes+This is convenient but imports React components - use `generatePrompt` for pure backend routes.-- Root component requirement comes from the library `root` passed to `createLibrary`.-- Prompt signatures include component descriptions, argument names, and required/optional structure.+## What gets generated++The generated prompt includes:++- Syntax rules and expression types+- Component signatures (from your registered components)+- Built-in function reference (`@Count`, `@Filter`, `@Sort`, etc.)+- Query/Mutation/Action workflow (if `toolCalls` enabled)+- `$variable` and reactive binding rules (if `bindings` enabled)+- Tool descriptions and tool examples (if `tools` provided)+- Edit mode instructions (if `editMode` enabled)+- Inline mode instructions (if `inlineMode` enabled)+- Hoisting/streaming rules+- Your optional examples and rules## Backend usage example```tsimport OpenAI from "openai";-import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui/genui-lib";+import { generatePrompt, type PromptSpec } from "@openuidev/lang-core";+import componentSpec from "./generated/component-spec.json";const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });+const systemPrompt = generatePrompt({ ...componentSpec, preamble: "You are a helpful assistant." });export async function POST(req: Request) {const { messages } = await req.json();const completion = await client.chat.completions.create({- model: "gpt-5.2",+ model: "gpt-5.4-mini",stream: true,- messages: [{ role: "system", content: openuiLibrary.prompt(openuiPromptOptions) }, ...messages],+ messages: [{ role: "system", content: systemPrompt }, ...messages],});return new Response(completion.toReadableStream(), {@@ -86,11 +122,3 @@ export async function POST(req: Request) {});}```--## Next Steps--<Cards>- <Card title="Renderer" href="/docs/openui-lang/renderer">- Render streamed OpenUI Lang in React.- </Card>-</Cards>diff --git a/docs/content/docs/openui-lang/troubleshooting.mdx b/docs/content/docs/openui-lang/troubleshooting.mdxindex 5144e81ed..4bfe5545f 100644--- a/docs/content/docs/openui-lang/troubleshooting.mdx+++ b/docs/content/docs/openui-lang/troubleshooting.mdx@@ -5,21 +5,6 @@ description: Common issues and fixes when working with OpenUI Lang and the Rende## LLM Output Issues-### Why is nothing rendering?--The first statement must assign to `root`. Without it, nothing renders.--```text-// Wrong — no root-header = Header("Title")-body = TextContent("Content")--// Correct-root = Stack([header, body])-header = Header("Title")-body = TextContent("Content")-```-### Why are extra arguments being dropped?Providing more arguments than the schema defines causes the extra arguments to be dropped or the statement to fail validation.@@ -48,7 +33,7 @@ text = TextContent("Hello world")### Can I nest children inline or do I need references?-Both are valid — inline children or references work.+Both are valid. Inline children or references work.```text// Inline@@ -60,21 +45,91 @@ h = Header("Title")t = TextContent("Body")```+### Why doesn't `Count(arr)` work?++Built-in functions require the `@` prefix. Use `@Count(arr)`, not `Count(arr)`.++```text+// Wrong+count = Count(items)++// Correct+count = @Count(items)+```++### Query or Mutation used inline++`Query` and `Mutation` must be top-level statements, not inside component arguments.++```text+// Wrong — Query inside Table+tbl = Table([Col("Title", Query("list", {}).rows.title)])++// Correct — Query as a separate statement+data = Query("list", {}, {rows: []})+tbl = Table([Col("Title", data.rows.title)])+```++---+## Renderer Issues-### How do I inspect what went wrong?+### How do I debug errors?-Pass an `onParseResult` callback to `<Renderer />`. Inspect `meta.errors` for schema mismatches and `meta.unresolved` for identifiers that were referenced but never defined.+Use the `onError` callback. It receives structured errors from the parser, runtime, and query system. Each error includes a `source`, `code`, `message`, and often a `hint` with a suggested fix.```tsx<Rendererlibrary={library}- response={content}- isStreaming={isStreaming}+ response={code}+ toolProvider={tp}+ onError={(errors) => {+ for (const e of errors) {+ console.log(`[${e.source}] ${e.message}`);+ if (e.hint) console.log(`Hint: ${e.hint}`);+ }+ }}+/>+```++If you don't provide `onError`, errors are logged to `console.warn` automatically.++For LLM self-correction loops, format the errors and send them back:++```tsx+onError={(errors) => {+ if (!errors.length) return;+ const msg = errors+ .map((e) => `[${e.source}] ${e.statementId ? `"${e.statementId}": ` : ""}${e.message}${e.hint ? `\nHint: ${e.hint}` : ""}`)+ .join("\n\n");+ sendToLLM(`Fix these errors:\n\n${msg}`);+}}+```++Error codes:++- `unknown-component`: component name not in the library (hint lists available components)+- `missing-required`: required prop not provided+- `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+- `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)++### `onParseResult` vs `onError`++`onError` is for error handling. It collects errors from all layers (parser, runtime, queries) into a single callback.++`onParseResult` is for inspection. It gives you the raw parse tree: the AST, statement count, unresolved references. Use it when you need to see what the parser produced, not just what went wrong.++```tsx+<RendereronParseResult={(result) => {if (result) {- console.log("Validation errors:", result.meta.errors);- console.log("Unresolved refs:", result.meta.unresolved);+ console.log("Statements:", result.meta.statementCount);+ console.log("Unresolved:", result.meta.unresolved);}}}/>@@ -88,8 +143,12 @@ Call `library.toJSONSchema()` to see exactly what the parser expects, and compar### Why are parts of the UI missing?-The parser drops invalid portions and renders everything else. If parts of the UI are missing, log the raw streamed text before parsing and look for:+The parser drops invalid portions and renders everything else. If parts of the UI are missing, check `onError` for `unknown-component` or `missing-required` errors.++### Why isn't my Query fetching data?++Check that:-- Missing `root` assignment-- Typos in component names-- Wrong argument count+1. The `toolProvider` prop is set on `<Renderer />`+2. Your tool function or MCP server includes the tool name used in `Query("tool_name", ...)`+3. The tool name in the code matches exactly (case-sensitive)diff --git a/docs/generated/chat-system-prompt.txt b/docs/generated/chat-system-prompt.txtindex 9a444471c..1cff93aac 100644--- a/docs/generated/chat-system-prompt.txt+++ b/docs/generated/chat-system-prompt.txt@@ -4,24 +4,24 @@ You are an AI assistant that responds using openui-lang, a declarative UI langua1. Each statement is on its own line: `identifier = Expression`2. `root` is the entry point — every program must define `root = Card(...)`-3. Expressions are: strings ("..."), numbers, booleans (true/false), arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)+3. Expressions are: strings ("..."), numbers, booleans (true/false), null, arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)4. Use references for readability: define `name = ...` on one line, then use `name` later5. EVERY variable (except root) MUST be referenced by at least one other variable. Unreferenced variables are silently dropped and will NOT render. Always include defined variables in their parent's children/items array.-6. Arguments are POSITIONAL (order matters, not names)+6. Arguments are POSITIONAL (order matters, not names). Write `Stack([children], "row", "l")` NOT `Stack([children], direction: "row", gap: "l")` — colon syntax is NOT supported and silently breaks7. Optional arguments can be omitted from the end-8. No operators, no logic, no variables — only declarations-9. Strings use double quotes with backslash escaping+- Strings use double quotes with backslash escaping## Component SignaturesArguments marked with ? are optional. Sub-components can be inline or referenced; prefer references for better streaming.-The `action` prop type accepts: ContinueConversation (sends message to LLM), OpenUrl (navigates to URL), or Custom (app-defined).+Props typed `ActionExpression` accept an Action([@steps...]) expression. See the Action section for available steps (@ToAssistant, @OpenUrl).+Props marked `$binding<type>` accept a `$variable` reference for two-way binding.### ContentCardHeader(title?: string, subtitle?: string) — Header with optional title and subtitleTextContent(text: string, size?: "small" | "default" | "large" | "small-heavy" | "large-heavy") — Text block. Supports markdown. Optional size: "small" | "default" | "large" | "small-heavy" | "large-heavy".MarkDownRenderer(textMarkdown: string, variant?: "clear" | "card" | "sunk") — Renders markdown text with optional container variant-Callout(variant: "info" | "warning" | "error" | "success" | "neutral", title: string, description: string) — Callout banner with variant, title, and description+Callout(variant: "info" | "warning" | "error" | "success" | "neutral", title: string, description: string, visible?: $binding<boolean>) — Callout banner. Optional visible is a reactive $boolean — auto-dismisses after 3s by setting $visible to false.TextCallout(variant?: "neutral" | "info" | "warning" | "success" | "danger", title?: string, description?: string) — Text callout with variant, title, and descriptionImage(alt: string, src?: string) — Image with alt text and optional URLImageBlock(src: string, alt?: string) — Image block with loading state@@ -30,8 +30,8 @@ CodeBlock(language: string, codeString: string) — Syntax-highlighted code blocSeparator(orientation?: "horizontal" | "vertical", decorative?: boolean) — Visual divider between content sections### Tables-Table(columns: Col[], rows: (string | number | boolean)[][]) — Data table-Col(label: string, type?: "string" | "number" | "action") — Column definition+Table(columns: Col[]) — Data table — column-oriented. Each Col holds its own data array.+Col(label: string, data, type?: "string" | "number" | "action") — Column definition — holds label + data array### Charts (2D)BarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Vertical bars; use for comparing values across categories with one or more series@@ -42,9 +42,9 @@ HorizontalBarChart(labels: string[], series: Series[], variant?: "grouped" | "stSeries(category: string, values: number[]) — One data series### Charts (1D)-PieChart(slices: Slice[], variant?: "pie" | "donut") — Circular slices showing part-to-whole proportions; supports pie and donut variants-RadialChart(slices: Slice[]) — Radial bars showing proportional distribution across named segments-SingleStackedBarChart(slices: Slice[]) — Single horizontal stacked bar; use for showing part-to-whole proportions in one row+PieChart(labels: string[], values: number[], variant?: "pie" | "donut") — Circular slices; use plucked arrays: PieChart(data.categories, data.values)+RadialChart(labels: string[], values: number[]) — Radial bars; use plucked arrays: RadialChart(data.categories, data.values)+SingleStackedBarChart(labels: string[], values: number[]) — Single horizontal stacked bar; use plucked arrays: SingleStackedBarChart(data.categories, data.values)Slice(category: string, value: number) — One slice with label and numeric value### Charts (Scatter)@@ -56,17 +56,17 @@ Point(x: number, y: number, z?: number) — Data point with numeric coordinatesForm(name: string, buttons: Buttons, fields) — Form container with fields and explicit action buttonsFormControl(label: string, input: Input | TextArea | Select | DatePicker | Slider | CheckBoxGroup | RadioGroup, hint?: string) — Field with label, input component, and optional hint textLabel(text: string) — Text label-Input(name: string, placeholder?: string, type?: "text" | "email" | "password" | "number" | "url", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})-TextArea(name: string, placeholder?: string, rows?: number, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})-Select(name: string, items: SelectItem[], placeholder?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})+Input(name: string, placeholder?: string, type?: "text" | "email" | "password" | "number" | "url", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)+TextArea(name: string, placeholder?: string, rows?: number, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)+Select(name: string, items: SelectItem[], placeholder?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)SelectItem(value: string, label: string) — Option for Select-DatePicker(name: string, mode: "single" | "range", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})-Slider(name: string, variant: "continuous" | "discrete", min: number, max: number, step?: number, defaultValue?: number[], label?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}) — Numeric slider input; supports continuous and discrete (stepped) variants-CheckBoxGroup(name: string, items: CheckBoxItem[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})+DatePicker(name: string, mode?: "single" | "range", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?)+Slider(name: string, variant: "continuous" | "discrete", min: number, max: number, step?: number, defaultValue?: number[], label?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<number[]>) — Numeric slider input; supports continuous and discrete (stepped) variants+CheckBoxGroup(name: string, items: CheckBoxItem[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?)CheckBoxItem(label: string, description: string, name: string, defaultChecked?: boolean)-RadioGroup(name: string, items: RadioItem[], defaultValue?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})+RadioGroup(name: string, items: RadioItem[], defaultValue?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)RadioItem(label: string, description: string, value: string)-SwitchGroup(name: string, items: SwitchItem[], variant?: "clear" | "card" | "sunk") — Group of switch toggles+SwitchGroup(name: string, items: SwitchItem[], variant?: "clear" | "card" | "sunk", value?) — Group of switch togglesSwitchItem(label?: string, description?: string, name: string, defaultChecked?: boolean) — Individual switch toggle- Define EACH FormControl as its own reference — do NOT inline all controls in one array.- NEVER nest Form inside Form.@@ -75,12 +75,12 @@ SwitchItem(label?: string, description?: string, name: string, defaultChecked?:- The renderer shows error messages automatically — do NOT generate error text in the UI### Buttons-Button(label: string, action?: {type: "open_url", url: string} | {type: "continue_conversation", context?: string} | {type: string, params?}, variant?: "primary" | "secondary" | "tertiary", type?: "normal" | "destructive", size?: "extra-small" | "small" | "medium" | "large") — Clickable button+Button(label: string, action?: ActionExpression, variant?: "primary" | "secondary" | "tertiary", type?: "normal" | "destructive", size?: "extra-small" | "small" | "medium" | "large") — Clickable buttonButtons(buttons: Button[], direction?: "row" | "column") — Group of Button components. direction: "row" (default) | "column".### Lists & Follow-upsListBlock(items: ListItem[], variant?: "number" | "image") — A list of items with number or image indicators. Each item can optionally have an action.-ListItem(title: string, subtitle?: string, image?: {src: string, alt: string}, actionLabel?: string, action?: {type: "open_url", url: string} | {type: "continue_conversation", context?: string} | {type: string, params?}) — Item in a ListBlock — displays a title with an optional subtitle and image. When action is provided, the item becomes clickable.+ListItem(title: string, subtitle?: string, image?: {src: string, alt: string}, actionLabel?: string, action?: ActionExpression) — Item in a ListBlock — displays a title with an optional subtitle and image. When action is provided, the item becomes clickable.FollowUpBlock(items: FollowUpItem[]) — List of clickable follow-up suggestions placed at the end of a responseFollowUpItem(text: string) — Clickable follow-up suggestion — when clicked, sends text as user message- Use ListBlock with ListItem references for numbered, clickable lists.@@ -114,9 +114,53 @@ Carousel(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextTagBlock(tags: string[]) — tags is an array of stringsTag(text: string, icon?: string, size?: "sm" | "md" | "lg", variant?: "neutral" | "info" | "success" | "warning" | "danger") — Styled tag/badge with optional icon and variant-### Ungrouped+### OtherCard(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps | ListBlock | FollowUpBlock | SectionBlock | Tabs | Carousel)[]) — Vertical container for all content in a chat response. Children stack top to bottom automatically.+## Built-in Functions++Data functions prefixed with `@` to distinguish from components. These are the ONLY functions available — do NOT invent new ones.+Use @-prefixed built-in functions (@Count, @Sum, @Avg, @Min, @Max, @Round) on Query results — do NOT hardcode computed values.++@Count(array) → number — Returns array length+@First(array) → element — Returns first element of array+@Last(array) → element — Returns last element of array+@Sum(numbers[]) → number — Sum of numeric array+@Avg(numbers[]) → number — Average of numeric array+@Min(numbers[]) → number — Minimum value in array+@Max(numbers[]) → number — Maximum value in array+@Sort(array, field, direction?) → sorted array — Sort array by field. Direction: "asc" (default) or "desc"+@Filter(array, field, operator: "==" | "!=" | ">" | "<" | ">=" | "<=" | "contains", value) → filtered array — Filter array by field value+@Round(number, decimals?) → number — Round to N decimal places (default 0)+@Abs(number) → number — Absolute value+@Floor(number) → number — Round down to nearest integer+@Ceil(number) → number — Round up to nearest integer+@Each(array, varName, template) — Evaluate template for each element. varName is the loop variable — use it ONLY inside the template expression (inline). Do NOT create a separate statement for the template.++Builtins compose — output of one is input to the next:+`@Count(@Filter(data.rows, "field", "==", "val"))` for KPIs/chart values, `@Round(@Avg(data.rows.score), 1)`, `@Each(data.rows, "item", Comp(item.field))` for per-item rendering.+Array pluck: `data.rows.field` extracts a field from every row → use with @Sum, @Avg, charts, tables.++IMPORTANT @Each rule: The loop variable (e.g. "item") is ONLY available inside the @Each template expression. Always inline the template — do NOT extract it to a separate statement.+CORRECT: `Col("Actions", @Each(rows, "t", Button("Edit", Action([@Set($id, t.id)]))))`+WRONG: `myBtn = Button("Edit", Action([@Set($id, t.id)]))` then `Col("Actions", @Each(rows, "t", myBtn))` — t is undefined in myBtn.++## Action — Button Behavior++Action([@steps...]) wires button clicks to operations. Steps are @-prefixed built-in actions. Steps execute in order.+Buttons without an explicit Action prop automatically send their label to the assistant (equivalent to Action([@ToAssistant(label)])).++Available steps:+- @ToAssistant("message") — Send a message to the assistant (for conversational buttons like "Tell me more", "Explain this")+- @OpenUrl("https://...") — Navigate to a URL++Example — simple nav:+```+viewBtn = Button("View", Action([@OpenUrl("https://example.com")]))+```++- Action can be assigned to a variable or inlined: Button("Go", onSubmit) and Button("Go", Action([...])) both work+## Hoisting & Streaming (CRITICAL)openui-lang supports hoisting: a reference can be used BEFORE it is defined. The parser resolves all references after the full input is parsed.@@ -125,24 +169,29 @@ During streaming, the output is re-parsed on every chunk. Undefined references a**Recommended statement order for optimal streaming:**1. `root = Card(...)` — UI shell appears immediately-2. Component definitions — fill in as they stream-3. Data values — leaf content last+2. $variable declarations — state ready for bindings+3. Query statements — defaults resolve immediately so components render with data+4. Component definitions — fill in with data already available+5. Data values — leaf content lastAlways write the root = Card(...) statement first so the UI shell appears immediately, even before child data has streamed in.## ExamplesExample 1 — Table with follow-ups:+root = Card([title, tbl, followUps])title = TextContent("Top Languages", "large-heavy")-tbl = Table(cols, rows)-cols = [Col("Language", "string"), Col("Users (M)", "number"), Col("Year", "number")]-rows = [["Python", 15.7, 1991], ["JavaScript", 14.2, 1995], ["Java", 12.1, 1995]]+tbl = Table([Col("Language", langs), Col("Users (M)", users), Col("Year", years)])+langs = ["Python", "JavaScript", "Java"]+users = [15.7, 14.2, 12.1]+years = [1991, 1995, 1995]followUps = FollowUpBlock([fu1, fu2])fu1 = FollowUpItem("Tell me more about Python")fu2 = FollowUpItem("Show me a JavaScript comparison")Example 2 — Clickable list:+root = Card([title, list])title = TextContent("Choose a topic", "large-heavy")list = ListBlock([item1, item2, item3])@@ -151,6 +200,7 @@ item2 = ListItem("Advanced features", "Deep dives into powerful capabilities.")item3 = ListItem("Troubleshooting", "Common issues and how to fix them.")Example 3 — Image carousel with consistent slides + follow-ups:+root = Card([header, carousel, followups])header = CardHeader("Featured Destinations", "Discover highlights and best time to visit")carousel = Carousel([[t1, img1, d1, tags1], [t2, img2, d2, tags2], [t3, img3, d3, tags3]], "card")@@ -171,22 +221,23 @@ fu1 = FollowUpItem("Show me only beach destinations")fu2 = FollowUpItem("Turn this into a comparison table")Example 4 — Form with validation:+root = Card([title, form])title = TextContent("Contact Us", "large-heavy")form = Form("contact", btns, [nameField, emailField, msgField])nameField = FormControl("Name", Input("name", "Your name", "text", { required: true, minLength: 2 }))emailField = FormControl("Email", Input("email", "[email protected]", "email", { required: true, email: true }))msgField = FormControl("Message", TextArea("message", "Tell us more...", 4, { required: true, minLength: 10 }))-btns = Buttons([Button("Submit", { type: "continue_conversation" }, "primary")])+btns = Buttons([Button("Submit", Action([@ToAssistant("Submit")]), "primary")])## Important Rules-- ALWAYS start with root = Card(...)-- Write statements in TOP-DOWN order: root → components → data (leverages hoisting for progressive streaming)-- Each statement on its own line-- No trailing text or explanations — output ONLY openui-lang code- When asked about data, generate realistic/plausible data- Choose components that best represent the content (tables for comparisons, charts for trends, forms for input, etc.)-- NEVER define a variable without referencing it from the tree. Every variable must be reachable from root, otherwise it will not render.++## Final Verification+Before finishing, walk your output and verify:+1. root = Card(...) is the FIRST line (for optimal streaming).+2. Every referenced name is defined. Every defined name (other than root) is reachable from root.- Every response is a single Card(children) — children stack vertically automatically. No layout params are needed on Card.- Card is the only layout container. Do NOT use Stack. Use Tabs to switch between sections, Carousel for horizontal scroll.diff --git a/docs/generated/playground-component-spec.json b/docs/generated/playground-component-spec.jsonnew file mode 100644index 000000000..c10423427--- /dev/null+++ b/docs/generated/playground-component-spec.json@@ -0,0 +1,372 @@+{+ "root": "Stack",+ "components": {+ "Card": {+ "signature": "Card(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps | Tabs | Carousel | Stack)[], variant?: \"card\" | \"sunk\" | \"clear\", direction?: \"row\" | \"column\", gap?: \"none\" | \"xs\" | \"s\" | \"m\" | \"l\" | \"xl\" | \"2xl\", align?: \"start\" | \"center\" | \"end\" | \"stretch\" | \"baseline\", justify?: \"start\" | \"center\" | \"end\" | \"between\" | \"around\" | \"evenly\", wrap?: boolean)",+ "description": "Styled container. variant: \"card\" (default, elevated) | \"sunk\" (recessed) | \"clear\" (transparent). Always full width. Accepts all Stack flex params (default: direction \"column\"). Cards flex to share space in row/wrap layouts."+ },+ "CardHeader": {+ "signature": "CardHeader(title?: string, subtitle?: string)",+ "description": "Header with optional title and subtitle"+ },+ "TextContent": {+ "signature": "TextContent(text: string, size?: \"small\" | \"default\" | \"large\" | \"small-heavy\" | \"large-heavy\")",+ "description": "Text block. Supports markdown. Optional size: \"small\" | \"default\" | \"large\" | \"small-heavy\" | \"large-heavy\"."+ },+ "MarkDownRenderer": {+ "signature": "MarkDownRenderer(textMarkdown: string, variant?: \"clear\" | \"card\" | \"sunk\")",+ "description": "Renders markdown text with optional container variant"+ },+ "Callout": {+ "signature": "Callout(variant: \"info\" | \"warning\" | \"error\" | \"success\" | \"neutral\", title: string, description: string, visible?: $binding<boolean>)",+ "description": "Callout banner. Optional visible is a reactive $boolean — auto-dismisses after 3s by setting $visible to false."+ },+ "TextCallout": {+ "signature": "TextCallout(variant?: \"neutral\" | \"info\" | \"warning\" | \"success\" | \"danger\", title?: string, description?: string)",+ "description": "Text callout with variant, title, and description"+ },+ "Image": {+ "signature": "Image(alt: string, src?: string)",+ "description": "Image with alt text and optional URL"+ },+ "ImageBlock": {+ "signature": "ImageBlock(src: string, alt?: string)",+ "description": "Image block with loading state"+ },+ "ImageGallery": {+ "signature": "ImageGallery(images: {src: string, alt?: string, details?: string}[])",+ "description": "Gallery grid of images with modal preview"+ },+ "CodeBlock": {+ "signature": "CodeBlock(language: string, codeString: string)",+ "description": "Syntax-highlighted code block"+ },+ "Table": {+ "signature": "Table(columns: Col[])",+ "description": "Data table — column-oriented. Each Col holds its own data array."+ },+ "Col": {+ "signature": "Col(label: string, data, type?: \"string\" | \"number\" | \"action\")",+ "description": "Column definition — holds label + data array"+ },+ "BarChart": {+ "signature": "BarChart(labels: string[], series: Series[], variant?: \"grouped\" | \"stacked\", xLabel?: string, yLabel?: string)",+ "description": "Vertical bars; use for comparing values across categories with one or more series"+ },+ "LineChart": {+ "signature": "LineChart(labels: string[], series: Series[], variant?: \"linear\" | \"natural\" | \"step\", xLabel?: string, yLabel?: string)",+ "description": "Lines over categories; use for trends and continuous data over time"+ },+ "AreaChart": {+ "signature": "AreaChart(labels: string[], series: Series[], variant?: \"linear\" | \"natural\" | \"step\", xLabel?: string, yLabel?: string)",+ "description": "Filled area under lines; use for cumulative totals or volume trends over time"+ },+ "RadarChart": {+ "signature": "RadarChart(labels: string[], series: Series[])",+ "description": "Spider/web chart; use for comparing multiple variables across one or more entities"+ },+ "HorizontalBarChart": {+ "signature": "HorizontalBarChart(labels: string[], series: Series[], variant?: \"grouped\" | \"stacked\", xLabel?: string, yLabel?: string)",+ "description": "Horizontal bars; prefer when category labels are long or for ranked lists"+ },+ "Series": {+ "signature": "Series(category: string, values: number[])",+ "description": "One data series"+ },+ "PieChart": {+ "signature": "PieChart(labels: string[], values: number[], variant?: \"pie\" | \"donut\")",+ "description": "Circular slices; use plucked arrays: PieChart(data.categories, data.values)"+ },+ "RadialChart": {+ "signature": "RadialChart(labels: string[], values: number[])",+ "description": "Radial bars; use plucked arrays: RadialChart(data.categories, data.values)"+ },+ "SingleStackedBarChart": {+ "signature": "SingleStackedBarChart(labels: string[], values: number[])",+ "description": "Single horizontal stacked bar; use plucked arrays: SingleStackedBarChart(data.categories, data.values)"+ },+ "Slice": {+ "signature": "Slice(category: string, value: number)",+ "description": "One slice with label and numeric value"+ },+ "ScatterChart": {+ "signature": "ScatterChart(datasets: ScatterSeries[], xLabel?: string, yLabel?: string)",+ "description": "X/Y scatter plot; use for correlations, distributions, and clustering"+ },+ "ScatterSeries": {+ "signature": "ScatterSeries(name: string, points: Point[])",+ "description": "Named dataset"+ },+ "Point": {+ "signature": "Point(x: number, y: number, z?: number)",+ "description": "Data point with numeric coordinates"+ },+ "Form": {+ "signature": "Form(name: string, buttons: Buttons, fields)",+ "description": "Form container with fields and explicit action buttons"+ },+ "FormControl": {+ "signature": "FormControl(label: string, input: Input | TextArea | Select | DatePicker | Slider | CheckBoxGroup | RadioGroup, hint?: string)",+ "description": "Field with label, input component, and optional hint text"+ },+ "Label": {+ "signature": "Label(text: string)",+ "description": "Text label"+ },+ "Input": {+ "signature": "Input(name: string, placeholder?: string, type?: \"text\" | \"email\" | \"password\" | \"number\" | \"url\", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)",+ "description": ""+ },+ "TextArea": {+ "signature": "TextArea(name: string, placeholder?: string, rows?: number, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)",+ "description": ""+ },+ "Select": {+ "signature": "Select(name: string, items: SelectItem[], placeholder?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)",+ "description": ""+ },+ "SelectItem": {+ "signature": "SelectItem(value: string, label: string)",+ "description": "Option for Select"+ },+ "DatePicker": {+ "signature": "DatePicker(name: string, mode?: \"single\" | \"range\", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?)",+ "description": ""+ },+ "Slider": {+ "signature": "Slider(name: string, variant: \"continuous\" | \"discrete\", min: number, max: number, step?: number, defaultValue?: number[], label?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<number[]>)",+ "description": "Numeric slider input; supports continuous and discrete (stepped) variants"+ },+ "CheckBoxGroup": {+ "signature": "CheckBoxGroup(name: string, items: CheckBoxItem[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?)",+ "description": ""+ },+ "CheckBoxItem": {+ "signature": "CheckBoxItem(label: string, description: string, name: string, defaultChecked?: boolean)",+ "description": ""+ },+ "RadioGroup": {+ "signature": "RadioGroup(name: string, items: RadioItem[], defaultValue?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)",+ "description": ""+ },+ "RadioItem": {+ "signature": "RadioItem(label: string, description: string, value: string)",+ "description": ""+ },+ "SwitchGroup": {+ "signature": "SwitchGroup(name: string, items: SwitchItem[], variant?: \"clear\" | \"card\" | \"sunk\", value?)",+ "description": "Group of switch toggles"+ },+ "SwitchItem": {+ "signature": "SwitchItem(label?: string, description?: string, name: string, defaultChecked?: boolean)",+ "description": "Individual switch toggle"+ },+ "Button": {+ "signature": "Button(label: string, action?: ActionExpression, variant?: \"primary\" | \"secondary\" | \"tertiary\", type?: \"normal\" | \"destructive\", size?: \"extra-small\" | \"small\" | \"medium\" | \"large\")",+ "description": "Clickable button"+ },+ "Buttons": {+ "signature": "Buttons(buttons: Button[], direction?: \"row\" | \"column\")",+ "description": "Group of Button components. direction: \"row\" (default) | \"column\"."+ },+ "Stack": {+ "signature": "Stack([children], direction?: \"row\" | \"column\", gap?: \"none\" | \"xs\" | \"s\" | \"m\" | \"l\" | \"xl\" | \"2xl\", align?: \"start\" | \"center\" | \"end\" | \"stretch\" | \"baseline\", justify?: \"start\" | \"center\" | \"end\" | \"between\" | \"around\" | \"evenly\", wrap?: boolean)",+ "description": "Flex container. direction: \"row\"|\"column\" (default \"column\"). gap: \"none\"|\"xs\"|\"s\"|\"m\"|\"l\"|\"xl\"|\"2xl\" (default \"m\"). align: \"start\"|\"center\"|\"end\"|\"stretch\"|\"baseline\". justify: \"start\"|\"center\"|\"end\"|\"between\"|\"around\"|\"evenly\"."+ },+ "Tabs": {+ "signature": "Tabs(items: TabItem[])",+ "description": "Tabbed container"+ },+ "TabItem": {+ "signature": "TabItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[])",+ "description": "value is unique id, trigger is tab label, content is array of components"+ },+ "Accordion": {+ "signature": "Accordion(items: AccordionItem[])",+ "description": "Collapsible sections"+ },+ "AccordionItem": {+ "signature": "AccordionItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[])",+ "description": "value is unique id, trigger is section title"+ },+ "Steps": {+ "signature": "Steps(items: StepsItem[])",+ "description": "Step-by-step guide"+ },+ "StepsItem": {+ "signature": "StepsItem(title: string, details: string)",+ "description": "title and details text for one step"+ },+ "Carousel": {+ "signature": "Carousel(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[][], variant?: \"card\" | \"sunk\")",+ "description": "Horizontal scrollable carousel"+ },+ "Separator": {+ "signature": "Separator(orientation?: \"horizontal\" | \"vertical\", decorative?: boolean)",+ "description": "Visual divider between content sections"+ },+ "TagBlock": {+ "signature": "TagBlock(tags: string[])",+ "description": "tags is an array of strings"+ },+ "Tag": {+ "signature": "Tag(text: string, icon?: string, size?: \"sm\" | \"md\" | \"lg\", variant?: \"neutral\" | \"info\" | \"success\" | \"warning\" | \"danger\")",+ "description": "Styled tag/badge with optional icon and variant"+ },+ "Modal": {+ "signature": "Modal(title: string, open?: $binding<boolean>, children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[], size?: \"sm\" | \"md\" | \"lg\")",+ "description": "Modal dialog. open is a reactive $boolean binding — set to true to open, X/Escape/backdrop auto-closes. Put Form with buttons inside children."+ }+ },+ "componentGroups": [+ {+ "name": "Layout",+ "components": [+ "Stack",+ "Tabs",+ "TabItem",+ "Accordion",+ "AccordionItem",+ "Steps",+ "StepsItem",+ "Carousel",+ "Separator",+ "Modal"+ ],+ "notes": [+ "- For grid-like layouts, use Stack with direction \"row\" and wrap set to true.",+ "- Prefer justify \"start\" (or omit justify) with wrap=true for stable columns instead of uneven gutters.",+ "- Use nested Stacks when you need explicit rows/sections.",+ "- Show/hide sections: $editId != \"\" ? Card([editForm]) : null",+ "- Modal: Modal(\"Title\", $showModal, [content]) — $showModal is boolean, X/Escape auto-closes. Put Form with its own buttons inside children.",+ "- Use Tabs for alternative views (chart types, data sections) — no $variable needed",+ "- Shared filter across Tabs: same $days binding in Query args works across all TabItems"+ ]+ },+ {+ "name": "Content",+ "components": [+ "Card",+ "CardHeader",+ "TextContent",+ "MarkDownRenderer",+ "Callout",+ "TextCallout",+ "Image",+ "ImageBlock",+ "ImageGallery",+ "CodeBlock"+ ],+ "notes": [+ "- Use Cards to group related KPIs or sections. Stack with direction \"row\" for side-by-side layouts.",+ "- Success toast: Callout(\"success\", \"Saved\", \"Done.\", $showSuccess) — use @Set($showSuccess, true) in save action, auto-dismisses after 3s. For errors: result.status == \"error\" ? Callout(\"error\", \"Failed\", result.error) : null",+ "- KPI card: Card([TextContent(\"Label\", \"small\"), TextContent(\"\" + @Count(@Filter(data.rows, \"field\", \"==\", \"value\")), \"large-heavy\")])"+ ]+ },+ {+ "name": "Tables",+ "components": [+ "Table",+ "Col"+ ],+ "notes": [+ "- Table is COLUMN-oriented: Table([Col(\"Label\", dataArray), Col(\"Count\", countArray, \"number\")]). Use array pluck for data: data.rows.fieldName",+ "- Col data can be component arrays for styled cells: Col(\"Status\", @Each(data.rows, \"item\", Tag(item.status, null, \"sm\", item.status == \"open\" ? \"success\" : \"danger\")))",+ "- Row actions: Col(\"Actions\", @Each(data.rows, \"t\", Button(\"Edit\", Action([@Set($showEdit, true), @Set($editId, t.id)]))))",+ "- Sortable: sorted = @Sort(data.rows, $sortField, \"desc\"). Bind $sortField to Select. Use sorted.fieldName for Col data",+ "- Searchable: filtered = @Filter(data.rows, \"title\", \"contains\", $search). Bind $search to Input",+ "- Chain sort + filter: filtered = @Filter(...) then sorted = @Sort(filtered, ...) — use sorted for both Table and Charts",+ "- Empty state: @Count(data.rows) > 0 ? Table([...]) : TextContent(\"No data yet\")"+ ]+ },+ {+ "name": "Charts (2D)",+ "components": [+ "BarChart",+ "LineChart",+ "AreaChart",+ "RadarChart",+ "HorizontalBarChart",+ "Series"+ ],+ "notes": [+ "- Charts accept column arrays: LineChart(labels, [Series(\"Name\", values)]). Use array pluck: LineChart(data.rows.day, [Series(\"Views\", data.rows.views)])",+ "- Use Cards to wrap charts with CardHeader for titled sections",+ "- Chart + Table from same source: use @Sort or @Filter result for both LineChart and Table Col data",+ "- Multiple chart views: use Tabs — Tabs([TabItem(\"line\", \"Line\", [LineChart(...)]), TabItem(\"bar\", \"Bar\", [BarChart(...)])])"+ ]+ },+ {+ "name": "Charts (1D)",+ "components": [+ "PieChart",+ "RadialChart",+ "SingleStackedBarChart",+ "Slice"+ ],+ "notes": [+ "- PieChart and BarChart need NUMBERS, not objects. For list data, use @Count(@Filter(...)) to aggregate:",+ "- PieChart from list: `PieChart([\"Low\", \"Med\", \"High\"], [@Count(@Filter(data.rows, \"priority\", \"==\", \"low\")), @Count(@Filter(data.rows, \"priority\", \"==\", \"medium\")), @Count(@Filter(data.rows, \"priority\", \"==\", \"high\"))], \"donut\")`",+ "- KPI from count: `TextContent(\"\" + @Count(@Filter(data.rows, \"status\", \"==\", \"open\")), \"large-heavy\")`"+ ]+ },+ {+ "name": "Charts (Scatter)",+ "components": [+ "ScatterChart",+ "ScatterSeries",+ "Point"+ ]+ },+ {+ "name": "Forms",+ "components": [+ "Form",+ "FormControl",+ "Label",+ "Input",+ "TextArea",+ "Select",+ "SelectItem",+ "DatePicker",+ "Slider",+ "CheckBoxGroup",+ "CheckBoxItem",+ "RadioGroup",+ "RadioItem",+ "SwitchGroup",+ "SwitchItem"+ ],+ "notes": [+ "- For Form fields, define EACH FormControl as its own reference — do NOT inline all controls in one array. This allows progressive field-by-field streaming.",+ "- NEVER nest Form inside Form — each Form should be a standalone container.",+ "- Form requires explicit buttons. Always pass a Buttons(...) reference as the third Form argument.",+ "- rules is an optional object: {required: true, email: true, minLength: 8, maxLength: 100}",+ "- Available rules: required, email, min, max, minLength, maxLength, pattern, url, numeric",+ "- The renderer shows error messages automatically — do NOT generate error text in the UI",+ "- Conditional fields: $country == \"US\" ? stateField : $country == \"UK\" ? postcodeField : addressField",+ "- Edit form in Modal: Modal(\"Edit\", $showEdit, [Form(\"edit\", Buttons([saveBtn, cancelBtn]), [fields...])]). Save button should include @Set($showEdit, false) to close modal."+ ]+ },+ {+ "name": "Buttons",+ "components": [+ "Button",+ "Buttons"+ ],+ "notes": [+ "- Toggle in @Each: @Each(rows, \"t\", Button(t.status == \"open\" ? \"Close\" : \"Reopen\", Action([...])))"+ ]+ },+ {+ "name": "Data Display",+ "components": [+ "TagBlock",+ "Tag"+ ],+ "notes": [+ "- Color-mapped Tag: Tag(value, null, \"sm\", value == \"high\" ? \"danger\" : value == \"medium\" ? \"warning\" : \"neutral\")"+ ]+ }+ ]+}diff --git a/docs/generated/playground-system-prompt.txt b/docs/generated/playground-system-prompt.txtindex d873ba87f..2e87a5674 100644--- a/docs/generated/playground-system-prompt.txt+++ b/docs/generated/playground-system-prompt.txt@@ -4,18 +4,18 @@ You are an AI assistant that responds using openui-lang, a declarative UI langua1. Each statement is on its own line: `identifier = Expression`2. `root` is the entry point — every program must define `root = Stack(...)`-3. Expressions are: strings ("..."), numbers, booleans (true/false), arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)+3. Expressions are: strings ("..."), numbers, booleans (true/false), null, arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)4. Use references for readability: define `name = ...` on one line, then use `name` later5. EVERY variable (except root) MUST be referenced by at least one other variable. Unreferenced variables are silently dropped and will NOT render. Always include defined variables in their parent's children/items array.-6. Arguments are POSITIONAL (order matters, not names)+6. Arguments are POSITIONAL (order matters, not names). Write `Stack([children], "row", "l")` NOT `Stack([children], direction: "row", gap: "l")` — colon syntax is NOT supported and silently breaks7. Optional arguments can be omitted from the end-8. No operators, no logic, no variables — only declarations-9. Strings use double quotes with backslash escaping+- Strings use double quotes with backslash escaping## Component SignaturesArguments marked with ? are optional. Sub-components can be inline or referenced; prefer references for better streaming.-The `action` prop type accepts: ContinueConversation (sends message to LLM), OpenUrl (navigates to URL), or Custom (app-defined).+Props typed `ActionExpression` accept an Action([@steps...]) expression. See the Action section for available steps (@ToAssistant, @OpenUrl).+Props marked `$binding<type>` accept a `$variable` reference for two-way binding.### LayoutStack([children], direction?: "row" | "column", gap?: "none" | "xs" | "s" | "m" | "l" | "xl" | "2xl", align?: "start" | "center" | "end" | "stretch" | "baseline", justify?: "start" | "center" | "end" | "between" | "around" | "evenly", wrap?: boolean) — Flex container. direction: "row"|"column" (default "column"). gap: "none"|"xs"|"s"|"m"|"l"|"xl"|"2xl" (default "m"). align: "start"|"center"|"end"|"stretch"|"baseline". justify: "start"|"center"|"end"|"between"|"around"|"evenly".@@ -27,25 +27,40 @@ Steps(items: StepsItem[]) — Step-by-step guideStepsItem(title: string, details: string) — title and details text for one stepCarousel(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[][], variant?: "card" | "sunk") — Horizontal scrollable carouselSeparator(orientation?: "horizontal" | "vertical", decorative?: boolean) — Visual divider between content sections+Modal(title: string, open?: $binding<boolean>, children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[], size?: "sm" | "md" | "lg") — Modal dialog. open is a reactive $boolean binding — set to true to open, X/Escape/backdrop auto-closes. Put Form with buttons inside children.- For grid-like layouts, use Stack with direction "row" and wrap set to true.- Prefer justify "start" (or omit justify) with wrap=true for stable columns instead of uneven gutters.- Use nested Stacks when you need explicit rows/sections.+- Show/hide sections: $editId != "" ? Card([editForm]) : null+- Modal: Modal("Title", $showModal, [content]) — $showModal is boolean, X/Escape auto-closes. Put Form with its own buttons inside children.+- Use Tabs for alternative views (chart types, data sections) — no $variable needed+- Shared filter across Tabs: same $days binding in Query args works across all TabItems### ContentCard(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps | Tabs | Carousel | Stack)[], variant?: "card" | "sunk" | "clear", direction?: "row" | "column", gap?: "none" | "xs" | "s" | "m" | "l" | "xl" | "2xl", align?: "start" | "center" | "end" | "stretch" | "baseline", justify?: "start" | "center" | "end" | "between" | "around" | "evenly", wrap?: boolean) — Styled container. variant: "card" (default, elevated) | "sunk" (recessed) | "clear" (transparent). Always full width. Accepts all Stack flex params (default: direction "column"). Cards flex to share space in row/wrap layouts.CardHeader(title?: string, subtitle?: string) — Header with optional title and subtitleTextContent(text: string, size?: "small" | "default" | "large" | "small-heavy" | "large-heavy") — Text block. Supports markdown. Optional size: "small" | "default" | "large" | "small-heavy" | "large-heavy".MarkDownRenderer(textMarkdown: string, variant?: "clear" | "card" | "sunk") — Renders markdown text with optional container variant-Callout(variant: "info" | "warning" | "error" | "success" | "neutral", title: string, description: string) — Callout banner with variant, title, and description+Callout(variant: "info" | "warning" | "error" | "success" | "neutral", title: string, description: string, visible?: $binding<boolean>) — Callout banner. Optional visible is a reactive $boolean — auto-dismisses after 3s by setting $visible to false.TextCallout(variant?: "neutral" | "info" | "warning" | "success" | "danger", title?: string, description?: string) — Text callout with variant, title, and descriptionImage(alt: string, src?: string) — Image with alt text and optional URLImageBlock(src: string, alt?: string) — Image block with loading stateImageGallery(images: {src: string, alt?: string, details?: string}[]) — Gallery grid of images with modal previewCodeBlock(language: string, codeString: string) — Syntax-highlighted code block+- Use Cards to group related KPIs or sections. Stack with direction "row" for side-by-side layouts.+- Success toast: Callout("success", "Saved", "Done.", $showSuccess) — use @Set($showSuccess, true) in save action, auto-dismisses after 3s. For errors: result.status == "error" ? Callout("error", "Failed", result.error) : null+- KPI card: Card([TextContent("Label", "small"), TextContent("" + @Count(@Filter(data.rows, "field", "==", "value")), "large-heavy")])### Tables-Table(columns: Col[], rows: (string | number | boolean)[][]) — Data table-Col(label: string, type?: "string" | "number" | "action") — Column definition+Table(columns: Col[]) — Data table — column-oriented. Each Col holds its own data array.+Col(label: string, data, type?: "string" | "number" | "action") — Column definition — holds label + data array+- Table is COLUMN-oriented: Table([Col("Label", dataArray), Col("Count", countArray, "number")]). Use array pluck for data: data.rows.fieldName+- Col data can be component arrays for styled cells: Col("Status", @Each(data.rows, "item", Tag(item.status, null, "sm", item.status == "open" ? "success" : "danger")))+- Row actions: Col("Actions", @Each(data.rows, "t", Button("Edit", Action([@Set($showEdit, true), @Set($editId, t.id)]))))+- Sortable: sorted = @Sort(data.rows, $sortField, "desc"). Bind $sortField to Select. Use sorted.fieldName for Col data+- Searchable: filtered = @Filter(data.rows, "title", "contains", $search). Bind $search to Input+- Chain sort + filter: filtered = @Filter(...) then sorted = @Sort(filtered, ...) — use sorted for both Table and Charts+- Empty state: @Count(data.rows) > 0 ? Table([...]) : TextContent("No data yet")### Charts (2D)BarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Vertical bars; use for comparing values across categories with one or more series@@ -54,12 +69,19 @@ AreaChart(labels: string[], series: Series[], variant?: "linear" | "natural" | "RadarChart(labels: string[], series: Series[]) — Spider/web chart; use for comparing multiple variables across one or more entitiesHorizontalBarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Horizontal bars; prefer when category labels are long or for ranked listsSeries(category: string, values: number[]) — One data series+- Charts accept column arrays: LineChart(labels, [Series("Name", values)]). Use array pluck: LineChart(data.rows.day, [Series("Views", data.rows.views)])+- Use Cards to wrap charts with CardHeader for titled sections+- Chart + Table from same source: use @Sort or @Filter result for both LineChart and Table Col data+- Multiple chart views: use Tabs — Tabs([TabItem("line", "Line", [LineChart(...)]), TabItem("bar", "Bar", [BarChart(...)])])### Charts (1D)-PieChart(slices: Slice[], variant?: "pie" | "donut") — Circular slices showing part-to-whole proportions; supports pie and donut variants-RadialChart(slices: Slice[]) — Radial bars showing proportional distribution across named segments-SingleStackedBarChart(slices: Slice[]) — Single horizontal stacked bar; use for showing part-to-whole proportions in one row+PieChart(labels: string[], values: number[], variant?: "pie" | "donut") — Circular slices; use plucked arrays: PieChart(data.categories, data.values)+RadialChart(labels: string[], values: number[]) — Radial bars; use plucked arrays: RadialChart(data.categories, data.values)+SingleStackedBarChart(labels: string[], values: number[]) — Single horizontal stacked bar; use plucked arrays: SingleStackedBarChart(data.categories, data.values)Slice(category: string, value: number) — One slice with label and numeric value+- PieChart and BarChart need NUMBERS, not objects. For list data, use @Count(@Filter(...)) to aggregate:+- PieChart from list: `PieChart(["Low", "Med", "High"], [@Count(@Filter(data.rows, "priority", "==", "low")), @Count(@Filter(data.rows, "priority", "==", "medium")), @Count(@Filter(data.rows, "priority", "==", "high"))], "donut")`+- KPI from count: `TextContent("" + @Count(@Filter(data.rows, "status", "==", "open")), "large-heavy")`### Charts (Scatter)ScatterChart(datasets: ScatterSeries[], xLabel?: string, yLabel?: string) — X/Y scatter plot; use for correlations, distributions, and clustering@@ -70,32 +92,80 @@ Point(x: number, y: number, z?: number) — Data point with numeric coordinatesForm(name: string, buttons: Buttons, fields) — Form container with fields and explicit action buttonsFormControl(label: string, input: Input | TextArea | Select | DatePicker | Slider | CheckBoxGroup | RadioGroup, hint?: string) — Field with label, input component, and optional hint textLabel(text: string) — Text label-Input(name: string, placeholder?: string, type?: "text" | "email" | "password" | "number" | "url", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})-TextArea(name: string, placeholder?: string, rows?: number, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})-Select(name: string, items: SelectItem[], placeholder?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})+Input(name: string, placeholder?: string, type?: "text" | "email" | "password" | "number" | "url", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)+TextArea(name: string, placeholder?: string, rows?: number, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)+Select(name: string, items: SelectItem[], placeholder?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)SelectItem(value: string, label: string) — Option for Select-DatePicker(name: string, mode: "single" | "range", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})-Slider(name: string, variant: "continuous" | "discrete", min: number, max: number, step?: number, defaultValue?: number[], label?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}) — Numeric slider input; supports continuous and discrete (stepped) variants-CheckBoxGroup(name: string, items: CheckBoxItem[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})+DatePicker(name: string, mode?: "single" | "range", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?)+Slider(name: string, variant: "continuous" | "discrete", min: number, max: number, step?: number, defaultValue?: number[], label?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<number[]>) — Numeric slider input; supports continuous and discrete (stepped) variants+CheckBoxGroup(name: string, items: CheckBoxItem[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?)CheckBoxItem(label: string, description: string, name: string, defaultChecked?: boolean)-RadioGroup(name: string, items: RadioItem[], defaultValue?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})+RadioGroup(name: string, items: RadioItem[], defaultValue?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)RadioItem(label: string, description: string, value: string)-SwitchGroup(name: string, items: SwitchItem[], variant?: "clear" | "card" | "sunk") — Group of switch toggles+SwitchGroup(name: string, items: SwitchItem[], variant?: "clear" | "card" | "sunk", value?) — Group of switch togglesSwitchItem(label?: string, description?: string, name: string, defaultChecked?: boolean) — Individual switch toggle- For Form fields, define EACH FormControl as its own reference — do NOT inline all controls in one array. This allows progressive field-by-field streaming.- NEVER nest Form inside Form — each Form should be a standalone container.- Form requires explicit buttons. Always pass a Buttons(...) reference as the third Form argument.-- rules is an optional array of validation strings: ["required", "email", "min:8", "maxLength:100"]-- Available rules: required, email, min:N, max:N, minLength:N, maxLength:N, pattern:REGEX, url, numeric+- rules is an optional object: {required: true, email: true, minLength: 8, maxLength: 100}+- Available rules: required, email, min, max, minLength, maxLength, pattern, url, numeric- The renderer shows error messages automatically — do NOT generate error text in the UI+- Conditional fields: $country == "US" ? stateField : $country == "UK" ? postcodeField : addressField+- Edit form in Modal: Modal("Edit", $showEdit, [Form("edit", Buttons([saveBtn, cancelBtn]), [fields...])]). Save button should include @Set($showEdit, false) to close modal.### Buttons-Button(label: string, action?: {type: "open_url", url: string} | {type: "continue_conversation", context?: string} | {type: string, params?}, variant?: "primary" | "secondary" | "tertiary", type?: "normal" | "destructive", size?: "extra-small" | "small" | "medium" | "large") — Clickable button+Button(label: string, action?: ActionExpression, variant?: "primary" | "secondary" | "tertiary", type?: "normal" | "destructive", size?: "extra-small" | "small" | "medium" | "large") — Clickable buttonButtons(buttons: Button[], direction?: "row" | "column") — Group of Button components. direction: "row" (default) | "column".+- Toggle in @Each: @Each(rows, "t", Button(t.status == "open" ? "Close" : "Reopen", Action([...])))### Data DisplayTagBlock(tags: string[]) — tags is an array of stringsTag(text: string, icon?: string, size?: "sm" | "md" | "lg", variant?: "neutral" | "info" | "success" | "warning" | "danger") — Styled tag/badge with optional icon and variant+- Color-mapped Tag: Tag(value, null, "sm", value == "high" ? "danger" : value == "medium" ? "warning" : "neutral")++## Built-in Functions++Data functions prefixed with `@` to distinguish from components. These are the ONLY functions available — do NOT invent new ones.+Use @-prefixed built-in functions (@Count, @Sum, @Avg, @Min, @Max, @Round) on Query results — do NOT hardcode computed values.++@Count(array) → number — Returns array length+@First(array) → element — Returns first element of array+@Last(array) → element — Returns last element of array+@Sum(numbers[]) → number — Sum of numeric array+@Avg(numbers[]) → number — Average of numeric array+@Min(numbers[]) → number — Minimum value in array+@Max(numbers[]) → number — Maximum value in array+@Sort(array, field, direction?) → sorted array — Sort array by field. Direction: "asc" (default) or "desc"+@Filter(array, field, operator: "==" | "!=" | ">" | "<" | ">=" | "<=" | "contains", value) → filtered array — Filter array by field value+@Round(number, decimals?) → number — Round to N decimal places (default 0)+@Abs(number) → number — Absolute value+@Floor(number) → number — Round down to nearest integer+@Ceil(number) → number — Round up to nearest integer+@Each(array, varName, template) — Evaluate template for each element. varName is the loop variable — use it ONLY inside the template expression (inline). Do NOT create a separate statement for the template.++Builtins compose — output of one is input to the next:+`@Count(@Filter(data.rows, "field", "==", "val"))` for KPIs/chart values, `@Round(@Avg(data.rows.score), 1)`, `@Each(data.rows, "item", Comp(item.field))` for per-item rendering.+Array pluck: `data.rows.field` extracts a field from every row → use with @Sum, @Avg, charts, tables.++IMPORTANT @Each rule: The loop variable (e.g. "item") is ONLY available inside the @Each template expression. Always inline the template — do NOT extract it to a separate statement.+CORRECT: `Col("Actions", @Each(rows, "t", Button("Edit", Action([@Set($id, t.id)]))))`+WRONG: `myBtn = Button("Edit", Action([@Set($id, t.id)]))` then `Col("Actions", @Each(rows, "t", myBtn))` — t is undefined in myBtn.++## Action — Button Behavior++Action([@steps...]) wires button clicks to operations. Steps are @-prefixed built-in actions. Steps execute in order.+Buttons without an explicit Action prop automatically send their label to the assistant (equivalent to Action([@ToAssistant(label)])).++Available steps:+- @ToAssistant("message") — Send a message to the assistant (for conversational buttons like "Tell me more", "Explain this")+- @OpenUrl("https://...") — Navigate to a URL++Example — simple nav:+```+viewBtn = Button("View", Action([@OpenUrl("https://example.com")]))+```++- Action can be assigned to a variable or inlined: Button("Go", onSubmit) and Button("Go", Action([...])) both work## Hoisting & Streaming (CRITICAL)@@ -105,21 +175,26 @@ During streaming, the output is re-parsed on every chunk. Undefined references a**Recommended statement order for optimal streaming:**1. `root = Stack(...)` — UI shell appears immediately-2. Component definitions — fill in as they stream-3. Data values — leaf content last+2. $variable declarations — state ready for bindings+3. Query statements — defaults resolve immediately so components render with data+4. Component definitions — fill in with data already available+5. Data values — leaf content lastAlways write the root = Stack(...) statement first so the UI shell appears immediately, even before child data has streamed in.## Examples-Example 1 — Table:+Example 1 — Table (column-oriented):+root = Stack([title, tbl])title = TextContent("Top Languages", "large-heavy")-tbl = Table(cols, rows)-cols = [Col("Language", "string"), Col("Users (M)", "number"), Col("Year", "number")]-rows = [["Python", 15.7, 1991], ["JavaScript", 14.2, 1995], ["Java", 12.1, 1995], ["TypeScript", 8.5, 2012], ["Go", 5.2, 2009]]+tbl = Table([Col("Language", langs), Col("Users (M)", users), Col("Year", years)])+langs = ["Python", "JavaScript", "Java", "TypeScript", "Go"]+users = [15.7, 14.2, 12.1, 8.5, 5.2]+years = [1991, 1995, 1995, 2012, 2009]Example 2 — Bar chart:+root = Stack([title, chart])title = TextContent("Q4 Revenue", "large-heavy")chart = BarChart(labels, [s1, s2], "grouped")@@ -128,6 +203,7 @@ s1 = Series("Product A", [120, 150, 180])s2 = Series("Product B", [90, 110, 140])Example 3 — Form with validation:+root = Stack([title, form])title = TextContent("Contact Us", "large-heavy")form = Form("contact", btns, [nameField, emailField, countryField, msgField])@@ -136,9 +212,10 @@ emailField = FormControl("Email", Input("email", "[email protected]", "email", { rcountryField = FormControl("Country", Select("country", countryOpts, "Select...", { required: true }))msgField = FormControl("Message", TextArea("message", "Tell us more...", 4, { required: true, minLength: 10 }))countryOpts = [SelectItem("us", "United States"), SelectItem("uk", "United Kingdom"), SelectItem("de", "Germany")]-btns = Buttons([Button("Submit", { type: "continue_conversation" }, "primary"), Button("Cancel", { type: "continue_conversation" }, "secondary")])+btns = Buttons([Button("Submit", Action([@ToAssistant("Submit")]), "primary"), Button("Cancel", Action([@ToAssistant("Cancel")]), "secondary")])Example 4 — Tabs with mixed content:+root = Stack([title, tabs])title = TextContent("React vs Vue", "large-heavy")tabs = Tabs([tabReact, tabVue])@@ -148,10 +225,10 @@ reactContent = [TextContent("React is a library by Meta for building UIs."), CalvueContent = [TextContent("Vue is a progressive framework by Evan You."), Callout("success", "Tip", "Vue has a gentle learning curve.")]## Important Rules-- ALWAYS start with root = Stack(...)-- Write statements in TOP-DOWN order: root → components → data (leverages hoisting for progressive streaming)-- Each statement on its own line-- No trailing text or explanations — output ONLY openui-lang code- When asked about data, generate realistic/plausible data- Choose components that best represent the content (tables for comparisons, charts for trends, forms for input, etc.)-- NEVER define a variable without referencing it from the tree. Every variable must be reachable from root, otherwise it will not render.++## Final Verification+Before finishing, walk your output and verify:+1. root = Stack(...) is the FIRST line (for optimal streaming).+2. Every referenced name is defined. Every defined name (other than root) is reachable from root.diff --git a/docs/imports/HomeIllustrationCode.tsx b/docs/imports/HomeIllustrationCode.tsxnew file mode 100644index 000000000..519a0268f--- /dev/null+++ b/docs/imports/HomeIllustrationCode.tsx@@ -0,0 +1,43 @@+import { Highlight, themes } from "prism-react-renderer";++type HomeIllustrationLanguage = "tsx" | "typescript" | "javascript";++export function HomeIllustrationCode({+ code,+ language = "tsx",+ className,+}: {+ code: string;+ language?: HomeIllustrationLanguage;+ className?: string;+}) {+ return (+ <Highlight theme={themes.vsDark} code={code.trimEnd()} language={language}>+ {({ className: highlightClassName, style, tokens, getLineProps, getTokenProps }) => (+ <pre+ className={`${highlightClassName} ${className ?? ""}`.trim()}+ style={{+ ...style,+ margin: 0,+ background: "transparent",+ fontFamily: "var(--font-geist-mono)",+ fontSize: "0.7em",+ lineHeight: 1.5,+ whiteSpace: "pre-wrap",+ overflow: "hidden",+ }}+ >+ <code>+ {tokens.map((line, index) => (+ <div key={index} {...getLineProps({ line })}>+ {line.map((token, tokenIndex) => (+ <span key={tokenIndex} {...getTokenProps({ token })} />+ ))}+ </div>+ ))}+ </code>+ </pre>+ )}+ </Highlight>+ );+}diff --git a/docs/imports/LlmRespondsInOpenUiLang.tsx b/docs/imports/LlmRespondsInOpenUiLang.tsxindex 3378cb559..c7aa4fe87 100644--- a/docs/imports/LlmRespondsInOpenUiLang.tsx+++ b/docs/imports/LlmRespondsInOpenUiLang.tsx@@ -1,8 +1,29 @@+import { HomeIllustrationCode } from "./HomeIllustrationCode";import svgPaths from "./svg-l2c2kzuful";const hotelPlazaImg = "/images/home/706ccb488b69a5bdb06bdd002656a2fdfb017071.png";const hotelGeorgeVImg = "/images/home/6dea3a71b902a0282d8518928f3b06373b617aba.png";const hotelShangriLaImg = "/images/home/d781d9c958cc5cf8f3fc5fd61562ebcf0c7ba0a5.png";+const OPENUI_LANG_CODE = `root = Carousel([c1, c2, c3])+c1 = CarouselCard(+ "Hotel Plaza Athenee",+ "Haute couture suites; courtyard dining; Dior spa.",+ "https://images.example.com/plaza.jpg",+ "Book"+)+c2 = CarouselCard(+ "Four Seasons George V",+ "Landmark hotel with opulent rooms and spa.",+ "https://images.example.com/george-v.jpg",+ "Book"+)+c3 = CarouselCard(+ "Shangri-La Hotel",+ "Stunning Eiffel Tower views and Michelin dining.",+ "https://images.example.com/shangri-la.jpg",+ "Book"+)`;+type CardPreviewData = {imageSrc: string;tag: string;@@ -39,25 +60,11 @@ function Group() {return (<div className="absolute contents left-[49px] top-[48px]"><div className="absolute bg-black h-[290px] left-[49px] rounded-[16px] top-[48px] w-[443px]" />- <p className="absolute font-['Andale_Mono:Regular',sans-serif] h-[198px] leading-none left-[73px] not-italic text-[10px] text-white top-[74px] w-[254px] whitespace-pre-wrap">{`root = Carousel([c1, c2, c3])-c1 = CarouselCard(- "Hotel Plaza Athenee",- "Haute couture suites; courtyard dining; Dior spa.",- "https://images.example.com/plaza.jpg",- "Book"-)-c2 = CarouselCard(- "Four Seasons George V",- "Landmark hotel with opulent rooms and spa.",- "https://images.example.com/george-v.jpg",- "Book"-)-c3 = CarouselCard(- "Shangri-La Hotel",- "Stunning Eiffel Tower views and Michelin dining.",- "https://images.example.com/shangri-la.jpg",- "Book"-)`}</p>+ <HomeIllustrationCode+ className="absolute h-[198px] left-[73px] text-[10px] top-[74px] w-[254px]"+ code={OPENUI_LANG_CODE}+ language="javascript"+ /><div className="absolute bg-gradient-to-b from-[rgba(0,0,0,0)] h-[65px] left-[60px] to-black top-[272px] w-[285px]" /></div>);@@ -380,9 +387,6 @@ export default function LlmRespondsInOpenUiLang() {</div></div><Group2 />- <p className="absolute font-['Geist_Mono:Medium',sans-serif] font-medium leading-none left-[58px] text-[12px] text-[rgba(0,0,0,0.4)] top-[366px]">- OPENUI LANG (TOKEN EFFICIENT)- </p></div>);}diff --git a/docs/imports/OpenUiGeneratesSchema.tsx b/docs/imports/OpenUiGeneratesSchema.tsxindex b361ce8be..f794b5649 100644--- a/docs/imports/OpenUiGeneratesSchema.tsx+++ b/docs/imports/OpenUiGeneratesSchema.tsx@@ -1,5 +1,16 @@+import { HomeIllustrationCode } from "./HomeIllustrationCode";import svgPaths from "./svg-pr6qxiizdt";+const SYSTEM_PROMPT_CODE = `# generate system prompt from library+npx @openuidev/cli@latest generate ./src/library.ts++# use in your backend+const completion = await client.chat.completions.create({+ model: "gpt-5.2",+ stream: true,+ messages: [{ role: "system", content: systemPrompt }, ...messages]+})`;+function Group() {return (<div className="absolute contents left-[49px] top-[48px]">@@ -13,15 +24,11 @@ function Group() {<path d={svgPaths.p1bd62700} fill="var(--fill-0, black)" id="Rectangle 34662625" /></svg></div>- <p className="absolute font-['Andale_Mono:Regular',sans-serif] h-[262px] leading-none left-[73px] not-italic text-[10px] text-white top-[71px] w-[254px] whitespace-pre-wrap">{`# generate system prompt from library-npx @openuidev/cli@latest generate ./src/library.ts--# use in your backend-const completion = await client.chat.completions.create({- model: "gpt-5.2",- stream: true,- messages: [{ role: "system", content: systemPrompt }, ...messages]-})`}</p>+ <HomeIllustrationCode+ className="absolute h-[262px] left-[73px] text-[10px] top-[71px] w-[254px]"+ code={SYSTEM_PROMPT_CODE}+ language="typescript"+ /><div className="absolute bg-gradient-to-b from-[rgba(0,0,0,0)] h-[64px] left-[60px] to-black top-[272px] w-[285px]" /></div>);@@ -176,9 +183,6 @@ export default function OpenUiGeneratesSchema() {><Group /><Frame2 />- <p className="absolute font-['Geist_Mono:Medium',sans-serif] font-medium leading-none left-[58px] text-[12px] text-[rgba(0,0,0,0.4)] top-[366px]">- SEND SYSTEM PROMPT TO LLM- </p></div>);}diff --git a/docs/imports/YouRegisterComponents-43-365.tsx b/docs/imports/YouRegisterComponents-43-365.tsxindex 83807bee7..01fe3fb8b 100644--- a/docs/imports/YouRegisterComponents-43-365.tsx+++ b/docs/imports/YouRegisterComponents-43-365.tsx@@ -1,6 +1,35 @@+import { HomeIllustrationCode } from "./HomeIllustrationCode";import svgPaths from "./svg-7fdz4sm9ln";const hotelPlazaImg = "/images/home/706ccb488b69a5bdb06bdd002656a2fdfb017071.png";+const LIBRARY_CODE = `import { z } from "zod"+import { Carousel, CarouselCard } from "components/Carousel"+import { defineComponent, createLibrary } from "@openuidev/react-lang"++const CarouselCard = defineComponent({+ name: "CarouselCard",+ props: z.object({+ title: z.string(),+ description: z.string().optional(),+ imageUrl: z.string().url(),+ ctaLabel: z.string(),+ }),+ component: ({ props }) => <CarouselCard {...props} />,+})++const Carousel = defineComponent({+ name: "Carousel",+ props: z.object({+ cards: z.array(CarouselCard.ref),+ }),+ component: ({ props }) => <Carousel {...props} />,+})++export const library = createLibrary({+ root: "Carousel",+ components: [Carousel, CarouselCard],+})`;+function Frame() {return (<div className="aspect-[296/196] bg-[#ffb4b4] overflow-clip relative rounded-[8.663px] shrink-0 w-full">@@ -132,37 +161,11 @@ export default function YouRegisterComponents() {data-name="image 4"/><div className="absolute bg-black h-[350px] left-[49px] rounded-[16px] top-[48px] w-[443px]" />- <p className="absolute font-['Andale_Mono:Regular',sans-serif] h-[262px] leading-none left-[73px] not-italic text-[10px] text-white top-[71px] w-[254px] whitespace-pre-wrap">{`-import { z } from "zod"-import { Carousel, CarouselCard } from "components/Carousel"-import { defineComponent, createLibrary } from "@openuidev/react-lang"--const CarouselCard = defineComponent({- name: "CarouselCard",- props: z.object({- title: z.string(),- description: z.string().optional(),- imageUrl: z.string().url(),- ctaLabel: z.string(),- }),- component: ({ props }) => <CarouselCard {...props} />,-})--const Carousel = defineComponent({- name: "Carousel",- props: z.object({- cards: z.array(CarouselCard.ref),- }),- component: ({ props }) => <Carousel {...props} />,-})--export const library = createLibrary({- root: "Carousel",- components: [Carousel, CarouselCard],-})`}</p>- <p className="absolute font-['Geist_Mono:Medium',sans-serif] font-medium leading-none left-[58px] text-[12px] text-[rgba(0,0,0,0.4)] top-[366px]">- DEFINE COMPONENT + LIBRARY- </p>+ <HomeIllustrationCode+ className="absolute h-[262px] left-[73px] text-[10px] top-[71px] w-[254px]"+ code={LIBRARY_CODE}+ language="tsx"+ /><Frame2 /></div>);diff --git a/docs/package.json b/docs/package.jsonindex 676daa44e..c1d2d8cad 100644--- a/docs/package.json+++ b/docs/package.json@@ -3,7 +3,7 @@"version": "0.0.0","private": true,"scripts": {- "generate:prompts": "pnpm --filter @openuidev/cli build && pnpm exec openui generate lib/chat-library.ts --out generated/chat-system-prompt.txt && pnpm exec openui generate lib/playground-library.ts --out generated/playground-system-prompt.txt",+ "generate:prompts": "pnpm --filter @openuidev/cli build && pnpm exec openui generate lib/chat-library.ts --out generated/chat-system-prompt.txt && pnpm exec openui generate lib/playground-library.ts --out generated/playground-system-prompt.txt && pnpm exec openui generate lib/playground-library.ts --json-schema --out generated/playground-component-spec.json","build": "next build","dev": "pnpm generate:prompts && next dev","start": "next start",@@ -15,6 +15,7 @@},"dependencies": {"@openuidev/cli": "workspace:*",+ "@openuidev/lang-core": "workspace:^","@openuidev/react-lang": "workspace:^","@openuidev/react-headless": "workspace:^","@openuidev/react-ui": "workspace:^",@@ -33,6 +34,7 @@"react": "^19.2.4","react-dom": "^19.2.4","tailwind-merge": "^3.4.1",+ "octokit": "^5.0.0","zod": "^4.3.6"},"devDependencies": {diff --git a/docs/public/homepage/conversational-apps-dark.png b/docs/public/homepage/conversational-apps-dark.pngnew file mode 100644index 000000000..4624b7495Binary files /dev/null and b/docs/public/homepage/conversational-apps-dark.png differdiff --git a/docs/public/homepage/conversational-apps-light.png b/docs/public/homepage/conversational-apps-light.pngnew file mode 100644index 000000000..7d8101e29Binary files /dev/null and b/docs/public/homepage/conversational-apps-light.png differdiff --git a/docs/public/homepage/dashboard-dark.png b/docs/public/homepage/dashboard-dark.pngnew file mode 100644index 000000000..5a99f7df8Binary files /dev/null and b/docs/public/homepage/dashboard-dark.png differdiff --git a/docs/public/homepage/dashboard-light.png b/docs/public/homepage/dashboard-light.pngnew file mode 100644index 000000000..63766ed97Binary files /dev/null and b/docs/public/homepage/dashboard-light.png differdiff --git a/docs/public/homepage/hero-web-dark.png b/docs/public/homepage/hero-web-dark.pngnew file mode 100644index 000000000..01710a499Binary files /dev/null and b/docs/public/homepage/hero-web-dark.png differdiff --git a/docs/public/homepage/hero-web.png b/docs/public/homepage/hero-web.pngnew file mode 100644index 000000000..9885d146cBinary files /dev/null and b/docs/public/homepage/hero-web.png differdiff --git a/docs/public/homepage/image.png b/docs/public/homepage/image.pngnew file mode 100644index 000000000..5890cd835Binary files /dev/null and b/docs/public/homepage/image.png differdiff --git a/docs/public/homepage/mobile-dark.png b/docs/public/homepage/mobile-dark.pngnew file mode 100644index 000000000..2459c9e08Binary files /dev/null and b/docs/public/homepage/mobile-dark.png differdiff --git a/docs/public/homepage/mobile-hero-dark.png b/docs/public/homepage/mobile-hero-dark.pngnew file mode 100644index 000000000..f18265bbbBinary files /dev/null and b/docs/public/homepage/mobile-hero-dark.png differdiff --git a/docs/public/homepage/mobile-hero.png b/docs/public/homepage/mobile-hero.pngnew file mode 100644index 000000000..e25bab081Binary files /dev/null and b/docs/public/homepage/mobile-hero.png differdiff --git a/docs/public/homepage/mobile-light.png b/docs/public/homepage/mobile-light.pngnew file mode 100644index 000000000..3b429d6c5Binary files /dev/null and b/docs/public/homepage/mobile-light.png differdiff --git a/docs/public/homepage/tray-dark.png b/docs/public/homepage/tray-dark.pngnew file mode 100644index 000000000..0e18a5abfBinary files /dev/null and b/docs/public/homepage/tray-dark.png differdiff --git a/docs/public/homepage/tray-light.png b/docs/public/homepage/tray-light.pngnew file mode 100644index 000000000..309cac716Binary files /dev/null and b/docs/public/homepage/tray-light.png differdiff --git a/docs/public/images/openui-lang/architecture.png b/docs/public/images/openui-lang/architecture.pngnew file mode 100644index 000000000..95c8f31b7Binary files /dev/null and b/docs/public/images/openui-lang/architecture.png differdiff --git a/docs/public/images/openui-lang/query-flow.png b/docs/public/images/openui-lang/query-flow.pngnew file mode 100644index 000000000..fb12dd82dBinary files /dev/null and b/docs/public/images/openui-lang/query-flow.png differdiff --git a/docs/public/images/openui-lang/reactive.png b/docs/public/images/openui-lang/reactive.pngnew file mode 100644index 000000000..879cd3a77Binary files /dev/null and b/docs/public/images/openui-lang/reactive.png differdiff --git a/docs/public/videos/openui-lang/chat-quickstart.mp4 b/docs/public/videos/openui-lang/chat-quickstart.mp4new file mode 100644index 000000000..e6a99719aBinary files /dev/null and b/docs/public/videos/openui-lang/chat-quickstart.mp4 differdiff --git a/docs/public/videos/openui-lang/dashboard.mp4 b/docs/public/videos/openui-lang/dashboard.mp4new file mode 100644index 000000000..fc179fcceBinary files /dev/null and b/docs/public/videos/openui-lang/dashboard.mp4 differdiff --git a/docs/public/videos/openui-lang/incremental-editing.mp4 b/docs/public/videos/openui-lang/incremental-editing.mp4new file mode 100644index 000000000..ce4675520Binary files /dev/null and b/docs/public/videos/openui-lang/incremental-editing.mp4 differdiff --git a/docs/public/videos/openui-lang/reactive.mp4 b/docs/public/videos/openui-lang/reactive.mp4new file mode 100644index 000000000..378819eabBinary files /dev/null and b/docs/public/videos/openui-lang/reactive.mp4 differdiff --git a/docs/public/videos/openui-lang/ticket-tracker.mp4 b/docs/public/videos/openui-lang/ticket-tracker.mp4new file mode 100644index 000000000..bc2857849Binary files /dev/null and b/docs/public/videos/openui-lang/ticket-tracker.mp4 differdiff --git a/docs/shared/theme/openuiThemeBridge.ts b/docs/shared/theme/openuiThemeBridge.tsnew file mode 100644index 000000000..78fc9c326--- /dev/null+++ b/docs/shared/theme/openuiThemeBridge.ts@@ -0,0 +1,230 @@+import { swatchTokens } from "@openuidev/react-ui/ThemeProvider";++const FONT_FAMILY = 'var(--font-inter), "Inter", "Segoe UI", Arial, sans-serif';++export const fontOverrides = {+ fontBody: FONT_FAMILY,+ fontHeading: FONT_FAMILY,+ fontLabel: FONT_FAMILY,+ fontNumbers: FONT_FAMILY,+};++const ALIASES: Record<string, string> = {+ "--background": "var(--openui-background)",+ "--foreground": "var(--openui-foreground)",+ "--openui-background": "var(--background)",+ "--openui-foreground": "var(--foreground)",+ "--popover-background": "var(--openui-popover-background)",+ "--sunk-light": "var(--openui-sunk-light)",+ "--sunk": "var(--openui-sunk)",+ "--sunk-deep": "var(--openui-sunk-deep)",+ "--elevated-light": "var(--openui-elevated-light)",+ "--elevated": "var(--openui-elevated)",+ "--elevated-strong": "var(--openui-elevated-strong)",+ "--elevated-intense": "var(--openui-elevated-intense)",+ "--overlay": "var(--openui-overlay)",+ "--highlight-subtle": "var(--openui-highlight-subtle)",+ "--highlight": "var(--openui-highlight)",+ "--highlight-strong": "var(--openui-highlight-strong)",+ "--highlight-intense": "var(--openui-highlight-intense)",+ "--inverted-background": "var(--openui-inverted-background)",+ "--info-background": "var(--openui-info-background)",+ "--success-background": "var(--openui-success-background)",+ "--alert-background": "var(--openui-alert-background)",+ "--danger-background": "var(--openui-danger-background)",+ "--purple-background": "var(--openui-purple-background)",+ "--pink-background": "var(--openui-pink-background)",+ "--text-neutral-primary": "var(--openui-text-neutral-primary)",+ "--text-neutral-secondary": "var(--openui-text-neutral-secondary)",+ "--text-neutral-tertiary": "var(--openui-text-neutral-tertiary)",+ "--text-neutral-link": "var(--openui-text-neutral-link)",+ "--text-brand": "var(--openui-text-brand)",+ "--text-white": "var(--openui-text-white)",+ "--text-black": "var(--openui-text-black)",+ "--text-accent-primary": "var(--openui-text-accent-primary)",+ "--text-accent-secondary": "var(--openui-text-accent-secondary)",+ "--text-accent-tertiary": "var(--openui-text-accent-tertiary)",+ "--text-success-primary": "var(--openui-text-success-primary)",+ "--text-success-inverted": "var(--openui-text-success-inverted)",+ "--text-alert-primary": "var(--openui-text-alert-primary)",+ "--text-alert-inverted": "var(--openui-text-alert-inverted)",+ "--text-danger-primary": "var(--openui-text-danger-primary)",+ "--text-danger-secondary": "var(--openui-text-danger-secondary)",+ "--text-danger-tertiary": "var(--openui-text-danger-tertiary)",+ "--text-danger-inverted-primary": "var(--openui-text-danger-inverted-primary)",+ "--text-danger-inverted-secondary": "var(--openui-text-danger-inverted-secondary)",+ "--text-danger-inverted-tertiary": "var(--openui-text-danger-inverted-tertiary)",+ "--text-info-primary": "var(--openui-text-info-primary)",+ "--text-info-inverted": "var(--openui-text-info-inverted)",+ "--text-pink-primary": "var(--openui-text-pink-primary)",+ "--text-pink-inverted": "var(--openui-text-pink-inverted)",+ "--text-purple-primary": "var(--openui-text-purple-primary)",+ "--text-purple-inverted": "var(--openui-text-purple-inverted)",+ "--interactive-accent-default": "var(--openui-interactive-accent-default)",+ "--interactive-brand-default": "var(--openui-interactive-accent-default)",+ "--interactive-accent-hover": "var(--openui-interactive-accent-hover)",+ "--interactive-accent-disabled": "var(--openui-interactive-accent-disabled)",+ "--interactive-accent-pressed": "var(--openui-interactive-accent-pressed)",+ "--interactive-destructive-default": "var(--openui-interactive-destructive-default)",+ "--interactive-destructive-hover": "var(--openui-interactive-destructive-hover)",+ "--interactive-destructive-disabled": "var(--openui-interactive-destructive-disabled)",+ "--interactive-destructive-pressed": "var(--openui-interactive-destructive-pressed)",+ "--interactive-destructive-accent-default":+ "var(--openui-interactive-destructive-accent-default)",+ "--interactive-destructive-accent-hover": "var(--openui-interactive-destructive-accent-hover)",+ "--interactive-destructive-accent-pressed":+ "var(--openui-interactive-destructive-accent-pressed)",+ "--interactive-destructive-accent-disabled":+ "var(--openui-interactive-destructive-accent-disabled)",+ "--border-default": "var(--openui-border-default)",+ "--border-interactive": "var(--openui-border-interactive)",+ "--border-interactive-emphasis": "var(--openui-border-interactive-emphasis)",+ "--border-interactive-selected": "var(--openui-border-interactive-selected)",+ "--border-interactive-elements-selected": "var(--openui-border-interactive-selected)",+ "--border-accent": "var(--openui-border-accent)",+ "--border-accent-emphasis": "var(--openui-border-accent-emphasis)",+ "--border-info": "var(--openui-border-info)",+ "--border-info-emphasis": "var(--openui-border-info-emphasis)",+ "--border-alert": "var(--openui-border-alert)",+ "--border-alert-emphasis": "var(--openui-border-alert-emphasis)",+ "--border-success": "var(--openui-border-success)",+ "--border-success-emphasis": "var(--openui-border-success-emphasis)",+ "--border-danger": "var(--openui-border-danger)",+ "--border-danger-emphasis": "var(--openui-border-danger-emphasis)",+ "--space-000": "var(--openui-space-000)",+ "--space-3xs": "var(--openui-space-3xs)",+ "--space-2xs": "var(--openui-space-2xs)",+ "--space-xs": "var(--openui-space-xs)",+ "--space-s": "var(--openui-space-s)",+ "--space-s-m": "var(--openui-space-s-m)",+ "--space-m": "var(--openui-space-m)",+ "--space-m-l": "var(--openui-space-m-l)",+ "--space-l": "var(--openui-space-l)",+ "--space-xl": "var(--openui-space-xl)",+ "--space-2xl": "var(--openui-space-2xl)",+ "--space-3xl": "var(--openui-space-3xl)",+ "--space-0": "var(--space-000)",+ "--space-1": "var(--space-3xs)",+ "--space-2": "var(--space-2xs)",+ "--space-3": "var(--space-xs)",+ "--space-4": "var(--space-s)",+ "--space-5": "var(--space-s-m)",+ "--space-6": "var(--space-m)",+ "--space-8": "var(--space-m-l)",+ "--space-10": "var(--space-l)",+ "--space-12": "var(--space-xl)",+ "--space-16": "var(--space-2xl)",+ "--radius-none": "var(--openui-radius-none)",+ "--radius-3xs": "var(--openui-radius-3xs)",+ "--radius-2xs": "var(--openui-radius-2xs)",+ "--radius-xs": "var(--openui-radius-xs)",+ "--radius-s": "var(--openui-radius-s)",+ "--radius-m": "var(--openui-radius-m)",+ "--radius-l": "var(--openui-radius-l)",+ "--radius-xl": "var(--openui-radius-xl)",+ "--radius-2xl": "var(--openui-radius-2xl)",+ "--radius-3xl": "var(--openui-radius-3xl)",+ "--radius-4xl": "var(--openui-radius-4xl)",+ "--radius-5xl": "var(--openui-radius-5xl)",+ "--radius-6xl": "var(--openui-radius-6xl)",+ "--radius-7xl": "var(--openui-radius-7xl)",+ "--radius-8xl": "var(--openui-radius-8xl)",+ "--radius-9xl": "var(--openui-radius-9xl)",+ "--radius-full": "var(--openui-radius-full)",+ "--shadow-none": "var(--openui-shadow-0)",+ "--shadow-s": "var(--openui-shadow-s)",+ "--shadow-m": "var(--openui-shadow-m)",+ "--shadow-l": "var(--openui-shadow-l)",+ "--shadow-xl": "var(--openui-shadow-xl)",+ "--shadow-2xl": "var(--openui-shadow-2xl)",+ "--shadow-3xl": "var(--openui-shadow-3xl)",+ "--font-body": "var(--openui-font-body)",+ "--font-code": "var(--openui-font-code)",+ "--font-heading": "var(--openui-font-heading)",+ "--font-label": "var(--openui-font-label)",+ "--font-numbers": "var(--openui-font-numbers)",+ "--text-body-xs": "var(--openui-text-body-xs)",+ "--text-body-xs-letter-spacing": "var(--openui-text-body-xs-letter-spacing)",+ "--text-body-xs-heavy": "var(--openui-text-body-xs-heavy)",+ "--text-body-xs-heavy-letter-spacing": "var(--openui-text-body-xs-heavy-letter-spacing)",+ "--text-body-sm": "var(--openui-text-body-sm)",+ "--text-body-sm-letter-spacing": "var(--openui-text-body-sm-letter-spacing)",+ "--text-body-sm-heavy": "var(--openui-text-body-sm-heavy)",+ "--text-body-sm-heavy-letter-spacing": "var(--openui-text-body-sm-heavy-letter-spacing)",+ "--text-body-default": "var(--openui-text-body-default)",+ "--text-body-default-letter-spacing": "var(--openui-text-body-default-letter-spacing)",+ "--text-body-default-heavy": "var(--openui-text-body-default-heavy)",+ "--text-body-default-heavy-letter-spacing":+ "var(--openui-text-body-default-heavy-letter-spacing)",+ "--text-body-lg": "var(--openui-text-body-lg)",+ "--text-body-lg-letter-spacing": "var(--openui-text-body-lg-letter-spacing)",+ "--text-body-lg-heavy": "var(--openui-text-body-lg-heavy)",+ "--text-body-lg-heavy-letter-spacing": "var(--openui-text-body-lg-heavy-letter-spacing)",+ "--text-heading-xs": "var(--openui-text-heading-xs)",+ "--text-heading-xs-letter-spacing": "var(--openui-text-heading-xs-letter-spacing)",+ "--text-heading-sm": "var(--openui-text-heading-sm)",+ "--text-heading-sm-letter-spacing": "var(--openui-text-heading-sm-letter-spacing)",+ "--text-heading-md": "var(--openui-text-heading-md)",+ "--text-heading-md-letter-spacing": "var(--openui-text-heading-md-letter-spacing)",+ "--text-heading-lg": "var(--openui-text-heading-lg)",+ "--text-heading-lg-letter-spacing": "var(--openui-text-heading-lg-letter-spacing)",+ "--text-heading-xl": "var(--openui-text-heading-xl)",+ "--text-heading-xl-letter-spacing": "var(--openui-text-heading-xl-letter-spacing)",+ "--text-label-xs": "var(--openui-text-label-xs)",+ "--text-label-xs-letter-spacing": "var(--openui-text-label-xs-letter-spacing)",+ "--text-label-xs-heavy": "var(--openui-text-label-xs-heavy)",+ "--text-label-xs-heavy-letter-spacing": "var(--openui-text-label-xs-heavy-letter-spacing)",+ "--text-label-sm": "var(--openui-text-label-sm)",+ "--text-label-sm-letter-spacing": "var(--openui-text-label-sm-letter-spacing)",+ "--text-label-sm-heavy": "var(--openui-text-label-sm-heavy)",+ "--text-label-sm-heavy-letter-spacing": "var(--openui-text-label-sm-heavy-letter-spacing)",+ "--text-label-default": "var(--openui-text-label-default)",+ "--text-label-default-letter-spacing": "var(--openui-text-label-default-letter-spacing)",+ "--text-label-default-heavy": "var(--openui-text-label-default-heavy)",+ "--text-label-default-heavy-letter-spacing":+ "var(--openui-text-label-default-heavy-letter-spacing)",+ "--text-label-lg": "var(--openui-text-label-lg)",+ "--text-label-lg-letter-spacing": "var(--openui-text-label-lg-letter-spacing)",+ "--text-label-lg-heavy": "var(--openui-text-label-lg-heavy)",+ "--text-label-lg-heavy-letter-spacing": "var(--openui-text-label-lg-heavy-letter-spacing)",+ "--text-numbers-xs": "var(--openui-text-numbers-xs)",+ "--text-numbers-xs-letter-spacing": "var(--openui-text-numbers-xs-letter-spacing)",+ "--text-numbers-xs-heavy": "var(--openui-text-numbers-xs-heavy)",+ "--text-numbers-xs-heavy-letter-spacing": "var(--openui-text-numbers-xs-heavy-letter-spacing)",+ "--text-numbers-sm": "var(--openui-text-numbers-sm)",+ "--text-numbers-sm-letter-spacing": "var(--openui-text-numbers-sm-letter-spacing)",+ "--text-numbers-sm-heavy": "var(--openui-text-numbers-sm-heavy)",+ "--text-numbers-sm-heavy-letter-spacing": "var(--openui-text-numbers-sm-heavy-letter-spacing)",+ "--text-numbers-default": "var(--openui-text-numbers-default)",+ "--text-numbers-default-letter-spacing": "var(--openui-text-numbers-default-letter-spacing)",+ "--text-numbers-default-heavy": "var(--openui-text-numbers-default-heavy)",+ "--text-numbers-default-heavy-letter-spacing":+ "var(--openui-text-numbers-default-heavy-letter-spacing)",+ "--text-numbers-lg": "var(--openui-text-numbers-lg)",+ "--text-numbers-lg-letter-spacing": "var(--openui-text-numbers-lg-letter-spacing)",+ "--text-numbers-lg-heavy": "var(--openui-text-numbers-lg-heavy)",+ "--text-numbers-lg-heavy-letter-spacing": "var(--openui-text-numbers-lg-heavy-letter-spacing)",+ "--text-code-sm": "var(--openui-text-code-sm)",+ "--text-code-sm-letter-spacing": "var(--openui-text-code-sm-letter-spacing)",+ "--text-code-sm-heavy": "var(--openui-text-code-sm-heavy)",+ "--text-code-sm-heavy-letter-spacing": "var(--openui-text-code-sm-heavy-letter-spacing)",+ "--text-code-default": "var(--openui-text-code-default)",+ "--text-code-default-letter-spacing": "var(--openui-text-code-default-letter-spacing)",+ "--text-code-default-heavy": "var(--openui-text-code-default-heavy)",+ "--text-code-default-heavy-letter-spacing":+ "var(--openui-text-code-default-heavy-letter-spacing)",+ "--motion-duration-fast": "120ms",+ "--motion-duration-default": "200ms",+ "--motion-duration-slow": "320ms",+ "--motion-duration-slower": "480ms",+ "--motion-ease-standard": "cubic-bezier(0.2, 0, 0, 1)",+ "--motion-ease-emphasized": "cubic-bezier(0.2, 0, 0, 1.2)",+};++export const legacyVarCss = Object.entries(ALIASES)+ .map(([name, value]) => `${name}: ${value};`)+ .join("\n");++export const swatchVarCss = Object.entries(swatchTokens)+ .map(([name, value]) => `--swatch-${name}: ${value};`)+ .join("\n");diff --git a/docs/types/twitter-widgets.d.ts b/docs/types/twitter-widgets.d.tsnew file mode 100644index 000000000..fdfd14b1b--- /dev/null+++ b/docs/types/twitter-widgets.d.ts@@ -0,0 +1,23 @@+/** Loaded by https://platform.twitter.com/widgets.js */+declare global {+ interface Window {+ twttr?: {+ widgets: {+ createTweet: (+ tweetId: string,+ element: HTMLElement,+ options?: {+ align?: "center" | "left" | "right";+ conversation?: "all" | "none";+ dnt?: boolean;+ theme?: "light" | "dark";+ width?: number;+ },+ ) => Promise<HTMLElement>;+ load: (element?: HTMLElement | null) => void;+ };+ };+ }+}++export {};diff --git a/examples/form-generator/next-env.d.ts b/examples/form-generator/next-env.d.tsindex c4b7818fb..9edff1c7c 100644--- a/examples/form-generator/next-env.d.ts+++ b/examples/form-generator/next-env.d.ts@@ -1,6 +1,6 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-import "./.next/dev/types/routes.d.ts";+import "./.next/types/routes.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/examples/form-generator/src/generated/system-prompt.txt b/examples/form-generator/src/generated/system-prompt.txtindex 1b149850b..99070f4d5 100644--- a/examples/form-generator/src/generated/system-prompt.txt+++ b/examples/form-generator/src/generated/system-prompt.txt@@ -5,18 +5,18 @@ You are an AI assistant that responds using openui-lang, a declarative UI langua1. Each statement is on its own line: `identifier = Expression`2. `root` is the entry point — every program must define `root = Form(...)`-3. Expressions are: strings ("..."), numbers, booleans (true/false), arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)+3. Expressions are: strings ("..."), numbers, booleans (true/false), null, arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)4. Use references for readability: define `name = ...` on one line, then use `name` later5. EVERY variable (except root) MUST be referenced by at least one other variable. Unreferenced variables are silently dropped and will NOT render. Always include defined variables in their parent's children/items array.-6. Arguments are POSITIONAL (order matters, not names)+6. Arguments are POSITIONAL (order matters, not names). Write `Stack([children], "row", "l")` NOT `Stack([children], direction: "row", gap: "l")` — colon syntax is NOT supported and silently breaks7. Optional arguments can be omitted from the end-8. No operators, no logic, no variables — only declarations-9. Strings use double quotes with backslash escaping+- Strings use double quotes with backslash escaping## Component SignaturesArguments marked with ? are optional. Sub-components can be inline or referenced; prefer references for better streaming.-The `action` prop type accepts: ContinueConversation (sends message to LLM), OpenUrl (navigates to URL), or Custom (app-defined).+Props typed `ActionExpression` accept an Action([@steps...]) expression. See the Action section for available steps (@ToAssistant, @OpenUrl).+Props marked `$binding<type>` accept a `$variable` reference for two-way binding.### ButtonsButton(label: string, action?: {type: "open_url", url: string} | {type: "continue_conversation", context?: string}, variant?: "primary" | "secondary" | "tertiary" | "outline" | "ghost" | "danger") — Clickable button@@ -39,6 +39,50 @@ RadioItem(label: string, description: string, value: string) — Option for RadiSwitchGroup(name: string, items: SwitchItem[]) — Group of switch togglesSwitchItem(label?: string, description?: string, name: string, defaultChecked?: boolean) — Individual switch toggle+## Built-in Functions++Data functions prefixed with `@` to distinguish from components. These are the ONLY functions available — do NOT invent new ones.+Use @-prefixed built-in functions (@Count, @Sum, @Avg, @Min, @Max, @Round) on Query results — do NOT hardcode computed values.++@Count(array) → number — Returns array length+@First(array) → element — Returns first element of array+@Last(array) → element — Returns last element of array+@Sum(numbers[]) → number — Sum of numeric array+@Avg(numbers[]) → number — Average of numeric array+@Min(numbers[]) → number — Minimum value in array+@Max(numbers[]) → number — Maximum value in array+@Sort(array, field, direction?) → sorted array — Sort array by field. Direction: "asc" (default) or "desc"+@Filter(array, field, operator: "==" | "!=" | ">" | "<" | ">=" | "<=" | "contains", value) → filtered array — Filter array by field value+@Round(number, decimals?) → number — Round to N decimal places (default 0)+@Abs(number) → number — Absolute value+@Floor(number) → number — Round down to nearest integer+@Ceil(number) → number — Round up to nearest integer+@Each(array, varName, template) — Evaluate template for each element. varName is the loop variable — use it ONLY inside the template expression (inline). Do NOT create a separate statement for the template.++Builtins compose — output of one is input to the next:+`@Count(@Filter(data.rows, "field", "==", "val"))` for KPIs/chart values, `@Round(@Avg(data.rows.score), 1)`, `@Each(data.rows, "item", Comp(item.field))` for per-item rendering.+Array pluck: `data.rows.field` extracts a field from every row → use with @Sum, @Avg, charts, tables.++IMPORTANT @Each rule: The loop variable (e.g. "item") is ONLY available inside the @Each template expression. Always inline the template — do NOT extract it to a separate statement.+CORRECT: `Col("Actions", @Each(rows, "t", Button("Edit", Action([@Set($id, t.id)]))))`+WRONG: `myBtn = Button("Edit", Action([@Set($id, t.id)]))` then `Col("Actions", @Each(rows, "t", myBtn))` — t is undefined in myBtn.++## Action — Button Behavior++Action([@steps...]) wires button clicks to operations. Steps are @-prefixed built-in actions. Steps execute in order.+Buttons without an explicit Action prop automatically send their label to the assistant (equivalent to Action([@ToAssistant(label)])).++Available steps:+- @ToAssistant("message") — Send a message to the assistant (for conversational buttons like "Tell me more", "Explain this")+- @OpenUrl("https://...") — Navigate to a URL++Example — simple nav:+```+viewBtn = Button("View", Action([@OpenUrl("https://example.com")]))+```++- Action can be assigned to a variable or inlined: Button("Go", onSubmit) and Button("Go", Action([...])) both work+## Hoisting & Streaming (CRITICAL)openui-lang supports hoisting: a reference can be used BEFORE it is defined. The parser resolves all references after the full input is parsed.@@ -47,18 +91,20 @@ During streaming, the output is re-parsed on every chunk. Undefined references a**Recommended statement order for optimal streaming:**1. `root = Form(...)` — UI shell appears immediately-2. Component definitions — fill in as they stream-3. Data values — leaf content last+2. $variable declarations — state ready for bindings+3. Query statements — defaults resolve immediately so components render with data+4. Component definitions — fill in with data already available+5. Data values — leaf content lastAlways write the root = Form(...) statement first so the UI shell appears immediately, even before child data has streamed in.## Important Rules-- ALWAYS start with root = Form(...)-- Write statements in TOP-DOWN order: root → components → data (leverages hoisting for progressive streaming)-- Each statement on its own line-- No trailing text or explanations — output ONLY openui-lang code- When asked about data, generate realistic/plausible data- Choose components that best represent the content (tables for comparisons, charts for trends, forms for input, etc.)-- NEVER define a variable without referencing it from the tree. Every variable must be reachable from root, otherwise it will not render.++## Final Verification+Before finishing, walk your output and verify:+1. root = Form(...) is the FIRST line (for optimal streaming).+2. Every referenced name is defined. Every defined name (other than root) is reachable from root.- Every response is a single Form(...) — Form is the root element.- Always include explicit Buttons with at least one primary submit button.diff --git a/examples/openui-artifact-demo/src/app/api/chat/route.ts b/examples/openui-artifact-demo/src/app/api/chat/route.tsindex 40ad28c27..851a94950 100644--- a/examples/openui-artifact-demo/src/app/api/chat/route.ts+++ b/examples/openui-artifact-demo/src/app/api/chat/route.ts@@ -202,7 +202,7 @@ export async function POST(req: NextRequest) {const client = new OpenAI({apiKey: process.env.OPENAI_API_KEY,});- const MODEL = process.env.OPENAI_MODEL || "gpt-4o";+ const MODEL = process.env.OPENAI_MODEL || "gpt-5.4-mini";// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst cleanMessages = (messages as any[])diff --git a/examples/openui-chat/src/generated/system-prompt.txt b/examples/openui-chat/src/generated/system-prompt.txtindex 9a444471c..1cff93aac 100644--- a/examples/openui-chat/src/generated/system-prompt.txt+++ b/examples/openui-chat/src/generated/system-prompt.txt@@ -4,24 +4,24 @@ You are an AI assistant that responds using openui-lang, a declarative UI langua1. Each statement is on its own line: `identifier = Expression`2. `root` is the entry point — every program must define `root = Card(...)`-3. Expressions are: strings ("..."), numbers, booleans (true/false), arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)+3. Expressions are: strings ("..."), numbers, booleans (true/false), null, arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)4. Use references for readability: define `name = ...` on one line, then use `name` later5. EVERY variable (except root) MUST be referenced by at least one other variable. Unreferenced variables are silently dropped and will NOT render. Always include defined variables in their parent's children/items array.-6. Arguments are POSITIONAL (order matters, not names)+6. Arguments are POSITIONAL (order matters, not names). Write `Stack([children], "row", "l")` NOT `Stack([children], direction: "row", gap: "l")` — colon syntax is NOT supported and silently breaks7. Optional arguments can be omitted from the end-8. No operators, no logic, no variables — only declarations-9. Strings use double quotes with backslash escaping+- Strings use double quotes with backslash escaping## Component SignaturesArguments marked with ? are optional. Sub-components can be inline or referenced; prefer references for better streaming.-The `action` prop type accepts: ContinueConversation (sends message to LLM), OpenUrl (navigates to URL), or Custom (app-defined).+Props typed `ActionExpression` accept an Action([@steps...]) expression. See the Action section for available steps (@ToAssistant, @OpenUrl).+Props marked `$binding<type>` accept a `$variable` reference for two-way binding.### ContentCardHeader(title?: string, subtitle?: string) — Header with optional title and subtitleTextContent(text: string, size?: "small" | "default" | "large" | "small-heavy" | "large-heavy") — Text block. Supports markdown. Optional size: "small" | "default" | "large" | "small-heavy" | "large-heavy".MarkDownRenderer(textMarkdown: string, variant?: "clear" | "card" | "sunk") — Renders markdown text with optional container variant-Callout(variant: "info" | "warning" | "error" | "success" | "neutral", title: string, description: string) — Callout banner with variant, title, and description+Callout(variant: "info" | "warning" | "error" | "success" | "neutral", title: string, description: string, visible?: $binding<boolean>) — Callout banner. Optional visible is a reactive $boolean — auto-dismisses after 3s by setting $visible to false.TextCallout(variant?: "neutral" | "info" | "warning" | "success" | "danger", title?: string, description?: string) — Text callout with variant, title, and descriptionImage(alt: string, src?: string) — Image with alt text and optional URLImageBlock(src: string, alt?: string) — Image block with loading state@@ -30,8 +30,8 @@ CodeBlock(language: string, codeString: string) — Syntax-highlighted code blocSeparator(orientation?: "horizontal" | "vertical", decorative?: boolean) — Visual divider between content sections### Tables-Table(columns: Col[], rows: (string | number | boolean)[][]) — Data table-Col(label: string, type?: "string" | "number" | "action") — Column definition+Table(columns: Col[]) — Data table — column-oriented. Each Col holds its own data array.+Col(label: string, data, type?: "string" | "number" | "action") — Column definition — holds label + data array### Charts (2D)BarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Vertical bars; use for comparing values across categories with one or more series@@ -42,9 +42,9 @@ HorizontalBarChart(labels: string[], series: Series[], variant?: "grouped" | "stSeries(category: string, values: number[]) — One data series### Charts (1D)-PieChart(slices: Slice[], variant?: "pie" | "donut") — Circular slices showing part-to-whole proportions; supports pie and donut variants-RadialChart(slices: Slice[]) — Radial bars showing proportional distribution across named segments-SingleStackedBarChart(slices: Slice[]) — Single horizontal stacked bar; use for showing part-to-whole proportions in one row+PieChart(labels: string[], values: number[], variant?: "pie" | "donut") — Circular slices; use plucked arrays: PieChart(data.categories, data.values)+RadialChart(labels: string[], values: number[]) — Radial bars; use plucked arrays: RadialChart(data.categories, data.values)+SingleStackedBarChart(labels: string[], values: number[]) — Single horizontal stacked bar; use plucked arrays: SingleStackedBarChart(data.categories, data.values)Slice(category: string, value: number) — One slice with label and numeric value### Charts (Scatter)@@ -56,17 +56,17 @@ Point(x: number, y: number, z?: number) — Data point with numeric coordinatesForm(name: string, buttons: Buttons, fields) — Form container with fields and explicit action buttonsFormControl(label: string, input: Input | TextArea | Select | DatePicker | Slider | CheckBoxGroup | RadioGroup, hint?: string) — Field with label, input component, and optional hint textLabel(text: string) — Text label-Input(name: string, placeholder?: string, type?: "text" | "email" | "password" | "number" | "url", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})-TextArea(name: string, placeholder?: string, rows?: number, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})-Select(name: string, items: SelectItem[], placeholder?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})+Input(name: string, placeholder?: string, type?: "text" | "email" | "password" | "number" | "url", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)+TextArea(name: string, placeholder?: string, rows?: number, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)+Select(name: string, items: SelectItem[], placeholder?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)SelectItem(value: string, label: string) — Option for Select-DatePicker(name: string, mode: "single" | "range", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})-Slider(name: string, variant: "continuous" | "discrete", min: number, max: number, step?: number, defaultValue?: number[], label?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}) — Numeric slider input; supports continuous and discrete (stepped) variants-CheckBoxGroup(name: string, items: CheckBoxItem[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})+DatePicker(name: string, mode?: "single" | "range", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?)+Slider(name: string, variant: "continuous" | "discrete", min: number, max: number, step?: number, defaultValue?: number[], label?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<number[]>) — Numeric slider input; supports continuous and discrete (stepped) variants+CheckBoxGroup(name: string, items: CheckBoxItem[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?)CheckBoxItem(label: string, description: string, name: string, defaultChecked?: boolean)-RadioGroup(name: string, items: RadioItem[], defaultValue?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string})+RadioGroup(name: string, items: RadioItem[], defaultValue?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)RadioItem(label: string, description: string, value: string)-SwitchGroup(name: string, items: SwitchItem[], variant?: "clear" | "card" | "sunk") — Group of switch toggles+SwitchGroup(name: string, items: SwitchItem[], variant?: "clear" | "card" | "sunk", value?) — Group of switch togglesSwitchItem(label?: string, description?: string, name: string, defaultChecked?: boolean) — Individual switch toggle- Define EACH FormControl as its own reference — do NOT inline all controls in one array.- NEVER nest Form inside Form.@@ -75,12 +75,12 @@ SwitchItem(label?: string, description?: string, name: string, defaultChecked?:- The renderer shows error messages automatically — do NOT generate error text in the UI### Buttons-Button(label: string, action?: {type: "open_url", url: string} | {type: "continue_conversation", context?: string} | {type: string, params?}, variant?: "primary" | "secondary" | "tertiary", type?: "normal" | "destructive", size?: "extra-small" | "small" | "medium" | "large") — Clickable button+Button(label: string, action?: ActionExpression, variant?: "primary" | "secondary" | "tertiary", type?: "normal" | "destructive", size?: "extra-small" | "small" | "medium" | "large") — Clickable buttonButtons(buttons: Button[], direction?: "row" | "column") — Group of Button components. direction: "row" (default) | "column".### Lists & Follow-upsListBlock(items: ListItem[], variant?: "number" | "image") — A list of items with number or image indicators. Each item can optionally have an action.-ListItem(title: string, subtitle?: string, image?: {src: string, alt: string}, actionLabel?: string, action?: {type: "open_url", url: string} | {type: "continue_conversation", context?: string} | {type: string, params?}) — Item in a ListBlock — displays a title with an optional subtitle and image. When action is provided, the item becomes clickable.+ListItem(title: string, subtitle?: string, image?: {src: string, alt: string}, actionLabel?: string, action?: ActionExpression) — Item in a ListBlock — displays a title with an optional subtitle and image. When action is provided, the item becomes clickable.FollowUpBlock(items: FollowUpItem[]) — List of clickable follow-up suggestions placed at the end of a responseFollowUpItem(text: string) — Clickable follow-up suggestion — when clicked, sends text as user message- Use ListBlock with ListItem references for numbered, clickable lists.@@ -114,9 +114,53 @@ Carousel(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextTagBlock(tags: string[]) — tags is an array of stringsTag(text: string, icon?: string, size?: "sm" | "md" | "lg", variant?: "neutral" | "info" | "success" | "warning" | "danger") — Styled tag/badge with optional icon and variant-### Ungrouped+### OtherCard(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps | ListBlock | FollowUpBlock | SectionBlock | Tabs | Carousel)[]) — Vertical container for all content in a chat response. Children stack top to bottom automatically.+## Built-in Functions++Data functions prefixed with `@` to distinguish from components. These are the ONLY functions available — do NOT invent new ones.+Use @-prefixed built-in functions (@Count, @Sum, @Avg, @Min, @Max, @Round) on Query results — do NOT hardcode computed values.++@Count(array) → number — Returns array length+@First(array) → element — Returns first element of array+@Last(array) → element — Returns last element of array+@Sum(numbers[]) → number — Sum of numeric array+@Avg(numbers[]) → number — Average of numeric array+@Min(numbers[]) → number — Minimum value in array+@Max(numbers[]) → number — Maximum value in array+@Sort(array, field, direction?) → sorted array — Sort array by field. Direction: "asc" (default) or "desc"+@Filter(array, field, operator: "==" | "!=" | ">" | "<" | ">=" | "<=" | "contains", value) → filtered array — Filter array by field value+@Round(number, decimals?) → number — Round to N decimal places (default 0)+@Abs(number) → number — Absolute value+@Floor(number) → number — Round down to nearest integer+@Ceil(number) → number — Round up to nearest integer+@Each(array, varName, template) — Evaluate template for each element. varName is the loop variable — use it ONLY inside the template expression (inline). Do NOT create a separate statement for the template.++Builtins compose — output of one is input to the next:+`@Count(@Filter(data.rows, "field", "==", "val"))` for KPIs/chart values, `@Round(@Avg(data.rows.score), 1)`, `@Each(data.rows, "item", Comp(item.field))` for per-item rendering.+Array pluck: `data.rows.field` extracts a field from every row → use with @Sum, @Avg, charts, tables.++IMPORTANT @Each rule: The loop variable (e.g. "item") is ONLY available inside the @Each template expression. Always inline the template — do NOT extract it to a separate statement.+CORRECT: `Col("Actions", @Each(rows, "t", Button("Edit", Action([@Set($id, t.id)]))))`+WRONG: `myBtn = Button("Edit", Action([@Set($id, t.id)]))` then `Col("Actions", @Each(rows, "t", myBtn))` — t is undefined in myBtn.++## Action — Button Behavior++Action([@steps...]) wires button clicks to operations. Steps are @-prefixed built-in actions. Steps execute in order.+Buttons without an explicit Action prop automatically send their label to the assistant (equivalent to Action([@ToAssistant(label)])).++Available steps:+- @ToAssistant("message") — Send a message to the assistant (for conversational buttons like "Tell me more", "Explain this")+- @OpenUrl("https://...") — Navigate to a URL++Example — simple nav:+```+viewBtn = Button("View", Action([@OpenUrl("https://example.com")]))+```++- Action can be assigned to a variable or inlined: Button("Go", onSubmit) and Button("Go", Action([...])) both work+## Hoisting & Streaming (CRITICAL)openui-lang supports hoisting: a reference can be used BEFORE it is defined. The parser resolves all references after the full input is parsed.@@ -125,24 +169,29 @@ During streaming, the output is re-parsed on every chunk. Undefined references a**Recommended statement order for optimal streaming:**1. `root = Card(...)` — UI shell appears immediately-2. Component definitions — fill in as they stream-3. Data values — leaf content last+2. $variable declarations — state ready for bindings+3. Query statements — defaults resolve immediately so components render with data+4. Component definitions — fill in with data already available+5. Data values — leaf content lastAlways write the root = Card(...) statement first so the UI shell appears immediately, even before child data has streamed in.## ExamplesExample 1 — Table with follow-ups:+root = Card([title, tbl, followUps])title = TextContent("Top Languages", "large-heavy")-tbl = Table(cols, rows)-cols = [Col("Language", "string"), Col("Users (M)", "number"), Col("Year", "number")]-rows = [["Python", 15.7, 1991], ["JavaScript", 14.2, 1995], ["Java", 12.1, 1995]]+tbl = Table([Col("Language", langs), Col("Users (M)", users), Col("Year", years)])+langs = ["Python", "JavaScript", "Java"]+users = [15.7, 14.2, 12.1]+years = [1991, 1995, 1995]followUps = FollowUpBlock([fu1, fu2])fu1 = FollowUpItem("Tell me more about Python")fu2 = FollowUpItem("Show me a JavaScript comparison")Example 2 — Clickable list:+root = Card([title, list])title = TextContent("Choose a topic", "large-heavy")list = ListBlock([item1, item2, item3])@@ -151,6 +200,7 @@ item2 = ListItem("Advanced features", "Deep dives into powerful capabilities.")item3 = ListItem("Troubleshooting", "Common issues and how to fix them.")Example 3 — Image carousel with consistent slides + follow-ups:+root = Card([header, carousel, followups])header = CardHeader("Featured Destinations", "Discover highlights and best time to visit")carousel = Carousel([[t1, img1, d1, tags1], [t2, img2, d2, tags2], [t3, img3, d3, tags3]], "card")@@ -171,22 +221,23 @@ fu1 = FollowUpItem("Show me only beach destinations")fu2 = FollowUpItem("Turn this into a comparison table")Example 4 — Form with validation:+root = Card([title, form])title = TextContent("Contact Us", "large-heavy")form = Form("contact", btns, [nameField, emailField, msgField])nameField = FormControl("Name", Input("name", "Your name", "text", { required: true, minLength: 2 }))emailField = FormControl("Email", Input("email", "[email protected]", "email", { required: true, email: true }))msgField = FormControl("Message", TextArea("message", "Tell us more...", 4, { required: true, minLength: 10 }))-btns = Buttons([Button("Submit", { type: "continue_conversation" }, "primary")])+btns = Buttons([Button("Submit", Action([@ToAssistant("Submit")]), "primary")])## Important Rules-- ALWAYS start with root = Card(...)-- Write statements in TOP-DOWN order: root → components → data (leverages hoisting for progressive streaming)-- Each statement on its own line-- No trailing text or explanations — output ONLY openui-lang code- When asked about data, generate realistic/plausible data- Choose components that best represent the content (tables for comparisons, charts for trends, forms for input, etc.)-- NEVER define a variable without referencing it from the tree. Every variable must be reachable from root, otherwise it will not render.++## Final Verification+Before finishing, walk your output and verify:+1. root = Card(...) is the FIRST line (for optimal streaming).+2. Every referenced name is defined. Every defined name (other than root) is reachable from root.- Every response is a single Card(children) — children stack vertically automatically. No layout params are needed on Card.- Card is the only layout container. Do NOT use Stack. Use Tabs to switch between sections, Carousel for horizontal scroll.diff --git a/examples/openui-dashboard/.gitignore b/examples/openui-dashboard/.gitignorenew file mode 100644index 000000000..5ef6a5207--- /dev/null+++ b/examples/openui-dashboard/.gitignore@@ -0,0 +1,41 @@+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.++# dependencies+/node_modules+/.pnp+.pnp.*+.yarn/*+!.yarn/patches+!.yarn/plugins+!.yarn/releases+!.yarn/versions++# testing+/coverage++# next.js+/.next/+/out/++# production+/build++# misc+.DS_Store+*.pem++# debug+npm-debug.log*+yarn-debug.log*+yarn-error.log*+.pnpm-debug.log*++# env files (can opt-in for committing if needed)+.env*++# vercel+.vercel++# typescript+*.tsbuildinfo+next-env.d.tsdiff --git a/examples/openui-dashboard/README.md b/examples/openui-dashboard/README.mdnew file mode 100644index 000000000..ad2d96af8--- /dev/null+++ b/examples/openui-dashboard/README.md@@ -0,0 +1,44 @@+# OpenUI Dashboard Example++A live dashboard builder powered by [OpenUI](https://openui.com) and openui-lang. Chat with an LLM to create interactive dashboards with real-time data from MCP tools.++## Features++- **Conversational dashboard building** — describe what you want, get a live dashboard+- **MCP tool integration** — Query live data sources (PostHog, server health, tickets)+- **Streaming rendering** — dashboards appear progressively as the LLM generates code+- **Edit support** — refine dashboards through follow-up messages+- **16 built-in tools** — analytics, monitoring, ticket management, and more++## Getting Started++```bash+# Set your LLM API key+export OPENAI_API_KEY=sk-...+# Or use any OpenAI-compatible provider:+# export LLM_API_KEY=your-key+# export LLM_BASE_URL=https://openrouter.ai/api/v1+# export LLM_MODEL=your-model++# Install dependencies+pnpm install++# Run the development server+pnpm dev+```++Open [http://localhost:3000](http://localhost:3000) to start building dashboards.++## Optional: PostHog Integration++For real analytics data, set PostHog credentials:++```bash+export POSTHOG_API_KEY=phx_...+export POSTHOG_PROJECT_ID=12345+```++## Learn More++- [OpenUI Documentation](https://openui.com/docs)+- [OpenUI GitHub](https://github.com/thesysdev/openui)diff --git a/examples/openui-dashboard/eslint.config.mjs b/examples/openui-dashboard/eslint.config.mjsnew file mode 100644index 000000000..05e726d1b--- /dev/null+++ b/examples/openui-dashboard/eslint.config.mjs@@ -0,0 +1,18 @@+import { defineConfig, globalIgnores } from "eslint/config";+import nextVitals from "eslint-config-next/core-web-vitals";+import nextTs from "eslint-config-next/typescript";++const eslintConfig = defineConfig([+ ...nextVitals,+ ...nextTs,+ // Override default ignores of eslint-config-next.+ globalIgnores([+ // Default ignores of eslint-config-next:+ ".next/**",+ "out/**",+ "build/**",+ "next-env.d.ts",+ ]),+]);++export default eslintConfig;diff --git a/examples/openui-dashboard/next.config.ts b/examples/openui-dashboard/next.config.tsnew file mode 100644index 000000000..d6663987d--- /dev/null+++ b/examples/openui-dashboard/next.config.ts@@ -0,0 +1,9 @@+import type { NextConfig } from "next";++const nextConfig: NextConfig = {+ output: "standalone",+ turbopack: {},+ transpilePackages: ["@openuidev/react-ui", "@openuidev/react-headless", "@openuidev/react-lang"],+};++export default nextConfig;diff --git a/examples/openui-dashboard/package.json b/examples/openui-dashboard/package.jsonnew file mode 100644index 000000000..be4cc7525--- /dev/null+++ b/examples/openui-dashboard/package.json@@ -0,0 +1,36 @@+{+ "name": "openui-dashboard",+ "version": "0.1.0",+ "private": true,+ "scripts": {+ "generate:prompt": "pnpm --filter @openuidev/cli build && pnpm exec openui generate src/library.ts --json-schema --out src/generated/component-spec.json",+ "dev": "pnpm generate:prompt && next dev",+ "build": "next build",+ "start": "next start",+ "lint": "eslint"+ },+ "dependencies": {+ "@openuidev/cli": "workspace:*",+ "@openuidev/react-ui": "workspace:*",+ "@openuidev/lang-core": "workspace:*",+ "@openuidev/react-headless": "workspace:*",+ "@modelcontextprotocol/sdk": "^1.27.1",+ "@openuidev/react-lang": "workspace:*",+ "lucide-react": "^0.575.0",+ "next": "16.1.6",+ "openai": "^6.22.0",+ "react": "19.2.3",+ "react-dom": "19.2.3",+ "zod": "^4.0.0"+ },+ "devDependencies": {+ "@tailwindcss/postcss": "^4",+ "@types/node": "^20",+ "@types/react": "^19",+ "@types/react-dom": "^19",+ "eslint": "^9",+ "eslint-config-next": "16.1.6",+ "tailwindcss": "^4",+ "typescript": "^5"+ }+}diff --git a/examples/openui-dashboard/postcss.config.mjs b/examples/openui-dashboard/postcss.config.mjsnew file mode 100644index 000000000..61e36849c--- /dev/null+++ b/examples/openui-dashboard/postcss.config.mjs@@ -0,0 +1,7 @@+const config = {+ plugins: {+ "@tailwindcss/postcss": {},+ },+};++export default config;diff --git a/examples/openui-dashboard/src/app/api/chat/route.ts b/examples/openui-dashboard/src/app/api/chat/route.tsnew file mode 100644index 000000000..b2bcaaeaf--- /dev/null+++ b/examples/openui-dashboard/src/app/api/chat/route.ts@@ -0,0 +1,42 @@+import { NextRequest } from "next/server";+import OpenAI from "openai";+import type { ChatCompletionMessageParam } from "openai/resources/chat/completions.mjs";+import { generatePrompt } from "@openuidev/lang-core";+import { promptSpec } from "@/prompt-config";+import { tools as toolDefs } from "@/tools";+import { sseResponseFromRunner } from "@/lib/sse-stream";++const tools = toolDefs.map((t) => t.toOpenAITool());++function buildSystemPrompt(): string {+ return generatePrompt({+ ...promptSpec,+ tools: toolDefs.map((t) => t.toToolSpec()),+ });+}++export async function POST(req: NextRequest) {+ const { messages } = (await req.json()) as { messages: ChatCompletionMessageParam[] };++ const apiKey = process.env.LLM_API_KEY || process.env.OPENAI_API_KEY || "";+ const baseURL = process.env.LLM_BASE_URL || "https://api.openai.com/v1";+ const model = process.env.LLM_MODEL || "gpt-5.4";++ if (!apiKey) {+ return new Response(+ JSON.stringify({ error: "Set LLM_API_KEY or OPENAI_API_KEY env var" }),+ { status: 500 },+ );+ }++ const client = new OpenAI({ apiKey, baseURL });+ const runner = client.chat.completions.runTools({+ model,+ messages: [{ role: "system" as const, content: buildSystemPrompt() }, ...messages],+ tools,+ stream: true,+ // reasoning: { effort: "low" },+ });++ return sseResponseFromRunner(runner);+}diff --git a/examples/openui-dashboard/src/app/api/mcp/route.ts b/examples/openui-dashboard/src/app/api/mcp/route.tsnew file mode 100644index 000000000..d12e4b3d5--- /dev/null+++ b/examples/openui-dashboard/src/app/api/mcp/route.ts@@ -0,0 +1,60 @@+/**+ * MCP Server — exposes all tools via MCP protocol.+ *+ * Tool definitions live in src/tools.ts (shared with /api/chat).+ * This file only sets up the MCP transport and registers tools.+ */+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";+import { tools } from "@/tools";++// ── MCP Server factory ───────────────────────────────────────────────────────++function createServer(): McpServer {+ const server = new McpServer(+ { name: "openui-tools", version: "1.0.0" },+ );++ for (const tool of tools) {+ server.registerTool(tool.name, {+ description: tool.description,+ inputSchema: tool.inputSchema,+ }, async (args) => ({+ content: [{ type: "text" as const, text: JSON.stringify(await tool.execute(args)) }],+ }));+ }++ return server;+}++// ── Request handler ──────────────────────────────────────────────────────────++async function handleMcpRequest(request: Request): Promise<Response> {+ const transport = new WebStandardStreamableHTTPServerTransport({+ sessionIdGenerator: undefined, // stateless+ enableJsonResponse: true,+ });+ const server = createServer();+ await server.connect(transport);++ try {+ return await transport.handleRequest(request);+ } finally {+ await transport.close();+ await server.close();+ }+}++// ── Next.js route exports ────────────────────────────────────────────────────++export async function POST(req: Request) {+ return handleMcpRequest(req);+}++export async function GET(req: Request) {+ return handleMcpRequest(req);+}++export async function DELETE(req: Request) {+ return handleMcpRequest(req);+}diff --git a/examples/openui-dashboard/src/app/dashboard/page.tsx b/examples/openui-dashboard/src/app/dashboard/page.tsxnew file mode 100644index 000000000..ad7911616--- /dev/null+++ b/examples/openui-dashboard/src/app/dashboard/page.tsx@@ -0,0 +1,9 @@+"use client";++import { openuiLibrary } from "@openuidev/react-ui/genui-lib";+import { OpenUIDashboard } from "@/components/OpenUIDashboard";+import { STARTERS } from "@/starters";++export default function DashboardPage() {+ return <OpenUIDashboard library={openuiLibrary} starters={STARTERS} />;+}diff --git a/examples/openui-dashboard/src/app/globals.css b/examples/openui-dashboard/src/app/globals.cssnew file mode 100644index 000000000..975bcec94--- /dev/null+++ b/examples/openui-dashboard/src/app/globals.css@@ -0,0 +1,6 @@+@import "tailwindcss";++@keyframes openui-loading-bar {+ 0% { background-position: 200% 0; }+ 100% { background-position: -200% 0; }+}diff --git a/examples/openui-dashboard/src/app/layout.tsx b/examples/openui-dashboard/src/app/layout.tsxnew file mode 100644index 000000000..7e44b0451--- /dev/null+++ b/examples/openui-dashboard/src/app/layout.tsx@@ -0,0 +1,22 @@+import type { Metadata } from "next";+import { ThemeProvider } from "@/hooks/use-system-theme";+import "./globals.css";++export const metadata: Metadata = {+ title: "OpenUI Chat",+ description: "Generative UI Chat with OpenAI SDK",+};++export default function RootLayout({+ children,+}: Readonly<{+ children: React.ReactNode;+}>) {+ return (+ <html lang="en">+ <body>+ <ThemeProvider>{children}</ThemeProvider>+ </body>+ </html>+ );+}diff --git a/examples/openui-dashboard/src/app/page.tsx b/examples/openui-dashboard/src/app/page.tsxnew file mode 100644index 000000000..2faa5d843--- /dev/null+++ b/examples/openui-dashboard/src/app/page.tsx@@ -0,0 +1 @@+export { default } from "./dashboard/page";diff --git a/examples/openui-dashboard/src/components/OpenUIDashboard/ConversationPanel.tsx b/examples/openui-dashboard/src/components/OpenUIDashboard/ConversationPanel.tsxnew file mode 100644index 000000000..7a53d75fd--- /dev/null+++ b/examples/openui-dashboard/src/components/OpenUIDashboard/ConversationPanel.tsx@@ -0,0 +1,200 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { MarkDownRenderer } from "@openuidev/react-ui";+import { useDashboard } from "./context";++export function ConversationPanel() {+ const {+ conversation, isStreaming, streamingText, streamingHasCode,+ llmTools, toolCalls, elapsed, dashboardCode, send,+ } = useDashboard();+ const [input, setInput] = useState("");+ const inputRef = useRef<HTMLInputElement>(null);+ const chatEndRef = useRef<HTMLDivElement>(null);++ const hasDashboard = dashboardCode !== null;+ const canSend = input.trim().length > 0 && !isStreaming;+ const pendingTools = toolCalls.filter((t) => t.status === "pending");++ useEffect(() => { inputRef.current?.focus(); }, [isStreaming]);+ useEffect(() => { chatEndRef.current?.scrollIntoView({ behavior: "smooth" }); }, [conversation]);++ const handleSend = () => {+ if (!canSend) return;+ send(input);+ setInput("");+ };++ return (+ <div style={{+ width: "340px", minWidth: "340px", borderLeft: "1px solid #e5e7eb",+ background: "white", display: "flex", flexDirection: "column",+ }}>+ <div style={{ padding: "12px 16px", borderBottom: "1px solid #e5e7eb", fontSize: "13px", fontWeight: 600, color: "#374151" }}>+ Conversation+ </div>++ <div style={{ flex: 1, overflow: "auto", padding: "12px 16px" }}>+ {conversation.map((msg, i) => (+ <div key={i} style={{ marginBottom: "12px" }}>+ {msg.role === "user" ? (+ <div style={{+ background: "#f0f4ff", color: "#1e40af", padding: "8px 12px",+ borderRadius: "10px", fontSize: "13px", lineHeight: "1.4",+ marginLeft: "40px",+ }}>{msg.content}</div>+ ) : (+ <div style={{ marginRight: "20px" }}>+ {msg.llmTools && msg.llmTools.length > 0 && (+ <div style={{+ padding: "6px 10px", borderRadius: "8px", marginBottom: "6px",+ background: "#f0f4ff", border: "1px solid #dbeafe", fontSize: "11px",+ }}>+ <div style={{ color: "#1d4ed8", fontWeight: 600, marginBottom: "3px", display: "flex", alignItems: "center", gap: "4px" }}>+ <span>🔍</span> Queried data+ </div>+ <div style={{ display: "flex", flexWrap: "wrap", gap: "3px" }}>+ {msg.llmTools.map((tc, j) => (+ <span key={j} style={{+ padding: "1px 6px", borderRadius: "4px",+ background: tc.status === "done" ? "#dbeafe" : "#e0e7ff",+ color: "#1e40af", fontSize: "10px",+ }}>✓ {tc.name}</span>+ ))}+ </div>+ </div>+ )}+ {msg.text && (+ <div style={{+ background: "#f9fafb", border: "1px solid #e5e7eb",+ padding: "8px 12px", borderRadius: "10px", fontSize: "13px",+ lineHeight: "1.5", color: "#374151",+ }}>+ <MarkDownRenderer textMarkdown={msg.text} />+ </div>+ )}+ {msg.hasCode && (+ <div style={{+ display: "inline-flex", alignItems: "center", gap: "4px",+ padding: "2px 8px", borderRadius: "8px", fontSize: "11px",+ background: "#ecfdf5", color: "#059669", marginTop: msg.text ? "4px" : "0",+ }}>✓ dashboard updated</div>+ )}+ {msg.runtimeTools && msg.runtimeTools.length > 0 && (+ <div style={{+ marginTop: "6px", padding: "6px 10px", borderRadius: "8px",+ background: "#f0fdf4", border: "1px solid #bbf7d0", fontSize: "11px",+ }}>+ <div style={{ color: "#15803d", fontWeight: 600, marginBottom: "3px", display: "flex", alignItems: "center", gap: "4px" }}>+ <span>⚡</span> Live data fetched+ </div>+ <div style={{ display: "flex", flexWrap: "wrap", gap: "3px" }}>+ {msg.runtimeTools.map((tc, j) => (+ <span key={j} style={{+ padding: "1px 6px", borderRadius: "4px",+ background: tc.status === "done" ? "#dcfce7" : tc.status === "error" ? "#fef2f2" : "#fef3c7",+ color: tc.status === "done" ? "#166534" : tc.status === "error" ? "#991b1b" : "#92400e",+ fontSize: "10px",+ }}>{tc.status === "done" ? "✓" : tc.status === "error" ? "✗" : "⏳"} {tc.tool}</span>+ ))}+ </div>+ </div>+ )}+ {!msg.text && !msg.hasCode && !msg.llmTools?.length && (+ <div style={{ fontSize: "12px", color: "#9ca3af", fontStyle: "italic" }}>+ (empty response)+ </div>+ )}+ </div>+ )}+ </div>+ ))}++ {isStreaming && (+ <div style={{ marginBottom: "12px", marginRight: "20px" }}>+ {llmTools.length > 0 && llmTools.some((t) => t.status === "calling") && (+ <div style={{ fontSize: "11px", color: "#1d4ed8", marginBottom: "4px", display: "flex", alignItems: "center", gap: "4px" }}>+ <span>🔍</span>+ <span>Querying {llmTools.filter((t) => t.status === "calling").length} tool{llmTools.filter((t) => t.status === "calling").length > 1 ? "s" : ""}...</span>+ </div>+ )}+ {streamingText ? (+ <div style={{+ background: "#f9fafb", border: "1px solid #e5e7eb",+ padding: "8px 12px", borderRadius: "10px", fontSize: "13px",+ lineHeight: "1.5", color: "#374151",+ }}>+ <MarkDownRenderer textMarkdown={streamingText} />+ </div>+ ) : (+ <div style={{+ background: "#f9fafb", border: "1px solid #e5e7eb",+ padding: "8px 12px", borderRadius: "10px", fontSize: "13px", color: "#059669",+ }}>+ {llmTools.length > 0 && llmTools.some((t) => t.status === "calling")+ ? "fetching data before generating..."+ : elapsed+ ? `${(elapsed / 1000).toFixed(1)}s — ${streamingHasCode ? "writing code..." : "thinking..."}`+ : "thinking..."}+ </div>+ )}+ {streamingHasCode && (+ <div style={{+ display: "inline-flex", alignItems: "center", gap: "4px",+ padding: "2px 8px", borderRadius: "8px", fontSize: "11px",+ background: "#ecfdf5", color: "#059669", marginTop: "4px",+ }}>⟳ updating dashboard...</div>+ )}+ {toolCalls.length > 0 && (+ <div style={{+ marginTop: "4px", padding: "4px 8px", borderRadius: "6px",+ background: "#f8fafc", border: "1px solid #e2e8f0", fontSize: "10px",+ }}>+ <div style={{ display: "flex", flexWrap: "wrap", gap: "3px", alignItems: "center" }}>+ <span style={{ color: "#64748b", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.5px" }}>+ {pendingTools.length > 0 ? "Fetching" : "Loaded"}+ </span>+ {toolCalls.map((tc, j) => (+ <span key={j} style={{+ padding: "1px 5px", borderRadius: "3px",+ background: tc.status === "pending" ? "#fef3c7" : tc.status === "done" ? "#ecfdf5" : "#fef2f2",+ color: tc.status === "pending" ? "#92400e" : tc.status === "done" ? "#065f46" : "#991b1b",+ }}>{tc.status === "pending" ? "⏳" : "✓"} {tc.tool}</span>+ ))}+ </div>+ </div>+ )}+ </div>+ )}+ <div ref={chatEndRef} />+ </div>++ <div style={{ padding: "12px 16px", borderTop: "1px solid #e5e7eb" }}>+ <div style={{ display: "flex", gap: "8px" }}>+ <input+ ref={inputRef}+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onKeyDown={(e) => { if (e.key === "Enter") handleSend(); }}+ placeholder={hasDashboard ? "Ask or edit..." : "Describe a dashboard..."}+ disabled={isStreaming}+ style={{+ flex: 1, padding: "8px 12px", border: "1px solid #d1d5db",+ borderRadius: "8px", fontSize: "13px", outline: "none",+ }}+ />+ <button+ onClick={handleSend}+ disabled={!canSend}+ style={{+ padding: "8px 16px", border: "none", borderRadius: "8px",+ background: canSend ? "#111" : "#d1d5db", color: "white",+ cursor: canSend ? "pointer" : "not-allowed", fontSize: "13px", fontWeight: 600,+ }}+ >{isStreaming ? "..." : "Send"}</button>+ </div>+ </div>+ </div>+ );+}diff --git a/examples/openui-dashboard/src/components/OpenUIDashboard/DashboardCanvas.tsx b/examples/openui-dashboard/src/components/OpenUIDashboard/DashboardCanvas.tsxnew file mode 100644index 000000000..1a3d25433--- /dev/null+++ b/examples/openui-dashboard/src/components/OpenUIDashboard/DashboardCanvas.tsx@@ -0,0 +1,80 @@+"use client";++import { useState } from "react";+import { Renderer } from "@openuidev/react-lang";+import type { Library } from "@openuidev/react-lang";+import { ThemeProvider } from "@openuidev/react-ui";+import { useDashboard } from "./context";++interface DashboardCanvasProps {+ library: Library;+}++export function DashboardCanvas({ library }: DashboardCanvasProps) {+ const { dashboardCode, isStreaming, elapsed, toolProvider, send } = useDashboard();+ const [showSource, setShowSource] = useState(false);++ if (!dashboardCode && !isStreaming) return null;++ return (+ <>+ {dashboardCode && !isStreaming && (+ <div style={{ display: "flex", gap: "12px", marginBottom: "8px", fontSize: "12px", color: "#888" }}>+ {elapsed && <span>{(elapsed / 1000).toFixed(1)}s</span>}+ <button onClick={() => setShowSource(!showSource)} style={{+ background: "none", border: "none", cursor: "pointer",+ color: "#2563eb", fontSize: "12px", padding: 0,+ }}>{showSource ? "Hide code" : "View code"}</button>+ </div>+ )}++ {dashboardCode && showSource && (+ <pre style={{+ background: "#1e1e2e", color: "#cdd6f4", padding: "12px", borderRadius: "8px",+ fontSize: "11px", overflow: "auto", whiteSpace: "pre-wrap", maxHeight: "250px",+ lineHeight: "1.4", marginBottom: "12px",+ }}>{dashboardCode}</pre>+ )}++ {dashboardCode && (+ <div style={{+ border: "1px solid #e2e5e9", borderRadius: "12px", padding: "20px",+ background: "white", minHeight: "200px", boxShadow: "0 1px 3px rgba(0,0,0,0.04)",+ }}>+ <ThemeProvider>+ <Renderer+ response={dashboardCode}+ library={library}+ isStreaming={isStreaming}+ toolProvider={toolProvider}+ queryLoader={+ <div style={{+ position: "absolute", top: 0, left: 0, right: 0, height: "3px",+ background: "linear-gradient(90deg, transparent 0%, #3b82f6 50%, transparent 100%)",+ backgroundSize: "200% 100%",+ animation: "openui-loading-bar 1.5s ease-in-out infinite",+ zIndex: 10,+ }} />+ }+ onAction={(event) => {+ if (event.type === "continue_conversation") {+ const contextText = typeof event.params?.context === "string"+ ? event.params.context : "";+ const text = contextText || event.humanFriendlyMessage || "";+ if (text) send(text);+ }+ }}+ />+ </ThemeProvider>+ </div>+ )}++ {isStreaming && !dashboardCode && (+ <div style={{ textAlign: "center", padding: "40px", color: "#888" }}>+ <div style={{ fontSize: "14px" }}>Generating dashboard...</div>+ {elapsed && <div style={{ fontSize: "12px", marginTop: "4px" }}>{(elapsed / 1000).toFixed(1)}s</div>}+ </div>+ )}+ </>+ );+}diff --git a/examples/openui-dashboard/src/components/OpenUIDashboard/StarterGrid.tsx b/examples/openui-dashboard/src/components/OpenUIDashboard/StarterGrid.tsxnew file mode 100644index 000000000..37f2122cc--- /dev/null+++ b/examples/openui-dashboard/src/components/OpenUIDashboard/StarterGrid.tsx@@ -0,0 +1,40 @@+"use client";++import { useDashboard } from "./context";+import type { Starter } from "@/starters";++interface StarterGridProps {+ starters: Starter[];+}++export function StarterGrid({ starters }: StarterGridProps) {+ const { send } = useDashboard();++ return (+ <div style={{ maxWidth: "700px", margin: "60px auto" }}>+ <div style={{ textAlign: "center", marginBottom: "32px" }}>+ <div style={{ fontSize: "40px", marginBottom: "8px" }}>⚡</div>+ <div style={{ fontSize: "16px", fontWeight: 600, color: "#111" }}>Build a dashboard</div>+ <div style={{ fontSize: "13px", color: "#888", marginTop: "4px" }}>Pick a starter or type your own prompt</div>+ </div>+ <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: "10px" }}>+ {starters.map((s) => (+ <button key={s.prompt} onClick={() => send(s.prompt)} style={{+ padding: "12px", border: "1px solid #e2e5e9", borderRadius: "10px",+ background: "white", cursor: "pointer", fontSize: "13px", textAlign: "left",+ transition: "all 0.15s", lineHeight: "1.4",+ }}+ onMouseEnter={(e) => { e.currentTarget.style.borderColor = "#111"; }}+ onMouseLeave={(e) => { e.currentTarget.style.borderColor = "#e2e5e9"; }}+ >+ <span style={{ fontSize: "16px" }}>{s.icon}</span>+ <div style={{ fontWeight: 600, marginTop: "4px", fontSize: "13px" }}>{s.label}</div>+ <div style={{ color: "#888", fontSize: "11px", marginTop: "2px" }}>+ {s.prompt.length > 50 ? s.prompt.slice(0, 50) + "..." : s.prompt}+ </div>+ </button>+ ))}+ </div>+ </div>+ );+}diff --git a/examples/openui-dashboard/src/components/OpenUIDashboard/context.tsx b/examples/openui-dashboard/src/components/OpenUIDashboard/context.tsxnew file mode 100644index 000000000..d9aecd414--- /dev/null+++ b/examples/openui-dashboard/src/components/OpenUIDashboard/context.tsx@@ -0,0 +1,224 @@+"use client";++import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";+import type { ReactNode } from "react";+import type { McpClientLike } from "@openuidev/react-lang";+import { mergeStatements } from "@openuidev/react-lang";+import { wrapMcpClient } from "@/lib/mcp-tracker";+import type { ToolCallEntry } from "@/lib/mcp-tracker";+import { streamChat } from "@/lib/llm-stream";+import type { LLMToolCall } from "@/lib/llm-stream";+import { extractCodeOnly, extractText, responseHasCode, isPureCode } from "@/lib/response-parser";+import type { ChatMessage } from "./types";++// ── Context shape ────────────────────────────────────────────────────────────++interface DashboardContextValue {+ conversation: ChatMessage[];+ dashboardCode: string | null;+ isStreaming: boolean;+ streamingText: string;+ streamingHasCode: boolean;+ elapsed: number | null;+ llmTools: LLMToolCall[];+ toolCalls: ToolCallEntry[];+ toolProvider: McpClientLike | null;+ send: (text: string) => void;+ clear: () => void;+}++const DashboardContext = createContext<DashboardContextValue | null>(null);++export function useDashboard(): DashboardContextValue {+ const ctx = useContext(DashboardContext);+ if (!ctx) throw new Error("useDashboard must be used within DashboardProvider");+ return ctx;+}++// ── Provider ─────────────────────────────────────────────────────────────────++interface DashboardProviderProps {+ chatEndpoint: string;+ mcpEndpoint: string;+ children: ReactNode;+}++export function DashboardProvider({ chatEndpoint, mcpEndpoint, children }: DashboardProviderProps) {+ const [dashboardCode, setDashboardCode] = useState<string | null>(null);+ const [isStreaming, setIsStreaming] = useState(false);+ const [streamingHasCode, setStreamingHasCode] = useState(false);+ const [startTime, setStartTime] = useState<number | null>(null);+ const [elapsed, setElapsed] = useState<number | null>(null);+ const [toolCalls, setToolCalls] = useState<ToolCallEntry[]>([]);+ const [llmTools, setLlmTools] = useState<LLMToolCall[]>([]);+ const [conversation, setConversation] = useState<ChatMessage[]>([]);+ const [streamingText, setStreamingText] = useState<string>("");+ const [toolProvider, setToolProvider] = useState<McpClientLike | null>(null);+ const abortRef = useRef<AbortController | null>(null);+ const responseRef = useRef("");+ const llmToolCallsRef = useRef<LLMToolCall[]>([]);+ const toolCallsRef = useRef<ToolCallEntry[]>([]);+ const clientRef = useRef<McpClientLike | null>(null);++ useEffect(() => {+ let cancelled = false;+ (async () => {+ try {+ const { Client } = await import("@modelcontextprotocol/sdk/client/index.js");+ const { StreamableHTTPClientTransport } = await import("@modelcontextprotocol/sdk/client/streamableHttp.js");+ const client = new Client({ name: "openui-dashboard", version: "1.0.0" });+ const transport = new StreamableHTTPClientTransport(new URL(mcpEndpoint, globalThis.location.href));+ await client.connect(transport);+ if (cancelled) { client.close?.(); return; }+ const mcpClient = client as unknown as McpClientLike;+ clientRef.current = mcpClient;+ setToolProvider(wrapMcpClient(mcpClient, (calls) => {+ toolCallsRef.current = calls;+ setToolCalls(calls);+ setConversation((prev) => {+ if (prev.length === 0) return prev;+ const last = prev[prev.length - 1];+ if (last.role !== "assistant") return prev;+ return [...prev.slice(0, -1), { ...last, runtimeTools: calls }];+ });+ }));+ } catch (err) {+ console.error("[mcp] Failed:", err);+ }+ })();+ return () => { cancelled = true; clientRef.current?.close?.(); };+ }, [mcpEndpoint]);++ useEffect(() => {+ const p = new URLSearchParams(window.location.search).get("code");+ if (p) { try { setDashboardCode(atob(p)); } catch { /* */ } }+ }, []);++ useEffect(() => {+ if (!isStreaming || !startTime) return;+ const iv = setInterval(() => setElapsed(Date.now() - startTime), 100);+ return () => clearInterval(iv);+ }, [isStreaming, startTime]);++ const send = useCallback(+ async (text: string) => {+ if (!text.trim() || isStreaming) return;+ const trimmed = text.trim();+ setIsStreaming(true);+ setStreamingHasCode(false);+ setStartTime(null);+ setElapsed(null);+ toolCallsRef.current = [];+ setToolCalls([]);+ responseRef.current = "";+ llmToolCallsRef.current = [];+ setStreamingText("");+ let streamStartTime: number | null = null;++ const userMsg: ChatMessage = { role: "user", content: trimmed, hasCode: false };+ const updated = [...conversation, userMsg];+ setConversation(updated);+ const existingCode = dashboardCode;++ const apiMessages = updated.map((m, i) => {+ if (m.role === "assistant" && m.llmTools?.length) {+ const toolSummary = m.llmTools+ .map((tc) => {+ const snippet = tc.result ? ` → ${tc.result.slice(0, 500)}` : " → completed";+ return `[Tool: ${tc.name}${snippet}]`;+ })+ .join("\n");+ return { role: m.role, content: `${toolSummary}\n\n${m.content}` };+ }+ if (m.role === "user" && i === updated.length - 1 && existingCode) {+ return {+ role: m.role,+ content: `${m.content}\n\n<current-dashboard>\n${existingCode}\n</current-dashboard>`,+ };+ }+ return { role: m.role, content: m.content };+ });++ const controller = new AbortController();+ abortRef.current = controller;++ await streamChat(+ chatEndpoint,+ apiMessages,+ (chunk) => {+ responseRef.current += chunk;+ const raw = responseRef.current;+ setStreamingText(extractText(raw) || "");+ if (responseHasCode(raw)) setStreamingHasCode(true);+ setDashboardCode(existingCode ? existingCode + "\n" + raw : raw);+ },+ () => {+ setIsStreaming(false);+ setStreamingText("");+ if (streamStartTime) setElapsed(Date.now() - streamStartTime);++ const raw = responseRef.current;+ const hasCode = responseHasCode(raw);+ const pureCode = isPureCode(raw);+ const text = pureCode ? undefined : extractText(raw) || undefined;+ const llmToolsCurrent = llmToolCallsRef.current;++ setConversation((prev) => [+ ...prev,+ {+ role: "assistant",+ content: raw,+ text,+ hasCode,+ llmTools: llmToolsCurrent.length > 0 ? [...llmToolsCurrent] : undefined,+ runtimeTools: toolCallsRef.current.length > 0 ? [...toolCallsRef.current] : undefined,+ },+ ]);++ if (hasCode) {+ const newCode = pureCode ? raw : extractCodeOnly(raw);+ if (newCode) {+ setDashboardCode(existingCode ? mergeStatements(existingCode, newCode) : newCode);+ }+ }+ },+ (calls) => {+ llmToolCallsRef.current = calls;+ setLlmTools(calls);+ },+ controller.signal,+ () => { streamStartTime = Date.now(); setStartTime(streamStartTime); },+ );+ },+ [isStreaming, conversation, dashboardCode, chatEndpoint],+ );++ const clear = () => {+ abortRef.current?.abort();+ setDashboardCode(null);+ setConversation([]);+ setIsStreaming(false);+ setStreamingHasCode(false);+ setStartTime(null);+ setElapsed(null);+ responseRef.current = "";+ };++ return (+ <DashboardContext.Provider value={{+ conversation,+ dashboardCode,+ isStreaming,+ streamingText,+ streamingHasCode,+ elapsed,+ llmTools,+ toolCalls,+ toolProvider,+ send,+ clear,+ }}>+ {children}+ </DashboardContext.Provider>+ );+}diff --git a/examples/openui-dashboard/src/components/OpenUIDashboard/index.tsx b/examples/openui-dashboard/src/components/OpenUIDashboard/index.tsxnew file mode 100644index 000000000..1fc4de287--- /dev/null+++ b/examples/openui-dashboard/src/components/OpenUIDashboard/index.tsx@@ -0,0 +1,181 @@+"use client";++import type { Starter } from "@/starters";+import type { Library } from "@openuidev/react-lang";+import "@openuidev/react-ui/components.css";+import { useRef, useState } from "react";+import { DashboardProvider, useDashboard } from "./context";+import { ConversationPanel } from "./ConversationPanel";+import { DashboardCanvas } from "./DashboardCanvas";+import { StarterGrid } from "./StarterGrid";++export { useDashboard } from "./context";++// ── Internal layout ───────────────────────────────────────────────────────────++function DashboardLayout({ library, starters }: { library: Library; starters: Starter[] }) {+ const { conversation, dashboardCode, isStreaming, clear } = useDashboard();+ const hasDashboard = dashboardCode !== null;+ const isEmpty = conversation.length === 0 && !hasDashboard;++ return (+ <div+ style={{+ minHeight: "100vh",+ background: "#fafbfc",+ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',+ }}+ >+ {/* Top bar */}+ <div+ style={{+ borderBottom: "1px solid #e5e7eb",+ background: "white",+ padding: "12px 24px",+ display: "flex",+ alignItems: "center",+ gap: "16px",+ }}+ >+ <h1 style={{ fontSize: "16px", fontWeight: 700, margin: 0 }}>openui-lang</h1>+ <span style={{ fontSize: "12px", color: "#888" }}>Live Demo</span>+ <div style={{ display: "flex", gap: "6px", marginLeft: "auto" }}>+ {["Live Data", "Streaming", "Conversational"].map((label, i) => (+ <span+ key={label}+ style={{+ padding: "2px 8px",+ borderRadius: "12px",+ fontSize: "11px",+ fontWeight: 500,+ background: ["#ecfdf5", "#eff6ff", "#fef3c7"][i],+ color: ["#059669", "#2563eb", "#d97706"][i],+ }}+ >+ {label}+ </span>+ ))}+ </div>+ {(hasDashboard || conversation.length > 0) && (+ <button+ onClick={clear}+ style={{+ padding: "4px 12px",+ border: "1px solid #d1d5db",+ borderRadius: "6px",+ background: "white",+ cursor: "pointer",+ fontSize: "12px",+ color: "#666",+ }}+ >+ Clear+ </button>+ )}+ </div>++ {/* Main layout */}+ <div style={{ display: "flex", height: "calc(100vh - 49px)" }}>+ <div+ style={{+ flex: hasDashboard ? "1 1 60%" : "1 1 100%",+ overflow: "auto",+ padding: "20px",+ transition: "flex 0.3s",+ }}+ >+ {isEmpty && <StarterGrid starters={starters} />}+ <DashboardCanvas library={library} />+ </div>+ {(conversation.length > 0 || isStreaming) && <ConversationPanel />}+ </div>++ {isEmpty && !isStreaming && <CenteredInput />}+ </div>+ );+}++function CenteredInput() {+ const { send, isStreaming } = useDashboard();+ const [input, setInput] = useState("");+ const inputRef = useRef<HTMLInputElement>(null);+ const canSend = input.trim().length > 0 && !isStreaming;++ const handleSend = () => {+ if (!canSend) return;+ send(input);+ setInput("");+ };++ return (+ <div+ style={{+ position: "fixed",+ bottom: "24px",+ left: "50%",+ transform: "translateX(-50%)",+ width: "min(600px, calc(100% - 48px))",+ }}+ >+ <div style={{ display: "flex", gap: "8px" }}>+ <input+ ref={inputRef}+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") handleSend();+ }}+ placeholder="Describe a dashboard..."+ style={{+ flex: 1,+ padding: "14px 18px",+ border: "1px solid #d1d5db",+ borderRadius: "12px",+ fontSize: "14px",+ outline: "none",+ boxShadow: "0 2px 8px rgba(0,0,0,0.08)",+ }}+ />+ <button+ onClick={handleSend}+ disabled={!canSend}+ style={{+ padding: "14px 24px",+ border: "none",+ borderRadius: "12px",+ background: canSend ? "#111" : "#d1d5db",+ color: "white",+ cursor: canSend ? "pointer" : "not-allowed",+ fontSize: "14px",+ fontWeight: 600,+ boxShadow: "0 2px 8px rgba(0,0,0,0.08)",+ }}+ >+ Send+ </button>+ </div>+ </div>+ );+}++// ── Public component ──────────────────────────────────────────────────────────++export interface OpenUIDashboardProps {+ library: Library;+ starters?: Starter[];+ chatEndpoint?: string;+ mcpEndpoint?: string;+}++export function OpenUIDashboard({+ library,+ starters = [],+ chatEndpoint = "/api/chat",+ mcpEndpoint = "/api/mcp",+}: OpenUIDashboardProps) {+ return (+ <DashboardProvider chatEndpoint={chatEndpoint} mcpEndpoint={mcpEndpoint}>+ <DashboardLayout library={library} starters={starters} />+ </DashboardProvider>+ );+}diff --git a/examples/openui-dashboard/src/components/OpenUIDashboard/types.ts b/examples/openui-dashboard/src/components/OpenUIDashboard/types.tsnew file mode 100644index 000000000..e80ae93a9--- /dev/null+++ b/examples/openui-dashboard/src/components/OpenUIDashboard/types.ts@@ -0,0 +1,11 @@+import type { LLMToolCall } from "@/lib/llm-stream";+import type { ToolCallEntry } from "@/lib/mcp-tracker";++export interface ChatMessage {+ role: "user" | "assistant";+ content: string;+ text?: string;+ hasCode: boolean;+ llmTools?: LLMToolCall[];+ runtimeTools?: ToolCallEntry[];+}diff --git a/examples/openui-dashboard/src/generated/component-spec.json b/examples/openui-dashboard/src/generated/component-spec.jsonnew file mode 100644index 000000000..c10423427--- /dev/null+++ b/examples/openui-dashboard/src/generated/component-spec.json@@ -0,0 +1,372 @@+{+ "root": "Stack",+ "components": {+ "Card": {+ "signature": "Card(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps | Tabs | Carousel | Stack)[], variant?: \"card\" | \"sunk\" | \"clear\", direction?: \"row\" | \"column\", gap?: \"none\" | \"xs\" | \"s\" | \"m\" | \"l\" | \"xl\" | \"2xl\", align?: \"start\" | \"center\" | \"end\" | \"stretch\" | \"baseline\", justify?: \"start\" | \"center\" | \"end\" | \"between\" | \"around\" | \"evenly\", wrap?: boolean)",+ "description": "Styled container. variant: \"card\" (default, elevated) | \"sunk\" (recessed) | \"clear\" (transparent). Always full width. Accepts all Stack flex params (default: direction \"column\"). Cards flex to share space in row/wrap layouts."+ },+ "CardHeader": {+ "signature": "CardHeader(title?: string, subtitle?: string)",+ "description": "Header with optional title and subtitle"+ },+ "TextContent": {+ "signature": "TextContent(text: string, size?: \"small\" | \"default\" | \"large\" | \"small-heavy\" | \"large-heavy\")",+ "description": "Text block. Supports markdown. Optional size: \"small\" | \"default\" | \"large\" | \"small-heavy\" | \"large-heavy\"."+ },+ "MarkDownRenderer": {+ "signature": "MarkDownRenderer(textMarkdown: string, variant?: \"clear\" | \"card\" | \"sunk\")",+ "description": "Renders markdown text with optional container variant"+ },+ "Callout": {+ "signature": "Callout(variant: \"info\" | \"warning\" | \"error\" | \"success\" | \"neutral\", title: string, description: string, visible?: $binding<boolean>)",+ "description": "Callout banner. Optional visible is a reactive $boolean — auto-dismisses after 3s by setting $visible to false."+ },+ "TextCallout": {+ "signature": "TextCallout(variant?: \"neutral\" | \"info\" | \"warning\" | \"success\" | \"danger\", title?: string, description?: string)",+ "description": "Text callout with variant, title, and description"+ },+ "Image": {+ "signature": "Image(alt: string, src?: string)",+ "description": "Image with alt text and optional URL"+ },+ "ImageBlock": {+ "signature": "ImageBlock(src: string, alt?: string)",+ "description": "Image block with loading state"+ },+ "ImageGallery": {+ "signature": "ImageGallery(images: {src: string, alt?: string, details?: string}[])",+ "description": "Gallery grid of images with modal preview"+ },+ "CodeBlock": {+ "signature": "CodeBlock(language: string, codeString: string)",+ "description": "Syntax-highlighted code block"+ },+ "Table": {+ "signature": "Table(columns: Col[])",+ "description": "Data table — column-oriented. Each Col holds its own data array."+ },+ "Col": {+ "signature": "Col(label: string, data, type?: \"string\" | \"number\" | \"action\")",+ "description": "Column definition — holds label + data array"+ },+ "BarChart": {+ "signature": "BarChart(labels: string[], series: Series[], variant?: \"grouped\" | \"stacked\", xLabel?: string, yLabel?: string)",+ "description": "Vertical bars; use for comparing values across categories with one or more series"+ },+ "LineChart": {+ "signature": "LineChart(labels: string[], series: Series[], variant?: \"linear\" | \"natural\" | \"step\", xLabel?: string, yLabel?: string)",+ "description": "Lines over categories; use for trends and continuous data over time"+ },+ "AreaChart": {+ "signature": "AreaChart(labels: string[], series: Series[], variant?: \"linear\" | \"natural\" | \"step\", xLabel?: string, yLabel?: string)",+ "description": "Filled area under lines; use for cumulative totals or volume trends over time"+ },+ "RadarChart": {+ "signature": "RadarChart(labels: string[], series: Series[])",+ "description": "Spider/web chart; use for comparing multiple variables across one or more entities"+ },+ "HorizontalBarChart": {+ "signature": "HorizontalBarChart(labels: string[], series: Series[], variant?: \"grouped\" | \"stacked\", xLabel?: string, yLabel?: string)",+ "description": "Horizontal bars; prefer when category labels are long or for ranked lists"+ },+ "Series": {+ "signature": "Series(category: string, values: number[])",+ "description": "One data series"+ },+ "PieChart": {+ "signature": "PieChart(labels: string[], values: number[], variant?: \"pie\" | \"donut\")",+ "description": "Circular slices; use plucked arrays: PieChart(data.categories, data.values)"+ },+ "RadialChart": {+ "signature": "RadialChart(labels: string[], values: number[])",+ "description": "Radial bars; use plucked arrays: RadialChart(data.categories, data.values)"+ },+ "SingleStackedBarChart": {+ "signature": "SingleStackedBarChart(labels: string[], values: number[])",+ "description": "Single horizontal stacked bar; use plucked arrays: SingleStackedBarChart(data.categories, data.values)"+ },+ "Slice": {+ "signature": "Slice(category: string, value: number)",+ "description": "One slice with label and numeric value"+ },+ "ScatterChart": {+ "signature": "ScatterChart(datasets: ScatterSeries[], xLabel?: string, yLabel?: string)",+ "description": "X/Y scatter plot; use for correlations, distributions, and clustering"+ },+ "ScatterSeries": {+ "signature": "ScatterSeries(name: string, points: Point[])",+ "description": "Named dataset"+ },+ "Point": {+ "signature": "Point(x: number, y: number, z?: number)",+ "description": "Data point with numeric coordinates"+ },+ "Form": {+ "signature": "Form(name: string, buttons: Buttons, fields)",+ "description": "Form container with fields and explicit action buttons"+ },+ "FormControl": {+ "signature": "FormControl(label: string, input: Input | TextArea | Select | DatePicker | Slider | CheckBoxGroup | RadioGroup, hint?: string)",+ "description": "Field with label, input component, and optional hint text"+ },+ "Label": {+ "signature": "Label(text: string)",+ "description": "Text label"+ },+ "Input": {+ "signature": "Input(name: string, placeholder?: string, type?: \"text\" | \"email\" | \"password\" | \"number\" | \"url\", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)",+ "description": ""+ },+ "TextArea": {+ "signature": "TextArea(name: string, placeholder?: string, rows?: number, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)",+ "description": ""+ },+ "Select": {+ "signature": "Select(name: string, items: SelectItem[], placeholder?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)",+ "description": ""+ },+ "SelectItem": {+ "signature": "SelectItem(value: string, label: string)",+ "description": "Option for Select"+ },+ "DatePicker": {+ "signature": "DatePicker(name: string, mode?: \"single\" | \"range\", rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?)",+ "description": ""+ },+ "Slider": {+ "signature": "Slider(name: string, variant: \"continuous\" | \"discrete\", min: number, max: number, step?: number, defaultValue?: number[], label?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<number[]>)",+ "description": "Numeric slider input; supports continuous and discrete (stepped) variants"+ },+ "CheckBoxGroup": {+ "signature": "CheckBoxGroup(name: string, items: CheckBoxItem[], rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?)",+ "description": ""+ },+ "CheckBoxItem": {+ "signature": "CheckBoxItem(label: string, description: string, name: string, defaultChecked?: boolean)",+ "description": ""+ },+ "RadioGroup": {+ "signature": "RadioGroup(name: string, items: RadioItem[], defaultValue?: string, rules?: {required?: boolean, email?: boolean, url?: boolean, numeric?: boolean, min?: number, max?: number, minLength?: number, maxLength?: number, pattern?: string}, value?: $binding<string>)",+ "description": ""+ },+ "RadioItem": {+ "signature": "RadioItem(label: string, description: string, value: string)",+ "description": ""+ },+ "SwitchGroup": {+ "signature": "SwitchGroup(name: string, items: SwitchItem[], variant?: \"clear\" | \"card\" | \"sunk\", value?)",+ "description": "Group of switch toggles"+ },+ "SwitchItem": {+ "signature": "SwitchItem(label?: string, description?: string, name: string, defaultChecked?: boolean)",+ "description": "Individual switch toggle"+ },+ "Button": {+ "signature": "Button(label: string, action?: ActionExpression, variant?: \"primary\" | \"secondary\" | \"tertiary\", type?: \"normal\" | \"destructive\", size?: \"extra-small\" | \"small\" | \"medium\" | \"large\")",+ "description": "Clickable button"+ },+ "Buttons": {+ "signature": "Buttons(buttons: Button[], direction?: \"row\" | \"column\")",+ "description": "Group of Button components. direction: \"row\" (default) | \"column\"."+ },+ "Stack": {+ "signature": "Stack([children], direction?: \"row\" | \"column\", gap?: \"none\" | \"xs\" | \"s\" | \"m\" | \"l\" | \"xl\" | \"2xl\", align?: \"start\" | \"center\" | \"end\" | \"stretch\" | \"baseline\", justify?: \"start\" | \"center\" | \"end\" | \"between\" | \"around\" | \"evenly\", wrap?: boolean)",+ "description": "Flex container. direction: \"row\"|\"column\" (default \"column\"). gap: \"none\"|\"xs\"|\"s\"|\"m\"|\"l\"|\"xl\"|\"2xl\" (default \"m\"). align: \"start\"|\"center\"|\"end\"|\"stretch\"|\"baseline\". justify: \"start\"|\"center\"|\"end\"|\"between\"|\"around\"|\"evenly\"."+ },+ "Tabs": {+ "signature": "Tabs(items: TabItem[])",+ "description": "Tabbed container"+ },+ "TabItem": {+ "signature": "TabItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[])",+ "description": "value is unique id, trigger is tab label, content is array of components"+ },+ "Accordion": {+ "signature": "Accordion(items: AccordionItem[])",+ "description": "Collapsible sections"+ },+ "AccordionItem": {+ "signature": "AccordionItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[])",+ "description": "value is unique id, trigger is section title"+ },+ "Steps": {+ "signature": "Steps(items: StepsItem[])",+ "description": "Step-by-step guide"+ },+ "StepsItem": {+ "signature": "StepsItem(title: string, details: string)",+ "description": "title and details text for one step"+ },+ "Carousel": {+ "signature": "Carousel(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[][], variant?: \"card\" | \"sunk\")",+ "description": "Horizontal scrollable carousel"+ },+ "Separator": {+ "signature": "Separator(orientation?: \"horizontal\" | \"vertical\", decorative?: boolean)",+ "description": "Visual divider between content sections"+ },+ "TagBlock": {+ "signature": "TagBlock(tags: string[])",+ "description": "tags is an array of strings"+ },+ "Tag": {+ "signature": "Tag(text: string, icon?: string, size?: \"sm\" | \"md\" | \"lg\", variant?: \"neutral\" | \"info\" | \"success\" | \"warning\" | \"danger\")",+ "description": "Styled tag/badge with optional icon and variant"+ },+ "Modal": {+ "signature": "Modal(title: string, open?: $binding<boolean>, children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[], size?: \"sm\" | \"md\" | \"lg\")",+ "description": "Modal dialog. open is a reactive $boolean binding — set to true to open, X/Escape/backdrop auto-closes. Put Form with buttons inside children."+ }+ },+ "componentGroups": [+ {+ "name": "Layout",+ "components": [+ "Stack",+ "Tabs",+ "TabItem",+ "Accordion",+ "AccordionItem",+ "Steps",+ "StepsItem",+ "Carousel",+ "Separator",+ "Modal"+ ],+ "notes": [+ "- For grid-like layouts, use Stack with direction \"row\" and wrap set to true.",+ "- Prefer justify \"start\" (or omit justify) with wrap=true for stable columns instead of uneven gutters.",+ "- Use nested Stacks when you need explicit rows/sections.",+ "- Show/hide sections: $editId != \"\" ? Card([editForm]) : null",+ "- Modal: Modal(\"Title\", $showModal, [content]) — $showModal is boolean, X/Escape auto-closes. Put Form with its own buttons inside children.",+ "- Use Tabs for alternative views (chart types, data sections) — no $variable needed",+ "- Shared filter across Tabs: same $days binding in Query args works across all TabItems"+ ]+ },+ {+ "name": "Content",+ "components": [+ "Card",+ "CardHeader",+ "TextContent",+ "MarkDownRenderer",+ "Callout",+ "TextCallout",+ "Image",+ "ImageBlock",+ "ImageGallery",+ "CodeBlock"+ ],+ "notes": [+ "- Use Cards to group related KPIs or sections. Stack with direction \"row\" for side-by-side layouts.",+ "- Success toast: Callout(\"success\", \"Saved\", \"Done.\", $showSuccess) — use @Set($showSuccess, true) in save action, auto-dismisses after 3s. For errors: result.status == \"error\" ? Callout(\"error\", \"Failed\", result.error) : null",+ "- KPI card: Card([TextContent(\"Label\", \"small\"), TextContent(\"\" + @Count(@Filter(data.rows, \"field\", \"==\", \"value\")), \"large-heavy\")])"+ ]+ },+ {+ "name": "Tables",+ "components": [+ "Table",+ "Col"+ ],+ "notes": [+ "- Table is COLUMN-oriented: Table([Col(\"Label\", dataArray), Col(\"Count\", countArray, \"number\")]). Use array pluck for data: data.rows.fieldName",+ "- Col data can be component arrays for styled cells: Col(\"Status\", @Each(data.rows, \"item\", Tag(item.status, null, \"sm\", item.status == \"open\" ? \"success\" : \"danger\")))",+ "- Row actions: Col(\"Actions\", @Each(data.rows, \"t\", Button(\"Edit\", Action([@Set($showEdit, true), @Set($editId, t.id)]))))",+ "- Sortable: sorted = @Sort(data.rows, $sortField, \"desc\"). Bind $sortField to Select. Use sorted.fieldName for Col data",+ "- Searchable: filtered = @Filter(data.rows, \"title\", \"contains\", $search). Bind $search to Input",+ "- Chain sort + filter: filtered = @Filter(...) then sorted = @Sort(filtered, ...) — use sorted for both Table and Charts",+ "- Empty state: @Count(data.rows) > 0 ? Table([...]) : TextContent(\"No data yet\")"+ ]+ },+ {+ "name": "Charts (2D)",+ "components": [+ "BarChart",+ "LineChart",+ "AreaChart",+ "RadarChart",+ "HorizontalBarChart",+ "Series"+ ],+ "notes": [+ "- Charts accept column arrays: LineChart(labels, [Series(\"Name\", values)]). Use array pluck: LineChart(data.rows.day, [Series(\"Views\", data.rows.views)])",+ "- Use Cards to wrap charts with CardHeader for titled sections",+ "- Chart + Table from same source: use @Sort or @Filter result for both LineChart and Table Col data",+ "- Multiple chart views: use Tabs — Tabs([TabItem(\"line\", \"Line\", [LineChart(...)]), TabItem(\"bar\", \"Bar\", [BarChart(...)])])"+ ]+ },+ {+ "name": "Charts (1D)",+ "components": [+ "PieChart",+ "RadialChart",+ "SingleStackedBarChart",+ "Slice"+ ],+ "notes": [+ "- PieChart and BarChart need NUMBERS, not objects. For list data, use @Count(@Filter(...)) to aggregate:",+ "- PieChart from list: `PieChart([\"Low\", \"Med\", \"High\"], [@Count(@Filter(data.rows, \"priority\", \"==\", \"low\")), @Count(@Filter(data.rows, \"priority\", \"==\", \"medium\")), @Count(@Filter(data.rows, \"priority\", \"==\", \"high\"))], \"donut\")`",+ "- KPI from count: `TextContent(\"\" + @Count(@Filter(data.rows, \"status\", \"==\", \"open\")), \"large-heavy\")`"+ ]+ },+ {+ "name": "Charts (Scatter)",+ "components": [+ "ScatterChart",+ "ScatterSeries",+ "Point"+ ]+ },+ {+ "name": "Forms",+ "components": [+ "Form",+ "FormControl",+ "Label",+ "Input",+ "TextArea",+ "Select",+ "SelectItem",+ "DatePicker",+ "Slider",+ "CheckBoxGroup",+ "CheckBoxItem",+ "RadioGroup",+ "RadioItem",+ "SwitchGroup",+ "SwitchItem"+ ],+ "notes": [+ "- For Form fields, define EACH FormControl as its own reference — do NOT inline all controls in one array. This allows progressive field-by-field streaming.",+ "- NEVER nest Form inside Form — each Form should be a standalone container.",+ "- Form requires explicit buttons. Always pass a Buttons(...) reference as the third Form argument.",+ "- rules is an optional object: {required: true, email: true, minLength: 8, maxLength: 100}",+ "- Available rules: required, email, min, max, minLength, maxLength, pattern, url, numeric",+ "- The renderer shows error messages automatically — do NOT generate error text in the UI",+ "- Conditional fields: $country == \"US\" ? stateField : $country == \"UK\" ? postcodeField : addressField",+ "- Edit form in Modal: Modal(\"Edit\", $showEdit, [Form(\"edit\", Buttons([saveBtn, cancelBtn]), [fields...])]). Save button should include @Set($showEdit, false) to close modal."+ ]+ },+ {+ "name": "Buttons",+ "components": [+ "Button",+ "Buttons"+ ],+ "notes": [+ "- Toggle in @Each: @Each(rows, \"t\", Button(t.status == \"open\" ? \"Close\" : \"Reopen\", Action([...])))"+ ]+ },+ {+ "name": "Data Display",+ "components": [+ "TagBlock",+ "Tag"+ ],+ "notes": [+ "- Color-mapped Tag: Tag(value, null, \"sm\", value == \"high\" ? \"danger\" : value == \"medium\" ? \"warning\" : \"neutral\")"+ ]+ }+ ]+}diff --git a/examples/openui-dashboard/src/hooks/use-system-theme.tsx b/examples/openui-dashboard/src/hooks/use-system-theme.tsxnew file mode 100644index 000000000..2a95a534d--- /dev/null+++ b/examples/openui-dashboard/src/hooks/use-system-theme.tsx@@ -0,0 +1,41 @@+"use client";++import { createContext, useContext, useEffect, useState } from "react";++type ThemeMode = "light" | "dark";++interface ThemeContextType {+ mode: ThemeMode;+}++const ThemeContext = createContext<ThemeContextType | undefined>(undefined);++function getSystemMode(): ThemeMode {+ if (typeof window === "undefined") return "light";+ return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";+}++export function ThemeProvider({ children }: { children: React.ReactNode }) {+ const [mode, setMode] = useState<ThemeMode>(getSystemMode);++ useEffect(() => {+ const mq = window.matchMedia("(prefers-color-scheme: dark)");+ const handler = (e: MediaQueryListEvent) => setMode(e.matches ? "dark" : "light");+ mq.addEventListener("change", handler);+ return () => mq.removeEventListener("change", handler);+ }, []);++ useEffect(() => {+ document.body.setAttribute("data-theme", mode);+ }, [mode]);++ return <ThemeContext.Provider value={{ mode }}>{children}</ThemeContext.Provider>;+}++export function useTheme(): ThemeMode {+ const ctx = useContext(ThemeContext);+ if (!ctx) {+ throw new Error("useTheme must be used within a ThemeProvider");+ }+ return ctx.mode;+}diff --git a/examples/openui-dashboard/src/lib/llm-stream.ts b/examples/openui-dashboard/src/lib/llm-stream.tsnew file mode 100644index 000000000..afbadd8e2--- /dev/null+++ b/examples/openui-dashboard/src/lib/llm-stream.ts@@ -0,0 +1,87 @@+export type LLMToolCall = { id: string; name: string; status: "calling" | "done"; result?: string };++export async function streamChat(+ endpoint: string,+ messages: Array<{ role: string; content: string }>,+ onChunk: (text: string) => void,+ onDone: (usage?: { prompt_tokens?: number; completion_tokens?: number }) => void,+ onToolCall: (calls: LLMToolCall[]) => void,+ signal?: AbortSignal,+ onFirstChunk?: () => void,+) {+ const activeCalls: LLMToolCall[] = [];+ onToolCall([]);++ const res = await fetch(endpoint, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ messages }),+ signal,+ });++ if (!res.ok) {+ const err = await res.text();+ onChunk(`Error: ${err}`);+ onDone();+ return;+ }++ const reader = res.body!.getReader();+ const decoder = new TextDecoder();+ let buffer = "";+ let lastUsage: { prompt_tokens?: number; completion_tokens?: number } | undefined;+ let firstChunkFired = false;++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });++ const lines = buffer.split("\n");+ buffer = lines.pop() ?? "";++ for (const line of lines) {+ if (!line.startsWith("data: ")) continue;+ const data = line.slice(6).trim();+ if (data === "[DONE]") {+ for (const tc of activeCalls) {+ if (tc.status === "calling") tc.status = "done";+ }+ onToolCall([...activeCalls]);+ onDone(lastUsage);+ return;+ }+ try {+ const chunk = JSON.parse(data);+ const tcDeltas = chunk.choices?.[0]?.delta?.tool_calls;+ if (tcDeltas) {+ for (const tc of tcDeltas) {+ if (tc.id && tc.function?.name) {+ activeCalls.push({ id: tc.id, name: tc.function.name, status: "calling" });+ onToolCall([...activeCalls]);+ } else if (tc.function?.arguments) {+ const existing = activeCalls[tc.index];+ if (existing) {+ existing.status = "done";+ try {+ const parsed = JSON.parse(tc.function.arguments);+ if (parsed._response) {+ existing.result = JSON.stringify(parsed._response).slice(0, 2000);+ }+ } catch { /* ignore parse errors */ }+ onToolCall([...activeCalls]);+ }+ }+ }+ }+ const content = chunk.choices?.[0]?.delta?.content;+ if (content) {+ if (!firstChunkFired) { firstChunkFired = true; onFirstChunk?.(); }+ onChunk(content);+ }+ if (chunk.usage) lastUsage = chunk.usage;+ } catch { /* skip malformed chunks */ }+ }+ }+ onDone(lastUsage);+}diff --git a/examples/openui-dashboard/src/lib/mcp-tracker.ts b/examples/openui-dashboard/src/lib/mcp-tracker.tsnew file mode 100644index 000000000..ea5addd38--- /dev/null+++ b/examples/openui-dashboard/src/lib/mcp-tracker.ts@@ -0,0 +1,28 @@+import type { McpClientLike } from "@openuidev/react-lang";++export type ToolCallEntry = { tool: string; status: "pending" | "done" | "error" };++export function wrapMcpClient(+ client: McpClientLike,+ onToolCall: (calls: ToolCallEntry[]) => void,+): McpClientLike {+ const activeCalls: ToolCallEntry[] = [];+ return {+ ...client,+ callTool: async (params, options) => {+ const entry: ToolCallEntry = { tool: params.name, status: "pending" };+ activeCalls.push(entry);+ onToolCall([...activeCalls]);+ try {+ const result = await client.callTool(params, options);+ entry.status = "done";+ onToolCall([...activeCalls]);+ return result;+ } catch (err) {+ entry.status = "error";+ onToolCall([...activeCalls]);+ throw err;+ }+ },+ };+}diff --git a/examples/openui-dashboard/src/lib/response-parser.ts b/examples/openui-dashboard/src/lib/response-parser.tsnew file mode 100644index 000000000..9744e4030--- /dev/null+++ b/examples/openui-dashboard/src/lib/response-parser.ts@@ -0,0 +1,39 @@+export function extractCodeOnly(response: string): string | null {+ const fenceRegex = /```[\w-]*\n([\s\S]*?)```/g;+ const blocks: string[] = [];+ let match;+ while ((match = fenceRegex.exec(response)) !== null) {+ blocks.push(match[1].trim());+ }+ if (blocks.length > 0) return blocks.join("\n");++ const unclosedMatch = response.match(/```[\w-]*\n([\s\S]*)$/);+ if (unclosedMatch) return unclosedMatch[1].trim() || null;++ if (isPureCode(response)) return response;++ return null;+}++export function extractText(response: string): string {+ const withoutFences = response.replace(/```[\w-]*\n[\s\S]*?```/g, "").trim();+ const withoutUnclosed = withoutFences.replace(/```[\w-]*\n[\s\S]*$/g, "").trim();+ if (withoutUnclosed && isPureCode(withoutUnclosed)) return "";+ return withoutUnclosed;+}++export function responseHasCode(response: string): boolean {+ if (/```[\w-]*\n/.test(response)) return true;+ if (/^[a-zA-Z_$][\w$]*\s*=\s*/.test(response.trim())) return true;+ return false;+}++export function isPureCode(response: string): boolean {+ const trimmed = response.trim();+ if (/```/.test(trimmed)) return false;+ const lines = trimmed.split("\n").filter((l) => l.trim());+ if (lines.length === 0) return false;+ const stmtPattern = /^[a-zA-Z_$][\w$]*\s*=/;+ const stmtCount = lines.filter((l) => stmtPattern.test(l.trim())).length;+ return stmtCount / lines.length > 0.7;+}diff --git a/examples/openui-dashboard/src/lib/sse-stream.ts b/examples/openui-dashboard/src/lib/sse-stream.tsnew file mode 100644index 000000000..aedfe4c50--- /dev/null+++ b/examples/openui-dashboard/src/lib/sse-stream.ts@@ -0,0 +1,115 @@+import type { ChatCompletionStreamingRunner } from "openai/lib/ChatCompletionStreamingRunner";++const SSE_HEADERS = {+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache, no-transform",+ Connection: "keep-alive",+} as const;++function sseEvent(data: unknown): string {+ return `data: ${JSON.stringify(data)}\n\n`;+}++function toolCallStartChunk(id: string, name: string, index: number) {+ return {+ id: `chatcmpl-tc-${id}`,+ object: "chat.completion.chunk",+ choices: [+ {+ index: 0,+ delta: {+ tool_calls: [{ index, id, type: "function", function: { name, arguments: "" } }],+ },+ finish_reason: null,+ },+ ],+ };+}++function toolCallArgsChunk(id: string, rawArgs: string, result: string, index: number) {+ let enrichedArgs: string;+ try {+ enrichedArgs = JSON.stringify({+ _request: JSON.parse(rawArgs),+ _response: JSON.parse(result),+ });+ } catch {+ enrichedArgs = rawArgs;+ }+ return {+ id: `chatcmpl-tc-${id}-args`,+ object: "chat.completion.chunk",+ choices: [+ {+ index: 0,+ delta: { tool_calls: [{ index, function: { arguments: enrichedArgs } }] },+ finish_reason: null,+ },+ ],+ };+}++/**+ * Wraps a ChatCompletionStreamingRunner in an SSE Response that+ * streams tool-call events and content chunks to the client.+ */+export function sseResponseFromRunner(+ runner: ChatCompletionStreamingRunner<unknown>,+): Response {+ const encoder = new TextEncoder();+ let closed = false;++ const readable = new ReadableStream({+ start(controller) {+ const send = (text: string) => {+ if (closed) return;+ try { controller.enqueue(encoder.encode(text)); } catch { /* closed */ }+ };+ const finish = () => {+ if (closed) return;+ closed = true;+ try { controller.close(); } catch { /* closed */ }+ };++ const pendingCalls: Array<{ id: string; name: string; arguments: string }> = [];+ let callIdx = 0;+ let resultIdx = 0;++ runner.on("functionToolCall", (fc) => {+ const id = `tc-${callIdx}`;+ pendingCalls.push({ id, name: fc.name, arguments: fc.arguments });+ send(sseEvent(toolCallStartChunk(id, fc.name, callIdx)));+ callIdx++;+ });++ runner.on("functionToolCallResult", (result) => {+ const tc = pendingCalls[resultIdx];+ if (tc) {+ send(sseEvent(toolCallArgsChunk(tc.id, tc.arguments, result, resultIdx)));+ }+ resultIdx++;+ });++ runner.on("chunk", (chunk) => {+ const choice = chunk.choices?.[0];+ if (!choice?.delta) return;+ if (choice.delta.content || choice.finish_reason === "stop") {+ send(sseEvent(chunk));+ }+ });++ runner.on("end", () => {+ send("data: [DONE]\n\n");+ finish();+ });++ runner.on("error", (err) => {+ console.error("[chat] Error:", err);+ send(sseEvent({ error: err.message }));+ finish();+ });+ },+ });++ return new Response(readable, { headers: SSE_HEADERS });+}diff --git a/examples/openui-dashboard/src/lib/tool-def.ts b/examples/openui-dashboard/src/lib/tool-def.tsnew file mode 100644index 000000000..41ae737a7--- /dev/null+++ b/examples/openui-dashboard/src/lib/tool-def.ts@@ -0,0 +1,53 @@+import type { ToolSpec } from "@openuidev/lang-core";+import type { RunnableToolFunction } from "openai/lib/RunnableFunction";+import type { JSONSchema } from "openai/lib/jsonschema";+import { z } from "zod";++interface ToolDefOptions {+ name: string;+ description: string;+ inputSchema: z.ZodObject<z.ZodRawShape>;+ outputSchema: z.ZodType;+ execute: (args: Record<string, unknown>) => Promise<unknown>;+}++export class ToolDef {+ readonly name: string;+ readonly description: string;+ readonly inputSchema: z.ZodObject<z.ZodRawShape>;+ readonly outputSchema: z.ZodType;+ readonly execute: (args: Record<string, unknown>) => Promise<unknown>;++ constructor(opts: ToolDefOptions) {+ this.name = opts.name;+ this.description = opts.description;+ this.inputSchema = opts.inputSchema;+ this.outputSchema = opts.outputSchema;+ this.execute = opts.execute;+ }++ /** Format accepted by `client.chat.completions.runTools()` */+ toOpenAITool(): RunnableToolFunction<Record<string, unknown>> {+ return {+ type: "function",+ function: {+ name: this.name,+ description: this.description,+ parameters: z.toJSONSchema(this.inputSchema) as JSONSchema,+ function: async (args: Record<string, unknown>) =>+ JSON.stringify(await this.execute(args)),+ parse: JSON.parse,+ },+ };+ }++ /** Format used by `generatePrompt()` for the system prompt */+ toToolSpec(): ToolSpec {+ return {+ name: this.name,+ description: this.description,+ inputSchema: z.toJSONSchema(this.inputSchema) as Record<string, unknown>,+ outputSchema: z.toJSONSchema(this.outputSchema) as Record<string, unknown>,+ };+ }+}diff --git a/examples/openui-dashboard/src/library.ts b/examples/openui-dashboard/src/library.tsnew file mode 100644index 000000000..121d5fd5a--- /dev/null+++ b/examples/openui-dashboard/src/library.ts@@ -0,0 +1 @@+export { openuiLibrary as library } from "@openuidev/react-ui/genui-lib";diff --git a/examples/openui-dashboard/src/prompt-config.ts b/examples/openui-dashboard/src/prompt-config.tsnew file mode 100644index 000000000..3247b19f1--- /dev/null+++ b/examples/openui-dashboard/src/prompt-config.ts@@ -0,0 +1,78 @@+// Prompt configuration for the chat API route.+// This file has NO React dependencies — safe to import from server-only routes.+//+// Component specs are generated by `pnpm generate:prompt` and imported from the+// generated JSON file. Tools are injected at request time from MCP.++import type { PromptSpec } from "@openuidev/react-lang";+import componentSpec from "./generated/component-spec.json";++export const promptSpec: PromptSpec = {+ ...componentSpec as PromptSpec,+ editMode: true,+ inlineMode: true,+ toolExamples: [+ `Example — Usage Overview Dashboard:+root = Stack([header, controls, kpiRow, trendCard])+header = CardHeader("Usage Overview", "Events, users and errors over time")+$days = "14"+controls = Stack([filterRow], "row", "m", "end", "between")+filterRow = FormControl("Date Range", Select("days", [r7, r14, r30], null, null, $days))+r7 = SelectItem("7", "Last 7 days")+r14 = SelectItem("14", "Last 14 days")+r30 = SelectItem("30", "Last 30 days")+metrics = Query("get_usage_metrics", {dateRange: $days}, {totalEvents: 0, totalUsers: 0, totalErrors: 0, totalCost: 0, data: []})+kpiRow = Stack([kpi1, kpi2, kpi3, kpi4], "row", "m", "stretch", "start", true)+kpi1 = Card([TextContent("Total Events", "small"), TextContent("" + metrics.totalEvents, "large-heavy")])+kpi2 = Card([TextContent("Total Users", "small"), TextContent("" + metrics.totalUsers, "large-heavy")])+kpi3 = Card([TextContent("Errors", "small"), TextContent("" + metrics.totalErrors, "large-heavy")])+kpi4 = Card([TextContent("Cost", "small"), TextContent("$" + @Round(metrics.totalCost, 2), "large-heavy")])+trendCard = Card([CardHeader("Daily Trend"), LineChart(metrics.data.day, [Series("Events", metrics.data.events), Series("Users", metrics.data.users), Series("Errors", metrics.data.errors)])])`,++ `Example — Server Health Dashboard:+root = Stack([header, kpiRow, trendCard])+header = CardHeader("Server Monitoring", "Auto-refreshes every 30 seconds")+health = Query("get_server_health", {}, {cpu: 0, memory: 0, latencyP95: 0, errorRate: 0, timeseries: []}, 30)+kpiRow = Stack([cpuCard, memCard, latCard, errCard], "row", "m", "stretch", "start", true)+cpuCard = Card([TextContent("CPU", "small"), TextContent("" + @Round(health.cpu, 1) + "%", "large-heavy")])+memCard = Card([TextContent("Memory", "small"), TextContent("" + @Round(health.memory, 1) + "%", "large-heavy")])+latCard = Card([TextContent("Latency P95", "small"), TextContent("" + @Round(health.latencyP95, 0) + " ms", "large-heavy")])+errCard = Card([TextContent("Error Rate", "small"), TextContent("" + @Round(health.errorRate, 2) + "%", "large-heavy")])+trendCard = Card([CardHeader("24-Hour Trend"), LineChart(health.timeseries.time, [Series("CPU", health.timeseries.cpu), Series("Memory", health.timeseries.memory), Series("Latency", health.timeseries.latencyP95)])])`,++ `Example — Analytics deep-dive (endpoints, errors, geo, funnel):+root = Stack([header, row1, row2])+header = CardHeader("Analytics Deep-Dive", "Endpoints, errors, geography and conversion")+endpoints = Query("get_top_endpoints", {limit: 10}, {endpoints: []})+errors = Query("get_error_breakdown", {}, {errors: []})+geo = Query("get_geo_usage", {}, {regions: []})+funnel = Query("get_funnel_metrics", {}, {steps: []})+row1 = Stack([endpointsCard, errorsCard], "row", "m", "stretch")+endpointsCard = Card([CardHeader("Top Endpoints"), Table([Col("Path", endpoints.endpoints.path), Col("Requests", endpoints.endpoints.requests, "number"), Col("Avg Latency (ms)", endpoints.endpoints.avgLatency, "number"), Col("Error Rate", endpoints.endpoints.errorRate, "number")])])+errorsCard = Card([CardHeader("Error Breakdown"), PieChart(errors.errors.category, errors.errors.count)])+row2 = Stack([geoCard, funnelCard], "row", "m", "stretch")+geoCard = Card([CardHeader("Geographic Usage"), Table([Col("Region", geo.regions.region), Col("Users", geo.regions.users, "number"), Col("Events", geo.regions.events, "number")])])+funnelCard = Card([CardHeader("Conversion Funnel"), BarChart(funnel.steps.step, [Series("Users", funnel.steps.users)])])`,+ ],+ additionalRules: [+ "For time-series analytics, use get_usage_metrics with dateRange as a numeric string (\"7\", \"14\", \"30\")",+ "For server monitoring / CPU / memory / latency, use get_server_health — it returns a 24h timeseries",+ "For endpoint performance, use get_top_endpoints; for error categories, use get_error_breakdown",+ "For geographic breakdown, use get_geo_usage; for conversion funnel, use get_funnel_metrics",+ "For A/B testing results, use get_experiment_results; for resource cost breakdown, use get_resource_breakdown",+ "Prefer including a date range selector for dashboards that use get_usage_metrics or get_top_endpoints",+ 'dateRange values are numeric strings: "7", "14", "30", "90". Do not use suffixes like "d" or "h".',+ ],+ preamble: `You are an AI assistant that builds dashboards using openui-lang, a declarative UI language.++## Available Tools++- **get_usage_metrics** — events, users, errors, cost over time. Returns \`totalEvents\`, \`totalUsers\`, \`totalErrors\`, \`totalCost\`, and \`data[]\` (per-day rows with \`day\`, \`events\`, \`users\`, \`errors\`, \`cost\`). Accepts optional \`dateRange\` (numeric string of days).+- **get_top_endpoints** — top API endpoints by request count. Returns \`endpoints[]\` with \`path\`, \`requests\`, \`avgLatency\`, \`errorRate\`. Accepts optional \`limit\` and \`dateRange\`.+- **get_resource_breakdown** — usage split by resource type (API, Web App, Mobile, Webhook). Returns \`resources[]\` with \`name\`, \`events\`, \`users\`, \`cost\`.+- **get_error_breakdown** — errors by category. Returns \`errors[]\` with \`category\` and \`count\`.+- **get_server_health** — current CPU, memory, latency, error rate plus 24h timeseries. Returns scalar fields and \`timeseries[]\` with \`time\`, \`cpu\`, \`memory\`, \`latencyP95\`.+- **get_experiment_results** — A/B test variants. Returns \`variants[]\` with \`variant\`, \`conversionRate\`, \`users\`.+- **get_geo_usage** — usage by region. Returns \`regions[]\` with \`region\`, \`users\`, \`events\`.+- **get_funnel_metrics** — conversion funnel steps. Returns \`steps[]\` with \`step\` and \`users\`.`,+};diff --git a/examples/openui-dashboard/src/starters.ts b/examples/openui-dashboard/src/starters.tsnew file mode 100644index 000000000..8b1fdc69b--- /dev/null+++ b/examples/openui-dashboard/src/starters.ts@@ -0,0 +1,13 @@+export interface Starter {+ label: string;+ prompt: string;+ icon: string;+}++export const STARTERS: Starter[] = [+ { label: "Usage Overview", prompt: "Build a usage overview dashboard with KPI cards (events, users, errors, cost) and a daily trend chart with a date range selector", icon: "📊" },+ { label: "Server Health", prompt: "Create a server monitoring dashboard that auto-refreshes every 30 seconds showing CPU, memory, latency P95 and a 24-hour trend chart", icon: "🖥️" },+ { label: "Top Endpoints", prompt: "Build a dashboard showing the top 10 API endpoints by request count alongside an error breakdown pie chart", icon: "🔥" },+ { label: "Geo & Funnel", prompt: "Create a dashboard with a geographic usage table by region and a conversion funnel bar chart", icon: "🌍" },+ { label: "Full Analytics", prompt: "Build a full analytics dashboard with usage KPIs, top endpoints, error breakdown, geo usage, funnel metrics, and A/B experiment results", icon: "📈" },+];diff --git a/examples/openui-dashboard/src/tools.ts b/examples/openui-dashboard/src/tools.tsnew file mode 100644index 000000000..6b1871536--- /dev/null+++ b/examples/openui-dashboard/src/tools.ts@@ -0,0 +1,235 @@+/**+ * Shared tool registry — single source of truth for all tools.+ *+ * Consumed by:+ * - /api/mcp/route.ts (MCP server, uses Zod inputSchema directly)+ * - /api/chat/route.ts (OpenAI function-calling, via toOpenAITool())+ */+import { z } from "zod";+import { ToolDef } from "./lib/tool-def";++// ── Helpers ──────────────────────────────────────────────────────────────────++function dateOffset(daysAgo: number): string {+ const d = new Date();+ d.setDate(d.getDate() + daysAgo);+ return d.toISOString().slice(0, 10);+}++function generateTimeseries<T>(count: number, fn: (index: number) => T): T[] {+ return Array.from({ length: count }, (_, i) => fn(i));+}++// ── Mock data generators ─────────────────────────────────────────────────────++function getUsageMetrics(args: Record<string, unknown>) {+ const days = Number(args.dateRange ?? args.days ?? 14);+ return {+ totalEvents: 48200 + Math.floor(days * 120),+ totalUsers: 3200 + Math.floor(days * 40),+ totalErrors: 142 + Math.floor(days * 3),+ totalCost: 1250.5 + days * 15,+ data: generateTimeseries(days, (i) => ({+ day: dateOffset(-days + i),+ events: 2800 + Math.floor(Math.random() * 1200),+ users: 180 + Math.floor(Math.random() * 80),+ errors: 5 + Math.floor(Math.random() * 15),+ cost: 70 + Math.random() * 30,+ })),+ };+}++function getTopEndpoints(args: Record<string, unknown>) {+ const limit = Number(args.limit ?? 10);+ const paths = ["/api/users", "/api/events", "/api/auth", "/api/data", "/api/search", "/api/upload", "/api/export", "/api/notify", "/api/billing", "/api/health"];+ return {+ endpoints: Array.from({ length: limit }, (_, i) => ({+ path: paths[i % 10],+ requests: 12000 - i * 900 + Math.floor(Math.random() * 400),+ avgLatency: 45 + i * 12 + Math.floor(Math.random() * 20),+ errorRate: Math.round((0.5 + i * 0.3 + Math.random() * 0.5) * 100) / 100,+ })),+ };+}++function getResourceBreakdown() {+ return {+ resources: [+ { name: "API", events: 22000, users: 1800, cost: 450 },+ { name: "Web App", events: 18000, users: 2400, cost: 380 },+ { name: "Mobile", events: 8200, users: 900, cost: 220 },+ { name: "Webhook", events: 3500, users: 120, cost: 95 },+ ],+ };+}++function getErrorBreakdown() {+ return {+ errors: [+ { category: "TimeoutError", count: 45 },+ { category: "AuthError", count: 32 },+ { category: "RateLimitError", count: 28 },+ { category: "ValidationError", count: 22 },+ { category: "NotFoundError", count: 15 },+ ],+ };+}++function getServerHealth() {+ return {+ cpu: 42 + Math.floor(Math.random() * 20),+ memory: 68 + Math.floor(Math.random() * 15),+ latencyP95: 120 + Math.floor(Math.random() * 60),+ errorRate: Math.round((1.2 + Math.random() * 0.8) * 100) / 100,+ timeseries: generateTimeseries(24, (i) => ({+ time: `${String(i).padStart(2, "0")}:00`,+ cpu: 35 + Math.floor(Math.random() * 30),+ memory: 60 + Math.floor(Math.random() * 20),+ latencyP95: 80 + Math.floor(Math.random() * 80),+ })),+ };+}++function getExperimentResults() {+ return {+ variants: [+ { variant: "Control", conversionRate: 3.2, users: 5200 },+ { variant: "Variant A", conversionRate: 4.1, users: 5150 },+ { variant: "Variant B", conversionRate: 3.8, users: 5100 },+ ],+ };+}++function getGeoUsage() {+ return {+ regions: [+ { region: "North America", users: 4200, events: 18000 },+ { region: "Europe", users: 3100, events: 14000 },+ { region: "Asia Pacific", users: 1800, events: 8000 },+ { region: "Latin America", users: 600, events: 2800 },+ { region: "Africa", users: 200, events: 900 },+ ],+ };+}++function getFunnelMetrics() {+ return {+ steps: [+ { step: "Visit", users: 10000 },+ { step: "Sign Up", users: 3200 },+ { step: "Activate", users: 1800 },+ { step: "Subscribe", users: 450 },+ { step: "Retain (30d)", users: 320 },+ ],+ };+}++// ── Tool registry ───────────────────────────────────────────────────────────++export { ToolDef } from "./lib/tool-def";++export const tools: ToolDef[] = [+ new ToolDef({+ name: "get_usage_metrics",+ description: "Get usage metrics for the specified date range",+ inputSchema: z.object({+ dateRange: z.string().optional(),+ days: z.string().optional(),+ resource: z.string().optional(),+ }),+ outputSchema: z.object({+ totalEvents: z.number(),+ totalUsers: z.number(),+ totalErrors: z.number(),+ totalCost: z.number(),+ data: z.array(+ z.object({+ day: z.string(),+ events: z.number(),+ users: z.number(),+ errors: z.number(),+ cost: z.number(),+ }),+ ),+ }),+ execute: async (args) => getUsageMetrics(args),+ }),+ new ToolDef({+ name: "get_top_endpoints",+ description: "Get top API endpoints by request count",+ inputSchema: z.object({ limit: z.number().optional(), dateRange: z.string().optional() }),+ outputSchema: z.object({+ endpoints: z.array(+ z.object({+ path: z.string(),+ requests: z.number(),+ avgLatency: z.number(),+ errorRate: z.number(),+ }),+ ),+ }),+ execute: async (args) => getTopEndpoints(args),+ }),+ new ToolDef({+ name: "get_resource_breakdown",+ description: "Get resource usage breakdown by type",+ inputSchema: z.object({}),+ outputSchema: z.object({+ resources: z.array(+ z.object({ name: z.string(), events: z.number(), users: z.number(), cost: z.number() }),+ ),+ }),+ execute: async () => getResourceBreakdown(),+ }),+ new ToolDef({+ name: "get_error_breakdown",+ description: "Get error breakdown by category",+ inputSchema: z.object({}),+ outputSchema: z.object({+ errors: z.array(z.object({ category: z.string(), count: z.number() })),+ }),+ execute: async () => getErrorBreakdown(),+ }),+ new ToolDef({+ name: "get_server_health",+ description: "Get current server health metrics (CPU, memory, latency)",+ inputSchema: z.object({}),+ outputSchema: z.object({+ cpu: z.number(),+ memory: z.number(),+ latencyP95: z.number(),+ errorRate: z.number(),+ timeseries: z.array(+ z.object({ time: z.string(), cpu: z.number(), memory: z.number(), latencyP95: z.number() }),+ ),+ }),+ execute: async () => getServerHealth(),+ }),+ new ToolDef({+ name: "get_experiment_results",+ description: "Get A/B experiment results with conversion rates",+ inputSchema: z.object({}),+ outputSchema: z.object({+ variants: z.array(+ z.object({ variant: z.string(), conversionRate: z.number(), users: z.number() }),+ ),+ }),+ execute: async () => getExperimentResults(),+ }),+ new ToolDef({+ name: "get_geo_usage",+ description: "Get geographic usage breakdown by region",+ inputSchema: z.object({}),+ outputSchema: z.object({+ regions: z.array(z.object({ region: z.string(), users: z.number(), events: z.number() })),+ }),+ execute: async () => getGeoUsage(),+ }),+ new ToolDef({+ name: "get_funnel_metrics",+ description: "Get conversion funnel metrics",+ inputSchema: z.object({}),+ outputSchema: z.object({ steps: z.array(z.object({ step: z.string(), users: z.number() })) }),+ execute: async () => getFunnelMetrics(),+ }),+];diff --git a/examples/openui-dashboard/tsconfig.json b/examples/openui-dashboard/tsconfig.jsonnew file mode 100644index 000000000..cf9c65d3e--- /dev/null+++ b/examples/openui-dashboard/tsconfig.json@@ -0,0 +1,34 @@+{+ "compilerOptions": {+ "target": "ES2017",+ "lib": ["dom", "dom.iterable", "esnext"],+ "allowJs": true,+ "skipLibCheck": true,+ "strict": true,+ "noEmit": true,+ "esModuleInterop": true,+ "module": "esnext",+ "moduleResolution": "bundler",+ "resolveJsonModule": true,+ "isolatedModules": true,+ "jsx": "react-jsx",+ "incremental": true,+ "plugins": [+ {+ "name": "next"+ }+ ],+ "paths": {+ "@/*": ["./src/*"]+ }+ },+ "include": [+ "next-env.d.ts",+ "**/*.ts",+ "**/*.tsx",+ ".next/types/**/*.ts",+ ".next/dev/types/**/*.ts",+ "**/*.mts"+ ],+ "exclude": ["node_modules"]+}diff --git a/examples/react-email/next-env.d.ts b/examples/react-email/next-env.d.tsindex c4b7818fb..9edff1c7c 100644--- a/examples/react-email/next-env.d.ts+++ b/examples/react-email/next-env.d.ts@@ -1,6 +1,6 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-import "./.next/dev/types/routes.d.ts";+import "./.next/types/routes.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/examples/react-email/src/generated/system-prompt.txt b/examples/react-email/src/generated/system-prompt.txtindex 01539c412..99d5812b3 100644--- a/examples/react-email/src/generated/system-prompt.txt+++ b/examples/react-email/src/generated/system-prompt.txt@@ -4,18 +4,18 @@ You are an AI assistant that responds using openui-lang, a declarative UI langua1. Each statement is on its own line: `identifier = Expression`2. `root` is the entry point — every program must define `root = EmailTemplate(...)`-3. Expressions are: strings ("..."), numbers, booleans (true/false), arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)+3. Expressions are: strings ("..."), numbers, booleans (true/false), null, arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)4. Use references for readability: define `name = ...` on one line, then use `name` later5. EVERY variable (except root) MUST be referenced by at least one other variable. Unreferenced variables are silently dropped and will NOT render. Always include defined variables in their parent's children/items array.-6. Arguments are POSITIONAL (order matters, not names)+6. Arguments are POSITIONAL (order matters, not names). Write `Stack([children], "row", "l")` NOT `Stack([children], direction: "row", gap: "l")` — colon syntax is NOT supported and silently breaks7. Optional arguments can be omitted from the end-8. No operators, no logic, no variables — only declarations-9. Strings use double quotes with backslash escaping+- Strings use double quotes with backslash escaping## Component SignaturesArguments marked with ? are optional. Sub-components can be inline or referenced; prefer references for better streaming.-The `action` prop type accepts: ContinueConversation (sends message to LLM), OpenUrl (navigates to URL), or Custom (app-defined).+Props typed `ActionExpression` accept an Action([@steps...]) expression. See the Action section for available steps (@ToAssistant, @OpenUrl).+Props marked `$binding<type>` accept a `$variable` reference for two-way binding.### Email StructureEmailTemplate(subject: string, previewText?: string, children: (EmailHeading | EmailText | EmailButton | EmailImage | EmailDivider | EmailLink | EmailCodeBlock | EmailCodeInline | EmailMarkdown | EmailArticle | EmailProductCard | EmailFeatureGrid | EmailFeatureList | EmailNumberedSteps | EmailCheckoutTable | EmailPricingCard | EmailTestimonial | EmailSurveyRating | EmailStats | EmailImageGrid | EmailAvatarGroup | EmailAvatarWithText | EmailList | EmailCustomerReview | EmailBentoGrid | EmailSection | EmailColumns | EmailColumn | EmailHeaderSideNav | EmailHeaderCenteredNav | EmailHeaderSocial | EmailFooterCentered | EmailFooterTwoColumn)[]) — Root email template. Renders a live email preview with Copy HTML export. Always provide a subject line.@@ -135,6 +135,50 @@ EmailBentoGrid(heroTitle: string, heroDescription: string, heroLinkText?: string- EmailBentoGrid: Bento-style layout with a dark hero section on top and product cards below. Pass EmailBentoItem children.- Great for product showcase and marketing emails.+## Built-in Functions++Data functions prefixed with `@` to distinguish from components. These are the ONLY functions available — do NOT invent new ones.+Use @-prefixed built-in functions (@Count, @Sum, @Avg, @Min, @Max, @Round) on Query results — do NOT hardcode computed values.++@Count(array) → number — Returns array length+@First(array) → element — Returns first element of array+@Last(array) → element — Returns last element of array+@Sum(numbers[]) → number — Sum of numeric array+@Avg(numbers[]) → number — Average of numeric array+@Min(numbers[]) → number — Minimum value in array+@Max(numbers[]) → number — Maximum value in array+@Sort(array, field, direction?) → sorted array — Sort array by field. Direction: "asc" (default) or "desc"+@Filter(array, field, operator: "==" | "!=" | ">" | "<" | ">=" | "<=" | "contains", value) → filtered array — Filter array by field value+@Round(number, decimals?) → number — Round to N decimal places (default 0)+@Abs(number) → number — Absolute value+@Floor(number) → number — Round down to nearest integer+@Ceil(number) → number — Round up to nearest integer+@Each(array, varName, template) — Evaluate template for each element. varName is the loop variable — use it ONLY inside the template expression (inline). Do NOT create a separate statement for the template.++Builtins compose — output of one is input to the next:+`@Count(@Filter(data.rows, "field", "==", "val"))` for KPIs/chart values, `@Round(@Avg(data.rows.score), 1)`, `@Each(data.rows, "item", Comp(item.field))` for per-item rendering.+Array pluck: `data.rows.field` extracts a field from every row → use with @Sum, @Avg, charts, tables.++IMPORTANT @Each rule: The loop variable (e.g. "item") is ONLY available inside the @Each template expression. Always inline the template — do NOT extract it to a separate statement.+CORRECT: `Col("Actions", @Each(rows, "t", Button("Edit", Action([@Set($id, t.id)]))))`+WRONG: `myBtn = Button("Edit", Action([@Set($id, t.id)]))` then `Col("Actions", @Each(rows, "t", myBtn))` — t is undefined in myBtn.++## Action — Button Behavior++Action([@steps...]) wires button clicks to operations. Steps are @-prefixed built-in actions. Steps execute in order.+Buttons without an explicit Action prop automatically send their label to the assistant (equivalent to Action([@ToAssistant(label)])).++Available steps:+- @ToAssistant("message") — Send a message to the assistant (for conversational buttons like "Tell me more", "Explain this")+- @OpenUrl("https://...") — Navigate to a URL++Example — simple nav:+```+viewBtn = Button("View", Action([@OpenUrl("https://example.com")]))+```++- Action can be assigned to a variable or inlined: Button("Go", onSubmit) and Button("Go", Action([...])) both work+## Hoisting & Streaming (CRITICAL)openui-lang supports hoisting: a reference can be used BEFORE it is defined. The parser resolves all references after the full input is parsed.@@ -143,8 +187,10 @@ During streaming, the output is re-parsed on every chunk. Undefined references a**Recommended statement order for optimal streaming:**1. `root = EmailTemplate(...)` — UI shell appears immediately-2. Component definitions — fill in as they stream-3. Data values — leaf content last+2. $variable declarations — state ready for bindings+3. Query statements — defaults resolve immediately so components render with data+4. Component definitions — fill in with data already available+5. Data values — leaf content lastAlways write the root = EmailTemplate(...) statement first so the UI shell appears immediately, even before child data has streamed in.@@ -330,13 +376,13 @@ si1 = EmailSocialIcon("https://react.email/static/x-logo.png", "X", "https://x.csi2 = EmailSocialIcon("https://react.email/static/instagram-logo.png", "Instagram", "https://instagram.com/acme")## Important Rules-- ALWAYS start with root = EmailTemplate(...)-- Write statements in TOP-DOWN order: root → components → data (leverages hoisting for progressive streaming)-- Each statement on its own line-- No trailing text or explanations — output ONLY openui-lang code- When asked about data, generate realistic/plausible data- Choose components that best represent the content (tables for comparisons, charts for trends, forms for input, etc.)-- NEVER define a variable without referencing it from the tree. Every variable must be reachable from root, otherwise it will not render.++## Final Verification+Before finishing, walk your output and verify:+1. root = EmailTemplate(...) is the FIRST line (for optimal streaming).+2. Every referenced name is defined. Every defined name (other than root) is reachable from root.- You are an expert email designer using react-email components.- The 10 supported email types are: Welcome/Onboarding, Newsletter, Order Confirmation, Password Reset, Promotional/Sale, Event Invitation, Feedback Request, Shipping/Delivery Update, Account Verification, Onboarding Tutorial.diff --git a/examples/shadcn-chat/next-env.d.ts b/examples/shadcn-chat/next-env.d.tsindex c4b7818fb..9edff1c7c 100644--- a/examples/shadcn-chat/next-env.d.ts+++ b/examples/shadcn-chat/next-env.d.ts@@ -1,6 +1,6 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-import "./.next/dev/types/routes.d.ts";+import "./.next/types/routes.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/examples/shadcn-chat/src/lib/shadcn-genui/components/slider.tsx b/examples/shadcn-chat/src/lib/shadcn-genui/components/slider.tsxindex 2f0a2676b..acd824fb8 100644--- a/examples/shadcn-chat/src/lib/shadcn-genui/components/slider.tsx+++ b/examples/shadcn-chat/src/lib/shadcn-genui/components/slider.tsx@@ -46,11 +46,11 @@ export const Slider = defineComponent({<div className="space-y-2"><div className="flex justify-between text-sm"><span>{fieldName}</span>- <span className="text-muted-foreground tabular-nums">{val}</span>+ <span className="text-muted-foreground">{val}</span></div><ShadcnSlidermin={props.min ?? 0}- max={props.max ?? 100}+ max={props.max ?? 100}step={props.step ?? 1}value={[val]}onValueChange={([v]) => {diff --git a/packages/lang-core/README.md b/packages/lang-core/README.mdnew file mode 100644index 000000000..134f8839a--- /dev/null+++ b/packages/lang-core/README.md@@ -0,0 +1,138 @@+# @openuidev/lang-core++Framework-agnostic core for [OpenUI Lang](https://openui.com): parser, prompt generation, runtime evaluator, and type definitions.++[](https://www.npmjs.com/package/@openuidev/lang-core)+[](https://github.com/thesysdev/openui/blob/main/LICENSE)++## Install++```bash+npm install @openuidev/lang-core+# or+pnpm add @openuidev/lang-core+```++## What this package does++`@openuidev/lang-core` is the framework-agnostic foundation that powers OpenUI Lang. It has no React or other framework dependencies. Use it when you need to:++- **Parse** OpenUI Lang text into a typed element tree (one-shot or streaming)+- **Generate system prompts** from a component spec + tool definitions+- **Evaluate** reactive expressions, `$variables`, and query results at runtime+- **Merge** incremental edits into existing programs++If you're building a framework-specific app, use `@openuidev/react-lang`, `@openuidev/vue-lang` or `@openuidev/svelte-lang` instead. It re-exports everything from this package plus framework-specific components and hooks.++## Quick Start++### Parse OpenUI Lang++```ts+import { createParser } from "@openuidev/lang-core";++const parser = createParser(libraryJsonSchema);+const result = parser.parse(`+root = Stack([header, content])+header = CardHeader("Hello")+content = TextContent("World")+`);++console.log(result.root); // ElementNode tree+console.log(result.meta); // { incomplete, unresolved, statementCount, validationErrors }+```++### Streaming parser++```ts+import { createStreamingParser } from "@openuidev/lang-core";++const sp = createStreamingParser(libraryJsonSchema);++// Feed chunks as they arrive from the LLM+const result1 = sp.set("root = Stack([header])\n");+const result2 = sp.set("root = Stack([header])\nheader = CardHeader(\"Hello\")\n");+// result2.root now resolves the forward reference+```++### Generate a system prompt++```ts+import { generatePrompt, type PromptSpec } from "@openuidev/lang-core";+import componentSpec from "./generated/component-spec.json";++const prompt = generatePrompt({+ ...componentSpec,+ tools: myToolSpecs,+ toolCalls: true,+ bindings: true,+ editMode: true,+ preamble: "You build dashboards.",+});+```++### Merge incremental edits++```ts+import { mergeStatements } from "@openuidev/lang-core";++const original = `root = Stack([header, tbl])\nheader = CardHeader("Tickets")\ntbl = Table([...])`;+const patch = `root = Stack([header, chart, tbl])\nchart = PieChart(...)`;+const merged = mergeStatements(original, patch);+// header and tbl kept from original, root replaced, chart added+```++## API++### Parser++| Export | Description |+| :--- | :--- |+| `createParser(schema)` | One-shot parser for complete text |+| `createStreamingParser(schema)` | Incremental parser for streaming input |+| `parse(input, schema)` | Convenience one-shot parse |++### Prompt Generation++| Export | Description |+| :--- | :--- |+| `generatePrompt(spec)` | Generate a system prompt from a `PromptSpec` |++**`PromptSpec`** includes component signatures, tool definitions (`ToolSpec[]`), feature flags (`toolCalls`, `bindings`, `editMode`, `inlineMode`), examples, and custom rules.++**`ToolSpec`** describes a tool for prompt generation (name, description, inputSchema, outputSchema). Shape inspired by MCP's tool schema.++### Runtime++| Export | Description |+| :--- | :--- |+| `createQueryManager(toolProvider)` | Manages Query/Mutation execution and caching |+| `createStore()` | Reactive store for `$variables` and form state |+| `evaluate(ast, context)` | Evaluate an AST node to a concrete value |+| `evaluateElementProps(root, context)` | Recursively evaluate all props in an element tree |+| `extractToolResult(result)` | Extract data from an MCP `callTool` response |+| `mergeStatements(original, patch)` | Merge incremental edits by statement name |++### Types++```ts+import type {+ PromptSpec,+ ToolSpec,+ ParseResult,+ ElementNode,+ ToolProvider,+ McpClientLike,+ QueryManager,+ Store,+ OpenUIError,+} from "@openuidev/lang-core";+```++## Documentation++Full documentation, guides, and the language specification are available at **[openui.com](https://openui.com)**.++## License++[MIT](https://github.com/thesysdev/openui/blob/main/LICENSE)diff --git a/packages/lang-core/package.json b/packages/lang-core/package.jsonindex ee5e500b9..12802a2fb 100644--- a/packages/lang-core/package.json+++ b/packages/lang-core/package.json@@ -1,6 +1,6 @@{"name": "@openuidev/lang-core",- "version": "0.1.0",+ "version": "0.1.1","description": "Framework-agnostic core for OpenUI Lang: parser, prompt generation, validation, and type definitions","license": "MIT","type": "module",@@ -31,6 +31,14 @@"dependencies": {"zod": "^4.0.0"},+ "peerDependencies": {+ "@modelcontextprotocol/sdk": ">=1.0.0"+ },+ "peerDependenciesMeta": {+ "@modelcontextprotocol/sdk": {+ "optional": true+ }+ },"keywords": ["openui","openui-lang",@@ -53,6 +61,7 @@},"author": "[email protected]","devDependencies": {+ "@modelcontextprotocol/sdk": "^1.27.1","vitest": "^4.0.18"}}diff --git a/packages/lang-core/src/index.ts b/packages/lang-core/src/index.tsindex f0696373d..7e8018432 100644--- a/packages/lang-core/src/index.ts+++ b/packages/lang-core/src/index.ts@@ -6,16 +6,71 @@ export type {DefinedComponent,Library,LibraryDefinition,+ LibraryJSONSchema,PromptOptions,SubComponentOf,+ ToolDescriptor,} from "./library";// ── Parser ──export { createParser, createStreamingParser, parse } from "./parser";-export type { LibraryJSONSchema, Parser, StreamParser } from "./parser";+export type { Parser, StreamParser } from "./parser";+export { isASTNode, isRuntimeExpr } from "./parser/ast";+export type { ASTNode, CallNode, RuntimeExprNode, Statement } from "./parser/ast";+export {+ ACTION_NAMES,+ ACTION_STEPS,+ BUILTINS,+ BUILTIN_NAMES,+ LAZY_BUILTINS,+ isBuiltin,+ toNumber,+} from "./parser/builtins";+export type { BuiltinDef } from "./parser/builtins";+export { enrichErrors } from "./parser/enrich-errors";+export { mergeStatements } from "./parser/merge";export { generatePrompt } from "./parser/prompt";+export type { ComponentPromptSpec, PromptSpec, ToolSpec } from "./parser/prompt";export { BuiltinActionType } from "./parser/types";-export type { ActionEvent, ElementNode, ParseResult, ValidationErrorCode } from "./parser/types";+export type {+ ActionEvent,+ ActionPlan,+ ActionStep,+ ElementNode,+ MutationStatementInfo,+ OpenUIError,+ OpenUIErrorCode,+ OpenUIErrorSource,+ ParseResult,+ QueryStatementInfo,+ ValidationError,+ ValidationErrorCode,+} from "./parser/types";++// ── Reactive schema marker ──+export { isReactiveSchema, markReactive } from "./reactive";++// ── Runtime ──+export { evaluateElementProps } from "./runtime/evaluate-tree";+export type { EvalContext } from "./runtime/evaluate-tree";+export { evaluate, isReactiveAssign, stripReactiveAssign } from "./runtime/evaluator";+export type { EvaluationContext, ReactiveAssign } from "./runtime/evaluator";+export { McpToolError, extractToolResult } from "./runtime/mcp";+export type { McpClientLike } from "./runtime/mcp";+export { createQueryManager } from "./runtime/queryManager";+export type {+ MutationNode,+ MutationResult,+ QueryManager,+ QueryNode,+ QuerySnapshot,+ ToolProvider,+} from "./runtime/queryManager";+export { resolveStateField } from "./runtime/state-field";+export type { InferStateFieldValue, StateField } from "./runtime/state-field";+export { createStore } from "./runtime/store";+export type { Store } from "./runtime/store";+export { ToolNotFoundError } from "./runtime/toolProvider";// ── Validation ──export { builtInValidators, parseRules, parseStructuredRules, validate } from "./utils/validation";diff --git a/packages/lang-core/src/library.ts b/packages/lang-core/src/library.tsindex 8d0a4b18c..fdbe46238 100644--- a/packages/lang-core/src/library.ts+++ b/packages/lang-core/src/library.ts@@ -1,5 +1,10 @@import { z } from "zod";+import type { ComponentPromptSpec, PromptSpec, ToolSpec } from "./parser/prompt";import { generatePrompt } from "./parser/prompt";+import type { LibraryJSONSchema } from "./parser/types";+import { isReactiveSchema } from "./reactive";++export type { LibraryJSONSchema } from "./parser/types";// ─── Sub-component type ──────────────────────────────────────────────────────@@ -62,7 +67,7 @@ export function defineComponent<T extends z.ZodObject<any>, C>(config: {};}-// ─── Groups & Prompt ──────────────────────────────────────────────────────────+// ─── Groups & Prompt Options ─────────────────────────────────────────────────export interface ComponentGroup {name: string;@@ -70,13 +75,206 @@ export interface ComponentGroup {notes?: string[];}+/** Tool descriptor for prompt generation — simple string or rich ToolSpec. */+export type ToolDescriptor = string | ToolSpec;+export interface PromptOptions {preamble?: string;additionalRules?: string[];+ /** Examples shown when no tools are present (static/layout patterns). */examples?: string[];+ /** Examples shown when tools ARE present (Query/Mutation patterns). Takes priority over `examples`. */+ toolExamples?: string[];+ /** Available tools for Query() — string names or rich ToolSpec descriptors injected into the prompt. */+ tools?: ToolDescriptor[];+ /** Enable edit-mode instructions in the prompt. */+ editMode?: boolean;+ /** Enable inline mode — LLM can respond with text + optional openui-lang fenced code. */+ inlineMode?: boolean;+ /** Enable Query(), Mutation(), @Run, tool workflow. Default: true if tools provided. */+ toolCalls?: boolean;+ /** Enable $variables, @Set, @Reset, interactive filters. Default: true if toolCalls. */+ bindings?: boolean;+}++// ─── Zod introspection ──────────────────────────────────────────────────────++function getZodDef(schema: unknown): any {+ return (schema as any)?._zod?.def;+}++function getZodType(schema: unknown): string | undefined {+ return getZodDef(schema)?.type;+}++function isOptionalType(schema: unknown): boolean {+ return getZodType(schema) === "optional";+}++function unwrapOptional(schema: unknown): unknown {+ const def = getZodDef(schema);+ if (def?.type === "optional") return def.innerType;+ return schema;+}++function unwrap(schema: unknown): unknown {+ return unwrapOptional(schema);+}++function isArrayType(schema: unknown): boolean {+ const s = unwrap(schema);+ return getZodType(s) === "array";+}++function getArrayInnerType(schema: unknown): unknown | undefined {+ const s = unwrap(schema);+ const def = getZodDef(s);+ if (def?.type === "array") return def.element ?? def.innerType;+ return undefined;+}++function getEnumValues(schema: unknown): string[] | undefined {+ const s = unwrap(schema);+ const def = getZodDef(s);+ if (def?.type !== "enum") return undefined;+ if (Array.isArray(def.values)) return def.values;+ if (def.entries && typeof def.entries === "object") return Object.keys(def.entries);+ return undefined;+}++function getSchemaId(schema: unknown): string | undefined {+ try {+ const meta = z.globalRegistry.get(schema as z.ZodType);+ return meta?.id;+ } catch {+ return undefined;+ }+}++function getUnionOptions(schema: unknown): unknown[] | undefined {+ const def = getZodDef(schema);+ if (def?.type === "union" && Array.isArray(def.options)) return def.options;+ return undefined;+}++function getObjectShape(schema: unknown): Record<string, unknown> | undefined {+ const def = getZodDef(schema);+ if (def?.type === "object" && def.shape && typeof def.shape === "object")+ return def.shape as Record<string, unknown>;+ return undefined;+}++/**+ * Resolve the type annotation for a schema field.+ * Returns a human-readable type string for the schema.+ * If the schema is marked reactive(), prefixes with "$binding<...>".+ */+function resolveTypeAnnotation(schema: unknown): string | undefined {+ const isReactive = isReactiveSchema(schema);+ const inner = unwrap(schema);++ const baseType = resolveBaseType(inner);+ if (!baseType) return undefined;+ return isReactive ? `$binding<${baseType}>` : baseType;}-// ─── Library ──────────────────────────────────────────────────────────────────+function resolveBaseType(inner: unknown): string | undefined {+ const directId = getSchemaId(inner);+ if (directId) return directId;++ const unionOpts = getUnionOptions(inner);+ if (unionOpts) {+ const resolved = unionOpts.map((o) => resolveTypeAnnotation(o));+ const names = resolved.filter(Boolean) as string[];+ if (names.length > 0) return names.join(" | ");+ }++ if (isArrayType(inner)) {+ const arrayInner = getArrayInnerType(inner);+ if (!arrayInner) return undefined;+ const innerType = resolveTypeAnnotation(arrayInner);+ if (innerType) {+ const isUnion = getUnionOptions(unwrap(arrayInner)) !== undefined;+ return isUnion ? `(${innerType})[]` : `${innerType}[]`;+ }+ return undefined;+ }++ const zodType = getZodType(inner);+ if (zodType === "string") return "string";+ if (zodType === "number") return "number";+ if (zodType === "boolean") return "boolean";++ const enumVals = getEnumValues(inner);+ if (enumVals) return enumVals.map((v) => `"${v}"`).join(" | ");++ if (zodType === "literal") {+ const vals = getZodDef(inner)?.values;+ if (Array.isArray(vals) && vals.length === 1) {+ const v = vals[0];+ return typeof v === "string" ? `"${v}"` : String(v);+ }+ }++ const shape = getObjectShape(inner);+ if (shape) {+ const fields = Object.entries(shape).map(([name, fieldSchema]) => {+ const opt = isOptionalType(fieldSchema) ? "?" : "";+ const fieldType = resolveTypeAnnotation(fieldSchema as z.ZodType);+ return fieldType ? `${name}${opt}: ${fieldType}` : `${name}${opt}`;+ });+ return `{${fields.join(", ")}}`;+ }++ return undefined;+}++// ─── Field analysis & signature generation ──────────────────────────────────++interface FieldInfo {+ name: string;+ isOptional: boolean;+ isArray: boolean;+ typeAnnotation?: string;+}++function analyzeFields(shape: Record<string, z.ZodType>): FieldInfo[] {+ return Object.entries(shape).map(([name, schema]) => ({+ name,+ isOptional: isOptionalType(schema),+ isArray: isArrayType(schema),+ typeAnnotation: resolveTypeAnnotation(schema),+ }));+}++function buildSignature(componentName: string, fields: FieldInfo[]): string {+ const params = fields.map((f) => {+ if (f.typeAnnotation) {+ return f.isOptional ? `${f.name}?: ${f.typeAnnotation}` : `${f.name}: ${f.typeAnnotation}`;+ }+ if (f.isArray) {+ return f.isOptional ? `[${f.name}]?` : `[${f.name}]`;+ }+ return f.isOptional ? `${f.name}?` : f.name;+ });+ return `${componentName}(${params.join(", ")})`;+}++function buildComponentSpecs(+ components: Record<string, DefinedComponent<any, any>>,+): Record<string, ComponentPromptSpec> {+ const specs: Record<string, ComponentPromptSpec> = {};+ for (const [name, def] of Object.entries(components)) {+ const fields = analyzeFields(def.props.shape);+ specs[name] = {+ signature: buildSignature(name, fields),+ description: def.description,+ };+ }+ return specs;+}++// ─── Library ────────────────────────────────────────────────────────────────export interface Library<C = unknown> {readonly components: Record<string, DefinedComponent<any, C>>;@@ -84,7 +282,8 @@ export interface Library<C = unknown> {readonly root: string | undefined;prompt(options?: PromptOptions): string;- toJSONSchema(): object;+ toSpec(): PromptSpec;+ toJSONSchema(): LibraryJSONSchema;}export interface LibraryDefinition<C = unknown> {@@ -118,10 +317,24 @@ export function createLibrary<C = unknown>(input: LibraryDefinition<C>): Libraryroot: input.root,prompt(options?: PromptOptions): string {- return generatePrompt(library, options);+ const spec: PromptSpec = {+ root: input.root,+ components: buildComponentSpecs(componentsRecord),+ componentGroups: input.componentGroups,+ ...options,+ };+ return generatePrompt(spec);+ },++ toSpec(): PromptSpec {+ return {+ root: input.root,+ components: buildComponentSpecs(componentsRecord),+ componentGroups: input.componentGroups,+ };},- toJSONSchema(): object {+ toJSONSchema(): LibraryJSONSchema {const combinedSchema = z.object(Object.fromEntries(Object.entries(componentsRecord).map(([k, v]) => [k, v.props])) as any,);diff --git a/packages/lang-core/src/parser/__tests__/parser.test.ts b/packages/lang-core/src/parser/__tests__/parser.test.tsindex 1ea6cfb7d..4c2f5498e 100644--- a/packages/lang-core/src/parser/__tests__/parser.test.ts+++ b/packages/lang-core/src/parser/__tests__/parser.test.ts@@ -36,18 +36,14 @@ describe("unknown-component", () => {const result = parse('root = DataTable("col")', schema);expect(result.meta.errors).toHaveLength(1);expect(result.meta.errors[0]).toMatchObject({- type: "validation",code: "unknown-component",component: "DataTable",- path: "",});});- it("still renders the element with _args when unknown", () => {+ it("drops unknown component from tree (returns null)", () => {const result = parse('root = DataTable("col")', schema);- expect(result.root).not.toBeNull();- expect(result.root?.typeName).toBe("DataTable");- expect((result.root?.props as any)._args).toEqual(["col"]);+ expect(result.root).toBeNull();});it("reports all unknown components in a tree", () => {@@ -65,20 +61,10 @@ describe("unknown-component", () => {// ── excess-args ───────────────────────────────────────────────────────────────describe("excess-args", () => {- it("reports when more args are passed than params", () => {- const result = parse('root = Title("hello", "extra")', schema);- expect(result.meta.errors).toHaveLength(1);- expect(result.meta.errors[0]).toMatchObject({- type: "validation",- code: "excess-args",- component: "Title",- path: "",- });- expect(result.meta.errors[0].message).toMatch(/takes 1 arg/);- });-- it("still renders the component despite excess args", () => {+ it("silently accepts extra args (no excess-args error emitted)", () => {const result = parse('root = Title("hello", "extra")', schema);+ expect(codes('root = Title("hello", "extra")')).not.toContain("excess-args");+ // Extra args are ignored; first arg maps to the defined paramexpect(result.root).not.toBeNull();expect(result.root?.props.text).toBe("hello");});@@ -144,8 +130,8 @@ describe("existing errors carry type and code", () => {const result = parse("root = Stack()", schema);expect(result.meta.errors).toHaveLength(1);expect(result.meta.errors[0]).toMatchObject({- type: "validation",code: "missing-required",+ component: "Stack",});});@@ -153,8 +139,8 @@ describe("existing errors carry type and code", () => {const result = parse("root = Stack(null)", schema);expect(result.meta.errors).toHaveLength(1);expect(result.meta.errors[0]).toMatchObject({- type: "validation",code: "null-required",+ component: "Stack",});});});diff --git a/packages/lang-core/src/parser/ast.ts b/packages/lang-core/src/parser/ast.tsnew file mode 100644index 000000000..d39a567a7--- /dev/null+++ b/packages/lang-core/src/parser/ast.ts@@ -0,0 +1,167 @@+// ─────────────────────────────────────────────────────────────────────────────+// AST node types for openui-lang+// ─────────────────────────────────────────────────────────────────────────────++/**+ * Discriminated union representing every value that can appear in an+ * openui-lang expression. The `k` field is the discriminant.+ *+ * Literal & structural nodes:+ * - `Comp` — a component call: `Header("Hello", "Subtitle")`+ * - `Str` — a string literal: `"hello"`+ * - `Num` — a number literal: `42` or `3.14`+ * - `Bool` — a boolean literal: `true` or `false`+ * - `Null` — the null literal+ * - `Arr` — an array: `[a, b, c]`+ * - `Obj` — an object: `{ key: value }`+ * - `Ref` — a reference to another statement: `myTable`+ * - `Ph` — a placeholder for an unresolvable reference+ *+ * Reactive & expression nodes:+ * - `StateRef` — a reactive state variable reference: `$count`+ * - `RuntimeRef` — a reference resolved at runtime (e.g. Query results)+ * - `BinOp` — a binary operation: `a + b`, `x == y`+ * - `UnaryOp` — a unary operation: `!flag`+ * - `Ternary` — a conditional expression: `cond ? a : b`+ * - `Member` — dot member access: `obj.field`+ * - `Index` — bracket index access: `arr[0]`+ * - `Assign` — state assignment: `$count = $count + 1`+ */+export type ASTNode =+ | { k: "Comp"; name: string; args: ASTNode[]; mappedProps?: Record<string, ASTNode> }+ | { k: "Str"; v: string }+ | { k: "Num"; v: number }+ | { k: "Bool"; v: boolean }+ | { k: "Null" }+ | { k: "Arr"; els: ASTNode[] }+ | { k: "Obj"; entries: [string, ASTNode][] }+ | { k: "Ref"; n: string }+ | { k: "Ph"; n: string }+ | { k: "StateRef"; n: string }+ | { k: "RuntimeRef"; n: string; refType: "query" | "mutation" }+ | { k: "BinOp"; op: string; left: ASTNode; right: ASTNode }+ | { k: "UnaryOp"; op: string; operand: ASTNode }+ | { k: "Ternary"; cond: ASTNode; then: ASTNode; else: ASTNode }+ | { k: "Member"; obj: ASTNode; field: string }+ | { k: "Index"; obj: ASTNode; index: ASTNode }+ | { k: "Assign"; target: string; value: ASTNode };++/**+ * Subset of ASTNode that must be preserved for runtime evaluation.+ * These nodes survive parser lowering and are resolved by the evaluator.+ */+export type RuntimeExprNode = Extract<+ ASTNode,+ | { k: "StateRef" }+ | { k: "RuntimeRef" }+ | { k: "BinOp" }+ | { k: "UnaryOp" }+ | { k: "Ternary" }+ | { k: "Member" }+ | { k: "Index" }+ | { k: "Assign" }+>;++/** Type guard for runtime expression nodes that survive parser lowering. */+export function isRuntimeExpr(node: ASTNode): node is RuntimeExprNode {+ switch (node.k) {+ case "StateRef":+ case "RuntimeRef":+ case "BinOp":+ case "UnaryOp":+ case "Ternary":+ case "Member":+ case "Index":+ case "Assign":+ return true;+ default:+ return false;+ }+}++/** Valid AST discriminant values. */+const AST_KINDS = new Set([+ "Comp",+ "Ref",+ "StateRef",+ "RuntimeRef",+ "BinOp",+ "UnaryOp",+ "Ternary",+ "Member",+ "Index",+ "Assign",+ "Str",+ "Num",+ "Bool",+ "Null",+ "Arr",+ "Obj",+ "Ph",+]);++/** Check if a value is an AST node (has a valid `k` discriminant field). */+export function isASTNode(value: unknown): value is ASTNode {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;+ return AST_KINDS.has((value as Record<string, unknown>).k as string);+}++export function walkAST(node: ASTNode, visit: (node: ASTNode) => void): void {+ const walk = (current: ASTNode) => {+ visit(current);++ switch (current.k) {+ case "Comp":+ current.args.forEach(walk);+ Object.values(current.mappedProps ?? {}).forEach(walk);+ break;+ case "Arr":+ current.els.forEach(walk);+ break;+ case "Obj":+ current.entries.forEach(([, value]) => walk(value));+ break;+ case "BinOp":+ walk(current.left);+ walk(current.right);+ break;+ case "UnaryOp":+ walk(current.operand);+ break;+ case "Ternary":+ walk(current.cond);+ walk(current.then);+ walk(current.else);+ break;+ case "Member":+ walk(current.obj);+ break;+ case "Index":+ walk(current.obj);+ walk(current.index);+ break;+ case "Assign":+ walk(current.value);+ break;+ }+ };++ walk(node);+}++// ─── Typed Statement model ─────────────────────────────────────────────────+// Classification determined at parse time from token type + expression shape.+// Eliminates id.startsWith("$") and ast.name === "Query" hacks downstream.++/** Tool/Query call shape extracted from Comp nodes */+export interface CallNode {+ callee: string;+ args: ASTNode[];+}++/** Typed statement — kind known at parse time */+export type Statement =+ | { kind: "value"; id: string; expr: ASTNode }+ | { kind: "state"; id: string; init: ASTNode }+ | { kind: "query"; id: string; call: CallNode; expr: ASTNode; deps?: string[] }+ | { kind: "mutation"; id: string; call: CallNode; expr: ASTNode };diff --git a/packages/lang-core/src/parser/builtins.ts b/packages/lang-core/src/parser/builtins.tsnew file mode 100644index 000000000..f132d802f--- /dev/null+++ b/packages/lang-core/src/parser/builtins.ts@@ -0,0 +1,228 @@+/**+ * Shared parser/runtime registry hub for:+ * - Runtime data builtins (evaluator.ts imports `.fn`)+ * - Prompt builtin docs (prompt.ts imports `.signature` + `.description`)+ * - Parser/runtime call classification (`isBuiltin`, action names, reserved calls)+ */++export interface BuiltinDef {+ /** PascalCase name matching the openui-lang syntax: Count, Sum, etc. */+ name: string;+ /** Signature for prompt docs: "@Count(array) → number" */+ signature: string;+ /** One-line description for prompt docs */+ description: string;+ /** Runtime implementation */+ fn: (...args: unknown[]) => unknown;+}++/** Resolve a field path on an object. Supports dot-paths: "state.name" → obj.state.name */+function resolveField(obj: any, path: string): unknown {+ if (!path || obj == null) return undefined;+ if (!path.includes(".")) return obj[path];+ let cur = obj;+ for (const p of path.split(".")) {+ if (cur == null) return undefined;+ cur = cur[p];+ }+ return cur;+}++function toNumber(val: unknown): number {+ if (typeof val === "number") return val;+ if (typeof val === "string") {+ const n = Number(val);+ return isNaN(n) ? 0 : n;+ }+ if (typeof val === "boolean") return val ? 1 : 0;+ return 0;+}++export const BUILTINS: Record<string, BuiltinDef> = {+ Count: {+ name: "Count",+ signature: "Count(array) → number",+ description: "Returns array length",+ fn: (arr) => (Array.isArray(arr) ? arr.length : 0),+ },+ First: {+ name: "First",+ signature: "First(array) → element",+ description: "Returns first element of array",+ fn: (arr) => (Array.isArray(arr) ? (arr[0] ?? null) : null),+ },+ Last: {+ name: "Last",+ signature: "Last(array) → element",+ description: "Returns last element of array",+ fn: (arr) => (Array.isArray(arr) ? (arr[arr.length - 1] ?? null) : null),+ },+ Sum: {+ name: "Sum",+ signature: "Sum(numbers[]) → number",+ description: "Sum of numeric array",+ fn: (arr) =>+ Array.isArray(arr) ? arr.reduce((a: number, b: unknown) => a + toNumber(b), 0) : 0,+ },+ Avg: {+ name: "Avg",+ signature: "Avg(numbers[]) → number",+ description: "Average of numeric array",+ fn: (arr) =>+ Array.isArray(arr) && arr.length+ ? (arr.reduce((a: number, b: unknown) => a + toNumber(b), 0) as number) / arr.length+ : 0,+ },+ Min: {+ name: "Min",+ signature: "Min(numbers[]) → number",+ description: "Minimum value in array",+ fn: (arr) =>+ Array.isArray(arr) && arr.length+ ? arr.reduce((acc: number, b: unknown) => Math.min(acc, toNumber(b)), toNumber(arr[0]))+ : 0,+ },+ Max: {+ name: "Max",+ signature: "Max(numbers[]) → number",+ description: "Maximum value in array",+ fn: (arr) =>+ Array.isArray(arr) && arr.length+ ? arr.reduce((acc: number, b: unknown) => Math.max(acc, toNumber(b)), toNumber(arr[0]))+ : 0,+ },+ Sort: {+ name: "Sort",+ signature: "Sort(array, field, direction?) → sorted array",+ description: 'Sort array by field. Direction: "asc" (default) or "desc"',+ fn: (arr, field, dir) => {+ if (!Array.isArray(arr)) return arr;+ const f = String(field ?? "");+ const desc = String(dir ?? "asc") === "desc";+ return [...arr].sort((a: any, b: any) => {+ const av = f ? resolveField(a, f) : a;+ const bv = f ? resolveField(b, f) : b;+ const aIsNumeric =+ typeof av === "number" || (typeof av === "string" && !isNaN(Number(av)) && av !== "");+ const bIsNumeric =+ typeof bv === "number" || (typeof bv === "string" && !isNaN(Number(bv)) && bv !== "");+ if (aIsNumeric && bIsNumeric) {+ const diff = toNumber(av) - toNumber(bv);+ return desc ? -diff : diff;+ }+ const cmp = String(av ?? "").localeCompare(String(bv ?? ""));+ return desc ? -cmp : cmp;+ });+ },+ },+ Filter: {+ name: "Filter",+ signature:+ 'Filter(array, field, operator: "==" | "!=" | ">" | "<" | ">=" | "<=" | "contains", value) → filtered array',+ description: "Filter array by field value",+ fn: (arr, field, op, value) => {+ if (!Array.isArray(arr)) return [];+ const f = String(field ?? "");+ const o = String(op ?? "==");+ return arr.filter((item: any) => {+ const v = f ? resolveField(item, f) : item;+ switch (o) {+ case "==":+ return v == value;+ case "!=":+ return v != value;+ case ">":+ return toNumber(v) > toNumber(value);+ case "<":+ return toNumber(v) < toNumber(value);+ case ">=":+ return toNumber(v) >= toNumber(value);+ case "<=":+ return toNumber(v) <= toNumber(value);+ case "contains":+ return String(v ?? "").includes(String(value ?? ""));+ default:+ return false;+ }+ });+ },+ },+ Round: {+ name: "Round",+ signature: "Round(number, decimals?) → number",+ description: "Round to N decimal places (default 0)",+ fn: (n, decimals) => {+ const num = toNumber(n);+ const d = decimals != null ? toNumber(decimals) : 0;+ const factor = Math.pow(10, d);+ return Math.round(num * factor) / factor;+ },+ },+ Abs: {+ name: "Abs",+ signature: "Abs(number) → number",+ description: "Absolute value",+ fn: (n) => Math.abs(toNumber(n)),+ },+ Floor: {+ name: "Floor",+ signature: "Floor(number) → number",+ description: "Round down to nearest integer",+ fn: (n) => Math.floor(toNumber(n)),+ },+ Ceil: {+ name: "Ceil",+ signature: "Ceil(number) → number",+ description: "Round up to nearest integer",+ fn: (n) => Math.ceil(toNumber(n)),+ },+};++/**+ * Lazy builtins — these receive AST nodes (not evaluated values) and+ * control their own evaluation. Handled specially in evaluator.ts.+ */+export const LAZY_BUILTINS: Set<string> = new Set(["Each"]);++export const LAZY_BUILTIN_DEFS: Record<string, { signature: string; description: string }> = {+ Each: {+ signature: "Each(array, varName, template)",+ description:+ "Evaluate template for each element. varName is the loop variable — use it ONLY inside the template expression (inline). Do NOT create a separate statement for the template.",+ },+};++/** Maps parser-level action step names → runtime step type values. Single source of truth. */+export const ACTION_STEPS = {+ Run: "run",+ ToAssistant: "continue_conversation",+ OpenUrl: "open_url",+ Set: "set",+ Reset: "reset",+} as const;++/** All action expression names (steps + the Action container) */+export const ACTION_NAMES: Set<string> = new Set(["Action", ...Object.keys(ACTION_STEPS)]);++/** Set of builtin names for fast lookup (includes action expressions) */+export const BUILTIN_NAMES: Set<string> = new Set([+ ...Object.keys(BUILTINS),+ ...LAZY_BUILTINS,+ ...ACTION_NAMES,+]);++/** Check if a name is a builtin function (not a component) */+export function isBuiltin(name: string): boolean {+ return BUILTIN_NAMES.has(name);+}++/** Reserved statement-level call names — not builtins, not components */+export const RESERVED_CALLS = { Query: "Query", Mutation: "Mutation" } as const;++/** Check if a name is a reserved statement call (Query, Mutation) */+export function isReservedCall(name: string): boolean {+ return name in RESERVED_CALLS;+}++/** Re-export toNumber for evaluator compatibility */+export { toNumber };diff --git a/packages/lang-core/src/parser/enrich-errors.ts b/packages/lang-core/src/parser/enrich-errors.tsnew file mode 100644index 000000000..65fef725d--- /dev/null+++ b/packages/lang-core/src/parser/enrich-errors.ts@@ -0,0 +1,44 @@+import type { LibraryJSONSchema, OpenUIError, ValidationError } from "./types";++/** Build a signature hint like "Header(title*, subtitle, icon)" from JSON schema. */+function buildSignatureHint(+ componentName: string,+ schema: { properties?: Record<string, unknown>; required?: string[] } | undefined,+): string | undefined {+ if (!schema?.properties) return undefined;+ const required = new Set(schema.required ?? []);+ const params = Object.keys(schema.properties)+ .map((k) => (required.has(k) ? `${k}*` : k))+ .join(", ");+ return `Signature: ${componentName}(${params}) — * marks required`;+}++/**+ * Convert parser ValidationErrors into enriched OpenUIErrors with hints.+ *+ * Framework-agnostic — usable by React, Svelte, Vue, or standalone.+ */+export function enrichErrors(+ validationErrors: ValidationError[],+ schema: LibraryJSONSchema,+ componentNames: string[],+): OpenUIError[] {+ return validationErrors.map((ve) => {+ const error: OpenUIError = {+ source: "parser",+ code: ve.code,+ message: ve.message,+ component: ve.component,+ path: ve.path || undefined,+ statementId: ve.statementId,+ };+ if (ve.code === "unknown-component" && componentNames.length) {+ error.hint = `Available components: ${componentNames.join(", ")}`;+ } else if (ve.code === "missing-required" || ve.code === "null-required") {+ error.hint = buildSignatureHint(ve.component, schema.$defs?.[ve.component]);+ } else if (ve.code === "inline-reserved") {+ error.hint = `Declare as a top-level statement: myVar = ${ve.component}(...)`;+ }+ return error;+ });+}diff --git a/packages/lang-core/src/parser/expressions.ts b/packages/lang-core/src/parser/expressions.tsnew file mode 100644index 000000000..8efc8e69f--- /dev/null+++ b/packages/lang-core/src/parser/expressions.ts@@ -0,0 +1,331 @@+// ─────────────────────────────────────────────────────────────────────────────+// Pratt precedence expression parser for openui-lang+// ─────────────────────────────────────────────────────────────────────────────++import type { ASTNode } from "./ast";+import { isBuiltin } from "./builtins";+import { T, type Token } from "./tokens";++// ── Precedence levels (from spec Section 2.11) ─────────────────────────────+const PREC_TERNARY = 1;+const PREC_OR = 2;+const PREC_AND = 3;+const PREC_EQ = 4;+const PREC_CMP = 5;+const PREC_ADD = 6;+const PREC_MUL = 7;+const PREC_UNARY = 8;+const PREC_MEMBER = 9;++/**+ * Parse a token array into an AST node using a Pratt (top-down operator+ * precedence) parser.+ */+export function parseExpression(tokens: Token[]): ASTNode {+ let pos = 0;++ const cur = (): Token => tokens[pos] ?? { t: T.EOF };+ const adv = (): Token => {+ const tok = cur();+ pos++;+ return tok;+ };+ const eat = (kind: T): void => {+ if (cur().t === kind) pos++;+ };++ // ── Infix precedence lookup ─────────────────────────────────────────────+ function getInfixPrec(tok: Token): number {+ switch (tok.t) {+ case T.Question:+ return PREC_TERNARY;+ case T.Or:+ return PREC_OR;+ case T.And:+ return PREC_AND;+ case T.EqEq:+ case T.NotEq:+ return PREC_EQ;+ case T.Greater:+ case T.Less:+ case T.GreaterEq:+ case T.LessEq:+ return PREC_CMP;+ case T.Plus:+ case T.Minus:+ return PREC_ADD;+ case T.Star:+ case T.Slash:+ case T.Percent:+ return PREC_MUL;+ case T.Dot:+ case T.LBrack:+ return PREC_MEMBER;+ default:+ return 0;+ }+ }++ // ── Main Pratt loop ─────────────────────────────────────────────────────+ function parseExpr(minPrec: number = 0): ASTNode {+ let left = parsePrefix();+ while (getInfixPrec(cur()) > minPrec) {+ left = parseInfix(left);+ }+ return left;+ }++ // ── Prefix / atoms ─────────────────────────────────────────────────────+ function parsePrefix(): ASTNode {+ const tok = cur();++ // String literal+ if (tok.t === T.Str) {+ adv();+ return { k: "Str", v: tok.v as string };+ }++ // Number literal+ if (tok.t === T.Num) {+ adv();+ return { k: "Num", v: tok.v as number };+ }++ // Boolean literals+ if (tok.t === T.True) {+ adv();+ return { k: "Bool", v: true };+ }+ if (tok.t === T.False) {+ adv();+ return { k: "Bool", v: false };+ }++ // Null literal+ if (tok.t === T.Null) {+ adv();+ return { k: "Null" };+ }++ // Array+ if (tok.t === T.LBrack) return parseArr();++ // Object+ if (tok.t === T.LBrace) return parseObj();++ // State variable — may be assignment or reference+ if (tok.t === T.StateVar) {+ const name = tok.v as string;+ adv();+ // Check for assignment: $var = expr (Equals, NOT EqEq)+ if (cur().t === T.Equals) {+ adv(); // consume =+ const value = parseExpr(0);+ return { k: "Assign", target: name, value };+ }+ return { k: "StateRef", n: name };+ }++ // PascalCase — component call or reference+ if (tok.t === T.Type) {+ const name = tok.v as string;+ // Builtins (Count, Each, Set, Run, etc.) require @-prefix — only Action is exempt+ if (tokens[pos + 1]?.t === T.LParen && (!isBuiltin(name) || name === "Action"))+ return parseComp();+ adv();+ return { k: "Ref", n: name };+ }++ // @-prefixed builtin call: @Count(...), @Each(...), @Set(...), etc.+ if (tok.t === T.BuiltinCall) {+ if (tokens[pos + 1]?.t === T.LParen) return parseComp();+ adv();+ return { k: "Ref", n: tok.v as string };+ }++ // Lowercase identifier — reference+ if (tok.t === T.Ident) {+ adv();+ return { k: "Ref", n: tok.v as string };+ }++ // Unary NOT+ if (tok.t === T.Not) {+ adv();+ return { k: "UnaryOp", op: "!", operand: parseExpr(PREC_UNARY) };+ }++ // Unary negation+ if (tok.t === T.Minus) {+ adv();+ return { k: "UnaryOp", op: "-", operand: parseExpr(PREC_UNARY) };+ }++ // Grouped expression+ if (tok.t === T.LParen) {+ adv(); // skip (+ const inner = parseExpr(0);+ eat(T.RParen);+ return inner;+ }++ // Unknown token — skip and return Null+ adv();+ return { k: "Null" };+ }++ // ── Infix / postfix ────────────────────────────────────────────────────+ function parseInfix(left: ASTNode): ASTNode {+ const tok = cur();++ // Arithmetic: + -+ if (tok.t === T.Plus) {+ adv();+ return { k: "BinOp", op: "+", left, right: parseExpr(PREC_ADD) };+ }+ if (tok.t === T.Minus) {+ adv();+ return { k: "BinOp", op: "-", left, right: parseExpr(PREC_ADD) };+ }++ // Arithmetic: * / %+ if (tok.t === T.Star) {+ adv();+ return { k: "BinOp", op: "*", left, right: parseExpr(PREC_MUL) };+ }+ if (tok.t === T.Slash) {+ adv();+ return { k: "BinOp", op: "/", left, right: parseExpr(PREC_MUL) };+ }+ if (tok.t === T.Percent) {+ adv();+ return { k: "BinOp", op: "%", left, right: parseExpr(PREC_MUL) };+ }++ // Equality: == !=+ if (tok.t === T.EqEq) {+ adv();+ return { k: "BinOp", op: "==", left, right: parseExpr(PREC_EQ) };+ }+ if (tok.t === T.NotEq) {+ adv();+ return { k: "BinOp", op: "!=", left, right: parseExpr(PREC_EQ) };+ }++ // Comparison: > < >= <=+ if (tok.t === T.Greater) {+ adv();+ return { k: "BinOp", op: ">", left, right: parseExpr(PREC_CMP) };+ }+ if (tok.t === T.Less) {+ adv();+ return { k: "BinOp", op: "<", left, right: parseExpr(PREC_CMP) };+ }+ if (tok.t === T.GreaterEq) {+ adv();+ return { k: "BinOp", op: ">=", left, right: parseExpr(PREC_CMP) };+ }+ if (tok.t === T.LessEq) {+ adv();+ return { k: "BinOp", op: "<=", left, right: parseExpr(PREC_CMP) };+ }++ // Logical AND+ if (tok.t === T.And) {+ adv();+ return { k: "BinOp", op: "&&", left, right: parseExpr(PREC_AND) };+ }++ // Logical OR+ if (tok.t === T.Or) {+ adv();+ return { k: "BinOp", op: "||", left, right: parseExpr(PREC_OR) };+ }++ // Ternary: cond ? then : else (right-associative)+ if (tok.t === T.Question) {+ adv(); // consume ?+ const then = parseExpr(0);+ eat(T.Colon);+ const els = parseExpr(0); // right-assoc: parse at lowest prec+ return { k: "Ternary", cond: left, then, else: els };+ }++ // Member access: obj.field+ if (tok.t === T.Dot) {+ adv(); // consume .+ const fieldTok = cur();+ const field =+ fieldTok.t === T.Ident ||+ fieldTok.t === T.Type ||+ fieldTok.t === T.Str ||+ fieldTok.t === T.Num+ ? (adv(), String(fieldTok.v))+ : fieldTok.t === T.StateVar+ ? (adv(), (fieldTok.v as string).replace(/^\$/, ""))+ : (adv(), "?");+ return { k: "Member", obj: left, field };+ }++ // Index access: obj[expr]+ if (tok.t === T.LBrack) {+ adv(); // consume [+ const index = parseExpr(0);+ eat(T.RBrack);+ return { k: "Index", obj: left, index };+ }++ // Fallback — should not be reached if getInfixPrec is correct+ return left;+ }++ // ── Compound parsers ───────────────────────────────────────────────────++ /** Parse `TypeName(arg1, arg2, ...)` */+ function parseComp(): ASTNode {+ const name = cur().v as string;+ adv(); // consume TypeName+ eat(T.LParen);+ const args: ASTNode[] = [];+ while (cur().t !== T.RParen && cur().t !== T.EOF) {+ args.push(parseExpr(0));+ if (cur().t === T.Comma) adv();+ }+ eat(T.RParen);+ return { k: "Comp", name, args };+ }++ /** Parse `[elem1, elem2, ...]` */+ function parseArr(): ASTNode {+ adv(); // skip [+ const els: ASTNode[] = [];+ while (cur().t !== T.RBrack && cur().t !== T.EOF) {+ els.push(parseExpr(0));+ if (cur().t === T.Comma) adv();+ }+ eat(T.RBrack);+ return { k: "Arr", els };+ }++ /** Parse `{ key: value, ... }` */+ function parseObj(): ASTNode {+ adv(); // skip {+ const entries: [string, ASTNode][] = [];+ while (cur().t !== T.RBrace && cur().t !== T.EOF) {+ const kt = cur();+ const key =+ kt.t === T.Ident || kt.t === T.Str || kt.t === T.Type || kt.t === T.Num+ ? (adv(), String(kt.v))+ : kt.t === T.StateVar+ ? (adv(), (kt.v as string).replace(/^\$/, ""))+ : (adv(), "?");+ eat(T.Colon);+ entries.push([key, parseExpr(0)]);+ if (cur().t === T.Comma) adv();+ }+ eat(T.RBrace);+ return { k: "Obj", entries };+ }++ return parseExpr(0);+}diff --git a/packages/lang-core/src/parser/index.ts b/packages/lang-core/src/parser/index.tsindex 1dc9018ee..c447a066d 100644--- a/packages/lang-core/src/parser/index.ts+++ b/packages/lang-core/src/parser/index.ts@@ -2,12 +2,31 @@ export { BuiltinActionType } from "./types";export type {ActionEvent,ElementNode,+ LibraryJSONSchema,+ MutationStatementInfo,OpenUIError,+ ParamDef,+ ParamMap,ParseResult,+ QueryStatementInfo,+ ValidationError,ValidationErrorCode,} from "./types";export { createParser, createStreamingParser, parse } from "./parser";-export type { LibraryJSONSchema, Parser, StreamParser } from "./parser";+export type { Parser, StreamParser } from "./parser";++export { enrichErrors } from "./enrich-errors";export { generatePrompt } from "./prompt";+export type { ComponentGroup, ComponentPromptSpec, PromptSpec, ToolSpec } from "./prompt";++export { mergeStatements } from "./merge";++// Shared builtin registry+export { BUILTINS, BUILTIN_NAMES, isBuiltin } from "./builtins";+export type { BuiltinDef } from "./builtins";++// Typed statement model + AST utilities+export { isASTNode, isRuntimeExpr } from "./ast";+export type { ASTNode, CallNode, RuntimeExprNode, Statement } from "./ast";diff --git a/packages/lang-core/src/parser/lexer.ts b/packages/lang-core/src/parser/lexer.tsnew file mode 100644index 000000000..61df2389a--- /dev/null+++ b/packages/lang-core/src/parser/lexer.ts@@ -0,0 +1,380 @@+// ─────────────────────────────────────────────────────────────────────────────+// Lexer for openui-lang+// ─────────────────────────────────────────────────────────────────────────────++import { T, type Token } from "./tokens";++/**+ * Tokenize an openui-lang source string into a flat token array.+ *+ * Handles all token types: identifiers, literals, operators,+ * state variables ($name), dot access, ternary.+ */+export function tokenize(src: string): Token[] {+ const tokens: Token[] = [];+ let i = 0;+ const n = src.length;++ while (i < n) {+ // Skip horizontal whitespace (not newlines — they're significant)+ while (i < n && (src[i] === " " || src[i] === "\t" || src[i] === "\r")) i++;+ if (i >= n) break;++ const c = src[i];++ // ── Newline ────────────────────────────────────────────────────────+ if (c === "\n") {+ tokens.push({ t: T.Newline });+ i++;+ continue;+ }++ // ── Single-character punctuation (brackets, comma, colon) ─────────+ if (c === "(") {+ tokens.push({ t: T.LParen });+ i++;+ continue;+ }+ if (c === ")") {+ tokens.push({ t: T.RParen });+ i++;+ continue;+ }+ if (c === "[") {+ tokens.push({ t: T.LBrack });+ i++;+ continue;+ }+ if (c === "]") {+ tokens.push({ t: T.RBrack });+ i++;+ continue;+ }+ if (c === "{") {+ tokens.push({ t: T.LBrace });+ i++;+ continue;+ }+ if (c === "}") {+ tokens.push({ t: T.RBrace });+ i++;+ continue;+ }+ if (c === ",") {+ tokens.push({ t: T.Comma });+ i++;+ continue;+ }+ if (c === ":") {+ tokens.push({ t: T.Colon });+ i++;+ continue;+ }++ // ── Equals / EqEq ─────────────────────────────────────────────────+ if (c === "=") {+ if (i + 1 < n && src[i + 1] === "=") {+ tokens.push({ t: T.EqEq });+ i += 2;+ } else {+ tokens.push({ t: T.Equals });+ i++;+ }+ continue;+ }++ // ── Not / NotEq ───────────────────────────────────────────────────+ if (c === "!") {+ if (i + 1 < n && src[i + 1] === "=") {+ tokens.push({ t: T.NotEq });+ i += 2;+ } else {+ tokens.push({ t: T.Not });+ i++;+ }+ continue;+ }++ // ── Greater / GreaterEq ───────────────────────────────────────────+ if (c === ">") {+ if (i + 1 < n && src[i + 1] === "=") {+ tokens.push({ t: T.GreaterEq });+ i += 2;+ } else {+ tokens.push({ t: T.Greater });+ i++;+ }+ continue;+ }++ // ── Less / LessEq ────────────────────────────────────────────────+ if (c === "<") {+ if (i + 1 < n && src[i + 1] === "=") {+ tokens.push({ t: T.LessEq });+ i += 2;+ } else {+ tokens.push({ t: T.Less });+ i++;+ }+ continue;+ }++ // ── And (&&) ──────────────────────────────────────────────────────+ if (c === "&") {+ if (i + 1 < n && src[i + 1] === "&") {+ tokens.push({ t: T.And });+ i += 2;+ } else {+ tokens.push({ t: T.And });+ i++;+ }+ continue;+ }++ // ── Or (||) ───────────────────────────────────────────────────────+ if (c === "|") {+ if (i + 1 < n && src[i + 1] === "|") {+ tokens.push({ t: T.Or });+ i += 2;+ } else {+ tokens.push({ t: T.Or });+ i++;+ }+ continue;+ }++ // ── Dot ───────────────────────────────────────────────────────────+ if (c === ".") {+ tokens.push({ t: T.Dot });+ i++;+ continue;+ }++ // ── Question ──────────────────────────────────────────────────────+ if (c === "?") {+ tokens.push({ t: T.Question });+ i++;+ continue;+ }++ // ── Plus ──────────────────────────────────────────────────────────+ if (c === "+") {+ tokens.push({ t: T.Plus });+ i++;+ continue;+ }++ // ── Star ──────────────────────────────────────────────────────────+ if (c === "*") {+ tokens.push({ t: T.Star });+ i++;+ continue;+ }++ // ── Slash ─────────────────────────────────────────────────────────+ if (c === "/") {+ tokens.push({ t: T.Slash });+ i++;+ continue;+ }++ // ── Percent ───────────────────────────────────────────────────────+ if (c === "%") {+ tokens.push({ t: T.Percent });+ i++;+ continue;+ }++ // ── String literal: "..." ─────────────────────────────────────────+ if (c === '"') {+ const start = i;+ i++; // skip opening quote+ let isClosed = false;+ // Fast-forward to the closing quote, respecting escapes+ while (i < n) {+ if (src[i] === "\\") {+ i += 2; // skip backslash and the escaped character+ } else if (src[i] === '"') {+ i++; // include the closing quote+ isClosed = true;+ break;+ } else {+ i++;+ }+ }+ const rawString = src.slice(start, i);+ try {+ // Let JavaScript's native JSON parser handle all unescaping (\n, \t, \uXXXX, etc.)+ // If the string is incomplete (streaming), we add a closing quote to parse what we have so far.+ const validJsonString = isClosed ? rawString : rawString + '"';+ tokens.push({ t: T.Str, v: JSON.parse(validJsonString) });+ } catch {+ // Fallback if JSON.parse fails (e.g., malformed unicode escape during streaming)+ // Strip the quotes and return the raw text so the UI doesn't crash+ const stripped = rawString.replace(/^"|"$/g, "");+ tokens.push({ t: T.Str, v: stripped });+ }+ continue;+ }++ // ── String literal: '...' (single quotes) ────────────────────────+ if (c === "'") {+ i++; // skip opening quote+ let result = "";+ let isClosed = false;+ while (i < n) {+ if (src[i] === "\\") {+ i++; // skip backslash+ if (i < n) {+ const esc = src[i];+ if (esc === "'") result += "'";+ else if (esc === "\\") result += "\\";+ else if (esc === "n") result += "\n";+ else if (esc === "t") result += "\t";+ else result += esc; // pass through other escaped chars+ i++;+ }+ } else if (src[i] === "'") {+ i++; // skip closing quote+ isClosed = true;+ break;+ } else {+ result += src[i];+ i++;+ }+ }+ void isClosed; // consumed for streaming parity with double-quote path+ tokens.push({ t: T.Str, v: result });+ continue;+ }++ // ── Minus: negative number literal or subtraction operator ────────+ if (c === "-") {+ const prev = tokens.length > 0 ? tokens[tokens.length - 1] : null;+ const afterValue =+ prev != null &&+ (prev.t === T.Num ||+ prev.t === T.Str ||+ prev.t === T.Ident ||+ prev.t === T.Type ||+ prev.t === T.RParen ||+ prev.t === T.RBrack ||+ prev.t === T.True ||+ prev.t === T.False ||+ prev.t === T.Null ||+ prev.t === T.StateVar ||+ prev.t === T.BuiltinCall);++ if (!afterValue && i + 1 < n && src[i + 1] >= "0" && src[i + 1] <= "9") {+ // Negative number literal — fall through to number parsing below+ } else {+ // Binary subtraction operator (or unary minus handled by expression parser)+ tokens.push({ t: T.Minus });+ i++;+ continue;+ }+ }++ // ── Number literal: 42, -3, 1.5, 1e10 ────────────────────────────+ const isDigit = c >= "0" && c <= "9";+ const isNegDigit = c === "-" && i + 1 < n && src[i + 1] >= "0" && src[i + 1] <= "9";+ if (isDigit || isNegDigit) {+ const start = i;+ if (src[i] === "-") i++; // optional minus+ while (i < n && src[i] >= "0" && src[i] <= "9") i++; // integer part+ if (i < n && src[i] === "." && i + 1 < n && src[i + 1] >= "0" && src[i + 1] <= "9") {+ // optional decimal — only if a digit follows the dot+ i++;+ while (i < n && src[i] >= "0" && src[i] <= "9") i++;+ }+ if (i < n && (src[i] === "e" || src[i] === "E")) {+ // optional exponent+ i++;+ if (i < n && (src[i] === "+" || src[i] === "-")) i++;+ while (i < n && src[i] >= "0" && src[i] <= "9") i++;+ }+ tokens.push({ t: T.Num, v: +src.slice(start, i) });+ continue;+ }++ // ── State variable: $identifier ───────────────────────────────────+ if (+ c === "$" &&+ i + 1 < n &&+ ((src[i + 1] >= "a" && src[i + 1] <= "z") ||+ (src[i + 1] >= "A" && src[i + 1] <= "Z") ||+ src[i + 1] === "_")+ ) {+ const start = i;+ i++; // skip $+ while (+ i < n &&+ ((src[i] >= "a" && src[i] <= "z") ||+ (src[i] >= "A" && src[i] <= "Z") ||+ (src[i] >= "0" && src[i] <= "9") ||+ src[i] === "_")+ )+ i++;+ tokens.push({ t: T.StateVar, v: src.slice(start, i) });+ continue;+ }++ // ── Keyword or identifier ─────────────────────────────────────────+ const isAlpha = (c >= "a" && c <= "z") || (c >= "A" && c <= "Z") || c === "_";+ if (isAlpha) {+ const start = i;+ while (+ i < n &&+ ((src[i] >= "a" && src[i] <= "z") ||+ (src[i] >= "A" && src[i] <= "Z") ||+ (src[i] >= "0" && src[i] <= "9") ||+ src[i] === "_")+ )+ i++;+ const word = src.slice(start, i);+ if (word === "true") {+ tokens.push({ t: T.True });+ continue;+ }+ if (word === "false") {+ tokens.push({ t: T.False });+ continue;+ }+ if (word === "null") {+ tokens.push({ t: T.Null });+ continue;+ }+ // PascalCase → component type name; lowercase → variable reference+ const kind = c >= "A" && c <= "Z" ? T.Type : T.Ident;+ tokens.push({ t: kind, v: word });+ continue;+ }++ // ── Builtin call: @identifier ───────────────────────────────────+ if (+ c === "@" &&+ i + 1 < n &&+ ((src[i + 1] >= "a" && src[i + 1] <= "z") ||+ (src[i + 1] >= "A" && src[i + 1] <= "Z") ||+ src[i + 1] === "_")+ ) {+ i++; // skip @+ const start = i;+ while (+ i < n &&+ ((src[i] >= "a" && src[i] <= "z") ||+ (src[i] >= "A" && src[i] <= "Z") ||+ (src[i] >= "0" && src[i] <= "9") ||+ src[i] === "_")+ )+ i++;+ tokens.push({ t: T.BuiltinCall, v: src.slice(start, i) });+ continue;+ }++ i++; // skip any other character (e.g. #, emojis)+ }++ tokens.push({ t: T.EOF });+ return tokens;+}diff --git a/packages/lang-core/src/parser/materialize.ts b/packages/lang-core/src/parser/materialize.tsnew file mode 100644index 000000000..8105da44d--- /dev/null+++ b/packages/lang-core/src/parser/materialize.ts@@ -0,0 +1,316 @@+// ─────────────────────────────────────────────────────────────────────────────+// Schema-aware materialization — single-pass lowering+// ─────────────────────────────────────────────────────────────────────────────++import type { ASTNode } from "./ast";+import { isASTNode, isRuntimeExpr } from "./ast";+import { isBuiltin, isReservedCall, LAZY_BUILTINS, RESERVED_CALLS } from "./builtins";+import { isElementNode, type ParamMap, type ValidationError } from "./types";++/**+ * Recursively check if a prop value contains any AST nodes that need runtime+ * evaluation. Walks into arrays, ElementNode children, and plain objects.+ */+export function containsDynamicValue(v: unknown): boolean {+ if (v == null || typeof v !== "object") return false;+ if (isASTNode(v)) return true;+ if (Array.isArray(v)) return v.some(containsDynamicValue);+ if (isElementNode(v)) {+ return Object.values(v.props).some(containsDynamicValue);+ }+ const obj = v as Record<string, unknown>;+ return Object.values(obj).some(containsDynamicValue);+}++export interface MaterializeCtx {+ syms: Map<string, ASTNode>;+ cat: ParamMap | undefined;+ errors: ValidationError[];+ unres: string[];+ visited: Set<string>;+ partial: boolean;+ /** Tracks which statement is currently being materialized (for error attribution). */+ currentStatementId?: string;+}++/**+ * Resolve a Ref node: inline from symbol table, detect cycles, emit RuntimeRef+ * for Query/Mutation declarations. Shared by materializeValue and materializeExpr.+ */+function resolveRef(name: string, ctx: MaterializeCtx, mode: "value" | "expr"): unknown | ASTNode {+ if (ctx.visited.has(name)) {+ ctx.unres.push(name);+ return mode === "expr" ? { k: "Ph", n: name } : null;+ }+ if (!ctx.syms.has(name)) {+ ctx.unres.push(name);+ return mode === "expr" ? { k: "Ph", n: name } : null;+ }+ const target = ctx.syms.get(name)!;+ // Query/Mutation declarations → RuntimeRef (resolved at runtime by evaluator)+ if (target.k === "Comp" && isReservedCall(target.name)) {+ const refType =+ target.name === RESERVED_CALLS.Mutation ? ("mutation" as const) : ("query" as const);+ return { k: "RuntimeRef", n: name, refType };+ }+ ctx.visited.add(name);+ const prevStatementId = ctx.currentStatementId;+ ctx.currentStatementId = name;+ try {+ const result = mode === "value" ? materializeValue(target, ctx) : materializeExpr(target, ctx);+ // Tag ElementNode with its source statement name+ if (mode === "value" && isElementNode(result)) {+ result.statementId = name;+ }+ return result;+ } finally {+ ctx.currentStatementId = prevStatementId;+ ctx.visited.delete(name);+ }+}++/**+ * If node is a lazy builtin like Each(arr, varName, template), temporarily+ * scope the iterator variable during materialization so template refs resolve.+ * Returns the materialized Comp node, or null if not a lazy builtin.+ */+function materializeLazyBuiltin(+ node: ASTNode & { k: "Comp" },+ ctx: MaterializeCtx,+ scopedRefs: ReadonlySet<string>,+): ASTNode | null {+ if (!LAZY_BUILTINS.has(node.name) || node.args.length < 3) return null;+ const varArg = node.args[1];+ const varName = varArg.k === "Ref" ? varArg.n : varArg.k === "Str" ? varArg.v : null;+ if (!varName) return null;++ const nextScopedRefs = new Set(scopedRefs);+ nextScopedRefs.add(varName);+ // Skip args[1] (the iterator declaration) but preserve scoped refs elsewhere.+ const recursedArgs = node.args.map((a, i) =>+ i === 1 ? a : materializeExprInternal(a, ctx, nextScopedRefs),+ );+ return { ...node, args: recursedArgs };+}++function materializeExprInternal(+ node: ASTNode,+ ctx: MaterializeCtx,+ scopedRefs: ReadonlySet<string>,+): ASTNode {+ switch (node.k) {+ case "Ref":+ return scopedRefs.has(node.n) ? node : (resolveRef(node.n, ctx, "expr") as ASTNode);++ case "Ph":+ return node;++ case "Comp": {+ const lazy = materializeLazyBuiltin(node, ctx, scopedRefs);+ if (lazy) return lazy;+ const recursedArgs = node.args.map((a) => materializeExprInternal(a, ctx, scopedRefs));+ // Builtins, reserved calls, and action calls: recurse args, keep as-is+ if (isBuiltin(node.name) || isReservedCall(node.name)) {+ return { ...node, args: recursedArgs };+ }+ // Catalog component: add mappedProps for the evaluator+ const def = ctx.cat?.get(node.name);+ if (def) {+ const mappedProps: Record<string, ASTNode> = {};+ for (let i = 0; i < def.params.length && i < recursedArgs.length; i++) {+ mappedProps[def.params[i].name] = recursedArgs[i];+ }+ return { ...node, args: recursedArgs, mappedProps };+ }+ // Unknown component in expression: push error (same as value path)+ ctx.errors.push({+ code: "unknown-component",+ component: node.name,+ path: "",+ message: `Unknown component "${node.name}" — not found in catalog or builtins`,+ statementId: ctx.currentStatementId,+ });+ return { ...node, args: recursedArgs };+ }++ case "Arr":+ return { ...node, els: node.els.map((e) => materializeExprInternal(e, ctx, scopedRefs)) };+ case "Obj":+ return {+ ...node,+ entries: node.entries.map(+ ([k, v]) => [k, materializeExprInternal(v, ctx, scopedRefs)] as [string, ASTNode],+ ),+ };+ case "BinOp":+ return {+ ...node,+ left: materializeExprInternal(node.left, ctx, scopedRefs),+ right: materializeExprInternal(node.right, ctx, scopedRefs),+ };+ case "UnaryOp":+ return { ...node, operand: materializeExprInternal(node.operand, ctx, scopedRefs) };+ case "Ternary":+ return {+ ...node,+ cond: materializeExprInternal(node.cond, ctx, scopedRefs),+ then: materializeExprInternal(node.then, ctx, scopedRefs),+ else: materializeExprInternal(node.else, ctx, scopedRefs),+ };+ case "Member":+ return { ...node, obj: materializeExprInternal(node.obj, ctx, scopedRefs) };+ case "Index":+ return {+ ...node,+ obj: materializeExprInternal(node.obj, ctx, scopedRefs),+ index: materializeExprInternal(node.index, ctx, scopedRefs),+ };+ case "Assign":+ return { ...node, value: materializeExprInternal(node.value, ctx, scopedRefs) };++ // Literals, StateRef, RuntimeRef — pass through unchanged+ default:+ return node;+ }+}++/**+ * Normalize an AST node for use inside runtime expressions.+ * Resolves Refs, adds mappedProps to catalog Comp nodes.+ * Returns ASTNode — structure preserved for runtime evaluation by the evaluator.+ */+export function materializeExpr(node: ASTNode, ctx: MaterializeCtx): ASTNode {+ return materializeExprInternal(node, ctx, new Set());+}++/**+ * Schema-aware materialization: resolves refs, normalizes catalog component args+ * to named props, validates required props, applies defaults, converts literals+ * to plain values, and preserves runtime expressions as AST nodes — all in a+ * single recursive traversal.+ *+ * Returns:+ * - ElementNode for catalog/unknown components+ * - ASTNode for builtins and runtime expression nodes+ * - Plain values for literals, arrays, objects+ * - null for placeholders+ */+export function materializeValue(node: ASTNode, ctx: MaterializeCtx): unknown {+ switch (node.k) {+ // ── Ref resolution ───────────────────────────────────────────────────+ case "Ref":+ return resolveRef(node.n, ctx, "value");++ // ── Literals → plain values ──────────────────────────────────────────+ case "Str":+ return node.v;+ case "Num":+ return node.v;+ case "Bool":+ return node.v;+ case "Null":+ return null;+ case "Ph":+ return null;++ // ── Collections ──────────────────────────────────────────────────────+ case "Arr": {+ const items: unknown[] = [];+ for (const e of node.els) {+ if (e.k === "Ph") continue;+ items.push(materializeValue(e, ctx));+ }+ return items;+ }+ case "Obj": {+ const o: Record<string, unknown> = {};+ for (const [k, v] of node.entries) o[k] = materializeValue(v, ctx);+ return o;+ }++ // ── Component nodes ──────────────────────────────────────────────────+ case "Comp": {+ const { name, args } = node;++ // Builtins (Sum, Count, Filter, Action, etc.) → preserve as ASTNode for runtime+ if (isBuiltin(name)) {+ const lazy = materializeLazyBuiltin(node, ctx, new Set());+ if (lazy) return lazy;+ return { ...node, args: args.map((a) => materializeExpr(a, ctx)) };+ }++ // Inline Query/Mutation (not from a statement-level declaration) → validation error+ if (isReservedCall(name)) {+ ctx.errors.push({+ code: "inline-reserved",+ component: name,+ path: "",+ message: `${name}() must be declared as a top-level statement, not used inline as a value`,+ statementId: ctx.currentStatementId,+ });+ return null;+ }++ const def = ctx.cat?.get(name);+ const props: Record<string, unknown> = {};++ if (def) {+ // Catalog component: map positional args → named props+ for (let i = 0; i < def.params.length && i < args.length; i++) {+ props[def.params[i].name] = materializeValue(args[i], ctx);+ }++ // Validate required props — try defaultValue first before dropping+ const missingRequired = def.params.filter(+ (p) => p.required && (!(p.name in props) || props[p.name] === null),+ );+ if (missingRequired.length) {+ const stillInvalid = missingRequired.filter((p) => {+ if (p.defaultValue !== undefined) {+ props[p.name] = p.defaultValue;+ return false;+ }+ return true;+ });+ if (stillInvalid.length) {+ for (const p of stillInvalid) {+ const isNull = p.name in props;+ ctx.errors.push({+ code: isNull ? "null-required" : "missing-required",+ component: name,+ path: `/${p.name}`,+ message: isNull+ ? `required field "${p.name}" cannot be null`+ : `missing required field "${p.name}"`,+ statementId: ctx.currentStatementId,+ });+ }+ return null;+ }+ }+ } else if (!isBuiltin(name) && !isReservedCall(name)) {+ // Unknown component: error and drop from tree+ ctx.errors.push({+ code: "unknown-component",+ component: name,+ path: "",+ message: `Unknown component "${name}" — not found in catalog or builtins`,+ statementId: ctx.currentStatementId,+ });+ return null;+ }++ const hasDynamicProps = Object.values(props).some((v) => containsDynamicValue(v));+ return { type: "element", typeName: name, props, partial: ctx.partial, hasDynamicProps };+ }++ // ── Runtime expression nodes → preserve as ASTNode, normalize children ─+ default: {+ if (isRuntimeExpr(node)) {+ return materializeExpr(node, ctx);+ }+ // Unreachable for well-formed AST, but preserve the value defensively.+ return node;+ }+ }+}diff --git a/packages/lang-core/src/parser/merge.ts b/packages/lang-core/src/parser/merge.tsnew file mode 100644index 000000000..69ba9a093--- /dev/null+++ b/packages/lang-core/src/parser/merge.ts@@ -0,0 +1,184 @@+// ─────────────────────────────────────────────────────────────────────────────+// Edit/Merge for openui-lang+// ─────────────────────────────────────────────────────────────────────────────++import type { ASTNode } from "./ast";+import { walkAST } from "./ast";+import { parseExpression } from "./expressions";+import { tokenize } from "./lexer";+import { stripFences } from "./parser";+import { split } from "./statements";++interface ParsedStatement {+ id: string;+ ast: ASTNode;+ raw: string;+}++function splitStatementSource(input: string): string[] {+ const stmts: string[] = [];+ let depth = 0;+ let inStr: false | '"' | "'" = false;+ let esc = false;+ let start = 0;++ for (let i = 0; i < input.length; i++) {+ const c = input[i];++ if (esc) {+ esc = false;+ continue;+ }+ if (c === "\\" && inStr) {+ esc = true;+ continue;+ }+ if (inStr) {+ if (c === inStr) inStr = false;+ continue;+ }+ if (c === '"' || c === "'") {+ inStr = c;+ continue;+ }++ if (c === "(" || c === "[" || c === "{") depth++;+ else if (c === ")" || c === "]" || c === "}") depth = Math.max(0, depth - 1);+ else if (c === "\n" && depth <= 0) {+ const stmt = input.slice(start, i).trim();+ if (stmt) stmts.push(stmt);+ start = i + 1;+ }+ }++ const tail = input.slice(start).trim();+ if (tail) stmts.push(tail);+ return stmts;+}++function parseStatements(input: string): ParsedStatement[] {+ const trimmed = input.trim();+ if (!trimmed) return [];++ const result: ParsedStatement[] = [];+ for (const raw of splitStatementSource(trimmed)) {+ const stmt = split(tokenize(raw))[0];+ if (!stmt) continue;+ result.push({+ id: stmt.id,+ ast: parseExpression(stmt.tokens),+ raw,+ });+ }++ return result;+}++/**+ * Recursively collect all Ref names from an AST node.+ */+function collectRefs(node: ASTNode, out: Set<string>): void {+ walkAST(node, (current) => {+ if (current.k === "Ref") out.add(current.n);+ if (current.k === "RuntimeRef") out.add(current.n);+ });+}++/**+ * Remove statements unreachable from `root` (garbage collection).+ * Walks the AST graph from root, collecting all referenced statement IDs.+ * $state variables are always kept (they're referenced at runtime, not by Ref nodes).+ */+function gcUnreachable(+ order: string[],+ merged: Map<string, string>,+ asts: Map<string, ASTNode>,+ rootId = "root",+): void {+ const rootAst = asts.get(rootId);+ if (!rootAst) return; // no root → can't GC++ // BFS from root to find all reachable statements+ const reachable = new Set<string>([rootId]);+ const queue: string[] = [rootId];++ while (queue.length > 0) {+ const id = queue.pop()!;+ const ast = asts.get(id);+ if (!ast) continue;++ const refs = new Set<string>();+ collectRefs(ast, refs);++ for (const ref of refs) {+ if (!reachable.has(ref) && asts.has(ref)) {+ reachable.add(ref);+ queue.push(ref);+ }+ }+ }++ // Keep $state variables — they're bound at runtime, not via Ref+ for (const id of order) {+ if (id.startsWith("$")) reachable.add(id);+ }++ // Remove unreachable statements+ for (let i = order.length - 1; i >= 0; i--) {+ if (!reachable.has(order[i])) {+ merged.delete(order[i]);+ order.splice(i, 1);+ }+ }+}++/**+ * Merge an existing program with a patch (partial update).+ * Patch statements override existing ones by name.+ * Unreachable statements are automatically garbage-collected.+ * Returns the merged program as a string.+ */+export function mergeStatements(existing: string, patch: string, rootId = "root"): string {+ const existingStmts = parseStatements(existing);+ const patchStmts = parseStatements(stripFences(patch));++ if (!existingStmts.length) {+ return patchStmts.map((stmt) => stmt.raw).join("\n");+ }+ if (!patchStmts.length) return existing;++ // Merge: patch statements override existing by name+ const merged = new Map<string, string>();+ const asts = new Map<string, ASTNode>();+ const order: string[] = [];++ for (const stmt of existingStmts) {+ merged.set(stmt.id, stmt.raw);+ asts.set(stmt.id, stmt.ast);+ order.push(stmt.id);+ }++ for (const stmt of patchStmts) {+ if (stmt.ast.k === "Null") {+ // `name = null` in a patch means "delete this statement"+ merged.delete(stmt.id);+ asts.delete(stmt.id);+ const idx = order.indexOf(stmt.id);+ if (idx !== -1) order.splice(idx, 1);+ continue;+ }+ if (!merged.has(stmt.id)) {+ order.push(stmt.id);+ }+ merged.set(stmt.id, stmt.raw);+ asts.set(stmt.id, stmt.ast);+ }++ // GC: remove statements unreachable from root+ gcUnreachable(order, merged, asts, rootId);++ return order+ .filter((id) => merged.has(id))+ .map((id) => merged.get(id)!)+ .join("\n");+}diff --git a/packages/lang-core/src/parser/parser.ts b/packages/lang-core/src/parser/parser.tsindex de99071b9..1e9f914c2 100644--- a/packages/lang-core/src/parser/parser.ts+++ b/packages/lang-core/src/parser/parser.ts@@ -1,629 +1,219 @@-import type { ParseResult } from "./types";--/**- * The JSON Schema document produced by `library.toJSONSchema()`.- * All component schemas live in `$defs`, keyed by component name.- */-export interface LibraryJSONSchema {- $defs?: Record<- string,- {- properties?: Record<string, unknown>;- required?: string[];- }- >;-}--export interface ParamDef {- /** Parameter name, e.g. "title", "columns". */- name: string;- /** Whether the parameter is required by the component. */- required: boolean;- /** Default value from JSON Schema — used when the required field is missing/null. */- defaultValue?: unknown;-}--/**- * Internal parameter map.- */-export type ParamMap = Map<string, { params: ParamDef[] }>;+import type { ASTNode, Statement } from "./ast";+import { isASTNode, walkAST } from "./ast";+import { isBuiltin, RESERVED_CALLS } from "./builtins";+import { parseExpression } from "./expressions";+import { tokenize } from "./lexer";+import { materializeValue, type MaterializeCtx } from "./materialize";+import { autoClose, split, type RawStmt } from "./statements";+import { T } from "./tokens";+import {+ isElementNode,+ type LibraryJSONSchema,+ type MutationStatementInfo,+ type ParamMap,+ type ParseResult,+ type QueryStatementInfo,+ type ValidationError,+} from "./types";// ─────────────────────────────────────────────────────────────────────────────-// AST node types+// Result building// ─────────────────────────────────────────────────────────────────────────────-/**- * Discriminated union representing every value that can appear in an- * openui-lang expression. The `k` field is the discriminant.- *- * - `Comp` — a component call: `Header("Hello", "Subtitle")`- * - `Str` — a string literal: `"hello"`- * - `Num` — a number literal: `42` or `3.14`- * - `Bool` — a boolean literal: `true` or `false`- * - `Null` — the null literal- * - `Arr` — an array: `[a, b, c]`- * - `Obj` — an object: `{ key: value }`- * - `Ref` — a reference to another statement: `myTable` (resolved later)- * - `Ph` — a placeholder for an unresolvable reference (dropped as null in output)- */-type ASTNode =- | { k: "Comp"; name: string; args: ASTNode[] }- | { k: "Str"; v: string }- | { k: "Num"; v: number }- | { k: "Bool"; v: boolean }- | { k: "Null" }- | { k: "Arr"; els: ASTNode[] }- | { k: "Obj"; entries: [string, ASTNode][] }- | { k: "Ref"; n: string }- | { k: "Ph"; n: string };--const enum T {- Newline = 0,- LParen = 1, // (- RParen = 2, // )- LBrack = 3, // [- RBrack = 4, // ]- LBrace = 5, // {- RBrace = 6, // }- Comma = 7, // ,- Colon = 8, // :- Equals = 9, // =- True = 10,- False = 11,- Null = 12,- EOF = 13,- Str = 14, // carries string value- Num = 15, // carries numeric value- Ident = 16, // lowercase identifier — becomes a reference- Type = 17, // PascalCase identifier — becomes a component name or reference-}--type Token = { t: T; v?: string | number };--function autoClose(input: string): { text: string; wasIncomplete: boolean } {- const stack: string[] = [];- let inStr = false,- esc = false;-- for (let i = 0; i < input.length; i++) {- const c = input[i];-- if (esc) {- esc = false;- continue;- }- if (c === "\\" && inStr) {- esc = true;- continue;- }- if (c === '"') {- inStr = !inStr;- continue;- }- if (inStr) continue;-- if (c === "(" || c === "[" || c === "{") stack.push(c);- else if (c === ")" && stack[stack.length - 1] === "(") stack.pop();- else if (c === "]" && stack[stack.length - 1] === "[") stack.pop();- else if (c === "}" && stack[stack.length - 1] === "{") stack.pop();- }-- const wasIncomplete = inStr || stack.length > 0;- if (!wasIncomplete) return { text: input, wasIncomplete: false };-- let out = input;- if (inStr) {- if (esc) out += "\\";- out += '"';- } // close open string- for (- let j = stack.length - 1;- j >= 0;- j-- // close brackets in reverse- )- out += stack[j] === "(" ? ")" : stack[j] === "[" ? "]" : "}";-- return { text: out, wasIncomplete: true };-}--// lexer-function tokenize(src: string): Token[] {- const tokens: Token[] = [];- let i = 0;- const n = src.length;-- while (i < n) {- // Skip horizontal whitespace (not newlines — they're significant)- while (i < n && (src[i] === " " || src[i] === "\t" || src[i] === "\r")) i++;- if (i >= n) break;-- const c = src[i];-- // ── Single-character punctuation ──────────────────────────────────────- if (c === "\n") {- tokens.push({ t: T.Newline });- i++;- continue;- }- if (c === "(") {- tokens.push({ t: T.LParen });- i++;- continue;- }- if (c === ")") {- tokens.push({ t: T.RParen });- i++;- continue;- }- if (c === "[") {- tokens.push({ t: T.LBrack });- i++;- continue;- }- if (c === "]") {- tokens.push({ t: T.RBrack });- i++;- continue;- }- if (c === "{") {- tokens.push({ t: T.LBrace });- i++;- continue;- }- if (c === "}") {- tokens.push({ t: T.RBrace });- i++;- continue;- }- if (c === ",") {- tokens.push({ t: T.Comma });- i++;- continue;- }- if (c === ":") {- tokens.push({ t: T.Colon });- i++;- continue;- }- if (c === "=") {- tokens.push({ t: T.Equals });- i++;- continue;- }-- // string literal: "..."- if (c === '"') {- const start = i;- i++; // skip opening quote-- let isClosed = false;- // Fast-forward to the closing quote, respecting escapes- while (i < n) {- if (src[i] === "\\") {- i += 2; // skip backslash and the escaped character- } else if (src[i] === '"') {- i++; // include the closing quote- isClosed = true;- break;- } else {- i++;- }- }-- const rawString = src.slice(start, i);-- try {- // Let JavaScript's native JSON parser handle all unescaping (\n, \t, \uXXXX, etc.)- // If the string is incomplete (streaming), we add a closing quote to parse what we have so far.- const validJsonString = isClosed ? rawString : rawString + '"';-- tokens.push({ t: T.Str, v: JSON.parse(validJsonString) });- } catch {- // Fallback if JSON.parse fails (e.g., malformed unicode escape during streaming)- // Strip the quotes and return the raw text so the UI doesn't crash- const stripped = rawString.replace(/^"|"$/g, "");- tokens.push({ t: T.Str, v: stripped });- }- continue;- }-- // number literal: 42, -3, 1.5- const isDigit = c >= "0" && c <= "9";- const isNegDigit = c === "-" && i + 1 < n && src[i + 1] >= "0" && src[i + 1] <= "9";- if (isDigit || isNegDigit) {- const start = i;- if (src[i] === "-") i++; // optional minus- while (i < n && src[i] >= "0" && src[i] <= "9") i++; // integer part- if (i < n && src[i] === ".") {- // optional decimal- i++;- while (i < n && src[i] >= "0" && src[i] <= "9") i++;- }- if (i < n && (src[i] === "e" || src[i] === "E")) {- // optional exponent- i++;- if (i < n && (src[i] === "+" || src[i] === "-")) i++;- while (i < n && src[i] >= "0" && src[i] <= "9") i++;- }- tokens.push({ t: T.Num, v: +src.slice(start, i) });- continue;- }-- // keyword or identifier- const isAlpha = (c >= "a" && c <= "z") || (c >= "A" && c <= "Z") || c === "_";- if (isAlpha) {- const start = i;- while (- i < n &&- ((src[i] >= "a" && src[i] <= "z") ||- (src[i] >= "A" && src[i] <= "Z") ||- (src[i] >= "0" && src[i] <= "9") ||- src[i] === "_")- )- i++;-- const word = src.slice(start, i);-- if (word === "true") {- tokens.push({ t: T.True });- continue;- }- if (word === "false") {- tokens.push({ t: T.False });- continue;- }- if (word === "null") {- tokens.push({ t: T.Null });- continue;- }-- // PascalCase → component type name; lowercase → variable reference- const kind = c >= "A" && c <= "Z" ? T.Type : T.Ident;- tokens.push({ t: kind, v: word });- continue;- }-- i++; // skip any other character (e.g. @, #, emojis)- }-- tokens.push({ t: T.EOF });- return tokens;-}--interface RawStmt {- id: string;- tokens: Token[];+function emptyResult(incomplete = true): ParseResult {+ return {+ root: null,+ meta: {+ incomplete,+ unresolved: [],+ statementCount: 0,+ errors: [],+ },+ stateDeclarations: {},+ queryStatements: [],+ mutationStatements: [],+ };}/**- * Splits the flat token stream into individual statements.- *- * Each statement has the form `identifier = expression`. Statements are- * separated by newlines at depth 0 (newlines inside brackets are ignored).- *- * Example input tokens for:- * `root = Root([tbl])\ntbl = Table(...)`- *- * Produces two RawStmts:- * { id: "root", tokens: [Root, (, [, tbl, ], )] }- * { id: "tbl", tokens: [Table, (, ..., )] }- *- * Invalid lines (no `=`, or no identifier) are silently skipped.+ * Walk an AST node to collect all StateRef ($variable) names referenced+ * within. Used at parse time to pre-compute per-query state dependencies.*/-function split(tokens: Token[]): RawStmt[] {- const stmts: RawStmt[] = [];- let pos = 0;-- while (pos < tokens.length) {- // Skip blank lines- while (pos < tokens.length && tokens[pos].t === T.Newline) pos++;- if (pos >= tokens.length || tokens[pos].t === T.EOF) break;-- // Expect: Ident|Type = expression- const tok = tokens[pos];- if (tok.t !== T.Ident && tok.t !== T.Type) {- while (pos < tokens.length && tokens[pos].t !== T.Newline && tokens[pos].t !== T.EOF) pos++;- continue;- }- const id = tok.v as string;- pos++;-- // Must be followed by `=`- if (pos >= tokens.length || tokens[pos].t !== T.Equals) {- while (pos < tokens.length && tokens[pos].t !== T.Newline && tokens[pos].t !== T.EOF) pos++;- continue;- }- pos++;-- // Collect expression tokens until a depth-0 newline or EOF- const expr: Token[] = [];- let depth = 0;- while (pos < tokens.length && tokens[pos].t !== T.EOF) {- const tt = tokens[pos].t;- if (tt === T.Newline && depth <= 0) break; // statement boundary- if (tt === T.Newline) {- pos++;- continue;- } // newline inside bracket — skip- if (tt === T.LParen || tt === T.LBrack || tt === T.LBrace) depth++;- else if (tt === T.RParen || tt === T.RBrack || tt === T.RBrace) depth--;- expr.push(tokens[pos++]);- }-- if (expr.length) stmts.push({ id, tokens: expr });- }-- return stmts;+export function collectQueryDeps(node: unknown): string[] {+ if (!isASTNode(node)) return [];+ const refs = new Set<string>();+ walkAST(node, (current) => {+ if (current.k === "StateRef") refs.add(current.n);+ });+ return [...refs];}-function parseTokens(tokens: Token[]): ASTNode {- let pos = 0;- const cur = (): Token => tokens[pos] ?? { t: T.EOF };- const adv = () => pos++;- const eat = (kind: T) => {- if (cur().t === kind) adv();- };-- function parseExpr(): ASTNode {- const tok = cur();-- if (tok.t === T.Type) {- // PascalCase followed by `(` → component call; otherwise a reference- return tokens[pos + 1]?.t === T.LParen- ? parseComp()- : (adv(), { k: "Ref", n: tok.v as string });- }- if (tok.t === T.Str) {- adv();- return { k: "Str", v: tok.v as string };- }- if (tok.t === T.Num) {- adv();- return { k: "Num", v: tok.v as number };- }- if (tok.t === T.True) {- adv();- return { k: "Bool", v: true };- }- if (tok.t === T.False) {- adv();- return { k: "Bool", v: false };- }- if (tok.t === T.Null) {- adv();- return { k: "Null" };- }- if (tok.t === T.LBrack) return parseArr();- if (tok.t === T.LBrace) return parseObj();- if (tok.t === T.Ident) {- adv();- return { k: "Ref", n: tok.v as string };- }-- adv();- return { k: "Null" }; // unknown token — treat as null- }-- /** Parse `TypeName(arg1, arg2, ...)` */- function parseComp(): ASTNode {- const name = cur().v as string;- adv();- eat(T.LParen);- const args: ASTNode[] = [];- while (cur().t !== T.RParen && cur().t !== T.EOF) {- args.push(parseExpr());- if (cur().t === T.Comma) adv();- }- eat(T.RParen);- return { k: "Comp", name, args };- }-- /** Parse `[elem1, elem2, ...]` */- function parseArr(): ASTNode {- adv(); // skip [- const els: ASTNode[] = [];- while (cur().t !== T.RBrack && cur().t !== T.EOF) {- els.push(parseExpr());- if (cur().t === T.Comma) adv();- }- eat(T.RBrack);- return { k: "Arr", els };- }-- /** Parse `{ key: value, ... }` */- function parseObj(): ASTNode {- adv(); // skip {- const entries: [string, ASTNode][] = [];- while (cur().t !== T.RBrace && cur().t !== T.EOF) {- const kt = cur();- const key =- kt.t === T.Ident || kt.t === T.Str || kt.t === T.Type || kt.t === T.Num- ? (adv(), String(kt.v))- : (adv(), "?");- eat(T.Colon);- entries.push([key, parseExpr()]);- if (cur().t === T.Comma) adv();- }- eat(T.RBrace);- return { k: "Obj", entries };- }-- return parseExpr();-}--function resolveNode(- node: ASTNode,- syms: Map<string, ASTNode>,- unres: string[],- visited: Set<string>,-): ASTNode {- if (node.k === "Ref") {- const { n } = node;- if (visited.has(n)) {- unres.push(n);- return { k: "Ph", n };- } // cycle- if (!syms.has(n)) {- unres.push(n);- return { k: "Ph", n };- } // missing-- visited.add(n);- const resolved = resolveNode(syms.get(n)!, syms, unres, visited);- visited.delete(n);- return resolved;- }-- if (node.k === "Comp")- return {- ...node,- args: node.args.map((a) => resolveNode(a, syms, unres, visited)),- };- if (node.k === "Arr")+/**+ * Classify a raw statement + parsed expression into a typed Statement.+ * Determined at parse time from token type + expression shape.+ */+function classifyStatement(raw: RawStmt, expr: ASTNode): Statement {+ // Query(...) → query declaration — check BEFORE $var to handle `$foo = Query(...)` correctly+ if (expr.k === "Comp" && expr.name === RESERVED_CALLS.Query) {+ const deps = collectQueryDeps(expr.args[1]);return {- ...node,- els: node.els.map((e) => resolveNode(e, syms, unres, visited)),+ kind: "query",+ id: raw.id,+ call: { callee: RESERVED_CALLS.Query, args: expr.args },+ expr,+ deps: deps.length > 0 ? deps : undefined,};- if (node.k === "Obj")+ }+ // Mutation(...) → mutation declaration+ if (expr.k === "Comp" && expr.name === RESERVED_CALLS.Mutation) {return {- ...node,- entries: node.entries.map(([k, v]) => [k, resolveNode(v, syms, unres, visited)]),+ kind: "mutation",+ id: raw.id,+ call: { callee: RESERVED_CALLS.Mutation, args: expr.args },+ expr,};-- // Literals and placeholders pass through unchanged- return node;-}--type JsonVal = string | number | boolean | null | JsonVal[] | { [k: string]: JsonVal };--function toJson(- node: ASTNode,- partial: boolean,- errors: ParseResult["meta"]["errors"],- cat: ParamMap | undefined,-): JsonVal {- if (node.k === "Str") return node.v;- if (node.k === "Num") return node.v;- if (node.k === "Bool") return node.v;- if (node.k === "Null") return null;- if (node.k === "Arr") {- const items: JsonVal[] = [];- for (const e of node.els) {- // Drop unresolved references from arrays to avoid null entries like [null, element]- if (e.k === "Ph") continue;- const value = toJson(e, partial, errors, cat);- // Drop invalid component entries from arrays (e.g. incomplete required props while streaming)- if (e.k === "Comp" && value === null) continue;- items.push(value);- }- return items;}- if (node.k === "Obj") {- const o: { [k: string]: JsonVal } = {};- for (const [k, v] of node.entries) o[k] = toJson(v, partial, errors, cat);- return o;+ // $variables → state declaration+ if (raw.idTokenType === T.StateVar) {+ return { kind: "state", id: raw.id, init: expr };}- if (node.k === "Comp") return mapNode(node, partial, errors, cat) as unknown as JsonVal;- if (node.k === "Ph") return null;- return null;+ // Everything else → value declaration+ return { kind: "value", id: raw.id, expr };}-function mapNode(- node: ASTNode,- partial: boolean,- errors: ParseResult["meta"]["errors"],- cat: ParamMap | undefined,-): ParseResult["root"] {- if (node.k === "Ph") return null;- if (node.k !== "Comp") return null;-- const { name, args } = node;- const def = cat?.get(name);- const props: { [k: string]: JsonVal } = {};-- if (def) {- // Map positional args → named props using library param order- for (let i = 0; i < def.params.length && i < args.length; i++)- props[def.params[i].name] = toJson(args[i], partial, errors, cat);-- // Report extra positional args that have no corresponding param- if (args.length > def.params.length) {- errors.push({- type: "validation",- code: "excess-args",- component: name,- path: "",- message: `${name} takes ${def.params.length} arg(s), got ${args.length}`,- });+/**+ * Extract typed statements from the symbol table.+ * State defaults are materialized to plain values (no raw AST in output).+ */+function extractStatements(+ stmts: Statement[],+ ctx: MaterializeCtx,+): {+ stateDeclarations: Record<string, unknown>;+ queryStatements: QueryStatementInfo[];+ mutationStatements: MutationStatementInfo[];+} {+ const stateDeclarations: Record<string, unknown> = {};+ const queryStatements: QueryStatementInfo[] = [];+ const mutationStatements: MutationStatementInfo[] = [];++ for (const stmt of stmts) {+ switch (stmt.kind) {+ case "state":+ stateDeclarations[stmt.id] = materializeValue(stmt.init, ctx);+ break;+ case "query":+ queryStatements.push({+ statementId: stmt.id,+ toolAST: stmt.call.args[0] ?? null,+ argsAST: stmt.call.args[1] ?? null,+ defaultsAST: stmt.call.args[2] ?? null,+ refreshAST: stmt.call.args[3] ?? null,+ deps: stmt.deps,+ complete: true,+ });+ break;+ case "mutation":+ mutationStatements.push({+ statementId: stmt.id,+ toolAST: stmt.call.args[0] ?? null,+ argsAST: stmt.call.args[1] ?? null,+ });+ break;}+ }- // Validate required props — try defaultValue first before dropping- const missingRequired = def.params.filter(- (p) => p.required && (!(p.name in props) || props[p.name] === null),- );- if (missingRequired.length) {- const stillInvalid = missingRequired.filter((p) => {- if (p.defaultValue !== undefined) {- props[p.name] = p.defaultValue as JsonVal;- return false;+ // Auto-declare: any $var referenced in code but not explicitly declared → null default.+ // collectQueryDeps already walks AST for StateRef nodes — reuse it here.+ for (const stmt of stmts) {+ const nodes =+ stmt.kind === "state"+ ? [stmt.init]+ : stmt.kind === "value"+ ? [stmt.expr]+ : stmt.kind === "query" || stmt.kind === "mutation"+ ? stmt.call.args+ : [];+ for (const node of nodes) {+ for (const dep of collectQueryDeps(node)) {+ if (!(dep in stateDeclarations)) {+ stateDeclarations[dep] = null;}- return true;- });- if (stillInvalid.length) {- for (const p of stillInvalid)- errors.push({- type: "validation",- code: p.name in props ? "null-required" : "missing-required",- component: name,- path: `/${p.name}`,- message:- p.name in props- ? `required field "${p.name}" cannot be null`- : `missing required field "${p.name}"`,- });- return null;}}- } else {- // Component name not found in schema — report and preserve args for debugging- errors.push({- type: "validation",- code: "unknown-component",- component: name,- path: "",- message: `unknown component "${name}"`,- });- props._args = args.map((a) => toJson(a, partial, errors, cat));}- return { type: "element", typeName: name, props, partial };+ return { stateDeclarations, queryStatements, mutationStatements };}-function emptyResult(incomplete = true): ParseResult {- return {- root: null,- meta: {- incomplete,- unresolved: [],- statementCount: 0,- errors: [],- },- };+const DEFAULT_ROOT_STATEMENT_ID = "root";++function isComponentStatement(+ stmt: Statement,+): stmt is Extract<Statement, { kind: "value" }> & { expr: Extract<ASTNode, { k: "Comp" }> } {+ return (+ stmt.kind === "value" &&+ stmt.expr.k === "Comp" &&+ !isBuiltin(stmt.expr.name) &&+ stmt.expr.name !== RESERVED_CALLS.Query &&+ stmt.expr.name !== RESERVED_CALLS.Mutation+ );+}++function pickEntryId(+ stmtMap: Map<string, Statement>,+ typedStmts: Statement[],+ firstId: string,+ rootName?: string,+): string {+ if (stmtMap.has(DEFAULT_ROOT_STATEMENT_ID)) return DEFAULT_ROOT_STATEMENT_ID;+ if (rootName && stmtMap.has(rootName)) return rootName;++ const preferredComponent = rootName+ ? typedStmts.find((stmt) => isComponentStatement(stmt) && stmt.expr.name === rootName)+ : undefined;+ if (preferredComponent) return preferredComponent.id;++ const firstComponent = typedStmts.find(isComponentStatement);+ return firstComponent?.id ?? firstId;}function buildResult(- syms: Map<string, ASTNode>,+ stmtMap: Map<string, Statement>,+ typedStmts: Statement[],firstId: string,wasIncomplete: boolean,stmtCount: number,cat: ParamMap | undefined,+ rootName?: string,): ParseResult {- if (!syms.has(firstId)) return emptyResult(wasIncomplete);+ const entryId = pickEntryId(stmtMap, typedStmts, firstId, rootName);+ if (!stmtMap.has(entryId)) return emptyResult(wasIncomplete);+ const syms = new Map<string, ASTNode>();+ for (const [id, stmt] of stmtMap) {+ syms.set(id, stmt.kind === "state" ? stmt.init : stmt.expr);+ }const unres: string[] = [];- const resolved = resolveNode(syms.get(firstId)!, syms, unres, new Set());- const errors: ParseResult["meta"]["errors"] = [];- const root = mapNode(resolved, wasIncomplete, errors, cat);+ const errors: ValidationError[] = [];+ const ctx: MaterializeCtx = {+ syms,+ cat,+ errors,+ unres,+ visited: new Set(),+ partial: wasIncomplete,+ currentStatementId: entryId,+ };+ const materialized = materializeValue(syms.get(entryId)!, ctx);++ const root = isElementNode(materialized) ? materialized : null;+ if (root) root.statementId = entryId;++ const { stateDeclarations, queryStatements, mutationStatements } = extractStatements(+ typedStmts,+ ctx,+ );return {root,@@ -631,54 +221,197 @@ function buildResult(incomplete: wasIncomplete,unresolved: unres,statementCount: stmtCount,- errors,+ errors: errors,},+ stateDeclarations,+ queryStatements,+ mutationStatements,};}+// ─────────────────────────────────────────────────────────────────────────────+// Public API+// ─────────────────────────────────────────────────────────────────────────────++/** Extract code from markdown fences, or return as-is if no fences found.+ * String-context-aware: skips ``` inside double-quoted strings. */+export function stripFences(input: string): string {+ const blocks: string[] = [];+ let i = 0;++ while (i < input.length) {+ // Look for opening ```+ const fenceStart = input.indexOf("```", i);+ if (fenceStart === -1) break;++ // Skip language tag until newline+ let j = fenceStart + 3;+ while (j < input.length && input[j] !== "\n") j++;+ if (j >= input.length) {+ // No newline after opening fence (streaming) — take everything after fence marker + lang tag+ blocks.push(input.slice(fenceStart + 3).replace(/^[^\n]*\n?/, ""));+ i = input.length;+ break;+ }+ j++; // skip the newline++ // Scan for closing ``` while tracking string context+ let inStr = false;+ let closePos = -1;+ let k = j;+ while (k < input.length) {+ const c = input[k];+ if (inStr) {+ if (c === "\\" && k + 1 < input.length) {+ k += 2; // skip escaped character+ continue;+ }+ if (c === '"') inStr = false;+ k++;+ continue;+ }+ // Not in string+ if (c === '"') {+ inStr = true;+ k++;+ continue;+ }+ if (+ c === "`" &&+ k + 1 < input.length &&+ input[k + 1] === "`" &&+ k + 2 < input.length &&+ input[k + 2] === "`"+ ) {+ closePos = k;+ break;+ }+ k++;+ }++ if (closePos !== -1) {+ blocks.push(input.slice(j, closePos));+ i = closePos + 3;+ } else {+ // No closing fence found (streaming) — take everything after opening fence+ blocks.push(input.slice(j));+ i = input.length;+ }+ }++ if (blocks.length > 0) return blocks.join("\n");++ // Fallback: if input starts with ``` but wasn't matched (e.g. no newline after fence)+ if (input.startsWith("```")) {+ let j = 3;+ while (j < input.length && input[j] !== "\n") j++;+ const start = j < input.length ? j + 1 : 3;+ // Try to strip trailing ```+ const body = input.slice(start);+ const trailingFence = body.lastIndexOf("```");+ if (trailingFence !== -1) {+ return body.slice(0, trailingFence);+ }+ return body;+ }++ return input;+}++/** Strip // and # line comments outside of strings (handles both " and ' delimiters). */+function stripComments(input: string): string {+ return input+ .split("\n")+ .map((line) => {+ let inStr: false | '"' | "'" = false;+ for (let i = 0; i < line.length; i++) {+ const c = line[i];+ if (inStr) {+ if (c === "\\" && i + 1 < line.length) {+ i++; // skip escaped char+ continue;+ }+ if (c === inStr) inStr = false;+ continue;+ }+ if (c === '"' || c === "'") {+ inStr = c;+ continue;+ }+ // // style comments+ if (c === "/" && line[i + 1] === "/") {+ return line.substring(0, i).trimEnd();+ }+ // # style comments (Python/YAML style — LLMs sometimes use these)+ if (c === "#") {+ return line.substring(0, i).trimEnd();+ }+ }+ return line;+ })+ .join("\n");+}++/** Clean LLM response: strip fences, comments, whitespace. */+function preprocess(input: string): string {+ return stripComments(stripFences(input.trim())).trim();+}+/*** Parse a complete openui-lang string in one pass.** @param input - Full openui-lang source text (may be partial/streaming)- * @param cat - Optional param map for positional-arg → named-prop mapping+ * @param cat - Param map for positional-arg → named-prop mapping* @returns ParseResult with root ElementNode (or null) and metadata*/-export function parse(input: string, cat?: ParamMap): ParseResult {- const trimmed = input.trim();+export function parse(input: string, cat: ParamMap, rootName?: string): ParseResult {+ const trimmed = preprocess(input);if (!trimmed) return emptyResult();const { text, wasIncomplete } = autoClose(trimmed);const stmts = split(tokenize(text));if (!stmts.length) return emptyResult(wasIncomplete);- const syms = new Map<string, ASTNode>();+ const stmtMap = new Map<string, Statement>();let firstId = "";for (const s of stmts) {- syms.set(s.id, parseTokens(s.tokens));+ const expr = parseExpression(s.tokens);+ const stmt = classifyStatement(s, expr);+ stmtMap.set(s.id, stmt);if (!firstId) firstId = s.id;}+ // Derive from map to deduplicate — Map.set overwrites duplicates+ const typedStmts = [...stmtMap.values()];- return buildResult(syms, firstId, wasIncomplete, stmts.length, cat);+ return buildResult(stmtMap, typedStmts, firstId, wasIncomplete, stmtMap.size, cat, rootName);}export interface StreamParser {/** Feed the next SSE/stream chunk and get the latest ParseResult. */push(chunk: string): ParseResult;+ /** Set the full text — diffs against internal buffer, pushes only the delta.+ * Resets automatically if the text was replaced (not appended). */+ set(fullText: string): ParseResult;/** Get the latest ParseResult without consuming new data. */getResult(): ParseResult;}-export function createStreamParser(cat?: ParamMap): StreamParser {+export function createStreamParser(cat: ParamMap, rootName?: string): StreamParser {let buf = "";let completedEnd = 0;- const completedSyms = new Map<string, ASTNode>();+ const completedStmtMap = new Map<string, Statement>();let completedCount = 0;let firstId = "";function addStmt(text: string) {- for (const s of split(tokenize(text))) {- completedSyms.set(s.id, parseTokens(s.tokens));+ // Strip comments and skip fence markers+ const cleaned = stripComments(text).trim();+ if (!cleaned || /^```/.test(cleaned)) return;+ for (const s of split(tokenize(cleaned))) {+ const expr = parseExpression(s.tokens);+ const stmt = classifyStatement(s, expr);+ completedStmtMap.set(s.id, stmt);completedCount++;if (!firstId) firstId = s.id;}@@ -686,7 +419,8 @@ export function createStreamParser(cat?: ParamMap): StreamParser {function scanNewCompleted(): number {let depth = 0,- inStr = false,+ ternaryDepth = 0,+ inStr: false | '"' | "'" = false,esc = false;let stmtStart = completedEnd;@@ -700,15 +434,32 @@ export function createStreamParser(cat?: ParamMap): StreamParser {esc = true;continue;}- if (c === '"') {- inStr = !inStr;+ if (inStr) {+ if (c === inStr) inStr = false;+ continue;+ }+ if (c === '"' || c === "'") {+ inStr = c;continue;}- if (inStr) continue;if (c === "(" || c === "[" || c === "{") depth++;- else if (c === ")" || c === "]" || c === "}") depth--;- else if (c === "\n" && depth <= 0) {+ else if (c === ")" || c === "]" || c === "}") depth = Math.max(0, depth - 1);+ // Track ternary ? and : at bracket depth 0 (colons inside {} are object key separators)+ else if (c === "?" && depth === 0) ternaryDepth++;+ else if (c === ":" && depth === 0 && ternaryDepth > 0) ternaryDepth--;+ else if (c === "\n" && depth <= 0 && ternaryDepth <= 0) {+ // Before splitting, look ahead past whitespace to see if the next+ // meaningful character is `?` or `:` — ternary continuation.+ let peek = i + 1;+ while (+ peek < buf.length &&+ (buf[peek] === " " || buf[peek] === "\t" || buf[peek] === "\r" || buf[peek] === "\n")+ )+ peek++;+ if (peek < buf.length && (buf[peek] === "?" || (buf[peek] === ":" && ternaryDepth > 0))) {+ continue; // ternary continuation — don't split+ }// Depth-0 newline = end of a statementconst t = buf.slice(stmtStart, i).trim();if (t) addStmt(t);@@ -727,25 +478,80 @@ export function createStreamParser(cat?: ParamMap): StreamParser {// No pending text — all statements are completeif (!pendingText) {if (completedCount === 0) return emptyResult();- return buildResult(completedSyms, firstId, false, completedCount, cat);+ return buildResult(+ completedStmtMap,+ [...completedStmtMap.values()],+ firstId,+ false,+ completedCount,+ cat,+ rootName,+ );+ }++ // Apply same cleanup as parse() — strip fences, comments, whitespace+ const cleaned = stripComments(stripFences(pendingText)).trim();+ if (!cleaned) {+ if (completedCount === 0) return emptyResult();+ return buildResult(+ completedStmtMap,+ [...completedStmtMap.values()],+ firstId,+ false,+ completedCount,+ cat,+ rootName,+ );}-// Autoclose the incomplete last statement so it's syntactically valid- const { text: closed, wasIncomplete } = autoClose(pendingText);+ const { text: closed, wasIncomplete } = autoClose(cleaned);const stmts = split(tokenize(closed));if (!stmts.length) {if (completedCount === 0) return emptyResult(wasIncomplete);- return buildResult(completedSyms, firstId, wasIncomplete, completedCount, cat);- }-- // Merge: completed cache + re-parsed pending statement- // (Map spread is cheap since completedSyms only grows by one entry at a time)- const allSyms = new Map(completedSyms);- for (const s of stmts) allSyms.set(s.id, parseTokens(s.tokens));+ return buildResult(+ completedStmtMap,+ [...completedStmtMap.values()],+ firstId,+ wasIncomplete,+ completedCount,+ cat,+ rootName,+ );+ }++ // Merge: completed cache + re-parsed pending statement.+ // Pending statements can only add NEW IDs — they cannot overwrite completed ones.+ // This prevents mid-stream partial text (e.g. `root = Card`) from corrupting+ // existing completed statements during edit streaming.+ const allStmtMap = new Map(completedStmtMap);+ for (const s of stmts) {+ if (completedStmtMap.has(s.id)) continue;+ const expr = parseExpression(s.tokens);+ const stmt = classifyStatement(s, expr);+ allStmtMap.set(s.id, stmt);+ }+ // Derive from map to deduplicate+ const allTypedStmts = [...allStmtMap.values()];const fid = firstId || stmts[0].id;- return buildResult(allSyms, fid, wasIncomplete, completedCount + stmts.length, cat);+ return buildResult(+ allStmtMap,+ allTypedStmts,+ fid,+ wasIncomplete,+ completedCount + stmts.length,+ cat,+ rootName,+ );+ }++ function reset() {+ buf = "";+ completedEnd = 0;+ completedStmtMap.clear();+ completedCount = 0;+ firstId = "";}return {@@ -753,6 +559,14 @@ export function createStreamParser(cat?: ParamMap): StreamParser {buf += chunk;return currentResult();},+ set(fullText) {+ if (fullText.length < buf.length || !fullText.startsWith(buf)) {+ reset();+ }+ const delta = fullText.slice(buf.length);+ if (delta) buf += delta;+ return currentResult();+ },getResult: currentResult,};}@@ -761,6 +575,13 @@ export interface Parser {parse(input: string): ParseResult;}+function getSchemaDefaultValue(property: unknown): unknown {+ if (!property || typeof property !== "object" || Array.isArray(property)) {+ return undefined;+ }+ return (property as { default?: unknown }).default;+}+function compileSchema(schema: LibraryJSONSchema): ParamMap {const map: ParamMap = new Map();const defs = schema.$defs ?? {};@@ -768,10 +589,10 @@ function compileSchema(schema: LibraryJSONSchema): ParamMap {for (const [name, def] of Object.entries(defs)) {const properties = def.properties ?? {};const required = def.required ?? [];- const params = Object.keys(properties).map((k) => ({- name: k,- required: required.includes(k),- defaultValue: (properties[k] as any)?.default,+ const params = Object.keys(properties).map((key) => ({+ name: key,+ required: required.includes(key),+ defaultValue: getSchemaDefaultValue(properties[key]),}));map.set(name, { params });}@@ -789,11 +610,11 @@ function compileSchema(schema: LibraryJSONSchema): ParamMap {* const result = parser.parse(openuiLangString);* ```*/-export function createParser(schema: LibraryJSONSchema): Parser {+export function createParser(schema: LibraryJSONSchema, rootName?: string): Parser {const paramMap = compileSchema(schema);return {parse(input: string): ParseResult {- return parse(input, paramMap);+ return parse(input, paramMap, rootName);},};}@@ -802,6 +623,6 @@ export function createParser(schema: LibraryJSONSchema): Parser {* Create a streaming parser from a library JSON Schema document.* Pass `library.toJSONSchema()` to get the schema.*/-export function createStreamingParser(schema: LibraryJSONSchema): StreamParser {- return createStreamParser(compileSchema(schema));+export function createStreamingParser(schema: LibraryJSONSchema, rootName?: string): StreamParser {+ return createStreamParser(compileSchema(schema), rootName);}diff --git a/packages/lang-core/src/parser/prompt.ts b/packages/lang-core/src/parser/prompt.tsindex 11119d678..0fc81d74c 100644--- a/packages/lang-core/src/parser/prompt.ts+++ b/packages/lang-core/src/parser/prompt.ts@@ -1,333 +1,655 @@-import { z } from "zod";-import type { DefinedComponent, Library, PromptOptions } from "../library";+import { BUILTINS, LAZY_BUILTIN_DEFS } from "./builtins";-const PREAMBLE = `You are an AI assistant that responds using openui-lang, a declarative UI language. Your ENTIRE response must be valid openui-lang code — no markdown, no explanations, just openui-lang.`;+// ─── PromptSpec types (JSON-serializable, no Zod deps) ──────────────────────-function syntaxRules(rootName: string): string {- return `## Syntax Rules--1. Each statement is on its own line: \`identifier = Expression\`-2. \`root\` is the entry point — every program must define \`root = ${rootName}(...)\`-3. Expressions are: strings ("..."), numbers, booleans (true/false), arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)-4. Use references for readability: define \`name = ...\` on one line, then use \`name\` later-5. EVERY variable (except root) MUST be referenced by at least one other variable. Unreferenced variables are silently dropped and will NOT render. Always include defined variables in their parent's children/items array.-6. Arguments are POSITIONAL (order matters, not names)-7. Optional arguments can be omitted from the end-8. No operators, no logic, no variables — only declarations-9. Strings use double quotes with backslash escaping`;+/**+ * Tool schema for prompt generation — describes a tool the LLM can use via Query()/Mutation().+ * Shape inspired by MCP's tool schema (name, description, inputSchema, annotations).+ */+export interface ToolSpec {+ name: string;+ description?: string;+ inputSchema: Record<string, unknown>;+ outputSchema: Record<string, unknown>;+ annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean };}-function streamingRules(rootName: string): string {- return `## Hoisting & Streaming (CRITICAL)+export interface ComponentPromptSpec {+ signature: string; // pre-built: "Card(children: Component[], title?: string)"+ description?: string;+}-openui-lang supports hoisting: a reference can be used BEFORE it is defined. The parser resolves all references after the full input is parsed.+export interface ComponentGroup {+ name: string;+ components: string[];+ notes?: string[];+}-During streaming, the output is re-parsed on every chunk. Undefined references are temporarily unresolved and appear once their definitions stream in. This creates a progressive top-down reveal — structure first, then data fills in.+export interface PromptSpec {+ root?: string;+ components: Record<string, ComponentPromptSpec>;+ componentGroups?: ComponentGroup[];+ tools?: (string | ToolSpec)[];+ editMode?: boolean;+ inlineMode?: boolean;+ /** Enable Query(), Mutation(), @Run, tool workflow. Default: true if tools provided. */+ toolCalls?: boolean;+ /** Enable $variables, @Set, @Reset, interactive filters. Default: true if toolCalls. */+ bindings?: boolean;+ preamble?: string;+ /** General examples (static/layout patterns). Both `examples` and `toolExamples` are included when present. */+ examples?: string[];+ /** Tool-specific examples (Query/Mutation patterns). Both `examples` and `toolExamples` are included when present. */+ toolExamples?: string[];+ additionalRules?: string[];+}-**Recommended statement order for optimal streaming:**-1. \`root = ${rootName}(...)\` — UI shell appears immediately-2. Component definitions — fill in as they stream-3. Data values — leaf content last+// ─── JSON Schema → type string helper ───────────────────────────────────────-Always write the root = ${rootName}(...) statement first so the UI shell appears immediately, even before child data has streamed in.`;-}+function jsonSchemaTypeStr(schema: Record<string, unknown>): string {+ const type = schema.type as string | undefined;-function importantRules(rootName: string): string {- return `## Important Rules-- ALWAYS start with root = ${rootName}(...)-- Write statements in TOP-DOWN order: root → components → data (leverages hoisting for progressive streaming)-- Each statement on its own line-- No trailing text or explanations — output ONLY openui-lang code-- When asked about data, generate realistic/plausible data-- Choose components that best represent the content (tables for comparisons, charts for trends, forms for input, etc.)-- NEVER define a variable without referencing it from the tree. Every variable must be reachable from root, otherwise it will not render.`;-}+ if (type === "string") {+ const enumVals = schema.enum as string[] | undefined;+ if (enumVals) return enumVals.map((v) => `"${v}"`).join(" | ");+ return "string";+ }+ if (type === "number" || type === "integer") return "number";+ if (type === "boolean") return "boolean";+ if (type === "array") {+ const items = schema.items as Record<string, unknown> | undefined;+ if (items) return `${jsonSchemaTypeStr(items)}[]`;+ return "any[]";+ }+ if (type === "object") {+ const props = schema.properties as Record<string, Record<string, unknown>> | undefined;+ if (props && Object.keys(props).length > 0) {+ const required = (schema.required as string[]) ?? [];+ const fields = Object.entries(props).map(([k, v]) => {+ const opt = required.includes(k) ? "" : "?";+ return `${k}${opt}: ${jsonSchemaTypeStr(v)}`;+ });+ return `{${fields.join(", ")}}`;+ }+ return "object";+ }-function getZodDef(schema: unknown): any {- return (schema as any)?._zod?.def;+ return "any";}-function getZodType(schema: unknown): string | undefined {- return getZodDef(schema)?.type;+/** Generate a default-values hint object for an output schema. */+function defaultForSchema(schema: Record<string, unknown>): unknown {+ const type = schema.type as string | undefined;+ if (type === "string") return "";+ if (type === "number" || type === "integer") return 0;+ if (type === "boolean") return false;+ if (type === "array") return [];+ if (type === "object") {+ const props = schema.properties as Record<string, Record<string, unknown>> | undefined;+ if (props && Object.keys(props).length > 0) {+ const result: Record<string, unknown> = {};+ for (const [k, v] of Object.entries(props)) {+ result[k] = defaultForSchema(v);+ }+ return result;+ }+ return {};+ }+ return null;}-function isOptionalType(schema: unknown): boolean {- return getZodType(schema) === "optional";-}+// ─── Section generators ─────────────────────────────────────────────────────-function unwrapOptional(schema: unknown): unknown {- const def = getZodDef(schema);- if (def?.type === "optional") return def.innerType;- return schema;-}+const PREAMBLE = `You are an AI assistant that responds using openui-lang, a declarative UI language. Your ENTIRE response must be valid openui-lang code — no markdown, no explanations, just openui-lang.`;++function syntaxRules(+ rootName: string,+ flags: { supportsExpressions: boolean; bindings: boolean },+): string {+ const lines = [+ "## Syntax Rules",+ "",+ "1. Each statement is on its own line: `identifier = Expression`",+ `2. \`root\` is the entry point — every program must define \`root = ${rootName}(...)\``,+ '3. Expressions are: strings ("..."), numbers, booleans (true/false), null, arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)',+ "4. Use references for readability: define `name = ...` on one line, then use `name` later",+ "5. EVERY variable (except root) MUST be referenced by at least one other variable. Unreferenced variables are silently dropped and will NOT render. Always include defined variables in their parent's children/items array.",+ '6. Arguments are POSITIONAL (order matters, not names). Write `Stack([children], "row", "l")` NOT `Stack([children], direction: "row", gap: "l")` — colon syntax is NOT supported and silently breaks',+ "7. Optional arguments can be omitted from the end",+ ];++ let ruleNum = 8;+ if (flags.bindings) {+ lines.push(+ `${ruleNum++}. Declare mutable state with \`$varName = defaultValue\`. Components marked with \`$binding\` can read/write these. Undeclared $variables are auto-created with null default.`,+ );+ }+ if (flags.supportsExpressions) {+ lines.push(+ `${ruleNum++}. String concatenation: \`"text" + $var + "more"\``,+ `${ruleNum++}. Dot member access: \`query.field\` reads a field; on arrays it extracts that field from every element`,+ `${ruleNum++}. Index access: \`arr[0]\`, \`data[index]\``,+ `${ruleNum++}. Arithmetic operators: +, -, *, /, % (work on numbers; + is string concat when either side is a string)`,+ `${ruleNum++}. Comparison: ==, !=, >, <, >=, <=`,+ `${ruleNum++}. Logical: &&, ||, ! (prefix)`,+ `${ruleNum++}. Ternary: \`condition ? valueIfTrue : valueIfFalse\``,+ `${ruleNum++}. Parentheses for grouping: \`(a + b) * c\``,+ );+ }-/** Strip optional wrapper to reach the core schema. */-function unwrap(schema: unknown): unknown {- return unwrapOptional(schema);+ lines.push("- Strings use double quotes with backslash escaping");++ return lines.join("\n");}-function isArrayType(schema: unknown): boolean {- const s = unwrap(schema);- return getZodType(s) === "array";+function builtinFunctionsSection(): string {+ // Auto-generated from shared builtin registry — single source of truth+ const builtinLines = Object.values(BUILTINS).map((b) => `@${b.signature} — ${b.description}`);+ const lazyLines = Object.values(LAZY_BUILTIN_DEFS).map(+ (b) => `@${b.signature} — ${b.description}`,+ );+ const lines = [...builtinLines, ...lazyLines].join("\n");++ return `## Built-in Functions++Data functions prefixed with \`@\` to distinguish from components. These are the ONLY functions available — do NOT invent new ones.+Use @-prefixed built-in functions (@Count, @Sum, @Avg, @Min, @Max, @Round) on Query results — do NOT hardcode computed values.++${lines}++Builtins compose — output of one is input to the next:+\`@Count(@Filter(data.rows, "field", "==", "val"))\` for KPIs/chart values, \`@Round(@Avg(data.rows.score), 1)\`, \`@Each(data.rows, "item", Comp(item.field))\` for per-item rendering.+Array pluck: \`data.rows.field\` extracts a field from every row → use with @Sum, @Avg, charts, tables.++IMPORTANT @Each rule: The loop variable (e.g. "item") is ONLY available inside the @Each template expression. Always inline the template — do NOT extract it to a separate statement.+CORRECT: \`Col("Actions", @Each(rows, "t", Button("Edit", Action([@Set($id, t.id)]))))\`+WRONG: \`myBtn = Button("Edit", Action([@Set($id, t.id)]))\` then \`Col("Actions", @Each(rows, "t", myBtn))\` — t is undefined in myBtn.`;}-function getArrayInnerType(schema: unknown): unknown | undefined {- const s = unwrap(schema);- const def = getZodDef(s);- if (def?.type === "array") return def.element ?? def.innerType;- return undefined;+function querySection(): string {+ return `## Query — Live Data Fetching++Fetch data from available tools. Returns defaults instantly, swaps in real data when it arrives.++\`\`\`+metrics = Query("tool_name", {arg1: value, arg2: $binding}, {defaultField: 0, defaultData: []}, refreshInterval?)+\`\`\`++- First arg: tool name (string)+- Second arg: arguments object (may reference $bindings — re-fetches automatically on change)+- Third arg: default data (rendered immediately before fetch resolves)+- Fourth arg (optional): refresh interval in seconds (e.g. 30 for auto-refresh every 30s)+- Use dot access on results: metrics.totalEvents, metrics.data.day (array pluck)+- Query results must use regular identifiers: \`metrics = Query(...)\`, NOT \`$metrics = Query(...)\`+- Manual refresh: \`Button("Refresh", Action([@Run(query1), @Run(query2)]), "secondary")\` — re-fetches the listed queries+- Refresh all queries: create Action with @Run for each query`;}-function getEnumValues(schema: unknown): string[] | undefined {- const s = unwrap(schema);- const def = getZodDef(s);- if (def?.type !== "enum") return undefined;- if (Array.isArray(def.values)) return def.values;- if (def.entries && typeof def.entries === "object") return Object.keys(def.entries);- return undefined;+function mutationSection(): string {+ return `## Mutation — Write Operations++Execute state-changing tool calls (create, update, delete). Unlike Query (auto-fetches on render), Mutation fires only on button click via Action.++\`\`\`+result = Mutation("tool_name", {arg1: $binding, arg2: "value"})+\`\`\`++- First arg: tool name (string)+- Second arg: arguments object (evaluated with current $binding values at click time)+- result.status: "idle" | "loading" | "success" | "error"+- result.data: tool response on success+- result.error: error message on failure+- Mutation results use regular identifiers: \`result = Mutation(...)\`, NOT \`$result\`+- Show loading state: \`result.status == "loading" ? TextContent("Saving...") : null\``;}-function getSchemaId(schema: unknown): string | undefined {- try {- const meta = z.globalRegistry.get(schema as z.ZodType);- return meta?.id;- } catch {- return undefined;+function actionSection(flags: { toolCalls: boolean; bindings: boolean }): string {+ const steps = [+ '- @ToAssistant("message") — Send a message to the assistant (for conversational buttons like "Tell me more", "Explain this")',+ '- @OpenUrl("https://...") — Navigate to a URL',+ ];++ if (flags.bindings) {+ steps.push(+ "- @Set($variable, value) — Set a $variable to a specific value",+ '- @Reset($var1, $var2, ...) — Reset $variables to their declared defaults (e.g. @Reset($title, $priority) restores $title="" and $priority="medium")',+ );+ }++ if (flags.toolCalls) {+ steps.unshift(+ "- @Run(queryOrMutationRef) — Execute a Mutation or re-fetch a Query (ref must be a declared Query/Mutation)",+ );+ }++ const examples: string[] = [];+ if (flags.toolCalls) {+ examples.push(`Example — mutation + refresh + reset (PREFERRED pattern):+\`\`\`+$binding = "default"+result = Mutation("tool_name", {field: $binding})+data = Query("tool_name", {}, {rows: []})+onSubmit = Action([@Run(result), @Run(data), @Reset($binding)])+\`\`\``);+ }++ examples.push(`Example — simple nav:+\`\`\`+viewBtn = Button("View", Action([@OpenUrl("https://example.com")]))+\`\`\``);++ const rules = [+ '- Action can be assigned to a variable or inlined: Button("Go", onSubmit) and Button("Go", Action([...])) both work',+ ];+ if (flags.toolCalls) {+ rules.push(+ "- If a @Run(mutation) step fails, remaining steps are skipped (halt on failure)",+ "- @Run(queryRef) re-fetches the query (fire-and-forget, cannot fail)",+ );}++ return `## Action — Button Behavior++Action([@steps...]) wires button clicks to operations. Steps are @-prefixed built-in actions. Steps execute in order.+Buttons without an explicit Action prop automatically send their label to the assistant (equivalent to Action([@ToAssistant(label)])).++Available steps:+${steps.join("\n")}++${examples.join("\n\n")}++${rules.join("\n")}`;}-function getUnionOptions(schema: unknown): unknown[] | undefined {- const def = getZodDef(schema);- if (def?.type === "union" && Array.isArray(def.options)) return def.options;- return undefined;+function interactiveFiltersSection(): string {+ return `## Interactive Filters++To let the user filter data with a dropdown:+1. Declare a $variable with a default: \`$dateRange = "14"\`+2. Create a Select with name, items, and binding: \`Select("dateRange", [SelectItem("7", "Last 7 days"), ...], null, null, $dateRange)\`+3. Wrap in FormControl for a label: \`FormControl("Date Range", Select(...))\`+4. Pass $dateRange in Query args: \`Query("tool", {dateRange: $dateRange}, {defaults})\`+5. When the user changes the Select, $dateRange updates and the Query automatically re-fetches++FILTER WIRING RULE: If a $binding filter is visible in the UI, EVERY relevant Query MUST reference that $binding in its args. Never show a filter dropdown while hardcoding the query args.++Rules for $variables:+- $variables hold simple values (strings or numbers), NOT arrays or objects+- $variables must be bound to a Select/Input component via the value argument (last positional arg) to be interactive+- Queries must use regular identifiers (NOT $variables): \`metrics = Query(...)\` not \`$metrics = Query(...)\`+- **Auto-declare**: You do NOT need to explicitly declare $variables. If you use \`$foo\` without declaring it, the parser auto-creates \`$foo = null\`. You can still declare explicitly to set a default: \`$days = "14"\`++## Forms++Simple form — no $bindings needed. Field values are managed internally by the Form via the name prop:+\`\`\`+contactForm = Form("contact", submitBtn, [nameField, emailField])+nameField = FormControl("Name", Input("name", "Your name", "text", {required: true}))+emailField = FormControl("Email", Input("email", "[email protected]", "email", {required: true, email: true}))+submitBtn = Button("Submit")+\`\`\`++Use $bindings when you need to read field values elsewhere (in Action context, Query args, or conditionals). They are auto-declared:+\`\`\`+$role = "engineer"+contactForm = Form("contact", submitBtn, [nameField, emailField, roleField])+nameField = FormControl("Name", Input("name", "Enter your name", "text", {required: true}, $name))+emailField = FormControl("Email", Input("email", "Enter your email", "email", {required: true, email: true}, $email))+roleField = FormControl("Role", Select("role", [SelectItem("engineer", "Engineer"), SelectItem("designer", "Designer"), SelectItem("pm", "PM")], null, {required: true}, $role))+submitBtn = Button("Submit")+\`\`\`++For form + mutation patterns (create, refresh, reset), see the Action section example above.++IMPORTANT: Always add validation rules to form fields used with Mutations. Use OBJECT syntax: {required: true, email: true, minLength: 8}. The renderer shows error messages automatically and blocks submit when validation fails.`;}-function getObjectShape(schema: unknown): Record<string, unknown> | undefined {- const def = getZodDef(schema);- if (def?.type === "object" && def.shape && typeof def.shape === "object")- return def.shape as Record<string, unknown>;- return undefined;+function editModeSection(): string {+ return `## Edit Mode++The runtime merges by statement name: same name = replace, new name = append.+Output ONLY statements that changed or are new. Everything else is kept automatically.++### Delete+To remove a component, update the parent to exclude it from its children array. Orphaned statements are automatically garbage-collected.+Example — remove chart: \`root = Stack([header, kpiRow, table])\` — chart is no longer in the children list, so it and any statements only it referenced are auto-deleted.++### Patch size guide+- Changing a title or label: 1 statement+- Adding a component: 2-3 statements (the new component + parent update)+- Removing a component: 1 statement (re-declare parent without the removed child)+- Adding a filter + wiring to query: 3-5 statements+- Restructuring into tabs: 5-10 statements++### Rules+- Reuse existing statement names exactly — do not rename+- Do NOT re-emit unchanged statements — the runtime keeps them+- A typical edit patch is 1-10 statements, not 20++- If the existing code already satisfies the request, output only the root statement+- NEVER output the entire program as a patch. Only output what actually changes+- If you are about to output more than 10 statements, reconsider — most edits need fewer`;}-/**- * Resolve the type annotation for a schema field.- * Returns a human-readable type string for the schema.- *- * Examples:- * - z.string() → "string"- * - z.number() → "number"- * - z.boolean() → "boolean"- * - z.enum(["a","b"]) → '"a" | "b"'- * - z.array(TabItemSchema) → "TabItem[]"- * - z.union([Input, TextArea]) → "Input | TextArea"- * - z.array(z.union([A, B])) → "(A | B)[]"- * - ButtonGroupSchema → "ButtonGroup"- * - z.object({src: z.string()}) → "{src: string}" (inline when unregistered)- */-function resolveTypeAnnotation(schema: unknown): string | undefined {- const inner = unwrap(schema);-- const directId = getSchemaId(inner);- if (directId) return directId;-- const unionOpts = getUnionOptions(inner);- if (unionOpts) {- const resolved = unionOpts.map((o) => resolveTypeAnnotation(o));- const names = resolved.filter(Boolean) as string[];- if (names.length > 0) {- if (names.length < unionOpts.length) {- console.warn(- `[prompt] Partially resolved union: ${names.length}/${unionOpts.length} options resolved`,- );- }- return names.join(" | ");- }- }+function streamingRules(rootName: string): string {+ return `## Hoisting & Streaming (CRITICAL)- if (isArrayType(schema)) {- const arrayInner = getArrayInnerType(schema);- if (!arrayInner) return undefined;+openui-lang supports hoisting: a reference can be used BEFORE it is defined. The parser resolves all references after the full input is parsed.- const innerType = resolveTypeAnnotation(arrayInner);- if (innerType) {- const isUnion = getUnionOptions(unwrap(arrayInner)) !== undefined;- return isUnion ? `(${innerType})[]` : `${innerType}[]`;- }+During streaming, the output is re-parsed on every chunk. Undefined references are temporarily unresolved and appear once their definitions stream in. This creates a progressive top-down reveal — structure first, then data fills in.++**Recommended statement order for optimal streaming:**+1. \`root = ${rootName}(...)\` — UI shell appears immediately+2. $variable declarations — state ready for bindings+3. Query statements — defaults resolve immediately so components render with data+4. Component definitions — fill in with data already available+5. Data values — leaf content last++Always write the root = ${rootName}(...) statement first so the UI shell appears immediately, even before child data has streamed in.`;+}++function inlineModeSection(): string {+ return `## Inline Mode++You are in inline mode. You can respond in two ways:++### 1. Code response (when the user wants to CREATE or CHANGE the UI)+Wrap openui-lang code in triple-backtick fences. You can include explanatory text before/after:++Here's your dashboard:++\`\`\`openui-lang+root = RootComp([header, content])+header = SomeHeader("Title")+content = SomeContent("Hello world")+\`\`\`++I created a simple layout with a header.++### 2. Text-only response (when the user asks a QUESTION)+If the user asks "what is this?", "explain the chart", "how does this work", etc. — respond with plain text. Do NOT output any openui-lang code. The existing dashboard stays unchanged.++### Rules+- When the user asks for changes, output ONLY the changed/new statements in a fenced block+- When the user asks a question, respond with text only — NO code. The dashboard stays unchanged.+- The parser extracts code from fences automatically. Text outside fences is shown as chat.`;+}++function toolWorkflowSection(): string {+ return `## Data Workflow++When tools are available, follow this workflow:+1. FIRST: Call the most relevant tool to inspect the real data shape before generating code+2. Use Query() for READ operations (data that should stay live) — NEVER hardcode tool results as literal arrays or objects+3. Use Mutation() for WRITE operations (create, update, delete) — triggered by button clicks via Action([@Run(mutationRef)])+4. Use the real data from step 1 as condensed Query defaults (3-5 rows) so the UI renders immediately+5. Use @-prefixed builtins (@Count, @Filter, @Sort, @Sum) on Query results for KPIs and aggregations — the runtime evaluates these live on every refresh+6. Hardcoded arrays are ONLY for static display data (labels, options) where no tool exists++WRONG — you called a tool and got data back, but you inlined the results:+\`\`\`+openCount = 2+item1 = SomeComp("first item title")+item2 = SomeComp("second item title")+list = Stack([item1, item2])+chart = SomeChart(["A", "B"], [12, 8])+\`\`\`+This is static — it shows stale data and won't update. Creating item1, item2, item3... manually is ALWAYS wrong when a tool exists.++RIGHT — use Query() for live data, Mutation() for writes, @builtins to derive values:+\`\`\`+data = Query("tool_name", {}, {rows: []})+openCount = @Count(@Filter(data.rows, "field", "==", "value"))+list = @Each(data.rows, "item", SomeComp(item.title, item.field))+createResult = Mutation("create_tool", {title: $title})+submitBtn = Button("Create", Action([@Run(createResult), @Run(data), @Reset($title)]))+\`\`\`+Everything derives from the Query — when data refreshes, the entire dashboard updates automatically.`;+}- console.warn(- `[prompt] Could not resolve array element type (inner zod type: "${getZodType(arrayInner) ?? "unknown"}")`,+function importantRules(+ rootName: string,+ flags: { toolCalls: boolean; bindings: boolean },+): string {+ const verifyLines = [+ `1. root = ${rootName}(...) is the FIRST line (for optimal streaming).`,+ "2. Every referenced name is defined. Every defined name (other than root) is reachable from root.",+ ];+ if (flags.toolCalls) {+ verifyLines.push("3. Every Query result is referenced by at least one component.");+ }+ if (flags.bindings) {+ verifyLines.push(+ `${flags.toolCalls ? "4" : "3"}. Every $binding appears in at least one component or expression.`,);- return undefined;}- const zodType = getZodType(inner);- if (zodType === "string") return "string";- if (zodType === "number") return "number";- if (zodType === "boolean") return "boolean";+ return `## Important Rules+- When asked about data, generate realistic/plausible data+- Choose components that best represent the content (tables for comparisons, charts for trends, forms for input, etc.)- const enumVals = getEnumValues(inner);- if (enumVals) return enumVals.map((v) => `"${v}"`).join(" | ");+## Final Verification+Before finishing, walk your output and verify:+${verifyLines.join("\n")}`;+}- if (zodType === "literal") {- const vals = getZodDef(inner)?.values;- if (Array.isArray(vals) && vals.length === 1) {- const v = vals[0];- return typeof v === "string" ? `"${v}"` : String(v);+// ─── Tool rendering ─────────────────────────────────────────────────────────++function renderToolSignature(tool: ToolSpec): string {+ let args = "";+ if (tool.inputSchema) {+ const props = (tool.inputSchema as any).properties as+ | Record<string, Record<string, unknown>>+ | undefined;+ const required = ((tool.inputSchema as any).required as string[]) ?? [];+ if (props && Object.keys(props).length > 0) {+ args = Object.entries(props)+ .map(([k, v]) => {+ const opt = required.includes(k) ? "" : "?";+ return `${k}${opt}: ${jsonSchemaTypeStr(v)}`;+ })+ .join(", ");}}- const shape = getObjectShape(inner);- if (shape) {- const fields = Object.entries(shape).map(([name, fieldSchema]) => {- const opt = isOptionalType(fieldSchema) ? "?" : "";- const fieldType = resolveTypeAnnotation(fieldSchema as z.ZodType);- return fieldType ? `${name}${opt}: ${fieldType}` : `${name}${opt}`;- });- return `{${fields.join(", ")}}`;+ let returnType = "";+ if (tool.outputSchema) {+ returnType = ` → ${jsonSchemaTypeStr(tool.outputSchema as Record<string, unknown>)}`;}- if (zodType === "lazy") {- console.warn(- `[prompt] z.lazy() schemas are not resolved — remove z.lazy() wrapper from the schema`,- );- } else if (zodType) {- console.warn(`[prompt] Unresolved schema type: "${zodType}"`);+ let line = `- ${tool.name}(${args})${returnType}`;+ if (tool.description) {+ line += `\n ${tool.description}`;}-- return undefined;+ return line;}-// ─── Field analysis ───+function renderToolsSection(tools: (string | ToolSpec)[]): string {+ const lines: string[] = [];-interface FieldInfo {- name: string;- isOptional: boolean;- isArray: boolean;- typeAnnotation?: string;-}+ const stringTools: string[] = [];+ const specTools: ToolSpec[] = [];-function analyzeFields(shape: Record<string, z.ZodType>): FieldInfo[] {- return Object.entries(shape).map(([name, schema]) => ({- name,- isOptional: isOptionalType(schema),- isArray: isArrayType(schema),- typeAnnotation: resolveTypeAnnotation(schema),- }));-}+ for (const tool of tools) {+ if (typeof tool === "string") {+ stringTools.push(tool);+ } else {+ specTools.push(tool);+ }+ }-// ─── Signature generation ───+ lines.push("## Available Tools");+ lines.push("");+ lines.push(+ "Use these with Query() for read operations or Mutation() for write operations. The LLM decides which is appropriate based on the tool's purpose.",+ );+ lines.push("");+ for (const t of stringTools) {+ lines.push(`- ${t}`);+ }+ for (const t of specTools) {+ lines.push(renderToolSignature(t));+ }-function buildSignature(componentName: string, fields: FieldInfo[]): string {- const params = fields.map((f) => {- if (f.typeAnnotation) {- return f.isOptional ? `${f.name}?: ${f.typeAnnotation}` : `${f.name}: ${f.typeAnnotation}`;- }- if (f.isArray) {- return f.isOptional ? `[${f.name}]?` : `[${f.name}]`;+ // Default values hint for ToolSpec tools with outputSchema+ const toolsWithOutput = specTools.filter((t) => t.outputSchema);+ if (toolsWithOutput.length > 0) {+ lines.push("");+ lines.push("### Default values for Query results");+ lines.push("");+ lines.push("Use these shapes as minimal Query defaults:");+ for (const t of toolsWithOutput) {+ const defaults = defaultForSchema(t.outputSchema as Record<string, unknown>);+ lines.push(`- ${t.name}: \`${JSON.stringify(defaults)}\``);}- return f.isOptional ? `${f.name}?` : f.name;- });- return `${componentName}(${params.join(", ")})`;-}--function buildComponentLine(componentName: string, def: DefinedComponent): string {- const fields = analyzeFields(def.props.shape);- const sig = buildSignature(componentName, fields);- if (def.description) {- return `${sig} — ${def.description}`;}- return sig;-}-// ─── Prompt assembly ───+ lines.push("");+ lines.push(+ "CRITICAL: Use ONLY the tools listed above in Query() and Mutation() calls. Do NOT invent or guess tool names. If the user asks for functionality that doesn't match any available tool, use realistic mock data instead of fabricating a tool call.",+ );++ return lines.join("\n");+}-function generateComponentSignatures(library: Library): string {- const lines: string[] = [+// ─── Component signatures ───────────────────────────────────────────────────++function generateComponentSignatures(spec: PromptSpec): string {+ const toolCalls = spec.toolCalls ?? !!spec.tools?.length;+ const bindings = spec.bindings ?? toolCalls;+ const allSteps = [+ toolCalls ? "@Run" : "",+ "@ToAssistant",+ "@OpenUrl",+ bindings ? "@Set" : "",+ bindings ? "@Reset" : "",+ ].filter(Boolean);+ const actionHint = `Props typed \`ActionExpression\` accept an Action([@steps...]) expression. See the Action section for available steps (${allSteps.join(", ")}).`;++ const lines = ["## Component Signatures","","Arguments marked with ? are optional. Sub-components can be inline or referenced; prefer references for better streaming.",- "The `action` prop type accepts: ContinueConversation (sends message to LLM), OpenUrl (navigates to URL), or Custom (app-defined).",+ actionHint,+ "Props marked `$binding<type>` accept a `$variable` reference for two-way binding.",];- if (library.componentGroups?.length) {- const groupedComponents = new Set<string>();-- for (const group of library.componentGroups) {- lines.push("");- lines.push(`### ${group.name}`);+ if (spec.componentGroups?.length) {+ const grouped = new Set<string>();+ for (const group of spec.componentGroups) {+ lines.push("", `### ${group.name}`);for (const name of group.components) {- if (groupedComponents.has(name)) {- console.warn(- `[prompt] Component "${name}" appears in multiple groups; keeping the first occurrence only.`,- );- continue;- }- const def = library.components[name];- if (!def) {- console.warn(- `[prompt] Component "${name}" listed in group "${group.name}" was not found in the library and will be omitted from the prompt.`,- );- continue;- }- groupedComponents.add(name);- lines.push(buildComponentLine(name, def));+ if (grouped.has(name)) continue;+ const comp = spec.components[name];+ if (!comp) continue;+ grouped.add(name);+ lines.push(comp.description ? `${comp.signature} — ${comp.description}` : comp.signature);}if (group.notes?.length) {- for (const note of group.notes) {- lines.push(note);- }+ for (const note of group.notes) lines.push(note);}}-- const ungrouped = Object.keys(library.components).filter(- (name) => !groupedComponents.has(name),- );+ const ungrouped = Object.keys(spec.components).filter((n) => !grouped.has(n));if (ungrouped.length) {- lines.push("");- lines.push("### Ungrouped");+ lines.push("", "### Other");for (const name of ungrouped) {- const def = library.components[name];- lines.push(buildComponentLine(name, def));+ const comp = spec.components[name];+ lines.push(comp.description ? `${comp.signature} — ${comp.description}` : comp.signature);}}} else {lines.push("");- for (const [name, def] of Object.entries(library.components)) {- lines.push(buildComponentLine(name, def));+ for (const [, comp] of Object.entries(spec.components)) {+ lines.push(comp.description ? `${comp.signature} — ${comp.description}` : comp.signature);}}-return lines.join("\n");}-export function generatePrompt(library: Library, options?: PromptOptions): string {- const rootName = library.root ?? "Root";+// ─── Prompt assembly ────────────────────────────────────────────────────────++export function generatePrompt(spec: PromptSpec): string {+ const rootName = spec.root ?? "Root";+ const hasTools = !!spec.tools?.length;++ // Resolve prompt flags — defaults preserve backward compat+ const toolCalls = spec.toolCalls ?? hasTools;+ const bindings = spec.bindings ?? toolCalls;+ const supportsExpressions = toolCalls || bindings;+const parts: string[] = [];- parts.push(options?.preamble ?? PREAMBLE);+ parts.push(spec.preamble ?? PREAMBLE);parts.push("");- parts.push(syntaxRules(rootName));+ parts.push(syntaxRules(rootName, { supportsExpressions, bindings }));parts.push("");- parts.push(generateComponentSignatures(library));+ parts.push(generateComponentSignatures(spec));++ // Built-in functions — always included+ parts.push("");+ parts.push(builtinFunctionsSection());++ // Query + Mutation sections+ if (toolCalls) {+ parts.push("");+ parts.push(querySection());+ parts.push("");+ parts.push(mutationSection());+ }++ // Action section — always included (ToAssistant, OpenUrl always; @Run/@Set/@Reset gated)+ parts.push("");+ parts.push(actionSection({ toolCalls, bindings }));++ // Interactive filters (needs both toolCalls and bindings)+ if (toolCalls && bindings) {+ parts.push("");+ parts.push(interactiveFiltersSection());+ }++ // Tool workflow+ if (toolCalls) {+ parts.push("");+ parts.push(toolWorkflowSection());+ }++ // Tools list (only if actual tools provided)+ if (spec.tools?.length) {+ parts.push("");+ parts.push(renderToolsSection(spec.tools));+ }+parts.push("");parts.push(streamingRules(rootName));- const examples = options?.examples;- if (examples?.length) {+ // Append both examples and toolExamples when both are present+ const allExamples = [...(spec.examples ?? []), ...(spec.toolExamples ?? [])];+ if (allExamples.length) {parts.push("");parts.push("## Examples");parts.push("");- for (const ex of examples) {+ for (const ex of allExamples) {parts.push(ex);parts.push("");}}- parts.push(importantRules(rootName));+ // Edit mode instructions+ if (spec.editMode) {+ parts.push("");+ parts.push(editModeSection());+ }++ // Inline mode instructions+ if (spec.inlineMode) {+ parts.push("");+ parts.push(inlineModeSection());+ }++ parts.push(importantRules(rootName, { toolCalls, bindings }));- if (options?.additionalRules?.length) {+ if (spec.additionalRules?.length) {parts.push("");- for (const rule of options.additionalRules) {+ for (const rule of spec.additionalRules) {parts.push(`- ${rule}`);}}diff --git a/packages/lang-core/src/parser/statements.ts b/packages/lang-core/src/parser/statements.tsnew file mode 100644index 000000000..9cc3d6b32--- /dev/null+++ b/packages/lang-core/src/parser/statements.ts@@ -0,0 +1,137 @@+// ─────────────────────────────────────────────────────────────────────────────+// Statement splitter for openui-lang+// ─────────────────────────────────────────────────────────────────────────────++import { T, type Token } from "./tokens";++export interface RawStmt {+ id: string;+ /** Token type of the LHS identifier — used to classify statement kind */+ idTokenType: T;+ tokens: Token[];+}++/**+ * Auto-close unclosed strings and brackets so that partial/streaming input+ * can be parsed without syntax errors.+ */+export function autoClose(input: string): { text: string; wasIncomplete: boolean } {+ const stack: string[] = [];+ let inStr: false | '"' | "'" = false;+ let esc = false;++ for (let i = 0; i < input.length; i++) {+ const c = input[i];+ if (esc) {+ esc = false;+ continue;+ }+ if (c === "\\" && inStr) {+ esc = true;+ continue;+ }+ if (inStr) {+ if (c === inStr) inStr = false;+ continue;+ }+ if (c === '"' || c === "'") {+ inStr = c;+ continue;+ }+ if (c === "(" || c === "[" || c === "{") stack.push(c);+ else if (c === ")" && stack[stack.length - 1] === "(") stack.pop();+ else if (c === "]" && stack[stack.length - 1] === "[") stack.pop();+ else if (c === "}" && stack[stack.length - 1] === "{") stack.pop();+ }++ const wasIncomplete = !!inStr || stack.length > 0;+ if (!wasIncomplete) return { text: input, wasIncomplete: false };++ let out = input;+ if (inStr) {+ if (esc) out += "\\";+ out += inStr; // close with matching quote+ }+ for (let j = stack.length - 1; j >= 0; j--)+ out += stack[j] === "(" ? ")" : stack[j] === "[" ? "]" : "}";++ return { text: out, wasIncomplete: true };+}++/**+ * Splits the flat token stream into individual statements.+ *+ * Each statement has the form `identifier = expression`. Statements are+ * separated by newlines at depth 0 (newlines inside brackets are ignored).+ *+ * Accepts `Ident`, `Type`, and `StateVar` as statement identifiers.+ * For StateVar, the id is the full token value including $ (e.g., "$count").+ *+ * Invalid lines (no `=`, or no identifier) are silently skipped.+ */+export function split(tokens: Token[]): RawStmt[] {+ const stmts: RawStmt[] = [];+ let pos = 0;++ while (pos < tokens.length) {+ // Skip blank lines+ while (pos < tokens.length && tokens[pos].t === T.Newline) pos++;+ if (pos >= tokens.length || tokens[pos].t === T.EOF) break;++ // Expect: Ident|Type|StateVar = expression+ const tok = tokens[pos];+ if (tok.t !== T.Ident && tok.t !== T.Type && tok.t !== T.StateVar) {+ while (pos < tokens.length && tokens[pos].t !== T.Newline && tokens[pos].t !== T.EOF) pos++;+ continue;+ }+ const id = tok.v as string;+ const idTokenType = tok.t;+ pos++;++ // Must be followed by `=`+ if (pos >= tokens.length || tokens[pos].t !== T.Equals) {+ while (pos < tokens.length && tokens[pos].t !== T.Newline && tokens[pos].t !== T.EOF) pos++;+ continue;+ }+ pos++;++ // Collect expression tokens until a depth-0 newline or EOF.+ // Track both bracket depth and ternary depth so that multiline+ // ternary expressions (condition on one line, ? ... : on the next)+ // are not incorrectly split into separate statements.+ const expr: Token[] = [];+ let depth = 0;+ let ternaryDepth = 0;+ while (pos < tokens.length && tokens[pos].t !== T.EOF) {+ const tt = tokens[pos].t;+ if (tt === T.Newline && depth <= 0 && ternaryDepth <= 0) {+ // Before breaking, look ahead past whitespace/newlines to see if+ // the next meaningful token is `?` or `:` — if so, the ternary+ // continues on the next line and we should NOT split here.+ let peek = pos + 1;+ while (peek < tokens.length && tokens[peek].t === T.Newline) peek++;+ const nextT = peek < tokens.length ? tokens[peek].t : T.EOF;+ if (nextT === T.Question || (nextT === T.Colon && ternaryDepth > 0)) {+ // Ternary continuation — skip the newline and keep collecting+ pos++;+ continue;+ }+ break; // statement boundary+ }+ if (tt === T.Newline) {+ pos++;+ continue;+ } // newline inside bracket/ternary — skip+ if (tt === T.LParen || tt === T.LBrack || tt === T.LBrace) depth++;+ else if ((tt === T.RParen || tt === T.RBrack || tt === T.RBrace) && depth > 0) depth--;+ // Track ternary ? and : at bracket depth 0 (colons inside {} are object key separators)+ else if (tt === T.Question && depth === 0) ternaryDepth++;+ else if (tt === T.Colon && depth === 0 && ternaryDepth > 0) ternaryDepth--;+ expr.push(tokens[pos++]);+ }++ if (expr.length) stmts.push({ id, idTokenType, tokens: expr });+ }++ return stmts;+}diff --git a/packages/lang-core/src/parser/tokens.ts b/packages/lang-core/src/parser/tokens.tsnew file mode 100644index 000000000..4202a955b--- /dev/null+++ b/packages/lang-core/src/parser/tokens.ts@@ -0,0 +1,52 @@+// ─────────────────────────────────────────────────────────────────────────────+// Token types for openui-lang+// ─────────────────────────────────────────────────────────────────────────────++/**+ * Token type discriminant. Uses `const enum` for zero-cost at runtime+ * (TypeScript inlines the numeric values).+ */+export const enum T {+ Newline = 0,+ LParen = 1, // (+ RParen = 2, // )+ LBrack = 3, // [+ RBrack = 4, // ]+ LBrace = 5, // {+ RBrace = 6, // }+ Comma = 7, // ,+ Colon = 8, // :+ Equals = 9, // =+ True = 10,+ False = 11,+ Null = 12,+ EOF = 13,+ Str = 14, // carries string value+ Num = 15, // carries numeric value+ Ident = 16, // lowercase identifier — becomes a reference+ Type = 17, // PascalCase identifier — becomes a component name or reference+ // Reactive & expression tokens+ StateVar = 18, // $identifier — reactive state reference+ Dot = 19, // .+ Plus = 20, // ++ Minus = 21, // -+ Star = 22, // *+ Slash = 23, // /+ Percent = 24, // %+ EqEq = 25, // ==+ NotEq = 26, // !=+ Greater = 27, // >+ Less = 28, // <+ GreaterEq = 29, // >=+ LessEq = 30, // <=+ And = 31, // &&+ Or = 32, // ||+ Not = 33, // !+ Question = 34, // ?+ BuiltinCall = 35, // @identifier — builtin function call+}++export type Token = {+ t: T;+ v?: string | number;+};diff --git a/packages/lang-core/src/parser/types.ts b/packages/lang-core/src/parser/types.tsindex 9c20c8a45..236b47e24 100644--- a/packages/lang-core/src/parser/types.ts+++ b/packages/lang-core/src/parser/types.ts@@ -1,3 +1,31 @@+import type { ASTNode } from "./ast";++/**+ * The JSON Schema document produced by `library.toJSONSchema()`.+ * All component schemas live in `$defs`, keyed by component name.+ */+export interface LibraryJSONSchema {+ $defs?: Record<+ string,+ {+ properties?: Record<string, unknown>;+ required?: string[];+ }+ >;+}++export interface ParamDef {+ /** Parameter name, e.g. "title", "columns". */+ name: string;+ /** Whether the parameter is required by the component. */+ required: boolean;+ /** Default value from JSON Schema — used when the required field is missing/null. */+ defaultValue?: unknown;+}++/** Internal parameter map for positional-arg to named-prop mapping. */+export type ParamMap = Map<string, { params: ParamDef[] }>;+/*** A fully resolved component node from the parser.*@@ -7,40 +35,51 @@*/export interface ElementNode {type: "element";+ /** Source variable name (e.g. "header" from `header = TextContent(...)`). Undefined for inline components. */+ statementId?: string;/** Component name as defined in the library (e.g. "Table", "BarChart"). */typeName: string;- /** Named props produced by positional-to-named mapping in the Rust parser. */+ /** Named props produced by positional-to-named mapping in the parser. */props: Record<string, unknown>;/*** True when the parser hasn't received all tokens for this node yet* (streaming in progress).*/partial: boolean;+ /**+ * False when all props are static literals — evaluation can be skipped.+ * Undefined is treated as true (dynamic) for backward compatibility.+ */+ hasDynamicProps?: boolean;+}++export function isElementNode(value: unknown): value is ElementNode {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;+ const node = value as Record<string, unknown>;+ return (+ node.type === "element" &&+ typeof node.typeName === "string" &&+ typeof node.props === "object" &&+ node.props !== null &&+ typeof node.partial === "boolean"+ );}/*** Validation error codes for schema-related issues.- *- * - `missing-required` — a required prop was absent and has no default value- * - `null-required` — a required prop was explicitly null with no default- * - `unknown-component` — the component name is not in the library schema- * - `excess-args` — more positional args were passed than the schema defines*/export type ValidationErrorCode =| "missing-required"| "null-required"| "unknown-component"- | "excess-args";+ | "inline-reserved";/**- * Structured error from the parser.- *- * Currently only `type: "validation"` exists; future versions may add- * `type: "parser"` for diagnostics like incomplete input.+ * A prop validation error. Components with missing required props are+ * dropped from the output tree and errors are recorded here.*/-export type OpenUIError = {- type: "validation";- /** Which validation rule produced this error. */+export interface ValidationError {+ /** Machine-readable error code. */code: ValidationErrorCode;/** Component type name, e.g. "Header", "BarChart". */component: string;@@ -48,32 +87,135 @@ export type OpenUIError = {path: string;/** Human-readable error message. */message: string;-};+ /** Statement name that triggered the error (e.g. "header", "chart"). */+ statementId?: string;+}/**- * Built-in action types for interactive components.+ * Error sources across the openui-lang pipeline.+ */+export type OpenUIErrorSource = "parser" | "runtime" | "query" | "mutation";++/**+ * Machine-readable error codes for the openui-lang pipeline.+ *+ * - Parser: "unknown-component", "missing-required", "null-required", "inline-reserved",+ * "parse-exception", "parse-failed"+ * - Runtime: "runtime-error" (prop evaluation), "render-error" (React render)+ * - Query/Mutation: "tool-not-found", "tool-error", "mcp-error"+ */+export type OpenUIErrorCode =+ | ValidationErrorCode+ | "runtime-error"+ | "render-error"+ | "parse-exception"+ | "parse-failed"+ | "tool-not-found"+ | "tool-error"+ | "mcp-error";++/**+ * Structured, LLM-friendly error from the openui-lang pipeline.+ *+ * Designed for an automated correction loop: send these to the LLM so it can+ * generate patches. Only includes errors that are fixable by changing the+ * openui-lang code — transient streaming errors, network failures, and tool+ * execution errors are excluded.+ */+export interface OpenUIError {+ /** Where the error originated. */+ source: OpenUIErrorSource;+ /** Machine-readable error code. */+ code: OpenUIErrorCode;+ /** Human/LLM-readable description of what went wrong. */+ message: string;+ /** Statement name (e.g. "header", "metrics") — tells the LLM which statement to patch. */+ statementId?: string;+ /** Component type name (e.g. "BarChart", "Query"). */+ component?: string;+ /** Prop path (e.g. "/title"). */+ path?: string;+ /** Tool name for query/mutation errors (e.g. "get_users", "create_item"). */+ toolName?: string;+ /** Actionable fix context for the LLM (e.g. available components, correct signature). */+ hint?: string;+}++/**+ * Built-in action types for host app events.*/export enum BuiltinActionType {ContinueConversation = "continue_conversation",OpenUrl = "open_url",}+/**+ * A single step in an ActionPlan.+ * Step type values match ACTION_STEPS in builtins.ts (single source of truth).+ */+export type ActionStep =+ | { type: "run"; statementId: string; refType: "query" | "mutation" }+ | { type: "continue_conversation"; message: string; context?: string }+ | { type: "open_url"; url: string }+ | { type: "set"; target: string; valueAST: ASTNode }+ | { type: "reset"; targets: string[] };++/**+ * An ordered sequence of steps to execute when a button is clicked.+ * Produced by evaluating an Action() expression at runtime.+ */+export interface ActionPlan {+ steps: ActionStep[];+}+/*** Structured action event fired by interactive components.*/export interface ActionEvent {/** Action type. See `BuiltinActionType` for built-in types. */- type: string;+ type: BuiltinActionType | (string & {});/** Action-specific params (e.g. { url } for OpenUrl, custom params for Custom). */- params: Record<string, any>;+ params: Record<string, unknown>;/** Human-readable label for the action (displayed as user message in chat). */humanFriendlyMessage: string;/** Raw form state at the time of the action — all field values. */- formState?: Record<string, any>;+ formState?: Record<string, unknown>;/** The form name that triggered this action, if any. */formName?: string;}+/**+ * Extracted info about a Query() call from the parsed program.+ */+export interface QueryStatementInfo {+ /** Statement name that holds this query (e.g. "metrics"). */+ statementId: string;+ /** First arg AST — the tool name (should evaluate to a string). */+ toolAST: ASTNode | null;+ /** Second arg AST — the arguments object (may contain $var refs). */+ argsAST: ASTNode | null;+ /** Third arg AST — default data returned before fetch resolves. */+ defaultsAST: ASTNode | null;+ /** Fourth arg AST — refresh interval in seconds. */+ refreshAST: ASTNode | null;+ /** Pre-computed $variable deps from argsAST (extracted at parse time). */+ deps?: string[];+ /** False while the Query() call is still being streamed. */+ complete: boolean;+}++/**+ * Extracted info about a Mutation() call from the parsed program.+ */+export interface MutationStatementInfo {+ /** Statement name that holds this mutation (e.g. "createResult"). */+ statementId: string;+ /** First arg AST — the tool name (should evaluate to a string). */+ toolAST: ASTNode | null;+ /** Second arg AST — the arguments object (may contain $var refs). */+ argsAST: ASTNode | null;+}+/*** The output of a single `parser.parse(text)` call.*@@ -92,9 +234,15 @@ export interface ParseResult {/** Total number of `identifier = Expression` statements parsed. */statementCount: number;/**- * Structured errors from the parser. Components with missing required- * props are redacted (dropped as null) and listed here.+ * Prop validation errors. Components with missing required props are+ * redacted (dropped as null) and listed here.*/- errors: OpenUIError[];+ errors: ValidationError[];};+ /** $variable declarations — maps "$varName" to its materialized default value. */+ stateDeclarations: Record<string, unknown>;+ /** Extracted Query() calls with their positional args as AST nodes. */+ queryStatements: QueryStatementInfo[];+ /** Extracted Mutation() calls with their positional args as AST nodes. */+ mutationStatements: MutationStatementInfo[];}diff --git a/packages/lang-core/src/reactive.ts b/packages/lang-core/src/reactive.tsnew file mode 100644index 000000000..caf77e2f1--- /dev/null+++ b/packages/lang-core/src/reactive.ts@@ -0,0 +1,17 @@+// ─────────────────────────────────────────────────────────────────────────────+// Reactive schema marker — shared between lang-core (introspection) and+// framework adapters (runtime binding).+// ─────────────────────────────────────────────────────────────────────────────++/** WeakSet tracks reactive schemas without mutating the schema objects. */+const reactiveSchemas = new WeakSet<object>();++/** Mark a schema as reactive. Called by framework adapters' reactive() function. */+export function markReactive(schema: object): void {+ reactiveSchemas.add(schema);+}++/** Check if a schema was marked reactive. Used by Zod introspection for $binding<> prefix. */+export function isReactiveSchema(schema: unknown): boolean {+ return typeof schema === "object" && schema !== null && reactiveSchemas.has(schema as object);+}diff --git a/packages/lang-core/src/runtime/evaluate-prop.ts b/packages/lang-core/src/runtime/evaluate-prop.tsnew file mode 100644index 000000000..d1736853e--- /dev/null+++ b/packages/lang-core/src/runtime/evaluate-prop.ts@@ -0,0 +1,108 @@+/**+ * Shared prop value evaluation logic.+ *+ * Both evaluator.ts (inline path) and evaluate-tree.ts (React path) need+ * identical prop evaluation — AST resolution, ReactiveAssign handling,+ * ElementNode recursion, ActionPlan preservation. The only difference is+ * how they recurse into ElementNodes. This module extracts the shared core+ * and takes recursion callbacks so each caller can supply its own strategy.+ *+ * Also fixes the nested reactive drop bug: reactiveSchema is now correctly+ * passed through plain object recursion.+ */++import { isASTNode } from "../parser/ast";+import type { ElementNode } from "../parser/types";+import { isElementNode } from "../parser/types";+import { isReactiveSchema } from "../reactive";+import type { EvaluationContext, SchemaContext } from "./evaluator";+import { evaluate, isReactiveAssign } from "./evaluator";++export interface PropEvalCallbacks {+ /** How to recurse into an ElementNode (evaluator vs evaluate-tree differ here). */+ recurseElement: (el: ElementNode) => ElementNode;+ /** How to self-recurse for a prop value. */+ recurse: (value: unknown, reactiveSchema?: unknown) => unknown;+}++/**+ * Evaluate a single prop value with schema awareness. Handles AST nodes,+ * ReactiveAssign markers, nested ElementNodes, arrays, and ActionPlans.+ */+export function evaluatePropCore(+ value: unknown,+ context: EvaluationContext,+ schemaCtx: SchemaContext,+ reactiveSchema: unknown | undefined,+ callbacks: PropEvalCallbacks,+): unknown {+ if (value == null) return value;+ if (typeof value !== "object") return value;++ // AST node — evaluate with schema context+ if (isASTNode(value)) {+ // StateRef on reactive prop → ReactiveAssign marker+ if (value.k === "StateRef" && reactiveSchema && isReactiveSchema(reactiveSchema)) {+ return {+ __reactive: "assign" as const,+ target: value.n,+ expr: { k: "StateRef" as const, n: "$value" },+ };+ }+ const result = evaluate(value, context, schemaCtx);+ // ElementNode result (from ternary/Comp) → recurse into its props+ if (isElementNode(result)) {+ return callbacks.recurseElement(result as ElementNode);+ }+ // Array result (from Each) → recurse into any ElementNodes+ if (Array.isArray(result)) {+ return result.map((item) =>+ isElementNode(item) ? callbacks.recurseElement(item as ElementNode) : item,+ );+ }+ // Strip ReactiveAssign from non-reactive props+ if (isReactiveAssign(result) && !(reactiveSchema && isReactiveSchema(reactiveSchema))) {+ return context.getState(result.target) ?? null;+ }+ return result;+ }++ // String on reactive schema → pass through (component's useStateField resolves it)+ if (typeof value === "string" && reactiveSchema && isReactiveSchema(reactiveSchema)) {+ return value;+ }++ // Array — recurse+ if (Array.isArray(value)) {+ return value.map((v) => callbacks.recurse(v, reactiveSchema));+ }++ // ElementNode — recurse with schema+ if (isElementNode(value)) {+ return callbacks.recurseElement(value as ElementNode);+ }++ // ActionPlan / ActionStep — preserve as-is (deferred click-time evaluation)+ const obj = value as Record<string, unknown>;+ if ("steps" in obj && Array.isArray(obj.steps)) return value;+ if ("type" in obj && "valueAST" in obj) return value;++ // Plain data object — recurse if contains nested objects+ // NOTE: reactiveSchema is passed through — fixes nested reactive drop bug+ let needsEval = false;+ for (const val of Object.values(obj)) {+ if (typeof val === "object" && val !== null) {+ needsEval = true;+ break;+ }+ }+ if (needsEval) {+ const result: Record<string, unknown> = {};+ for (const [k, v] of Object.entries(obj)) {+ result[k] = callbacks.recurse(v, reactiveSchema);+ }+ return result;+ }++ return value;+}diff --git a/packages/lang-core/src/runtime/evaluate-tree.ts b/packages/lang-core/src/runtime/evaluate-tree.tsnew file mode 100644index 000000000..ded4de75d--- /dev/null+++ b/packages/lang-core/src/runtime/evaluate-tree.ts@@ -0,0 +1,77 @@+/**+ * Evaluate-tree: entry point for evaluating ElementNode prop trees.+ *+ * Delegates to the evaluator's schema-aware evaluation when schema context+ * is available. This ensures reactive schemas, ActionPlan preservation,+ * Each loop variable substitution, and ternary resolution all happen in+ * a single unified pass.+ */++import type { Library } from "../library";+import type { ElementNode, OpenUIError } from "../parser/types";+import { evaluatePropCore } from "./evaluate-prop";+import type { EvaluationContext, SchemaContext } from "./evaluator";+import type { Store } from "./store";++/** Context passed through the evaluation chain — no module-level state. */+export interface EvalContext {+ /** AST evaluation context (getState, resolveRef) */+ ctx: EvaluationContext;+ /** Component library for reactive schema lookup */+ library: Library;+ /** Reactive binding store (null in v1 mode) */+ store: Store | null;+ /** Runtime errors collected during prop evaluation (optional — populated by evaluateElementProps). */+ errors?: OpenUIError[];+}++/**+ * Evaluate all AST nodes in an ElementNode tree's props.+ * Returns a new ElementNode with all props resolved to concrete values.+ *+ * Uses the unified evaluator with schema context for reactive-aware evaluation.+ */+export function evaluateElementProps(el: ElementNode, evalCtx: EvalContext): ElementNode {+ if (el.hasDynamicProps === false) return el;++ const schemaCtx: SchemaContext = { library: evalCtx.library };+ const def = evalCtx.library.components[el.typeName];+ const evaluated: Record<string, unknown> = {};++ for (const [key, value] of Object.entries(el.props)) {+ const propSchema = def?.props?.shape?.[key];+ try {+ evaluated[key] = evaluatePropValue(value, evalCtx, schemaCtx, propSchema);+ } catch (e) {+ // Use raw value as fallback for this prop, collect structured error+ evaluated[key] = value;+ const msg = e instanceof Error ? e.message : String(e);+ evalCtx.errors?.push({+ source: "runtime",+ code: "runtime-error",+ component: el.typeName,+ statementId: el.statementId,+ message: `Evaluating prop "${key}" on ${el.typeName} failed: ${msg}`,+ hint: `Check the expression used for prop "${key}"`,+ });+ }+ }++ return { ...el, props: evaluated };+}++/**+ * Evaluate a single prop value with schema awareness.+ * Delegates to shared evaluatePropCore with evaluate-tree-specific recursion callbacks.+ */+function evaluatePropValue(+ value: unknown,+ evalCtx: EvalContext,+ schemaCtx: SchemaContext,+ reactiveSchema?: unknown,+): unknown {+ return evaluatePropCore(value, evalCtx.ctx, schemaCtx, reactiveSchema, {+ recurseElement: (el) => evaluateElementProps(el, evalCtx),+ recurse: (v, rs) => evaluatePropValue(v, evalCtx, schemaCtx, rs),+ });+}diff --git a/packages/lang-core/src/runtime/evaluator.ts b/packages/lang-core/src/runtime/evaluator.tsnew file mode 100644index 000000000..baf6252e0--- /dev/null+++ b/packages/lang-core/src/runtime/evaluator.ts@@ -0,0 +1,483 @@+// ─────────────────────────────────────────────────────────────────────────────+// AST evaluator — resolves AST nodes to runtime values.+// Framework-agnostic. No React imports.+// ─────────────────────────────────────────────────────────────────────────────++import type { ASTNode } from "../parser/ast";+import { isASTNode } from "../parser/ast";+import { ACTION_NAMES, ACTION_STEPS, BUILTINS, LAZY_BUILTINS, toNumber } from "../parser/builtins";+import type { ActionPlan, ActionStep, ElementNode } from "../parser/types";+import { isElementNode } from "../parser/types";+import { isReactiveSchema } from "../reactive";+import { evaluatePropCore } from "./evaluate-prop";++/** Optional schema context for reactive-aware evaluation. */+export interface SchemaContext {+ /** Component library — used to look up reactive schemas per prop. */+ library: { components: Record<string, { props: { shape?: Record<string, unknown> } }> };+}++export interface EvaluationContext {+ /** Read $variable from the store */+ getState(name: string): unknown;+ /** Resolve a reference to another declaration's evaluated value */+ resolveRef(name: string): unknown;+ /** Extra scope for $value injection during reactive prop evaluation */+ extraScope?: Record<string, unknown>;+}++export interface ReactiveAssign {+ __reactive: "assign";+ target: string;+ expr: ASTNode;+}++export function isReactiveAssign(value: unknown): value is ReactiveAssign {+ return typeof value === "object" && value !== null && (value as any).__reactive === "assign";+}++/**+ * Evaluate an AST node to a runtime value.+ */+export function evaluate(+ node: ASTNode,+ context: EvaluationContext,+ schemaCtx?: SchemaContext,+): unknown {+ switch (node.k) {+ // ── Literals ──────────────────────────────────────────────────────────+ case "Str":+ return node.v;+ case "Num":+ return node.v;+ case "Bool":+ return node.v;+ case "Null":+ return null;+ case "Ph":+ return null;++ // ── State references ──────────────────────────────────────────────────+ case "StateRef":+ return context.extraScope?.[node.n] ?? context.getState(node.n);++ // ── References ────────────────────────────────────────────────────────+ case "Ref":+ case "RuntimeRef":+ return context.resolveRef(node.n);++ // ── Collections ───────────────────────────────────────────────────────+ case "Arr":+ return node.els.map((el) => evaluate(el, context));+ case "Obj":+ return Object.fromEntries(node.entries.map(([k, v]) => [k, evaluate(v, context)]));++ // ── Component ─────────────────────────────────────────────────────────+ case "Comp": {+ // Lazy builtins — control their own evaluation+ if (LAZY_BUILTINS.has(node.name)) {+ return evaluateLazyBuiltin(node.name, node.args, context, schemaCtx);+ }+ // Check shared builtin registry first+ const builtin = BUILTINS[node.name];+ if (builtin) {+ const args = node.args.map((a) => evaluate(a, context));+ return builtin.fn(...args);+ }+ // Action calls → evaluate to ActionPlan/ActionStep+ if (ACTION_NAMES.has(node.name)) {+ return evaluateActionCall(node.name, node.args, context);+ }+ // If parser already mapped args→props (via materializeExpr), use named props.+ // With schema context: emit ReactiveAssign for StateRef on reactive props.+ // Without schema context: preserve StateRef as AST for evaluate-tree to handle.+ if (node.mappedProps) {+ const def = schemaCtx?.library.components[node.name];+ const props: Record<string, unknown> = {};+ for (const [key, val] of Object.entries(node.mappedProps)) {+ const propSchema = def?.props?.shape?.[key];+ if (val.k === "StateRef" && propSchema && isReactiveSchema(propSchema)) {+ // Reactive schema + StateRef → emit ReactiveAssign marker+ props[key] = {+ __reactive: "assign" as const,+ target: val.n,+ expr: { k: "StateRef" as const, n: "$value" },+ };+ } else if (val.k === "StateRef") {+ // Non-reactive StateRef or no schema context → preserve for evaluate-tree+ props[key] = schemaCtx ? context.getState(val.n) : val;+ } else {+ props[key] = evaluate(val, context, schemaCtx);+ }+ }+ const result: ElementNode = {+ type: "element",+ typeName: node.name,+ props,+ partial: false,+ hasDynamicProps: true,+ };+ // If we have schema context, recursively evaluate nested ElementNodes in props+ if (schemaCtx) {+ for (const [key, val] of Object.entries(props)) {+ if (isElementNode(val)) {+ props[key] = evaluateElementInline(val, context, schemaCtx);+ } else if (Array.isArray(val)) {+ props[key] = val.map((item) =>+ isElementNode(item) ? evaluateElementInline(item, context, schemaCtx) : item,+ );+ }+ }+ }+ return result;+ }+ // After materializeValue, all catalog/unknown components are lowered to+ // ElementNode at parse time. Only builtins and mappedProps Comp nodes+ // reach here. If we somehow get an unmapped Comp, warn and return null.+ console.warn(`[openui] Unexpected unmapped Comp node: ${node.name}`);+ return null;+ }++ // ── Binary operators ──────────────────────────────────────────────────+ case "BinOp": {+ // Short-circuit operators evaluate lazily+ if (node.op === "&&") {+ const left = evaluate(node.left, context);+ return left ? evaluate(node.right, context) : left;+ }+ if (node.op === "||") {+ const left = evaluate(node.left, context);+ return left ? left : evaluate(node.right, context);+ }++ const left = evaluate(node.left, context);+ const right = evaluate(node.right, context);++ switch (node.op) {+ case "+":+ if (typeof left === "string" || typeof right === "string") {+ // Treat null/undefined as "" for string concat to avoid "textnull"+ return String(left ?? "") + String(right ?? "");+ }+ return toNumber(left) + toNumber(right);+ case "-":+ return toNumber(left) - toNumber(right);+ case "*":+ return toNumber(left) * toNumber(right);+ case "/":+ // DSL design choice: division by zero returns 0 instead of JavaScript's Infinity/NaN.+ return toNumber(right) === 0 ? 0 : toNumber(left) / toNumber(right);+ case "%":+ return toNumber(right) === 0 ? 0 : toNumber(left) % toNumber(right);+ case "==":+ // Use loose equality so that e.g. 5 == "5" is true,+ // consistent with the toNumber coercion used by comparison operators.+ return left == right;+ case "!=":+ return left != right;+ case ">":+ return toNumber(left) > toNumber(right);+ case "<":+ return toNumber(left) < toNumber(right);+ case ">=":+ return toNumber(left) >= toNumber(right);+ case "<=":+ return toNumber(left) <= toNumber(right);+ default:+ return null;+ }+ }++ // ── Unary operators ───────────────────────────────────────────────────+ case "UnaryOp":+ if (node.op === "!") {+ return !evaluate(node.operand, context);+ }+ if (node.op === "-") {+ return -toNumber(evaluate(node.operand, context));+ }+ return null;++ // ── Ternary ───────────────────────────────────────────────────────────+ case "Ternary": {+ const cond = evaluate(node.cond, context);+ return cond ? evaluate(node.then, context) : evaluate(node.else, context);+ }++ // ── Member access ─────────────────────────────────────────────────────+ case "Member": {+ const obj = evaluate(node.obj, context) as any;+ if (obj == null) return null;+ // Array pluck: if obj is an array, extract field from every element+ if (Array.isArray(obj)) {+ if (node.field === "length") return obj.length;+ return obj.map((item: any) => item?.[node.field] ?? null);+ }+ return obj[node.field];+ }++ // ── Index access ──────────────────────────────────────────────────────+ case "Index": {+ const obj = evaluate(node.obj, context) as any;+ const idx = evaluate(node.index, context);+ if (obj == null || idx == null) return null;+ if (Array.isArray(obj)) {+ return obj[toNumber(idx)];+ }+ return obj[String(idx)];+ }++ // ── Assignment ────────────────────────────────────────────────────────+ case "Assign":+ return {+ __reactive: "assign" as const,+ target: node.target,+ expr: node.value,+ };+ }+}++/**+ * Strip a ReactiveAssign to its current value in a non-reactive context.+ * When transport args or non-reactive props contain a ReactiveAssign, this+ * resolves it to the current state value (or null if getState is unavailable).+ */+export function stripReactiveAssign(value: unknown, context: EvaluationContext): unknown {+ if (!isReactiveAssign(value)) return value;+ return context.getState(value.target) ?? null;+}++/**+ * Evaluate an ElementNode's props with schema awareness. Used by evaluate()+ * when schema context is available and a Comp produces an ElementNode that+ * needs its own props evaluated with reactive schema detection.+ */+function evaluateElementInline(+ el: ElementNode,+ context: EvaluationContext,+ schemaCtx: SchemaContext,+): ElementNode {+ if (el.hasDynamicProps === false) return el;+ const def = schemaCtx.library.components[el.typeName];+ const evaluated: Record<string, unknown> = {};++ for (const [key, value] of Object.entries(el.props)) {+ const propSchema = def?.props?.shape?.[key];+ evaluated[key] = evaluatePropInline(value, context, schemaCtx, propSchema);+ }+ return { ...el, props: evaluated };+}++/**+ * Evaluate a single prop value with schema awareness.+ * Delegates to shared evaluatePropCore with inline-specific recursion callbacks.+ */+function evaluatePropInline(+ value: unknown,+ context: EvaluationContext,+ schemaCtx: SchemaContext,+ reactiveSchema?: unknown,+): unknown {+ return evaluatePropCore(value, context, schemaCtx, reactiveSchema, {+ recurseElement: (el) => evaluateElementInline(el, context, schemaCtx),+ recurse: (v, rs) => evaluatePropInline(v, context, schemaCtx, rs),+ });+}++/** Convert a resolved runtime value back to a literal AST node for deferred evaluation. */+function toLiteralAST(value: unknown): ASTNode {+ if (value === null || value === undefined) return { k: "Null" };+ if (typeof value === "string") return { k: "Str", v: value };+ if (typeof value === "number") return { k: "Num", v: value };+ if (typeof value === "boolean") return { k: "Bool", v: value };+ if (Array.isArray(value)) return { k: "Arr", els: value.map(toLiteralAST) };+ if (typeof value === "object") {+ return {+ k: "Obj",+ entries: Object.entries(value).map(([k, v]) => [k, toLiteralAST(v)] as [string, ASTNode]),+ };+ }+ return { k: "Null" };+}++/**+ * Evaluate Action/Run/ToAssistant/OpenUrl Comp nodes into ActionPlan/ActionStep values.+ */+function evaluateActionCall(+ name: string,+ args: ASTNode[],+ context: EvaluationContext,+): ActionPlan | ActionStep | null {+ switch (name) {+ case "Action": {+ // Action([step1, step2, ...]) → ActionPlan+ const stepsArg = args.length > 0 ? evaluate(args[0], context) : [];+ const rawSteps = Array.isArray(stepsArg) ? stepsArg : [];+ const steps: ActionStep[] = rawSteps.filter(+ (s): s is ActionStep => s != null && typeof s === "object" && "type" in s,+ );+ return { steps };+ }+ case "Run": {+ // Run(runtimeRef) → ActionStep { type: "run", statementId, refType }+ if (args.length === 0) return null;+ const refNode = args[0];+ if (refNode.k === "RuntimeRef") {+ return { type: ACTION_STEPS.Run, statementId: refNode.n, refType: refNode.refType };+ }+ // Unresolved Ref — skip (filtered out by Action's step array)+ return null;+ }+ case "ToAssistant": {+ // ToAssistant("message") or ToAssistant("message", "context")+ const message = args.length > 0 ? String(evaluate(args[0], context) ?? "") : "";+ const ctx = args.length > 1 ? String(evaluate(args[1], context) ?? "") : undefined;+ return { type: ACTION_STEPS.ToAssistant, message, context: ctx };+ }+ case "OpenUrl": {+ // OpenUrl("url")+ const url = args.length > 0 ? String(evaluate(args[0], context) ?? "") : "";+ return { type: ACTION_STEPS.OpenUrl, url };+ }+ case "Set": {+ // Set($varName, value) → ActionStep { type: "set", target, valueAST }+ // First arg must be a StateRef (the $variable), second arg is the value expression.+ // valueAST is preserved as-is and evaluated at click time by triggerAction.+ // Loop variables (e.g. t.id from Each) are pre-resolved by Each's substituteRef.+ if (args.length < 2) return null;+ const targetNode = args[0];+ if (targetNode.k !== "StateRef") return null;+ return { type: ACTION_STEPS.Set, target: targetNode.n, valueAST: args[1] };+ }+ case "Reset": {+ // Reset($var1, $var2, ...) → ActionStep { type: "reset", targets: [...] }+ // All args must be StateRef nodes. Restores to declared defaults at runtime.+ const targets = args+ .filter((a): a is ASTNode & { k: "StateRef" } => a.k === "StateRef")+ .map((a) => a.n);+ if (targets.length === 0) return null;+ return { type: ACTION_STEPS.Reset, targets };+ }+ default:+ return null;+ }+}++/**+ * Substitute all Ref(varName) nodes in an AST tree with a literal value.+ * This pre-resolves loop variables so deferred expressions (like Action steps)+ * don't lose scope when evaluated later at click time.+ */+function substituteRef(node: ASTNode, varName: string, value: unknown): ASTNode {+ switch (node.k) {+ case "Ref":+ return node.n === varName ? toLiteralAST(value) : node;+ case "Member": {+ // Member access on the loop var: t.id → resolve t, then access .id+ if (isASTNode(node.obj)) {+ const subObj = substituteRef(node.obj as ASTNode, varName, value);+ // If obj resolved to a literal, we can inline the member access result+ if (subObj.k === "Obj") {+ const entry = subObj.entries.find(([k]) => k === node.field);+ if (entry) return entry[1];+ }+ return { ...node, obj: subObj };+ }+ return node;+ }+ case "Index":+ return {+ ...node,+ obj: isASTNode(node.obj) ? substituteRef(node.obj as ASTNode, varName, value) : node.obj,+ index: isASTNode(node.index)+ ? substituteRef(node.index as ASTNode, varName, value)+ : node.index,+ };+ case "BinOp":+ return {+ ...node,+ left: substituteRef(node.left, varName, value),+ right: substituteRef(node.right, varName, value),+ };+ case "UnaryOp":+ return { ...node, operand: substituteRef(node.operand, varName, value) };+ case "Ternary":+ return {+ ...node,+ cond: substituteRef(node.cond, varName, value),+ then: substituteRef(node.then, varName, value),+ else: substituteRef(node.else, varName, value),+ };+ case "Arr":+ return { ...node, els: node.els.map((e) => substituteRef(e, varName, value)) };+ case "Obj":+ return {+ ...node,+ entries: node.entries.map(+ ([k, v]) => [k, substituteRef(v, varName, value)] as [string, ASTNode],+ ),+ };+ case "Comp": {+ const result = { ...node, args: node.args.map((a) => substituteRef(a, varName, value)) };+ // Also substitute in mappedProps (added by materializer for catalog components)+ if (node.mappedProps) {+ const subProps: Record<string, ASTNode> = {};+ for (const [k, v] of Object.entries(node.mappedProps)) {+ subProps[k] = substituteRef(v, varName, value);+ }+ (result as any).mappedProps = subProps;+ }+ return result;+ }+ case "Assign":+ return { ...node, value: substituteRef(node.value, varName, value) };+ default:+ return node;+ }+}++/**+ * Each(array, varName, template) — evaluate template once per array item.+ * varName is user-defined (e.g. `issue`, `ticket`) — no $ prefix collision.+ *+ * Before evaluation, substitutes all Ref(varName) in the template with the+ * current item's literal value. This ensures deferred expressions (like+ * Action/Set steps) capture concrete values instead of dangling loop refs.+ */+function evaluateLazyBuiltin(+ name: string,+ args: ASTNode[],+ context: EvaluationContext,+ schemaCtx?: SchemaContext,+): unknown {+ if (name === "Each") {+ if (args.length < 3) return [];+ const arr = evaluate(args[0], context);+ if (!Array.isArray(arr)) return [];++ const varName =+ args[1].k === "Ref" ? args[1].n : args[1].k === "Str" ? (args[1] as any).v : null;+ if (!varName) return [];+ const template = args[2];++ return arr.map((item, _idx) => {+ // Pre-substitute loop variable refs with concrete values in the template AST.+ // This captures the item for deferred expressions (Action steps evaluated at click time).+ const substituted = substituteRef(template, varName, item);+ const childCtx: EvaluationContext = {+ ...context,+ resolveRef: (refName: string) => {+ if (refName === varName) return item;+ return context.resolveRef(refName);+ },+ };+ const result = evaluate(substituted, childCtx, schemaCtx);+ // If schema context is available and result is an ElementNode, evaluate its props+ if (schemaCtx && isElementNode(result)) {+ return evaluateElementInline(result as ElementNode, childCtx, schemaCtx);+ }+ return result;+ });+ }+ return null;+}diff --git a/packages/lang-core/src/runtime/index.ts b/packages/lang-core/src/runtime/index.tsnew file mode 100644index 000000000..bfc1e8031--- /dev/null+++ b/packages/lang-core/src/runtime/index.ts@@ -0,0 +1,26 @@+export { createStore } from "./store";+export type { Store } from "./store";++export { evaluate, isReactiveAssign, stripReactiveAssign } from "./evaluator";+export type { EvaluationContext, ReactiveAssign } from "./evaluator";++export { createQueryManager } from "./queryManager";+export type {+ MutationNode,+ MutationResult,+ QueryManager,+ QueryNode,+ QuerySnapshot,+ ToolProvider,+} from "./queryManager";++export { evaluateElementProps } from "./evaluate-tree";+export type { EvalContext } from "./evaluate-tree";++export { resolveStateField } from "./state-field";+export type { InferStateFieldValue, StateField } from "./state-field";++export { McpToolError, extractToolResult } from "./mcp";+export type { McpClientLike } from "./mcp";++export { ToolNotFoundError } from "./toolProvider";diff --git a/packages/lang-core/src/runtime/mcp.ts b/packages/lang-core/src/runtime/mcp.tsnew file mode 100644index 000000000..1615d0b2c--- /dev/null+++ b/packages/lang-core/src/runtime/mcp.ts@@ -0,0 +1,86 @@+/**+ * MCP utilities — type definitions and result extraction for MCP client integration.+ *+ * The Renderer accepts an MCP client directly as `toolProvider`.+ * It detects the MCP client shape (has `callTool({ name, arguments })`) and+ * wraps responses with `extractToolResult` automatically.+ *+ * @example+ * ```tsx+ * import { Client } from "@modelcontextprotocol/sdk/client/index.js";+ * import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";+ *+ * const client = new Client({ name: "my-app", version: "1.0.0" });+ * await client.connect(new StreamableHTTPClientTransport(new URL("/api/mcp")));+ *+ * // Pass directly — Renderer handles MCP response extraction+ * <Renderer toolProvider={client} library={library} response={content} />+ * ```+ */++/**+ * Error thrown when an MCP tool call returns `isError: true`.+ * Preserves the raw error content from the MCP response for structured handling.+ */+export class McpToolError extends Error {+ readonly toolErrorText: string;++ constructor(errorText: string) {+ super(`MCP tool error: ${errorText || "Unknown error"}`);+ this.name = "McpToolError";+ this.toolErrorText = errorText;+ }+}++/**+ * Minimal shape of an MCP Client — matches @modelcontextprotocol/sdk Client+ * without requiring it as a hard import. Users can pass any object that+ * implements these methods.+ */+export interface McpClientLike {+ callTool(+ params: { name: string; arguments?: Record<string, unknown> },+ options?: unknown,+ ): Promise<{+ content: Array<{ type: string; text?: string; [key: string]: unknown }>;+ structuredContent?: unknown;+ isError?: boolean;+ }>;+ close?(): Promise<void>;+}++/**+ * Extract the actual data from an MCP callTool result.+ * Prefers structuredContent (machine-readable JSON), falls back to parsing text content.+ */+export function extractToolResult(result: {+ content: Array<{ type: string; text?: string; [key: string]: unknown }>;+ structuredContent?: unknown;+ isError?: boolean;+}): unknown {+ if (result.isError) {+ const errorText = result.content+ ?.filter((c) => c.type === "text")+ .map((c) => c.text)+ .join("\n");+ throw new McpToolError(errorText || "Unknown error");+ }++ // Prefer structuredContent (JSON data, no parsing needed)+ if (result.structuredContent != null) {+ return result.structuredContent;+ }++ // Fall back to text content — try to parse as JSON+ const textParts = result.content?.filter((c) => c.type === "text").map((c) => c.text ?? "");+ if (textParts?.length) {+ const text = textParts.join("");+ try {+ return JSON.parse(text);+ } catch {+ return text;+ }+ }++ return null;+}diff --git a/packages/lang-core/src/runtime/queryManager.ts b/packages/lang-core/src/runtime/queryManager.tsnew file mode 100644index 000000000..ebb615a3e--- /dev/null+++ b/packages/lang-core/src/runtime/queryManager.ts@@ -0,0 +1,594 @@+// ─────────────────────────────────────────────────────────────────────────────+// Query Manager — reactive data fetching for openui-lang+// ─────────────────────────────────────────────────────────────────────────────++import type { OpenUIError } from "../parser/types";+import { McpToolError } from "./mcp";+import { ToolNotFoundError } from "./toolProvider";++/**+ * ToolProvider interface for Query() and Mutation() tool calls.+ * Framework-agnostic — works with MCP, REST, GraphQL, or any backend.+ *+ * @example+ * ```ts+ * // Function map (Renderer normalizes this automatically)+ * <Renderer toolProvider={{+ * get_users: (args) => fetch(`/api/users`).then(r => r.json()),+ * }} />+ *+ * // MCP client (Renderer wraps extractToolResult automatically)+ * <Renderer toolProvider={mcpClient} />+ * ```+ */+export interface ToolProvider {+ callTool(toolName: string, args: Record<string, unknown>): Promise<unknown>;+}++// ── Public types ─────────────────────────────────────────────────────────────++export interface QueryNode {+ statementId: string;+ toolName: string;+ args: unknown;+ defaults: unknown;+ /** Evaluated dependency value — included in cache key to force re-fetch on change. */+ deps: unknown;+ /** Auto-refresh interval in seconds. */+ refreshInterval?: number;+ complete: boolean;+}++export interface MutationNode {+ statementId: string;+ toolName: string;+}++export interface MutationResult {+ status: "idle" | "loading" | "success" | "error";+ data?: unknown;+ error?: unknown;+}++export interface QuerySnapshot extends Record<string, unknown> {+ __openui_loading: string[];+ __openui_refetching: string[];+ __openui_errors: OpenUIError[];+}++export interface QueryManager {+ evaluateQueries(queryNodes: QueryNode[]): void;+ getResult(statementId: string): unknown;+ isLoading(statementId: string): boolean;+ isAnyLoading(): boolean;+ invalidate(statementIds?: string[]): void;+ registerMutations(nodes: MutationNode[]): void;+ fireMutation(+ statementId: string,+ evaluatedArgs: Record<string, unknown>,+ refreshQueryIds?: string[],+ ): Promise<boolean>;+ getMutationResult(statementId: string): MutationResult | null;+ subscribe(listener: () => void): () => void;+ getSnapshot(): QuerySnapshot;+ activate(): void;+ dispose(): void;+}++// ── Internal types ───────────────────────────────────────────────────────────++interface QueryEntry {+ toolName: string;+ args: unknown;+ defaults: unknown;+ cacheKey: string;+ prevCacheKey?: string;+ loading: boolean;+ everFetched: boolean;+ refreshInterval: number;+ timer?: ReturnType<typeof setInterval>;+ needsRefetch: boolean;+ error?: OpenUIError;+}++interface MutationEntry {+ toolName: string;+ result: MutationResult;+ error?: OpenUIError;+}++interface CacheEntry {+ data: unknown;+ inFlight: boolean;+}++// ── Utilities ────────────────────────────────────────────────────────────────++/** JSON.stringify with stable key ordering at all nesting levels. */+function stableStringify(value: unknown): string {+ return JSON.stringify(value, (_key: string, val: unknown) => {+ if (val && typeof val === "object" && !Array.isArray(val)) {+ const sorted: Record<string, unknown> = {};+ for (const k of Object.keys(val as object).sort()) {+ sorted[k] = (val as any)[k];+ }+ return sorted;+ }+ // Serialize non-JSON-safe primitives to stable strings.+ // evaluate() can pull arbitrary values from store/ref state,+ // including undefined in object literals and edge-case numbers.+ if (val === undefined) return "__undefined__";+ if (typeof val === "number") {+ if (Number.isNaN(val)) return "__NaN__";+ if (val === Infinity) return "__Inf__";+ if (val === -Infinity) return "__-Inf__";+ }+ return val;+ });+}++function buildCacheKey(toolName: string, args: unknown, deps: unknown): string {+ const depsKey = deps != null ? "::" + stableStringify(deps) : "";+ return toolName + "::" + stableStringify(args) + depsKey;+}++// ── Factory ──────────────────────────────────────────────────────────────────++export function createQueryManager(toolProvider: ToolProvider | null): QueryManager {+ const queries = new Map<string, QueryEntry>();+ const mutations = new Map<string, MutationEntry>();+ const cache = new Map<string, CacheEntry>();+ const listeners = new Set<() => void>();++ let snapshot: QuerySnapshot = {+ __openui_loading: [],+ __openui_refetching: [],+ __openui_errors: [],+ };+ let snapshotJson = JSON.stringify(snapshot);+ let disposed = false;+ let generation = 0;++ // ── Snapshot & notification ──────────────────────────────────────────────++ function rebuildSnapshot(): boolean {+ const out: QuerySnapshot = {+ __openui_loading: [],+ __openui_refetching: [],+ __openui_errors: [],+ };++ for (const [sid, q] of queries) {+ const entry = cache.get(q.cacheKey);+ if (entry && entry.data !== undefined) {+ // Use settled data (even while refetching — shows last good value)+ out[sid] = entry.data;+ } else if (q.prevCacheKey) {+ const prev = cache.get(q.prevCacheKey);+ if (prev && prev.data !== undefined) {+ out[sid] = prev.data;+ } else {+ out[sid] = q.defaults;+ }+ } else {+ out[sid] = q.defaults;+ }+ if (q.loading) {+ out.__openui_loading.push(sid);+ if (q.everFetched) out.__openui_refetching.push(sid);+ }+ if (q.error) out.__openui_errors.push(q.error);+ }++ for (const [sid, m] of mutations) {+ out[sid] = m.result;+ if (m.error) out.__openui_errors.push(m.error);+ }++ try {+ const outJson = JSON.stringify(out);+ if (outJson === snapshotJson) return false;+ snapshot = out;+ snapshotJson = outJson;+ } catch {+ snapshot = out;+ snapshotJson = "";+ }+ return true;+ }++ function notify() {+ for (const listener of [...listeners]) {+ listener();+ }+ }++ // ── Fetch execution ──────────────────────────────────────────────────────++ async function executeFetch(cacheKey: string, statementId: string) {+ if (!toolProvider) return;++ const q = queries.get(statementId);+ if (!q) return;++ // Capture the cache key at fetch start — if the query's key changes+ // while we're in-flight (deps changed), this fetch is stale.+ const fetchKey = cacheKey;+ const toolName = q.toolName;+ const args = q.args;++ // Mark in-flight — use undefined as "no data yet" sentinel (distinct from null)+ let entry = cache.get(fetchKey);+ if (!entry) {+ entry = { data: undefined, inFlight: true };+ cache.set(fetchKey, entry);+ } else {+ entry.inFlight = true;+ }+ q.loading = true;+ rebuildSnapshot();+ notify();++ try {+ const data = await toolProvider.callTool(toolName, (args as Record<string, unknown>) ?? {});+ if (disposed) return;+ // Query removed or moved to a different cache key while in-flight — discard+ const current = queries.get(statementId);+ if (!current || current.cacheKey !== fetchKey) {+ entry.inFlight = false;+ return;+ }++ entry.data = data ?? null;+ current.everFetched = true;+ current.error = undefined;++ // Clean up previous cache entry — clear prevCacheKey FIRST so+ // cleanupCacheEntry doesn't see this query as a live reference.+ if (current.prevCacheKey && current.prevCacheKey !== fetchKey) {+ const prevKey = current.prevCacheKey;+ current.prevCacheKey = undefined;+ cleanupCacheEntry(prevKey);+ }+ } catch (err) {+ // Only update error state if this fetch is still current+ const current = queries.get(statementId);+ if (current && current.cacheKey === fetchKey) {+ if (err instanceof ToolNotFoundError) {+ current.error = {+ source: "query",+ code: "tool-not-found",+ message: `Query tool "${toolName}" not found`,+ statementId,+ component: "Query",+ toolName,+ hint: err.availableTools.length+ ? `Available tools: ${err.availableTools.join(", ")}`+ : undefined,+ };+ } else if (err instanceof McpToolError) {+ current.error = {+ source: "query",+ code: "mcp-error",+ message: `Query "${toolName}" returned an error: ${err.toolErrorText}`,+ statementId,+ component: "Query",+ toolName,+ };+ } else {+ const msg = err instanceof Error ? err.message : String(err);+ current.error = {+ source: "query",+ code: "tool-error",+ message: `Query "${toolName}" failed: ${msg}`,+ statementId,+ component: "Query",+ toolName,+ };+ }+ }+ console.error(`Query "${toolName}" failed:`, err);+ } finally {+ entry.inFlight = false;+ const current = queries.get(statementId);+ // Only clear loading if this fetch is still current+ if (current && current.cacheKey === fetchKey) {+ current.loading = false;+ if (rebuildSnapshot()) notify();+ // Re-fetch if invalidation occurred while in-flight+ if (current.needsRefetch) {+ current.needsRefetch = false;+ executeFetch(current.cacheKey, statementId);+ }+ } else {+ if (rebuildSnapshot()) notify();+ }+ }+ }++ /** Remove a cache entry if no query references it. */+ function cleanupCacheEntry(cacheKey: string) {+ for (const q of queries.values()) {+ if (q.cacheKey === cacheKey || q.prevCacheKey === cacheKey) return;+ }+ cache.delete(cacheKey);+ }++ // ── Query evaluation ─────────────────────────────────────────────────────++ function evaluateQueries(queryNodes: QueryNode[]) {+ if (disposed) return;++ const activeIds = new Set(queryNodes.map((n) => n.statementId));++ // Clean up removed queries+ for (const [sid, q] of queries) {+ if (!activeIds.has(sid)) {+ if (q.timer) clearInterval(q.timer);+ queries.delete(sid);+ // Clean up cache entries that are no longer referenced+ cleanupCacheEntry(q.cacheKey);+ if (q.prevCacheKey) cleanupCacheEntry(q.prevCacheKey);+ }+ }++ // Process active queries+ for (const node of queryNodes) {+ if (!node.complete) continue;++ const cacheKey = buildCacheKey(node.toolName, node.args, node.deps);+ const existing = queries.get(node.statementId);++ if (existing) {+ // Track previous cache key for fallback display+ if (existing.cacheKey !== cacheKey) {+ existing.prevCacheKey = existing.cacheKey;+ }+ existing.toolName = node.toolName;+ existing.args = node.args;+ existing.defaults = node.defaults;+ existing.cacheKey = cacheKey;+ } else {+ queries.set(node.statementId, {+ toolName: node.toolName,+ args: node.args,+ defaults: node.defaults,+ cacheKey,+ loading: false,+ everFetched: false,+ refreshInterval: 0,+ needsRefetch: false,+ });+ }++ const q = queries.get(node.statementId)!;++ // Fire fetch if no settled data and not already in-flight+ const entry = cache.get(cacheKey);+ const hasSettledData = entry && entry.data !== undefined && !entry.inFlight;+ if (toolProvider && !hasSettledData && !entry?.inFlight) {+ executeFetch(cacheKey, node.statementId);+ }++ // Configure auto-refresh timer+ const newInterval = node.refreshInterval ?? 0;+ if (newInterval !== q.refreshInterval) {+ if (q.timer) {+ clearInterval(q.timer);+ q.timer = undefined;+ }+ if (newInterval > 0) {+ q.timer = setInterval(() => {+ if (disposed || !toolProvider) return;+ const entry = cache.get(q.cacheKey);+ if (!entry?.inFlight) {+ executeFetch(q.cacheKey, node.statementId);+ }+ }, newInterval * 1000);+ }+ q.refreshInterval = newInterval;+ }+ }++ if (rebuildSnapshot()) notify();+ }++ // ── Query accessors ──────────────────────────────────────────────────────++ function getResult(statementId: string): unknown {+ const q = queries.get(statementId);+ if (!q) return null;+ const entry = cache.get(q.cacheKey);+ if (entry && entry.data !== undefined) return entry.data;+ // Fall back to previous cache entry while loading+ if (q.prevCacheKey) {+ const prev = cache.get(q.prevCacheKey);+ if (prev && prev.data !== undefined) return prev.data;+ }+ return q.defaults;+ }++ function isLoading(statementId: string): boolean {+ return queries.get(statementId)?.loading ?? false;+ }++ function isAnyLoading(): boolean {+ for (const q of queries.values()) {+ if (q.loading) return true;+ }+ return false;+ }++ function invalidate(statementIds?: string[]) {+ if (disposed || !toolProvider) return;++ const targets = statementIds?.length+ ? statementIds.filter((sid) => queries.has(sid))+ : [...queries.keys()];++ for (const sid of targets) {+ const q = queries.get(sid);+ if (!q) continue;+ const entry = cache.get(q.cacheKey);+ if (entry?.inFlight) {+ q.needsRefetch = true;+ } else {+ executeFetch(q.cacheKey, sid);+ }+ }+ }++ // ── Mutation methods ─────────────────────────────────────────────────────++ function registerMutations(nodes: MutationNode[]) {+ const activeIds = new Set(nodes.map((n) => n.statementId));++ // Clean up removed mutations+ for (const sid of mutations.keys()) {+ if (!activeIds.has(sid)) mutations.delete(sid);+ }++ // Register/update active mutations+ for (const node of nodes) {+ const existing = mutations.get(node.statementId);+ if (existing) {+ if (existing.toolName !== node.toolName) {+ existing.toolName = node.toolName;+ existing.result = { status: "idle", data: null, error: null };+ existing.error = undefined;+ }+ } else {+ mutations.set(node.statementId, {+ toolName: node.toolName,+ result: { status: "idle" },+ });+ }+ }++ if (rebuildSnapshot()) notify();+ }++ async function fireMutation(+ statementId: string,+ evaluatedArgs: Record<string, unknown>,+ refreshQueryIds?: string[],+ ): Promise<boolean> {+ if (disposed || !toolProvider) return false;+ const m = mutations.get(statementId);+ if (!m) return false;++ // Reject concurrent calls on the same mutation — prevents double-submit+ if (m.result.status === "loading") return false;++ const gen = generation;++ m.result = { status: "loading" };+ rebuildSnapshot();+ notify();++ let success = false;+ try {+ const data = await toolProvider.callTool(m.toolName, evaluatedArgs);+ if (disposed || gen !== generation) return false;+ m.result = { status: "success", data };+ m.error = undefined;+ success = true;+ } catch (err) {+ if (disposed || gen !== generation) return false;+ const msg = err instanceof Error ? err.message : String(err);+ m.result = { status: "error", error: msg };+ if (err instanceof ToolNotFoundError) {+ m.error = {+ source: "mutation",+ code: "tool-not-found",+ message: `Mutation tool "${m.toolName}" not found`,+ statementId,+ component: "Mutation",+ toolName: m.toolName,+ hint: err.availableTools.length+ ? `Available tools: ${err.availableTools.join(", ")}`+ : undefined,+ };+ } else if (err instanceof McpToolError) {+ m.error = {+ source: "mutation",+ code: "mcp-error",+ message: `Mutation "${m.toolName}" returned an error: ${err.toolErrorText}`,+ statementId,+ component: "Mutation",+ toolName: m.toolName,+ };+ } else {+ m.error = {+ source: "mutation",+ code: "tool-error",+ message: `Mutation "${m.toolName}" failed: ${msg}`,+ statementId,+ component: "Mutation",+ toolName: m.toolName,+ };+ }+ }++ rebuildSnapshot();+ notify();++ if (success && refreshQueryIds?.length) {+ invalidate(refreshQueryIds);+ }++ return success;+ }++ function getMutationResult(statementId: string): MutationResult | null {+ return mutations.get(statementId)?.result ?? null;+ }++ // ── Pub/sub ──────────────────────────────────────────────────────────────++ function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+ }++ function getSnapshot(): QuerySnapshot {+ return snapshot;+ }++ // ── Lifecycle ────────────────────────────────────────────────────────────++ function activate() {+ disposed = false;+ }++ function dispose() {+ disposed = true;+ generation++;+ listeners.clear();+ // Clear timers and transient state, preserve cache + query entries for Strict Mode re-attach+ for (const q of queries.values()) {+ if (q.timer) {+ clearInterval(q.timer);+ q.timer = undefined;+ }+ q.loading = false;+ q.needsRefetch = false;+ }+ mutations.clear();+ }++ return {+ evaluateQueries,+ getResult,+ isLoading,+ isAnyLoading,+ invalidate,+ registerMutations,+ fireMutation,+ getMutationResult,+ subscribe,+ getSnapshot,+ activate,+ dispose,+ };+}diff --git a/packages/lang-core/src/runtime/state-field.ts b/packages/lang-core/src/runtime/state-field.tsnew file mode 100644index 000000000..347af83d2--- /dev/null+++ b/packages/lang-core/src/runtime/state-field.ts@@ -0,0 +1,42 @@+import type { EvaluationContext } from "./evaluator";+import { evaluate, isReactiveAssign } from "./evaluator";+import type { Store } from "./store";++export interface StateField<T = unknown> {+ name: string;+ value: T;+ setValue: (newValue: T) => void;+ isReactive: boolean;+}++export type InferStateFieldValue<T> = T extends StateField<infer U> ? U : T;++export function resolveStateField<T = unknown>(+ name: string,+ bindingValue: unknown,+ store: Store | null,+ evaluationContext: EvaluationContext | null,+ fieldGetter: (fieldName: string) => unknown,+ fieldSetter: (fieldName: string, value: unknown) => void,+): StateField<T> {+ if (isReactiveAssign(bindingValue) && store && evaluationContext) {+ const { target, expr } = bindingValue;+ return {+ name,+ value: store.get(target) as T,+ setValue: (value: T) => {+ const extraScope: Record<string, unknown> = { $value: value };+ const nextValue = evaluate(expr, { ...evaluationContext, extraScope });+ store.set(target, nextValue);+ },+ isReactive: true,+ };+ }++ return {+ name,+ value: (fieldGetter(name) ?? bindingValue) as T,+ setValue: (value: T) => fieldSetter(name, value),+ isReactive: false,+ };+}diff --git a/packages/lang-core/src/runtime/store.ts b/packages/lang-core/src/runtime/store.tsnew file mode 100644index 000000000..ac05d5dbc--- /dev/null+++ b/packages/lang-core/src/runtime/store.ts@@ -0,0 +1,100 @@+// ─────────────────────────────────────────────────────────────────────────────+// Reactive state store for openui-lang+// ─────────────────────────────────────────────────────────────────────────────++export interface Store {+ get(name: string): unknown;+ set(name: string, value: unknown): void;+ subscribe(listener: () => void): () => void;+ getSnapshot(): Record<string, unknown>;+ initialize(defaults: Record<string, unknown>, persisted: Record<string, unknown>): void;+ dispose(): void;+}++export function createStore(): Store {+ const state = new Map<string, unknown>();+ const listeners = new Set<() => void>();+ let snapshot: Record<string, unknown> = {};++ function notify() {+ const currentListeners = [...listeners];+ for (const listener of currentListeners) {+ listener();+ }+ }++ function rebuildSnapshot() {+ snapshot = Object.fromEntries(state);+ }++ function get(name: string): unknown {+ return state.get(name);+ }++ function set(name: string, value: unknown): void {+ const existing = state.get(name);+ if (Object.is(existing, value)) return;+ // Shallow-compare plain objects (form data)+ if (+ value &&+ existing &&+ typeof value === "object" &&+ typeof existing === "object" &&+ !Array.isArray(value) &&+ !Array.isArray(existing)+ ) {+ const nk = Object.keys(value as Record<string, unknown>);+ const ok = Object.keys(existing as Record<string, unknown>);+ if (+ nk.length === ok.length &&+ nk.every((k) =>+ Object.is(+ (value as Record<string, unknown>)[k],+ (existing as Record<string, unknown>)[k],+ ),+ )+ ) {+ return;+ }+ }+ state.set(name, value);+ rebuildSnapshot();+ notify();+ }++ function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ }++ function getSnapshot(): Record<string, unknown> {+ return snapshot;+ }++ function initialize(defaults: Record<string, unknown>, persisted: Record<string, unknown>): void {+ // Apply persisted values (explicit restore) and defaults for NEW keys only.+ // Existing user-modified $binding values are always preserved — never+ // overwrite with defaults, never delete. During streaming, declarations+ // can temporarily disappear; deleting user state here would cause data loss.+ for (const key of Object.keys(persisted)) {+ state.set(key, persisted[key]);+ }+ for (const key of Object.keys(defaults)) {+ if (!state.has(key)) {+ state.set(key, defaults[key]);+ }+ }+ rebuildSnapshot();+ notify();+ }++ function dispose(): void {+ state.clear();+ listeners.clear();+ snapshot = {};+ }++ return { get, set, subscribe, getSnapshot, initialize, dispose };+}diff --git a/packages/lang-core/src/runtime/toolProvider.ts b/packages/lang-core/src/runtime/toolProvider.tsnew file mode 100644index 000000000..42779f370--- /dev/null+++ b/packages/lang-core/src/runtime/toolProvider.ts@@ -0,0 +1,17 @@+/**+ * Standard error thrown when a tool name is not found in a function-map ToolProvider.+ * Used by Renderer's inline normalization to give clear error messages.+ */+export class ToolNotFoundError extends Error {+ readonly toolName: string;+ readonly availableTools: string[];++ constructor(toolName: string, availableTools: string[] = []) {+ super(+ `[openui] No handler for tool "${toolName}". Available: ${availableTools.join(", ") || "(none)"}`,+ );+ this.name = "ToolNotFoundError";+ this.toolName = toolName;+ this.availableTools = availableTools;+ }+}diff --git a/packages/lang-core/src/utils/validation.ts b/packages/lang-core/src/utils/validation.tsindex 3d3870681..c3e6fcadd 100644--- a/packages/lang-core/src/utils/validation.ts+++ b/packages/lang-core/src/utils/validation.ts@@ -10,14 +10,16 @@ export interface ParsedRule {* "minLength:3" → { type: "minLength", arg: 3 }* "pattern:^[a-z]" → { type: "pattern", arg: "^[a-z]" }*/+const NUMERIC_RULES = new Set(["min", "max", "minLength", "maxLength"]);+export function parseRule(rule: string): ParsedRule {const colonIdx = rule.indexOf(":");if (colonIdx === -1) return { type: rule };const type = rule.slice(0, colonIdx);const rawArg = rule.slice(colonIdx + 1);- const num = Number(rawArg);- return { type, arg: Number.isFinite(num) && rawArg !== "" ? num : rawArg };+ const arg = NUMERIC_RULES.has(type) && !Number.isNaN(Number(rawArg)) ? Number(rawArg) : rawArg;+ return { type, arg };}export function parseRules(rules: unknown): ParsedRule[] {@@ -135,7 +137,10 @@ export function validate(): string | undefined {for (const rule of rules) {const validator = customValidators?.[rule.type] ?? builtInValidators[rule.type];- if (!validator) continue;+ if (!validator) {+ console.warn(`[openui] Unknown validation rule type: "${rule.type}"`);+ continue;+ }const error = validator(value, rule.arg);if (error) return error;}diff --git a/packages/openui-cli/README.md b/packages/openui-cli/README.mdindex 8bfeea375..421f4364a 100644--- a/packages/openui-cli/README.md+++ b/packages/openui-cli/README.md@@ -53,6 +53,8 @@ openui create [options]Options:- `-n, --name <string>`: Project name+- `--skill`: Install the OpenUI agent skill for AI coding assistants+- `--no-skill`: Skip installing the OpenUI agent skill- `--no-interactive`: Fail instead of prompting for missing required inputWhat it does:@@ -61,13 +63,16 @@ What it does:- copies the bundled `openui-chat` template into a new directory- rewrites `workspace:*` dependencies in the generated `package.json` to `latest`- installs dependencies automatically using the detected package manager+- optionally installs the OpenUI agent skill for AI coding assistants+- prompts for your OpenAI API key and writes it to `.env` (interactive mode only)Examples:```bashopenui create-openui create-openui create --no-interactive+openui create --name my-app+openui create --name my-app --no-skill+openui create --no-interactive --name my-app```### `openui generate`diff --git a/packages/openui-cli/src/commands/generate-worker.ts b/packages/openui-cli/src/commands/generate-worker.tsindex 1bf20fefd..6ae1a9cc5 100644--- a/packages/openui-cli/src/commands/generate-worker.ts+++ b/packages/openui-cli/src/commands/generate-worker.ts@@ -17,6 +17,7 @@ import * as esbuild from "esbuild";interface Library {prompt(options?: unknown): string;+ toSpec(): object;toJSONSchema(): object;}@@ -50,7 +51,7 @@ function createAssetStubPlugin(): esbuild.Plugin {function isLibrary(value: unknown): value is Library {if (typeof value !== "object" || value === null) return false;const obj = value as Record<string, unknown>;- return typeof obj["prompt"] === "function" && typeof obj["toJSONSchema"] === "function";+ return typeof obj["prompt"] === "function" && typeof obj["toSpec"] === "function";}function findLibrary(mod: Record<string, unknown>, exportName?: string): Library | undefined {@@ -74,15 +75,26 @@ interface PromptOptions {preamble?: string;additionalRules?: string[];examples?: string[];+ toolExamples?: string[];+ editMode?: boolean;+ inlineMode?: boolean;+ toolCalls?: boolean;+ bindings?: boolean;}function isPromptOptions(value: unknown): value is PromptOptions {if (typeof value !== "object" || value === null) return false;const obj = value as Record<string, unknown>;- const hasExamples = Array.isArray(obj["examples"]);- const hasRules = Array.isArray(obj["additionalRules"]);- const hasPreamble = typeof obj["preamble"] === "string";- return hasExamples || hasRules || hasPreamble;+ return (+ Array.isArray(obj["examples"]) ||+ Array.isArray(obj["additionalRules"]) ||+ Array.isArray(obj["toolExamples"]) ||+ typeof obj["preamble"] === "string" ||+ typeof obj["editMode"] === "boolean" ||+ typeof obj["inlineMode"] === "boolean" ||+ typeof obj["toolCalls"] === "boolean" ||+ typeof obj["bindings"] === "boolean"+ );}function findPromptOptions(@@ -172,7 +184,8 @@ async function main(): Promise<void> {let output: string;if (jsonSchema) {- output = JSON.stringify(library.toJSONSchema(), null, 2);+ // Output a PromptSpec-compatible JSON with component signatures, groups, and JSON schema.+ output = JSON.stringify(library.toSpec(), null, 2);} else {const promptOptions = findPromptOptions(mod, promptOptionsName);output = library.prompt(promptOptions);diff --git a/packages/openui-cli/src/index.ts b/packages/openui-cli/src/index.tsindex d0e642203..43a2140c5 100644--- a/packages/openui-cli/src/index.ts+++ b/packages/openui-cli/src/index.ts@@ -8,7 +8,7 @@ import { resolveArgs } from "./lib/resolve-args";const program = new Command();-program.name("openui").description("CLI for OpenUI").version("0.0.1");+program.name("openui").description("CLI for OpenUI").version("0.0.6");program.command("create")@@ -30,7 +30,10 @@ program.description("Generate system prompt or JSON schema from a library definition").argument("[entry]", "Path to a file that exports a createLibrary() result").option("-o, --out <file>", "Write output to a file instead of stdout")- .option("--json-schema", "Output JSON schema instead of the system prompt")+ .option(+ "--json-schema",+ "Output JSON schema with component signatures for standalone prompt generation",+ ).option("--export <name>", "Name of the export to use (auto-detected by default)").option("--prompt-options <name>",diff --git a/packages/react-lang/package.json b/packages/react-lang/package.jsonindex 77c6c95ae..aad59a664 100644--- a/packages/react-lang/package.json+++ b/packages/react-lang/package.json@@ -1,6 +1,6 @@{"name": "@openuidev/react-lang",- "version": "0.1.4",+ "version": "0.1.5","description": "Define component libraries, generate LLM system prompts, and render streaming OpenUI Lang output in React — the core runtime for OpenUI generative UI","license": "MIT","type": "module",@@ -59,9 +59,16 @@"zod": "^4.0.0"},"peerDependencies": {+ "@modelcontextprotocol/sdk": ">=1.0.0","react": ">=19.0.0"},+ "peerDependenciesMeta": {+ "@modelcontextprotocol/sdk": {+ "optional": true+ }+ },"devDependencies": {+ "@modelcontextprotocol/sdk": "^1.27.1","@types/react": "^19.0.0","vitest": "^4.0.18"}diff --git a/packages/react-lang/src/Renderer.tsx b/packages/react-lang/src/Renderer.tsxindex fdd8c6eb9..80d1a6251 100644--- a/packages/react-lang/src/Renderer.tsx+++ b/packages/react-lang/src/Renderer.tsx@@ -1,5 +1,13 @@-import type { ActionEvent, ElementNode, ParseResult } from "@openuidev/lang-core";-import React, { Component, Fragment, useEffect } from "react";+import type {+ ActionEvent,+ ElementNode,+ McpClientLike,+ OpenUIError,+ ParseResult,+ ToolProvider,+} from "@openuidev/lang-core";+import { ToolNotFoundError, extractToolResult } from "@openuidev/lang-core";+import React, { Component, Fragment, useEffect, useInsertionEffect, useRef } from "react";import { OpenUIContext, useOpenUI, useRenderNode } from "./context";import { useOpenUIState } from "./hooks/useOpenUIState";import type { ComponentRenderer, Library } from "./library";@@ -17,26 +25,53 @@ export interface RendererProps {* Called whenever a form field value changes. Receives the raw form state map.* The consumer decides how to persist this (e.g. embed in message, store separately).*/- onStateUpdate?: (state: Record<string, any>) => void;+ onStateUpdate?: (state: Record<string, unknown>) => void;/*** Initial form state to hydrate on load (e.g. from a previously persisted message).- * Shape: { formName: { fieldName: { value, componentType } } }+ * Shape: { formName: { fieldName: { value, componentType } }, $varName: value }+ * $-prefixed keys are treated as reactive bindings, everything else is form state.*/initialState?: Record<string, any>;/** Called whenever the parse result changes. */onParseResult?: (result: ParseResult | null) => void;+ /**+ * Tool provider for Query()/Mutation() calls.+ * - Function map: `{ tool_name: async (args) => result }` — simplest option+ * - MCP client: any object with `callTool({ name, arguments })` (e.g. from @modelcontextprotocol/sdk)+ */+ toolProvider?:+ | Record<string, (args: Record<string, unknown>) => Promise<unknown>>+ | McpClientLike+ | null;+ /** Custom loading indicator shown while queries are fetching. Defaults to a spinner. */+ queryLoader?: React.ReactNode;+ /**+ * Called with structured, LLM-friendly errors from the parser and query system.+ * Only includes errors fixable by changing the openui-lang code (unknown components,+ * missing required props, tool-not-found). Suitable for an automated LLM correction loop.+ * Called with [] when all errors are resolved.+ */+ onError?: (errors: OpenUIError[]) => void;}// ─── Error boundary ───interface ErrorBoundaryProps {children: React.ReactNode;+ componentName?: string;+ onError?: (error: OpenUIError) => void;}interface ErrorBoundaryState {hasError: boolean;}+/**+ * Error boundary that intentionally shows the last successfully rendered+ * children when a render error occurs. This "show last good state" behavior+ * prevents the UI from going blank during streaming or transient evaluation+ * errors, and auto-recovers when new valid children arrive.+ */class ElementErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {private lastValidChildren: React.ReactNode = null;@@ -64,8 +99,14 @@ class ElementErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt}}- componentDidCatch(error: Error, info: React.ErrorInfo): void {- console.error("[openui] Component render error:", error, info);+ componentDidCatch(error: Error): void {+ const name = this.props.componentName ?? "Unknown";+ this.props.onError?.({+ source: "runtime",+ code: "render-error",+ component: name,+ message: `Component ${name} render failed: ${error.message}`,+ });}render() {@@ -106,47 +147,57 @@ function renderDeep(value: unknown): React.ReactNode {* Renders a single ElementNode.*/function RenderNode({ node }: { node: ElementNode }) {- const { library } = useOpenUI();+ const { library, reportError } = useOpenUI();const Comp = library.components[node.typeName]?.component;if (!Comp) return null;return (- <ElementErrorBoundary>+ <ElementErrorBoundary componentName={node.typeName} onError={reportError}><RenderNodeInner el={node} Comp={Comp} /></ElementErrorBoundary>);}/**- * Renders a resolved element using its renderer. Gets renderNode from context.+ * Renders a resolved element using its renderer.+ * Props are already evaluated by evaluate-tree — no AST awareness needed.*/function RenderNodeInner({ el, Comp }: { el: ElementNode; Comp: ComponentRenderer<any> }) {const renderNode = useRenderNode();- const { library } = useOpenUI();-- // Handle elements that have positional `args` instead of named `props`- let props = el.props;- if (!props) {- const args = (el as any).args as unknown[] | undefined;- if (args) {- const def = library.components[el.typeName];- if (def) {- const fieldNames = Object.keys(def.props.shape);- props = {};- for (let i = 0; i < fieldNames.length && i < args.length; i++) {- props[fieldNames[i]] = args[i];- }- }- }- props = props ?? {};- }+ return <Comp props={el.props} renderNode={renderNode} />;+}++// ─── Loading style injection (once per document) ───- return <Comp props={props} renderNode={renderNode} />;+let loadingStyleInjected = false;+function ensureLoadingStyle() {+ if (loadingStyleInjected || typeof document === "undefined") return;+ loadingStyleInjected = true;+ const style = document.createElement("style");+ style.textContent = `@keyframes openui-spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`;+ document.head.appendChild(style);}// ─── Public component ───+const DefaultQueryLoader = () => (+ <div+ style={{+ position: "absolute",+ top: 8,+ right: 8,+ width: 16,+ height: 16,+ border: "2px solid #e5e7eb",+ borderTopColor: "#3b82f6",+ borderRadius: "50%",+ animation: "openui-spin 0.6s linear infinite",+ zIndex: 10,+ }}+ />+);+export function Renderer({response,library,@@ -155,8 +206,46 @@ export function Renderer({onStateUpdate,initialState,onParseResult,+ toolProvider,+ queryLoader,+ onError,}: RendererProps) {- const { result, contextValue } = useOpenUIState(+ useInsertionEffect(() => {+ ensureLoadingStyle();+ }, []);++ const onParseResultRef = useRef(onParseResult);+ onParseResultRef.current = onParseResult;++ // Stable ToolProvider wrapper — identity never changes, so QueryManager+ // is created once. callTool() reads the latest input from a ref on every+ // call, so function map updates, closure changes, and provider swaps+ // are always observed without triggering re-creation.+ const toolProviderInputRef = useRef(toolProvider);+ toolProviderInputRef.current = toolProvider;++ const stableToolProvider = useRef<ToolProvider>({+ async callTool(toolName: string, args: Record<string, unknown>): Promise<unknown> {+ const current = toolProviderInputRef.current ?? null;+ if (current == null) throw new Error("[openui] toolProvider is null");+ // MCP client — has callTool({ name, arguments }) returning MCP envelope+ if (typeof (current as McpClientLike).callTool === "function") {+ const result = await (current as McpClientLike).callTool({+ name: toolName,+ arguments: args,+ });+ return extractToolResult(result);+ }+ // Function map — plain object of async functions+ const map = current as Record<string, (a: Record<string, unknown>) => Promise<unknown>>;+ const fn = map[toolName];+ if (!fn) throw new ToolNotFoundError(toolName, Object.keys(map));+ return fn(args);+ },+ });+ const resolvedToolProvider = toolProvider != null ? stableToolProvider.current : null;++ const { result, parseResult, contextValue, isQueryLoading } = useOpenUIState({response,library,@@ -164,13 +253,17 @@ export function Renderer({onAction,onStateUpdate,initialState,+ toolProvider: resolvedToolProvider,+ onError,},renderDeep,);+ // Fire onParseResult with the RAW parse result (not evaluated),+ // so hosts only see changes when the parser output actually changes.useEffect(() => {- onParseResult?.(result);- }, [result, onParseResult]);+ onParseResultRef.current?.(parseResult);+ }, [parseResult]);if (!result?.root) {return null;@@ -178,7 +271,12 @@ export function Renderer({return (<OpenUIContext.Provider value={contextValue}>- <RenderNode node={result.root} />+ <div style={{ position: "relative" }}>+ {isQueryLoading && (queryLoader ?? <DefaultQueryLoader />)}+ <div style={{ opacity: isQueryLoading ? 0.7 : 1, transition: "opacity 0.2s ease" }}>+ <RenderNode node={result.root} />+ </div>+ </div></OpenUIContext.Provider>);}diff --git a/packages/react-lang/src/context.ts b/packages/react-lang/src/context.tsindex f521f9b73..7aeddfd2c 100644--- a/packages/react-lang/src/context.ts+++ b/packages/react-lang/src/context.ts@@ -1,10 +1,8 @@+import type { ActionPlan, EvaluationContext, OpenUIError, Store } from "@openuidev/lang-core";import type { ReactNode } from "react";import { createContext, useContext, useEffect } from "react";import type { Library } from "./library";-/**- * Shared context provided by <Renderer /> to all rendered components.- */export interface OpenUIContextValue {/** The active component library (schema + renderers). */library: Library;@@ -15,32 +13,31 @@ export interface OpenUIContextValue {renderNode: (value: unknown) => ReactNode;/**- * Trigger an action. Components call this to fire structured ActionEvents.- *- * @param userMessage Human-readable label ("Submit Application")- * @param formName Optional form name — if provided, form state for this form is included- * @param action Optional custom action config { type, params }+ * Trigger an action. Accepts either:+ * - ActionPlan (v0.5): runs steps sequentially (Run, Set, ToAssistant, OpenUrl)+ * - Legacy action config (v0.4): { type?: string, params?: Record<string, any> }+ * - Nothing: fires ContinueConversation with the label*/triggerAction: (userMessage: string,formName?: string,- action?: { type?: string; params?: Record<string, any> },- ) => void;+ action?: ActionPlan | { type?: string; params?: Record<string, any> },+ ) => void | Promise<void>;/** Whether the LLM is currently streaming content. */isStreaming: boolean;- /** Get a form field value. Returns undefined if not set. */+ /** Get a field value. Top-level for $bindings, nested under formName for form fields. */getFieldValue: (formName: string | undefined, name: string) => any;/*** Set a form field value.** @param formName The form's name prop- * @param componentType The component type (e.g. "Input", "Select", "RadioGroup")+ * @param componentType The component type (e.g. "Input", "Select") — optional* @param name The field's name prop* @param value The new value- * @param shouldTriggerSaveCallback When true, persists the updated state via updateMessage.+ * @param shouldTriggerSaveCallback When true, persists state via onStateUpdate.* Text inputs should pass `false` on change and `true` on blur.* Discrete inputs (Select, RadioGroup, etc.) should always pass `true`.*/@@ -48,9 +45,18 @@ export interface OpenUIContextValue {formName: string | undefined,componentType: string | undefined,name: string,- value: any,+ value: unknown,shouldTriggerSaveCallback?: boolean,) => void;++ /** Reactive binding store for $variables and form data. */+ store: Store;++ /** AST evaluation context used by runtime expression evaluation. */+ evaluationContext: EvaluationContext;++ /** Report a structured error (used internally by error boundary). */+ reportError?: (error: OpenUIError) => void;}export const OpenUIContext = createContext<OpenUIContextValue | null>(null);@@ -112,7 +118,7 @@ export function useGetFieldValue() {* @example* ```tsx* const setFieldValue = useSetFieldValue();- * <input onChange={(e) => setFieldValue("contactForm", "Input", "name", e.target.value)} />+ * <input onChange={(e) => setFieldValue("contactForm", "Input", "name", e.target.value, false)} />* ```*/export function useSetFieldValue() {@@ -152,10 +158,10 @@ export function useSetDefaultValue({shouldTriggerSaveCallback = false,}: {formName?: string;- componentType: string;+ componentType?: string;name: string;- existingValue: any;- defaultValue: any;+ existingValue: unknown;+ defaultValue: unknown;shouldTriggerSaveCallback?: boolean;}) {const setFieldValue = useSetFieldValue();@@ -165,5 +171,14 @@ export function useSetDefaultValue({if (!isStreaming && existingValue === undefined && defaultValue !== undefined) {setFieldValue(formName, componentType, name, defaultValue, shouldTriggerSaveCallback);}- }, [existingValue, defaultValue, isStreaming]);+ }, [+ defaultValue,+ existingValue,+ formName,+ componentType,+ name,+ isStreaming,+ setFieldValue,+ shouldTriggerSaveCallback,+ ]);}diff --git a/packages/react-lang/src/hooks/useFormValidation.ts b/packages/react-lang/src/hooks/useFormValidation.tsindex 073448b36..0d8aadbea 100644--- a/packages/react-lang/src/hooks/useFormValidation.ts+++ b/packages/react-lang/src/hooks/useFormValidation.ts@@ -3,6 +3,7 @@ import { createContext, useCallback, useContext, useMemo, useRef, useState } froexport interface 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;@@ -12,7 +13,7 @@ export interface FormValidationContextValue {export const FormValidationContext = createContext<FormValidationContextValue | null>(null);-export function useFormValidation() {+export function useFormValidation(): FormValidationContextValue | null {return useContext(FormValidationContext);}@@ -23,8 +24,12 @@ interface FieldRegistration {export function useCreateFormValidation(): FormValidationContextValue {const [errors, setErrors] = useState<Record<string, string | undefined>>({});+ const errorsRef = useRef(errors);+ errorsRef.current = errors;const fieldsRef = useRef<Record<string, FieldRegistration>>({});+ const getFieldError = useCallback((name: string) => errorsRef.current[name], []);+const validateField = useCallback((name: string, value: unknown, rules: ParsedRule[]): boolean => {const error = validate(value, rules);@@ -79,15 +84,24 @@ export function useCreateFormValidation(): FormValidationContextValue {});}, []);- return useMemo(+ return useMemo<FormValidationContextValue>(() => ({errors,+ getFieldError,validateField,registerField,unregisterField,validateForm,clearFieldError,}),- [errors, validateField, registerField, unregisterField, validateForm, clearFieldError],+ [+ errors,+ getFieldError,+ validateField,+ registerField,+ unregisterField,+ validateForm,+ clearFieldError,+ ],);}diff --git a/packages/react-lang/src/hooks/useOpenUIState.ts b/packages/react-lang/src/hooks/useOpenUIState.tsindex f10875088..cfff2de8c 100644--- a/packages/react-lang/src/hooks/useOpenUIState.ts+++ b/packages/react-lang/src/hooks/useOpenUIState.ts@@ -1,89 +1,236 @@import {+ ACTION_STEPS,BuiltinActionType,- createParser,+ createQueryManager,+ createStore,+ createStreamingParser,+ enrichErrors,+ evaluate,+ evaluateElementProps,type ActionEvent,+ type ActionPlan,+ type EvalContext,+ type EvaluationContext,+ type OpenUIError,type ParseResult,+ type QueryManager,+ type QuerySnapshot,+ type Store,+ type ToolProvider,} from "@openuidev/lang-core";import type React from "react";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react";import type { OpenUIContextValue } from "../context";import type { Library } from "../library";+/** Unwrap { value, componentType } wrapper from form field entries. Returns raw value. */+function unwrapFieldValue(v: unknown): unknown {+ if (+ v &&+ typeof v === "object" &&+ !Array.isArray(v) &&+ "value" in (v as Record<string, unknown>)+ ) {+ return (v as Record<string, unknown>).value;+ }+ return v;+}+export interface UseOpenUIStateOptions {response: string | null;library: Library;isStreaming: boolean;onAction?: (event: ActionEvent) => void;- onStateUpdate?: (state: Record<string, any>) => void;+ onStateUpdate?: (state: Record<string, unknown>) => void;initialState?: Record<string, any>;+ /** ToolProvider for Query data fetching — MCP, REST, GraphQL, or any backend. */+ toolProvider?: ToolProvider | null;+ /** Callback for structured, LLM-friendly errors. See OpenUIError type. */+ onError?: (errors: OpenUIError[]) => void;}export interface OpenUIState {+ /** Evaluated result (props resolved to concrete values). Used by Renderer. */result: ParseResult | null;+ /** Raw parse result (AST nodes in props). Used by onParseResult callback. */+ parseResult: ParseResult | null;contextValue: OpenUIContextValue;+ /** Whether any Query is currently fetching data. */+ isQueryLoading: boolean;}/*** Core state hook — extracts all form state, action handling, parser* management, and context assembly out of the Renderer component.*- * - propsRef avoids stale closures in callbacks- * - stable getFieldValue/setFieldValue/triggerAction via useCallback([])- * - setFieldValue accepts shouldTriggerSaveCallback (blur-based persistence for text inputs)+ * Store holds everything: $bindings as top-level keys, form fields nested+ * under formName as plain values.*/export function useOpenUIState(- { response, library, isStreaming, onAction, onStateUpdate, initialState }: UseOpenUIStateOptions,+ {+ response,+ library,+ isStreaming,+ onAction,+ onStateUpdate,+ initialState,+ toolProvider,+ onError,+ }: UseOpenUIStateOptions,renderDeep: (value: unknown) => React.ReactNode,): OpenUIState {- // ─── Parser (synchronous, created once from the library's JSON schema) ───- const parser = useMemo(() => createParser(library.toJSONSchema()), []); // intentionally empty deps — parser is created once+ // ─── Streaming parser (incremental — caches completed statements) ───+ const sp = useMemo(() => createStreamingParser(library.toJSONSchema(), library.root), [library]);// ─── Parse result ───+ const parseExceptionRef = useRef<OpenUIError | null>(null);const result = useMemo<ParseResult | null>(() => {+ parseExceptionRef.current = null;if (!response) return null;try {- return parser.parse(response);+ return sp.set(response);} catch (e) {- console.error("[openui] Parse error:", e);+ const msg = e instanceof Error ? e.message : String(e);+ parseExceptionRef.current = {+ source: "parser",+ code: "parse-exception",+ message: `Parser crashed: ${msg}`,+ hint: "The response may contain syntax the parser cannot handle",+ };return null;}- }, [parser, response]);+ }, [sp, response]);- // Log the final parsed tree once streaming ends (dev debugging).- const prevIsStreaming = useRef(isStreaming);- useEffect(() => {- prevIsStreaming.current = isStreaming;- }, [isStreaming, result]);+ // ─── Store (holds everything: $bindings + form fields) ───+ const store = useMemo<Store>(() => createStore(), []);- // ─── Form state ───- const [formState, setFormState] = useState<Record<string, any>>(() => initialState ?? {});+ // ─── QueryManager ───+ const queryManager = useMemo<QueryManager>(+ () => createQueryManager(toolProvider ?? null),+ [toolProvider],+ );++ useEffect(() => {+ queryManager.activate();+ return () => queryManager.dispose();+ }, [queryManager]);- // Sync if initialState changes (e.g. loading a different message)- const prevInitialFormState = useRef(initialState);+ // ─── Initialize Store ───+ const storeInitKeyRef = useRef<unknown>(Symbol());useEffect(() => {- if (prevInitialFormState.current !== initialState) {- prevInitialFormState.current = initialState;- setFormState(initialState ?? {});+ if (!result?.stateDeclarations && !initialState) return;+ const key = `${JSON.stringify(result?.stateDeclarations)}::${JSON.stringify(initialState)}`;+ if (storeInitKeyRef.current === key) return;+ storeInitKeyRef.current = key;++ // Split initialState: $-prefixed keys are bindings, everything else is form state+ const bindingDefaults: Record<string, unknown> = {};+ if (initialState) {+ for (const [key, value] of Object.entries(initialState)) {+ if (key.startsWith("$")) {+ bindingDefaults[key] = value;+ } else {+ // Form state — restore as-is (preserves { value, componentType } wrapper)+ store.set(key, value);+ }+ }}- }, [initialState]);+ store.initialize(result?.stateDeclarations ?? {}, bindingDefaults);+ }, [result?.stateDeclarations, store, initialState]);++ // ─── Subscribe to Store and QueryManager for re-renders ───+ const storeSnapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);+ const querySnapshot = useSyncExternalStore(+ queryManager.subscribe,+ queryManager.getSnapshot,+ queryManager.getSnapshot,+ ) as QuerySnapshot;++ // ─── Build EvaluationContext ───+ const evaluationContext = useMemo<EvaluationContext>(+ () => ({+ getState: (name: string) => unwrapFieldValue(store.get(name)),+ resolveRef: (name: string) => {+ const mutResult = queryManager.getMutationResult(name);+ if (mutResult) return mutResult;+ return queryManager.getResult(name);+ },+ }),+ [store, queryManager],+ );++ // ─── Evaluate and submit queries ───+ useEffect(() => {+ if (isStreaming) return;++ const queryStmts = result?.queryStatements ?? [];+ const evaluatedNodes = queryStmts.map((qn) => {+ const relevantDeps: Record<string, unknown> = {};+ if (qn.deps) {+ for (const ref of qn.deps) {+ relevantDeps[ref] = storeSnapshot[ref];+ }+ }+ return {+ statementId: qn.statementId,+ toolName: qn.toolAST ? (evaluate(qn.toolAST, evaluationContext) as string) : "",+ args: qn.argsAST ? evaluate(qn.argsAST, evaluationContext) : null,+ defaults: qn.defaultsAST ? evaluate(qn.defaultsAST, evaluationContext) : null,+ refreshInterval: qn.refreshAST+ ? (evaluate(qn.refreshAST, evaluationContext) as number)+ : undefined,+ deps: Object.keys(relevantDeps).length > 0 ? relevantDeps : undefined,+ complete: qn.complete,+ };+ });++ // Always call — empty array clears removed queries and their errors+ queryManager.evaluateQueries(evaluatedNodes);+ }, [isStreaming, result?.queryStatements, evaluationContext, queryManager, storeSnapshot]);++ // ─── Register mutations ───+ useEffect(() => {+ if (isStreaming) return;++ const mutStmts = result?.mutationStatements ?? [];+ const nodes = mutStmts.map((mn) => ({+ statementId: mn.statementId,+ toolName: mn.toolAST ? (evaluate(mn.toolAST, evaluationContext) as string) : "",+ }));+ // Always call — empty array clears removed mutations and their errors+ queryManager.registerMutations(nodes);+ }, [isStreaming, result?.mutationStatements, evaluationContext, queryManager]);// ─── Ref for stable callbacks ───- const propsRef = useRef({- formState,- onAction,- onStateUpdate,- });- propsRef.current = {- formState,- onAction,- onStateUpdate,- };+ const propsRef = useRef({ onAction, onStateUpdate, onError });+ propsRef.current = { onAction, onStateUpdate, onError };++ const resultRef = useRef(result);+ resultRef.current = result;++ // ─── Fire onStateUpdate when Store changes ───+ const lastInitSnapshotRef = useRef<Record<string, unknown> | null>(null);+ useEffect(() => {+ lastInitSnapshotRef.current = store.getSnapshot();+ const unsub = store.subscribe(() => {+ const currentSnapshot = store.getSnapshot();+ if (currentSnapshot === lastInitSnapshotRef.current) return;+ lastInitSnapshotRef.current = null;+ propsRef.current.onStateUpdate?.(currentSnapshot);+ });+ return unsub;+ }, [store]);// ─── getFieldValue ───- const getFieldValue = useCallback((formName: string | undefined, name: string) => {- const state = propsRef.current.formState;- return formName ? state[formName]?.[name]?.value : state[name]?.value;- }, []);+ const getFieldValue = useCallback(+ (formName: string | undefined, name: string) => {+ if (!formName) return unwrapFieldValue(store.get(name));+ const formData = store.get(formName);+ if (!formData || typeof formData !== "object" || Array.isArray(formData)) return undefined;+ return unwrapFieldValue((formData as Record<string, unknown>)[name]);+ },+ [store],+ );// ─── setFieldValue ───const setFieldValue = useCallback(@@ -91,63 +238,149 @@ export function useOpenUIState(formName: string | undefined,componentType: string | undefined,name: string,- value: any,+ value: unknown,shouldTriggerSaveCallback: boolean = true,) => {- const { formState: currentState } = propsRef.current;- const newState = { ...currentState };-- if (formName) {- newState[formName] = {- ...newState[formName],- [name]: { value, componentType },- };+ const wrapped = { value, componentType };+ if (!formName) {+ store.set(name, wrapped);} else {- newState[name] = { value, componentType };+ const raw = store.get(formName);+ const formData =+ raw && typeof raw === "object" && !Array.isArray(raw)+ ? (raw as Record<string, unknown>)+ : {};+ store.set(formName, { ...formData, [name]: wrapped });}-- setFormState(newState);- propsRef.current.formState = newState;-if (shouldTriggerSaveCallback) {- propsRef.current.onStateUpdate?.(newState);+ propsRef.current.onStateUpdate?.(store.getSnapshot());}},- [],+ [store],+ );++ // ─── Materialize form payload ───+ const getFormPayload = useCallback(+ (formName?: string): Record<string, unknown> | undefined => {+ if (formName) {+ const raw = store.get(formName);+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {+ return { [formName]: raw };+ }+ }+ return store.getSnapshot();+ },+ [store],);// ─── triggerAction ───const triggerAction = useCallback(- (+ async (userMessage: string,formName?: string,- action?: { type?: string; params?: Record<string, any> },+ action?: ActionPlan | { type?: string; params?: Record<string, any> },) => {- const { formState: currentState, onAction: handler } = propsRef.current;- const actionType = action?.type || BuiltinActionType.ContinueConversation;- const actionParams = action?.params;-- // Collect relevant form state- let relevantState: Record<string, any> | undefined;- if (formName && currentState[formName]) {- relevantState = { [formName]: currentState[formName] };- } else if (Object.keys(currentState).length > 0) {- relevantState = currentState;+ const formPayload = getFormPayload(formName);+ const { onAction: handler } = propsRef.current;++ // Legacy action config path (v0.4 compat) — { type?, params? }+ if (action && !("steps" in action)) {+ const actionType = action.type || BuiltinActionType.ContinueConversation;+ const params = { ...(action.params || {}) };+ // v0.4 compat — url and context were top-level, not in params+ if ((action as any).url) params.url = (action as any).url;+ if ((action as any).context) params.context = (action as any).context;+ handler?.({+ type: actionType,+ params,+ humanFriendlyMessage: userMessage,+ formState: formPayload,+ formName,+ });+ return;}- if (!handler) return;+ // ActionPlan path (v0.5) — sequential steps with halt-on-mutation-failure+ const actionPlan = action as ActionPlan | undefined;+ if (actionPlan?.steps) {+ for (const step of actionPlan.steps) {+ switch (step.type) {+ case ACTION_STEPS.Run: {+ if (step.refType === "mutation") {+ const mn = resultRef.current?.mutationStatements?.find(+ (m) => m.statementId === step.statementId,+ );+ const evaluatedArgs = mn?.argsAST+ ? (evaluate(mn.argsAST, evaluationContext) as Record<string, unknown>)+ : {};+ const ok = await queryManager.fireMutation(step.statementId, evaluatedArgs);+ if (!ok) return; // halt on failure+ } else {+ queryManager.invalidate([step.statementId]);+ }+ break;+ }+ case ACTION_STEPS.ToAssistant:+ handler?.({+ type: BuiltinActionType.ContinueConversation,+ params: step.context ? { context: step.context } : {},+ humanFriendlyMessage: step.message,+ formState: formPayload,+ formName,+ });+ break;+ case ACTION_STEPS.OpenUrl:+ handler?.({+ type: BuiltinActionType.OpenUrl,+ params: { url: step.url },+ humanFriendlyMessage: "",+ formState: formPayload,+ formName,+ });+ break;+ case ACTION_STEPS.Set: {+ if (!step.valueAST) {+ console.warn(`[openui] Set action for ${step.target} has no valueAST — skipping`);+ break;+ }+ const value = evaluate(step.valueAST, evaluationContext);+ store.set(step.target, value);+ break;+ }+ case ACTION_STEPS.Reset: {+ const decls = resultRef.current?.stateDeclarations ?? {};+ for (const target of step.targets) {+ store.set(target, decls[target] ?? null);+ }+ break;+ }+ }+ }+ return;+ }- handler({- type: actionType,- params: actionParams || {},+ // Default — ContinueConversation with label+ handler?.({+ type: BuiltinActionType.ContinueConversation,+ params: {},humanFriendlyMessage: userMessage,- formState: relevantState,+ formState: formPayload,formName,});},- [],+ [queryManager, evaluationContext, getFormPayload, store],);+ // ─── reportError (for error boundary) ───+ const renderErrorsRef = useRef<OpenUIError[]>([]);+ const isStreamingRef = useRef(isStreaming);+ isStreamingRef.current = isStreaming;+ const reportError = useCallback((error: OpenUIError) => {+ // Skip during streaming — render errors are transient and onError won't fire until streaming stops+ if (isStreamingRef.current) return;+ renderErrorsRef.current.push(error);+ }, []);+// ─── Context value ───const contextValue = useMemo<OpenUIContextValue>(() => ({@@ -157,9 +390,116 @@ export function useOpenUIState(isStreaming,getFieldValue,setFieldValue,+ store,+ evaluationContext,+ reportError,}),- [library, renderDeep, isStreaming, triggerAction, getFieldValue, setFieldValue, formState],+ [+ library,+ renderDeep,+ isStreaming,+ triggerAction,+ getFieldValue,+ setFieldValue,+ store,+ evaluationContext,+ reportError,+ ],);- return { result, contextValue };+ // ─── Evaluate props ───+ const runtimeErrorsRef = useRef<OpenUIError[]>([]);++ const evaluatedResult = useMemo<ParseResult | null>(() => {+ if (!result?.root) return result;+ // Fresh errors array each pass — avoids mutating memoized context+ const errors: OpenUIError[] = [];+ const evalCtx: EvalContext = { ctx: evaluationContext, library, store, errors };+ try {+ const evaluatedRoot = evaluateElementProps(result.root, evalCtx);+ runtimeErrorsRef.current = errors;+ return { ...result, root: evaluatedRoot };+ } catch (e) {+ // Safety net — per-prop catch in evaluateElementProps handles most cases+ const msg = e instanceof Error ? e.message : String(e);+ errors.push({+ source: "runtime",+ code: "runtime-error",+ message: `Prop evaluation failed: ${msg}`,+ });+ runtimeErrorsRef.current = errors;+ return result;+ }+ }, [result, evaluationContext, library, store, storeSnapshot, querySnapshot]);++ const isQueryLoading = querySnapshot.__openui_loading.length > 0;++ // ─── Collect and fire onError ───+ const lastErrorKeyRef = useRef<string>("");+ useEffect(() => {+ if (isStreaming) {+ // Clear stale errors from previous session so the correction loop+ // gets a clean signal when this streaming session completes.+ if (lastErrorKeyRef.current !== "") {+ lastErrorKeyRef.current = "";+ propsRef.current.onError?.([]);+ }+ return;+ }+ const errors: OpenUIError[] = [];++ // Parser exception (parser itself crashed)+ if (parseExceptionRef.current) {+ errors.push(parseExceptionRef.current);+ }++ // Parse failure — response exists but produced no renderable root+ if (response && !result?.root && !parseExceptionRef.current) {+ errors.push({+ source: "parser",+ code: "parse-failed",+ message: result+ ? "Code parsed but produced no renderable root component"+ : "Response could not be parsed as valid openui-lang",+ hint: `The entire response must be valid openui-lang code starting with root = ${library.root ?? "Root"}(...)`,+ });+ }++ // Parser validation errors → enriched OpenUIError (with hints)+ if (result?.meta?.errors?.length) {+ errors.push(+ ...enrichErrors(+ result.meta.errors,+ library.toJSONSchema(),+ Object.keys(library.components),+ ),+ );+ }++ // Runtime eval errors (collected per-prop by evaluateElementProps)+ errors.push(...runtimeErrorsRef.current);++ // Render errors (collected by error boundary via reportError)+ errors.push(...renderErrorsRef.current);+ renderErrorsRef.current = [];++ // Query/mutation tool errors — already OpenUIError, pass through directly+ errors.push(...(querySnapshot.__openui_errors ?? []));++ // Deduplicate — only fire when errors actually change+ const key = JSON.stringify(errors);+ if (key === lastErrorKeyRef.current) return;+ lastErrorKeyRef.current = key;++ // Fire onError or fall back to console.warn+ if (propsRef.current.onError) {+ propsRef.current.onError(errors);+ } else if (errors.length > 0) {+ for (const e of errors) {+ console.warn(`[openui] ${e.source}/${e.code}: ${e.message}`);+ }+ }+ }, [isStreaming, response, result, evaluatedResult, querySnapshot, library]);++ return { result: evaluatedResult, parseResult: result, contextValue, isQueryLoading };}diff --git a/packages/react-lang/src/hooks/useStateField.ts b/packages/react-lang/src/hooks/useStateField.tsnew file mode 100644index 000000000..ac0d4d2da--- /dev/null+++ b/packages/react-lang/src/hooks/useStateField.ts@@ -0,0 +1,23 @@+import {+ resolveStateField,+ type InferStateFieldValue,+ type StateField,+} from "@openuidev/lang-core";+import { useFormName, useOpenUI } from "../context";++export function useStateField<T = unknown>(+ name: string,+ value?: T,+): StateField<InferStateFieldValue<T>> {+ const ctx = useOpenUI();+ const formName = useFormName();++ return resolveStateField<InferStateFieldValue<T>>(+ name,+ value,+ ctx.store ?? null,+ ctx.evaluationContext ?? null,+ (fieldName) => ctx.getFieldValue(formName, fieldName),+ (fieldName, nextValue) => ctx.setFieldValue(formName, undefined, fieldName, nextValue),+ );+}diff --git a/packages/react-lang/src/index.ts b/packages/react-lang/src/index.tsindex 9ef8bdce5..abd445fc0 100644--- a/packages/react-lang/src/index.ts+++ b/packages/react-lang/src/index.ts@@ -9,6 +9,7 @@ export type {LibraryDefinition,PromptOptions,SubComponentOf,+ ToolDescriptor,} from "./library";// openui-lang renderer@@ -16,11 +17,25 @@ export { Renderer } from "./Renderer";export type { RendererProps } from "./Renderer";// openui-lang action types-export { BuiltinActionType } from "@openuidev/lang-core";-export type { ActionEvent, ElementNode, ParseResult } from "@openuidev/lang-core";+export { ACTION_STEPS, BuiltinActionType } from "@openuidev/lang-core";+export type {+ ActionEvent,+ ActionPlan,+ ActionStep,+ ElementNode,+ OpenUIError,+ ParseResult,+} from "@openuidev/lang-core";// openui-lang parser (server-side use)-export { createParser, createStreamingParser, type LibraryJSONSchema } from "@openuidev/lang-core";+export { createParser, createStreamingParser } from "@openuidev/lang-core";++// Standalone prompt generation (no Zod deps — usable on backend)+export { generatePrompt } from "@openuidev/lang-core";+export type { ComponentPromptSpec, PromptSpec, ToolSpec } from "@openuidev/lang-core";++// openui-lang edit/merge+export { mergeStatements } from "@openuidev/lang-core";// openui-lang context hooks (for use inside component renderers)export {@@ -34,6 +49,20 @@ export {useTriggerAction,} from "./context";+// Runtime — reactive bindings, store, evaluator, query manager, field binding+export { ToolNotFoundError, extractToolResult, isReactiveAssign } from "@openuidev/lang-core";+export type {+ EvaluationContext,+ McpClientLike,+ ReactiveAssign,+ StateField,+ ToolProvider,+} from "@openuidev/lang-core";+export { reactive } from "./runtime";++// Unified field state hook — component authors use this+export { useStateField } from "./hooks/useStateField";+// openui-lang form validationexport {FormValidationContext,diff --git a/packages/react-lang/src/library.ts b/packages/react-lang/src/library.tsindex e0cdc8109..2c64bc9b0 100644--- a/packages/react-lang/src/library.ts+++ b/packages/react-lang/src/library.ts@@ -10,7 +10,13 @@ import type { ReactNode } from "react";import { z } from "zod";// Re-export framework-agnostic types unchanged-export type { ComponentGroup, PromptOptions, SubComponentOf } from "@openuidev/lang-core";+export type {+ ComponentGroup,+ LibraryJSONSchema,+ PromptOptions,+ SubComponentOf,+ ToolDescriptor,+} from "@openuidev/lang-core";// ─── React-specific types ───────────────────────────────────────────────────@@ -30,29 +36,6 @@ export type LibraryDefinition = CoreLibraryDefinition<ComponentRenderer<any>>;// ─── defineComponent (React) ────────────────────────────────────────────────-/**- * Define a component with name, schema, description, and renderer.- * Registers the Zod schema globally and returns a `.ref` for parent schemas.- *- * @example- * ```ts- * const TabItem = defineComponent({- * name: "TabItem",- * props: z.object({ value: z.string(), trigger: z.string(), content: z.array(ContentChildUnion) }),- * description: "Tab panel",- * component: () => null,- * });- *- * const Tabs = defineComponent({- * name: "Tabs",- * props: z.object({ items: z.array(TabItem.ref) }),- * description: "Tabbed container",- * component: ({ props, renderNode }) => {- * props.items.map(item => renderNode(item.props.content));- * },- * });- * ```- */export function defineComponent<T extends z.ZodObject<any>>(config: {name: string;props: T;@@ -64,17 +47,6 @@ export function defineComponent<T extends z.ZodObject<any>>(config: {// ─── createLibrary (React) ──────────────────────────────────────────────────-/**- * Create a component library from an array of defined components.- *- * @example- * ```ts- * const library = createLibrary({- * components: [TabItem, Tabs, Card],- * root: "Card",- * });- * ```- */export function createLibrary(input: LibraryDefinition): Library {return coreCreateLibrary<ComponentRenderer<any>>(input) as Library;}diff --git a/packages/react-lang/src/runtime/index.ts b/packages/react-lang/src/runtime/index.tsnew file mode 100644index 000000000..b0f2bf762--- /dev/null+++ b/packages/react-lang/src/runtime/index.ts@@ -0,0 +1,2 @@+// React-specific reactive() wrapper — marks schemas for $binding support+export { isReactiveSchema, reactive } from "./reactive";diff --git a/packages/react-lang/src/runtime/reactive.ts b/packages/react-lang/src/runtime/reactive.tsnew file mode 100644index 000000000..1a149fc3f--- /dev/null+++ b/packages/react-lang/src/runtime/reactive.ts@@ -0,0 +1,21 @@+// ─────────────────────────────────────────────────────────────────────────────+// Reactive schema marker for openui-lang (React adapter)+// ─────────────────────────────────────────────────────────────────────────────++import type { StateField } from "@openuidev/lang-core";+import { markReactive } from "@openuidev/lang-core";+import type { z } from "zod";++// Re-export for internal use+export { isReactiveSchema } from "@openuidev/lang-core";++/**+ * Mark a schema prop as reactive so runtime evaluation can preserve $bindings.+ *+ * The widened return type carries the eventual value shape into helpers like+ * `useStateField()`. The actual bound value is still resolved at render time.+ */+export function reactive<T extends z.ZodType>(schema: T): z.ZodType<StateField<z.infer<T>>> {+ markReactive(schema);+ return schema as unknown as z.ZodType<StateField<z.infer<T>>>;+}diff --git a/packages/react-ui/package.json b/packages/react-ui/package.jsonindex 7e141f434..31f7c52f3 100644--- a/packages/react-ui/package.json+++ b/packages/react-ui/package.json@@ -2,7 +2,7 @@"type": "module","name": "@openuidev/react-ui","license": "MIT",- "version": "0.10.0",+ "version": "0.10.1","description": "Component library for Generative UI SDK","main": "dist/index.js","types": "dist/index.d.ts",diff --git a/packages/react-ui/src/components/Callout/Callout.tsx b/packages/react-ui/src/components/Callout/Callout.tsxindex 305e6905f..a6112e6db 100644--- a/packages/react-ui/src/components/Callout/Callout.tsx+++ b/packages/react-ui/src/components/Callout/Callout.tsx@@ -7,6 +7,8 @@ export interface CalloutProps extends Omit<React.HTMLAttributes<HTMLDivElement>,variant?: CalloutVariant;title?: React.ReactNode;description?: React.ReactNode;+ /** Auto-dismiss after N milliseconds. CSS-only fade + collapse. */+ duration?: number;}const variantMap: Record<CalloutVariant, string> = {@@ -18,10 +20,24 @@ const variantMap: Record<CalloutVariant, string> = {};export const Callout = React.forwardRef<HTMLDivElement, CalloutProps>((props, ref) => {- const { className, variant = "neutral", title, description, ...rest } = props;+ const { className, variant = "neutral", title, description, duration, style, ...rest } = props;++ const dismissStyle = duration+ ? ({ ...style, "--callout-duration": `${duration}ms` } as React.CSSProperties)+ : style;return (- <div ref={ref} className={clsx("openui-callout", variantMap[variant], className)} {...rest}>+ <div+ ref={ref}+ className={clsx(+ "openui-callout",+ variantMap[variant],+ duration && "openui-callout-autodismiss",+ className,+ )}+ style={dismissStyle}+ {...rest}+ >{title && <span className="openui-callout-title">{title}</span>}{description && <span className="openui-callout-description">{description}</span>}</div>diff --git a/packages/react-ui/src/components/Callout/callout.scss b/packages/react-ui/src/components/Callout/callout.scssindex 90fe6ba0f..3431be8bc 100644--- a/packages/react-ui/src/components/Callout/callout.scss+++ b/packages/react-ui/src/components/Callout/callout.scss@@ -51,4 +51,31 @@@include cssUtils.typography(body, default);color: cssUtils.$text-neutral-primary;}++ &-autodismiss {+ animation: openui-callout-fadeout 0.4s ease-in forwards;+ animation-delay: var(--callout-duration, 3000ms);+ }+}++@keyframes openui-callout-fadeout {+ 0% {+ opacity: 1;+ max-height: 200px;+ padding-top: cssUtils.$space-000;+ padding-bottom: cssUtils.$space-000;+ margin-bottom: 0;+ }+ 70% {+ opacity: 0;+ max-height: 200px;+ }+ 100% {+ opacity: 0;+ max-height: 0;+ padding-top: 0;+ padding-bottom: 0;+ margin-bottom: 0;+ overflow: hidden;+ }}diff --git a/packages/react-ui/src/components/Modal/Modal.scss b/packages/react-ui/src/components/Modal/Modal.scssnew file mode 100644index 000000000..f6a857b98--- /dev/null+++ b/packages/react-ui/src/components/Modal/Modal.scss@@ -0,0 +1,117 @@+@use "../../cssUtils" as cssUtils;++.openui-modal-root {+ position: relative;+ z-index: 9999;+}++.openui-modal-overlay {+ position: fixed;+ inset: 0;+ background: cssUtils.$overlay;+ z-index: 9999;+ animation: openui-modal-fade-in 0.15s ease-out;+}++.openui-modal-content {+ position: fixed;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ z-index: 10000;+ background: cssUtils.$foreground;+ border: 1px solid cssUtils.$border-default;+ border-radius: 12px;+ box-shadow: 0 16px 48px rgba(0, 0, 0, 0.2);+ display: flex;+ flex-direction: column;+ max-height: 85vh;+ animation: openui-modal-slide-in 0.15s ease-out;++ &:focus {+ outline: none;+ }+}++.openui-modal-sm {+ width: 400px;+ max-width: 90vw;+}+.openui-modal-md {+ width: 560px;+ max-width: 90vw;+}+.openui-modal-lg {+ width: 720px;+ max-width: 90vw;+}++.openui-modal-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: cssUtils.$space-m;+ border-bottom: 1px solid cssUtils.$border-default;+}++.openui-modal-title {+ @include cssUtils.typography(body, heavy);+ margin: 0;+}++.openui-modal-close {+ all: unset;+ cursor: pointer;+ display: flex;+ align-items: center;+ justify-content: center;+ width: 28px;+ height: 28px;+ border-radius: 6px;+ color: cssUtils.$text-neutral-secondary;++ &:hover {+ color: cssUtils.$text-neutral-primary;+ }+}++.openui-modal-body {+ padding: cssUtils.$space-m;+ overflow-y: auto;+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: cssUtils.$space-m;+}++.openui-modal-sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+}++@keyframes openui-modal-fade-in {+ from {+ opacity: 0;+ }+ to {+ opacity: 1;+ }+}++@keyframes openui-modal-slide-in {+ from {+ opacity: 0;+ transform: translate(-50%, -48%);+ }+ to {+ opacity: 1;+ transform: translate(-50%, -50%);+ }+}diff --git a/packages/react-ui/src/components/Modal/Modal.tsx b/packages/react-ui/src/components/Modal/Modal.tsxnew file mode 100644index 000000000..2f8df2916--- /dev/null+++ b/packages/react-ui/src/components/Modal/Modal.tsx@@ -0,0 +1,76 @@+"use client";++import clsx from "clsx";+import { X } from "lucide-react";+import React, { useCallback, useEffect, useRef } from "react";+import { createPortal } from "react-dom";+import { useTheme } from "../ThemeProvider";++export interface ModalProps {+ title: string;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ size?: "sm" | "md" | "lg";+ children?: React.ReactNode;+}++const sizeClass: Record<string, string> = {+ sm: "openui-modal-sm",+ md: "openui-modal-md",+ lg: "openui-modal-lg",+};++export const Modal: React.FC<ModalProps> = ({+ title,+ open,+ onOpenChange,+ size = "md",+ children,+}) => {+ const { portalThemeClassName } = useTheme();+ const contentRef = useRef<HTMLDivElement>(null);++ const handleClose = useCallback(() => onOpenChange(false), [onOpenChange]);++ // Escape key+ useEffect(() => {+ if (!open) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape") handleClose();+ };+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ }, [open, handleClose]);++ // Focus trap — focus the content on open+ useEffect(() => {+ if (open && contentRef.current) {+ contentRef.current.focus();+ }+ }, [open]);++ if (!open) return null;++ return createPortal(+ <div className={clsx("openui-modal-root", portalThemeClassName)}>+ <div className="openui-modal-overlay" onClick={handleClose} />+ <div+ ref={contentRef}+ className={clsx("openui-modal-content", sizeClass[size])}+ role="dialog"+ aria-modal="true"+ aria-label={title}+ tabIndex={-1}+ >+ <div className="openui-modal-header">+ <h2 className="openui-modal-title">{title}</h2>+ <button className="openui-modal-close" aria-label="Close" onClick={handleClose}>+ <X size={18} />+ </button>+ </div>+ <div className="openui-modal-body">{children}</div>+ </div>+ </div>,+ document.body,+ );+};diff --git a/packages/react-ui/src/components/Modal/index.ts b/packages/react-ui/src/components/Modal/index.tsnew file mode 100644index 000000000..1ae2df910--- /dev/null+++ b/packages/react-ui/src/components/Modal/index.ts@@ -0,0 +1,2 @@+export { Modal } from "./Modal";+export type { ModalProps } from "./Modal";diff --git a/packages/react-ui/src/components/Select/select.scss b/packages/react-ui/src/components/Select/select.scssindex ebc2979d0..a596ecb65 100644--- a/packages/react-ui/src/components/Select/select.scss+++ b/packages/react-ui/src/components/Select/select.scss@@ -66,7 +66,7 @@.openui-select-content {box-sizing: border-box;position: relative;- z-index: 50;+ z-index: 99999;max-height: 372px;min-width: var(--radix-select-trigger-width);overflow: hidden;diff --git a/packages/react-ui/src/components/index.scss b/packages/react-ui/src/components/index.scssindex e2d3d5808..661dc1456 100644--- a/packages/react-ui/src/components/index.scss+++ b/packages/react-ui/src/components/index.scss@@ -56,3 +56,4 @@@forward "./ToolCall/toolCall.scss";@forward "./ToolResult/toolResult.scss";@forward "./_shared/shared.scss";+@forward "./Modal/Modal.scss";diff --git a/packages/react-ui/src/genui-lib/Action/schema.ts b/packages/react-ui/src/genui-lib/Action/schema.tsindex 84b2d6b74..038b85ec5 100644--- a/packages/react-ui/src/genui-lib/Action/schema.ts+++ b/packages/react-ui/src/genui-lib/Action/schema.ts@@ -1,24 +1,5 @@-import { BuiltinActionType } from "@openuidev/react-lang";import { z } from "zod";-const continueConversationAction = z.object({- type: z.literal(BuiltinActionType.ContinueConversation),- /** Extra context string passed to the LLM — useful for carousel/list item data. */- context: z.string().optional(),-});--const openUrlAction = z.object({- type: z.literal(BuiltinActionType.OpenUrl),- url: z.string(),-});--const customAction = z.object({- type: z.string(),- params: z.record(z.string(), z.any()).optional(),-});--export const actionSchema = z- .union([openUrlAction, continueConversationAction, customAction])- .optional();--export type ActionSchema = z.infer<typeof actionSchema>;+/** Shared action prop schema — shows as `ActionExpression` in prompt signatures. */+export const actionPropSchema = z.any();+actionPropSchema.register(z.globalRegistry, { id: "ActionExpression" });diff --git a/packages/react-ui/src/genui-lib/Button/index.tsx b/packages/react-ui/src/genui-lib/Button/index.tsxindex f3090d4b7..6f2023a63 100644--- a/packages/react-ui/src/genui-lib/Button/index.tsx+++ b/packages/react-ui/src/genui-lib/Button/index.tsx@@ -1,7 +1,8 @@"use client";+import type { ActionPlan } from "@openuidev/react-lang";import {- BuiltinActionType,+ ACTION_STEPS,defineComponent,useFormName,useFormValidation,@@ -38,33 +39,22 @@ export const Button = defineComponent({buttonType={props.type as "normal" | "destructive"}disabled={isStreaming}onClick={() => {- const action = props.action as- | { type?: string; url?: string; context?: string; params?: Record<string, any> }- | undefined;- const actionType = action?.type ?? BuiltinActionType.ContinueConversation;+ const action = props.action as ActionPlan | undefined;- // Only validate for primary buttons with continue_conversation action (form submit).- // Secondary/tertiary buttons (e.g. "Ask to customize") skip validation.- const variant = (props.variant as string) || "primary";- if (- formValidation &&- variant === "primary" &&- actionType === BuiltinActionType.ContinueConversation- ) {- const valid = formValidation.validateForm();- if (!valid) return;+ // Validate form for primary buttons with mutation/ToAssistant steps+ if (action?.steps && formValidation) {+ const variant = (props.variant as string) || "primary";+ if (variant === "primary") {+ const needsValidation = action.steps.some(+ (s) =>+ s.type === ACTION_STEPS.ToAssistant ||+ (s.type === ACTION_STEPS.Run && s.refType === "mutation"),+ );+ if (needsValidation && !formValidation.validateForm()) return;+ }}- const actionParams =- actionType === BuiltinActionType.OpenUrl- ? { url: action?.url }- : {- ...(action?.params ?? {}),- ...(action?.context ? { context: action.context } : {}),- };- triggerAction(label, formName, {- type: actionType,- params: actionParams,- });++ triggerAction(label, formName, action);}}>{label}diff --git a/packages/react-ui/src/genui-lib/Button/schema.ts b/packages/react-ui/src/genui-lib/Button/schema.tsindex 1d012a5f1..aeb67c970 100644--- a/packages/react-ui/src/genui-lib/Button/schema.ts+++ b/packages/react-ui/src/genui-lib/Button/schema.ts@@ -1,11 +1,9 @@import { z } from "zod";-import { actionSchema } from "../Action/schema";--export { actionSchema, type ActionSchema } from "../Action/schema";+import { actionPropSchema } from "../Action/schema";export const ButtonSchema = z.object({label: z.string(),- action: actionSchema,+ action: actionPropSchema.optional(),variant: z.enum(["primary", "secondary", "tertiary"]).optional(),type: z.enum(["normal", "destructive"]).optional(),size: z.enum(["extra-small", "small", "medium", "large"]).optional(),diff --git a/packages/react-ui/src/genui-lib/Callout/index.tsx b/packages/react-ui/src/genui-lib/Callout/index.tsxindex c736c9e40..8f338af02 100644--- a/packages/react-ui/src/genui-lib/Callout/index.tsx+++ b/packages/react-ui/src/genui-lib/Callout/index.tsx@@ -1,6 +1,7 @@"use client";-import { defineComponent } from "@openuidev/react-lang";+import { defineComponent, useStateField } from "@openuidev/react-lang";+import React from "react";import { Callout as OpenUICallout } from "../../components/Callout";import { MarkDownRenderer } from "../../components/MarkDownRenderer";import { CalloutSchema } from "./schema";@@ -10,8 +11,27 @@ export { CalloutSchema } from "./schema";export const Callout = defineComponent({name: "Callout",props: CalloutSchema,- description: "Callout banner with variant, title, and description",+ description:+ "Callout banner. Optional visible is a reactive $boolean — auto-dismisses after 3s by setting $visible to false.",component: ({ props }) => {+ const field = useStateField("visible", props.visible);++ const hasVisibleBinding = field.isReactive;+ const isVisible = hasVisibleBinding+ ? field.value === true || (field.value as any) === "true"+ : true;++ // Auto-dismiss: set $visible = false after 3s+ React.useEffect(() => {+ if (!hasVisibleBinding || !isVisible) return;+ const timer = setTimeout(() => {+ field.setValue(false);+ }, 3000);+ return () => clearTimeout(timer);+ }, [hasVisibleBinding, isVisible, field]);++ if (!isVisible) return null;+const variantMap: Record<string, "neutral" | "info" | "warning" | "success"> = {info: "info",warning: "warning",@@ -24,6 +44,7 @@ export const Callout = defineComponent({variant={variantMap[props.variant as string] || "info"}title={props.title as string}description={<MarkDownRenderer textMarkdown={props.description as string} />}+ duration={hasVisibleBinding ? 3000 : undefined}/>);},diff --git a/packages/react-ui/src/genui-lib/Callout/schema.ts b/packages/react-ui/src/genui-lib/Callout/schema.tsindex a21791c53..eb85448b8 100644--- a/packages/react-ui/src/genui-lib/Callout/schema.ts+++ b/packages/react-ui/src/genui-lib/Callout/schema.ts@@ -1,7 +1,9 @@+import { reactive } from "@openuidev/react-lang";import { z } from "zod";export const CalloutSchema = z.object({variant: z.enum(["info", "warning", "error", "success", "neutral"]),title: z.string(),description: z.string(),+ visible: reactive(z.boolean().optional()),});diff --git a/packages/react-ui/src/genui-lib/Charts/PieChart.ts b/packages/react-ui/src/genui-lib/Charts/PieChart.tsindex 71feb636d..a98c9da2f 100644--- a/packages/react-ui/src/genui-lib/Charts/PieChart.ts+++ b/packages/react-ui/src/genui-lib/Charts/PieChart.ts@@ -4,28 +4,50 @@ import { defineComponent } from "@openuidev/react-lang";import React from "react";import { z } from "zod";import { PieChart as PieChartComponent } from "../../components/Charts";-import { buildSliceData, hasAllProps } from "../helpers";-import { SliceSchema } from "./Slice";+import { asArray, buildSliceData } from "../helpers";export const PieChartSchema = z.object({- slices: z.array(SliceSchema),+ labels: z.array(z.string()),+ values: z.array(z.number()),variant: z.enum(["pie", "donut"]).optional(),});export const PieChart = defineComponent({name: "PieChart",props: PieChartSchema,- description: "Circular slices showing part-to-whole proportions; supports pie and donut variants",+ description: "Circular slices; use plucked arrays: PieChart(data.categories, data.values)",component: ({ props }) => {- if (!hasAllProps(props as Record<string, unknown>, "slices")) return null;- const data = buildSliceData(props.slices);- if (!data.length) return null;- return React.createElement(PieChartComponent, {- data,- categoryKey: "category",- dataKey: "value",- variant: props.variant as "pie" | "donut" | undefined,- isAnimationActive: false,- });+ const labels = asArray(props.labels) as string[];+ const values = asArray(props.values) as number[];++ // New format: labels[] + values[]+ if (labels.length > 0 && values.length > 0) {+ const data = labels.map((cat, i) => ({+ category: cat,+ value: typeof values[i] === "number" ? values[i] : 0,+ }));+ if (!data.length) return null;+ return React.createElement(PieChartComponent, {+ data,+ categoryKey: "category",+ dataKey: "value",+ variant: props.variant as "pie" | "donut" | undefined,+ isAnimationActive: false,+ });+ }++ // Legacy fallback: Slice[] objects (backwards compat)+ const sliceData = buildSliceData(props.labels);+ if (sliceData.length) {+ return React.createElement(PieChartComponent, {+ data: sliceData,+ categoryKey: "category",+ dataKey: "value",+ variant: props.variant as "pie" | "donut" | undefined,+ isAnimationActive: false,+ });+ }++ return null;},});diff --git a/packages/react-ui/src/genui-lib/Charts/RadialChart.ts b/packages/react-ui/src/genui-lib/Charts/RadialChart.tsindex 31f0da5fb..d76801f0a 100644--- a/packages/react-ui/src/genui-lib/Charts/RadialChart.ts+++ b/packages/react-ui/src/genui-lib/Charts/RadialChart.ts@@ -4,26 +4,45 @@ import { defineComponent } from "@openuidev/react-lang";import React from "react";import { z } from "zod";import { RadialChart as RadialChartComponent } from "../../components/Charts";-import { buildSliceData, hasAllProps } from "../helpers";-import { SliceSchema } from "./Slice";+import { asArray, buildSliceData } from "../helpers";export const RadialChartSchema = z.object({- slices: z.array(SliceSchema),+ labels: z.array(z.string()),+ values: z.array(z.number()),});export const RadialChart = defineComponent({name: "RadialChart",props: RadialChartSchema,- description: "Radial bars showing proportional distribution across named segments",+ description: "Radial bars; use plucked arrays: RadialChart(data.categories, data.values)",component: ({ props }) => {- if (!hasAllProps(props as Record<string, unknown>, "slices")) return null;- const data = buildSliceData((props as any).slices);- if (!data.length) return null;- return React.createElement(RadialChartComponent, {- data,- categoryKey: "category",- dataKey: "value",- isAnimationActive: false,- });+ const labels = asArray(props.labels) as string[];+ const values = asArray(props.values) as number[];++ if (labels.length > 0 && values.length > 0) {+ const data = labels.map((cat, i) => ({+ category: cat,+ value: typeof values[i] === "number" ? values[i] : 0,+ }));+ if (!data.length) return null;+ return React.createElement(RadialChartComponent, {+ data,+ categoryKey: "category",+ dataKey: "value",+ isAnimationActive: false,+ });+ }++ const sliceData = buildSliceData(props.labels);+ if (sliceData.length) {+ return React.createElement(RadialChartComponent, {+ data: sliceData,+ categoryKey: "category",+ dataKey: "value",+ isAnimationActive: false,+ });+ }++ return null;},});diff --git a/packages/react-ui/src/genui-lib/Charts/SingleStackedBarChart.ts b/packages/react-ui/src/genui-lib/Charts/SingleStackedBarChart.tsindex a1a049b91..3712efdfc 100644--- a/packages/react-ui/src/genui-lib/Charts/SingleStackedBarChart.ts+++ b/packages/react-ui/src/genui-lib/Charts/SingleStackedBarChart.ts@@ -4,26 +4,44 @@ import { defineComponent } from "@openuidev/react-lang";import React from "react";import { z } from "zod";import { SingleStackedBar as SingleStackedBarChartComponent } from "../../components/Charts";-import { buildSliceData, hasAllProps } from "../helpers";-import { SliceSchema } from "./Slice";+import { asArray, buildSliceData } from "../helpers";export const SingleStackedBarChartSchema = z.object({- slices: z.array(SliceSchema),+ labels: z.array(z.string()),+ values: z.array(z.number()),});export const SingleStackedBarChart = defineComponent({name: "SingleStackedBarChart",props: SingleStackedBarChartSchema,description:- "Single horizontal stacked bar; use for showing part-to-whole proportions in one row",+ "Single horizontal stacked bar; use plucked arrays: SingleStackedBarChart(data.categories, data.values)",component: ({ props }) => {- if (!hasAllProps(props as Record<string, unknown>, "slices")) return null;- const data = buildSliceData((props as any).slices);- if (!data.length) return null;- return React.createElement(SingleStackedBarChartComponent, {- data,- categoryKey: "category",- dataKey: "value",- });+ const labels = asArray(props.labels) as string[];+ const values = asArray(props.values) as number[];++ if (labels.length > 0 && values.length > 0) {+ const data = labels.map((cat, i) => ({+ category: cat,+ value: typeof values[i] === "number" ? values[i] : 0,+ }));+ if (!data.length) return null;+ return React.createElement(SingleStackedBarChartComponent, {+ data,+ categoryKey: "category",+ dataKey: "value",+ });+ }++ const sliceData = buildSliceData(props.labels);+ if (sliceData.length) {+ return React.createElement(SingleStackedBarChartComponent, {+ data: sliceData,+ categoryKey: "category",+ dataKey: "value",+ });+ }++ return null;},});diff --git a/packages/react-ui/src/genui-lib/CheckBoxGroup/index.tsx b/packages/react-ui/src/genui-lib/CheckBoxGroup/index.tsxindex 61d6af5af..7e32f427c 100644--- a/packages/react-ui/src/genui-lib/CheckBoxGroup/index.tsx+++ b/packages/react-ui/src/genui-lib/CheckBoxGroup/index.tsx@@ -3,19 +3,15 @@import {defineComponent,parseStructuredRules,- useFormName,useFormValidation,- useGetFieldValue,useIsStreaming,- useSetFieldValue,+ useStateField,type SubComponentOf,} from "@openuidev/react-lang";import React from "react";-import { z } from "zod";import { CheckBoxGroup as OpenUICheckBoxGroup } from "../../components/CheckBoxGroup";import { CheckBoxItem as OpenUICheckBoxItem } from "../../components/CheckBoxItem";-import { rulesSchema } from "../rules";-import { CheckBoxItemSchema } from "./schema";+import { CheckBoxItemSchema, createCheckBoxGroupSchema } from "./schema";export { CheckBoxItemSchema } from "./schema";@@ -35,49 +31,34 @@ export const CheckBoxItem = defineComponent({export const CheckBoxGroup = defineComponent({name: "CheckBoxGroup",- props: z.object({- name: z.string(),- items: z.array(CheckBoxItem.ref),- rules: rulesSchema,- }),+ props: createCheckBoxGroupSchema(CheckBoxItem),description: "",component: ({ props }) => {- const formName = useFormName();- const getFieldValue = useGetFieldValue();- const setFieldValue = useSetFieldValue();const isStreaming = useIsStreaming();const formValidation = useFormValidation();- const fieldName = props.name as string;+ const field = useStateField(props.name, props.value);const rules = React.useMemo(() => parseStructuredRules(props.rules), [props.rules]);+ const hasRules = rules.length > 0;const items = (props.items ?? []) as Array<SubComponentOf<CheckBoxItemProps>>;+ // Aggregate: map of item name → checked booleanconst getAggregate = React.useCallback((): Record<string, boolean> => {- const stored = getFieldValue(formName, fieldName) as Record<string, boolean> | undefined;+ const stored = field.value;const result: Record<string, boolean> = {};for (const item of items) {result[item.props.name] = stored?.[item.props.name] ?? item.props.defaultChecked ?? false;}return result;- }, [formName, fieldName, items, getFieldValue]);+ }, [field.value, items]);React.useEffect(() => {- if (!isStreaming && items.length > 0 && getFieldValue(formName, fieldName) == null) {- const initial: Record<string, boolean> = {};- for (const item of items) {- initial[item.props.name] = item.props.defaultChecked ?? false;- }- setFieldValue(formName, "CheckBoxGroup", fieldName, initial, false);- }- }, [isStreaming]);-- React.useEffect(() => {- if (!isStreaming && rules.length > 0 && formValidation) {- formValidation.registerField(fieldName, rules, () => getFieldValue(formName, fieldName));- return () => formValidation.unregisterField(fieldName);+ if (!isStreaming && hasRules && formValidation) {+ formValidation.registerField(field.name, rules, () => field.value);+ return () => formValidation.unregisterField(field.name);}return undefined;- }, [isStreaming, rules.length > 0]);+ }, [field.name, field.value, formValidation, hasRules, isStreaming, rules]);if (!items.length) return null;@@ -94,9 +75,9 @@ export const CheckBoxGroup = defineComponent({checked={aggregate[item.props.name] ?? item.props.defaultChecked ?? false}onChange={(val: boolean) => {const newAggregate = { ...getAggregate(), [item.props.name]: val };- setFieldValue(formName, "CheckBoxGroup", fieldName, newAggregate, true);- if (rules.length > 0) {- formValidation?.validateField(fieldName, newAggregate, rules);+ field.setValue(newAggregate);+ if (hasRules) {+ formValidation?.validateField(field.name, newAggregate, rules);}}}disabled={isStreaming}diff --git a/packages/react-ui/src/genui-lib/CheckBoxGroup/schema.ts b/packages/react-ui/src/genui-lib/CheckBoxGroup/schema.tsindex f02dc15af..3b1b87a26 100644--- a/packages/react-ui/src/genui-lib/CheckBoxGroup/schema.ts+++ b/packages/react-ui/src/genui-lib/CheckBoxGroup/schema.ts@@ -1,6 +1,9 @@+import { reactive } from "@openuidev/react-lang";import { z } from "zod";import { rulesSchema } from "../rules";+type RefComponent = { ref: z.ZodTypeAny };+export const CheckBoxItemSchema = z.object({label: z.string(),description: z.string(),@@ -8,8 +11,11 @@ export const CheckBoxItemSchema = z.object({defaultChecked: z.boolean().optional(),});-export const CheckBoxGroupSchema = z.object({- name: z.string(),- items: z.array(z.any()), // filled by CheckBoxItem.ref in index- rules: rulesSchema,-});+export function createCheckBoxGroupSchema(CheckBoxItem: RefComponent) {+ return z.object({+ name: z.string(),+ items: z.array(CheckBoxItem.ref),+ rules: rulesSchema,+ value: reactive(z.record(z.string(), z.boolean()).optional()),+ });+}diff --git a/packages/react-ui/src/genui-lib/DatePicker/index.tsx b/packages/react-ui/src/genui-lib/DatePicker/index.tsxindex 0bc27f41e..3ce388cb7 100644--- a/packages/react-ui/src/genui-lib/DatePicker/index.tsx+++ b/packages/react-ui/src/genui-lib/DatePicker/index.tsx@@ -3,11 +3,9 @@import {defineComponent,parseStructuredRules,- useFormName,useFormValidation,- useGetFieldValue,useIsStreaming,- useSetFieldValue,+ useStateField,} from "@openuidev/react-lang";import React from "react";import { DatePicker as OpenUIDatePicker } from "../../components/DatePicker";@@ -20,29 +18,26 @@ export const DatePicker = defineComponent({props: DatePickerSchema,description: "",component: ({ props }) => {- const formName = useFormName();- const getFieldValue = useGetFieldValue();- const setFieldValue = useSetFieldValue();const isStreaming = useIsStreaming();const formValidation = useFormValidation();- const fieldName = (props.name as string) || "date";+ const field = useStateField(props.name, props.value);const mode = (props.mode as "single" | "range") || "single";const rules = React.useMemo(() => parseStructuredRules(props.rules), [props.rules]);- const value = getFieldValue(formName, fieldName);+ const hasRules = rules.length > 0;React.useEffect(() => {- if (!isStreaming && rules.length > 0 && formValidation) {- formValidation.registerField(fieldName, rules, () => getFieldValue(formName, fieldName));- return () => formValidation.unregisterField(fieldName);+ if (!isStreaming && hasRules && formValidation) {+ formValidation.registerField(field.name, rules, () => field.value);+ return () => formValidation.unregisterField(field.name);}return undefined;- }, [isStreaming, rules.length > 0]);+ }, [field.name, field.value, formValidation, hasRules, isStreaming, rules]);const handleChange = (val: unknown) => {- setFieldValue(formName, "DatePicker", fieldName, val, true);- if (rules.length > 0) {- formValidation?.validateField(fieldName, val, rules);+ field.setValue(val);+ if (hasRules) {+ formValidation?.validateField(field.name, val, rules);}};@@ -50,7 +45,7 @@ export const DatePicker = defineComponent({return (<OpenUIDatePickermode="range"- selectedRangeDates={value}+ selectedRangeDates={field.value as any}setSelectedRangeDates={handleChange}/>);@@ -59,7 +54,7 @@ export const DatePicker = defineComponent({return (<OpenUIDatePickermode="single"- selectedSingleDate={value}+ selectedSingleDate={field.value as any}setSelectedSingleDate={handleChange}/>);diff --git a/packages/react-ui/src/genui-lib/DatePicker/schema.ts b/packages/react-ui/src/genui-lib/DatePicker/schema.tsindex f3ff46773..844c59389 100644--- a/packages/react-ui/src/genui-lib/DatePicker/schema.ts+++ b/packages/react-ui/src/genui-lib/DatePicker/schema.ts@@ -1,8 +1,10 @@+import { reactive } from "@openuidev/react-lang";import { z } from "zod";import { rulesSchema } from "../rules";export const DatePickerSchema = z.object({name: z.string(),- mode: z.enum(["single", "range"]),+ mode: z.enum(["single", "range"]).optional(),rules: rulesSchema,+ value: reactive(z.unknown().optional()),});diff --git a/packages/react-ui/src/genui-lib/FormControl/index.tsx b/packages/react-ui/src/genui-lib/FormControl/index.tsxindex de2b358b5..f18aaa82d 100644--- a/packages/react-ui/src/genui-lib/FormControl/index.tsx+++ b/packages/react-ui/src/genui-lib/FormControl/index.tsx@@ -16,8 +16,10 @@ export const FormControl = defineComponent({component: ({ props, renderNode }) => {const formValidation = useFormValidation();const inputObj = props.input as any;+ // Extract the field name from the rendered input element props.+ const rawName = inputObj?.type === "element" ? inputObj.props?.name : undefined;const fieldName =- inputObj?.type === "element" ? (inputObj.props?.name as string | undefined) : undefined;+ typeof rawName === "object" && rawName?.name ? rawName.name : (rawName as string | undefined);const error = fieldName ? formValidation?.errors[fieldName] : undefined;const isRequired = inputObj?.type === "element" && inputObj.props?.rules?.required === true;diff --git a/packages/react-ui/src/genui-lib/Input/index.tsx b/packages/react-ui/src/genui-lib/Input/index.tsxindex a9c0b10f9..fa4b4e098 100644--- a/packages/react-ui/src/genui-lib/Input/index.tsx+++ b/packages/react-ui/src/genui-lib/Input/index.tsx@@ -3,11 +3,9 @@import {defineComponent,parseStructuredRules,- useFormName,useFormValidation,- useGetFieldValue,useIsStreaming,- useSetFieldValue,+ useStateField,} from "@openuidev/react-lang";import React from "react";import { Input as OpenUIInput } from "../../components/Input";@@ -20,39 +18,39 @@ export const Input = defineComponent({props: InputSchema,description: "",component: ({ props }) => {- const formName = useFormName();- const getFieldValue = useGetFieldValue();- const setFieldValue = useSetFieldValue();const isStreaming = useIsStreaming();const formValidation = useFormValidation();- const fieldName = props.name as string;+ const field = useStateField(props.name, props.value);const rules = React.useMemo(() => parseStructuredRules(props.rules), [props.rules]);- const savedValue = getFieldValue(formName, fieldName) ?? "";+ const hasRules = rules.length > 0;React.useEffect(() => {- if (!isStreaming && rules.length > 0 && formValidation) {- formValidation.registerField(fieldName, rules, () => getFieldValue(formName, fieldName));- return () => formValidation.unregisterField(fieldName);+ if (!isStreaming && hasRules && formValidation) {+ formValidation.registerField(field.name, rules, () => field.value);+ return () => formValidation.unregisterField(field.name);}return undefined;- }, [isStreaming, rules.length > 0]);+ }, [field.name, field.value, formValidation, hasRules, isStreaming, rules]);return (<OpenUIInput- id={fieldName}- name={fieldName}+ id={field.name}+ name={field.name}placeholder={(props.placeholder as string) || ""}type={(props.type as string) || "text"}- defaultValue={savedValue}- onFocus={() => formValidation?.clearFieldError(fieldName)}- onBlur={(e: React.FocusEvent<HTMLInputElement>) => {+ value={field.value ?? ""}+ onFocus={() => formValidation?.clearFieldError(field.name)}+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => {const val = e.target.value;- if (val !== savedValue) {- setFieldValue(formName, "Input", fieldName, val, true);+ field.setValue(val);+ if (hasRules) {+ formValidation?.clearFieldError(field.name);}- if (rules.length > 0) {- formValidation?.validateField(fieldName, val, rules);+ }}+ onBlur={(e: React.FocusEvent<HTMLInputElement>) => {+ if (hasRules) {+ formValidation?.validateField(field.name, e.target.value, rules);}}}disabled={isStreaming}diff --git a/packages/react-ui/src/genui-lib/Input/schema.ts b/packages/react-ui/src/genui-lib/Input/schema.tsindex 948938a86..c496ac738 100644--- a/packages/react-ui/src/genui-lib/Input/schema.ts+++ b/packages/react-ui/src/genui-lib/Input/schema.ts@@ -1,3 +1,4 @@+import { reactive } from "@openuidev/react-lang";import { z } from "zod";import { rulesSchema } from "../rules";@@ -6,4 +7,5 @@ export const InputSchema = z.object({placeholder: z.string().optional(),type: z.enum(["text", "email", "password", "number", "url"]).optional(),rules: rulesSchema,+ value: reactive(z.string().optional()),});diff --git a/packages/react-ui/src/genui-lib/ListBlock/index.tsx b/packages/react-ui/src/genui-lib/ListBlock/index.tsxindex e3f581b99..275f00e22 100644--- a/packages/react-ui/src/genui-lib/ListBlock/index.tsx+++ b/packages/react-ui/src/genui-lib/ListBlock/index.tsx@@ -1,11 +1,11 @@"use client";-import { BuiltinActionType, defineComponent, useTriggerAction } from "@openuidev/react-lang";+import type { ActionPlan } from "@openuidev/react-lang";+import { defineComponent, useTriggerAction } from "@openuidev/react-lang";import { ChevronRight } from "lucide-react";import { z } from "zod";import { ListBlock as OpenUIListBlock } from "../../components/ListBlock";import { ListItem as OpenUIListItem } from "../../components/ListItem";-import { ActionSchema } from "../Action/schema";import { ListItem } from "../ListItem";export const ListBlock = defineComponent({@@ -29,24 +29,11 @@ export const ListBlock = defineComponent({const subtitle = item?.props?.subtitle ? String(item.props.subtitle) : undefined;const image = item?.props?.image as { src: string; alt: string } | undefined;const actionLabel = item?.props?.actionLabel ? String(item.props.actionLabel) : undefined;- const action = item?.props?.action as ActionSchema;+ const action = item?.props?.action;const hasAction = !!action;const handleClick = hasAction- ? () => {- const actionType = action.type ?? BuiltinActionType.ContinueConversation;- const actionParams =- actionType === BuiltinActionType.OpenUrl- ? { url: (action as any).url }- : {- ...((action as any).params ?? {}),- ...((action as any).context ? { context: (action as any).context } : {}),- };- triggerAction(title, undefined, {- type: actionType,- params: actionParams,- });- }+ ? () => triggerAction(title, undefined, action as ActionPlan | undefined): undefined;return (diff --git a/packages/react-ui/src/genui-lib/ListItem/index.tsx b/packages/react-ui/src/genui-lib/ListItem/index.tsxindex 92229b3a9..7ec9d0be3 100644--- a/packages/react-ui/src/genui-lib/ListItem/index.tsx+++ b/packages/react-ui/src/genui-lib/ListItem/index.tsx@@ -2,7 +2,7 @@import { defineComponent } from "@openuidev/react-lang";import { z } from "zod";-import { actionSchema } from "../Action/schema";+import { actionPropSchema } from "../Action/schema";export const ListItem = defineComponent({name: "ListItem",@@ -16,7 +16,7 @@ export const ListItem = defineComponent({}).optional(),actionLabel: z.string().optional(),- action: actionSchema,+ action: actionPropSchema.optional(),}),description:"Item in a ListBlock — displays a title with an optional subtitle and image. When action is provided, the item becomes clickable.",diff --git a/packages/react-ui/src/genui-lib/Modal/index.tsx b/packages/react-ui/src/genui-lib/Modal/index.tsxnew file mode 100644index 000000000..f32668622--- /dev/null+++ b/packages/react-ui/src/genui-lib/Modal/index.tsx@@ -0,0 +1,36 @@+"use client";++import { defineComponent, useStateField } from "@openuidev/react-lang";+import { Modal as OpenUIModal } from "../../components/Modal";+import { ModalSchema } from "./schema";++export { ModalSchema } from "./schema";++export const Modal = defineComponent({+ name: "Modal",+ props: ModalSchema,+ description:+ "Modal dialog. open is a reactive $boolean binding — set to true to open, X/Escape/backdrop auto-closes. Put Form with buttons inside children.",+ component: ({ props, renderNode }) => {+ const field = useStateField("open", props.open);++ const isOpen = field.value === true || (field.value as any) === "true";++ const handleOpenChange = (open: boolean) => {+ if (!open) {+ field.setValue(false);+ }+ };++ return (+ <OpenUIModal+ title={props.title as string}+ open={isOpen}+ onOpenChange={handleOpenChange}+ size={(props.size as "sm" | "md" | "lg") ?? "md"}+ >+ {renderNode(props.children)}+ </OpenUIModal>+ );+ },+});diff --git a/packages/react-ui/src/genui-lib/Modal/schema.ts b/packages/react-ui/src/genui-lib/Modal/schema.tsnew file mode 100644index 000000000..3e6cd70bd--- /dev/null+++ b/packages/react-ui/src/genui-lib/Modal/schema.ts@@ -0,0 +1,10 @@+import { reactive } from "@openuidev/react-lang";+import { z } from "zod";+import { ContentChildUnion } from "../unions";++export const ModalSchema = z.object({+ title: z.string(),+ open: reactive(z.boolean().optional()),+ children: z.array(ContentChildUnion),+ size: z.enum(["sm", "md", "lg"]).optional(),+});diff --git a/packages/react-ui/src/genui-lib/RadioGroup/index.tsx b/packages/react-ui/src/genui-lib/RadioGroup/index.tsxindex 67b9896e7..92f4075c5 100644--- a/packages/react-ui/src/genui-lib/RadioGroup/index.tsx+++ b/packages/react-ui/src/genui-lib/RadioGroup/index.tsx@@ -3,11 +3,10 @@import {defineComponent,parseStructuredRules,- useFormName,+ reactive,useFormValidation,- useGetFieldValue,useIsStreaming,- useSetFieldValue,+ useStateField,} from "@openuidev/react-lang";import React from "react";import { z } from "zod";@@ -32,51 +31,40 @@ export const RadioGroup = defineComponent({items: z.array(RadioItem.ref),defaultValue: z.string().optional(),rules: rulesSchema,+ value: reactive(z.string().optional()),}),description: "",component: ({ props }) => {- const formName = useFormName();- const getFieldValue = useGetFieldValue();- const setFieldValue = useSetFieldValue();const isStreaming = useIsStreaming();const formValidation = useFormValidation();- const fieldName = props.name as string;+ const field = useStateField(props.name, props.value);const rules = React.useMemo(() => parseStructuredRules(props.rules), [props.rules]);+ const hasRules = rules.length > 0;const items = (props.items ?? []) as Array<{props: { value: string; label?: string; description?: string };}>;- const value = (getFieldValue(formName, fieldName) ?? props.defaultValue) as string | undefined;+ const value = field.value ?? props.defaultValue;React.useEffect(() => {- if (- !isStreaming &&- props.defaultValue != null &&- getFieldValue(formName, fieldName) == null- ) {- setFieldValue(formName, "RadioGroup", fieldName, props.defaultValue, false);- }- }, [isStreaming]);-- React.useEffect(() => {- if (!isStreaming && rules.length > 0 && formValidation) {- formValidation.registerField(fieldName, rules, () => getFieldValue(formName, fieldName));- return () => formValidation.unregisterField(fieldName);+ if (!isStreaming && hasRules && formValidation) {+ formValidation.registerField(field.name, rules, () => field.value);+ return () => formValidation.unregisterField(field.name);}return undefined;- }, [isStreaming, rules.length > 0]);+ }, [field.name, field.value, formValidation, hasRules, isStreaming, rules]);if (!items.length) return null;return (<OpenUIRadioGroup- name={fieldName}+ name={field.name}value={value ?? ""}onValueChange={(val: string) => {- setFieldValue(formName, "RadioGroup", fieldName, val, true);- if (rules.length > 0) {- formValidation?.validateField(fieldName, val, rules);+ field.setValue(val);+ if (hasRules) {+ formValidation?.validateField(field.name, val, rules);}}}disabled={isStreaming}diff --git a/packages/react-ui/src/genui-lib/Select/index.tsx b/packages/react-ui/src/genui-lib/Select/index.tsxindex 5a7a8f8b1..a47147775 100644--- a/packages/react-ui/src/genui-lib/Select/index.tsx+++ b/packages/react-ui/src/genui-lib/Select/index.tsx@@ -3,11 +3,9 @@import {defineComponent,parseStructuredRules,- useFormName,useFormValidation,- useGetFieldValue,useIsStreaming,- useSetFieldValue,+ useStateField,} from "@openuidev/react-lang";import React from "react";import {@@ -33,36 +31,42 @@ export const Select = defineComponent({props: createSelectSchema(SelectItem),description: "",component: ({ props }) => {- const formName = useFormName();- const getFieldValue = useGetFieldValue();- const setFieldValue = useSetFieldValue();const isStreaming = useIsStreaming();const formValidation = useFormValidation();+ const field = useStateField(props.name, props.value);+const rules = React.useMemo(() => parseStructuredRules(props.rules), [props.rules]);+ const hasRules = rules.length > 0;const items = ((props.items ?? []) as Array<{ props: { value: string; label?: string } }>- ).filter((item) => item.props.value);- const value = getFieldValue(formName, props.name);+ ).filter((item) => item?.props?.value);++ const value = field.value ?? "";++ const handleChange = React.useCallback(+ (val: string) => {+ field.setValue(val);+ if (hasRules) {+ formValidation?.validateField(field.name, val, rules);+ }+ },+ [field, formValidation, hasRules, rules],+ );React.useEffect(() => {- if (!isStreaming && rules.length > 0 && formValidation) {- formValidation.registerField(props.name, rules, () => getFieldValue(formName, props.name));- return () => formValidation.unregisterField(props.name);+ if (!isStreaming && hasRules && formValidation) {+ formValidation.registerField(field.name, rules, () => field.value);+ return () => formValidation.unregisterField(field.name);}return undefined;- }, [isStreaming, rules.length > 0]);+ }, [field.name, field.value, formValidation, hasRules, isStreaming, rules]);return (<OpenUISelect- name={props.name}- value={value ?? ""}- onValueChange={(val: string) => {- setFieldValue(formName, "Select", props.name, val, true);- if (rules.length > 0) {- formValidation?.validateField(props.name, val, rules);- }- }}+ name={field.name}+ value={value}+ onValueChange={handleChange}disabled={isStreaming}><OpenUISelectTrigger>diff --git a/packages/react-ui/src/genui-lib/Select/schema.ts b/packages/react-ui/src/genui-lib/Select/schema.tsindex 1d09c1cba..7de8c6b67 100644--- a/packages/react-ui/src/genui-lib/Select/schema.ts+++ b/packages/react-ui/src/genui-lib/Select/schema.ts@@ -1,3 +1,4 @@+import { reactive } from "@openuidev/react-lang";import { z } from "zod";import { rulesSchema } from "../rules";@@ -14,5 +15,6 @@ export function createSelectSchema(SelectItem: RefComponent) {items: z.array(SelectItem.ref),placeholder: z.string().optional(),rules: rulesSchema,+ value: reactive(z.string().optional()),});}diff --git a/packages/react-ui/src/genui-lib/Slider/index.tsx b/packages/react-ui/src/genui-lib/Slider/index.tsxindex a46d0da24..0873f567e 100644--- a/packages/react-ui/src/genui-lib/Slider/index.tsx+++ b/packages/react-ui/src/genui-lib/Slider/index.tsx@@ -3,12 +3,9 @@import {defineComponent,parseStructuredRules,- useFormName,useFormValidation,- useGetFieldValue,useIsStreaming,- useSetDefaultValue,- useSetFieldValue,+ useStateField,} from "@openuidev/react-lang";import React from "react";import { SliderBlock as OpenUISliderBlock } from "../../components/Slider";@@ -21,48 +18,35 @@ export const Slider = defineComponent({props: SliderSchema,description: "Numeric slider input; supports continuous and discrete (stepped) variants",component: ({ props }) => {- const formName = useFormName();- const getFieldValue = useGetFieldValue();- const setFieldValue = useSetFieldValue();const isStreaming = useIsStreaming();const formValidation = useFormValidation();- const fieldName = props.name as string;+ const field = useStateField(props.name, props.value);const rules = React.useMemo(() => parseStructuredRules(props.rules), [props.rules]);- const existingValue = getFieldValue(formName, fieldName);- const defaultVal = props.defaultValue;-- useSetDefaultValue({- formName,- componentType: "Slider",- name: fieldName,- existingValue,- defaultValue: defaultVal,- });+ const hasRules = rules.length > 0;+ const value = field.value ?? props.defaultValue;React.useEffect(() => {- if (!isStreaming && rules.length > 0 && formValidation) {- formValidation.registerField(fieldName, rules, () => getFieldValue(formName, fieldName));- return () => formValidation.unregisterField(fieldName);+ if (!isStreaming && hasRules && formValidation) {+ formValidation.registerField(field.name, rules, () => field.value);+ return () => formValidation.unregisterField(field.name);}return undefined;- }, [isStreaming, rules.length > 0]);-- const value = existingValue ?? defaultVal;+ }, [field.name, field.value, formValidation, hasRules, isStreaming, rules]);return (<OpenUISliderBlock- label={(props.label as string) || fieldName}- name={fieldName}+ label={(props.label as string) || field.name}+ name={field.name}variant={(props.variant as "continuous" | "discrete") || "continuous"}min={props.min as number}max={props.max as number}step={props.step as number | undefined}- defaultValue={value != null ? value : undefined}+ defaultValue={value != null ? (value as number[]) : undefined}onValueCommit={(vals: number[]) => {- setFieldValue(formName, "Slider", fieldName, vals, true);- if (rules.length > 0) {- formValidation?.validateField(fieldName, vals[0], rules);+ field.setValue(vals);+ if (hasRules) {+ formValidation?.validateField(field.name, vals[0], rules);}}}disabled={isStreaming}diff --git a/packages/react-ui/src/genui-lib/Slider/schema.ts b/packages/react-ui/src/genui-lib/Slider/schema.tsindex 3e7f4079e..e9223527a 100644--- a/packages/react-ui/src/genui-lib/Slider/schema.ts+++ b/packages/react-ui/src/genui-lib/Slider/schema.ts@@ -1,3 +1,4 @@+import { reactive } from "@openuidev/react-lang";import { z } from "zod";import { rulesSchema } from "../rules";@@ -10,4 +11,5 @@ export const SliderSchema = z.object({defaultValue: z.array(z.number()).optional(),label: z.string().optional(),rules: rulesSchema,+ value: reactive(z.array(z.number()).optional()),});diff --git a/packages/react-ui/src/genui-lib/SwitchGroup/index.tsx b/packages/react-ui/src/genui-lib/SwitchGroup/index.tsxindex 2fa1fc7ea..4233d3a54 100644--- a/packages/react-ui/src/genui-lib/SwitchGroup/index.tsx+++ b/packages/react-ui/src/genui-lib/SwitchGroup/index.tsx@@ -2,17 +2,14 @@import {defineComponent,- useFormName,- useGetFieldValue,useIsStreaming,- useSetFieldValue,+ useStateField,type SubComponentOf,} from "@openuidev/react-lang";import React from "react";-import { z } from "zod";import { SwitchGroup as OpenUISwitchGroup } from "../../components/SwitchGroup";import { SwitchItem as OpenUISwitchItem } from "../../components/SwitchItem";-import { SwitchItemSchema } from "./schema";+import { SwitchItemSchema, createSwitchGroupSchema } from "./schema";export { SwitchItemSchema } from "./schema";@@ -32,29 +29,23 @@ export const SwitchItem = defineComponent({export const SwitchGroup = defineComponent({name: "SwitchGroup",- props: z.object({- name: z.string(),- items: z.array(SwitchItem.ref),- variant: z.enum(["clear", "card", "sunk"]).optional(),- }),+ props: createSwitchGroupSchema(SwitchItem),description: "Group of switch toggles",component: ({ props }) => {- const formName = useFormName();- const getFieldValue = useGetFieldValue();- const setFieldValue = useSetFieldValue();const isStreaming = useIsStreaming();- const fieldName = props.name as string;+ const field = useStateField(props.name, props.value);const items = (props.items ?? []) as Array<SubComponentOf<SwitchItemProps>>;+ // Aggregate: map of item name → checked booleanconst getAggregate = React.useCallback((): Record<string, boolean> => {- const stored = getFieldValue(formName, fieldName) as Record<string, boolean> | undefined;+ const stored = field.value;const result: Record<string, boolean> = {};for (const item of items) {result[item.props.name] = stored?.[item.props.name] ?? item.props.defaultChecked ?? false;}return result;- }, [formName, fieldName, items, getFieldValue]);+ }, [field.value, items]);if (!items.length) return null;@@ -71,7 +62,7 @@ export const SwitchGroup = defineComponent({checked={aggregate[item.props.name] ?? item.props.defaultChecked ?? false}onChange={(val: boolean) => {const newAggregate = { ...getAggregate(), [item.props.name]: val };- setFieldValue(formName, "SwitchGroup", fieldName, newAggregate, true);+ field.setValue(newAggregate);}}disabled={isStreaming}/>diff --git a/packages/react-ui/src/genui-lib/SwitchGroup/schema.ts b/packages/react-ui/src/genui-lib/SwitchGroup/schema.tsindex 3ec0ebf54..cef17fe7b 100644--- a/packages/react-ui/src/genui-lib/SwitchGroup/schema.ts+++ b/packages/react-ui/src/genui-lib/SwitchGroup/schema.ts@@ -1,5 +1,8 @@+import { reactive } from "@openuidev/react-lang";import { z } from "zod";+type RefComponent = { ref: z.ZodTypeAny };+export const SwitchItemSchema = z.object({label: z.string().optional(),description: z.string().optional(),@@ -7,8 +10,11 @@ export const SwitchItemSchema = z.object({defaultChecked: z.boolean().optional(),});-export const SwitchGroupSchema = z.object({- name: z.string(),- items: z.array(z.any()), // filled by SwitchItem.ref in index- variant: z.enum(["clear", "card", "sunk"]).optional(),-});+export function createSwitchGroupSchema(SwitchItem: RefComponent) {+ return z.object({+ name: z.string(),+ items: z.array(SwitchItem.ref),+ variant: z.enum(["clear", "card", "sunk"]).optional(),+ value: reactive(z.record(z.string(), z.boolean()).optional()),+ });+}diff --git a/packages/react-ui/src/genui-lib/Table/index.tsx b/packages/react-ui/src/genui-lib/Table/index.tsxindex 2dfb85534..fb1ee3848 100644--- a/packages/react-ui/src/genui-lib/Table/index.tsx+++ b/packages/react-ui/src/genui-lib/Table/index.tsx@@ -1,7 +1,10 @@"use client";import { defineComponent } from "@openuidev/react-lang";+import { ChevronLeft, ChevronRight } from "lucide-react";+import React from "react";import { z } from "zod";+import { IconButton } from "../../components/IconButton";import {ScrollableTable as OpenUITable,TableBody as OpenUITableBody,@@ -15,10 +18,12 @@ import { ColSchema } from "./schema";export { ColSchema } from "./schema";+const DEFAULT_PAGE_SIZE = 10;+export const Col = defineComponent({name: "Col",props: ColSchema,- description: "Column definition",+ description: "Column definition — holds label + data array",component: () => null,});@@ -26,41 +31,94 @@ export const Table = defineComponent({name: "Table",props: z.object({columns: z.array(Col.ref),- rows: z.array(z.array(z.union([z.string(), z.number(), z.boolean()]))),}),- description: "Data table",+ description: "Data table — column-oriented. Each Col holds its own data array.",component: ({ props, renderNode }) => {- const columns = props.columns ?? [];- const rows = asArray(props.rows) as unknown[][];+ const effectivePageSize = DEFAULT_PAGE_SIZE;+ const [currentPage, setCurrentPage] = React.useState(0);++ const columns = props.columns ?? [];if (!columns.length) return null;+ const colDefs = columns+ .filter((c: any) => c != null && c.props)+ .map((c: any) => ({+ label: c.props?.label ?? "",+ data: asArray(c.props?.data ?? []),+ }));+ if (!colDefs.length) return null;++ const rowCount = Math.max(...colDefs.map((c) => c.data.length), 0);++ const totalPages = Math.ceil(rowCount / effectivePageSize);+ const safePage = Math.min(currentPage, Math.max(0, totalPages - 1));+ const startRow = safePage * effectivePageSize;+ const endRow = Math.min(startRow + effectivePageSize, rowCount);+ const visibleRowCount = endRow - startRow;+return (- <OpenUITable>- <OpenUITableHeader>- <OpenUITableRow>- {columns.map((c, i) => (- <OpenUITableHead key={i}>{c.props.label}</OpenUITableHead>- ))}- </OpenUITableRow>- </OpenUITableHeader>- <OpenUITableBody>- {rows.map((row, ri) => {- const cells = asArray(row);- return (- <OpenUITableRow key={ri}>- {cells.map((cell, ci) => (- <OpenUITableCell key={ci}>- {typeof cell === "object" && cell !== null- ? renderNode(cell)- : String(cell ?? "")}- </OpenUITableCell>- ))}- </OpenUITableRow>- );- })}- </OpenUITableBody>- </OpenUITable>+ <div>+ <OpenUITable>+ <OpenUITableHeader>+ <OpenUITableRow>+ {colDefs.map((c, i) => (+ <OpenUITableHead key={i}>{c.label}</OpenUITableHead>+ ))}+ </OpenUITableRow>+ </OpenUITableHeader>+ <OpenUITableBody>+ {Array.from({ length: visibleRowCount }, (_, i) => {+ const ri = startRow + i;+ return (+ <OpenUITableRow key={ri}>+ {colDefs.map((col, ci) => {+ const cell = col.data[ri];+ return (+ <OpenUITableCell key={ci}>+ {typeof cell === "object" && cell !== null+ ? renderNode(cell)+ : String(cell ?? "")}+ </OpenUITableCell>+ );+ })}+ </OpenUITableRow>+ );+ })}+ </OpenUITableBody>+ </OpenUITable>+ {totalPages > 1 && (+ <div+ style={{+ display: "flex",+ alignItems: "center",+ justifyContent: "flex-end",+ gap: "8px",+ paddingTop: "8px",+ }}+ >+ <IconButton+ aria-label="Previous page"+ size="small"+ variant="secondary"+ icon={<ChevronLeft size={16} />}+ disabled={safePage === 0}+ onClick={() => setCurrentPage((p) => Math.max(0, p - 1))}+ />+ <span style={{ fontSize: "13px", color: "#6b7280" }}>+ {safePage + 1} / {totalPages}+ </span>+ <IconButton+ aria-label="Next page"+ size="small"+ variant="secondary"+ icon={<ChevronRight size={16} />}+ disabled={safePage >= totalPages - 1}+ onClick={() => setCurrentPage((p) => Math.min(totalPages - 1, p + 1))}+ />+ </div>+ )}+ </div>);},});diff --git a/packages/react-ui/src/genui-lib/Table/schema.ts b/packages/react-ui/src/genui-lib/Table/schema.tsindex c40291c8e..10a2224af 100644--- a/packages/react-ui/src/genui-lib/Table/schema.ts+++ b/packages/react-ui/src/genui-lib/Table/schema.ts@@ -1,6 +1,10 @@import { z } from "zod";export const ColSchema = z.object({+ /** Column header label */label: z.string(),+ /** Column data — array of values or components (one per row). Use array pluck for text, Each() for styled cells like Tag. */+ data: z.any(),+ /** Optional display type hint */type: z.enum(["string", "number", "action"]).optional(),});diff --git a/packages/react-ui/src/genui-lib/Tabs/index.tsx b/packages/react-ui/src/genui-lib/Tabs/index.tsxindex b036e3051..2d8934672 100644--- a/packages/react-ui/src/genui-lib/Tabs/index.tsx+++ b/packages/react-ui/src/genui-lib/Tabs/index.tsx@@ -27,7 +27,7 @@ export const Tabs = defineComponent({}),description: "Tabbed container",component: ({ props, renderNode }) => {- const items = props.items ?? [];+ const items = (props.items ?? []).filter((item) => item?.props?.value != null);const [activeTab, setActiveTab] = React.useState("");const userHasInteracted = React.useRef(false);const prevContentSizes = React.useRef<Record<string, number>>({});diff --git a/packages/react-ui/src/genui-lib/TextArea/index.tsx b/packages/react-ui/src/genui-lib/TextArea/index.tsxindex c6baa1f19..758b43005 100644--- a/packages/react-ui/src/genui-lib/TextArea/index.tsx+++ b/packages/react-ui/src/genui-lib/TextArea/index.tsx@@ -3,11 +3,9 @@import {defineComponent,parseStructuredRules,- useFormName,useFormValidation,- useGetFieldValue,useIsStreaming,- useSetFieldValue,+ useStateField,} from "@openuidev/react-lang";import React from "react";import { TextArea as OpenUITextArea } from "../../components/TextArea";@@ -20,38 +18,38 @@ export const TextArea = defineComponent({props: TextAreaSchema,description: "",component: ({ props }) => {- const formName = useFormName();- const getFieldValue = useGetFieldValue();- const setFieldValue = useSetFieldValue();const isStreaming = useIsStreaming();const formValidation = useFormValidation();- const fieldName = props.name as string;+ const field = useStateField(props.name, props.value);const rules = React.useMemo(() => parseStructuredRules(props.rules), [props.rules]);- const savedValue = getFieldValue(formName, fieldName) ?? "";+ const hasRules = rules.length > 0;React.useEffect(() => {- if (!isStreaming && rules.length > 0 && formValidation) {- formValidation.registerField(fieldName, rules, () => getFieldValue(formName, fieldName));- return () => formValidation.unregisterField(fieldName);+ if (!isStreaming && hasRules && formValidation) {+ formValidation.registerField(field.name, rules, () => field.value);+ return () => formValidation.unregisterField(field.name);}return undefined;- }, [isStreaming, rules.length > 0]);+ }, [field.name, field.value, formValidation, hasRules, isStreaming, rules]);return (<OpenUITextArea- name={fieldName}+ name={field.name}placeholder={(props.placeholder as string) || ""}rows={(props.rows as number) || 3}- defaultValue={savedValue}- onFocus={() => formValidation?.clearFieldError(fieldName)}- onBlur={(e: React.FocusEvent<HTMLTextAreaElement>) => {+ value={field.value ?? ""}+ onFocus={() => formValidation?.clearFieldError(field.name)}+ onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => {const val = e.target.value;- if (val !== savedValue) {- setFieldValue(formName, "TextArea", fieldName, val, true);+ field.setValue(val);+ if (hasRules) {+ formValidation?.clearFieldError(field.name);}- if (rules.length > 0) {- formValidation?.validateField(fieldName, val, rules);+ }}+ onBlur={(e: React.FocusEvent<HTMLTextAreaElement>) => {+ if (hasRules) {+ formValidation?.validateField(field.name, e.target.value, rules);}}}disabled={isStreaming}diff --git a/packages/react-ui/src/genui-lib/TextArea/schema.ts b/packages/react-ui/src/genui-lib/TextArea/schema.tsindex 376136872..b805a161d 100644--- a/packages/react-ui/src/genui-lib/TextArea/schema.ts+++ b/packages/react-ui/src/genui-lib/TextArea/schema.ts@@ -1,3 +1,4 @@+import { reactive } from "@openuidev/react-lang";import { z } from "zod";import { rulesSchema } from "../rules";@@ -6,4 +7,5 @@ export const TextAreaSchema = z.object({placeholder: z.string().optional(),rows: z.number().optional(),rules: rulesSchema,+ value: reactive(z.string().optional()),});diff --git a/packages/react-ui/src/genui-lib/openuiChatLibrary.tsx b/packages/react-ui/src/genui-lib/openuiChatLibrary.tsxindex 5ec9dc737..0fbc0916a 100644--- a/packages/react-ui/src/genui-lib/openuiChatLibrary.tsx+++ b/packages/react-ui/src/genui-lib/openuiChatLibrary.tsx@@ -212,16 +212,19 @@ export const openuiChatComponentGroups: ComponentGroup[] = [export const openuiChatExamples: string[] = [`Example 1 — Table with follow-ups:+root = Card([title, tbl, followUps])title = TextContent("Top Languages", "large-heavy")-tbl = Table(cols, rows)-cols = [Col("Language", "string"), Col("Users (M)", "number"), Col("Year", "number")]-rows = [["Python", 15.7, 1991], ["JavaScript", 14.2, 1995], ["Java", 12.1, 1995]]+tbl = Table([Col("Language", langs), Col("Users (M)", users), Col("Year", years)])+langs = ["Python", "JavaScript", "Java"]+users = [15.7, 14.2, 12.1]+years = [1991, 1995, 1995]followUps = FollowUpBlock([fu1, fu2])fu1 = FollowUpItem("Tell me more about Python")fu2 = FollowUpItem("Show me a JavaScript comparison")`,`Example 2 — Clickable list:+root = Card([title, list])title = TextContent("Choose a topic", "large-heavy")list = ListBlock([item1, item2, item3])@@ -230,6 +233,7 @@ item2 = ListItem("Advanced features", "Deep dives into powerful capabilities.")item3 = ListItem("Troubleshooting", "Common issues and how to fix them.")`,`Example 3 — Image carousel with consistent slides + follow-ups:+root = Card([header, carousel, followups])header = CardHeader("Featured Destinations", "Discover highlights and best time to visit")carousel = Carousel([[t1, img1, d1, tags1], [t2, img2, d2, tags2], [t3, img3, d3, tags3]], "card")@@ -250,13 +254,14 @@ fu1 = FollowUpItem("Show me only beach destinations")fu2 = FollowUpItem("Turn this into a comparison table")`,`Example 4 — Form with validation:+root = Card([title, form])title = TextContent("Contact Us", "large-heavy")form = Form("contact", btns, [nameField, emailField, msgField])nameField = FormControl("Name", Input("name", "Your name", "text", { required: true, minLength: 2 }))emailField = FormControl("Email", Input("email", "[email protected]", "email", { required: true, email: true }))msgField = FormControl("Message", TextArea("message", "Tell us more...", 4, { required: true, minLength: 10 }))-btns = Buttons([Button("Submit", { type: "continue_conversation" }, "primary")])`,+btns = Buttons([Button("Submit", Action([@ToAssistant("Submit")]), "primary")])`,];export const openuiChatAdditionalRules: string[] = [diff --git a/packages/react-ui/src/genui-lib/openuiLibrary.tsx b/packages/react-ui/src/genui-lib/openuiLibrary.tsxindex 3758e770a..048c09854 100644--- a/packages/react-ui/src/genui-lib/openuiLibrary.tsx+++ b/packages/react-ui/src/genui-lib/openuiLibrary.tsx@@ -62,6 +62,9 @@ import { Col, Table } from "./Table";import { Tag } from "./Tag";import { TagBlock } from "./TagBlock";+// Modal+import { Modal } from "./Modal";+// ── Component Groups ──export const openuiComponentGroups: ComponentGroup[] = [@@ -77,11 +80,16 @@ export const openuiComponentGroups: ComponentGroup[] = ["StepsItem","Carousel","Separator",+ "Modal",],notes: ['- For grid-like layouts, use Stack with direction "row" and wrap set to true.','- Prefer justify "start" (or omit justify) with wrap=true for stable columns instead of uneven gutters.',"- Use nested Stacks when you need explicit rows/sections.",+ '- Show/hide sections: $editId != "" ? Card([editForm]) : null',+ '- Modal: Modal("Title", $showModal, [content]) — $showModal is boolean, X/Escape auto-closes. Put Form with its own buttons inside children.',+ "- Use Tabs for alternative views (chart types, data sections) — no $variable needed",+ "- Shared filter across Tabs: same $days binding in Query args works across all TabItems",],},{@@ -98,10 +106,24 @@ export const openuiComponentGroups: ComponentGroup[] = ["ImageGallery","CodeBlock",],+ notes: [+ '- Use Cards to group related KPIs or sections. Stack with direction "row" for side-by-side layouts.',+ '- Success toast: Callout("success", "Saved", "Done.", $showSuccess) — use @Set($showSuccess, true) in save action, auto-dismisses after 3s. For errors: result.status == "error" ? Callout("error", "Failed", result.error) : null',+ '- KPI card: Card([TextContent("Label", "small"), TextContent("" + @Count(@Filter(data.rows, "field", "==", "value")), "large-heavy")])',+ ],},{name: "Tables",components: ["Table", "Col"],+ notes: [+ '- Table is COLUMN-oriented: Table([Col("Label", dataArray), Col("Count", countArray, "number")]). Use array pluck for data: data.rows.fieldName',+ '- Col data can be component arrays for styled cells: Col("Status", @Each(data.rows, "item", Tag(item.status, null, "sm", item.status == "open" ? "success" : "danger")))',+ '- Row actions: Col("Actions", @Each(data.rows, "t", Button("Edit", Action([@Set($showEdit, true), @Set($editId, t.id)]))))',+ '- Sortable: sorted = @Sort(data.rows, $sortField, "desc"). Bind $sortField to Select. Use sorted.fieldName for Col data',+ '- Searchable: filtered = @Filter(data.rows, "title", "contains", $search). Bind $search to Input',+ "- Chain sort + filter: filtered = @Filter(...) then sorted = @Sort(filtered, ...) — use sorted for both Table and Charts",+ '- Empty state: @Count(data.rows) > 0 ? Table([...]) : TextContent("No data yet")',+ ],},{name: "Charts (2D)",@@ -113,10 +135,21 @@ export const openuiComponentGroups: ComponentGroup[] = ["HorizontalBarChart","Series",],+ notes: [+ '- Charts accept column arrays: LineChart(labels, [Series("Name", values)]). Use array pluck: LineChart(data.rows.day, [Series("Views", data.rows.views)])',+ "- Use Cards to wrap charts with CardHeader for titled sections",+ "- Chart + Table from same source: use @Sort or @Filter result for both LineChart and Table Col data",+ '- Multiple chart views: use Tabs — Tabs([TabItem("line", "Line", [LineChart(...)]), TabItem("bar", "Bar", [BarChart(...)])])',+ ],},{name: "Charts (1D)",components: ["PieChart", "RadialChart", "SingleStackedBarChart", "Slice"],+ notes: [+ "- PieChart and BarChart need NUMBERS, not objects. For list data, use @Count(@Filter(...)) to aggregate:",+ '- PieChart from list: `PieChart(["Low", "Med", "High"], [@Count(@Filter(data.rows, "priority", "==", "low")), @Count(@Filter(data.rows, "priority", "==", "medium")), @Count(@Filter(data.rows, "priority", "==", "high"))], "donut")`',+ '- KPI from count: `TextContent("" + @Count(@Filter(data.rows, "status", "==", "open")), "large-heavy")`',+ ],},{name: "Charts (Scatter)",@@ -145,32 +178,43 @@ export const openuiComponentGroups: ComponentGroup[] = ["- For Form fields, define EACH FormControl as its own reference — do NOT inline all controls in one array. This allows progressive field-by-field streaming.","- NEVER nest Form inside Form — each Form should be a standalone container.","- Form requires explicit buttons. Always pass a Buttons(...) reference as the third Form argument.",- '- rules is an optional array of validation strings: ["required", "email", "min:8", "maxLength:100"]',- "- Available rules: required, email, min:N, max:N, minLength:N, maxLength:N, pattern:REGEX, url, numeric",+ "- rules is an optional object: {required: true, email: true, minLength: 8, maxLength: 100}",+ "- Available rules: required, email, min, max, minLength, maxLength, pattern, url, numeric","- The renderer shows error messages automatically — do NOT generate error text in the UI",+ '- Conditional fields: $country == "US" ? stateField : $country == "UK" ? postcodeField : addressField',+ '- Edit form in Modal: Modal("Edit", $showEdit, [Form("edit", Buttons([saveBtn, cancelBtn]), [fields...])]). Save button should include @Set($showEdit, false) to close modal.',],},{name: "Buttons",components: ["Button", "Buttons"],+ notes: [+ '- Toggle in @Each: @Each(rows, "t", Button(t.status == "open" ? "Close" : "Reopen", Action([...])))',+ ],},{name: "Data Display",components: ["TagBlock", "Tag"],+ notes: [+ '- Color-mapped Tag: Tag(value, null, "sm", value == "high" ? "danger" : value == "medium" ? "warning" : "neutral")',+ ],},];// ── Examples ──export const openuiExamples: string[] = [- `Example 1 — Table:+ `Example 1 — Table (column-oriented):+root = Stack([title, tbl])title = TextContent("Top Languages", "large-heavy")-tbl = Table(cols, rows)-cols = [Col("Language", "string"), Col("Users (M)", "number"), Col("Year", "number")]-rows = [["Python", 15.7, 1991], ["JavaScript", 14.2, 1995], ["Java", 12.1, 1995], ["TypeScript", 8.5, 2012], ["Go", 5.2, 2009]]`,+tbl = Table([Col("Language", langs), Col("Users (M)", users), Col("Year", years)])+langs = ["Python", "JavaScript", "Java", "TypeScript", "Go"]+users = [15.7, 14.2, 12.1, 8.5, 5.2]+years = [1991, 1995, 1995, 2012, 2009]`,`Example 2 — Bar chart:+root = Stack([title, chart])title = TextContent("Q4 Revenue", "large-heavy")chart = BarChart(labels, [s1, s2], "grouped")@@ -179,6 +223,7 @@ s1 = Series("Product A", [120, 150, 180])s2 = Series("Product B", [90, 110, 140])`,`Example 3 — Form with validation:+root = Stack([title, form])title = TextContent("Contact Us", "large-heavy")form = Form("contact", btns, [nameField, emailField, countryField, msgField])@@ -187,9 +232,10 @@ emailField = FormControl("Email", Input("email", "[email protected]", "email", { rcountryField = FormControl("Country", Select("country", countryOpts, "Select...", { required: true }))msgField = FormControl("Message", TextArea("message", "Tell us more...", 4, { required: true, minLength: 10 }))countryOpts = [SelectItem("us", "United States"), SelectItem("uk", "United Kingdom"), SelectItem("de", "Germany")]-btns = Buttons([Button("Submit", { type: "continue_conversation" }, "primary"), Button("Cancel", { type: "continue_conversation" }, "secondary")])`,+btns = Buttons([Button("Submit", Action([@ToAssistant("Submit")]), "primary"), Button("Cancel", Action([@ToAssistant("Cancel")]), "secondary")])`,`Example 4 — Tabs with mixed content:+root = Stack([title, tabs])title = TextContent("React vs Vue", "large-heavy")tabs = Tabs([tabReact, tabVue])@@ -204,6 +250,10 @@ export const openuiAdditionalRules: string[] = ["For forms, define one FormControl reference per field so controls can stream progressively.","For forms, always provide the second Form argument with Buttons(...) actions: Form(name, buttons, fields).","Never nest Form inside Form.",+ 'Use @Reset($var1, $var2) after form submit to restore defaults — not @Set($var, "")',+ "Multi-query refresh: Action([@Run(mutation), @Run(query1), @Run(query2), @Reset(...)])",+ "$variables are reactive: changing via Select or @Set re-evaluates all Queries and expressions referencing them",+ "Use existing components (Tabs, Accordion, Modal) before inventing ternary show/hide patterns",];export const openuiPromptOptions: PromptOptions = {@@ -280,5 +330,7 @@ export const openuiLibrary = createLibrary({// Data DisplayTagBlock,Tag,+ // Modal+ Modal,],});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b92f491d1..d0d64cbad 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -47,6 +47,9 @@ importers:'@openuidev/cli':specifier: workspace:*version: link:../packages/openui-cli+ '@openuidev/lang-core':+ specifier: workspace:^+ version: link:../packages/lang-core'@openuidev/react-headless':specifier: workspace:^version: link:../packages/react-headless@@ -64,7 +67,7 @@ importers:version: 16.6.5(@mdx-js/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])fumadocs-mdx:specifier: 14.2.8- version: 14.2.8(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 14.2.8(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected]))fumadocs-ui:specifier: 16.6.5version: 16.6.5(@takumi-rs/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected](@mdx-js/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])@@ -83,6 +86,9 @@ importers:next-themes:specifier: ^0.4.6+ octokit:+ specifier: ^5.0.0+ version: 5.0.5openai:specifier: ^6.22.0version: 6.22.0([email protected])([email protected])@@ -198,7 +204,7 @@ importers:version: 0.0.45'@ag-ui/mastra':specifier: ^1.0.1- version: 1.0.1(d5bfccb2283c9e6cfb0a090aaed772b1)+ version: 1.0.1(ypgyhrljo5kobpqehkhvtoi6ry)'@mastra/core':specifier: 1.15.0version: 1.15.0(@cfworker/[email protected])(@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-community/[email protected](@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-schema/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])@@ -438,6 +444,70 @@ importers:specifier: ^5version: 5.9.3+ examples/openui-dashboard:+ dependencies:+ '@modelcontextprotocol/sdk':+ specifier: ^1.27.1+ version: 1.27.1(@cfworker/[email protected])([email protected])+ '@openuidev/cli':+ specifier: workspace:*+ version: link:../../packages/openui-cli+ '@openuidev/lang-core':+ specifier: workspace:*+ version: link:../../packages/lang-core+ '@openuidev/react-headless':+ specifier: workspace:*+ version: link:../../packages/react-headless+ '@openuidev/react-lang':+ specifier: workspace:*+ version: link:../../packages/react-lang+ '@openuidev/react-ui':+ specifier: workspace:*+ version: link:../../packages/react-ui+ lucide-react:+ specifier: ^0.575.0+ version: 0.575.0([email protected])+ next:+ specifier: 16.1.6+ version: 16.1.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])+ openai:+ specifier: ^6.22.0+ version: 6.22.0([email protected])([email protected])+ react:+ specifier: 19.2.3+ version: 19.2.3+ react-dom:+ specifier: 19.2.3+ version: 19.2.3([email protected])+ zod:+ specifier: ^4.0.0+ version: 4.3.6+ devDependencies:+ '@tailwindcss/postcss':+ specifier: ^4+ version: 4.2.1+ '@types/node':+ specifier: ^20+ version: 20.19.35+ '@types/react':+ specifier: ^19+ version: 19.2.14+ '@types/react-dom':+ specifier: ^19+ version: 19.2.3(@types/[email protected])+ eslint:+ specifier: ^9+ version: 9.29.0([email protected])+ eslint-config-next:+ specifier: 16.1.6+ version: 16.1.6(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ tailwindcss:+ specifier: ^4+ version: 4.2.1+ typescript:+ specifier: ^5+ version: 5.9.3+examples/openui-react-native: {}examples/openui-react-native/backend:@@ -897,6 +967,9 @@ importers:specifier: ^4.0.0version: 4.3.6devDependencies:+ '@modelcontextprotocol/sdk':+ specifier: ^1.27.1+ version: 1.27.1(@cfworker/[email protected])([email protected])vitest:specifier: ^4.0.18version: 4.0.18(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -979,6 +1052,9 @@ importers:specifier: ^4.0.0version: 4.3.6devDependencies:+ '@modelcontextprotocol/sdk':+ specifier: ^1.27.1+ version: 1.27.1(@cfworker/[email protected])([email protected])'@types/react':specifier: ^19.0.0version: 19.2.14@@ -3157,6 +3233,12 @@ packages:peerDependencies:tailwindcss: '>=4.0.0'+ '@hono/[email protected]':+ resolution: {integrity: sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g==}+ engines: {node: '>=18.14.1'}+ peerDependencies:+ hono: ^4+'@hono/[email protected]':resolution: {integrity: sha512-txsUW4SQ1iilgE0l9/e9VQWmELXifEFvmdA1j6WFh/aFPj99hIntrSsq/if0UWyGVkmrRPKA1wCeP+UCr1B9Uw==}engines: {node: '>=18.14.1'}@@ -3636,6 +3718,16 @@ packages:'@mermaid-js/[email protected]':resolution: {integrity: sha512-gxK9ZX2+Fex5zu8LhRQoMeMPEHbc73UKZ0FQ54YrQtUxE1VVhMwzeNtKRPAu5aXks4FasbMe4xB4bWrmq6Jlxw==}+ '@modelcontextprotocol/[email protected]':+ resolution: {integrity: sha512-sr6GbP+4edBwFndLbM60gf07z0FQ79gaExpnsjMGePXqFcSSb7t6iscpjk9DhFhwd+mTEQrzNafGP8/iGGFYaA==}+ engines: {node: '>=18'}+ peerDependencies:+ '@cfworker/json-schema': ^4.1.1+ zod: ^3.25 || ^4.0+ peerDependenciesMeta:+ '@cfworker/json-schema':+ optional: true+'@modelcontextprotocol/[email protected]':resolution: {integrity: sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==}engines: {node: '>=18'}@@ -3847,6 +3939,113 @@ packages:rollup-plugin-visualizer:optional: true+ '@octokit/[email protected]':+ resolution: {integrity: sha512-8j7sEpUYVj18dxvh0KWj6W/l6uAiVRBl1JBDVRqH1VHKAO/G5eRVl4yEoYACjakWers1DjUkcCHyJNQK47JqyQ==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-vVjdtQQwomrZ4V46B9LaCsxsySxGoHsyw6IYBov/TqJVROrlYdyNgw5q6tQbB7KZt53v1l1W53RiqTvpzL907g==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-+yoFQquaF8OxJSxTb7rnytBIC2ZLbLqA/yb71I4ZXT9+Slw4TziV9j/kyGhUFRRTF2+7WlnIWsePZCWHs+OGjg==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-zh2W0mKKMh/VWZhSqlaCzY7qFyrgd9oTWmTmHaXnHNeQRCZr/CXy2jCgHo4e4dJVTiuxP5dLa0YM5p5QVhJHbw==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-qLoPPc6E6GJoz3XeDG/pnDhJpTkODTGG4kY0/Py154i/I003O9NazkrwJwRuzgCalhzyIeWQ+6MDvkUmKXjg/A==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-P4YJBPdPSpWTQ1NU4XYdvHvXJJDxM6YwpS0FZHRgP7YFkdVxsWcpWGy/NVqlAA7PcPCnMacXlRm1y2PFZRWL/w==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-8Jb1mtUdmBHL7lGmop9mU9ArMRUTRhg8vp0T1VtZ4yd9vEm3zcLwmjQkhNEduKawOOORie61xhtYIhTDN+ZQ3g==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-DhGl4xMVFGVIyMwswXeyzdL4uXD5OGILGX5N8Y+f6W7LhC1Ze2poSNrkF/fedpVDHEEZ+PHFW0vL14I+mm8K3Q==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-grAEuupr/C1rALFnXTv6ZQhFuL1D8G5y8CN04RgrO4FIPMrtm+mcZzFG7dcBm+nq+1ppNixu+Jd78aeJOYxlGA==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-jnAjvTsPepyUaMu9e69hYBuozEPgYqP4Z3UnpmvoIzHDpf8EXDGvTY1l1jK0RsZ194oRd+k6Hm13oRU8EoDFwg==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-7QoLPRh/ssEA/HuHBHdVdSgF8xNLz/Bc5m9fZkArJE5bb6NmVkDm3anKxXPmN1zh6b5WKZPRr3697xKT/yM3qQ==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-HiNOO3MqLxlt5Da5bZbLV8Zarnphi4y9XehrbaFMkcoJ+FL7sMxH/UlUsCVxpddVu4qvNDrBdaTVE2o4ITK8ng==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA==}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-WiuzhOsiOvb7W3Pvmhf8d2C6qaLHXrWiLBP4nJ/4kydu+wpagV5Fkz9RfQwV2afYzv3PB+3xYgp4mAdNGjDprA==}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-crfpnIoFiBtRkvPqOyLOsw12XsveYuY2ieP6uYDosoUegBJpSVxGwut9sxUgFFcll3VTOTqpUf8yGd8x1OmAkQ==}+ engines: {node: '>= 20'}+ peerDependencies:+ '@octokit/core': '>=6'++ '@octokit/[email protected]':+ resolution: {integrity: sha512-fNVRE7ufJiAA3XUrha2omTA39M6IXIc6GIZLvlbsm8QOQCYvpq/LkMNGyFlB1d8hTDzsAXa3OKtybdMAYsV/fw==}+ engines: {node: '>= 20'}+ peerDependencies:+ '@octokit/core': '>=6'++ '@octokit/[email protected]':+ resolution: {integrity: sha512-B5yCyIlOJFPqUUeiD0cnBJwWJO8lkJs5d8+ze9QDP6SvfiXSz1BF+91+0MeI1d2yxgOhU/O+CvtiZ9jSkHhFAw==}+ engines: {node: '>= 20'}+ peerDependencies:+ '@octokit/core': '>=6'++ '@octokit/[email protected]':+ resolution: {integrity: sha512-O1FZgXeiGb2sowEr/hYTr6YunGdSAFWnr2fyW39Ah85H8O33ELASQxcvOFF5LE6Tjekcyu2ms4qAzJVhSaJxTw==}+ engines: {node: '>= 20'}+ peerDependencies:+ '@octokit/core': '>=7'++ '@octokit/[email protected]':+ resolution: {integrity: sha512-34eE0RkFCKycLl2D2kq7W+LovheM/ex3AwZCYN8udpi6bxsyjZidb2McXs69hZhLmJlDqTSP8cH+jSRpiaijBg==}+ engines: {node: '>= 20'}+ peerDependencies:+ '@octokit/core': ^7.0.0++ '@octokit/[email protected]':+ resolution: {integrity: sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-SJZNwY9pur9Agf7l87ywFi14W+Hd9Jg6Ifivsd33+/bGUQIjNujdFiXII2/qSlN2ybqUHfp5xpekMEjIBTjlSw==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg==}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-MFlzzoDJVw/GcbfzVC1RLR36QqkTLUf79vLVO3D+xn7r0QgxnFoLZgtrzxiQErAjFUOdH6fas2KeQJ1yr/qaXQ==}+ engines: {node: '>= 20'}++ '@octokit/[email protected]':+ resolution: {integrity: sha512-da6KbdNCV5sr1/txD896V+6W0iamFWrvVl8cHkBSPT+YlvmT3DwXa4jxZnQc+gnuTEqSWbBeoSZYTayXH9wXcw==}+ engines: {node: '>= 20'}+'@one-ini/[email protected]':resolution: {integrity: sha512-XuySG1E38YScSJoMlqovLru4KTUNSjgVTIjyh7qMX6aNN5HY5Ct5LhRJdxO79JtTzKfzV/bnWpz+zquYrISsvw==}@@ -7202,6 +7401,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-rUYdp+MQwSFocxIOcSsYSF3YYYC/uUpMbCY/mbO21vGqfrEYvNSoPyKYDj6RhXXpPfS0KstW9RwG3qXh9sL7FQ==}+'@types/[email protected]':resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==}@@ -8355,6 +8557,9 @@ packages:engines: {node: '>=6.0.0'}hasBin: true+ resolution: {integrity: sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ==}+resolution: {integrity: sha512-aVNobHnJqLiUelTaHat9DZ1qM2w0C0Eym4LPI/3JxOnSokGVdsl1T1kN7TFvsEAD8G47A6VKQ0TVHqbBnYMJlQ==}engines: {node: '>=12.0.0'}@@ -8390,6 +8595,9 @@ packages:resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}+ resolution: {integrity: sha512-VHiNCbI1lKdl44tGrhNfU3lup0Tj/ZBMJB5/2ZbNXRCPuRCO7ed2mgcK4r17y+KB2EfuYuRaVlwNbAeaWGSpbw==}+resolution: {integrity: sha512-sXaHZicyEEmY86WyueLTQesbeoH/mquvarJaQNbjuOQO+7gbFcDEWqKmcWA4cOTLzFlfgvkiVxolk1k5bBIpmg==}@@ -9857,6 +10065,12 @@ packages:resolution: {integrity: sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==}+ resolution: {integrity: sha512-D1dKN+cmyPWuvB+G2SREQDzPY1agpBIcTa9sJxOPMCNeH3gwzhqJRDWCXW3gg0y//+LQ/8j52JbMROWyrKdMdw==}+ engines: {node: '>= 16'}+ peerDependencies:+ express: '>= 4.11'+resolution: {integrity: sha512-77VmFeJkO0/rvimEDuUC5H30oqUC4EyOhyGccfqoLebB0oiEYfM7nwPrsDsBL1gsTpwfzX8SFy2MT3TDyRq+bg==}engines: {node: '>= 16'}@@ -9884,6 +10098,9 @@ packages:resolution: {integrity: sha512-LyExtJWKxtgVzmgtEHyQtLFpw1KFhQphF9nTG8TpAIVkiI/xQ3FJh75tRFLYl4hkn7BNIIdLJInuDAavX35pMw==}+ resolution: {integrity: sha512-ZvLdcY8P+N8mGQJahJV5G4U88CSvT1rP8ApL6uETe88MBXrBHAkZlSEySdUlyztF7ccb+Znos3TFqaepHxdhBg==}+resolution: {integrity: sha512-dl0O9Vhju8IrcLndv2eU4ldt1ftXMqqfgN4H1cpmGV7P6jeB9FwpN9a2c8DPGE1Ys88rNUJVYDHq73CGAGOPfQ==}@@ -10502,6 +10719,10 @@ packages:hono:optional: true+ resolution: {integrity: sha512-VJCEvtrezO1IAR+kqEYnxUOoStaQPGrCmX3j4wDTNOcD1uRPFpGlwQUIW8niPuvHXaTUxeOUl5MMDGrl+tmO9A==}+ engines: {node: '>=16.9.0'}+resolution: {integrity: sha512-wy3T8Zm2bsEvxKZM5w21VdHDDcwVS1yUFFY6i8UobSsKfFceT7TOwhbhfKsDyx7tYQlmRM5FLpIuYvNFyjctiA==}engines: {node: '>=16.9.0'}@@ -11080,6 +11301,9 @@ packages:resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==}+ resolution: {integrity: sha512-eq/4KP6K34kwa7TcFdtvnftvHCD9KvHOGGICWwMFc4dOOKF5t4iYqnfLK8otCRCRv06FXOzGGyqE8h8ElMvvdw==}+resolution: {integrity: sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==}hasBin: true@@ -12207,6 +12431,10 @@ packages:resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==}+ resolution: {integrity: sha512-4+/OFSqOjoyULo7eN7EA97DE0Xydj/PW5aIckxqQIoFjFwqXKuFCvXUJObyJfBF9Khu4RL/jlDRI9FPaMGfPnw==}+ engines: {node: '>= 20'}+resolution: {integrity: sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA==}@@ -14112,6 +14340,10 @@ packages:resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}engines: {node: '>=8.0'}+ resolution: {integrity: sha512-/m8M+2BJUpoJdgAHoG+baCwBT+tf2VraSfkBgl0Y00qIWt41DJ8R5B8nsEw0I58YwF5IZH6z24/2TobDKnqSWw==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}engines: {node: '>=0.6'}@@ -14361,6 +14593,12 @@ packages:resolution: {integrity: sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==}+ resolution: {integrity: sha512-dcmbeSrOdTnsjGjUfAlqNDJrhxXizjAz94ija9Qw8YkZ1uu0d+GoZzyH+Jb9tIIqvGsadUfwg+22k5aDqqwzbw==}++ resolution: {integrity: sha512-TmnEAEAsBJVZM/AADELsK76llnwcf9vMKuPz8JflO1frO8Lchitr0fNaN9d+Ap0BjKtqWqd/J17qeDnXh8CL2A==}+resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}engines: {node: '>= 10.0.0'}@@ -15182,6 +15420,11 @@ packages:resolution: {integrity: sha512-/dNaicfdhJTOuUd4RImbLUE2g5yrSzzDjI/S6C2vO2ecAGZzn9UcRVgtyLSnENSmAOBRiSpUdzDS6fDWX3Z35g==}+ resolution: {integrity: sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==}+ peerDependencies:+ zod: ^3.25 || ^4+resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==}peerDependencies:@@ -15289,12 +15532,12 @@ snapshots:'@ag-ui/core': 0.0.49'@ag-ui/proto': 0.0.49- '@ag-ui/[email protected](@ag-ui/[email protected])(@ag-ui/[email protected])(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])':+ '@ag-ui/[email protected](@ag-ui/[email protected])(@ag-ui/[email protected])(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))([email protected]([email protected]))([email protected])':dependencies:'@ag-ui/client': 0.0.46'@ag-ui/core': 0.0.46- '@langchain/core': 0.3.80(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))- '@langchain/langgraph-sdk': 0.1.10(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected])))([email protected]([email protected]))([email protected])+ '@langchain/core': 0.3.80(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))+ '@langchain/langgraph-sdk': 0.1.10(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])))([email protected]([email protected]))([email protected])partial-json: 0.1.7rxjs: 7.8.1transitivePeerDependencies:@@ -15305,12 +15548,12 @@ snapshots:- react- react-dom- '@ag-ui/[email protected](d5bfccb2283c9e6cfb0a090aaed772b1)':+ '@ag-ui/[email protected](ypgyhrljo5kobpqehkhvtoi6ry)':dependencies:'@ag-ui/client': 0.0.49'@ag-ui/core': 0.0.45'@ai-sdk/ui-utils': 1.2.11([email protected])- '@copilotkit/runtime': 0.0.0-mme-ag-ui-0-0-46-20260227141603(@ag-ui/[email protected])(@cfworker/[email protected])(@copilotkitnext/[email protected])(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected])))(@langchain/[email protected](@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected])))([email protected]([email protected]))([email protected]))(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])+ '@copilotkit/runtime': 0.0.0-mme-ag-ui-0-0-46-20260227141603(@ag-ui/[email protected])(@cfworker/[email protected])(@copilotkitnext/[email protected])(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])))(@langchain/[email protected](@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])))([email protected]([email protected]))([email protected]))(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))([email protected]([email protected]))([email protected])'@mastra/client-js': 1.11.2(@cfworker/[email protected])(@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-community/[email protected](@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-schema/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])'@mastra/core': 1.15.0(@cfworker/[email protected])(@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-community/[email protected](@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-schema/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])rxjs: 7.8.1@@ -16303,11 +16546,11 @@ snapshots:'@cloudflare/[email protected]': {}- '@copilotkit/[email protected](@ag-ui/[email protected])(@cfworker/[email protected])(@copilotkitnext/[email protected])(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected])))(@langchain/[email protected](@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected])))([email protected]([email protected]))([email protected]))(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])':+ '@copilotkit/[email protected](@ag-ui/[email protected])(@cfworker/[email protected])(@copilotkitnext/[email protected])(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])))(@langchain/[email protected](@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])))([email protected]([email protected]))([email protected]))(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))([email protected]([email protected]))([email protected])':dependencies:'@ag-ui/client': 0.0.46'@ag-ui/core': 0.0.46- '@ag-ui/langgraph': 0.0.24(@ag-ui/[email protected])(@ag-ui/[email protected])(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])+ '@ag-ui/langgraph': 0.0.24(@ag-ui/[email protected])(@ag-ui/[email protected])(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))([email protected]([email protected]))([email protected])'@ai-sdk/anthropic': 2.0.71([email protected])'@ai-sdk/openai': 2.0.101([email protected])'@copilotkit/shared': 0.0.0-mme-ag-ui-0-0-46-20260227141603(@ag-ui/[email protected])@@ -16315,7 +16558,7 @@ snapshots:'@copilotkitnext/runtime': 0.0.0-mme-ag-ui-0-0-46-20260227141603(@ag-ui/[email protected])(@ag-ui/[email protected])(@ag-ui/[email protected])(@copilotkitnext/[email protected])'@graphql-yoga/plugin-defer-stream': 3.19.0([email protected]([email protected]))([email protected])'@hono/node-server': 1.19.12([email protected])- '@langchain/core': 0.3.80(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))+ '@langchain/core': 0.3.80(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))'@scarf/scarf': 1.4.0ai: 5.0.161([email protected])class-transformer: 0.5.1@@ -16332,8 +16575,8 @@ snapshots:type-graphql: 2.0.0-rc.1([email protected])([email protected]([email protected]))([email protected])zod: 3.25.76optionalDependencies:- '@langchain/langgraph-sdk': 0.1.10(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected])))([email protected]([email protected]))([email protected])- openai: 4.104.0([email protected])([email protected])+ '@langchain/langgraph-sdk': 0.1.10(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])))([email protected]([email protected]))([email protected])+ openai: 4.104.0([email protected])transitivePeerDependencies:- '@ag-ui/encoder'- '@cfworker/json-schema'@@ -17292,6 +17535,10 @@ snapshots:transitivePeerDependencies:- tailwind-merge+ '@hono/[email protected]([email protected])':+ dependencies:+ hono: 4.12.8+'@hono/[email protected]([email protected])':dependencies:hono: 4.12.9@@ -17677,14 +17924,14 @@ snapshots:'@kwsites/[email protected]': {}- '@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))':+ '@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))':dependencies:'@cfworker/json-schema': 4.1.1ansi-styles: 5.2.0camelcase: 6.3.0decamelize: 1.2.0js-tiktoken: 1.0.21- langsmith: 0.3.87(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))+ langsmith: 0.3.87(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))mustache: 4.2.0p-queue: 6.6.2p-retry: 4.6.2@@ -17697,14 +17944,14 @@ snapshots:- '@opentelemetry/sdk-trace-base'- openai- '@langchain/[email protected](@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected])))([email protected]([email protected]))([email protected])':+ '@langchain/[email protected](@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])))([email protected]([email protected]))([email protected])':dependencies:'@types/json-schema': 7.0.15p-queue: 6.6.2p-retry: 4.6.2uuid: 9.0.1optionalDependencies:- '@langchain/core': 0.3.80(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))+ '@langchain/core': 0.3.80(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))react: 19.2.3react-dom: 19.2.3([email protected])@@ -17887,6 +18134,30 @@ snapshots:dependencies:langium: 4.2.1+ dependencies:+ '@hono/node-server': 1.19.11([email protected])+ ajv: 8.18.0+ ajv-formats: 3.0.1([email protected])+ content-type: 1.0.5+ cors: 2.8.6+ cross-spawn: 7.0.6+ eventsource: 3.0.7+ eventsource-parser: 3.0.6+ express: 5.2.1+ express-rate-limit: 8.3.1([email protected])+ hono: 4.12.8+ jose: 6.2.2+ json-schema-typed: 8.0.2+ pkce-challenge: 5.0.1+ raw-body: 3.0.2+ zod: 4.3.6+ zod-to-json-schema: 3.25.1([email protected])+ optionalDependencies:+ '@cfworker/json-schema': 4.1.1+ transitivePeerDependencies:+ - supports-color+dependencies:'@hono/node-server': 1.19.12([email protected])@@ -18291,6 +18562,154 @@ snapshots:- vue-tsc- yaml+ '@octokit/[email protected]':+ dependencies:+ '@octokit/auth-app': 8.2.0+ '@octokit/auth-unauthenticated': 7.0.3+ '@octokit/core': 7.0.6+ '@octokit/oauth-app': 8.0.3+ '@octokit/plugin-paginate-rest': 14.0.0(@octokit/[email protected])+ '@octokit/types': 16.0.0+ '@octokit/webhooks': 14.2.0++ '@octokit/[email protected]':+ dependencies:+ '@octokit/auth-oauth-app': 9.0.3+ '@octokit/auth-oauth-user': 6.0.2+ '@octokit/request': 10.0.8+ '@octokit/request-error': 7.1.0+ '@octokit/types': 16.0.0+ toad-cache: 3.7.0+ universal-github-app-jwt: 2.2.2+ universal-user-agent: 7.0.3++ '@octokit/[email protected]':+ dependencies:+ '@octokit/auth-oauth-device': 8.0.3+ '@octokit/auth-oauth-user': 6.0.2+ '@octokit/request': 10.0.8+ '@octokit/types': 16.0.0+ universal-user-agent: 7.0.3++ '@octokit/[email protected]':+ dependencies:+ '@octokit/oauth-methods': 6.0.2+ '@octokit/request': 10.0.8+ '@octokit/types': 16.0.0+ universal-user-agent: 7.0.3++ '@octokit/[email protected]':+ dependencies:+ '@octokit/auth-oauth-device': 8.0.3+ '@octokit/oauth-methods': 6.0.2+ '@octokit/request': 10.0.8+ '@octokit/types': 16.0.0+ universal-user-agent: 7.0.3++ '@octokit/[email protected]': {}++ '@octokit/[email protected]':+ dependencies:+ '@octokit/request-error': 7.1.0+ '@octokit/types': 16.0.0++ '@octokit/[email protected]':+ dependencies:+ '@octokit/auth-token': 6.0.0+ '@octokit/graphql': 9.0.3+ '@octokit/request': 10.0.8+ '@octokit/request-error': 7.1.0+ '@octokit/types': 16.0.0+ before-after-hook: 4.0.0+ universal-user-agent: 7.0.3++ '@octokit/[email protected]':+ dependencies:+ '@octokit/types': 16.0.0+ universal-user-agent: 7.0.3++ '@octokit/[email protected]':+ dependencies:+ '@octokit/request': 10.0.8+ '@octokit/types': 16.0.0+ universal-user-agent: 7.0.3++ '@octokit/[email protected]':+ dependencies:+ '@octokit/auth-oauth-app': 9.0.3+ '@octokit/auth-oauth-user': 6.0.2+ '@octokit/auth-unauthenticated': 7.0.3+ '@octokit/core': 7.0.6+ '@octokit/oauth-authorization-url': 8.0.0+ '@octokit/oauth-methods': 6.0.2+ '@types/aws-lambda': 8.10.161+ universal-user-agent: 7.0.3++ '@octokit/[email protected]': {}++ '@octokit/[email protected]':+ dependencies:+ '@octokit/oauth-authorization-url': 8.0.0+ '@octokit/request': 10.0.8+ '@octokit/request-error': 7.1.0+ '@octokit/types': 16.0.0++ '@octokit/[email protected]': {}++ '@octokit/[email protected]': {}++ '@octokit/[email protected](@octokit/[email protected])':+ dependencies:+ '@octokit/core': 7.0.6++ '@octokit/[email protected](@octokit/[email protected])':+ dependencies:+ '@octokit/core': 7.0.6+ '@octokit/types': 16.0.0++ '@octokit/[email protected](@octokit/[email protected])':+ dependencies:+ '@octokit/core': 7.0.6+ '@octokit/types': 16.0.0++ '@octokit/[email protected](@octokit/[email protected])':+ dependencies:+ '@octokit/core': 7.0.6+ '@octokit/request-error': 7.1.0+ '@octokit/types': 16.0.0+ bottleneck: 2.19.5++ '@octokit/[email protected](@octokit/[email protected])':+ dependencies:+ '@octokit/core': 7.0.6+ '@octokit/types': 16.0.0+ bottleneck: 2.19.5++ '@octokit/[email protected]':+ dependencies:+ '@octokit/types': 16.0.0++ '@octokit/[email protected]':+ dependencies:+ '@octokit/endpoint': 11.0.3+ '@octokit/request-error': 7.1.0+ '@octokit/types': 16.0.0+ fast-content-type-parse: 3.0.0+ json-with-bigint: 3.5.8+ universal-user-agent: 7.0.3++ '@octokit/[email protected]':+ dependencies:+ '@octokit/openapi-types': 27.0.0++ '@octokit/[email protected]': {}++ '@octokit/[email protected]':+ dependencies:+ '@octokit/openapi-webhooks-types': 12.1.0+ '@octokit/request-error': 7.1.0+ '@octokit/webhooks-methods': 6.0.0+'@one-ini/[email protected]': {}'@opentelemetry/[email protected]':@@ -22661,6 +23080,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]':dependencies:'@babel/parser': 7.27.5@@ -24072,6 +24493,8 @@ snapshots:+ [email protected]: {}+dependencies:open: 8.4.2@@ -24126,6 +24549,8 @@ snapshots:+ [email protected]: {}+dependencies:stream-buffers: 2.2.0@@ -24477,7 +24902,7 @@ snapshots:dependencies:- mime-db: 1.52.0+ mime-db: 1.54.0dependencies:@@ -25456,7 +25881,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])([email protected]([email protected])))([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:@@ -25478,7 +25903,7 @@ snapshots:doctrine: 2.1.0eslint: 9.29.0([email protected])eslint-import-resolver-node: 0.3.9- eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected]))+ eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])([email protected]([email protected])))([email protected]([email protected]))hasown: 2.0.2is-core-module: 2.16.1is-glob: 4.0.3@@ -25845,6 +26270,11 @@ snapshots:+ dependencies:+ express: 5.2.1+ ip-address: 10.1.0+dependencies:express: 5.2.1@@ -25934,6 +26364,8 @@ snapshots:pathe: 1.1.2ufo: 1.6.3+ [email protected]: {}+@@ -26179,7 +26611,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])):dependencies:'@mdx-js/mdx': 3.1.1'@standard-schema/spec': 1.1.0@@ -26668,6 +27100,8 @@ snapshots:optionalDependencies:hono: 4.12.9+ [email protected]: {}+@@ -27288,6 +27722,8 @@ snapshots:+ [email protected]: {}+dependencies:minimist: 1.2.8@@ -27341,7 +27777,7 @@ snapshots:vscode-languageserver-textdocument: 1.0.12vscode-uri: 3.1.0- [email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])):dependencies:'@types/uuid': 10.0.0chalk: 4.1.2@@ -27352,7 +27788,7 @@ snapshots:optionalDependencies:'@opentelemetry/api': 1.9.0'@opentelemetry/sdk-trace-base': 2.2.0(@opentelemetry/[email protected])- openai: 4.104.0([email protected])([email protected])+ openai: 4.104.0([email protected])@@ -29081,6 +29517,20 @@ snapshots:+ dependencies:+ '@octokit/app': 16.1.2+ '@octokit/core': 7.0.6+ '@octokit/oauth-app': 8.0.3+ '@octokit/plugin-paginate-graphql': 6.0.0(@octokit/[email protected])+ '@octokit/plugin-paginate-rest': 14.0.0(@octokit/[email protected])+ '@octokit/plugin-rest-endpoint-methods': 17.0.0(@octokit/[email protected])+ '@octokit/plugin-retry': 8.1.0(@octokit/[email protected])+ '@octokit/plugin-throttling': 11.0.3(@octokit/[email protected])+ '@octokit/request-error': 7.1.0+ '@octokit/types': 16.0.0+ '@octokit/webhooks': 14.2.0+dependencies:destr: 2.0.5@@ -29152,7 +29602,7 @@ snapshots:is-docker: 2.2.1is-wsl: 2.2.0dependencies:'@types/node': 18.19.130'@types/node-fetch': 2.6.11@@ -29163,12 +29613,11 @@ snapshots:node-fetch: 2.7.0optionalDependencies:ws: 8.20.0- zod: 3.25.76+ zod: 4.3.6transitivePeerDependencies:- encoding- optional: truedependencies:'@types/node': 18.19.130'@types/node-fetch': 2.6.11@@ -29178,10 +29627,10 @@ snapshots:formdata-node: 4.4.1node-fetch: 2.7.0optionalDependencies:- ws: 8.20.0- zod: 4.3.6+ zod: 3.25.76transitivePeerDependencies:- encoding+ optional: trueoptionalDependencies:@@ -31695,6 +32144,8 @@ snapshots:dependencies:is-number: 7.0.0+ [email protected]: {}+@@ -31975,6 +32426,10 @@ snapshots:unist-util-is: 6.0.0unist-util-visit-parents: 6.0.1+ [email protected]: {}++ [email protected]: {}+@@ -32791,6 +33246,10 @@ snapshots:dependencies:zod: 4.3.6+ dependencies:+ zod: 4.3.6+dependencies:zod: 3.25.76