@alquimia-ai/tools 2.2.0 → 2.4.0

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.
Files changed (76) hide show
  1. package/dist/actions/index.d.mts +1 -0
  2. package/dist/actions/index.d.ts +1 -0
  3. package/dist/actions/index.js.map +1 -1
  4. package/dist/actions/index.mjs.map +1 -1
  5. package/dist/actions-B0hfoYRd.d.ts +57 -0
  6. package/dist/actions-CZU_GRy5.d.mts +57 -0
  7. package/dist/adapters/fetch.d.mts +1 -0
  8. package/dist/adapters/fetch.d.ts +1 -0
  9. package/dist/adapters/fetch.js +4 -0
  10. package/dist/adapters/fetch.js.map +1 -1
  11. package/dist/adapters/fetch.mjs +4 -0
  12. package/dist/adapters/fetch.mjs.map +1 -1
  13. package/dist/adapters/index.d.mts +1 -0
  14. package/dist/adapters/index.d.ts +1 -0
  15. package/dist/adapters/index.js.map +1 -1
  16. package/dist/adapters/next.d.mts +1 -0
  17. package/dist/adapters/next.d.ts +1 -0
  18. package/dist/adapters/next.js +4 -0
  19. package/dist/adapters/next.js.map +1 -1
  20. package/dist/adapters/next.mjs +4 -0
  21. package/dist/adapters/next.mjs.map +1 -1
  22. package/dist/genui/index.d.mts +3027 -0
  23. package/dist/genui/index.d.ts +3027 -0
  24. package/dist/genui/index.js +3368 -0
  25. package/dist/genui/index.js.map +1 -0
  26. package/dist/genui/index.mjs +3345 -0
  27. package/dist/genui/index.mjs.map +1 -0
  28. package/dist/hooks/index.d.mts +25 -2
  29. package/dist/hooks/index.d.ts +25 -2
  30. package/dist/hooks/index.js +510 -0
  31. package/dist/hooks/index.js.map +1 -1
  32. package/dist/hooks/index.mjs +511 -1
  33. package/dist/hooks/index.mjs.map +1 -1
  34. package/dist/next/index.d.mts +7 -0
  35. package/dist/next/index.d.ts +7 -0
  36. package/dist/next/index.js +50 -0
  37. package/dist/next/index.js.map +1 -1
  38. package/dist/next/index.mjs +50 -0
  39. package/dist/next/index.mjs.map +1 -1
  40. package/dist/providers/index.d.mts +3 -2
  41. package/dist/providers/index.d.ts +3 -2
  42. package/dist/providers/index.js.map +1 -1
  43. package/dist/providers/index.mjs.map +1 -1
  44. package/dist/proxy.d.mts +2 -0
  45. package/dist/proxy.d.ts +2 -0
  46. package/dist/proxy.js +41 -0
  47. package/dist/proxy.js.map +1 -1
  48. package/dist/proxy.mjs +41 -0
  49. package/dist/proxy.mjs.map +1 -1
  50. package/dist/registry-Bcu_ZYL1.d.mts +19 -0
  51. package/dist/registry-Bcu_ZYL1.d.ts +19 -0
  52. package/dist/sdk/index.d.mts +10 -0
  53. package/dist/sdk/index.d.ts +10 -0
  54. package/dist/sdk/index.js +26 -0
  55. package/dist/sdk/index.js.map +1 -1
  56. package/dist/sdk/index.mjs +26 -0
  57. package/dist/sdk/index.mjs.map +1 -1
  58. package/dist/services/index.d.mts +1 -0
  59. package/dist/services/index.d.ts +1 -0
  60. package/dist/types/index.d.mts +12 -1
  61. package/dist/types/index.d.ts +12 -1
  62. package/dist/types/index.js.map +1 -1
  63. package/dist/types/index.mjs.map +1 -1
  64. package/dist/types-DnfWUE9V.d.mts +56 -0
  65. package/dist/types-DnfWUE9V.d.ts +56 -0
  66. package/dist/{types-CIqszY3g.d.mts → types-Dvu9y4WM.d.mts} +1 -1
  67. package/dist/{types-CIqszY3g.d.ts → types-Dvu9y4WM.d.ts} +1 -1
  68. package/dist/utils/index.d.mts +6 -2
  69. package/dist/utils/index.d.ts +6 -2
  70. package/dist/utils/index.js +4 -0
  71. package/dist/utils/index.js.map +1 -1
  72. package/dist/utils/index.mjs +4 -0
  73. package/dist/utils/index.mjs.map +1 -1
  74. package/dist/worklog/index.d.mts +2 -2
  75. package/dist/worklog/index.d.ts +2 -2
  76. package/package.json +19 -7
