@elurjs/universal 0.1.7 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/sdui/a2ui.ts CHANGED
@@ -3,6 +3,15 @@
3
3
  // mantiene el estado por superficie (components + data model) y
4
4
  // materializa un `SduiEnvelope` que entra por `mountEnvelope` — todo el
5
5
  // contrato existente aplica (signals, exprs, intents, fail-closed).
6
+ // ADR-0222 — v1.0: el dialecto se fija por superficie en createSurface
7
+ // (`version` o URL del catálogo; sin pistas → 0.9); directivas `@path`/
8
+ // `@call`/`@index`, mixins `@checks`/`@accessibility`/`@metadata`/
9
+ // `@catalogId`, `{path}`/`{call}` planos = literales (@@ escapa),
10
+ // createSurface inline, `null` borra en updateDataModel, theme
11
+ // rechazado, RPC bidireccional (callRendererFunction →
12
+ // rendererFunctionResponse/error, callAgentFunction →
13
+ // agentFunctionResponse) por la cola `takeOutbound`/`onOutbound` —
14
+ // nunca eval de JS remoto: solo handlers registrados por el host.
6
15
  //
7
16
  // Mapa normativo:
8
17
  // - Data model → signals planas por path: "/contact/firstName" →
@@ -36,7 +45,8 @@ import type { Intent } from "./intents";
36
45
  import type { IRNode } from "../ir/schema";
37
46
  import type { RichNode } from "./lower";
38
47
 
