The Studio LLM guide
The prog document model, the xu-* attribute reference, and the workflow rules an AI agent is taught before its first tool call.
Every Studio project, every table, screen, script and route inside it, is one CouchDB JSON document
called a prog (docType: "studio"). This page is the same reference an AI agent receives when
it builds one, rewritten as documentation: the shape of that document, the attributes that drive
its UI, the actions a workflow can take, and the mistakes that show up in real builds.
How an AI agent gets this guide
Connect an MCP client to Xuda and the first response, the initialize call, carries this guide as
the session's instructions, merged fresh from the platform's own live rules so it can never
describe something the deployed checker no longer enforces. See
Connecting an AI client over MCP.
From inside a session, two methods reach the same material directly, over MCP or plain REST, and require nothing beyond a normal API key:
The prescribed order: read the topic that matches what you are building, fetch a matching example,
create the prog through the factory (create_prog), build inside its content sections, validate
(validate_prog) and fix everything it reports, save (save_prog), then re-fetch to verify. A
save that returns -409 means the document changed since it was read: re-fetch, reapply, retry.
The prog document model
The envelope
Server and factory code own these fields; an authored build only ever edits the content sections below them.
_idfollows<last 3 chars of app_id>_<3-letter type abbreviation>_<12 hex>, for example392_cmp_...for a component,392_tbl_...for a table,392_jvs_...for a javascript prog,392_gtd_.../392_std_...for get_data / set_data,392_fld_...for a folder. The factory generates ids, a build never invents one.statis 3 for active, 4 for soft-deleted (what deleting a prog sets). Studio's tree only showsstat: 3.properties.menuTypeis one ofglobals,table,get_data,set_data,batch,alert,javascript,folder,route,api,component,ai_agent.studio_meta.parentIdplaces the node in the Studio tree: either another prog's id (usually a folder) or one of the type roots,programs(logic and components),database(tables),routes,globals,ai_agents. An unrecognizedparentIdleaves the node invisible in the tree and is a checker error.
Content sections by menuType
The globals doc
Each project has exactly one global_<app_id> document (menuType: "globals"). Its progFields
are readable from every other prog as @field_id. Two system globals ship on every project:
@SYS_GLOBAL_OBJ_LOGIN_USER_INFO for the signed-in user, and @SYS_GLOBAL_OBJ_REFS for elements
registered with xu-ref. Neither the globals doc nor the tree root can be deleted.
Structural musts
properties,properties.menuType,properties.menuName,studio_meta, andstudio_meta.parentIdare mandatory on every doc.- A
progFieldsentry needs a uniqueid,data.field_id, adata.typeofvirtual,table,expressionordatasource, and aprops.fieldTypeofstring,number,boolean,arrayorobject. - Reserved runtime variable names,
_NULL,_THIS,_FOR_KEY,_FOR_VAL,_ROWNO,_ROWID,_ROWDOC,_KEY,_VAL, are never redefined as field ids. - Duplicate ids, unknown
menuTypes and malformed sections are all hard errors thatvalidate_progreports directly.
Expressions and xu-* attributes
Expression syntax
Expressions run against the prog's own dataset. Any field, local, table-bound, global or a
parameter, is referenced with @: @search_v, @ORD_Total, @SYS_GLOBAL_OBJ_LOGIN_USER_INFO,
plain JavaScript around it, @count_v > 0 ? 'has rows' : 'empty'. An object literal needs wrapping
parens, ({ ORD_Status: @status_v }). Inside an xu-for loop, the current item is @_FOR_VAL and
its key or index @_FOR_KEY (renameable with xu-for-key / xu-for-val). xu-render and other
conditions return the truthy or falsy value directly, never a "Y" / "N" string or an extra
comparison.
Everywhere else a field is referenced with @. xu-bind takes the bare field id instead:
xu-bind="search_v", never xu-bind="@search_v".
The xu attributes
Prefix families
Attribute families that take a suffix. xu-on values are always arrays of handler objects;
xu-exp values are always expression strings.
The value of an xu-on:* attribute is always an array of handler objects, and each workflow is
an array of action steps (the full action reference is below, under Logic programs and
workflows). A step's props.condition gates it; props.async: true fires it without waiting.
Critical semantics
xu-exp:classreplaces the staticclassattribute rather than adding to it. An element carrying both has the static one ignored, so the layout classes belong inside the expression too:xu-exp:class="'card p-4 ' + (@active_v ? 'ring' : '')".xu-scripttakes a barefunction (el) { ... }expression,eval'd and called with the DOM element once the node becomes visible. Guard against re-runs (if (el.__bound) return; el.__bound = true;) and scope every query toel, never todocument.xu-styleis auto-scoped: every selector is prefixed with the node's[xu-ui-id], so plain element and class selectors stay local and never leak.- Neither
xu-scriptnorxu-stylevalues may contain a quote character ('or"), the designer canvas serializes attributes unescaped and one quote corrupts the component. The JavaScript programs section below covers quote-free techniques. - Static text belongs in an element's
contentproperty.xu-exp:xu-contentis for dynamic text only.
Tags
Authoring tags besides plain HTML: xu-template, xu-single-view, xu-multi-view, xu-panel,
xu-teleport, xu-slot.
xu-single-viewscopes a single record (a form root, also usable nested).xu-multi-viewrepeats its children once per row of the bound data.xu-panelembeds another prog (programattribute plusxu-exp:<param>inputs). Only standard HTML attributes (class,id,style,title,hidden,slot,name,role,tabindex) belong on it besides the param expressions.xu-teleportrenders its children at another DOM target (toorxu-exp:to).- A capitalized tag name (
Button,Card) is a compiled component, not an HTML element, see Embedding below.
Components
A component (menuType: "component") is a UI unit: an element tree (progUi) bound to local
state (progFields), optional data (progDataSource), lifecycle logic (progEvents) and an
input/output interface (properties.progParams).
Properties
renderTypeisformfor a single record (root elementxu-single-view) orgrid/listfor one repeated per data row (root elementxu-multi-view).rwModeisRfor read orUfor update;allowCreatesays whether a new row can be inserted when none matches.progParamsnaming convention: parameters end_in/_out, component-local virtual fields end_v.uiFrameworkmirrors whatever the project's existing components already use. An existing project that omits it should keep omitting it, setting a framework plugin the project's drive does not actually serve stalls the live preview on a blank screen.
The element tree (progUi)
The factory root node stays; a build works inside its children. Every node needs a unique id
(new nodes use ui-<uuid>), type: "element", and a tagName, no comment or text node types,
static text lives in content instead. Every node needs attributes: {} and children: []
even when empty, the designer canvas serializer dereferences both on every node and an omission
breaks the component's own preview.
Embedding: xu-panel or a compiled component
Both mount transparently, no wrapper element, and both are decided by one signal: whether
tagName starts with a capital letter.
xu-panel, lower-casetagNameplus aprogramattribute, embeds another prog, a database-bound or stateful child with its own fields and events.programis the child's id (orxu-exp:progfor a dynamic one), values reach its_inparams throughxu-exp:<param>.- A capitalized tag plus a
libraryattribute mounts a compiled component, a design-system primitive or a part the app itself compiled. Every plain attribute becomes a prop (props.<name>), never a DOM attribute, since the component renders no element of its own. A component node has no out-params, unlikexu-panelnothing writes a value back to your fields.
A typo'd <Buton> is still claimed as a component tag, never falls back to an unknown HTML
element, and throws at mount naming the tag, the library, and every source tried. validate_prog
does not check component tags or library values today, the live preview is the only check.
progFields
data.type is virtual for local state, table for a column of the bound datasource, or
expression / datasource. A field's workflow runs on change. A default sets
props.fieldValue; a computed field sets props.fieldComputed: true plus
propExpressions.fieldValue.
progDataSource
A single record by key (form): dataSourceFilterModelType: "index" with a dataSourceIndexId
that exists on the table's own tableIndexes. A filtered list (grid or list):
dataSourceFilterModelType: "query" with filterModelMongoFx, a Mongo-style expression string.
dataSourceType is table, array, json, csv, none, or empty for a purely presentational
component with no data source at all.
progEvents and the three lifecycle hooks
Event types: on_load, on_exit, before_record, after_record, record_not_found,
locate_not_found, screen_ready, on_refresh, on_unload, client_interval, user_defined.
user_defined events fire from anywhere with the
raise_event action; screen_ready is the usual mount hook.
A component's three built-in hooks split the work, using the wrong one is a common source of bugs:
screen_ready
Fires once per instance. Create DOM and widgets here.
on_refresh
Fires after every load, including the first, right after screen_ready. Hand new data to widgets
that already exist. Putting refresh work in screen_ready instead re-runs create code against DOM
that still exists and stacks a second widget.
on_unload
Fires when the instance is torn down. Destroy what the prog created, widgets, timers,
document / window listeners, observers. The engine can only free what it created, a listener
bound to document outlives the panel otherwise.
Patterns
- Loading and empty states: put
xu-ref="myref"on the data-bound element, then gate skeleton or empty elements withxu-renderover(@SYS_GLOBAL_OBJ_REFS).myref, its dataset attaches once data arrives. - Modals: build the dialog as its own component, open it with the
call_modalaction. - Save or delete a bound row:
invoke_actionwithact_save/act_delete, or a dedicatedset_dataprog for anything past the current row.
Logic programs and workflows
Logic prog types share a component's data machinery (progDataSource, progFields,
progEvents, properties.progParams) without any UI:
Parameters
A caller passes values through the action's name.parameters,
{ "order_id_in": { "value": "", "fx": "@selected_id_v" } }, value for a static value, fx for
an expression. The checker verifies the target program exists and its menuType matches the
action.
Workflow actions
A workflow is an array of steps, { "id": "...", "data": { "action": "...", "name": { ... }, "enabled": true }, "props": {} }, run in order. props.condition gates a step, props.async: true fires it without waiting. Workflows appear in xu-on:* handlers, progEvents[].workflow,
and a field's own workflow.
invoke_action accepts act_next, act_prev, act_first, act_last, act_reload,
act_refresh, act_print, act_save, act_delete (component context only).
alter_ui_element, create_ui_element, info_ui_element, remove_ui_element,
empty_ui_element, cache_ui_element, load_ui_element. Drive UI through fields and xu-exp /
xu-render instead of an imperative element action.
Studio's own action picker offers Call AI Agent and Call Triage Agent next to the actions
above. Neither is in this table because neither is one: validate_prog has no case for them and
reports invalid trigger type, and the runtime workflow engine has no handler for them either, so
a saved step never runs even if the error is ignored. To have one prog reach a published agent, add
an AI Agent tool to another agent's own tool list instead (a menuType: "ai_agent" doc's
agentConfig.agent_tools), not a workflow step on a component, get_data, or any other prog type.
update's name.value assigns fields with semicolon-separated @field: expression pairs, or a
JSON5 object, "@saving_v: true; @status_v: 'sent'". Calling another program names it under
name.prog, matching the action to the program's own type
(get_data needs a get_data prog, call_native_javascript a javascript prog, and so on).
call_library calls an installed plugin method: name.plugin_name must be purchased and
installed on the app or the checker rejects the step, name.library_method one of the methods the
plugin exports, name.library_props its declared fields. Two prop names are a convention across
plugins rather than specific to any one of them: event_name_for_successful_callback raises that
event with the method's response, field_id_to_return_result writes the response into that field
directly, neither is required.
progEvents types
on_load, on_exit, before_record, after_record, record_not_found, locate_not_found,
screen_ready, on_refresh, on_unload, client_interval, user_defined. screen_ready is
the usual init hook; before_record / after_record /
record_not_found / locate_not_found are data lifecycle, especially for set_data and batch;
client_interval is a repeating timer; user_defined fires from the raise_event action.
Tables
A table prog (menuType: "table") defines a database table: its columns (tableFields), its
indexes (tableIndexes), and the database plugin storing it (properties.databaseSocket). Tree
parent: database, or a folder under it.
databaseSocketmust name a database plugin installed on the project,@xuda.io/xuda-dbs-plugin-xudais the platform default; an existing table in the same project is the reference for which socket to reuse.- At least one field and at least one index are required.
field_idstarts with a letter, then letters, digits, underscore, dash, colon or dot, and stays unique within the table.fieldTypeisstring,number,boolean,array,objectordate;mandatory: truemakes it required on save.- Every index needs a non-empty
nameandkeys, and every key must be an existingfield_id.
Convention: prefix columns with a three-letter table code, a table named "ORD - Orders" gets
ORD_Id, ORD_Total, ORD_Status. Give every table a unique <TBL>_Id field with a unique index
on it, a single-record component binding needs it.
A table is used three ways: a component or query's progDataSource.dataSourceTableId, a
get_data / set_data / batch prog for row-level access from workflows, or xu.dbs_create /
dbs_read / dbs_update / dbs_delete from a script, covered next.
JavaScript programs
A javascript prog (menuType: "javascript") holds real JS source in scriptData.value, compiled
on save. save_prog triggers that build and returns the result as data.compile, { ok: true, dependencies } or { ok: false, error }. A failed compile still saves the doc, so a build reads
compile.ok and fixes it before moving on.
The execution contract
The source is written as a plain async body, no export, no wrapper. At run time it executes as:
params are the caller's already-evaluated inputs; xu is the runtime API below; a return value
is optional, the idiomatic way to hand results back is xu.set_field_value on the calling
component's fields. Quotes are fine here, unlike an xu-script attribute value.
The xu runtime API
dbs_* methods take the table prog's own _id, never a name. Selectors are Mongo-style objects on
the field ids, {} returns everything (default limit 999). The fields projection is optional,
[] returns every field and a list of field ids returns only those.
Passing data in: fields, not parameters
call_native_javascript does not evaluate {value, fx} parameter wrappers, name.parameters
reaches the script raw. The reliable contract: the component puts the payload in a field first (an
update step or an xu-bind input), the workflow calls the prog with empty parameters: {}, and
the script reads it with xu.get_field_value and reports back with xu.set_field_value. Calling
from another script instead, xu.call_javascript(prog_id, {...}) does pass params directly.
Live-preview quirks
- Data writes reach the real database, but
xu.dbs_readreads a local draft store that may not hold fresh server rows, a read right after a write can come back empty in preview even though the write landed (visible in the table's Data tab in Studio). Deployed apps read and write the same store. - Compiled scripts cache hard in dev previews, a running preview can keep executing the previous script even across reloads after a save recompiles it. A hard browser refresh clears it.
xu.alertwithmodal,toastorbrowserdisplay can surface as a native, blockingalert()in preview.xu.set_field_valueinto a status field is the safer way to report back.
javascript prog vs xu-script attribute
Quote-free techniques for xu-script / xu-style
The designer canvas serializes attribute values unescaped, so a single quote corrupts the
component's markup. Template literals avoid string quotes entirely
(el.textContent = `Ready`); the literal " character, for example while building CSV, comes
from String.fromCharCode(34); CSS attribute selectors are valid unquoted
(el.querySelector(`[data-role=import-btn]`)); and a re-run guard,
if (el.__bound) return; el.__bound = true;, keeps a script from double-binding on re-render.
Landmines
Every entry below broke a real build at some point. validate_prog catches most of them, run it
before every save.
API mechanics
- Every response is
{ code, data },code < 0is an error. create_progreturns the new doc underdata.prog, saving the whole response instead persists a malformed doc withpropertiesburied underprog.save_progreplaces the whole document. Start from the current doc, never a hand-assembled skeleton; a-409means it changed since the last read, re-fetch, reapply, retry.- Over MCP,
prog_jsonandproperties_jsonare passed as strings, the tool schema layer strips unknown keys from an object parameter and can silently drop whole sections. delete_progis a soft delete, it setsstat: 4. Theglobal_<app_id>node cannot be deleted.
Doc content
- No
'or"insidexu-scriptorxu-stylevalues. $-prefixed keys ($folded,$childrenClass,$nodeBackClass), pluspath,code,editCode, are designer view-state and never belong in a savedprogUinode.- No
commentortextnode types, elements only, static text incontent. - Every element node needs
attributes: {}andchildren: []even when empty. xu-exp:classreplaces the staticclass, every needed class belongs inside the expression.xu-bindis a bare field id, no@, everywhere else fields use@.- Only the documented
xu-*attributes do anything, an invented one is silently ignored andvalidate_progwarns. - An
ai_agentprog's tree root isai_agents, save it withstudio_meta.parentId: "ai_agents"(or a folder id under it) if the checker flagsparentId.
Runtime and rendering
- A capitalized
tagNameis always claimed as a component, even a typo, and throws at mount naming the tag, thelibrary, and every source tried, there is no silent "does not render" the way anxu-panelwith no program selected has. validate_progdoes not check component tags orlibraryvalues, only the live preview catches a misspelt one.- No utility CSS (Tailwind or otherwise) at runtime unless the project's
uiFrameworkplugin actually provides it, classes likep-4silently no-op otherwise. Self-contained styling isxu-style, auto-scoped by[xu-ui-id]. xu-scriptruns once per element visibility and may re-fire on re-render, guard withel.__boundand scope queries toel.
Data and scripts
call_native_javascriptparameters are not evaluated, pass data through fields instead (see Passing data in, above).dbs_readrows are{id, value}, fields live under.value, the row id on.id. Do not pass afieldsprojection, it breaks the server-side read.- Inside
xu-for, wrap the iterator in parens,(@_FOR_VAL).CNT_Nameevaluates,@_FOR_VAL.CNT_Namefails silently and renders the substituted source text instead. - Preview writes land in the real database; preview reads come from a local draft store that can look empty right after a write.
- Prefer a status field over
xu.alert's modal or toast display in previews, it can render as a native, blockingalert().
Verifying your work
Re-fetch with get_prog after saving and diff what was expected. For UI work, open the component
in Studio and press the preview play button, or the project's live-preview URL when one is
available. For a javascript prog, check data.compile.ok on every save. Fix every
validate_prog error; treat its warnings, quotes, $-keys, unknown attributes, as fix-now items
rather than noise.