@copilotkit/runtime 2.0.0-rc.42 → 2.0.0-rc.44

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 (63) hide show
  1. package/dist/agent/converters/aisdk.cjs +1 -1
  2. package/dist/agent/converters/aisdk.mjs +1 -1
  3. package/dist/agent/converters/tanstack.cjs +1 -1
  4. package/dist/agent/converters/tanstack.mjs +1 -1
  5. package/dist/index.cjs +2 -1
  6. package/dist/index.d.cts +3 -2
  7. package/dist/index.d.mts +3 -2
  8. package/dist/index.mjs +3 -2
  9. package/dist/runtime/core/package-info.cjs +1 -1
  10. package/dist/runtime/core/package-info.mjs +1 -1
  11. package/dist/runtime/core/runtime.cjs +1 -19
  12. package/dist/runtime/core/runtime.cjs.map +1 -1
  13. package/dist/runtime/core/runtime.d.cts +77 -29
  14. package/dist/runtime/core/runtime.d.cts.map +1 -1
  15. package/dist/runtime/core/runtime.d.mts +77 -29
  16. package/dist/runtime/core/runtime.d.mts.map +1 -1
  17. package/dist/runtime/core/runtime.mjs +2 -19
  18. package/dist/runtime/core/runtime.mjs.map +1 -1
  19. package/dist/runtime/event-transforms/recorded-events.cjs +4 -0
  20. package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -1
  21. package/dist/runtime/event-transforms/recorded-events.d.cts +5 -1
  22. package/dist/runtime/event-transforms/recorded-events.d.cts.map +1 -1
  23. package/dist/runtime/event-transforms/recorded-events.d.mts +5 -1
  24. package/dist/runtime/event-transforms/recorded-events.d.mts.map +1 -1
  25. package/dist/runtime/event-transforms/recorded-events.mjs +4 -0
  26. package/dist/runtime/event-transforms/recorded-events.mjs.map +1 -1
  27. package/dist/runtime/generative-ui/a2ui-v09-actions.cjs +106 -0
  28. package/dist/runtime/generative-ui/a2ui-v09-actions.cjs.map +1 -0
  29. package/dist/runtime/generative-ui/a2ui-v09-actions.mjs +106 -0
  30. package/dist/runtime/generative-ui/a2ui-v09-actions.mjs.map +1 -0
  31. package/dist/runtime/generative-ui/a2ui-v09-catalog.cjs +422 -0
  32. package/dist/runtime/generative-ui/a2ui-v09-catalog.cjs.map +1 -0
  33. package/dist/runtime/generative-ui/a2ui-v09-catalog.mjs +422 -0
  34. package/dist/runtime/generative-ui/a2ui-v09-catalog.mjs.map +1 -0
  35. package/dist/runtime/generative-ui/a2ui-v09-middleware.cjs +84 -0
  36. package/dist/runtime/generative-ui/a2ui-v09-middleware.cjs.map +1 -0
  37. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.cts +41 -0
  38. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.cts.map +1 -0
  39. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.mts +41 -0
  40. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.mts.map +1 -0
  41. package/dist/runtime/generative-ui/a2ui-v09-middleware.mjs +83 -0
  42. package/dist/runtime/generative-ui/a2ui-v09-middleware.mjs.map +1 -0
  43. package/dist/runtime/generative-ui/a2ui-v09-operations.cjs +620 -0
  44. package/dist/runtime/generative-ui/a2ui-v09-operations.cjs.map +1 -0
  45. package/dist/runtime/generative-ui/a2ui-v09-operations.mjs +620 -0
  46. package/dist/runtime/generative-ui/a2ui-v09-operations.mjs.map +1 -0
  47. package/dist/runtime/generative-ui/index.d.cts +1 -0
  48. package/dist/runtime/generative-ui/index.d.mts +1 -0
  49. package/dist/runtime/handlers/get-runtime-info.cjs +19 -5
  50. package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
  51. package/dist/runtime/handlers/get-runtime-info.mjs +20 -6
  52. package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
  53. package/dist/runtime/handlers/handle-run.cjs +0 -2
  54. package/dist/runtime/handlers/handle-run.cjs.map +1 -1
  55. package/dist/runtime/handlers/handle-run.mjs +0 -2
  56. package/dist/runtime/handlers/handle-run.mjs.map +1 -1
  57. package/dist/runtime/handlers/shared/agent-utils.cjs +17 -14
  58. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  59. package/dist/runtime/handlers/shared/agent-utils.mjs +18 -15
  60. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  61. package/dist/runtime/index.d.cts +2 -1
  62. package/dist/runtime/index.d.mts +2 -1
  63. package/package.json +6 -6