@@ -1,5 +1,5 @@
1
1
  // src/hooks/alquimia.hook.tsx
2
- import { useMemo, useRef, useState } from "react";
2
+ import { useCallback as useCallback2, useEffect, useMemo, useRef, useState } from "react";
3
3
 
4
4
  // src/sdk/alquimia-sdk.ts
5
5
  import axios from "axios";
@@ -139,6 +139,32 @@ var AlquimiaSDK = class {
139
139
  this.attachments = [];
140
140
  return this;
141
141
  }
142
+ /**
143
+ * Complete a pending client-tool execution (the missing "submit half" of the
144
+ * client-tool loop). POSTs a {@link ToolExecutionResponse} to the runtime's
145
+ * `/event/tool-completion`. For interactive `render_ui` surfaces `result` is
146
+ * the user's data; for display-only surfaces the SDK sends `{ shown: true }`.
147
+ * The pending call is correlated by `control_id` in the body + the
148
+ * `context-metadata` header (taskid + sessionid).
149
+ */
150
+ async submitToolResult(response) {
151
+ const url = this.adapter.resolveToolCompletionUrl?.();
152
+ if (!url) {
153
+ throw new Error(
154
+ "AlquimiaSDK: adapter does not support tool completion (resolveToolCompletionUrl missing)"
155
+ );
156
+ }
157
+ const adapterHeaders = this.adapter.getHeaders?.() ?? {};
158
+ const headers = {
159
+ "Content-Type": "application/json",
160
+ assistantid: this.assistantId,
161
+ ...this.streamId && { taskid: this.streamId },
162
+ ...this.conversationId && { sessionid: this.conversationId },
163
+ ...this.userId && { userid: this.userId },
164
+ ...adapterHeaders
165
+ };
166
+ await this.axiosInstance.post(url, response, { headers });
167
+ }
142
168
  async generateImage(query) {
143
169
  if (!this.stableDiffusionProvider) {
144
170
  throw new Error("Stable Diffusion provider not initialized");
@@ -300,6 +326,9 @@ function mergeToolEvents(initial, toolEvents) {
300
326
  initial
301
327
  );
302
328
  }
329
+ function resolveGenuiAllow(catalog, allow) {
330
+ return !allow || allow === "all" ? Object.keys(catalog.components) : allow;
331
+ }
303
332
 
304
333
  // src/worklog/types.ts
305
334
  function initialWorklogState(taskId = null) {
@@ -461,6 +490,359 @@ function frameToRecord(frame) {
461
490
  };
462
491
  }
463
492
 
493
+ // src/hooks/pending-client-tool.ts
494
+ function extractPendingClientTool(frame) {
495
+ if (!frame || typeof frame !== "object") return null;
496
+ const f = frame;
497
+ if (f.event_class !== "ClientToolExecution") return null;
498
+ const name = f.data?.name;
499
+ const parameters = f.data?.parameters;
500
+ const controlId = f.control_id;
501
+ if (typeof name !== "string" || parameters === void 0 || typeof controlId !== "string") return null;
502
+ return { controlId, toolName: name, parameters };
503
+ }
504
+
505
+ // src/genui/style.ts
506
+ import { z } from "zod";
507
+ var TONES = ["default", "muted", "primary", "success", "warning", "danger"];
508
+ var SIZES = ["sm", "md", "lg"];
509
+ var EMPHASES = ["low", "medium", "high"];
510
+ var ALIGNS = ["start", "center", "end"];
511
+ var DENSITIES = ["compact", "comfortable"];
512
+ var styleSchemaShape = {
513
+ tone: z.enum(TONES).optional(),
514
+ size: z.enum(SIZES).optional(),
515
+ emphasis: z.enum(EMPHASES).optional(),
516
+ align: z.enum(ALIGNS).optional(),
517
+ density: z.enum(DENSITIES).optional()
518
+ };
519
+
520
+ // src/genui/registry.ts
521
+ function resolveComponent(manifest, name) {
522
+ if (!name || typeof name !== "string") return null;
523
+ return manifest.components[name] ?? null;
524
+ }
525
+
526
+ // src/genui/catalog.ts
527
+ import { z as z2 } from "zod";
528
+ var CORE_CATALOG_ID = "https://alquimia.ai/catalogs/core/v1/catalog.json";
529
+ var def = (name, own, opts) => ({
530
+ name,
531
+ schema: z2.object({
532
+ ...styleSchemaShape,
533
+ ...opts?.variant ? { variant: z2.enum(opts.variant).optional() } : {},
534
+ ...own
535
+ }).passthrough(),
536
+ allowedActions: opts?.allowedActions
537
+ });
538
+ var option = z2.object({ label: z2.string(), value: z2.union([z2.string(), z2.number()]) });
539
+ var coreCatalog = {
540
+ id: CORE_CATALOG_ID,
541
+ components: {
542
+ // ---- layout ----
543
+ Stack: def("Stack", {
544
+ direction: z2.enum(["vertical", "horizontal"]).optional(),
545
+ gap: z2.enum(["sm", "md", "lg"]).optional()
546
+ }),
547
+ Grid: def("Grid", {
548
+ columns: z2.number().int().min(1).max(6).optional(),
549
+ gap: z2.enum(["sm", "md", "lg"]).optional()
550
+ }),
551
+ Row: def("Row", { gap: z2.enum(["sm", "md", "lg"]).optional(), wrap: z2.boolean().optional() }),
552
+ Column: def("Column", { gap: z2.enum(["sm", "md", "lg"]).optional() }),
553
+ Divider: def("Divider", { label: z2.string().optional() }),
554
+ Spacer: def("Spacer", { size: z2.enum(["sm", "md", "lg"]).optional() }),
555
+ Card: def("Card", { title: z2.string().optional(), description: z2.string().optional() }, {
556
+ variant: ["elevated", "outline", "ghost"]
557
+ }),
558
+ Accordion: def("Accordion", {
559
+ items: z2.array(z2.object({ title: z2.string(), value: z2.string() })).optional()
560
+ }),
561
+ Tabs: def("Tabs", { tabs: z2.array(z2.object({ label: z2.string(), value: z2.string() })).min(1) }),
562
+ // ---- content ----
563
+ Text: def("Text", { text: z2.string() }, { variant: ["body", "muted", "caption", "lead"] }),
564
+ Heading: def("Heading", { text: z2.string(), level: z2.number().int().min(1).max(4).optional() }),
565
+ Markdown: def("Markdown", { text: z2.string() }),
566
+ Image: def("Image", { src: z2.string(), alt: z2.string().optional() }),
567
+ Icon: def("Icon", { name: z2.string() }),
568
+ Badge: def("Badge", { text: z2.string() }, { variant: ["solid", "outline", "subtle"] }),
569
+ Avatar: def("Avatar", { src: z2.string().optional(), fallback: z2.string().optional() }),
570
+ Alert: def("Alert", { text: z2.string(), title: z2.string().optional() }, {
571
+ variant: ["info", "success", "warning", "danger"]
572
+ }),
573
+ Stat: def("Stat", { label: z2.string(), value: z2.union([z2.string(), z2.number()]), delta: z2.string().optional() }),
574
+ KeyValue: def("KeyValue", {}),
575
+ List: def("List", { ordered: z2.boolean().optional() }),
576
+ Quote: def("Quote", { text: z2.string(), cite: z2.string().optional() }),
577
+ // ---- inputs ----
578
+ TextField: def("TextField", { label: z2.string().optional(), placeholder: z2.string().optional() }),
579
+ TextArea: def("TextArea", {
580
+ label: z2.string().optional(),
581
+ placeholder: z2.string().optional(),
582
+ rows: z2.number().int().optional()
583
+ }),
584
+ NumberField: def("NumberField", {
585
+ label: z2.string().optional(),
586
+ min: z2.number().optional(),
587
+ max: z2.number().optional(),
588
+ step: z2.number().optional()
589
+ }),
590
+ Select: def("Select", {
591
+ label: z2.string().optional(),
592
+ placeholder: z2.string().optional(),
593
+ options: z2.array(option).min(1)
594
+ }),
595
+ MultiSelect: def("MultiSelect", { label: z2.string().optional(), options: z2.array(option).min(1) }),
596
+ Combobox: def("Combobox", {
597
+ label: z2.string().optional(),
598
+ placeholder: z2.string().optional(),
599
+ options: z2.array(option).min(1)
600
+ }),
601
+ Checkbox: def("Checkbox", { label: z2.string().optional() }),
602
+ CheckboxGroup: def("CheckboxGroup", { label: z2.string().optional(), options: z2.array(option).min(1) }),
603
+ Radio: def("Radio", { label: z2.string().optional(), options: z2.array(option).min(1) }),
604
+ Switch: def("Switch", { label: z2.string().optional() }),
605
+ Slider: def("Slider", {
606
+ label: z2.string().optional(),
607
+ min: z2.number().optional(),
608
+ max: z2.number().optional(),
609
+ step: z2.number().optional()
610
+ }),
611
+ DatePicker: def("DatePicker", { label: z2.string().optional() }),
612
+ DateRange: def("DateRange", { label: z2.string().optional() }),
613
+ FileUpload: def("FileUpload", {
614
+ label: z2.string().optional(),
615
+ accept: z2.string().optional(),
616
+ multiple: z2.boolean().optional()
617
+ }),
618
+ Rating: def("Rating", { label: z2.string().optional(), max: z2.number().int().optional() }),
619
+ // ---- data ----
620
+ Table: def("Table", {
621
+ columns: z2.array(z2.object({ key: z2.string(), header: z2.string().optional() })).min(1),
622
+ sortable: z2.boolean().optional()
623
+ }, { allowedActions: ["sort", "filter"] }),
624
+ Chart: def("Chart", {
625
+ kind: z2.enum(["bar", "line", "area", "pie"]),
626
+ x: z2.string().optional(),
627
+ series: z2.array(z2.object({ key: z2.string(), label: z2.string().optional() })).min(1),
628
+ title: z2.string().optional()
629
+ }),
630
+ Progress: def("Progress", { value: z2.number(), max: z2.number().optional(), label: z2.string().optional() }),
631
+ Timeline: def("Timeline", {
632
+ items: z2.array(z2.object({ title: z2.string(), description: z2.string().optional(), timestamp: z2.string().optional() })).min(1)
633
+ }),
634
+ // ---- actions ----
635
+ Button: def("Button", { text: z2.string() }, {
636
+ variant: ["solid", "outline", "ghost", "link"],
637
+ allowedActions: ["submit", "cancel", "reset", "select", "confirm"]
638
+ }),
639
+ ButtonGroup: def("ButtonGroup", {}),
640
+ Link: def("Link", { text: z2.string(), href: z2.string().optional() })
641
+ }
642
+ };
643
+
644
+ // src/genui/actions.ts
645
+ var DISMISS_ACTION = "userDismissedSurface";
646
+ function buildDismissResult(surfaceId, userMessage) {
647
+ const said = typeof userMessage === "string" ? userMessage.trim() : "";
648
+ return {
649
+ action: DISMISS_ACTION,
650
+ surfaceId,
651
+ componentId: "",
652
+ data: {},
653
+ ...said ? { userMessage: said } : {}
654
+ };
655
+ }
656
+ function buildSurfaceResult(action) {
657
+ return {
658
+ action: action.action,
659
+ surfaceId: action.surfaceId,
660
+ componentId: action.componentId,
661
+ data: action.payload ?? {}
662
+ };
663
+ }
664
+ var URL_LIKE = /^\s*([a-z][a-z0-9+.-]*:|\/\/)/i;
665
+ function assertSafeActionName(name) {
666
+ if (typeof name !== "string" || name.length === 0) {
667
+ throw new Error("action.name must be a non-empty string");
668
+ }
669
+ if (URL_LIKE.test(name)) {
670
+ throw new Error(`action.name must be a semantic name, not a URL: ${name}`);
671
+ }
672
+ }
673
+
674
+ // src/genui/validate.ts
675
+ import { z as z3 } from "zod";
676
+ var surfaceShape = z3.object({
677
+ surfaceId: z3.string().min(1),
678
+ // Tier 2 canonical id (versioned URI); `catalog` is the legacy alias. Both optional on the
679
+ // wire — the SDK stamps `catalogId` if the agent omits it.
680
+ catalogId: z3.string().min(1).optional(),
681
+ catalog: z3.string().min(1).optional(),
682
+ // Legacy explicit root. A2UI uses the component with id "root"; kept optional for back-compat.
683
+ root: z3.string().min(1).optional(),
684
+ components: z3.array(
685
+ z3.object({
686
+ id: z3.string().min(1),
687
+ component: z3.string().min(1),
688
+ children: z3.array(z3.string()).optional(),
689
+ child: z3.string().optional(),
690
+ binding: z3.string().optional(),
691
+ action: z3.object({ name: z3.string(), wantResponse: z3.boolean().optional() }).optional()
692
+ }).passthrough()
693
+ ),
694
+ dataModel: z3.record(z3.unknown()).optional()
695
+ });
696
+ var UAX31_ID = /^[\p{XID_Start}_][\p{XID_Continue}]*$/u;
697
+ function validateProps(node, def2) {
698
+ const { id, component, children, child, binding, action, ...props } = node;
699
+ const parsed = def2.schema.safeParse(props);
700
+ if (parsed.success) return { ok: true, value: parsed.data, errors: [] };
701
+ return {
702
+ ok: false,
703
+ errors: parsed.error.issues.map((i) => ({ path: `${id}.${i.path.join(".")}`, message: i.message }))
704
+ };
705
+ }
706
+ function validateSurface(input, manifest) {
707
+ const shape = surfaceShape.safeParse(input);
708
+ if (!shape.success) {
709
+ return { ok: false, errors: shape.error.issues.map((i) => ({ path: i.path.join("."), message: i.message })) };
710
+ }
711
+ const surface = shape.data;
712
+ const errors = [];
713
+ const warnings = [];
714
+ const ids = new Set(surface.components.map((c) => c.id));
715
+ const rootId = ids.has("root") ? "root" : surface.root;
716
+ if (!rootId || !ids.has(rootId)) {
717
+ errors.push({ path: "root", message: `no root component (expected a component with id "root")` });
718
+ }
719
+ if (!surface.catalogId && !surface.catalog) {
720
+ warnings.push({ path: "catalogId", message: "surface has no catalogId (SDK will stamp the active catalog)" });
721
+ }
722
+ for (const node of surface.components) {
723
+ if (!UAX31_ID.test(node.id)) {
724
+ warnings.push({ path: node.id, message: `id "${node.id}" is not a valid UAX#31 identifier` });
725
+ }
726
+ const def2 = resolveComponent(manifest, node.component);
727
+ if (!def2) {
728
+ warnings.push({ path: node.id, message: `unknown component "${node.component}" (renders as text)` });
729
+ continue;
730
+ }
731
+ warnings.push(...validateProps(node, def2).errors);
732
+ for (const childId of node.children ?? []) {
733
+ if (!ids.has(childId)) {
734
+ warnings.push({ path: node.id, message: `child "${childId}" does not exist (skipped)` });
735
+ }
736
+ }
737
+ if (node.child && !ids.has(node.child)) {
738
+ warnings.push({ path: node.id, message: `child "${node.child}" does not exist (skipped)` });
739
+ }
740
+ if (node.action) {
741
+ try {
742
+ assertSafeActionName(node.action.name);
743
+ } catch (e) {
744
+ errors.push({ path: `${node.id}.action`, message: e.message });
745
+ }
746
+ }
747
+ }
748
+ return errors.length === 0 ? { ok: true, value: surface, errors: [], warnings } : { ok: false, errors, warnings };
749
+ }
750
+
751
+ // src/genui/tool-schema.ts
752
+ var DESCRIPTION = 'Render a UI using A2UI. The arguments are a UI surface, NOT free-form. Shape: { surfaceId, root, components, dataModel? }. `components` is a FLAT array; every item is { id, component, children?, ...props } where `component` is one of the allowed names (use `component`, never `type`) and `children` is an array of string ids referencing other items (never nested objects). Inputs bind to the data model via `binding` (a JSON Pointer like "/name"). To collect input, include a Button with action { name, wantResponse: true } \u2014 its result (the data model) is returned to you; a surface with no such button is display-only. Example: { "surfaceId": "signup", "root": "root", "components": [ { "id": "root", "component": "Stack", "children": ["name", "desc", "submit"] }, { "id": "name", "component": "TextField", "label": "Username", "binding": "/name" }, { "id": "desc", "component": "TextField", "label": "Description", "binding": "/description" }, { "id": "submit", "component": "Button", "text": "Save", "action": { "name": "save", "wantResponse": true } } ], "dataModel": { "name": "", "description": "" } }. IMPORTANT: when you call render_ui, the rendered surface IS your reply \u2014 do NOT also reproduce its content as text, markdown, or ASCII. Any accompanying message must be a brief one-line intro at most, never a duplicate of the UI.';
753
+ function buildRenderUiSchema(manifest, allowlist) {
754
+ const allowed = allowlist.filter((name) => name in manifest.components);
755
+ return {
756
+ title: "render_ui",
757
+ name: "render_ui",
758
+ description: DESCRIPTION,
759
+ type: "object",
760
+ properties: {
761
+ surfaceId: { type: "string" },
762
+ // A2UI catalog id — a versioned URI. `const` nudges the model to echo it; the SDK
763
+ // also stamps it if omitted, so the client always knows which catalog version to render.
764
+ catalogId: { type: "string", const: manifest.id },
765
+ catalog: { type: "string" },
766
+ // legacy alias (accepted, ignored)
767
+ root: { type: "string" },
768
+ // legacy explicit root (accepted; A2UI uses the id:"root" component)
769
+ components: {
770
+ type: "array",
771
+ items: {
772
+ type: "object",
773
+ properties: {
774
+ id: { type: "string" },
775
+ component: { type: "string", enum: allowed },
776
+ children: { type: "array", items: { type: "string" } },
777
+ child: { type: "string" },
778
+ binding: { type: "string" },
779
+ action: {
780
+ type: "object",
781
+ properties: {
782
+ name: { type: "string" },
783
+ wantResponse: { type: "boolean" }
784
+ },
785
+ required: ["name"]
786
+ },
787
+ tone: { type: "string", enum: [...TONES] },
788
+ size: { type: "string", enum: [...SIZES] },
789
+ emphasis: { type: "string", enum: [...EMPHASES] },
790
+ align: { type: "string", enum: [...ALIGNS] },
791
+ density: { type: "string", enum: [...DENSITIES] },
792
+ variant: { type: "string" },
793
+ text: { type: "string" },
794
+ label: { type: "string" },
795
+ placeholder: { type: "string" },
796
+ title: { type: "string" },
797
+ direction: { type: "string" },
798
+ gap: { type: "string" },
799
+ // Data props for data components. Several are legitimately polymorphic across
800
+ // components — type them as their real unions so the runtime doesn't reject
801
+ // valid output (adapters normalize each shape):
802
+ // data: array (Chart/Table rows) | object (KeyValue)
803
+ // rows: array (Table) | number (TextArea row count)
804
+ // columns: array (Table col defs) | number (Grid column count)
805
+ data: { type: ["array", "object"] },
806
+ rows: { type: ["array", "number"] },
807
+ items: { type: "array" },
808
+ // Accept string OR object items — models routinely emit the terse string
809
+ // form (e.g. series:["revenue"], options:["A","B"]); adapters normalize.
810
+ columns: { type: ["array", "number"], items: { type: ["object", "string"] } },
811
+ series: { type: "array", items: { type: ["object", "string"] } },
812
+ options: { type: "array", items: { type: ["object", "string"] } },
813
+ kind: { type: "string" },
814
+ x: { type: "string" },
815
+ value: {}
816
+ },
817
+ required: ["id", "component"]
818
+ }
819
+ },
820
+ dataModel: { type: "object" }
821
+ },
822
+ required: ["surfaceId", "root", "components"],
823
+ additionalProperties: false
824
+ };
825
+ }
826
+
827
+ // src/genui/clause.ts
828
+ function buildGenuiClause(manifest, allowlist) {
829
+ const names = allowlist.filter((n) => n in manifest.components);
830
+ return [
831
+ "You can render UI by calling render_ui with an A2UI surface (a flat components array; each item is { id, component, children?, ...props }; component is one of the allowed names; children are string ids referencing other items).",
832
+ `Components: ${names.join(", ")}.`,
833
+ `Style each component via the semantic vocabulary (never CSS, colors, or HTML): tone (${TONES.join("/")}), size (${SIZES.join("/")}), emphasis (low/medium/high), align (start/center/end), density (compact/comfortable), plus a component-specific variant where offered.`,
834
+ "Data components MUST carry their data: Chart takes `data` (an array of row objects) + `series` (keys to plot) + `x` (the category key); Table takes `rows` (array of row objects) + `columns` ([{ key, header }] matching the row keys); List takes `items` (array); Stat takes `label`+`value`; KeyValue takes `data` (an object). Put the data inline on the component (or in dataModel referenced via `binding`).",
835
+ "To collect input, add a Button with an action { name, wantResponse: true }. You get back { action, surfaceId, componentId, data } \u2014 `data` is the collected data model and `componentId` is the id of the component that was acted on. A surface with no such button is display-only.",
836
+ "When you render several options to choose from (a grid of cards, each with its own button), give every option component a MEANINGFUL id (e.g. flight-NH107, hotel-memmo-alfama): `componentId` tells you which one the user picked, so never ask them to repeat a choice they already made.",
837
+ 'The user may ignore an interactive surface and just type instead. You then receive action "userDismissedSurface" with their words in `userMessage` \u2014 treat it as their reply, answer it directly, and do not re-render the same surface or scold them for not using it.',
838
+ "IMPORTANT: the rendered surface IS your reply \u2014 do NOT reproduce its content as text, markdown, or ASCII; a one-line intro at most.",
839
+ "Prefer plain text for simple replies."
840
+ ].join(" ");
841
+ }
842
+
843
+ // src/genui/emit.ts
844
+ import { zodToJsonSchema } from "zod-to-json-schema";
845
+
464
846
  // src/hooks/alquimia.hook.tsx
465
847
  function useAlquimia(config) {
466
848
  const sdk = useMemo(() => {
@@ -474,6 +856,15 @@ function useAlquimia(config) {
474
856
  if (config.providers?.logger) instance.withLoggerProvider(config.providers.logger);
475
857
  if (config.options?.userId) instance.withUserId(config.options.userId);
476
858
  if (config.options?.extraInstructions) instance.withExtraInstructions(config.options.extraInstructions);
859
+ if (config.genui && (config.genui.source ?? "client") === "client") {
860
+ const cat = config.genui.catalog ?? coreCatalog;
861
+ const allow = resolveGenuiAllow(cat, config.genui.allow);
862
+ instance.withTools([buildRenderUiSchema(cat, allow)]);
863
+ instance.withExtraInstructions({
864
+ ...config.options?.extraInstructions ?? {},
865
+ genui: buildGenuiClause(cat, allow)
866
+ });
867
+ }
477
868
  return instance;
478
869
  }, [config.assistantId, config.adapter]);
479
870
  const [input, setInput] = useState("");
@@ -495,6 +886,23 @@ function useAlquimia(config) {
495
886
  );
496
887
  const [attachments, setAttachments] = useState([]);
497
888
  const [isUploadingAttachments, setIsUploadingAttachments] = useState(false);
889
+ const [pendingClientTool, setPendingClientTool] = useState(null);
890
+ const completedToolsRef = useRef(/* @__PURE__ */ new Set());
891
+ const genuiCatalog = config.genui?.catalog ?? coreCatalog;
892
+ const [genuiSurfaces, setGenuiSurfaces] = useState([]);
893
+ const messagesLenRef = useRef(0);
894
+ messagesLenRef.current = messages.length;
895
+ const genuiAnchorRef = useRef(0);
896
+ {
897
+ let anchor = messages.length;
898
+ for (let i = messages.length - 1; i >= 0; i--) {
899
+ if (messages[i].role === "user") {
900
+ anchor = i + 1;
901
+ break;
902
+ }
903
+ }
904
+ genuiAnchorRef.current = anchor;
905
+ }
498
906
  const isLoading = isMessageLoading || isStreamingLoading || isUploadingAttachments;
499
907
  function cleanMessages() {
500
908
  setMessages([]);
@@ -762,6 +1170,11 @@ function useAlquimia(config) {
762
1170
  if (worklogEnabled) {
763
1171
  setWorklog((prev) => reduceWorklog(prev ?? initialWorklogState(), frameToRecord(data)));
764
1172
  }
1173
+ const pending = extractPendingClientTool(data);
1174
+ if (pending) {
1175
+ setPendingClientTool(pending);
1176
+ return;
1177
+ }
765
1178
  const eventTaskId = data.taskid || "";
766
1179
  if (data.errors?.length) {
767
1180
  for (const error of data.errors) {
@@ -791,9 +1204,106 @@ function useAlquimia(config) {
791
1204
  cleanup(false, eventSource);
792
1205
  }
793
1206
  }
1207
+ const completeToolExecution = useCallback2(
1208
+ async (controlId, result) => {
1209
+ if (completedToolsRef.current.has(controlId)) return;
1210
+ completedToolsRef.current.add(controlId);
1211
+ try {
1212
+ await sdk.submitToolResult({ ...result, control_id: controlId });
1213
+ setPendingClientTool((cur) => cur?.controlId === controlId ? null : cur);
1214
+ } catch (err) {
1215
+ completedToolsRef.current.delete(controlId);
1216
+ throw err;
1217
+ }
1218
+ },
1219
+ [sdk]
1220
+ );
1221
+ useEffect(() => {
1222
+ if (!config.genui) return;
1223
+ if (!pendingClientTool || pendingClientTool.toolName !== "render_ui") return;
1224
+ const { controlId } = pendingClientTool;
1225
+ const parameters = pendingClientTool.parameters && typeof pendingClientTool.parameters === "object" ? { catalogId: genuiCatalog.id, ...pendingClientTool.parameters } : pendingClientTool.parameters;
1226
+ const res = validateSurface(parameters, genuiCatalog);
1227
+ if (!res.ok || !res.value) {
1228
+ void completeToolExecution(controlId, {
1229
+ control_id: controlId,
1230
+ tool_name: "render_ui",
1231
+ status: "error",
1232
+ message: "Surface failed client validation: " + res.errors.map((e) => `${e.path} ${e.message}`).join("; "),
1233
+ result: { errors: res.errors }
1234
+ });
1235
+ return;
1236
+ }
1237
+ const surface = res.value;
1238
+ setGenuiSurfaces(
1239
+ (prev) => prev.some((s) => s.controlId === controlId) ? prev : [...prev, { controlId, surface, afterCount: genuiAnchorRef.current }]
1240
+ );
1241
+ const interactive = surface.components.some((c) => c.action?.wantResponse === true);
1242
+ if (!interactive) {
1243
+ void completeToolExecution(controlId, {
1244
+ control_id: controlId,
1245
+ tool_name: "render_ui",
1246
+ status: "success",
1247
+ result: {
1248
+ shown: true,
1249
+ instruction: "The UI is rendered and visible to the user. Do NOT restate it as text/markdown/ASCII; reply with at most one short sentence."
1250
+ }
1251
+ });
1252
+ }
1253
+ }, [pendingClientTool, completeToolExecution, config.genui]);
1254
+ const genuiOnAgentAction = useCallback2(
1255
+ (controlId) => (action) => {
1256
+ setGenuiSurfaces(
1257
+ (prev) => prev.map((s) => s.controlId === controlId ? { ...s, submitted: true } : s)
1258
+ );
1259
+ void completeToolExecution(controlId, {
1260
+ control_id: controlId,
1261
+ tool_name: "render_ui",
1262
+ status: "success",
1263
+ // Includes componentId, so the agent can tell which element was acted on when
1264
+ // several share one action name (a grid of option cards, say).
1265
+ result: buildSurfaceResult(action)
1266
+ });
1267
+ },
1268
+ [completeToolExecution]
1269
+ );
1270
+ const genuiDismiss = useCallback2(
1271
+ (userMessage) => {
1272
+ if (!pendingClientTool || pendingClientTool.toolName !== "render_ui") return;
1273
+ const { controlId } = pendingClientTool;
1274
+ const said = typeof userMessage === "string" ? userMessage.trim() : "";
1275
+ const item = genuiSurfaces.find((s) => s.controlId === controlId);
1276
+ setGenuiSurfaces(
1277
+ (prev) => prev.map(
1278
+ (s) => s.controlId === controlId ? { ...s, submitted: true, dismissedWith: said || void 0 } : s
1279
+ )
1280
+ );
1281
+ if (said) setInput("");
1282
+ void completeToolExecution(controlId, {
1283
+ control_id: controlId,
1284
+ tool_name: "render_ui",
1285
+ status: "success",
1286
+ result: buildDismissResult(item?.surface.surfaceId ?? "", said)
1287
+ });
1288
+ },
1289
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1290
+ [pendingClientTool, genuiSurfaces, completeToolExecution]
1291
+ );
1292
+ const genuiAwaitingUser = !!(pendingClientTool && pendingClientTool.toolName === "render_ui" && genuiSurfaces.some(
1293
+ (s) => s.controlId === pendingClientTool.controlId && s.surface.components.some((c) => c.action?.wantResponse === true)
1294
+ ));
1295
+ const genui = config.genui ? {
1296
+ surfaces: genuiSurfaces,
1297
+ onAgentAction: genuiOnAgentAction,
1298
+ awaitingUser: genuiAwaitingUser,
1299
+ dismiss: genuiDismiss
1300
+ } : void 0;
794
1301
  return {
795
1302
  sdk,
796
1303
  activeTool,
1304
+ pendingClientTool,
1305
+ completeToolExecution,
1306
+ genui,
797
1307
  cleanMessages,
798
1308
  createMessageId,
799
1309
  handleInputChange,