ai_sdk_openui 3.1.0
ai_sdk_openui: ^3.1.0 copied to clipboard
OpenUI Lang 1.0 in pure Dart (parser, evaluator, state, queries, prompt generator) and the Open Intelligent UI component library spec.
3.1.0 #
OpenUiSession(policy: ValidationPolicy(...))applies the validator's policy at runtime. WithunknownComponents: UnknownComponentPolicy.fail, a program that names a component the library lacks has noroot.maxNodescaps the evaluated tree,@Eachexpansions included (an item that builds no component, such as a string, still counts as one): past it the session stops evaluating, has noroot, and reports atoo-many-nodeserror.OpenUiErrorCodegainstooManyNodes, so an exhaustiveswitchover it needs a new case.OpenUiAnswerskeeps one session per message for any transport: feed it full text, deltas, edit-mode patches or aStream<OpenUiMessageEvent>, save withonSave, and replay a saved message withupdate(id, text, streaming: false).messageWithStateandmessageStateread and write an answer's saved state.- Async host actions:
ActionSpec(handler:)runs a library action in the session and returnsActionSuccessorActionFailure(message). Each run gets anidempotencyKeythat stays the same for retries of the same write, andOpenUiSession.actionStatus(action, nodeId:)reports pending, done or failed per triggering node.confirm:makesrunwait forconfirmed: true, anddisableAfterSuccess:stops repeats. Statuses are saved insession.stateunder__openui_actionsand restored frominitialState; a run cut off mid-flight restores as failed. Actions without a handler still reach the host as events. - A handled action's idempotency key and status come from the message scope, the action name and its resolved
params, never from the control's position: an
@Eachrow keeps its key, and adisableAfterSuccessrow stays disabled, when a restore adds rows around it. Two controls with the same action and params share one key. OpenUiSession(resolveAction:)settles a handled run that a restore cut off mid-flight: it gets the run's name, params and original idempotency key, and the run reads as the newActionPhase.unknown(disabled, never retried) until it returns done or failed. Without it, such a run still restores as failed.ActionSuccess(data)carries the host's JSON receipt, such as the id of the record it wrote. It is saved with the session state, and later steps of the same plan read it fromActionInvocation.resultsandActionEvent.results, keyed by action name, also after a restore.Impure(the clock and random seams that@Today,@Nowand@Randomuse) is public, so hosts and tests can pin time and randomness.OpenUiSessionandOpenUiAnswerstakeclock,randomandtimeZone, so two sessions in one process can read their own time, randomness and zone; theImpurehooks are now only the defaults.OpenUiTimeZoneis a host-supplied offset per instant (OpenUiTimeZone.fixed,OpenUiTimeZone.utc); null keeps the device zone.intelligentUiWithout(optionalIuiComponents)gives a library without Math, Map, MapMarker, YouTube and HtmlView, andchatPromptFor(library)/dashboardPrompt(library:)drop the medium-rule clauses for components the library lacks.intelligentUiandchatPromptare unchanged.- The system prompt follows the library:
chatPromptForanddashboardPrompt(library:)leave out rules and examples that use a component or@callthe library lacks,extenddrops group notes that name a removed component, and component, function and action descriptions lose the sentences that call a missing component or name an unlisted step.PromptOptions(allowedActions:)(the same set asValidationPolicy.allowedActions) lists only those steps and actions, takes the others out of component signatures (leaving out a component whose step slot keeps none), and the fixed text (action examples,@Runrefresh and Mutation, Forms, and the "tables, charts, forms" hints) names only steps and components the prompt offers.intelligentUi's prompts are unchanged. library.validate(program, policy: ValidationPolicy(...))andvalidateProgram(from a spec's JSON Schema alone) return aValidationReport: parse issues plus node, depth and string limits, unknown-component handling (drop or fail) and allowed actions, each with its statement id.toJson()is the wire form.dart run ai_sdk_openui:openui validate <spec.json> <program>prints that report for any spec exported withtoSpecJson(), including host extensions.conformance/vectors.json: programs and the parse results@openuidev/lang-core1.0.0 gives them, for any server;make test-openui-conformancechecks them against lang-core, and the Dart tests check this port.openui spec <spec.json|intelligent-ui>prints a library spec as canonical JSON (sorted keys; schemapropertieskeep their positional order), andcanonicalJson(library.toSpec())prints the same bytes for a host library. Policy flags add apolicyblock, whichopenui validateapplies under its own flags;ValidationPolicy.toJson/fromJsonread and write it.- Bound record schemas:
library.validate(program, boundSchemas: {r'$order': jsonSchema})(alsolibrary.parse,validateProgramandopenui validate --bound-schemas=<file>) checks every bound path against its record's schema: a path the schema lacks is the newunknown-bound-patherror, and a value whose type does not fit the prop istype-mismatch. A computed index into a record ($order[$k]) is no longer a bound path, so it cannot feed a bound-only prop, in sessions too. Steps.setandSteps.resetlet an action slot list@Setand@Reset. Every@step given to a restricted slot (directly, inAction([...])or in a ternary branch) must be one the slot lists, or it is atype-mismatchand the prop is dropped, so the Dart validator agrees with one that readsspec.json.- Migration:
ValidationCodeandOpenUiErrorCodegainunknownBoundPath. An exhaustiveswitchover either needs a case. - Validator vectors:
conformance/vectors.jsongains vectors withbound,policyandexpectReport, run againstconformance/validator-spec.json, for every report code.doc/validation.mddocuments the report (codes, severities, path syntax) as a stable contract for validators in other languages. Money: an exact amount in integer minor units with an ISO 4217 code (scale from CLDR), parsed from{minor, currency}or{amount: "12.34", currency}, with+,-andformat({locale}). It never uses a double.formatMoneyadds@FormatMoneyto a library throughextend.Money.format(trimZeroFraction: true)writes whole amounts without the zero fraction (₹1,23,456in en-IN;₹1,23,456.50keeps it).formatMoneyWith(boundOnly: true, trimZeroFraction: true)builds an@FormatMoneythat takes only host-bound amounts and/or trims.Moneyrejects codes outside ISO 4217 (XYZ).@Format(x, "currency")stays double-based for the reference and is documented as not money-safe.OpenUiSession(locale: 'de-DE')formats@Format,@Pluraland@FormatDatefor that locale (en-IN groups 12,34,567.00; de-DE writes 1.234,56 €). No locale, or en-US, keeps the reference's output.FunctionSpec.localizedlets a library function do the same.- Host-bound records:
OpenUiSession(records: [BoundRecord('order', json)])gives a program a read-only$order. Props, action params and function params marked.boundOnly()take only a path into a record ($order.total,$orders[0], an@Eachitem); a literal is rejected with the newbound-onlyerror (also checked bylibrary.parse(program, bound: {...})). The JSON Schema marks them"x-openui-bound": true, which lang-core ignores. - Bound-only fields nested in a prop are enforced too: an object field or list item marked
.boundOnly()(S.object({'amount': S.any().boundOnly()}),S.list(S.string().boundOnly())) takes only a bound path, reported at its own path (/payment/amount,/ids/0), and the whole prop is dropped. A computed container (state, a ternary, a call) around such fields is rejected unless it is itself a bound path. PromptOptions.recordsadds a "Bound Data" section andPromptOptions.statea "Current State" section for seeded$variables;describeBoundRecordsreturns the first for per-turn use. Default prompts are unchanged.- Migration:
ValidationCodeandOpenUiErrorCodegainboundOnly. An exhaustiveswitchover either enum needs a case for it. - A
patternvalidation rule that repeats a repeating group, such as^(a+)+$, or a choice whose alternatives can overlap, such as^(a|aa)+$, is ignored like a pattern that does not compile, so model-written input cannot freeze the UI thread with catastrophic backtracking. OpenUiAnswers.listen(events, onError:): an error on the event stream cancels it and goes toonErrorwith the id of the message it was feeding, which stays unfinished, instead of becoming an uncaught zone error.- Streaming is cheaper per delta: an unframed answer is no longer split into message sections twice per update, the
streaming parser no longer scans the whole text for a trailing
$name, and the initial state is serialised once. A 20 KB answer in 1-character deltas went from about 15 s to under 3 s. ValidationMessagesholds the built-in validation rules' error messages (English by default);validate(value, rules, customValidators, messages)reports in a subclass's words.- First release: OpenUI Lang 1.0 (a port of
@openuidev/lang-coreand the state, query and action handling of@openuidev/react-lang1.0.0) and the Open Intelligent UI library spec (a port of thesysdev/open-intelligent-ui at9df2e64), withOpenUiSession,OpenUiLibrary, a schema DSL, the chat and dashboard prompts and demo data tools. - The engine's tests also run compiled to JavaScript:
make test-webruns them on Node withTZ=UTC. - Runtime values follow lang-core's JavaScript semantics: negative zero, integers past 2^53, object key order
and
__proto__handling, andJs.stringifyoutput likeJSON.stringify. @Sorton text compares exactly as ICUlocaleCompare(CLDR root order), not an approximation.- JSON forms:
jsonToOpenUIaccepts plain JSON element maps, and element nodes and the AST have JSON forms. - OpenUI Cloud config runs the full
validateChatLibrarychecks the Dart DSL can reach. - New lang-core exports from
lang_core.dart:parse,actionSteps,generatePrompt,buildSignature,resolveStateField, and the mutation and tool types. Schema.withDefault(Zod's.default()): the JSON Schema carries the default and an omitted argument takes it.buildActionUserMessagewrites the user turn for acontinue_conversationevent.ResponseMetadataexposes the response's OpenUI Cloud metadata, such as its name.OpenUiSessiongainsonParseResult,setTools,metadata,isGenerating,fieldValue,setDefaultValue,retryQueriesandreportRenderError.retryQuerieswith nothing failed refetches every Query, as react-lang does.Js.stringify(used for saved message context, store comparison and query keys) now writes numbers and integer-like object keys asJSON.stringifydoes.