@genkit-ai/a2ui 0.5.0-rc.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 (51) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +314 -0
  3. package/lib/catalog.d.mts +70 -0
  4. package/lib/catalog.d.ts +70 -0
  5. package/lib/catalog.js +285 -0
  6. package/lib/catalog.js.map +1 -0
  7. package/lib/catalog.mjs +256 -0
  8. package/lib/catalog.mjs.map +1 -0
  9. package/lib/client.d.mts +59 -0
  10. package/lib/client.d.ts +59 -0
  11. package/lib/client.js +82 -0
  12. package/lib/client.js.map +1 -0
  13. package/lib/client.mjs +55 -0
  14. package/lib/client.mjs.map +1 -0
  15. package/lib/index.d.mts +8 -0
  16. package/lib/index.d.ts +8 -0
  17. package/lib/index.js +62 -0
  18. package/lib/index.js.map +1 -0
  19. package/lib/index.mjs +36 -0
  20. package/lib/index.mjs.map +1 -0
  21. package/lib/loader.d.mts +70 -0
  22. package/lib/loader.d.ts +70 -0
  23. package/lib/loader.js +92 -0
  24. package/lib/loader.js.map +1 -0
  25. package/lib/loader.mjs +61 -0
  26. package/lib/loader.mjs.map +1 -0
  27. package/lib/middleware.d.mts +112 -0
  28. package/lib/middleware.d.ts +112 -0
  29. package/lib/middleware.js +259 -0
  30. package/lib/middleware.js.map +1 -0
  31. package/lib/middleware.mjs +240 -0
  32. package/lib/middleware.mjs.map +1 -0
  33. package/lib/parser.d.mts +132 -0
  34. package/lib/parser.d.ts +132 -0
  35. package/lib/parser.js +282 -0
  36. package/lib/parser.js.map +1 -0
  37. package/lib/parser.mjs +260 -0
  38. package/lib/parser.mjs.map +1 -0
  39. package/lib/part.d.mts +56 -0
  40. package/lib/part.d.ts +56 -0
  41. package/lib/part.js +52 -0
  42. package/lib/part.js.map +1 -0
  43. package/lib/part.mjs +26 -0
  44. package/lib/part.mjs.map +1 -0
  45. package/lib/types.d.mts +153 -0
  46. package/lib/types.d.ts +153 -0
  47. package/lib/types.js +38 -0
  48. package/lib/types.js.map +1 -0
  49. package/lib/types.mjs +11 -0
  50. package/lib/types.mjs.map +1 -0
  51. package/package.json +80 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,314 @@
