@copilotkit/shared 1.80.0 → 1.82.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 (133) hide show
  1. package/dist/a2ui-envelope.cjs +154 -0
  2. package/dist/a2ui-envelope.cjs.map +1 -0
  3. package/dist/a2ui-envelope.d.cts +101 -0
  4. package/dist/a2ui-envelope.d.cts.map +1 -0
  5. package/dist/a2ui-envelope.d.mts +101 -0
  6. package/dist/a2ui-envelope.d.mts.map +1 -0
  7. package/dist/a2ui-envelope.mjs +151 -0
  8. package/dist/a2ui-envelope.mjs.map +1 -0
  9. package/dist/a2ui-prompts.cjs +139 -0
  10. package/dist/a2ui-prompts.cjs.map +1 -1
  11. package/dist/a2ui-prompts.d.cts +60 -1
  12. package/dist/a2ui-prompts.d.cts.map +1 -1
  13. package/dist/a2ui-prompts.d.mts +60 -1
  14. package/dist/a2ui-prompts.d.mts.map +1 -1
  15. package/dist/a2ui-prompts.mjs +134 -1
  16. package/dist/a2ui-prompts.mjs.map +1 -1
  17. package/dist/generative-ui/basic-functions.cjs +177 -0
  18. package/dist/generative-ui/basic-functions.cjs.map +1 -0
  19. package/dist/generative-ui/basic-functions.d.cts +108 -0
  20. package/dist/generative-ui/basic-functions.d.cts.map +1 -0
  21. package/dist/generative-ui/basic-functions.d.mts +108 -0
  22. package/dist/generative-ui/basic-functions.d.mts.map +1 -0
  23. package/dist/generative-ui/basic-functions.mjs +167 -0
  24. package/dist/generative-ui/basic-functions.mjs.map +1 -0
  25. package/dist/generative-ui/child-refs.cjs +161 -0
  26. package/dist/generative-ui/child-refs.cjs.map +1 -0
  27. package/dist/generative-ui/child-refs.d.cts +68 -0
  28. package/dist/generative-ui/child-refs.d.cts.map +1 -0
  29. package/dist/generative-ui/child-refs.d.mts +68 -0
  30. package/dist/generative-ui/child-refs.d.mts.map +1 -0
  31. package/dist/generative-ui/child-refs.mjs +152 -0
  32. package/dist/generative-ui/child-refs.mjs.map +1 -0
  33. package/dist/generative-ui/is-record.cjs +10 -0
  34. package/dist/generative-ui/is-record.cjs.map +1 -0
  35. package/dist/generative-ui/is-record.mjs +9 -0
  36. package/dist/generative-ui/is-record.mjs.map +1 -0
  37. package/dist/generative-ui/prompt.cjs +91 -0
  38. package/dist/generative-ui/prompt.cjs.map +1 -0
  39. package/dist/generative-ui/prompt.d.cts +13 -0
  40. package/dist/generative-ui/prompt.d.cts.map +1 -0
  41. package/dist/generative-ui/prompt.d.mts +13 -0
  42. package/dist/generative-ui/prompt.d.mts.map +1 -0
  43. package/dist/generative-ui/prompt.mjs +90 -0
  44. package/dist/generative-ui/prompt.mjs.map +1 -0
  45. package/dist/generative-ui/render-ui-args.cjs +160 -0
  46. package/dist/generative-ui/render-ui-args.cjs.map +1 -0
  47. package/dist/generative-ui/render-ui-args.d.cts +40 -0
  48. package/dist/generative-ui/render-ui-args.d.cts.map +1 -0
  49. package/dist/generative-ui/render-ui-args.d.mts +40 -0
  50. package/dist/generative-ui/render-ui-args.d.mts.map +1 -0
  51. package/dist/generative-ui/render-ui-args.mjs +159 -0
  52. package/dist/generative-ui/render-ui-args.mjs.map +1 -0
  53. package/dist/generative-ui/types.cjs +101 -0
  54. package/dist/generative-ui/types.cjs.map +1 -0
  55. package/dist/generative-ui/types.d.cts +270 -0
  56. package/dist/generative-ui/types.d.cts.map +1 -0
  57. package/dist/generative-ui/types.d.mts +270 -0
  58. package/dist/generative-ui/types.d.mts.map +1 -0
  59. package/dist/generative-ui/types.mjs +86 -0
  60. package/dist/generative-ui/types.mjs.map +1 -0
  61. package/dist/generative-ui/validate-operation.cjs +405 -0
  62. package/dist/generative-ui/validate-operation.cjs.map +1 -0
  63. package/dist/generative-ui/validate-operation.d.cts +86 -0
  64. package/dist/generative-ui/validate-operation.d.cts.map +1 -0
  65. package/dist/generative-ui/validate-operation.d.mts +86 -0
  66. package/dist/generative-ui/validate-operation.d.mts.map +1 -0
  67. package/dist/generative-ui/validate-operation.mjs +399 -0
  68. package/dist/generative-ui/validate-operation.mjs.map +1 -0
  69. package/dist/index.cjs +63 -0
  70. package/dist/index.cjs.map +1 -1
  71. package/dist/index.d.cts +9 -2
  72. package/dist/index.d.cts.map +1 -1
  73. package/dist/index.d.mts +9 -2
  74. package/dist/index.d.mts.map +1 -1
  75. package/dist/index.mjs +9 -2
  76. package/dist/index.mjs.map +1 -1
  77. package/dist/index.umd.js +1421 -20
  78. package/dist/index.umd.js.map +1 -1
  79. package/dist/package.cjs +1 -1
  80. package/dist/package.mjs +1 -1
  81. package/dist/telemetry/telemetry-client.cjs +1 -1
  82. package/dist/telemetry/telemetry-client.cjs.map +1 -1
  83. package/dist/telemetry/telemetry-client.d.cts.map +1 -1
  84. package/dist/telemetry/telemetry-client.d.mts.map +1 -1
  85. package/dist/telemetry/telemetry-client.mjs +1 -1
  86. package/dist/telemetry/telemetry-client.mjs.map +1 -1
  87. package/dist/utils/dashboard-url.cjs +19 -0
  88. package/dist/utils/dashboard-url.cjs.map +1 -0
  89. package/dist/utils/dashboard-url.mjs +18 -0
  90. package/dist/utils/dashboard-url.mjs.map +1 -0
  91. package/dist/utils/index.cjs +2 -1
  92. package/dist/utils/index.cjs.map +1 -1
  93. package/dist/utils/index.d.cts.map +1 -1
  94. package/dist/utils/index.d.mts.map +1 -1
  95. package/dist/utils/index.mjs +2 -1
  96. package/dist/utils/index.mjs.map +1 -1
  97. package/dist/utils/inspector-learning.cjs +10 -7
  98. package/dist/utils/inspector-learning.cjs.map +1 -1
  99. package/dist/utils/inspector-learning.d.cts.map +1 -1
  100. package/dist/utils/inspector-learning.d.mts.map +1 -1
  101. package/dist/utils/inspector-learning.mjs +11 -7
  102. package/dist/utils/inspector-learning.mjs.map +1 -1
  103. package/dist/utils/inspector-metadata.cjs +2 -3
  104. package/dist/utils/inspector-metadata.cjs.map +1 -1
  105. package/dist/utils/inspector-metadata.d.cts.map +1 -1
  106. package/dist/utils/inspector-metadata.d.mts.map +1 -1
  107. package/dist/utils/inspector-metadata.mjs +3 -3
  108. package/dist/utils/inspector-metadata.mjs.map +1 -1
  109. package/package.json +1 -1
  110. package/src/__tests__/a2ui-envelope.test.ts +434 -0
  111. package/src/__tests__/a2ui-prompts.test.ts +362 -0
  112. package/src/a2ui-envelope.ts +309 -0
  113. package/src/a2ui-prompts.ts +207 -0
  114. package/src/generative-ui/__tests__/render-ui-args.test.ts +175 -0
  115. package/src/generative-ui/__tests__/validate-operation.test.ts +977 -0
  116. package/src/generative-ui/basic-functions.ts +282 -0
  117. package/src/generative-ui/child-refs.ts +210 -0
  118. package/src/generative-ui/index.ts +6 -0
  119. package/src/generative-ui/is-record.ts +4 -0
  120. package/src/generative-ui/prompt.ts +174 -0
  121. package/src/generative-ui/render-ui-args.ts +199 -0
  122. package/src/generative-ui/types.ts +314 -0
  123. package/src/generative-ui/validate-operation.ts +723 -0
  124. package/src/index.ts +15 -0
  125. package/src/telemetry/telemetry-client.test.ts +18 -0
  126. package/src/telemetry/telemetry-client.ts +3 -1
  127. package/src/utils/dashboard-url.ts +17 -0
  128. package/src/utils/index.ts +7 -1
  129. package/src/utils/inspector-learning.test.ts +58 -0
  130. package/src/utils/inspector-learning.ts +26 -5
  131. package/src/utils/inspector-metadata.test.ts +2 -1
  132. package/src/utils/inspector-metadata.ts +3 -13
  133. package/src/utils.test.ts +71 -0
package/dist/index.umd.js CHANGED
@@ -797,9 +797,25 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
797
797
  return convertJsonSchemaToZodSchema(actionParametersToJsonSchema(parameters), true);
798
798
  }
799
799
 
800
+ //#endregion
801
+ //#region src/utils/dashboard-url.ts
802
+ /**
803
+ * Checks dashboard navigation transport and credentials only.
804
+ * Callers must separately enforce the configured origin and allowed paths.
805
+ * This policy does not authorize server-side requests.
806
+ */
807
+ function isSafeDashboardUrl(url) {
808
+ const local = [
809
+ "localhost",
810
+ "127.0.0.1",
811
+ "[::1]"
812
+ ].includes(url.hostname) || /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+localhost$/u.test(url.hostname);
813
+ return !url.username && !url.password && (url.protocol === "https:" || url.protocol === "http:" && local);
814
+ }
815
+
800
816
  //#endregion
801
817
  //#region src/utils/inspector-metadata.ts
802
- function isRecord(value) {
818
+ function isRecord$1(value) {
803
819
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
804
820
  try {
805
821
  const prototype = Object.getPrototypeOf(value);
@@ -822,7 +838,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
822
838
  return parsed.length > 0 ? parsed : void 0;
823
839
  }
824
840
  function parseIdentity(value) {
825
- if (!isRecord(value)) return;
841
+ if (!isRecord$1(value)) return;
826
842
  const organizationName = parseNonBlankString(value.organizationName);
827
843
  const projectName = parseNonBlankString(value.projectName);
828
844
  if (organizationName === void 0 || projectName === void 0) return;
@@ -832,7 +848,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
832
848
  };
833
849
  }
834
850
  function parsePlan(value) {
835
- if (!isRecord(value)) return;
851
+ if (!isRecord$1(value)) return;
836
852
  const code = parseNonBlankString(value.code);
837
853
  const label = parseNonBlankString(value.label);
838
854
  if (code === void 0 || label === void 0) return;
@@ -842,7 +858,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
842
858
  };
843
859
  }
844
860
  function parseLicense(value) {
845
- if (!isRecord(value)) return;
861
+ if (!isRecord$1(value)) return;
846
862
  switch (value.state) {
847
863
  case "valid":
848
864
  case "none":
@@ -874,12 +890,10 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
874
890
  return;
875
891
  }
876
892
  if (parsed.hostname.length === 0 || parsed.username || parsed.password) return;
877
- if (parsed.protocol === "https:") return url;
878
- const isLoopbackHost = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1" || parsed.hostname === "[::1]";
879
- if (parsed.protocol === "http:" && isLoopbackHost) return url;
893
+ return isSafeDashboardUrl(parsed) ? url : void 0;
880
894
  }
881
895
  function parseAction(value) {
882
- if (!isRecord(value)) return;
896
+ if (!isRecord$1(value)) return;
883
897
  const kind = parseActionKind(value.kind);
884
898
  const url = parseSafeActionUrl(value.url);
885
899
  if (kind === void 0 || url === void 0) return;
@@ -892,7 +906,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
892
906
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
893
907
  }
