@copilotkit/shared 1.79.2-canary.1792172552 → 1.81.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 (156) 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/constants/index.cjs +7 -0
  18. package/dist/constants/index.cjs.map +1 -1
  19. package/dist/constants/index.d.cts +7 -1
  20. package/dist/constants/index.d.cts.map +1 -1
  21. package/dist/constants/index.d.mts +7 -1
  22. package/dist/constants/index.d.mts.map +1 -1
  23. package/dist/constants/index.mjs +7 -1
  24. package/dist/constants/index.mjs.map +1 -1
  25. package/dist/event-transforms/open-generative-ui-middleware.cjs +7 -6
  26. package/dist/event-transforms/open-generative-ui-middleware.cjs.map +1 -1
  27. package/dist/event-transforms/open-generative-ui-middleware.d.cts.map +1 -1
  28. package/dist/event-transforms/open-generative-ui-middleware.d.mts.map +1 -1
  29. package/dist/event-transforms/open-generative-ui-middleware.mjs +7 -6
  30. package/dist/event-transforms/open-generative-ui-middleware.mjs.map +1 -1
  31. package/dist/generative-ui/basic-functions.cjs +177 -0
  32. package/dist/generative-ui/basic-functions.cjs.map +1 -0
  33. package/dist/generative-ui/basic-functions.d.cts +108 -0
  34. package/dist/generative-ui/basic-functions.d.cts.map +1 -0
  35. package/dist/generative-ui/basic-functions.d.mts +108 -0
  36. package/dist/generative-ui/basic-functions.d.mts.map +1 -0
  37. package/dist/generative-ui/basic-functions.mjs +167 -0
  38. package/dist/generative-ui/basic-functions.mjs.map +1 -0
  39. package/dist/generative-ui/child-refs.cjs +161 -0
  40. package/dist/generative-ui/child-refs.cjs.map +1 -0
  41. package/dist/generative-ui/child-refs.d.cts +68 -0
  42. package/dist/generative-ui/child-refs.d.cts.map +1 -0
  43. package/dist/generative-ui/child-refs.d.mts +68 -0
  44. package/dist/generative-ui/child-refs.d.mts.map +1 -0
  45. package/dist/generative-ui/child-refs.mjs +152 -0
  46. package/dist/generative-ui/child-refs.mjs.map +1 -0
  47. package/dist/generative-ui/is-record.cjs +10 -0
  48. package/dist/generative-ui/is-record.cjs.map +1 -0
  49. package/dist/generative-ui/is-record.mjs +9 -0
  50. package/dist/generative-ui/is-record.mjs.map +1 -0
  51. package/dist/generative-ui/prompt.cjs +91 -0
  52. package/dist/generative-ui/prompt.cjs.map +1 -0
  53. package/dist/generative-ui/prompt.d.cts +13 -0
  54. package/dist/generative-ui/prompt.d.cts.map +1 -0
  55. package/dist/generative-ui/prompt.d.mts +13 -0
  56. package/dist/generative-ui/prompt.d.mts.map +1 -0
  57. package/dist/generative-ui/prompt.mjs +90 -0
  58. package/dist/generative-ui/prompt.mjs.map +1 -0
  59. package/dist/generative-ui/render-ui-args.cjs +160 -0
  60. package/dist/generative-ui/render-ui-args.cjs.map +1 -0
  61. package/dist/generative-ui/render-ui-args.d.cts +40 -0
  62. package/dist/generative-ui/render-ui-args.d.cts.map +1 -0
  63. package/dist/generative-ui/render-ui-args.d.mts +40 -0
  64. package/dist/generative-ui/render-ui-args.d.mts.map +1 -0
  65. package/dist/generative-ui/render-ui-args.mjs +159 -0
  66. package/dist/generative-ui/render-ui-args.mjs.map +1 -0
  67. package/dist/generative-ui/types.cjs +101 -0
  68. package/dist/generative-ui/types.cjs.map +1 -0
  69. package/dist/generative-ui/types.d.cts +270 -0
  70. package/dist/generative-ui/types.d.cts.map +1 -0
  71. package/dist/generative-ui/types.d.mts +270 -0
  72. package/dist/generative-ui/types.d.mts.map +1 -0
  73. package/dist/generative-ui/types.mjs +86 -0
  74. package/dist/generative-ui/types.mjs.map +1 -0
  75. package/dist/generative-ui/validate-operation.cjs +405 -0
  76. package/dist/generative-ui/validate-operation.cjs.map +1 -0
  77. package/dist/generative-ui/validate-operation.d.cts +86 -0
  78. package/dist/generative-ui/validate-operation.d.cts.map +1 -0
  79. package/dist/generative-ui/validate-operation.d.mts +86 -0
  80. package/dist/generative-ui/validate-operation.d.mts.map +1 -0
  81. package/dist/generative-ui/validate-operation.mjs +399 -0
  82. package/dist/generative-ui/validate-operation.mjs.map +1 -0
  83. package/dist/index.cjs +64 -0
  84. package/dist/index.cjs.map +1 -1
  85. package/dist/index.d.cts +11 -4
  86. package/dist/index.d.cts.map +1 -1
  87. package/dist/index.d.mts +11 -4
  88. package/dist/index.d.mts.map +1 -1
  89. package/dist/index.mjs +10 -3
  90. package/dist/index.mjs.map +1 -1
  91. package/dist/index.umd.js +1466 -29
  92. package/dist/index.umd.js.map +1 -1
  93. package/dist/package.cjs +1 -1
  94. package/dist/package.mjs +1 -1
  95. package/dist/telemetry/lambda-client.cjs.map +1 -1
  96. package/dist/telemetry/lambda-client.mjs.map +1 -1
  97. package/dist/telemetry/utils.cjs +0 -2
  98. package/dist/telemetry/utils.cjs.map +1 -1
  99. package/dist/telemetry/utils.mjs +0 -2
  100. package/dist/telemetry/utils.mjs.map +1 -1
  101. package/dist/utils/dashboard-url.cjs +19 -0
  102. package/dist/utils/dashboard-url.cjs.map +1 -0
  103. package/dist/utils/dashboard-url.mjs +18 -0
  104. package/dist/utils/dashboard-url.mjs.map +1 -0
  105. package/dist/utils/index.cjs +2 -1
  106. package/dist/utils/index.cjs.map +1 -1
  107. package/dist/utils/index.d.cts +1 -1
  108. package/dist/utils/index.d.cts.map +1 -1
  109. package/dist/utils/index.d.mts +1 -1
  110. package/dist/utils/index.d.mts.map +1 -1
  111. package/dist/utils/index.mjs +2 -1
  112. package/dist/utils/index.mjs.map +1 -1
  113. package/dist/utils/inspector-learning.cjs +48 -16
  114. package/dist/utils/inspector-learning.cjs.map +1 -1
  115. package/dist/utils/inspector-learning.d.cts +14 -1
  116. package/dist/utils/inspector-learning.d.cts.map +1 -1
  117. package/dist/utils/inspector-learning.d.mts +14 -1
  118. package/dist/utils/inspector-learning.d.mts.map +1 -1
  119. package/dist/utils/inspector-learning.mjs +49 -16
  120. package/dist/utils/inspector-learning.mjs.map +1 -1
  121. package/dist/utils/inspector-metadata.cjs +2 -3
  122. package/dist/utils/inspector-metadata.cjs.map +1 -1
  123. package/dist/utils/inspector-metadata.d.cts.map +1 -1
  124. package/dist/utils/inspector-metadata.d.mts.map +1 -1
  125. package/dist/utils/inspector-metadata.mjs +3 -3
  126. package/dist/utils/inspector-metadata.mjs.map +1 -1
  127. package/package.json +3 -4
  128. package/src/__tests__/a2ui-envelope.test.ts +434 -0
  129. package/src/__tests__/a2ui-prompts.test.ts +362 -0
  130. package/src/a2ui-envelope.ts +309 -0
  131. package/src/a2ui-prompts.ts +207 -0
  132. package/src/constants/index.ts +7 -0
  133. package/src/event-transforms/open-generative-ui-middleware.ts +19 -10
  134. package/src/generative-ui/__tests__/render-ui-args.test.ts +175 -0
  135. package/src/generative-ui/__tests__/validate-operation.test.ts +977 -0
  136. package/src/generative-ui/basic-functions.ts +282 -0
  137. package/src/generative-ui/child-refs.ts +210 -0
  138. package/src/generative-ui/index.ts +6 -0
  139. package/src/generative-ui/is-record.ts +4 -0
  140. package/src/generative-ui/prompt.ts +174 -0
  141. package/src/generative-ui/render-ui-args.ts +199 -0
  142. package/src/generative-ui/types.ts +314 -0
  143. package/src/generative-ui/validate-operation.ts +723 -0
  144. package/src/index.ts +15 -0
  145. package/src/telemetry/lambda-client.ts +3 -3
  146. package/src/telemetry/utils.ts +0 -28
  147. package/src/utils/dashboard-url.ts +17 -0
  148. package/src/utils/index.ts +7 -1
  149. package/src/utils/inspector-learning.test.ts +210 -0
  150. package/src/utils/inspector-learning.ts +117 -17
  151. package/src/utils/inspector-metadata.test.ts +2 -1
  152. package/src/utils/inspector-metadata.ts +3 -13
  153. package/src/utils.test.ts +71 -0
  154. package/tsdown.config.ts +0 -1
  155. package/src/telemetry/scarf-client.ts +0 -39
  156. package/src/telemetry/security-check.ts +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt.cjs","names":["functionCallers","GENERATIVE_UI_AGENT_FUNCTION_CALLS","generativeUIGuideFeatures","GENERATIVE_UI_RENDER_TOOL","GENERATIVE_UI_WHEN_TO_SHOW"],"sources":["../../src/generative-ui/prompt.ts"],"sourcesContent":["import {\n GENERATIVE_UI_WHEN_TO_SHOW,\n generativeUIGuideFeatures,\n} from \"../a2ui-prompts\";\nimport { functionCallers } from \"./basic-functions\";\nimport {\n GENERATIVE_UI_AGENT_FUNCTION_CALLS,\n GENERATIVE_UI_RENDER_TOOL,\n} from \"./types\";\nimport type { GenerativeUIManifest } from \"./types\";\n\nexport const GENERATIVE_UI_CONTEXT_DESCRIPTION =\n \"Generative UI guide: available components, functions, targets, and how to call render_ui.\";\n\n/** Most characters of the user values of one surface in the guide. */\nconst MAX_USER_VALUES_LENGTH = 500;\n\n/** Cuts long text and marks the cut with \"...\". */\nfunction shorten(text: string) {\n return text.length > MAX_USER_VALUES_LENGTH\n ? `${text.slice(0, MAX_USER_VALUES_LENGTH)}...`\n : text;\n}\n\n/**\n * The guide that the runtime adds as a context entry to a tool-transport run:\n * the `render_ui` rules, the targets, components, functions, and surfaces of\n * the manifest. It is in shared so that the inspector shows the same text.\n */\nexport function buildGenerativeUIPrompt(manifest: GenerativeUIManifest) {\n const targets = manifest.targets\n .map((t) => {\n const place =\n t.kind === \"chat\"\n ? \"inside the chat transcript\"\n : \"a named area of the app\";\n const limit = t.components\n ? `; only ${t.components.join(\", \") || \"no components\"}`\n : \"\";\n const description = t.description ? `: ${t.description}` : \"\";\n return `- \"${t.id}\" (${place}${limit})${description}`;\n })\n .join(\"\\n\");\n const components = Object.entries(manifest.components)\n .map(([name, c]) => {\n const lines = [\n `- **${name}**${c.description ? `: ${c.description}` : \"\"}`,\n ` props: ${JSON.stringify(c.props)}`,\n ];\n if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);\n if (c.slots)\n lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);\n return lines.join(\"\\n\");\n })\n .join(\"\\n\");\n const functions = Object.entries(manifest.functions)\n .map(([name, f]) => {\n // A built-in function carries its short signature in the description\n // of its parameters; an app function has a JSON Schema.\n const signature = f.parameters.description;\n const args =\n typeof signature === \"string\" &&\n signature.startsWith(\"{\") &&\n Object.keys(f.parameters).length === 2\n ? signature\n : JSON.stringify(f.parameters);\n // A function is for the UI unless marked: the agent calls only what\n // the mark allows.\n const callers = functionCallers(f);\n const who =\n callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS\n ? callers.renderer\n ? \" (UI or agent)\"\n : \" (agent only)\"\n : \"\";\n return `- **${name}**${who}${f.description ? `: ${f.description}` : \"\"}\\n args: ${args}`;\n })\n .join(\"\\n\");\n const surfaces = Object.entries(manifest.surfaces)\n .map(([id, s]) => {\n const state =\n s.status === \"deleted\"\n ? \", deleted: never use this id again\"\n : s.status === \"failed\"\n ? \", not created: send a corrected createSurface with this id\"\n : \"\";\n const lines = [`- \"${id}\" (target \"${s.target}\"${state})`];\n if (s.dataModel) {\n lines.push(` user values: ${shorten(JSON.stringify(s.dataModel))}`);\n }\n for (const rejection of s.rejected ?? []) {\n lines.push(` rejected: ${rejection}`);\n }\n return lines.join(\"\\n\");\n })\n .join(\"\\n\");\n const hasSurfaceNotes = Object.values(manifest.surfaces).some(\n (s) => s.dataModel !== undefined || (s.rejected?.length ?? 0) > 0,\n );\n const surfaceNotes = hasSurfaceNotes\n ? \"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\"\n : \"\";\n\n // Rules for functions, events, and templates go only to runs whose manifest\n // has them, so the guide stays small.\n const {\n functions: hasFunctions,\n events,\n templates,\n checks,\n } = generativeUIGuideFeatures(manifest);\n // The agent calls functions only while that path is on.\n const agentCalls = hasFunctions && GENERATIVE_UI_AGENT_FUNCTION_CALLS;\n const operations = [\n '{\"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.',\n '{\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.',\n '{\"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\".',\n '{\"version\":\"v1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.',\n ...(agentCalls\n ? [\n '{\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}: run an app function now, with no click. It needs no surface.',\n ]\n : []),\n ];\n const eventRule = hasFunctions\n ? '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.'\n : '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\".';\n const rules = [\n 'Components are flat objects: {\"id\":\"...\",\"component\":\"<Name>\", ...props}. Every surface renders from the component with id \"root\". Reference children by id in slot props.',\n '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.',\n '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.',\n \"Updating a component replaces all of its props, so resend every prop.\",\n 'Prop values are literals or data bindings {\"@path\":\"/data/path\"}. Never write {\"path\":\"/data/path\"} as a binding.',\n ...(events ? [eventRule] : []),\n \"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.\",\n \"Never use a surfaceId again, also after deleteSurface.\",\n '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.',\n '${...} 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\"}}}.',\n \"For a computed list (chart data, template items) use series. Its description under Functions gives the rules and an example.\",\n ...(checks\n ? [\n '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.',\n ]\n : []),\n ...(templates\n ? [\n '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.',\n ]\n : []),\n ...(agentCalls\n ? [\n \"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.\",\n '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.',\n ]\n : []),\n ];\n\n return [\n `## Generative UI\nCall \\`${GENERATIVE_UI_RENDER_TOOL}\\` to show UI. Arguments: \\`target\\` first, then \\`operations\\` (A2UI v1.0 operations, applied in order).\n\n${GENERATIVE_UI_WHEN_TO_SHOW}\n\nEvery operation has \"version\":\"v1.0\" and exactly one of:\n${operations.map((op) => `- ${op}`).join(\"\\n\")}\n\nRules:\n${rules.map((rule, index) => `${index + 1}. ${rule}`).join(\"\\n\")}`,\n `### Targets\\n${targets || \"- none\"}`,\n `### Components\\n${components || \"- none\"}`,\n `### Functions\\n${functions || \"- none\"}`,\n `### Existing surfaces\\n${surfaceNotes}${surfaces || \"- none\"}`,\n ].join(\"\\n\\n\");\n}\n"],"mappings":"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"}