1
+ # @genkit-ai/a2ui
2
+
3
+ A Genkit plugin that brings [A2UI](https://a2ui.org/) ("Agent to UI"), a
4
+ transport-agnostic, JSON-based streaming UI protocol, to Genkit agents.
5
+
6
+ An A2UI-enabled agent can stream more than prose. It streams rich, interactive UI
7
+ **surfaces** (cards, lists, forms, buttons) that a client renders incrementally
8
+ as the model responds. The whole server-side integration is a single model
9
+ middleware: add `a2ui()` to an agent's `use` array and nothing else changes.
10
+
11
+ > Status: experimental.
12
+
13
+ ## Installation
14
+
15
+ Install the plugin in your project:
16
+
17
+ ```bash
18
+ npm i @genkit-ai/a2ui
19
+ ```
20
+
21
+ To render surfaces in the browser you will also want a renderer and its
22
+ supporting packages. A2UI ships renderers for several frameworks:
23
+ [`@a2ui/lit`](https://www.npmjs.com/package/@a2ui/lit),
24
+ [`@a2ui/react`](https://www.npmjs.com/package/@a2ui/react), and
25
+ [`@a2ui/angular`](https://www.npmjs.com/package/@a2ui/angular). The examples
26
+ below use the Lit renderer:
27
+
28
+ ```bash
29
+ npm i @a2ui/lit @a2ui/web_core @a2ui/markdown-it
30
+ ```
31
+
32
+ You will also load the **Material Symbols Outlined** font on the client (the
33
+ basic catalog's `Icon` component renders names as font ligatures). See the
34
+ [renderer note](#renderer-requirements) below.
35
+
36
+
37
+ ## Quickstart
38
+
39
+ ### 1. Add the middleware on the server
40
+
41
+ Add `a2ui()` to your agent's `use` array. That is the entire server-side setup.
42
+
43
+ ```ts
44
+ import { genkit } from 'genkit/beta';
45
+ import { googleAI } from '@genkit-ai/google-genai';
46
+ import { a2ui } from '@genkit-ai/a2ui';
47
+
48
+ const ai = genkit({ plugins: [googleAI()] });
49
+
50
+ export const uiAgent = ai.defineAgent({
51
+ name: 'uiAgent',
52
+ model: 'googleai/gemini-flash-latest',
53
+ system: 'You help users. Render UI when it is clearer than prose.',
54
+ use: [a2ui()], // <- A2UI support (defaults to the bundled 'basic' catalog)
55
+ });
56
+ ```
57
+
58
+ It works the same on a one-shot `generate`:
59
+
60
+ ```ts
61
+ const res = await ai.generate({
62
+ prompt: 'Show me the weather in Tokyo',
63
+ use: [a2ui()],
64
+ });
65
+ ```
66
+
67
+ ### 2. Render surfaces on the client
68
+
69
+ `@genkit-ai/a2ui/client` is browser-safe (no Node dependencies). Consume the
70
+ agent with `remoteAgent` from `genkit/beta/client`, pull A2UI envelopes off each
71
+ chunk with `a2uiEnvelopesFromParts`, and feed them to a renderer. The example
72
+ below uses [`@a2ui/lit`](https://www.npmjs.com/package/@a2ui/lit), but the same
73
+ approach works with the [`@a2ui/react`](https://www.npmjs.com/package/@a2ui/react)
74
+ and [`@a2ui/angular`](https://www.npmjs.com/package/@a2ui/angular) renderers:
75
+
76
+ ```ts
77
+ import { MessageProcessor } from '@a2ui/web_core/v0_9';
78
+ import { basicCatalog } from '@a2ui/lit/v0_9';
79
+ import '@a2ui/lit/v0_9'; // registers <a2ui-surface> + basic components
80
+ import { a2uiEnvelopesFromParts } from '@genkit-ai/a2ui/client';
81
+ import { remoteAgent } from 'genkit/beta/client';
82
+
83
+ const processor = new MessageProcessor([basicCatalog]);
84
+ processor.onSurfaceCreated((s) => {
85
+ document.querySelector('a2ui-surface').surface = s;
86
+ });
87
+
88
+ const chat = remoteAgent({ url: '/api/uiAgent' }).chat();
89
+ const turn = chat.sendStream('weather in Tokyo');
90
+ for await (const chunk of turn.stream) {
91
+ if (chunk.text) appendProse(chunk.text);
92
+ const envelopes = a2uiEnvelopesFromParts(chunk.raw.modelChunk?.content);
93
+ if (envelopes.length) processor.processMessages(envelopes);
94
+ }
95
+ ```
96
+
97
+ If you are not using the full agent client, `@genkit-ai/a2ui/client` also ships a
98
+ lightweight `streamA2uiAgent({ url, message, sessionId })` async-generator helper
99
+ that yields `{ type: 'text' }` and `{ type: 'envelopes' }` events.
100
+
101
+ > See [`js/testapps/a2ui`](../../testapps/a2ui) for a complete, runnable sample
102
+ > (Express backend plus a Vite + Lit frontend).
103
+
104
+ ## Options
105
+
106
+ Pass options to `a2ui()` to control the catalog, prompt injection, and
107
+ validation:
108
+
109
+ | Option | Default | Description |
110
+ | -------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------- |
111
+ | `catalog` | `'basic'` | The id of the catalog describing what the agent may render. |
112
+ | `instructions` | `'system'` | Where to inject catalog capabilities. `'none'` injects nothing. |
113
+ | `validate` | `'warn'` | Validate emitted envelopes against the catalog. `'warn'` logs and drops bad blocks; `'strict'` throws; `'off'` skips checking. |
114
+ | `surfaceId` | fresh UUID | Surface id policy. Defaults to a new UUID per surface; pass a fixed string to reuse one id for every surface. |
115
+ | `version` | `'v0.9'` | Protocol version stamped on envelopes. |
116
+
117
+ ## Handling user actions
118
+
119
+ When a user interacts with a surface (for example, presses a `Button`), the
120
+ renderer emits an `A2uiClientAction`. Turn it into an agent input with
121
+ `actionToMessage` and send it as the next turn:
122
+
123
+ ```ts
124
+ import { actionToMessage, type A2uiClientAction } from '@genkit-ai/a2ui/client';
125
+
126
+ const processor = new MessageProcessor([basicCatalog], (action) => {
127
+ const turn = chat.sendStream({ message: actionToMessage(action) });
128
+ // …consume turn.stream like above…
129
+ });
130
+ ```
131
+
132
+ The action's `name` is sent as the user message; the full action (including its
133
+ `context`) is attached as an a2ui data part so the agent can react to it.
134
+
135
+ ### Forms
136
+
137
+ Input components (`TextField`, `CheckBox`, `Slider`) do **not** send their values
138
+ automatically. To capture what the user entered, the model must:
139
+
140
+ 1. Bind each input's `value` to a data-model path (`{ "path": "/email" }`).
141
+ 2. Echo those same paths in the submit `Button`'s `action.event.context`.
142
+
143
+ The catalog capabilities injected into the system prompt already instruct the
144
+ model to do this. Without both steps, the action arrives with an empty `context`.
145
+
146
+ ### Renderer requirements
147
+
148
+ The `@a2ui/lit` basic catalog needs two host-side pieces to render fully:
149
+
150
+ - A **MarkdownRenderer** provided via Lit context (for example, backed by
151
+ `@a2ui/markdown-it`). `Text` heading variants are rendered as Markdown.
152
+ - The **Material Symbols Outlined** font. The `Icon` component renders names as
153
+ font ligatures.
154
+
155
+ Without them, headings show as literal `##` and icons show as literal names. See
156
+ [`js/testapps/a2ui`](../../testapps/a2ui) for the wiring.
157
+
158
+ ## Custom catalogs
159
+
160
+ The `catalog` option is a **catalog id** resolved from the Genkit registry. The
161
+ bundled `'basic'` catalog (mirroring `@a2ui/web_core`'s basic catalog) is the
162
+ default and needs no registration.
163
+
164
+ To match your own layout elements and design system, define a custom catalog,
165
+ register it with `loadCatalog`, and reference it by id.
166
+
167
+ ### Catalog format
168
+
169
+ An A2UI catalog describes the components the model is allowed to emit:
170
+
171
+ - `id`: A globally unique URI identifying the catalog (used as `catalogId` on
172
+ `createSurface`).
173
+ - `components`: An array of components, where each has:
174
+ - `name`: The component type name, matching the renderer type (for example
175
+ `CustomCard`, `Text`).
176
+ - `description`: A clear, one-line summary of what the component is and when to
177
+ use it.
178
+ - `props`: A compact, model-facing text description of its properties (kept as
179
+ a simple, human-readable string to minimize system prompt token usage).
180
+
181
+ ### Option A: load from a JSON file
182
+
183
+ Create a JSON file (for example `./my-catalog.json`) following this format:
184
+
185
+ ```json
186
+ {
187
+ "id": "https://my-app.org/catalogs/custom.json",
188
+ "components": [
189
+ {
190
+ "name": "Banner",
191
+ "description": "Displays a prominent alert banner at the top of a section.",
192
+ "props": "title: string (required); severity?: info|warning|error."
193
+ },
194
+ {
195
+ "name": "Text",
196
+ "description": "Displays a plain or inline-markdown text run.",
197
+ "props": "text: string (required); variant?: body|caption."
198
+ }
199
+ ]
200
+ }
201
+ ```
202
+
203
+ Then register it under a lookup identifier (for example `'my-catalog'`) on the
204
+ server:
205
+
206
+ ```ts
207
+ import { loadCatalog } from '@genkit-ai/a2ui';
208
+
209
+ await loadCatalog(ai, { id: 'my-catalog', file: './my-catalog.json' });
210
+ ```
211
+
212
+ ### Option B: in-memory definition
213
+
214
+ You can construct and register an `A2uiCatalog` directly:
215
+
216
+ ```ts
217
+ import { loadCatalog, type A2uiCatalog } from '@genkit-ai/a2ui';
218
+
219
+ const myCatalog: A2uiCatalog = {
220
+ id: 'https://my-app.org/catalogs/custom.json',
221
+ components: [
222
+ {
223
+ name: 'Banner',
224
+ description: 'Displays a prominent alert banner at the top of a section.',
225
+ props: 'title: string (required); severity?: info|warning|error.',
226
+ },
227
+ {
228
+ name: 'Text',
229
+ description: 'Displays a plain or inline-markdown text run.',
230
+ props: 'text: string (required); variant?: body|caption.',
231
+ },
232
+ ],
233
+ };
234
+
235
+ await loadCatalog(ai, { id: 'my-catalog', catalog: myCatalog });
236
+ ```
237
+
238
+ ### Using a registered catalog
239
+
240
+ Once registered, reference the lookup id in your `a2ui()` options:
241
+
242
+ ```ts
243
+ export const uiAgent = ai.defineAgent({
244
+ name: 'uiAgent',
245
+ model: 'googleai/gemini-flash-latest',
246
+ use: [a2ui({ catalog: 'my-catalog' })],
247
+ });
248
+ ```
249
+
250
+ Catalogs live in the registry (value type `a2ui-catalog`) so the middleware can
251
+ resolve them by id and, in the future, tooling can list them.
252
+
253
+ ## Security and the trust boundary
254
+
255
+ Generative UI moves model output into the DOM, so treat every surface an agent
256
+ emits as **untrusted input**. The `a2ui()` middleware's `validate` option
257
+ (including `'strict'`) checks envelope structure and component *type names*
258
+ against the catalog only. It does **not** validate component props or data-model
259
+ values: model-controlled values such as `Image.url` and `Text` (inline Markdown,
260
+ which a renderer may turn into HTML) pass through untouched. `'strict'` is a
261
+ well-formedness check, not a security boundary.
262
+
263
+ A prompt-injected or simply mistaken model can therefore emit an arbitrary remote
264
+ image URL, or Markdown that a renderer turns into HTML. To keep that safe:
265
+
266
+ - **The renderer/catalog owns prop sanitization.** Whatever renders a surface
267
+ (for example `@a2ui/lit` plus your Markdown renderer) is responsible for
268
+ escaping and sanitizing prop values before they reach the DOM. If you ship a
269
+ custom catalog, its renderer must sanitize its own components' props.
270
+ - **Restrict remote sources at the host.** Serve the app with a Content Security
271
+ Policy that limits `img-src` (and other fetch directives) to origins you trust,
272
+ so a model-supplied image or link URL cannot exfiltrate data or load
273
+ unexpected content.
274
+ - **Do not put secrets in the data model.** Anything bound into a surface's data
275
+ model can be echoed back through an action's `context`.
276
+
277
+ If you need server-side control over props (for example, allow-listing image
278
+ hosts), add your own model middleware after `a2ui()` to inspect and rewrite the
279
+ emitted a2ui parts.
280
+
281
+ ## How it works
282
+
283
+ ### One representation
284
+
285
+ A2UI rides on its own part channel: a Genkit `data` part carrying the mime type
286
+ `application/a2ui+json` whose `data` is an object `{ envelopes }` wrapping an
287
+ array of A2UI envelope messages. This maps 1:1 onto the A2A binding of the A2UI
288
+ spec, so an A2A or MCP binding can drop in later for free.
289
+
290
+ - A **mixed** turn is a message whose content is `[textPart, a2uiPart, …]`.
291
+ - A **pure-surface** turn is the special case with no text parts.
292
+ - Downstream consumers (client transport, `@a2ui/web_core`) only ever see a2ui
293
+ parts. "Pure vs mixed" is a prompting choice, not a separate code path.
294
+
295
+ ### The middleware pipeline
296
+
297
+ On each model call inside the agent's tool loop, `a2ui()`:
298
+
299
+ 1. Injects the catalog's capabilities into the system prompt so the model knows
300
+ what UI it may render (unless `instructions: 'none'`).
301
+ 2. Intercepts the model's output, both the streamed chunks and the final
302
+ aggregated message.
303
+ 3. Extracts `a2ui` fenced code blocks from the model's text.
304
+ 4. Validates them against the catalog (per the `validate` option).
305
+ 5. Rewrites them into canonical a2ui data parts.
306
+
307
+ Inbound a2ui parts (for example, a surface action sent back as the next turn, or
308
+ replayed history) are summarized into plain text before the underlying model sees
309
+ them, so a model that does not understand the a2ui mime type can still reason
310
+ about prior surfaces and user actions.
311
+
312
+ ## License
313
+
314
+ Apache-2.0
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * The registry value type under which A2UI catalogs are stored, so the
18
+ * {@link a2ui} middleware can look them up by id (and, in the future, tooling
19
+ * can list them). Register with `ai.registry.registerValue(...)` via
20
+ * {@link loadCatalog}.
21
+ */
22
+ declare const A2UI_CATALOG_VALUE_TYPE = "a2ui-catalog";
23
+ /**
24
+ * The default catalog id used by the {@link a2ui} middleware when none is
25
+ * given. Resolves to the bundled {@link basicCatalog}.
26
+ */
27
+ declare const DEFAULT_CATALOG_ID = "basic";
28
+ /** A component the model may use, plus a short description of its props. */
29
+ interface A2uiCatalogComponent {
30
+ /** The component type name, e.g. `Text`. */
31
+ name: string;
32
+ /** One-line description of what the component renders. */
33
+ description: string;
34
+ /**
35
+ * A short, model-facing description of the component's props. Kept as plain
36
+ * text (rather than a JSON Schema) to keep the injected prompt compact.
37
+ */
38
+ props: string;
39
+ }
40
+ /** A parsed catalog: an id plus the components it exposes. */
41
+ interface A2uiCatalog {
42
+ /** Globally-unique catalog id (also used as `catalogId` on `createSurface`). */
43
+ id: string;
44
+ /** The components available in this catalog. */
45
+ components: A2uiCatalogComponent[];
46
+ }
47
+ /**
48
+ * The set of icon names the basic catalog's `Icon` component supports. Names
49
+ * outside this list render as literal text (the renderer degrades gracefully),
50
+ * so the prompt lists them to steer the model toward valid names. Note the
51
+ * middleware validates component *types* against the catalog but does not
52
+ * validate individual `Icon` name values.
53
+ */
54
+ declare const BASIC_ICON_NAMES: readonly ["accountCircle", "add", "arrowBack", "arrowForward", "attachFile", "calendarToday", "call", "camera", "check", "close", "delete", "download", "edit", "event", "error", "fastForward", "favorite", "favoriteOff", "folder", "help", "home", "info", "locationOn", "lock", "lockOpen", "mail", "menu", "moreVert", "moreHoriz", "notificationsOff", "notifications", "pause", "payment", "person", "phone", "photo", "play", "print", "refresh", "rewind", "search", "send", "settings", "share", "shoppingCart", "skipNext", "skipPrevious", "star", "starHalf", "starOff", "stop", "upload", "visibility", "visibilityOff", "volumeDown", "volumeMute", "volumeOff", "volumeUp", "warning"];
55
+ /**
56
+ * The A2UI "Basic Catalog" (v0.9), mirroring the components published by
57
+ * `@a2ui/web_core`'s basic catalog. Use this to render standard UI without
58
+ * defining your own design system.
59
+ */
60
+ declare const basicCatalog: A2uiCatalog;
61
+ /**
62
+ * Renders a catalog into model-facing instructions describing the A2UI protocol
63
+ * and the available components. Injected into the system prompt by the
64
+ * middleware when `instructions !== 'none'`.
65
+ */
66
+ declare function renderCatalogInstructions(catalog: A2uiCatalog): string;
67
+ /** The literal placeholder the model is told to use for surface ids. */
68
+ declare const SURFACE_ID_PLACEHOLDER = "SURFACE_ID";
69
+
70
+ export { A2UI_CATALOG_VALUE_TYPE, type A2uiCatalog, type A2uiCatalogComponent, BASIC_ICON_NAMES, DEFAULT_CATALOG_ID, SURFACE_ID_PLACEHOLDER, basicCatalog, renderCatalogInstructions };
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Copyright 2026 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * The registry value type under which A2UI catalogs are stored, so the
18
+ * {@link a2ui} middleware can look them up by id (and, in the future, tooling
19
+ * can list them). Register with `ai.registry.registerValue(...)` via
20
+ * {@link loadCatalog}.
21
+ */
22
+ declare const A2UI_CATALOG_VALUE_TYPE = "a2ui-catalog";
23
+ /**
24
+ * The default catalog id used by the {@link a2ui} middleware when none is
25
+ * given. Resolves to the bundled {@link basicCatalog}.
26
+ */
27
+ declare const DEFAULT_CATALOG_ID = "basic";
28
+ /** A component the model may use, plus a short description of its props. */
29
+ interface A2uiCatalogComponent {
30
+ /** The component type name, e.g. `Text`. */
31
+ name: string;
32
+ /** One-line description of what the component renders. */
33
+ description: string;
34
+ /**
35
+ * A short, model-facing description of the component's props. Kept as plain
36
+ * text (rather than a JSON Schema) to keep the injected prompt compact.
37
+ */
38
+ props: string;
39
+ }
40
+ /** A parsed catalog: an id plus the components it exposes. */
41
+ interface A2uiCatalog {
42
+ /** Globally-unique catalog id (also used as `catalogId` on `createSurface`). */
43
+ id: string;
44
+ /** The components available in this catalog. */
45
+ components: A2uiCatalogComponent[];
46
+ }
47
+ /**
48
+ * The set of icon names the basic catalog's `Icon` component supports. Names
49
+ * outside this list render as literal text (the renderer degrades gracefully),
50
+ * so the prompt lists them to steer the model toward valid names. Note the
51
+ * middleware validates component *types* against the catalog but does not
52
+ * validate individual `Icon` name values.
53
+ */
54
+ declare const BASIC_ICON_NAMES: readonly ["accountCircle", "add", "arrowBack", "arrowForward", "attachFile", "calendarToday", "call", "camera", "check", "close", "delete", "download", "edit", "event", "error", "fastForward", "favorite", "favoriteOff", "folder", "help", "home", "info", "locationOn", "lock", "lockOpen", "mail", "menu", "moreVert", "moreHoriz", "notificationsOff", "notifications", "pause", "payment", "person", "phone", "photo", "play", "print", "refresh", "rewind", "search", "send", "settings", "share", "shoppingCart", "skipNext", "skipPrevious", "star", "starHalf", "starOff", "stop", "upload", "visibility", "visibilityOff", "volumeDown", "volumeMute", "volumeOff", "volumeUp", "warning"];
55
+ /**
56
+ * The A2UI "Basic Catalog" (v0.9), mirroring the components published by
57
+ * `@a2ui/web_core`'s basic catalog. Use this to render standard UI without
58
+ * defining your own design system.
59
+ */
60
+ declare const basicCatalog: A2uiCatalog;
61
+ /**
62
+ * Renders a catalog into model-facing instructions describing the A2UI protocol
63
+ * and the available components. Injected into the system prompt by the
64
+ * middleware when `instructions !== 'none'`.
65
+ */
66
+ declare function renderCatalogInstructions(catalog: A2uiCatalog): string;
67
+ /** The literal placeholder the model is told to use for surface ids. */
68
+ declare const SURFACE_ID_PLACEHOLDER = "SURFACE_ID";
69
+
70
+ export { A2UI_CATALOG_VALUE_TYPE, type A2uiCatalog, type A2uiCatalogComponent, BASIC_ICON_NAMES, DEFAULT_CATALOG_ID, SURFACE_ID_PLACEHOLDER, basicCatalog, renderCatalogInstructions };