894
908
  function parseUsageLimit(value) {
895
- if (!isRecord(value)) return;
909
+ if (!isRecord$1(value)) return;
896
910
  if (value.kind === "finite") {
897
911
  if (typeof value.value !== "number" || !Number.isSafeInteger(value.value) || value.value < 1) return;
898
912
  return {
@@ -904,7 +918,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
904
918
  if (value.kind === "unknown") return { kind: "unknown" };
905
919
  }
906
920
  function parseUsage(value) {
907
- if (!isRecord(value)) return;
921
+ if (!isRecord$1(value)) return;
908
922
  const limit = parseUsageLimit(value.limit);
909
923
  const used = value.used;
910
924
  if (!isFiniteNonnegativeInteger(used) || limit === void 0) return;
@@ -925,7 +939,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
925
939
  * top-level payload.
926
940
  */
927
941
  function parseInspectorMetadataV1(value) {
928
- if (!isRecord(value) || value.schemaVersion !== 1) return;
942
+ if (!isRecord$1(value) || value.schemaVersion !== 1) return;
929
943
  const identity = parseIdentity(value.identity);
930
944
  const plan = parsePlan(value.plan);
931
945
  const license = parseLicense(value.license);
@@ -959,17 +973,19 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
959
973
  try {
960
974
  const parsed = new URL(value);
961
975
  const configured = new URL(trustedOrigin);
962
- const loopback = [
963
- "localhost",
964
- "127.0.0.1",
965
- "[::1]"
966
- ].includes(configured.hostname);
967
- if (parsed.username || parsed.password || configured.username || configured.password || configured.pathname !== "/" || configured.search || configured.hash || configured.protocol !== "https:" && !(configured.protocol === "http:" && loopback) || parsed.origin !== configured.origin) return;
976
+ if (parsed.username || parsed.password || configured.username || configured.password || configured.pathname !== "/" || configured.search || configured.hash || !isSafeDashboardUrl(configured) || parsed.origin !== configured.origin) return;
968
977
  return parsed.toString();
969
978
  } catch (_unused) {
970
979
  return;
971
980
  }
972
981
  }
982
+ /** Validates the canonical dashboard route after the origin check. */
983
+ function validLearningPath(value, kind) {
984
+ const url = new URL(value);
985
+ if (url.search || url.hash) return false;
986
+ if (kind === "learning") return url.pathname === "/learning" || /^\/o\/[^/]+\/[^/]+\/learning(?:\/[^/]+)?$/u.test(url.pathname);
987
+ return kind === "candidates" ? /^\/o\/[^/]+\/[^/]+\/learning\/[^/]+\/skills$/u.test(url.pathname) : /^\/o\/[^/]+\/[^/]+\/learning\/[^/]+\/analysis-results$/u.test(url.pathname);
988
+ }
973
989
  function parseEvidence(value) {
974
990
  if (record(value) && value.status === "unavailable") return Object.keys(value).length === 1 ? { status: "unavailable" } : void 0;
975
991
  if (!record(value) || value.status !== "available" || !string(value.threadId, 128) || !date(value.updatedAt)) return;
@@ -1106,7 +1122,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
1106
1122
  const learning = parseInspectorLearningUrl(value.links.learning, webAppOrigin);
1107
1123
  const candidates = value.links.candidates === null ? null : parseInspectorLearningUrl(value.links.candidates, webAppOrigin);
1108
1124
  const runs = value.links.runs === null ? null : parseInspectorLearningUrl(value.links.runs, webAppOrigin);
1109
- if (!learning || candidates === void 0 || runs === void 0 || value.pendingThreadCount > 0 && runs === null || value.pendingCandidateCount > 0 && candidates === null) return void 0;
1125
+ if (!learning || candidates === void 0 || runs === void 0 || !validLearningPath(learning, "learning") || candidates !== null && !validLearningPath(candidates, "candidates") || runs !== null && !validLearningPath(runs, "runs") || value.pendingThreadCount > 0 && runs === null || value.pendingCandidateCount > 0 && candidates === null) return void 0;
1110
1126
  return {
1111
1127
  schemaVersion: 1,
1112
1128
  projectKey: value.projectKey,
@@ -1469,13 +1485,14 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
1469
1485
  return fallback === "unset" ? null : fallback;
1470
1486
  }
1471
1487
  }
1488
+ const PARTIAL_JSON_ALLOW = partial_json.Allow.ALL & ~partial_json.Allow.NUM;
1472
1489
  /**
1473
1490
  * Parses a partial/incomplete JSON string, returning as much valid data as possible.
1474
1491
  * Falls back to an empty object if parsing fails entirely.
1475
1492
  */
1476
1493
  function partialJSONParse(json) {
1477
1494
  try {
1478
- const parsed = partial_json.parse(json);
1495
+ const parsed = partial_json.parse(json, PARTIAL_JSON_ALLOW);
1479
1496
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
1480
1497
  return {};
1481
1498
  } catch (_unused2) {
@@ -2306,7 +2323,414 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
2306
2323
 
2307
2324
  //#endregion
2308
2325
  //#region package.json
2309
- var version = "1.80.0";
2326
+ var version = "1.82.0";
2327
+
2328
+ //#endregion
2329
+ //#region src/generative-ui/basic-functions.ts
2330
+ /**
2331
+ * The callers of an app function that names none: the renderer only, as
2332
+ * in A2UI 1.0. The agent calls a function with `callRendererFunction` only
2333
+ * when its declaration allows it (`"rendererOrAgent"` or `"agentOnly"`).
2334
+ * The manifests and the exported catalog write the value out.
2335
+ */
2336
+ const GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS = "rendererOnly";
2337
+ /**
2338
+ * Who may call a function, from its permissions. A function that needs a
2339
+ * user gesture is for the renderer only, whatever `allowedCallers` says.
2340
+ *
2341
+ * @example
2342
+ * ```ts
2343
+ * functionCallers({}); // { renderer: true, agent: true }
2344
+ * functionCallers({ allowedCallers: "rendererOnly" }); // { renderer: true, agent: false }
2345
+ * functionCallers({ requiresUserActivation: true }); // { renderer: true, agent: false }
2346
+ * ```
2347
+ */
2348
+ function functionCallers(fn) {
2349
+ var _fn$allowedCallers;
2350
+ if (fn.requiresUserActivation) return {
2351
+ renderer: true,
2352
+ agent: false
2353
+ };
2354
+ const callers = (_fn$allowedCallers = fn.allowedCallers) !== null && _fn$allowedCallers !== void 0 ? _fn$allowedCallers : GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS;
2355
+ return {
2356
+ renderer: callers !== "agentOnly",
2357
+ agent: callers !== "rendererOnly"
2358
+ };
2359
+ }
2360
+ /** Marks a table of built-in functions as callable by the renderer only. */
2361
+ function rendererOnly(functions) {
2362
+ return Object.fromEntries(Object.entries(functions).map(([name, info]) => [name, {
2363
+ ...info,
2364
+ allowedCallers: "rendererOnly"
2365
+ }]));
2366
+ }
2367
+ /**
2368
+ * The basic functions by name. A `{"@call"}` in a prop, in an event
2369
+ * binding, or in a `callRendererFunction` may name any of them without a
2370
+ * declaration in `createGenerativeUI({ functions })`.
2371
+ */
2372
+ const A2UI_BASIC_FUNCTIONS = rendererOnly({
2373
+ required: {
2374
+ description: "Valid when the value is not empty",
2375
+ parameters: "{ value: unknown }",
2376
+ returnType: "validationResult"
2377
+ },
2378
+ regex: {
2379
+ description: "Valid when the value matches the pattern",
2380
+ parameters: "{ value: string; pattern: string }",
2381
+ returnType: "validationResult"
2382
+ },
2383
+ length: {
2384
+ description: "Valid when the length of the value is within min and max",
2385
+ parameters: "{ value: string; min?: number; max?: number }",
2386
+ returnType: "validationResult"
2387
+ },
2388
+ numeric: {
2389
+ description: "Valid when the value is a number within min and max",
2390
+ parameters: "{ value: number; min?: number; max?: number }",
2391
+ returnType: "validationResult"
2392
+ },
2393
+ email: {
2394
+ description: "Valid when the value is an email address",
2395
+ parameters: "{ value: string }",
2396
+ returnType: "validationResult"
2397
+ },
2398
+ formatString: {
2399
+ description: "Interpolates ${/path}, ${relative/path} and ${fn(arg: value)} in the value; \\${ is a literal",
2400
+ parameters: "{ value: string }",
2401
+ returnType: "string"
2402
+ },
2403
+ formatNumber: {
2404
+ description: "The number in the locale of the user",
2405
+ parameters: "{ value: number; decimals?: number; grouping?: boolean }",
2406
+ returnType: "string"
2407
+ },
2408
+ formatCurrency: {
2409
+ description: "The amount as money, with an ISO 4217 currency code",
2410
+ parameters: "{ value: number; currency: string; decimals?: number; grouping?: boolean }",
2411
+ returnType: "string"
2412
+ },
2413
+ formatDate: {
2414
+ description: "A date or ISO string in a TR35 pattern, for example \"MMM d, yyyy\" or \"HH:mm\"",
2415
+ parameters: "{ value: string | number; format: string }",
2416
+ returnType: "string"
2417
+ },
2418
+ pluralize: {
2419
+ description: "The string of the plural category of the value",
2420
+ parameters: "{ value: number; zero?: string; one?: string; two?: string; few?: string; many?: string; other: string }",
2421
+ returnType: "string"
2422
+ },
2423
+ openUrl: {
2424
+ description: "Opens an http(s) URL in a new tab. Only from an event",
2425
+ parameters: "{ url: string }",
2426
+ returnType: "void",
2427
+ requiresUserActivation: true
2428
+ },
2429
+ and: {
2430
+ description: "True when every value is true",
2431
+ parameters: "{ values: boolean[] }",
2432
+ returnType: "boolean"
2433
+ },
2434
+ or: {
2435
+ description: "True when any value is true",
2436
+ parameters: "{ values: boolean[] }",
2437
+ returnType: "boolean"
2438
+ },
2439
+ not: {
2440
+ description: "The negated value",
2441
+ parameters: "{ value: boolean }",
2442
+ returnType: "boolean"
2443
+ }
2444
+ });
2445
+ /**
2446
+ * The value functions that CopilotKit adds to the basic catalog, because
2447
+ * A2UI 1.0 has no arithmetic: `calc` evaluates an expression over named
2448
+ * args, and `series` builds a computed list. A catalog may declare its own
2449
+ * functions in A2UI, so these are regular catalog functions to the model;
2450
+ * a renderer without them rejects the call instead of misrendering.
2451
+ */
2452
+ const COPILOTKIT_FUNCTIONS = rendererOnly({
2453
+ calc: {
2454
+ description: "The value of an arithmetic expression over the other args, by name: + - * / % ( ), comparisons, && || !, cond ? a : b, min max round floor ceil abs, 'text' + name",
2455
+ parameters: "{ expression: string; [name: string]: number | string | boolean }",
2456
+ returnType: "any",
2457
+ extension: true
2458
+ },
2459
+ series: {
2460
+ description: "A list of count copies of item, for chart data and template lists. Put arithmetic in ${expression} strings in item, using the loop variable (default i, counting from start, default 1) and other named args. A whole-expression string retains the result type, so \"${i * monthlyCost}\" yields a number. Arguments, including nested calc or formatString calls in item, resolve before the series loop; those calls cannot use the loop variable. Example: {\"@call\":\"series\",\"args\":{\"count\":6,\"item\":{\"month\":\"${i}\",\"cost\":\"${i * monthlyCost}\"},\"monthlyCost\":{\"@path\":\"/monthlyCost\"}}}. Omit variable to use i.",
2461
+ parameters: "{ count: number; item: unknown; variable?: string; start?: number; [name: string]: unknown }",
2462
+ returnType: "array",
2463
+ extension: true
2464
+ }
2465
+ });
2466
+ /** Every function a `{"@call"}` may name without a declaration: basic and CopilotKit. */
2467
+ const GENERATIVE_UI_FUNCTIONS = {
2468
+ ...A2UI_BASIC_FUNCTIONS,
2469
+ ...COPILOTKIT_FUNCTIONS
2470
+ };
2471
+ /** The name of the system function that gives the index of a template item. */
2472
+ const A2UI_INDEX_FUNCTION = "@index";
2473
+ /** True for a built-in function name: basic, CopilotKit, or `@index`. */
2474
+ function isA2UIBasicFunction(name) {
2475
+ return name === A2UI_INDEX_FUNCTION || Object.prototype.hasOwnProperty.call(GENERATIVE_UI_FUNCTIONS, name);
2476
+ }
2477
+ /**
2478
+ * True for a built-in function that a prop or a check may call: every one
2479
+ * except the functions that need a user gesture.
2480
+ */
2481
+ function isA2UIValueFunction(name) {
2482
+ if (name === A2UI_INDEX_FUNCTION) return true;
2483
+ const info = Object.prototype.hasOwnProperty.call(GENERATIVE_UI_FUNCTIONS, name) ? GENERATIVE_UI_FUNCTIONS[name] : void 0;
2484
+ return info !== void 0 && !info.requiresUserActivation;
2485
+ }
2486
+ /** `{ "@call": "<name>", "args"?: {...} }`: a function call value. */
2487
+ function isCallBinding(value) {
2488
+ return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value["@call"] === "string";
2489
+ }
2490
+ function isValidationResult(value) {
2491
+ return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.valid === "boolean";
2492
+ }
2493
+
2494
+ //#endregion
2495
+ //#region src/generative-ui/is-record.ts
2496
+ /** True for a plain object: not null, not an array. Internal, not exported. */
2497
+ function isRecord(value) {
2498
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2499
+ }
2500
+
2501
+ //#endregion
2502
+ //#region src/generative-ui/child-refs.ts
2503
+ /**
2504
+ * How A2UI 1.0 marks a prop that holds a component reference: the JSON
2505
+ * Schema of the prop is a `$ref` to one of these two common types.
2506
+ * Validators and renderers find the children of a component by these refs,
2507
+ * at any depth of the props schema.
2508
+ */
2509
+ const A2UI_COMPONENT_ID_REF = "common_types.json#/$defs/ComponentId";
2510
+ const A2UI_CHILD_LIST_REF = "common_types.json#/$defs/ChildList";
2511
+ /**
2512
+ * The start of the `description` that marks a schema as a component
2513
+ * reference before it is turned into JSON Schema. `child()` and
2514
+ * `childList()` set it; a schema from another library can set a description
2515
+ * that starts with the same mark to get the same effect. What follows the
2516
+ * mark (after a space) stays as the description of the reference.
2517
+ */
2518
+ const A2UI_COMPONENT_ID_MARK = "@a2ui/ComponentId";
2519
+ const A2UI_CHILD_LIST_MARK = "@a2ui/ChildList";
2520
+ /** The ref kind of a JSON Schema node, or `undefined` for a plain value. */
2521
+ function childRefKind(schema) {
2522
+ const ref = schema.$ref;
2523
+ if (ref === A2UI_COMPONENT_ID_REF) return "single";
2524
+ if (ref === A2UI_CHILD_LIST_REF) return "multiple";
2525
+ }
2526
+ /**
2527
+ * Turns the reference marks of a JSON Schema into A2UI `$ref`s, in place of
2528
+ * the marked node. The mark is the `description` set by `child()` and
2529
+ * `childList()`; after this, the node is `{ "$ref": "common_types.json#/..." }`.
2530
+ */
2531
+ function applyChildRefMarks(schema) {
2532
+ const marked = (description, mark, ref) => {
2533
+ if (typeof description !== "string" || !description.startsWith(mark)) return;
2534
+ const rest = description.slice(mark.length).trim();
2535
+ return rest === "" ? { $ref: ref } : {
2536
+ $ref: ref,
2537
+ description: rest
2538
+ };
2539
+ };
2540
+ const visit = (node) => {
2541
+ var _marked;
2542
+ if (Array.isArray(node)) return node.map(visit);
2543
+ if (!isRecord(node)) return node;
2544
+ const reference = (_marked = marked(node.description, A2UI_COMPONENT_ID_MARK, A2UI_COMPONENT_ID_REF)) !== null && _marked !== void 0 ? _marked : marked(node.description, A2UI_CHILD_LIST_MARK, A2UI_CHILD_LIST_REF);
2545
+ if (reference) return reference;
2546
+ return Object.fromEntries(Object.entries(node).map(([key, value]) => [key, visit(value)]));
2547
+ };
2548
+ return visit(schema);
2549
+ }
2550
+ /**
2551
+ * Every component reference in a props schema, with its path. Walks
2552
+ * `properties`, array `items`, and the variants of `anyOf` / `oneOf` /
2553
+ * `allOf`. A union counts as a reference only when every alternative is
2554
+ * one of the same kind: a prop that is text in one branch and a child in
2555
+ * another cannot be told apart from its value, so it stays data.
2556
+ */
2557
+ function collectChildRefs(schema) {
2558
+ const refs = [];
2559
+ const seen = /* @__PURE__ */ new Set();
2560
+ const add = (path, kind) => {
2561
+ const key = path.join("\0");
2562
+ if (seen.has(key)) return;
2563
+ seen.add(key);
2564
+ refs.push({
2565
+ path,
2566
+ kind
2567
+ });
2568
+ };
2569
+ const visit = (node, path) => {
2570
+ if (!isRecord(node)) return;
2571
+ const kind = childRefKind(node);
2572
+ if (kind) return add(path, kind);
2573
+ for (const list of [node.anyOf, node.oneOf]) {
2574
+ if (!Array.isArray(list) || list.length === 0) continue;
2575
+ const kinds = list.map((variant) => isRecord(variant) ? childRefKind(variant) : void 0);
2576
+ const [first] = kinds;
2577
+ if (first && kinds.every((k) => k === first)) add(path, first);
2578
+ else if (kinds.every((k) => k === void 0)) {
2579
+ const perVariant = list.map((variant) => collectChildRefs(variant));
2580
+ const key = (ref) => `${ref.kind}\u0000${ref.path.join("\0")}`;
2581
+ perVariant[0].filter((ref) => perVariant.every((refs) => refs.some((r) => key(r) === key(ref)))).forEach((ref) => add([...path, ...ref.path], ref.kind));
2582
+ }
2583
+ }
2584
+ if (Array.isArray(node.allOf)) node.allOf.forEach((variant) => visit(variant, path));
2585
+ if (isRecord(node.properties)) for (const [key, value] of Object.entries(node.properties)) visit(value, [...path, key]);
2586
+ if (isRecord(node.items)) visit(node.items, [...path, "*"]);
2587
+ };
2588
+ visit(schema, []);
2589
+ return refs;
2590
+ }
2591
+ /**
2592
+ * The component ids at the references of one component node: a string id,
2593
+ * a list of ids, or the `componentId` of a template, at every ref path.
2594
+ * Bound or computed values are not ids and are left out.
2595
+ */
2596
+ function childIdsAtRefs(component, refs) {
2597
+ const ids = [];
2598
+ const collect = (value) => {
2599
+ if (typeof value === "string") ids.push(value);
2600
+ else if (Array.isArray(value)) value.forEach((id) => typeof id === "string" && ids.push(id));
2601
+ else if (isRecord(value) && typeof value.componentId === "string") ids.push(value.componentId);
2602
+ };
2603
+ const visit = (value, path) => {
2604
+ if (path.length === 0) return collect(value);
2605
+ const [head, ...rest] = path;
2606
+ if (head === "*") {
2607
+ if (Array.isArray(value)) value.forEach((item) => visit(item, rest));
2608
+ return;
2609
+ }
2610
+ if (isRecord(value) && Object.prototype.hasOwnProperty.call(value, head)) visit(value[head], rest);
2611
+ };
2612
+ for (const ref of refs) visit(component, ref.path);
2613
+ return ids;
2614
+ }
2615
+ /**
2616
+ * True when a reference of the component is bound or computed (`{"@path"}`,
2617
+ * `{"@call"}`) at the ref itself or above it, so its ids are known only
2618
+ * at render time.
2619
+ */
2620
+ function hasBoundChildRef(component, refs) {
2621
+ const isDynamic = (value) => isRecord(value) && ("@path" in value || "@call" in value);
2622
+ const visit = (value, path) => {
2623
+ if (isDynamic(value)) return true;
2624
+ if (path.length === 0) return false;
2625
+ const [head, ...rest] = path;
2626
+ if (head === "*") return Array.isArray(value) && value.some((item) => visit(item, rest));
2627
+ return isRecord(value) && Object.prototype.hasOwnProperty.call(value, head) && visit(value[head], rest);
2628
+ };
2629
+ return refs.some((ref) => visit(component, ref.path));
2630
+ }
2631
+ /**
2632
+ * Walks `value` along a ref path and replaces what sits at the end with
2633
+ * `replace(found)`. Objects and arrays on the way are copied; everything
2634
+ * else keeps its identity. Missing keys are left alone.
2635
+ */
2636
+ function mapAtChildRef(value, path, replace) {
2637
+ if (path.length === 0) return replace(value);
2638
+ const [head, ...rest] = path;
2639
+ if (head === "*") {
2640
+ if (!Array.isArray(value)) return value;
2641
+ return value.map((item) => mapAtChildRef(item, rest, replace));
2642
+ }
2643
+ if (!isRecord(value) || !Object.prototype.hasOwnProperty.call(value, head)) return value;
2644
+ return {
2645
+ ...value,
2646
+ [head]: mapAtChildRef(value[head], rest, replace)
2647
+ };
2648
+ }
2649
+
2650
+ //#endregion
2651
+ //#region src/generative-ui/types.ts
2652
+ /** A2UI protocol version used on the wire. */
2653
+ const A2UI_VERSION = "v1.0";
2654
+ /** Activity type of a generated surface message. */
2655
+ const GENERATIVE_UI_ACTIVITY_TYPE = "generative-ui-surface";
2656
+ /** Activity type of a function call that the agent asks the client to run. */
2657
+ const GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE = "generative-ui-function-call";
2658
+ /** Tool the model calls to render or update surfaces. */
2659
+ const GENERATIVE_UI_RENDER_TOOL = "render_ui";
2660
+ /** Target id of the chat transcript. */
2661
+ const GENERATIVE_UI_CHAT_TARGET = "chat";
2662
+ /** Component id every surface renders from. */
2663
+ const GENERATIVE_UI_ROOT_ID = "root";
2664
+ /**
2665
+ * Whether the agent may call renderer functions with `callRendererFunction`.
2666
+ * Off for now: the result goes back as a developer message, and not every
2667
+ * backend keeps that message where the model reads it in order. While off,
2668
+ * the prompts do not mention the operation, the validator rejects it, and
2669
+ * the dispatcher refuses the agent, whatever a declaration's
2670
+ * `allowedCallers` says. The code and its tests stay for when it is on.
2671
+ */
2672
+ const GENERATIVE_UI_AGENT_FUNCTION_CALLS = false;
2673
+ /** The reason an agent function call is rejected while they are off. */
2674
+ const GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON = "callRendererFunction is not supported in this version: the agent cannot call renderer functions until their results can be sent back to it reliably";
2675
+ /** Activity message id of a surface. One message per surface. */
2676
+ function generativeUISurfaceMessageId(surfaceId) {
2677
+ return `genui:${surfaceId}`;
2678
+ }
2679
+ /**
2680
+ * Activity message id of an agent-called function. One message per
2681
+ * `functionCallId`.
2682
+ *
2683
+ * @param functionCallId - The `functionCallId` of the `callRendererFunction` operation.
2684
+ *
2685
+ * @example
2686
+ * ```ts
2687
+ * generativeUIFunctionCallMessageId("f1"); // "genui-fn:f1"
2688
+ * ```
2689
+ */
2690
+ function generativeUIFunctionCallMessageId(functionCallId) {
2691
+ return `genui-fn:${functionCallId}`;
2692
+ }
2693
+ /**
2694
+ * The keys of the A2UI 1.0 component envelope next to `id` and
2695
+ * `component`: `catalogId`, `accessibility` and `metadata`. They are not
2696
+ * props of the component. The renderer reads `accessibility` and ignores
2697
+ * the other two.
2698
+ */
2699
+ const A2UI_COMPONENT_ENVELOPE_KEYS = new Set([
2700
+ "catalogId",
2701
+ "accessibility",
2702
+ "metadata"
2703
+ ]);
2704
+ /** Most component names that one target can list. */
2705
+ const GENERATIVE_UI_MAX_TARGET_COMPONENTS = 100;
2706
+ /** Most rejections that a surface summary lists. */
2707
+ const GENERATIVE_UI_MAX_SUMMARY_REJECTIONS = 20;
2708
+ /** Most characters of one rejection in a surface summary. */
2709
+ const GENERATIVE_UI_MAX_REJECTION_LENGTH = 500;
2710
+ /**
2711
+ * The action message of a user event, with the A2UI field names. Takes the
2712
+ * time of the call when the event has no timestamp.
2713
+ *
2714
+ * @example
2715
+ * ```ts
2716
+ * toA2UIActionMessage({ name: "buy", surfaceId: "s1", componentId: "b", context: { sku: "a" } });
2717
+ * // { version: "v1.0", action: { name: "buy", surfaceId: "s1", sourceComponentId: "b", timestamp: "2026-…", context: { sku: "a" } } }
2718
+ * ```
2719
+ */
2720
+ function toA2UIActionMessage(event) {
2721
+ var _event$timestamp;
2722
+ return {
2723
+ version: A2UI_VERSION,
2724
+ action: {
2725
+ name: event.name,
2726
+ surfaceId: event.surfaceId,
2727
+ sourceComponentId: event.componentId,
2728
+ timestamp: (_event$timestamp = event.timestamp) !== null && _event$timestamp !== void 0 ? _event$timestamp : (/* @__PURE__ */ new Date()).toISOString(),
2729
+ ...event.userMessage === void 0 ? {} : { userMessage: event.userMessage },
2730
+ context: event.context
2731
+ }
2732
+ };
2733
+ }
2310
2734
 
2311
2735
  //#endregion
2312
2736
  //#region src/a2ui-prompts.ts
@@ -2423,12 +2847,933 @@ Design principles:
2423
2847
  action context should reference the same paths to capture user input.
2424
2848
 
2425
2849
  Use the SAME surfaceId as the main surface. Match action names to button action event names.`;
2850
+ /**
2851
+ * When UI helps the user, for both transports: a light nudge to reach for UI
2852
+ * where it conveys the answer better than prose, and to stay in prose
2853
+ * otherwise.
2854
+ */
2855
+ const GENERATIVE_UI_WHEN_TO_SHOW = "Show UI when it conveys the answer better than prose: to illustrate a concept (a diagram, a chart of how something changes), to compare options side by side, to let the user explore or adjust values, or to collect input. A small, focused surface next to your explanation often lands better than a long description. Reply in prose alone for a quick fact, a short answer, or conversation, and never add UI only as decoration.";
2856
+ /** Description of the context entry that carries `GENERATIVE_UI_MARKDOWN_GUIDELINES`. */
2857
+ const GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION = "Generative UI markdown guide: how to write UI surfaces inside ```a2ui code fences in a normal markdown reply.";
2858
+ /**
2859
+ * Description of the context entry that carries the compact component schema
2860
+ * in the markdown transport.
2861
+ *
2862
+ * It must not equal `A2UI_SCHEMA_CONTEXT_DESCRIPTION` (the key that
2863
+ * `@ag-ui/a2ui-middleware` stamps for tool mode). The LangGraph and Strands
2864
+ * adapters find that exact string and move the entry into
2865
+ * `state["ag-ui"]["a2ui_schema"]` for the `render_a2ui` tool, so it never
2866
+ * gets to the system prompt. The markdown transport has no tool, so the
2867
+ * schema must stay ordinary context that the model reads as App Context.
2868
+ */
2869
+ const GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION = "Generative UI component schema: the components, props, events, slots, functions, and targets that ```a2ui code fences can use, and the surfaces that already exist.";
2870
+ /** Every optional rule group. Use it when the manifest is not known. */
2871
+ const ALL_GENERATIVE_UI_GUIDE_FEATURES = {
2872
+ functions: true,
2873
+ events: true,
2874
+ templates: true,
2875
+ checks: true
2876
+ };
2877
+ /**
2878
+ * The optional parts of A2UI that a manifest uses, so that a guide sends only
2879
+ * the rules that the model can apply.
2880
+ *
2881
+ * @param manifest - The components and the mounted functions of a run.
2882
+ * @returns Which optional rule groups the guides include.
2883
+ *
2884
+ * @example
2885
+ * ```ts
2886
+ * const guide = buildGenerativeUIMarkdownGuidelines(
2887
+ * generativeUIGuideFeatures(manifest),
2888
+ * );
2889
+ * ```
2890
+ */
2891
+ function generativeUIGuideFeatures(manifest) {
2892
+ const components = Object.values(manifest.components);
2893
+ const hasChildList = (schema) => {
2894
+ if (Array.isArray(schema)) return schema.some(hasChildList);
2895
+ if (typeof schema !== "object" || schema === null) return false;
2896
+ const node = schema;
2897
+ if (node.$ref === A2UI_CHILD_LIST_REF) return true;
2898
+ return Object.values(node).some(hasChildList);
2899
+ };
2900
+ return {
2901
+ functions: Object.keys(manifest.functions).some((name) => !isA2UIBasicFunction(name)),
2902
+ events: components.some((c) => {
2903
+ var _c$events;
2904
+ return Object.keys((_c$events = c.events) !== null && _c$events !== void 0 ? _c$events : {}).length > 0;
2905
+ }),
2906
+ templates: components.some((c) => {
2907
+ var _c$slots;
2908
+ return Object.values((_c$slots = c.slots) !== null && _c$slots !== void 0 ? _c$slots : {}).includes("multiple") || hasChildList(c.props);
2909
+ }),
2910
+ checks: components.some((c) => {
2911
+ const properties = c.props.properties;
2912
+ return typeof properties === "object" && properties !== null && Object.prototype.hasOwnProperty.call(properties, "checks");
2913
+ })
2914
+ };
2915
+ }
2916
+ /** The first rules of every markdown guideline, before the optional groups. */
2917
+ const MARKDOWN_BASE_RULES = [
2918
+ "Write explanations as normal markdown prose outside the fences.",
2919
+ "Open a fence with ```a2ui to show the surface in the chat, at the place of the fence.",
2920
+ "Open a fence with ```a2ui target=<id> to show the surface in a named target. Use only target ids from the schema. When a target has \"components\", its surfaces can use only those components.",
2921
+ "Inside a fence, write one JSON object per line and nothing else. No comments, no trailing commas, no pretty-printing.",
2922
+ "Keep each operation whole on its line.",
2923
+ "Give every operation \"version\":\"v1.0\".",
2924
+ `Start a surface with one createSurface. Put all the initial data in "dataModel" and the "root" component in "components". Then write the children in updateComponents lines, so that they show while you write:
2925
+ \`\`\`a2ui
2926
+ {"version":"v1.0","createSurface":{"surfaceId":"plan-picker","dataModel":{ ...initial data... },"components":[{"id":"root","component":"<Name>","children":["seats","pick"]}]}}
2927
+ {"version":"v1.0","updateComponents":{"surfaceId":"plan-picker","components":[ ...the children... ]}}
2928
+ \`\`\``,
2929
+ "Keep \"dataModel\" flat: top-level keys such as \"seats\" or \"form\", never one wrapper object around everything. Check that every { and [ you open in a line is closed.",
2930
+ "Every surface renders from the component with id \"root\". Make every other component reachable from \"root\" through slots.",
2931
+ "Use unique ids. Do not make cycles. A component cannot be its own child.",
2932
+ "Write a component as one flat object: {\"id\":\"title\",\"component\":\"<Name>\",\"text\":\"Hello\"}.",
2933
+ "Put the component name in \"component\" (never \"type\"). Put props next to it, never inside a \"props\" object.",
2934
+ "A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component, and \"live\":\"polite\" only on text that changes by itself.",
2935
+ "Use only the components, props, events, and slots in the schema. A component with \"includesCommonProps\" also takes every prop in \"commonProps\".",
2936
+ "Give a prop a literal value, or bind it to the data model with {\"@path\":\"/x\"}. Never write {\"path\":\"/x\"} as a binding.",
2937
+ "A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Use only the functions under \"functions\" in the schema. Write a literal when the value never changes.",
2938
+ "formatString interpolates ${...}: {\"@call\":\"formatString\",\"args\":{\"value\":\"${/qty} × ${formatCurrency(value: /price, currency: 'EUR')}\"}}. Inside ${...}, a path has no quotes, a string has single quotes, and a function takes named args.",
2939
+ "${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}. Inside formatString: ${formatCurrency(value: calc(expression: 'seats * 29', seats: /seats), currency: 'USD')}. The UI then follows the user's input with no round trip.",
2940
+ "For a computed list (chart data, template items) use series. Its description under \"functions\" in the schema gives the rules and an example. Bind the \"data\" of a Chart or the \"items\" of a List to it; a template path stays a literal path.",
2941
+ "Bind a writable prop to let the user edit it: \"value\":{\"@path\":\"/form/email\"}. The user's input goes to that path.",
2942
+ "To change data, write updateDataModel with a \"path\" and a \"value\": {\"version\":\"v1.0\",\"updateDataModel\":{\"surfaceId\":\"plan-picker\",\"path\":\"/seats\",\"value\":12}}. Always give \"value\".",
2943
+ "Set \"value\":null to delete the key at \"path\"."
2944
+ ];
2945
+ /** The last rules of every markdown guideline, after the optional groups. */
2946
+ const MARKDOWN_CLOSING_RULES = [
2947
+ "The schema lists the surfaces that already exist under \"surfaces\". \"dataModel\" holds the values that the user entered: read them, and do not write those paths. \"rejected\" lists operations that the client dropped: send corrected operations in a new fence for that surfaceId. \"status\":\"deleted\" means the surface is gone: never use its id again. \"status\":\"failed\" means its createSurface was rejected: send a corrected createSurface with that id.",
2948
+ "Never make a surface that is only prose. Write headings, paragraphs, lists of text, intros, and summaries as markdown outside the fences, also between two fences.",
2949
+ "Put in a fence only what markdown cannot show: charts, tables, maps, images, badges, inputs, buttons, cards with controls.",
2950
+ "Use Card only for an interactive panel (controls, a form, a configurator). Put everything else in a plain layout component.",
2951
+ "Never wrap the whole reply in a fence."
2952
+ ];
2953
+ /**
2954
+ * Builds the markdown-transport guideline. The model writes A2UI v1.0
2955
+ * operations inside ```a2ui fences between normal markdown prose. The rules
2956
+ * for functions, events, and templates are left out when the manifest has
2957
+ * none of them, so the guideline stays small.
2958
+ *
2959
+ * @param features - The optional rule groups to include. Defaults to all.
2960
+ * @returns The guideline text, one rule per line.
2961
+ */
2962
+ function buildGenerativeUIMarkdownGuidelines(features = ALL_GENERATIVE_UI_GUIDE_FEATURES) {
2963
+ const { functions, events, templates, checks } = features;
2964
+ const rules = [...MARKDOWN_BASE_RULES];
2965
+ if (events) rules.push("Give an event prop an object: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} or {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}}. Never a flat {\"event\":\"<name>\"}.", functions ? "Use {\"functionCall\": ...} to run a function in the browser when the user clicks: an app function from the schema, or openUrl: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call." : "Use {\"functionCall\": ...} to open a URL when the user clicks: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call.", "Use {\"event\": ...} to send the interaction back to you as a user message. Put the text of that message in \"userMessage\": {\"event\":{\"name\":\"choose\",\"userMessage\":\"Show me the Team plan\"}}. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\".", "To send input values with an event, bind them in the context: \"context\":{\"email\":{\"@path\":\"/form/email\"}}.", "A button or other event prop without an event or functionCall does nothing.");
2966
+ if (checks) rules.push("Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email; a condition can also be a boolean {\"@path\"}. A failed check shows the message under the input and disables a Button that has the same checks.");
2967
+ rules.push("A prop typed componentId takes the id of another component, and a childList takes ids [\"a\",\"b\"]: \"child\":\"card\", \"children\":[\"a\",\"b\"], \"tabs\":[{\"title\":\"Specs\",\"child\":\"specs\"}].");
2968
+ if (templates) rules.push("To repeat a component for each item of a list, give a childList a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}.", "Inside a template, paths are relative to the item (\"name\", not \"/name\").", "Inside a template, {\"@call\":\"@index\"} gives the position of the item, from 0. To count from 1, write {\"@call\":\"@index\",\"args\":{\"offset\":1}}.");
2969
+ rules.push("Updating a component replaces all of its props. Send every prop again.", "To change a surface in this reply, write another fence with the same surfaceId. Do not send createSurface again. The surface changes where it already is. A surface in a target can also be changed from a later reply; a chat surface cannot, because the chat is a transcript: a later reply with the same surfaceId makes a new surface.", "Use a new surfaceId for a different view. Never use a surfaceId again, also after the surface is deleted.");
2970
+ if (functions && GENERATIVE_UI_AGENT_FUNCTION_CALLS) rules.push("To run an app function now, with no click, write a callRendererFunction line in a fence: {\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}. It needs no surface.", "Give every callRendererFunction a new functionCallId. Call only a function from the schema with \"callers\": \"UI or agent\" or \"agent only\"; a function without \"callers\" is for the UI only. A function with \"callers\": \"agent only\" is only for callRendererFunction: do not bind an event to it.", "The result of a callRendererFunction comes back to you as a developer message: {\"version\":\"v1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Then you get a new turn.", "Do not guess the result of a callRendererFunction. Wait for the developer message.");
2971
+ rules.push(...MARKDOWN_CLOSING_RULES);
2972
+ return `You can show interactive UI in your reply. Write A2UI operations inside a fenced code block tagged a2ui.
2973
+
2974
+ ${GENERATIVE_UI_WHEN_TO_SHOW}
2975
+
2976
+ RULES
2977
+ ${rules.map((rule) => `- ${rule}`).join("\n")}
2978
+ `;
2979
+ }
2980
+ /**
2981
+ * The markdown-transport guideline with every rule group. A run sends
2982
+ * `buildGenerativeUIMarkdownGuidelines` for its own manifest instead.
2983
+ */
2984
+ const GENERATIVE_UI_MARKDOWN_GUIDELINES = buildGenerativeUIMarkdownGuidelines();
2985
+
2986
+ //#endregion
2987
+ //#region src/a2ui-envelope.ts
2988
+ /**
2989
+ * The generative UI envelope that the client sends on every run as
2990
+ * `forwardedProps.copilotkit.ui`. It has the A2UI v1.0 renderer capabilities
2991
+ * shape, so a backend that speaks A2UI v1.0 can read the catalog as it is.
2992
+ * CopilotKit data goes in `metadata.extensions`, under `copilotkit_` keys.
2993
+ * The runtime reads it to pick the transport and to build the guide.
2994
+ */
2995
+ /** Top-level `forwardedProps` key that holds the CopilotKit run properties. */
2996
+ const COPILOTKIT_FORWARDED_PROPS_KEY = "copilotkit";
2997
+ /** Version of the envelope shape (not of the UI protocol that it carries). */
2998
+ const COPILOTKIT_UI_ENVELOPE_FORMAT = 3;
2999
+ function isOptionalString(value) {
3000
+ return value === void 0 || typeof value === "string";
3001
+ }
3002
+ function isNonEmptyString(value) {
3003
+ return typeof value === "string" && value !== "";
3004
+ }
3005
+ function isRecordOf(value, isEntry) {
3006
+ return isRecord(value) && Object.values(value).every(isEntry);
3007
+ }
3008
+ /** A function, or an event of a component: a description and a parameter schema. */
3009
+ function isSchemaEntry(value) {
3010
+ return isRecord(value) && isRecord(value.parameters) && isOptionalString(value.description);
3011
+ }
3012
+ function isSlotKind(value) {
3013
+ return value === "single" || value === "multiple";
3014
+ }
3015
+ /**
3016
+ * `validateOperation` reads `properties` and `required` of a props schema,
3017
+ * so those two must have the right shape when they are there.
3018
+ */
3019
+ function isPropsSchema(value) {
3020
+ return isRecord(value) && (value.properties === void 0 || isRecord(value.properties)) && (value.required === void 0 || Array.isArray(value.required) && value.required.every((name) => typeof name === "string"));
3021
+ }
3022
+ function isComponentManifest(value) {
3023
+ var _value$props$properti, _value$slots, _value$events;
3024
+ if (!isRecord(value) || !isPropsSchema(value.props) || !isOptionalString(value.description) || value.events !== void 0 && !isRecordOf(value.events, isSchemaEntry) || value.slots !== void 0 && !isRecordOf(value.slots, isSlotKind)) return false;
3025
+ const order = value.parameterOrder;
3026
+ if (order === void 0) return true;
3027
+ const keys = new Set([
3028
+ ...Object.keys((_value$props$properti = value.props.properties) !== null && _value$props$properti !== void 0 ? _value$props$properti : {}),
3029
+ ...Object.keys((_value$slots = value.slots) !== null && _value$slots !== void 0 ? _value$slots : {}),
3030
+ ...Object.keys((_value$events = value.events) !== null && _value$events !== void 0 ? _value$events : {})
3031
+ ]);
3032
+ return Array.isArray(order) && new Set(order).size === order.length && order.every((key) => typeof key === "string" && keys.has(key));
3033
+ }
3034
+ function isInlineCatalog(value) {
3035
+ return isRecord(value) && isNonEmptyString(value.catalogId) && value.protocolVersion === "1.0" && (value.components === void 0 || isRecordOf(value.components, isComponentManifest)) && isRecordOf(value.functions, isSchemaEntry) && isOptionalString(value.instructions);
3036
+ }
3037
+ function isCapabilities(value) {
3038
+ return isRecord(value) && Array.isArray(value.supportedCatalogIds) && value.supportedCatalogIds.length > 0 && value.supportedCatalogIds.every(isNonEmptyString) && (value.inlineCatalogs === void 0 || Array.isArray(value.inlineCatalogs) && value.inlineCatalogs.every(isInlineCatalog));
3039
+ }
3040
+ /** A short list of component names. */
3041
+ function isComponentNameList(value) {
3042
+ return Array.isArray(value) && value.length <= GENERATIVE_UI_MAX_TARGET_COMPONENTS && value.every(isNonEmptyString);
3043
+ }
3044
+ function isTarget(value) {
3045
+ return isRecord(value) && isNonEmptyString(value.id) && (value.kind === "chat" || value.kind === "inline") && isOptionalString(value.description) && (value.components === void 0 || isComponentNameList(value.components));
3046
+ }
3047
+ /** A short list of short strings. The summary limits keep the guide small. */
3048
+ function isRejectionList(value) {
3049
+ return Array.isArray(value) && value.length <= GENERATIVE_UI_MAX_SUMMARY_REJECTIONS && value.every((entry) => typeof entry === "string" && entry.length <= GENERATIVE_UI_MAX_REJECTION_LENGTH);
3050
+ }
3051
+ function isSurfaceEntry(value) {
3052
+ return isRecord(value) && isNonEmptyString(value.target) && (value.dataModel === void 0 || isRecord(value.dataModel)) && (value.rejected === void 0 || isRejectionList(value.rejected)) && (value.status === void 0 || value.status === "deleted" || value.status === "failed");
3053
+ }
3054
+ /** Checks the `copilotkit_` keys only. Other extensions can be there too. */
3055
+ function isExtensions(value) {
3056
+ return isRecord(value) && value.copilotkit_format === COPILOTKIT_UI_ENVELOPE_FORMAT && (value.copilotkit_transport === "tool" || value.copilotkit_transport === "markdown") && Array.isArray(value.copilotkit_targets) && value.copilotkit_targets.every(isTarget) && isRecordOf(value.copilotkit_surfaces, isSurfaceEntry) && typeof value.copilotkit_contextSent === "boolean";
3057
+ }
3058
+ function isEnvelope(value) {
3059
+ return isRecord(value) && isCapabilities(value["v1.0"]) && isRecord(value.metadata) && isExtensions(value.metadata.extensions);
3060
+ }
3061
+ /**
3062
+ * Reads the generative UI envelope from the `forwardedProps` of a run.
3063
+ *
3064
+ * The envelope comes from the client, so it is not trusted: every field is
3065
+ * checked. Returns `undefined` when the envelope is not there, or when it is
3066
+ * malformed (for example a wrong `copilotkit_format` or
3067
+ * `copilotkit_transport`, or no catalog id).
3068
+ *
3069
+ * @param forwardedProps - The `forwardedProps` of the run input.
3070
+ *
3071
+ * @example
3072
+ * ```ts
3073
+ * const envelope = readCopilotKitUIEnvelope(input.forwardedProps);
3074
+ * if (envelope?.metadata.extensions.copilotkit_transport === "markdown") {
3075
+ * // The model writes ```a2ui fences. Add no render tool.
3076
+ * }
3077
+ * ```
3078
+ */
3079
+ function readCopilotKitUIEnvelope(forwardedProps) {
3080
+ if (!isRecord(forwardedProps)) return void 0;
3081
+ const namespace = forwardedProps[COPILOTKIT_FORWARDED_PROPS_KEY];
3082
+ if (!isRecord(namespace)) return void 0;
3083
+ const envelope = namespace.ui;
3084
+ return isEnvelope(envelope) ? envelope : void 0;
3085
+ }
3086
+ /**
3087
+ * Turns an envelope into the manifest that the runtime and the prompts use.
3088
+ *
3089
+ * The catalog is the first of `supportedCatalogIds`, and `catalogIds` lists
3090
+ * all of them. The components, functions, and instructions come from the
3091
+ * inline catalog of the first id.
3092
+ * With no such inline catalog, there are no components and no functions.
3093
+ *
3094
+ * The result also has:
3095
+ * - `transport` and `contextSent`, from the extensions.
3096
+ * - `instructions`, when the inline catalog has them.
3097
+ * - `hasComponents`: false when the client left the component schemas out.
3098
+ * The runtime cannot check operations without them.
3099
+ * - `action`: the A2UI action message of the user event that started the
3100
+ * run, when one did.
3101
+ *
3102
+ * @param envelope - An envelope from `readCopilotKitUIEnvelope`.
3103
+ *
3104
+ * @example
3105
+ * ```ts
3106
+ * const envelope = readCopilotKitUIEnvelope(input.forwardedProps);
3107
+ * const manifest = envelope && envelopeToManifest(envelope);
3108
+ * if (manifest?.transport === "tool" && manifest.hasComponents) {
3109
+ * // Add the render tool and validate operations against manifest.components.
3110
+ * }
3111
+ * ```
3112
+ */
3113
+ function envelopeToManifest(envelope) {
3114
+ var _catalog$components, _catalog$functions;
3115
+ const { supportedCatalogIds, inlineCatalogs } = envelope["v1.0"];
3116
+ const catalogId = supportedCatalogIds[0];
3117
+ const catalog = inlineCatalogs === null || inlineCatalogs === void 0 ? void 0 : inlineCatalogs.find((entry) => entry.catalogId === catalogId);
3118
+ const extensions = envelope.metadata.extensions;
3119
+ return {
3120
+ catalogId,
3121
+ catalogIds: supportedCatalogIds,
3122
+ components: (_catalog$components = catalog === null || catalog === void 0 ? void 0 : catalog.components) !== null && _catalog$components !== void 0 ? _catalog$components : {},
3123
+ functions: (_catalog$functions = catalog === null || catalog === void 0 ? void 0 : catalog.functions) !== null && _catalog$functions !== void 0 ? _catalog$functions : {},
3124
+ targets: extensions.copilotkit_targets,
3125
+ surfaces: extensions.copilotkit_surfaces,
3126
+ transport: extensions.copilotkit_transport,
3127
+ contextSent: extensions.copilotkit_contextSent,
3128
+ instructions: catalog === null || catalog === void 0 ? void 0 : catalog.instructions,
3129
+ hasComponents: (catalog === null || catalog === void 0 ? void 0 : catalog.components) !== void 0,
3130
+ ...extensions.copilotkit_action === void 0 ? {} : { action: extensions.copilotkit_action }
3131
+ };
3132
+ }
2426
3133
 
2427
3134
  //#endregion
2428
3135
  //#region src/open-generative-ui-prompts.ts
2429
3136
  /** Shared generation contract for all Open Generative UI renderers. */
2430
3137
  const GENERATE_SANDBOXED_UI_DESCRIPTION = "Generate sandboxed UI. IMPORTANT: The generated code runs in a sandboxed iframe WITHOUT same-origin access. Do NOT use localStorage, sessionStorage, document.cookie, IndexedDB, or fetch/XMLHttpRequest to same-origin URLs. To communicate with the host application, use Websandbox.connection.remote.<functionName>(args) which returns a Promise.\n\nYou CAN use external libraries from CDNs by including <script> or <link> tags in the HTML <head> (e.g., Chart.js, D3, Three.js, x-data-spreadsheet, etc.). CDN resources load normally inside the sandbox.\n\nPARAMETER ORDER IS CRITICAL — generate parameters in exactly this order:\n1. initialHeight + placeholderMessages (shown to user while generating)\n2. css (all styles FIRST — the user sees a placeholder until CSS is complete)\n3. html (streams in live — the user watches the UI build as HTML is generated)\n4. jsFunctions (reusable helper functions)\n5. jsExpressions (applied one-by-one — the user sees each expression take effect)\n\nINITIALIZATION CONTRACT: jsFunctions and jsExpressions run after the final HTML DOM is ready, in both live generation and saved-thread replay. Define reusable functions in jsFunctions, then initialize the UI directly in the first jsExpressions entry (for example, initializeCalculator()). Attach click/keyboard handlers and set initial display values there. Do NOT wait for DOMContentLoaded, window.onload, or the load event in jsFunctions or jsExpressions: these events may already have fired. Each expression is executed once per rendered sandbox; later expressions must not repeat initialization or reattach the same handlers. Keep initialization self-contained so a new sandbox can reconstruct the UI when a saved thread is opened. If a library loads asynchronously, initialize from its explicit load promise instead of waiting for document readiness.\n\nINTERACTION CONTRACT: Every visible interactive control needs a working handler, including controls created during initialization. If the handlers are supplied through jsFunctions/jsExpressions, initialize them in the first expression; if supplied by an inline HTML script, ensure it runs when the final sandbox mounts and replays. Every user action must update the visible UI to reflect its completed result, including success and error paths. Changing a JavaScript variable alone does not update the DOM. After changing state, call the rendering function or update the displayed element directly. When delegating clicks from a parent element, resolve the clicked control with closest('button') so clicks on nested labels and values work. For a calculator, pressing = must replace the visible expression with the computed answer; metric shortcuts must visibly insert their values. Trace each button handler through its final display update before emitting the tool call.";
2431
3138
 
3139
+ //#endregion
3140
+ //#region src/generative-ui/validate-operation.ts
3141
+ const OPERATION_KINDS = [
3142
+ "createSurface",
3143
+ "updateComponents",
3144
+ "updateDataModel",
3145
+ "deleteSurface",
3146
+ "callRendererFunction"
3147
+ ];
3148
+ const OK = { ok: true };
3149
+ const fail = (reason) => ({
3150
+ ok: false,
3151
+ reason
3152
+ });
3153
+ /** Models write the v0.9 binding from habit. The reason names the v1.0 form. */
3154
+ const V09_PATH_REASON = "bind data with {\"@path\": \"/x\"}, not {\"path\": \"/x\"}";
3155
+ function hasOwn(record, key) {
3156
+ return Object.prototype.hasOwnProperty.call(record, key);
3157
+ }
3158
+ /**
3159
+ * Reads an own property only. Model-controlled keys such as "constructor" or
3160
+ * "toString" must not resolve to Object.prototype members.
3161
+ */
3162
+ function ownValue(record, key) {
3163
+ return record && hasOwn(record, key) ? record[key] : void 0;
3164
+ }
3165
+ function getOperationKind(op) {
3166
+ if (!isRecord(op)) return void 0;
3167
+ const kinds = OPERATION_KINDS.filter((kind) => kind in op);
3168
+ return kinds.length === 1 ? kinds[0] : void 0;
3169
+ }
3170
+ /** The `surfaceId` of a surface operation. `callRendererFunction` has none. */
3171
+ function getOperationSurfaceId(op) {
3172
+ if (!isRecord(op)) return void 0;
3173
+ const kind = getOperationKind(op);
3174
+ if (!kind) return void 0;
3175
+ const payload = op[kind];
3176
+ return isRecord(payload) && typeof payload.surfaceId === "string" ? payload.surfaceId : void 0;
3177
+ }
3178
+ /** `{ "@path": "/x" }`: a data-model binding. */
3179
+ function isPathBinding(value) {
3180
+ return isRecord(value) && typeof value["@path"] === "string" && Object.keys(value).length === 1;
3181
+ }
3182
+ /** `{ "path": "/x" }`: the v0.9 binding, which v1.0 does not accept. */
3183
+ function isV09PathBinding(value) {
3184
+ return isRecord(value) && typeof value.path === "string" && Object.keys(value).length === 1;
3185
+ }
3186
+ /**
3187
+ * `{ "@call": "@index" }` or `{ "@call": "@index", "args": { "offset": 1 } }`:
3188
+ * the 0-based position of the item in a template, plus `offset`.
3189
+ */
3190
+ function isIndexCall(value) {
3191
+ if (!isRecord(value) || value["@call"] !== "@index") return false;
3192
+ if (!Object.keys(value).every((key) => key === "@call" || key === "args")) return false;
3193
+ const { args } = value;
3194
+ if (args === void 0) return true;
3195
+ return isRecord(args) && Object.keys(args).every((key) => key === "offset") && (args.offset === void 0 || Number.isFinite(args.offset));
3196
+ }
3197
+ function isActionBinding(value) {
3198
+ return isRecord(value) && Object.keys(value).length === 1 && (isRecord(value.functionCall) || isRecord(value.event));
3199
+ }
3200
+ /**
3201
+ * Checks one A2UI v1.0 operation against the catalog and the surfaces that
3202
+ * exist. The operation comes from the model, so nothing in it is trusted.
3203
+ *
3204
+ * @param op - The operation, as parsed from JSON.
3205
+ * @param options - The catalog, the known and created surfaces, the
3206
+ * functions that the UI can call, and the components that the target of
3207
+ * the surface takes.
3208
+ *
3209
+ * @example
3210
+ * ```ts
3211
+ * const result = validateOperation(op, { manifest, knownSurfaces });
3212
+ * if (!result.ok) rejected.push({ index, reason: result.reason });
3213
+ * ```
3214
+ */
3215
+ function validateOperation(op, options) {
3216
+ if (!isRecord(op)) return fail("operation must be a JSON object");
3217
+ if (op.version !== A2UI_VERSION) return fail(versionProblem(op.version));
3218
+ const kind = getOperationKind(op);
3219
+ if (!kind) return fail(`operation must contain exactly one of ${OPERATION_KINDS.join(", ")}`);
3220
+ const payload = op[kind];
3221
+ if (kind === "callRendererFunction") {
3222
+ if (!GENERATIVE_UI_AGENT_FUNCTION_CALLS) return fail(GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON);
3223
+ return validateRendererFunctionCall(payload, options);
3224
+ }
3225
+ if (!isRecord(payload) || typeof payload.surfaceId !== "string" || !payload.surfaceId) return fail(`${kind}.surfaceId is required`);
3226
+ const surfaceId = payload.surfaceId;
3227
+ if (kind === "createSurface") return validateCreateSurface(payload, surfaceId, options);
3228
+ if (!options.knownSurfaces.has(surfaceId)) return fail(`surface "${surfaceId}" does not exist; send createSurface first`);
3229
+ switch (kind) {
3230
+ case "deleteSurface": return OK;
3231
+ case "updateDataModel": return validateDataModelUpdate(payload);
3232
+ case "updateComponents": return validateComponents(payload.components, "updateComponents.components", options);
3233
+ }
3234
+ }
3235
+ function versionProblem(version) {
3236
+ return typeof version === "string" ? `unsupported version "${version}"; use "${A2UI_VERSION}"` : `operation needs "version":"${A2UI_VERSION}"`;
3237
+ }
3238
+ /** A `catalogId` can name the catalog of the run or one of its bases. */
3239
+ function catalogProblem(catalogId, manifest) {
3240
+ var _manifest$catalogIds;
3241
+ const ids = (_manifest$catalogIds = manifest.catalogIds) !== null && _manifest$catalogIds !== void 0 ? _manifest$catalogIds : [manifest.catalogId];
3242
+ if (catalogId === void 0 || ids.includes(catalogId)) return;
3243
+ const names = ids.map((id) => `"${id}"`).join(", ");
3244
+ const use = ids.length === 1 ? names : `one of: ${names}`;
3245
+ return `unknown catalog "${String(catalogId)}"; leave out catalogId or use ${use}`;
3246
+ }
3247
+ function validateCreateSurface(payload, surfaceId, options) {
3248
+ var _options$createdSurfa;
3249
+ if (options.knownSurfaces.has(surfaceId)) return fail(`surface "${surfaceId}" already exists`);
3250
+ if ((_options$createdSurfa = options.createdSurfaces) === null || _options$createdSurfa === void 0 ? void 0 : _options$createdSurfa.has(surfaceId)) return fail(`surface id "${surfaceId}" was used before; use a new surfaceId`);
3251
+ const catalogReason = catalogProblem(payload.catalogId, options.manifest);
3252
+ if (catalogReason) return fail(catalogReason);
3253
+ const { dataModel, components } = payload;
3254
+ if (dataModel !== void 0 && !isRecord(dataModel)) return fail("createSurface.dataModel must be a JSON object");
3255
+ if (components === void 0) return OK;
3256
+ return validateComponents(components, "createSurface.components", options);
3257
+ }
3258
+ function validateRendererFunctionCall(payload, options) {
3259
+ if (!(isRecord(payload) && typeof payload.functionCallId === "string" && payload.functionCallId !== "")) return fail("callRendererFunction.functionCallId must be a non-empty string");
3260
+ const reason = functionCallProblem(payload.callFunction, "callRendererFunction.callFunction", options);
3261
+ return reason ? fail(reason) : OK;
3262
+ }
3263
+ const FORBIDDEN_SEGMENTS = new Set([
3264
+ "__proto__",
3265
+ "constructor",
3266
+ "prototype"
3267
+ ]);
3268
+ function decodeSegment(segment) {
3269
+ return segment.replace(/~([01])/g, (_, g) => g === "1" ? "/" : "~");
3270
+ }
3271
+ function validateDataModelUpdate(payload) {
3272
+ var _payload$path;
3273
+ if (payload.value === void 0) return fail("updateDataModel.value is required; use \"value\":null to delete");
3274
+ const path = (_payload$path = payload.path) !== null && _payload$path !== void 0 ? _payload$path : "/";
3275
+ if (typeof path !== "string" || !path.startsWith("/")) return fail("updateDataModel.path must be an absolute JSON pointer");
3276
+ if (path === "/") {
3277
+ if (!isRecord(payload.value)) return fail("a root updateDataModel value must be a JSON object");
3278
+ return OK;
3279
+ }
3280
+ const reason = pathProblem(path, "updateDataModel.path");
3281
+ return reason ? fail(reason) : OK;
3282
+ }
3283
+ /**
3284
+ * Checks the segments of an absolute JSON pointer ("/a/b") or of a path
3285
+ * relative to a template item ("a/b"). `label` names the field in the reason.
3286
+ */
3287
+ function pathProblem(path, label) {
3288
+ const segments = (path.startsWith("/") ? path.slice(1) : path).split("/");
3289
+ if (segments.some((segment) => segment === "")) return `${label} must not contain empty segments`;
3290
+ const forbidden = segments.map(decodeSegment).find((segment) => FORBIDDEN_SEGMENTS.has(segment));
3291
+ if (forbidden !== void 0) return `path segment "${forbidden}" is not allowed in ${label}`;
3292
+ }
3293
+ function validateComponents(components, label, options) {
3294
+ if (!Array.isArray(components) || components.length === 0) return fail(`${label} must be a non-empty array`);
3295
+ const ids = /* @__PURE__ */ new Set();
3296
+ for (const node of components) {
3297
+ if (!isRecord(node)) return fail("component must be a JSON object");
3298
+ const { id } = node;
3299
+ if (typeof id !== "string" || !id) return fail("id is required");
3300
+ const reason = nodeProblem(node, id, options);
3301
+ if (reason) return fail(`component "${id}": ${reason}`);
3302
+ if (ids.has(id)) return fail(`component "${id}" appears twice in one update`);
3303
+ ids.add(id);
3304
+ }
3305
+ return OK;
3306
+ }
3307
+ function nodeProblem(node, id, options) {
3308
+ if (typeof node.component !== "string") return "component type is required";
3309
+ const entry = ownValue(options.manifest.components, node.component);
3310
+ if (!entry) return `unknown component "${node.component}"`;
3311
+ const { allowedComponents } = options;
3312
+ if (allowedComponents && !allowedComponents.names.has(node.component)) {
3313
+ const names = [...allowedComponents.names].join(", ") || "none";
3314
+ return `"${node.component}" is not allowed in target "${allowedComponents.target}"; use one of: ${names}`;
3315
+ }
3316
+ const { properties, required } = entry.props;
3317
+ const propNames = isRecord(properties) ? Object.keys(properties) : [];
3318
+ const props = Object.entries(node);
3319
+ for (const [key, value] of props) {
3320
+ if (key === "id" || key === "component") continue;
3321
+ if (key === "catalogId") {
3322
+ const reason = catalogProblem(value, options.manifest);
3323
+ if (reason) return `${key}: ${reason}`;
3324
+ continue;
3325
+ }
3326
+ if (key === "metadata") {
3327
+ if (!(isRecord(value) && (value.extensions === void 0 || isRecord(value.extensions)))) return "metadata must be { \"extensions\": { ... } }";
3328
+ continue;
3329
+ }
3330
+ if (key === "accessibility") {
3331
+ const reason = accessibilityProblem(value);
3332
+ if (reason) return `${key}: ${reason}`;
3333
+ continue;
3334
+ }
3335
+ if (ownValue(entry.events, key)) {
3336
+ const reason = actionBindingProblem(value, options);
3337
+ if (reason) return `${key}: ${reason}`;
3338
+ continue;
3339
+ }
3340
+ const slot = ownValue(entry.slots, key);
3341
+ if (slot) {
3342
+ const reason = slotProblem(value, slot, id);
3343
+ if (reason) return `${key}: ${reason}`;
3344
+ continue;
3345
+ }
3346
+ if (!propNames.includes(key)) return `unknown prop "${key}"`;
3347
+ if (isV09PathBinding(value)) return `${key}: ${V09_PATH_REASON}`;
3348
+ const call = findForbiddenCall(value, { allowValueFunctions: true });
3349
+ if (call !== void 0) return `${key}: ${call}; a data prop can call only ${VALUE_FUNCTION_LIST}`;
3350
+ }
3351
+ for (const ref of childRefsOf(entry.props)) {
3352
+ const reason = childRefProblem(node, ref, id);
3353
+ if (reason) return reason;
3354
+ }
3355
+ const requiredNames = Array.isArray(required) ? required : [];
3356
+ for (const name of requiredNames) if (typeof name === "string" && !(name in node)) return `missing required prop "${name}"`;
3357
+ }
3358
+ const ACCESSIBILITY_KEYS = [
3359
+ "label",
3360
+ "description",
3361
+ "live",
3362
+ "hidden"
3363
+ ];
3364
+ const LIVE_VALUES = [
3365
+ "off",
3366
+ "polite",
3367
+ "assertive"
3368
+ ];
3369
+ /**
3370
+ * Checks the `accessibility` of a component envelope: `label` and
3371
+ * `description` are strings or dynamic values, `live` is one of the ARIA
3372
+ * values, `hidden` is a boolean or a dynamic value.
3373
+ */
3374
+ function accessibilityProblem(value) {
3375
+ if (!isRecord(value)) return "must be { \"label\": \"...\", \"description\": \"...\", \"live\": \"polite\", \"hidden\": false }";
3376
+ const isDynamic = (field) => isPathBinding(field) || isCallBinding(field);
3377
+ for (const [key, field] of Object.entries(value)) {
3378
+ if (!ACCESSIBILITY_KEYS.includes(key)) return `unknown key "${key}"`;
3379
+ if (isV09PathBinding(field)) return `${key}: ${V09_PATH_REASON}`;
3380
+ if (isDynamic(field)) {
3381
+ const call = findForbiddenCall(field, { allowValueFunctions: true });
3382
+ if (call !== void 0) return `${key}: ${call}`;
3383
+ continue;
3384
+ }
3385
+ if (key === "live") {
3386
+ if (typeof field !== "string" || !LIVE_VALUES.includes(field)) return `live must be one of ${LIVE_VALUES.join(", ")}`;
3387
+ } else if (key === "hidden") {
3388
+ if (typeof field !== "boolean") return "hidden must be a boolean";
3389
+ } else if (typeof field !== "string") return `${key} must be a string`;
3390
+ }
3391
+ }
3392
+ function actionBindingProblem(value, options) {
3393
+ if (!isRecord(value)) return "must be an action object";
3394
+ const keys = Object.keys(value);
3395
+ if (!(keys.length === 1 && (keys[0] === "functionCall" || keys[0] === "event"))) return "must be { \"event\": ... } or { \"functionCall\": ... }";
3396
+ if (keys[0] === "functionCall") return functionCallProblem(value.functionCall, "functionCall", options);
3397
+ return eventProblem(value.event);
3398
+ }
3399
+ /**
3400
+ * Checks `{ "@call": "<function>", "args": { ... } }`. `label` names the
3401
+ * field in the reason.
3402
+ */
3403
+ function functionCallProblem(call, label, options) {
3404
+ if (!isRecord(call)) return `${label} must be { "@call": "<function>", "args": { ... } }`;
3405
+ const name = call["@call"];
3406
+ if (typeof name !== "string" || !name) return typeof call.call === "string" ? `${label} names the function with "@call", not "call"` : `${label}["@call"] must be a function name`;
3407
+ const { args } = call;
3408
+ if (args !== void 0 && !isRecord(args)) return `${label}.args must be an object`;
3409
+ const catalogReason = catalogProblem(call.catalogId, options.manifest);
3410
+ if (catalogReason) return `${label}: ${catalogReason}`;
3411
+ const argEntries = Object.entries(args !== null && args !== void 0 ? args : {});
3412
+ for (const [key, arg] of argEntries) if (isV09PathBinding(arg)) return `${label}.args.${key}: ${V09_PATH_REASON}`;
3413
+ const appFunctions = options.functions;
3414
+ const declared = appFunctions !== void 0 && hasOwn(appFunctions, name) ? appFunctions[name] : void 0;
3415
+ const builtIn = declared === void 0 && hasOwn(GENERATIVE_UI_FUNCTIONS, name) ? GENERATIVE_UI_FUNCTIONS[name] : void 0;
3416
+ if (declared === void 0 && builtIn === void 0) return appFunctions === void 0 ? void 0 : `function "${name}" is not exposed to generative UI`;
3417
+ if (declared === void 0 && appFunctions === void 0) return void 0;
3418
+ return callerProblem(name, declared !== null && declared !== void 0 ? declared : builtIn, label.startsWith("callRendererFunction") ? "agent" : "renderer");
3419
+ }
3420
+ /**
3421
+ * Why `caller` may not call a function with these permissions, or
3422
+ * `undefined` when it may. The dispatcher gives the same reasons at run
3423
+ * time, for the calls that are not validated against a function list.
3424
+ */
3425
+ function callerProblem(name, fn, caller) {
3426
+ const callers = functionCallers(fn);
3427
+ if (caller === "agent" && !callers.agent) return fn.requiresUserActivation ? `function "${name}" runs only from a user gesture; the agent cannot call it` : `function "${name}" runs only in the UI (allowedCallers "rendererOnly"); the agent cannot call it`;
3428
+ if (caller === "renderer" && !callers.renderer) return `function "${name}" runs only for the agent (allowedCallers "agentOnly"); the UI cannot call it`;
3429
+ }
3430
+ function eventProblem(event) {
3431
+ if (!isRecord(event) || typeof event.name !== "string" || !event.name) return "event.name is required";
3432
+ const { userMessage, context } = event;
3433
+ if (!(userMessage === void 0 || typeof userMessage === "string" || isPathBinding(userMessage) || isRecord(userMessage) && typeof userMessage["@call"] === "string" && findForbiddenCall(userMessage, { allowValueFunctions: true }) === void 0)) return isV09PathBinding(userMessage) ? `event.userMessage: ${V09_PATH_REASON}` : "event.userMessage must be a string, {\"@path\": \"/x\"} or a function value";
3434
+ if (context === void 0) return void 0;
3435
+ if (!isRecord(context)) return "event.context must be an object";
3436
+ const entries = Object.entries(context);
3437
+ for (const [key, entry] of entries) {
3438
+ if (isV09PathBinding(entry)) return `event.context.${key}: ${V09_PATH_REASON}`;
3439
+ const call = findForbiddenCall(entry, { allowValueFunctions: true });
3440
+ if (call !== void 0) return `event.context.${key}: ${call}; a context value can call only ${VALUE_FUNCTION_LIST}`;
3441
+ }
3442
+ }
3443
+ function slotProblem(value, kind, ownId) {
3444
+ const isTemplate = isRecord(value) && "componentId" in value;
3445
+ if (kind === "single" && isTemplate) return "a template { \"componentId\", \"path\" } is only allowed in a \"multiple\" slot";
3446
+ if (kind === "multiple" && isTemplate) return templateProblem(value, ownId);
3447
+ if (kind === "multiple" && !Array.isArray(value)) return "must be an array of component ids or a template { \"componentId\", \"path\" }";
3448
+ const ids = kind === "multiple" && Array.isArray(value) ? value : [value];
3449
+ for (const id of ids) {
3450
+ if (typeof id !== "string" || !id) return "must reference component ids (strings)";
3451
+ if (id === ownId) return "a component cannot be its own child";
3452
+ }
3453
+ }
3454
+ function templateProblem(template, ownId) {
3455
+ if (!Object.keys(template).every((key) => key === "componentId" || key === "path")) return "a template takes only \"componentId\" and \"path\"";
3456
+ const { componentId, path } = template;
3457
+ if (typeof componentId !== "string" || !componentId) return "template componentId must be a component id";
3458
+ if (componentId === ownId) return "a component cannot be its own child";
3459
+ if (typeof path !== "string" || !path) return "template path must be a JSON pointer or a relative path";
3460
+ return pathProblem(path, "template path");
3461
+ }
3462
+ const VALUE_FUNCTION_LIST = `@index and the built-in functions (${Object.keys(GENERATIVE_UI_FUNCTIONS).filter(isA2UIValueFunction).join(", ")})`;
3463
+ /**
3464
+ * The reason for the first function call in `value` that a data value may
3465
+ * not make, at any depth, or `undefined`. A data value may call `@index`
3466
+ * and, with `allowValueFunctions`, the basic functions that need no user
3467
+ * gesture; the renderer resolves those. An app function, `openUrl`, or an
3468
+ * event binding is not a value.
3469
+ */
3470
+ function findForbiddenCall(value, options) {
3471
+ if (Array.isArray(value)) {
3472
+ for (const item of value) {
3473
+ const reason = findForbiddenCall(item, options);
3474
+ if (reason !== void 0) return reason;
3475
+ }
3476
+ return;
3477
+ }
3478
+ if (!isRecord(value)) return void 0;
3479
+ if (isIndexCall(value)) return void 0;
3480
+ if (value["@call"] === "@index") return "@index takes only an offset";
3481
+ if (typeof value.call === "string") return "name the function with \"@call\", not \"call\"";
3482
+ if ("functionCall" in value) return "an event binding is not a value";
3483
+ const name = value["@call"];
3484
+ if (typeof name === "string") {
3485
+ if (!options.allowValueFunctions || !isA2UIValueFunction(name)) return isA2UIBasicFunction(name) ? `"${name}" runs only from an event` : `"${name}" is not a basic function`;
3486
+ const args = value.args;
3487
+ if (args !== void 0 && !isRecord(args)) return `the args of "${name}" must be an object`;
3488
+ return args === void 0 ? void 0 : findForbiddenCall(args, options);
3489
+ }
3490
+ for (const item of Object.values(value)) {
3491
+ const reason = findForbiddenCall(item, options);
3492
+ if (reason !== void 0) return reason;
3493
+ }
3494
+ }
3495
+ const childRefCache = /* @__PURE__ */ new WeakMap();
3496
+ /** The component references of a props schema, computed once per schema. */
3497
+ function childRefsOf(props) {
3498
+ let refs = childRefCache.get(props);
3499
+ if (!refs) {
3500
+ refs = collectChildRefs(props);
3501
+ childRefCache.set(props, refs);
3502
+ }
3503
+ return refs;
3504
+ }
3505
+ /**
3506
+ * Checks the component ids at one reference of a node: a typed `child()`
3507
+ * or `childList()` prop, at any depth. A missing key is fine; the props
3508
+ * schema reports a required one.
3509
+ */
3510
+ function childRefProblem(node, ref, ownId) {
3511
+ const label = ref.path.filter((step) => step !== "*").join(".");
3512
+ const isDynamic = (value) => isPathBinding(value) || isRecord(value) && "@call" in value;
3513
+ const visit = (value, steps) => {
3514
+ if (isDynamic(value)) return void 0;
3515
+ if (steps.length === 0) {
3516
+ const reason = slotProblem(value, ref.kind, ownId);
3517
+ return reason ? `${label}: ${reason}` : void 0;
3518
+ }
3519
+ const [head, ...rest] = steps;
3520
+ if (head === "*") {
3521
+ if (!Array.isArray(value)) return void 0;
3522
+ for (const item of value) {
3523
+ const reason = visit(item, rest);
3524
+ if (reason) return reason;
3525
+ }
3526
+ return;
3527
+ }
3528
+ if (!isRecord(value) || !hasOwn(value, head)) return void 0;
3529
+ return visit(value[head], rest);
3530
+ };
3531
+ return visit(node, ref.path);
3532
+ }
3533
+
3534
+ //#endregion
3535
+ //#region src/generative-ui/render-ui-args.ts
3536
+ /**
3537
+ * Reads `target` and every complete `operations[]` element from a possibly
3538
+ * truncated `render_ui` argument string.
3539
+ */
3540
+ function extractRenderUIArgs(text) {
3541
+ return new RenderUIArgsScanner().scan(text);
3542
+ }
3543
+ /**
3544
+ * The parser of {@link extractRenderUIArgs}, with its state kept between
3545
+ * calls. Each call scans only the text after the text it scanned before, so
3546
+ * a streamed argument string is scanned once in total.
3547
+ */
3548
+ var RenderUIArgsScanner = class {
3549
+ constructor() {
3550
+ this.result = { operations: [] };
3551
+ this.stack = [];
3552
+ this.inString = false;
3553
+ this.escaped = false;
3554
+ this.stringStart = -1;
3555
+ this.pendingKey = null;
3556
+ this.currentKey = null;
3557
+ this.expectingValue = false;
3558
+ this.inOperations = false;
3559
+ this.elementStart = -1;
3560
+ this.scanned = 0;
3561
+ }
3562
+ /**
3563
+ * Scans `text` from where the last call stopped.
3564
+ *
3565
+ * @param text - The whole text so far. It starts with the text of the
3566
+ * last call.
3567
+ * @returns The result so far. It is the same object on each call.
3568
+ */
3569
+ scan(text) {
3570
+ const { result, stack } = this;
3571
+ let { inString, escaped, stringStart, pendingKey, currentKey, expectingValue, inOperations, elementStart } = this;
3572
+ for (let i = this.scanned; i < text.length; i++) {
3573
+ const ch = text[i];
3574
+ if (inString) {
3575
+ if (escaped) escaped = false;
3576
+ else if (ch === "\\") escaped = true;
3577
+ else if (ch === "\"") {
3578
+ inString = false;
3579
+ if (stack.length === 1) {
3580
+ const literal = text.slice(stringStart, i + 1);
3581
+ if (expectingValue) {
3582
+ if (currentKey === "target") try {
3583
+ result.target = JSON.parse(literal);
3584
+ } catch (_unused) {}
3585
+ expectingValue = false;
3586
+ } else pendingKey = literal;
3587
+ }
3588
+ }
3589
+ continue;
3590
+ }
3591
+ switch (ch) {
3592
+ case "\"":
3593
+ inString = true;
3594
+ stringStart = i;
3595
+ break;
3596
+ case ":":
3597
+ if (stack.length === 1 && pendingKey !== null) {
3598
+ try {
3599
+ currentKey = JSON.parse(pendingKey);
3600
+ } catch (_unused2) {
3601
+ currentKey = null;
3602
+ }
3603
+ pendingKey = null;
3604
+ expectingValue = true;
3605
+ }
3606
+ break;
3607
+ case ",":
3608
+ if (stack.length === 1) {
3609
+ expectingValue = false;
3610
+ currentKey = null;
3611
+ }
3612
+ break;
3613
+ case "{":
3614
+ if (inOperations && stack.length === 2) elementStart = i;
3615
+ stack.push("{");
3616
+ break;
3617
+ case "[":
3618
+ if (stack.length === 1 && expectingValue && currentKey === "operations") inOperations = true;
3619
+ stack.push("[");
3620
+ break;
3621
+ case "}":
3622
+ case "]":
3623
+ stack.pop();
3624
+ if (ch === "}" && inOperations && stack.length === 2 && elementStart >= 0) {
3625
+ result.operations.push(parseObject(text.slice(elementStart, i + 1)));
3626
+ elementStart = -1;
3627
+ }
3628
+ if (ch === "]" && inOperations && stack.length === 1) {
3629
+ inOperations = false;
3630
+ expectingValue = false;
3631
+ }
3632
+ break;
3633
+ }
3634
+ }
3635
+ this.inString = inString;
3636
+ this.escaped = escaped;
3637
+ this.stringStart = stringStart;
3638
+ this.pendingKey = pendingKey;
3639
+ this.currentKey = currentKey;
3640
+ this.expectingValue = expectingValue;
3641
+ this.inOperations = inOperations;
3642
+ this.elementStart = elementStart;
3643
+ this.scanned = text.length;
3644
+ if (elementStart >= 0) result.incompleteOperation = true;
3645
+ else delete result.incompleteOperation;
3646
+ return result;
3647
+ }
3648
+ };
3649
+ function parseObject(raw) {
3650
+ try {
3651
+ const value = JSON.parse(raw);
3652
+ return isRecord(value) ? value : null;
3653
+ } catch (_unused3) {
3654
+ return null;
3655
+ }
3656
+ }
3657
+ /** Feeds streamed argument deltas and reports operations not yet seen. */
3658
+ var RenderUIArgsStream = class {
3659
+ constructor() {
3660
+ this.buffer = "";
3661
+ this.emitted = 0;
3662
+ this.incomplete = false;
3663
+ this.scanner = new RenderUIArgsScanner();
3664
+ }
3665
+ push(delta) {
3666
+ this.buffer += delta;
3667
+ const { target, operations, incompleteOperation } = this.scanner.scan(this.buffer);
3668
+ const newOperations = operations.slice(this.emitted);
3669
+ this.emitted = operations.length;
3670
+ this.incomplete = incompleteOperation === true;
3671
+ return {
3672
+ target,
3673
+ newOperations
3674
+ };
3675
+ }
3676
+ /** Every argument delta received so far, concatenated. */
3677
+ get text() {
3678
+ return this.buffer;
3679
+ }
3680
+ /**
3681
+ * True when the text received so far ends inside an `operations[]` element.
3682
+ * Once the tool call has ended, that element was truncated.
3683
+ */
3684
+ get hasIncompleteOperation() {
3685
+ return this.incomplete;
3686
+ }
3687
+ };
3688
+
3689
+ //#endregion
3690
+ //#region src/generative-ui/prompt.ts
3691
+ const GENERATIVE_UI_CONTEXT_DESCRIPTION = "Generative UI guide: available components, functions, targets, and how to call render_ui.";
3692
+ /** Most characters of the user values of one surface in the guide. */
3693
+ const MAX_USER_VALUES_LENGTH = 500;
3694
+ /** Cuts long text and marks the cut with "...". */
3695
+ function shorten(text) {
3696
+ return text.length > MAX_USER_VALUES_LENGTH ? `${text.slice(0, MAX_USER_VALUES_LENGTH)}...` : text;
3697
+ }
3698
+ /**
3699
+ * The guide that the runtime adds as a context entry to a tool-transport run:
3700
+ * the `render_ui` rules, the targets, components, functions, and surfaces of
3701
+ * the manifest. It is in shared so that the inspector shows the same text.
3702
+ */
3703
+ function buildGenerativeUIPrompt(manifest) {
3704
+ const targets = manifest.targets.map((t) => {
3705
+ const place = t.kind === "chat" ? "inside the chat transcript" : "a named area of the app";
3706
+ const limit = t.components ? `; only ${t.components.join(", ") || "no components"}` : "";
3707
+ const description = t.description ? `: ${t.description}` : "";
3708
+ return `- "${t.id}" (${place}${limit})${description}`;
3709
+ }).join("\n");
3710
+ const components = Object.entries(manifest.components).map(([name, c]) => {
3711
+ const lines = [`- **${name}**${c.description ? `: ${c.description}` : ""}`, ` props: ${JSON.stringify(c.props)}`];
3712
+ if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);
3713
+ if (c.slots) lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);
3714
+ return lines.join("\n");
3715
+ }).join("\n");
3716
+ const functions = Object.entries(manifest.functions).map(([name, f]) => {
3717
+ const signature = f.parameters.description;
3718
+ const args = typeof signature === "string" && signature.startsWith("{") && Object.keys(f.parameters).length === 2 ? signature : JSON.stringify(f.parameters);
3719
+ const callers = functionCallers(f);
3720
+ return `- **${name}**${callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS ? callers.renderer ? " (UI or agent)" : " (agent only)" : ""}${f.description ? `: ${f.description}` : ""}\n args: ${args}`;
3721
+ }).join("\n");
3722
+ const surfaces = Object.entries(manifest.surfaces).map(([id, s]) => {
3723
+ var _s$rejected;
3724
+ const state = s.status === "deleted" ? ", deleted: never use this id again" : s.status === "failed" ? ", not created: send a corrected createSurface with this id" : "";
3725
+ const lines = [`- "${id}" (target "${s.target}"${state})`];
3726
+ if (s.dataModel) lines.push(` user values: ${shorten(JSON.stringify(s.dataModel))}`);
3727
+ for (const rejection of (_s$rejected = s.rejected) !== null && _s$rejected !== void 0 ? _s$rejected : []) lines.push(` rejected: ${rejection}`);
3728
+ return lines.join("\n");
3729
+ }).join("\n");
3730
+ const surfaceNotes = Object.values(manifest.surfaces).some((s) => {
3731
+ var _s$rejected$length, _s$rejected2;
3732
+ return s.dataModel !== void 0 || ((_s$rejected$length = (_s$rejected2 = s.rejected) === null || _s$rejected2 === void 0 ? void 0 : _s$rejected2.length) !== null && _s$rejected$length !== void 0 ? _s$rejected$length : 0) > 0;
3733
+ }) ? "User values are what the user entered, by path. Your writes to those paths are ignored. Rejected operations were dropped: send them again with the problem fixed.\n" : "";
3734
+ const { functions: hasFunctions, events, templates, checks } = generativeUIGuideFeatures(manifest);
3735
+ const agentCalls = hasFunctions && GENERATIVE_UI_AGENT_FUNCTION_CALLS;
3736
+ const operations = [
3737
+ "{\"version\":\"v1.0\",\"createSurface\":{\"surfaceId\":\"<new id>\",\"dataModel\":{...},\"components\":[{\"id\":\"root\",\"component\":\"<Name>\",\"children\":[\"<child id>\"]}]}}: the first operation of a new surface. \"dataModel\" and \"components\" are optional.",
3738
+ "{\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.",
3739
+ "{\"version\":\"v1.0\",\"updateDataModel\":{\"surfaceId\":\"<id>\",\"path\":\"/some/path\",\"value\":<json>}}: set the value at \"path\". Always give \"value\". \"value\":null deletes the key at \"path\".",
3740
+ "{\"version\":\"v1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.",
3741
+ ...agentCalls ? ["{\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}: run an app function now, with no click. It needs no surface."] : []
3742
+ ];
3743
+ const rules = [
3744
+ "Components are flat objects: {\"id\":\"...\",\"component\":\"<Name>\", ...props}. Every surface renders from the component with id \"root\". Reference children by id in slot props.",
3745
+ "A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component, and \"live\":\"polite\" only on text that changes by itself.",
3746
+ "Stream progressively: put the initial data in \"dataModel\" and the root in \"components\" of the createSurface operation, then send one updateComponents operation per child, so the UI appears while you are still writing. The root must already list the ids of its children in its slot props (for example \"children\":[\"card-1\",\"card-2\"]), even though the children come later. A component that no slot references is never shown.",
3747
+ "Updating a component replaces all of its props, so resend every prop.",
3748
+ "Prop values are literals or data bindings {\"@path\":\"/data/path\"}. Never write {\"path\":\"/data/path\"} as a binding.",
3749
+ ...events ? [hasFunctions ? "Event props take an action. {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}} runs an app function in the browser immediately, and you are not told about it. {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} sends the interaction back to you as a user message, with \"userMessage\" as its first line. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\". Only call functions listed below." : "Event props take an action: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} sends the interaction back to you as a user message, with \"userMessage\" as its first line. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\"."] : [],
3750
+ "To show a different view, create a new surface with a new surfaceId (for example, a checkout form after a cart summary). Update an existing surface only when the user asks to change that same view: then do not send createSurface, use its surfaceId, and pass its existing target. Never reuse an earlier chat surface for a different view, because that replaces the earlier UI and anything the user typed into it.",
3751
+ "Never use a surfaceId again, also after deleteSurface.",
3752
+ "A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Only call functions listed below. formatString interpolates ${/path} and ${fn(arg: value)} in its value.",
3753
+ "${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}.",
3754
+ "For a computed list (chart data, template items) use series. Its description under Functions gives the rules and an example.",
3755
+ ...checks ? ["Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email. A failed check shows the message under the input and disables a Button that has the same checks."] : [],
3756
+ ...templates ? ["To repeat a component for each item of a list, give a multiple slot a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}. Inside the template, paths are relative to the item (\"name\", not \"/name\"). {\"@call\":\"@index\"} gives the position of the item, from 0; {\"@call\":\"@index\",\"args\":{\"offset\":1}} counts from 1."] : [],
3757
+ ...agentCalls ? ["Give every callRendererFunction a new functionCallId. Call only a function marked (UI or agent) or (agent only); a function with no mark is for the UI only. A function marked (agent only) is only for callRendererFunction: do not bind an event to it.", "The result of a callRendererFunction comes back to you in a new turn, as a developer message: {\"version\":\"v1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Do not wait for the result in this reply, and do not guess it."] : []
3758
+ ];
3759
+ return [
3760
+ `## Generative UI
3761
+ Call \`${GENERATIVE_UI_RENDER_TOOL}\` to show UI. Arguments: \`target\` first, then \`operations\` (A2UI v1.0 operations, applied in order).
3762
+
3763
+ ${GENERATIVE_UI_WHEN_TO_SHOW}
3764
+
3765
+ Every operation has "version":"v1.0" and exactly one of:
3766
+ ${operations.map((op) => `- ${op}`).join("\n")}
3767
+
3768
+ Rules:
3769
+ ${rules.map((rule, index) => `${index + 1}. ${rule}`).join("\n")}`,
3770
+ `### Targets\n${targets || "- none"}`,
3771
+ `### Components\n${components || "- none"}`,
3772
+ `### Functions\n${functions || "- none"}`,
3773
+ `### Existing surfaces\n${surfaceNotes}${surfaces || "- none"}`
3774
+ ].join("\n\n");
3775
+ }
3776
+
2432
3777
  //#endregion
2433
3778
  //#region src/index.ts
2434
3779
  const COPILOTKIT_VERSION = version;
@@ -2476,10 +3821,22 @@ Use the SAME surfaceId as the main surface. Match action names to button action
2476
3821
  }
2477
3822
 
2478
3823
  //#endregion
3824
+ exports.A2UI_BASIC_FUNCTIONS = A2UI_BASIC_FUNCTIONS;
3825
+ exports.A2UI_CHILD_LIST_MARK = A2UI_CHILD_LIST_MARK;
3826
+ exports.A2UI_CHILD_LIST_REF = A2UI_CHILD_LIST_REF;
3827
+ exports.A2UI_COMPONENT_ENVELOPE_KEYS = A2UI_COMPONENT_ENVELOPE_KEYS;
3828
+ exports.A2UI_COMPONENT_ID_MARK = A2UI_COMPONENT_ID_MARK;
3829
+ exports.A2UI_COMPONENT_ID_REF = A2UI_COMPONENT_ID_REF;
2479
3830
  exports.A2UI_DEFAULT_DESIGN_GUIDELINES = A2UI_DEFAULT_DESIGN_GUIDELINES;
2480
3831
  exports.A2UI_DEFAULT_GENERATION_GUIDELINES = A2UI_DEFAULT_GENERATION_GUIDELINES;
3832
+ exports.A2UI_INDEX_FUNCTION = A2UI_INDEX_FUNCTION;
3833
+ exports.A2UI_VERSION = A2UI_VERSION;
2481
3834
  exports.AG_UI_CHANNEL_EVENT = AG_UI_CHANNEL_EVENT;
3835
+ exports.ALL_GENERATIVE_UI_GUIDE_FEATURES = ALL_GENERATIVE_UI_GUIDE_FEATURES;
2482
3836
  exports.BANNER_ERROR_NAMES = BANNER_ERROR_NAMES;
3837
+ exports.COPILOTKIT_FORWARDED_PROPS_KEY = COPILOTKIT_FORWARDED_PROPS_KEY;
3838
+ exports.COPILOTKIT_FUNCTIONS = COPILOTKIT_FUNCTIONS;
3839
+ exports.COPILOTKIT_UI_ENVELOPE_FORMAT = COPILOTKIT_UI_ENVELOPE_FORMAT;
2483
3840
  exports.COPILOTKIT_VERSION = COPILOTKIT_VERSION;
2484
3841
  exports.COPILOT_CLOUD_API_URL = COPILOT_CLOUD_API_URL;
2485
3842
  exports.COPILOT_CLOUD_CHAT_URL = COPILOT_CLOUD_CHAT_URL;
@@ -2502,10 +3859,27 @@ exports.ERROR_CONFIG = ERROR_CONFIG;
2502
3859
  exports.ERROR_NAMES = ERROR_NAMES;
2503
3860
  exports.ErrorVisibility = ErrorVisibility;
2504
3861
  exports.GENERATE_SANDBOXED_UI_DESCRIPTION = GENERATE_SANDBOXED_UI_DESCRIPTION;
3862
+ exports.GENERATIVE_UI_ACTIVITY_TYPE = GENERATIVE_UI_ACTIVITY_TYPE;
3863
+ exports.GENERATIVE_UI_AGENT_FUNCTION_CALLS = GENERATIVE_UI_AGENT_FUNCTION_CALLS;
3864
+ exports.GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON = GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON;
3865
+ exports.GENERATIVE_UI_CHAT_TARGET = GENERATIVE_UI_CHAT_TARGET;
3866
+ exports.GENERATIVE_UI_CONTEXT_DESCRIPTION = GENERATIVE_UI_CONTEXT_DESCRIPTION;
3867
+ exports.GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS = GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS;
3868
+ exports.GENERATIVE_UI_FUNCTIONS = GENERATIVE_UI_FUNCTIONS;
3869
+ exports.GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE = GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE;
3870
+ exports.GENERATIVE_UI_MARKDOWN_GUIDELINES = GENERATIVE_UI_MARKDOWN_GUIDELINES;
3871
+ exports.GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION = GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION;
3872
+ exports.GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION = GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION;
3873
+ exports.GENERATIVE_UI_MAX_REJECTION_LENGTH = GENERATIVE_UI_MAX_REJECTION_LENGTH;
3874
+ exports.GENERATIVE_UI_MAX_SUMMARY_REJECTIONS = GENERATIVE_UI_MAX_SUMMARY_REJECTIONS;
3875
+ exports.GENERATIVE_UI_MAX_TARGET_COMPONENTS = GENERATIVE_UI_MAX_TARGET_COMPONENTS;
3876
+ exports.GENERATIVE_UI_RENDER_TOOL = GENERATIVE_UI_RENDER_TOOL;
3877
+ exports.GENERATIVE_UI_ROOT_ID = GENERATIVE_UI_ROOT_ID;
2505
3878
  exports.MODEL_HOST_CLASSES = MODEL_HOST_CLASSES;
2506
3879
  exports.MissingPublicApiKeyError = MissingPublicApiKeyError;
2507
3880
  exports.RUNTIME_MODE_INTELLIGENCE = RUNTIME_MODE_INTELLIGENCE;
2508
3881
  exports.RUNTIME_MODE_SSE = RUNTIME_MODE_SSE;
3882
+ exports.RenderUIArgsStream = RenderUIArgsStream;
2509
3883
  exports.ResolvedCopilotKitError = ResolvedCopilotKitError;
2510
3884
  exports.Severity = Severity;
2511
3885
  exports.TELEMETRY_EMITTER_V1 = TELEMETRY_EMITTER_V1;
@@ -2518,7 +3892,14 @@ exports.TranscriptionErrors = TranscriptionErrors;
2518
3892
  exports.UNSAMPLED_RATE = UNSAMPLED_RATE;
2519
3893
  exports.UpgradeRequiredError = UpgradeRequiredError;
2520
3894
  exports.actionParametersToJsonSchema = actionParametersToJsonSchema;
3895
+ exports.applyChildRefMarks = applyChildRefMarks;
3896
+ exports.buildGenerativeUIMarkdownGuidelines = buildGenerativeUIMarkdownGuidelines;
3897
+ exports.buildGenerativeUIPrompt = buildGenerativeUIPrompt;
3898
+ exports.callerProblem = callerProblem;
3899
+ exports.childIdsAtRefs = childIdsAtRefs;
3900
+ exports.childRefKind = childRefKind;
2521
3901
  exports.classifyModelHost = classifyModelHost;
3902
+ exports.collectChildRefs = collectChildRefs;
2522
3903
  exports.commitRowKeyStore = commitRowKeyStore;
2523
3904
  exports.computeSamplingMeta = computeSamplingMeta;
2524
3905
  exports.convertJsonSchemaToZodSchema = convertJsonSchemaToZodSchema;
@@ -2529,26 +3910,43 @@ exports.createRowKeyStore = createRowKeyStore;
2529
3910
  exports.createRunEventFinalizer = createRunEventFinalizer;
2530
3911
  exports.dataToUUID = dataToUUID;
2531
3912
  exports.ensureStructuredError = ensureStructuredError;
3913
+ exports.envelopeToManifest = envelopeToManifest;
2532
3914
  exports.exceedsMaxSize = exceedsMaxSize;
2533
3915
  exports.executeConditions = executeConditions;
3916
+ exports.extractRenderUIArgs = extractRenderUIArgs;
2534
3917
  exports.finalizeRunEvents = finalizeRunEvents;
2535
3918
  exports.firstNonBlankTelemetryId = firstNonBlankTelemetryId;
2536
3919
  exports.formatFileSize = formatFileSize;
3920
+ exports.functionCallers = functionCallers;
2537
3921
  exports.generateVideoThumbnail = generateVideoThumbnail;
3922
+ exports.generativeUIFunctionCallMessageId = generativeUIFunctionCallMessageId;
3923
+ exports.generativeUIGuideFeatures = generativeUIGuideFeatures;
3924
+ exports.generativeUISurfaceMessageId = generativeUISurfaceMessageId;
2538
3925
  exports.getDocumentIcon = getDocumentIcon;
2539
3926
  exports.getModalityFromMimeType = getModalityFromMimeType;
3927
+ exports.getOperationKind = getOperationKind;
3928
+ exports.getOperationSurfaceId = getOperationSurfaceId;
2540
3929
  exports.getPossibleVersionMismatch = getPossibleVersionMismatch;
2541
3930
  exports.getSourceUrl = getSourceUrl;
2542
3931
  exports.getZodParameters = getZodParameters;
3932
+ exports.hasBoundChildRef = hasBoundChildRef;
3933
+ exports.isA2UIBasicFunction = isA2UIBasicFunction;
3934
+ exports.isA2UIValueFunction = isA2UIValueFunction;
3935
+ exports.isActionBinding = isActionBinding;
3936
+ exports.isCallBinding = isCallBinding;
3937
+ exports.isIndexCall = isIndexCall;
2543
3938
  exports.isMacOS = isMacOS;
3939
+ exports.isPathBinding = isPathBinding;
2544
3940
  exports.isStructuredCopilotKitError = isStructuredCopilotKitError;
2545
3941
  exports.isTelemetryDisabled = isTelemetryDisabled;
2546
3942
  exports.isValidUUID = isValidUUID;
3943
+ exports.isValidationResult = isValidationResult;
2547
3944
  exports.jsonSchemaToActionParameters = jsonSchemaToActionParameters;
2548
3945
  exports.lambdaClient = lambdaClient;
2549
3946
  exports.logCopilotKitPlatformMessage = logCopilotKitPlatformMessage;
2550
3947
  exports.logStyled = logStyled;
2551
3948
  exports.logger = logger;
3949
+ exports.mapAtChildRef = mapAtChildRef;
2552
3950
  exports.matchesAcceptFilter = matchesAcceptFilter;
2553
3951
  exports.parseAndWarnTelemetryId = parseAndWarnTelemetryId;
2554
3952
  exports.parseInspectorLearningRequestV1 = parseInspectorLearningRequestV1;
@@ -2564,6 +3962,7 @@ exports.publicApiKeyRequired = publicApiKeyRequired;
2564
3962
  exports.randomId = randomId;
2565
3963
  exports.randomUUID = randomUUID;
2566
3964
  exports.readBody = readBody;
3965
+ exports.readCopilotKitUIEnvelope = readCopilotKitUIEnvelope;
2567
3966
  exports.readFileAsBase64 = readFileAsBase64;
2568
3967
  exports.resolveDebugConfig = resolveDebugConfig;
2569
3968
  exports.resolveRowRenderKeys = resolveRowRenderKeys;
@@ -2573,6 +3972,8 @@ exports.schemaToJsonSchema = schemaToJsonSchema;
2573
3972
  exports.shouldEnableInspector = shouldEnableInspector;
2574
3973
  exports.stripIntelligenceRoutingFields = stripIntelligenceRoutingFields;
2575
3974
  exports.styledConsole = styledConsole;
3975
+ exports.toA2UIActionMessage = toA2UIActionMessage;
2576
3976
  exports.tryMap = tryMap;
3977
+ exports.validateOperation = validateOperation;
2577
3978
  });
2578
3979
  //# sourceMappingURL=index.umd.js.map