The Open Standard for Generative UI
Adds Grok Build harness example (#791)
Visharad Kashyap9c72eeffdc2d
diff --git a/examples/harnesses/grok-build/.env.example b/examples/harnesses/grok-build/.env.examplenew file mode 100644index 000000000..acd68f322--- /dev/null+++ b/examples/harnesses/grok-build/.env.example@@ -0,0 +1,18 @@+# Authenticate once with `grok login`, or set an API key for headless environments.+# XAI_API_KEY=xai-...++# Grok Build executable. Defaults to `grok` on PATH.+# GROK_BUILD_BIN=/absolute/path/to/grok++# Workspace the coding agent can inspect and modify. Defaults to this example directory.+# GROK_BUILD_CWD=/absolute/path/to/project++# Optional model override. When omitted, the installed Grok Build CLI chooses its configured default.+# GROK_BUILD_MODEL=++# Headless tool execution is auto-approved by default so turns cannot stall on a terminal prompt.+# Set this to false and configure Grok permissions if you do not want that behavior.+# GROK_BUILD_ALWAYS_APPROVE=true++# Optional model reasoning effort.+# GROK_BUILD_REASONING_EFFORT=highdiff --git a/examples/harnesses/grok-build/.gitignore b/examples/harnesses/grok-build/.gitignorenew file mode 100644index 000000000..2655c8cd8--- /dev/null+++ b/examples/harnesses/grok-build/.gitignore@@ -0,0 +1,4 @@+node_modules/+.next/+.env*+!.env.examplediff --git a/examples/harnesses/grok-build/README.md b/examples/harnesses/grok-build/README.mdnew file mode 100644index 000000000..e854266df--- /dev/null+++ b/examples/harnesses/grok-build/README.md@@ -0,0 +1,155 @@+# OpenUI + Grok Build Harness++An [OpenUI](https://openui.com) coding-agent demo backed by+[Grok Build](https://github.com/xai-org/grok-build). The app uses OpenUI's+`<AgentInterface />` for the chat surface and Grok Build's official Agent Client Protocol (ACP)+stdio mode for persistent coding sessions, live reasoning, tool activity, and cancellation.++## What this demonstrates++- A current OpenUI `<AgentInterface />` wired with `agUIAdapter()` and `openuiChatLibrary`.+- One long-lived `grok agent --no-leader stdio` process hosting an isolated Grok session for each+ OpenUI thread.+- ACP text, reasoning, and tool-call updates translated to AG-UI SSE events.+- Retry-safe OpenUI output buffering: valid candidates are checkpointed across retries, the final+ candidate is validated against the generated component schema, then revealed in paced chunks.+- One bounded, parser-guided correction turn when Grok's final OpenUI has syntax errors or unresolved+ references. Invalid source is never exposed as the main assistant response.+- The generated OpenUI component-library prompt injected as Grok session `rules`, preserving Grok+ Build's native coding-agent instructions and tools.+- Browser thread metadata and transcripts stored in `localStorage`, with the same UUID used for the+ persisted Grok session.++## Prerequisites++- Node.js 22 and pnpm 9+- The released `grok` CLI on `PATH`+- A Grok login or `XAI_API_KEY`++Install Grok Build by following the+[official installation instructions](https://github.com/xai-org/grok-build#installing-the-released-binary),+then authenticate:++```bash+grok login+grok --version+```++For a non-interactive environment, set `XAI_API_KEY` instead.++## Run locally++Install dependencies from the OpenUI repository root:++```bash+pnpm install+```++Then start the example:++```bash+cd examples/harnesses/grok-build+cp .env.example .env.local+pnpm dev+```++Open [http://localhost:3000](http://localhost:3000). To let Grok work on a different project, set+`GROK_BUILD_CWD` in `.env.local` before starting the server.++## How it works++```text+Browser / OpenUI AgentInterface+ | localStorage threads + transcript+ | POST /api/chat { threadId, messages }+ v+Next.js route+ | latest user turn+ v+Grok ACP client ──► grok agent --always-approve --no-leader stdio+ | | one persisted session per OpenUI thread UUID+ | | repository tools + model+ | v+ |◄── ACP session/update: thought, text, tool_call, tool_call_update+ v+ACP-to-AG-UI bridge ──► SSE ──► AgentInterface + OpenUI renderer+```++The server starts one ACP process lazily and authenticates using the method advertised by the+installed Grok Build CLI. A new OpenUI thread creates a Grok session with the same UUID. Restored+browser threads use `session/load`, so Grok's on-disk conversation state survives a Next.js restart.+If a restored browser transcript no longer has a matching Grok session on disk, the route fails+explicitly instead of silently continuing with empty model context.++The system prompt and validation schema are derived directly from `src/library.ts` in memory. The+prompt is attached to `session/new` as ACP `_meta.rules`; it teaches Grok to produce the exact+OpenUI Lang understood by the `openuiChatLibrary` passed to `AgentInterface`. The schema lets the+server verify that the final candidate has a renderable `Card` root before any assistant text+reaches the browser.++The event bridge maps Grok ACP updates as follows:++```text+agent_thought_chunk -> Thinking tool card+tool_call -> TOOL_CALL_START + TOOL_CALL_ARGS+tool_call_update -> TOOL_CALL_END + TOOL_CALL_RESULT+agent_message_chunk -> latest OpenUI candidate buffer+retry_state -> checkpoint valid output + rotate Thinking state+prompt response -> validate, optionally correct once, then paced TEXT_MESSAGE_CONTENT + END+```++Grok Build may emit progress prose and multiple full answers during one ACP prompt when an xAI+request is retried. AG-UI text deltas are append-only, so sending those candidates immediately+would concatenate them into invalid OpenUI Lang. This harness keeps only the latest line-start+`root = ...` candidate. If no valid candidate can be recovered, the harness asks Grok for one+parser-guided correction without tools. If that still fails, it renders a concise valid warning card+instead of exposing raw OpenUI or surfacing a renderer `parse-failed` warning.++OpenUI delivery rules are attached when a Grok session is created. Start a new browser thread after+changing the component library or prompt options so the corresponding Grok session gets the new+rules.++The browser transcript persists user and assistant text, matching the lightweight Eve example.+Reasoning and tool cards are streamed live but are not restored after a page reload. Deleting an+OpenUI browser thread removes its local transcript; it does not delete Grok Build's on-disk session.++Grok's interactive ask-user and exit-plan-mode ACP extension requests are cancelled immediately+because this demo does not implement their dedicated response UI. Normal tool permissions are+auto-approved when `GROK_BUILD_ALWAYS_APPROVE=true`.++## Configuration++| Environment variable | Default | Purpose |+| ----------------------------- | ------------------------ | --------------------------------------------------- |+| `XAI_API_KEY` | existing `grok login` | Non-interactive Grok authentication |+| `GROK_BUILD_BIN` | `grok` | Grok Build executable |+| `GROK_BUILD_CWD` | this example's directory | Workspace the coding agent can inspect and modify |+| `GROK_BUILD_MODEL` | CLI-configured default | Optional model override |+| `GROK_BUILD_REASONING_EFFORT` | CLI-configured default | Optional reasoning-effort override |+| `GROK_BUILD_ALWAYS_APPROVE` | `true` | Auto-approve Grok tool execution in the web harness |++## Project layout++```text+examples/harnesses/grok-build/+|- src/app/page.tsx # OpenUI AgentInterface+|- src/app/api/chat/route.ts # AG-UI SSE route+|- src/lib/grok-build-acp.ts # Grok ACP process, auth, sessions, prompts, cancellation+|- src/lib/grok-build-stream.ts # ACP session updates to AG-UI events+|- src/lib/openui-output.ts # Retry-safe validation, fallback, and paced output chunks+|- src/lib/grok-build-chat.ts # AgentInterface LLM + storage adapters+|- src/lib/thread-store.ts # localStorage thread/transcript persistence+`- src/library.ts # OpenUI library, prompt options, and validation schema+```++## Security++This is a local, single-user coding-agent harness. Its API route is unauthenticated, and+`GROK_BUILD_ALWAYS_APPROVE=true` gives Grok Build permission to run tools with the server user's+filesystem and process privileges inside—and potentially beyond—`GROK_BUILD_CWD`.++Do not expose this server to a network as-is. Add authentication and authorization, run the agent+inside an OS-level sandbox or container, restrict network access and credentials, and configure+Grok's permission policy for the deployment. Setting `GROK_BUILD_ALWAYS_APPROVE=false` makes this+demo cancel permission requests because `AgentInterface` does not currently provide a Grok-specific+approval/resume UI.diff --git a/examples/harnesses/grok-build/eslint.config.mjs b/examples/harnesses/grok-build/eslint.config.mjsnew file mode 100644index 000000000..c22de0bd9--- /dev/null+++ b/examples/harnesses/grok-build/eslint.config.mjs@@ -0,0 +1,11 @@+import nextVitals from "eslint-config-next/core-web-vitals";+import nextTs from "eslint-config-next/typescript";+import { defineConfig, globalIgnores } from "eslint/config";++const eslintConfig = defineConfig([+ ...nextVitals,+ ...nextTs,+ globalIgnores([".next/**", "out/**", "build/**", "next-env.d.ts"]),+]);++export default eslintConfig;diff --git a/examples/harnesses/grok-build/next-env.d.ts b/examples/harnesses/grok-build/next-env.d.tsnew file mode 100644index 000000000..9edff1c7c--- /dev/null+++ b/examples/harnesses/grok-build/next-env.d.ts@@ -0,0 +1,6 @@+/// <reference types="next" />+/// <reference types="next/image-types/global" />+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/harnesses/grok-build/next.config.ts b/examples/harnesses/grok-build/next.config.tsnew file mode 100644index 000000000..e1a6241cd--- /dev/null+++ b/examples/harnesses/grok-build/next.config.ts@@ -0,0 +1,23 @@+import type { NextConfig } from "next";++const nextConfig: NextConfig = {+ webpack: (config, { isServer }) => {+ if (isServer) {+ const externalizeOpenUI = (+ { request }: { request?: string },+ callback: (error?: null, result?: string) => void,+ ) => {+ if (request === "@openuidev/react-ui/genui-lib") {+ return callback(null, `commonjs ${request}`);+ }+ return callback();+ };+ config.externals = Array.isArray(config.externals)+ ? [externalizeOpenUI, ...config.externals]+ : [externalizeOpenUI];+ }+ return config;+ },+};++export default nextConfig;diff --git a/examples/harnesses/grok-build/package.json b/examples/harnesses/grok-build/package.jsonnew file mode 100644index 000000000..62ef7b120--- /dev/null+++ b/examples/harnesses/grok-build/package.json@@ -0,0 +1,36 @@+{+ "name": "grok-build-harness",+ "version": "0.1.0",+ "private": true,+ "scripts": {+ "dev": "next dev --webpack",+ "build": "next build --webpack",+ "start": "next start",+ "lint": "eslint",+ "test": "vitest run",+ "typecheck": "tsc --noEmit"+ },+ "dependencies": {+ "@ag-ui/core": "^0.0.53",+ "@agentclientprotocol/sdk": "0.10.0",+ "@openuidev/lang-core": "workspace:*",+ "@openuidev/react-headless": "workspace:*",+ "@openuidev/react-lang": "workspace:*",+ "@openuidev/react-ui": "workspace:*",+ "next": "16.2.6",+ "react": "19.2.3",+ "react-dom": "19.2.3",+ "zod": "4.4.3"+ },+ "devDependencies": {+ "@tailwindcss/postcss": "^4",+ "@types/node": "catalog:",+ "@types/react": "^19",+ "@types/react-dom": "^19",+ "eslint": "^9",+ "eslint-config-next": "16.2.6",+ "tailwindcss": "^4",+ "typescript": "^5",+ "vitest": "^4.0.18"+ }+}diff --git a/examples/harnesses/grok-build/postcss.config.mjs b/examples/harnesses/grok-build/postcss.config.mjsnew file mode 100644index 000000000..61e36849c--- /dev/null+++ b/examples/harnesses/grok-build/postcss.config.mjs@@ -0,0 +1,7 @@+const config = {+ plugins: {+ "@tailwindcss/postcss": {},+ },+};++export default config;diff --git a/examples/harnesses/grok-build/src/app/api/chat/route.ts b/examples/harnesses/grok-build/src/app/api/chat/route.tsnew file mode 100644index 000000000..0f7d107c8--- /dev/null+++ b/examples/harnesses/grok-build/src/app/api/chat/route.ts@@ -0,0 +1,164 @@+import {+ formatGrokBuildError,+ GrokBuildBusyError,+ isGrokBuildThreadBusy,+ runGrokBuildTurn,+} from "@/lib/grok-build-acp";+import { GrokBuildAGUIBridge } from "@/lib/grok-build-stream";+import { EventType, type AGUIEvent } from "@ag-ui/core";+import type { Message } from "@openuidev/react-headless";+import type { NextRequest } from "next/server";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++interface ChatBody {+ messages?: Message[];+ threadId?: string;+}++const encoder = new TextEncoder();+const STREAM_FRAME_MS = 16;+const TOOL_TRANSITION_MS = 24;++function pause(milliseconds: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, milliseconds));+}++function messageText(message: Pick<Message, "content">): string {+ const content = message.content as unknown;+ if (typeof content === "string") return content;+ if (Array.isArray(content)) {+ return content+ .map((part) =>+ part && typeof part === "object" && "text" in part+ ? String((part as { text?: unknown }).text ?? "")+ : "",+ )+ .join("\n");+ }+ return "";+}++function latestUserText(messages: Message[] | undefined): string {+ const user = [...(messages ?? [])].reverse().find((message) => message.role === "user");+ return user ? messageText(user).trim() : "";+}++function sse(event: AGUIEvent | "[DONE]"): Uint8Array {+ return encoder.encode(+ event === "[DONE]" ? "data: [DONE]\n\n" : `data: ${JSON.stringify(event)}\n\n`,+ );+}++export async function POST(request: NextRequest) {+ const body = (await request.json().catch(() => ({}))) as ChatBody;+ const messages = body.messages ?? [];+ const conversationId = body.threadId?.trim() || crypto.randomUUID();+ const prompt = latestUserText(messages);++ if (!prompt) {+ return Response.json({ error: "No user message was provided." }, { status: 400 });+ }+ if (isGrokBuildThreadBusy(conversationId)) {+ return Response.json(+ { error: "Grok Build is still responding to your previous message." },+ { status: 409 },+ );+ }++ const bridge = new GrokBuildAGUIBridge();+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ let closed = false;+ let pending = Promise.resolve();+ const enqueue = (event: AGUIEvent | "[DONE]") => {+ if (closed) return;+ try {+ controller.enqueue(sse(event));+ } catch {+ closed = true;+ }+ };+ const queueEvents = (events: AGUIEvent[]): Promise<void> => {+ pending = pending.then(async () => {+ for (const event of events) {+ if (closed) return;+ enqueue(event);+ if (event.type === EventType.TEXT_MESSAGE_CONTENT) {+ await pause(STREAM_FRAME_MS);+ } else if (event.type === EventType.TOOL_CALL_RESULT) {+ // Give the completed card a paint before the next lifecycle starts.+ await pause(TOOL_TRANSITION_MS);+ }+ }+ });+ return pending;+ };+ const finish = async () => {+ if (closed) return;+ await queueEvents(bridge.finish());+ if (closed) return;+ enqueue("[DONE]");+ closed = true;+ try {+ controller.close();+ } catch {+ // The browser may already have closed the stream.+ }+ };++ const onUpdate: Parameters<typeof runGrokBuildTurn>[0]["onUpdate"] = (update) => {+ void queueEvents(bridge.consume(update));+ };++ void (async () => {+ try {+ await runGrokBuildTurn({+ sessionId: conversationId,+ prompt,+ hasHistory: messages.some((message) => message.role === "assistant"),+ signal: request.signal,+ onUpdate,+ });++ // One bounded parser-guided repair. It is an internal continuation of+ // the same Grok session and explicitly forbids additional tool calls.+ if (bridge.needsCorrection() && !request.signal.aborted) {+ const correctionPrompt = bridge.correctionPrompt();+ await queueEvents(bridge.beginCorrection());+ await runGrokBuildTurn({+ sessionId: conversationId,+ prompt: correctionPrompt,+ hasHistory: true,+ signal: request.signal,+ onUpdate,+ });+ }+ } catch (error: unknown) {+ if (request.signal.aborted) {+ await queueEvents(bridge.fail("Turn cancelled."));+ return;+ }+ const message =+ error instanceof GrokBuildBusyError+ ? error.message+ : formatGrokBuildError(error);+ await queueEvents(bridge.fail(message));+ await queueEvents([{ type: EventType.RUN_ERROR, message } as AGUIEvent]);+ } finally {+ await finish();+ }+ })();+ },+ });++ return new Response(stream, {+ headers: {+ "Cache-Control": "no-cache, no-transform",+ Connection: "keep-alive",+ "Content-Type": "text/event-stream",+ "x-conversation-id": conversationId,+ },+ });+}diff --git a/examples/harnesses/grok-build/src/app/globals.css b/examples/harnesses/grok-build/src/app/globals.cssnew file mode 100644index 000000000..a836e4cda--- /dev/null+++ b/examples/harnesses/grok-build/src/app/globals.css@@ -0,0 +1,13 @@+@import "tailwindcss";++html,+body {+ margin: 0;+}++.app-shell {+ height: 100vh;+ overflow: hidden;+ position: relative;+ width: 100vw;+}diff --git a/examples/harnesses/grok-build/src/app/layout.tsx b/examples/harnesses/grok-build/src/app/layout.tsxnew file mode 100644index 000000000..ec7c72032--- /dev/null+++ b/examples/harnesses/grok-build/src/app/layout.tsx@@ -0,0 +1,23 @@+import { ThemeProvider } from "@/hooks/use-system-theme";+import type { Metadata } from "next";+import "@openuidev/react-ui/styles/index.css";+import "./globals.css";++export const metadata: Metadata = {+ title: "Grok Build + OpenUI",+ description: "OpenUI Agent Interface powered by the Grok Build coding-agent harness",+};++export default function RootLayout({+ children,+}: Readonly<{+ children: React.ReactNode;+}>) {+ return (+ <html lang="en">+ <body>+ <ThemeProvider>{children}</ThemeProvider>+ </body>+ </html>+ );+}diff --git a/examples/harnesses/grok-build/src/app/page.tsx b/examples/harnesses/grok-build/src/app/page.tsxnew file mode 100644index 000000000..9eceafe24--- /dev/null+++ b/examples/harnesses/grok-build/src/app/page.tsx@@ -0,0 +1,47 @@+"use client";++import { useTheme } from "@/hooks/use-system-theme";+import { createGrokBuildChatProps } from "@/lib/grok-build-chat";+import { AgentInterface } from "@openuidev/react-ui";+import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";+import { useMemo } from "react";++export default function Page() {+ const mode = useTheme();+ const { llm, storage } = useMemo(() => createGrokBuildChatProps(), []);++ return (+ <div className="app-shell">+ <AgentInterface+ llm={llm}+ storage={storage}+ componentLibrary={openuiChatLibrary}+ agentName="Grok Build + OpenUI"+ theme={{ mode }}+ starterVariant="short"+ starters={[+ {+ displayText: "Map this repository",+ prompt:+ "Inspect this repository and build a concise architecture map with the key packages and how they connect.",+ },+ {+ displayText: "Review current changes",+ prompt:+ "Review the current git changes and show the important findings, risks, and recommended next actions.",+ },+ {+ displayText: "Plan a feature",+ prompt:+ "Create an implementation plan for adding a health-check endpoint, including files, dependencies, tests, and risks.",+ },+ {+ displayText: "Summarize test health",+ prompt:+ "Inspect the available test commands and present a test-health dashboard with the highest-value checks to run.",+ },+ ]}+ />+ </div>+ );+}diff --git a/examples/harnesses/grok-build/src/hooks/use-system-theme.tsx b/examples/harnesses/grok-build/src/hooks/use-system-theme.tsxnew file mode 100644index 000000000..aa70c3a70--- /dev/null+++ b/examples/harnesses/grok-build/src/hooks/use-system-theme.tsx@@ -0,0 +1,39 @@+"use client";++import { createContext, useContext, useLayoutEffect, 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);++ useLayoutEffect(() => {+ const media = window.matchMedia("(prefers-color-scheme: dark)");+ const onChange = (event: MediaQueryListEvent) => setMode(event.matches ? "dark" : "light");+ media.addEventListener("change", onChange);+ return () => media.removeEventListener("change", onChange);+ }, []);++ useLayoutEffect(() => {+ document.body.setAttribute("data-theme", mode);+ }, [mode]);++ return <ThemeContext.Provider value={{ mode }}>{children}</ThemeContext.Provider>;+}++export function useTheme(): ThemeMode {+ const context = useContext(ThemeContext);+ if (!context) throw new Error("useTheme must be used within a ThemeProvider");+ return context.mode;+}diff --git a/examples/harnesses/grok-build/src/lib/grok-build-acp.ts b/examples/harnesses/grok-build/src/lib/grok-build-acp.tsnew file mode 100644index 000000000..b9369e499--- /dev/null+++ b/examples/harnesses/grok-build/src/lib/grok-build-acp.ts@@ -0,0 +1,579 @@+import {+ ClientSideConnection,+ PROTOCOL_VERSION,+ RequestError,+ ndJsonStream,+ type Client,+ type InitializeResponse,+ type RequestPermissionRequest,+ type RequestPermissionResponse,+ type SessionNotification,+ type SessionUpdate,+} from "@agentclientprotocol/sdk";+import { spawn } from "node:child_process";+import { createHash } from "node:crypto";+import { Readable, Writable } from "node:stream";+import { systemPrompt } from "../library";++const OPENUI_RULES = systemPrompt;+const OPENUI_RULES_HASH = createHash("sha256").update(OPENUI_RULES).digest("hex");++const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;++interface GrokBuildConfig {+ alwaysApprove: boolean;+ bin: string;+ cwd: string;+ model?: string;+ reasoningEffort?: string;+}++interface GrokBuildRetryState {+ attempt?: number;+ error_type?: string;+ max_retries?: number;+ message?: string;+ reason?: string;+ sessionUpdate: "retry_state";+ type?: string;+}++interface GrokBuildTurnCompleted {+ agent_result?: string;+ sessionUpdate: "turn_completed";+ stop_reason?: string;+ usage?: Record<string, unknown>;+}++export type GrokBuildSessionUpdate =+ | SessionUpdate+ | GrokBuildRetryState+ | GrokBuildTurnCompleted;++type UpdateListener = (update: GrokBuildSessionUpdate) => void;++const GROK_SESSION_NOTIFICATION_METHODS = new Set([+ "_x.ai/session_notification",+ "x.ai/session_notification",+ "_x.ai/session/update",+ "x.ai/session/update",+]);++export function decodeGrokSessionNotification(+ method: string,+ params: Record<string, unknown>,+): { sessionId: string; update: GrokBuildSessionUpdate } | undefined {+ if (!GROK_SESSION_NOTIFICATION_METHODS.has(method)) return undefined;+ const sessionId = params.sessionId;+ const update = recordValue(params.update);+ const kind = update?.sessionUpdate;+ if (+ typeof sessionId !== "string" ||+ (kind !== "retry_state" && kind !== "turn_completed")+ ) {+ return undefined;+ }+ return { sessionId, update: update as unknown as GrokBuildSessionUpdate };+}++function optionalEnv(name: string): string | undefined {+ const value = process.env[name]?.trim();+ return value || undefined;+}++function booleanEnv(name: string, fallback: boolean): boolean {+ const value = optionalEnv(name)?.toLowerCase();+ if (!value) return fallback;+ return !["0", "false", "no", "off"].includes(value);+}++function readConfig(): GrokBuildConfig {+ return {+ alwaysApprove: booleanEnv("GROK_BUILD_ALWAYS_APPROVE", true),+ bin: optionalEnv("GROK_BUILD_BIN") ?? "grok",+ cwd: optionalEnv("GROK_BUILD_CWD") ?? process.cwd(),+ model: optionalEnv("GROK_BUILD_MODEL"),+ reasoningEffort: optionalEnv("GROK_BUILD_REASONING_EFFORT"),+ };+}++function configSignature(config: GrokBuildConfig): string {+ return JSON.stringify({ ...config, openUIRulesHash: OPENUI_RULES_HASH });+}++function recordValue(value: unknown): Record<string, unknown> | undefined {+ return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;+}++function errorData(error: unknown): unknown {+ if (error instanceof RequestError) return error.data;+ return recordValue(error)?.data;+}++export function formatGrokBuildError(error: unknown): string {+ const errorRecord = recordValue(error);+ const message =+ error instanceof Error+ ? error.message === "[object Object]"+ ? "Grok Build request failed"+ : error.message+ : typeof errorRecord?.message === "string"+ ? errorRecord.message+ : errorRecord+ ? issueSafeJson(errorRecord)+ : String(error);+ const data = errorData(error);+ if (data === undefined) return message;+ if (typeof data === "string") return `${message}: ${data}`;+ return `${message}: ${issueSafeJson(data)}`;+}++function issueSafeJson(value: unknown): string {+ try {+ return JSON.stringify(value);+ } catch {+ return String(value);+ }+}++function looksMissing(error: unknown): boolean {+ const code = recordValue(errorData(error))?.code;+ if (code === "FS_NOT_FOUND") return true;+ return /not found|no such|unknown session|does not exist|failed to (read|load)/i.test(+ formatGrokBuildError(error),+ );+}++function withTimeout<T>(promise: Promise<T>, milliseconds: number, label: string): Promise<T> {+ return new Promise<T>((resolvePromise, rejectPromise) => {+ const timer = setTimeout(() => rejectPromise(new Error(`${label} timed out.`)), milliseconds);+ timer.unref?.();+ promise.then(+ (value) => {+ clearTimeout(timer);+ resolvePromise(value);+ },+ (error) => {+ clearTimeout(timer);+ rejectPromise(error);+ },+ );+ });+}++function preferredAuthMethod(response: InitializeResponse): string | undefined {+ const methods = response.authMethods ?? [];+ const preferred = response._meta?.defaultAuthMethodId;+ if (typeof preferred === "string" && methods.some((method) => method.id === preferred)) {+ return preferred;+ }+ return methods[0]?.id;+}++/** A single long-lived Grok ACP process that can host multiple OpenUI sessions. */+class GrokBuildACPClient {+ readonly signature: string;++ private readonly activeThreads = new Set<string>();+ private readonly child;+ private readonly config: GrokBuildConfig;+ private readonly connection: ClientSideConnection;+ private readonly listeners = new Map<string, Set<UpdateListener>>();+ private readonly openingSessions = new Map<string, Promise<void>>();+ private readonly residentSessions = new Set<string>();+ private processError: Error | undefined;+ private stderrTail = "";++ private constructor(config: GrokBuildConfig) {+ this.config = config;+ this.signature = configSignature(config);++ const args = ["agent"];+ if (config.model) args.push("--model", config.model);+ if (config.reasoningEffort) args.push("--reasoning-effort", config.reasoningEffort);+ if (config.alwaysApprove) args.push("--always-approve");+ args.push("--no-leader", "stdio");++ this.child = spawn(config.bin, args, {+ cwd: config.cwd,+ env: process.env,+ stdio: ["pipe", "pipe", "pipe"],+ });++ this.child.on("error", (error) => {+ this.processError = error;+ });+ this.child.stderr?.setEncoding("utf8");+ this.child.stderr?.on("data", (chunk: string) => {+ this.stderrTail = `${this.stderrTail}${chunk}`.slice(-12_000);+ });++ if (!this.child.stdin || !this.child.stdout) {+ throw new Error("Grok Build did not expose ACP stdio streams.");+ }++ const stream = ndJsonStream(+ Writable.toWeb(this.child.stdin) as WritableStream<Uint8Array>,+ Readable.toWeb(this.child.stdout) as ReadableStream<Uint8Array>,+ );+ const client: Client = {+ requestPermission: (request) => this.requestPermission(request),+ sessionUpdate: (notification) => this.sessionUpdate(notification),+ extMethod: (method) => this.extensionRequest(method),+ extNotification: (method, params) => this.extensionNotification(method, params),+ };+ this.connection = new ClientSideConnection(() => client, stream);+ }++ static async create(config: GrokBuildConfig): Promise<GrokBuildACPClient> {+ const client = new GrokBuildACPClient(config);+ try {+ const initialized = await withTimeout(+ client.request("Grok Build ACP initialization", () =>+ client.connection.initialize({+ protocolVersion: PROTOCOL_VERSION,+ clientCapabilities: {+ fs: { readTextFile: false, writeTextFile: false },+ terminal: false,+ },+ clientInfo: {+ name: "OpenUI Grok Build Harness",+ version: "0.1.0",+ },+ _meta: {+ clientType: "openui-grok-build-harness",+ clientVersion: "0.1.0",+ startupHints: {+ nonInteractive: true,+ skipGitStatus: true,+ skipProjectLayout: true,+ },+ },+ }),+ ),+ 30_000,+ "Grok Build ACP initialization",+ );++ const authMethod = preferredAuthMethod(initialized);+ if (authMethod) {+ await withTimeout(+ client.request("Grok Build authentication", () =>+ client.connection.authenticate({+ methodId: authMethod,+ _meta: { headless: true },+ }),+ ),+ 30_000,+ "Grok Build authentication",+ );+ }+ return client;+ } catch (error) {+ client.dispose();+ const processDetail = client.processError ? ` ${client.processError.message}` : "";+ const stderr = client.stderrTail.trim();+ const stderrDetail = stderr ? `\n\nGrok stderr:\n${stderr}` : "";+ throw new Error(+ `Could not start Grok Build ACP.${processDetail} ${formatGrokBuildError(error)}${stderrDetail}\n\n` ++ "Install the `grok` CLI and run `grok login`, or set XAI_API_KEY.",+ );+ }+ }++ get alive(): boolean {+ return !this.connection.signal.aborted && this.child.exitCode === null;+ }++ isBusy(threadId: string): boolean {+ return this.activeThreads.has(threadId);+ }++ dispose(): void {+ if (this.child.exitCode === null) this.child.kill("SIGTERM");+ }++ private connectionClosedError(label: string): Error {+ const cause = this.processError?.message+ ? `: ${this.processError.message}`+ : this.child.signalCode+ ? ` (signal ${this.child.signalCode})`+ : this.child.exitCode !== null+ ? ` (exit ${this.child.exitCode})`+ : "";+ const stderr = this.stderrTail.trim();+ return new Error(+ `${label} stopped because the Grok Build ACP process exited${cause}.` ++ (stderr ? `\n\nGrok stderr:\n${stderr}` : ""),+ );+ }++ /**+ * The ACP SDK currently leaves an in-flight request pending when its stdio+ * transport closes. Race every request against the connection signal so a+ * crashed CLI releases the route and its per-thread busy flag immediately.+ */+ private async request<T>(label: string, operation: () => Promise<T>): Promise<T> {+ const signal = this.connection.signal;+ if (signal.aborted || this.child.exitCode !== null) throw this.connectionClosedError(label);++ let onClose: (() => void) | undefined;+ const closed = new Promise<never>((_, reject) => {+ onClose = () => reject(this.connectionClosedError(label));+ signal.addEventListener("abort", onClose, { once: true });+ });++ try {+ return await Promise.race([operation(), closed]);+ } finally {+ if (onClose) signal.removeEventListener("abort", onClose);+ }+ }++ private async requestPermission(+ request: RequestPermissionRequest,+ ): Promise<RequestPermissionResponse> {+ if (this.config.alwaysApprove) {+ // Match Grok's own headless helper: grant only this invocation whenever+ // possible, falling back to a persistent grant only when it is the sole+ // affirmative option.+ const option =+ request.options.find((candidate) => candidate.kind === "allow_once") ??+ request.options.find((candidate) => candidate.kind === "allow_always");+ if (option) {+ return { outcome: { outcome: "selected", optionId: option.optionId } };+ }+ }+ return { outcome: { outcome: "cancelled" } };+ }++ private async extensionRequest(method: string): Promise<Record<string, unknown>> {+ // Grok's conversational questions and plan approval are interactive ACP+ // extension requests, independent of normal tool permissions. AgentInterface+ // does not expose their response UI, so answer immediately and explicitly;+ // leaving either request pending would hang the prompt turn.+ if (method === "_x.ai/ask_user_question" || method === "x.ai/ask_user_question") {+ return { outcome: "cancelled" };+ }+ if (method === "_x.ai/exit_plan_mode" || method === "x.ai/exit_plan_mode") {+ return { outcome: "cancelled" };+ }+ throw RequestError.methodNotFound(method);+ }++ private async extensionNotification(+ method: string,+ params: Record<string, unknown>,+ ): Promise<void> {+ const notification = decodeGrokSessionNotification(method, params);+ if (notification) this.notifyListeners(notification.sessionId, notification.update);+ }++ private notifyListeners(sessionId: string, update: GrokBuildSessionUpdate): void {+ const listeners = this.listeners.get(sessionId);+ if (!listeners) return;+ for (const listener of listeners) listener(update);+ }++ private async sessionUpdate(notification: SessionNotification): Promise<void> {+ this.notifyListeners(notification.sessionId, notification.update);+ }++ private subscribe(sessionId: string, listener: UpdateListener): () => void {+ const listeners = this.listeners.get(sessionId) ?? new Set<UpdateListener>();+ listeners.add(listener);+ this.listeners.set(sessionId, listeners);+ return () => {+ listeners.delete(listener);+ if (listeners.size === 0) this.listeners.delete(sessionId);+ };+ }++ private async createSession(sessionId: string): Promise<void> {+ await this.request("Creating the Grok Build session", () =>+ this.connection.newSession({+ cwd: this.config.cwd,+ mcpServers: [],+ _meta: {+ clientIdentifier: "openui-grok-build-harness",+ rules: OPENUI_RULES,+ sessionId,+ yoloMode: this.config.alwaysApprove,+ },+ }),+ );+ }++ private async loadSession(sessionId: string): Promise<void> {+ await this.request("Loading the Grok Build session", () =>+ this.connection.loadSession({+ cwd: this.config.cwd,+ mcpServers: [],+ sessionId,+ _meta: { clientIdentifier: "openui-grok-build-harness" },+ }),+ );+ }++ private async ensureSession(sessionId: string, hasHistory: boolean): Promise<void> {+ if (!UUID_PATTERN.test(sessionId)) {+ throw new Error(`OpenUI thread id ${JSON.stringify(sessionId)} is not a valid UUID.`);+ }+ if (this.residentSessions.has(sessionId)) return;++ const existing = this.openingSessions.get(sessionId);+ if (existing) return existing;++ const opening = (async () => {+ // Grok's session/new accepts an existing on-disk UUID but starts it with+ // an empty chat history. Loading first is therefore essential even when+ // the browser has no assistant transcript (for example after a cancel or+ // crash); only Grok's explicit FS_NOT_FOUND response means it is safe to+ // create a fresh session and attach the OpenUI rules.+ try {+ await this.loadSession(sessionId);+ } catch (error) {+ if (!looksMissing(error)) throw error;+ if (hasHistory) {+ throw new Error(+ "This OpenUI thread has browser history, but its persisted Grok Build session " ++ `${sessionId} is missing. Start a new thread instead of continuing with lost context.`,+ );+ }+ await this.createSession(sessionId);+ }+ this.residentSessions.add(sessionId);+ })().finally(() => {+ this.openingSessions.delete(sessionId);+ });++ this.openingSessions.set(sessionId, opening);+ return opening;+ }++ async runTurn({+ hasHistory,+ onUpdate,+ prompt,+ sessionId,+ signal,+ }: {+ hasHistory: boolean;+ onUpdate: UpdateListener;+ prompt: string;+ sessionId: string;+ signal: AbortSignal;+ }): Promise<{ stopReason?: string }> {+ await this.ensureSession(sessionId, hasHistory);+ if (this.activeThreads.has(sessionId)) throw new GrokBuildBusyError();+ if (signal.aborted) throw new DOMException("The request was aborted.", "AbortError");++ this.activeThreads.add(sessionId);+ let terminalError: string | undefined;+ const unsubscribe = this.subscribe(sessionId, (update) => {+ if (update.sessionUpdate === "retry_state" && update.type === "failed") {+ terminalError = update.message || update.reason || terminalError;+ } else if (+ update.sessionUpdate === "turn_completed" &&+ update.stop_reason === "error"+ ) {+ terminalError = update.agent_result || terminalError;+ }+ onUpdate(update);+ });+ const cancel = () => {+ void this.request("Cancelling the Grok Build turn", () =>+ this.connection.cancel({ sessionId }),+ ).catch(() => undefined);+ };+ signal.addEventListener("abort", cancel, { once: true });++ try {+ const response = await this.request("Running the Grok Build turn", () =>+ this.connection.prompt({+ sessionId,+ prompt: [{ type: "text", text: prompt }],+ _meta: {+ clientIdentifier: "openui-grok-build-harness",+ screenMode: "headless",+ },+ }),+ );+ const stopReason = response.stopReason ? String(response.stopReason) : undefined;+ if (terminalError || stopReason === "error") {+ throw new GrokBuildTurnError(+ terminalError ?? "Grok Build completed the turn with an error.",+ );+ }+ return { stopReason };+ } catch (error) {+ if (error instanceof GrokBuildTurnError) throw error;+ throw new GrokBuildTurnError(terminalError ?? formatGrokBuildError(error), error);+ } finally {+ signal.removeEventListener("abort", cancel);+ unsubscribe();+ this.activeThreads.delete(sessionId);+ }+ }+}++export class GrokBuildBusyError extends Error {+ constructor() {+ super("Grok Build is still responding to the previous message in this thread.");+ this.name = "GrokBuildBusyError";+ }+}++export class GrokBuildTurnError extends Error {+ constructor(message: string, options?: { cause?: unknown } | unknown) {+ const cause =+ options && typeof options === "object" && "cause" in options+ ? (options as { cause?: unknown }).cause+ : options;+ super(message, cause === undefined ? undefined : { cause });+ this.name = "GrokBuildTurnError";+ }+}++const globalStore = globalThis as unknown as {+ __openuiGrokBuildACP?: GrokBuildACPClient;+ __openuiGrokBuildACPStarting?: Promise<GrokBuildACPClient>;+};++async function getClient(): Promise<GrokBuildACPClient> {+ const config = readConfig();+ const signature = configSignature(config);+ const existing = globalStore.__openuiGrokBuildACP;+ if (existing && existing.alive && existing.signature === signature) return existing;+ if (existing) {+ existing.dispose();+ globalStore.__openuiGrokBuildACP = undefined;+ }++ if (!globalStore.__openuiGrokBuildACPStarting) {+ globalStore.__openuiGrokBuildACPStarting = GrokBuildACPClient.create(config)+ .then((client) => {+ globalStore.__openuiGrokBuildACP = client;+ return client;+ })+ .finally(() => {+ globalStore.__openuiGrokBuildACPStarting = undefined;+ });+ }+ return globalStore.__openuiGrokBuildACPStarting;+}++export function isGrokBuildThreadBusy(threadId: string): boolean {+ return globalStore.__openuiGrokBuildACP?.isBusy(threadId) ?? false;+}++export async function runGrokBuildTurn(options: {+ hasHistory: boolean;+ onUpdate: UpdateListener;+ prompt: string;+ sessionId: string;+ signal: AbortSignal;+}): Promise<{ stopReason?: string }> {+ const client = await getClient();+ return client.runTurn(options);+}diff --git a/examples/harnesses/grok-build/src/lib/grok-build-chat.ts b/examples/harnesses/grok-build/src/lib/grok-build-chat.tsnew file mode 100644index 000000000..c0aba2f02--- /dev/null+++ b/examples/harnesses/grok-build/src/lib/grok-build-chat.ts@@ -0,0 +1,85 @@+import {+ EventType,+ agUIAdapter,+ type ChatLLM,+ type ChatStorage,+ type Message,+} from "@openuidev/react-headless";+import {+ createThreadStore,+ getClientStorage,+ type KVStorage,+ type ThreadStore,+} from "./thread-store";++async function persistAssistantFromStream(+ body: ReadableStream<Uint8Array>,+ threadId: string,+ messages: Message[],+ store: ThreadStore,+): Promise<void> {+ let assistant = "";++ try {+ for await (const event of agUIAdapter().parse(new Response(body))) {+ if (event.type === EventType.TEXT_MESSAGE_CONTENT) {+ assistant += event.delta;+ }+ }+ } finally {+ // Preserve text received before a cancel or transport failure. The caller+ // intentionally swallows the tee reader's error after this checkpoint so+ // an aborted browser request cannot become an unhandled rejection.+ if (assistant) {+ store.saveMessages(threadId, [+ ...messages,+ { id: crypto.randomUUID(), role: "assistant", content: assistant } as Message,+ ]);+ }+ }+}++/**+ * Returns the two independent adapters AgentInterface needs: an AG-UI-backed+ * LLM transport and a localStorage-backed thread store.+ */+export function createGrokBuildChatProps(+ storage: KVStorage = getClientStorage(),+ store: ThreadStore = createThreadStore(storage),+): { llm: ChatLLM; storage: ChatStorage } {+ const send: ChatLLM["send"] = async ({ messages, threadId, signal }): Promise<Response> => {+ store.saveMessages(threadId, messages);++ const response = await fetch("/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ messages, threadId }),+ signal,+ });++ if (!response.ok || !response.body) return response;+ const [clientBody, persistenceBody] = response.body.tee();+ void persistAssistantFromStream(persistenceBody, threadId, messages, store).catch(+ () => undefined,+ );++ return new Response(clientBody, {+ status: response.status,+ statusText: response.statusText,+ headers: response.headers,+ });+ };++ return {+ llm: { send, streamProtocol: agUIAdapter() },+ storage: {+ thread: {+ listThreads: () => store.fetchThreadList(),+ createThread: (firstMessage) => store.createThread(firstMessage),+ getMessages: (threadId) => store.loadThread(threadId),+ updateThread: (thread) => store.updateThread(thread),+ deleteThread: (threadId) => store.deleteThread(threadId),+ },+ },+ };+}diff --git a/examples/harnesses/grok-build/src/lib/grok-build-stream.test.ts b/examples/harnesses/grok-build/src/lib/grok-build-stream.test.tsnew file mode 100644index 000000000..203fc5978--- /dev/null+++ b/examples/harnesses/grok-build/src/lib/grok-build-stream.test.ts@@ -0,0 +1,545 @@+import { EventType, type AGUIEvent } from "@ag-ui/core";+import { describe, expect, it } from "vitest";+import {+ decodeGrokSessionNotification,+ formatGrokBuildError,+ type GrokBuildSessionUpdate,+} from "./grok-build-acp";+import { GrokBuildAGUIBridge } from "./grok-build-stream";+import {+ chunkOpenUIOutput,+ createOpenUIStatus,+ describeOpenUIProblems,+ isRenderableOpenUI,+ OpenUIOutputAccumulator,+} from "./openui-output";++function agentMessage(text: string): GrokBuildSessionUpdate {+ return {+ sessionUpdate: "agent_message_chunk",+ content: { type: "text", text },+ };+}++function retry(): GrokBuildSessionUpdate {+ return {+ sessionUpdate: "retry_state",+ type: "retrying",+ attempt: 1,+ max_retries: 15,+ };+}++function emittedText(events: AGUIEvent[]): string {+ return events+ .filter(+ (event): event is AGUIEvent & { delta: string } =>+ event.type === EventType.TEXT_MESSAGE_CONTENT && "delta" in event,+ )+ .map((event) => event.delta)+ .join("");+}++describe("OpenUI output safety", () => {+ it("keeps only the final renderable candidate when Grok emits several roots", () => {+ const bridge = new GrokBuildAGUIBridge();+ const failedCandidate =+ 'root = Card([old])\nold = TextContent("This attempt was retried")';+ const finalCandidate =+ 'root = Card([answer])\nanswer = TextContent("Final retry-safe answer")';++ bridge.consume(agentMessage("I'll inspect the repository first."));+ bridge.consume(agentMessage(failedCandidate));+ bridge.consume(agentMessage('root = Card([stale])\nstale = TextContent("stale")'));+ bridge.consume(agentMessage(finalCandidate));++ const text = emittedText(bridge.finish());+ expect(text).toBe(finalCandidate);+ expect(isRenderableOpenUI(text)).toBe(true);+ });++ it("decodes Grok's live retry envelope and clears the failed attempt", () => {+ const bridge = new GrokBuildAGUIBridge();+ bridge.consume(agentMessage("failed attempt prose"));+ const notification = decodeGrokSessionNotification("x.ai/session_notification", {+ sessionId: crypto.randomUUID(),+ update: retry(),+ });++ expect(notification).toBeDefined();+ bridge.consume(notification!.update);+ const final =+ 'root = Card([answer])\nanswer = TextContent("final retry-safe answer")';+ bridge.consume(agentMessage(final));++ const text = emittedText(bridge.finish());+ expect(text).toBe(final);+ expect(text).not.toContain("failed attempt prose");+ expect(isRenderableOpenUI(text)).toBe(true);+ });++ it("handles a stale candidate delivered after its retry notification", () => {+ const bridge = new GrokBuildAGUIBridge();+ const stale = 'root = Card([stale])\nstale = TextContent("overtaken attempt")';+ const final = 'root = Card([answer])\nanswer = TextContent("final answer")';++ bridge.consume(retry());+ bridge.consume(agentMessage(stale));+ bridge.consume(agentMessage("ro"));+ bridge.consume(agentMessage(final.slice(2)));++ const text = emittedText(bridge.finish());+ expect(text).toBe(final);+ expect(isRenderableOpenUI(text)).toBe(true);+ });++ it("recovers the last valid retry candidate when the final candidate has an unresolved ref", () => {+ const bridge = new GrokBuildAGUIBridge();+ const valid = [+ "root = Card([summary])",+ 'summary = TextContent("validated retry answer")',+ ].join("\n");+ const invalid = [+ "root = Card([header, layout])",+ 'header = CardHeader("Project map")',+ 'sLayout = TextContent("layout was defined under the wrong identifier")',+ ].join("\n");++ bridge.consume(retry());+ bridge.consume(agentMessage(valid));+ bridge.consume(agentMessage(invalid));++ const text = emittedText(bridge.finish());+ expect(text).toBe(valid);+ expect(text).not.toContain("sLayout");+ });++ it("recognizes a root statement split across ACP chunks", () => {+ const output = new OpenUIOutputAccumulator();+ output.push("progress prose\nro");+ output.push('ot = Card([answer])\nanswer = TextContent("chunked")');++ expect(output.finish()).toBe(+ 'root = Card([answer])\nanswer = TextContent("chunked")',+ );+ });++ it("recovers a newer root split across chunks directly after another answer", () => {+ const output = new OpenUIOutputAccumulator();+ output.push('root = Card([old])\nold = TextContent("retried answer")');+ output.push("ro");+ output.push('ot = Card([answer])\nanswer = TextContent("newest answer")');++ expect(output.finish()).toBe(+ 'root = Card([answer])\nanswer = TextContent("newest answer")',+ );+ });++ it("extracts a valid root after a malformed same-line prefix", () => {+ const output = new OpenUIOutputAccumulator();+ output.push('?\")ro');+ output.push('ot = Card([answer])\nanswer = TextContent("recovered")');++ expect(output.finish()).toBe(+ 'root = Card([answer])\nanswer = TextContent("recovered")',+ );+ });++ it("ignores a root-looking example inside a component string", () => {+ const output = new OpenUIOutputAccumulator();+ const source =+ 'root = Card([answer])\nanswer = TextContent("literal root = Card([fake])\\nfake = TextContent(\\"fake\\")")';+ expect(isRenderableOpenUI(source)).toBe(true);+ output.push(source);++ expect(output.finish()).toBe(source);+ });++ it("tracks single-quoted strings while finding candidate boundaries", () => {+ const output = new OpenUIOutputAccumulator();+ const source =+ "root = Card([answer])\nanswer = TextContent('literal ) root = Card([])')";+ expect(isRenderableOpenUI(source)).toBe(true);+ output.push(source);++ expect(output.finish()).toBe(source);+ });++ it("ignores root-like text and delimiters inside line comments", () => {+ const output = new OpenUIOutputAccumulator();+ const source = [+ "root = Card([answer])",+ "// ) root = Card([])",+ "# ] root = Card([])",+ 'answer = TextContent("comments are ignored")',+ ].join("\n");+ expect(isRenderableOpenUI(source)).toBe(true);+ output.push(source);++ expect(output.finish()).toBe(source);+ });++ it("stops a fenced OpenUI candidate before trailing prose", () => {+ const output = new OpenUIOutputAccumulator();+ output.push(+ 'Here is the UI:\n```openui\nroot = Card([answer])\nanswer = TextContent("fenced")\n```\nHope that helps.',+ );++ expect(output.finish()).toBe(+ 'root = Card([answer])\nanswer = TextContent("fenced")',+ );+ });++ it("prefers fenced OpenUI over a root-looking example in trailing prose", () => {+ const output = new OpenUIOutputAccumulator();+ output.push(+ [+ "Here:",+ "```openui",+ 'root = Card([answer])',+ 'answer = TextContent("correct")',+ "```",+ "Syntax reminder: call Card() root = Card([])",+ ].join("\n"),+ );++ expect(output.finish()).toBe(+ 'root = Card([answer])\nanswer = TextContent("correct")',+ );+ });++ it("recognizes a fence after possessive prose", () => {+ const output = new OpenUIOutputAccumulator();+ output.push(+ [+ "Here is the users' requested UI:",+ "```openui",+ "root = Card([])",+ "```",+ 'Reminder: root = Card([missing])',+ ].join("\n"),+ );++ expect(output.finish()).toBe("root = Card([])");+ });++ it("lets a later unfenced retry supersede an earlier fenced answer", () => {+ const output = new OpenUIOutputAccumulator();+ output.push(+ [+ "```openui",+ 'root = Card([old])',+ 'old = TextContent("stale")',+ "```",+ 'root = Card([answer])',+ 'answer = TextContent("final")',+ ].join("\n"),+ );++ expect(output.finish()).toBe(+ 'root = Card([answer])\nanswer = TextContent("final")',+ );+ });++ it("lets a later fenced retry supersede an earlier unfenced answer", () => {+ const output = new OpenUIOutputAccumulator();+ output.push(+ [+ 'root = Card([old])',+ 'old = TextContent("stale")',+ "```openui",+ 'root = Card([answer])',+ 'answer = TextContent("final")',+ "```",+ ].join("\n"),+ );++ expect(output.finish()).toBe(+ 'root = Card([answer])\nanswer = TextContent("final")',+ );+ });++ it("recovers a split same-line final root after mixed retry formats", () => {+ const output = new OpenUIOutputAccumulator();+ output.push(+ [+ "```openui",+ 'root = Card([old])',+ 'old = TextContent("fenced stale")',+ "```",+ 'root = Card([stale])',+ 'stale = TextContent("unfenced stale")',+ ].join("\n"),+ );+ output.push("ro");+ output.push(+ 'ot = Card([answer])\nanswer = TextContent("actual final answer")',+ );++ expect(output.finish()).toBe(+ 'root = Card([answer])\nanswer = TextContent("actual final answer")',+ );+ });++ it("does not treat a fence marker inside a component string as Markdown", () => {+ const output = new OpenUIOutputAccumulator();+ const source = [+ "root = Card([answer])",+ 'answer = TextContent("',+ "```openui",+ 'root = Card([fake])',+ "```",+ '")',+ ].join("\n");+ expect(isRenderableOpenUI(source)).toBe(true);+ output.push(source);++ expect(output.finish()).toBe(source);+ });++ it("falls back to the newest renderable candidate when a later root is invalid", () => {+ const output = new OpenUIOutputAccumulator();+ const valid = 'root = Card([answer])\nanswer = TextContent("keep me")';+ output.push(valid);+ output.push("root = Stack([])");++ expect(output.finish()).toBe(valid);+ });++ it("rejects a newer candidate with an unresolved component reference", () => {+ const output = new OpenUIOutputAccumulator();+ const valid = 'root = Card([answer])\nanswer = TextContent("keep me")';+ output.push(valid);+ output.push("root = Card([missing])");++ expect(output.finish()).toBe(valid);+ });++ it("rejects a newer candidate containing an unknown component", () => {+ const output = new OpenUIOutputAccumulator();+ const valid = 'root = Card([answer])\nanswer = TextContent("keep me")';+ output.push(valid);+ output.push("root = Card([bad])\nbad = MadeUp(\"nope\")");++ expect(output.finish()).toBe(valid);+ });++ it("does not mistake a chunk starting with root text inside a string for a new answer", () => {+ const output = new OpenUIOutputAccumulator();+ output.push('root = Card([answer])\nanswer = TextContent("The ');+ output.push('root = token stays inside this string")');++ expect(output.finish()).toBe(+ 'root = Card([answer])\nanswer = TextContent("The root = token stays inside this string")',+ );+ });++ it("wraps prose-only output in a valid OpenUI fallback", () => {+ const output = new OpenUIOutputAccumulator();+ output.push("A plain-text answer that would previously trigger parse-failed.");++ const result = output.finish();+ expect(result).toContain("Unable to render Grok Build response");+ expect(result).not.toContain("A plain-text answer that would previously trigger");+ expect(isRenderableOpenUI(result)).toBe(true);+ });++ it("describes unresolved references for a bounded correction turn", () => {+ const invalid = [+ "root = Card([header, layout])",+ 'header = CardHeader("Project map")',+ 'sLayout = TextContent("wrong identifier")',+ ].join("\n");+ const output = new OpenUIOutputAccumulator();+ output.push(invalid);++ expect(describeOpenUIProblems(invalid)).toContain("Unresolved reference: layout");+ expect(output.needsCorrection()).toBe(true);+ expect(output.correctionPrompt()).toContain("Unresolved reference: layout");+ expect(output.correctionPrompt()).toContain("Do not call tools");+ });++ it("replaces an invalid attempt with a corrected final program", () => {+ const bridge = new GrokBuildAGUIBridge();+ bridge.consume(+ agentMessage(+ 'root = Card([layout])\nsLayout = TextContent("wrong identifier")',+ ),+ );+ expect(bridge.needsCorrection()).toBe(true);+ expect(bridge.correctionPrompt()).toContain("Unresolved reference: layout");++ bridge.beginCorrection();+ const corrected =+ 'root = Card([layout])\nlayout = TextContent("corrected identifier")';+ bridge.consume(agentMessage(corrected));++ expect(emittedText(bridge.finish())).toBe(corrected);+ });++ it("produces renderable fallback status cards", () => {+ expect(+ isRenderableOpenUI(createOpenUIStatus("warning", "No message", "Nothing to send.")),+ ).toBe(true);+ });++ it("chunks without changing the validated program", () => {+ const source = `root = Card([answer])\nanswer = TextContent(${JSON.stringify("smooth ".repeat(300))})`;+ const chunks = chunkOpenUIOutput(source);++ expect(chunks.length).toBeGreaterThan(1);+ expect(chunks.length).toBeLessThanOrEqual(72);+ expect(chunks.join("")).toBe(source);+ });++ it("preserves validated buffered output when the upstream turn fails", () => {+ const bridge = new GrokBuildAGUIBridge();+ const valid = 'root = Card([answer])\nanswer = TextContent("keep the useful answer")';+ bridge.consume(+ agentMessage(valid),+ );++ expect(emittedText(bridge.fail("Upstream failed."))).toBe(valid);+ expect(bridge.finish()).toEqual([]);+ });++ it("rotates the Thinking card when Grok retries", () => {+ const bridge = new GrokBuildAGUIBridge();+ const thought = (text: string): GrokBuildSessionUpdate => ({+ sessionUpdate: "agent_thought_chunk",+ content: { type: "text", text },+ });+ const first = bridge.consume(thought("First model attempt"));+ const firstId = first.find((event) => event.type === EventType.TOOL_CALL_START);+ const boundary = bridge.consume(retry());+ const second = bridge.consume(thought("Second model attempt"));+ const secondId = second.find((event) => event.type === EventType.TOOL_CALL_START);++ expect(boundary.some((event) => event.type === EventType.TOOL_CALL_END)).toBe(true);+ expect(firstId && "toolCallId" in firstId ? firstId.toolCallId : undefined).not.toBe(+ secondId && "toolCallId" in secondId ? secondId.toolCallId : undefined,+ );+ });++ it("uses Grok's terminal retry message instead of an object string", () => {+ const bridge = new GrokBuildAGUIBridge();+ bridge.consume({+ sessionUpdate: "agent_thought_chunk",+ content: { type: "text", text: "Trying the request" },+ });+ const terminal = bridge.consume({+ sessionUpdate: "retry_state",+ type: "failed",+ error_type: "api",+ message: "Service temporarily unavailable.",+ });++ const events = bridge.fail("[object Object]");+ const result = terminal.find((event) => event.type === EventType.TOOL_CALL_RESULT) as+ | (AGUIEvent & { content?: string })+ | undefined;+ expect(result?.content).toBe("Service temporarily unavailable.");+ expect(emittedText(events)).toBe("");+ });++ it("does not invent a fallback assistant card when a turn fails before output", () => {+ const bridge = new GrokBuildAGUIBridge();++ expect(bridge.fail("Grok Build failed to start.")).toEqual([]);+ });++ it("uses the turn_completed agent result for terminal errors", () => {+ const bridge = new GrokBuildAGUIBridge();+ bridge.consume({+ sessionUpdate: "agent_thought_chunk",+ content: { type: "text", text: "Waiting for the model" },+ });+ const terminal = bridge.consume({+ sessionUpdate: "turn_completed",+ stop_reason: "error",+ agent_result: "Provider unavailable.",+ });+ const result = terminal.find((event) => event.type === EventType.TOOL_CALL_RESULT) as+ | (AGUIEvent & { content?: string; isError?: boolean })+ | undefined;++ expect(result?.content).toBe("Provider unavailable.");+ expect(result?.isError).toBe(true);+ });++ it("serializes structured ACP failures without [object Object]", () => {+ const message = formatGrokBuildError({+ message: { error: "Service temporarily unavailable" },+ data: { status: 500 },+ });+ expect(message).not.toContain("[object Object]");+ expect(message).toContain("Service temporarily unavailable");+ expect(message).toContain("500");+ });++ it("merges partial tool updates before closing the AG-UI tool call", () => {+ const bridge = new GrokBuildAGUIBridge();+ const events = [+ ...bridge.consume({+ sessionUpdate: "tool_call",+ toolCallId: "partial",+ title: "Run command",+ kind: "execute",+ status: "pending",+ }),+ ...bridge.consume({+ sessionUpdate: "tool_call_update",+ toolCallId: "partial",+ status: "in_progress",+ }),+ ...bridge.consume({+ sessionUpdate: "tool_call_update",+ toolCallId: "partial",+ rawInput: { command: "pwd" },+ }),+ ...bridge.consume({+ sessionUpdate: "tool_call_update",+ toolCallId: "partial",+ rawOutput: { ok: true },+ }),+ ...bridge.consume({+ sessionUpdate: "tool_call_update",+ toolCallId: "partial",+ status: "completed",+ }),+ ];++ const argsIndex = events.findIndex((event) => event.type === EventType.TOOL_CALL_ARGS);+ const endIndex = events.findIndex((event) => event.type === EventType.TOOL_CALL_END);+ const result = events.find((event) => event.type === EventType.TOOL_CALL_RESULT) as+ | (AGUIEvent & { content?: string })+ | undefined;++ expect(argsIndex).toBeGreaterThan(-1);+ expect(endIndex).toBeGreaterThan(argsIndex);+ expect(events.filter((event) => event.type === EventType.TOOL_CALL_END)).toHaveLength(1);+ expect(result?.content).toBe('{"ok":true}');+ });++ it("marks an unfinished tool as failed instead of inventing success", () => {+ const bridge = new GrokBuildAGUIBridge();+ bridge.consume({+ sessionUpdate: "tool_call",+ toolCallId: "unfinished",+ title: "Pending tool",+ kind: "execute",+ status: "pending",+ rawInput: { command: "pwd" },+ });++ const result = bridge+ .finish()+ .find(+ (event) =>+ event.type === EventType.TOOL_CALL_RESULT &&+ "toolCallId" in event &&+ event.toolCallId === "unfinished",+ ) as (AGUIEvent & { isError?: boolean }) | undefined;+ expect(result?.isError).toBe(true);+ });+});diff --git a/examples/harnesses/grok-build/src/lib/grok-build-stream.ts b/examples/harnesses/grok-build/src/lib/grok-build-stream.tsnew file mode 100644index 000000000..26364521c--- /dev/null+++ b/examples/harnesses/grok-build/src/lib/grok-build-stream.ts@@ -0,0 +1,320 @@+import { EventType, type AGUIEvent } from "@ag-ui/core";+import type { GrokBuildSessionUpdate } from "./grok-build-acp";+import { chunkOpenUIOutput, OpenUIOutputAccumulator } from "./openui-output";++type ToolUpdate = Extract<+ GrokBuildSessionUpdate,+ { sessionUpdate: "tool_call" | "tool_call_update" }+>;++function safeJson(value: unknown): string {+ try {+ return JSON.stringify(value ?? {});+ } catch {+ return JSON.stringify({ value: String(value) });+ }+}++function jsonStringFragment(value: string): string {+ return JSON.stringify(value).slice(1, -1);+}++function resultText(value: unknown, failed: boolean): string {+ if (typeof value === "string") return value;+ if (value === undefined || value === null) return failed ? "Tool call failed." : "";+ return safeJson(value);+}++function contentText(content: unknown): string {+ if (!content || typeof content !== "object") return "";+ const record = content as { type?: unknown; text?: unknown };+ return record.type === "text" && typeof record.text === "string" ? record.text : "";+}++/** Maps Grok Build's ACP session updates into the AG-UI stream OpenUI consumes. */+export class GrokBuildAGUIBridge {+ private readonly assistantMessageId = crypto.randomUUID();+ private readonly endedTools = new Set<string>();+ private readonly resultedTools = new Set<string>();+ private readonly sentToolArgs = new Set<string>();+ private readonly startedTools = new Map<string, string>();+ private readonly toolOutputs = new Map<string, unknown>();+ private readonly toolStatuses = new Map<string, ToolUpdate["status"]>();+ private readonly output = new OpenUIOutputAccumulator();+ private messageEnded = false;+ private messageStarted = false;+ private terminalError: string | undefined;+ private thinkingId: string | undefined;++ private startMessage(): AGUIEvent[] {+ if (this.messageStarted) return [];+ this.messageStarted = true;+ return [+ {+ type: EventType.TEXT_MESSAGE_START,+ messageId: this.assistantMessageId,+ role: "assistant",+ } as AGUIEvent,+ ];+ }++ private startThinking(): AGUIEvent[] {+ if (this.thinkingId) return [];+ this.thinkingId = crypto.randomUUID();+ return [+ ...this.startMessage(),+ {+ type: EventType.TOOL_CALL_START,+ toolCallId: this.thinkingId,+ toolCallName: "Thinking",+ parentMessageId: this.assistantMessageId,+ } as AGUIEvent,+ {+ type: EventType.TOOL_CALL_ARGS,+ toolCallId: this.thinkingId,+ delta: '{"_request":"',+ } as AGUIEvent,+ ];+ }++ private endThinking(content = "Reasoning complete.", failed = false): AGUIEvent[] {+ const toolCallId = this.thinkingId;+ if (!toolCallId) return [];+ this.thinkingId = undefined;+ return [+ { type: EventType.TOOL_CALL_ARGS, toolCallId, delta: '"}' } as AGUIEvent,+ { type: EventType.TOOL_CALL_END, toolCallId } as AGUIEvent,+ {+ type: EventType.TOOL_CALL_RESULT,+ messageId: crypto.randomUUID(),+ toolCallId,+ content,+ role: "tool",+ ...(failed ? { isError: true, error: content } : {}),+ } as AGUIEvent,+ ];+ }++ private startTool(toolCallId: string, title: string): AGUIEvent[] {+ const events = this.endThinking();+ if (this.startedTools.has(toolCallId)) return events;+ this.startedTools.set(toolCallId, title);+ return [+ ...events,+ ...this.startMessage(),+ {+ type: EventType.TOOL_CALL_START,+ toolCallId,+ toolCallName: title,+ parentMessageId: this.assistantMessageId,+ } as AGUIEvent,+ ];+ }++ private toolArgs(toolCallId: string, value: unknown): AGUIEvent[] {+ if (value === undefined || this.sentToolArgs.has(toolCallId)) return [];+ this.sentToolArgs.add(toolCallId);+ const delta = safeJson(value);+ if (delta === "{}") return [];+ return [{ type: EventType.TOOL_CALL_ARGS, toolCallId, delta } as AGUIEvent];+ }++ private endTool(toolCallId: string): AGUIEvent[] {+ if (!this.startedTools.has(toolCallId) || this.endedTools.has(toolCallId)) return [];+ this.endedTools.add(toolCallId);+ return [{ type: EventType.TOOL_CALL_END, toolCallId } as AGUIEvent];+ }++ private toolResult(+ toolCallId: string,+ status: "completed" | "failed",+ value: unknown,+ ): AGUIEvent[] {+ if (!this.startedTools.has(toolCallId) || this.resultedTools.has(toolCallId)) return [];+ this.resultedTools.add(toolCallId);+ const failed = status === "failed";+ const content = resultText(value, failed);+ return [+ {+ type: EventType.TOOL_CALL_RESULT,+ messageId: crypto.randomUUID(),+ toolCallId,+ content,+ role: "tool",+ ...(failed ? { isError: true, error: content } : {}),+ } as AGUIEvent,+ ];+ }++ private closePendingTools(message: string): AGUIEvent[] {+ const events: AGUIEvent[] = [];+ for (const toolCallId of this.startedTools.keys()) {+ if (this.resultedTools.has(toolCallId)) continue;+ events.push(...this.endTool(toolCallId));+ events.push(...this.toolResult(toolCallId, "failed", message));+ }+ return events;+ }++ private consumeToolUpdate(update: ToolUpdate): AGUIEvent[] {+ const { toolCallId } = update;+ const title = update.title || this.startedTools.get(toolCallId) || update.kind || "Tool";+ const events = this.startTool(toolCallId, title);++ if (update.status) this.toolStatuses.set(toolCallId, update.status);+ if (Object.prototype.hasOwnProperty.call(update, "rawOutput")) {+ this.toolOutputs.set(toolCallId, update.rawOutput);+ } else if (Object.prototype.hasOwnProperty.call(update, "content")) {+ this.toolOutputs.set(toolCallId, update.content);+ }++ events.push(...this.toolArgs(toolCallId, update.rawInput));++ const status = this.toolStatuses.get(toolCallId);+ const terminal = status === "completed" || status === "failed";+ if (terminal || (status === "in_progress" && this.sentToolArgs.has(toolCallId))) {+ events.push(...this.endTool(toolCallId));+ }+ if (terminal) {+ events.push(+ ...this.toolResult(+ toolCallId,+ status,+ this.toolOutputs.has(toolCallId) ? this.toolOutputs.get(toolCallId) : undefined,+ ),+ );+ }++ return events;+ }++ private emitOutput(output: string): AGUIEvent[] {+ if (!output) return [];+ const events = this.startMessage();+ for (const delta of chunkOpenUIOutput(output)) {+ events.push({+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: this.assistantMessageId,+ delta,+ } as AGUIEvent);+ }+ return events;+ }++ consume(update: GrokBuildSessionUpdate): AGUIEvent[] {+ switch (update.sessionUpdate) {+ case "agent_message_chunk": {+ const delta = contentText(update.content);+ if (!delta) return [];+ this.output.push(delta);+ return [];+ }++ case "agent_thought_chunk": {+ const delta = contentText(update.content);+ if (!delta) return [];+ const started = this.startThinking();+ const toolCallId = this.thinkingId;+ if (!toolCallId) return started;+ return [+ ...started,+ {+ type: EventType.TOOL_CALL_ARGS,+ toolCallId,+ delta: jsonStringFragment(delta),+ } as AGUIEvent,+ ];+ }++ case "tool_call":+ case "tool_call_update":+ return this.consumeToolUpdate(update);++ case "retry_state": {+ if (update.type === "retrying") {+ this.output.retry();+ const attempt = update.attempt ? ` ${update.attempt}` : "";+ const maximum = update.max_retries ? ` of ${update.max_retries}` : "";+ const message = `Model attempt${attempt}${maximum} was retried.`;+ return [+ ...this.endThinking(message),+ ...this.closePendingTools("Tool call was superseded by a model retry."),+ ];+ }+ if (update.type === "failed") {+ const message = update.message || update.reason || "Grok Build retries failed.";+ this.terminalError = message;+ return [+ ...this.endThinking(message, true),+ ...this.closePendingTools(message),+ ];+ }+ return [];+ }++ case "turn_completed": {+ if (update.stop_reason === "error") {+ const message =+ update.agent_result || this.terminalError || "Grok Build completed with an error.";+ this.terminalError = message;+ return [+ ...this.endThinking(message, true),+ ...this.closePendingTools(message),+ ];+ }+ return [];+ }++ default:+ return [];+ }+ }++ needsCorrection(): boolean {+ return this.output.needsCorrection();+ }++ correctionPrompt(): string {+ return this.output.correctionPrompt();+ }++ beginCorrection(): AGUIEvent[] {+ const events = this.endThinking("Final UI validation failed; correcting the response.");+ this.output.resetForCorrection();+ return events;+ }++ finish(): AGUIEvent[] {+ if (this.messageEnded) return [];+ this.messageEnded = true;++ const events = this.endThinking();+ events.push(...this.closePendingTools("Tool call ended without a terminal result."));+ const output = this.output.finish();+ events.push(...this.emitOutput(output));+ if (this.messageStarted) {+ events.push({+ type: EventType.TEXT_MESSAGE_END,+ messageId: this.assistantMessageId,+ } as AGUIEvent);+ }+ return events;+ }++ fail(message: string): AGUIEvent[] {+ if (this.messageEnded) return [];+ this.messageEnded = true;+ const failure = this.terminalError ?? message;++ const events = this.endThinking(failure, true);+ events.push(...this.closePendingTools(failure));+ if (this.output.hasOutput()) events.push(...this.emitOutput(this.output.finish()));+ if (this.messageStarted) {+ events.push({+ type: EventType.TEXT_MESSAGE_END,+ messageId: this.assistantMessageId,+ } as AGUIEvent);+ }+ return events;+ }+}diff --git a/examples/harnesses/grok-build/src/lib/openui-output.ts b/examples/harnesses/grok-build/src/lib/openui-output.tsnew file mode 100644index 000000000..d80743af2--- /dev/null+++ b/examples/harnesses/grok-build/src/lib/openui-output.ts@@ -0,0 +1,418 @@+import { createParser } from "@openuidev/lang-core";+import { componentSpec } from "../library";++const parser = createParser(componentSpec, "Card");+const ROOT_CANDIDATE = /(?:^|[^A-Za-z0-9_$])root[\t ]*=/g;+const MAX_STREAM_CHUNKS = 72;+const MIN_STREAM_CHUNK_SIZE = 192;++function startsSingleQuotedString(value: string, index: number): boolean {+ let previous = index - 1;+ while (previous >= 0 && /[\t ]/.test(value[previous])) previous -= 1;+ if (previous < 0) return true;+ return /[([{:?,=+\-*/%!<>]/.test(value[previous]);+}++function scanQuoteState(+ value: string,+ initialQuote?: '"' | "'",+): '"' | "'" | undefined {+ let quote = initialQuote;+ let escaped = false;++ for (let index = 0; index < value.length; index += 1) {+ const character = value[index];+ if (quote) {+ if (escaped) escaped = false;+ else if (character === "\\") escaped = true;+ else if (character === quote) quote = undefined;+ continue;+ }++ if (character === '"') {+ quote = character;+ } else if (+ character === "'" &&+ startsSingleQuotedString(value, index)+ ) {+ // Ignore prose apostrophes and possessives while still+ // protecting fenced-looking text inside single-quoted OpenUI strings.+ quote = character;+ }+ }++ return quote;+}++interface FencedBlock {+ value: string;+ start: number;+ end: number;+}++/** Extract Markdown code blocks while ignoring fence markers inside strings. */+function fencedBlocks(value: string): FencedBlock[] {+ const blocks: FencedBlock[] = [];+ const lines = value.match(/.*(?:\n|$)/g) ?? [];+ let quote: '"' | "'" | undefined;+ let block: string[] | undefined;+ let blockStart = 0;+ let offset = 0;++ for (const line of lines) {+ if (!line) continue;+ const lineStart = offset;+ offset += line.length;+ const withoutNewline = line.replace(/\r?\n$/, "");++ if (!block) {+ if (!quote && /^[\t ]{0,3}```[^`\r\n]*$/.test(withoutNewline)) {+ block = [];+ blockStart = offset;+ quote = undefined;+ continue;+ }+ quote = scanQuoteState(line, quote);+ continue;+ }++ if (!quote && /^[\t ]{0,3}```+[\t ]*$/.test(withoutNewline)) {+ blocks.push({ value: block.join(""), start: blockStart, end: lineStart });+ block = undefined;+ quote = undefined;+ continue;+ }++ block.push(line);+ quote = scanQuoteState(line, quote);+ }++ // Match lang-core's streaming behavior: an unclosed fence owns the rest.+ if (block) blocks.push({ value: block.join(""), start: blockStart, end: value.length });+ return blocks;+}++function isInsideLineComment(value: string, index: number): boolean {+ const lineStart = value.lastIndexOf("\n", index - 1) + 1;+ let quote: '"' | "'" | undefined;+ let escaped = false;++ for (let cursor = lineStart; cursor < index; cursor += 1) {+ const character = value[cursor];+ if (quote) {+ if (escaped) escaped = false;+ else if (character === "\\") escaped = true;+ else if (character === quote) quote = undefined;+ continue;+ }+ if (character === '"' || character === "'") quote = character;+ else if (character === "#") return true;+ else if (character === "/" && value[cursor + 1] === "/") return true;+ }+ return false;+}++function rootCandidateIndexes(value: string): number[] {+ const indexes: number[] = [];+ for (const match of value.matchAll(ROOT_CANDIDATE)) {+ const rootOffset = match[0].indexOf("root");+ const index = match.index + rootOffset;+ if (!isInsideLineComment(value, index)) indexes.push(index);+ }+ return indexes;+}++function isRootCandidateAt(value: string, index: number): boolean {+ if (!value.startsWith("root", index)) return false;+ const previous = value[index - 1];+ if (previous && /[A-Za-z0-9_$]/.test(previous)) return false;++ let cursor = index + "root".length;+ while (value[cursor] === " " || value[cursor] === "\t") cursor += 1;+ return value[cursor] === "=";+}++/** Isolate one structurally complete candidate without crossing into a later root. */+function candidateAt(value: string, start: number): string | undefined {+ let quote: '"' | "'" | undefined;+ let escaped = false;+ let lineComment = false;+ let parentheses = 0;+ let brackets = 0;+ let braces = 0;++ for (let index = start; index < value.length; index += 1) {+ const character = value[index];+ if (lineComment) {+ if (character === "\n") lineComment = false;+ continue;+ }+ if (quote) {+ if (escaped) {+ escaped = false;+ } else if (character === "\\") {+ escaped = true;+ } else if (character === quote) {+ quote = undefined;+ }+ continue;+ }++ if (character === '"' || character === "'") {+ quote = character;+ continue;+ }+ if (character === "#" || (character === "/" && value[index + 1] === "/")) {+ lineComment = true;+ continue;+ }++ // OpenUI escapes only occur inside quoted strings. Seeing one here means+ // this root was probably recovered from an escaped example inside a string.+ if (character === "\\") return undefined;++ const atTopLevel = parentheses === 0 && brackets === 0 && braces === 0;+ if (index > start && atTopLevel) {+ if (value.startsWith("```", index) || isRootCandidateAt(value, index)) {+ return value.slice(start, index);+ }+ }++ if (character === "(") parentheses += 1;+ else if (character === ")") parentheses -= 1;+ else if (character === "[") brackets += 1;+ else if (character === "]") brackets -= 1;+ else if (character === "{") braces += 1;+ else if (character === "}") braces -= 1;++ if (parentheses < 0 || brackets < 0 || braces < 0) return undefined;+ }++ if (quote || parentheses !== 0 || brackets !== 0 || braces !== 0) return undefined;+ return value.slice(start);+}++function normalizeCandidate(value: string): string {+ return value+ .trim()+ .replace(/\n[\t ]*```[\t ]*$/, "")+ .trim();+}++export function isRenderableOpenUI(value: string): boolean {+ if (!value.trim()) return false;+ try {+ const result = parser.parse(value);+ return (+ result.root?.typeName === "Card" &&+ !result.meta.incomplete &&+ result.meta.errors.length === 0 &&+ result.meta.unresolved.length === 0+ );+ } catch {+ return false;+ }+}++export function createOpenUIStatus(+ variant: "neutral" | "info" | "warning" | "success" | "danger",+ title: string,+ description: string,+): string {+ return [+ "root = Card([notice])",+ `notice = TextCallout(${JSON.stringify(variant)}, ${JSON.stringify(title)}, ${JSON.stringify(description)})`,+ ].join("\n");+}++function issueText(value: unknown): string {+ if (typeof value === "string") return value;+ try {+ return JSON.stringify(value);+ } catch {+ return String(value);+ }+}++/** Parser feedback suitable for a bounded model correction turn. */+export function describeOpenUIProblems(value: string): string[] {+ if (!value.trim()) return ["The response was empty."];+ try {+ const result = parser.parse(value);+ const issues = result.meta.errors.map(issueText);+ issues.push(...result.meta.unresolved.map((name) => `Unresolved reference: ${name}`));+ if (!result.root) issues.push("No renderable root component was produced.");+ else if (result.root.typeName !== "Card") {+ issues.push(`The root component must be Card, not ${result.root.typeName}.`);+ }+ if (result.meta.incomplete) issues.push("The OpenUI program is incomplete.");+ return [...new Set(issues)];+ } catch (error) {+ return [error instanceof Error ? error.message : String(error)];+ }+}++function fallbackOpenUI(value: string): string {+ const detail = describeOpenUIProblems(value)[0] ?? "The final program was invalid.";+ return createOpenUIStatus(+ "warning",+ "Unable to render Grok Build response",+ `The final OpenUI response did not pass validation. ${detail}`,+ );+}++interface RenderableCandidate {+ value: string;+ index: number;+}++function latestRenderableRootCandidate(+ value: string,+ acceptsIndex: (index: number) => boolean = () => true,+): RenderableCandidate | undefined {+ const normalized = normalizeCandidate(value);+ const indexes = rootCandidateIndexes(normalized);+ for (let index = indexes.length - 1; index >= 0; index -= 1) {+ if (!acceptsIndex(indexes[index])) continue;+ const extracted = candidateAt(normalized, indexes[index]);+ if (!extracted) continue;+ const candidate = normalizeCandidate(extracted);+ if (isRenderableOpenUI(candidate)) {+ return { value: candidate, index: indexes[index] };+ }+ }+ return undefined;+}++function latestRenderableCandidate(value: string): string | undefined {+ const normalized = normalizeCandidate(value);++ const blocks = fencedBlocks(normalized);+ const candidates: RenderableCandidate[] = [];++ for (const block of blocks) {+ const candidate = latestRenderableRootCandidate(block.value);+ if (candidate) {+ candidates.push({+ value: candidate.value,+ index: block.start + candidate.index,+ });+ }+ }++ const rawCandidate = latestRenderableRootCandidate(normalized, (index) => {+ if (blocks.some((block) => index >= block.start && index < block.end)) {+ return false;+ }++ const lineStart = normalized.lastIndexOf("\n", index - 1) + 1;+ const startsOnOwnLine = normalized.slice(lineStart, index).trim() === "";+ const followsFence = blocks.some((block) => block.end <= index);+ const previousCharacter = normalized[index - 1];+ const followsCompletedExpression = Boolean(+ previousCharacter && /[)\]}]/.test(previousCharacter),+ );++ // After an explicit fenced program, same-line `root =` text is usually a+ // syntax reminder in prose. A later answer beginning on its own line still+ // wins by source order. So does a root jammed directly after a completed+ // expression, which is how split ACP retry chunks appeared in production.+ return startsOnOwnLine || !followsFence || followsCompletedExpression;+ });+ if (rawCandidate) candidates.push(rawCandidate);++ candidates.sort((left, right) => right.index - left.index);+ return candidates[0]?.value;+}++/**+ * Collects append-only ACP message chunks while making retries safe. Grok can+ * emit progress prose and several complete candidates during one prompt. ACP+ * may split the next `root =` across chunks without inserting a newline, so+ * candidate boundaries are retained here and resolved by validation at finish.+ */+export class OpenUIOutputAccumulator {+ private lastRenderable = "";+ private value = "";++ push(delta: string): void {+ this.value += delta;+ }++ retry(): void {+ const renderable = latestRenderableCandidate(normalizeCandidate(this.value));+ if (renderable) this.lastRenderable = renderable;+ this.value = "";+ }++ /** Clear an invalid attempt before a model correction without promoting it. */+ resetForCorrection(): void {+ this.value = "";+ }++ hasRenderable(): boolean {+ return Boolean(+ latestRenderableCandidate(normalizeCandidate(this.value)) || this.lastRenderable,+ );+ }++ hasOutput(): boolean {+ return Boolean(this.value.trim() || this.lastRenderable);+ }++ needsCorrection(): boolean {+ return Boolean(this.value.trim()) && !this.hasRenderable();+ }++ correctionPrompt(): string {+ const candidate = normalizeCandidate(this.value);+ const issues = describeOpenUIProblems(candidate);+ return [+ "Your previous final assistant response failed OpenUI validation.",+ "Do not call tools. Return exactly one corrected OpenUI Lang program and nothing else.",+ "Keep the same factual answer. Ensure every reference used by root and child components is defined.",+ "Validation issues:",+ ...issues.map((issue) => `- ${issue}`),+ "Invalid OpenUI Lang:",+ "```openui",+ candidate.slice(0, 12_000),+ "```",+ ].join("\n");+ }++ finish(): string {+ const candidate = normalizeCandidate(this.value);+ const renderable = latestRenderableCandidate(candidate);+ if (renderable) return renderable;+ if (this.lastRenderable) return this.lastRenderable;+ if (!candidate) {+ return createOpenUIStatus(+ "warning",+ "No final response",+ "Grok Build completed without producing an assistant response.",+ );+ }+ return fallbackOpenUI(candidate);+ }+}++/** Split validated output into at most ~72 pieces for a short, frame-paced reveal. */+export function chunkOpenUIOutput(value: string): string[] {+ if (!value) return [];+ const targetSize = Math.max(+ MIN_STREAM_CHUNK_SIZE,+ Math.ceil(value.length / MAX_STREAM_CHUNKS),+ );+ const chunks: string[] = [];++ for (let start = 0; start < value.length; ) {+ let end = Math.min(start + targetSize, value.length);+ const nearbyNewline = value.indexOf("\n", end);+ if (nearbyNewline !== -1 && nearbyNewline - end <= 96) end = nearbyNewline + 1;+ if (end < value.length && /[\uD800-\uDBFF]/.test(value[end - 1]!)) end -= 1;+ chunks.push(value.slice(start, end));+ start = end;+ }++ return chunks;+}diff --git a/examples/harnesses/grok-build/src/lib/thread-store.ts b/examples/harnesses/grok-build/src/lib/thread-store.tsnew file mode 100644index 000000000..667e00d76--- /dev/null+++ b/examples/harnesses/grok-build/src/lib/thread-store.ts@@ -0,0 +1,114 @@+import type { Message, Thread, UserMessage } from "@openuidev/react-headless";++export interface KVStorage {+ getItem(key: string): string | null;+ setItem(key: string, value: string): void;+ removeItem(key: string): void;+}++const THREADS_KEY = "grok-build-openui:threads";+const messagesKey = (threadId: string) => `grok-build-openui:messages:${threadId}`;++function readJson<T>(storage: KVStorage, key: string, fallback: T): T {+ try {+ const raw = storage.getItem(key);+ return raw ? (JSON.parse(raw) as T) : fallback;+ } catch {+ return fallback;+ }+}++function messageText(message: Pick<UserMessage, "content">): string {+ const content = message.content as unknown;+ if (typeof content === "string") return content;+ if (Array.isArray(content)) {+ return content+ .map((part) =>+ part && typeof part === "object" && "text" in part+ ? String((part as { text?: unknown }).text ?? "")+ : "",+ )+ .join(" ");+ }+ return "";+}++function deriveTitle(message: UserMessage): string {+ const text = messageText(message).trim().replace(/\s+/g, " ");+ if (!text) return "New chat";+ return text.length > 60 ? `${text.slice(0, 57)}...` : text;+}++export interface ThreadStore {+ createThread(firstMessage: UserMessage): Promise<Thread>;+ fetchThreadList(): Promise<{ threads: Thread[] }>;+ loadThread(threadId: string): Promise<Message[]>;+ deleteThread(threadId: string): Promise<void>;+ updateThread(updated: Thread): Promise<Thread>;+ saveMessages(threadId: string, messages: Message[]): void;+}++/**+ * The generated thread id is also the Grok Build session UUID. Keeping the+ * browser and harness identities aligned lets a restored OpenUI thread resume+ * the same on-disk Grok conversation after a Next.js restart.+ */+export function createThreadStore(+ storage: KVStorage,+ generateId: () => string = () => crypto.randomUUID(),+): ThreadStore {+ const listThreads = (): Thread[] => readJson<Thread[]>(storage, THREADS_KEY, []);+ const writeThreads = (threads: Thread[]) => storage.setItem(THREADS_KEY, JSON.stringify(threads));++ return {+ async createThread(firstMessage) {+ const thread: Thread = {+ id: generateId(),+ title: deriveTitle(firstMessage),+ createdAt: Date.now(),+ };+ writeThreads([thread, ...listThreads().filter((item) => item.id !== thread.id)]);+ return thread;+ },++ async fetchThreadList() {+ return { threads: listThreads() };+ },++ async loadThread(threadId) {+ return readJson<Message[]>(storage, messagesKey(threadId), []);+ },++ async deleteThread(threadId) {+ writeThreads(listThreads().filter((item) => item.id !== threadId));+ storage.removeItem(messagesKey(threadId));+ },++ async updateThread(updated) {+ writeThreads(listThreads().map((item) => (item.id === updated.id ? updated : item)));+ return updated;+ },++ saveMessages(threadId, messages) {+ storage.setItem(messagesKey(threadId), JSON.stringify(messages));+ },+ };+}++export function createMemoryStorage(): KVStorage {+ const map = new Map<string, string>();+ return {+ getItem: (key) => map.get(key) ?? null,+ setItem: (key, value) => {+ map.set(key, value);+ },+ removeItem: (key) => {+ map.delete(key);+ },+ };+}++export function getClientStorage(): KVStorage {+ if (typeof window !== "undefined" && window.localStorage) return window.localStorage;+ return createMemoryStorage();+}diff --git a/examples/harnesses/grok-build/src/library.ts b/examples/harnesses/grok-build/src/library.tsnew file mode 100644index 000000000..ce1dc36c2--- /dev/null+++ b/examples/harnesses/grok-build/src/library.ts@@ -0,0 +1,17 @@+import {+ openuiChatLibrary,+ openuiChatPromptOptions,+} from "@openuidev/react-ui/genui-lib";++export const library = openuiChatLibrary;++export const promptOptions = {+ ...openuiChatPromptOptions,+ preamble: `You are a coding agent connected to OpenUI. Use reasoning and tools normally before answering.+Do not emit OpenUI Lang in reasoning, progress messages, tool arguments, or tool results.+After all required work is complete, your final assistant response must consist entirely of valid openui-lang code with no markdown or explanatory prose.+Before sending the final response, verify that root is a Card and every referenced identifier is defined.`,+};++export const systemPrompt = library.prompt(promptOptions);+export const componentSpec = library.toJSONSchema();diff --git a/examples/harnesses/grok-build/tsconfig.json b/examples/harnesses/grok-build/tsconfig.jsonnew file mode 100644index 000000000..7d553a8b5--- /dev/null+++ b/examples/harnesses/grok-build/tsconfig.json@@ -0,0 +1,34 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "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/pnpm-lock.yaml b/pnpm-lock.yamlindex 2851c4109..564b6d5e7 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -456,6 +456,67 @@ importers:specifier: ^5version: 5.9.3+ examples/harnesses/grok-build:+ dependencies:+ '@ag-ui/core':+ specifier: ^0.0.53+ version: 0.0.53+ '@agentclientprotocol/sdk':+ specifier: 0.10.0+ version: 0.10.0([email protected])+ '@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+ next:+ specifier: 16.2.6+ version: 16.2.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([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.4.3+ version: 4.4.3+ devDependencies:+ '@tailwindcss/postcss':+ specifier: ^4+ version: 4.2.1+ '@types/node':+ specifier: 'catalog:'+ version: 22.19.19+ '@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.2.6+ version: 16.2.6(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ tailwindcss:+ specifier: ^4+ version: 4.2.2+ typescript:+ specifier: ^5+ version: 5.9.3+ vitest:+ specifier: ^4.0.18+ version: 4.1.7(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+examples/harnesses/pi-agent-harness:dependencies:'@earendil-works/pi-coding-agent':@@ -2209,6 +2270,11 @@ packages:'@ag-ui/[email protected]':resolution: {integrity: sha512-1c3J6cjEyAMT1GA/XOqvL9LEVgmrdT6vyUeEqUsEdVS1Kb4Ln5wcY6qmR7uoQCZWQRfDedCfth8RUwq2jynG1w==}+ '@agentclientprotocol/[email protected]':+ resolution: {integrity: sha512-+Bwmf8Uli480h4ONjANxVP6tnACqHOaCiLJslgwOJHJvjDFzhAHZX4aL/bPKpOPc3LU1RgkPnJ98rCdPBnakaQ==}+ peerDependencies:+ zod: ^3.25.0 || ^4.0.0+'@ai-sdk/[email protected]':resolution: {integrity: sha512-K0U09FPDO1kmLPjRLXFcNSvmnKHJBMARCb8r3Ulw7wU6/+Zh9djWcFDiPPNsklg6yAezcdLTcYPszgWJJ6iOTA==}engines: {node: '>=18'}@@ -19692,6 +19758,10 @@ snapshots:'@bufbuild/protobuf': 2.12.0'@protobuf-ts/protoc': 2.11.1+ '@agentclientprotocol/[email protected]([email protected])':+ dependencies:+ zod: 4.4.3+'@ai-sdk/[email protected]([email protected])':dependencies:'@ai-sdk/provider': 2.0.3