Skip to content

The Open Standard for Generative UI

Update lang-core & cli to move to spec generation (#811)

AB269d259417a5
diff --git a/docs/content/docs/api-reference/cli.mdx b/docs/content/docs/api-reference/cli.mdx
index 27c4c8917..6ae7655db 100644
--- a/docs/content/docs/api-reference/cli.mdx
+++ b/docs/content/docs/api-reference/cli.mdx
@@ -153,7 +153,7 @@ npx @openuidev/cli@latest create --name my-app --no-skill
## `openui generate`
-Generates a system prompt or JSON schema from a file that exports a `createLibrary()` result.
+Generates the system prompt **and** the serialized library spec from a file that exports a `createLibrary()` result. A single run emits both artifacts — they derive from the same `Library` instance, so they can never drift apart. Use the spec with `generateSystemPrompt` in backend routes; the prompt file supports static or legacy integrations.
```
openui generate [entry] [options]
@@ -167,14 +167,15 @@ openui generate [entry] [options]
**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) |
-| `--prompt-options <name>` | Name of the `PromptOptions` export to use (auto-detected by default) |
-| `--no-interactive` | Fail instead of prompting for missing `entry` |
-| `--agent-name <name>` | Declare the invoking coding-agent slug (default: `unknown`) |
+| Flag | Description |
+| ------------------------- | ------------------------------------------------------------------------------------------- |
+| `-o, --out <file>` | Write the prompt to `<file>`; the spec uses the same basename with a `.spec.json` extension |
+| `--json-schema` | Output only the JSON schema; it is not the input to `generateSystemPrompt` |
+| `--spec` | Output only the serialized library spec |
+| `--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` |
+| `--agent-name <name>` | Declare the invoking coding-agent slug (default: `unknown`) |
**Examples**
@@ -182,12 +183,15 @@ openui generate [entry] [options]
# Print system prompt to stdout
pnpx @openuidev/cli@latest generate ./src/library.ts
-# Write system prompt to a file
+# Write both artifacts; use the sibling .spec.json file with generateSystemPrompt
pnpx @openuidev/cli@latest generate ./src/library.ts --out ./src/generated/system-prompt.txt
-# Output JSON schema instead
+# Output JSON schema for external tooling (not generateSystemPrompt)
pnpx @openuidev/cli@latest generate ./src/library.ts --json-schema
+# Output only the spec file
+pnpx @openuidev/cli@latest generate ./src/library.ts --spec
+
# Explicit export names
pnpx @openuidev/cli@latest generate ./src/library.ts --export myLibrary --prompt-options myOptions
```
@@ -196,12 +200,15 @@ pnpx @openuidev/cli@latest generate ./src/library.ts --export myLibrary --prompt
# Print system prompt to stdout
bunx @openuidev/cli@latest generate ./src/library.ts
-# Write system prompt to a file
+# Write both artifacts; use the sibling .spec.json file with generateSystemPrompt
bunx @openuidev/cli@latest generate ./src/library.ts --out ./src/generated/system-prompt.txt
-# Output JSON schema instead
+# Output JSON schema for external tooling (not generateSystemPrompt)
bunx @openuidev/cli@latest generate ./src/library.ts --json-schema
+# Output only the spec file
+bunx @openuidev/cli@latest generate ./src/library.ts --spec
+
# Explicit export names
bunx @openuidev/cli@latest generate ./src/library.ts --export myLibrary --prompt-options myOptions
```
@@ -210,12 +217,15 @@ bunx @openuidev/cli@latest generate ./src/library.ts --export myLibrary --prompt
# Print system prompt to stdout
yarn dlx @openuidev/cli@latest generate ./src/library.ts
-# Write system prompt to a file
+# Write both artifacts; use the sibling .spec.json file with generateSystemPrompt
yarn dlx @openuidev/cli@latest generate ./src/library.ts --out ./src/generated/system-prompt.txt
-# Output JSON schema instead
+# Output JSON schema for external tooling (not generateSystemPrompt)
yarn dlx @openuidev/cli@latest generate ./src/library.ts --json-schema
+# Output only the spec file
+yarn dlx @openuidev/cli@latest generate ./src/library.ts --spec
+
# Explicit export names
yarn dlx @openuidev/cli@latest generate ./src/library.ts --export myLibrary --prompt-options myOptions
```
@@ -224,12 +234,15 @@ yarn dlx @openuidev/cli@latest generate ./src/library.ts --export myLibrary --pr
# Print system prompt to stdout
npx @openuidev/cli@latest generate ./src/library.ts
-# Write system prompt to a file
+# Write both artifacts; use the sibling .spec.json file with generateSystemPrompt
npx @openuidev/cli@latest generate ./src/library.ts --out ./src/generated/system-prompt.txt
-# Output JSON schema instead
+# Output JSON schema for external tooling (not generateSystemPrompt)
npx @openuidev/cli@latest generate ./src/library.ts --json-schema
+# Output only the spec file
+npx @openuidev/cli@latest generate ./src/library.ts --spec
+
# Explicit export names
npx @openuidev/cli@latest generate ./src/library.ts --export myLibrary --prompt-options myOptions
```
@@ -302,104 +315,6 @@ yarn dlx @openuidev/cli@latest generate ./src/library.ts --out src/generated/sys
npx @openuidev/cli@latest generate ./src/library.ts --out src/generated/system-prompt.txt
```
-## `openui generate-spec`
-
-Generates a serialized library spec as JSON — component signatures, component groups, and the library's JSON schema — from a file that exports a `createLibrary()` result.
-
-```
-openui generate-spec [entry] [options]
-```
-
-The spec is a handover artifact: the team that owns the component library generates it once and hands the JSON to whoever configures the model server — for example as the `chatLibrary` config value in OpenUI Cloud. The server rebuilds the system prompt, response validation, and sanitization from the spec, so the model can only be prompted with components the library actually registers.
-
-**Arguments**
-
-| 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 |
-| `--export <name>` | Name of the export to use (auto-detected by default) |
-| `--no-interactive` | Fail instead of prompting for missing `entry` |
-| `--agent-name <name>` | Declare the invoking coding-agent slug (default: `unknown`) |
-
-Entry bundling and library detection work the same as [`openui generate`](#export-auto-detection). `PromptOptions` exports are not folded into the spec — the spec is pure library data; consumers apply prompt customisation separately when they build the system prompt.
-
-**Output**
-
-{/* prettier-ignore */}
-```jsonc
-{
- // Optional root component the response must start with
- "root": "Page",
- // Pre-rendered signatures, for review and inspection
- "components": {
- "Metric": {
- "signature": "Metric(label: string, value: string, trend?: \"up\" | \"down\")",
- "description": "A single KPI stat"
- }
- },
- // Optional grouping, mirrored into the generated prompt
- "componentGroups": [{ "name": "Data display", "components": ["Metric"] }],
- // JSON schema of every registered component ($defs keyed by component name)
- "schema": {
- "$defs": {
- "Metric": { "type": "object", "description": "A single KPI stat", "properties": { /* … */ } }
- }
- }
-}
-```
-
-**Examples**
-
-```bash tab="pnpm" tab-group="pkg"
-# Print the spec to stdout
-pnpx @openuidev/cli@latest generate-spec ./src/library.ts
-
-# Write the handover file
-pnpx @openuidev/cli@latest generate-spec ./src/library.ts --out ./library-spec.json
-
-# Explicit export name
-pnpx @openuidev/cli@latest generate-spec ./src/library.ts --export myLibrary
-```
-
-```bash tab="bun" tab-group="pkg"
-# Print the spec to stdout
-bunx @openuidev/cli@latest generate-spec ./src/library.ts
-
-# Write the handover file
-bunx @openuidev/cli@latest generate-spec ./src/library.ts --out ./library-spec.json
-
-# Explicit export name
-bunx @openuidev/cli@latest generate-spec ./src/library.ts --export myLibrary
-```
-
-```bash tab="yarn" tab-group="pkg"
-# Print the spec to stdout
-yarn dlx @openuidev/cli@latest generate-spec ./src/library.ts
-
-# Write the handover file
-yarn dlx @openuidev/cli@latest generate-spec ./src/library.ts --out ./library-spec.json
-
-# Explicit export name
-yarn dlx @openuidev/cli@latest generate-spec ./src/library.ts --export myLibrary
-```
-
-```bash tab="npm" tab-group="pkg"
-# Print the spec to stdout
-npx @openuidev/cli@latest generate-spec ./src/library.ts
-
-# Write the handover file
-npx @openuidev/cli@latest generate-spec ./src/library.ts --out ./library-spec.json
-
-# Explicit export name
-npx @openuidev/cli@latest generate-spec ./src/library.ts --export myLibrary
-```
-
## Coding-agent attribution
When a coding agent invokes any CLI command, it should pass `--agent-name` using its stable,
@@ -418,7 +333,6 @@ manager selected for dependency installation (`npm`, `pnpm`, `yarn`, or `bun`).
<Cards>
<Card title="@openuidev/react-lang" href="/docs/api-reference/react-lang">
- `createLibrary`, `PromptOptions`, and the `Library` interface that `openui generate` and `openui
- generate-spec` read.
+ `createLibrary`, `PromptOptions`, and the `Library` interface that `openui generate` read.
</Card>
</Cards>
diff --git a/docs/content/docs/api-reference/index.mdx b/docs/content/docs/api-reference/index.mdx
index 1819f2e7d..90c5eb0fb 100644
--- a/docs/content/docs/api-reference/index.mdx
+++ b/docs/content/docs/api-reference/index.mdx
@@ -80,7 +80,7 @@ The OpenUI SDK is split into packages that build on each other:
CDN, iframe, and no-build browser bundle for the renderer, UI library, React, and styles.
</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
+ openui create (scaffold a Next.js app) and openui generate (system prompt + library spec from a
library definition).
</Card>
</Cards>
diff --git a/docs/content/docs/openui-lang/how-it-works.mdx b/docs/content/docs/openui-lang/how-it-works.mdx
index 6fe5e15b8..f6c1e6aa3 100644
--- a/docs/content/docs/openui-lang/how-it-works.mdx
+++ b/docs/content/docs/openui-lang/how-it-works.mdx
@@ -146,14 +146,12 @@ const tools: ToolSpec[] = [
```ts
// route.ts
-import { generatePrompt } from "@openuidev/lang-core";
+import { generateSystemPrompt, type LibrarySpec } from "@openuidev/lang-core";
import componentSpec from "./generated/component-spec.json";
-const systemPrompt = generatePrompt({
- ...componentSpec,
- tools,
- toolCalls: true,
- bindings: true,
+const systemPrompt = generateSystemPrompt({
+ library: componentSpec as LibrarySpec,
+ promptOptions: { tools, toolCalls: true, bindings: true },
});
const completion = await openai.chat.completions.create({
diff --git a/docs/content/docs/openui-lang/incremental-editing.mdx b/docs/content/docs/openui-lang/incremental-editing.mdx
index ab1b490e5..49c2740b1 100644
--- a/docs/content/docs/openui-lang/incremental-editing.mdx
+++ b/docs/content/docs/openui-lang/incremental-editing.mdx
@@ -90,4 +90,4 @@ const config: PromptSpec = {
**`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.
+Both flags are passed to `generateSystemPrompt()` via `promptOptions`. See [System Prompts](/docs/openui-lang/system-prompts) for the full reference.
diff --git a/docs/content/docs/openui-lang/quickstart.mdx b/docs/content/docs/openui-lang/quickstart.mdx
index 87e1e664c..7934e182b 100644
--- a/docs/content/docs/openui-lang/quickstart.mdx
+++ b/docs/content/docs/openui-lang/quickstart.mdx
@@ -74,16 +74,26 @@ src/
route.ts # Backend route with OpenAI streaming + example tools
library.ts # Re-exports openuiChatLibrary and openuiChatPromptOptions
generated/
- system-prompt.txt # Auto-generated at build time via `openui generate`
+ system-prompt.txt # Generated for static or legacy prompt integrations
+ system-prompt.spec.json # Generated library spec
```
- **`page.tsx`**: Renders the `AgentInterface` chat (an artifact chat surface with thread history) with `openuiChatLibrary` for Generative UI rendering. It provides an `llm` whose `send` posts messages to the route and whose `streamProtocol` is `openAIAdapter()`. Storage is optional — omit it and threads are kept in memory (wiped on reload).
-- **`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.
+- **`route.ts`**: A backend API route that uses `generateSystemPrompt` with the generated spec, then streams the response from the LLM.
+- **`library.ts`**: Your component library entrypoint. The `openui generate` CLI reads this file to produce both the prompt and the library spec.
-The `dev` and `build` scripts automatically regenerate the system prompt before starting:
+The `dev` and `build` scripts automatically regenerate both artifacts before starting. Use the emitted spec in your route:
```json
"generate:prompt": "openui generate src/library.ts --out src/generated/system-prompt.txt",
"dev": "pnpm generate:prompt && next dev"
```
+
+```ts
+import { generateSystemPrompt, type LibrarySpec } from "@openuidev/lang-core";
+import librarySpec from "../../../generated/system-prompt.spec.json";
+
+const systemPrompt = generateSystemPrompt({
+ library: librarySpec as LibrarySpec,
+});
+```
diff --git a/docs/content/docs/openui-lang/standard-library.mdx b/docs/content/docs/openui-lang/standard-library.mdx
index 7ffa462d0..749141635 100644
--- a/docs/content/docs/openui-lang/standard-library.mdx
+++ b/docs/content/docs/openui-lang/standard-library.mdx
@@ -33,9 +33,9 @@ import { openuiLibrary } from "@openuidev/react-ui";
<Renderer library={openuiLibrary} response={streamedText} isStreaming={isStreaming} />;
```
-## Generate prompt
+## Generate a spec and build the prompt
-Use the CLI to generate the system prompt at build time:
+Use the CLI to generate the prompt and serialized library spec at build time. In your backend, use the spec with `generateSystemPrompt`:
```bash tab="pnpm" tab-group="pkg"
pnpx @openuidev/cli@latest generate ./src/library.ts --out src/generated/system-prompt.txt
@@ -53,12 +53,15 @@ yarn dlx @openuidev/cli@latest generate ./src/library.ts --out src/generated/sys
npx @openuidev/cli@latest generate ./src/library.ts --out src/generated/system-prompt.txt
```
-Or generate programmatically:
+The command writes `src/generated/system-prompt.spec.json` beside the prompt file. Import that spec in your backend:
```ts
-import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui";
+import { generateSystemPrompt, type LibrarySpec } from "@openuidev/lang-core";
+import librarySpec from "./generated/system-prompt.spec.json";
-const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
+const systemPrompt = generateSystemPrompt({
+ library: librarySpec as LibrarySpec,
+});
```
## Extend it
@@ -89,4 +92,4 @@ const myLibrary = createLibrary({
- Default root component is `Stack`.
- `Form` requires explicit `buttons`.
-- Signature truth source is `openuiLibrary.prompt(openuiPromptOptions)`.
+- The generated library spec is the backend prompt source of truth
diff --git a/docs/content/docs/openui-lang/system-prompts.mdx b/docs/content/docs/openui-lang/system-prompts.mdx
index 33d8850ef..e77af5454 100644
--- a/docs/content/docs/openui-lang/system-prompts.mdx
+++ b/docs/content/docs/openui-lang/system-prompts.mdx
@@ -3,11 +3,11 @@ title: System Prompts
description: Generate and customize prompt instructions from your OpenUI library.
---
-The system prompt tells the LLM how to output valid OpenUI Lang. There are two ways to generate it.
+The system prompt tells the LLM how to output valid OpenUI Lang. Generate a serialized library spec at build time, then pass that spec to `generateSystemPrompt` in your backend.
## 1. CLI (recommended for most setups)
-The fastest way to generate a system prompt — works with any backend language:
+`openui generate` emits two artifacts from the same library: a prebuilt prompt and a serialized library spec. Use the **spec** with `generateSystemPrompt`; retain the prompt only for static or legacy integrations.
```bash tab="pnpm" tab-group="pkg"
pnpx @openuidev/cli@latest generate ./src/library.ts
@@ -43,72 +43,38 @@ yarn dlx @openuidev/cli@latest generate ./src/library.ts --out system-prompt.txt
npx @openuidev/cli@latest generate ./src/library.ts --out system-prompt.txt
```
-Generate the component spec as JSON (for use with `generatePrompt`):
-
-```bash tab="pnpm" tab-group="pkg"
-pnpx @openuidev/cli@latest generate ./src/library.ts --json-schema
-```
-
-```bash tab="bun" tab-group="pkg"
-bunx @openuidev/cli@latest generate ./src/library.ts --json-schema
-```
-
-```bash tab="yarn" tab-group="pkg"
-yarn dlx @openuidev/cli@latest generate ./src/library.ts --json-schema
-```
-
-```bash tab="npm" tab-group="pkg"
-npx @openuidev/cli@latest generate ./src/library.ts --json-schema
-```
+This writes the prompt to `system-prompt.txt` and the spec to `system-prompt.spec.json`. The `.spec.json` file is the input to `generateSystemPrompt`; `--json-schema` produces a JSON Schema for other tooling, not the library spec used to build the prompt.
The CLI auto-detects exported `PromptOptions` (examples, rules) alongside your library. Use `--prompt-options <name>` to pick a specific export.
-## 2. `generatePrompt` (programmatic)
-
-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.
+## 2. `generateSystemPrompt` (recommended backend integration)
-First, generate the component spec JSON via the CLI:
-
-```bash tab="pnpm" tab-group="pkg"
-pnpx @openuidev/cli generate ./src/library.ts --json-schema --out generated/component-spec.json
-```
-
-```bash tab="bun" tab-group="pkg"
-bunx @openuidev/cli generate ./src/library.ts --json-schema --out generated/component-spec.json
-```
-
-```bash tab="yarn" tab-group="pkg"
-yarn dlx @openuidev/cli generate ./src/library.ts --json-schema --out generated/component-spec.json
-```
-
-```bash tab="npm" tab-group="pkg"
-npx @openuidev/cli generate ./src/library.ts --json-schema --out generated/component-spec.json
-```
-
-Then build the prompt at runtime:
+For backends that need dynamic prompts — different tools, preambles, or feature flags per request — use `generateSystemPrompt` from `@openuidev/lang-core`. It has no React dependency, so it works in any Node, Edge, or serverless backend. Import the spec emitted by the command above and build the prompt at runtime:
```ts
-import { generatePrompt, type PromptSpec } from "@openuidev/lang-core";
-import componentSpec from "./generated/component-spec.json";
+import { generateSystemPrompt, type LibrarySpec } from "@openuidev/lang-core";
+import librarySpec from "./generated/system-prompt.spec.json";
-const systemPrompt = generatePrompt({
- ...componentSpec,
+const systemPrompt = generateSystemPrompt({
+ library: librarySpec as LibrarySpec,
- // Tool descriptions — so the LLM knows what tools exist
- tools: myToolSpecs,
+ promptOptions: {
+ // Tool descriptions — so the LLM knows what tools exist
+ tools: myToolSpecs,
- // Examples showing how to use your tools with Query/Mutation
- toolExamples: [`tickets = Query("list_tickets", {}, {rows: []})\n...`],
+ // 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)
+ // 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, "")'],
+ // Custom instructions
+ preamble: "You build dashboards using openui-lang.",
+ additionalRules: ['Use @Reset after form submit, not @Set($var, "")'],
+ },
});
```
@@ -131,7 +97,7 @@ import { openuiLibrary, openuiPromptOptions } from "@openuidev/react-ui";
const systemPrompt = openuiLibrary.prompt(openuiPromptOptions);
```
-This is convenient but imports React components - use `generatePrompt` for pure backend routes.
+This is convenient but imports React components. Prefer the generated spec plus `generateSystemPrompt` for backend routes.
## What gets generated
@@ -152,11 +118,14 @@ The generated prompt includes:
```ts
import OpenAI from "openai";
-import { generatePrompt, type PromptSpec } from "@openuidev/lang-core";
-import componentSpec from "./generated/component-spec.json";
+import { generateSystemPrompt, type LibrarySpec } from "@openuidev/lang-core";
+import librarySpec from "./generated/system-prompt.spec.json";
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
-const systemPrompt = generatePrompt({ ...componentSpec, preamble: "You are a helpful assistant." });
+const systemPrompt = generateSystemPrompt({
+ library: librarySpec as LibrarySpec,
+ promptOptions: { preamble: "You are a helpful assistant." },
+});
export async function POST(req: Request) {
const { messages } = await req.json();
diff --git a/docs/public/AGENTS.md b/docs/public/AGENTS.md
new file mode 100644
index 000000000..9156730e4
--- /dev/null
+++ b/docs/public/AGENTS.md
@@ -0,0 +1,3 @@
+# OpenUI: guide for coding agents
+
+See the maintained OpenUI skill for coding agents published at [thesysdev/skills](https://raw.githubusercontent.com/thesysdev/skills/refs/heads/main/skills/openui/SKILL.md).
diff --git a/packages/lang-core/package.json b/packages/lang-core/package.json
index 4773a1223..83d0edb27 100644
--- a/packages/lang-core/package.json
+++ b/packages/lang-core/package.json
@@ -1,6 +1,6 @@
{
"name": "@openuidev/lang-core",
- "version": "0.2.9",
+ "version": "0.2.10",
"description": "Framework-agnostic core for OpenUI Lang: parser, prompt generation, validation, and type definitions",
"license": "MIT",
"type": "module",
diff --git a/packages/lang-core/src/index.ts b/packages/lang-core/src/index.ts
index dccec529e..a0843435c 100644
--- a/packages/lang-core/src/index.ts
+++ b/packages/lang-core/src/index.ts
@@ -29,8 +29,15 @@ export {
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, LibrarySpec, PromptSpec, ToolSpec } from "./parser/prompt";
+export { generatePrompt, generateSystemPrompt } from "./parser/prompt";
+export type {
+ ComponentPromptSpec,
+ LibrarySpec,
+ PromptSpec,
+ SystemPromptOptions,
+ SystemPromptSpec,
+ ToolSpec,
+} from "./parser/prompt";
export { jsonToOpenUI } from "./parser/serialize";
export type { SerializeOptions } from "./parser/serialize";
export { BuiltinActionType } from "./parser/types";
diff --git a/packages/lang-core/src/parser/prompt.ts b/packages/lang-core/src/parser/prompt.ts
index 302ca80ce..69c9c8065 100644
--- a/packages/lang-core/src/parser/prompt.ts
+++ b/packages/lang-core/src/parser/prompt.ts
@@ -593,6 +593,7 @@ function generateComponentSignatures(
// ─── Prompt assembly ────────────────────────────────────────────────────────
+/** @deprecated Use {@link generateSystemPrompt}. */
export function generatePrompt(spec: PromptSpec): string {
const rootName = spec.root ?? "Root";
const hasTools = !!spec.tools?.length;
@@ -691,3 +692,31 @@ export function generatePrompt(spec: PromptSpec): string {
return parts.join("\n");
}
+
+// ─── System prompt (library + options + instructions) ───────────────────────
+
+/** Prompt options for {@link generateSystemPrompt} */
+export type SystemPromptOptions = Omit<PromptSpec, keyof BaseSpec>;
+
+/** Object input for {@link generateSystemPrompt}. */
+export interface SystemPromptSpec {
+ library: LibrarySpec;
+ promptOptions?: SystemPromptOptions;
+}
+
+/** Render the full system prompt for a library. */
+export function generateSystemPrompt(spec: SystemPromptSpec): string;
+/** @deprecated Pass `{ library, promptOptions, instructions }` instead. Removed at the next major. */
+export function generateSystemPrompt(spec: PromptSpec): string;
+export function generateSystemPrompt(spec: SystemPromptSpec | PromptSpec): string {
+ if (!isSystemPromptSpec(spec)) {
+ return generatePrompt(spec);
+ }
+ const merged: PromptSpec = { ...spec.library, ...spec.promptOptions };
+ return generatePrompt(merged);
+}
+
+// use `library` to discriminate SystemPromptSpec from the deprecated base-PromptSpec
+function isSystemPromptSpec(spec: SystemPromptSpec | PromptSpec): spec is SystemPromptSpec {
+ return "library" in spec && typeof (spec as SystemPromptSpec).library === "object";
+}
diff --git a/packages/openui-cli/README.md b/packages/openui-cli/README.md
index 2fa7b4304..f26648d36 100644
--- a/packages/openui-cli/README.md
+++ b/packages/openui-cli/README.md
@@ -112,7 +112,7 @@ openui create --no-interactive --name my-app --template openui-cloud --api-key t
### `openui generate`
-Generates a system prompt or JSON Schema from a file that exports a `createLibrary()` result.
+Generates a system prompt and serialized library spec from a file that exports a `createLibrary()` result. Use the spec with `generateSystemPrompt` in backend routes; the prompt file remains available for static or legacy integrations.
```bash
openui generate [options] [entry]
@@ -124,8 +124,9 @@ Arguments:
Options:
-- `-o, --out <file>`: Write output to a file instead of stdout
-- `--json-schema`: Output JSON Schema instead of the system prompt
+- `-o, --out <file>`: Write the prompt to a file and the spec alongside it with the extension replaced by `.spec.json`
+- `--json-schema`: Output only JSON Schema instead of the prompt and spec
+- `--spec`: Output only the serialized library spec
- `--export <name>`: Use a specific export name instead of auto-detecting the library export
- `--prompt-options <name>`: Use a specific `PromptOptions` export name (auto-detected by default)
- `--no-interactive`: Fail instead of prompting for a missing `entry`
@@ -145,6 +146,7 @@ Examples:
```bash
openui generate ./src/library.ts
openui generate ./src/library.ts --json-schema
+openui generate ./src/library.ts --spec
openui generate ./src/library.ts --export library
openui generate ./src/library.ts --out ./artifacts/system-prompt.txt
openui generate ./src/library.ts --prompt-options myPromptOptions
@@ -153,7 +155,7 @@ openui generate --no-interactive ./src/library.ts
## How `generate` resolves exports
-`openui generate` expects the target module to export a library object with both `prompt()` and `toJSONSchema()` methods.
+`openui generate` expects the target module to export a library object with `prompt()`, `toSpec()`, and `toJSONSchema()` methods.
If `--export` is not provided, it looks for exports in this order:
diff --git a/packages/openui-cli/package.json b/packages/openui-cli/package.json
index 3c810e859..ae063123a 100644
--- a/packages/openui-cli/package.json
+++ b/packages/openui-cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@openuidev/cli",
- "version": "0.1.9",
+ "version": "0.2.0",
"description": "CLI for OpenUI — scaffold generative UI chat apps and generate LLM system prompts from component libraries",
"bin": {
"openui": "dist/index.js"
diff --git a/packages/openui-cli/src/commands/generate-worker.ts b/packages/openui-cli/src/commands/generate-worker.ts
index cbbcf8f85..58a677512 100644
--- a/packages/openui-cli/src/commands/generate-worker.ts
+++ b/packages/openui-cli/src/commands/generate-worker.ts
@@ -5,7 +5,8 @@
* CSS/image/font loaders.
*
* argv: [entryPath, exportName?, "--json-schema"?, "--spec"?, "--prompt-options", name?]
- * stdout: the prompt string, JSON schema, or spec JSON
+ * stdout: one artifact for the mode flags; default emits BOTH the prompt and
+ * the spec JSON, joined by SEPARATION_DELIMITER (generate.ts splits them).
*/
import * as fs from "fs";
@@ -13,6 +14,7 @@ import * as os from "os";
import * as path from "path";
import * as esbuild from "esbuild";
+import { SEPARATION_DELIMITER } from "../lib/utils";
// ── Main ──
@@ -189,10 +191,15 @@ async function main(): Promise<void> {
output = JSON.stringify({ ...library.toSpec(), schema: library.toJSONSchema() }, null, 2);
} else if (jsonSchema) {
// Output a PromptSpec-compatible JSON with component signatures, groups, and JSON schema.
- output = JSON.stringify(library.toSpec(), null, 2);
+ output = JSON.stringify(library.toJSONSchema(), null, 2);
} else {
+ // This behaviour will be deprecated in next major release
+ // and only export standardised payloads
const promptOptions = findPromptOptions(mod, promptOptionsName);
- output = library.prompt(promptOptions);
+ output = [
+ library.prompt(promptOptions),
+ JSON.stringify({ ...library.toSpec(), schema: library.toJSONSchema() }, null, 2),
+ ].join(SEPARATION_DELIMITER); // record-separator-joined so generate.ts can split multi-artifact payloads
}
process.stdout.write(output);
diff --git a/packages/openui-cli/src/commands/generate.ts b/packages/openui-cli/src/commands/generate.ts
index 98381d857..7a0fb358b 100644
--- a/packages/openui-cli/src/commands/generate.ts
+++ b/packages/openui-cli/src/commands/generate.ts
@@ -1,19 +1,23 @@
import { execFileSync } from "child_process";
import * as fs from "fs";
import * as path from "path";
+import { SEPARATION_DELIMITER } from "../lib/utils";
import { CreateError, telemetry } from "../lib/telemetry";
export interface GenerateOptions {
out?: string;
jsonSchema?: boolean;
- /** Emit the serialized library spec JSON (toSpec + schema) — `generate-spec`. */
spec?: boolean;
export?: string;
promptOptions?: string;
+ interactive: boolean;
}
-export async function runGenerate(entry: string, options: GenerateOptions): Promise<void> {
+export async function runGenerate(
+ entry: string,
+ options: Omit<GenerateOptions, "interactive">,
+): Promise<void> {
const t0 = Date.now();
telemetry.capture("cli_generate_started", {
json_schema: !!options.jsonSchema,
@@ -45,13 +49,33 @@ export async function runGenerate(entry: string, options: GenerateOptions): Prom
throw new CreateError("generate_worker", err instanceof Error ? err.message : String(err));
}
- if (options.out) {
- const outPath = path.resolve(process.cwd(), options.out);
- fs.mkdirSync(path.dirname(outPath), { recursive: true });
- fs.writeFileSync(outPath, output + "\n");
- console.info(`Written to ${outPath}`);
+ if (options.jsonSchema || options.spec) {
+ if (options.out) {
+ const outPath = path.resolve(process.cwd(), options.out);
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
+ fs.writeFileSync(outPath, output + "\n");
+ console.info(`Written to ${outPath}`);
+ } else {
+ stdoutWrite(output);
+ }
} else {
- process.stdout.write(output + "\n");
+ // Both artifact mode
+ // `--out <file>` receives the prompt (legacy behavior preserved);
+ // the spec lands alongside it as `<file>.spec.json` (extension swapped).
+ // Without `--out` both go to stdout.
+ const [prompt = "", specJson = ""] = output.split(SEPARATION_DELIMITER);
+ if (options.out) {
+ const promptPath = path.resolve(process.cwd(), options.out);
+ fs.mkdirSync(path.dirname(promptPath), { recursive: true });
+ const base = promptPath.slice(0, promptPath.length - path.extname(promptPath).length);
+ const specPath = `${base}.spec.json`;
+ fs.writeFileSync(promptPath, prompt + "\n");
+ fs.writeFileSync(specPath, specJson + "\n");
+ console.info(`Written System Prompt to ${promptPath}`);
+ console.info(`Written Library Spec to ${specPath}`);
+ } else {
+ stdoutWrite(prompt + "\n\n" + specJson);
+ }
}
telemetry.capture("cli_generate_succeeded", {
@@ -61,3 +85,7 @@ export async function runGenerate(entry: string, options: GenerateOptions): Prom
duration_ms: Date.now() - t0,
});
}
+
+function stdoutWrite(content: string) {
+ process.stdout.write(content + "\n");
+}
diff --git a/packages/openui-cli/src/index.ts b/packages/openui-cli/src/index.ts
index 2537ccc87..447b561ff 100644
--- a/packages/openui-cli/src/index.ts
+++ b/packages/openui-cli/src/index.ts
@@ -6,7 +6,7 @@ import * as path from "node:path";
import { Command } from "commander";
import { runCreateApp } from "./commands/create-app";
-import { runGenerate } from "./commands/generate";
+import { GenerateOptions, runGenerate } from "./commands/generate";
import { detectAgent, UNKNOWN_AGENT_NAME } from "./lib/detect-agent";
import { resolveArgs } from "./lib/resolve-args";
import { telemetry } from "./lib/telemetry";
@@ -99,88 +99,43 @@ Templates:
program
.command("generate")
- .description("Generate system prompt or JSON schema from a library definition")
+ .description("Generate the system prompt + serialized spec 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(
+ "-o, --out <file>",
+ "Write the prompt to a file; the spec JSON lands alongside with .spec.json extension",
+ )
.option(
"--json-schema",
"Output JSON schema with component signatures for standalone prompt generation",
)
+ .option("--spec", "Generate a serialized library spec JSON (signatures, groups, JSON schema)")
.option("--export <name>", "Name of the export to use (auto-detected by default)")
.option(
"--prompt-options <name>",
"Name of the PromptOptions export to use (auto-detected by default)",
)
.option("--no-interactive", "Fail with error if required args are missing")
- .action(
- async (
- entry: string | undefined,
- options: {
- out?: string;
- jsonSchema?: boolean;
- export?: string;
- promptOptions?: string;
- interactive: boolean;
- },
- ) => {
- try {
- const args = await resolveArgs(
- {
- entry: entry
- ? { value: entry }
- : {
- prompt: { type: "input", message: "Entry file path?" },
- required: true,
- },
- },
- options.interactive,
- );
+ .action(async (entry: string | undefined, options: GenerateOptions) => {
+ try {
+ const args = await resolveArgs(
+ {
+ entry: entry
+ ? { value: entry }
+ : {
+ prompt: { type: "input", message: "Entry file path?" },
+ required: true,
+ },
+ },
+ options.interactive,
+ );
- await runGenerate((args as { entry: string }).entry, options);
- } catch (e) {
- handleCliError(e, "cli_generate_failed");
- } finally {
- await telemetry.shutdown();
- }
- },
- );
-
-program
- .command("generate-spec")
- .description("Generate a serialized library spec JSON (signatures, groups, JSON schema)")
- .argument("[entry]", "Path to a file that exports a createLibrary() result")
- .option("-o, --out <file>", "Write output to a file instead of stdout")
- .option("--export <name>", "Name of the export to use (auto-detected by default)")
- .option("--no-interactive", "Fail with error if required args are missing")
- .action(
- async (
- entry: string | undefined,
- options: {
- out?: string;
- export?: string;
- interactive: boolean;
- },
- ) => {
- try {
- const args = await resolveArgs(
- {
- entry: entry
- ? { value: entry }
- : {
- prompt: { type: "input", message: "Entry file path?" },
- required: true,
- },
- },
- options.interactive,
- );
-
- await runGenerate((args as { entry: string }).entry, { ...options, spec: true });
- } catch (e) {
- handleCliError(e, "cli_generate_spec_failed");
- } finally {
- await telemetry.shutdown();
- }
- },
- );
+ await runGenerate((args as { entry: string }).entry, options);
+ } catch (e) {
+ handleCliError(e, "cli_generate_failed");
+ } finally {
+ await telemetry.shutdown();
+ }
+ });
program.parse();
diff --git a/packages/openui-cli/src/lib/utils.ts b/packages/openui-cli/src/lib/utils.ts
index 50e7b880f..5c9211e7f 100644
--- a/packages/openui-cli/src/lib/utils.ts
+++ b/packages/openui-cli/src/lib/utils.ts
@@ -3,6 +3,10 @@ import { createFunnelProps } from "./create-telemetry";
import type { TemplateName } from "./create-types";
import { CreateError, telemetry as defaultTelemetry, type Telemetry } from "./telemetry";
+/** ASCII Record Separator — Untypeable in prompt text and always
+ * escaped by JSON.stringify, so it can never collide with either artifact. */
+export const SEPARATION_DELIMITER = "\u001E";
+
export function handleCliError(
e: unknown,
event: string,
diff --git a/packages/react-lang/package.json b/packages/react-lang/package.json
index a8cd3672a..1f14ab84d 100644
--- a/packages/react-lang/package.json
+++ b/packages/react-lang/package.json
@@ -1,6 +1,6 @@
{
"name": "@openuidev/react-lang",
- "version": "0.2.8",
+ "version": "0.2.9",
"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",
diff --git a/packages/react-lang/src/index.ts b/packages/react-lang/src/index.ts
index c6ecf8c29..586c5ef99 100644
--- a/packages/react-lang/src/index.ts
+++ b/packages/react-lang/src/index.ts
@@ -32,8 +32,14 @@ export type {
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";
+export { generatePrompt, generateSystemPrompt } from "@openuidev/lang-core";
+export type {
+ ComponentPromptSpec,
+ PromptSpec,
+ SystemPromptOptions,
+ SystemPromptSpec,
+ ToolSpec,
+} from "@openuidev/lang-core";
// openui-lang edit/merge
export { mergeStatements } from "@openuidev/lang-core";