A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(ai): let an action declare its parameters, instead of parsing one string
yhh7177a5a8deef
diff --git a/desktop/src/ai/paramOptions.ts b/desktop/src/ai/paramOptions.tsnew file mode 100644index 000000000..bb8c7c29d--- /dev/null+++ b/desktop/src/ai/paramOptions.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file paramOptions.ts+ * @brief Choice providers for an action parameter declared with an+ * `optionsSource` — the dynamic-enum escape hatch, for actions.+ *+ * A declared parameter can name a source instead of listing options, because the+ * real choices depend on the scene: which controllers the target entity resolves,+ * which pages the chosen controller has. This is the same shape (and for the same+ * reason) as `registerDynamicEnum` for component fields — one keyed provider map,+ * consulted by whoever renders the control. Kept out of the SDK registry on+ * purpose: the sdk declares WHAT a parameter is, the editor knows what is on+ * screen to choose from.+ */+import { resolveControllers } from '@/controller/controllerModel';+import type { DynamicEnumOption } from '@/engine/schema';+import type { EntityId } from '@/types';+import type { AiParamValue } from 'esengine';++export interface AiParamOptionContext {+ /** The entity the action will run on — a row's resolved target, not its owner. */+ entityId: EntityId;+ /** The row's current parameter values, for a parameter that narrows a sibling. */+ params: Readonly<Record<string, AiParamValue>>;+}++export type AiParamOptionProvider = (ctx: AiParamOptionContext) => readonly (string | DynamicEnumOption)[];++const providers = new Map<string, AiParamOptionProvider>();++export function registerAiParamOptions(source: string, provider: AiParamOptionProvider): void {+ providers.set(source, provider);+}++/** Options for an `optionsSource`, or null when unknown / nothing to offer. */+export function aiParamOptions(source: string, ctx: AiParamOptionContext): DynamicEnumOption[] | null {+ const opts = providers.get(source)?.(ctx);+ if (!opts || opts.length === 0) return null;+ return opts.map((o) => (typeof o === 'string' ? { value: o } : o));+}++// — Engine-provided sources —+// Registered here (module load) rather than by any one panel, so the Events+// section and the FSM/BT editors see the same list.++/** Every controller the target entity resolves — its own plus its ancestors'. */+registerAiParamOptions('uiController', ({ entityId }) =>+ resolveControllers(entityId).map((rc) => ({+ value: rc.ctrl.name,+ label: rc.inherited ? `${rc.ctrl.name} · ${rc.ownerName}` : rc.ctrl.name,+ })),+);++/** The pages of whichever controller the sibling `controller` parameter names. */+registerAiParamOptions('uiControllerPage', ({ entityId, params }) => {+ const name = typeof params.controller === 'string' ? params.controller : '';+ if (!name) return [];+ return resolveControllers(entityId).find((rc) => rc.ctrl.name === name)?.ctrl.pages ?? [];+});diff --git a/desktop/src/events/EventBindingSection.tsx b/desktop/src/events/EventBindingSection.tsxindex 5bcf134f0..ba3329ba0 100644--- a/desktop/src/events/EventBindingSection.tsx+++ b/desktop/src/events/EventBindingSection.tsx@@ -21,19 +21,22 @@*/import { useState } from 'react';import { useSyncExternalStore } from 'react';+import type { ReactNode } from 'react';import { ChevronDown, ChevronRight, CornerDownRight, MousePointerClick, Plus, SlidersHorizontal, X } from 'lucide-react';import { Select } from '@/components/Select';import { SuggestInput } from '@/components/SuggestInput';import { aiActionItems, aiConditionItems } from '@/components/aiSuggest';+import { aiParamOptions } from '@/ai/paramOptions';import { SceneStore } from '@/engine/SceneStore';import { SceneCommands } from '@/engine/SceneCommands';+import { prettyLabel } from '@/engine/schema';import { readEventRows, resolveTargetName, sceneEntityNames } from '@/events/eventBindingModel';import { useInspectorCollapse, isSectionCollapsed } from '@/store/inspectorCollapse';import { t } from '@/i18n';import type { EntityId } from '@/types';-import { UIEventType } from 'esengine';-import type { EventBindingRow } from 'esengine';+import { UIEventType, aiRegistry, parseActionArg } from 'esengine';+import type { AiParamDef, AiParamValue, EventBindingRow } from 'esengine';const SECTION_KEY = '__events';/** The type strings the built-in widgets emit — suggestions, not a closed set. */@@ -131,6 +134,14 @@ function EventRow({const patch = (p: Partial<EventBindingRow>) => SceneCommands.updateEventBinding(entityId, index, p);const enabled = row.enabled !== false;+ // What the chosen action takes. A row authored before the action declared its+ // parameters still shows them: the canonical string parses into the same+ // record the runtime would build (registry.ts owns that projection).+ const defs = aiRegistry.getActionParams(row.action);+ const values: Record<string, AiParamValue> = row.params && Object.keys(row.params).length+ ? { ...row.params }+ : parseActionArg(row.arg, defs, aiRegistry.getActionSeparator(row.action));+// An authored value the built-in list doesn't know (a widget's own event, or// an entity renamed since) still has to be selectable — append it rather than// silently snapping the row to something else.@@ -138,7 +149,8 @@ function EventRow({const names = sceneEntityNames();const target = row.target ?? SELF;const targetOptions = target === SELF || names.includes(target) ? names : [...names, target];- const dangling = target !== SELF && resolveTargetName(entityId, target) == null;+ const targetEntity = resolveTargetName(entityId, target);+ const dangling = target !== SELF && targetEntity == null;return (<div className={`evt-row${enabled ? '' : ' off'}`}>@@ -192,23 +204,48 @@ function EventRow({items={aiActionItems()}placeholder={t('evt.actionPh')}ariaLabel={t('evt.action')}- onCommit={(v) => patch({ action: v.trim() })}- />- <input- className="evt-arg"- defaultValue={row.arg ?? ''}- key={`${index}-arg-${row.arg ?? ''}`}- placeholder={t('evt.argPh')}- spellCheck={false}- onBlur={(e) => patch({ arg: e.target.value.trim() || undefined })}- onKeyDown={(e) => {- if (e.key === 'Enter') (e.target as HTMLInputElement).blur();- }}+ // The old input belongs to the old action — switching drops both forms.+ onCommit={(v) => (v.trim() === row.action ? undefined : patch({ action: v.trim(), params: undefined, arg: undefined }))}/>+ {defs.length === 0 && (+ <input+ className="evt-arg"+ defaultValue={row.arg ?? ''}+ key={`${index}-arg-${row.arg ?? ''}`}+ placeholder={t('evt.argPh')}+ spellCheck={false}+ onBlur={(e) => patch({ arg: e.target.value.trim() || undefined })}+ onKeyDown={(e) => {+ if (e.key === 'Enter') (e.target as HTMLInputElement).blur();+ }}+ />+ )}</div>+ {defs.length > 0 && (+ <div className="evt-params">+ {defs.map((def) => (+ <ParamControl+ key={def.name}+ def={def}+ value={values[def.name]}+ // Options come from the entity the action RUNS on, so a row that+ // targets a panel offers that panel's controllers, not the button's.+ optionsEntity={targetEntity ?? entityId}+ siblings={values}+ onChange={(v) => {+ const next = { ...values };+ if (v === undefined || v === '') delete next[def.name];+ else next[def.name] = v;+ patch({ params: Object.keys(next).length ? next : undefined, arg: undefined });+ }}+ />+ ))}+ </div>+ )}+{open && (- <div className="evt-row-more">+ <div className="evt-row-more" data-row={index}><SuggestInputkey={`${index}-guard-${row.guard ?? ''}`}defaultValue={row.guard ?? ''}@@ -230,3 +267,82 @@ function EventRow({</div>);}++/**+ * One declared parameter, rendered by its declared type. An `optionsSource` that+ * yields nothing (no controller on the target yet) degrades to a text box rather+ * than an empty dropdown — the row stays authorable while the scene is half-built.+ */+function ParamControl({+ def,+ value,+ optionsEntity,+ siblings,+ onChange,+}: {+ def: AiParamDef;+ value: AiParamValue | undefined;+ optionsEntity: EntityId;+ siblings: Readonly<Record<string, AiParamValue>>;+ onChange: (v: AiParamValue | undefined) => void;+}) {+ const label = def.label ?? prettyLabel(def.name);+ const dynamic = def.optionsSource ? aiParamOptions(def.optionsSource, { entityId: optionsEntity, params: siblings }) : null;+ const options = dynamic ?? (def.options ? def.options.map((o) => ({ value: o.value, label: o.label })) : null);+ const text = value === undefined ? '' : String(value);++ let control: ReactNode;+ if (def.type === 'bool') {+ control = (+ <input type="checkbox" checked={value === true} aria-label={label} onChange={(e) => onChange(e.target.checked)} />+ );+ } else if (def.type === 'number') {+ control = (+ <input+ className="evt-param-input"+ type="number"+ defaultValue={text}+ key={text}+ aria-label={label}+ min={def.min}+ max={def.max}+ step={def.step}+ onBlur={(e) => onChange(e.target.value === '' ? undefined : Number(e.target.value))}+ onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}+ />+ );+ } else if (options && options.length) {+ // The authored value survives even when it is no longer on offer (a renamed+ // page), so opening the row never silently rewrites the data.+ const opts = options.some((o) => o.value === text) || !text ? options : [...options, { value: text }];+ control = (+ <Select+ value={text}+ options={opts.map((o) => ({ value: o.value, label: o.label }))}+ onChange={(v) => onChange(v)}+ ariaLabel={label}+ className="evt-param-sel"+ />+ );+ } else {+ control = (+ <input+ className="evt-param-input"+ defaultValue={text}+ key={text}+ aria-label={label}+ placeholder={def.tooltip}+ spellCheck={false}+ onBlur={(e) => onChange(e.target.value.trim() || undefined)}+ onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}+ />+ );+ }++ return (+ <label className="evt-param" title={def.tooltip}>+ <span className="evt-param-label">{label}</span>+ {control}+ </label>+ );+}diff --git a/desktop/src/theme/events.css b/desktop/src/theme/events.cssindex ad7616ce4..38cda839b 100644--- a/desktop/src/theme/events.css+++ b/desktop/src/theme/events.css@@ -40,6 +40,15 @@.evt-arg { flex: 1 1 40%; min-width: 0; font-size: var(--fs-2xs); color: var(--text); background: var(--srf-2); border: 1px solid var(--border); border-radius: var(--r-sm); padding: 3px 6px; font-family: var(--font-mono); }.evt-arg:focus { border-color: var(--acc); outline: none; }+/* Declared action parameters: label + control per line, so `ui.setPage` reads+ "controller / page" instead of one opaque `tabs:settings` string. */+.evt-params { display: flex; flex-direction: column; gap: 4px; padding-left: 2px; }+.evt-param { display: flex; align-items: center; gap: 6px; min-width: 0; }+.evt-param-label { flex: 0 0 74px; font-size: var(--fs-2xs); color: var(--text-dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.evt-param-input { flex: 1 1 auto; min-width: 0; font-size: var(--fs-2xs); color: var(--text); background: var(--srf-2); border: 1px solid var(--border); border-radius: var(--r-sm); padding: 3px 6px; font-family: var(--font-mono); }+.evt-param-input:focus { border-color: var(--acc); outline: none; }+.evt-param .evt-param-sel { flex: 1 1 auto; min-width: 0; font-size: var(--fs-2xs); }+.evt-row-more { display: flex; align-items: center; gap: 6px; min-width: 0; }.evt-row-more > :first-child { flex: 1 1 auto; min-width: 0; }.evt-once { display: inline-flex; align-items: center; gap: 4px; flex: none; font-size: var(--fs-2xs); color: var(--text-dim); cursor: pointer; user-select: none; }diff --git a/desktop/tests/event-binding-commands.test.ts b/desktop/tests/event-binding-commands.test.tsindex ed2c56b0c..f130d8696 100644--- a/desktop/tests/event-binding-commands.test.ts+++ b/desktop/tests/event-binding-commands.test.ts@@ -103,6 +103,29 @@ describe.skipIf(!HAS_WASM)('EventBinding authoring commands', () => {expect(rowsOf(e)).toEqual([{ event: 'click', action: 'a' }]);});+ // The Events section writes parameters as a record and drops the canonical+ // string, so the two forms never disagree on disk; switching the action+ // drops both, because the old input belonged to the old action.+ it('writing parameters clears the canonical string', () => {+ const e = S.commands.addEntity()!;+ S.commands.addEventBinding(e, { event: 'click', action: 'ui.setPage', arg: 'tabs:home' });++ S.commands.updateEventBinding(e, 0, { params: { controller: 'tabs', page: 'settings' }, arg: undefined });++ expect(rowsOf(e)).toEqual([+ { event: 'click', action: 'ui.setPage', params: { controller: 'tabs', page: 'settings' } },+ ]);+ });++ it('switching the action drops the previous input entirely', () => {+ const e = S.commands.addEntity()!;+ S.commands.addEventBinding(e, { event: 'click', action: 'ui.setPage', params: { controller: 'tabs', page: 'home' } });++ S.commands.updateEventBinding(e, 0, { action: 'fsm.fire', params: undefined, arg: undefined });++ expect(rowsOf(e)).toEqual([{ event: 'click', action: 'fsm.fire' }]);+ });+it('an out-of-range patch or removal is a no-op', () => {const e = S.commands.addEntity()!;S.commands.addEventBinding(e, { event: 'click', action: 'a' });diff --git a/examples/ui-events/assets/scenes/main.esscene b/examples/ui-events/assets/scenes/main.essceneindex 6214261f2..7bc8cc565 100644--- a/examples/ui-events/assets/scenes/main.esscene+++ b/examples/ui-events/assets/scenes/main.esscene@@ -202,8 +202,8 @@"type": "EventBinding","data": {"rows": [- { "event": "click", "action": "ui.setPage", "arg": "tabs:settings" },- { "event": "click", "action": "ui.setPage", "arg": "badge:on", "target": "Card" }+ { "event": "click", "action": "ui.setPage", "params": { "controller": "tabs", "page": "settings" } },+ { "event": "click", "action": "ui.setPage", "params": { "controller": "badge", "page": "on" }, "target": "Card" }]}}diff --git a/examples/ui-events/src/main.ts b/examples/ui-events/src/main.tsindex aba71796c..d2ed3ed55 100644--- a/examples/ui-events/src/main.ts+++ b/examples/ui-events/src/main.ts@@ -6,6 +6,11 @@// Open the scene, select a button, and look at the Details panel's Events// section — that is the whole program.//+// The two buttons are deliberately authored differently: Home's rows carry the+// canonical string (`tabs:home`), Settings' carry named parameters. Both run the+// same action the same way — the registry projects between the forms — so data+// written before an action declared its parameters keeps working.+//// The entry point exists because a project has one; there is nothing to put in// it. Wiring only needs code when it needs LOGIC, and then the row points at an// action name (`fsm.fire`) instead of growing branches of its own.diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 91f19bd34..15b915a48 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1345 stable · 17 beta · 1 deprecated+Symbols: 1353 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -96,7 +96,25 @@ labels: string[]## AiAction — type```-(ctx: Ctx, bb: Blackboard, arg?: string) => void | Status+(+ ctx: Ctx,+ bb: Blackboard,+ arg?: string,+ params?: AiParams,+) => void | Status+```++## AiActionInput — interface+```+arg: string | undefined+params: Readonly<Record<string, AiParamValue>> | undefined+```++## AiActionSpec — interface+```+params: readonly AiParamDef[] | undefined+run: AiAction<Ctx>+separator: string | undefined```## AiBt — const@@ -126,16 +144,41 @@ world: WorldResourceDef<StateMachines>```+## AiParamDef — interface+```+label: string | undefined+max: number | undefined+min: number | undefined+name: string+options: readonly { label: string; value: string; }[] | undefined+optionsSource: string | undefined+step: number | undefined+tooltip: string | undefined+type: "string" | "number" | "bool" | "enum"+```++## AiParamValue — type+```+string | number | boolean+```++## AiParams — type+```+Readonly<Record<string, AiParamValue>>+```+## AiRegistry — class```actionNames: () => string[]clear: () => voidconditionNames: () => string[]getAction: (name: string) => AiAction<Ctx> | undefined+getActionParams: (name: string) => readonly AiParamDef[]+getActionSeparator: (name: string) => stringgetCondition: (name: string) => AiCondition<Ctx> | undefinedhasAction: (name: string) => booleanhasCondition: (name: string) => boolean-registerAction: (name: string, fn: AiAction<Ctx>) => void+registerAction: (name: string, fn: AiAction<Ctx> | AiActionSpec<Ctx>) => voidregisterCondition: (name: string, fn: AiCondition<Ctx>) => voidstatic new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>@@ -2554,6 +2597,7 @@ enabled: boolean | undefinedevent: stringguard: string | undefinedonce: boolean | undefined+params: Record<string, AiParamValue> | undefinedtarget: string | undefined```@@ -8801,6 +8845,11 @@ FocusPlugin(config: AssetGroupsConfig | null | undefined, folder: string): AssetGroupMode```+## formatActionArg — function+```+(params: Readonly<Record<string, AiParamValue>> | undefined, defs: readonly AiParamDef[], separator?: string): string | undefined+```+## fsmEdges — function```(def: FsmDefinition): FsmEdge[]@@ -9081,6 +9130,11 @@ InputRouter(m: Float32Array, result?: Float32Array): Float32Array```+## invokeAction — function+```+<Ctx>(registry: AiRegistry<Ctx>, name: string, ctx: Ctx, bb: Blackboard, input?: AiActionInput): void | Status+```+## isAuto — const```(d: Dimension) => boolean@@ -9381,6 +9435,11 @@ NavPlugin(tl: number, tr: number, br: number, bl: number): number```+## parseActionArg — function+```+(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>+```+## parseAnimClipAsset — function```(rawJson: unknown): AnimClipAssetDatadiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 4eee4d765..95e50a4b9 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1364 stable · 22 beta · 1 deprecated+Symbols: 1372 stable · 22 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -96,7 +96,25 @@ labels: string[]## AiAction — type```-(ctx: Ctx, bb: Blackboard, arg?: string) => void | Status+(+ ctx: Ctx,+ bb: Blackboard,+ arg?: string,+ params?: AiParams,+) => void | Status+```++## AiActionInput — interface+```+arg: string | undefined+params: Readonly<Record<string, AiParamValue>> | undefined+```++## AiActionSpec — interface+```+params: readonly AiParamDef[] | undefined+run: AiAction<Ctx>+separator: string | undefined```## AiBt — const@@ -126,16 +144,41 @@ world: WorldResourceDef<StateMachines>```+## AiParamDef — interface+```+label: string | undefined+max: number | undefined+min: number | undefined+name: string+options: readonly { label: string; value: string; }[] | undefined+optionsSource: string | undefined+step: number | undefined+tooltip: string | undefined+type: "string" | "number" | "bool" | "enum"+```++## AiParamValue — type+```+string | number | boolean+```++## AiParams — type+```+Readonly<Record<string, AiParamValue>>+```+## AiRegistry — class```actionNames: () => string[]clear: () => voidconditionNames: () => string[]getAction: (name: string) => AiAction<Ctx> | undefined+getActionParams: (name: string) => readonly AiParamDef[]+getActionSeparator: (name: string) => stringgetCondition: (name: string) => AiCondition<Ctx> | undefinedhasAction: (name: string) => booleanhasCondition: (name: string) => boolean-registerAction: (name: string, fn: AiAction<Ctx>) => void+registerAction: (name: string, fn: AiAction<Ctx> | AiActionSpec<Ctx>) => voidregisterCondition: (name: string, fn: AiCondition<Ctx>) => voidstatic new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>@@ -2562,6 +2605,7 @@ enabled: boolean | undefinedevent: stringguard: string | undefinedonce: boolean | undefined+params: Record<string, AiParamValue> | undefinedtarget: string | undefined```@@ -8998,6 +9042,11 @@ FocusPlugin(config: AssetGroupsConfig | null | undefined, folder: string): AssetGroupMode```+## formatActionArg — function+```+(params: Readonly<Record<string, AiParamValue>> | undefined, defs: readonly AiParamDef[], separator?: string): string | undefined+```+## fsmEdges — function```(def: FsmDefinition): FsmEdge[]@@ -9288,6 +9337,11 @@ InputRouter(m: Float32Array, result?: Float32Array): Float32Array```+## invokeAction — function+```+<Ctx>(registry: AiRegistry<Ctx>, name: string, ctx: Ctx, bb: Blackboard, input?: AiActionInput): void | Status+```+## isAuto — const```(d: Dimension) => boolean@@ -9588,6 +9642,11 @@ NavPlugin(tl: number, tr: number, br: number, bl: number): number```+## parseActionArg — function+```+(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>+```+## parseAnimClipAsset — function```(rawJson: unknown): AnimClipAssetDatadiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex a3a770c27..54d6ceb9e 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1344 stable · 19 beta · 1 deprecated+Symbols: 1352 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -91,7 +91,25 @@ labels: string[]## AiAction — type```-(ctx: Ctx, bb: Blackboard, arg?: string) => void | Status+(+ ctx: Ctx,+ bb: Blackboard,+ arg?: string,+ params?: AiParams,+) => void | Status+```++## AiActionInput — interface+```+arg: string | undefined+params: Readonly<Record<string, AiParamValue>> | undefined+```++## AiActionSpec — interface+```+params: readonly AiParamDef[] | undefined+run: AiAction<Ctx>+separator: string | undefined```## AiBt — const@@ -121,16 +139,41 @@ world: WorldResourceDef<StateMachines>```+## AiParamDef — interface+```+label: string | undefined+max: number | undefined+min: number | undefined+name: string+options: readonly { label: string; value: string; }[] | undefined+optionsSource: string | undefined+step: number | undefined+tooltip: string | undefined+type: "string" | "number" | "bool" | "enum"+```++## AiParamValue — type+```+string | number | boolean+```++## AiParams — type+```+Readonly<Record<string, AiParamValue>>+```+## AiRegistry — class```actionNames: () => string[]clear: () => voidconditionNames: () => string[]getAction: (name: string) => AiAction<Ctx> | undefined+getActionParams: (name: string) => readonly AiParamDef[]+getActionSeparator: (name: string) => stringgetCondition: (name: string) => AiCondition<Ctx> | undefinedhasAction: (name: string) => booleanhasCondition: (name: string) => boolean-registerAction: (name: string, fn: AiAction<Ctx>) => void+registerAction: (name: string, fn: AiAction<Ctx> | AiActionSpec<Ctx>) => voidregisterCondition: (name: string, fn: AiCondition<Ctx>) => voidstatic new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>@@ -2549,6 +2592,7 @@ enabled: boolean | undefinedevent: stringguard: string | undefinedonce: boolean | undefined+params: Record<string, AiParamValue> | undefinedtarget: string | undefined```@@ -8796,6 +8840,11 @@ FocusPlugin(config: AssetGroupsConfig | null | undefined, folder: string): AssetGroupMode```+## formatActionArg — function+```+(params: Readonly<Record<string, AiParamValue>> | undefined, defs: readonly AiParamDef[], separator?: string): string | undefined+```+## fsmEdges — function```(def: FsmDefinition): FsmEdge[]@@ -9076,6 +9125,11 @@ InputRouter(m: Float32Array, result?: Float32Array): Float32Array```+## invokeAction — function+```+<Ctx>(registry: AiRegistry<Ctx>, name: string, ctx: Ctx, bb: Blackboard, input?: AiActionInput): void | Status+```+## isAuto — const```(d: Dimension) => boolean@@ -9386,6 +9440,11 @@ NodePlatformAdapter(tl: number, tr: number, br: number, bl: number): number```+## parseActionArg — function+```+(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>+```+## parseAnimClipAsset — function```(rawJson: unknown): AnimClipAssetDatadiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 41b9f7037..fc637ab0e 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1365 stable · 17 beta · 1 deprecated+Symbols: 1373 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -91,7 +91,25 @@ labels: string[]## AiAction — type```-(ctx: Ctx, bb: Blackboard, arg?: string) => void | Status+(+ ctx: Ctx,+ bb: Blackboard,+ arg?: string,+ params?: AiParams,+) => void | Status+```++## AiActionInput — interface+```+arg: string | undefined+params: Readonly<Record<string, AiParamValue>> | undefined+```++## AiActionSpec — interface+```+params: readonly AiParamDef[] | undefined+run: AiAction<Ctx>+separator: string | undefined```## AiBt — const@@ -121,16 +139,41 @@ world: WorldResourceDef<StateMachines>```+## AiParamDef — interface+```+label: string | undefined+max: number | undefined+min: number | undefined+name: string+options: readonly { label: string; value: string; }[] | undefined+optionsSource: string | undefined+step: number | undefined+tooltip: string | undefined+type: "string" | "number" | "bool" | "enum"+```++## AiParamValue — type+```+string | number | boolean+```++## AiParams — type+```+Readonly<Record<string, AiParamValue>>+```+## AiRegistry — class```actionNames: () => string[]clear: () => voidconditionNames: () => string[]getAction: (name: string) => AiAction<Ctx> | undefined+getActionParams: (name: string) => readonly AiParamDef[]+getActionSeparator: (name: string) => stringgetCondition: (name: string) => AiCondition<Ctx> | undefinedhasAction: (name: string) => booleanhasCondition: (name: string) => boolean-registerAction: (name: string, fn: AiAction<Ctx>) => void+registerAction: (name: string, fn: AiAction<Ctx> | AiActionSpec<Ctx>) => voidregisterCondition: (name: string, fn: AiCondition<Ctx>) => voidstatic new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>@@ -2549,6 +2592,7 @@ enabled: boolean | undefinedevent: stringguard: string | undefinedonce: boolean | undefined+params: Record<string, AiParamValue> | undefinedtarget: string | undefined```@@ -9016,6 +9060,11 @@ FocusPlugin(config: AssetGroupsConfig | null | undefined, folder: string): AssetGroupMode```+## formatActionArg — function+```+(params: Readonly<Record<string, AiParamValue>> | undefined, defs: readonly AiParamDef[], separator?: string): string | undefined+```+## fsmEdges — function```(def: FsmDefinition): FsmEdge[]@@ -9306,6 +9355,11 @@ InputRouter(m: Float32Array, result?: Float32Array): Float32Array```+## invokeAction — function+```+<Ctx>(registry: AiRegistry<Ctx>, name: string, ctx: Ctx, bb: Blackboard, input?: AiActionInput): void | Status+```+## isAuto — const```(d: Dimension) => boolean@@ -9606,6 +9660,11 @@ NavPlugin(tl: number, tr: number, br: number, bl: number): number```+## parseActionArg — function+```+(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>+```+## parseAnimClipAsset — function```(rawJson: unknown): AnimClipAssetDatadiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 05dd061ae..7bc5033d8 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1355 stable · 17 beta · 1 deprecated+Symbols: 1363 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -91,7 +91,25 @@ labels: string[]## AiAction — type```-(ctx: Ctx, bb: Blackboard, arg?: string) => void | Status+(+ ctx: Ctx,+ bb: Blackboard,+ arg?: string,+ params?: AiParams,+) => void | Status+```++## AiActionInput — interface+```+arg: string | undefined+params: Readonly<Record<string, AiParamValue>> | undefined+```++## AiActionSpec — interface+```+params: readonly AiParamDef[] | undefined+run: AiAction<Ctx>+separator: string | undefined```## AiBt — const@@ -121,16 +139,41 @@ world: WorldResourceDef<StateMachines>```+## AiParamDef — interface+```+label: string | undefined+max: number | undefined+min: number | undefined+name: string+options: readonly { label: string; value: string; }[] | undefined+optionsSource: string | undefined+step: number | undefined+tooltip: string | undefined+type: "string" | "number" | "bool" | "enum"+```++## AiParamValue — type+```+string | number | boolean+```++## AiParams — type+```+Readonly<Record<string, AiParamValue>>+```+## AiRegistry — class```actionNames: () => string[]clear: () => voidconditionNames: () => string[]getAction: (name: string) => AiAction<Ctx> | undefined+getActionParams: (name: string) => readonly AiParamDef[]+getActionSeparator: (name: string) => stringgetCondition: (name: string) => AiCondition<Ctx> | undefinedhasAction: (name: string) => booleanhasCondition: (name: string) => boolean-registerAction: (name: string, fn: AiAction<Ctx>) => void+registerAction: (name: string, fn: AiAction<Ctx> | AiActionSpec<Ctx>) => voidregisterCondition: (name: string, fn: AiCondition<Ctx>) => voidstatic new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>@@ -2549,6 +2592,7 @@ enabled: boolean | undefinedevent: stringguard: string | undefinedonce: boolean | undefined+params: Record<string, AiParamValue> | undefinedtarget: string | undefined```@@ -8820,6 +8864,11 @@ FocusPlugin(config: AssetGroupsConfig | null | undefined, folder: string): AssetGroupMode```+## formatActionArg — function+```+(params: Readonly<Record<string, AiParamValue>> | undefined, defs: readonly AiParamDef[], separator?: string): string | undefined+```+## fsmEdges — function```(def: FsmDefinition): FsmEdge[]@@ -9105,6 +9154,11 @@ InputRouter(m: Float32Array, result?: Float32Array): Float32Array```+## invokeAction — function+```+<Ctx>(registry: AiRegistry<Ctx>, name: string, ctx: Ctx, bb: Blackboard, input?: AiActionInput): void | Status+```+## isAuto — const```(d: Dimension) => boolean@@ -9405,6 +9459,11 @@ NavPlugin(tl: number, tr: number, br: number, bl: number): number```+## parseActionArg — function+```+(arg: string | undefined, params: readonly AiParamDef[], separator?: string): Record<string, AiParamValue>+```+## parseAnimClipAsset — function```(rawJson: unknown): AnimClipAssetDatadiff --git a/sdk/src/ai/bt/BtRunner.ts b/sdk/src/ai/bt/BtRunner.tsindex 3d5d36d98..97a5082a8 100644--- a/sdk/src/ai/bt/BtRunner.ts+++ b/sdk/src/ai/bt/BtRunner.ts@@ -14,7 +14,7 @@*/import type { Blackboard } from '../fsm/Blackboard';-import type { AiRegistry } from '../fsm/registry';+import { invokeAction, type AiRegistry } from '../fsm/registry';import { Status } from '../status';import type { BtDefinition, BtNode } from './types';@@ -49,9 +49,9 @@ function tickNode<Ctx>(): Status {switch (node.type) {case 'action': {- const fn = registry.getAction(node.name ?? '');- if (!fn) return Status.Failure;- const r = fn(ctx, bb, node.arg);+ const name = node.name ?? '';+ if (!registry.hasAction(name)) return Status.Failure;+ const r = invokeAction(registry, name, ctx, bb, { arg: node.arg });// A void-returning (one-shot FSM-style) action completes as Success.return r === undefined ? Status.Success : r;}diff --git a/sdk/src/ai/fsm/FsmRunner.ts b/sdk/src/ai/fsm/FsmRunner.tsindex f7781f8b7..e613056d7 100644--- a/sdk/src/ai/fsm/FsmRunner.ts+++ b/sdk/src/ai/fsm/FsmRunner.ts@@ -12,7 +12,7 @@import { actionRefName, actionRefArg, type FsmActionRef, type FsmDefinition, type FsmState, type FsmTransition } from './types';import { Blackboard, evalGuards } from './Blackboard';-import type { AiRegistry } from './registry';+import { invokeAction, type AiRegistry } from './registry';/** A definition indexed by state name for O(1) lookup during ticks. */export interface CompiledFsm {@@ -95,5 +95,5 @@ function runAction<Ctx>(): void {const name = actionRefName(ref);if (!name) return;- registry.getAction(name)?.(ctx, bb, actionRefArg(ref));+ invokeAction(registry, name, ctx, bb, { arg: actionRefArg(ref) });}diff --git a/sdk/src/ai/fsm/index.ts b/sdk/src/ai/fsm/index.tsindex 9e4584463..e70b6f169 100644--- a/sdk/src/ai/fsm/index.ts+++ b/sdk/src/ai/fsm/index.ts@@ -15,7 +15,19 @@ export type {} from './types';export { actionRefName, actionRefArg } from './types';export { Blackboard, evalGuard, evalGuards } from './Blackboard';-export { AiRegistry, type AiAction, type AiCondition } from './registry';+export {+ AiRegistry,+ invokeAction,+ parseActionArg,+ formatActionArg,+ type AiAction,+ type AiCondition,+ type AiActionSpec,+ type AiActionInput,+ type AiParamDef,+ type AiParamValue,+ type AiParams,+} from './registry';export {compileFsm,createFsmRunState,diff --git a/sdk/src/ai/fsm/registry.ts b/sdk/src/ai/fsm/registry.tsindex 430c63ad9..33c086f3c 100644--- a/sdk/src/ai/fsm/registry.ts+++ b/sdk/src/ai/fsm/registry.ts@@ -2,31 +2,118 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file registry.ts- * @brief AiRegistry — names → leaf action/condition functions.+ * @brief AiRegistry — names → leaf action/condition functions, plus the+ * parameters those names take.*- * The binding between code-free AI data (`.esfsm`/`.esbt` referencing names) and- * real gameplay logic. Generic over the context type `Ctx` so the pure core- * stays wasm-free; the engine layer instantiates it with a concrete AiContext+ * The binding between code-free data (`.esfsm`/`.esbt`/`EventBinding` referencing+ * names) and real gameplay logic. Generic over the context type `Ctx` so the pure+ * core stays wasm-free; the engine layer instantiates it with a concrete AiContext* (a BehaviorContext superset) and exposes the `registerAction`/`registerCondition`* free functions over a shared singleton.+ *+ * An action may DECLARE its parameters ({@link AiParamDef}), which is what lets an+ * editor render real controls instead of one free-text box. Declaring them changes+ * nothing on disk: every action keeps a canonical string form (`"tabs:settings"`),+ * and {@link invokeAction} projects between the two in both directions — so+ * authored data written before the declaration still runs, data written as+ * parameters still reaches an action that only reads `arg`, and the FSM, the+ * behaviour tree and an event wire all dispatch through one path.*/import type { Blackboard } from './Blackboard';import type { Status } from '../status';+/** A parameter value as it is authored and serialized. */+export type AiParamValue = string | number | boolean;+/** Declared parameters of one action reference, keyed by {@link AiParamDef.name}. */+export type AiParams = Readonly<Record<string, AiParamValue>>;+// Returns Status (a BT leaf that may run across frames) or nothing (a one-shot// FSM action). FSM ignores the return; BT reads it, treating void as Success.-// `arg` is the optional per-reference string the authored data carries-// (FsmActionRef / BtNode.arg); argument-free actions simply ignore it.-export type AiAction<Ctx> = (ctx: Ctx, bb: Blackboard, arg?: string) => void | Status;+// `arg` is the canonical string form of the reference (what authored data has+// always carried); `params` is the same input keyed by declared parameter name,+// empty for an action that declares none. An action reads whichever it prefers —+// both are always supplied, so neither channel is a second way to be wrong.+export type AiAction<Ctx> = (+ ctx: Ctx,+ bb: Blackboard,+ arg?: string,+ params?: AiParams,+) => void | Status;export type AiCondition<Ctx> = (ctx: Ctx, bb: Blackboard) => boolean;+/**+ * One declared parameter. The vocabulary is deliberately the component-field one+ * (`enum` options, numeric range, tooltip) so an editor renders action parameters+ * with the very same controls it renders component fields with — including+ * `optionsSource`, the dynamic-enum escape hatch for choices that depend on the+ * entity (a controller's name, one of its pages).+ */+export interface AiParamDef {+ /** Key in the params record, and the fallback label. */+ name: string;+ /** Control kind. Asset/entity references are deliberately absent until the+ * cook's discovery pass and the scene's entity remapper can see them. */+ type: 'string' | 'number' | 'bool' | 'enum';+ /** Human label; defaults to a prettified `name`. */+ label?: string;+ tooltip?: string;+ /** Fixed choices for `type: 'enum'`. */+ options?: readonly { label: string; value: string }[];+ /** Editor-resolved choice provider (e.g. `'uiController'`, `'uiControllerPage'`). */+ optionsSource?: string;+ min?: number;+ max?: number;+ step?: number;+}++/** An action registered with metadata rather than as a bare function. */+export interface AiActionSpec<Ctx> {+ run: AiAction<Ctx>;+ /** Declared parameters, in canonical string order. */+ params?: readonly AiParamDef[];+ /**+ * Separator joining the parameters in the canonical string form. Default+ * `':'` — the convention authored data already uses (`"tabs:settings"`).+ * The LAST parameter absorbs any remaining separators, so a value may+ * contain one.+ */+ separator?: string;+}++interface ActionEntry<Ctx> {+ fn: AiAction<Ctx>;+ params: readonly AiParamDef[];+ separator: string;+}+export class AiRegistry<Ctx = unknown> {- private actions = new Map<string, AiAction<Ctx>>();+ private actions = new Map<string, ActionEntry<Ctx>>();private conditions = new Map<string, AiCondition<Ctx>>();- registerAction(name: string, fn: AiAction<Ctx>): void {- this.actions.set(name, fn);+ /**+ * Register `name`, either as a bare function (input is the raw `arg` string,+ * as it always was) or with declared parameters.+ *+ * A declared action is stored WRAPPED in the projection, so both shapes are+ * filled in no matter how it is reached — {@link invokeAction}, a direct+ * `getAction(name)(ctx, bb, "tabs:settings")`, anything. Normalizing once+ * here is what keeps the two forms from becoming two contracts.+ */+ registerAction(name: string, fn: AiAction<Ctx> | AiActionSpec<Ctx>): void {+ const spec = typeof fn === 'function' ? { run: fn } : fn;+ const params = spec.params ?? [];+ const separator = spec.separator ?? ':';+ const run = spec.run;+ const wrapped: AiAction<Ctx> = params.length === 0+ ? run // no declaration, no projection — byte-identical behaviour+ : (ctx, bb, arg, given) => {+ const named = given && Object.keys(given).length > 0+ ? given+ : parseActionArg(arg, params, separator);+ return run(ctx, bb, arg ?? formatActionArg(named, params, separator), named);+ };+ this.actions.set(name, { fn: wrapped, params, separator });}registerCondition(name: string, fn: AiCondition<Ctx>): void {@@ -34,7 +121,17 @@ export class AiRegistry<Ctx = unknown> {}getAction(name: string): AiAction<Ctx> | undefined {- return this.actions.get(name);+ return this.actions.get(name)?.fn;+ }++ /** The declared parameters of `name` (empty when it takes a bare string). */+ getActionParams(name: string): readonly AiParamDef[] {+ return this.actions.get(name)?.params ?? [];+ }++ /** The separator joining `name`'s parameters in the canonical string form. */+ getActionSeparator(name: string): string {+ return this.actions.get(name)?.separator ?? ':';}getCondition(name: string): AiCondition<Ctx> | undefined {@@ -64,3 +161,89 @@ export class AiRegistry<Ctx = unknown> {this.conditions.clear();}}++/** How an authored reference carries its input: a string, named values, or both. */+export interface AiActionInput {+ arg?: string;+ params?: Readonly<Record<string, AiParamValue>>;+}++/**+ * Split a canonical string into declared parameters. The last parameter absorbs+ * the remainder, so `"tabs:a:b"` against `[controller, page]` yields+ * `{controller: 'tabs', page: 'a:b'}` — the same rule `ui.setPage` hand-rolled.+ * Numbers and booleans are coerced to their declared type.+ */+export function parseActionArg(+ arg: string | undefined,+ params: readonly AiParamDef[],+ separator = ':',+): Record<string, AiParamValue> {+ const out: Record<string, AiParamValue> = {};+ if (!arg || params.length === 0) return out;+ const parts: string[] = [];+ let rest = arg;+ for (let i = 0; i < params.length - 1; i++) {+ const at = rest.indexOf(separator);+ if (at < 0) break;+ parts.push(rest.slice(0, at));+ rest = rest.slice(at + separator.length);+ }+ parts.push(rest);+ for (let i = 0; i < parts.length && i < params.length; i++) {+ out[params[i].name] = coerce(parts[i], params[i].type);+ }+ return out;+}++/**+ * Join declared parameters back into the canonical string — so data authored as+ * parameters still reaches an action (or a tool) that only speaks `arg`.+ * Trailing empties are dropped, keeping `"tabs"` rather than `"tabs:"`.+ */+export function formatActionArg(+ params: Readonly<Record<string, AiParamValue>> | undefined,+ defs: readonly AiParamDef[],+ separator = ':',+): string | undefined {+ if (!params || defs.length === 0) return undefined;+ const parts = defs.map((d) => {+ const v = params[d.name];+ return v === undefined || v === null ? '' : String(v);+ });+ while (parts.length && parts[parts.length - 1] === '') parts.pop();+ return parts.length ? parts.join(separator) : undefined;+}++/**+ * The one dispatch path for a named action, shared by the FSM, the behaviour+ * tree and event wires: resolve the name and hand it whichever form the authored+ * data carries — the registration wrapper fills in the other. An unknown name is+ * a silent no-op, so each caller reports it in its own vocabulary (a BT leaf+ * fails, an event wire warns).+ */+export function invokeAction<Ctx>(+ registry: AiRegistry<Ctx>,+ name: string,+ ctx: Ctx,+ bb: Blackboard,+ input: AiActionInput = {},+): void | Status {+ const fn = registry.getAction(name);+ if (!fn) return undefined;+ // Named values win over the string when the row carries both.+ const named = input.params && Object.keys(input.params).length > 0 ? input.params : undefined;+ const arg = named+ ? formatActionArg(named, registry.getActionParams(name), registry.getActionSeparator(name)) ?? input.arg+ : input.arg;+ return fn(ctx, bb, arg, named);+}++function coerce(raw: string, type: AiParamDef['type']): AiParamValue {+ if (type === 'number') {+ const n = Number(raw);+ return Number.isFinite(n) ? n : 0;+ }+ if (type === 'bool') return raw === 'true' || raw === '1';+ return raw;+}diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 04945fce2..160ed146e 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -603,6 +603,16 @@ export {aiRegistry,registerAction,registerCondition,+ // The declared-parameter surface: an action says what it takes, and the+ // projection to/from the canonical `arg` string keeps old data running.+ invokeAction,+ parseActionArg,+ formatActionArg,+ type AiParamDef,+ type AiParamValue,+ type AiParams,+ type AiActionSpec,+ type AiActionInput,StateMachineAgent,registerFsm,getFsm,diff --git a/sdk/src/eventBinding.ts b/sdk/src/eventBinding.tsindex c4a6ec008..fb3da3c92 100644--- a/sdk/src/eventBinding.ts+++ b/sdk/src/eventBinding.ts@@ -37,6 +37,7 @@ import { log } from './logger';import { EntityEvents, EntityEventQueue, type EntityEvent, type Unsubscribe } from './entityEvents';import { Blackboard } from './ai/fsm/Blackboard';import { aiRegistry, type AiContext } from './ai/fsm/AiContext';+import { invokeAction, type AiParamValue } from './ai/fsm/registry';import { AiFsm } from './ai/fsm/FsmPlugin';import { ensureBuiltinAiRegistrations } from './ai/builtins';@@ -57,8 +58,17 @@ export interface EventBindingRow {target?: string;/** Registered action name (`aiRegistry`), e.g. `'ui.setPage'`. */action: string;- /** The action's argument, e.g. `'tabs:settings'`. */+ /**+ * The action's argument in canonical string form, e.g. `'tabs:settings'`.+ * Rows authored before the action declared its parameters keep this and+ * still run — the registry projects between the two forms.+ */arg?: string;+ /**+ * The action's declared parameters by name, e.g. `{controller: 'tabs', page:+ * 'settings'}`. Present when the action declares parameters; wins over `arg`.+ */+ params?: Record<string, AiParamValue>;/** Registered condition name that must pass for the row to run. */guard?: string;/** Run at most once, then stay inert until the scene reloads. */@@ -152,8 +162,7 @@ export function createEventBindingRuntime(host: EventBindingHost): EventBindingRconst fired = new Set<string>();const runRow = (self: Entity, row: EventBindingRow): void => {- const action = aiRegistry.getAction(row.action);- if (!action) {+ if (!aiRegistry.hasAction(row.action)) {log.warn('events', `EventBinding: unknown action "${row.action}"`);return;}@@ -181,7 +190,9 @@ export function createEventBindingRuntime(host: EventBindingHost): EventBindingR}if (!guard(ctx, bb)) return;}- action(ctx, bb, row.arg);+ // The same dispatch path the FSM and the behaviour tree take, so an+ // action sees identical input whichever authored surface reached it.+ invokeAction(aiRegistry, row.action, ctx, bb, { arg: row.arg, params: row.params });};const handle = (event: EntityEvent): void => {@@ -306,28 +317,35 @@ export class EventBindingPlugin implements Plugin {*/export function ensureEventBindingActions(): void {if (!aiRegistry.hasAction('fsm.fire')) {- aiRegistry.registerAction('fsm.fire', (_ctx, bb, arg) => {- if (arg) bb.fire(arg);+ aiRegistry.registerAction('fsm.fire', {+ params: [{ name: 'trigger', type: 'string' }],+ run: (_ctx, bb, _arg, params) => {+ const trigger = params?.trigger;+ if (typeof trigger === 'string' && trigger) bb.fire(trigger);+ },});}if (!aiRegistry.hasAction('blackboard.set')) {- // `key=value` — value parsed as JSON when it can be (numbers, booleans),- // else kept as the raw string, so both `hp=3` and `mode=hard` do the- // obvious thing.- aiRegistry.registerAction('blackboard.set', (_ctx, bb, arg) => {- if (!arg) return;- const eq = arg.indexOf('=');- if (eq < 0) return;- const key = arg.slice(0, eq).trim();- const raw = arg.slice(eq + 1).trim();- if (!key) return;- let value: unknown = raw;- try {- value = JSON.parse(raw);- } catch {- /* a bare word is its own value */- }- bb.set(key, value);+ // `key=value`. The value keeps its JSON reading when it has one (`3`,+ // `true`), so both `lives=3` and `mode=hard` do the obvious thing.+ aiRegistry.registerAction('blackboard.set', {+ separator: '=',+ params: [{ name: 'key', type: 'string' }, { name: 'value', type: 'string' }],+ run: (_ctx, bb, _arg, params) => {+ const key = typeof params?.key === 'string' ? params.key.trim() : '';+ if (!key) return;+ const raw = params?.value;+ if (raw === undefined) return;+ let value: unknown = raw;+ if (typeof raw === 'string') {+ try {+ value = JSON.parse(raw.trim());+ } catch {+ value = raw.trim(); // a bare word is its own value+ }+ }+ bb.set(key, value);+ },});}}diff --git a/sdk/src/ui/controller/ai-builtins.ts b/sdk/src/ui/controller/ai-builtins.tsindex b2d681a25..3ccbff708 100644--- a/sdk/src/ui/controller/ai-builtins.ts+++ b/sdk/src/ui/controller/ai-builtins.ts@@ -22,10 +22,20 @@ import { setControllerPage } from './ui-controller';*/export function ensureControllerAiRegistrations(): void {if (aiRegistry.hasAction('ui.setPage')) return;- aiRegistry.registerAction('ui.setPage', (ctx, _bb, arg) => {- if (!arg) return;- const sep = arg.indexOf(':');- if (sep < 0) return;- setControllerPage(ctx.world, ctx.entity, arg.slice(0, sep), arg.slice(sep + 1));+ aiRegistry.registerAction('ui.setPage', {+ // Declaring the two halves is what turns the editor's single text box into+ // two dropdowns; the canonical `"controller:page"` string is unchanged, so+ // every `.esfsm` already on disk keeps working (registry.ts projects+ // between the two forms).+ params: [+ { name: 'controller', type: 'enum', optionsSource: 'uiController' },+ { name: 'page', type: 'enum', optionsSource: 'uiControllerPage' },+ ],+ run: (ctx, _bb, _arg, params) => {+ const controller = params?.controller;+ const page = params?.page;+ if (typeof controller !== 'string' || typeof page !== 'string' || !controller || !page) return;+ setControllerPage(ctx.world, ctx.entity, controller, page);+ },});}diff --git a/sdk/tests/ai-action-params.test.ts b/sdk/tests/ai-action-params.test.tsnew file mode 100644index 000000000..2aea190f0--- /dev/null+++ b/sdk/tests/ai-action-params.test.ts@@ -0,0 +1,114 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ai-action-params.test.ts+ * @brief Declared action parameters and their canonical string projection —+ * the contract that lets one action serve `.esfsm` strings and typed+ * editor rows without becoming two contracts.+ */+import { describe, expect, it, beforeEach } from 'vitest';+import {+ AiRegistry,+ invokeAction,+ parseActionArg,+ formatActionArg,+ type AiParamDef,+ type AiParams,+} from '../src/ai/fsm/registry';+import { Blackboard } from '../src/ai/fsm/Blackboard';++const PAIR: AiParamDef[] = [+ { name: 'controller', type: 'enum' },+ { name: 'page', type: 'enum' },+];++describe('parseActionArg', () => {+ it('splits positionally, last parameter absorbing the rest', () => {+ expect(parseActionArg('tabs:settings', PAIR)).toEqual({ controller: 'tabs', page: 'settings' });+ expect(parseActionArg('tabs:a:b', PAIR)).toEqual({ controller: 'tabs', page: 'a:b' });+ });++ it('honours a custom separator', () => {+ const defs: AiParamDef[] = [{ name: 'key', type: 'string' }, { name: 'value', type: 'string' }];+ expect(parseActionArg('mode=hard', defs, '=')).toEqual({ key: 'mode', value: 'hard' });+ });++ it('coerces to the declared type', () => {+ const defs: AiParamDef[] = [{ name: 'count', type: 'number' }, { name: 'loop', type: 'bool' }];+ expect(parseActionArg('3:true', defs)).toEqual({ count: 3, loop: true });+ expect(parseActionArg('nope:0', defs)).toEqual({ count: 0, loop: false });+ });++ it('is empty for no arg or no declaration', () => {+ expect(parseActionArg(undefined, PAIR)).toEqual({});+ expect(parseActionArg('x', [])).toEqual({});+ });++ it('fills only what the string provides', () => {+ expect(parseActionArg('tabs', PAIR)).toEqual({ controller: 'tabs' });+ });+});++describe('formatActionArg', () => {+ it('round-trips through parse', () => {+ const params = parseActionArg('tabs:settings', PAIR);+ expect(formatActionArg(params, PAIR)).toBe('tabs:settings');+ });++ it('drops trailing empties rather than emitting "tabs:"', () => {+ expect(formatActionArg({ controller: 'tabs' }, PAIR)).toBe('tabs');+ });++ it('is undefined when there is nothing to say', () => {+ expect(formatActionArg({}, PAIR)).toBeUndefined();+ expect(formatActionArg({ controller: 'x' }, [])).toBeUndefined();+ });+});++describe('a registered action sees both shapes, whichever the caller has', () => {+ let reg: AiRegistry<{ tag: string }>;+ let seen: Array<{ arg?: string; params?: AiParams }>;+ const ctx = { tag: 'ctx' };+ const bb = new Blackboard();++ beforeEach(() => {+ seen = [];+ reg = new AiRegistry<{ tag: string }>();+ reg.registerAction('ui.setPage', {+ params: PAIR,+ run: (_ctx, _bb, arg, params) => { seen.push({ arg, params }); },+ });+ });++ it('a legacy string call gets parsed parameters', () => {+ reg.getAction('ui.setPage')!(ctx, bb, 'tabs:settings');+ expect(seen[0]).toEqual({ arg: 'tabs:settings', params: { controller: 'tabs', page: 'settings' } });+ });++ it('a parameters-only call gets the canonical string', () => {+ invokeAction(reg, 'ui.setPage', ctx, bb, { params: { controller: 'tabs', page: 'home' } });+ expect(seen[0]).toEqual({ arg: 'tabs:home', params: { controller: 'tabs', page: 'home' } });+ });++ it('parameters win when a row carries a stale string too', () => {+ invokeAction(reg, 'ui.setPage', ctx, bb, { arg: 'old:value', params: { controller: 'tabs', page: 'home' } });+ expect(seen[0]!.params).toEqual({ controller: 'tabs', page: 'home' });+ });++ it('an undeclared action is untouched — the raw string, no params', () => {+ reg.registerAction('plain', (_c, _b, arg, params) => { seen.push({ arg, params }); });+ invokeAction(reg, 'plain', ctx, bb, { arg: 'a:b' });+ expect(seen[0]).toEqual({ arg: 'a:b', params: undefined });+ });++ it('invoking an unknown name is a no-op, not a throw', () => {+ expect(() => invokeAction(reg, 'nope', ctx, bb, { arg: 'x' })).not.toThrow();+ expect(seen).toHaveLength(0);+ });++ it('exposes the declaration for editor palettes', () => {+ expect(reg.getActionParams('ui.setPage')).toEqual(PAIR);+ expect(reg.getActionSeparator('ui.setPage')).toBe(':');+ expect(reg.getActionParams('unknown')).toEqual([]);+ });+});diff --git a/sdk/tests/event-binding.test.ts b/sdk/tests/event-binding.test.tsindex 1ed2cb127..f0b96e4da 100644--- a/sdk/tests/event-binding.test.ts+++ b/sdk/tests/event-binding.test.ts@@ -17,6 +17,7 @@ import {} from '../src/eventBinding';import { Blackboard } from '../src/ai/fsm/Blackboard';import { aiRegistry } from '../src/ai/fsm/AiContext';+import type { AiParams } from '../src/ai/fsm/registry';import { Children, Name, Parent } from '../src/component';import type { AnyComponentDef } from '../src/component';import type { Entity } from '../src/types';@@ -87,7 +88,7 @@ function makeRuntime(world: TestWorld) {}/** Records (entity, arg) for every invocation of the test action. */-let calls: Array<{ entity: Entity; arg?: string }> = [];+let calls: Array<{ entity: Entity; arg?: string; params?: AiParams }> = [];beforeEach(() => {calls = [];@@ -285,6 +286,40 @@ describe('dispatch', () => {});});+describe('declared parameters', () => {+ beforeEach(() => {+ aiRegistry.registerAction('test.pair', {+ params: [{ name: 'left', type: 'string' }, { name: 'right', type: 'string' }],+ run: (ctx, _bb, arg, params) => { calls.push({ entity: ctx.entity, arg, params }); },+ });+ });++ it('a row authored as params reaches the action as params AND as the canonical string', () => {+ const world = makeWorld();+ const button = world.spawn('Button');+ bind(world, button, { event: 'click', action: 'test.pair', params: { left: 'a', right: 'b' } });++ const { events, runtime } = makeRuntime(world);+ runtime.sync();+ events.emit(button, 'click');++ expect(calls[0]!.arg).toBe('a:b');+ expect(calls[0]!.params).toEqual({ left: 'a', right: 'b' });+ });++ it('a row authored as a string (before the action declared params) still runs', () => {+ const world = makeWorld();+ const button = world.spawn('Button');+ bind(world, button, { event: 'click', action: 'test.pair', arg: 'a:b' });++ const { events, runtime } = makeRuntime(world);+ runtime.sync();+ events.emit(button, 'click');++ expect(calls[0]!.params).toEqual({ left: 'a', right: 'b' });+ });+});+describe('the actions events unlock', () => {it('fsm.fire raises a trigger on the target blackboard', () => {ensureEventBindingActions();