Skip to content

The Open Standard for Generative UI

OpenUI 1.0 (#1348)

Aditya-thesys9e76b1d0b482
diff --git a/.changeset/README.md b/.changeset/README.md
index cb0e8db87..04bcb3707 100644
--- a/.changeset/README.md
+++ b/.changeset/README.md
@@ -8,10 +8,13 @@ Releases are automated with [changesets](https://github.com/changesets/changeset
- On every push to `main`, CI maintains a **Version Packages** PR carrying all
pending bumps and changelogs. Merging that PR publishes to npm, tags, and
creates GitHub Releases. Merge it whenever a release should go out.
-- All packages are 0.x: a **patch** is the normal bump; a **minor** signals a
- breaking change (it escapes consumers' `^` ranges).
+- A breaking change escapes consumers' `^` ranges: a **major** for packages at
+ 1.0 or above (lang-core, react-lang), a **minor** for packages still on 0.x.
+ Otherwise a **patch** is the normal bump.
- Packages that runtime-depend on a bumped package are patch-bumped
- automatically — don't add changesets for them.
+ automatically. When that dependency takes a breaking bump, give the dependent
+ a breaking bump too, or a `^` install of the old version pulls the new
+ dependency.
- Internal `peerDependencies` use hand-maintained bounded ranges (e.g.
`">=0.3.0 <0.4.0"`), never `workspace:` protocol. If your change makes a
package require a newer version of an internal peer, move that window in the
diff --git a/.changeset/action-slot-refs.md b/.changeset/action-slot-refs.md
new file mode 100644
index 000000000..b591637c4
--- /dev/null
+++ b/.changeset/action-slot-refs.md
@@ -0,0 +1,6 @@
+---
+"@openuidev/lang-core": minor
+"@openuidev/react-lang": patch
+---
+
+Action slots are JSON Schema `$ref`s, like component slots. An action prop is `{"$ref": "#/$defs/ActionExpression"}`, and the library's `$defs` has `ActionExpression` with the same legacy object union as before. A slot can name specific steps with refs, for example `share: z.union([steps.ToAssistant.ref, steps.OpenUrl.ref]).optional()` (lang-core, re-exported by react-lang): the JSON gets `ToAssistant` and `OpenUrl` `$defs`, and the prompt signature prints `share?: @ToAssistant | @OpenUrl`. These refs only shape the prompt and the JSON for now; the runtime accepts any step in them. Action `$defs` are never components.
diff --git a/.changeset/action-steps-without-wrapper.md b/.changeset/action-steps-without-wrapper.md
new file mode 100644
index 000000000..a100fb628
--- /dev/null
+++ b/.changeset/action-steps-without-wrapper.md
@@ -0,0 +1,11 @@
+---
+"@openuidev/lang-core": minor
+"@openuidev/react-lang": patch
+"@openuidev/react-ui": patch
+---
+
+Action steps are plans. Every step call now evaluates to a one-step plan (`{ steps: [step] }`), so a single step needs no wrapper: `Button("Ask", @ToAssistant("Tell me more"))`. Several steps still need `Action([...])`, for example `Button("Save", Action([@Set($saved, true), @ToAssistant("Saved")]))`; a plain list of steps stays a plain array. An invalid step evaluates to an empty plan (a no-op) instead of null, and `Action([...])` flattens nested plans. Legacy `{ type, params }` action configs are unchanged.
+
+New `action()` helper (lang-core, re-exported by react-lang), like `reactive()`: it returns the action prop schema, already tagged `ActionExpression`, so libraries write `action: action().optional()` instead of calling `tagSchemaId(..., "ActionExpression")` themselves. react-ui's action props use it.
+
+Prompt change: for libraries with action props (`ActionExpression`), the system prompt teaches one step bare and several steps in `Action([...])`. The react-ui prompt examples, including the chat library examples, use step calls instead of legacy objects.
diff --git a/.changeset/assistant-ui-warning-fallback.md b/.changeset/assistant-ui-warning-fallback.md
new file mode 100644
index 000000000..50095e675
--- /dev/null
+++ b/.changeset/assistant-ui-warning-fallback.md
@@ -0,0 +1,5 @@
+---
+"@openuidev/assistant-ui": patch
+---
+
+The error fallback no longer appears for warnings, such as a program without `root` whose entry still renders.
diff --git a/.changeset/config.json b/.changeset/config.json
index 9eff22371..ca427a771 100644
--- a/.changeset/config.json
+++ b/.changeset/config.json
@@ -6,14 +6,7 @@
"baseBranch": "main",
"updateInternalDependencies": "patch",
"fixed": [
- [
- "@openuidev/lang-core",
- "@openuidev/react-lang",
- "@openuidev/svelte-lang",
- "@openuidev/vue-lang",
- "@openuidev/angular-lang",
- "@openuidev/a2ui"
- ],
+ ["@openuidev/lang-core", "@openuidev/react-lang"],
["@openuidev/react-headless", "@openuidev/react-ui"]
],
"linked": [],
diff --git a/.changeset/content-line-mid-line.md b/.changeset/content-line-mid-line.md
new file mode 100644
index 000000000..0b2110107
--- /dev/null
+++ b/.changeset/content-line-mid-line.md
@@ -0,0 +1,6 @@
+---
+"@openuidev/react-lang": patch
+"@openuidev/react-ui": patch
+---
+
+Stored messages and Cloud responses whose second content line starts mid-line, after a cut-off first attempt, read the second attempt, as before.
diff --git a/.changeset/custom-actions.md b/.changeset/custom-actions.md
new file mode 100644
index 000000000..4d8e083c5
--- /dev/null
+++ b/.changeset/custom-actions.md
@@ -0,0 +1,15 @@
+---
+"@openuidev/lang-core": minor
+"@openuidev/react-lang": minor
+"@openuidev/react-ui": minor
+---
+
+Add custom actions: `defineAction({ name, description, params })` plus `createLibrary({ actions })`. Programs use them like the built-in steps, alone or in `Action([...])`, for example `Button("Copy", @CopyToClipboard(order.id))`, with positional arguments in `params` key order. On click the step reaches the host `onAction` as `{ type: name, params }` (schema defaults applied), in order with the other steps, and the event is typed from the library so `params` narrows by `type`. Args are validated like library function args, and a step with invalid args is a no-op. Only a real call produces a custom step: a plan read from data (an object literal, `$state`, an `@Each` item) loses its custom steps, and a legacy action object whose type names a custom action is ignored. `library.toJSONSchema()` lists actions under `actions`, the prompt lists them with the built-in action steps, and `toSpec()` includes them. The React `Renderer` and the server autofix parser pick them up automatically, and the react-ui `Button` validates its form before a custom action.
+
+Types: the exported `ActionStep` union adds `{ type: "custom_action"; name; params }`, so a `switch` over `ActionStep` types needs a case for it.
+
+In react-ui, `AgentInterface` takes `onAction`, which receives the actions the chat does not handle itself, such as custom actions.
+
+The built-in steps (`@Run`, `@ToAssistant`, `@OpenUrl`, `@Set`, `@Reset`) are now defined like custom actions and live in the same call registry, so their prompt lines are generated too (for example `@OpenUrl(url: string)`). `ACTION_NAMES` is removed.
+
+A defined action has a `.ref` for slots that take only some actions, for example `share: z.union([copy.ref, steps.OpenUrl.ref]).optional()`: the prompt signature prints `share?: @CopyToClipboard | @OpenUrl`, and the JSON gets a `CopyToClipboard` `$defs` entry `{ type: "CopyToClipboard", params }`.
diff --git a/.changeset/form-state-per-step.md b/.changeset/form-state-per-step.md
new file mode 100644
index 000000000..e4999235a
--- /dev/null
+++ b/.changeset/form-state-per-step.md
@@ -0,0 +1,5 @@
+---
+"@openuidev/react-lang": patch
+---
+
+Action steps read the form state when each step runs, so an earlier `@Set` in the same plan is visible.
diff --git a/.changeset/lang-core-entry-rule.md b/.changeset/lang-core-entry-rule.md
new file mode 100644
index 000000000..d7a3e5fee
--- /dev/null
+++ b/.changeset/lang-core-entry-rule.md
@@ -0,0 +1,13 @@
+---
+"@openuidev/lang-core": minor
+"@openuidev/react-lang": patch
+---
+
+OpenUI Lang 1.0 entry rule: the entry is the `root` statement, else the first statement that calls the library root component, wherever it is (`no-root` with `severity: "warning"`), else a `no-root` error. With no entry, statements are not also reported as orphaned. `root = $t ? A : B` is a valid entry, exposed as `ParseResult.rootExpression` and evaluated with the new `evaluateRoot()`. An `@Name(...)` call that is not a built-in or action step reports `unknown-function` and evaluates to null; its statement is kept.
+React: renders ternary entries and reports `no-root` instead of `parse-failed` when statements parsed but no entry rendered.
+`ValidationErrorCode` adds `no-root` and `unknown-function`. `ValidationError` and `OpenUIError` gain an optional `severity: "warning"`; react-lang passes it through to `onError`.
+
+Breaking:
+
+- A program without `root` in which no statement calls the library root component no longer renders its first component statement.
+- `@Name(...)` for a non-built-in, including `@Card(...)`, now evaluates to null with `unknown-function` instead of acting as a component call.
diff --git a/.changeset/lang-core-message-protocol.md b/.changeset/lang-core-message-protocol.md
new file mode 100644
index 000000000..c7d1b84b3
--- /dev/null
+++ b/.changeset/lang-core-message-protocol.md
@@ -0,0 +1,6 @@
+---
+"@openuidev/lang-core": minor
+"@openuidev/react-lang": minor
+---
+
+Add `parseMessage` and `buildMessage` for the OpenUI message protocol (`]]>openui:content`, `context`, `end` marker lines). The react-lang `Renderer` now accepts a stored message as `response` and renders its content.
diff --git a/.changeset/library-extend.md b/.changeset/library-extend.md
new file mode 100644
index 000000000..9843d2a0a
--- /dev/null
+++ b/.changeset/library-extend.md
@@ -0,0 +1,6 @@
+---
+"@openuidev/lang-core": minor
+"@openuidev/react-lang": patch
+---
+
+Add `library.extend()`, which derives a new library from an existing one (the base stays untouched): `lib.extend({ components: { add: [ProductCard], remove: ["Image"] }, functions: { add: [percent] }, actions: { add: [copy] } })`. Components support `add` (to the library only, or into content slots with `{ component, slots: ["Card"] }` or `"Card.children"`), `override` (every parent points at the replacement) and `remove` (dropped from every parent union and from `componentGroups`; removing the root or a slot's only type throws, and a removed name still in prompt notes, examples or rules warns once). Added functions and actions work like those passed to `createLibrary`. The result has no public `id`. Adding a name that already exists throws. The typed `onAction` event includes added actions and keeps the built-in events. Create derived libraries once at module scope, since parsers memoize by library identity. In development, react-lang registers each derived library with devtools under its own key.
diff --git a/.changeset/message-content-mid-line.md b/.changeset/message-content-mid-line.md
new file mode 100644
index 000000000..2fdd166d9
--- /dev/null
+++ b/.changeset/message-content-mid-line.md
@@ -0,0 +1,7 @@
+---
+"@openuidev/lang-core": patch
+"@openuidev/react-lang": patch
+"@openuidev/react-ui": patch
+---
+
+`parseMessage` reads a content line that starts mid-line as a new content section, so a regenerated response wins over the cut-off one, also while streaming. react-lang and react-ui drop their own copies of this step, and a Cloud response keeps the second attempt's scripts.
diff --git a/.changeset/openui-1-0-review-fixes.md b/.changeset/openui-1-0-review-fixes.md
new file mode 100644
index 000000000..f9297bbd3
--- /dev/null
+++ b/.changeset/openui-1-0-review-fixes.md
@@ -0,0 +1,15 @@
+---
+"@openuidev/lang-core": patch
+"@openuidev/react-ui": patch
+"@openuidev/a2ui": patch
+"@openuidev/assistant-ui": patch
+"@openuidev/devtools": patch
+"@openuidev/react-email": patch
+---
+
+OpenUI 1.0 review fixes:
+
+- lang-core: the built-in functions prompt no longer uses react-ui's `Col` in its `@Each` example, and names Query only when tool calls are on.
+- lang-core: `JSONSchemaDef` adds `type` and `anyOf`, so the CLI's spec for a library that uses `action()` passes to `generateSystemPrompt` without a cast.
+- react-ui: the chat prompt's button rules name `@ToAssistant` and `@OpenUrl`.
+- react-ui, a2ui, assistant-ui, devtools, react-email: the `@openuidev/react-lang` peer window now covers the version this release publishes.
diff --git a/.changeset/openui-1-0-versions.md b/.changeset/openui-1-0-versions.md
new file mode 100644
index 000000000..6548e77c4
--- /dev/null
+++ b/.changeset/openui-1-0-versions.md
@@ -0,0 +1,21 @@
+---
+"@openuidev/lang-core": major
+"@openuidev/react-lang": major
+"@openuidev/a2ui": minor
+"@openuidev/react-ui": minor
+"@openuidev/devtools": minor
+"@openuidev/assistant-ui": minor
+"@openuidev/react-email": minor
+"@openuidev/browser-bundle": minor
+"@openuidev/server": minor
+---
+
+OpenUI Lang 1.0.
+
+- Upgrade `@openuidev/lang-core` and `@openuidev/react-lang` together, and together with the server that generates the system prompt. A 1.0 prompt teaches bare action steps (`@ToAssistant("Hi")` without `Action([...])`), which a 0.x client does not run.
+- react-ui 0.18 requires react-lang 1.0 (peer `>=1.0.0 <2.0.0`); upgrade them together.
+- browser-bundle 0.2 bundles react-lang 1.0 and react-ui 0.18.
+- server 0.3 uses lang-core 1.0 for autofix (parser and system prompt); stay on server 0.2 with a 0.x client. Autofix ignores warnings and accepts a ternary entry, so a program that renders does not start a fix round.
+- vue-lang, svelte-lang and angular-lang stay on 0.4 (OpenUI Lang 0.x). Keep `@openuidev/lang-core` ^0.4 for the prompts they render.
+- A program whose `root` statement is written last shows nothing while it streams, until the `root` line arrives. Write `root` first, as the system prompt asks.
+- A cut-off output that never reached its `root` statement, or any statement calling the root component, now renders blank instead of a partial tree.
diff --git a/.changeset/react-ui-message-protocol.md b/.changeset/react-ui-message-protocol.md
new file mode 100644
index 000000000..cd06eaa5f
--- /dev/null
+++ b/.changeset/react-ui-message-protocol.md
@@ -0,0 +1,5 @@
+---
+"@openuidev/react-ui": patch
+---
+
+The chat components read and write stored messages with `parseMessage` and `buildMessage` from react-lang instead of their own marker parser. Stored bytes are unchanged, and older messages in the `<content>`/`<context>` XML envelope still read. A complete message whose content ends in `]` (or any other start of a marker) is no longer cut short, and `]]>openui:end` text in the middle of a line stays in the content.
diff --git a/.changeset/registered-functions.md b/.changeset/registered-functions.md
new file mode 100644
index 000000000..d8578ce2d
--- /dev/null
+++ b/.changeset/registered-functions.md
@@ -0,0 +1,8 @@
+---
+"@openuidev/lang-core": minor
+"@openuidev/react-lang": minor
+---
+
+Add library functions: `defineFunction({ name, description, params, returns, fn })` plus `createLibrary({ functions })`, for example `@Percent(done, total)`. Programs call them with positional arguments in `params` key order, and `fn` receives one object with schema defaults applied. `library.toJSONSchema()` lists them under `functions` (params and returns as JSON Schema) and `toSpec()` describes them like components, so every parser built from the schema, including the server autofix, accepts them. Args go through the component prop pipeline: the parser maps them by name and validates literals (`type-mismatch`, `missing-required`, `excess-args`; an invalid optional arg is dropped so its default applies), the runtime validates dynamic args and return values. An invalid call or a throwing `fn` evaluates to null with a `runtime-error`. Calls run on every streamed chunk like built-ins; the Renderer reports their errors once streaming ends. The prompt lists them with the built-in functions, and the new `builtinFunctions` prompt option lists the built-ins without `toolCalls` or `bindings`; prompt options never change what parses or runs.
+
+Built-ins are now defined with `defineFunction` too, so their prompt lines are generated (for example `@Sum(numbers: number[]) → number`). `BUILTINS`, `BUILTIN_NAMES`, `LAZY_BUILTINS`, `isBuiltin` and the `BuiltinDef` type are removed.
diff --git a/.changeset/streaming-state-defaults.md b/.changeset/streaming-state-defaults.md
new file mode 100644
index 000000000..b6e96a5a7
--- /dev/null
+++ b/.changeset/streaming-state-defaults.md
@@ -0,0 +1,6 @@
+---
+"@openuidev/lang-core": patch
+"@openuidev/react-lang": patch
+---
+
+A `$state` value that streams in no longer sticks at its half-written value: an untouched default is replaced when the full declaration arrives, a partly typed `$name` no longer becomes state, and setting up declared defaults no longer fires `onStateUpdate`. User edits are kept. `StreamParser.push`, `set` and `getResult` take a `complete` flag: pass `true` once the stream has ended, or a `$name` that is the last token is not declared.
diff --git a/.changeset/to-assistant-context.md b/.changeset/to-assistant-context.md
new file mode 100644
index 000000000..eb332ac69
--- /dev/null
+++ b/.changeset/to-assistant-context.md
@@ -0,0 +1,7 @@
+---
+"@openuidev/lang-core": minor
+"@openuidev/react-lang": patch
+"@openuidev/react-ui": patch
+---
+
+`@ToAssistant(message, context)` passes its context through unchanged as any value (object, array, number, string, including falsy ones). The `continue_conversation` step's `context` is now typed `unknown`, and react-lang forwards it in `params.context` whenever it is set. The react-ui chat adds it as the third element of the chat context, and card blocks append their item context to it as text, as before. The system prompt documents the context argument.
diff --git a/.changeset/trim-lang-core-exports.md b/.changeset/trim-lang-core-exports.md
new file mode 100644
index 000000000..3abcf9816
--- /dev/null
+++ b/.changeset/trim-lang-core-exports.md
@@ -0,0 +1,5 @@
+---
+"@openuidev/lang-core": major
+---
+
+Remove exports with no users: `isASTNode`, `isRuntimeExpr`, `CallNode`, `RuntimeExprNode`, `Statement`, `Token`, `BUILTINS`, `isBuiltin` and `toNumber`.
diff --git a/docs/generated/chat-library.spec.json b/docs/generated/chat-library.spec.json
index 94fd48a37..8ba172e3b 100644
--- a/docs/generated/chat-library.spec.json
+++ b/docs/generated/chat-library.spec.json
@@ -456,8 +456,8 @@
"- Use ListBlock with ListItem references for numbered lists.",
"- Use FollowUpBlock with FollowUpItem references at the end of a response to suggest next actions.",
"- A ListItem is clickable ONLY when given an action (5th argument); without one it is plain text.",
- "- Clicking a FollowUpItem, or a ListItem with a continue_conversation action, sends text to the LLM as a user message.",
- "- Example: list = ListBlock([item1, item2]) item1 = ListItem(\"Option A\", \"Details about A\", null, null, { type: \"continue_conversation\", context: \"Option A\" })"
+ "- Clicking a FollowUpItem, or a ListItem with a @ToAssistant action, sends text to the LLM as a user message.",
+ "- Example: list = ListBlock([item1, item2]) item1 = ListItem(\"Option A\", \"Details about A\", null, null, @ToAssistant(\"Option A\"))"
]
},
{
@@ -1702,60 +1702,7 @@
"type": "string"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
},
"variant": {
"type": "string",
@@ -1788,6 +1735,62 @@
"additionalProperties": false,
"description": "Clickable button"
},
+ "ActionExpression": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "const": "open_url"
+ },
+ "url": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "url"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "const": "continue_conversation"
+ },
+ "context": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string"
+ },
+ "params": {
+ "type": "object",
+ "propertyNames": {
+ "type": "string"
+ },
+ "additionalProperties": {}
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "additionalProperties": false
+ }
+ ]
+ },
"FormControl": {
"type": "object",
"properties": {
@@ -2563,60 +2566,7 @@
"$ref": "#/$defs/Icon"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
},
"variant": {
"type": "string",
@@ -2920,60 +2870,7 @@
"type": "boolean"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
},
"gap": {
"anyOf": [
@@ -3246,60 +3143,7 @@
"type": "boolean"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
},
"gap": {
"anyOf": [
@@ -3408,60 +3252,7 @@
"type": "boolean"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
},
"gap": {
"anyOf": [
@@ -3577,60 +3368,7 @@
"type": "boolean"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
},
"gap": {
"anyOf": [
@@ -3830,60 +3568,7 @@
"type": "string"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
}
},
"required": [
@@ -3954,60 +3639,7 @@
"type": "boolean"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
},
"gap": {
"anyOf": [
diff --git a/docs/generated/playground-library.spec.json b/docs/generated/playground-library.spec.json
index 9c5160c6b..350f77b06 100644
--- a/docs/generated/playground-library.spec.json
+++ b/docs/generated/playground-library.spec.json
@@ -1713,60 +1713,7 @@
"type": "string"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
},
"variant": {
"type": "string",
@@ -1799,6 +1746,62 @@
"additionalProperties": false,
"description": "Clickable button"
},
+ "ActionExpression": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "const": "open_url"
+ },
+ "url": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "url"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "const": "continue_conversation"
+ },
+ "context": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string"
+ },
+ "params": {
+ "type": "object",
+ "propertyNames": {
+ "type": "string"
+ },
+ "additionalProperties": {}
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "additionalProperties": false
+ }
+ ]
+ },
"FormControl": {
"type": "object",
"properties": {
@@ -2574,60 +2577,7 @@
"$ref": "#/$defs/Icon"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
},
"variant": {
"type": "string",
@@ -2931,60 +2881,7 @@
"type": "boolean"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
},
"gap": {
"anyOf": [
@@ -3257,60 +3154,7 @@
"type": "boolean"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
},
"gap": {
"anyOf": [
@@ -3419,60 +3263,7 @@
"type": "boolean"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
},
"gap": {
"anyOf": [
@@ -3588,60 +3379,7 @@
"type": "boolean"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
},
"gap": {
"anyOf": [
@@ -3841,60 +3579,7 @@
"type": "string"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
}
},
"required": [
@@ -3965,60 +3650,7 @@
"type": "boolean"
},
"action": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "open_url"
- },
- "url": {
- "type": "string"
- }
- },
- "required": [
- "type",
- "url"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string",
- "const": "continue_conversation"
- },
- "context": {
- "type": "string"
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "type": {
- "type": "string"
- },
- "params": {
- "type": "object",
- "propertyNames": {
- "type": "string"
- },
- "additionalProperties": {}
- }
- },
- "required": [
- "type"
- ],
- "additionalProperties": false
- }
- ]
+ "$ref": "#/$defs/ActionExpression"
},
"gap": {
"anyOf": [
diff --git a/packages/a2ui/package.json b/packages/a2ui/package.json
index 208015507..f65809e66 100644
--- a/packages/a2ui/package.json
+++ b/packages/a2ui/package.json
@@ -71,7 +71,7 @@
"@openuidev/lang-core": "workspace:^"
},
"peerDependencies": {
- "@openuidev/react-lang": ">=0.3.0 <0.5.0",
+ "@openuidev/react-lang": ">=1.0.0 <2.0.0",
"react": "catalog:",
"zod": "catalog:"
},
diff --git a/packages/angular-lang/package.json b/packages/angular-lang/package.json
index 2a7de5e94..7360f0b5b 100644
--- a/packages/angular-lang/package.json
+++ b/packages/angular-lang/package.json
@@ -57,7 +57,7 @@
},
"author": "[email protected]",
"dependencies": {
- "@openuidev/lang-core": "workspace:^",
+ "@openuidev/lang-core": "^0.4.1",
"tslib": "catalog:"
},
"peerDependencies": {
diff --git a/packages/assistant-ui/package.json b/packages/assistant-ui/package.json
index 80a80f01b..89b1c145a 100644
--- a/packages/assistant-ui/package.json
+++ b/packages/assistant-ui/package.json
@@ -79,9 +79,9 @@
"author": "[email protected]",
"peerDependencies": {
"@assistant-ui/react": "^0.15.0",
- "@openuidev/react-headless": ">=0.14.0 <0.18.0",
- "@openuidev/react-lang": ">=0.3.0 <0.5.0",
- "@openuidev/react-ui": ">=0.14.0 <0.18.0",
+ "@openuidev/react-headless": ">=0.14.0 <0.19.0",
+ "@openuidev/react-lang": ">=1.0.0 <2.0.0",
+ "@openuidev/react-ui": ">=0.14.0 <0.19.0",
"ai": "^6.0.0 || ^7.0.0",
"react": "catalog:",
"react-dom": "catalog:",
diff --git a/packages/assistant-ui/src/__tests__/renderers.test.tsx b/packages/assistant-ui/src/__tests__/renderers.test.tsx
index 12eb34fe2..b6b689771 100644
--- a/packages/assistant-ui/src/__tests__/renderers.test.tsx
+++ b/packages/assistant-ui/src/__tests__/renderers.test.tsx
@@ -257,4 +257,12 @@ describe("OpenUIPrompt", () => {
await renderPrompt(makeProps());
expect(container.querySelector('[role="alert"]')).toBeNull();
});
+
+ it("does not show the fallback for a warning when the program renders", async () => {
+ const args = { ui: 'card = Card([h])\nh = CardHeader("Entry", "B")' };
+ await renderPrompt(makeProps({ args, argsText: JSON.stringify(args) }));
+
+ expect(container.textContent).toContain("Entry");
+ expect(container.querySelector('[role="alert"]')).toBeNull();
+ });
});
diff --git a/packages/assistant-ui/src/renderers.tsx b/packages/assistant-ui/src/renderers.tsx
index e34fad5b5..25fdc7a96 100644
--- a/packages/assistant-ui/src/renderers.tsx
+++ b/packages/assistant-ui/src/renderers.tsx
@@ -84,6 +84,9 @@ export function OpenUIContent({
[onError],
);
+ // Warnings (a program without `root` whose entry renders) are not render failures.
+ const failures = errors.filter((error) => error.severity !== "warning");
+
const content = (
<>
<Renderer
@@ -95,8 +98,8 @@ export function OpenUIContent({
{...(initialState !== undefined && { initialState })}
{...(onAction !== undefined && { onAction })}
/>
- {!isStreaming && errors.length > 0 && ErrorFallback !== null && (
- <ErrorFallback errors={errors} />
+ {!isStreaming && failures.length > 0 && ErrorFallback !== null && (
+ <ErrorFallback errors={failures} />
)}
</>
);
diff --git a/packages/devtools/package.json b/packages/devtools/package.json
index 1f3413d67..dc381c4d1 100644
--- a/packages/devtools/package.json
+++ b/packages/devtools/package.json
@@ -41,7 +41,7 @@
},
"peerDependencies": {
"@openuidev/observability": ">=0.0.4 <0.1.0",
- "@openuidev/react-lang": ">=0.3.0 <0.5.0",
+ "@openuidev/react-lang": ">=1.0.0 <2.0.0",
"react": "catalog:",
"react-dom": "catalog:"
},
diff --git a/packages/devtools/src/debug/lib/usePlayback.ts b/packages/devtools/src/debug/lib/usePlayback.ts
index bfe34fd6e..1ab490ab4 100644
--- a/packages/devtools/src/debug/lib/usePlayback.ts
+++ b/packages/devtools/src/debug/lib/usePlayback.ts
@@ -255,7 +255,7 @@ export function usePlayback(
} else {
const sp = lang.createStreamingParser!(schema, rootName);
push = (chunk) => sp.push(chunk);
- getFinal = () => sp.getResult();
+ getFinal = () => sp.getResult(true);
}
const s: Session = {
diff --git a/packages/lang-core/package.json b/packages/lang-core/package.json
index 66fda107b..9db06d72e 100644
--- a/packages/lang-core/package.json
+++ b/packages/lang-core/package.json
@@ -56,7 +56,7 @@
"postinstall": "node ./postinstall.cjs",
"prepare": "pnpm run build",
"prepublishOnly": "pnpm run check:publint && pnpm run check:attw",
- "ci": "pnpm run lint:check && pnpm run format:check"
+ "ci": "pnpm run lint:check && pnpm run format:check && pnpm run test && tsc -p tsconfig.test.json --noEmit"
},
"peerDependencies": {
"@modelcontextprotocol/sdk": ">=1.0.0",
diff --git a/packages/lang-core/src/__tests__/extend.test.ts b/packages/lang-core/src/__tests__/extend.test.ts
new file mode 100644
index 000000000..97c921839
--- /dev/null
+++ b/packages/lang-core/src/__tests__/extend.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from "vitest";
+import { z } from "zod/v4";
+import { createLibrary, defineAction, defineComponent, defineFunction } from "../library";
+import { createParser } from "../parser";
+
+const comp = (name: string, props: z.ZodObject = z.object({ label: z.string() })) =>
+ defineComponent({ name, props, description: `${name} desc`, component: null });
+const Text = comp("Text");
+const Image = comp("Image");
+const Stack = comp("Stack", z.object({ children: z.array(z.union([Text.ref, Image.ref])) }));
+const Frame = comp("Frame", z.object({ image: Image.ref }));
+const parts = {
+ components: [Stack, Text, Image, Frame],
+ componentGroups: [
+ { name: "Media", components: ["Image", "Frame"], notes: ["Frame wraps one Image"] },
+ ],
+ root: "Stack",
+ id: "base",
+};
+const base = createLibrary(parts);
+const sig = (lib: { prompt(): string }, name: string) => lib.prompt().match(`\n${name}\\(.*`)?.[0];
+
+describe("library.extend", () => {
+ it("adds a component to the library only, and leaves the base untouched", () => {
+ const before = base.prompt();
+ const lib = base.extend({ components: { add: [comp("Card")] } });
+ expect(Object.keys(lib.components)).toEqual(["Stack", "Text", "Image", "Frame", "Card"]);
+ expect(sig(lib, "Card")).toContain("Card(label: string)");
+ expect(sig(lib, "Stack")).toContain("children: (Text | Image)[]");
+ expect(base.prompt()).toBe(before);
+ });
+
+ it('adds into a slot by "Parent.prop" or "Parent", and the parser accepts it', () => {
+ const program = 'root = Stack([Card("hi")])';
+ for (const slot of ["Stack.children", "Stack"]) {
+ const lib = base.extend({
+ components: { add: [{ component: comp("Card"), slots: [slot] }] },
+ });
+ expect(sig(lib, "Stack")).toContain("children: (Text | Image | Card)[]");
+ const parsed = createParser(lib.toJSONSchema(), "Stack").parse(program);
+ expect(parsed.meta.errors).toEqual([]);
+ expect(JSON.stringify(parsed.root)).toContain('"typeName":"Card"');
+ }
+ });
+
+ it("overrides a component and rebinds every parent", () => {
+ const lib = base.extend({
+ components: { override: [comp("Image", z.object({ src: z.string() }))] },
+ });
+ const merged = createLibrary({ ...parts, components: Object.values(lib.components) });
+ expect(lib.prompt()).toBe(merged.prompt());
+ expect(lib.toJSONSchema()).toEqual(merged.toJSONSchema());
+ });
+
+ it("removes from unions and groups", () => {
+ const lib = base.extend({ components: { remove: ["Frame", "Text"] } });
+ expect(sig(lib, "Stack")).toContain("children: (Image)[]");
+ expect(lib.componentGroups).toEqual([{ ...parts.componentGroups[0], components: ["Image"] }]);
+ });
+
+ it("slots a component that nests its new parent: Card(body: Stack) into Stack", () => {
+ const Card = comp("Card", z.object({ body: Stack.ref }));
+ const lib = base.extend({ components: { add: [{ component: Card, slots: ["Stack"] }] } });
+ const schema = lib.toJSONSchema();
+ const parsed = createParser(schema, "Stack").parse('root = Stack([Card(Stack([Text("x")]))])');
+ expect(parsed.meta.errors).toEqual([]);
+ expect(Object.keys(schema.$defs!).sort()).toEqual(["Card", "Frame", "Image", "Stack", "Text"]);
+ expect(schema.$defs!.Card).toMatchObject({ properties: { body: { $ref: "#/$defs/Stack" } } });
+ });
+
+ it("rebinds a self-recursive component to itself", () => {
+ const Tree: any = comp(
+ "Tree",
+ z.object({
+ get children(): z.ZodArray {
+ return z.array(z.union([Tree.ref, Text.ref]));
+ },
+ }),
+ );
+ const lib = createLibrary({ components: [Tree, Text], root: "Tree" }).extend({
+ components: { override: [comp("Text", z.object({ value: z.string() }))] },
+ });
+ const schema = lib.toJSONSchema();
+ expect(Object.keys(schema.$defs!).sort()).toEqual(["Text", "Tree"]);
+ const items = { anyOf: [{ $ref: "#/$defs/Tree" }, { $ref: "#/$defs/Text" }] };
+ expect(schema.$defs!.Tree).toMatchObject({ properties: { children: { items } } });
+ expect(schema.$defs!.Text).toMatchObject({ properties: { value: { type: "string" } } });
+ });
+
+ it("replaces every member of a slot in one call", () => {
+ const lib = base.extend({
+ components: {
+ remove: ["Text", "Image", "Frame"],
+ add: [{ component: comp("Card"), slots: ["Stack"] }],
+ },
+ });
+ expect(sig(lib, "Stack")).toContain("children: (Card)[]");
+ });
+
+ it("adds once when two slots name the same prop", () => {
+ const lib = base.extend({
+ components: { add: [{ component: comp("Card"), slots: ["Stack.children", "Stack"] }] },
+ });
+ expect(sig(lib, "Stack")).toContain("children: (Text | Image | Card)[]");
+ });
+
+ it("fails fast on bad slots and names", () => {
+ const add = (slots: string[]) =>
+ base.extend({ components: { add: [{ component: comp("Card"), slots }] } });
+ expect(() => add(["Frame"])).toThrow('"Frame" has no content slot');
+ expect(() => add(["Stack.kids"])).toThrow("Candidates: Stack.children.");
+ expect(() => base.extend({ components: { add: [comp("Text")] } })).toThrow("already exists");
+ expect(() => base.extend({ components: { override: [comp("Card")] } })).toThrow(
+ 'Cannot override "Card"',
+ );
+ expect(() => base.extend({ components: { add: [comp("Card")], remove: ["Card"] } })).toThrow(
+ "added or overridden in the same call",
+ );
+ expect(() => base.extend({ components: { remove: ["Image"] } })).toThrow("only type allowed");
+ expect(() => base.extend({ components: { remove: ["Stack"] } })).toThrow("library root");
+ });
+
+ it("adds functions and actions; a derived library has no id", () => {
+ const percent = defineFunction({
+ name: "Percent",
+ description: "a / b",
+ params: z.object({ a: z.number(), b: z.number() }),
+ fn: ({ a, b }) => a / b,
+ });
+ const copy = defineAction({ name: "Copy", description: "copy", params: z.object({}) });
+ const lib = base.extend({ functions: { add: [percent] }, actions: { add: [copy] } });
+ expect(lib.prompt()).toContain("@Percent(a: number, b: number)");
+ expect(lib.actions.Copy).toBe(copy);
+ expect(lib.id).toBeUndefined();
+ expect(() => lib.extend({ functions: { add: [percent] } })).toThrow('"Percent" collides');
+ });
+});
diff --git a/packages/lang-core/src/__tests__/library.test.ts b/packages/lang-core/src/__tests__/library.test.ts
index 046f76f7e..3da00cfcd 100644
--- a/packages/lang-core/src/__tests__/library.test.ts
+++ b/packages/lang-core/src/__tests__/library.test.ts
@@ -1,19 +1,23 @@
import { describe, expect, it } from "vitest";
import { z } from "zod/v4";
-import { createLibrary, defineComponent, tagSchemaId } from "../library";
+import { createLibrary, defineComponent, tagSchemaId, type Library } from "../library";
+import { createParser } from "../parser";
+import { action, steps } from "../parser/builtins";
+import type { LibrarySpec } from "../parser/prompt";
const Dummy = null as any;
// ─── tagSchemaId + registry integration ─────────────────────────────────────
describe("tagSchemaId", () => {
- it("tagged schema appears in prompt signatures", () => {
- const actionSchema = z.any();
- tagSchemaId(actionSchema, "ActionExpression");
-
+ it("action slots are ActionExpression or restricted @Name refs, $refs in JSON", () => {
const Button = defineComponent({
name: "Button",
- props: z.object({ label: z.string(), action: actionSchema.optional() }),
+ props: z.object({
+ label: z.string(),
+ action: action().optional(),
+ share: z.union([steps.ToAssistant.ref, steps.OpenUrl.ref]).optional(),
+ }),
description: "A button",
component: Dummy,
});
@@ -21,7 +25,15 @@ describe("tagSchemaId", () => {
const lib = createLibrary({ components: [Button], root: "Button" });
const prompt = lib.prompt();
- expect(prompt).toContain("action?: ActionExpression");
+ expect(prompt).toContain("action?: ActionExpression, share?: @ToAssistant | @OpenUrl)");
+ expect(prompt).toContain("Put several steps in Action([...])");
+ const schema = lib.toJSONSchema();
+ expect(schema.$defs?.Button.properties?.action).toEqual({ $ref: "#/$defs/ActionExpression" });
+ // A legacy object in an action slot is data, not a component: no type-mismatch
+ const parsed = createParser(schema, "Button").parse(
+ 'root = Button("x", {type: "continue_conversation", context: "x"})',
+ );
+ expect(parsed.meta.errors).toEqual([]);
});
it("tagged schema inside array is discovered", () => {
@@ -163,7 +175,7 @@ describe("per-library registry", () => {
expect(spec.root).toBe("Card");
expect(spec.components["Card"]?.signature).toContain("title");
expect(spec.componentGroups).toEqual([{ name: "Content", components: ["TextContent"] }]);
- expect(spec.schema).toEqual(lib.toJSONSchema());
+ expect((spec as LibrarySpec).schema).toEqual(lib.toJSONSchema());
});
it("toSpec carries the createLibrary id, omitted when unset", () => {
@@ -266,3 +278,21 @@ describe("assertV4Schema", () => {
).not.toThrow();
});
});
+
+// ─── Library type ───────────────────────────────────────────────────────────
+
+describe("Library type", () => {
+ it("accepts a hand-built library with only the pre-1.0 members", () => {
+ const mock: Library = {
+ components: {},
+ componentGroups: undefined,
+ root: undefined,
+ id: undefined,
+ __libraryId: "mock",
+ prompt: () => "",
+ toSpec: () => createLibrary({ components: [] }).toSpec(),
+ toJSONSchema: () => createLibrary({ components: [] }).toJSONSchema(),
+ };
+ expect(mock.functions).toBeUndefined();
+ });
+});
diff --git a/packages/lang-core/src/__tests__/message.test.ts b/packages/lang-core/src/__tests__/message.test.ts
new file mode 100644
index 000000000..71bea82b2
--- /dev/null
+++ b/packages/lang-core/src/__tests__/message.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from "vitest";
+import { buildMessage, parseMessage } from "../message";
+
+describe("message protocol", () => {
+ it("round trips content, context, attributes, and end", () => {
+ const input = {
+ content: 'root = Card([title])\ntitle = TextContent("a ]]>openui:end")',
+ context: [{ note: "rush" }],
+ attributes: { library: "@acme/[email protected]", note: "a b!" },
+ end: true,
+ };
+ const raw = buildMessage(input);
+ expect(raw.split("\n")[0]).toBe(
+ "]]>openui:content?" + new URLSearchParams(input.attributes).toString(),
+ );
+ expect(parseMessage(raw)).toEqual(input);
+ expect(parseMessage(`${raw}\n`).content).toBe(input.content);
+ });
+
+ it("keeps plain text byte for byte", () => {
+ const plain = "Hi\r\n```openui-lang\nroot = A()\n```\n";
+ expect(parseMessage(plain)).toMatchObject({ content: plain, context: null, end: false });
+ });
+
+ it("uses the last content and keeps non-JSON context as text", () => {
+ const raw =
+ ']]>openui:content\nold\n]]>openui:context\n{}\n]]>openui:content?v=2\nnew\r\n]]>openui:context\n{"a":';
+ expect(parseMessage(raw)).toEqual({
+ content: "new",
+ context: '{"a":',
+ attributes: { v: "2" },
+ end: false,
+ });
+ });
+
+ it("holds back a marker line cut mid-stream", () => {
+ const raw = "]]>openui:content\nroot = A()\n]]>open";
+ expect(parseMessage(raw, { streaming: true }).content).toBe("root = A()");
+ expect(parseMessage(raw).content).toBe("root = A()\n]]>open");
+ });
+
+ it("reads a content line that starts mid-line after a cut-off attempt", () => {
+ const header = "]]>openui:content?v=2";
+ const raw = `${header}\nroot = A("Broken${header}\nroot = B()\n]]>openui:end`;
+ expect(parseMessage(raw)).toMatchObject({
+ content: "root = B()",
+ attributes: { v: "2" },
+ end: true,
+ });
+ });
+
+ it("holds back a mid-line content line cut mid-stream", () => {
+ const raw = ']]>openui:content\nroot = A("Broken]]>openui:content?v=2\nroot = B()';
+ const header = raw.indexOf("]]>", 3);
+ // Chunks end inside the content line: `]]>`, `]]>openui:cont`, then the whole line.
+ for (const end of [header + 3, header + 14, raw.indexOf("\nroot = B")]) {
+ expect(parseMessage(raw.slice(0, end), { streaming: true }).content).toBe('root = A("Broken');
+ }
+ expect(parseMessage(raw, { streaming: true })).toMatchObject({
+ content: "root = B()",
+ attributes: { v: "2" },
+ });
+ });
+
+ it("ignores an end line before the winning content", () => {
+ const raw = `]]>openui:context\n{"$x":1}\n]]>openui:end\n]]>openui:content\nroot = A()`;
+ expect(parseMessage(raw)).toMatchObject({ content: "root = A()", context: null, end: false });
+ });
+});
diff --git a/packages/lang-core/src/extend.ts b/packages/lang-core/src/extend.ts
new file mode 100644
index 000000000..1a2c809fb
--- /dev/null
+++ b/packages/lang-core/src/extend.ts
@@ -0,0 +1,295 @@
+// library.extend: derives a library definition from a base plus additions, overrides and removals.
+import * as z from "zod/v4/core";
+import type {
+ AnyAction,
+ ComponentGroup,
+ DefinedComponent,
+ LibraryDefinition,
+ LibraryExtension,
+} from "./library";
+import { isReactiveSchema, markReactive } from "./reactive";
+import { copySchemaTags, getUnionOptions, getZodDef, unwrap } from "./signature";
+
+// ─── library.extend ─────────────────────────────────────────────────────────
+
+type Comp<C> = DefinedComponent<any, C>;
+
+const fail = (message: string): never => {
+ throw new Error(`[extend] ${message}`);
+};
+
+// add ProductCard into "Card", remove Frame -> the base parts with Card, every parent and the groups updated
+export function extendDefinition<C>(
+ base: LibraryDefinition<C, AnyAction>,
+ ext: LibraryExtension<C, AnyAction>,
+): LibraryDefinition<C, AnyAction> {
+ const changes = applyComponentVerbs(base, ext.components);
+ const slots = findContentSlots(changes);
+ const placements = placeInSlots(changes, slots);
+ return {
+ ...base,
+ id: undefined, // a derived library does not inherit the base's public id
+ components: rebuildComponents(changes, placements),
+ componentGroups: withoutRemoved(base.componentGroups, changes.removed),
+ functions: [...(base.functions ?? []), ...(ext.functions?.add ?? [])],
+ actions: [...(base.actions ?? []), ...(ext.actions?.add ?? [])],
+ };
+}
+
+interface ComponentChanges<C> {
+ /** The library's components after the verbs, in order. */
+ byName: Map<string, Comp<C>>;
+ /** Every schema that stands for a component, old, new or removed, mapped to its name. */
+ nameOf: Map<unknown, string>;
+ /** "ProductCard" -> ["Card"] */
+ slotRequests: Map<string, string[]>;
+ removed: Set<string>;
+}
+
+// add [Card], override [Image], remove ["Frame"] -> Stack, Text, Image (new), Card
+function applyComponentVerbs<C>(
+ base: LibraryDefinition<C, AnyAction>,
+ verbs: LibraryExtension<C, AnyAction>["components"] = {},
+): ComponentChanges<C> {
+ const byName = new Map(base.components.map((c) => [c.name, c]));
+ const nameOf = new Map<unknown, string>(base.components.map((c) => [c.props, c.name]));
+ const slotRequests = new Map<string, string[]>();
+ const touched = new Set<string>(); // added or overridden in this call
+ const put = (comp: Comp<C>) => {
+ byName.set(comp.name, comp);
+ nameOf.set(comp.props, comp.name);
+ touched.add(comp.name);
+ };
+
+ for (const entry of verbs.add ?? []) {
+ const { component, slots } = "slots" in entry ? entry : { component: entry, slots: undefined };
+ const name = component.name;
+ if (byName.has(name)) fail(`Component "${name}" already exists. Use override.`);
+ if (slots?.length === 0) fail(`"slots" for "${name}" is empty. Omit it to only list it.`);
+ put(component);
+ if (slots) slotRequests.set(name, slots);
+ }
+ const overridden = new Set<string>();
+ for (const comp of verbs.override ?? []) {
+ if (!byName.has(comp.name))
+ fail(`Cannot override "${comp.name}": not in the library. Use add.`);
+ if (overridden.has(comp.name)) fail(`Component "${comp.name}" is overridden twice.`);
+ overridden.add(comp.name);
+ put(comp);
+ }
+ const removed = new Set(verbs.remove);
+ for (const name of removed) {
+ if (touched.has(name))
+ fail(`Cannot remove "${name}": it is added or overridden in the same call.`);
+ if (!byName.delete(name)) fail(`Cannot remove "${name}": not in the library.`);
+ if (name === base.root) fail(`Cannot remove "${name}": it is the library root.`);
+ }
+ return { byName, nameOf, slotRequests, removed };
+}
+
+// A content slot holds a union of components, maybe optional or in an array:
+// children: z.array(z.union([Text.ref, Image.ref])) -> that union
+function slotUnion(schema: unknown, nameOf: Map<unknown, string>): unknown {
+ const inner = unwrap(schema);
+ const def = getZodDef(inner);
+ if (def?.type === "array") return slotUnion(def.element, nameOf);
+ return getUnionOptions(inner)?.some((o) => nameOf.has(o)) ? inner : undefined;
+}
+
+// Stack(children: (Text | Image)[]) -> ["Stack.children"]
+function findContentSlots<C>({ byName, nameOf }: ComponentChanges<C>): string[] {
+ const slots: string[] = [];
+ for (const comp of byName.values()) {
+ for (const [prop, schema] of Object.entries(comp.props.shape)) {
+ if (slotUnion(schema, nameOf)) slots.push(`${comp.name}.${prop}`);
+ }
+ }
+ return slots;
+}
+
+// ProductCard asks for ["Card"] -> "Card.children" -> ["ProductCard"]
+function placeInSlots<C>(changes: ComponentChanges<C>, slots: string[]): Map<string, string[]> {
+ const placements = new Map<string, string[]>();
+ for (const [name, requested] of changes.slotRequests) {
+ for (const slot of requested) {
+ const path = resolveSlot(slot, name, slots, changes.byName);
+ const placed = placements.get(path) ?? [];
+ // slots: ["Stack.children", "Stack"] name one path; Card joins it once
+ if (!placed.includes(name)) placements.set(path, [...placed, name]);
+ }
+ }
+ return placements;
+}
+
+// "Stack.children" stays; "Stack" -> "Stack.children" when Stack has exactly one content slot
+function resolveSlot(slot: string, name: string, slots: string[], byName: Map<string, unknown>) {
+ if (slots.includes(slot)) return slot;
+ const parent = slot.split(".")[0]!;
+ const candidates = slots.filter((s) => s.startsWith(`${parent}.`));
+ if (!slot.includes(".") && candidates.length === 1) return candidates[0]!;
+ const what = `Slot "${slot}" for "${name}"`;
+ if (!byName.has(parent)) fail(`${what}: "${parent}" is not in the library.`);
+ if (!candidates.length)
+ fail(
+ `${what}: "${parent}" has no content slot (a prop that is a union of components, or an optional or array of one).`,
+ );
+ return fail(`${what} must be one content slot. Candidates: ${candidates.join(", ")}.`);
+}
+
+/** The prop being rebuilt, its content-slot union if any, and the schemas slotted into it. */
+type Slot = { path: string; union: unknown; added: unknown[] };
+
+// Zod parents hold their children's schema objects, not their names, so every parent of an
+// overridden, removed or slotted-in component is cloned to point at the final schemas.
+// Schemas with nothing to change keep their identity. Built in two passes so cycles work:
+// every clone exists (with an empty shape) before any shape is filled, so Card(body: Stack)
+// slotted into Stack.children points at the new Stack, and the new Stack at the new Card.
+function rebuildComponents<C>(
+ changes: ComponentChanges<C>,
+ placements: Map<string, string[]>,
+): Comp<C>[] {
+ const { byName, nameOf, removed } = changes;
+ const final = new Map<string, Comp<C>>(byName);
+ const shapes = new Map<string, Record<string, unknown>>();
+ for (const name of findRebuilt(changes, placements)) {
+ const comp = byName.get(name)!;
+ const shape: Record<string, unknown> = {};
+ const props = cloneSchema(comp.props, {
+ get shape() {
+ return shape; // filled below, read by zod only after
+ },
+ }) as z.$ZodObject;
+ final.set(name, { ...comp, props, ref: props as unknown as Comp<C>["ref"] });
+ shapes.set(name, shape);
+ }
+ const finalProps = (name: string) => final.get(name)!.props;
+
+ const onlyType = (name: string | undefined, slot: Slot): never =>
+ fail(`Cannot remove "${name}": it is the only type allowed in ${slot.path}.`);
+
+ // z.array(z.union([Text, Frame])) with Frame removed -> z.array(z.union([Text]))
+ const rebind = (schema: unknown, slot: Slot, memo: Map<unknown, unknown>): unknown => {
+ const name = nameOf.get(schema);
+ if (name !== undefined) {
+ if (removed.has(name)) onlyType(name, slot);
+ return finalProps(name);
+ }
+ const def = getZodDef(schema);
+ if (!def || def.type === "lazy") return schema;
+ if (memo.has(schema)) return memo.get(schema);
+ memo.set(schema, schema); // cycle guard
+ const walk = (child: unknown) => rebind(child, slot, memo);
+
+ const patch: Record<string, unknown> = {};
+ const options = getUnionOptions(schema);
+ const holdsComponents = options?.some((o) => nameOf.has(o));
+ for (const [key, value] of Object.entries(def)) {
+ if (key === "checks" || (holdsComponents && key === "options")) continue;
+ const next = rebindField(key, value, walk);
+ if (!sameField(next, value)) patch[key] = next;
+ }
+ if (holdsComponents) {
+ // Text | Image | Frame, Frame removed and Card slotted in -> Text | Image | Card
+ const kept = options!.filter((o) => !removed.has(nameOf.get(o) ?? "")).map(walk);
+ const added = schema === slot.union ? slot.added.filter((a) => !kept.includes(a)) : [];
+ if (!kept.length && !added.length) onlyType(nameOf.get(options![0]), slot);
+ const next = [...kept, ...added];
+ if (!sameField(next, options)) patch.options = next;
+ }
+ const out = Object.keys(patch).length ? cloneSchema(schema, patch) : schema;
+ memo.set(schema, out);
+ return out;
+ };
+
+ for (const [name, shape] of shapes) {
+ for (const [prop, schema] of Object.entries(byName.get(name)!.props.shape)) {
+ const path = `${name}.${prop}`;
+ const added = (placements.get(path) ?? []).map(finalProps);
+ shape[prop] = rebind(schema, { path, union: slotUnion(schema, nameOf), added }, new Map());
+ }
+ }
+ return [...final.values()];
+}
+
+// Stack gets a slotted-in Card, Frame nests a removed or overridden Image, or a component nests
+// one of those (repeated until nothing changes, so cycles settle) -> those names
+function findRebuilt<C>(
+ { byName, nameOf, removed }: ComponentChanges<C>,
+ placements: Map<string, string[]>,
+): Set<string> {
+ const nested = new Map<string, Set<unknown>>();
+ for (const [name, comp] of byName) {
+ const found = new Set<unknown>();
+ for (const schema of Object.values(comp.props.shape)) nestedComponents(schema, nameOf, found);
+ nested.set(name, found);
+ }
+ const stale = (s: unknown) => {
+ const name = nameOf.get(s)!;
+ return removed.has(name) || byName.get(name)!.props !== s;
+ };
+ const slotted = new Set([...placements.keys()].map((path) => path.split(".")[0]!));
+ const rebuilt = new Set([...byName.keys()].filter((n) => slotted.has(n)));
+ for (const [name, found] of nested) if ([...found].some(stale)) rebuilt.add(name);
+ for (let grew = true; grew;) {
+ grew = false;
+ for (const [name, found] of nested) {
+ if (rebuilt.has(name) || ![...found].some((s) => rebuilt.has(nameOf.get(s)!))) continue;
+ rebuilt.add(name);
+ grew = true;
+ }
+ }
+ return rebuilt;
+}
+
+// Card(body: Stack, tags?: (Text | Image)[]) -> Stack, Text, Image; stops at each component
+function nestedComponents(
+ schema: unknown,
+ nameOf: Map<unknown, string>,
+ found: Set<unknown>,
+ seen = new Set<unknown>(),
+): void {
+ if (nameOf.has(schema)) return void found.add(schema);
+ const def = getZodDef(schema);
+ if (!def || def.type === "lazy" || seen.has(schema)) return;
+ seen.add(schema);
+ for (const [key, value] of Object.entries(def)) {
+ if (key === "checks") continue;
+ rebindField(key, value, (child) => nestedComponents(child, nameOf, found, seen));
+ }
+}
+
+// A def field holds a schema, an array of schemas, a shape of schemas, or plain data
+function rebindField(key: string, value: unknown, walk: (s: unknown) => unknown): unknown {
+ if (getZodDef(value)) return walk(value);
+ if (Array.isArray(value)) return value.map(walk);
+ if (key !== "shape") return value;
+ const shape: Record<string, unknown> = {};
+ for (const [prop, child] of Object.entries(value as object)) shape[prop] = walk(child);
+ return shape;
+}
+
+// Arrays and shapes are rebuilt on every walk, so compare their entries, not their identity
+function sameField(next: unknown, old: any): boolean {
+ if (next === old) return true;
+ if (getZodDef(next)) return false;
+ const entries = Object.entries(next as object);
+ return entries.length === Object.keys(old).length && entries.every(([i, c]) => c === old[i]);
+}
+
+// Copy a schema with a patched def, keeping its prompt tags and metadata.
+function cloneSchema(s: unknown, patch: Record<string, unknown>): unknown {
+ const schema = s as z.$ZodType;
+ const copy = z.clone(schema, z.util.mergeDefs(schema._zod.def, patch) as any);
+ copySchemaTags(schema, copy);
+ if (isReactiveSchema(schema)) markReactive(copy);
+ const meta = z.globalRegistry.get(schema);
+ if (meta) z.globalRegistry.add(copy, meta);
+ return copy;
+}
+
+// Media: ["Image", "Frame"] with Frame removed -> Media: ["Image"]; a group left empty is dropped
+function withoutRemoved(groups: ComponentGroup[] | undefined, removed: Set<string>) {
+ return groups
+ ?.map((g) => ({ ...g, components: g.components.filter((n) => !removed.has(n)) }))
+ .filter((g) => g.components.length);
+}
diff --git a/packages/lang-core/src/functions.ts b/packages/lang-core/src/functions.ts
new file mode 100644
index 000000000..d9ced8d6a
--- /dev/null
+++ b/packages/lang-core/src/functions.ts
@@ -0,0 +1,56 @@
+import { literal, object } from "zod/v4";
+import type * as z from "zod/v4/core";
+import type { ActionRef } from "./parser/builtins";
+import { actionRef, assertV4Schema } from "./signature";
+
+function assertParamsObject(params: z.$ZodType, name: string): void {
+ assertV4Schema(params, name);
+ if (params?._zod?.def.type !== "object") {
+ throw new Error(`[OpenUI] "${name}" params must be a z.object().`);
+ }
+}
+
+/** defineFunction({name: "Percent", params, fn}) -> called as @Percent(done, total) */
+export interface DefinedFunction<
+ T extends z.$ZodObject = z.$ZodObject,
+ R extends z.$ZodType | undefined = z.$ZodType | undefined,
+> {
+ name: string;
+ description: string;
+ /** z.object({part, total}) -> @Percent(part, total), in key order */
+ params: T;
+ /** z.string() -> the return type in the prompt signature, checked at runtime */
+ returns?: R;
+ /** `@Percent(3, 4)` -> fn({part: 3, total: 4}); bad args or result, or a throw -> null */
+ fn: (args: z.infer<T>) => R extends z.$ZodType ? z.infer<R> : unknown;
+}
+
+/** createLibrary({ functions: [defineFunction({name: "Percent", ...})] }) */
+export function defineFunction<
+ T extends z.$ZodObject,
+ R extends z.$ZodType | undefined = undefined,
+>(config: DefinedFunction<T, R>): DefinedFunction<T, R> {
+ assertParamsObject(config.params, config.name);
+ if (config.returns) assertV4Schema(config.returns, config.name);
+ return config;
+}
+
+/** A library action step, delivered to `onAction` as `{ type: name, params }` on click. */
+export interface DefinedAction<T extends z.$ZodObject = z.$ZodObject, N extends string = string> {
+ name: N;
+ description: string;
+ /** Parameters as a Zod object. Key order is the positional order in programs. */
+ params: T;
+ /** For a slot that takes only some actions: `z.union([copy.ref, steps.OpenUrl.ref])` */
+ ref: ActionRef;
+}
+
+/** Define a library action for `createLibrary({ actions })`. */
+export function defineAction<const N extends string, T extends z.$ZodObject>(
+ config: Omit<DefinedAction<T, N>, "ref">,
+): DefinedAction<T, N> {
+ assertParamsObject(config.params, config.name);
+ // copy.ref in JSON: {type: "CopyToClipboard", params: {text: string}}
+ const data = object({ type: literal(config.name), params: config.params });
+ return { ...config, ref: actionRef(config.name, data) };
+}
diff --git a/packages/lang-core/src/index.ts b/packages/lang-core/src/index.ts
index 8fc38cf4f..0c00458b2 100644
--- a/packages/lang-core/src/index.ts
+++ b/packages/lang-core/src/index.ts
@@ -1,34 +1,39 @@
// ── Library (framework-generic) ──
-export { buildSignature, createLibrary, defineComponent, tagSchemaId } from "./library";
+export {
+ buildSignature,
+ createLibrary,
+ defineAction,
+ defineComponent,
+ defineFunction,
+ tagSchemaId,
+} from "./library";
export type {
ComponentGroup,
ComponentRenderProps,
+ DefinedAction,
DefinedComponent,
+ DefinedFunction,
Library,
+ LibraryActionEvent,
LibraryDefinition,
+ LibraryExtension,
LibraryJSONSchema,
PromptOptions,
SubComponentOf,
ToolDescriptor,
} from "./library";
+// ── Message protocol ──
+export { buildMessage, parseMessage } from "./message";
+export type { BuildMessageInput, ParseMessageOptions, ParsedMessage } from "./message";
+
// ── Parser ──
export { createParser, createStreamingParser, parse } from "./parser";
export type { Parser, StreamParser } from "./parser";
-export { isASTNode, isRuntimeExpr, walkAST } from "./parser/ast";
-export type { ASTNode, CallNode, RuntimeExprNode, Statement } from "./parser/ast";
-// Low-level parsing pipeline (tokenize → split → parseExpression) for consumers
-// that walk partial/streaming openui-lang source without a full parser.
-export {
- ACTION_NAMES,
- ACTION_STEPS,
- BUILTINS,
- BUILTIN_NAMES,
- LAZY_BUILTINS,
- isBuiltin,
- toNumber,
-} from "./parser/builtins";
-export type { BuiltinDef } from "./parser/builtins";
+export { walkAST } from "./parser/ast";
+export type { ASTNode } from "./parser/ast";
+export { ACTION_STEPS, action, steps } from "./parser/builtins";
+export type { ActionRef } from "./parser/builtins";
export { enrichErrors } from "./parser/enrich-errors";
export { parseExpression } from "./parser/expressions";
export { tokenize } from "./parser/lexer";
@@ -46,7 +51,6 @@ export type {
export { jsonToOpenUI } from "./parser/serialize";
export type { SerializeOptions } from "./parser/serialize";
export { autoClose, split } from "./parser/statements";
-export type { Token } from "./parser/tokens";
export { BuiltinActionType } from "./parser/types";
export type {
ActionEvent,
@@ -67,7 +71,7 @@ export type {
export { isReactiveSchema, markReactive } from "./reactive";
// ── Runtime ──
-export { evaluateElementProps } from "./runtime/evaluate-tree";
+export { evaluateElementProps, evaluateRoot } from "./runtime/evaluate-tree";
export type { EvalContext } from "./runtime/evaluate-tree";
export { evaluate, isReactiveAssign, stripReactiveAssign } from "./runtime/evaluator";
export type { EvaluationContext, ReactiveAssign } from "./runtime/evaluator";
diff --git a/packages/lang-core/src/library.ts b/packages/lang-core/src/library.ts
index c49848a98..546b62233 100644
--- a/packages/lang-core/src/library.ts
+++ b/packages/lang-core/src/library.ts
@@ -1,40 +1,27 @@
import { object as zObject } from "zod/v4";
import * as z from "zod/v4/core";
+import { extendDefinition } from "./extend";
+import type { DefinedAction, DefinedFunction } from "./functions";
+import { ACTION_DEFS, isBuiltin, isReservedCall } from "./parser/builtins";
import type { ComponentPromptSpec, LibrarySpec, PromptSpec, ToolSpec } from "./parser/prompt";
import { generatePrompt } from "./parser/prompt";
-import type { LibraryJSONSchema } from "./parser/types";
-import { isReactiveSchema } from "./reactive";
-
+import type {
+ ActionEvent,
+ BuiltinActionType,
+ FunctionSchema,
+ JSONSchemaDef,
+ LibraryJSONSchema,
+} from "./parser/types";
+import { assertV4Schema, schemaSignature, tagSchemaId, type SchemaRegistry } from "./signature";
+
+export {
+ defineAction,
+ defineFunction,
+ type DefinedAction,
+ type DefinedFunction,
+} from "./functions";
export type { LibraryJSONSchema } from "./parser/types";
-
-// ─── Schema ID tagging ─────────────────────────────────────────────────────
-// WeakMap-based naming for schemas. defineComponent tags component schemas
-// automatically. tagSchemaId is exported for non-component schemas
-// (e.g. ActionExpression) that also need friendly names in prompts.
-
-const schemaIdTags = new WeakMap<object, string>();
-
-/**
- * Tag a schema with an ID for prompt signatures.
- * Use for non-component schemas that need friendly type names (e.g. ActionExpression).
- * This affects prompt output only, not JSON Schema $defs.
- */
-export function tagSchemaId(schema: object, id: string): void {
- schemaIdTags.set(schema, id);
-}
-
-// ─── Zod v3 detection ──────────────────────────────────────────────────────
-
-function assertV4Schema(schema: unknown, componentName: string): void {
- if (schema != null && typeof schema === "object" && "_def" in schema && !("_zod" in schema)) {
- throw new Error(
- `[OpenUI] Component "${componentName}" was defined with a Zod 3 schema. ` +
- `OpenUI requires Zod 4 schemas. ` +
- `If you're on [email protected]+, import from "zod/v4" instead of "zod". ` +
- `See: https://zod.dev/v4/versioning`,
- );
- }
-}
+export { buildSignature, tagSchemaId } from "./signature";
// ─── Sub-component type ──────────────────────────────────────────────────────
@@ -94,7 +81,7 @@ export function defineComponent<T extends z.$ZodObject, C>(config: {
component: C;
}): DefinedComponent<T, C> {
assertV4Schema(config.props, config.name);
- schemaIdTags.set(config.props, config.name);
+ tagSchemaId(config.props, config.name);
return {
...config,
ref: config.props as unknown as z.$ZodType<
@@ -131,188 +118,8 @@ export interface PromptOptions {
toolCalls?: boolean;
/** Enable $variables, @Set, @Reset, interactive filters. Default: true if toolCalls. */
bindings?: boolean;
-}
-
-// ─── Zod introspection ──────────────────────────────────────────────────────
-
-function getZodDef(schema: unknown): any {
- return (schema as any)?._zod?.def;
-}
-
-function getZodType(schema: unknown): string | undefined {
- return getZodDef(schema)?.type;
-}
-
-function isOptionalType(schema: unknown): boolean {
- const type = getZodType(schema);
- return type === "optional" || type === "default" || type === "nullable";
-}
-
-function unwrap(schema: unknown): unknown {
- let s = schema;
- let def = getZodDef(s);
- while (def?.type === "optional" || def?.type === "default" || def?.type === "nullable") {
- s = def.innerType;
- def = getZodDef(s);
- }
- return s;
-}
-
-function isArrayType(schema: unknown): boolean {
- const s = unwrap(schema);
- return getZodType(s) === "array";
-}
-
-function getArrayInnerType(schema: unknown): unknown | undefined {
- const s = unwrap(schema);
- const def = getZodDef(s);
- if (def?.type === "array") return def.element ?? def.innerType;
- return undefined;
-}
-
-function getEnumValues(schema: unknown): string[] | undefined {
- const s = unwrap(schema);
- const def = getZodDef(s);
- if (def?.type !== "enum") return undefined;
- if (Array.isArray(def.values)) return def.values;
- if (def.entries && typeof def.entries === "object") return Object.keys(def.entries);
- return undefined;
-}
-
-type SchemaRegistry = ReturnType<typeof z.registry<{ id: string }>>;
-
-function getSchemaId(schema: unknown, reg: SchemaRegistry): string | undefined {
- // Check per-library registry first
- try {
- const meta = reg.get(schema as z.$ZodType) as { id?: string } | undefined;
- if (meta?.id) return meta.id;
- } catch {
- // not registered — fall through
- }
- // Fallback: WeakMap tags from defineComponent / tagSchemaId
- if (typeof schema === "object" && schema !== null) {
- return schemaIdTags.get(schema);
- }
- return undefined;
-}
-
-function getUnionOptions(schema: unknown): unknown[] | undefined {
- const def = getZodDef(schema);
- if (def?.type === "union" && Array.isArray(def.options)) return def.options;
- return undefined;
-}
-
-function getObjectShape(schema: unknown): Record<string, unknown> | undefined {
- const def = getZodDef(schema);
- if (def?.type === "object" && def.shape && typeof def.shape === "object")
- return def.shape as Record<string, unknown>;
- return undefined;
-}
-
-/**
- * Resolve the type annotation for a schema field.
- * Returns a human-readable type string for the schema.
- * If the schema is marked reactive(), prefixes with "$binding<...>".
- */
-function resolveTypeAnnotation(schema: unknown, reg: SchemaRegistry): string | undefined {
- const isReactive = isReactiveSchema(schema);
- const inner = unwrap(schema);
-
- const baseType = resolveBaseType(inner, reg);
- if (!baseType) return undefined;
- return isReactive ? `$binding<${baseType}>` : baseType;
-}
-
-function resolveBaseType(inner: unknown, reg: SchemaRegistry): string | undefined {
- const directId = getSchemaId(inner, reg);
- if (directId) return directId;
-
- const unionOpts = getUnionOptions(inner);
- if (unionOpts) {
- const resolved = unionOpts.map((o) => resolveTypeAnnotation(o, reg));
- const names = resolved.filter(Boolean) as string[];
- if (names.length > 0) return names.join(" | ");
- }
-
- if (isArrayType(inner)) {
- const arrayInner = getArrayInnerType(inner);
- if (!arrayInner) return undefined;
- const innerType = resolveTypeAnnotation(arrayInner, reg);
- if (innerType) {
- const isUnion = getUnionOptions(unwrap(arrayInner)) !== undefined;
- return isUnion ? `(${innerType})[]` : `${innerType}[]`;
- }
- return undefined;
- }
-
- const zodType = getZodType(inner);
- if (zodType === "string") return "string";
- if (zodType === "number") return "number";
- if (zodType === "boolean") return "boolean";
- if (zodType === "any") return "any";
-
- if (zodType === "record") {
- const def = getZodDef(inner);
- const keyType = resolveTypeAnnotation(def?.keyType, reg) ?? "string";
- const valueType = resolveTypeAnnotation(def?.valueType, reg) ?? "any";
- return `Record<${keyType}, ${valueType}>`;
- }
-
- const enumVals = getEnumValues(inner);
- if (enumVals) return enumVals.map((v) => `"${v}"`).join(" | ");
-
- if (zodType === "literal") {
- const vals = getZodDef(inner)?.values;
- if (Array.isArray(vals) && vals.length === 1) {
- const v = vals[0];
- return typeof v === "string" ? `"${v}"` : String(v);
- }
- }
-
- const shape = getObjectShape(inner);
- if (shape) {
- const fields = Object.entries(shape).map(([name, fieldSchema]) => {
- const opt = isOptionalType(fieldSchema) ? "?" : "";
- const fieldType = resolveTypeAnnotation(fieldSchema as z.$ZodType, reg);
- return fieldType ? `${name}${opt}: ${fieldType}` : `${name}${opt}`;
- });
- return `{${fields.join(", ")}}`;
- }
-
- // Fallback for unrecognized Zod types (z.tuple, z.date, etc.)
- // "any" is safer than undefined — the LLM sees `param: any` instead of bare `param`
- return "any";
-}
-
-// ─── Field analysis & signature generation ──────────────────────────────────
-
-interface FieldInfo {
- name: string;
- isOptional: boolean;
- isArray: boolean;
- typeAnnotation?: string;
-}
-
-function analyzeFields(shape: Record<string, z.$ZodType>, reg: SchemaRegistry): FieldInfo[] {
- return Object.entries(shape).map(([name, schema]) => ({
- name,
- isOptional: isOptionalType(schema),
- isArray: isArrayType(schema),
- typeAnnotation: resolveTypeAnnotation(schema, reg),
- }));
-}
-
-export function buildSignature(componentName: string, fields: FieldInfo[]): string {
- const params = fields.map((f) => {
- if (f.typeAnnotation) {
- return f.isOptional ? `${f.name}?: ${f.typeAnnotation}` : `${f.name}: ${f.typeAnnotation}`;
- }
- if (f.isArray) {
- return f.isOptional ? `[${f.name}]?` : `[${f.name}]`;
- }
- return f.isOptional ? `${f.name}?` : f.name;
- });
- return `${componentName}(${params.join(", ")})`;
+ /** List the built-in functions (@Count, @Sum, ...). Default: true if toolCalls or bindings. */
+ builtinFunctions?: boolean;
}
function buildComponentSpecs(
@@ -321,9 +128,27 @@ function buildComponentSpecs(
): Record<string, ComponentPromptSpec> {
const specs: Record<string, ComponentPromptSpec> = {};
for (const [name, def] of Object.entries(components)) {
- const fields = analyzeFields(def.props.shape, reg);
specs[name] = {
- signature: buildSignature(name, fields),
+ signature: schemaSignature(name, def.props, undefined, reg),
+ description: def.description,
+ };
+ }
+ return specs;
+}
+
+type CallDefinition = DefinedFunction<any, any> | DefinedAction<any>;
+
+/** Function or action specs in the same shape as component specs. Undefined when there are none. */
+function buildCallSpecs(
+ calls: Record<string, CallDefinition>,
+ reg: SchemaRegistry,
+): Record<string, ComponentPromptSpec> | undefined {
+ const entries = Object.entries(calls);
+ if (!entries.length) return undefined;
+ const specs: Record<string, ComponentPromptSpec> = {};
+ for (const [name, def] of entries) {
+ specs[name] = {
+ signature: schemaSignature(name, def.params, "returns" in def ? def.returns : undefined, reg),
description: def.description,
};
}
@@ -332,9 +157,15 @@ function buildComponentSpecs(
// ─── Library ────────────────────────────────────────────────────────────────
-export interface Library<C = unknown> {
+export type AnyAction = DefinedAction<any, string>;
+
+export interface Library<C = unknown, A extends AnyAction = AnyAction> {
readonly components: Record<string, DefinedComponent<any, C>>;
readonly componentGroups: ComponentGroup[] | undefined;
+ /** Library functions keyed by name; optional so hand-built libraries without them still type-check. */
+ readonly functions?: Record<string, DefinedFunction<any, any>>;
+ /** Custom actions keyed by name; optional like `functions`. */
+ readonly actions?: { readonly [K in A as K["name"]]: K };
readonly root: string | undefined;
readonly id: string | undefined;
/** Instance id minted by `createLibrary()`. Distinct from the optional public `id`. */
@@ -343,11 +174,57 @@ export interface Library<C = unknown> {
prompt(options?: PromptOptions): string;
toSpec(): PromptSpec;
toJSONSchema(): LibraryJSONSchema;
+ /** Derive a new library (the base stays untouched); create it at module scope, parsers memoize by identity. */
+ extend?<A2 extends AnyAction = never>(
+ extension: LibraryExtension<C, A2>,
+ ): Required<Library<C, A | A2>>;
}
-export interface LibraryDefinition<C = unknown> {
+export interface LibraryExtension<C = unknown, A extends AnyAction = AnyAction> {
+ components?: {
+ /** New components; with `slots` ("Parent.prop", or "Parent" with one slot) they join those unions. */
+ add?: (DefinedComponent<any, C> | { component: DefinedComponent<any, C>; slots: string[] })[];
+ /** Replacements (schema and renderer) by name. Every parent points at the new one. */
+ override?: DefinedComponent<any, C>[];
+ /**
+ * Names to drop from the library, every parent union and componentGroups.
+ * Throws when a prop would be left with no type, even an optional one
+ * (`image?: Image` with Image removed): override that parent instead.
+ */
+ remove?: string[];
+ };
+ functions?: ExtensionVerbs<DefinedFunction<any, any>>;
+ actions?: ExtensionVerbs<A>;
+}
+
+interface ExtensionVerbs<T> {
+ /** Joins the library and is listed in the prompt. */
+ add?: T[];
+}
+
+type LibraryAction<L> = L extends { readonly actions?: infer R }
+ ? NonNullable<R>[keyof NonNullable<R>]
+ : never;
+type CustomActionEvent<A> =
+ A extends DefinedAction<infer T, infer N>
+ ? Omit<ActionEvent, "type" | "params"> & { type: N; params: z.infer<T> }
+ : never;
+
+/** The `onAction` event for library `L`: a union discriminated on `type` when it has custom actions. */
+export type LibraryActionEvent<L> = [LibraryAction<L>] extends [never]
+ ? ActionEvent
+ : string extends LibraryAction<L>["name"]
+ ? ActionEvent
+ : | (Omit<ActionEvent, "type"> & { type: `${BuiltinActionType}` | "custom" })
+ | CustomActionEvent<LibraryAction<L>>;
+
+export interface LibraryDefinition<C = unknown, A extends AnyAction = AnyAction> {
components: DefinedComponent<any, C>[];
componentGroups?: ComponentGroup[];
+ /** Library functions, called as `@Name(...)` in programs. */
+ functions?: DefinedFunction<any, any>[];
+ /** Custom actions, used as `@Name(...)` steps in action props. */
+ actions?: A[];
root?: string;
id?: string;
}
@@ -365,7 +242,10 @@ function createLibraryId(): string {
/**
* Create a component library from an array of defined components.
*/
-export function createLibrary<C = unknown>(input: LibraryDefinition<C>): Library<C> {
+// A defaults to never so a library without actions extends to a real union.
+export function createLibrary<C = unknown, A extends AnyAction = never>(
+ input: LibraryDefinition<C, A>,
+): Required<Library<C, A>> {
const componentsRecord: Record<string, DefinedComponent<any, C>> = {};
const reg = z.registry<{ id: string }>();
const __libraryId = createLibraryId();
@@ -375,6 +255,11 @@ export function createLibrary<C = unknown>(input: LibraryDefinition<C>): Library
componentsRecord[comp.name] = comp;
}
+ // Action slots are $refs like component slots; a component of the same name wins
+ for (const [id, schema] of Object.entries(ACTION_DEFS)) {
+ if (!componentsRecord[id]) reg.add(schema, { id });
+ }
+
if (input.root && !componentsRecord[input.root]) {
const available = Object.keys(componentsRecord).join(", ");
throw new Error(
@@ -382,9 +267,37 @@ export function createLibrary<C = unknown>(input: LibraryDefinition<C>): Library
);
}
- const library: Library<C> = {
+ const names = new Set(Object.keys(componentsRecord));
+ const claim = (kind: string, name: string) => {
+ if (isBuiltin(name) || isReservedCall(name) || names.has(name)) {
+ throw new Error(
+ `[createLibrary] ${kind} "${name}" collides with a built-in, component, function, or action of the same name. Rename it.`,
+ );
+ }
+ names.add(name);
+ };
+ const functionsRecord: Record<string, DefinedFunction<any, any>> = {};
+ for (const fn of input.functions ?? []) {
+ claim("Function", fn.name);
+ functionsRecord[fn.name] = fn;
+ }
+ const actionsRecord: Record<string, DefinedAction<any>> = {};
+ for (const action of input.actions ?? []) {
+ claim("Action", action.name);
+ actionsRecord[action.name] = action;
+ reg.add(action.ref, { id: action.name });
+ }
+ const callSpecs = () => {
+ const functions = buildCallSpecs(functionsRecord, reg);
+ const actions = buildCallSpecs(actionsRecord, reg);
+ return { ...(functions ? { functions } : {}), ...(actions ? { actions } : {}) };
+ };
+
+ const library: Required<Library<C, A>> = {
components: componentsRecord,
componentGroups: input.componentGroups,
+ functions: functionsRecord,
+ actions: actionsRecord as Required<Library<C, A>>["actions"],
root: input.root,
id: input.id,
__libraryId,
@@ -394,6 +307,7 @@ export function createLibrary<C = unknown>(input: LibraryDefinition<C>): Library
root: input.root,
components: buildComponentSpecs(componentsRecord, reg),
componentGroups: input.componentGroups,
+ ...callSpecs(),
...options,
};
return generatePrompt(spec);
@@ -404,6 +318,7 @@ export function createLibrary<C = unknown>(input: LibraryDefinition<C>): Library
root: input.root,
components: buildComponentSpecs(componentsRecord, reg),
componentGroups: input.componentGroups,
+ ...callSpecs(),
schema: buildJSONSchema(),
...(input.id !== undefined ? { id: input.id } : {}),
};
@@ -412,8 +327,36 @@ export function createLibrary<C = unknown>(input: LibraryDefinition<C>): Library
toJSONSchema(): LibraryJSONSchema {
return buildJSONSchema();
},
+
+ // lib.extend({ components: { add: [ProductCard] }, functions: { add: [percent] } })
+ extend<A2 extends AnyAction = never>(extension: LibraryExtension<C, A2>) {
+ return createLibrary(extendDefinition<C>(input, extension)) as Required<Library<C, A | A2>>;
+ },
};
+ // Component refs resolve against the library's top-level $defs
+ function toCallJSONSchema(schema: z.$ZodType): Record<string, unknown> {
+ const { $schema: _, $defs: __, ...rest } = z.toJSONSchema(schema, { metadata: reg });
+ return rest;
+ }
+
+ function callSchemas(
+ calls: Record<string, CallDefinition>,
+ ): Record<string, FunctionSchema> | undefined {
+ const entries = Object.entries(calls);
+ if (!entries.length) return undefined;
+ return Object.fromEntries(
+ entries.map(([name, def]) => [
+ name,
+ {
+ description: def.description,
+ params: toCallJSONSchema(def.params) as JSONSchemaDef,
+ ...("returns" in def && def.returns ? { returns: toCallJSONSchema(def.returns) } : {}),
+ },
+ ]),
+ );
+ }
+
function buildJSONSchema(): LibraryJSONSchema {
const combinedSchema = zObject(
Object.fromEntries(Object.entries(componentsRecord).map(([k, v]) => [k, v.props])) as any,
@@ -426,6 +369,10 @@ export function createLibrary<C = unknown>(input: LibraryDefinition<C>): Library
const def = schema.$defs?.[name];
if (def && comp.description) def.description = comp.description;
}
+ const functions = callSchemas(functionsRecord);
+ if (functions) schema.functions = functions;
+ const actions = callSchemas(actionsRecord);
+ if (actions) schema.actions = actions;
return schema;
}
diff --git a/packages/lang-core/src/message.ts b/packages/lang-core/src/message.ts
new file mode 100644
index 000000000..9cd26b2eb
--- /dev/null
+++ b/packages/lang-core/src/message.ts
@@ -0,0 +1,125 @@
+// The OpenUI message protocol (spec section 7): marker lines around a stored response,
+// e.g. `]]>openui:content?library=x`, `]]>openui:context`, `]]>openui:end`.
+
+const PREFIX = "]]>openui:";
+const MARKER = /^\]\]>openui:([a-z]+)(?:\?(.*))?$/;
+// A regenerated response writes its content line right after the cut-off text, with no newline
+// before it. Start it on its own line so the last content wins.
+const RETRY = /([^\n])(?=\]\]>openui:content(?:\?|\r?\n|$))/g;
+// While streaming, hold back a mid-line `]]>openui:con` that may become a content line.
+const RETRY_CUT = /[^\n](\]\]>[a-z:]*)$/;
+
+export interface ParsedMessage {
+ /** Body of the last `content` section, or the whole text when there is none. */
+ content: string;
+ /** Body of the `context` section: parsed JSON, else raw text. null when absent. */
+ context: unknown;
+ /** String attributes of the winning `content` marker. */
+ attributes: Record<string, string>;
+ /** An `end` line follows the winning `content` section. */
+ end: boolean;
+}
+
+export interface ParseMessageOptions {
+ /** Hold back a last line that may be a marker cut mid-stream. */
+ streaming?: boolean;
+}
+
+export interface BuildMessageInput {
+ content: string;
+ /** Written as is when a string, else as JSON. Omitted when null or undefined. */
+ context?: unknown;
+ attributes?: Record<string, string>;
+ end?: boolean;
+}
+
+interface Section {
+ kind: string | null;
+ attributes: Record<string, string>;
+ lines: string[];
+}
+
+// Same bytes as URLSearchParams, which React Native only partly implements.
+const encode = (s: string) =>
+ encodeURIComponent(s)
+ .replace(/[!'()~]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)
+ .replace(/%20/g, "+");
+
+const decode = (s: string) => {
+ try {
+ return decodeURIComponent(s.replace(/\+/g, " "));
+ } catch {
+ return s;
+ }
+};
+
+function readAttributes(query = ""): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const pair of query.split("&")) {
+ const eq = pair.indexOf("=");
+ const key = decode(eq === -1 ? pair : pair.slice(0, eq));
+ if (key) out[key] = eq === -1 ? "" : decode(pair.slice(eq + 1));
+ }
+ return out;
+}
+
+/** Splits a stored message into its content, context, attributes and end flag. */
+export function parseMessage(raw: string, { streaming }: ParseMessageOptions = {}): ParsedMessage {
+ let text = raw.replace(RETRY, "$1\n");
+ const cut = streaming ? RETRY_CUT.exec(text) : null;
+ if (cut && `${PREFIX}content`.startsWith(cut[1])) text = text.slice(0, cut.index + 1);
+ const lines = text.split("\n");
+ const last = lines[lines.length - 1];
+ const held = streaming && last !== "" && (last.startsWith(PREFIX) || PREFIX.startsWith(last));
+ if (held) lines.pop();
+
+ const sections: Section[] = [{ kind: null, attributes: {}, lines: [] }];
+ // The newline (and its `\r`) before a marker is not part of the body.
+ const close = () => {
+ const body = sections[sections.length - 1].lines;
+ if (body.length) body[body.length - 1] = body[body.length - 1].replace(/\r$/, "");
+ };
+ let endAt = -1;
+ for (const [i, line] of lines.entries()) {
+ const match = MARKER.exec(line.replace(/\r$/, ""));
+ if (!match) {
+ sections[sections.length - 1].lines.push(line);
+ continue;
+ }
+ close();
+ if (match[1] === "end") {
+ endAt = sections.length - 1;
+ if (i === lines.length - 2 && lines[i + 1] === "") break;
+ continue;
+ }
+ sections.push({ kind: match[1], attributes: readAttributes(match[2]), lines: [] });
+ }
+ if (held) close();
+
+ // Last content wins; text before the first marker is content only when there is none.
+ const kinds = sections.map((s) => s.kind);
+ const win = Math.max(0, kinds.lastIndexOf("content"));
+ const ctx = kinds.lastIndexOf("context");
+ let context: unknown = ctx > win ? sections[ctx].lines.join("\n") : null;
+ try {
+ if (typeof context === "string") context = JSON.parse(context);
+ } catch {
+ // Not JSON (yet): keep the raw text.
+ }
+ const winner = sections[win];
+ // Like context, an `end` before the winning content belongs to an earlier attempt.
+ const end = endAt >= win;
+ return { content: winner.lines.join("\n"), context, attributes: winner.attributes, end };
+}
+
+/** Writes a stored message with its marker lines. */
+export function buildMessage({ content, context, attributes, end }: BuildMessageInput): string {
+ const query = Object.entries(attributes ?? {})
+ .map(([key, value]) => `${encode(key)}=${encode(value)}`)
+ .join("&");
+ let out = `${PREFIX}content${query ? `?${query}` : ""}\n${content}`;
+ if (context != null) {
+ out += `\n${PREFIX}context\n${typeof context === "string" ? context : JSON.stringify(context)}`;
+ }
+ return end ? `${out}\n${PREFIX}end` : out;
+}
diff --git a/packages/lang-core/src/parser/__tests__/entry.test.ts b/packages/lang-core/src/parser/__tests__/entry.test.ts
new file mode 100644
index 000000000..573553954
--- /dev/null
+++ b/packages/lang-core/src/parser/__tests__/entry.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vitest";
+import { evaluateRoot } from "../../runtime/evaluate-tree";
+import { parse } from "../parser";
+import type { ParamMap } from "../types";
+
+const schema: ParamMap = new Map([
+ ["Card", { params: [{ name: "children", required: true }] }],
+ ["Title", { params: [{ name: "text", required: true }] }],
+]);
+
+const codes = (result: ReturnType<typeof parse>) => result.meta.errors.map((e) => e.code);
+
+describe("entry rule", () => {
+ it("falls back to a first root-component statement, after $state, with a no-root warning", () => {
+ const result = parse('$t = 1\npage = Card([t])\nt = Title("x")', schema, "Card");
+ expect(result.root).toMatchObject({ typeName: "Card", statementId: "page" });
+ expect(result.meta.errors).toMatchObject([{ code: "no-root", severity: "warning" }]);
+ });
+
+ it("falls back to a later root-component statement when children come first", () => {
+ const result = parse('t = Title("x")\npage = Card([t])', schema, "Card");
+ expect(result.root).toMatchObject({ typeName: "Card", statementId: "page" });
+ expect(result.meta.orphaned).toEqual([]);
+ expect(result.meta.errors).toMatchObject([{ code: "no-root", severity: "warning" }]);
+ });
+
+ it("renders nothing and reports no orphans when there is no entry", () => {
+ const result = parse('t = Title("x")', schema, "Card");
+ expect(result.root).toBeNull();
+ expect(result.meta.orphaned).toEqual([]);
+ expect(result.meta.errors).toEqual([expect.objectContaining({ code: "no-root" })]);
+ expect(result.meta.errors[0]?.severity).toBeUndefined();
+ expect(codes(parse("page = Card([])", schema))).toEqual(["no-root"]);
+ });
+
+ it("evaluates a ternary entry at runtime", () => {
+ const result = parse('$t = true\nroot = $t ? a : b\na = Title("A")\nb = Title("B")', schema);
+ expect(result.meta.errors).toEqual([]);
+ const ctx = { getState: () => false, resolveRef: () => undefined };
+ const picked = evaluateRoot(result, { ctx, library: { components: {} } as never, store: null });
+ expect(picked).toMatchObject({ typeName: "Title", props: { text: "B" } });
+ });
+
+ it("reports an unknown @Name call as unknown-function and keeps the statement", () => {
+ const result = parse('root = Title("p" + @Foo(1))', schema);
+ expect(codes(result)).toEqual(["unknown-function"]);
+ expect(result.root?.props.text).toMatchObject({ k: "BinOp", right: { k: "Null" } });
+ });
+});
diff --git a/packages/lang-core/src/parser/__tests__/parser.test.ts b/packages/lang-core/src/parser/__tests__/parser.test.ts
index 71a88ec90..23d9b6921 100644
--- a/packages/lang-core/src/parser/__tests__/parser.test.ts
+++ b/packages/lang-core/src/parser/__tests__/parser.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import type { ParamMap } from "../parser";
import { createStreamParser, parse } from "../parser";
+import type { ParamMap } from "../types";
// ── Test schema ──────────────────────────────────────────────────────────────
diff --git a/packages/lang-core/src/parser/__tests__/prompt.test.ts b/packages/lang-core/src/parser/__tests__/prompt.test.ts
index 24c1ca94e..5aaf00576 100644
--- a/packages/lang-core/src/parser/__tests__/prompt.test.ts
+++ b/packages/lang-core/src/parser/__tests__/prompt.test.ts
@@ -46,7 +46,7 @@ const library = {
components: ["TextContent"],
},
],
-} as LibrarySpec;
+} as unknown as LibrarySpec; // a spec without components, as Cloud stores it
describe("generateSystemPrompt — self-hosted", () => {
const spec: LibrarySpec = {
@@ -62,6 +62,13 @@ describe("generateSystemPrompt — self-hosted", () => {
expect(prompt).toContain("Card(children: Component[])");
expect(prompt.startsWith(CONFIG_MARKER)).toBe(false);
});
+
+ it("without tools, names no Query and no library component outside the spec", () => {
+ const prompt = generateSystemPrompt({ library: spec, promptOptions: { bindings: true } });
+ expect(prompt).toContain("IMPORTANT @Each rule");
+ expect(prompt).not.toContain("Query");
+ expect(prompt).not.toContain("Col(");
+ });
});
describe("generateSystemPrompt({ cloud: true }) — sentinel", () => {
diff --git a/packages/lang-core/src/parser/__tests__/serialize.test.ts b/packages/lang-core/src/parser/__tests__/serialize.test.ts
index 6652292d6..87645de24 100644
--- a/packages/lang-core/src/parser/__tests__/serialize.test.ts
+++ b/packages/lang-core/src/parser/__tests__/serialize.test.ts
@@ -1,7 +1,10 @@
import { describe, expect, it } from "vitest";
+import { z } from "zod/v4";
import type { Library } from "../../library";
+import { createLibrary, defineAction, defineComponent, defineFunction } from "../../library";
+import { action } from "../builtins";
import { mergeStatements } from "../merge";
-import { parse } from "../parser";
+import { createParser, parse } from "../parser";
import { jsonToOpenUI } from "../serialize";
import type { ElementNode, ParamMap } from "../types";
@@ -106,6 +109,35 @@ function isElNode(v: unknown): v is ElementNode {
// ── Basic serialization ─────────────────────────────────────────────────────
describe("jsonToOpenUI", () => {
+ it("writes @ before library functions and actions", () => {
+ const Btn = defineComponent({
+ name: "Btn",
+ description: "",
+ props: z.object({ label: z.any(), action: action().optional() }),
+ component: null,
+ });
+ const upper = defineFunction({
+ name: "Upper",
+ description: "",
+ params: z.object({ s: z.string() }),
+ fn: ({ s }) => s.toUpperCase(),
+ });
+ const copy = defineAction({
+ name: "Copy",
+ description: "",
+ params: z.object({ t: z.string() }),
+ });
+ const lib = createLibrary({
+ root: "Btn",
+ components: [Btn],
+ functions: [upper],
+ actions: [copy],
+ });
+ const src = 'root = Btn(@Upper($name), @Copy("x"))';
+ const { root } = createParser(lib.toJSONSchema(), "Btn").parse(src);
+ expect(jsonToOpenUI(root!, lib)).toBe(src);
+ });
+
describe("single component", () => {
it("serializes a simple component", () => {
const node: ElementNode = {
diff --git a/packages/lang-core/src/parser/ast.ts b/packages/lang-core/src/parser/ast.ts
index d39a567a7..b614d0927 100644
--- a/packages/lang-core/src/parser/ast.ts
+++ b/packages/lang-core/src/parser/ast.ts
@@ -28,7 +28,14 @@
* - `Assign` — state assignment: `$count = $count + 1`
*/
export type ASTNode =
- | { k: "Comp"; name: string; args: ASTNode[]; mappedProps?: Record<string, ASTNode> }
+ | {
+ k: "Comp";
+ name: string;
+ args: ASTNode[];
+ mappedProps?: Record<string, ASTNode>;
+ /** Set on an `@Name(...)` call whose name is not a built-in or action step. */
+ fn?: true;
+ }
| { k: "Str"; v: string }
| { k: "Num"; v: number }
| { k: "Bool"; v: boolean }
@@ -165,3 +172,51 @@ export type Statement =
| { kind: "state"; id: string; init: ASTNode }
| { kind: "query"; id: string; call: CallNode; expr: ASTNode; deps?: string[] }
| { kind: "mutation"; id: string; call: CallNode; expr: ASTNode };
+
+// {n: [1]} -> {k:"Obj", entries: [["n", {k:"Arr", els:[Num 1]}]]}
+export function toLiteralAST(value: unknown): ASTNode {
+ if (value === null || value === undefined) return { k: "Null" };
+ if (typeof value === "string") return { k: "Str", v: value };
+ if (typeof value === "number") return { k: "Num", v: value };
+ if (typeof value === "boolean") return { k: "Bool", v: value };
+ if (Array.isArray(value)) return { k: "Arr", els: value.map(toLiteralAST) };
+ if (typeof value === "object") {
+ return {
+ k: "Obj",
+ entries: Object.entries(value).map(([k, v]) => [k, toLiteralAST(v)] as [string, ASTNode]),
+ };
+ }
+ return { k: "Null" };
+}
+
+// {k:"Arr", els:[Num 1]} -> {v: [1]}; a Ref or call -> undefined
+export function literalValue(node: ASTNode): { v: unknown } | undefined {
+ switch (node.k) {
+ case "Str":
+ case "Num":
+ case "Bool":
+ return { v: node.v };
+ case "Null":
+ return { v: null };
+ case "Arr": {
+ const v: unknown[] = [];
+ for (const e of node.els) {
+ const lit = literalValue(e);
+ if (!lit) return undefined;
+ v.push(lit.v);
+ }
+ return { v };
+ }
+ case "Obj": {
+ const v: Record<string, unknown> = {};
+ for (const [k, e] of node.entries) {
+ const lit = literalValue(e);
+ if (!lit) return undefined;
+ v[k] = lit.v;
+ }
+ return { v };
+ }
+ default:
+ return undefined;
+ }
+}
diff --git a/packages/lang-core/src/parser/builtins.ts b/packages/lang-core/src/parser/builtins.ts
index f132d802f..0b2c97a05 100644
--- a/packages/lang-core/src/parser/builtins.ts
+++ b/packages/lang-core/src/parser/builtins.ts
@@ -1,20 +1,14 @@
-/**
- * Shared parser/runtime registry hub for:
- * - Runtime data builtins (evaluator.ts imports `.fn`)
- * - Prompt builtin docs (prompt.ts imports `.signature` + `.description`)
- * - Parser/runtime call classification (`isBuiltin`, action names, reserved calls)
- */
+/** Built-in functions and action steps (defined like library ones), and reserved calls. */
-export interface BuiltinDef {
- /** PascalCase name matching the openui-lang syntax: Count, Sum, etc. */
- name: string;
- /** Signature for prompt docs: "@Count(array) → number" */
- signature: string;
- /** One-line description for prompt docs */
- description: string;
- /** Runtime implementation */
- fn: (...args: unknown[]) => unknown;
-}
+import { z } from "zod/v4";
+import {
+ defineAction,
+ defineFunction,
+ type DefinedAction,
+ type DefinedFunction,
+} from "../functions";
+import { actionRef, tagSchemaId } from "../signature";
+import type { ActionStep, CallDef, ParamMap } from "./types";
/** Resolve a field path on an object. Supports dot-paths: "state.name" → obj.state.name */
function resolveField(obj: any, path: string): unknown {
@@ -38,68 +32,88 @@ function toNumber(val: unknown): number {
return 0;
}
-export const BUILTINS: Record<string, BuiltinDef> = {
- Count: {
+const sumOf = (arr: unknown[]) => arr.reduce((a: number, b: unknown) => a + toNumber(b), 0);
+const array = () => z.array(z.any());
+const numbers = () => z.object({ numbers: z.array(z.number()) });
+const number = () => z.object({ number: z.number() });
+
+/** A built-in function. A lazy one (@Each) has no `fn`: the evaluator runs it on raw args. */
+export type BuiltinFunction = Omit<DefinedFunction<any, any>, "fn"> & {
+ fn?: (args: any) => unknown;
+ lazy?: true;
+};
+
+const builtins: BuiltinFunction[] = [
+ defineFunction({
name: "Count",
- signature: "Count(array) → number",
description: "Returns array length",
- fn: (arr) => (Array.isArray(arr) ? arr.length : 0),
- },
- First: {
+ params: z.object({ array: array() }),
+ returns: z.number(),
+ fn: ({ array }) => (Array.isArray(array) ? array.length : 0),
+ }),
+ defineFunction({
name: "First",
- signature: "First(array) → element",
description: "Returns first element of array",
- fn: (arr) => (Array.isArray(arr) ? (arr[0] ?? null) : null),
- },
- Last: {
+ params: z.object({ array: array() }),
+ returns: z.any(),
+ fn: ({ array }) => (Array.isArray(array) ? (array[0] ?? null) : null),
+ }),
+ defineFunction({
name: "Last",
- signature: "Last(array) → element",
description: "Returns last element of array",
- fn: (arr) => (Array.isArray(arr) ? (arr[arr.length - 1] ?? null) : null),
- },
- Sum: {
+ params: z.object({ array: array() }),
+ returns: z.any(),
+ fn: ({ array }) => (Array.isArray(array) ? (array[array.length - 1] ?? null) : null),
+ }),
+ defineFunction({
name: "Sum",
- signature: "Sum(numbers[]) → number",
description: "Sum of numeric array",
- fn: (arr) =>
- Array.isArray(arr) ? arr.reduce((a: number, b: unknown) => a + toNumber(b), 0) : 0,
- },
- Avg: {
+ params: numbers(),
+ returns: z.number(),
+ fn: ({ numbers }) => (Array.isArray(numbers) ? sumOf(numbers) : 0),
+ }),
+ defineFunction({
name: "Avg",
- signature: "Avg(numbers[]) → number",
description: "Average of numeric array",
- fn: (arr) =>
- Array.isArray(arr) && arr.length
- ? (arr.reduce((a: number, b: unknown) => a + toNumber(b), 0) as number) / arr.length
- : 0,
- },
- Min: {
+ params: numbers(),
+ returns: z.number(),
+ fn: ({ numbers }) =>
+ Array.isArray(numbers) && numbers.length ? sumOf(numbers) / numbers.length : 0,
+ }),
+ defineFunction({
name: "Min",
- signature: "Min(numbers[]) → number",
description: "Minimum value in array",
- fn: (arr) =>
- Array.isArray(arr) && arr.length
- ? arr.reduce((acc: number, b: unknown) => Math.min(acc, toNumber(b)), toNumber(arr[0]))
+ params: numbers(),
+ returns: z.number(),
+ fn: ({ numbers }) =>
+ Array.isArray(numbers) && numbers.length
+ ? numbers.reduce((acc, b) => Math.min(acc, toNumber(b)), toNumber(numbers[0]))
: 0,
- },
- Max: {
+ }),
+ defineFunction({
name: "Max",
- signature: "Max(numbers[]) → number",
description: "Maximum value in array",
- fn: (arr) =>
- Array.isArray(arr) && arr.length
- ? arr.reduce((acc: number, b: unknown) => Math.max(acc, toNumber(b)), toNumber(arr[0]))
+ params: numbers(),
+ returns: z.number(),
+ fn: ({ numbers }) =>
+ Array.isArray(numbers) && numbers.length
+ ? numbers.reduce((acc, b) => Math.max(acc, toNumber(b)), toNumber(numbers[0]))
: 0,
- },
- Sort: {
+ }),
+ defineFunction({
name: "Sort",
- signature: "Sort(array, field, direction?) → sorted array",
description: 'Sort array by field. Direction: "asc" (default) or "desc"',
- fn: (arr, field, dir) => {
- if (!Array.isArray(arr)) return arr;
+ params: z.object({
+ array: array(),
+ field: z.string(),
+ direction: z.enum(["asc", "desc"]).optional(),
+ }),
+ returns: array(),
+ fn: ({ array, field, direction }) => {
+ if (!Array.isArray(array)) return array;
const f = String(field ?? "");
- const desc = String(dir ?? "asc") === "desc";
- return [...arr].sort((a: any, b: any) => {
+ const desc = String(direction ?? "asc") === "desc";
+ return [...array].sort((a: any, b: any) => {
const av = f ? resolveField(a, f) : a;
const bv = f ? resolveField(b, f) : b;
const aIsNumeric =
@@ -114,17 +128,22 @@ export const BUILTINS: Record<string, BuiltinDef> = {
return desc ? -cmp : cmp;
});
},
- },
- Filter: {
+ }),
+ defineFunction({
name: "Filter",
- signature:
- 'Filter(array, field, operator: "==" | "!=" | ">" | "<" | ">=" | "<=" | "contains", value) → filtered array',
description: "Filter array by field value",
- fn: (arr, field, op, value) => {
- if (!Array.isArray(arr)) return [];
+ params: z.object({
+ array: array(),
+ field: z.string(),
+ operator: z.enum(["==", "!=", ">", "<", ">=", "<=", "contains"]),
+ value: z.any(),
+ }),
+ returns: array(),
+ fn: ({ array, field, operator, value }) => {
+ if (!Array.isArray(array)) return [];
const f = String(field ?? "");
- const o = String(op ?? "==");
- return arr.filter((item: any) => {
+ const o = String(operator ?? "==");
+ return array.filter((item: any) => {
const v = f ? resolveField(item, f) : item;
switch (o) {
case "==":
@@ -146,51 +165,53 @@ export const BUILTINS: Record<string, BuiltinDef> = {
}
});
},
- },
- Round: {
+ }),
+ defineFunction({
name: "Round",
- signature: "Round(number, decimals?) → number",
description: "Round to N decimal places (default 0)",
- fn: (n, decimals) => {
- const num = toNumber(n);
+ params: z.object({ number: z.number(), decimals: z.number().optional() }),
+ returns: z.number(),
+ fn: ({ number, decimals }) => {
+ const num = toNumber(number);
const d = decimals != null ? toNumber(decimals) : 0;
const factor = Math.pow(10, d);
return Math.round(num * factor) / factor;
},
- },
- Abs: {
+ }),
+ defineFunction({
name: "Abs",
- signature: "Abs(number) → number",
description: "Absolute value",
- fn: (n) => Math.abs(toNumber(n)),
- },
- Floor: {
+ params: number(),
+ returns: z.number(),
+ fn: ({ number }) => Math.abs(toNumber(number)),
+ }),
+ defineFunction({
name: "Floor",
- signature: "Floor(number) → number",
description: "Round down to nearest integer",
- fn: (n) => Math.floor(toNumber(n)),
- },
- Ceil: {
+ params: number(),
+ returns: z.number(),
+ fn: ({ number }) => Math.floor(toNumber(number)),
+ }),
+ defineFunction({
name: "Ceil",
- signature: "Ceil(number) → number",
description: "Round up to nearest integer",
- fn: (n) => Math.ceil(toNumber(n)),
- },
-};
-
-/**
- * Lazy builtins — these receive AST nodes (not evaluated values) and
- * control their own evaluation. Handled specially in evaluator.ts.
- */
-export const LAZY_BUILTINS: Set<string> = new Set(["Each"]);
-
-export const LAZY_BUILTIN_DEFS: Record<string, { signature: string; description: string }> = {
- Each: {
- signature: "Each(array, varName, template)",
+ params: number(),
+ returns: z.number(),
+ fn: ({ number }) => Math.ceil(toNumber(number)),
+ }),
+ {
+ name: "Each",
description:
"Evaluate template for each element. varName is the loop variable — use it ONLY inside the template expression (inline). Do NOT create a separate statement for the template.",
+ params: z.object({ array: array(), varName: z.string(), template: z.any() }),
+ lazy: true,
},
-};
+];
+
+/** All built-in functions by name, in prompt order. */
+export const BUILTINS: Record<string, BuiltinFunction> = Object.fromEntries(
+ builtins.map((b) => [b.name, b]),
+);
/** Maps parser-level action step names → runtime step type values. Single source of truth. */
export const ACTION_STEPS = {
@@ -201,19 +222,146 @@ export const ACTION_STEPS = {
Reset: "reset",
} as const;
-/** All action expression names (steps + the Action container) */
-export const ACTION_NAMES: Set<string> = new Set(["Action", ...Object.keys(ACTION_STEPS)]);
+/** A schema that only names its type in prompt signatures, e.g. `$variable`. */
+function named(id: string) {
+ const schema = z.any();
+ tagSchemaId(schema, id);
+ return schema;
+}
+
+const openUrlData = () => z.object({ type: z.literal("open_url"), url: z.string() });
+const toAssistantData = () =>
+ z.object({ type: z.literal("continue_conversation"), context: z.string().optional() });
-/** Set of builtin names for fast lookup (includes action expressions) */
-export const BUILTIN_NAMES: Set<string> = new Set([
- ...Object.keys(BUILTINS),
- ...LAZY_BUILTINS,
- ...ACTION_NAMES,
+const actionSchema = z.union([
+ openUrlData(),
+ toAssistantData(),
+ z.object({ type: z.string(), params: z.record(z.string(), z.any()).optional() }),
]);
+tagSchemaId(actionSchema, "ActionExpression");
+
+/**
+ * Schema for a component's action prop: `action: action().optional()`. Tagged
+ * `ActionExpression`, so the prompt teaches the @step syntax (one @step, or
+ * Action([...]) for several). Its JSON schema describes the legacy `{ type, ... }`
+ * action objects, which also still work. Returns the same schema on every call.
+ */
+export function action() {
+ return actionSchema;
+}
+
+/** A slot schema naming one action, typed like an action prop: `z.union([steps.OpenUrl.ref])`. */
+export type ActionRef = z.ZodType<z.infer<typeof actionSchema>>;
-/** Check if a name is a builtin function (not a component) */
+/** Refs of the built-in steps that have a legacy JSON shape, for restricted action slots. */
+export const steps = {
+ OpenUrl: { ref: actionRef("OpenUrl", openUrlData()) },
+ ToAssistant: { ref: actionRef("ToAssistant", toAssistantData()) },
+};
+
+/** The action `$defs` of every library, e.g. action: {$ref: "#/$defs/ActionExpression"}. */
+export const ACTION_DEFS: Record<string, z.ZodType> = {
+ ActionExpression: actionSchema,
+ OpenUrl: steps.OpenUrl.ref,
+ ToAssistant: steps.ToAssistant.ref,
+};
+
+/** A built-in step: `step` builds it from coerced args; a lazy one reads raw args in the evaluator. */
+export type BuiltinStep = DefinedAction<any> & {
+ step?: (args: any) => ActionStep;
+ lazy?: true;
+};
+
+const builtinSteps: BuiltinStep[] = [
+ {
+ ...defineAction({
+ name: "Run",
+ description: "Execute a Mutation or re-fetch a Query (ref must be a declared Query/Mutation)",
+ params: z.object({ ref: named("Query | Mutation") }),
+ }),
+ lazy: true,
+ },
+ {
+ ...defineAction({
+ name: "ToAssistant",
+ description:
+ 'Send a message to the assistant (for conversational buttons like "Tell me more", "Explain this"). The optional context is any value (object, array, string, number) passed to the assistant as hidden data, e.g. @ToAssistant("Show details", {orderId: 42})',
+ params: z.object({ message: z.string(), context: z.any().optional() }),
+ }),
+ ref: steps.ToAssistant.ref,
+ // The context may be any value and is passed through unchanged; null means none
+ step: ({ message, context }) => ({
+ type: ACTION_STEPS.ToAssistant,
+ message: String(message ?? ""),
+ context: context ?? undefined,
+ }),
+ },
+ {
+ ...defineAction({
+ name: "OpenUrl",
+ description: "Navigate to a URL",
+ params: z.object({ url: z.string() }),
+ }),
+ ref: steps.OpenUrl.ref,
+ step: ({ url }) => ({ type: ACTION_STEPS.OpenUrl, url: String(url ?? "") }),
+ },
+ {
+ ...defineAction({
+ name: "Set",
+ description: "Set a $variable to a specific value",
+ params: z.object({ variable: named("$variable"), value: z.any() }),
+ }),
+ lazy: true,
+ },
+ {
+ ...defineAction({
+ name: "Reset",
+ description:
+ 'Reset $variables to their declared defaults; pass several to reset each (e.g. @Reset($title, $priority) restores $title="" and $priority="medium")',
+ params: z.object({ variable: named("$variable") }),
+ }),
+ lazy: true,
+ },
+];
+
+/** All built-in steps by name, in prompt order. */
+export const BUILTIN_STEPS: Record<string, BuiltinStep> = Object.fromEntries(
+ builtinSteps.map((s) => [s.name, s]),
+);
+
+const callDef = (kind: CallDef["kind"], def: BuiltinFunction | BuiltinStep): CallDef => ({
+ kind,
+ params: Object.keys(def.params.shape).map((name) => ({ name, required: false })),
+ builtin: true,
+ ...(def.lazy ? { lazy: true } : {}),
+});
+
+/** The built-in functions, steps and Action: the base of every library's call registry. */
+export const BUILTIN_CALLS: ReadonlyMap<string, CallDef> = new Map([
+ ...builtins.map((b) => [b.name, callDef("function", b)] as const),
+ ...builtinSteps.map((s) => [s.name, callDef("action", s)] as const),
+ [
+ "Action",
+ { kind: "action", params: [{ name: "steps", required: true }], builtin: true, lazy: true },
+ ],
+]);
+
+// getCallDefs(cat).get("Percent") -> the library's @Percent; no cat -> built-ins only
+export function getCallDefs(cat: ParamMap | undefined): ReadonlyMap<string, CallDef> {
+ return cat?.callDefs ?? BUILTIN_CALLS;
+}
+
+/** True for a built-in function, step, or Action (not a component). */
export function isBuiltin(name: string): boolean {
- return BUILTIN_NAMES.has(name);
+ return BUILTIN_CALLS.has(name);
+}
+
+/** True for a step call: a built-in step, Action, or one of `actions`. */
+export function isStep(name: string, actions?: object): boolean {
+ return (
+ BUILTIN_CALLS.get(name)?.kind === "action" ||
+ (!!actions && Object.prototype.hasOwnProperty.call(actions, name))
+ );
}
/** Reserved statement-level call names — not builtins, not components */
@@ -224,5 +372,4 @@ export function isReservedCall(name: string): boolean {
return name in RESERVED_CALLS;
}
-/** Re-export toNumber for evaluator compatibility */
export { toNumber };
diff --git a/packages/lang-core/src/parser/enrich-errors.ts b/packages/lang-core/src/parser/enrich-errors.ts
index 9677da56d..553373b98 100644
--- a/packages/lang-core/src/parser/enrich-errors.ts
+++ b/packages/lang-core/src/parser/enrich-errors.ts
@@ -35,6 +35,7 @@ export function enrichErrors(
component: ve.component,
path: ve.path || undefined,
statementId: ve.statementId,
+ ...(ve.severity && { severity: ve.severity }),
};
if (ve.code === "unknown-component" && componentNames.length) {
error.hint = `Available components: ${componentNames.join(", ")}`;
diff --git a/packages/lang-core/src/parser/expressions.ts b/packages/lang-core/src/parser/expressions.ts
index 8efc8e69f..483483e60 100644
--- a/packages/lang-core/src/parser/expressions.ts
+++ b/packages/lang-core/src/parser/expressions.ts
@@ -138,7 +138,11 @@ export function parseExpression(tokens: Token[]): ASTNode {
// @-prefixed builtin call: @Count(...), @Each(...), @Set(...), etc.
if (tok.t === T.BuiltinCall) {
- if (tokens[pos + 1]?.t === T.LParen) return parseComp();
+ if (tokens[pos + 1]?.t === T.LParen) {
+ const call = parseComp();
+ if (call.k === "Comp" && !isBuiltin(call.name)) call.fn = true;
+ return call;
+ }
adv();
return { k: "Ref", n: tok.v as string };
}
diff --git a/packages/lang-core/src/parser/index.ts b/packages/lang-core/src/parser/index.ts
index 13c2138bb..553a182e0 100644
--- a/packages/lang-core/src/parser/index.ts
+++ b/packages/lang-core/src/parser/index.ts
@@ -29,8 +29,7 @@ export type { SerializeOptions } from "./serialize";
export { compileSchema } from "./parser";
// Shared builtin registry
-export { BUILTINS, BUILTIN_NAMES, isBuiltin } from "./builtins";
-export type { BuiltinDef } from "./builtins";
+export { BUILTINS, isBuiltin } from "./builtins";
// Typed statement model + AST utilities
export { isASTNode, isRuntimeExpr } from "./ast";
diff --git a/packages/lang-core/src/parser/materialize.ts b/packages/lang-core/src/parser/materialize.ts
index 310e2eab8..f20ca14da 100644
--- a/packages/lang-core/src/parser/materialize.ts
+++ b/packages/lang-core/src/parser/materialize.ts
@@ -3,11 +3,12 @@
// ─────────────────────────────────────────────────────────────────────────────
import type { ASTNode } from "./ast";
-import { isASTNode, isRuntimeExpr } from "./ast";
-import { isBuiltin, isReservedCall, LAZY_BUILTINS, RESERVED_CALLS } from "./builtins";
-import { isElementNode, type MaterializeCtx } from "./types";
+import { isASTNode, isRuntimeExpr, literalValue, toLiteralAST, walkAST } from "./ast";
+import { getCallDefs, isReservedCall, RESERVED_CALLS } from "./builtins";
+import { isElementNode, type CallDef, type MaterializeCtx, type ParamDef } from "./types";
import {
buildParamsSignature,
+ INVALID,
pushValidationIssue,
resolveInvalidValue,
validateSchemaValue,
@@ -25,6 +26,8 @@ export function containsDynamicValue(v: unknown): boolean {
return Object.values(v.props).some(containsDynamicValue);
}
const obj = v as Record<string, unknown>;
+ // A `{steps: [...]}` literal is evaluated too, so data cannot pose as custom action steps
+ if (Array.isArray(obj.steps)) return true;
return Object.values(obj).some(containsDynamicValue);
}
@@ -65,6 +68,100 @@ function resolveRef(name: string, ctx: MaterializeCtx, mode: "value" | "expr"):
}
}
+/** Registry calls (functions and steps) and reserved calls stay AST for the runtime. */
+function isRuntimeCall(name: string, ctx: MaterializeCtx): boolean {
+ return getCallDefs(ctx.cat).has(name) || isReservedCall(name);
+}
+
+// [Num 1, Ref x] with params [a, b] -> {a: Num 1, b: Ref x}; extra args dropped
+export function nameArgs(args: ASTNode[], params: ParamDef[]): Record<string, ASTNode> {
+ const named: Record<string, ASTNode> = {};
+ for (let i = 0; i < params.length && i < args.length; i++) named[params[i]!.name] = args[i]!;
+ return named;
+}
+
+// @Percent("x", 4) -> type-mismatch at parse time, call becomes null
+export function mapCallArgs(
+ name: string,
+ args: ASTNode[],
+ def: CallDef,
+ ctx: MaterializeCtx,
+): Record<string, ASTNode> | null {
+ const { params } = def;
+ if (args.length > params.length) {
+ pushValidationIssue(ctx, name, "", {
+ code: "excess-args",
+ declared: params.length,
+ got: args.length,
+ });
+ }
+ const mapped = nameArgs(args, params);
+ let invalid = false;
+ const errorsBefore = ctx.errors.length;
+ for (const p of params) {
+ const arg = mapped[p.name];
+ const lit = arg ? literalValue(arg) : { v: undefined };
+ if (!lit) continue;
+ if (lit.v == null) {
+ if (!p.required || p.defaultValue !== undefined) continue;
+ pushValidationIssue(ctx, name, `/${p.name}`, {
+ code: arg ? "null-required" : "missing-required",
+ signature: buildParamsSignature(name, params),
+ });
+ invalid = true;
+ continue;
+ }
+ let next = validateSchemaValue(lit.v, p.schema, name, `/${p.name}`, ctx);
+ if (next === INVALID) next = resolveInvalidValue(p.required, p.defaultValue);
+ if (next === INVALID) invalid = true;
+ else if (next === undefined) delete mapped[p.name];
+ else if (next !== lit.v) mapped[p.name] = toLiteralAST(next);
+ }
+ // An action never runs with a value the model did not write:
+ // @ExportFile("report", "xlsx") is a no-op, not an export with the "csv" default
+ if (def.kind === "action" && ctx.errors.length > errorsBefore) invalid = true;
+ return invalid ? null : mapped;
+}
+
+// @Percent(3, total) -> mappedProps {part: Num 3, total: <total AST>}
+function materializeCall(
+ node: ASTNode & { k: "Comp" },
+ ctx: MaterializeCtx,
+ materializeArg: (a: ASTNode) => ASTNode,
+): ASTNode {
+ const args = node.args.map(materializeArg);
+ const def = getCallDefs(ctx.cat).get(node.name);
+ if (!def || def.lazy) return { ...node, args };
+ // Built-ins coerce their args, so only library calls are checked
+ const mappedProps = def.builtin
+ ? nameArgs(args, def.params)
+ : mapCallArgs(node.name, args, def, ctx);
+ if (mappedProps) return { ...node, args, mappedProps };
+ // An invalid action step is an empty plan, a no-op
+ return def.kind === "action"
+ ? { k: "Comp", name: "Action", args: [{ k: "Arr", els: [] }] }
+ : { k: "Null" };
+}
+
+// Query("s", {n: @Count(rows)}): names @Count's args in place.
+// Literal library args are checked like props; an invalid call keeps raw names and is null at runtime.
+export function nameRawCallArgs(args: ASTNode[], ctx: MaterializeCtx, statementId: string): void {
+ const prevStatementId = ctx.currentStatementId;
+ ctx.currentStatementId = statementId;
+ const seen = new Set<ASTNode>(); // walkAST visits nested calls through args and mappedProps
+ for (const arg of args) {
+ walkAST(arg, (node) => {
+ if (node.k !== "Comp" || seen.has(node)) return;
+ seen.add(node);
+ const def = getCallDefs(ctx.cat).get(node.name);
+ if (!def || def.lazy) return;
+ const checked = def.builtin ? null : mapCallArgs(node.name, node.args, def, ctx);
+ node.mappedProps = checked ?? nameArgs(node.args, def.params);
+ });
+ }
+ ctx.currentStatementId = prevStatementId;
+}
+
/**
* If node is a lazy builtin like Each(arr, varName, template), temporarily
* scope the iterator variable during materialization so template refs resolve.
@@ -75,7 +172,8 @@ function materializeLazyBuiltin(
ctx: MaterializeCtx,
scopedRefs: ReadonlySet<string>,
): ASTNode | null {
- if (!LAZY_BUILTINS.has(node.name) || node.args.length < 3) return null;
+ const def = getCallDefs(ctx.cat).get(node.name);
+ if (def?.kind !== "function" || !def.lazy || node.args.length < 3) return null;
const varArg = node.args[1];
const varName = varArg.k === "Ref" ? varArg.n : varArg.k === "Str" ? varArg.v : null;
if (!varName) return null;
@@ -102,13 +200,17 @@ function materializeExprInternal(
return node;
case "Comp": {
+ if (node.fn && !isRuntimeCall(node.name, ctx)) {
+ pushValidationIssue(ctx, node.name, "", { code: "unknown-function" });
+ return { k: "Null" };
+ }
const lazy = materializeLazyBuiltin(node, ctx, scopedRefs);
if (lazy) return lazy;
- const recursedArgs = node.args.map((a) => materializeExprInternal(a, ctx, scopedRefs));
- // Builtins, reserved calls, and action calls: recurse args, keep as-is
- if (isBuiltin(node.name) || isReservedCall(node.name)) {
- return { ...node, args: recursedArgs };
+ // Built-ins, library functions, action steps, reserved calls: keep as AST
+ if (isRuntimeCall(node.name, ctx)) {
+ return materializeCall(node, ctx, (a) => materializeExprInternal(a, ctx, scopedRefs));
}
+ const recursedArgs = node.args.map((a) => materializeExprInternal(a, ctx, scopedRefs));
// Catalog component: add mappedProps for the evaluator
const def = ctx.cat?.get(node.name);
if (def) {
@@ -229,11 +331,9 @@ export function materializeValue(node: ASTNode, ctx: MaterializeCtx): unknown {
case "Comp": {
const { name, args } = node;
- // Builtins (Sum, Count, Filter, Action, etc.) → preserve as ASTNode for runtime
- if (isBuiltin(name)) {
- const lazy = materializeLazyBuiltin(node, ctx, new Set());
- if (lazy) return lazy;
- return { ...node, args: args.map((a) => materializeExpr(a, ctx)) };
+ if (node.fn && !isRuntimeCall(name, ctx)) {
+ pushValidationIssue(ctx, name, "", { code: "unknown-function" });
+ return null;
}
// Inline Query/Mutation (not from a statement-level declaration) → validation error
@@ -242,6 +342,13 @@ export function materializeValue(node: ASTNode, ctx: MaterializeCtx): unknown {
return null;
}
+ // Built-ins, library functions and action steps → preserve as ASTNode for runtime
+ if (isRuntimeCall(name, ctx)) {
+ const lazy = materializeLazyBuiltin(node, ctx, new Set());
+ if (lazy) return lazy;
+ return materializeCall(node, ctx, (a) => materializeExpr(a, ctx));
+ }
+
const def = ctx.cat?.get(name);
const props: Record<string, unknown> = {};
@@ -254,18 +361,18 @@ export function materializeValue(node: ASTNode, ctx: MaterializeCtx): unknown {
const param = def.params[i];
const value = materializeValue(args[i], ctx);
props[param.name] = value;
+ if (param.schema === undefined) continue;
// Single validation entry point: scalar leaf type/enum for simple
// props, recursive key/type checks (with pruning) for nested shapes.
- if (
- param.schema !== undefined &&
- validateSchemaValue(value, param.schema, name, `/${param.name}`, ctx)
- ) {
+ let next = validateSchemaValue(value, param.schema, name, `/${param.name}`, ctx);
+ if (next === INVALID) {
// Invalid prop value (error already reported). Same resolution rule as
// every nested edge; propagation here means dropping the component.
- if (resolveInvalidValue(props, param.name, param.required, param.defaultValue)) {
- dropComponent = true;
- }
+ next = resolveInvalidValue(param.required, param.defaultValue);
+ if (next === INVALID) dropComponent = true;
+ else if (next === undefined) delete props[param.name];
}
+ if (next !== INVALID && next !== undefined) props[param.name] = next;
}
// Report excess positional args (extra args are silently dropped)
@@ -303,7 +410,7 @@ export function materializeValue(node: ASTNode, ctx: MaterializeCtx): unknown {
// A required prop with unsalvageable data (no default) drops the
// component — its error was already reported during validation.
if (dropComponent) return null;
- } else if (!isBuiltin(name) && !isReservedCall(name)) {
+ } else {
// Unknown component: error and drop from tree
pushValidationIssue(ctx, name, "", {
code: "unknown-component",
diff --git a/packages/lang-core/src/parser/parser.ts b/packages/lang-core/src/parser/parser.ts
index 9e932a656..a3a7618be 100644
--- a/packages/lang-core/src/parser/parser.ts
+++ b/packages/lang-core/src/parser/parser.ts
@@ -5,23 +5,26 @@ import {
} from "../telemetry/runtime";
import type { ASTNode, Statement } from "./ast";
import { isASTNode, walkAST } from "./ast";
-import { isBuiltin, RESERVED_CALLS } from "./builtins";
+import { ACTION_DEFS, BUILTIN_CALLS, isBuiltin, isReservedCall, RESERVED_CALLS } from "./builtins";
import { parseExpression } from "./expressions";
import { tokenize } from "./lexer";
-import { materializeValue } from "./materialize";
+import { materializeValue, nameRawCallArgs } from "./materialize";
import { autoClose, split, type RawStmt } from "./statements";
import { T } from "./tokens";
import {
isElementNode,
+ type ElementNode,
+ type JSONSchemaDef,
type LibraryJSONSchema,
type MaterializeCtx,
type MutationStatementInfo,
+ type ParamDef,
type ParamMap,
type ParseResult,
type QueryStatementInfo,
type ValidationError,
} from "./types";
-import { getSchemaDefaultValue } from "./validation";
+import { getSchemaDefaultValue, pushValidationIssue } from "./validation";
// ─────────────────────────────────────────────────────────────────────────────
// Result building
@@ -93,9 +96,16 @@ function classifyStatement(raw: RawStmt, expr: ASTNode): Statement {
* Extract typed statements from the symbol table.
* State defaults are materialized to plain values (no raw AST in output).
*/
+/** A `$name` at the very end of streamed text, which may still be growing (`$d` of `$dishes`). */
+interface PartialRef {
+ name: string;
+ stmts: ReadonlySet<Statement>;
+}
+
function extractStatements(
stmts: Statement[],
ctx: MaterializeCtx,
+ partialRef?: PartialRef,
): {
stateDeclarations: Record<string, unknown>;
queryStatements: QueryStatementInfo[];
@@ -111,6 +121,7 @@ function extractStatements(
stateDeclarations[stmt.id] = materializeValue(stmt.init, ctx);
break;
case "query":
+ nameRawCallArgs(stmt.call.args, ctx, stmt.id);
queryStatements.push({
statementId: stmt.id,
toolAST: stmt.call.args[0] ?? null,
@@ -122,6 +133,7 @@ function extractStatements(
});
break;
case "mutation":
+ nameRawCallArgs(stmt.call.args, ctx, stmt.id);
mutationStatements.push({
statementId: stmt.id,
toolAST: stmt.call.args[0] ?? null,
@@ -144,6 +156,7 @@ function extractStatements(
: [];
for (const node of nodes) {
for (const dep of collectQueryDeps(node)) {
+ if (dep === partialRef?.name && partialRef.stmts.has(stmt)) continue;
if (!(dep in stateDeclarations)) {
stateDeclarations[dep] = null;
}
@@ -156,47 +169,54 @@ function extractStatements(
const DEFAULT_ROOT_STATEMENT_ID = "root";
-function isComponentStatement(
- stmt: Statement,
-): stmt is Extract<Statement, { kind: "value" }> & { expr: Extract<ASTNode, { k: "Comp" }> } {
- return (
- stmt.kind === "value" &&
- stmt.expr.k === "Comp" &&
- !isBuiltin(stmt.expr.name) &&
- stmt.expr.name !== RESERVED_CALLS.Query &&
- stmt.expr.name !== RESERVED_CALLS.Mutation
- );
+/** A call to a library component: not an `@` function, built-in, Query or Mutation. */
+function isComponentCall(node: ASTNode | undefined): node is Extract<ASTNode, { k: "Comp" }> {
+ return node?.k === "Comp" && !node.fn && !isBuiltin(node.name) && !isReservedCall(node.name);
}
-function pickEntryId(
+/** Entry: `root`, else the first statement that calls the root component. */
+function pickEntry(
stmtMap: Map<string, Statement>,
- typedStmts: Statement[],
- firstId: string,
rootName?: string,
-): string {
- if (stmtMap.has(DEFAULT_ROOT_STATEMENT_ID)) return DEFAULT_ROOT_STATEMENT_ID;
- if (rootName && stmtMap.has(rootName)) return rootName;
+): { id: string; fallback: boolean } | null {
+ if (stmtMap.has(DEFAULT_ROOT_STATEMENT_ID))
+ return { id: DEFAULT_ROOT_STATEMENT_ID, fallback: false };
+ for (const stmt of stmtMap.values()) {
+ if (stmt.kind === "value" && isComponentCall(stmt.expr) && stmt.expr.name === rootName)
+ return { id: stmt.id, fallback: true };
+ }
+ return null;
+}
- const preferredComponent = rootName
- ? typedStmts.find((stmt) => isComponentStatement(stmt) && stmt.expr.name === rootName)
- : undefined;
- if (preferredComponent) return preferredComponent.id;
+/** Follow refs to the entry's value; a component call that did not render was dropped by validation. */
+function resolvesToComponentCall(node: ASTNode | undefined, syms: Map<string, ASTNode>): boolean {
+ const seen = new Set<string>();
+ while (node?.k === "Ref" && !seen.has(node.n)) {
+ seen.add(node.n);
+ node = syms.get(node.n);
+ }
+ return isComponentCall(node);
+}
- const firstComponent = typedStmts.find(isComponentStatement);
- return firstComponent?.id ?? firstId;
+/** True when a runtime expression can produce a component, e.g. `$t ? A : B`. */
+function containsComponent(node: ASTNode): boolean {
+ let found = false;
+ walkAST(node, (current) => {
+ if (isComponentCall(current)) found = true;
+ });
+ return found;
}
function buildResult(
stmtMap: Map<string, Statement>,
typedStmts: Statement[],
- firstId: string,
wasIncomplete: boolean,
stmtCount: number,
cat: ParamMap | undefined,
rootName?: string,
+ partialRef?: PartialRef,
): ParseResult {
- const entryId = pickEntryId(stmtMap, typedStmts, firstId, rootName);
- if (!stmtMap.has(entryId)) return emptyResult(wasIncomplete);
+ const entry = pickEntry(stmtMap, rootName);
const syms = new Map<string, ASTNode>();
for (const [id, stmt] of stmtMap) {
@@ -208,7 +228,7 @@ function buildResult(
// Exclude root, state ($var), query, and mutation declarations — they're consumed separately.
const unreached = new Set<string>();
for (const [id, stmt] of stmtMap) {
- if (id === entryId) continue;
+ if (id === entry?.id) continue;
if (stmt.kind === "state" || stmt.kind === "query" || stmt.kind === "mutation") continue;
unreached.add(id);
}
@@ -219,23 +239,48 @@ function buildResult(
unres,
visited: new Set(),
partial: wasIncomplete,
- currentStatementId: entryId,
+ currentStatementId: entry?.id,
unreached,
};
- const materialized = materializeValue(syms.get(entryId)!, ctx);
- const root = isElementNode(materialized) ? materialized : null;
- if (root) root.statementId = entryId;
+ let root: ElementNode | null = null;
+ let rootExpression: ASTNode | undefined;
+ if (entry) {
+ const materialized = materializeValue(syms.get(entry.id)!, ctx);
+ if (isElementNode(materialized)) {
+ root = materialized;
+ root.statementId = entry.id;
+ } else if (isASTNode(materialized) && containsComponent(materialized)) {
+ rootExpression = materialized;
+ }
+ }
const { stateDeclarations, queryStatements, mutationStatements } = extractStatements(
typedStmts,
ctx,
+ partialRef,
);
- const orphaned = [...unreached];
+ // Streaming consumers drop parser errors until the stream ends, so this reads as a stream-end check.
+ ctx.currentStatementId = entry?.id;
+ const component = rootName ?? "";
+ if (!entry) {
+ pushValidationIssue(ctx, component, "", { code: "no-root", reason: "missing" });
+ } else if (!root && !rootExpression && !resolvesToComponentCall(syms.get(entry.id), syms)) {
+ pushValidationIssue(ctx, component, "", { code: "no-root", reason: "not-component" });
+ } else if (entry.fallback) {
+ pushValidationIssue(ctx, component, "", {
+ code: "no-root",
+ reason: root ? "fallback" : "missing",
+ });
+ }
+
+ // With no entry nothing is reachable; `no-root` alone describes the problem.
+ const orphaned = entry ? [...unreached] : [];
return {
root,
+ ...(rootExpression ? { rootExpression } : {}),
meta: {
incomplete: wasIncomplete,
unresolved: unres,
@@ -419,27 +464,27 @@ export function parse(input: string, cat: ParamMap, rootName?: string): ParseRes
if (!stmts.length) return emptyResult(wasIncomplete);
const stmtMap = new Map<string, Statement>();
- let firstId = "";
for (const s of stmts) {
const expr = parseExpression(s.tokens);
const stmt = classifyStatement(s, expr);
stmtMap.set(s.id, stmt);
- if (!firstId) firstId = s.id;
}
// Derive from map to deduplicate — Map.set overwrites duplicates
const typedStmts = [...stmtMap.values()];
- return buildResult(stmtMap, typedStmts, firstId, wasIncomplete, stmtMap.size, cat, rootName);
+ return buildResult(stmtMap, typedStmts, wasIncomplete, stmtMap.size, cat, rootName);
}
export interface StreamParser {
- /** Feed the next SSE/stream chunk and get the latest ParseResult. */
- push(chunk: string): ParseResult;
+ /** Feed the next SSE/stream chunk and get the latest ParseResult.
+ * Pass `complete` once the stream has ended. */
+ push(chunk: string, complete?: boolean): ParseResult;
/** Set the full text — diffs against internal buffer, pushes only the delta.
- * Resets automatically if the text was replaced (not appended). */
- set(fullText: string): ParseResult;
+ * Resets automatically if the text was replaced (not appended).
+ * Pass `complete` once the stream has ended. */
+ set(fullText: string, complete?: boolean): ParseResult;
/** Get the latest ParseResult without consuming new data. */
- getResult(): ParseResult;
+ getResult(complete?: boolean): ParseResult;
}
export function createStreamParser(cat: ParamMap, rootName?: string): StreamParser {
@@ -453,7 +498,6 @@ export function createStreamParser(cat: ParamMap, rootName?: string): StreamPars
const completedStmtMap = new Map<string, Statement>();
let completedCount = 0;
- let firstId = "";
function addStmt(text: string) {
// `text` is sliced from `cleaned`, so it's already fence/comment-free.
@@ -464,7 +508,6 @@ export function createStreamParser(cat: ParamMap, rootName?: string): StreamPars
const stmt = classifyStatement(s, expr);
completedStmtMap.set(s.id, stmt);
completedCount++;
- if (!firstId) firstId = s.id;
}
}
@@ -479,7 +522,6 @@ export function createStreamParser(cat: ParamMap, rootName?: string): StreamPars
completedEnd = 0;
completedStmtMap.clear();
completedCount = 0;
- firstId = "";
}
cleaned = next;
}
@@ -544,7 +586,7 @@ export function createStreamParser(cat: ParamMap, rootName?: string): StreamPars
return stmtStart; // start of the current pending (incomplete) statement
}
- function currentResult(): ParseResult {
+ function currentResult(complete = false): ParseResult {
refreshCleaned();
const pendingStart = scanNewCompleted();
const pendingText = cleaned.slice(pendingStart).trim();
@@ -555,7 +597,6 @@ export function createStreamParser(cat: ParamMap, rootName?: string): StreamPars
return buildResult(
completedStmtMap,
[...completedStmtMap.values()],
- firstId,
false,
completedCount,
cat,
@@ -573,7 +614,6 @@ export function createStreamParser(cat: ParamMap, rootName?: string): StreamPars
return buildResult(
completedStmtMap,
[...completedStmtMap.values()],
- firstId,
wasIncomplete,
completedCount,
cat,
@@ -584,24 +624,34 @@ export function createStreamParser(cat: ParamMap, rootName?: string): StreamPars
// New IDs can render progressively; existing IDs are replaced only when
// the pending expression no longer needs automatic closing.
const allStmtMap = new Map(completedStmtMap);
+ const pendingStmts = new Set<Statement>();
for (const s of stmts) {
if (completedStmtMap.has(s.id) && wasIncomplete) continue;
const expr = parseExpression(s.tokens);
const stmt = classifyStatement(s, expr);
allStmtMap.set(s.id, stmt);
+ pendingStmts.add(stmt);
}
+ // A `$name` ending the raw text may still be growing (`$d` of `$dishes`): skip it unless
+ // the stream is complete or the same name already appears in full in the pending text.
+ const tail = complete ? undefined : /\$\w+$/.exec(buf)?.[0];
+ const tailName =
+ tail &&
+ pendingText.endsWith(tail) &&
+ !new RegExp(`\\${tail}(?!\\w)`).test(pendingText.slice(0, -tail.length))
+ ? tail
+ : undefined;
// Derive from map to deduplicate
const allTypedStmts = [...allStmtMap.values()];
- const fid = firstId || stmts[0].id;
return buildResult(
allStmtMap,
allTypedStmts,
- fid,
wasIncomplete,
completedCount + stmts.length,
cat,
rootName,
+ tailName ? { name: tailName, stmts: pendingStmts } : undefined,
);
}
@@ -611,21 +661,20 @@ export function createStreamParser(cat: ParamMap, rootName?: string): StreamPars
completedEnd = 0;
completedStmtMap.clear();
completedCount = 0;
- firstId = "";
}
return {
- push(chunk) {
+ push(chunk, complete) {
buf += chunk;
- return currentResult();
+ return currentResult(complete);
},
- set(fullText) {
+ set(fullText, complete) {
if (fullText.length < buf.length || !fullText.startsWith(buf)) {
reset();
}
const delta = fullText.slice(buf.length);
if (delta) buf += delta;
- return currentResult();
+ return currentResult(complete);
},
getResult: currentResult,
};
@@ -635,25 +684,55 @@ export interface Parser {
parse(input: string): ParseResult;
}
+type ActionDefs = Map<string, unknown>;
+
+// {$ref: "#/$defs/ActionExpression"} -> its body, so action slots validate as inline unions
+function inlineActionRefs(node: unknown, defs: ActionDefs): unknown {
+ if (!node || typeof node !== "object") return node;
+ const ref = (node as { $ref?: unknown }).$ref;
+ if (typeof ref === "string") return defs.has(ref) ? inlineActionRefs(defs.get(ref), defs) : node;
+ const copy = (Array.isArray(node) ? [...node] : { ...node }) as Record<string, unknown>;
+ let changed = false;
+ for (const [key, value] of Object.entries(copy)) {
+ copy[key] = inlineActionRefs(value, defs);
+ changed ||= copy[key] !== value;
+ }
+ return changed ? copy : node;
+}
+
+function compileParams(def: JSONSchemaDef, defs: ActionDefs): ParamDef[] {
+ const properties = def.properties ?? {};
+ const required = def.required ?? [];
+ return Object.keys(properties).map((key) => ({
+ name: key,
+ required: required.includes(key),
+ defaultValue: getSchemaDefaultValue(properties[key]),
+ schema: defs.size ? inlineActionRefs(properties[key], defs) : properties[key],
+ }));
+}
+
export function compileSchema(schema: LibraryJSONSchema): ParamMap {
const map: ParamMap = new Map();
- const defs = schema.$defs ?? {};
const components = schema.properties && new Set(Object.keys(schema.properties));
-
- for (const [name, def] of Object.entries(defs)) {
+ // Action $defs (ActionExpression, OpenUrl, custom actions) are data shapes, never components
+ const defs: ActionDefs = new Map();
+ for (const name of [...Object.keys(ACTION_DEFS), ...Object.keys(schema.actions ?? {})]) {
+ const body = schema.$defs?.[name];
+ if (body && !components?.has(name)) defs.set(`#/$defs/${name}`, body);
+ }
+ for (const [name, def] of Object.entries(schema.$defs ?? {})) {
// Skip non-component defs, e.g. zod's hoisted recursive schemas (__schema0).
- if (components && !components.has(name)) continue;
- const properties = def.properties ?? {};
- const required = def.required ?? [];
- const params = Object.keys(properties).map((key) => ({
- name: key,
- required: required.includes(key),
- defaultValue: getSchemaDefaultValue(properties[key]),
- schema: properties[key],
- }));
- map.set(name, { params });
+ if (components ? !components.has(name) : defs.has(`#/$defs/${name}`)) continue;
+ map.set(name, { params: compileParams(def, defs) });
+ }
+ // The call registry: the built-ins plus the library's functions and actions
+ map.callDefs = new Map(BUILTIN_CALLS);
+ for (const [name, fn] of Object.entries(schema.functions ?? {})) {
+ map.callDefs.set(name, { kind: "function", params: compileParams(fn.params, defs) });
+ }
+ for (const [name, action] of Object.entries(schema.actions ?? {})) {
+ map.callDefs.set(name, { kind: "action", params: compileParams(action.params, defs) });
}
-
return map;
}
diff --git a/packages/lang-core/src/parser/prompt.ts b/packages/lang-core/src/parser/prompt.ts
index 28f8da017..697b799aa 100644
--- a/packages/lang-core/src/parser/prompt.ts
+++ b/packages/lang-core/src/parser/prompt.ts
@@ -1,5 +1,6 @@
+import { schemaSignature } from "../signature";
import { recordSystemPromptGeneration } from "../telemetry/runtime";
-import { BUILTINS, LAZY_BUILTIN_DEFS } from "./builtins";
+import { BUILTIN_STEPS, BUILTINS, type BuiltinStep } from "./builtins";
import { generateCloudConfig } from "./cloud-config";
import type { LibraryJSONSchema } from "./types";
@@ -33,6 +34,10 @@ export interface BaseSpec {
root?: string;
components: Record<string, ComponentPromptSpec>;
componentGroups?: ComponentGroup[];
+ /** Library functions, listed next to the built-ins. Signatures are pre-built. */
+ functions?: Record<string, ComponentPromptSpec>;
+ /** Custom library actions, listed with the built-in action steps. Signatures are pre-built. */
+ actions?: Record<string, ComponentPromptSpec>;
}
export interface PromptSpec extends BaseSpec {
@@ -43,6 +48,8 @@ export interface PromptSpec extends BaseSpec {
toolCalls?: boolean;
/** Enable $variables, @Set, @Reset, interactive filters. Default: true if toolCalls. */
bindings?: boolean;
+ /** List the built-in functions (@Count, @Sum, ...). Default: true if toolCalls or bindings. */
+ builtinFunctions?: boolean;
preamble?: string;
/** General examples (static/layout patterns). Both `examples` and `toolExamples` are included when present. */
examples?: string[];
@@ -153,18 +160,22 @@ function syntaxRules(
return lines.join("\n");
}
-function builtinFunctionsSection(): string {
- // Auto-generated from shared builtin registry — single source of truth
- const builtinLines = Object.values(BUILTINS).map((b) => `@${b.signature} — ${b.description}`);
- const lazyLines = Object.values(LAZY_BUILTIN_DEFS).map(
- (b) => `@${b.signature} — ${b.description}`,
- );
- const lines = [...builtinLines, ...lazyLines].join("\n");
+function functionLine(f: { signature: string; description?: string }): string {
+ return f.description ? `@${f.signature} — ${f.description}` : `@${f.signature}`;
+}
+
+function builtinFunctionsSection(custom: string[], toolCalls: boolean): string {
+ const lines = [
+ ...Object.values(BUILTINS).map((b) =>
+ functionLine({ ...b, signature: schemaSignature(b.name, b.params, b.returns) }),
+ ),
+ ...custom,
+ ].join("\n");
return `## Built-in Functions
Data functions prefixed with \`@\` to distinguish from components. These are the ONLY functions available — do NOT invent new ones.
-Use @-prefixed built-in functions (@Count, @Sum, @Avg, @Min, @Max, @Round) on Query results — do NOT hardcode computed values.
+Use @-prefixed built-in functions (@Count, @Sum, @Avg, @Min, @Max, @Round) on ${toolCalls ? "Query results" : "data"}. Do NOT hardcode computed values.
${lines}
@@ -173,8 +184,8 @@ Builtins compose — output of one is input to the next:
Array pluck: \`data.rows.field\` extracts a field from every row → use with @Sum, @Avg, charts, tables.
IMPORTANT @Each rule: The loop variable (e.g. "item") is ONLY available inside the @Each template expression. Always inline the template — do NOT extract it to a separate statement.
-CORRECT: \`Col("Actions", @Each(rows, "t", Button("Edit", Action([@Set($id, t.id)]))))\`
-WRONG: \`myBtn = Button("Edit", Action([@Set($id, t.id)]))\` then \`Col("Actions", @Each(rows, "t", myBtn))\` — t is undefined in myBtn.`;
+CORRECT: \`list = @Each(rows, "t", Comp(t.name))\`
+WRONG: \`item = Comp(t.name)\` then \`list = @Each(rows, "t", item)\`, because t is undefined in item.`;
}
function querySection(): string {
@@ -214,24 +225,24 @@ result = Mutation("tool_name", {arg1: $binding, arg2: "value"})
- Show loading state: \`result.status == "loading" ? TextContent("Saving...") : null\``;
}
-function actionSection(flags: { toolCalls: boolean; bindings: boolean }): string {
- const steps = [
- '- @ToAssistant("message") — Send a message to the assistant (for conversational buttons like "Tell me more", "Explain this")',
- '- @OpenUrl("https://...") — Navigate to a URL',
- ];
+const ACTION_HEADER = "## Action — Button Behavior";
- if (flags.bindings) {
- steps.push(
- "- @Set($variable, value) — Set a $variable to a specific value",
- '- @Reset($var1, $var2, ...) — Reset $variables to their declared defaults (e.g. @Reset($title, $priority) restores $title="" and $priority="medium")',
- );
- }
+/** The built-in steps the prompt lists: @Run needs toolCalls, @Set and @Reset need bindings. */
+function builtinSteps(flags: { toolCalls: boolean; bindings: boolean }): BuiltinStep[] {
+ return Object.values(BUILTIN_STEPS).filter((s) => {
+ if (s.name === "Run") return flags.toolCalls;
+ if (s.name === "Set" || s.name === "Reset") return flags.bindings;
+ return true;
+ });
+}
- if (flags.toolCalls) {
- steps.unshift(
- "- @Run(queryOrMutationRef) — Execute a Mutation or re-fetch a Query (ref must be a declared Query/Mutation)",
- );
- }
+function actionSection(flags: { toolCalls: boolean; bindings: boolean }, custom: string[]): string {
+ const steps = [
+ ...builtinSteps(flags).map(
+ (s) => `- ${functionLine({ ...s, signature: schemaSignature(s.name, s.params) })}`,
+ ),
+ ...custom,
+ ];
const examples: string[] = [];
if (flags.toolCalls) {
@@ -246,11 +257,11 @@ onSubmit = Action([@Run(result), @Run(data), @Reset($binding)])
examples.push(`Example — simple nav:
\`\`\`
-viewBtn = Button("View", Action([@OpenUrl("https://example.com")]))
+viewBtn = Button("View", @OpenUrl("https://example.com"))
\`\`\``);
const rules = [
- '- Action can be assigned to a variable or inlined: Button("Go", onSubmit) and Button("Go", Action([...])) both work',
+ '- An action can be assigned to a variable or inlined: Button("Go", onSubmit) and Button("Go", Action([...])) both work',
];
if (flags.toolCalls) {
rules.push(
@@ -259,10 +270,10 @@ viewBtn = Button("View", Action([@OpenUrl("https://example.com")]))
);
}
- return `## Action — Button Behavior
+ return `${ACTION_HEADER}
-Action([@steps...]) wires button clicks to operations. Steps are @-prefixed built-in actions. Steps execute in order.
-Buttons without an explicit Action prop automatically send their label to the assistant (equivalent to Action([@ToAssistant(label)])).
+An action wires a button click to operations. Pass one @-prefixed step bare, e.g. Button("Ask", @ToAssistant("Tell me more")). Put several steps in Action([...]), e.g. Button("Read", Action([@OpenUrl("https://example.com"), @ToAssistant("Summarize this page")])). Steps execute in order.
+Buttons without an action automatically send their label to the assistant (equivalent to @ToAssistant(label)).
Available steps:
${steps.join("\n")}
@@ -340,13 +351,21 @@ To remove a component, re-declare its parent without that component in the paren
- If you are about to output more than 10 statements, reconsider — most edits need fewer`;
}
-function streamingRules(rootName: string, flags: { supportsExpressions: boolean }): string {
+function streamingRules(
+ rootName: string,
+ flags: { supportsExpressions: boolean; toolCalls: boolean },
+): string {
const steps = [`1. \`root = ${rootName}(...)\` — UI shell appears immediately`];
if (flags.supportsExpressions) {
steps.push("2. $variable declarations — state ready for bindings");
- steps.push("3. Query statements — defaults resolve immediately so components render with data");
- steps.push("4. Component definitions — fill in with data already available");
- steps.push("5. Data values — leaf content last");
+ if (flags.toolCalls) {
+ steps.push(
+ "3. Query statements — defaults resolve immediately so components render with data",
+ );
+ }
+ const n = steps.length;
+ steps.push(`${n + 1}. Component definitions — fill in with data already available`);
+ steps.push(`${n + 2}. Data values — leaf content last`);
} else {
steps.push("2. Component definitions — fill in as they stream");
steps.push("3. Data values — leaf content last");
@@ -397,7 +416,7 @@ function toolWorkflowSection(): string {
When tools are available, follow this workflow:
1. FIRST: Call the most relevant tool to inspect the real data shape before generating code
2. Use Query() for READ operations (data that should stay live) — NEVER hardcode tool results as literal arrays or objects
-3. Use Mutation() for WRITE operations (create, update, delete) — triggered by button clicks via Action([@Run(mutationRef)])
+3. Use Mutation() for WRITE operations (create, update, delete) — triggered by button clicks via @Run(mutationRef)
4. Use the real data from step 1 as condensed Query defaults (3-5 rows) so the UI renders immediately
5. Use @-prefixed builtins (@Count, @Filter, @Sort, @Sum) on Query results for KPIs and aggregations — the runtime evaluates these live on every refresh
6. Hardcoded arrays are ONLY for static display data (labels, options) where no tool exists
@@ -531,6 +550,9 @@ function renderToolsSection(tools: (string | ToolSpec)[]): string {
// ─── Component signatures ───────────────────────────────────────────────────
+// A restricted action slot in a signature, e.g. `share?: @CopyToClipboard | @OpenUrl`
+const RESTRICTED_SLOT = /[:|] @[A-Z]/;
+
function generateComponentSignatures(
spec: PromptSpec,
flags: { toolCalls: boolean; bindings: boolean; usesActionExpression: boolean },
@@ -542,15 +564,15 @@ function generateComponentSignatures(
];
if (flags.usesActionExpression) {
const allSteps = [
- flags.toolCalls ? "@Run" : "",
- "@ToAssistant",
- "@OpenUrl",
- flags.bindings ? "@Set" : "",
- flags.bindings ? "@Reset" : "",
- ].filter(Boolean);
+ ...builtinSteps(flags).map((step) => step.name),
+ ...Object.keys(spec.actions ?? {}),
+ ].map((name) => `@${name}`);
lines.push(
- `Props typed \`ActionExpression\` accept an Action([@steps...]) expression. See the Action section for available steps (${allSteps.join(", ")}).`,
+ `Props typed \`ActionExpression\` accept one @step, or Action([@steps...]) for several. See the Action section for available steps (${allSteps.join(", ")}).`,
);
+ if (Object.values(spec.components).some((c) => RESTRICTED_SLOT.test(c.signature ?? ""))) {
+ lines.push("Props typed like `@OpenUrl | @ToAssistant` accept only the steps listed.");
+ }
}
const usesBindings =
flags.bindings || Object.values(spec.components).some((c) => c.signature?.includes("$binding"));
@@ -606,8 +628,8 @@ export function generatePrompt(spec: PromptSpec): string {
const supportsExpressions = toolCalls || bindings;
// Detect component-level feature usage
- const usesActionExpression = Object.values(spec.components).some((c) =>
- c.signature?.includes("ActionExpression"),
+ const usesActionExpression = Object.values(spec.components).some(
+ (c) => c.signature?.includes("ActionExpression") || RESTRICTED_SLOT.test(c.signature ?? ""),
);
const parts: string[] = [];
@@ -618,10 +640,14 @@ export function generatePrompt(spec: PromptSpec): string {
parts.push("");
parts.push(generateComponentSignatures(spec, { toolCalls, bindings, usesActionExpression }));
- // Built-in functions — only when expressions are enabled (Query/reactive state)
- if (supportsExpressions) {
+ // Library functions get the section alone when built-ins are not listed
+ const customFunctions = Object.values(spec.functions ?? {}).map(functionLine);
+ if (spec.builtinFunctions ?? supportsExpressions) {
+ parts.push("");
+ parts.push(builtinFunctionsSection(customFunctions, toolCalls));
+ } else if (customFunctions.length) {
parts.push("");
- parts.push(builtinFunctionsSection());
+ parts.push(`## Built-in Functions\n\n${customFunctions.join("\n")}`);
}
// Query + Mutation sections
@@ -632,10 +658,16 @@ export function generatePrompt(spec: PromptSpec): string {
parts.push(mutationSection());
}
- // Action section — only when components use ActionExpression (v0.5 action syntax)
+ // Library actions get the Action section alone when no component uses ActionExpression
+ const customActions = Object.values(spec.actions ?? {}).map((a) => `- ${functionLine(a)}`);
if (usesActionExpression) {
parts.push("");
- parts.push(actionSection({ toolCalls, bindings }));
+ parts.push(actionSection({ toolCalls, bindings }, customActions));
+ } else if (customActions.length) {
+ parts.push("");
+ parts.push(
+ `${ACTION_HEADER}\n\nPass one step, or Action([...]) with several steps, as a button's action.\n\nAvailable steps:\n${customActions.join("\n")}`,
+ );
}
// Interactive filters (needs both toolCalls and bindings)
@@ -657,7 +689,7 @@ export function generatePrompt(spec: PromptSpec): string {
}
parts.push("");
- parts.push(streamingRules(rootName, { supportsExpressions }));
+ parts.push(streamingRules(rootName, { supportsExpressions, toolCalls }));
// Append both examples and toolExamples when both are present
const allExamples = [...(spec.examples ?? []), ...(spec.toolExamples ?? [])];
diff --git a/packages/lang-core/src/parser/serialize.ts b/packages/lang-core/src/parser/serialize.ts
index c8da15856..436aa50fb 100644
--- a/packages/lang-core/src/parser/serialize.ts
+++ b/packages/lang-core/src/parser/serialize.ts
@@ -6,9 +6,9 @@
import type { Library } from "../library";
import type { ASTNode } from "./ast";
import { isASTNode } from "./ast";
-import { isBuiltin } from "./builtins";
+import { getCallDefs } from "./builtins";
import { compileSchema } from "./parser";
-import { isElementNode, type ElementNode, type ParamMap } from "./types";
+import { isElementNode, type CallDef, type ElementNode, type ParamMap } from "./types";
// ─── Operator precedence (mirrors expressions.ts) ────────────────────────────
@@ -57,7 +57,8 @@ class StatementCollector {
// ─── AST node serializer ─────────────────────────────────────────────────────
-function serializeASTNode(node: ASTNode): string {
+/** `calls` are the library's call names (built-ins, functions, actions), written with `@`. */
+function serializeASTNode(node: ASTNode, calls: ReadonlyMap<string, CallDef>): string {
switch (node.k) {
case "Str":
return JSON.stringify(node.v);
@@ -74,28 +75,30 @@ function serializeASTNode(node: ASTNode): string {
case "RuntimeRef":
return node.n;
case "Arr":
- return "[" + node.els.map(serializeASTNode).join(", ") + "]";
+ return "[" + node.els.map((el) => serializeASTNode(el, calls)).join(", ") + "]";
case "Obj":
- return "{" + node.entries.map(([k, v]) => `${k}: ${serializeASTNode(v)}`).join(", ") + "}";
+ return (
+ "{" + node.entries.map(([k, v]) => `${k}: ${serializeASTNode(v, calls)}`).join(", ") + "}"
+ );
case "BinOp": {
- const left = serializeBinOpChild(node.left, node.op, "left");
- const right = serializeBinOpChild(node.right, node.op, "right");
+ const left = serializeBinOpChild(node.left, node.op, "left", calls);
+ const right = serializeBinOpChild(node.right, node.op, "right", calls);
return `${left} ${node.op} ${right}`;
}
case "UnaryOp":
- return `${node.op}${serializeASTNode(node.operand)}`;
+ return `${node.op}${serializeASTNode(node.operand, calls)}`;
case "Ternary":
- return `${serializeASTNode(node.cond)} ? ${serializeASTNode(node.then)} : ${serializeASTNode(node.else)}`;
+ return `${serializeASTNode(node.cond, calls)} ? ${serializeASTNode(node.then, calls)} : ${serializeASTNode(node.else, calls)}`;
case "Member":
- return `${serializeASTNode(node.obj)}.${node.field}`;
+ return `${serializeASTNode(node.obj, calls)}.${node.field}`;
case "Index":
- return `${serializeASTNode(node.obj)}[${serializeASTNode(node.index)}]`;
+ return `${serializeASTNode(node.obj, calls)}[${serializeASTNode(node.index, calls)}]`;
case "Assign":
- return `${node.target} = ${serializeASTNode(node.value)}`;
+ return `${node.target} = ${serializeASTNode(node.value, calls)}`;
case "Comp": {
- const args = node.args.map(serializeASTNode).join(", ");
- // Builtin (not Action) → @-prefix
- if (isBuiltin(node.name) && node.name !== "Action") {
+ const args = node.args.map((arg) => serializeASTNode(arg, calls)).join(", ");
+ // Built-ins, library functions and actions (not Action) → @-prefix
+ if (calls.has(node.name) && node.name !== "Action") {
return `@${node.name}(${args})`;
}
// Action, reserved calls (Query/Mutation), catalog components → no prefix
@@ -110,8 +113,13 @@ function serializeASTNode(node: ASTNode): string {
}
/** Wrap a BinOp child in parens if its precedence is lower than the parent's. */
-function serializeBinOpChild(child: ASTNode, parentOp: string, _side: "left" | "right"): string {
- const inner = serializeASTNode(child);
+function serializeBinOpChild(
+ child: ASTNode,
+ parentOp: string,
+ _side: "left" | "right",
+ calls: ReadonlyMap<string, CallDef>,
+): string {
+ const inner = serializeASTNode(child, calls);
if (child.k !== "BinOp") return inner;
const parentPrec = PRECEDENCE[parentOp] ?? 0;
const childPrec = PRECEDENCE[child.op] ?? 0;
@@ -134,7 +142,7 @@ function serializeValue(value: unknown, paramMap: ParamMap, collector: Statement
// ASTNode (surviving runtime expressions in dynamic props)
if (isASTNode(value)) {
- return serializeASTNode(value);
+ return serializeASTNode(value, getCallDefs(paramMap));
}
// Array
diff --git a/packages/lang-core/src/parser/types.ts b/packages/lang-core/src/parser/types.ts
index 26e689071..fde85503f 100644
--- a/packages/lang-core/src/parser/types.ts
+++ b/packages/lang-core/src/parser/types.ts
@@ -1,20 +1,36 @@
import type { ASTNode } from "./ast";
export type JSONSchemaProperty = Record<string, unknown>;
+/** A JSON Schema object; keywords are added as libraries use them (anyOf: the ActionExpression union). */
export type JSONSchemaDef = {
properties?: JSONSchemaProperty;
required?: string[];
description?: string;
+ type?: string;
+ anyOf?: JSONSchemaProperty[];
};
+/** A function's params and return value as JSON Schema. */
+export interface FunctionSchema {
+ description?: string;
+ /** JSON Schema object of the params. Property order is the positional order in programs. */
+ params: JSONSchemaDef;
+ /** JSON Schema of the return value. */
+ returns?: JSONSchemaProperty;
+}
+
/**
* The JSON Schema document produced by `library.toJSONSchema()`.
* All component schemas live in `$defs`, keyed by component name.
+ * Library functions and actions live in `functions` and `actions`.
*/
export interface LibraryJSONSchema {
$defs?: Record<string, JSONSchemaDef>;
/** Component names as keys. Other `$defs` are data shapes. */
properties?: Record<string, unknown>;
+ functions?: Record<string, FunctionSchema>;
+ /** Custom actions, when the library has any. They have no `returns`. */
+ actions?: Record<string, FunctionSchema>;
}
/** Scalar JSON Schema types we can reliably check a positional literal against. */
@@ -31,8 +47,20 @@ export interface ParamDef {
schema?: unknown;
}
-/** Internal parameter map for positional-arg to named-prop mapping. */
-export type ParamMap = Map<string, { params: ParamDef[] }>;
+/** `@Percent(part, total)` -> params [{name: "part"}, {name: "total"}], kept as AST */
+export interface CallDef {
+ kind: "function" | "action";
+ params: ParamDef[];
+ /** Built-ins coerce their args: the runtime maps them by name, unvalidated. */
+ builtin?: true;
+ /** Lazy built-ins (@Each, Action, @Run, @Set, @Reset) get their args unevaluated. */
+ lazy?: true;
+}
+
+/** "Card" -> its params; callDefs: "Sum" -> built-in CallDef, "Percent" -> library CallDef */
+export type ParamMap = Map<string, { params: ParamDef[] }> & {
+ callDefs?: Map<string, CallDef>;
+};
/**
* A fully resolved component node from the parser.
@@ -82,7 +110,9 @@ export type ValidationErrorCode =
| "unknown-component"
| "inline-reserved"
| "excess-args"
- | "type-mismatch";
+ | "type-mismatch"
+ | "unknown-function"
+ | "no-root";
/**
* A prop validation error. Components with missing required props are
@@ -99,6 +129,8 @@ export interface ValidationError {
message: string;
/** Statement name that triggered the error (e.g. "header", "chart"). */
statementId?: string;
+ /** "warning" when the program still renders (e.g. the `no-root` fallback); absent means error. */
+ severity?: "warning";
}
export interface MaterializeCtx {
@@ -123,7 +155,7 @@ export type OpenUIErrorSource = "parser" | "runtime" | "query" | "mutation";
* Machine-readable error codes for the openui-lang pipeline.
*
* - Parser: "unknown-component", "missing-required", "null-required", "inline-reserved",
- * "parse-exception", "parse-failed"
+ * "excess-args", "type-mismatch", "unknown-function", "no-root", "parse-exception", "parse-failed"
* - Runtime: "runtime-error" (prop evaluation), "render-error" (React render)
* - Query/Mutation: "tool-not-found", "tool-error", "mcp-error"
*/
@@ -162,6 +194,8 @@ export interface OpenUIError {
toolName?: string;
/** Actionable fix context for the LLM (e.g. available components, correct signature). */
hint?: string;
+ /** "warning" when the program still renders; absent means error. */
+ severity?: "warning";
}
/**
@@ -178,10 +212,12 @@ export enum BuiltinActionType {
*/
export type ActionStep =
| { type: "run"; statementId: string; refType: "query" | "mutation" }
- | { type: "continue_conversation"; message: string; context?: string }
+ | { type: "continue_conversation"; message: string; context?: unknown }
| { type: "open_url"; url: string }
| { type: "set"; target: string; valueAST: ASTNode }
- | { type: "reset"; targets: string[] };
+ | { type: "reset"; targets: string[] }
+ /** A library action from `defineAction`; delivered to `onAction` as `{ type: name, params }`. */
+ | { type: "custom_action"; name: string; params: Record<string, unknown> };
/**
* An ordered sequence of steps to execute when a button is clicked.
@@ -249,6 +285,8 @@ export interface MutationStatementInfo {
export interface ParseResult {
/** The root ElementNode (typically a Root component), or null if parsing hasn't produced one yet. */
root: ElementNode | null;
+ /** Set when the entry picks a component at runtime (`root = $t ? A : B`); see `evaluateRoot`. */
+ rootExpression?: ASTNode;
meta: {
/** True if the parser detected truncated/incomplete input. */
incomplete: boolean;
diff --git a/packages/lang-core/src/parser/validation.ts b/packages/lang-core/src/parser/validation.ts
index e9a086d7a..1a100329d 100644
--- a/packages/lang-core/src/parser/validation.ts
+++ b/packages/lang-core/src/parser/validation.ts
@@ -136,7 +136,9 @@ export type ValidationIssue =
| { code: "null-required"; signature?: string }
| { code: "unknown-component"; available?: string[] }
| { code: "inline-reserved" }
- | { code: "excess-args"; declared: number; got: number };
+ | { code: "excess-args"; declared: number; got: number }
+ | { code: "unknown-function" }
+ | { code: "no-root"; reason: "missing" | "not-component" | "fallback" };
function validationMessage(component: string, path: string, issue: ValidationIssue): string {
switch (issue.code) {
@@ -152,6 +154,16 @@ function validationMessage(component: string, path: string, issue: ValidationIss
return `${component}() must be declared as a top-level statement, not used inline as a value`;
case "excess-args":
return `${component} takes ${issue.declared} arg(s), got ${issue.got} (${issue.got - issue.declared} excess dropped)`;
+ case "unknown-function":
+ return `Unknown function "@${component}": not a built-in or action step. The call evaluates to null`;
+ case "no-root":
+ if (issue.reason === "not-component") return "root does not evaluate to a component";
+ if (issue.reason === "fallback") {
+ return `No root statement. Rendering the first statement that calls the root component ${component}`;
+ }
+ return component
+ ? `No root statement, and no statement calls the root component ${component}`
+ : "No root statement";
}
}
@@ -168,6 +180,8 @@ export function pushValidationIssue(
path,
message: validationMessage(component, path, issue),
statementId: ctx.currentStatementId,
+ ...(issue.code === "no-root" &&
+ issue.reason === "fallback" && { severity: "warning" as const }),
});
}
@@ -175,24 +189,13 @@ export function pushValidationIssue(
// Invalid-value resolution — the edge rule
// ─────────────────────────────────────────────────────────────────────────────
-/**
- * Override invalid value with a default one if present.
- * Propagate upwards if it's a required key.
- * Else, delete the key.
- */
-export function resolveInvalidValue(
- container: Record<string, unknown>,
- key: string,
- required: boolean,
- defaultValue: unknown,
-): boolean {
- if (defaultValue !== undefined) {
- container[key] = defaultValue;
- return false;
- }
- if (required) return true;
- delete container[key];
- return false;
+// "x" against {type: "number"} -> INVALID, after reporting the type-mismatch
+export const INVALID: unique symbol = Symbol("invalid");
+
+// invalid value: default 5 -> 5; no default -> INVALID if required, else undefined (omit)
+export function resolveInvalidValue(required: boolean, defaultValue: unknown): unknown {
+ if (defaultValue !== undefined) return defaultValue;
+ return required ? INVALID : undefined;
}
// ─────────────────────────────────────────────────────────────────────────────
@@ -238,7 +241,8 @@ function isOnlyComponentSlot(s: Record<string, unknown>, ctx: MaterializeCtx): b
/**
* Validate an object-shaped slot: container type, required keys (absent/null
* ones fill silently from their schema default), then each declared property
- * recursively, resolving invalid children via the edge rule.
+ * recursively, resolving invalid children via the edge rule. Copies the object
+ * only when a key changes.
*/
function validateObjectValue(
value: unknown,
@@ -246,16 +250,17 @@ function validateObjectValue(
component: string,
path: string,
ctx: MaterializeCtx,
-): boolean {
+): unknown {
if (typeof value !== "object" || Array.isArray(value)) {
pushValidationIssue(ctx, component, path, {
code: "type-mismatch",
expected: "object",
actual: jsType(value),
});
- return true;
+ return INVALID;
}
const obj = value as Record<string, unknown>;
+ let out: Record<string, unknown> | undefined;
const props =
s["properties"] && typeof s["properties"] === "object"
? (s["properties"] as Record<string, unknown>)
@@ -269,7 +274,7 @@ function validateObjectValue(
if (!present || obj[key] == null) {
const fallback = getSchemaDefaultValue(props[key]);
if (fallback !== undefined) {
- obj[key] = fallback;
+ (out ??= { ...obj })[key] = fallback;
continue;
}
pushValidationIssue(ctx, component, `${path}/${key}`, {
@@ -280,21 +285,27 @@ function validateObjectValue(
}
}
for (const key of Object.keys(props)) {
- if (key in obj) {
- const sub = props[key];
- if (validateSchemaValue(obj[key], sub, component, `${path}/${key}`, ctx)) {
- if (resolveInvalidValue(obj, key, required.includes(key), getSchemaDefaultValue(sub))) {
- invalid = true;
- }
+ if (!(key in obj)) continue;
+ const sub = props[key];
+ let next = validateSchemaValue(obj[key], sub, component, `${path}/${key}`, ctx);
+ if (next === INVALID) {
+ next = resolveInvalidValue(required.includes(key), getSchemaDefaultValue(sub));
+ if (next === INVALID) {
+ invalid = true;
+ continue;
}
}
+ if (next === obj[key]) continue;
+ out ??= { ...obj };
+ if (next === undefined) delete out[key];
+ else out[key] = next;
}
- return invalid;
+ return invalid ? INVALID : (out ?? obj);
}
/**
- * Validate an array slot: Invalid items are pruned in
- * place: validated first so error paths keep original indices
+ * Validate an array slot. Invalid items are pruned; error paths keep the
+ * original indices. Copies the array only when an item changes.
*/
function validateArrayValue(
value: unknown,
@@ -302,27 +313,24 @@ function validateArrayValue(
component: string,
path: string,
ctx: MaterializeCtx,
-): boolean {
+): unknown {
if (!Array.isArray(value)) {
pushValidationIssue(ctx, component, path, {
code: "type-mismatch",
expected: "array",
actual: jsType(value),
});
- return true;
+ return INVALID;
}
const items = s["items"];
- if (!items || typeof items !== "object" || Array.isArray(items)) return false;
- let invalid: number[] | undefined;
+ if (!items || typeof items !== "object" || Array.isArray(items)) return value;
+ let out: unknown[] | undefined;
for (let i = 0; i < value.length; i++) {
- if (validateSchemaValue(value[i], items, component, `${path}/${i}`, ctx)) {
- (invalid ??= []).push(i);
- }
- }
- if (invalid) {
- for (let i = invalid.length - 1; i >= 0; i--) value.splice(invalid[i], 1); // prune the array
+ const next = validateSchemaValue(value[i], items, component, `${path}/${i}`, ctx);
+ if (next !== value[i] && !out) out = value.slice(0, i);
+ if (out && next !== INVALID) out.push(next);
}
- return false;
+ return out ?? value;
}
/**
@@ -349,17 +357,20 @@ function validateLeafValue(
}
/**
- * Recursively validate a materialized value against a JSON Schema fragment,
- * pruning unsalvageable data along the way. Dispatches on the schema shape:
- * objects and arrays descend recursively (reporting nested errors with
- * JSON-pointer paths), leaf scalars check type/enum, and component elements
- * get a position check only (their own args validate separately).
+ * Recursively validate a materialized value against a JSON Schema fragment.
+ * Dispatches on the schema shape: objects and arrays descend recursively
+ * (reporting nested errors with JSON-pointer paths), leaf scalars check
+ * type/enum, and component elements get a position check only (their own args
+ * validate separately).
*
* Every violation is reported, then the same rule (resolveInvalidValue)
* applies at each recursion edge: schema default → substitute; REQUIRED edge →
* parent invalid, caller repeats one level up; OPTIONAL edge → prune. ARRAY
* ITEMS are always pruned. Absent/null required keys fill silently from their
* schema default; reported violations keep their error even when a default steps in.
+ *
+ * Never mutates: returns the value itself when nothing changes, a cleaned copy
+ * when something does, or INVALID.
*/
export function validateSchemaValue(
value: unknown,
@@ -367,18 +378,20 @@ export function validateSchemaValue(
component: string,
path: string,
ctx: MaterializeCtx,
-): boolean {
- if (!schema || typeof schema !== "object" || Array.isArray(schema)) return false;
+): unknown {
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) return value;
const s = schema as Record<string, unknown>;
// Absence is handled by required checks on the parent; skip null/undefined.
- if (value == null) return false;
+ if (value == null) return value;
// Dynamic runtime expressions ($var, builtins) resolve later — don't flag.
- if (isASTNode(value)) return false;
+ if (isASTNode(value)) return value;
// Child components: only their position is checked here.
- if (isElementNode(value)) return validateElementPosition(value, s, component, path, ctx);
+ if (isElementNode(value)) {
+ return validateElementPosition(value, s, component, path, ctx) ? INVALID : value;
+ }
if (isCompositeSchema(s)) {
// Data (an object, array, string, number or boolean) in a component-only slot is invalid.
- if (!isOnlyComponentSlot(s, ctx)) return false;
+ if (!isOnlyComponentSlot(s, ctx)) return value;
pushValidationIssue(ctx, component, path, {
code: "type-mismatch",
expected: slotRefNames(s).join(" | "),
@@ -388,11 +401,11 @@ export function validateSchemaValue(
? "plain object"
: typeof value,
});
- return true;
+ return INVALID;
}
const type = s["type"];
if (type === "object") return validateObjectValue(value, s, component, path, ctx);
if (type === "array") return validateArrayValue(value, s, component, path, ctx);
- return validateLeafValue(value, s, component, path, ctx);
+ return validateLeafValue(value, s, component, path, ctx) ? INVALID : value;
}
diff --git a/packages/lang-core/src/runtime/__tests__/actions.test.ts b/packages/lang-core/src/runtime/__tests__/actions.test.ts
new file mode 100644
index 000000000..e3aa5afe7
--- /dev/null
+++ b/packages/lang-core/src/runtime/__tests__/actions.test.ts
@@ -0,0 +1,204 @@
+import { describe, expect, it } from "vitest";
+import { z } from "zod/v4";
+import { createLibrary, defineAction, defineComponent, defineFunction } from "../../library";
+import { createParser } from "../../parser";
+import { action, steps } from "../../parser/builtins";
+import type { OpenUIError } from "../../parser/types";
+import { evaluateElementProps } from "../evaluate-tree";
+
+const Button = defineComponent({
+ name: "Button",
+ props: z.object({ label: z.string(), action: action().optional() }),
+ description: "",
+ component: null as any,
+});
+const library = createLibrary({ root: "Button", components: [Button] });
+const parser = createParser(library.toJSONSchema(), "Button");
+
+function actionOf(action: string): any {
+ const { root } = parser.parse(`root = Button("Go", ${action})`);
+ const ctx = { getState: () => undefined, resolveRef: () => null };
+ return evaluateElementProps(root!, { ctx, library, store: null }).props.action;
+}
+
+describe("action plans", () => {
+ it("evaluates a bare step to a one-step plan", () => {
+ expect(actionOf(`@OpenUrl("u")`)).toEqual({ steps: [{ type: "open_url", url: "u" }] });
+ });
+
+ it("flattens nested Action([...]) plans and drops invalid steps", () => {
+ const { steps } = actionOf(`Action([@Set($a, 1), @Reset("a"), Action([@OpenUrl("u")])])`);
+ expect(steps.map((s: { type: string }) => s.type)).toEqual(["set", "open_url"]);
+ });
+
+ it("passes any @ToAssistant context through; null means none", () => {
+ expect(actionOf(`@ToAssistant("Save", {ticket: "T-42"})`).steps[0].context).toEqual({
+ ticket: "T-42",
+ });
+ expect(actionOf(`@ToAssistant("Save", null)`).steps[0].context).toBeUndefined();
+ });
+
+ it("keeps data with a null in its steps array as data", () => {
+ const Text = defineComponent({
+ name: "Text",
+ props: z.object({ text: z.any() }),
+ description: "",
+ component: null as any,
+ });
+ const textLib = createLibrary({ root: "Text", components: [Text] });
+ const { root } = createParser(textLib.toJSONSchema(), "Text").parse(
+ `root = Text({title: "Recipe", steps: ["Boil", null]})`,
+ );
+ const ctx = { getState: () => undefined, resolveRef: () => null };
+ const errors: OpenUIError[] = [];
+ const el = evaluateElementProps(root!, { ctx, library: textLib, store: null, errors });
+ expect(errors).toEqual([]);
+ expect(el.props.text).toEqual({ title: "Recipe", steps: ["Boil", null] });
+ });
+});
+
+describe("custom actions", () => {
+ const copy = defineAction({
+ name: "CopyToClipboard",
+ description: "Copies text to the clipboard",
+ params: z.object({ text: z.string() }),
+ });
+ const lib = createLibrary({ root: "Button", components: [Button], actions: [copy] });
+ const schema = lib.toJSONSchema();
+ const actionWith = (action: string, state: Record<string, unknown> = {}): any => {
+ const { root } = createParser(schema, "Button").parse(`root = Button("Go", ${action})`);
+ const ctx = {
+ getState: (n: string) => state[n],
+ resolveRef: () => null,
+ actions: schema.actions,
+ };
+ return evaluateElementProps(root!, { ctx, library: lib, store: null }).props.action;
+ };
+ const real = {
+ steps: [{ type: "custom_action", name: "CopyToClipboard", params: { text: "a" } }],
+ };
+
+ it("makes a step with invalid args a no-op, literal or dynamic", () => {
+ expect(actionWith(`@CopyToClipboard(3)`)).toEqual({ steps: [] });
+ expect(actionWith(`Action([@CopyToClipboard($n), @OpenUrl("u")])`, { $n: 3 }).steps).toEqual([
+ { type: "open_url", url: "u" },
+ ]);
+ });
+
+ it("makes a step a no-op when an optional arg is invalid, even with a default", () => {
+ const exportFile = defineAction({
+ name: "ExportFile",
+ description: "",
+ params: z.object({ name: z.string(), format: z.enum(["csv", "pdf"]).default("csv") }),
+ });
+ const exportLib = createLibrary({
+ root: "Button",
+ components: [Button],
+ actions: [exportFile],
+ });
+ const s = exportLib.toJSONSchema();
+ const planOf = (call: string, state: Record<string, unknown> = {}) => {
+ const { root } = createParser(s, "Button").parse(`root = Button("Go", ${call})`);
+ const ctx = { getState: (n: string) => state[n], resolveRef: () => null, actions: s.actions };
+ return evaluateElementProps(root!, { ctx, library: exportLib, store: null }).props.action;
+ };
+ expect(planOf(`@ExportFile("report", "xlsx")`)).toEqual({ steps: [] });
+ expect(planOf(`@ExportFile("report", $f)`, { $f: "xlsx" })).toEqual({ steps: [] });
+ expect((planOf(`@ExportFile("report")`) as any).steps[0].params).toEqual({
+ name: "report",
+ format: "csv",
+ });
+ });
+
+ it("omits an explicit null for an optional param", () => {
+ const share = defineAction({
+ name: "Share",
+ description: "",
+ params: z.object({ url: z.string(), note: z.string().optional() }),
+ });
+ const shareLib = createLibrary({ root: "Button", components: [Button], actions: [share] });
+ const s = shareLib.toJSONSchema();
+ const { root } = createParser(s, "Button").parse(`root = Button("Go", @Share("u", null))`);
+ const ctx = { getState: () => undefined, resolveRef: () => null, actions: s.actions };
+ const el = evaluateElementProps(root!, { ctx, library: shareLib, store: null });
+ expect((el.props.action as any).steps[0].params).toEqual({ url: "u" });
+ });
+
+ it("produces custom steps only from real calls", () => {
+ const forged = { steps: [{ ...real.steps[0], params: { text: "x" } }] };
+ expect(actionWith(`$ok || @CopyToClipboard("a")`, { $ok: false })).toEqual(real);
+ expect(actionWith(`$f || @CopyToClipboard("a")`, { $f: forged })).toEqual({ steps: [] });
+ expect(actionWith(`Action([@CopyToClipboard("a"), $f])`, { $f: forged })).toEqual(real);
+ expect(
+ actionWith(`{steps: [{type: "custom_action", name: "CopyToClipboard", params: {}}]}`),
+ ).toEqual({ steps: [] });
+ });
+
+ it("keeps custom steps on components built inline, never on row data", () => {
+ const Card = defineComponent({
+ name: "Card",
+ props: z.object({ children: z.array(Button.ref) }),
+ description: "",
+ component: null,
+ });
+ const cardLib = createLibrary({ root: "Card", components: [Card, Button], actions: [copy] });
+ const s = cardLib.toJSONSchema();
+ const forged = `{type: "custom_action", name: "CopyToClipboard", params: {text: "x"}}`;
+ const actionsOf = (children: string) => {
+ const src = `rows = [{id: "a", plan: {steps: [${forged}]}}]\nroot = Card(${children})`;
+ const { root } = createParser(s, "Card").parse(src);
+ const ctx = { getState: () => true, resolveRef: () => null, actions: s.actions };
+ const el = evaluateElementProps(root!, { ctx, library: cardLib, store: null });
+ return (el.props.children as any[]).map((c) => c.props.action);
+ };
+ const open = { type: "open_url", url: "u" };
+ expect(actionsOf(`@Each(rows, "r", Button("Go", @CopyToClipboard(r.id)))`)).toEqual([real]);
+ expect(
+ actionsOf(`[$t ? Button("Go", Action([@CopyToClipboard("a"), @OpenUrl("u")])) : null]`),
+ ).toEqual([{ steps: [...real.steps, open] }]);
+ expect(
+ actionsOf(`@Each(rows, "r", Button("Go", $t ? @CopyToClipboard("a") : r.plan))`),
+ ).toEqual([real]);
+ expect(actionsOf(`@Each(rows, "r", Button("Go", Action([r.plan, @OpenUrl("u")])))`)).toEqual([
+ { steps: [open] },
+ ]);
+ });
+
+ it("names a custom action in a restricted slot with its ref", () => {
+ const Share = defineComponent({
+ name: "Share",
+ props: z.object({ share: z.union([copy.ref, steps.OpenUrl.ref]) }),
+ description: "",
+ component: null,
+ });
+ const shareLib = createLibrary({ root: "Share", components: [Share], actions: [copy] });
+ expect(shareLib.prompt()).toContain("Share(share: @CopyToClipboard | @OpenUrl)");
+ expect(shareLib.toJSONSchema().$defs?.CopyToClipboard).toMatchObject({
+ properties: { type: { const: "CopyToClipboard" }, params: { required: ["text"] } },
+ });
+ });
+
+ it("rejects a name taken by a built-in, step, component, or function", () => {
+ const fn = defineFunction({ name: "Fmt", description: "", params: z.object({}), fn: () => 1 });
+ for (const name of ["Sum", "OpenUrl", "Button", "Fmt"]) {
+ const actions = [defineAction({ name, description: "", params: z.object({}) })];
+ expect(() => createLibrary({ components: [Button], functions: [fn], actions })).toThrow(
+ `Action "${name}" collides`,
+ );
+ }
+ });
+
+ it("leaves the prompt byte-identical without actions", () => {
+ const step = "\n- @CopyToClipboard(text: string) — Copies text to the clipboard";
+ const ActionButton = defineComponent({
+ name: "ActionButton",
+ props: z.object({ label: z.string(), action: action() }),
+ description: "",
+ component: null,
+ });
+ const prompt = (actions: (typeof copy)[]) =>
+ createLibrary({ root: "ActionButton", components: [ActionButton], actions }).prompt();
+ expect(prompt([copy])).toContain(step);
+ expect(prompt([copy]).replace(step, "").replace(", @CopyToClipboard)", ")")).toBe(prompt([]));
+ });
+});
diff --git a/packages/lang-core/src/runtime/__tests__/functions.test.ts b/packages/lang-core/src/runtime/__tests__/functions.test.ts
new file mode 100644
index 000000000..131d63239
--- /dev/null
+++ b/packages/lang-core/src/runtime/__tests__/functions.test.ts
@@ -0,0 +1,134 @@
+import { describe, expect, it } from "vitest";
+import { z } from "zod/v4";
+import { createLibrary, defineComponent, defineFunction } from "../../library";
+import { parseExpression } from "../../parser/expressions";
+import { tokenize } from "../../parser/lexer";
+import { createParser, createStreamingParser } from "../../parser/parser";
+import type { ElementNode, OpenUIError } from "../../parser/types";
+import { evaluateElementProps } from "../evaluate-tree";
+import { evaluate } from "../evaluator";
+
+const Text = defineComponent({
+ name: "Text",
+ props: z.object({ value: z.any() }),
+ description: "Shows a value",
+ component: null,
+});
+const fns = [
+ defineFunction({
+ name: "Percent",
+ description: "Formats part / total as a percentage",
+ params: z.object({ part: z.number(), total: z.number().default(100) }),
+ returns: z.string(),
+ fn: ({ part, total }) => `${((part / total) * 100).toFixed(1)}%`,
+ }),
+ defineFunction({
+ name: "Sum2",
+ description: "Sums numbers, with an optional label",
+ params: z.object({ numbers: z.array(z.number()), label: z.string().optional() }),
+ fn: ({ numbers, label }) => `${label ?? ""}${numbers.reduce((a, b) => a + b, 0)}`,
+ }),
+];
+const lib = createLibrary({ root: "Text", components: [Text], functions: fns });
+const schema = lib.toJSONSchema();
+const functions = Object.fromEntries(
+ Object.entries(schema.functions!).map(([name, s]) => [
+ name,
+ { ...s, fn: lib.functions[name]!.fn },
+ ]),
+);
+
+function evalRoot(root: ElementNode, state: Record<string, unknown> = {}) {
+ const errors: OpenUIError[] = [];
+ const ctx = {
+ getState: (n: string) => state[n],
+ resolveRef: () => undefined,
+ functions,
+ };
+ const evaluated = evaluateElementProps(root, { ctx, library: lib, store: null, errors });
+ return { value: evaluated.props["value"], errors: errors.map((e) => e.message) };
+}
+
+function run(source: string, state?: Record<string, unknown>) {
+ const result = createParser(schema, "Text").parse(`root = Text(${source})`);
+ return { ...evalRoot(result.root!, state), parseErrors: result.meta.errors.map((e) => e.code) };
+}
+
+describe("library functions", () => {
+ it("are described in toSpec and toJSONSchema", () => {
+ expect(lib.toSpec().functions!["Percent"]).toEqual({
+ signature: "Percent(part: number, total?: number) → string",
+ description: "Formats part / total as a percentage",
+ });
+ expect(Object.keys(schema.functions!["Percent"]!.params.properties!)).toEqual([
+ "part",
+ "total",
+ ]);
+ });
+
+ it("map args by name, validate literals at parse time, apply defaults", () => {
+ expect(run("@Percent(1, 4)")).toEqual({ value: "25.0%", errors: [], parseErrors: [] });
+ expect(run("@Percent(25)").value).toBe("25.0%");
+ expect(run('@Percent("1", 4)')).toMatchObject({ value: null, parseErrors: ["type-mismatch"] });
+ expect(run("@Sum2([1, 2], 3, 4)")).toMatchObject({
+ value: "3",
+ parseErrors: ["excess-args", "type-mismatch"],
+ });
+ expect(run("@Sum2([1], null)").value).toBe("1");
+ });
+
+ it("validate literal args in Query and Mutation statements at parse time", () => {
+ const errors = createParser(schema, "Text").parse(
+ `root = Text("a")\nq = Query("save", { p: @Sum2([@Percent("bad")]), n: @Percent(3) })\nm = Mutation("save", { p: @Percent("bad") })`,
+ ).meta.errors;
+ expect(errors.map((e) => [e.code, e.statementId])).toEqual([
+ ["type-mismatch", "q"],
+ ["type-mismatch", "m"],
+ ]);
+ });
+
+ it("validate dynamic args at runtime without touching the data", () => {
+ const state = { $n: [1, "x", 2] };
+ expect(run("@Sum2($n)", state)).toMatchObject({ value: "3", parseErrors: [] });
+ expect(state.$n).toEqual([1, "x", 2]);
+ expect(run("@Percent($p)", { $p: "1" }).errors).toEqual([
+ 'Evaluating prop "value" on Text failed: @Percent: field "/part" expects number but got string',
+ ]);
+ // A required arg not set yet (or a query still loading) gives null without an error
+ expect(run("@Percent($p)", {})).toMatchObject({ value: null, errors: [] });
+ });
+
+ it("run on every streamed chunk", () => {
+ const stream = createStreamingParser(schema, "Text");
+ expect(evalRoot(stream.push("root = Text(@Percent(1").root!).value).toBe("1.0%");
+ expect(evalRoot(stream.push("2, 4))").root!).value).toBe("300.0%");
+ });
+
+ it("take positional args from an AST made by parseExpression() alone", () => {
+ const ctx = { getState: () => undefined, resolveRef: () => null, functions };
+ const evalSource = (src: string) => evaluate(parseExpression(tokenize(src)), ctx);
+ expect(evalSource("@Sum([1, 2, 3])")).toBe(6);
+ expect(evalSource('@ToAssistant("hi")')).toMatchObject({ steps: [{ message: "hi" }] });
+ expect(evalSource("@Percent(1, 4)")).toBe("25.0%");
+ });
+
+ it("reject a name taken by a built-in or a component", () => {
+ for (const name of ["Sum", "Text"]) {
+ const fn = defineFunction({ name, description: "", params: z.object({}), fn: () => 1 });
+ expect(() => createLibrary({ components: [Text], functions: [fn] })).toThrow("collides");
+ }
+ });
+
+ it("are listed in the prompt with the generated built-in lines", () => {
+ const line = "@Percent(part: number, total?: number) → string — Formats part / total";
+ const plain = createLibrary({ root: "Text", components: [Text] });
+ expect(lib.prompt({ toolCalls: true })).toContain(
+ "@Sum(numbers: number[]) → number — Sum of numeric array",
+ );
+ expect(lib.prompt()).toContain(`## Built-in Functions\n\n${line}`);
+ expect(plain.prompt({ toolCalls: true })).not.toContain("@Percent");
+ expect(plain.prompt({ toolCalls: true, builtinFunctions: false })).not.toContain(
+ "## Built-in Functions",
+ );
+ });
+});
diff --git a/packages/lang-core/src/runtime/__tests__/store.test.ts b/packages/lang-core/src/runtime/__tests__/store.test.ts
new file mode 100644
index 000000000..531f45dcd
--- /dev/null
+++ b/packages/lang-core/src/runtime/__tests__/store.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest";
+import { createParser, createStreamingParser } from "../../parser";
+import type { LibraryJSONSchema } from "../../parser/types";
+import { createStore } from "../store";
+
+// From an end-to-end chat run (issue #767): a long $ingredients list and a `@Each($dishes` tail.
+const PROGRAM = `root = Col([shopping, copyButton, dinnerCards], 4)
+$ingredients = ["500 g (about 1 lb) ground beef", "12 small tortillas or taco shells", "1 packet taco seasoning (about 28 g / 1 oz)", "1 small head lettuce", "2 medium tomatoes", "1 small onion", "150 g (about 1½ cups) shredded cheddar", "2 avocados", "200 g (about ¾ cup) salsa", "150 g (about ⅔ cup) sour cream", "2 limes"]
+$checked = []
+$dishes = [{name: "Lemon chicken pasta", time: "30 minutes"}, {name: "Chickpea and spinach curry", time: "35 minutes"}]
+shopping = Card([Col(@Each($ingredients, "item", Pressable([Text(item)], @Set($checked, @Toggle($checked, item)), @Includes($checked, item))))])
+copyButton = Button("Copy whole shopping list", @CopyToClipboard(@Join($ingredients, "\\n")))
+dinnerCards = Grid(@Each($dishes, "dish", Card([Title(dish.name), Button("Get recipe", @ToAssistant("Recipe for " + dish.name, {dishName: dish.name}))])))
+`;
+
+const schema = {} as LibraryJSONSchema;
+
+/** Streams PROGRAM in 20-character steps, applying each parse to the store the way the renderers do. */
+function streamInto(store: ReturnType<typeof createStore>, onStep?: (text: string) => void) {
+ const sp = createStreamingParser(schema, "Col");
+ for (let end = 20; end < PROGRAM.length + 20; end += 20) {
+ const text = PROGRAM.slice(0, end);
+ store.initialize(sp.set(text).stateDeclarations, {});
+ onStep?.(text);
+ }
+}
+
+describe("store defaults while streaming", () => {
+ it("ends with the batch-parse state: full values, no half-typed names", () => {
+ const store = createStore();
+ streamInto(store);
+ const batch = createParser(schema, "Col").parse(PROGRAM).stateDeclarations;
+ expect(store.getSnapshot()).toEqual(batch);
+ expect(store.get("$ingredients")).toHaveLength(11);
+ expect(Object.keys(store.getSnapshot()).sort()).toEqual([
+ "$checked",
+ "$dishes",
+ "$ingredients",
+ ]);
+ });
+
+ it("keeps a value the user set mid-stream", () => {
+ const store = createStore();
+ streamInto(store, (text) => {
+ if (text.includes("$checked = []\n") && !(store.get("$checked") as string[] | null)?.length) {
+ store.set("$checked", ["2 limes"]);
+ }
+ });
+ expect(store.get("$checked")).toEqual(["2 limes"]);
+ expect(store.get("$ingredients")).toHaveLength(11);
+ });
+
+ it.each(["", "\n"])("declares a $name that ends the program (trailing %j)", (end) => {
+ const src = `root = Col([Input(email)])\nemail = $email${end}`;
+ const sp = createStreamingParser(schema, "Col");
+ const store = createStore();
+ for (let i = 5; i < src.length; i += 5)
+ store.initialize(sp.set(src.slice(0, i)).stateDeclarations, {});
+ store.initialize(sp.set(src, true).stateDeclarations, {});
+ const batch = createParser(schema, "Col").parse(src).stateDeclarations;
+ expect(batch).toEqual({ $email: null });
+ expect(store.getSnapshot()).toEqual(batch);
+ });
+
+ it("a value restored with pristine: true (@Reset) can still be replaced", () => {
+ const store = createStore();
+ store.initialize({ $title: "Quarterly rev" }, {});
+ store.set("$title", "user edit");
+ store.set("$title", "Quarterly rev", { pristine: true });
+ store.initialize({ $title: "Quarterly revenue" }, {});
+ expect(store.get("$title")).toBe("Quarterly revenue");
+ });
+});
diff --git a/packages/lang-core/src/runtime/evaluate-prop.ts b/packages/lang-core/src/runtime/evaluate-prop.ts
index d1736853e..ec1fc8bf6 100644
--- a/packages/lang-core/src/runtime/evaluate-prop.ts
+++ b/packages/lang-core/src/runtime/evaluate-prop.ts
@@ -16,7 +16,7 @@ import type { ElementNode } from "../parser/types";
import { isElementNode } from "../parser/types";
import { isReactiveSchema } from "../reactive";
import type { EvaluationContext, SchemaContext } from "./evaluator";
-import { evaluate, isReactiveAssign } from "./evaluator";
+import { evaluate, isActionPlan, isReactiveAssign, ownSteps } from "./evaluator";
export interface PropEvalCallbacks {
/** How to recurse into an ElementNode (evaluator vs evaluate-tree differ here). */
@@ -35,6 +35,18 @@ export function evaluatePropCore(
schemaCtx: SchemaContext,
reactiveSchema: unknown | undefined,
callbacks: PropEvalCallbacks,
+): unknown {
+ const result = evaluatePropValue(value, context, schemaCtx, reactiveSchema, callbacks);
+ // Only real calls make custom steps: a plan read from data loses them
+ return isActionPlan(result) ? ownSteps(result) : result;
+}
+
+function evaluatePropValue(
+ value: unknown,
+ context: EvaluationContext,
+ schemaCtx: SchemaContext,
+ reactiveSchema: unknown | undefined,
+ callbacks: PropEvalCallbacks,
): unknown {
if (value == null) return value;
if (typeof value !== "object") return value;
@@ -82,10 +94,9 @@ export function evaluatePropCore(
return callbacks.recurseElement(value as ElementNode);
}
- // ActionPlan / ActionStep — preserve as-is (deferred click-time evaluation)
+ // ActionPlan — preserve as-is (deferred click-time evaluation)
+ if (isActionPlan(value)) return value;
const obj = value as Record<string, unknown>;
- if ("steps" in obj && Array.isArray(obj.steps)) return value;
- if ("type" in obj && "valueAST" in obj) return value;
// Plain data object — recurse if contains nested objects
// NOTE: reactiveSchema is passed through — fixes nested reactive drop bug
diff --git a/packages/lang-core/src/runtime/evaluate-tree.ts b/packages/lang-core/src/runtime/evaluate-tree.ts
index ded4de75d..7463f98eb 100644
--- a/packages/lang-core/src/runtime/evaluate-tree.ts
+++ b/packages/lang-core/src/runtime/evaluate-tree.ts
@@ -8,9 +8,14 @@
*/
import type { Library } from "../library";
-import type { ElementNode, OpenUIError } from "../parser/types";
+import {
+ isElementNode,
+ type ElementNode,
+ type OpenUIError,
+ type ParseResult,
+} from "../parser/types";
import { evaluatePropCore } from "./evaluate-prop";
-import type { EvaluationContext, SchemaContext } from "./evaluator";
+import { evaluate, type EvaluationContext, type SchemaContext } from "./evaluator";
import type { Store } from "./store";
/** Context passed through the evaluation chain — no module-level state. */
@@ -38,28 +43,56 @@ export function evaluateElementProps(el: ElementNode, evalCtx: EvalContext): Ele
const def = evalCtx.library.components[el.typeName];
const evaluated: Record<string, unknown> = {};
- for (const [key, value] of Object.entries(el.props)) {
+ let key = "";
+ const report = (msg: string) => {
+ evalCtx.errors?.push({
+ source: "runtime",
+ code: "runtime-error",
+ component: el.typeName,
+ statementId: el.statementId,
+ message: `Evaluating prop "${key}" on ${el.typeName} failed: ${msg}`,
+ hint: `Check the expression used for prop "${key}"`,
+ });
+ };
+ // Library function calls and actions that fail report why here
+ const propCtx =
+ evalCtx.ctx.functions || evalCtx.ctx.actions
+ ? { ...evalCtx, ctx: { ...evalCtx.ctx, reportError: report } }
+ : evalCtx;
+
+ for (const [propKey, value] of Object.entries(el.props)) {
+ key = propKey;
const propSchema = def?.props?.shape?.[key];
try {
- evaluated[key] = evaluatePropValue(value, evalCtx, schemaCtx, propSchema);
+ evaluated[key] = evaluatePropValue(value, propCtx, schemaCtx, propSchema);
} catch (e) {
// Use raw value as fallback for this prop, collect structured error
evaluated[key] = value;
- const msg = e instanceof Error ? e.message : String(e);
- evalCtx.errors?.push({
- source: "runtime",
- code: "runtime-error",
- component: el.typeName,
- statementId: el.statementId,
- message: `Evaluating prop "${key}" on ${el.typeName} failed: ${msg}`,
- hint: `Check the expression used for prop "${key}"`,
- });
+ report(e instanceof Error ? e.message : String(e));
}
}
return { ...el, props: evaluated };
}
+/** Evaluate `root`, or the component a runtime entry (`rootExpression`) picks; null if none. */
+export function evaluateRoot(
+ result: Pick<ParseResult, "root" | "rootExpression">,
+ evalCtx: EvalContext,
+): ElementNode | null {
+ if (result.root) return evaluateElementProps(result.root, evalCtx);
+ if (!result.rootExpression) return null;
+ const value = evaluate(result.rootExpression, evalCtx.ctx, { library: evalCtx.library });
+ if (isElementNode(value)) return evaluateElementProps(value, evalCtx);
+ evalCtx.errors?.push({
+ source: "runtime",
+ code: "no-root",
+ statementId: "root",
+ message: "root does not evaluate to a component",
+ });
+ return null;
+}
+
/**
* Evaluate a single prop value with schema awareness.
* Delegates to shared evaluatePropCore with evaluate-tree-specific recursion callbacks.
diff --git a/packages/lang-core/src/runtime/evaluator.ts b/packages/lang-core/src/runtime/evaluator.ts
index baf6252e0..bf44174cb 100644
--- a/packages/lang-core/src/runtime/evaluator.ts
+++ b/packages/lang-core/src/runtime/evaluator.ts
@@ -4,10 +4,27 @@
// ─────────────────────────────────────────────────────────────────────────────
import type { ASTNode } from "../parser/ast";
-import { isASTNode } from "../parser/ast";
-import { ACTION_NAMES, ACTION_STEPS, BUILTINS, LAZY_BUILTINS, toNumber } from "../parser/builtins";
-import type { ActionPlan, ActionStep, ElementNode } from "../parser/types";
+import { isASTNode, toLiteralAST } from "../parser/ast";
+import {
+ ACTION_STEPS,
+ BUILTIN_CALLS,
+ BUILTIN_STEPS,
+ BUILTINS,
+ isStep,
+ toNumber,
+} from "../parser/builtins";
+import { nameArgs } from "../parser/materialize";
+import type {
+ ActionPlan,
+ ActionStep,
+ ElementNode,
+ FunctionSchema,
+ JSONSchemaDef,
+ MaterializeCtx,
+ ParamDef,
+} from "../parser/types";
import { isElementNode } from "../parser/types";
+import { getSchemaDefaultValue, INVALID, validateSchemaValue } from "../parser/validation";
import { isReactiveSchema } from "../reactive";
import { evaluatePropCore } from "./evaluate-prop";
@@ -24,6 +41,17 @@ export interface EvaluationContext {
resolveRef(name: string): unknown;
/** Extra scope for $value injection during reactive prop evaluation */
extraScope?: Record<string, unknown>;
+ /** Library functions: `library.toJSONSchema().functions` entries plus each `fn`. */
+ functions?: Record<string, RuntimeFunction>;
+ /** Custom actions: the `library.toJSONSchema().actions` entries. */
+ actions?: Record<string, FunctionSchema>;
+ /** Reports a runtime error, such as a library function call that evaluated to null. */
+ reportError?: (message: string) => void;
+}
+
+/** A library function as the evaluator runs it. */
+export interface RuntimeFunction extends FunctionSchema {
+ fn: (args: any) => unknown;
}
export interface ReactiveAssign {
@@ -74,19 +102,34 @@ export function evaluate(
// ── Component ─────────────────────────────────────────────────────────
case "Comp": {
- // Lazy builtins — control their own evaluation
- if (LAZY_BUILTINS.has(node.name)) {
- return evaluateLazyBuiltin(node.name, node.args, context, schemaCtx);
- }
- // Check shared builtin registry first
+ // Built-ins coerce their args, so they skip validation. Lazy ones get them unevaluated.
const builtin = BUILTINS[node.name];
if (builtin) {
- const args = node.args.map((a) => evaluate(a, context));
- return builtin.fn(...args);
+ if (builtin.lazy) return evaluateLazyBuiltin(node.name, node.args, context, schemaCtx);
+ return builtin.fn!(evaluateArgs(node, context));
}
- // Action calls → evaluate to ActionPlan/ActionStep
- if (ACTION_NAMES.has(node.name)) {
- return evaluateActionCall(node.name, node.args, context);
+ // Built-in steps and Action([...]) → an ActionPlan
+ if (isStep(node.name)) return evaluateActionCall(node, context);
+ const fns = context.functions;
+ if (fns && Object.prototype.hasOwnProperty.call(fns, node.name)) {
+ return callFunction(node.name, fns[node.name]!, node, context);
+ }
+ // Custom actions: a one-step plan; any invalid arg gives an empty plan, a no-op,
+ // even an optional one with a default: @ExportFile("r", "xlsx") must not export csv
+ const acts = context.actions;
+ if (acts && Object.prototype.hasOwnProperty.call(acts, node.name)) {
+ const def = acts[node.name]!;
+ const args = callArgs(node, context, def.params);
+ if (missesRequired(args, def.params)) return { steps: [] };
+ const params = checkValue(args, def.params, node.name, "", context, true);
+ if (params === INVALID) return { steps: [] };
+ const step: ActionStep = {
+ type: "custom_action",
+ name: node.name,
+ params: params as Record<string, unknown>,
+ };
+ customSteps.add(step);
+ return { steps: [step] };
}
// If parser already mapped args→props (via materializeExpr), use named props.
// With schema context: emit ReactiveAssign for StateRef on reactive props.
@@ -284,74 +327,140 @@ function evaluatePropInline(
});
}
-/** Convert a resolved runtime value back to a literal AST node for deferred evaluation. */
-function toLiteralAST(value: unknown): ASTNode {
- if (value === null || value === undefined) return { k: "Null" };
- if (typeof value === "string") return { k: "Str", v: value };
- if (typeof value === "number") return { k: "Num", v: value };
- if (typeof value === "boolean") return { k: "Bool", v: value };
- if (Array.isArray(value)) return { k: "Arr", els: value.map(toLiteralAST) };
- if (typeof value === "object") {
- return {
- k: "Obj",
- entries: Object.entries(value).map(([k, v]) => [k, toLiteralAST(v)] as [string, ASTNode]),
- };
+// @Percent(done, 10) with done = 3 -> {part: 3, total: 10}
+function evaluateArgs(
+ node: ASTNode & { k: "Comp" },
+ context: EvaluationContext,
+ params: ParamDef[] = BUILTIN_CALLS.get(node.name)?.params ?? [],
+): Record<string, unknown> {
+ // The parser names args in mappedProps; an AST from parseExpression() alone is named here
+ const named = node.mappedProps ?? nameArgs(node.args, params);
+ const args: Record<string, unknown> = {};
+ for (const key in named) args[key] = evaluate(named[key]!, context);
+ return args;
+}
+
+/** A library function's or action's args; an explicit null for an optional param is omitted, so its default applies. */
+function callArgs(
+ node: ASTNode & { k: "Comp" },
+ context: EvaluationContext,
+ params: JSONSchemaDef,
+): Record<string, unknown> {
+ const names = Object.keys(params.properties ?? {});
+ const args = evaluateArgs(
+ node,
+ context,
+ names.map((name) => ({ name, required: false })),
+ );
+ for (const key in args) {
+ if (args[key] === null && !params.required?.includes(key)) delete args[key];
}
- return { k: "Null" };
+ return args;
}
-/**
- * Evaluate Action/Run/ToAssistant/OpenUrl Comp nodes into ActionPlan/ActionStep values.
- */
-function evaluateActionCall(
+// returns z.string() but fn gives 5 -> reports "@Percent: ... expects string but got number".
+// strict: any reported error gives INVALID instead of falling back to a default.
+function checkValue(
+ value: unknown,
+ schema: unknown,
name: string,
- args: ASTNode[],
+ path: string,
context: EvaluationContext,
-): ActionPlan | ActionStep | null {
+ strict = false,
+): unknown {
+ const ctx = { errors: [], partial: false } as unknown as MaterializeCtx;
+ const checked = validateSchemaValue(value, schema, name, path, ctx);
+ for (const e of ctx.errors) context.reportError?.(`@${name}: ${e.message}`);
+ return strict && ctx.errors.length > 0 ? INVALID : checked;
+}
+
+// @Percent($p) with $p unset -> null, no error
+function missesRequired(args: Record<string, unknown>, params: RuntimeFunction["params"]): boolean {
+ return !!params.required?.some(
+ (key) => args[key] == null && getSchemaDefaultValue(params.properties?.[key]) === undefined,
+ );
+}
+
+// @Percent(1, 0) where fn throws -> null, reports "@Percent threw: ..."
+function callFunction(
+ name: string,
+ def: RuntimeFunction,
+ node: ASTNode & { k: "Comp" },
+ context: EvaluationContext,
+): unknown {
+ const raw = callArgs(node, context, def.params);
+ if (missesRequired(raw, def.params)) return null;
+ const args = checkValue(raw, def.params, name, "", context);
+ if (args === INVALID) return null;
+ let result: unknown;
+ try {
+ result = def.fn(args);
+ } catch (e) {
+ context.reportError?.(`@${name} threw: ${e instanceof Error ? e.message : String(e)}`);
+ return null;
+ }
+ if (!def.returns) return result;
+ const checked = checkValue(result, def.returns, name, "/returns", context);
+ return checked === INVALID ? null : (checked ?? null);
+}
+
+/** True for an evaluated action plan (`{ steps: [...] }`). */
+export function isActionPlan(value: unknown): value is ActionPlan {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ Array.isArray((value as { steps?: unknown }).steps)
+ );
+}
+
+/** Flatten plans (and stray step objects) into one plan; other values are dropped. */
+function flattenPlans(values: unknown[]): ActionPlan {
+ return ownSteps({
+ steps: values.flatMap((v): ActionStep[] => {
+ if (isActionPlan(v)) return v.steps;
+ return v != null && typeof v === "object" && "type" in v ? [v as ActionStep] : [];
+ }),
+ });
+}
+
+/** The custom steps made by real calls; a custom step read from data is not among them. */
+const customSteps = new WeakSet<ActionStep>();
+
+/** Drops the custom steps no real call made, so data cannot pose as a custom action. */
+export function ownSteps(plan: ActionPlan): ActionPlan {
+ const own = (s: ActionStep | null) => s?.type !== "custom_action" || customSteps.has(s);
+ return plan.steps.every(own) ? plan : { ...plan, steps: plan.steps.filter(own) };
+}
+
+/** A step call is a one-step plan, an invalid step an empty plan; Action([...]) flattens. */
+function evaluateActionCall(node: ASTNode & { k: "Comp" }, context: EvaluationContext): ActionPlan {
+ const { name, args } = node;
+ if (name === "Action") {
+ const list = args.length > 0 ? evaluate(args[0], context) : [];
+ return flattenPlans(Array.isArray(list) ? list : []);
+ }
+ const def = BUILTIN_STEPS[name]!;
+ const step = def.step ? def.step(evaluateArgs(node, context)) : evaluateLazyStep(name, args);
+ return { steps: step ? [step] : [] };
+}
+
+/** The steps whose args are refs, read as AST. */
+function evaluateLazyStep(name: string, args: ASTNode[]): ActionStep | null {
switch (name) {
- case "Action": {
- // Action([step1, step2, ...]) → ActionPlan
- const stepsArg = args.length > 0 ? evaluate(args[0], context) : [];
- const rawSteps = Array.isArray(stepsArg) ? stepsArg : [];
- const steps: ActionStep[] = rawSteps.filter(
- (s): s is ActionStep => s != null && typeof s === "object" && "type" in s,
- );
- return { steps };
- }
case "Run": {
- // Run(runtimeRef) → ActionStep { type: "run", statementId, refType }
- if (args.length === 0) return null;
+ // Run(runtimeRef); an unresolved Ref is invalid
const refNode = args[0];
- if (refNode.k === "RuntimeRef") {
- return { type: ACTION_STEPS.Run, statementId: refNode.n, refType: refNode.refType };
- }
- // Unresolved Ref — skip (filtered out by Action's step array)
- return null;
- }
- case "ToAssistant": {
- // ToAssistant("message") or ToAssistant("message", "context")
- const message = args.length > 0 ? String(evaluate(args[0], context) ?? "") : "";
- const ctx = args.length > 1 ? String(evaluate(args[1], context) ?? "") : undefined;
- return { type: ACTION_STEPS.ToAssistant, message, context: ctx };
- }
- case "OpenUrl": {
- // OpenUrl("url")
- const url = args.length > 0 ? String(evaluate(args[0], context) ?? "") : "";
- return { type: ACTION_STEPS.OpenUrl, url };
+ if (refNode?.k !== "RuntimeRef") return null;
+ return { type: ACTION_STEPS.Run, statementId: refNode.n, refType: refNode.refType };
}
case "Set": {
- // Set($varName, value) → ActionStep { type: "set", target, valueAST }
- // First arg must be a StateRef (the $variable), second arg is the value expression.
- // valueAST is preserved as-is and evaluated at click time by triggerAction.
- // Loop variables (e.g. t.id from Each) are pre-resolved by Each's substituteRef.
- if (args.length < 2) return null;
- const targetNode = args[0];
- if (targetNode.k !== "StateRef") return null;
- return { type: ACTION_STEPS.Set, target: targetNode.n, valueAST: args[1] };
+ // Set($varName, value). valueAST is evaluated at click time by triggerAction;
+ // loop variables (e.g. t.id from Each) are pre-resolved by Each's substituteRef.
+ if (args.length < 2 || args[0].k !== "StateRef") return null;
+ return { type: ACTION_STEPS.Set, target: args[0].n, valueAST: args[1] };
}
case "Reset": {
- // Reset($var1, $var2, ...) → ActionStep { type: "reset", targets: [...] }
- // All args must be StateRef nodes. Restores to declared defaults at runtime.
+ // Reset($var1, $var2, ...) restores declared defaults at runtime.
const targets = args
.filter((a): a is ASTNode & { k: "StateRef" } => a.k === "StateRef")
.map((a) => a.n);
@@ -418,15 +527,9 @@ function substituteRef(node: ASTNode, varName: string, value: unknown): ASTNode
),
};
case "Comp": {
- const result = { ...node, args: node.args.map((a) => substituteRef(a, varName, value)) };
- // Also substitute in mappedProps (added by materializer for catalog components)
- if (node.mappedProps) {
- const subProps: Record<string, ASTNode> = {};
- for (const [k, v] of Object.entries(node.mappedProps)) {
- subProps[k] = substituteRef(v, varName, value);
- }
- (result as any).mappedProps = subProps;
- }
+ const sub = (a: ASTNode) => substituteRef(a, varName, value);
+ const result = { ...node, args: node.args.map(sub) };
+ if (node.mappedProps) result.mappedProps = mapValues(node.mappedProps, sub);
return result;
}
case "Assign":
@@ -436,6 +539,15 @@ function substituteRef(node: ASTNode, varName: string, value: unknown): ASTNode
}
}
+function mapValues(
+ record: Record<string, ASTNode>,
+ fn: (node: ASTNode) => ASTNode,
+): Record<string, ASTNode> {
+ const out: Record<string, ASTNode> = {};
+ for (const key in record) out[key] = fn(record[key]!);
+ return out;
+}
+
/**
* Each(array, varName, template) — evaluate template once per array item.
* varName is user-defined (e.g. `issue`, `ticket`) — no $ prefix collision.
diff --git a/packages/lang-core/src/runtime/index.ts b/packages/lang-core/src/runtime/index.ts
index bfc1e8031..dd567db79 100644
--- a/packages/lang-core/src/runtime/index.ts
+++ b/packages/lang-core/src/runtime/index.ts
@@ -14,7 +14,7 @@ export type {
ToolProvider,
} from "./queryManager";
-export { evaluateElementProps } from "./evaluate-tree";
+export { evaluateElementProps, evaluateRoot } from "./evaluate-tree";
export type { EvalContext } from "./evaluate-tree";
export { resolveStateField } from "./state-field";
diff --git a/packages/lang-core/src/runtime/store.ts b/packages/lang-core/src/runtime/store.ts
index ac05d5dbc..9264170ba 100644
--- a/packages/lang-core/src/runtime/store.ts
+++ b/packages/lang-core/src/runtime/store.ts
@@ -4,7 +4,8 @@
export interface Store {
get(name: string): unknown;
- set(name: string, value: unknown): void;
+ /** `pristine: true` restores a declared default that a later parse may still replace. */
+ set(name: string, value: unknown, options?: { pristine?: boolean }): void;
subscribe(listener: () => void): () => void;
getSnapshot(): Record<string, unknown>;
initialize(defaults: Record<string, unknown>, persisted: Record<string, unknown>): void;
@@ -13,6 +14,8 @@ export interface Store {
export function createStore(): Store {
const state = new Map<string, unknown>();
+ // Keys still holding their declared default; a later parse may replace it.
+ const pristine = new Set<string>();
const listeners = new Set<() => void>();
let snapshot: Record<string, unknown> = {};
@@ -31,7 +34,9 @@ export function createStore(): Store {
return state.get(name);
}
- function set(name: string, value: unknown): void {
+ function set(name: string, value: unknown, options?: { pristine?: boolean }): void {
+ if (options?.pristine) pristine.add(name);
+ else pristine.delete(name);
const existing = state.get(name);
if (Object.is(existing, value)) return;
// Shallow-compare plain objects (form data)
@@ -74,24 +79,36 @@ export function createStore(): Store {
}
function initialize(defaults: Record<string, unknown>, persisted: Record<string, unknown>): void {
- // Apply persisted values (explicit restore) and defaults for NEW keys only.
- // Existing user-modified $binding values are always preserved — never
- // overwrite with defaults, never delete. During streaming, declarations
- // can temporarily disappear; deleting user state here would cause data loss.
+ // Defaults replace a pristine value (e.g. one read from a truncated statement
+ // while streaming). User-set and persisted values are never overwritten, and
+ // keys are never deleted: declarations can briefly disappear while streaming.
+ let changed = false;
for (const key of Object.keys(persisted)) {
- state.set(key, persisted[key]);
+ pristine.delete(key);
+ if (!state.has(key) || !Object.is(state.get(key), persisted[key])) {
+ state.set(key, persisted[key]);
+ changed = true;
+ }
}
for (const key of Object.keys(defaults)) {
if (!state.has(key)) {
state.set(key, defaults[key]);
+ pristine.add(key);
+ changed = true;
+ } else if (pristine.has(key) && !Object.is(state.get(key), defaults[key])) {
+ state.set(key, defaults[key]);
+ changed = true;
}
}
- rebuildSnapshot();
- notify();
+ if (changed) {
+ rebuildSnapshot();
+ notify();
+ }
}
function dispose(): void {
state.clear();
+ pristine.clear();
listeners.clear();
snapshot = {};
}
diff --git a/packages/lang-core/src/signature.ts b/packages/lang-core/src/signature.ts
new file mode 100644
index 000000000..08cee27fe
--- /dev/null
+++ b/packages/lang-core/src/signature.ts
@@ -0,0 +1,251 @@
+import * as z from "zod/v4/core";
+import type { ActionRef } from "./parser/builtins";
+import { isReactiveSchema } from "./reactive";
+
+// Zod introspection and the one prompt signature builder for components,
+// functions and actions.
+
+// ─── Schema ID tagging ─────────────────────────────────────────────────────
+// WeakMap-based naming for schemas. defineComponent tags component schemas
+// automatically. tagSchemaId is exported for non-component schemas
+// (e.g. ActionExpression) that also need friendly names in prompts.
+
+export const schemaIdTags = new WeakMap<object, string>();
+
+/**
+ * Tag a schema with an ID for prompt signatures.
+ * Use for non-component schemas that need friendly type names (e.g. ActionExpression).
+ * This affects prompt output only, not JSON Schema $defs.
+ */
+export function tagSchemaId(schema: object, id: string): void {
+ schemaIdTags.set(schema, id);
+}
+
+// Action refs print as `@Name` in signatures: share?: @CopyToClipboard | @OpenUrl
+const actionRefTags = new WeakMap<object, string>();
+
+// actionRef("OpenUrl", data) -> `$defs.OpenUrl` = data in JSON, `@OpenUrl` in prompt signatures
+export function actionRef(name: string, data: z.$ZodType): ActionRef {
+ actionRefTags.set(data, name);
+ return data as unknown as ActionRef;
+}
+
+// A cloned schema keeps its prompt name: Card's clone still prints as Card, an action ref as @Name
+export function copySchemaTags(from: object, to: object): void {
+ const id = schemaIdTags.get(from);
+ if (id) schemaIdTags.set(to, id);
+ const action = actionRefTags.get(from);
+ if (action) actionRefTags.set(to, action);
+}
+
+// ─── Zod v3 detection ──────────────────────────────────────────────────────
+
+export function assertV4Schema(schema: unknown, componentName: string): void {
+ if (schema != null && typeof schema === "object" && "_def" in schema && !("_zod" in schema)) {
+ throw new Error(
+ `[OpenUI] Component "${componentName}" was defined with a Zod 3 schema. ` +
+ `OpenUI requires Zod 4 schemas. ` +
+ `If you're on [email protected]+, import from "zod/v4" instead of "zod". ` +
+ `See: https://zod.dev/v4/versioning`,
+ );
+ }
+}
+
+// ─── Zod introspection ──────────────────────────────────────────────────────
+
+export function getZodDef(schema: unknown): any {
+ return (schema as any)?._zod?.def;
+}
+
+function getZodType(schema: unknown): string | undefined {
+ return getZodDef(schema)?.type;
+}
+
+function isOptionalType(schema: unknown): boolean {
+ const type = getZodType(schema);
+ return type === "optional" || type === "default" || type === "nullable";
+}
+
+export function unwrap(schema: unknown): unknown {
+ let s = schema;
+ let def = getZodDef(s);
+ while (def?.type === "optional" || def?.type === "default" || def?.type === "nullable") {
+ s = def.innerType;
+ def = getZodDef(s);
+ }
+ return s;
+}
+
+function isArrayType(schema: unknown): boolean {
+ const s = unwrap(schema);
+ return getZodType(s) === "array";
+}
+
+function getArrayInnerType(schema: unknown): unknown | undefined {
+ const s = unwrap(schema);
+ const def = getZodDef(s);
+ if (def?.type === "array") return def.element ?? def.innerType;
+ return undefined;
+}
+
+function getEnumValues(schema: unknown): string[] | undefined {
+ const s = unwrap(schema);
+ const def = getZodDef(s);
+ if (def?.type !== "enum") return undefined;
+ if (Array.isArray(def.values)) return def.values;
+ if (def.entries && typeof def.entries === "object") return Object.keys(def.entries);
+ return undefined;
+}
+
+export type SchemaRegistry = ReturnType<typeof z.registry<{ id: string }>>;
+
+function getSchemaId(schema: unknown, reg?: SchemaRegistry): string | undefined {
+ // Check per-library registry first
+ try {
+ const meta = reg?.get(schema as z.$ZodType) as { id?: string } | undefined;
+ if (meta?.id) return meta.id;
+ } catch {
+ // not registered — fall through
+ }
+ // Fallback: WeakMap tags from defineComponent / tagSchemaId
+ if (typeof schema === "object" && schema !== null) {
+ return schemaIdTags.get(schema);
+ }
+ return undefined;
+}
+
+export function getUnionOptions(schema: unknown): unknown[] | undefined {
+ const def = getZodDef(schema);
+ if (def?.type === "union" && Array.isArray(def.options)) return def.options;
+ return undefined;
+}
+
+function getObjectShape(schema: unknown): Record<string, unknown> | undefined {
+ const def = getZodDef(schema);
+ if (def?.type === "object" && def.shape && typeof def.shape === "object")
+ return def.shape as Record<string, unknown>;
+ return undefined;
+}
+
+/**
+ * Resolve the type annotation for a schema field.
+ * Returns a human-readable type string for the schema.
+ * If the schema is marked reactive(), prefixes with "$binding<...>".
+ */
+function resolveTypeAnnotation(schema: unknown, reg?: SchemaRegistry): string | undefined {
+ const isReactive = isReactiveSchema(schema);
+ const inner = unwrap(schema);
+
+ const baseType = resolveBaseType(inner, reg);
+ if (!baseType) return undefined;
+ return isReactive ? `$binding<${baseType}>` : baseType;
+}
+
+function resolveBaseType(inner: unknown, reg?: SchemaRegistry): string | undefined {
+ const actionRef = typeof inner === "object" && inner !== null && actionRefTags.get(inner);
+ if (actionRef) return `@${actionRef}`;
+ const directId = getSchemaId(inner, reg);
+ if (directId) return directId;
+
+ const unionOpts = getUnionOptions(inner);
+ if (unionOpts) {
+ const resolved = unionOpts.map((o) => resolveTypeAnnotation(o, reg));
+ const names = resolved.filter(Boolean) as string[];
+ if (names.length > 0) return names.join(" | ");
+ }
+
+ if (isArrayType(inner)) {
+ const arrayInner = getArrayInnerType(inner);
+ if (!arrayInner) return undefined;
+ const innerType = resolveTypeAnnotation(arrayInner, reg);
+ if (innerType) {
+ const isUnion = getUnionOptions(unwrap(arrayInner)) !== undefined;
+ return isUnion ? `(${innerType})[]` : `${innerType}[]`;
+ }
+ return undefined;
+ }
+
+ const zodType = getZodType(inner);
+ if (zodType === "string") return "string";
+ if (zodType === "number") return "number";
+ if (zodType === "boolean") return "boolean";
+ if (zodType === "any") return "any";
+
+ if (zodType === "record") {
+ const def = getZodDef(inner);
+ const keyType = resolveTypeAnnotation(def?.keyType, reg) ?? "string";
+ const valueType = resolveTypeAnnotation(def?.valueType, reg) ?? "any";
+ return `Record<${keyType}, ${valueType}>`;
+ }
+
+ const enumVals = getEnumValues(inner);
+ if (enumVals) return enumVals.map((v) => `"${v}"`).join(" | ");
+
+ if (zodType === "literal") {
+ const vals = getZodDef(inner)?.values;
+ if (Array.isArray(vals) && vals.length === 1) {
+ const v = vals[0];
+ return typeof v === "string" ? `"${v}"` : String(v);
+ }
+ }
+
+ const shape = getObjectShape(inner);
+ if (shape) {
+ const fields = Object.entries(shape).map(([name, fieldSchema]) => {
+ const opt = isOptionalType(fieldSchema) ? "?" : "";
+ const fieldType = resolveTypeAnnotation(fieldSchema as z.$ZodType, reg);
+ return fieldType ? `${name}${opt}: ${fieldType}` : `${name}${opt}`;
+ });
+ return `{${fields.join(", ")}}`;
+ }
+
+ // Fallback for unrecognized Zod types (z.tuple, z.date, etc.)
+ // "any" is safer than undefined — the LLM sees `param: any` instead of bare `param`
+ return "any";
+}
+
+// ─── Field analysis & signature generation ──────────────────────────────────
+
+interface FieldInfo {
+ name: string;
+ isOptional: boolean;
+ isArray: boolean;
+ typeAnnotation?: string;
+}
+
+function analyzeFields(shape: Record<string, z.$ZodType>, reg?: SchemaRegistry): FieldInfo[] {
+ return Object.entries(shape).map(([name, schema]) => ({
+ name,
+ isOptional: isOptionalType(schema),
+ isArray: isArrayType(schema),
+ typeAnnotation: resolveTypeAnnotation(schema, reg),
+ }));
+}
+
+export function buildSignature(componentName: string, fields: FieldInfo[]): string {
+ const params = fields.map((f) => {
+ if (f.typeAnnotation) {
+ return f.isOptional ? `${f.name}?: ${f.typeAnnotation}` : `${f.name}: ${f.typeAnnotation}`;
+ }
+ if (f.isArray) {
+ return f.isOptional ? `[${f.name}]?` : `[${f.name}]`;
+ }
+ return f.isOptional ? `${f.name}?` : f.name;
+ });
+ return `${componentName}(${params.join(", ")})`;
+}
+
+/**
+ * Prompt signature of a component, function or action: `Name(a: T, b?: U)`,
+ * plus ` → R` when it declares a return type. Key order is the positional order.
+ */
+export function schemaSignature(
+ name: string,
+ params: z.$ZodObject,
+ returns?: z.$ZodType,
+ reg?: SchemaRegistry,
+): string {
+ const signature = buildSignature(name, analyzeFields(params._zod.def.shape, reg));
+ const type = returns && resolveTypeAnnotation(returns, reg);
+ return type ? `${signature} → ${type}` : signature;
+}
diff --git a/packages/lang-core/src/telemetry/runtime.ts b/packages/lang-core/src/telemetry/runtime.ts
index dde4b3853..c46ab069c 100644
--- a/packages/lang-core/src/telemetry/runtime.ts
+++ b/packages/lang-core/src/telemetry/runtime.ts
@@ -471,12 +471,14 @@ function getValidationErrorCounts(
| "validation_error_count"
> {
const counts: Record<ValidationErrorCode, number> = {
- "type-mismatch": 0,
"unknown-component": 0,
"missing-required": 0,
"null-required": 0,
"inline-reserved": 0,
"excess-args": 0,
+ "type-mismatch": 0,
+ "unknown-function": 0,
+ "no-root": 0,
};
for (const error of result.meta.errors) counts[error.code] += 1;
diff --git a/packages/react-email/package.json b/packages/react-email/package.json
index 78e6874ee..eb49a7065 100644
--- a/packages/react-email/package.json
+++ b/packages/react-email/package.json
@@ -42,7 +42,7 @@
"@react-email/components": "^0.0.41"
},
"peerDependencies": {
- "@openuidev/react-lang": ">=0.3.0 <0.5.0",
+ "@openuidev/react-lang": ">=1.0.0 <2.0.0",
"react": "catalog:",
"react-dom": "catalog:",
"zod": "catalog:"
diff --git a/packages/react-lang/package.json b/packages/react-lang/package.json
index 08ac0508e..6560be60b 100644
--- a/packages/react-lang/package.json
+++ b/packages/react-lang/package.json
@@ -53,7 +53,7 @@
"check:attw": "attw --pack .",
"prepare": "pnpm run build",
"prepublishOnly": "pnpm run check:publint && pnpm run check:attw",
- "ci": "pnpm run lint:check && pnpm run format:check"
+ "ci": "pnpm run lint:check && pnpm run format:check && pnpm run test && tsc -p tsconfig.test.json --noEmit"
},
"keywords": [
"openui",
diff --git a/packages/react-lang/src/Renderer.entry.test.tsx b/packages/react-lang/src/Renderer.entry.test.tsx
new file mode 100644
index 000000000..93a46e24c
--- /dev/null
+++ b/packages/react-lang/src/Renderer.entry.test.tsx
@@ -0,0 +1,48 @@
+// @vitest-environment jsdom
+import type { OpenUIError } from "@openuidev/lang-core";
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it } from "vitest";
+import { z } from "zod/v4";
+import { createLibrary, defineComponent } from "./library";
+import { Renderer } from "./Renderer";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const Card = defineComponent({
+ name: "Card",
+ props: z.object({ children: z.array(z.any()) }),
+ description: "Card",
+ component: ({ props, renderNode }) =>
+ createElement("section", null, renderNode(props.children) as never),
+});
+const Title = defineComponent({
+ name: "Title",
+ props: z.object({ text: z.string() }),
+ description: "Title",
+ component: ({ props }) => createElement("h1", null, props.text),
+});
+const library = createLibrary({ root: "Card", components: [Card, Title] });
+
+function render(response: string) {
+ const errors: OpenUIError[][] = [];
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ act(() =>
+ root.render(createElement(Renderer, { response, library, onError: (e) => errors.push(e) })),
+ );
+ const text = container.textContent;
+ act(() => root.unmount());
+ return { codes: (errors.at(-1) ?? []).map((e) => e.code), text };
+}
+
+it("reports no-root instead of parse-failed, and renders a ternary entry", () => {
+ expect(render('title = Title("Orders")')).toEqual({
+ codes: ["no-root"],
+ text: "",
+ });
+ expect(render('$wide = false\nroot = $wide ? a : b\na = Card([])\nb = Title("narrow")')).toEqual({
+ codes: [],
+ text: "narrow",
+ });
+});
diff --git a/packages/react-lang/src/Renderer.test.tsx b/packages/react-lang/src/Renderer.test.tsx
new file mode 100644
index 000000000..a901cbed1
--- /dev/null
+++ b/packages/react-lang/src/Renderer.test.tsx
@@ -0,0 +1,48 @@
+// @vitest-environment jsdom
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it } from "vitest";
+import { z } from "zod/v4";
+import { FormNameContext } from "./context";
+import { useStateField } from "./hooks/useStateField";
+import { createLibrary, defineComponent } from "./library";
+import { Renderer } from "./Renderer";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const Field = defineComponent({
+ name: "Field",
+ description: "Field",
+ props: z.object({ name: z.string() }),
+ component: ({ props }) => {
+ const field = useStateField<string>(props.name);
+ return <button onClick={() => field.setValue("typed")}>{field.value ?? ""}</button>;
+ },
+});
+
+const Form = defineComponent({
+ name: "Form",
+ description: "Form",
+ props: z.object({ name: z.string(), fields: z.array(Field.ref) }),
+ component: ({ props, renderNode }) => (
+ <FormNameContext.Provider value={props.name}>
+ {renderNode(props.fields)}
+ </FormNameContext.Provider>
+ ),
+});
+
+const library = createLibrary({ components: [Form, Field], root: "Form" });
+
+it("shows field input in a program without dynamic props", async () => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ await act(async () =>
+ root.render(
+ <Renderer library={library} response={'root = Form("c", [e])\ne = Field("email")'} />,
+ ),
+ );
+ const button = container.querySelector("button")!;
+ await act(async () => button.dispatchEvent(new MouseEvent("click", { bubbles: true })));
+ expect(button.textContent).toBe("typed");
+ await act(async () => root.unmount());
+});
diff --git a/packages/react-lang/src/Renderer.tsx b/packages/react-lang/src/Renderer.tsx
index 5dd5e4a3c..a08dc7462 100644
--- a/packages/react-lang/src/Renderer.tsx
+++ b/packages/react-lang/src/Renderer.tsx
@@ -1,6 +1,7 @@
import type {
ActionEvent,
ElementNode,
+ LibraryActionEvent,
McpClientLike,
OpenUIError,
ParseResult,
@@ -29,15 +30,15 @@ export interface RendererQueryState {
isRetrying: boolean;
}
-export interface RendererProps {
- /** OpenUI Lang code or the complete Cloud response bundle. */
+export interface RendererProps<L extends Library = Library> {
+ /** Raw response: openui-lang code, or a stored message with protocol markers (see buildMessage). */
response: string | null;
/** Component library from createLibrary(). */
- library: Library;
+ library: L;
/** Whether the LLM is still streaming (form interactions disabled during streaming). */
isStreaming?: boolean;
- /** Callback when a component triggers an action. */
- onAction?: (event: ActionEvent) => void;
+ /** Callback when a component triggers an action. Typed by the library's custom actions. */
+ onAction?: (event: LibraryActionEvent<L>) => void;
/**
* Called whenever a form field value changes. Receives the raw form state map.
* The consumer decides how to persist this (e.g. embed in message, store separately).
@@ -67,6 +68,7 @@ export interface RendererProps {
* Includes generation errors (unknown components, missing required props)
* and tool execution failures. Retry data-source failures instead of treating
* every query error as a reason to regenerate the program.
+ * Can include warnings (`severity: "warning"`) for programs that still render.
* Called with [] when all errors are resolved.
*/
onError?: (errors: OpenUIError[]) => void;
@@ -219,7 +221,7 @@ const DefaultQueryLoader = () => (
/>
);
-function RendererRoot({
+function RendererRoot<L extends Library = Library>({
response,
library,
isStreaming = false,
@@ -232,7 +234,7 @@ function RendererRoot({
children,
onError,
publishObservability,
-}: RendererProps) {
+}: RendererProps<L>) {
useInsertionEffect(() => {
ensureLoadingStyle();
}, []);
@@ -274,7 +276,8 @@ function RendererRoot({
response,
library,
isStreaming,
- onAction,
+ // The hook builds plain ActionEvents; LibraryActionEvent<L> is the same shape, narrowed.
+ onAction: onAction as ((event: ActionEvent) => void) | undefined,
onStateUpdate,
initialState,
toolProvider: resolvedToolProvider,
@@ -401,7 +404,7 @@ function DefaultRendererContent() {
);
}
-function DefaultRenderer({ children, ...props }: RendererProps) {
+function DefaultRenderer<L extends Library = Library>({ children, ...props }: RendererProps<L>) {
return (
<RendererRoot {...props}>
{children === undefined ? <DefaultRendererContent /> : children}
diff --git a/packages/react-lang/src/__tests__/Renderer.message.test.tsx b/packages/react-lang/src/__tests__/Renderer.message.test.tsx
new file mode 100644
index 000000000..1e799dddc
--- /dev/null
+++ b/packages/react-lang/src/__tests__/Renderer.message.test.tsx
@@ -0,0 +1,25 @@
+// @vitest-environment jsdom
+import { buildMessage } from "@openuidev/lang-core";
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it } from "vitest";
+import { z } from "zod/v4";
+import { createLibrary, defineComponent } from "../library";
+import { Renderer } from "../Renderer";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const Text = defineComponent({
+ name: "Text",
+ props: z.object({ value: z.string() }),
+ description: "Text",
+ component: ({ props }) => createElement("p", null, props.value),
+});
+const library = createLibrary({ root: "Text", components: [Text] });
+
+it("renders the content of a stored message", () => {
+ const response = buildMessage({ content: 'root = Text("hi")', context: [{}], end: true });
+ const el = document.createElement("div");
+ act(() => createRoot(el).render(createElement(Renderer, { response, library })));
+ expect(el.textContent).toBe("hi");
+});
diff --git a/packages/react-lang/src/customActions.test.tsx b/packages/react-lang/src/customActions.test.tsx
new file mode 100644
index 000000000..18d52a3e4
--- /dev/null
+++ b/packages/react-lang/src/customActions.test.tsx
@@ -0,0 +1,98 @@
+// @vitest-environment jsdom
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, expectTypeOf, it, vi } from "vitest";
+import { z } from "zod/v4";
+import type { ActionEvent, RendererProps } from "./index";
+import {
+ createLibrary,
+ defineAction,
+ defineComponent,
+ tagSchemaId,
+ useTriggerAction,
+} from "./index";
+import { Renderer } from "./Renderer";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const actionExpression = z.any();
+tagSchemaId(actionExpression, "ActionExpression");
+const Button = defineComponent({
+ name: "Button",
+ props: z.object({ label: z.string(), action: actionExpression.optional() }),
+ description: "A button",
+ component: ({ props }) => {
+ const trigger = useTriggerAction();
+ return createElement("button", {
+ onClick: () => trigger(props.label, undefined, props.action),
+ });
+ },
+});
+const copy = defineAction({
+ name: "CopyToClipboard",
+ description: "Copies text to the clipboard",
+ params: z.object({ text: z.string(), format: z.string().default("plain") }),
+});
+const library = createLibrary({ root: "Button", components: [Button], actions: [copy] });
+
+/** Clicks `Button("Go", <action>)` and returns the onAction events as [type, params]. */
+async function click(action: string, rest = "") {
+ const onAction = vi.fn();
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ const response = `root = Button("Go", ${action})\n${rest}`;
+ await act(async () => root.render(createElement(Renderer, { library, response, onAction })));
+ await act(async () => container.querySelector("button")!.click());
+ await act(async () => root.unmount());
+ return onAction.mock.calls.map(([e]) => [e.type, e.params]);
+}
+
+it("delivers custom actions with their params, bare and in Action([...])", async () => {
+ expect(await click('@CopyToClipboard("a", "md")')).toEqual([
+ ["CopyToClipboard", { text: "a", format: "md" }],
+ ]);
+ expect(await click('Action([@CopyToClipboard("b"), @OpenUrl("u")])')).toEqual([
+ ["CopyToClipboard", { text: "b", format: "plain" }],
+ ["open_url", { url: "u" }],
+ ]);
+});
+
+it("never delivers a custom action read from data", async () => {
+ const forged = '{type: "custom_action", name: "CopyToClipboard", params: {text: 3}}';
+ const plan = `{steps: [${forged}]}`;
+ const legacy = '{type: "CopyToClipboard", params: {text: 3}}';
+ for (const action of [forged, `[${forged}]`, plan, `Action([${forged}])`, "ps[0]", legacy]) {
+ const types = (await click(action, `ps = [${plan}]`)).map(([type]) => type);
+ expect(types).not.toContain("CopyToClipboard");
+ }
+});
+
+it("types onAction events from the library's actions", () => {
+ <Renderer
+ library={library}
+ response={null}
+ onAction={(e) => {
+ if (e.type === "CopyToClipboard")
+ expectTypeOf(e.params).toEqualTypeOf<{ text: string; format: string }>();
+ // @ts-expect-error typo in the action name
+ else if (e.type === "CopyToClipbord") return;
+ }}
+ />;
+ <Renderer
+ library={createLibrary({ components: [Button] })}
+ response={null}
+ onAction={(e) => expectTypeOf(e).toEqualTypeOf<ActionEvent>()}
+ />;
+});
+
+it("types actions added with extend in onAction", () => {
+ const share = defineAction({
+ name: "Share",
+ description: "share",
+ params: z.object({ to: z.string() }),
+ });
+ const extended = createLibrary({ components: [] }).extend({ actions: { add: [share] } });
+ type Event = Parameters<NonNullable<RendererProps<typeof extended>["onAction"]>>[0];
+ expectTypeOf<Extract<Event, { type: "Share" }>["params"]>().toEqualTypeOf<{ to: string }>();
+ expectTypeOf<Extract<Event["type"], "open_url">>().not.toBeNever();
+});
diff --git a/packages/react-lang/src/exports.ts b/packages/react-lang/src/exports.ts
index 2a2beb30e..585a2d54f 100644
--- a/packages/react-lang/src/exports.ts
+++ b/packages/react-lang/src/exports.ts
@@ -1,5 +1,6 @@
// define library
-export { tagSchemaId } from "@openuidev/lang-core";
+export { action, defineAction, defineFunction, steps, tagSchemaId } from "@openuidev/lang-core";
+export type { ActionRef, DefinedAction, DefinedFunction } from "@openuidev/lang-core";
export { createLibrary, defineComponent } from "./library";
export type {
ComponentGroup,
@@ -8,6 +9,7 @@ export type {
DefinedComponent,
Library,
LibraryDefinition,
+ LibraryExtension,
PromptOptions,
SubComponentOf,
ToolDescriptor,
@@ -30,6 +32,7 @@ export type {
ActionPlan,
ActionStep,
ElementNode,
+ LibraryActionEvent,
OpenUIError,
ParseResult,
} from "@openuidev/lang-core";
@@ -37,6 +40,10 @@ export type {
// openui-lang parser (server-side use)
export { createParser, createStreamingParser } from "@openuidev/lang-core";
+// Message protocol: marker lines around a stored response
+export { buildMessage, parseMessage } from "@openuidev/lang-core";
+export type { BuildMessageInput, ParseMessageOptions, ParsedMessage } from "@openuidev/lang-core";
+
// Standalone prompt generation (no Zod deps — usable on backend)
export { generatePrompt, generateSystemPrompt } from "@openuidev/lang-core";
export type {
diff --git a/packages/react-lang/src/hooks/__tests__/actions.test.tsx b/packages/react-lang/src/hooks/__tests__/actions.test.tsx
new file mode 100644
index 000000000..1e19dc63b
--- /dev/null
+++ b/packages/react-lang/src/hooks/__tests__/actions.test.tsx
@@ -0,0 +1,51 @@
+// @vitest-environment jsdom
+import { action, type ActionEvent } from "@openuidev/lang-core";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it } from "vitest";
+import { z } from "zod/v4";
+import { useTriggerAction } from "../../context";
+import { createLibrary, defineComponent } from "../../library";
+import { Renderer } from "../../Renderer";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+it("delivers bare and Action([...]) steps, with the @ToAssistant context", async () => {
+ const clicks = new Map<string, () => void | Promise<void>>();
+ const Btn = defineComponent({
+ name: "Btn",
+ description: "",
+ props: z.object({ label: z.string(), action: action().optional() }),
+ component: ({ props }) => {
+ const trigger = useTriggerAction();
+ clicks.set(props.label, () => trigger(props.label, undefined, props.action as any));
+ return null;
+ },
+ });
+ const Stack = defineComponent({
+ name: "Stack",
+ description: "",
+ props: z.object({ children: z.array(z.any()) }),
+ component: ({ props, renderNode }) => <>{renderNode(props.children)}</>,
+ });
+ const library = createLibrary({ components: [Stack, Btn], root: "Stack" });
+ const response = [
+ `root = Stack([a, b])`,
+ `a = Btn("a", @ToAssistant("A", { ticket: "T-42" }))`,
+ `b = Btn("b", Action([@OpenUrl("https://x.test"), @ToAssistant("B", 0)]))`,
+ ].join("\n");
+ const events: ActionEvent[] = [];
+ const root = createRoot(document.createElement("div"));
+ act(() => {
+ root.render(
+ <Renderer library={library} response={response} onAction={(e) => events.push(e)} />,
+ );
+ });
+ for (const click of [...clicks.values()]) await act(click);
+ act(() => root.unmount());
+ expect(events.map((e) => [e.type, e.humanFriendlyMessage, e.params])).toEqual([
+ ["continue_conversation", "A", { context: { ticket: "T-42" } }],
+ ["open_url", "", { url: "https://x.test" }],
+ ["continue_conversation", "B", { context: 0 }],
+ ]);
+});
diff --git a/packages/react-lang/src/hooks/__tests__/formStatePerStep.test.tsx b/packages/react-lang/src/hooks/__tests__/formStatePerStep.test.tsx
new file mode 100644
index 000000000..6e6a264ef
--- /dev/null
+++ b/packages/react-lang/src/hooks/__tests__/formStatePerStep.test.tsx
@@ -0,0 +1,68 @@
+// @vitest-environment jsdom
+import type { ActionEvent } from "@openuidev/lang-core";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it } from "vitest";
+import { z } from "zod/v4";
+import { useTriggerAction } from "../../context";
+import { createLibrary, defineComponent } from "../../library";
+import { Renderer } from "../../Renderer";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+/** Renders `root = Stack([b])`, clicks the one `Btn`, and returns the action events. */
+async function clickOnce(statements: string[]): Promise<ActionEvent[]> {
+ let click: () => void | Promise<void> = () => {};
+ const Btn = defineComponent({
+ name: "Btn",
+ description: "",
+ props: z.object({ label: z.string(), action: z.any().optional() }),
+ component: ({ props }) => {
+ const trigger = useTriggerAction();
+ click = () => trigger(props.label as string, undefined, props.action as never);
+ return <button>{props.label as string}</button>;
+ },
+ });
+ const Stack = defineComponent({
+ name: "Stack",
+ description: "",
+ props: z.object({ children: z.array(z.any()) }),
+ component: ({ props, renderNode }) => <div>{renderNode(props.children)}</div>,
+ });
+ const library = createLibrary({ components: [Stack, Btn], root: "Stack" });
+ const events: ActionEvent[] = [];
+ const root = createRoot(document.createElement("div"));
+ const response = [`root = Stack([b])`, ...statements].join("\n");
+ act(() => {
+ root.render(
+ <Renderer
+ library={library}
+ response={response}
+ isStreaming={false}
+ onAction={(e) => events.push(e)}
+ />,
+ );
+ });
+ await act(() => click());
+ act(() => root.unmount());
+ return events;
+}
+
+describe("form state is read when each step runs", () => {
+ it("an earlier @Set in the same plan is visible in the event's form state", async () => {
+ const events = await clickOnce([
+ `$x = 1`,
+ `b = Btn("go", Action([@Set($x, 2), @ToAssistant("m")]))`,
+ ]);
+ expect(events).toHaveLength(1);
+ expect(events[0].formState).toMatchObject({ $x: 2 });
+ });
+
+ it("each event in a plan carries the state as of its own step", async () => {
+ const events = await clickOnce([
+ `$x = 1`,
+ `b = Btn("go", Action([@ToAssistant("first"), @Set($x, 2), @ToAssistant("second")]))`,
+ ]);
+ expect(events.map((e) => (e.formState as Record<string, unknown>).$x)).toEqual([1, 2]);
+ });
+});
diff --git a/packages/react-lang/src/hooks/__tests__/truncatedDefaultRoundTrip.test.tsx b/packages/react-lang/src/hooks/__tests__/truncatedDefaultRoundTrip.test.tsx
new file mode 100644
index 000000000..2ce48262d
--- /dev/null
+++ b/packages/react-lang/src/hooks/__tests__/truncatedDefaultRoundTrip.test.tsx
@@ -0,0 +1,51 @@
+// @vitest-environment jsdom
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it } from "vitest";
+import { z } from "zod/v4";
+import { createLibrary, defineComponent } from "../../library";
+import { Renderer } from "../../Renderer";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("truncated default with onStateUpdate fed back as initialState", () => {
+ it("the full statement still replaces the truncated default", () => {
+ const Text = defineComponent({
+ name: "Text",
+ description: "",
+ props: z.object({ text: z.any() }),
+ component: ({ props }) => <span>{String(props.text)}</span>,
+ });
+ const Stack = defineComponent({
+ name: "Stack",
+ description: "",
+ props: z.object({ children: z.array(z.any()) }),
+ component: ({ props, renderNode }) => <div>{renderNode(props.children)}</div>,
+ });
+ const library = createLibrary({ components: [Stack, Text], root: "Stack" });
+
+ // The reference chat persists every onStateUpdate and passes it back as initialState.
+ let persisted: Record<string, unknown> | undefined;
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ const render = (response: string) =>
+ act(() => {
+ root.render(
+ <Renderer
+ library={library}
+ response={response}
+ isStreaming={true}
+ onStateUpdate={(s) => (persisted = s)}
+ initialState={persisted}
+ />,
+ );
+ });
+
+ render(`root = Stack([Text($title)])\n`);
+ render(`root = Stack([Text($title)])\n$title = "Quarterly rev`);
+ render(`root = Stack([Text($title)])\n$title = "Quarterly rev`);
+ render(`root = Stack([Text($title)])\n$title = "Quarterly revenue"\n`);
+ expect(container.textContent).toBe("Quarterly revenue");
+ act(() => root.unmount());
+ });
+});
diff --git a/packages/react-lang/src/hooks/useOpenUIErrors.ts b/packages/react-lang/src/hooks/useOpenUIErrors.ts
index e51052663..10293f791 100644
--- a/packages/react-lang/src/hooks/useOpenUIErrors.ts
+++ b/packages/react-lang/src/hooks/useOpenUIErrors.ts
@@ -65,13 +65,12 @@ export function useOpenUIErrors({
errors.push(parseExceptionRef.current);
}
- if (response && !result?.root && !parseExceptionRef.current) {
+ // A missing or unusable entry is reported by the parser as `no-root`.
+ if (response && !result?.meta.statementCount && !parseExceptionRef.current) {
errors.push({
source: "parser",
code: "parse-failed",
- message: result
- ? "Code parsed but produced no renderable root component"
- : "Response could not be parsed as valid openui-lang",
+ message: "Response could not be parsed as valid openui-lang",
hint: `The entire response must be valid openui-lang code starting with root = ${library.root ?? "Root"}(...)`,
});
}
diff --git a/packages/react-lang/src/hooks/useOpenUIState.ts b/packages/react-lang/src/hooks/useOpenUIState.ts
index 7ff171c01..528cb0bc2 100644
--- a/packages/react-lang/src/hooks/useOpenUIState.ts
+++ b/packages/react-lang/src/hooks/useOpenUIState.ts
@@ -5,7 +5,7 @@ import {
createStore,
createStreamingParser,
evaluate,
- evaluateElementProps,
+ evaluateRoot,
type ActionEvent,
type ActionPlan,
type EvalContext,
@@ -39,6 +39,7 @@ function unwrapFieldValue(v: unknown): unknown {
}
export interface UseOpenUIStateOptions {
+ /** Raw response: openui-lang code, or a stored message with protocol markers. */
response: string | null;
library: Library;
isStreaming: boolean;
@@ -74,7 +75,7 @@ export interface OpenUIState {
*/
export function useOpenUIState(
{
- response,
+ response: raw,
library,
isStreaming,
onAction,
@@ -86,7 +87,8 @@ export function useOpenUIState(
}: UseOpenUIStateOptions,
renderDeep: (value: unknown) => React.ReactNode,
): OpenUIState {
- const bundle = useMemo(() => parseResponseBundle(response, isStreaming), [response, isStreaming]);
+ // Strip protocol markers and read Cloud scripts; plain responses pass through unchanged.
+ const bundle = useMemo(() => parseResponseBundle(raw, isStreaming), [raw, isStreaming]);
const blocked = isStreaming || !bundle.complete || !!bundle.error;
// Bare DSL keeps its existing manager, cached results and imperative actions while streaming.
const bundleBlocked = bundle.isBundle && blocked;
@@ -102,7 +104,20 @@ export function useOpenUIState(
const scriptNames = settledScripts.current.names;
// ─── Streaming parser (incremental — caches completed statements) ───
- const sp = useMemo(() => createStreamingParser(library.toJSONSchema(), library.root), [library]);
+ const schema = useMemo(() => library.toJSONSchema(), [library]);
+ const sp = useMemo(() => createStreamingParser(schema, library.root), [schema, library.root]);
+ // Library functions: the schema's entries plus each `fn`, for the evaluator
+ const functions = useMemo(
+ () =>
+ Object.fromEntries(
+ Object.entries(schema.functions ?? {}).flatMap(([name, s]) => {
+ // A hand-built library may list a function in its schema without an implementation
+ const fn = library.functions?.[name]?.fn;
+ return fn ? [[name, { ...s, fn }]] : [];
+ }),
+ ),
+ [schema, library.functions],
+ );
// ─── Parse result ───
const parseExceptionRef = useRef<OpenUIError | null>(null);
@@ -112,7 +127,7 @@ export function useOpenUIState(
: null;
if (!bundle.program) return null;
try {
- return sp.set(bundle.program);
+ return sp.set(bundle.program, !isStreaming);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
parseExceptionRef.current = {
@@ -123,7 +138,7 @@ export function useOpenUIState(
};
return null;
}
- }, [sp, bundle.program, bundle.error]);
+ }, [sp, bundle.program, bundle.error, isStreaming]);
// ─── Store (holds everything: $bindings + form fields) ───
const store = useMemo<Store>(() => createStore(), []);
@@ -140,6 +155,9 @@ export function useOpenUIState(
}, [queryManager]);
// ─── Initialize Store ───
+ // Declared defaults are not a user change, so they do not fire onStateUpdate: a saved
+ // default read from a half-streamed statement would come back as initialState and stick.
+ const initializingRef = useRef(false);
const storeInitKeyRef = useRef<unknown>(Symbol());
useEffect(() => {
if (!result?.stateDeclarations && !initialState) return;
@@ -159,7 +177,9 @@ export function useOpenUIState(
}
}
}
+ initializingRef.current = true;
store.initialize(result?.stateDeclarations ?? {}, bindingDefaults);
+ initializingRef.current = false;
}, [result?.stateDeclarations, store, initialState]);
// ─── Subscribe to Store and QueryManager for re-renders ───
@@ -179,8 +199,10 @@ export function useOpenUIState(
if (mutResult) return mutResult;
return queryManager.getResult(name);
},
+ functions,
+ actions: schema.actions,
}),
- [store, queryManager],
+ [store, queryManager, functions, schema.actions],
);
// ─── Evaluate and submit queries ───
@@ -249,7 +271,7 @@ export function useOpenUIState(
lastInitSnapshotRef.current = store.getSnapshot();
const unsub = store.subscribe(() => {
const currentSnapshot = store.getSnapshot();
- if (currentSnapshot === lastInitSnapshotRef.current) return;
+ if (initializingRef.current || currentSnapshot === lastInitSnapshotRef.current) return;
lastInitSnapshotRef.current = null;
propsRef.current.onStateUpdate?.(currentSnapshot);
});
@@ -316,12 +338,15 @@ export function useOpenUIState(
action?: ActionPlan | { type?: string; params?: Record<string, any> },
) => {
if (bundleBlocked) return;
- const formPayload = getFormPayload(formName);
const { onAction: handler } = propsRef.current;
// Legacy action config path (v0.1 compat) — { type?, params? }
if (action && !("steps" in action)) {
+ const formPayload = getFormPayload(formName);
const actionType = action.type || BuiltinActionType.ContinueConversation;
+ // Only a real call delivers a custom action; a legacy object cannot pose as one
+ if (schema.actions && Object.prototype.hasOwnProperty.call(schema.actions, actionType))
+ return;
const params = { ...(action.params || {}) };
// v0.1 compat — url and context were top-level, not in params
if ((action as any).url) params.url = (action as any).url;
@@ -337,6 +362,7 @@ export function useOpenUIState(
}
// ActionPlan path (v0.5) — sequential steps with halt-on-mutation-failure
+ // Form state is read per step so an earlier @Set in the same plan is visible.
const actionPlan = action as ActionPlan | undefined;
if (actionPlan?.steps) {
for (const step of actionPlan.steps) {
@@ -359,9 +385,9 @@ export function useOpenUIState(
case ACTION_STEPS.ToAssistant:
handler?.({
type: BuiltinActionType.ContinueConversation,
- params: step.context ? { context: step.context } : {},
+ params: step.context !== undefined ? { context: step.context } : {},
humanFriendlyMessage: step.message,
- formState: formPayload,
+ formState: getFormPayload(formName),
formName,
});
break;
@@ -370,7 +396,16 @@ export function useOpenUIState(
type: BuiltinActionType.OpenUrl,
params: { url: step.url },
humanFriendlyMessage: "",
- formState: formPayload,
+ formState: getFormPayload(formName),
+ formName,
+ });
+ break;
+ case "custom_action":
+ handler?.({
+ type: step.name,
+ params: step.params,
+ humanFriendlyMessage: "",
+ formState: getFormPayload(formName),
formName,
});
break;
@@ -386,7 +421,7 @@ export function useOpenUIState(
case ACTION_STEPS.Reset: {
const decls = resultRef.current?.stateDeclarations ?? {};
for (const target of step.targets) {
- store.set(target, decls[target] ?? null);
+ store.set(target, decls[target] ?? null, { pristine: true });
}
break;
}
@@ -400,11 +435,11 @@ export function useOpenUIState(
type: BuiltinActionType.ContinueConversation,
params: {},
humanFriendlyMessage: userMessage,
- formState: formPayload,
+ formState: getFormPayload(formName),
formName,
});
},
- [bundleBlocked, queryManager, evaluationContext, getFormPayload, store],
+ [bundleBlocked, queryManager, evaluationContext, getFormPayload, store, schema.actions],
);
// ─── reportError (for error boundary) ───
@@ -433,12 +468,12 @@ export function useOpenUIState(
const runtimeErrorsRef = useRef<OpenUIError[]>([]);
const evaluatedResult = useMemo<ParseResult | null>(() => {
- if (!result?.root) return result;
+ if (!result?.root && !result?.rootExpression) return result;
// Fresh errors array each pass — avoids mutating memoized context
const errors: OpenUIError[] = [];
const evalCtx: EvalContext = { ctx: evaluationContext, library, store, errors };
try {
- const evaluatedRoot = evaluateElementProps(result.root, evalCtx);
+ const evaluatedRoot = evaluateRoot(result, evalCtx);
runtimeErrorsRef.current = errors;
return { ...result, root: evaluatedRoot };
} catch (e) {
@@ -484,7 +519,7 @@ export function useOpenUIState(
// Keep error collection first: its effect refreshes this ref before the
// observability effect publishes the terminal stream event.
const { errorsRef, errorRevision } = useOpenUIErrors({
- response,
+ response: bundle.program,
isStreaming,
result,
evaluatedResult,
diff --git a/packages/react-lang/src/library.test.ts b/packages/react-lang/src/library.test.ts
index 2a4226c57..b2d0a54ec 100644
--- a/packages/react-lang/src/library.test.ts
+++ b/packages/react-lang/src/library.test.ts
@@ -54,6 +54,13 @@ describe("createLibrary publish", () => {
remove();
});
+ it("registers a derived library next to its base", () => {
+ const base = createLibrary({ root: "Card", id: "demo", components: [makeComponent("Card")] });
+ const a = base.extend({ components: { add: [makeComponent("Note")] } });
+ const b = base.extend({ components: { add: [makeComponent("Tip")] } });
+ expect(Object.values(registry())).toEqual([base, a, b]);
+ });
+
it("replaces a library with the same key on re-create (HMR)", () => {
const Card = makeComponent("Card");
createLibrary({ root: "Card", id: "demo", components: [Card] });
diff --git a/packages/react-lang/src/library.ts b/packages/react-lang/src/library.ts
index e34d41a56..5214c2110 100644
--- a/packages/react-lang/src/library.ts
+++ b/packages/react-lang/src/library.ts
@@ -4,12 +4,14 @@ import {
type DefinedComponent as CoreDefinedComponent,
type Library as CoreLibrary,
type LibraryDefinition as CoreLibraryDefinition,
+ type LibraryExtension as CoreLibraryExtension,
type ComponentRenderProps as CoreRenderProps,
+ type DefinedAction,
} from "@openuidev/lang-core";
import type { ReactNode } from "react";
import type { z } from "zod/v4";
import type { $ZodObject } from "zod/v4/core";
-import { publishLibrary } from "./publishLibrary";
+import { libraryKey, publishLibrary } from "./publishLibrary";
// Re-export framework-agnostic types unchanged
export type {
@@ -34,9 +36,19 @@ export type DefinedComponent<T extends $ZodObject = $ZodObject> = CoreDefinedCom
ComponentRenderer<z.infer<T>>
>;
-export type Library = CoreLibrary<ComponentRenderer<any>>;
+type AnyAction = DefinedAction<any, string>;
-export type LibraryDefinition = CoreLibraryDefinition<ComponentRenderer<any>>;
+export type Library<A extends AnyAction = AnyAction> = CoreLibrary<ComponentRenderer<any>, A>;
+
+export type LibraryDefinition<A extends AnyAction = AnyAction> = CoreLibraryDefinition<
+ ComponentRenderer<any>,
+ A
+>;
+
+export type LibraryExtension<A extends AnyAction = AnyAction> = CoreLibraryExtension<
+ ComponentRenderer<any>,
+ A
+>;
// ─── defineComponent (React) ────────────────────────────────────────────────
@@ -51,10 +63,27 @@ export function defineComponent<T extends $ZodObject>(config: {
// ─── createLibrary (React) ──────────────────────────────────────────────────
-export function createLibrary(input: LibraryDefinition): Library {
- const library = coreCreateLibrary<ComponentRenderer<any>>(input) as Library;
+export function createLibrary<A extends AnyAction = never>(
+ input: LibraryDefinition<A>,
+): Required<Library<A>> {
+ return published(coreCreateLibrary<ComponentRenderer<any>, A>(input));
+}
+
+let extendCount = 0;
+
+// Dev-only devtools registration. Each derived library gets its own key so it
+// does not replace its base or a sibling.
+function published<A extends AnyAction>(
+ library: Required<Library<A>>,
+ key = libraryKey(library),
+): Required<Library<A>> {
if (process.env["NODE_ENV"] !== "production") {
- publishLibrary(library);
+ publishLibrary(library, key);
}
- return library;
+ const extend = library.extend;
+ return Object.assign(library, {
+ extend: ((ext) => published(extend(ext), `${key}:extend-${++extendCount}`)) as Required<
+ Library<A>
+ >["extend"],
+ });
}
diff --git a/packages/react-lang/src/publishLibrary.ts b/packages/react-lang/src/publishLibrary.ts
index 229fd58d7..4f6c9e4b8 100644
--- a/packages/react-lang/src/publishLibrary.ts
+++ b/packages/react-lang/src/publishLibrary.ts
@@ -29,13 +29,9 @@ function getRegistry(): LibraryRegistry {
return (store[DEVTOOLS_LIBRARIES_KEY] ??= {});
}
-function upsertRegistry(library: Library): void {
- getRegistry()[libraryKey(library)] = library;
-}
-
/** Dev-only: stash the live library and emit a serializable registration ping. */
-export function publishLibrary(library: Library): void {
- upsertRegistry(library);
+export function publishLibrary(library: Library, key = libraryKey(library)): void {
+ getRegistry()[key] = library;
observability.info({
kind: LIBRARY_EVENT_KIND,
__libraryId: library.__libraryId,
diff --git a/packages/react-lang/src/registeredFunctions.test.tsx b/packages/react-lang/src/registeredFunctions.test.tsx
new file mode 100644
index 000000000..4ebc4f887
--- /dev/null
+++ b/packages/react-lang/src/registeredFunctions.test.tsx
@@ -0,0 +1,33 @@
+// @vitest-environment jsdom
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it } from "vitest";
+import { z } from "zod/v4";
+import { createLibrary, defineComponent, defineFunction } from "./index";
+import { Renderer } from "./Renderer";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const Text = defineComponent({
+ name: "Text",
+ props: z.object({ value: z.string() }),
+ description: "Shows a value",
+ component: ({ props }) => createElement("span", null, props.value),
+});
+const percent = defineFunction({
+ name: "Percent",
+ description: "Formats part / total as a percentage",
+ params: z.object({ part: z.number(), total: z.number() }),
+ returns: z.string(),
+ fn: ({ part, total }) => `${((part / total) * 100).toFixed(1)}%`,
+});
+const library = createLibrary({ root: "Text", components: [Text], functions: [percent] });
+
+it("Renderer evaluates library function calls", async () => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ const response = "root = Text(@Percent(763, 1000))";
+ await act(async () => root.render(createElement(Renderer, { library, response })));
+ expect(container.textContent).toBe("76.3%");
+ await act(async () => root.unmount());
+});
diff --git a/packages/react-lang/src/responseBundle.test.ts b/packages/react-lang/src/responseBundle.test.ts
index 532667804..6b0dc96f5 100644
--- a/packages/react-lang/src/responseBundle.test.ts
+++ b/packages/react-lang/src/responseBundle.test.ts
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";
import { parseResponseBundle } from "./responseBundle";
const program = '```openui-lang\nroot = Text("Hello")\n```\n';
+// The newline before a marker line is not part of the program (spec 7.2).
+const body = program.trimEnd();
const script = { name: "sales_total", code: "async ({ tools }) => tools.get_sales({})" };
function scriptsSection(values: unknown, count: unknown = 1) {
@@ -29,10 +31,10 @@ describe("parseResponseBundle", () => {
describe("content and metadata", () => {
it("decodes the optional name and separates the program from its envelope", () => {
- const response = ` \n]]>openui:content?thesys=true&name=Sales+%26+Growth+%E2%82%AC\n${program}]]>openui:end\n`;
+ const response = ` \n]]>openui:content?v=2&name=Sales+%26+Growth+%E2%82%AC\n${program}]]>openui:end\n`;
expect(parseResponseBundle(response, false)).toEqual({
- program,
+ program: body,
metadata: { name: "Sales & Growth €" },
scripts: new Set(),
complete: true,
@@ -45,7 +47,7 @@ describe("parseResponseBundle", () => {
const response = `]]>openui:content\n${program}]]>openui:end`;
expect(parseResponseBundle(response, false)).toMatchObject({
- program,
+ program: body,
metadata: {},
complete: true,
error: undefined,
@@ -56,7 +58,7 @@ describe("parseResponseBundle", () => {
const response = `]]>openui:content?name=Sales\r\n${program.replaceAll("\n", "\r\n")}${scriptsSection([script]).replaceAll("\n", "\r\n")}]]>openui:end\r\n`;
expect(parseResponseBundle(response, false)).toMatchObject({
- program: program.replaceAll("\n", "\r\n"),
+ program: body.replaceAll("\n", "\r\n"),
metadata: { name: "Sales" },
scripts: new Set(["sales_total"]),
complete: true,
@@ -70,7 +72,7 @@ describe("parseResponseBundle", () => {
const response = `${previous}]]>openui:content\n${replacement}]]>openui:end`;
expect(parseResponseBundle(response, false)).toEqual({
- program: replacement,
+ program: replacement.trimEnd(),
metadata: {},
scripts: new Set(),
complete: true,
@@ -86,7 +88,7 @@ describe("parseResponseBundle", () => {
const response = `]]>openui:content\n${program}${scriptsSection(values, 2)}]]>openui:end`;
expect(parseResponseBundle(response, false)).toMatchObject({
- program,
+ program: body,
scripts: new Set(["sales_total", "save_sales"]),
complete: true,
error: undefined,
@@ -107,7 +109,7 @@ describe("parseResponseBundle", () => {
const response = `${program}${scriptsSection([script])}${end}`;
expect(parseResponseBundle(response, false)).toMatchObject({
- program,
+ program: body,
isBundle: true,
scripts: new Set(["sales_total"]),
complete: true,
@@ -133,12 +135,12 @@ describe("parseResponseBundle", () => {
const response = `]]>openui:content\n${program}${scriptsSection(values, count)}]]>openui:end`;
expect(parseResponseBundle(response, false)).toMatchObject({
- program,
+ program: body,
complete: false,
error: "Invalid scripts bundle",
});
expect(parseResponseBundle(response, true)).toMatchObject({
- program,
+ program: body,
complete: false,
error: undefined,
});
@@ -150,7 +152,7 @@ describe("parseResponseBundle", () => {
const response = `]]>openui:content\n${program}${section}]]>openui:end`;
expect(parseResponseBundle(response, false)).toMatchObject({
- program,
+ program: body,
complete: false,
error: "Invalid scripts bundle",
});
@@ -166,42 +168,59 @@ describe("parseResponseBundle", () => {
for (let length = 1; length <= response.length; length++) {
const parsed = parseResponseBundle(response.slice(0, length), true);
expect(parsed.error, `prefix length ${length}`).toBeUndefined();
- expect(parsed.complete, `prefix length ${length}`).toBe(length === response.length);
- expect(parsed.isBundle).toBe(true);
+ // A marker line, the end line included, is held back until its newline or the stream end.
+ expect(parsed.isBundle, `prefix length ${length}`).toBe(length >= header.length);
+ if (parsed.isBundle) expect(parsed.complete, `prefix length ${length}`).toBe(false);
const visibleLength = Math.max(0, Math.min(program.length, length - header.length));
- expect(parsed.program).toBe(program.slice(0, visibleLength));
+ expect(parsed.program.trimEnd()).toBe(program.slice(0, visibleLength).trimEnd());
}
+ expect(parseResponseBundle(response, false)).toMatchObject({
+ complete: true,
+ error: undefined,
+ });
});
it.each(["]]", "]]>openui:content?name=Sales"])(
- "reports an unfinished header only when streaming stops: %j",
+ "holds back an unfinished header while streaming: %j",
(response) => {
expect(parseResponseBundle(response, true)).toMatchObject({
program: "",
- complete: false,
error: undefined,
});
+ },
+ );
+
+ it("reads a header without a body as an empty program", () => {
+ expect(parseResponseBundle("]]>openui:content?name=Sales", false)).toMatchObject({
+ program: "",
+ metadata: { name: "Sales" },
+ complete: true,
+ error: undefined,
+ });
+ });
+
+ it.each(["", scriptsSection([script]), "]]>openui:unknown"])(
+ "renders a stored message without an end line: %j",
+ (tail) => {
+ const response = `]]>openui:content\n${program}${tail}`;
+
expect(parseResponseBundle(response, false)).toMatchObject({
- program: "",
- complete: false,
- error: "Incomplete response header",
+ program: tail ? body : program,
+ complete: true,
+ error: undefined,
});
+ // While streaming, the end line is what finishes a framed response.
+ expect(parseResponseBundle(response, true)).toMatchObject({ complete: false });
},
);
- it.each([
- "",
- "]]>openui:scripts",
- scriptsSection([script]),
- "]]>openui:unknown",
- "]]>openui:end\nunexpected content",
- ])("does not mark an unfinished or invalid envelope complete: %j", (tail) => {
- const response = `]]>openui:content\n${program}${tail}`;
+ it("rejects a scripts line without its JSON", () => {
+ const response = `]]>openui:content\n${program}]]>openui:scripts`;
expect(parseResponseBundle(response, false)).toMatchObject({
- program,
+ program: body,
complete: false,
- error: "Incomplete response bundle",
+ error: "Invalid scripts bundle",
});
});
});
@@ -223,7 +242,7 @@ describe("parseResponseBundle", () => {
expect(
parseResponseBundle(`]]>openui:content\n${content}]]>openui:end`, false),
).toMatchObject({
- program: content,
+ program: content.trimEnd(),
complete: true,
error: undefined,
});
@@ -234,11 +253,21 @@ describe("parseResponseBundle", () => {
const response = `]]>openui:content\n${program}${scriptsSection([{ ...script, code }])}]]>openui:end`;
expect(parseResponseBundle(response, false)).toMatchObject({
- program,
+ program: body,
scripts: new Set(["sales_total"]),
complete: true,
error: undefined,
});
});
});
+
+ it("reads a content line that starts mid-line after a cut-off attempt", () => {
+ const header = "]]>openui:content?v=2";
+ const response = `${header}\nroot = Text("Broken${header}\n${program}${scriptsSection([script])}]]>openui:end`;
+ expect(parseResponseBundle(response, false)).toMatchObject({
+ program: body,
+ scripts: new Set(["sales_total"]),
+ complete: true,
+ });
+ });
});
diff --git a/packages/react-lang/src/responseBundle.ts b/packages/react-lang/src/responseBundle.ts
index 3135cd02c..8f7d9130b 100644
--- a/packages/react-lang/src/responseBundle.ts
+++ b/packages/react-lang/src/responseBundle.ts
@@ -1,14 +1,25 @@
+import { parseMessage } from "@openuidev/lang-core";
+
/** Metadata emitted by OpenUI Cloud. */
export interface ResponseMetadata {
name?: string;
}
-const CONTENT = "]]>openui:content";
+// OpenUI Cloud writes its scripts after the program: `]]>openui:scripts {"count":1}`, then
+// `[{"name":"sales_total","code":"async ({ tools }) => …"}]`. This file cuts that section out;
+// parseMessage reads the rest (content, attributes, end).
const SCRIPTS = "]]>openui:scripts";
-const END = "]]>openui:end";
+const CONTENT_LINE = /^\]\]>openui:content(?:\?.*)?\r?$(\n?)/m;
+// A scripts line without its JSON would read as a message marker; keep it in the content.
+const BARE_SCRIPTS = /^\]\]>openui:scripts(?=\?|\r?$)/gm;
+
+interface Scripts {
+ names: Set<string>;
+ revision: string;
+}
// Markers inside DSL/JSON strings are ordinary content.
-function markerIndex(text: string, partial = false): number {
+function markerIndex(text: string): number {
let quote = "";
let escaped = false;
for (let i = 0; i < text.length; i++) {
@@ -22,104 +33,95 @@ function markerIndex(text: string, partial = false): number {
if (newline < 0) return -1;
i = newline;
} else if (c === '"' || c === "'") quote = c;
- else if (text.startsWith("]]>", i) || (partial && "]]>".startsWith(text.slice(i)))) return i;
+ else if (text.startsWith("]]>", i)) return i;
}
return -1;
}
+function readScripts(header: string, payload: string): Scripts | null {
+ try {
+ const { count } = JSON.parse(header);
+ const values: unknown = JSON.parse(payload);
+ if (!Array.isArray(values) || !Number.isSafeInteger(count) || count !== values.length)
+ return null;
+ const names = new Set<string>();
+ for (const script of values) {
+ if (
+ !script ||
+ typeof script.name !== "string" ||
+ !script.name ||
+ typeof script.code !== "string" ||
+ names.has(script.name)
+ )
+ return null;
+ names.add(script.name);
+ }
+ const revision = JSON.stringify(
+ values
+ .map((script) => ({ name: script.name as string, code: script.code as string }))
+ .sort((a, b) => a.name.localeCompare(b.name)),
+ );
+ return { names, revision };
+ } catch {
+ return null;
+ }
+}
+
+/** Reads an OpenUI Cloud response: a stored message (see parseMessage) plus its scripts section. */
export function parseResponseBundle(response: string | null, streaming: boolean) {
- let program = response ?? "";
- const metadata: ResponseMetadata = {};
- const scripts = new Set<string>();
- let scriptRevision: string | undefined;
- let error: string | undefined;
- let complete = true;
- let framed = false;
- let body = program.trimStart();
- if (body && (body.startsWith(CONTENT) || CONTENT.startsWith(body))) {
- framed = true;
- // A new content section replaces a progressive preview or failed retry.
- const sections = [...body.matchAll(/^\]\]>openui:content(?:\?[^\r\n]*)?\r?$/gm)];
- const last = sections[sections.length - 1];
- if (last) body = body.slice(last.index);
- const newline = body.indexOf("\n");
- if (newline < 0)
- return {
- isBundle: true,
- program: "",
- metadata,
- scripts,
- complete: false,
- error: streaming ? undefined : "Incomplete response header",
- };
- const header = body.slice(0, newline).trimEnd();
- const name = new URLSearchParams(header.slice(CONTENT.length).replace(/^\?/, "")).get("name");
- if (name !== null) metadata.name = name;
- body = body.slice(newline + 1);
+ const text = response ?? "";
+ // Framed once a content line is in. A line still streaming does not count yet.
+ const line = CONTENT_LINE.exec(text);
+ const framed = !!line && (!streaming || line[1] === "\n");
+ const { content, attributes, end } = parseMessage(text.replace(BARE_SCRIPTS, "$& "), {
+ streaming,
+ });
+ let program = content;
+ // The scripts section is the first marker in the winning content, as Cloud writes it.
+ let section = false;
+ let scripts: Scripts | null = null;
+ const at = markerIndex(program);
+ if (at >= 0 && program.startsWith(SCRIPTS, at)) {
+ section = true;
+ const newline = program.indexOf("\n", at);
+ let to = program.length;
+ if (newline >= 0) {
+ const next = markerIndex(program.slice(newline + 1));
+ if (next >= 0) to = newline + 1 + next;
+ scripts = readScripts(
+ program.slice(at + SCRIPTS.length, newline),
+ program.slice(newline + 1, to),
+ );
+ }
+ // The newline before the section belongs to its marker (spec 7.2), unless the program is empty.
+ const before = at > 0 ? program.slice(0, at).replace(/\r?\n$/, "") : "";
+ const after = program.slice(to);
+ program = after ? `${before}\n${after}` : before;
}
- program = body;
- const marker = markerIndex(body, framed && streaming);
- const isBundle = framed || marker >= 0;
- if (!isBundle) {
- return { program: response ?? "", metadata, scripts, complete, isBundle, error };
+
+ const metadata: ResponseMetadata = {};
+ if (!framed && !section && !end) {
+ const error: string | undefined = undefined;
+ return {
+ program,
+ metadata,
+ scripts: new Set<string>(),
+ complete: true,
+ isBundle: false,
+ error,
+ };
}
- if (marker >= 0) {
- program = body.slice(0, marker);
- let tail = body.slice(marker).trimEnd();
- if (tail.startsWith(SCRIPTS)) {
- complete = false;
- const newline = tail.indexOf("\n");
- if (newline >= 0) {
- try {
- const header = JSON.parse(tail.slice(SCRIPTS.length, newline));
- let payload = tail.slice(newline + 1);
- const end = markerIndex(payload);
- if (end >= 0) {
- tail = payload.slice(end).trim();
- payload = payload.slice(0, end);
- } else tail = "";
- const values: unknown = JSON.parse(payload);
- if (
- !Array.isArray(values) ||
- !Number.isSafeInteger(header.count) ||
- header.count !== values.length
- )
- throw new Error("Invalid script count");
- for (const script of values) {
- if (
- !script ||
- typeof script.name !== "string" ||
- !script.name ||
- typeof script.code !== "string" ||
- scripts.has(script.name)
- )
- throw new Error("Invalid or duplicate script definition");
- scripts.add(script.name);
- }
- scriptRevision = JSON.stringify(
- values
- .map((script) => ({ name: script.name as string, code: script.code as string }))
- .sort((a, b) => a.name.localeCompare(b.name)),
- );
- complete = framed ? tail === END : tail === "" || tail === END;
- if (!complete) error = "Incomplete response bundle";
- } catch {
- error = "Invalid scripts bundle";
- }
- }
- } else {
- complete = tail === END;
- if (!complete) error = "Incomplete response bundle";
- }
- } else if (framed) complete = false;
- if (!complete && !streaming) error ??= "Incomplete response bundle";
+ if (framed && attributes.name !== undefined) metadata.name = attributes.name;
+ const error = section && !scripts ? "Invalid scripts bundle" : undefined;
return {
program,
metadata,
- scripts,
- complete,
- isBundle,
+ scripts: scripts?.names ?? new Set<string>(),
+ // The end line only says the response is finished, so a stored message renders without one.
+ // While streaming, a framed response is complete at its end line.
+ complete: !error && (end || !streaming || !framed),
+ isBundle: true,
error: streaming ? undefined : error,
- ...(scripts.size ? { scriptRevision } : {}),
+ ...(scripts?.names.size ? { scriptRevision: scripts.revision } : {}),
};
}
diff --git a/packages/react-ui/package.json b/packages/react-ui/package.json
index 8feea0e1e..e4a53e354 100644
--- a/packages/react-ui/package.json
+++ b/packages/react-ui/package.json
@@ -109,8 +109,8 @@
"ci": "pnpm run lint:check && pnpm run format:check && pnpm run test"
},
"peerDependencies": {
- "@openuidev/react-headless": ">=0.14.0 <0.18.0",
- "@openuidev/react-lang": ">=0.3.0 <0.5.0",
+ "@openuidev/react-headless": ">=0.14.0 <0.19.0",
+ "@openuidev/react-lang": ">=1.0.0 <2.0.0",
"react": "catalog:",
"react-dom": "catalog:",
"zustand": "catalog:",
diff --git a/packages/react-ui/src/components/AgentInterface/AgentInterface.tsx b/packages/react-ui/src/components/AgentInterface/AgentInterface.tsx
index d76ffe9e4..47ddeea57 100644
--- a/packages/react-ui/src/components/AgentInterface/AgentInterface.tsx
+++ b/packages/react-ui/src/components/AgentInterface/AgentInterface.tsx
@@ -9,11 +9,12 @@ import {
type ChatProviderProps,
type UserMessage,
} from "@openuidev/react-headless";
-import type { Library } from "@openuidev/react-lang";
+import type { ActionEvent, Library } from "@openuidev/react-lang";
import { ArrowLeft, MessageSquare } from "lucide-react";
import {
Children,
isValidElement,
+ useCallback,
useEffect,
useMemo,
useRef,
@@ -72,6 +73,8 @@ export interface AgentInterfaceComponents {
export interface AgentInterfaceProps extends Omit<ChatProviderProps, "children"> {
/** Component library for auto-GenUI rendering when `components.AssistantMessage` is not provided. */
componentLibrary?: Library;
+ /** Receives the actions the chat does not handle itself, such as custom actions from `defineAction`. */
+ onAction?: (event: ActionEvent) => void;
/** Explicit component overrides. Takes precedence over GenUI auto-derivation. */
components?: AgentInterfaceComponents;
/** Theme props passed to <ThemeProvider>. */
@@ -191,6 +194,7 @@ export const AgentInterface: AgentInterfaceComponent = ((props: AgentInterfacePr
artifactCategories,
artifactAutoOpen,
componentLibrary,
+ onAction,
components,
theme,
disableThemeProvider,
@@ -218,16 +222,25 @@ export const AgentInterface: AgentInterfaceComponent = ((props: AgentInterfacePr
slots.sidebarHeader = undefined;
}
+ // Read through a ref so a new onAction does not remount every message
+ const onActionRef = useRef(onAction);
+ onActionRef.current = onAction;
+ const forwardAction = useCallback((event: ActionEvent) => onActionRef.current?.(event), []);
+
const resolvedAssistantMessage = useMemo<AssistantMessageComponent | undefined>(() => {
if (components?.AssistantMessage) return components.AssistantMessage;
if (componentLibrary) {
const Cmp = ({ message }: { message: AssistantMessage }) => (
- <GenUIAssistantMessage message={message} library={componentLibrary} />
+ <GenUIAssistantMessage
+ message={message}
+ library={componentLibrary}
+ onAction={forwardAction}
+ />
);
return Cmp;
}
return undefined;
- }, [components?.AssistantMessage, componentLibrary]);
+ }, [components?.AssistantMessage, componentLibrary, forwardAction]);
const resolvedUserMessage = useMemo<UserMessageComponent | undefined>(() => {
if (components?.UserMessage) return components.UserMessage;
diff --git a/packages/react-ui/src/components/AgentInterface/README.md b/packages/react-ui/src/components/AgentInterface/README.md
index 3bd258e1c..843705072 100644
--- a/packages/react-ui/src/components/AgentInterface/README.md
+++ b/packages/react-ui/src/components/AgentInterface/README.md
@@ -171,6 +171,7 @@ Defined as `AgentInterfaceProps` in `AgentInterface.tsx`. It `extends Omit<ChatP
| Prop | Type | Default | Notes |
| ---------------------- | -------------------------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------- |
| `componentLibrary` | `Library` (react-lang) | — | Auto-derive assistant (and user) message rendering via GenUI when `components.AssistantMessage` is absent |
+| `onAction` | `(event: ActionEvent) => void` | — | GenUI actions the chat does not handle itself, such as custom actions from `defineAction` |
| `components` | `{ AssistantMessage?; UserMessage?; ToolCallTimeline? }` | — | Explicit render overrides; `ToolCallTimeline` replaces the turn-level tool activity UI |
| `theme` | `ThemeProps` | — | Passed to `<ThemeProvider>` |
| `disableThemeProvider` | `boolean` | `false` | Skip the internal `<ThemeProvider>` wrapper |
diff --git a/packages/react-ui/src/components/AgentInterface/Thread.tsx b/packages/react-ui/src/components/AgentInterface/Thread.tsx
index 943e5f5be..aac419953 100644
--- a/packages/react-ui/src/components/AgentInterface/Thread.tsx
+++ b/packages/react-ui/src/components/AgentInterface/Thread.tsx
@@ -11,8 +11,12 @@ import clsx from "clsx";
import React, { memo, useId, useMemo, useRef } from "react";
import { useLayoutContext } from "../../context/LayoutContext";
import { ScrollVariant, useScrollToBottom } from "../../hooks/useScrollToBottom";
-import { getLastAssistantMessageId, getMatchedRendererActivities } from "../../utils/messages";
-import { hasLangSyntax, separateContentAndContext } from "../../utils/sentinelParser";
+import {
+ getLastAssistantMessageId,
+ getMatchedRendererActivities,
+ hasLangSyntax,
+ readMessage,
+} from "../../utils/messages";
import { ToolCallTimeline, type TimelineStep } from "../ToolCall";
import {
DetailedViewOverlay,
@@ -393,7 +397,7 @@ const InterleavedTurn = ({
);
const turnActivities = useToolActivities(turnMessage, allMessages);
- const lastContent = separateContentAndContext(last.content ?? "").content;
+ const lastContent = readMessage(last.content ?? "", turnLive).content;
// Show the last segment as the answer once it looks like Lang, or once the run
// settles.
const answer = !turnLive || hasLangSyntax(lastContent) ? last : null;
@@ -406,7 +410,7 @@ const InterleavedTurn = ({
const claimed = new Set<string>();
for (const seg of activeSegments) {
if (seg.id !== answer?.id) {
- const prose = separateContentAndContext(seg.content ?? "").content;
+ const prose = readMessage(seg.content ?? "", turnLive && seg === last).content;
if (prose) rows.push({ type: "text", id: seg.id, text: prose });
}
for (const tc of seg.toolCalls ?? []) {
@@ -426,7 +430,7 @@ const InterleavedTurn = ({
if (!claimed.has(activity.toolCall.id)) rows.push({ type: "activity", activity });
}
return rows;
- }, [activeSegments, turnActivities, answer?.id]);
+ }, [activeSegments, turnActivities, answer?.id, turnLive, last]);
// Matched renderers (artifact/search previews) render OUTSIDE the tray so
// they stay visible after it collapses.
diff --git a/packages/react-ui/src/components/AgentInterface/UserMessageContent.tsx b/packages/react-ui/src/components/AgentInterface/UserMessageContent.tsx
index 02fc015da..bc8adfd0d 100644
--- a/packages/react-ui/src/components/AgentInterface/UserMessageContent.tsx
+++ b/packages/react-ui/src/components/AgentInterface/UserMessageContent.tsx
@@ -1,7 +1,7 @@
import type { InputContent, Message } from "@openuidev/react-headless";
import clsx from "clsx";
import { useState } from "react";
-import { separateContentAndContext } from "../../utils/sentinelParser";
+import { readMessage } from "../../utils/messages";
/**
* Renders the content of a user message.
@@ -255,8 +255,8 @@ export const UserMessageContent = ({ message }: { message: Message }) => {
const content = message.content;
if (typeof content === "string") {
- // Strip XML wrapper tags (<content>, <context>) so the bubble shows clean text.
- const { content: humanText } = separateContentAndContext(content);
+ // Strip the marker lines (or older XML tags) so the bubble shows clean text.
+ const { content: humanText } = readMessage(content);
return <>{humanText}</>;
}
diff --git a/packages/react-ui/src/components/OpenUIChat/GenUIAssistantMessage.tsx b/packages/react-ui/src/components/OpenUIChat/GenUIAssistantMessage.tsx
index f36907ac6..3181b2e38 100644
--- a/packages/react-ui/src/components/OpenUIChat/GenUIAssistantMessage.tsx
+++ b/packages/react-ui/src/components/OpenUIChat/GenUIAssistantMessage.tsx
@@ -3,24 +3,22 @@
import type { AssistantMessage } from "@openuidev/react-headless";
import { useThread } from "@openuidev/react-headless";
import type { ActionEvent, Library } from "@openuidev/react-lang";
-import { BuiltinActionType, Renderer } from "@openuidev/react-lang";
+import { buildMessage, Renderer } from "@openuidev/react-lang";
import { useCallback, useMemo } from "react";
-import { getLastAssistantMessageId } from "../../utils/messages";
-import {
- separateContentAndContext,
- wrapContent,
- wrapContentWithHeader,
- wrapContext,
-} from "../../utils/sentinelParser";
+import { getLastAssistantMessageId, readMessage } from "../../utils/messages";
import { AssistantMessageContainer } from "./AssistantMessageContainer";
+import { runChatAction } from "./utils/actionMessage";
/** Renders the OpenUI-Lang response for one assistant message. */
export const GenUIAssistantMessage = ({
message,
library,
+ onAction,
}: {
message: AssistantMessage;
library: Library;
+ /** Receives the actions the chat does not handle itself, such as custom actions. */
+ onAction?: (event: ActionEvent) => void;
}) => {
const messages = useThread((s) => s.messages);
const isRunning = useThread((s) => s.isRunning);
@@ -30,68 +28,39 @@ export const GenUIAssistantMessage = ({
const lastAssistantId = useMemo(() => getLastAssistantMessageId(messages), [messages]);
const isStreaming = isRunning && lastAssistantId === message.id;
- // Strip the inline sentinels and separate any persisted form-state.
- const { content, contextString, contentHeader } = useMemo(
+ // Strip the marker lines and separate any persisted form-state.
+ const { content, context, attributes } = useMemo(
() =>
message.content
- ? separateContentAndContext(message.content)
- : { content: null, contextString: null, contentHeader: undefined },
- [message.content],
+ ? readMessage(message.content, isStreaming)
+ : { content: null, context: null, attributes: {} },
+ [message.content, isStreaming],
);
const initialState = useMemo(() => {
- if (!contextString) return undefined;
- try {
- const parsed = JSON.parse(contextString);
- if (Array.isArray(parsed) && typeof parsed[0] === "object") return parsed[0];
- if (typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
- return undefined;
- } catch {
- return undefined;
- }
- }, [contextString]);
+ if (Array.isArray(context) && typeof context[0] === "object") return context[0];
+ if (context && typeof context === "object" && !Array.isArray(context)) return context;
+ return undefined;
+ }, [context]);
- // Persist form state into the inline-wrapped message content. The original
- // header line (which may include `libraryVersion` and telemetry tags emitted
- // by the backend) is reused so attrs survive the persist round-trip.
+ // Persist form state, keeping the content attributes, e.g. ?libraryVersion=0.5&v=2
const handleStateUpdate = useCallback(
(state: Record<string, any>) => {
const hasState = Object.keys(state).length > 0;
- const contentPart = wrapContentWithHeader(content ?? "", contentHeader);
- const fullMessage = hasState
- ? contentPart + wrapContext(JSON.stringify([state]))
- : contentPart;
+ const fullMessage = buildMessage({
+ content: content ?? "",
+ attributes,
+ context: hasState ? [state] : undefined,
+ });
updateMessage({ ...message, content: fullMessage });
},
- [updateMessage, message, content, contentHeader],
+ [updateMessage, message, content, attributes],
);
- // Build LLM-friendly message from action + form state, then dispatch
const handleAction = useCallback(
- (event: ActionEvent) => {
- if (event.type === BuiltinActionType.ContinueConversation) {
- const contentPart = event.humanFriendlyMessage
- ? wrapContent(event.humanFriendlyMessage)
- : "";
- const messageCtx: (string | object)[] = [`User clicked: ${event.humanFriendlyMessage}`];
- if (event.formState) {
- messageCtx.push(event.formState);
- }
- const contextPart = wrapContext(JSON.stringify(messageCtx));
- const llmMessage = `${contentPart}${contextPart}`;
-
- processMessage({
- role: "user",
- content: llmMessage,
- });
- } else if (event.type === BuiltinActionType.OpenUrl) {
- const url = event.params?.["url"] as string | undefined;
- if (typeof window !== "undefined" && url) {
- window.open(url, "_blank");
- }
- }
- },
- [processMessage],
+ (event: ActionEvent) =>
+ runChatAction(event, (content) => processMessage({ role: "user", content }), onAction),
+ [processMessage, onAction],
);
return (
diff --git a/packages/react-ui/src/components/OpenUIChat/GenUIUserMessage.tsx b/packages/react-ui/src/components/OpenUIChat/GenUIUserMessage.tsx
index ad17e0351..537e879dc 100644
--- a/packages/react-ui/src/components/OpenUIChat/GenUIUserMessage.tsx
+++ b/packages/react-ui/src/components/OpenUIChat/GenUIUserMessage.tsx
@@ -3,29 +3,23 @@
import type { UserMessage } from "@openuidev/react-headless";
import { ChevronDown } from "lucide-react";
import { useState } from "react";
-import { separateContentAndContext } from "../../utils/sentinelParser";
+import { readMessage } from "../../utils/messages";
/**
- * Extracts the first plain object from a context string.
+ * Extracts the first plain object from a message context.
* The triggerAction context format is: ["action description string", { formState }]
*/
-function parseContextForDisplay(contextString: string | null): Record<string, any> {
- if (!contextString) return {};
- try {
- const parsed = JSON.parse(contextString);
- if (Array.isArray(parsed)) {
- const stateObj = parsed.find(
- (item) => item !== null && typeof item === "object" && !Array.isArray(item),
- );
- return stateObj ?? {};
- }
- if (typeof parsed === "object" && parsed !== null) {
- return parsed;
- }
- return {};
- } catch {
- return {};
+function parseContextForDisplay(context: unknown): Record<string, any> {
+ if (Array.isArray(context)) {
+ const stateObj = context.find(
+ (item) => item !== null && typeof item === "object" && !Array.isArray(item),
+ );
+ return stateObj ?? {};
+ }
+ if (typeof context === "object" && context !== null) {
+ return context;
}
+ return {};
}
function getEntries(state: Record<string, any>): { label: string; value: string }[] {
@@ -107,8 +101,8 @@ function FormDataAccordion({ state }: { state: Record<string, any> }) {
*/
export const GenUIUserMessage = ({ message }: { message: UserMessage }) => {
const rawContent = typeof message.content === "string" ? message.content : "";
- const { content: humanText, contextString } = separateContentAndContext(rawContent);
- const formState = parseContextForDisplay(contextString);
+ const { content: humanText, context } = readMessage(rawContent);
+ const formState = parseContextForDisplay(context);
const hasFormData = Object.keys(formState).length > 0;
return (
diff --git a/packages/react-ui/src/components/OpenUIChat/__tests__/actionMessage.test.ts b/packages/react-ui/src/components/OpenUIChat/__tests__/actionMessage.test.ts
new file mode 100644
index 000000000..b5ae009ef
--- /dev/null
+++ b/packages/react-ui/src/components/OpenUIChat/__tests__/actionMessage.test.ts
@@ -0,0 +1,28 @@
+import { BuiltinActionType, parseMessage, type ActionEvent } from "@openuidev/react-lang";
+import { expect, it, vi } from "vitest";
+import { buildActionUserMessage, runChatAction } from "../utils/actionMessage";
+
+const contextOf = (params: Record<string, unknown>, formState?: Record<string, unknown>) =>
+ parseMessage(
+ buildActionUserMessage({
+ type: BuiltinActionType.ContinueConversation,
+ humanFriendlyMessage: "Save",
+ params,
+ formState,
+ }),
+ ).context;
+
+it("adds the @ToAssistant context as the third element, holding the form slot", () => {
+ expect(contextOf({ context: 0 })).toEqual(["User clicked: Save", {}, 0]);
+ expect(contextOf({}, { $a: 1 })).toEqual(["User clicked: Save", { $a: 1 }]);
+});
+
+it("sends continue_conversation itself and hands a custom action to onAction", () => {
+ const send = vi.fn();
+ const onAction = vi.fn();
+ const event = (type: string): ActionEvent => ({ type, params: {}, humanFriendlyMessage: "Go" });
+ runChatAction(event(BuiltinActionType.ContinueConversation), send, onAction);
+ runChatAction(event("CopyToClipboard"), send, onAction);
+ expect(send).toHaveBeenCalledTimes(1);
+ expect(onAction.mock.calls.map(([e]) => e.type)).toEqual(["CopyToClipboard"]);
+});
diff --git a/packages/react-ui/src/components/OpenUIChat/utils/actionMessage.ts b/packages/react-ui/src/components/OpenUIChat/utils/actionMessage.ts
new file mode 100644
index 000000000..5055750dc
--- /dev/null
+++ b/packages/react-ui/src/components/OpenUIChat/utils/actionMessage.ts
@@ -0,0 +1,32 @@
+import { BuiltinActionType, buildMessage, type ActionEvent } from "@openuidev/react-lang";
+
+/** The stored user turn for a continue_conversation event; context is `["User clicked: msg", formState, context?]`. */
+export function buildActionUserMessage(event: ActionEvent): string {
+ const messageCtx: unknown[] = [`User clicked: ${event.humanFriendlyMessage}`];
+ const actionContext = event.params?.["context"];
+ if (event.formState || actionContext !== undefined) {
+ messageCtx.push(event.formState ?? {});
+ }
+ if (actionContext !== undefined) {
+ messageCtx.push(actionContext);
+ }
+ const built = buildMessage({ content: event.humanFriendlyMessage, context: messageCtx });
+ // No message: stored without the content line, e.g. "\n]]>openui:context\n[...]"
+ return event.humanFriendlyMessage ? built : built.slice(built.indexOf("\n") + 1);
+}
+
+/** continue_conversation sends a user turn, open_url opens a tab, any other action (e.g. a custom one) goes to `onAction`. */
+export function runChatAction(
+ event: ActionEvent,
+ send: (content: string) => void,
+ onAction?: (event: ActionEvent) => void,
+): void {
+ if (event.type === BuiltinActionType.ContinueConversation) {
+ send(buildActionUserMessage(event));
+ } else if (event.type === BuiltinActionType.OpenUrl) {
+ const url = event.params?.["url"] as string | undefined;
+ if (typeof window !== "undefined" && url) window.open(url, "_blank");
+ } else {
+ onAction?.(event);
+ }
+}
diff --git a/packages/react-ui/src/genui-lib/Action/schema.ts b/packages/react-ui/src/genui-lib/Action/schema.ts
index ded0c83de..9b38ddf39 100644
--- a/packages/react-ui/src/genui-lib/Action/schema.ts
+++ b/packages/react-ui/src/genui-lib/Action/schema.ts
@@ -1,17 +1,4 @@
-import { tagSchemaId } from "@openuidev/react-lang";
-import { z } from "zod/v4";
+import { action } from "@openuidev/react-lang";
-/**
- * Shared action prop schema.
- *
- * Tagged as `ActionExpression` so the local react-lang prompt renders the v0.5
- * `Action([@steps...])` expression syntax. The JSON schema (used by `openui
- * generate` and cloud/muse prompt rendering) carries the legacy object
- * contract, which react-lang also accepts at runtime (legacy action path).
- */
-export const actionPropSchema = z.union([
- z.object({ type: z.literal("open_url"), url: z.string() }),
- z.object({ type: z.literal("continue_conversation"), context: z.string().optional() }),
- z.object({ type: z.string(), params: z.record(z.string(), z.any()).optional() }),
-]);
-tagSchemaId(actionPropSchema, "ActionExpression");
+/** Shared action prop schema: react-lang's `action()`, tagged `ActionExpression`. */
+export const actionPropSchema = action();
diff --git a/packages/react-ui/src/genui-lib/Button/index.tsx b/packages/react-ui/src/genui-lib/Button/index.tsx
index 3a146c697..0962f341d 100644
--- a/packages/react-ui/src/genui-lib/Button/index.tsx
+++ b/packages/react-ui/src/genui-lib/Button/index.tsx
@@ -45,10 +45,11 @@ export const Button = defineComponent({
// Validate form for primary buttons before firing action
if (formValidation && variant === "primary") {
if (action?.steps) {
- // v0.5 ActionPlan — validate if any step is ToAssistant or mutation
+ // v0.5 ActionPlan: validate if any step is ToAssistant, a mutation, or a custom action
const needsValidation = action.steps.some(
(s) =>
s.type === ACTION_STEPS.ToAssistant ||
+ s.type === "custom_action" ||
(s.type === ACTION_STEPS.Run && s.refType === "mutation"),
);
if (needsValidation && !formValidation.validateForm()) return;
diff --git a/packages/react-ui/src/genui-lib/__tests__/cardActionUtils.test.ts b/packages/react-ui/src/genui-lib/__tests__/cardActionUtils.test.ts
index cd1e489ce..28fa574d1 100644
--- a/packages/react-ui/src/genui-lib/__tests__/cardActionUtils.test.ts
+++ b/packages/react-ui/src/genui-lib/__tests__/cardActionUtils.test.ts
@@ -66,6 +66,14 @@ describe("withItemContext", () => {
expect((plan.steps[0] as { context?: string }).context).toBe("cards");
});
+ it("keeps a falsy ToAssistant context such as 0", () => {
+ const plan = {
+ steps: [{ type: ACTION_STEPS.ToAssistant, message: "m", context: 0 }],
+ } as unknown as ActionPlan;
+ const [step] = (withItemContext(plan, { itemIndex: 1 }) as ActionPlan).steps;
+ expect((step as { context?: unknown }).context).toBe('0\nSelected item: {"itemIndex":1}');
+ });
+
it("returns the same ActionPlan when there is no item context", () => {
const plan = { steps: [{ type: ACTION_STEPS.OpenUrl, url: "https://x.test" }] } as ActionPlan;
expect(withItemContext(plan, { itemId: undefined })).toBe(plan);
diff --git a/packages/react-ui/src/genui-lib/cardActionUtils.ts b/packages/react-ui/src/genui-lib/cardActionUtils.ts
index da2ab342f..32107a244 100644
--- a/packages/react-ui/src/genui-lib/cardActionUtils.ts
+++ b/packages/react-ui/src/genui-lib/cardActionUtils.ts
@@ -57,7 +57,10 @@ export function withItemContext(
...action,
steps: action.steps.map((step) => {
if (step.type !== ACTION_STEPS.ToAssistant) return step;
- return { ...step, context: step.context ? `${step.context}\n${suffix}` : suffix };
+ if (step.context == null) return { ...step, context: suffix };
+ const existing =
+ typeof step.context === "string" ? step.context : JSON.stringify(step.context);
+ return { ...step, context: `${existing}\n${suffix}` };
}),
};
}
diff --git a/packages/react-ui/src/genui-lib/openuiChatLibrary.tsx b/packages/react-ui/src/genui-lib/openuiChatLibrary.tsx
index da3ea85ab..57706918a 100644
--- a/packages/react-ui/src/genui-lib/openuiChatLibrary.tsx
+++ b/packages/react-ui/src/genui-lib/openuiChatLibrary.tsx
@@ -311,8 +311,8 @@ export const openuiChatComponentGroups: ComponentGroup[] = [
"- Use ListBlock with ListItem references for numbered lists.",
"- Use FollowUpBlock with FollowUpItem references at the end of a response to suggest next actions.",
"- A ListItem is clickable ONLY when given an action (5th argument); without one it is plain text.",
- "- Clicking a FollowUpItem, or a ListItem with a continue_conversation action, sends text to the LLM as a user message.",
- '- Example: list = ListBlock([item1, item2]) item1 = ListItem("Option A", "Details about A", null, null, { type: "continue_conversation", context: "Option A" })',
+ "- Clicking a FollowUpItem, or a ListItem with a @ToAssistant action, sends text to the LLM as a user message.",
+ '- Example: list = ListBlock([item1, item2]) item1 = ListItem("Option A", "Details about A", null, null, @ToAssistant("Option A"))',
],
},
{
diff --git a/packages/react-ui/src/genui-lib/prompt-options/index.ts b/packages/react-ui/src/genui-lib/prompt-options/index.ts
index 30a76777f..96d5db0c1 100644
--- a/packages/react-ui/src/genui-lib/prompt-options/index.ts
+++ b/packages/react-ui/src/genui-lib/prompt-options/index.ts
@@ -33,7 +33,7 @@ emailField = FormControl("Email", Input("email", "[email protected]", "email", { r
countryField = FormControl("Country", Select("country", countryOpts, "Select...", { required: true }))
msgField = FormControl("Message", TextArea("message", "Tell us more...", 4, { required: true, minLength: 10 }))
countryOpts = [SelectItem("us", "United States"), SelectItem("uk", "United Kingdom"), SelectItem("de", "Germany")]
-btns = Buttons([Button("Submit", Action([@ToAssistant("Submit")]), "primary"), Button("Cancel", Action([@ToAssistant("Cancel")]), "secondary")])`,
+btns = Buttons([Button("Submit", @ToAssistant("Submit"), "primary"), Button("Cancel", @ToAssistant("Cancel"), "secondary")])`,
`Example 4 — Tabs with mixed content:
@@ -69,13 +69,13 @@ p1header = IconText(p1icon, "neutral", "m", "Widget Pro", "Best seller", true, "
p1icon = Icon("package", "shopping")
p1body = MetricIndicatorInline("2,410 units", "Sold this month", { direction: "up", value: 12 })
p1footer = { price: BoldText("text", "$29.00"), button: p1btn }
-p1btn = Button("View Details", Action([@ToAssistant("Show details for Widget Pro")]), "secondary")
+p1btn = Button("View Details", @ToAssistant("Show details for Widget Pro"), "secondary")
p2 = CompositeCardItem("widget-mini", p2header, [p2body], p2footer)
p2header = IconText(p2icon, "neutral", "m", "Widget Mini", "New arrival", true, "horizontal")
p2icon = Icon("box", "shopping")
p2body = MetricIndicatorInline("980 units", "Sold this month", { direction: "up", value: 4 })
p2footer = { price: BoldText("text", "$14.00"), button: p2btn }
-p2btn = Button("View Details", Action([@ToAssistant("Show details for Widget Mini")]), "secondary")`,
+p2btn = Button("View Details", @ToAssistant("Show details for Widget Mini"), "secondary")`,
`Example 6 — Editable table and a selection form:
@@ -105,7 +105,7 @@ tool2 = ChipItem("slack", "Slack", tool2icon)
tool2icon = Icon("message-square", "communication")
tool3 = ChipItem("notion", "Notion", tool3icon)
tool3icon = Icon("notebook", "text")
-formButtons = Buttons([Button("Save", Action([@ToAssistant("Save preferences")]), "primary")])`,
+formButtons = Buttons([Button("Save", @ToAssistant("Save preferences"), "primary")])`,
];
export const openuiAdditionalRules: string[] = [
@@ -139,7 +139,7 @@ export const openuiChatExamples: string[] = [
root = Card([header, intro, highlights, statsHeader, statsCards, sectionsBlock, actionBtns], [src1, src2])
header = CardHeader("Paris", "The City of Light · France's Eternal Capital")
intro = TextContent("Paris is one of the world's most visited cities — a timeless blend of iconic landmarks, world-class cuisine, art, and romance [1]. In 2026 the city is buzzing with new energy: the **Grand Palais** has reopened after a €466M renovation, and you can now **swim in the Seine** for the first time in over a century [2].")
-highlights = ContextCardBlock([h1, h2, h3], "grid", true, { type: "continue_conversation", context: "Tell me more about this aspect of Paris" })
+highlights = ContextCardBlock([h1, h2, h3], "grid", true, @ToAssistant("Tell me more about this aspect of Paris"))
h1 = ContextCardItem("art-museums", "Art & Museums", "143 museums including the Louvre & newly reopened Grand Palais.", "gray", "https://cdn.britannica.com/03/121003-050-2544BD4E/Interior-Louvre-Museum-Paris.jpg")
h2 = ContextCardItem("gastronomy", "Gastronomy", "9,000+ restaurants, 130+ Michelin stars, and the world's best baguettes.", "gray")
h3 = ContextCardItem("fashion-capital", "Fashion Capital", "Home to Chanel, Dior, Louis Vuitton & Hermès — the global luxury hub.", "gray", "https://thumbs.dreamstime.com/z/dior-storefront-facade-chanel-store-lvmh-s-french-designer-modehouse-christian-adjacent-to-luxury-fashion-beauty-brand-327161553.jpg")
@@ -159,7 +159,7 @@ ov3icon = Icon("circle-dollar-sign", "finance")
ov3metric = MetricIndicatorInline("€23.4B", "generated")
sectionsBlock = SectionBlock([secLandmarks, secFood, secWhen], false)
secLandmarks = SectionItem("landmarks", "Iconic Landmarks", [landmarksCarousel])
-landmarksCarousel = VisualCardBlock([lm1, lm2, lm3, lm4], "carousel", true, { type: "continue_conversation", context: "Tell me more about this Paris landmark" })
+landmarksCarousel = VisualCardBlock([lm1, lm2, lm3, lm4], "carousel", true, @ToAssistant("Tell me more about this Paris landmark"))
lm1 = VisualCardItem(lm1body, "eiffel-tower", "https://c8.alamy.com/comp/RYEB13/aerial-view-of-the-eiffel-tower-with-the-park-champ-de-mars-and-the-river-seine-paris-france-RYEB13.jpg", lm1tag, "Aerial view of the Eiffel Tower")
lm1body = BoldText("text", "Eiffel Tower", "Open daily 9am–midnight")
lm1tag = Tag("Must-See", lm1tagIcon, "sm", "info")
@@ -177,7 +177,7 @@ lm4body = BoldText("text", "Palace of Versailles", "Royal gardens & grand halls"
lm4tag = Tag("Day Trip", lm4tagIcon, "sm", "neutral")
lm4tagIcon = Icon("train-front", "travel")
secFood = SectionItem("food", "Food & Drink", [foodCards])
-foodCards = ContextCardBlock([f1, f2, f3], "grid", true, { type: "continue_conversation", context: "Tell me more about eating and drinking in Paris" })
+foodCards = ContextCardBlock([f1, f2, f3], "grid", true, @ToAssistant("Tell me more about eating and drinking in Paris"))
f1 = ContextCardItem("bistros", "Bistros", "Classic French fare — try Les Arlots for confit beef cheeks.", "gray", "https://everydayparisian.com/wp-content/uploads/2023/01/IMG_0221-768x1024.webp")
f2 = ContextCardItem("fine-dining", "Fine Dining", "Septime leads a new wave of creative Michelin-starred cuisine.", "gray", "https://production-data.worldofmouth.app/images/72b2e6db-97ea-49c4-aa5d-3b7c8121c812.jpg")
f3 = ContextCardItem("bakeries", "Bakeries", "Shinya Pain for sourdough. Grand Prix-winning baguettes citywide.", "gray", "https://www.davidlebovitz.com/wp-content/uploads/2018/09/Le-petit-grain-paris-bakery-boulangerie-patisserie-pastry-shop-8-640x895.jpg")
@@ -185,18 +185,18 @@ secWhen = SectionItem("when", "Best Time to Visit", [whenTabs])
whenTabs = Tabs([tabSpring, tabSummer])
tabSpring = TabItem("spring", "Spring", [springList])
springList = ListBlock([sp1, sp2, sp3], "number")
-sp1 = ListItem("Cherry blossoms at Parc de Sceaux", "March – May", null, null, { type: "continue_conversation", context: "Tell me about cherry blossom season in Paris" })
-sp2 = ListItem("Picnics along the Seine & in city parks", "Warm, lively atmosphere", null, null, { type: "continue_conversation", context: "Where are the best picnic spots in Paris?" })
-sp3 = ListItem("Fewer crowds than summer", "Ideal for sightseeing", null, null, { type: "continue_conversation", context: "How busy is Paris in spring?" })
+sp1 = ListItem("Cherry blossoms at Parc de Sceaux", "March – May", null, null, @ToAssistant("Tell me about cherry blossom season in Paris"))
+sp2 = ListItem("Picnics along the Seine & in city parks", "Warm, lively atmosphere", null, null, @ToAssistant("Where are the best picnic spots in Paris?"))
+sp3 = ListItem("Fewer crowds than summer", "Ideal for sightseeing", null, null, @ToAssistant("How busy is Paris in spring?"))
tabSummer = TabItem("summer", "Summer", [summerList])
summerList = ListBlock([su1, su2, su3], "number")
-su1 = ListItem("Swim in the Seine — open July & August 2026", "First time in 102 years", null, null, { type: "continue_conversation", context: "Tell me about swimming in the Seine" })
-su2 = ListItem("Open-air cinema at Parc de la Villette", "Free films under the stars", null, null, { type: "continue_conversation", context: "Tell me about the open-air cinema at Parc de la Villette" })
-su3 = ListItem("Bastille Day celebrations on July 14", "Fireworks at the Eiffel Tower", null, null, { type: "continue_conversation", context: "What happens in Paris on Bastille Day?" })
+su1 = ListItem("Swim in the Seine — open July & August 2026", "First time in 102 years", null, null, @ToAssistant("Tell me about swimming in the Seine"))
+su2 = ListItem("Open-air cinema at Parc de la Villette", "Free films under the stars", null, null, @ToAssistant("Tell me about the open-air cinema at Parc de la Villette"))
+su3 = ListItem("Bastille Day celebrations on July 14", "Fireworks at the Eiffel Tower", null, null, @ToAssistant("What happens in Paris on Bastille Day?"))
actionBtns = Buttons([btn1, btn2, btn3], "row")
-btn1 = Button("Plan a Trip to Paris", { type: "continue_conversation", context: "Help me plan a trip to Paris" }, "primary")
-btn2 = Button("Best Hotels in Paris", { type: "continue_conversation", context: "Show me the best hotels in Paris" }, "secondary")
-btn3 = Button("Build a Paris Itinerary", { type: "continue_conversation", context: "Build a 5-day Paris itinerary for me" }, "secondary")
+btn1 = Button("Plan a Trip to Paris", @ToAssistant("Help me plan a trip to Paris"), "primary")
+btn2 = Button("Best Hotels in Paris", @ToAssistant("Show me the best hotels in Paris"), "secondary")
+btn3 = Button("Build a Paris Itinerary", @ToAssistant("Build a 5-day Paris itinerary for me"), "secondary")
src1 = { title: "Paris Travel Guide 2025", sourceName: "Travel and Tour World", url: "https://www.travelandtourworld.com/news/article/from-iconic-landmarks-to-hidden-gems-the-ultimate-paris-travel-guide-for-2025-you-need-to-read-now/" }
src2 = { title: "Best Things to Do in Paris 2026", sourceName: "Time Out Paris", url: "http://www.timeout.fr/paris/en/for-tourists" }`,
@@ -250,7 +250,7 @@ colCac = Col("CAC ($)", [188, 395, 132, 109, 218, 154], "number")
colRevenue = Col("Revenue ($k)", [82.4, 68.1, 54.6, 38.2, 26.8, 14.4], "number")
colStatus = Col("Status", ["Scaling", "Optimizing", "Scaling", "Growing", "Stable", "Stable"], "string")
deepDiveHeader = InlineHeader("Support Health & Marketing ROI", "Click a card to explore deeper insights")
-compositeCards = CompositeCardBlock([cardSupport, cardMarketing], "grid", true, { type: "continue_conversation", context: "Explore this deep-dive area in more detail" })
+compositeCards = CompositeCardBlock([cardSupport, cardMarketing], "grid", true, @ToAssistant("Explore this deep-dive area in more detail"))
cardSupport = CompositeCardItem("support-health", supportHeader, [supportMetric, supportChart, supportList])
supportHeader = IconText(supportIcon, "neutral", "m", "Support Health", "Ticket volume & resolution trends", false, "horizontal")
supportIcon = Icon("headphones", "communication")
@@ -274,15 +274,15 @@ mkt1 = { left: "Total Ad Spend (Apr)", right: "$51,600", rightVariant: "number"
mkt2 = { left: "Cost per Lead", right: "$48.20", rightVariant: "number" }
mkt3 = { left: "Top Channel", right: "Organic Search", rightVariant: "text" }
actionButtons = Buttons([btnChannels, btnForecast], "row")
-btnChannels = Button("Break Down by Channel", { type: "continue_conversation", context: "Break down this month's revenue by acquisition channel" }, "primary")
-btnForecast = Button("Forecast Next Quarter", { type: "continue_conversation", context: "Forecast revenue and active users for next quarter" }, "secondary")`,
+btnChannels = Button("Break Down by Channel", @ToAssistant("Break down this month's revenue by acquisition channel"), "primary")
+btnForecast = Button("Forecast Next Quarter", @ToAssistant("Forecast revenue and active users for next quarter"), "secondary")`,
`Example 3 — Form response (help-me-choose/plan asks: inspiration cards FIRST, then a compact form). The inspiration-card images below came from an image tool call — include such cards ONLY when you have real URLs; with no real URLs, start directly with the form:
root = Card([header, intro, inspoCards, form])
header = CardHeader("Plan Your Trip", "A few ideas to spark inspiration — then tell me your preferences")
intro = TextContent("Tap a style to jump straight in, or fill the quick form below for a tailored plan.")
-inspoCards = VisualCardBlock([insp1, insp2], "grid", true, { type: "continue_conversation", context: "Plan me a trip in this style with destinations, itinerary, and costs" })
+inspoCards = VisualCardBlock([insp1, insp2], "grid", true, @ToAssistant("Plan me a trip in this style with destinations, itinerary, and costs"))
insp1 = VisualCardItem(insp1body, "inspo-beach", "https://www.travelandleisure.com/thmb/cuAB7XMQ6s_Gji-no956KNopT7M=/1500x0/filters:no_upscale():max_bytes(150000):strip_icc()/TAL-maldives-TROPVACAY0325-1b5047d5931d4850b47d082966f9f563.jpg", insp1tag, "Maldives overwater villas")
insp1body = BoldText("text", "Tropical Beach Escape", "Overwater villas & snorkeling")
insp1tag = Tag("Relaxation", insp1icon, "sm", "info")
@@ -293,8 +293,8 @@ insp2tag = Tag("Active", insp2icon, "sm", "warning")
insp2icon = Icon("mountain", "nature")
form = Form("trip-planner", formButtons, [fcDestination, fcDates, fcTravellers, fcTripType, fcBudget, fcStay, fcNotes])
formButtons = Buttons([btnSubmit, btnSkip], "row")
-btnSubmit = Button("Plan My Trip", { type: "continue_conversation", context: "Help me plan a trip based on my form submission" }, "primary")
-btnSkip = Button("Just Surprise Me", { type: "continue_conversation", context: "Skip the form and surprise me with a destination and itinerary" }, "secondary")
+btnSubmit = Button("Plan My Trip", @ToAssistant("Help me plan a trip based on my form submission"), "primary")
+btnSkip = Button("Just Surprise Me", @ToAssistant("Skip the form and surprise me with a destination and itinerary"), "secondary")
fcDestination = FormControl("Destination", destinationInput, "Leave blank if you'd like suggestions")
destinationInput = Input("destination", "e.g. Tokyo, Japan — or leave blank", "text")
fcDates = FormControl("Travel Dates", datesPicker, "Select your start and end dates")
@@ -335,7 +335,7 @@ notesArea = TextArea("special-requests", "e.g. vegetarian meals, wheelchair acce
root = Card([header, intro, posters, linksHeader, trackCards], [src1, src2])
header = CardHeader("Retro-Energetic Indian Tracks", "New Hindi releases with 80s/90s dance DNA")
intro = TextContent("These recent tracks channel retro synths and 90s party percussion [1][2]. Tap a poster to explore a track, or use its button to watch the exact official video.")
-posters = VisualCardBlock([v1, v2], "grid", true, { type: "continue_conversation", context: "Tell me more about this track and its retro influences" })
+posters = VisualCardBlock([v1, v2], "grid", true, @ToAssistant("Tell me more about this track and its retro influences"))
v1 = VisualCardItem(v1body, "tamma", "https://i.ytimg.com/vi/PQHeOb0Q9oo/hq720.jpg", v1tag, "Tamma Tamma video poster")
v1body = BoldText("text", "Tamma Tamma", "Dhurandhar · Ranveer Singh")
v1tag = Tag("80s Electro-Disco", v1icon, "sm", "success")
@@ -351,13 +351,13 @@ t1h = IconText(t1icon, "neutral", "m", "Tamma Tamma", "Bappi Lahiri classic, ele
t1icon = Icon("disc-3", "multimedia")
t1body = Text("text", "Heavy analog synths and brass over a fast disco groove.", "Retro Electro-Disco")
t1tags = TagBlock(["2026 Film Hit", "Peak Party"])
-t1btn = Button("Watch on YouTube", { type: "open_url", url: "https://www.youtube.com/watch?v=PQHeOb0Q9oo" }, "primary")
+t1btn = Button("Watch on YouTube", @OpenUrl("https://www.youtube.com/watch?v=PQHeOb0Q9oo"), "primary")
t2 = CompositeCardItem("t-sajan", t2h, [t2body, t2tags], { button: t2btn })
t2h = IconText(t2icon, "neutral", "m", "Sajan Re", "Nora Fatehi · Badshah · Sanjoy", true, "horizontal")
t2icon = Icon("music", "multimedia")
t2body = Text("text", "Synthwave melody hooks over a modern club beat.", "Retro-Fusion Electro")
t2tags = TagBlock(["Club Anthem", "Nora x Badshah"])
-t2btn = Button("Watch on YouTube", { type: "open_url", url: "https://www.youtube.com/watch?v=COUSCnFazzc" }, "primary")
+t2btn = Button("Watch on YouTube", @OpenUrl("https://www.youtube.com/watch?v=COUSCnFazzc"), "primary")
src1 = { title: "Tamma Tamma (Full Video) - Dhurandhar", sourceName: "YouTube (T-Series)", url: "https://www.youtube.com/watch?v=PQHeOb0Q9oo" }
src2 = { title: "Sajan Re (Official Music Video)", sourceName: "YouTube (T-Series)", url: "https://www.youtube.com/watch?v=COUSCnFazzc" }`,
@@ -393,8 +393,8 @@ export const openuiChatAdditionalRules: string[] = [
"If no image URL is in context, compose without image components — icons, gray ContextCardItems, and charts still make rich layouts.",
"Argument-order trap: Image takes alt FIRST, while ImageBlock, ImageText, and ImageTextLarge take src FIRST — alt text in a src slot ships a broken image.",
'Card blocks (SnippetCardBlock, OverviewCardBlock, ContextCardBlock, CompositeCardBlock, VisualCardBlock) need at least 2 items, all with the same structure; use layout "grid" for primary side-by-side comparison and "carousel" for secondary browsing.',
- 'The card-block action is BLOCK-LEVEL: one action shared by every card, with the clicked card\'s details attached automatically — keep continue_conversation context generic (e.g. "Tell me more about this destination"), and never use a block-level open_url since it would send every card to the same URL.',
- 'Card items have NO per-item action: to give each item its own external link, use CompositeCardItem with footer { button: Button(label, { type: "open_url", url }) } — never claim a card opens a link it cannot.',
+ 'The card-block action is BLOCK-LEVEL: one action shared by every card, with the clicked card\'s details attached automatically — keep the @ToAssistant message generic (e.g. "Tell me more about this destination"), and never use a block-level @OpenUrl since it would send every card to the same URL.',
+ "Card items have NO per-item action: to give each item its own external link, use CompositeCardItem with footer { button: Button(label, @OpenUrl(url)) } — never claim a card opens a link it cannot.",
"Text, BoldText, IconText, ImageText, ImageTextLarge and MetricIndicator* are inline building blocks used INSIDE card items — do not place them directly in the root Card.",
'EntityList size "small" is reserved for CompositeCardItem body content (no header/footer); use size "default" elsewhere.',
"Tag variant must be semantically correct (success=positive, danger=negative, warning=cautionary, info=informational, neutral=label); Tag takes an optional Icon second, so use Tag(text, icon, size, variant) when a variant is needed.",
@@ -410,8 +410,8 @@ export const openuiChatAdditionalRules: string[] = [
'Every Form MUST have EXACTLY ONE submit Button with variant "primary" — that button validates the form; other buttons (secondary/tertiary escape hatches like "Just Surprise Me") skip validation, and there is never a reset button.',
"Prefer structured inputs (Select, Chips, OptionCards, DatePicker, Slider) over free-text Input, give every FormControl a clear label (and a hint where it prevents mistakes), and keep each field name unique within the response.",
"Validation rules ({ required: true, email: true, minLength: 8, ... }) are enforced with inline errors — use them for genuinely essential fields, but never require a free-text field where leaving it blank is meaningful.",
- "Form inputs work ONLY inside a FormControl within a Form; for tappable suggestion choices OUTSIDE a form, use Buttons of continue_conversation Buttons — never a bare OptionCards or Chips.",
- "Only add Buttons for real actions: form submit, open_url with a URL from a tool or the user (never fabricated), or a continue_conversation follow-up — never a button for an app action (open, download, export, edit) you cannot perform.",
+ "Form inputs work ONLY inside a FormControl within a Form; for tappable suggestion choices OUTSIDE a form, use Buttons whose Button actions are @ToAssistant, never a bare OptionCards or Chips.",
+ "Only add Buttons for real actions: form submit, @OpenUrl with a URL from a tool or the user (never fabricated), or a @ToAssistant follow-up. Never add a button for an app action (open, download, export, edit) you cannot perform.",
'Every Button label must accurately describe what clicking it does; use "primary" for the main action and "secondary"/"tertiary" only for lower-emphasis supporting actions.',
"Icon: always include the category argument — it enables fallback matching when the exact lucide name is unavailable.",
"Pass sources on Card ONLY when the answer relies on real references you actually have, and cite them inline in TextContent as [1], [2] (1-based index into sources).",
diff --git a/packages/react-ui/src/utils/__tests__/messages.test.ts b/packages/react-ui/src/utils/__tests__/messages.test.ts
new file mode 100644
index 000000000..5f36b4257
--- /dev/null
+++ b/packages/react-ui/src/utils/__tests__/messages.test.ts
@@ -0,0 +1,48 @@
+import { buildMessage, type BuildMessageInput } from "@openuidev/react-lang";
+import { expect, it } from "vitest";
+import { readMessage } from "../messages";
+
+// Stored bytes as the old sentinelParser wrote them (wrapContent, wrapContentWithHeader, wrapContext)
+const stored: {
+ raw: string;
+ content: string;
+ context: unknown[] | null;
+ write?: Partial<BuildMessageInput>;
+}[] = [
+ { raw: "Hello", content: "Hello", context: null },
+ { raw: "]]>openui:content\nroot = A()", content: "root = A()", context: null, write: {} },
+ {
+ raw: "]]>openui:content?libraryVersion=0.5&v=2\nroot = A()\n]]>openui:end",
+ content: "root = A()",
+ context: null,
+ write: { attributes: { libraryVersion: "0.5", v: "2" }, end: true },
+ },
+ {
+ raw: ']]>openui:content?v=2\nroot = A()\n]]>openui:context\n[{"$a":{"value":1}}]',
+ content: "root = A()",
+ context: [{ $a: { value: 1 } }],
+ write: { attributes: { v: "2" } },
+ },
+ {
+ raw: ']]>openui:content\nSave\n]]>openui:context\n["User clicked: Save",{"$a":1}]',
+ content: "Save",
+ context: ["User clicked: Save", { $a: 1 }],
+ write: {},
+ },
+ { raw: '\n]]>openui:context\n["User clicked: "]', content: "", context: ["User clicked: "] },
+ {
+ raw: '<content version="2">root = A()</content><context>[1]</context>',
+ content: "root = A()",
+ context: [1],
+ },
+];
+
+it("reads and writes stored messages like the old sentinelParser", () => {
+ for (const { raw, content, context, write } of stored) {
+ expect(readMessage(raw)).toMatchObject({ content, context });
+ if (write) expect(buildMessage({ content, context: context ?? undefined, ...write })).toBe(raw);
+ }
+ expect(readMessage("]]>openui:content\nroot = A()\n]]>openui:con", true).content).toBe(
+ "root = A()",
+ );
+});
diff --git a/packages/react-ui/src/utils/messages.ts b/packages/react-ui/src/utils/messages.ts
index 2b2aa2232..4b5b4beea 100644
--- a/packages/react-ui/src/utils/messages.ts
+++ b/packages/react-ui/src/utils/messages.ts
@@ -4,6 +4,7 @@ import {
type Message,
type ToolActivity,
} from "@openuidev/react-headless";
+import { parseMessage, type ParsedMessage } from "@openuidev/react-lang";
type ArtifactRendererRegistry = ReturnType<typeof useArtifactRendererRegistry>;
@@ -26,3 +27,28 @@ export function getMatchedRendererActivities(
): ToolActivity[] {
return activities.filter((a) => !!(registry && lookupArtifactRenderer(registry, a.toolName)));
}
+
+/** parseMessage, plus older stored XML: `<content version="2">root = A()</content><context>[1]</context>` */
+export function readMessage(raw: string, streaming = false): ParsedMessage {
+ const parsed = parseMessage(raw, { streaming });
+ if (raw.includes("]]>openui:")) return parsed;
+ let content = parsed.content;
+ let context: unknown = null;
+ const contextMatch = content.match(/<context>([\s\S]*)<\/context>\s*$/);
+ if (contextMatch) {
+ context = contextMatch[1];
+ content = content.slice(0, contextMatch.index).trimEnd();
+ try {
+ context = JSON.parse(contextMatch[1]!);
+ } catch {
+ // Not JSON: keep the raw text, like parseMessage.
+ }
+ }
+ content = content.match(/^<content[^>]*>([\s\S]*)<\/content>\s*$/)?.[1] ?? content;
+ return { ...parsed, content, context };
+}
+
+/** True when content has OpenUI Lang: a ```openui-lang fence or an unfenced `root =` line. */
+export function hasLangSyntax(content: string | null | undefined): boolean {
+ return !!content && (content.includes("```openui-lang") || /(^|\n)\s*root\s*=/.test(content));
+}
diff --git a/packages/react-ui/src/utils/sentinelParser.ts b/packages/react-ui/src/utils/sentinelParser.ts
deleted file mode 100644
index 11c6d660c..000000000
--- a/packages/react-ui/src/utils/sentinelParser.ts
+++ /dev/null
@@ -1,234 +0,0 @@
-const OPENUI_INLINE_SENTINEL = "]]>openui:";
-const CONTENT_MARKER = `${OPENUI_INLINE_SENTINEL}content`;
-const CONTEXT_MARKER = `${OPENUI_INLINE_SENTINEL}context`;
-const END_MARKER = `${OPENUI_INLINE_SENTINEL}end`;
-
-// Tokens whose partial prefix can sit at the tail of a still-streaming chunk.
-// Trimming keeps a half-arrived marker from flashing as raw text; the next
-// delta re-parses the full message, so any false positive is transient.
-const STREAM_PARTIAL_TOKENS = [CONTENT_MARKER, CONTEXT_MARKER, END_MARKER];
-
-export interface ParsedMessageContent {
- content: string;
- contextString: string | null;
- contentHeader?: string;
- /**
- * True when the bare `]]>openui:end` liveness marker was present — the
- * stream reached its terminal chunk. Absent on a PERSISTED message ⇒ the
- * stream died mid-write. HOW a response ended is structural (output item
- * `status` + the Responses terminal event), never in-band bytes.
- */
- end?: boolean;
-}
-
-export function wrapContent(text: string): string {
- return `${CONTENT_MARKER}\n${text}`;
-}
-
-// Round-trip the original header verbatim so its attrs (libraryVersion, etc.)
-// survive form-state persistence.
-export function wrapContentWithHeader(text: string, contentHeader?: string): string {
- return contentHeader ? `${contentHeader}\n${text}` : wrapContent(text);
-}
-
-export function wrapContext(json: string): string {
- return `\n${CONTEXT_MARKER}\n${json}`;
-}
-
-// Separate openui-lang code from inline context in a message, stripping
-// display-only noise: the bare end marker and partial streaming tails. The
-// raw message bytes in the store stay untouched.
-export function separateContentAndContext(raw: string): ParsedMessageContent {
- const { text, end } = extractEndMarker(raw);
- const sections = splitSections(text);
- const content = stripStreamingTail(sections.content);
- return { ...sections, content, ...(end ? { end: true } : {}) };
-}
-
-/**
- * Whether the content carries recognizable OpenUI-lang syntax — the
- * ```openui-lang ``` fence, or a top-level `root =` binding when emitted
- * unfenced.
- */
-export function hasLangSyntax(content: string | null | undefined): boolean {
- return !!content && (content.includes("```openui-lang") || /(^|\n)\s*root\s*=/.test(content));
-}
-
-// The ordered section walk over the inline-sentinel format.
-function splitSections(raw: string): {
- content: string;
- contextString: string | null;
- contentHeader?: string;
-} {
- const lastContentIdx = raw.lastIndexOf(CONTENT_MARKER);
- const lastContextIdx = raw.lastIndexOf(CONTEXT_MARKER);
-
- // No inline markers: fall back to the deprecated XML envelope so messages
- // persisted by older app versions still round-trip on reload.
- if (lastContentIdx === -1 && lastContextIdx === -1) {
- return parseLegacyXml(raw);
- }
-
- // Only context section
- if (lastContentIdx === -1) {
- return {
- content: stripSectionSeparator(raw.slice(0, lastContextIdx)),
- contextString: raw.slice(bodyStartIndex(raw, lastContextIdx)),
- };
- }
-
- // Content-only response
- if (lastContextIdx === -1 || lastContentIdx > lastContextIdx) {
- return {
- content: raw.slice(bodyStartIndex(raw, lastContentIdx)),
- contextString: null,
- contentHeader: contentHeader(raw, lastContentIdx),
- };
- }
-
- // Content section followed by context section
- return {
- content: stripSectionSeparator(raw.slice(bodyStartIndex(raw, lastContentIdx), lastContextIdx)),
- contextString: raw.slice(bodyStartIndex(raw, lastContextIdx)),
- contentHeader: contentHeader(raw, lastContentIdx),
- };
-}
-
-// Strip every `]]>openui:end` marker LINE and report presence. Mirrors the
-// backend's inline-format 'end' case: the separator newline before the marker
-// is removed, header attrs on the marker line are ignored (a future
-// `?status=…` form must not break display), and defensive trailing text after
-// the line stays with the section it interrupted.
-function extractEndMarker(raw: string): { text: string; end: boolean } {
- let text = raw;
- let end = false;
- for (let idx = text.indexOf(END_MARKER); idx !== -1; idx = text.indexOf(END_MARKER)) {
- end = true;
- const lineEnd = text.indexOf("\n", idx);
- const before = stripSectionSeparator(text.slice(0, idx));
- const after = lineEnd === -1 ? "" : text.slice(lineEnd + 1);
- text = after === "" ? before : `${before}\n${after}`;
- }
- return { text, end };
-}
-
-// Trim a PROPER prefix of a marker token sitting at the very end of the
-// content. Full tokens are handled upstream (the section walk); this only
-// suppresses the one-frame flash while a chunk boundary splits a token.
-function stripStreamingTail(content: string): string {
- let trim = 0;
- for (const token of STREAM_PARTIAL_TOKENS) {
- const max = Math.min(token.length - 1, content.length);
- for (let k = max; k > trim; k--) {
- if (content.endsWith(token.slice(0, k))) {
- trim = k;
- break;
- }
- }
- }
- return trim > 0 ? stripSectionSeparator(content.slice(0, content.length - trim)) : content;
-}
-
-function contentHeader(raw: string, markerIdx: number): string {
- const headerEndIdx = raw.indexOf("\n", markerIdx);
- return headerEndIdx === -1 ? raw.slice(markerIdx) : raw.slice(markerIdx, headerEndIdx);
-}
-
-function bodyStartIndex(raw: string, markerIdx: number): number {
- const headerEndIdx = raw.indexOf("\n", markerIdx);
- return headerEndIdx === -1 ? raw.length : headerEndIdx + 1;
-}
-
-function stripSectionSeparator(value: string): string {
- if (value.endsWith("\r\n")) {
- return value.slice(0, -2);
- }
- if (value.endsWith("\n")) {
- return value.slice(0, -1);
- }
- return value;
-}
-
-/**
- * @deprecated Legacy `<content>`/`<context>` XML envelope. Retained only to
- * parse messages persisted before the inline sentinel format; new messages are
- * always wrapped with {@link wrapContent}/{@link wrapContext}.
- */
-function parseLegacyXml(raw: string): { content: string; contextString: string | null } {
- let content = raw;
- let contextString: string | null = null;
-
- const contextMatch = raw.match(/<context>([\s\S]*)<\/context>\s*$/);
- if (contextMatch) {
- contextString = contextMatch[1] ?? null;
- content = raw.slice(0, contextMatch.index!).trimEnd();
- }
-
- const contentMatch = content.match(/^<content[^>]*>([\s\S]*)<\/content>\s*$/);
- if (contentMatch) {
- content = contentMatch[1] ?? content;
- }
-
- return { content, contextString };
-}
-
-// ---------------------------------------------------------------------------
-// Artifact sentinel — the `]]>openui:artifact` member of the inline-sentinel
-// family. Unlike content/context (assistant-message channel), this rides the
-// tool-result channel (function_call_output + response.artifact_call.delta).
-// Carrier: `]]>openui:artifact <header-json>\n<program>` (header-only on a
-// stripped reload). Byte-mirrors the example renderer's parseArtifact.ts and
-// the backend builder (muse artifact-shared.ts buildArtifactSentinel).
-// ---------------------------------------------------------------------------
-const ARTIFACT_MARKER = `${OPENUI_INLINE_SENTINEL}artifact`;
-
-export type ArtifactKind = "slides" | "report";
-
-export interface ArtifactSentinelHeader {
- artifact_id: string;
- type: ArtifactKind;
- name?: string;
- version?: string;
-}
-
-const ARTIFACT_KIND_BY_TYPE: Record<string, ArtifactKind> = {
- slides: "slides",
- presentation: "slides",
- report: "report",
-};
-
-/**
- * Parse the artifact carrier `]]>openui:artifact <header-json>\n<program>` into
- * the validated header + raw program (program is "" on a stripped reload).
- * Returns null when `raw` is not an artifact sentinel.
- */
-export function parseArtifactSentinel(
- raw: unknown,
-): { header: ArtifactSentinelHeader; program: string } | null {
- if (typeof raw !== "string") return null;
- const prefix = `${ARTIFACT_MARKER} `;
- if (!raw.startsWith(prefix)) return null;
- const nl = raw.indexOf("\n");
- const headerStr = nl === -1 ? raw.slice(prefix.length) : raw.slice(prefix.length, nl);
- const program = nl === -1 ? "" : raw.slice(nl + 1);
- let parsed: unknown;
- try {
- parsed = JSON.parse(headerStr);
- } catch {
- return null;
- }
- if (typeof parsed !== "object" || parsed === null) return null;
- const h = parsed as Record<string, unknown>;
- if (typeof h["artifact_id"] !== "string" || h["artifact_id"] === "") return null;
- const kind = typeof h["type"] === "string" ? ARTIFACT_KIND_BY_TYPE[h["type"]] : undefined;
- if (kind === undefined) return null;
- return {
- header: {
- artifact_id: h["artifact_id"],
- type: kind,
- ...(typeof h["name"] === "string" && h["name"] !== "" ? { name: h["name"] } : {}),
- ...(typeof h["version"] === "string" && h["version"] !== "" ? { version: h["version"] } : {}),
- },
- program,
- };
-}
diff --git a/packages/server/src/shared/utils.test.ts b/packages/server/src/shared/utils.test.ts
new file mode 100644
index 000000000..a295825ff
--- /dev/null
+++ b/packages/server/src/shared/utils.test.ts
@@ -0,0 +1,13 @@
+import { parse } from "@openuidev/lang-core";
+import { expect, it } from "vitest";
+import { errorsOf } from "./utils";
+
+const schema = new Map([["Card", { params: [{ name: "children", required: true }] }]]);
+
+it("errorsOf ignores the no-root fallback warning but reports a missing entry", () => {
+ expect(errorsOf(parse("page = Card([])", schema, "Card"))).toEqual([]);
+ expect(errorsOf(parse("x = 1", schema, "Card")).map((e) => e.code)).toEqual([
+ "no-root",
+ "missing-root",
+ ]);
+});
diff --git a/packages/server/src/shared/utils.ts b/packages/server/src/shared/utils.ts
index a6169b5c1..d3964a896 100644
--- a/packages/server/src/shared/utils.ts
+++ b/packages/server/src/shared/utils.ts
@@ -3,9 +3,10 @@ import type { AutofixDiagnostic, AutofixResult, BaseAutofixInput } from "./types
import { AutofixError } from "./types";
// Collect parser errors, missing references, and incomplete output into diagnostics.
-export function errorsOf({ root, meta }: ParseResult): AutofixDiagnostic[] {
+// Warnings (the program still renders) are not errors and never trigger a fix.
+export function errorsOf({ root, rootExpression, meta }: ParseResult): AutofixDiagnostic[] {
return [
- ...meta.errors,
+ ...meta.errors.filter((error) => error.severity !== "warning"),
...meta.unresolved.map((name) => ({
code: "unresolved",
statementId: name,
@@ -17,7 +18,9 @@ export function errorsOf({ root, meta }: ParseResult): AutofixDiagnostic[] {
message: `Statement "${name}" is not reachable from root`,
})),
...(meta.incomplete ? [{ code: "incomplete", message: "Generation ends mid-statement" }] : []),
- ...(root === null ? [{ code: "missing-root", message: "No root element" }] : []),
+ ...(root === null && !rootExpression
+ ? [{ code: "missing-root", message: "No root element" }]
+ : []),
];
}
diff --git a/packages/svelte-lang/package.json b/packages/svelte-lang/package.json
index 0668d8451..a422257f2 100644
--- a/packages/svelte-lang/package.json
+++ b/packages/svelte-lang/package.json
@@ -28,7 +28,7 @@
"prepare": "pnpm run build",
"check": "svelte-check --tsconfig ./tsconfig.json",
"test": "vitest run",
- "ci": "pnpm run lint:check && pnpm run format:check"
+ "ci": "pnpm run lint:check && pnpm run format:check && pnpm run test && tsc -p tsconfig.test.json --noEmit"
},
"keywords": [
"openui",
@@ -58,7 +58,7 @@
},
"author": "[email protected]",
"dependencies": {
- "@openuidev/lang-core": "workspace:^"
+ "@openuidev/lang-core": "^0.4.1"
},
"peerDependencies": {
"svelte": ">=5.0.0",
diff --git a/packages/vue-lang/package.json b/packages/vue-lang/package.json
index 5cd3e71bb..996aa13c4 100644
--- a/packages/vue-lang/package.json
+++ b/packages/vue-lang/package.json
@@ -25,7 +25,7 @@
"format:fix": "prettier --write ./src",
"format:check": "prettier --check ./src",
"prepare": "pnpm run build",
- "ci": "pnpm run lint:check && pnpm run format:check"
+ "ci": "pnpm run lint:check && pnpm run format:check && pnpm run test && tsc -p tsconfig.test.json --noEmit"
},
"keywords": [
"openui",
@@ -55,7 +55,7 @@
},
"author": "[email protected]",
"dependencies": {
- "@openuidev/lang-core": "workspace:^"
+ "@openuidev/lang-core": "^0.4.1"
},
"peerDependencies": {
"vue": ">=3.5.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 57a2f2a10..d5ee5c064 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -315,8 +315,8 @@ importers:
packages/angular-lang:
dependencies:
'@openuidev/lang-core':
- specifier: workspace:^
- version: link:../lang-core
+ specifier: ^0.4.1
+ version: 0.4.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])
tslib:
specifier: 'catalog:'
version: 2.8.1
@@ -952,8 +952,8 @@ importers:
packages/svelte-lang:
dependencies:
'@openuidev/lang-core':
- specifier: workspace:^
- version: link:../lang-core
+ specifier: ^0.4.1
+ version: 0.4.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])
zod:
specifier: 'catalog:'
version: 4.4.3
@@ -989,8 +989,8 @@ importers:
packages/vue-lang:
dependencies:
'@openuidev/lang-core':
- specifier: workspace:^
- version: link:../lang-core
+ specifier: ^0.4.1
+ version: 0.4.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])
zod:
specifier: 'catalog:'
version: 4.4.3
@@ -2763,6 +2763,15 @@ packages:
resolution: {integrity: sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==}
engines: {node: '>=14'}
+ '@openuidev/[email protected]':
+ resolution: {integrity: sha512-t9XSiORKTgyn6pWv8qqBkgD45PBhORdGWpQAHo3APvj9SYy7YprKURQgmXNu3z6E/Ds8tsLAI+AZjX3errH+jQ==}
+ peerDependencies:
+ '@modelcontextprotocol/sdk': '>=1.0.0'
+ zod: ^3.25.0 || ^4.0.0
+ peerDependenciesMeta:
+ '@modelcontextprotocol/sdk':
+ optional: true
+
'@openuidev/[email protected]':
resolution: {integrity: sha512-bVnVy2OcGawikt+R5QR4EBKtRvd0Y2PD9+Z94EClD5fSVtfi9VT9yztBp9a+r104SdB1GZuRuO3J/U+UALZgyg==}
engines: {node: '>=20'}
@@ -12968,6 +12977,13 @@ snapshots:
'@opentelemetry/[email protected]':
optional: true
+ dependencies:
+ ci-info: 4.4.0
+ zod: 4.4.3
+ optionalDependencies:
+ '@modelcontextprotocol/sdk': 1.30.0(@cfworker/[email protected])([email protected])
+
'@openuidev/[email protected](@openuidev/lang-core@packages+lang-core)(@openuidev/react-headless@packages+react-headless)(@openuidev/react-lang@packages+react-lang)(@openuidev/react-ui@packages+react-ui)(@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected]))(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected]))':
dependencies:
'@floating-ui/react-dom': 2.1.3([email protected]([email protected]))([email protected])