@@ -0,0 +1,13 @@
1
+ import { GenerativeUIManifest } from "./types.cjs";
2
+
3
+ //#region src/generative-ui/prompt.d.ts
4
+ declare const GENERATIVE_UI_CONTEXT_DESCRIPTION = "Generative UI guide: available components, functions, targets, and how to call render_ui.";
5
+ /**
6
+ * The guide that the runtime adds as a context entry to a tool-transport run:
7
+ * the `render_ui` rules, the targets, components, functions, and surfaces of
8
+ * the manifest. It is in shared so that the inspector shows the same text.
9
+ */
10
+ declare function buildGenerativeUIPrompt(manifest: GenerativeUIManifest): string;
11
+ //#endregion
12
+ export { GENERATIVE_UI_CONTEXT_DESCRIPTION, buildGenerativeUIPrompt };
13
+ //# sourceMappingURL=prompt.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt.d.cts","names":[],"sources":["../../src/generative-ui/prompt.ts"],"mappings":";;;cAWa,iCAAA;;AAAb;;;;iBAkBgB,uBAAA,CAAwB,QAAA,EAAU,oBAAA"}
@@ -0,0 +1,13 @@
1
+ import { GenerativeUIManifest } from "./types.mjs";
2
+
3
+ //#region src/generative-ui/prompt.d.ts
4
+ declare const GENERATIVE_UI_CONTEXT_DESCRIPTION = "Generative UI guide: available components, functions, targets, and how to call render_ui.";
5
+ /**
6
+ * The guide that the runtime adds as a context entry to a tool-transport run:
7
+ * the `render_ui` rules, the targets, components, functions, and surfaces of
8
+ * the manifest. It is in shared so that the inspector shows the same text.
9
+ */
10
+ declare function buildGenerativeUIPrompt(manifest: GenerativeUIManifest): string;
11
+ //#endregion
12
+ export { GENERATIVE_UI_CONTEXT_DESCRIPTION, buildGenerativeUIPrompt };
13
+ //# sourceMappingURL=prompt.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt.d.mts","names":[],"sources":["../../src/generative-ui/prompt.ts"],"mappings":";;;cAWa,iCAAA;;AAAb;;;;iBAkBgB,uBAAA,CAAwB,QAAA,EAAU,oBAAA"}
@@ -0,0 +1,90 @@
1
+ import { functionCallers } from "./basic-functions.mjs";
2
+ import { GENERATIVE_UI_AGENT_FUNCTION_CALLS, GENERATIVE_UI_RENDER_TOOL } from "./types.mjs";
3
+ import { GENERATIVE_UI_WHEN_TO_SHOW, generativeUIGuideFeatures } from "../a2ui-prompts.mjs";
4
+
5
+ //#region src/generative-ui/prompt.ts
6
+ const GENERATIVE_UI_CONTEXT_DESCRIPTION = "Generative UI guide: available components, functions, targets, and how to call render_ui.";
7
+ /** Most characters of the user values of one surface in the guide. */
8
+ const MAX_USER_VALUES_LENGTH = 500;
9
+ /** Cuts long text and marks the cut with "...". */
10
+ function shorten(text) {
11
+ return text.length > MAX_USER_VALUES_LENGTH ? `${text.slice(0, MAX_USER_VALUES_LENGTH)}...` : text;
12
+ }
13
+ /**
14
+ * The guide that the runtime adds as a context entry to a tool-transport run:
15
+ * the `render_ui` rules, the targets, components, functions, and surfaces of
16
+ * the manifest. It is in shared so that the inspector shows the same text.
17
+ */
18
+ function buildGenerativeUIPrompt(manifest) {
19
+ const targets = manifest.targets.map((t) => {
20
+ const place = t.kind === "chat" ? "inside the chat transcript" : "a named area of the app";
21
+ const limit = t.components ? `; only ${t.components.join(", ") || "no components"}` : "";
22
+ const description = t.description ? `: ${t.description}` : "";
23
+ return `- "${t.id}" (${place}${limit})${description}`;
24
+ }).join("\n");
25
+ const components = Object.entries(manifest.components).map(([name, c]) => {
26
+ const lines = [`- **${name}**${c.description ? `: ${c.description}` : ""}`, ` props: ${JSON.stringify(c.props)}`];
27
+ if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);
28
+ if (c.slots) lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);
29
+ return lines.join("\n");
30
+ }).join("\n");
31
+ const functions = Object.entries(manifest.functions).map(([name, f]) => {
32
+ const signature = f.parameters.description;
33
+ const args = typeof signature === "string" && signature.startsWith("{") && Object.keys(f.parameters).length === 2 ? signature : JSON.stringify(f.parameters);
34
+ const callers = functionCallers(f);
35
+ return `- **${name}**${callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS ? callers.renderer ? " (UI or agent)" : " (agent only)" : ""}${f.description ? `: ${f.description}` : ""}\n args: ${args}`;
36
+ }).join("\n");
37
+ const surfaces = Object.entries(manifest.surfaces).map(([id, s]) => {
38
+ const state = s.status === "deleted" ? ", deleted: never use this id again" : s.status === "failed" ? ", not created: send a corrected createSurface with this id" : "";
39
+ const lines = [`- "${id}" (target "${s.target}"${state})`];
40
+ if (s.dataModel) lines.push(` user values: ${shorten(JSON.stringify(s.dataModel))}`);
41
+ for (const rejection of s.rejected ?? []) lines.push(` rejected: ${rejection}`);
42
+ return lines.join("\n");
43
+ }).join("\n");
44
+ const surfaceNotes = Object.values(manifest.surfaces).some((s) => s.dataModel !== void 0 || (s.rejected?.length ?? 0) > 0) ? "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" : "";
45
+ const { functions: hasFunctions, events, templates, checks } = generativeUIGuideFeatures(manifest);
46
+ const agentCalls = hasFunctions && GENERATIVE_UI_AGENT_FUNCTION_CALLS;
47
+ const operations = [
48
+ "{\"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.",
49
+ "{\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.",
50
+ "{\"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\".",
51
+ "{\"version\":\"v1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.",
52
+ ...agentCalls ? ["{\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}: run an app function now, with no click. It needs no surface."] : []
53
+ ];
54
+ const rules = [
55
+ "Components are flat objects: {\"id\":\"...\",\"component\":\"<Name>\", ...props}. Every surface renders from the component with id \"root\". Reference children by id in slot props.",
56
+ "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.",
57
+ "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.",
58
+ "Updating a component replaces all of its props, so resend every prop.",
59
+ "Prop values are literals or data bindings {\"@path\":\"/data/path\"}. Never write {\"path\":\"/data/path\"} as a binding.",
60
+ ...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\"."] : [],
61
+ "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.",
62
+ "Never use a surfaceId again, also after deleteSurface.",
63
+ "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.",
64
+ "${...} 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\"}}}.",
65
+ "For a computed list (chart data, template items) use series. Its description under Functions gives the rules and an example.",
66
+ ...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."] : [],
67
+ ...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."] : [],
68
+ ...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."] : []
69
+ ];
70
+ return [
71
+ `## Generative UI
72
+ Call \`${GENERATIVE_UI_RENDER_TOOL}\` to show UI. Arguments: \`target\` first, then \`operations\` (A2UI v1.0 operations, applied in order).
73
+
74
+ ${GENERATIVE_UI_WHEN_TO_SHOW}
75
+
76
+ Every operation has "version":"v1.0" and exactly one of:
77
+ ${operations.map((op) => `- ${op}`).join("\n")}
78
+
79
+ Rules:
80
+ ${rules.map((rule, index) => `${index + 1}. ${rule}`).join("\n")}`,
81
+ `### Targets\n${targets || "- none"}`,
82
+ `### Components\n${components || "- none"}`,
83
+ `### Functions\n${functions || "- none"}`,
84
+ `### Existing surfaces\n${surfaceNotes}${surfaces || "- none"}`
85
+ ].join("\n\n");
86
+ }
87
+
88
+ //#endregion
89
+ export { GENERATIVE_UI_CONTEXT_DESCRIPTION, buildGenerativeUIPrompt };
90
+ //# sourceMappingURL=prompt.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt.mjs","names":[],"sources":["../../src/generative-ui/prompt.ts"],"sourcesContent":["import {\n GENERATIVE_UI_WHEN_TO_SHOW,\n generativeUIGuideFeatures,\n} from \"../a2ui-prompts\";\nimport { functionCallers } from \"./basic-functions\";\nimport {\n GENERATIVE_UI_AGENT_FUNCTION_CALLS,\n GENERATIVE_UI_RENDER_TOOL,\n} from \"./types\";\nimport type { GenerativeUIManifest } from \"./types\";\n\nexport const GENERATIVE_UI_CONTEXT_DESCRIPTION =\n \"Generative UI guide: available components, functions, targets, and how to call render_ui.\";\n\n/** Most characters of the user values of one surface in the guide. */\nconst MAX_USER_VALUES_LENGTH = 500;\n\n/** Cuts long text and marks the cut with \"...\". */\nfunction shorten(text: string) {\n return text.length > MAX_USER_VALUES_LENGTH\n ? `${text.slice(0, MAX_USER_VALUES_LENGTH)}...`\n : text;\n}\n\n/**\n * The guide that the runtime adds as a context entry to a tool-transport run:\n * the `render_ui` rules, the targets, components, functions, and surfaces of\n * the manifest. It is in shared so that the inspector shows the same text.\n */\nexport function buildGenerativeUIPrompt(manifest: GenerativeUIManifest) {\n const targets = manifest.targets\n .map((t) => {\n const place =\n t.kind === \"chat\"\n ? \"inside the chat transcript\"\n : \"a named area of the app\";\n const limit = t.components\n ? `; only ${t.components.join(\", \") || \"no components\"}`\n : \"\";\n const description = t.description ? `: ${t.description}` : \"\";\n return `- \"${t.id}\" (${place}${limit})${description}`;\n })\n .join(\"\\n\");\n const components = Object.entries(manifest.components)\n .map(([name, c]) => {\n const lines = [\n `- **${name}**${c.description ? `: ${c.description}` : \"\"}`,\n ` props: ${JSON.stringify(c.props)}`,\n ];\n if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);\n if (c.slots)\n lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);\n return lines.join(\"\\n\");\n })\n .join(\"\\n\");\n const functions = Object.entries(manifest.functions)\n .map(([name, f]) => {\n // A built-in function carries its short signature in the description\n // of its parameters; an app function has a JSON Schema.\n const signature = f.parameters.description;\n const args =\n typeof signature === \"string\" &&\n signature.startsWith(\"{\") &&\n Object.keys(f.parameters).length === 2\n ? signature\n : JSON.stringify(f.parameters);\n // A function is for the UI unless marked: the agent calls only what\n // the mark allows.\n const callers = functionCallers(f);\n const who =\n callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS\n ? callers.renderer\n ? \" (UI or agent)\"\n : \" (agent only)\"\n : \"\";\n return `- **${name}**${who}${f.description ? `: ${f.description}` : \"\"}\\n args: ${args}`;\n })\n .join(\"\\n\");\n const surfaces = Object.entries(manifest.surfaces)\n .map(([id, s]) => {\n const state =\n s.status === \"deleted\"\n ? \", deleted: never use this id again\"\n : s.status === \"failed\"\n ? \", not created: send a corrected createSurface with this id\"\n : \"\";\n const lines = [`- \"${id}\" (target \"${s.target}\"${state})`];\n if (s.dataModel) {\n lines.push(` user values: ${shorten(JSON.stringify(s.dataModel))}`);\n }\n for (const rejection of s.rejected ?? []) {\n lines.push(` rejected: ${rejection}`);\n }\n return lines.join(\"\\n\");\n })\n .join(\"\\n\");\n const hasSurfaceNotes = Object.values(manifest.surfaces).some(\n (s) => s.dataModel !== undefined || (s.rejected?.length ?? 0) > 0,\n );\n const surfaceNotes = hasSurfaceNotes\n ? \"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\"\n : \"\";\n\n // Rules for functions, events, and templates go only to runs whose manifest\n // has them, so the guide stays small.\n const {\n functions: hasFunctions,\n events,\n templates,\n checks,\n } = generativeUIGuideFeatures(manifest);\n // The agent calls functions only while that path is on.\n const agentCalls = hasFunctions && GENERATIVE_UI_AGENT_FUNCTION_CALLS;\n const operations = [\n '{\"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.',\n '{\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.',\n '{\"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\".',\n '{\"version\":\"v1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.',\n ...(agentCalls\n ? [\n '{\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}: run an app function now, with no click. It needs no surface.',\n ]\n : []),\n ];\n const eventRule = hasFunctions\n ? '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.'\n : '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\".';\n const rules = [\n 'Components are flat objects: {\"id\":\"...\",\"component\":\"<Name>\", ...props}. Every surface renders from the component with id \"root\". Reference children by id in slot props.',\n '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.',\n '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.',\n \"Updating a component replaces all of its props, so resend every prop.\",\n 'Prop values are literals or data bindings {\"@path\":\"/data/path\"}. Never write {\"path\":\"/data/path\"} as a binding.',\n ...(events ? [eventRule] : []),\n \"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.\",\n \"Never use a surfaceId again, also after deleteSurface.\",\n '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.',\n '${...} 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\"}}}.',\n \"For a computed list (chart data, template items) use series. Its description under Functions gives the rules and an example.\",\n ...(checks\n ? [\n '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.',\n ]\n : []),\n ...(templates\n ? [\n '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.',\n ]\n : []),\n ...(agentCalls\n ? [\n \"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.\",\n '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.',\n ]\n : []),\n ];\n\n return [\n `## Generative UI\nCall \\`${GENERATIVE_UI_RENDER_TOOL}\\` to show UI. Arguments: \\`target\\` first, then \\`operations\\` (A2UI v1.0 operations, applied in order).\n\n${GENERATIVE_UI_WHEN_TO_SHOW}\n\nEvery operation has \"version\":\"v1.0\" and exactly one of:\n${operations.map((op) => `- ${op}`).join(\"\\n\")}\n\nRules:\n${rules.map((rule, index) => `${index + 1}. ${rule}`).join(\"\\n\")}`,\n `### Targets\\n${targets || \"- none\"}`,\n `### Components\\n${components || \"- none\"}`,\n `### Functions\\n${functions || \"- none\"}`,\n `### Existing surfaces\\n${surfaceNotes}${surfaces || \"- none\"}`,\n ].join(\"\\n\\n\");\n}\n"],"mappings":"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"}
@@ -0,0 +1,160 @@
1
+ const require_is_record = require('./is-record.cjs');
2
+
3
+ //#region src/generative-ui/render-ui-args.ts
4
+ /**
5
+ * Reads `target` and every complete `operations[]` element from a possibly
6
+ * truncated `render_ui` argument string.
7
+ */
8
+ function extractRenderUIArgs(text) {
9
+ return new RenderUIArgsScanner().scan(text);
10
+ }
11
+ /**
12
+ * The parser of {@link extractRenderUIArgs}, with its state kept between
13
+ * calls. Each call scans only the text after the text it scanned before, so
14
+ * a streamed argument string is scanned once in total.
15
+ */
16
+ var RenderUIArgsScanner = class {
17
+ constructor() {
18
+ this.result = { operations: [] };
19
+ this.stack = [];
20
+ this.inString = false;
21
+ this.escaped = false;
22
+ this.stringStart = -1;
23
+ this.pendingKey = null;
24
+ this.currentKey = null;
25
+ this.expectingValue = false;
26
+ this.inOperations = false;
27
+ this.elementStart = -1;
28
+ this.scanned = 0;
29
+ }
30
+ /**
31
+ * Scans `text` from where the last call stopped.
32
+ *
33
+ * @param text - The whole text so far. It starts with the text of the
34
+ * last call.
35
+ * @returns The result so far. It is the same object on each call.
36
+ */
37
+ scan(text) {
38
+ const { result, stack } = this;
39
+ let { inString, escaped, stringStart, pendingKey, currentKey, expectingValue, inOperations, elementStart } = this;
40
+ for (let i = this.scanned; i < text.length; i++) {
41
+ const ch = text[i];
42
+ if (inString) {
43
+ if (escaped) escaped = false;
44
+ else if (ch === "\\") escaped = true;
45
+ else if (ch === "\"") {
46
+ inString = false;
47
+ if (stack.length === 1) {
48
+ const literal = text.slice(stringStart, i + 1);
49
+ if (expectingValue) {
50
+ if (currentKey === "target") try {
51
+ result.target = JSON.parse(literal);
52
+ } catch {}
53
+ expectingValue = false;
54
+ } else pendingKey = literal;
55
+ }
56
+ }
57
+ continue;
58
+ }
59
+ switch (ch) {
60
+ case "\"":
61
+ inString = true;
62
+ stringStart = i;
63
+ break;
64
+ case ":":
65
+ if (stack.length === 1 && pendingKey !== null) {
66
+ try {
67
+ currentKey = JSON.parse(pendingKey);
68
+ } catch {
69
+ currentKey = null;
70
+ }
71
+ pendingKey = null;
72
+ expectingValue = true;
73
+ }
74
+ break;
75
+ case ",":
76
+ if (stack.length === 1) {
77
+ expectingValue = false;
78
+ currentKey = null;
79
+ }
80
+ break;
81
+ case "{":
82
+ if (inOperations && stack.length === 2) elementStart = i;
83
+ stack.push("{");
84
+ break;
85
+ case "[":
86
+ if (stack.length === 1 && expectingValue && currentKey === "operations") inOperations = true;
87
+ stack.push("[");
88
+ break;
89
+ case "}":
90
+ case "]":
91
+ stack.pop();
92
+ if (ch === "}" && inOperations && stack.length === 2 && elementStart >= 0) {
93
+ result.operations.push(parseObject(text.slice(elementStart, i + 1)));
94
+ elementStart = -1;
95
+ }
96
+ if (ch === "]" && inOperations && stack.length === 1) {
97
+ inOperations = false;
98
+ expectingValue = false;
99
+ }
100
+ break;
101
+ }
102
+ }
103
+ this.inString = inString;
104
+ this.escaped = escaped;
105
+ this.stringStart = stringStart;
106
+ this.pendingKey = pendingKey;
107
+ this.currentKey = currentKey;
108
+ this.expectingValue = expectingValue;
109
+ this.inOperations = inOperations;
110
+ this.elementStart = elementStart;
111
+ this.scanned = text.length;
112
+ if (elementStart >= 0) result.incompleteOperation = true;
113
+ else delete result.incompleteOperation;
114
+ return result;
115
+ }
116
+ };
117
+ function parseObject(raw) {
118
+ try {
119
+ const value = JSON.parse(raw);
120
+ return require_is_record.isRecord(value) ? value : null;
121
+ } catch {
122
+ return null;
123
+ }
124
+ }
125
+ /** Feeds streamed argument deltas and reports operations not yet seen. */
126
+ var RenderUIArgsStream = class {
127
+ constructor() {
128
+ this.buffer = "";
129
+ this.emitted = 0;
130
+ this.incomplete = false;
131
+ this.scanner = new RenderUIArgsScanner();
132
+ }
133
+ push(delta) {
134
+ this.buffer += delta;
135
+ const { target, operations, incompleteOperation } = this.scanner.scan(this.buffer);
136
+ const newOperations = operations.slice(this.emitted);
137
+ this.emitted = operations.length;
138
+ this.incomplete = incompleteOperation === true;
139
+ return {
140
+ target,
141
+ newOperations
142
+ };
143
+ }
144
+ /** Every argument delta received so far, concatenated. */
145
+ get text() {
146
+ return this.buffer;
147
+ }
148
+ /**
149
+ * True when the text received so far ends inside an `operations[]` element.
150
+ * Once the tool call has ended, that element was truncated.
151
+ */
152
+ get hasIncompleteOperation() {
153
+ return this.incomplete;
154
+ }
155
+ };
156
+
157
+ //#endregion
158
+ exports.RenderUIArgsStream = RenderUIArgsStream;
159
+ exports.extractRenderUIArgs = extractRenderUIArgs;
160
+ //# sourceMappingURL=render-ui-args.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-ui-args.cjs","names":["isRecord"],"sources":["../../src/generative-ui/render-ui-args.ts"],"sourcesContent":["import { isRecord } from \"./is-record\";\nexport interface ExtractedRenderUIArgs {\n target?: string;\n /**\n * Complete elements of the `operations` array, in order. A balanced element\n * that is not a valid JSON object is returned as `null`.\n */\n operations: Array<Record<string, unknown> | null>;\n /**\n * Set when an `operations[]` element was opened but its closing brace never\n * arrived: the text ends mid-operation (still streaming, or truncated).\n */\n incompleteOperation?: boolean;\n}\n\n/**\n * Reads `target` and every complete `operations[]` element from a possibly\n * truncated `render_ui` argument string.\n */\nexport function extractRenderUIArgs(text: string) {\n return new RenderUIArgsScanner().scan(text);\n}\n\n/**\n * The parser of {@link extractRenderUIArgs}, with its state kept between\n * calls. Each call scans only the text after the text it scanned before, so\n * a streamed argument string is scanned once in total.\n */\nclass RenderUIArgsScanner {\n private readonly result: ExtractedRenderUIArgs = { operations: [] };\n private readonly stack: Array<\"{\" | \"[\"> = [];\n private inString = false;\n private escaped = false;\n private stringStart = -1;\n private pendingKey: string | null = null;\n private currentKey: string | null = null;\n private expectingValue = false;\n private inOperations = false;\n private elementStart = -1;\n private scanned = 0;\n\n /**\n * Scans `text` from where the last call stopped.\n *\n * @param text - The whole text so far. It starts with the text of the\n * last call.\n * @returns The result so far. It is the same object on each call.\n */\n scan(text: string) {\n const { result, stack } = this;\n let {\n inString,\n escaped,\n stringStart,\n pendingKey,\n currentKey,\n expectingValue,\n inOperations,\n elementStart,\n } = this;\n for (let i = this.scanned; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (ch === \"\\\\\") {\n escaped = true;\n } else if (ch === '\"') {\n inString = false;\n if (stack.length === 1) {\n const literal = text.slice(stringStart, i + 1);\n if (expectingValue) {\n if (currentKey === \"target\") {\n try {\n result.target = JSON.parse(literal);\n } catch {\n // Unreachable for a closed literal; keep scanning.\n }\n }\n expectingValue = false;\n } else {\n pendingKey = literal;\n }\n }\n }\n continue;\n }\n switch (ch) {\n case '\"':\n inString = true;\n stringStart = i;\n break;\n case \":\":\n if (stack.length === 1 && pendingKey !== null) {\n try {\n currentKey = JSON.parse(pendingKey);\n } catch {\n currentKey = null;\n }\n pendingKey = null;\n expectingValue = true;\n }\n break;\n case \",\":\n if (stack.length === 1) {\n expectingValue = false;\n currentKey = null;\n }\n break;\n case \"{\":\n if (inOperations && stack.length === 2) elementStart = i;\n stack.push(\"{\");\n break;\n case \"[\":\n if (\n stack.length === 1 &&\n expectingValue &&\n currentKey === \"operations\"\n ) {\n inOperations = true;\n }\n stack.push(\"[\");\n break;\n case \"}\":\n case \"]\":\n stack.pop();\n if (\n ch === \"}\" &&\n inOperations &&\n stack.length === 2 &&\n elementStart >= 0\n ) {\n result.operations.push(\n parseObject(text.slice(elementStart, i + 1)),\n );\n elementStart = -1;\n }\n if (ch === \"]\" && inOperations && stack.length === 1) {\n inOperations = false;\n expectingValue = false;\n }\n break;\n }\n }\n this.inString = inString;\n this.escaped = escaped;\n this.stringStart = stringStart;\n this.pendingKey = pendingKey;\n this.currentKey = currentKey;\n this.expectingValue = expectingValue;\n this.inOperations = inOperations;\n this.elementStart = elementStart;\n this.scanned = text.length;\n if (elementStart >= 0) result.incompleteOperation = true;\n else delete result.incompleteOperation;\n return result;\n }\n}\n\nfunction parseObject(raw: string) {\n try {\n const value: unknown = JSON.parse(raw);\n return isRecord(value) ? value : null;\n } catch {\n return null;\n }\n}\n\n/** Feeds streamed argument deltas and reports operations not yet seen. */\nexport class RenderUIArgsStream {\n private buffer = \"\";\n private emitted = 0;\n private incomplete = false;\n private readonly scanner = new RenderUIArgsScanner();\n\n push(delta: string) {\n this.buffer += delta;\n const { target, operations, incompleteOperation } = this.scanner.scan(\n this.buffer,\n );\n const newOperations = operations.slice(this.emitted);\n this.emitted = operations.length;\n this.incomplete = incompleteOperation === true;\n return { target, newOperations };\n }\n\n /** Every argument delta received so far, concatenated. */\n get text() {\n return this.buffer;\n }\n\n /**\n * True when the text received so far ends inside an `operations[]` element.\n * Once the tool call has ended, that element was truncated.\n */\n get hasIncompleteOperation() {\n return this.incomplete;\n }\n}\n"],"mappings":";;;;;;;AAmBA,SAAgB,oBAAoB,MAAc;AAChD,QAAO,IAAI,qBAAqB,CAAC,KAAK,KAAK;;;;;;;AAQ7C,IAAM,sBAAN,MAA0B;;gBACyB,EAAE,YAAY,EAAE,EAAE;eACxB,EAAE;kBAC1B;iBACD;qBACI;oBACc;oBACA;wBACX;sBACF;sBACA;iBACL;;;;;;;;;CASlB,KAAK,MAAc;EACjB,MAAM,EAAE,QAAQ,UAAU;EAC1B,IAAI,EACF,UACA,SACA,aACA,YACA,YACA,gBACA,cACA,iBACE;AACJ,OAAK,IAAI,IAAI,KAAK,SAAS,IAAI,KAAK,QAAQ,KAAK;GAC/C,MAAM,KAAK,KAAK;AAChB,OAAI,UAAU;AACZ,QAAI,QACF,WAAU;aACD,OAAO,KAChB,WAAU;aACD,OAAO,MAAK;AACrB,gBAAW;AACX,SAAI,MAAM,WAAW,GAAG;MACtB,MAAM,UAAU,KAAK,MAAM,aAAa,IAAI,EAAE;AAC9C,UAAI,gBAAgB;AAClB,WAAI,eAAe,SACjB,KAAI;AACF,eAAO,SAAS,KAAK,MAAM,QAAQ;eAC7B;AAIV,wBAAiB;YAEjB,cAAa;;;AAInB;;AAEF,WAAQ,IAAR;IACE,KAAK;AACH,gBAAW;AACX,mBAAc;AACd;IACF,KAAK;AACH,SAAI,MAAM,WAAW,KAAK,eAAe,MAAM;AAC7C,UAAI;AACF,oBAAa,KAAK,MAAM,WAAW;cAC7B;AACN,oBAAa;;AAEf,mBAAa;AACb,uBAAiB;;AAEnB;IACF,KAAK;AACH,SAAI,MAAM,WAAW,GAAG;AACtB,uBAAiB;AACjB,mBAAa;;AAEf;IACF,KAAK;AACH,SAAI,gBAAgB,MAAM,WAAW,EAAG,gBAAe;AACvD,WAAM,KAAK,IAAI;AACf;IACF,KAAK;AACH,SACE,MAAM,WAAW,KACjB,kBACA,eAAe,aAEf,gBAAe;AAEjB,WAAM,KAAK,IAAI;AACf;IACF,KAAK;IACL,KAAK;AACH,WAAM,KAAK;AACX,SACE,OAAO,OACP,gBACA,MAAM,WAAW,KACjB,gBAAgB,GAChB;AACA,aAAO,WAAW,KAChB,YAAY,KAAK,MAAM,cAAc,IAAI,EAAE,CAAC,CAC7C;AACD,qBAAe;;AAEjB,SAAI,OAAO,OAAO,gBAAgB,MAAM,WAAW,GAAG;AACpD,qBAAe;AACf,uBAAiB;;AAEnB;;;AAGN,OAAK,WAAW;AAChB,OAAK,UAAU;AACf,OAAK,cAAc;AACnB,OAAK,aAAa;AAClB,OAAK,aAAa;AAClB,OAAK,iBAAiB;AACtB,OAAK,eAAe;AACpB,OAAK,eAAe;AACpB,OAAK,UAAU,KAAK;AACpB,MAAI,gBAAgB,EAAG,QAAO,sBAAsB;MAC/C,QAAO,OAAO;AACnB,SAAO;;;AAIX,SAAS,YAAY,KAAa;AAChC,KAAI;EACF,MAAM,QAAiB,KAAK,MAAM,IAAI;AACtC,SAAOA,2BAAS,MAAM,GAAG,QAAQ;SAC3B;AACN,SAAO;;;;AAKX,IAAa,qBAAb,MAAgC;;gBACb;iBACC;oBACG;iBACM,IAAI,qBAAqB;;CAEpD,KAAK,OAAe;AAClB,OAAK,UAAU;EACf,MAAM,EAAE,QAAQ,YAAY,wBAAwB,KAAK,QAAQ,KAC/D,KAAK,OACN;EACD,MAAM,gBAAgB,WAAW,MAAM,KAAK,QAAQ;AACpD,OAAK,UAAU,WAAW;AAC1B,OAAK,aAAa,wBAAwB;AAC1C,SAAO;GAAE;GAAQ;GAAe;;;CAIlC,IAAI,OAAO;AACT,SAAO,KAAK;;;;;;CAOd,IAAI,yBAAyB;AAC3B,SAAO,KAAK"}
@@ -0,0 +1,40 @@
1
+ //#region src/generative-ui/render-ui-args.d.ts
2
+ interface ExtractedRenderUIArgs {
3
+ target?: string;
4
+ /**
5
+ * Complete elements of the `operations` array, in order. A balanced element
6
+ * that is not a valid JSON object is returned as `null`.
7
+ */
8
+ operations: Array<Record<string, unknown> | null>;
9
+ /**
10
+ * Set when an `operations[]` element was opened but its closing brace never
11
+ * arrived: the text ends mid-operation (still streaming, or truncated).
12
+ */
13
+ incompleteOperation?: boolean;
14
+ }
15
+ /**
16
+ * Reads `target` and every complete `operations[]` element from a possibly
17
+ * truncated `render_ui` argument string.
18
+ */
19
+ declare function extractRenderUIArgs(text: string): ExtractedRenderUIArgs;
20
+ /** Feeds streamed argument deltas and reports operations not yet seen. */
21
+ declare class RenderUIArgsStream {
22
+ private buffer;
23
+ private emitted;
24
+ private incomplete;
25
+ private readonly scanner;
26
+ push(delta: string): {
27
+ target: string | undefined;
28
+ newOperations: (Record<string, unknown> | null)[];
29
+ };
30
+ /** Every argument delta received so far, concatenated. */
31
+ get text(): string;
32
+ /**
33
+ * True when the text received so far ends inside an `operations[]` element.
34
+ * Once the tool call has ended, that element was truncated.
35
+ */
36
+ get hasIncompleteOperation(): boolean;
37
+ }
38
+ //#endregion
39
+ export { ExtractedRenderUIArgs, RenderUIArgsStream, extractRenderUIArgs };
40
+ //# sourceMappingURL=render-ui-args.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-ui-args.d.cts","names":[],"sources":["../../src/generative-ui/render-ui-args.ts"],"mappings":";UACiB,qBAAA;EACf,MAAA;EADoC;;;;EAMpC,UAAA,EAAY,KAAA,CAAM,MAAA;EAAN;;;;EAKZ,mBAAA;AAAA;;;;;iBAOc,mBAAA,CAAoB,IAAA,WAAY,qBAAA;;cAsJnC,kBAAA;EAAA,QACH,MAAA;EAAA,QACA,OAAA;EAAA,QACA,UAAA;EAAA,iBACS,OAAA;EAEjB,IAAA,CAAK,KAAA;;oBANwB,MAAA;EAAA;;MAkBzB,IAAA,CAAA;EAAA;;;;EAAA,IAQA,sBAAA,CAAA;AAAA"}
@@ -0,0 +1,40 @@
1
+ //#region src/generative-ui/render-ui-args.d.ts
2
+ interface ExtractedRenderUIArgs {
3
+ target?: string;
4
+ /**
5
+ * Complete elements of the `operations` array, in order. A balanced element
6
+ * that is not a valid JSON object is returned as `null`.
7
+ */
8
+ operations: Array<Record<string, unknown> | null>;
9
+ /**
10
+ * Set when an `operations[]` element was opened but its closing brace never
11
+ * arrived: the text ends mid-operation (still streaming, or truncated).
12
+ */
13
+ incompleteOperation?: boolean;
14
+ }
15
+ /**
16
+ * Reads `target` and every complete `operations[]` element from a possibly
17
+ * truncated `render_ui` argument string.
18
+ */
19
+ declare function extractRenderUIArgs(text: string): ExtractedRenderUIArgs;
20
+ /** Feeds streamed argument deltas and reports operations not yet seen. */
21
+ declare class RenderUIArgsStream {
22
+ private buffer;
23
+ private emitted;
24
+ private incomplete;
25
+ private readonly scanner;
26
+ push(delta: string): {
27
+ target: string | undefined;
28
+ newOperations: (Record<string, unknown> | null)[];
29
+ };
30
+ /** Every argument delta received so far, concatenated. */
31
+ get text(): string;
32
+ /**
33
+ * True when the text received so far ends inside an `operations[]` element.
34
+ * Once the tool call has ended, that element was truncated.
35
+ */
36
+ get hasIncompleteOperation(): boolean;
37
+ }
38
+ //#endregion
39
+ export { ExtractedRenderUIArgs, RenderUIArgsStream, extractRenderUIArgs };
40
+ //# sourceMappingURL=render-ui-args.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-ui-args.d.mts","names":[],"sources":["../../src/generative-ui/render-ui-args.ts"],"mappings":";UACiB,qBAAA;EACf,MAAA;EADoC;;;;EAMpC,UAAA,EAAY,KAAA,CAAM,MAAA;EAAN;;;;EAKZ,mBAAA;AAAA;;;;;iBAOc,mBAAA,CAAoB,IAAA,WAAY,qBAAA;;cAsJnC,kBAAA;EAAA,QACH,MAAA;EAAA,QACA,OAAA;EAAA,QACA,UAAA;EAAA,iBACS,OAAA;EAEjB,IAAA,CAAK,KAAA;;oBANwB,MAAA;EAAA;;MAkBzB,IAAA,CAAA;EAAA;;;;EAAA,IAQA,sBAAA,CAAA;AAAA"}
@@ -0,0 +1,159 @@
1
+ import { isRecord } from "./is-record.mjs";
2
+
3
+ //#region src/generative-ui/render-ui-args.ts
4
+ /**
5
+ * Reads `target` and every complete `operations[]` element from a possibly
6
+ * truncated `render_ui` argument string.
7
+ */
8
+ function extractRenderUIArgs(text) {
9
+ return new RenderUIArgsScanner().scan(text);
10
+ }
11
+ /**
12
+ * The parser of {@link extractRenderUIArgs}, with its state kept between
13
+ * calls. Each call scans only the text after the text it scanned before, so
14
+ * a streamed argument string is scanned once in total.
15
+ */
16
+ var RenderUIArgsScanner = class {
17
+ constructor() {
18
+ this.result = { operations: [] };
19
+ this.stack = [];
20
+ this.inString = false;
21
+ this.escaped = false;
22
+ this.stringStart = -1;
23
+ this.pendingKey = null;
24
+ this.currentKey = null;
25
+ this.expectingValue = false;
26
+ this.inOperations = false;
27
+ this.elementStart = -1;
28
+ this.scanned = 0;
29
+ }
30
+ /**
31
+ * Scans `text` from where the last call stopped.
32
+ *
33
+ * @param text - The whole text so far. It starts with the text of the
34
+ * last call.
35
+ * @returns The result so far. It is the same object on each call.
36
+ */
37
+ scan(text) {
38
+ const { result, stack } = this;
39
+ let { inString, escaped, stringStart, pendingKey, currentKey, expectingValue, inOperations, elementStart } = this;
40
+ for (let i = this.scanned; i < text.length; i++) {
41
+ const ch = text[i];
42
+ if (inString) {
43
+ if (escaped) escaped = false;
44
+ else if (ch === "\\") escaped = true;
45
+ else if (ch === "\"") {
46
+ inString = false;
47
+ if (stack.length === 1) {
48
+ const literal = text.slice(stringStart, i + 1);
49
+ if (expectingValue) {
50
+ if (currentKey === "target") try {
51
+ result.target = JSON.parse(literal);
52
+ } catch {}
53
+ expectingValue = false;
54
+ } else pendingKey = literal;
55
+ }
56
+ }
57
+ continue;
58
+ }
59
+ switch (ch) {
60
+ case "\"":
61
+ inString = true;
62
+ stringStart = i;
63
+ break;
64
+ case ":":
65
+ if (stack.length === 1 && pendingKey !== null) {
66
+ try {
67
+ currentKey = JSON.parse(pendingKey);
68
+ } catch {
69
+ currentKey = null;
70
+ }
71
+ pendingKey = null;
72
+ expectingValue = true;
73
+ }
74
+ break;
75
+ case ",":
76
+ if (stack.length === 1) {
77
+ expectingValue = false;
78
+ currentKey = null;
79
+ }
80
+ break;
81
+ case "{":
82
+ if (inOperations && stack.length === 2) elementStart = i;
83
+ stack.push("{");
84
+ break;
85
+ case "[":
86
+ if (stack.length === 1 && expectingValue && currentKey === "operations") inOperations = true;
87
+ stack.push("[");
88
+ break;
89
+ case "}":
90
+ case "]":
91
+ stack.pop();
92
+ if (ch === "}" && inOperations && stack.length === 2 && elementStart >= 0) {
93
+ result.operations.push(parseObject(text.slice(elementStart, i + 1)));
94
+ elementStart = -1;
95
+ }
96
+ if (ch === "]" && inOperations && stack.length === 1) {
97
+ inOperations = false;
98
+ expectingValue = false;
99
+ }
100
+ break;
101
+ }
102
+ }
103
+ this.inString = inString;
104
+ this.escaped = escaped;
105
+ this.stringStart = stringStart;
106
+ this.pendingKey = pendingKey;
107
+ this.currentKey = currentKey;
108
+ this.expectingValue = expectingValue;
109
+ this.inOperations = inOperations;
110
+ this.elementStart = elementStart;
111
+ this.scanned = text.length;
112
+ if (elementStart >= 0) result.incompleteOperation = true;
113
+ else delete result.incompleteOperation;
114
+ return result;
115
+ }
116
+ };
117
+ function parseObject(raw) {
118
+ try {
119
+ const value = JSON.parse(raw);
120
+ return isRecord(value) ? value : null;
121
+ } catch {
122
+ return null;
123
+ }
124
+ }
125
+ /** Feeds streamed argument deltas and reports operations not yet seen. */
126
+ var RenderUIArgsStream = class {
127
+ constructor() {
128
+ this.buffer = "";
129
+ this.emitted = 0;
130
+ this.incomplete = false;
131
+ this.scanner = new RenderUIArgsScanner();
132
+ }
133
+ push(delta) {
134
+ this.buffer += delta;
135
+ const { target, operations, incompleteOperation } = this.scanner.scan(this.buffer);
136
+ const newOperations = operations.slice(this.emitted);
137
+ this.emitted = operations.length;
138
+ this.incomplete = incompleteOperation === true;
139
+ return {
140
+ target,
141
+ newOperations
142
+ };
143
+ }
144
+ /** Every argument delta received so far, concatenated. */
145
+ get text() {
146
+ return this.buffer;
147
+ }
148
+ /**
149
+ * True when the text received so far ends inside an `operations[]` element.
150
+ * Once the tool call has ended, that element was truncated.
151
+ */
152
+ get hasIncompleteOperation() {
153
+ return this.incomplete;
154
+ }
155
+ };
156
+
157
+ //#endregion
158
+ export { RenderUIArgsStream, extractRenderUIArgs };
159
+ //# sourceMappingURL=render-ui-args.mjs.map