39
- /** Mensaje del stream agente→renderer (v0.9 y v1.0 comparten nombres). */
48
+ /** Mensaje del stream agente→renderer (v0.9 y v1.0 comparten nombres;
49
+ * v1.0 añade RPC bidireccional). */
40
50
  export type A2uiMessage = {
41
51
  version?: string;
42
52
  createSurface?: {
@@ -44,6 +54,10 @@ export type A2uiMessage = {
44
54
  catalogId: string;
45
55
  sendDataModel?: boolean;
46
56
  theme?: { primaryColor?: string; iconUrl?: string; agentDisplayName?: string };
57
+ /** v1.0 — superficie completa en un solo mensaje. */
58
+ components?: Array<{ id: string; component: string } & Record<string, unknown>>;
59
+ dataModel?: Record<string, unknown>;
60
+ metadata?: Record<string, unknown>;
47
61
  };
48
62
  updateComponents?: {
49
63
  surfaceId: string;
@@ -55,14 +69,31 @@ export type A2uiMessage = {
55
69
  value?: unknown;
56
70
  };
57
71
  deleteSurface?: { surfaceId: string };
72
+ /** v1.0 — el agente invoca una función del renderer. */
73
+ callRendererFunction?: {
74
+ surfaceId?: string;
75
+ callId: string;
76
+ functionCall: { call: string; args?: Record<string, unknown>; catalogId?: string };
77
+ };
78
+ /** v1.0 — respuesta del agente a un `callAgentFunction` nuestro. */
79
+ agentFunctionResponse?: {
80
+ callId: string;
81
+ value?: unknown;
82
+ error?: { code?: string; message?: string };
83
+ };
58
84
  };
59
85
 
60
86
  export type A2uiComponent =
61
87
  { id: string; component: string } & Record<string, unknown>;
62
88
 
89
+ /** Dialecto de entrada por superficie — se fija en `createSurface` y
90
+ * no cambia (spec: los catálogos mezclados comparten versión). */
91
+ export type A2uiSpec = "0.9" | "1.0";
92
+
63
93
  type A2uiSurface = {
64
94
  surfaceId: string;
65
95
  catalogId: string;
96
+ spec: A2uiSpec;
66
97
  sendDataModel: boolean;
67
98
  components: Record<string, A2uiComponent>;
68
99
  model: Record<string, unknown>;
@@ -71,9 +102,40 @@ type A2uiSurface = {
71
102
  diags: Diagnostic[];
72
103
  };
73
104
 
105
+ /** Función registrada del renderer invocable por el agente (v1.0
106
+ * `callRendererFunction`). Nunca evalúa JS remoto: el agente solo
107
+ * nombra handlers ya declarados por el host. `args` viaja crudo. */
108
+ export type A2uiRendererFunction =
109
+ (args: Record<string, unknown>) => unknown;
110
+
111
+ export type A2uiRendererOpts = {
112
+ /** Funciones del renderer expuestas al agente (v1.0). */
113
+ rendererFunctions?: Record<string, A2uiRendererFunction>;
114
+ /** Callback push para mensajes renderer→agente (respuestas RPC,
115
+ * `callAgentFunction`, `error`). Opcional; `takeOutbound()` drena
116
+ * la cola en modo pull. */
117
+ onOutbound?: (msg: Record<string, unknown>) => void;
118
+ /** Generador de callIds (tests deterministas). */
119
+ nextCallId?: () => string;
120
+ };
121
+
74
122
  export type A2uiRenderer = {
75
123
  /** Aplica un mensaje del stream; devuelve los diagnósticos nuevos. */
76
124
  apply(msg: unknown): Diagnostic[];
125
+ /** Versión del dialecto que la superficie declaró (null si no existe). */
126
+ specVersion(surfaceId: string): A2uiSpec | null;
127
+ /** v1.0 — invoca una función del agente: encola `callAgentFunction`
128
+ * y devuelve el callId; la respuesta llega por
129
+ * `agentFunctionResponse` → `onAgentResult`. */
130
+ callAgentFunction(
131
+ surfaceId: string, call: string, args: Record<string, unknown>,
132
+ ): string | null;
133
+ /** Registra el receptor de `agentFunctionResponse` (una sola). */
134
+ onAgentResult(
135
+ cb: (callId: string, ok: boolean, payload: unknown) => void,
136
+ ): void;
137
+ /** Drena la cola de mensajes renderer→agente pendientes. */
138
+ takeOutbound(): Record<string, unknown>[];
77
139
  /** Envelope SDUI materializado del estado vigente (null sin root). */
78
140
  envelope(surfaceId: string): SduiEnvelope | null;
79
141
  /** Snapshot del data model de la superficie (sendDataModel). */
@@ -98,9 +160,42 @@ export type A2uiRenderer = {
98
160
  dispose(surfaceId: string): void;
99
161
  };
100
162
 
101
- export const A2UI_VERSIONS = ["v0.9", "v0.9.1", "v1.0"] as const;
163
+ export const A2UI_VERSIONS =
164
+ ["v0.9", "v0.9.1", "v1.0", "0.9", "0.9.1", "1.0"] as const;
102
165
  export const A2UI_BASIC_CATALOG =
103
166
  "https://a2ui.org/specification/v0_9/catalogs/basic/catalog.json";
167
+ export const A2UI_BASIC_CATALOG_V1 =
168
+ "https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json";
169
+ const KNOWN_CATALOGS = new Set([A2UI_BASIC_CATALOG, A2UI_BASIC_CATALOG_V1]);
170
+
171
+ /** Versión → dialecto. El campo `version` del mensaje manda; si falta
172
+ * se infiere de la URL del catálogo; sin pistas, 0.9 (retrocompatible). */
173
+ function detectSpec(msg: A2uiMessage): A2uiSpec {
174
+ const v = String(msg.version ?? "");
175
+ if (v === "1.0" || v === "v1.0") return "1.0";
176
+ const cat = String(msg.createSurface?.catalogId ?? "");
177
+ if (/v1(_0|\b)|v1\.0/.test(cat)) return "1.0";
178
+ return "0.9";
179
+ }
180
+
181
+ /** Clave mixin del envelope de componente según dialecto: v1.0 lleva
182
+ * prefijo `@` (`@checks`, `@accessibility`, `@metadata`, `@catalogId`). */
183
+ function mx(c: A2uiComponent, spec: A2uiSpec, name: string): unknown {
184
+ return spec === "1.0" ? c["@" + name] : c[name];
185
+ }
186
+
187
+ /** Desescapa el prefijo `@@` → `@` en claves literales (v1.0). */
188
+ function unescapeAt(v: unknown): unknown {
189
+ if (Array.isArray(v)) return v.map(unescapeAt);
190
+ if (v !== null && typeof v === "object") {
191
+ const out: Record<string, unknown> = {};
192
+ for (const [k, x] of Object.entries(v as object)) {
193
+ out[k.startsWith("@@") ? k.slice(1) : k] = unescapeAt(x);
194
+ }
195
+ return out;
196
+ }
197
+ return v;
198
+ }
104
199
  export const A2UI_COMPONENTS = [
105
200
  "Text", "Row", "Column", "Card", "Button", "Image", "Divider",
106
201
  "List", "CheckBox", "TextField", "Slider", "DateTimeInput",
@@ -244,7 +339,8 @@ function interpFormatString(
244
339
  cur = "";
245
340
  }
246
341
  const p = raw.slice(i + 2, end).trim();
247
- parts.push(dynToExpr({ path: p }, ctx, "formatString") ??
342
+ const key = ctx.surface.spec === "1.0" ? "@path" : "path";
343
+ parts.push(dynToExpr({ [key]: p }, ctx, "formatString") ??
248
344
  { lit: "" });
249
345
  i = end + 1;
250
346
  continue;
@@ -269,8 +365,37 @@ function dynToExpr(
269
365
  }
270
366
  if (typeof v !== "object") return null;
271
367
  const o = v as Record<string, unknown>;
272
- if (typeof o.path === "string") {
273
- const p = o.path;
368
+ const v1 = ctx.surface.spec === "1.0";
369
+ // Claves directivas por dialecto: 0.9 → path/call; 1.0 → @path/@call
370
+ // (@index extra). En 1.0 un `{path}`/`{call}` plano es LITERAL.
371
+ const pathKey = v1 ? "@path" : "path";
372
+ const callKey = v1 ? "@call" : "call";
373
+ if (v1) {
374
+ for (const k of Object.keys(o)) {
375
+ if (k.startsWith("@") && !k.startsWith("@@") &&
376
+ k !== "@path" && k !== "@call" && k !== "@index") {
377
+ ctx.diags.push(diagnostic("sdui.a2ui.directive", "schema",
378
+ "warn", `directiva desconocida "${k}" en ${where} ` +
379
+ "— objeto tratado como literal"));
380
+ break;
381
+ }
382
+ }
383
+ if (o["@index"] !== undefined) {
384
+ if (!ctx.rowFields) {
385
+ ctx.diags.push(diagnostic("sdui.a2ui.directive", "schema",
386
+ "warn", `@index fuera de template de colección ` +
387
+ `(${where}) — sin valor`));
388
+ return null;
389
+ }
390
+ ctx.diags.push(diagnostic("sdui.a2ui.index", "capability",
391
+ "warn", `@index sin índice de fila en el dialecto ` +
392
+ `(${where}) — se evalúa a null`));
393
+ return null;
394
+ }
395
+ }
396
+ const rawPath = o[pathKey];
397
+ if (typeof rawPath === "string") {
398
+ const p = rawPath;
274
399
  if (p.startsWith("/")) return { ref: a2uiSignalName(p) };
275
400
  // Relativo — dentro de template de lista es campo de fila.
276
401
  const leaf = p.split("/").map(unescapeSeg).pop() ?? p;
@@ -280,9 +405,10 @@ function dynToExpr(
280
405
  }
281
406
  return { ref: leaf };
282
407
  }
283
- if (typeof o.call === "string") {
408
+ const rawCall = o[callKey];
409
+ if (typeof rawCall === "string") {
284
410
  const args = (o.args ?? {}) as Record<string, unknown>;
285
- switch (o.call) {
411
+ switch (rawCall) {
286
412
  case "and":
287
413
  return {
288
414
  and: (args.values as unknown[] ?? []).map(
@@ -413,10 +539,13 @@ function dynToExpr(
413
539
  default:
414
540
  ctx.diags.push(diagnostic("sdui.a2ui.func", "schema",
415
541
  "warn", `función A2UI no soportada en valor: ` +
416
- `${o.call} (${where}) — se sirve args.value crudo`));
542
+ `${rawCall} (${where}) — se sirve args.value crudo`));
417
543
  return dynToExpr(args.value, ctx, where);
418
544
  }
419
545
  }
546
+ // 1.0 — todo lo demás (incluido `{path}`/`{call}` planos) es
547
+ // literal; las claves `@@x` se desescapan a `@x`.
548
+ if (v1) return { lit: unescapeAt(o) };
420
549
  return null;
421
550
  }
422
551
 
@@ -432,14 +561,15 @@ function actionArgs(
432
561
  surface: { lit: surfaceId },
433
562
  };
434
563
  if (context !== null && typeof context === "object") {
564
+ const pk = ctx.surface.spec === "1.0" ? "@path" : "path";
435
565
  for (const [k, v] of Object.entries(context as object)) {
436
566
  if (v !== null && typeof v === "object" &&
437
- typeof (v as { path?: unknown }).path === "string") {
567
+ typeof (v as Record<string, unknown>)[pk] === "string") {
438
568
  const e = dynToExpr(v, ctx, `action.${name}.${k}`);
439
569
  if (e !== null && typeof e === "object") args[k] = e;
440
570
  else args[k] = { lit: e };
441
571
  } else {
442
- args[k] = { lit: v };
572
+ args[k] = { lit: unescapeAt(v) };
443
573
  }
444
574
  }
445
575
  }
@@ -452,18 +582,26 @@ function actionToDo(
452
582
  if (action === null || typeof action !== "object") return undefined;
453
583
  const a = action as Record<string, unknown>;
454
584
  if (a.event !== null && typeof a.event === "object") {
455
- const ev = a.event as { name?: unknown; context?: unknown };
585
+ const ev = a.event as {
586
+ name?: unknown; context?: unknown; userMessage?: unknown;
587
+ };
456
588
  if (typeof ev.name !== "string") {
457
589
  ctx.diags.push(diagnostic("sdui.a2ui.action", "schema",
458
590
  "warn", "action.event sin name — ignorado"));
459
591
  return undefined;
460
592
  }
461
- return [{
462
- emit: "a2ui.action",
463
- args: actionArgs(ev.name, ev.context, surfaceId, ctx),
464
- }];
593
+ const args = actionArgs(ev.name, ev.context, surfaceId, ctx);
594
+ // v1.0 — `userMessage` (DynamicString) acompaña al evento.
595
+ const um = dynToExpr(ev.userMessage, ctx, `action.${ev.name}.userMessage`);
596
+ if (um !== null) {
597
+ args.userMessage = typeof um === "object" ? um : { lit: um };
598
+ }
599
+ return [{ emit: "a2ui.action", args }];
465
600
  }
466
601
  if (a.functionCall !== null && typeof a.functionCall === "object") {
602
+ // `call`/`args`/`catalogId` de FunctionCall son campos de
603
+ // mensaje — sin prefijo en 1.0. Los args se resuelven por nivel
604
+ // (directivas dinámicas dentro de objetos viajan literales).
467
605
  const fc = a.functionCall as { call?: unknown; args?: unknown };
468
606
  if (typeof fc.call !== "string") {
469
607
  ctx.diags.push(diagnostic("sdui.a2ui.action", "schema",
@@ -472,7 +610,10 @@ function actionToDo(
472
610
  }
473
611
  return [{
474
612
  emit: "a2ui.function",
475
- args: { call: { lit: fc.call }, args: { lit: fc.args ?? null } },
613
+ args: {
614
+ call: { lit: fc.call },
615
+ args: { lit: unescapeAt(fc.args ?? null) },
616
+ },
476
617
  }];
477
618
  }
478
619
  return undefined;
@@ -491,6 +632,15 @@ function dynProp(
491
632
  * input (TextField/Slider) lleva `text`/`progress`; change (CheckBox)
492
633
  * lleva `checked` — vocabulario src/events.ts. `{ref:"event"}` resuelve
493
634
  * al EventEnvelope completo: el payload va bajo `data`. */
635
+ /** Path de un binding two-way (`value:{path}`/`{"@path"}` — write-back,
636
+ * campo de binding, no directiva de lectura: se aceptan ambas formas). */
637
+ function bindingPath(v: unknown): string | undefined {
638
+ if (v === null || typeof v !== "object") return undefined;
639
+ const o = v as Record<string, unknown>;
640
+ const p = o.path ?? o["@path"];
641
+ return typeof p === "string" ? p : undefined;
642
+ }
643
+
494
644
  function bindValue(
495
645
  node: RichNode, valuePath: string | undefined,
496
646
  evName: "input" | "change", evField: "text" | "checked" | "progress",
@@ -537,9 +687,22 @@ function withChecks(
537
687
  }
538
688
  const c = raw as {
539
689
  call?: unknown; args?: unknown; message?: unknown;
690
+ valid?: unknown; severity?: unknown;
540
691
  };
541
692
  let expr: Expr | null = null;
542
- if (typeof c.call === "string") {
693
+ if (ctx.surface.spec === "1.0") {
694
+ // v1.0 — el check es un DynamicBoolean (`@call`/`@path`) o
695
+ // un ValidationResult literal (`{valid,code,message}`).
696
+ if (typeof c.valid === "boolean") {
697
+ expr = { lit: c.valid };
698
+ } else {
699
+ const e = dynToExpr(c, ctx, where);
700
+ if (e !== null && typeof e === "object" &&
701
+ !("lit" in e)) {
702
+ expr = e as Expr;
703
+ }
704
+ }
705
+ } else if (typeof c.call === "string") {
543
706
  const e = dynToExpr(
544
707
  { call: c.call, args: c.args }, ctx,
545
708
  `${where}.${c.call}`,
@@ -549,14 +712,15 @@ function withChecks(
549
712
  if (expr === null) {
550
713
  ctx.diags.push(diagnostic("sdui.a2ui.check", "schema",
551
714
  "warn", `check no soportado en ${where}: ` +
552
- `${String(c.call)} — ignorado`));
715
+ `${String(c.call ?? (raw as object)["@call" as keyof object] ?? c.valid)} — ignorado`));
553
716
  exprs.push(null);
554
717
  messages.push("");
555
718
  continue;
556
719
  }
557
720
  exprs.push(expr);
558
- messages.push(typeof c.message === "string"
559
- ? c.message : "Valor inválido");
721
+ const msgVal = dynToExpr(c.message, ctx, `${where}.message`);
722
+ messages.push(typeof msgVal === "string" ? msgVal
723
+ : "Valor inválido");
560
724
  }
561
725
  const valid = exprs.filter((e): e is Expr => e !== null);
562
726
  if (valid.length === 0) return root;
@@ -664,6 +828,7 @@ function collectRowFields(
664
828
  ): void {
665
829
  const c = ctx.surface.components[rootId];
666
830
  if (!c) return;
831
+ const pk = ctx.surface.spec === "1.0" ? "@path" : "path";
667
832
  const stack: unknown[] = [c];
668
833
  while (stack.length > 0) {
669
834
  const n = stack.pop();
@@ -673,8 +838,9 @@ function collectRowFields(
673
838
  continue;
674
839
  }
675
840
  const o = n as Record<string, unknown>;
676
- if (typeof o.path === "string" && !o.path.startsWith("/")) {
677
- const leaf = o.path.split("/").map(unescapeSeg).pop();
841
+ const rp = o[pk];
842
+ if (typeof rp === "string" && !rp.startsWith("/")) {
843
+ const leaf = rp.split("/").map(unescapeSeg).pop();
678
844
  if (leaf) out.add(leaf);
679
845
  }
680
846
  for (const v of Object.values(o)) stack.push(v);
@@ -732,8 +898,34 @@ function childrenOf(
732
898
  return {};
733
899
  }
734
900
 
901
+ /** `@accessibility`/`accessibility` del envelope → props semánticas
902
+ * (`label` ya viaja por update-semantics en los cuatro hosts). */
903
+ function applyA11y(
904
+ node: RichNode, c: A2uiComponent | undefined,
905
+ ctx: TranslateCtx, where: string,
906
+ ): void {
907
+ if (!c) return;
908
+ const a = mx(c, ctx.surface.spec, "accessibility");
909
+ if (a === null || typeof a !== "object") return;
910
+ const ax = a as { label?: unknown; description?: unknown; role?: unknown };
911
+ const label = dynToExpr(ax.label, ctx, `${where}.@accessibility.label`);
912
+ const props: Record<string, unknown> = { ...(node.props ?? {}) };
913
+ if (label !== null) props.label = dynProp(label);
914
+ if (typeof ax.description === "string") props.description = ax.description;
915
+ if (typeof ax.role === "string") props.role = ax.role;
916
+ node.props = props;
917
+ }
918
+
735
919
  function nodeFor(
736
920
  id: string, ctx: TranslateCtx, depth: number,
921
+ ): RichNode | null {
922
+ const n = nodeForRaw(id, ctx, depth);
923
+ if (n) applyA11y(n, ctx.surface.components[id], ctx, id);
924
+ return n;
925
+ }
926
+
927
+ function nodeForRaw(
928
+ id: string, ctx: TranslateCtx, depth: number,
737
929
  ): RichNode | null {
738
930
  if (depth > 32) {
739
931
  ctx.diags.push(diagnostic("sdui.a2ui.depth", "schema", "warn",
@@ -747,6 +939,26 @@ function nodeFor(
747
939
  return null;
748
940
  }
749
941
  const kind = c.component;
942
+ const spec = ctx.surface.spec;
943
+ // Resolución estricta de catálogo: override del componente → default
944
+ // de superficie → error. Un catálogo ajeno no renderiza en falso.
945
+ const catOverride = mx(c, spec, "catalogId");
946
+ if (typeof catOverride === "string" && catOverride.length > 0) {
947
+ if (!KNOWN_CATALOGS.has(catOverride) &&
948
+ catOverride !== ctx.surface.catalogId) {
949
+ ctx.diags.push(diagnostic("sdui.a2ui.catalog", "capability",
950
+ "warn", `catálogo desconocido en ${id}: ${catOverride} ` +
951
+ "— fallback declarativo"));
952
+ return unsupported(ctx, `${String(kind)}@${catOverride}`, id);
953
+ }
954
+ const catSpec = /v1(_0|\b)|v1\.0/.test(catOverride) ? "1.0" : "0.9";
955
+ if (catSpec !== spec) {
956
+ ctx.diags.push(diagnostic("sdui.a2ui.catalog", "schema",
957
+ "warn", `${id}: @catalogId ${catOverride} de otra ` +
958
+ `versión que la superficie (${spec}) — error de mezcla`));
959
+ return unsupported(ctx, `${String(kind)}@${catOverride}`, id);
960
+ }
961
+ }
750
962
  const node: RichNode = { id, type: "column" };
751
963
 
752
964
  // Propiedades comunes de layout de fila/columna.
@@ -849,8 +1061,7 @@ function nodeFor(
849
1061
  type: "switch", style: weight,
850
1062
  props: { variant: "checkbox" },
851
1063
  };
852
- const vp = typeof c.value === "object" && c.value !== null
853
- ? (c.value as { path?: unknown }).path : undefined;
1064
+ const vp = bindingPath(c.value);
854
1065
  if (typeof vp === "string") {
855
1066
  const sig = a2uiSignalName(vp);
856
1067
  ctx.boundPaths.set(sig, vp);
@@ -876,14 +1087,25 @@ function nodeFor(
876
1087
  };
877
1088
  node.children = [sw, lbl];
878
1089
  node.style = { alignItems: "center", gap: 8, ...weight };
879
- return withChecks(node, sw, c.checks, ctx, id);
1090
+ return withChecks(node, sw, mx(c, spec, "checks"), ctx, id);
880
1091
  }
881
1092
  case "TextField": {
882
1093
  node.type = "text-input";
883
- node.props = {
884
- placeholder: dynProp(
885
- dynToExpr(c.label, ctx, `${id}.label`)) as never,
886
- };
1094
+ node.props = {};
1095
+ // v1.0 — `placeholder` prop dedicado; `label` queda como
1096
+ // accesible. En 0.9 el label hacía las dos cosas.
1097
+ const ph = dynToExpr(
1098
+ spec === "1.0" ? (c.placeholder ?? c.label) : c.label,
1099
+ ctx, `${id}.placeholder`);
1100
+ node.props.placeholder = dynProp(ph) as never;
1101
+ if (spec === "1.0" && c.label !== undefined) {
1102
+ node.props.label = dynProp(
1103
+ dynToExpr(c.label, ctx, `${id}.label`));
1104
+ }
1105
+ if (spec === "1.0" && c.value === undefined) {
1106
+ ctx.diags.push(diagnostic("sdui.a2ui.field", "schema",
1107
+ "warn", `TextField ${id}: value requerido en v1.0`));
1108
+ }
887
1109
  const v = String(c.variant ?? "shortText");
888
1110
  if (v === "number") node.props.keyboard = "number";
889
1111
  if (v === "obscured") node.props.keyboard = "password";
@@ -893,29 +1115,33 @@ function nodeFor(
893
1115
  node.props.rows = c.rows;
894
1116
  }
895
1117
  }
896
- const vp = typeof c.value === "object" && c.value !== null
897
- ? (c.value as { path?: unknown }).path : undefined;
1118
+ const vp = bindingPath(c.value);
898
1119
  bindValue(node,
899
1120
  typeof vp === "string" ? vp : undefined,
900
1121
  "input", "text", ctx);
901
1122
  node.style = weight;
902
- return withChecks(node, node, c.checks, ctx, id);
1123
+ return withChecks(node, node, mx(c, spec, "checks"), ctx, id);
903
1124
  }
904
1125
  case "Slider": {
905
1126
  node.type = "slider";
906
1127
  const mn = dynToExpr(c.minValue, ctx, `${id}.min`);
907
- const mx = dynToExpr(c.maxValue, ctx, `${id}.max`);
1128
+ const mxv = dynToExpr(c.maxValue, ctx, `${id}.max`);
908
1129
  node.props = {
909
1130
  min: (mn === null ? 0 : dynProp(mn)) as never,
910
- max: (mx === null ? 100 : dynProp(mx)) as never,
1131
+ max: (mxv === null ? 100 : dynProp(mxv)) as never,
911
1132
  };
912
- const vp = typeof c.value === "object" && c.value !== null
913
- ? (c.value as { path?: unknown }).path : undefined;
1133
+ if (spec === "1.0" && c.steps !== undefined) {
1134
+ ctx.diags.push(diagnostic("sdui.a2ui.component",
1135
+ "capability", "warn",
1136
+ `Slider ${id}: steps v1.0 sin prop step en el ` +
1137
+ "dialecto — continuo"));
1138
+ }
1139
+ const vp = bindingPath(c.value);
914
1140
  bindValue(node,
915
1141
  typeof vp === "string" ? vp : undefined,
916
1142
  "input", "progress", ctx);
917
1143
  node.style = weight;
918
- return withChecks(node, node, c.checks, ctx, id);
1144
+ return withChecks(node, node, mx(c, spec, "checks"), ctx, id);
919
1145
  }
920
1146
  case "DateTimeInput": {
921
1147
  // `keyboard: date|time|datetime` es el contrato portable del
@@ -933,13 +1159,12 @@ function nodeFor(
933
1159
  dynToExpr(c.label, ctx, `${id}.label`)) as never,
934
1160
  keyboard,
935
1161
  };
936
- const vp = typeof c.value === "object" && c.value !== null
937
- ? (c.value as { path?: unknown }).path : undefined;
1162
+ const vp = bindingPath(c.value);
938
1163
  bindValue(node,
939
1164
  typeof vp === "string" ? vp : undefined,
940
1165
  "input", "text", ctx);
941
1166
  node.style = weight;
942
- return withChecks(node, node, c.checks, ctx, id);
1167
+ return withChecks(node, node, mx(c, spec, "checks"), ctx, id);
943
1168
  }
944
1169
  case "Tabs": {
945
1170
  const tabs = Array.isArray(c.tabs)
@@ -1073,11 +1298,7 @@ function nodeFor(
1073
1298
  ? c.options as Array<Record<string, unknown>> : [];
1074
1299
  const multiple = String(c.variant ?? "mutuallyExclusive") ===
1075
1300
  "multipleSelection";
1076
- const valueObj = c.value !== null &&
1077
- typeof c.value === "object"
1078
- ? c.value as { path?: unknown } : null;
1079
- const vp = typeof valueObj?.path === "string"
1080
- ? valueObj.path : undefined;
1301
+ const vp = bindingPath(c.value);
1081
1302
  let state: string;
1082
1303
  if (vp !== undefined && vp.startsWith("/")) {
1083
1304
  state = a2uiSignalName(vp);
@@ -1282,9 +1503,34 @@ function nodeFor(
1282
1503
  }
1283
1504
 
1284
1505
  /** Crea el renderer — un estado por surfaceId, mensajes aplicados en
1285
- * orden de stream (el transporte garantiza el orden). */
1286
- export function createA2uiRenderer(): A2uiRenderer {
1506
+ * orden de stream (el transporte garantiza el orden). v1.0: la cola
1507
+ * `outbound` lleva las respuestas RPC y los `callAgentFunction`. */
1508
+ export function createA2uiRenderer(opts?: A2uiRendererOpts): A2uiRenderer {
1287
1509
  const surfaces: Record<string, A2uiSurface> = {};
1510
+ const outbound: Record<string, unknown>[] = [];
1511
+ let callSeq = 0;
1512
+ const nextCallId = opts?.nextCallId ??
1513
+ (() => `call-${++callSeq}-${Date.now().toString(36)}`);
1514
+ let agentResultCb:
1515
+ ((callId: string, ok: boolean, payload: unknown) => void) | null =
1516
+ null;
1517
+
1518
+ const pushOutbound = (m: Record<string, unknown>): void => {
1519
+ outbound.push(m);
1520
+ try {
1521
+ opts?.onOutbound?.(m);
1522
+ } catch {
1523
+ // El callback del host no puede romper el renderer.
1524
+ }
1525
+ };
1526
+
1527
+ const replyError = (
1528
+ callId: string, code: string, message: string,
1529
+ ): void => {
1530
+ pushOutbound({
1531
+ error: { code, message, functionCallId: callId },
1532
+ });
1533
+ };
1288
1534
 
1289
1535
  const apply = (msg: unknown): Diagnostic[] => {
1290
1536
  const diags: Diagnostic[] = [];
@@ -1307,21 +1553,43 @@ export function createA2uiRenderer(): A2uiRenderer {
1307
1553
  cs.surfaceId));
1308
1554
  return diags;
1309
1555
  }
1310
- if (cs.catalogId !== BASIC_CATALOG) {
1556
+ const spec = detectSpec(m);
1557
+ if (!KNOWN_CATALOGS.has(cs.catalogId)) {
1311
1558
  diags.push(diagnostic("sdui.a2ui.catalog", "capability",
1312
1559
  "warn", `catalogId no declarado como básico: ` +
1313
1560
  `${cs.catalogId} — componentes desconocidos caen a ` +
1314
1561
  "fallback"));
1315
1562
  }
1563
+ if (spec === "1.0" && cs.theme !== undefined) {
1564
+ diags.push(diagnostic("sdui.a2ui.theme", "schema",
1565
+ "warn", "createSurface.theme eliminado en v1.0 — " +
1566
+ "ignorado"));
1567
+ }
1316
1568
  surfaces[cs.surfaceId] = {
1317
1569
  surfaceId: cs.surfaceId,
1318
1570
  catalogId: cs.catalogId ?? "",
1571
+ spec,
1319
1572
  sendDataModel: cs.sendDataModel === true,
1320
1573
  components: {},
1321
1574
  model: {},
1322
1575
  boundPaths: {},
1323
1576
  diags: [],
1324
1577
  };
1578
+ // v1.0 — el create puede traer la superficie completa.
1579
+ const s = surfaces[cs.surfaceId];
1580
+ for (const c of cs.components ?? []) {
1581
+ if (typeof c?.id === "string" &&
1582
+ typeof c?.component === "string") {
1583
+ s.components[c.id] = c;
1584
+ } else {
1585
+ diags.push(diagnostic("sdui.a2ui.component", "schema",
1586
+ "warn", "componente inline sin id/component " +
1587
+ "— omitido"));
1588
+ }
1589
+ }
1590
+ if (cs.dataModel !== null && typeof cs.dataModel === "object") {
1591
+ modelPatch(s.model, "/", cs.dataModel);
1592
+ }
1325
1593
  return diags;
1326
1594
  }
1327
1595
  if (m.updateComponents) {
@@ -1353,13 +1621,84 @@ export function createA2uiRenderer(): A2uiRenderer {
1353
1621
  ud.surfaceId));
1354
1622
  return diags;
1355
1623
  }
1356
- modelPatch(s.model, ud.path, ud.value);
1624
+ if (s.spec === "1.0" && !("value" in ud)) {
1625
+ diags.push(diagnostic("sdui.a2ui.data", "schema",
1626
+ "warn", "updateDataModel sin value en v1.0 — " +
1627
+ "mensaje rechazado"));
1628
+ return diags;
1629
+ }
1630
+ // v1.0: `value:null` borra la entrada (spec); 0.9 conserva
1631
+ // el set de null. `undefined` borra en ambos.
1632
+ if (s.spec === "1.0" && ud.value === null) {
1633
+ modelPatch(s.model, ud.path, undefined);
1634
+ } else {
1635
+ modelPatch(s.model, ud.path, ud.value);
1636
+ }
1357
1637
  return diags;
1358
1638
  }
1359
1639
  if (m.deleteSurface) {
1360
1640
  delete surfaces[m.deleteSurface.surfaceId];
1361
1641
  return diags;
1362
1642
  }
1643
+ if (m.callRendererFunction) {
1644
+ const rf = m.callRendererFunction;
1645
+ const callId = String(rf.callId ?? "");
1646
+ const name = rf.functionCall?.call;
1647
+ const fn = typeof name === "string"
1648
+ ? opts?.rendererFunctions?.[name] : undefined;
1649
+ if (!callId || typeof name !== "string" || !fn) {
1650
+ if (callId) {
1651
+ replyError(callId, "INVALID_FUNCTION_CALL",
1652
+ `función del renderer no registrada: ` +
1653
+ `${String(name ?? "?")}`);
1654
+ }
1655
+ diags.push(diagnostic("sdui.a2ui.rpc", "schema", "warn",
1656
+ `callRendererFunction inválido: ${String(name)} ` +
1657
+ `(${callId})`));
1658
+ return diags;
1659
+ }
1660
+ const args = (rf.functionCall.args ?? {}) as
1661
+ Record<string, unknown>;
1662
+ try {
1663
+ const r = fn(args);
1664
+ if (r !== null && typeof r === "object" &&
1665
+ typeof (r as Promise<unknown>).then === "function") {
1666
+ (r as Promise<unknown>).then(
1667
+ (value) => pushOutbound({
1668
+ rendererFunctionResponse: {
1669
+ callId, value: value ?? null,
1670
+ },
1671
+ }),
1672
+ (e) => replyError(callId, "FUNCTION_ERROR",
1673
+ String(e)),
1674
+ );
1675
+ } else {
1676
+ pushOutbound({
1677
+ rendererFunctionResponse: {
1678
+ callId, value: r ?? null,
1679
+ },
1680
+ });
1681
+ }
1682
+ } catch (e) {
1683
+ replyError(callId, "FUNCTION_ERROR", String(e));
1684
+ }
1685
+ return diags;
1686
+ }
1687
+ if (m.agentFunctionResponse) {
1688
+ const r = m.agentFunctionResponse;
1689
+ const callId = String(r.callId ?? "");
1690
+ try {
1691
+ agentResultCb?.(callId, r.error === undefined,
1692
+ r.error === undefined ? r.value : r.error);
1693
+ } catch {
1694
+ // callback del host — no puede romper el stream.
1695
+ }
1696
+ if (!agentResultCb) {
1697
+ diags.push(diagnostic("sdui.a2ui.rpc", "schema", "warn",
1698
+ `agentFunctionResponse sin receptor (${callId})`));
1699
+ }
1700
+ return diags;
1701
+ }
1363
1702
  diags.push(diagnostic("sdui.a2ui.shape", "schema", "warn",
1364
1703
  "mensaje A2UI sin tipo conocido — ignorado"));
1365
1704
  return diags;
@@ -1438,6 +1777,22 @@ export function createA2uiRenderer(): A2uiRenderer {
1438
1777
  return {
1439
1778
  apply,
1440
1779
  envelope,
1780
+ specVersion: (id) => surfaces[id]?.spec ?? null,
1781
+ callAgentFunction: (surfaceId, call, args) => {
1782
+ if (!surfaces[surfaceId]) return null;
1783
+ const callId = nextCallId();
1784
+ pushOutbound({
1785
+ callAgentFunction: {
1786
+ surfaceId, callId,
1787
+ functionCall: { call, args },
1788
+ },
1789
+ });
1790
+ return callId;
1791
+ },
1792
+ onAgentResult: (cb) => {
1793
+ agentResultCb = cb;
1794
+ },
1795
+ takeOutbound: () => outbound.splice(0, outbound.length),
1441
1796
  model: (id) => surfaces[id]?.model ?? null,
1442
1797
  dataSignals: (id) => {
1443
1798
  const s = surfaces[id];