@@ -0,0 +1,620 @@
1
+ import { isRecord } from "../../agent/converters/usage.mjs";
2
+ import { A2UI_VERSION, GENERATIVE_UI_ACTIVITY_TYPE, GENERATIVE_UI_CHAT_TARGET, cloneValue, generativeUISurfaceMessageId } from "@copilotkit/shared";
3
+ import { EventType } from "@ag-ui/client";
4
+ import { STANDARD_CATALOG_ID } from "@copilotkit/shared/generative-ui";
5
+
6
+ //#region src/runtime/generative-ui/a2ui-v09-operations.ts
7
+ /**
8
+ * The activity type and content key of v0.9 surfaces, as
9
+ * `@ag-ui/a2ui-middleware`, `@ag-ui/a2a` and the Python helpers emit them.
10
+ */
11
+ const A2UI_SURFACE_ACTIVITY_TYPE = "a2ui-surface";
12
+ const A2UI_OPERATIONS_KEY = "a2ui_operations";
13
+ /** The `version` values of A2UI v0.9 messages. */
14
+ const V09_VERSIONS = new Set(["v0.9", "v0.9.1"]);
15
+ const V09_KINDS = [
16
+ "createSurface",
17
+ "updateComponents",
18
+ "updateDataModel",
19
+ "deleteSurface"
20
+ ];
21
+ /**
22
+ * The ids of the v0.9 basic catalog: the one agents send, and the `$id` of
23
+ * the published catalog document. Both become the standard catalog, which has
24
+ * the same 18 components.
25
+ */
26
+ const V09_BASIC_CATALOG_IDS = new Set(["https://a2ui.org/specification/v0_9/basic_catalog.json", "https://a2ui.org/specification/v0_9/catalogs/basic/catalog.json"]);
27
+ /**
28
+ * The ids of the A2UI 1.0 basic catalog, which native 1.0 agents (for
29
+ * example ADK) send. It has the 18 components of the v0.9 basic catalog
30
+ * with 1.0 bindings, so it becomes the standard catalog too.
31
+ */
32
+ const V10_BASIC_CATALOG_IDS = new Set(["https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json"]);
33
+ /** v0.9 `Text` heading variants as 1.0 `Title` sizes, largest first. */
34
+ const HEADING_SIZES = {
35
+ h1: "2xl",
36
+ h2: "xl",
37
+ h3: "lg",
38
+ h4: "md",
39
+ h5: "sm"
40
+ };
41
+ /** The one v0.9 operation key of `op`, when it has exactly one. */
42
+ function v09Kind(op) {
43
+ const kinds = V09_KINDS.filter((kind) => kind in op);
44
+ return kinds.length === 1 ? kinds[0] : void 0;
45
+ }
46
+ /**
47
+ * True for an A2UI v0.9 operation: an object whose `version` is `"v0.9"` (or
48
+ * `"v0.9.1"`). An object without `version` counts when it has exactly one
49
+ * v0.9 operation key with an object payload. A 1.0 operation always carries
50
+ * `version: "1.0"` (the client rejects one without it), and v0.8 uses other
51
+ * keys (`beginRendering`, `surfaceUpdate`), so a versionless operation with
52
+ * a v0.9 key can only be v0.9. Agents leave `version` out often enough that
53
+ * requiring it would drop their surfaces.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * isA2UIV09Operation({ version: "v0.9", deleteSurface: { surfaceId: "s" } }); // true
58
+ * isA2UIV09Operation({ deleteSurface: { surfaceId: "s" } }); // true
59
+ * isA2UIV09Operation({ version: "1.0", deleteSurface: { surfaceId: "s" } }); // false
60
+ * ```
61
+ */
62
+ function isA2UIV09Operation(value) {
63
+ if (!isRecord(value)) return false;
64
+ if (value.version !== void 0) return typeof value.version === "string" && V09_VERSIONS.has(value.version);
65
+ const kind = v09Kind(value);
66
+ return kind !== void 0 && isRecord(value[kind]);
67
+ }
68
+ const ok = (value) => ({
69
+ ok: true,
70
+ value
71
+ });
72
+ const failed = (reason) => ({
73
+ ok: false,
74
+ reason
75
+ });
76
+ /**
77
+ * A v0.9 dynamic value as 1.0: `{ path }` becomes `{ "@path" }` and
78
+ * `{ call, args }` becomes `{ "@call", args }`, at any depth. Literals stay.
79
+ */
80
+ function convertValue(value) {
81
+ if (Array.isArray(value)) return value.map(convertValue);
82
+ if (!isRecord(value)) return value;
83
+ const keys = Object.keys(value);
84
+ if (keys.length === 1 && typeof value.path === "string") return { "@path": value.path };
85
+ if (typeof value.call === "string" && keys.every((key) => key === "call" || key === "args" || key === "returnType")) return convertCall(value);
86
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, convertValue(item)]));
87
+ }
88
+ /** A v0.9 function call `{ call, args, returnType }` as `{ "@call", args }`. */
89
+ function convertCall(call) {
90
+ return {
91
+ "@call": call.call,
92
+ ...call.args === void 0 ? {} : { args: convertValue(call.args) }
93
+ };
94
+ }
95
+ /** `{ event: {...} }` or `{ functionCall: {...} }`: the v0.9 Action. */
96
+ function isV09Action(value) {
97
+ if (!isRecord(value)) return false;
98
+ return Object.keys(value).length === 1 && (isRecord(value.event) || isRecord(value.functionCall));
99
+ }
100
+ /**
101
+ * A v0.9 action as a 1.0 event binding. The event keeps its name and
102
+ * context (with converted values); a function call gets the `@call` form.
103
+ */
104
+ function convertAction(action) {
105
+ if (!isV09Action(action)) return failed("action must be { \"event\": ... } or { \"functionCall\": ... }");
106
+ if (isRecord(action.functionCall)) {
107
+ const call = action.functionCall;
108
+ if (typeof call.call !== "string" || !call.call) return failed("action.functionCall.call must be a function name");
109
+ return ok({ functionCall: convertCall(call) });
110
+ }
111
+ const event = action.event;
112
+ if (typeof event.name !== "string" || !event.name) return failed("action.event.name is required");
113
+ return ok({ event: {
114
+ name: event.name,
115
+ ...event.context === void 0 ? {} : { context: convertValue(event.context) }
116
+ } });
117
+ }
118
+ /**
119
+ * The basic-catalog changes of one component. Every other prop keeps its
120
+ * name; the 1.0 standard catalog uses the v0.9 names.
121
+ *
122
+ * - `Text` with a heading `variant` becomes `Title` (h1 "2xl" to h5 "sm"),
123
+ * with `caption` it becomes `Caption`; `variant` goes. Title and Caption
124
+ * have no `weight`, so it goes too.
125
+ * - `Button.action` becomes `onClick`.
126
+ * - `TextField.validationRegexp` becomes a `regex` check on its value.
127
+ */
128
+ function applyBasicCatalogChanges(node) {
129
+ if (node.component === "Text" && "variant" in node) {
130
+ const { variant, ...rest } = node;
131
+ const size = typeof variant === "string" ? HEADING_SIZES[variant] : void 0;
132
+ if (size !== void 0) {
133
+ const { weight: _weight, ...title } = rest;
134
+ return {
135
+ ...title,
136
+ component: "Title",
137
+ size
138
+ };
139
+ }
140
+ if (variant === "caption") {
141
+ const { weight: _weight, ...caption } = rest;
142
+ return {
143
+ ...caption,
144
+ component: "Caption"
145
+ };
146
+ }
147
+ return rest;
148
+ }
149
+ if (node.component === "Button" && "action" in node) {
150
+ const { action, ...rest } = node;
151
+ return {
152
+ ...rest,
153
+ onClick: action
154
+ };
155
+ }
156
+ if (node.component === "TextField" && "validationRegexp" in node) {
157
+ const { validationRegexp, ...rest } = node;
158
+ if (typeof validationRegexp !== "string" || rest.value === void 0) return rest;
159
+ const check = { condition: {
160
+ "@call": "regex",
161
+ args: {
162
+ value: rest.value,
163
+ pattern: validationRegexp
164
+ }
165
+ } };
166
+ const checks = Array.isArray(rest.checks) ? rest.checks : [];
167
+ return {
168
+ ...rest,
169
+ checks: [...checks, check]
170
+ };
171
+ }
172
+ return node;
173
+ }
174
+ /** One v0.9 component (flat format) as a 1.0 component node. */
175
+ function convertComponent(node) {
176
+ if (!isRecord(node) || typeof node.id !== "string" || !node.id) return failed("a component needs a string id");
177
+ if (typeof node.component !== "string" || !node.component) return failed(`component "${node.id}": the component type must be a string (the v0.9 flat format)`);
178
+ const converted = {};
179
+ for (const [key, value] of Object.entries(node)) if (key === "id" || key === "component") converted[key] = value;
180
+ else if (key === "action" || isV09Action(value)) {
181
+ const action = convertAction(value);
182
+ if (action.ok === false) return failed(`component "${node.id}": ${action.reason}`);
183
+ converted[key] = action.value;
184
+ } else converted[key] = convertValue(value);
185
+ return ok(applyBasicCatalogChanges(converted));
186
+ }
187
+ function convertUpdateComponents(payload, surfaceId) {
188
+ const { components } = payload;
189
+ if (!Array.isArray(components) || components.length === 0) return failed("updateComponents.components must be a non-empty array");
190
+ const nodes = [];
191
+ for (const component of components) {
192
+ const converted = convertComponent(component);
193
+ if (converted.ok === false) return converted;
194
+ nodes.push(converted.value);
195
+ }
196
+ return ok({
197
+ version: A2UI_VERSION,
198
+ updateComponents: {
199
+ surfaceId,
200
+ components: nodes
201
+ }
202
+ });
203
+ }
204
+ /**
205
+ * v0.9 removes the key at `path` when `value` is left out; 1.0 removes it
206
+ * for `null`. At the root, removing means an empty data model.
207
+ */
208
+ function convertUpdateDataModel(payload, surfaceId) {
209
+ const { path, value } = payload;
210
+ if (path !== void 0 && typeof path !== "string") return failed("updateDataModel.path must be a string");
211
+ const relative = typeof path === "string" ? path : "";
212
+ const pointer = relative.startsWith("/") ? relative : `/${relative}`;
213
+ const isRoot = pointer === "/";
214
+ if (isRoot && value !== void 0 && !isRecord(value)) return failed("a root updateDataModel value must be a JSON object in A2UI 1.0");
215
+ return ok({
216
+ version: A2UI_VERSION,
217
+ updateDataModel: {
218
+ surfaceId,
219
+ path: pointer,
220
+ value: value === void 0 ? isRoot ? {} : null : value
221
+ }
222
+ });
223
+ }
224
+ function convertCreateSurface(payload, surfaceId) {
225
+ const { catalogId } = payload;
226
+ const sendDataModel = payload.sendDataModel ?? payload.attachDataModel;
227
+ return {
228
+ version: A2UI_VERSION,
229
+ createSurface: {
230
+ surfaceId,
231
+ ...typeof catalogId === "string" && catalogId ? { catalogId: V09_BASIC_CATALOG_IDS.has(catalogId) ? STANDARD_CATALOG_ID : catalogId } : {},
232
+ ...typeof sendDataModel === "boolean" ? { sendDataModel } : {}
233
+ }
234
+ };
235
+ }
236
+ /** Basic catalog components as standard ones; anything else stays. */
237
+ function standardComponents(components) {
238
+ return Array.isArray(components) ? components.map((node) => isRecord(node) ? applyBasicCatalogChanges(node) : node) : components;
239
+ }
240
+ /**
241
+ * A native A2UI 1.0 operation, for the standard catalog: the 1.0 basic
242
+ * catalog id becomes the standard catalog id, and the basic catalog
243
+ * components (inline in createSurface, or in updateComponents) get the
244
+ * changes of {@link applyBasicCatalogChanges}. Bindings are already 1.0.
245
+ * Everything else stays; the client validates the operation.
246
+ */
247
+ function upgradeV10Operation(op) {
248
+ const { createSurface: create, updateComponents: update } = op;
249
+ if (isRecord(create)) {
250
+ const { catalogId } = create;
251
+ return {
252
+ ...op,
253
+ createSurface: {
254
+ ...create,
255
+ ...typeof catalogId === "string" && V10_BASIC_CATALOG_IDS.has(catalogId) ? { catalogId: STANDARD_CATALOG_ID } : {},
256
+ ...create.components === void 0 ? {} : { components: standardComponents(create.components) }
257
+ }
258
+ };
259
+ }
260
+ if (isRecord(update)) return {
261
+ ...op,
262
+ updateComponents: {
263
+ ...update,
264
+ ...update.components === void 0 ? {} : { components: standardComponents(update.components) }
265
+ }
266
+ };
267
+ return op;
268
+ }
269
+ /** One operation as 1.0, or why it cannot be converted. */
270
+ function upgradeOperation(op) {
271
+ if (!isRecord(op)) return failed("operation must be a JSON object");
272
+ if (op.version === A2UI_VERSION) return ok(upgradeV10Operation(op));
273
+ if (!isA2UIV09Operation(op)) return failed(typeof op.version === "string" ? `unsupported A2UI version "${op.version}"; only v0.9 and 1.0 operations are supported` : `not an A2UI v0.9 operation: it needs exactly one of ${V09_KINDS.join(", ")}`);
274
+ const kind = v09Kind(op);
275
+ if (!kind) return failed(`operation must contain exactly one of ${V09_KINDS.join(", ")}`);
276
+ const payload = op[kind];
277
+ if (!isRecord(payload) || typeof payload.surfaceId !== "string" || !payload.surfaceId) return failed(`${kind}.surfaceId is required`);
278
+ const { surfaceId } = payload;
279
+ switch (kind) {
280
+ case "createSurface": return ok(convertCreateSurface(payload, surfaceId));
281
+ case "updateComponents": return convertUpdateComponents(payload, surfaceId);
282
+ case "updateDataModel": return convertUpdateDataModel(payload, surfaceId);
283
+ case "deleteSurface": return ok({
284
+ version: A2UI_VERSION,
285
+ deleteSurface: { surfaceId }
286
+ });
287
+ }
288
+ }
289
+ /**
290
+ * Converts A2UI v0.9 operations to A2UI 1.0, in order. Pure; never throws.
291
+ *
292
+ * - createSurface: the v0.9 basic catalog id becomes the standard catalog
293
+ * id (`copilotkit/standard@1`); any other catalog id stays. `theme` has no
294
+ * 1.0 field and goes; `sendDataModel` stays.
295
+ * - updateComponents: `{ path }` becomes `{ "@path" }` and `{ call, args }`
296
+ * becomes `{ "@call", args }` at any depth; an action becomes an
297
+ * `{ event }` or `{ functionCall }` binding; child lists and templates
298
+ * stay. See {@link applyBasicCatalogChanges} for the props that change.
299
+ * - updateDataModel: a left-out `value` (remove) becomes `null`, or `{}` at
300
+ * the root.
301
+ * - deleteSurface: unchanged.
302
+ *
303
+ * An operation that is already 1.0 (native, for example from ADK) keeps its
304
+ * form: only the 1.0 basic catalog id becomes the standard catalog id, and
305
+ * its basic catalog components get the same changes as v0.9 ones. Any other
306
+ * operation, and any v0.9 operation that cannot be converted, goes to
307
+ * `dropped` with the reason.
308
+ *
309
+ * @example
310
+ * ```ts
311
+ * upgradeA2UIV09Operations([
312
+ * { version: "v0.9", updateDataModel: { surfaceId: "s", path: "/x" } },
313
+ * ]);
314
+ * // { operations: [{ version: "1.0", updateDataModel: { surfaceId: "s", path: "/x", value: null } }], dropped: [] }
315
+ * ```
316
+ */
317
+ function upgradeA2UIV09Operations(operations) {
318
+ const upgraded = [];
319
+ const dropped = [];
320
+ for (const operation of Array.isArray(operations) ? operations : []) {
321
+ let result;
322
+ try {
323
+ result = upgradeOperation(operation);
324
+ } catch (error) {
325
+ result = failed(`operation could not be read: ${error instanceof Error ? error.message : String(error)}`);
326
+ }
327
+ if (result.ok === false) dropped.push({
328
+ operation,
329
+ reason: result.reason
330
+ });
331
+ else upgraded.push(result.value);
332
+ }
333
+ return {
334
+ operations: upgraded,
335
+ dropped
336
+ };
337
+ }
338
+ /** The nested `surfaceId` of a v0.9 or 1.0 surface operation. */
339
+ function surfaceIdOf(op) {
340
+ if (!isRecord(op)) return void 0;
341
+ for (const kind of V09_KINDS) {
342
+ const payload = op[kind];
343
+ if (isRecord(payload) && typeof payload.surfaceId === "string") return payload.surfaceId || void 0;
344
+ }
345
+ }
346
+ /** The operations of `a2ui-surface` content. Lifecycle content has none. */
347
+ function readOperations(content) {
348
+ if (!isRecord(content)) return [];
349
+ const operations = content[A2UI_OPERATIONS_KEY] ?? content.operations;
350
+ return Array.isArray(operations) ? operations : [];
351
+ }
352
+ function pointerSegments(pointer) {
353
+ if (pointer === "") return [];
354
+ if (!pointer.startsWith("/")) throw new Error(`invalid pointer "${pointer}"`);
355
+ return pointer.slice(1).split("/").map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
356
+ }
357
+ const FORBIDDEN_SEGMENTS = new Set([
358
+ "__proto__",
359
+ "constructor",
360
+ "prototype"
361
+ ]);
362
+ /**
363
+ * Applies RFC 6902 operations to `document` in place and returns the new
364
+ * root. Throws on a path that does not resolve, like `fast-json-patch` in
365
+ * the AG-UI client, so a bad delta leaves the stored content alone.
366
+ */
367
+ function applyJsonPatch(document, patch) {
368
+ if (!Array.isArray(patch)) throw new Error("patch must be an array");
369
+ let root = document;
370
+ const parentOf = (pointer) => {
371
+ const segments = pointerSegments(pointer);
372
+ const key = segments.pop();
373
+ let parent = root;
374
+ for (const segment of segments) {
375
+ if (FORBIDDEN_SEGMENTS.has(segment)) throw new Error("forbidden path");
376
+ parent = Array.isArray(parent) ? parent[Number(segment)] : isRecord(parent) ? parent[segment] : void 0;
377
+ if (parent === void 0) throw new Error(`path "${pointer}" not found`);
378
+ }
379
+ if (key !== void 0 && FORBIDDEN_SEGMENTS.has(key)) throw new Error("forbidden path");
380
+ return {
381
+ parent,
382
+ key
383
+ };
384
+ };
385
+ const read = (pointer) => {
386
+ const { parent, key } = parentOf(pointer);
387
+ if (key === void 0) return root;
388
+ if (Array.isArray(parent)) return parent[Number(key)];
389
+ return isRecord(parent) ? parent[key] : void 0;
390
+ };
391
+ const remove = (pointer) => {
392
+ const { parent, key } = parentOf(pointer);
393
+ if (key === void 0) throw new Error("cannot remove the root");
394
+ if (Array.isArray(parent)) parent.splice(Number(key), 1);
395
+ else if (isRecord(parent) && key in parent) delete parent[key];
396
+ else throw new Error(`path "${pointer}" not found`);
397
+ };
398
+ const write = (pointer, value, insert) => {
399
+ const { parent, key } = parentOf(pointer);
400
+ if (key === void 0) root = value;
401
+ else if (Array.isArray(parent)) {
402
+ const index = key === "-" ? parent.length : Number(key);
403
+ if (!Number.isInteger(index) || index < 0 || index > parent.length) throw new Error(`index "${key}" is out of range`);
404
+ parent.splice(index, insert ? 0 : 1, value);
405
+ } else if (isRecord(parent)) parent[key] = value;
406
+ else throw new Error(`path "${pointer}" not found`);
407
+ };
408
+ for (const entry of patch) {
409
+ if (!isRecord(entry) || typeof entry.path !== "string") throw new Error("invalid patch operation");
410
+ switch (entry.op) {
411
+ case "add":
412
+ write(entry.path, cloneValue(entry.value), true);
413
+ break;
414
+ case "replace":
415
+ if (read(entry.path) === void 0) throw new Error(`path "${entry.path}" not found`);
416
+ write(entry.path, cloneValue(entry.value), false);
417
+ break;
418
+ case "remove":
419
+ remove(entry.path);
420
+ break;
421
+ case "copy":
422
+ write(entry.path, cloneValue(read(entry.from ?? "")), true);
423
+ break;
424
+ case "move": {
425
+ const value = read(entry.from ?? "");
426
+ remove(entry.from ?? "");
427
+ write(entry.path, value, true);
428
+ break;
429
+ }
430
+ case "test":
431
+ if (JSON.stringify(read(entry.path)) !== JSON.stringify(entry.value)) throw new Error(`test failed at "${entry.path}"`);
432
+ break;
433
+ default: throw new Error(`unknown patch op "${String(entry.op)}"`);
434
+ }
435
+ }
436
+ return root;
437
+ }
438
+ /**
439
+ * Converts the `a2ui-surface` surfaces of one run (A2UI v0.9, or native
440
+ * A2UI 1.0) to `generative-ui-surface` surfaces. Create one per run and pass
441
+ * every event of the run through `transform`, in order.
442
+ *
443
+ * - An `a2ui-surface` `ACTIVITY_SNAPSHOT` or `ACTIVITY_DELTA` is kept per
444
+ * messageId (a delta is applied to the stored content), and its
445
+ * operations are converted with {@link upgradeA2UIV09Operations}.
446
+ * - Each surface becomes one `generative-ui-surface` message,
447
+ * `genui:<surfaceId>`, like a `render_ui` surface. A surface that is
448
+ * created in this run is sent as an `ACTIVITY_SNAPSHOT` with the
449
+ * cumulative 1.0 content: the operations of every source message for it,
450
+ * in order, with only the first createSurface. The target is the chat,
451
+ * the status is "ready", dropped operations are `rejected` (at their
452
+ * index in the source message), and `a2uiSourceVersion` is "0.9" for a
453
+ * surface written in v0.9.
454
+ * - A surface written in native A2UI 1.0 (`version: "1.0"`, for example
455
+ * from ADK) becomes the same `generative-ui-surface` message, without
456
+ * `a2uiSourceVersion`: a click on it is a 1.0 action, so it reaches the
457
+ * agent unchanged. One surface has one version, the version of its
458
+ * first operation; an operation of the other version is rejected.
459
+ * - A surface that this run updates but does not create (v0.9 sends no
460
+ * second createSurface) was created in an earlier run, so its new
461
+ * operations are appended to its message with an `ACTIVITY_DELTA`, as
462
+ * the `render_ui` path updates an existing surface.
463
+ * - A lifecycle snapshot (`status: "building"` and so on, no operations)
464
+ * names no surface, so it is consumed. Every other event passes through.
465
+ *
466
+ * @example
467
+ * ```ts
468
+ * const upgrader = createA2UIV09ActivityUpgrader();
469
+ * source.pipe(mergeMap((event) => upgrader.transform(event)));
470
+ * ```
471
+ */
472
+ function createA2UIV09ActivityUpgrader() {
473
+ const sources = /* @__PURE__ */ new Map();
474
+ const surfaces = /* @__PURE__ */ new Map();
475
+ const snapshotOf = (surfaceId, state, operations, rejected, version) => {
476
+ const create = operations.find((op) => "createSurface" in op);
477
+ const content = {
478
+ surfaceId,
479
+ target: GENERATIVE_UI_CHAT_TARGET,
480
+ catalogId: create && "createSurface" in create && create.createSurface.catalogId || STANDARD_CATALOG_ID,
481
+ operations,
482
+ status: "ready",
483
+ rejected,
484
+ ...version === "0.9" ? { a2uiSourceVersion: "0.9" } : {}
485
+ };
486
+ const json = JSON.stringify(content);
487
+ if (json === state.lastSnapshot) return [];
488
+ state.lastSnapshot = json;
489
+ return [{
490
+ type: EventType.ACTIVITY_SNAPSHOT,
491
+ messageId: generativeUISurfaceMessageId(surfaceId),
492
+ activityType: GENERATIVE_UI_ACTIVITY_TYPE,
493
+ content: cloneValue(content),
494
+ replace: true
495
+ }];
496
+ };
497
+ const deltaOf = (surfaceId, state, operations, rejected) => {
498
+ const sent = state.sentOperations;
499
+ let same = 0;
500
+ while (same < sent.length && same < operations.length && JSON.stringify(sent[same]) === JSON.stringify(operations[same])) same++;
501
+ const patch = operations.slice(same).map((op) => ({
502
+ op: "add",
503
+ path: "/operations/-",
504
+ value: cloneValue(op)
505
+ }));
506
+ const rejectedJson = JSON.stringify(rejected);
507
+ if (rejectedJson !== state.sentRejected) patch.push({
508
+ op: "replace",
509
+ path: "/rejected",
510
+ value: rejected
511
+ });
512
+ state.sentOperations = operations;
513
+ state.sentRejected = rejectedJson;
514
+ if (patch.length === 0) return [];
515
+ return [{
516
+ type: EventType.ACTIVITY_DELTA,
517
+ messageId: generativeUISurfaceMessageId(surfaceId),
518
+ activityType: GENERATIVE_UI_ACTIVITY_TYPE,
519
+ patch
520
+ }];
521
+ };
522
+ const emitSurface = (surfaceId) => {
523
+ const state = surfaces.get(surfaceId);
524
+ if (!state) return [];
525
+ const operations = [];
526
+ const rejected = [];
527
+ let created = false;
528
+ let version;
529
+ for (const part of state.parts.values()) {
530
+ for (const { operation, index, version: opVersion } of part.operations) {
531
+ version ??= opVersion;
532
+ if (opVersion !== version) {
533
+ rejected.push({
534
+ index,
535
+ reason: `surface "${surfaceId}" is A2UI ${version}; an A2UI ${opVersion} operation cannot change it`
536
+ });
537
+ continue;
538
+ }
539
+ if ("createSurface" in operation) {
540
+ if (created) continue;
541
+ created = true;
542
+ }
543
+ operations.push(operation);
544
+ }
545
+ rejected.push(...part.rejected);
546
+ }
547
+ return created ? snapshotOf(surfaceId, state, operations, rejected, version ?? "0.9") : deltaOf(surfaceId, state, operations, rejected);
548
+ };
549
+ /** Converts the stored content of one source message again. */
550
+ const refresh = (messageId) => {
551
+ const parts = /* @__PURE__ */ new Map();
552
+ readOperations(sources.get(messageId)).forEach((op, index) => {
553
+ const surfaceId = surfaceIdOf(op);
554
+ if (surfaceId === void 0) return;
555
+ let part = parts.get(surfaceId);
556
+ if (!part) {
557
+ part = {
558
+ operations: [],
559
+ rejected: []
560
+ };
561
+ parts.set(surfaceId, part);
562
+ }
563
+ const { operations, dropped } = upgradeA2UIV09Operations([op]);
564
+ const version = isRecord(op) && op.version === A2UI_VERSION ? "1.0" : "0.9";
565
+ for (const operation of operations) part.operations.push({
566
+ operation,
567
+ index,
568
+ version
569
+ });
570
+ for (const { reason } of dropped) part.rejected.push({
571
+ index,
572
+ reason
573
+ });
574
+ });
575
+ const touched = new Set(parts.keys());
576
+ for (const [surfaceId, state] of surfaces) if (!parts.has(surfaceId) && state.parts.delete(messageId)) touched.add(surfaceId);
577
+ for (const [surfaceId, part] of parts) {
578
+ let state = surfaces.get(surfaceId);
579
+ if (!state) {
580
+ state = {
581
+ parts: /* @__PURE__ */ new Map(),
582
+ sentOperations: [],
583
+ sentRejected: "[]"
584
+ };
585
+ surfaces.set(surfaceId, state);
586
+ }
587
+ state.parts.set(messageId, part);
588
+ }
589
+ return [...touched].flatMap(emitSurface);
590
+ };
591
+ return { transform(event) {
592
+ if (event.type === EventType.ACTIVITY_SNAPSHOT) {
593
+ const snapshot = event;
594
+ if (snapshot.activityType !== A2UI_SURFACE_ACTIVITY_TYPE) return [event];
595
+ const { messageId } = snapshot;
596
+ if (snapshot.replace === false && sources.has(messageId)) return [];
597
+ sources.set(messageId, cloneValue(snapshot.content));
598
+ return refresh(messageId);
599
+ }
600
+ if (event.type === EventType.ACTIVITY_DELTA) {
601
+ const delta = event;
602
+ if (delta.activityType !== A2UI_SURFACE_ACTIVITY_TYPE) return [event];
603
+ const { messageId } = delta;
604
+ if (!sources.has(messageId)) return [];
605
+ let content;
606
+ try {
607
+ content = applyJsonPatch(cloneValue(sources.get(messageId)), delta.patch);
608
+ } catch {
609
+ return [];
610
+ }
611
+ sources.set(messageId, content);
612
+ return refresh(messageId);
613
+ }
614
+ return [event];
615
+ } };
616
+ }
617
+
618
+ //#endregion
619
+ export { createA2UIV09ActivityUpgrader };
620
+ //# sourceMappingURL=a2ui-v09-operations.mjs.map