@copilotkit/core 2.0.0-rc.31 → 2.0.0-rc.33

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 (36) hide show
  1. package/dist/a2ui-markdown-BxZr1mEU.mjs +1360 -0
  2. package/dist/a2ui-markdown-BxZr1mEU.mjs.map +1 -0
  3. package/dist/a2ui-markdown-DkMXFQih.cjs +1419 -0
  4. package/dist/a2ui-markdown-DkMXFQih.cjs.map +1 -0
  5. package/dist/chat-configuration.cjs +1 -1
  6. package/dist/chat-configuration.d.cts +1 -1
  7. package/dist/chat-configuration.d.mts +1 -1
  8. package/dist/chat-configuration.mjs +1 -1
  9. package/dist/generative-ui/index.cjs +3121 -0
  10. package/dist/generative-ui/index.cjs.map +1 -0
  11. package/dist/generative-ui/index.d.cts +974 -0
  12. package/dist/generative-ui/index.d.cts.map +1 -0
  13. package/dist/generative-ui/index.d.mts +974 -0
  14. package/dist/generative-ui/index.d.mts.map +1 -0
  15. package/dist/generative-ui/index.mjs +3075 -0
  16. package/dist/generative-ui/index.mjs.map +1 -0
  17. package/dist/index.cjs +45 -1381
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.cts +1 -1
  20. package/dist/index.d.mts +1 -1
  21. package/dist/index.mjs +36 -1372
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/index.umd.js +28 -14
  24. package/dist/index.umd.js.map +1 -1
  25. package/dist/{learning-bridge-B0AcB3tM.d.mts → learning-bridge-C_WCUqF-.d.cts} +12 -5
  26. package/dist/learning-bridge-C_WCUqF-.d.cts.map +1 -0
  27. package/dist/{learning-bridge-ByrMGShn.d.cts → learning-bridge-D30guTHM.d.mts} +12 -5
  28. package/dist/learning-bridge-D30guTHM.d.mts.map +1 -0
  29. package/dist/{viewport-D9ZX0xqz.mjs → viewport-CksL5y8p.mjs} +1 -1
  30. package/dist/{viewport-D9ZX0xqz.mjs.map → viewport-CksL5y8p.mjs.map} +1 -1
  31. package/dist/{viewport-GwjIosf7.cjs → viewport-D-tuKCeb.cjs} +1 -1
  32. package/dist/{viewport-GwjIosf7.cjs.map → viewport-D-tuKCeb.cjs.map} +1 -1
  33. package/package.json +12 -5
  34. package/tsdown.config.ts +5 -0
  35. package/dist/learning-bridge-B0AcB3tM.d.mts.map +0 -1
  36. package/dist/learning-bridge-ByrMGShn.d.cts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["numberOf"],"sources":["../../src/generative-ui/runtime.ts","../../src/generative-ui/functions.ts","../../src/generative-ui/function-calls.ts","../../src/generative-ui/calc.ts","../../src/generative-ui/resolve.ts","../../src/generative-ui/surface-manager.ts","../../src/generative-ui/dispatcher.ts","../../src/generative-ui/events.ts","../../src/generative-ui/manifest.ts","../../src/generative-ui/markdown-source.ts","../../src/generative-ui/action-message.ts","../../src/generative-ui/debug-source.ts","../../src/generative-ui/accessibility.ts","../../src/generative-ui/targets.ts"],"sourcesContent":["import type {\n GenerativeUI,\n GenerativeUIErrorInfo,\n GenerativeUIInvokeResult,\n} from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUIUserEvent } from \"@copilotkit/shared\";\nimport type { GenerativeUIDispatcher } from \"./dispatcher\";\nimport type { GenerativeUISurfaceManager } from \"./surface-manager\";\n\n/**\n * What the engine needs from the runtime of a framework: the surfaces, the\n * function dispatcher, and how user events and errors leave the UI. A\n * framework's runtime object satisfies it structurally and adds its own\n * config and theme on top.\n */\nexport interface GenerativeUIEngine {\n manager: GenerativeUISurfaceManager;\n dispatcher: GenerativeUIDispatcher;\n /** The generative UI given to the provider. */\n ui: GenerativeUI;\n forwardEvent: (\n event: GenerativeUIUserEvent,\n agentId: string | undefined,\n ) => Promise<GenerativeUIInvokeResult>;\n reportError: (info: GenerativeUIErrorInfo) => void;\n}\n\n/**\n * Reports an error without ever throwing: `reportError` reaches host code\n * (`onError`), and a throwing host callback must not break rendering or an\n * event handler.\n */\nexport function reportErrorSafely(\n engine: Pick<GenerativeUIEngine, \"reportError\">,\n info: GenerativeUIErrorInfo,\n): void {\n try {\n engine.reportError(info);\n } catch {\n // Intentionally swallowed: there is nowhere safe left to report to.\n }\n}\n","import {\n GENERATIVE_UI_FUNCTIONS,\n isValidationResult,\n} from \"@copilotkit/shared\";\nimport type { A2UIValidationResult } from \"@copilotkit/shared\";\n\n/**\n * The renderer-side functions of the A2UI 1.0 basic catalog. Each one takes\n * resolved args (no bindings left in them) and gives a plain value. They\n * run synchronously, so a prop bound to one updates in the same render as\n * the data it reads. The signatures the model sees are in\n * `@copilotkit/shared` (`A2UI_BASIC_FUNCTIONS`).\n */\n\n/** Thrown for a bad call: an unknown function, bad args, or a bad value. */\nexport class ExpressionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ExpressionError\";\n }\n}\n\nexport type BasicFunction = (args: Record<string, unknown>) => unknown;\n\n/** The boolean of a DynamicBoolean: a ValidationResult counts as `valid`. */\nexport function truthOf(value: unknown): boolean {\n if (isValidationResult(value)) return value.valid;\n return Boolean(value);\n}\n\nconst valid = (): A2UIValidationResult => ({ valid: true });\n/** A failed result. `code` names the failure, the same for every locale. */\nconst invalid = (message: string, code: string): A2UIValidationResult => ({\n valid: false,\n message,\n code,\n});\n\nfunction text(value: unknown) {\n if (value === undefined || value === null) return \"\";\n return typeof value === \"string\" ? value : String(value);\n}\n\nfunction numberOf(value: unknown) {\n if (typeof value === \"number\") return value;\n if (typeof value === \"string\" && value.trim() !== \"\") return Number(value);\n return Number.NaN;\n}\n\nfunction optionalNumber(value: unknown, name: string) {\n if (value === undefined || value === null) return undefined;\n const parsed = numberOf(value);\n if (Number.isNaN(parsed))\n throw new ExpressionError(`${name} must be a number`);\n return parsed;\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/** The locale of the user. `undefined` lets Intl pick the default. */\nfunction locale() {\n return typeof navigator !== \"undefined\" ? navigator.language : undefined;\n}\n\nfunction numberFormat(\n args: Record<string, unknown>,\n options: Intl.NumberFormatOptions,\n) {\n const decimals = optionalNumber(args.decimals, \"decimals\");\n return new Intl.NumberFormat(locale(), {\n ...options,\n useGrouping: args.grouping !== false,\n ...(decimals === undefined\n ? {}\n : { minimumFractionDigits: decimals, maximumFractionDigits: decimals }),\n });\n}\n\n/** A date from an ISO string, a timestamp, or a Date. */\nfunction dateOf(value: unknown) {\n const date =\n value instanceof Date\n ? value\n : typeof value === \"number\"\n ? new Date(value)\n : typeof value === \"string\"\n ? new Date(\n /^\\d{4}-\\d{2}-\\d{2}$/.test(value) ? `${value}T00:00` : value,\n )\n : undefined;\n if (date === undefined || Number.isNaN(date.getTime())) {\n throw new ExpressionError(\"value must be a date\");\n }\n return date;\n}\n\nconst pad = (value: number, width: number) =>\n String(value).padStart(width, \"0\");\n\n/**\n * A TR35 field is a run of one letter (\"EEE\" is one abbreviated weekday,\n * not three), and text in single quotes is literal. Letters that are not\n * fields stay as they are.\n */\nconst DATE_FIELD = /([A-Za-z])\\1*|'(?:[^']|'')*'/g;\n\nfunction formatDatePattern(date: Date, pattern: string) {\n const parts = (options: Intl.DateTimeFormatOptions) =>\n new Intl.DateTimeFormat(locale(), options).format(date);\n const hours12 = date.getHours() % 12 || 12;\n const numeric = (value: number, width: number) =>\n width >= 2 ? pad(value, 2) : String(value);\n return pattern.replace(DATE_FIELD, (token) => {\n if (token.startsWith(\"'\")) return token.slice(1, -1).replace(/''/g, \"'\");\n const width = token.length;\n switch (token[0]) {\n case \"y\":\n return width === 2\n ? pad(date.getFullYear() % 100, 2)\n : String(date.getFullYear());\n case \"M\":\n if (width >= 4) return parts({ month: \"long\" });\n if (width === 3) return parts({ month: \"short\" });\n return numeric(date.getMonth() + 1, width);\n case \"d\":\n return numeric(date.getDate(), width);\n case \"E\":\n return parts({ weekday: width >= 4 ? \"long\" : \"short\" });\n case \"H\":\n return numeric(date.getHours(), width);\n case \"h\":\n return numeric(hours12, width);\n case \"m\":\n return pad(date.getMinutes(), 2);\n case \"s\":\n return pad(date.getSeconds(), 2);\n case \"a\":\n return date.getHours() < 12 ? \"AM\" : \"PM\";\n default:\n return token;\n }\n });\n}\n\n/** Opens an http(s) URL in a new tab. Any other scheme is refused. */\nexport function openUrlSafely(url: unknown) {\n if (typeof url !== \"string\" || url === \"\") {\n throw new ExpressionError(\"url must be a string\");\n }\n if (typeof window === \"undefined\") return;\n let parsed: URL;\n try {\n parsed = new URL(url, window.location.href);\n } catch {\n throw new ExpressionError(`\"${url}\" is not a URL`);\n }\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n throw new ExpressionError(\n `openUrl takes only http(s) URLs, not ${parsed.protocol}`,\n );\n }\n window.open(parsed.href, \"_blank\", \"noopener,noreferrer\");\n}\n\n/**\n * The basic functions, except `formatString`, which needs the resolver.\n * `calc` and `series` are added by `resolve.ts`, which imports both.\n */\nexport const BASIC_FUNCTIONS: Record<string, BasicFunction> = {\n required: ({ value }) => {\n const isEmpty =\n value === undefined ||\n value === null ||\n value === \"\" ||\n (Array.isArray(value) && value.length === 0);\n return isEmpty ? invalid(\"Required\", \"required\") : valid();\n },\n regex: ({ value, pattern }) => {\n if (typeof pattern !== \"string\") {\n throw new ExpressionError(\"pattern must be a string\");\n }\n let expression: RegExp;\n try {\n expression = new RegExp(pattern, \"u\");\n } catch {\n throw new ExpressionError(`\"${pattern}\" is not a regular expression`);\n }\n return expression.test(text(value))\n ? valid()\n : invalid(\"Invalid format\", \"pattern\");\n },\n length: ({ value, min, max }) => {\n const size = text(value).length;\n const low = optionalNumber(min, \"min\");\n const high = optionalNumber(max, \"max\");\n if (low !== undefined && size < low)\n return invalid(`At least ${low} characters`, \"tooShort\");\n if (high !== undefined && size > high)\n return invalid(`At most ${high} characters`, \"tooLong\");\n return valid();\n },\n numeric: ({ value, min, max }) => {\n const parsed = numberOf(value);\n if (Number.isNaN(parsed)) return invalid(\"Must be a number\", \"notANumber\");\n const low = optionalNumber(min, \"min\");\n const high = optionalNumber(max, \"max\");\n if (low !== undefined && parsed < low)\n return invalid(`At least ${low}`, \"tooSmall\");\n if (high !== undefined && parsed > high)\n return invalid(`At most ${high}`, \"tooLarge\");\n return valid();\n },\n email: ({ value }) =>\n EMAIL.test(text(value))\n ? valid()\n : invalid(\"Invalid email address\", \"email\"),\n formatNumber: (args) => {\n const parsed = numberOf(args.value);\n if (Number.isNaN(parsed))\n throw new ExpressionError(\"value must be a number\");\n return numberFormat(args, {}).format(parsed);\n },\n formatCurrency: (args) => {\n const parsed = numberOf(args.value);\n if (Number.isNaN(parsed))\n throw new ExpressionError(\"value must be a number\");\n if (typeof args.currency !== \"string\" || args.currency === \"\") {\n throw new ExpressionError(\"currency must be an ISO 4217 code\");\n }\n try {\n return numberFormat(args, {\n style: \"currency\",\n currency: args.currency,\n }).format(parsed);\n } catch {\n throw new ExpressionError(`\"${args.currency}\" is not a currency code`);\n }\n },\n formatDate: ({ value, format }) => {\n if (typeof format !== \"string\") {\n throw new ExpressionError(\"format must be a string\");\n }\n return formatDatePattern(dateOf(value), format);\n },\n pluralize: (args) => {\n const parsed = numberOf(args.value);\n if (Number.isNaN(parsed))\n throw new ExpressionError(\"value must be a number\");\n const category = new Intl.PluralRules(locale()).select(parsed);\n const exact = parsed === 0 ? args.zero : undefined;\n const chosen = exact ?? args[category] ?? args.other;\n return text(chosen);\n },\n and: ({ values }) => {\n if (!Array.isArray(values))\n throw new ExpressionError(\"values must be a list\");\n return values.every(truthOf);\n },\n or: ({ values }) => {\n if (!Array.isArray(values))\n throw new ExpressionError(\"values must be a list\");\n return values.some(truthOf);\n },\n not: ({ value }) => !truthOf(value),\n openUrl: ({ url }) => {\n openUrlSafely(url);\n return undefined;\n },\n};\n\n/** True when the basic function `name` must run from a user gesture. */\nexport function requiresUserActivation(name: string) {\n return GENERATIVE_UI_FUNCTIONS[name]?.requiresUserActivation === true;\n}\n\n/** True when a basic function gives a ValidationResult. */\nexport function givesValidationResult(name: string) {\n return GENERATIVE_UI_FUNCTIONS[name]?.returnType === \"validationResult\";\n}\n","import type { AbstractAgent, Message } from \"@ag-ui/client\";\nimport type { CopilotKitCore } from \"../core\";\nimport {\n A2UI_VERSION,\n GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE,\n randomUUID,\n validateOperation,\n} from \"@copilotkit/shared\";\nimport type {\n A2UIOperation,\n ValidateOperationOptions,\n} from \"@copilotkit/shared\";\nimport type { GenerativeUIDispatcher } from \"./dispatcher\";\nimport type { MarkdownFunctionCall } from \"./markdown-source\";\nimport type { GenerativeUIErrorCode } from \"@copilotkit/shared/generative-ui\";\n\n// The function calls of the agent (`callRendererFunction`), for both\n// transports. Each call runs once per thread, the answers are hidden\n// developer messages, they go to the agent only when it is idle, and a user\n// turn gets at most MAX_FUNCTION_FOLLOW_UPS follow-up runs.\n\n/** At most this many function follow-up runs for each user turn. */\nconst MAX_FUNCTION_FOLLOW_UPS = 5;\n\nexport type ReadonlyMessages = ReadonlyArray<Readonly<Message>>;\n\n/** One agent-called function, as the model sent it. */\nexport interface FunctionCallRequest {\n functionCallId: string;\n /** A `callRendererFunction` operation. It is not validated yet. */\n operation: unknown;\n}\n\n/** The answer to one function call, before it goes to the agent. */\ninterface FunctionCallAnswer {\n /** The text of the developer message: a `rendererFunctionResponse`. */\n content: string;\n /** `false` for a call over the cap. It starts no follow-up run. */\n followUp: boolean;\n}\n\n/** What the runner keeps for the function calls of one thread. */\ninterface ThreadFunctionCalls {\n /** The calls that ran, or that have an answer. They do not run again. */\n done: Set<string>;\n /** The answers that are not in the messages yet, in call order. */\n pending: Promise<FunctionCallAnswer>[];\n /** The id of the last user message: the user turn of `followUps`. */\n turn: string | undefined;\n /** The function follow-up runs of this user turn. */\n followUps: number;\n /** A flush adds answers or waits for its follow-up run. */\n flushing: boolean;\n}\n\n/** True when `value` names a `functionCallId`. */\nfunction hasFunctionCallId(\n value: unknown,\n): value is { functionCallId: string } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"functionCallId\" in value &&\n typeof value.functionCallId === \"string\" &&\n value.functionCallId !== \"\"\n );\n}\n\n/** The `functionCallId` that a developer message answers, if any. */\nfunction answeredCallId(content: string) {\n if (!content.includes(\"rendererFunctionResponse\")) return undefined;\n try {\n const parsed: unknown = JSON.parse(content);\n const response =\n typeof parsed === \"object\" &&\n parsed !== null &&\n \"rendererFunctionResponse\" in parsed\n ? parsed.rendererFunctionResponse\n : undefined;\n return hasFunctionCallId(response) ? response.functionCallId : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The function calls that a developer message in `messages` answers. */\nfunction answeredCallIds(messages: ReadonlyMessages) {\n const ids = new Set<string>();\n for (const message of messages) {\n if (message.role !== \"developer\") continue;\n const id = answeredCallId(message.content);\n if (id !== undefined) ids.add(id);\n }\n return ids;\n}\n\n/** The id of the last user message. A user turn starts with it. */\nfunction lastUserMessageId(messages: ReadonlyMessages) {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (message?.role === \"user\") return message.id;\n }\n return undefined;\n}\n\n/** The function calls of the tool transport: its function-call activities. */\nexport function activityFunctionCalls(messages: ReadonlyMessages) {\n const requests: FunctionCallRequest[] = [];\n for (const message of messages) {\n const isFunctionCall =\n message.role === \"activity\" &&\n message.activityType === GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE;\n if (!isFunctionCall || !hasFunctionCallId(message.content)) continue;\n requests.push({\n functionCallId: message.content.functionCallId,\n operation: {\n version: A2UI_VERSION,\n callRendererFunction: message.content,\n },\n });\n }\n return requests;\n}\n\n/** The function calls of the markdown transport: its fence lines. */\nexport function markdownFunctionCalls(calls: MarkdownFunctionCall[]) {\n const requests: FunctionCallRequest[] = [];\n for (const { operation } of calls) {\n const payload = operation.callRendererFunction;\n // With no functionCallId, there is nothing to answer.\n if (!hasFunctionCallId(payload)) continue;\n requests.push({ functionCallId: payload.functionCallId, operation });\n }\n return requests;\n}\n\n/** The text of a `rendererFunctionResponse` developer message. */\nfunction responseContent(\n response:\n | { functionCallId: string; value: unknown }\n | {\n functionCallId: string;\n error: {\n code: GenerativeUIErrorCode | \"follow_up_limit\";\n message: string;\n };\n },\n) {\n return JSON.stringify({\n version: A2UI_VERSION,\n rendererFunctionResponse: response,\n });\n}\n\nfunction errorAnswer(\n functionCallId: string,\n code: GenerativeUIErrorCode,\n message: string,\n): FunctionCallAnswer {\n return {\n content: responseContent({ functionCallId, error: { code, message } }),\n followUp: true,\n };\n}\n\nconst overCapAnswer = (functionCallId: string): FunctionCallAnswer => ({\n content: responseContent({\n functionCallId,\n error: {\n code: \"follow_up_limit\",\n message: `The function did not run. A user turn can have at most ${MAX_FUNCTION_FOLLOW_UPS} function follow-up runs. Wait for the next user message.`,\n },\n }),\n followUp: false,\n});\n\nexport interface FunctionCallRunnerOptions {\n /** Starts the follow-up runs. A framework's core subclass fits. */\n core: Pick<CopilotKitCore, \"runAgent\">;\n dispatcher: GenerativeUIDispatcher;\n manifest: ValidateOperationOptions[\"manifest\"];\n /**\n * Lets the app apply the state that the handlers set before the follow-up\n * run reads it: React commits its pending updates, Angular runs a change\n * detection tick.\n */\n settle: () => Promise<void>;\n /** Gets a failed follow-up run. Development only. */\n warn: (message: string, error: unknown) => void;\n}\n\nexport interface FunctionCallRunner {\n /**\n * Runs the calls of the thread of `agent` that did not run yet. When no\n * run goes on, it also sends the pending answers.\n *\n * @param agent - The agent of the thread.\n * @param requests - The function calls in the messages, in order.\n * @param messages - All messages of the thread.\n * @param running - A run goes on or starts now. The answers wait.\n */\n run(\n agent: AbstractAgent,\n requests: FunctionCallRequest[],\n messages: ReadonlyMessages,\n running: boolean,\n ): void;\n}\n\n/**\n * Runs the functions that the agent calls with `callRendererFunction`, for\n * both transports, and answers each call.\n *\n * - Each `functionCallId` runs once for each thread. A replay, a sync of\n * the same messages again, or a call that already has an answer message\n * does not run it again.\n * - The answer is a hidden developer message with a `rendererFunctionResponse`.\n * The answers go to the agent only when it is not running. Then one\n * follow-up run starts for all of them.\n * - A user turn has at most {@link MAX_FUNCTION_FOLLOW_UPS} follow-up runs.\n * A call after that does not run. It gets a `follow_up_limit` error and\n * starts no follow-up run.\n */\nexport function createFunctionCallRunner(\n options: FunctionCallRunnerOptions,\n): FunctionCallRunner {\n const { core, dispatcher, manifest, settle, warn } = options;\n const threads = new Map<string, ThreadFunctionCalls>();\n\n const threadState = (threadId: string) => {\n let state = threads.get(threadId);\n if (!state) {\n state = {\n done: new Set(),\n pending: [],\n turn: undefined,\n followUps: 0,\n flushing: false,\n };\n threads.set(threadId, state);\n }\n return state;\n };\n\n const answer = async (\n request: FunctionCallRequest,\n ): Promise<FunctionCallAnswer> => {\n const { functionCallId } = request;\n const validation = validateOperation(request.operation, {\n manifest,\n knownSurfaces: new Set(),\n });\n if (!validation.ok) {\n return errorAnswer(\n functionCallId,\n \"invalid_arguments\",\n validation.reason,\n );\n }\n // validateOperation checked the shape of the operation.\n const operation = request.operation as A2UIOperation;\n if (!(\"callRendererFunction\" in operation)) {\n return errorAnswer(\n functionCallId,\n \"invalid_arguments\",\n \"the operation is not a callRendererFunction\",\n );\n }\n const { callFunction } = operation.callRendererFunction;\n const name = callFunction[\"@call\"];\n const result = await dispatcher.invoke(name, callFunction.args ?? {}, {\n functionCallId,\n });\n if (!result.ok) {\n return errorAnswer(\n functionCallId,\n result.error.code,\n result.error.message,\n );\n }\n try {\n // A handler that returns nothing answers with null: JSON has no undefined.\n const value = result.result ?? null;\n return {\n content: responseContent({ functionCallId, value }),\n followUp: true,\n };\n } catch (cause) {\n return errorAnswer(\n functionCallId,\n \"handler_failed\",\n `The result of \"${name}\" is not JSON: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n }\n };\n\n /**\n * Adds the pending answers of a thread to the agent, then starts one\n * follow-up run. It waits while the agent runs: the next read of the\n * thread, at the end of the run, flushes again.\n */\n const flush = async (\n agent: AbstractAgent,\n threadId: string,\n state: ThreadFunctionCalls,\n ) => {\n if (state.flushing) return;\n state.flushing = true;\n try {\n while (state.pending.length > 0) {\n const batch = [...state.pending];\n const answers = await Promise.all(batch);\n // Let the app apply the state that the handlers set, so that the\n // follow-up run reads it.\n await settle();\n const isElsewhere = agent.isRunning || agent.threadId !== threadId;\n if (isElsewhere) return;\n // More calls came while these ran. They are one batch with them.\n if (state.pending.length > batch.length) continue;\n state.pending = [];\n for (const { content } of answers) {\n agent.addMessage({ id: randomUUID(), role: \"developer\", content });\n }\n if (!answers.some((item) => item.followUp)) continue;\n state.followUps++;\n await core.runAgent({ agent });\n }\n } catch (error) {\n warn(\"[generativeUI] function follow-up run failed:\", error);\n } finally {\n state.flushing = false;\n }\n };\n\n return {\n run(agent, requests, messages, running) {\n const { threadId } = agent;\n if (!threadId) return;\n const state = threadState(threadId);\n const turn = lastUserMessageId(messages);\n if (turn !== state.turn) {\n state.turn = turn;\n state.followUps = 0;\n }\n const fresh = requests.filter(\n (request) => !state.done.has(request.functionCallId),\n );\n const answered =\n fresh.length > 0 ? answeredCallIds(messages) : new Set<string>();\n for (const request of fresh) {\n const { functionCallId } = request;\n // The same id twice in one read runs once.\n if (state.done.has(functionCallId)) continue;\n state.done.add(functionCallId);\n if (answered.has(functionCallId)) continue;\n const isOverCap = state.followUps >= MAX_FUNCTION_FOLLOW_UPS;\n state.pending.push(\n isOverCap\n ? Promise.resolve(overCapAnswer(functionCallId))\n : answer(request),\n );\n }\n if (!running) void flush(agent, threadId, state);\n },\n };\n}\n","import { ExpressionError, truthOf } from \"./functions\";\n\n/**\n * The two CopilotKit value functions that A2UI 1.0 lacks: `calc`, an\n * arithmetic expression over named args, and `series`, a computed list.\n * Both are catalog functions in the sense of the spec: a catalog may\n * declare functions beyond the basic ones, and the model learns them from\n * the schema. The expression language is small and closed: numbers,\n * strings, booleans, the args by name, `+ - * / %`, `^` (power),\n * comparisons, `&& || !`, `cond ? a : b`, parentheses, min, max, round,\n * floor, ceil, abs, pow, sqrt, exp, ln (also log), log10, and the\n * constants pi and e. No property access, no assignment, no code.\n */\n\ntype Value = number | string | boolean | null;\nexport type CalcScope = Readonly<Record<string, unknown>>;\n\nconst MAX_SERIES = 1000;\n\n// ---- Lexer ----\n\ntype Token =\n | { kind: \"number\"; value: number }\n | { kind: \"string\"; value: string }\n | { kind: \"name\"; value: string }\n | { kind: \"op\"; value: string }\n | { kind: \"end\" };\n\nconst OPERATORS = [\n \"&&\",\n \"||\",\n \"==\",\n \"!=\",\n \"<=\",\n \">=\",\n \"<\",\n \">\",\n \"+\",\n \"-\",\n \"*\",\n \"/\",\n \"%\",\n \"^\",\n \"(\",\n \")\",\n \",\",\n \"?\",\n \":\",\n \"!\",\n];\n\nfunction tokenize(source: string): Token[] {\n const tokens: Token[] = [];\n let i = 0;\n while (i < source.length) {\n const char = source.charAt(i);\n if (/\\s/.test(char)) {\n i++;\n continue;\n }\n if (/[0-9.]/.test(char)) {\n const match = /^\\d*\\.?\\d+(?:[eE][-+]?\\d+)?|^\\d+\\.?/.exec(source.slice(i));\n if (!match)\n throw new ExpressionError(\n `calc: bad number at \"${source.slice(i, i + 8)}\"`,\n );\n tokens.push({ kind: \"number\", value: Number(match[0]) });\n i += match[0].length;\n continue;\n }\n if (char === \"'\" || char === '\"') {\n let value = \"\";\n i++;\n while (i < source.length && source[i] !== char) {\n if (source[i] === \"\\\\\" && i + 1 < source.length) i++;\n value += source.charAt(i++);\n }\n if (i >= source.length)\n throw new ExpressionError(\"calc: unclosed string\");\n i++;\n tokens.push({ kind: \"string\", value });\n continue;\n }\n if (/[A-Za-z_]/.test(char)) {\n const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i))!;\n tokens.push({ kind: \"name\", value: match[0] });\n i += match[0].length;\n continue;\n }\n const op = OPERATORS.find((candidate) => source.startsWith(candidate, i));\n if (!op) throw new ExpressionError(`calc: unexpected \"${char}\"`);\n tokens.push({ kind: \"op\", value: op });\n i += op.length;\n }\n tokens.push({ kind: \"end\" });\n return tokens;\n}\n\n// ---- Values ----\n\nfunction numberOf(value: unknown, what: string): number {\n if (typeof value === \"number\") {\n if (!Number.isFinite(value))\n throw new ExpressionError(`calc: ${what} is not finite`);\n return value;\n }\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) return parsed;\n }\n if (value === null || value === undefined) {\n throw new ExpressionError(`calc: ${what} has no value`);\n }\n throw new ExpressionError(`calc: ${what} is not a number`);\n}\n\nfunction describe(value: unknown) {\n return typeof value === \"string\" ? `\"${value}\"` : String(value);\n}\n\nconst MATH: Record<string, (args: number[]) => number> = {\n min: (args) => Math.min(...args),\n max: (args) => Math.max(...args),\n abs: ([x = Number.NaN]) => Math.abs(x),\n floor: ([x = Number.NaN]) => Math.floor(x),\n ceil: ([x = Number.NaN]) => Math.ceil(x),\n round: ([x = Number.NaN, decimals = 0]) => {\n const factor = 10 ** Math.trunc(decimals);\n return Math.round(x * factor) / factor;\n },\n pow: ([x = Number.NaN, y = Number.NaN]) => x ** y,\n sqrt: ([x = Number.NaN]) => Math.sqrt(x),\n exp: ([x = Number.NaN]) => Math.exp(x),\n ln: ([x = Number.NaN]) => Math.log(x),\n log10: ([x = Number.NaN]) => Math.log10(x),\n};\n\n/** How many args a function takes, at least and at most; min and max take any. */\nconst ARITY: Record<string, [number, number]> = {\n abs: [1, 1],\n floor: [1, 1],\n ceil: [1, 1],\n round: [1, 2],\n pow: [2, 2],\n sqrt: [1, 1],\n exp: [1, 1],\n ln: [1, 1],\n log10: [1, 1],\n};\n\n/** Named constants, when no arg of the same name is passed. */\nconst CONSTANTS: Record<string, number> = { pi: Math.PI, e: Math.E };\n\n// ---- Parser ----\n\nconst END: Token = { kind: \"end\" };\n\nclass CalcParser {\n private pos = 0;\n\n constructor(\n private readonly tokens: Token[],\n private readonly scope: CalcScope,\n private readonly source: string,\n ) {}\n\n /** The current token. The list always ends with an \"end\" token. */\n private peek(): Token {\n return this.tokens[this.pos] ?? END;\n }\n\n parse(): Value {\n const value = this.ternary();\n if (this.peek().kind !== \"end\") {\n this.fail(`unexpected \"${this.text(this.peek())}\"`);\n }\n return value;\n }\n\n private fail(what: string): never {\n throw new ExpressionError(`calc: ${what} in \"${this.source}\"`);\n }\n\n private text(token: Token) {\n return token.kind === \"end\" ? \"end\" : String(token.value);\n }\n\n private peekOp(...ops: string[]) {\n const token = this.peek();\n return token.kind === \"op\" && ops.includes(token.value)\n ? token.value\n : undefined;\n }\n\n private expectOp(op: string) {\n if (this.peekOp(op) === undefined) {\n this.fail(`expected \"${op}\" but found \"${this.text(this.peek())}\"`);\n }\n this.pos++;\n }\n\n /**\n * Parses a part of the expression that the result does not need (the\n * other branch of `?:`, the right side of a decided `&&` or `||`). It\n * still has to be parsed to find where it ends, so syntax errors are\n * reported, but no value is checked or computed: `n == 0 ? 0 : 10 / n`\n * is a valid guard.\n */\n private skipped(parse: () => Value): null {\n this.skipDepth++;\n try {\n parse();\n } finally {\n this.skipDepth--;\n }\n return null;\n }\n\n /** Above 0 while parsing a part whose value is not needed. */\n private skipDepth = 0;\n\n /** The number of a value, or 0 while skipping. */\n private num(value: unknown, what: string) {\n return this.skipDepth > 0 ? 0 : numberOf(value, what);\n }\n\n private ternary(): Value {\n const condition = this.or();\n if (this.peekOp(\"?\") === undefined) return condition;\n this.pos++;\n const takesFirst = truthOf(condition);\n const whenTrue = takesFirst\n ? this.ternary()\n : this.skipped(() => this.ternary());\n this.expectOp(\":\");\n const whenFalse = takesFirst\n ? this.skipped(() => this.ternary())\n : this.ternary();\n return takesFirst ? whenTrue : whenFalse;\n }\n\n private or(): Value {\n let left = this.and();\n while (this.peekOp(\"||\")) {\n this.pos++;\n if (truthOf(left)) {\n this.skipped(() => this.and());\n left = true;\n } else {\n left = truthOf(this.and());\n }\n }\n return left;\n }\n\n private and(): Value {\n let left = this.equality();\n while (this.peekOp(\"&&\")) {\n this.pos++;\n if (!truthOf(left)) {\n this.skipped(() => this.equality());\n left = false;\n } else {\n left = truthOf(this.equality());\n }\n }\n return left;\n }\n\n private equality(): Value {\n let left = this.comparison();\n for (let op = this.peekOp(\"==\", \"!=\"); op; op = this.peekOp(\"==\", \"!=\")) {\n this.pos++;\n const right = this.comparison();\n const isEqual =\n typeof left === \"number\" || typeof right === \"number\"\n ? this.num(left, \"the left side of ==\") ===\n this.num(right, \"the right side of ==\")\n : left === right;\n left = op === \"==\" ? isEqual : !isEqual;\n }\n return left;\n }\n\n private comparison(): Value {\n let left = this.additive();\n for (\n let op = this.peekOp(\"<\", \"<=\", \">\", \">=\");\n op;\n op = this.peekOp(\"<\", \"<=\", \">\", \">=\")\n ) {\n this.pos++;\n const a = this.num(left, `the left side of ${op}`);\n const b = this.num(this.additive(), `the right side of ${op}`);\n left =\n op === \"<\" ? a < b : op === \"<=\" ? a <= b : op === \">\" ? a > b : a >= b;\n }\n return left;\n }\n\n private additive(): Value {\n let left = this.multiplicative();\n for (let op = this.peekOp(\"+\", \"-\"); op; op = this.peekOp(\"+\", \"-\")) {\n this.pos++;\n const right = this.multiplicative();\n if (\n op === \"+\" &&\n (typeof left === \"string\" || typeof right === \"string\")\n ) {\n left = `${left ?? \"\"}${right ?? \"\"}`;\n } else {\n const a = this.num(left, `the left side of ${op}`);\n const b = this.num(right, `the right side of ${op}`);\n left = op === \"+\" ? a + b : a - b;\n }\n }\n return left;\n }\n\n private multiplicative(): Value {\n let left = this.unary();\n for (\n let op = this.peekOp(\"*\", \"/\", \"%\");\n op;\n op = this.peekOp(\"*\", \"/\", \"%\")\n ) {\n this.pos++;\n const a = this.num(left, `the left side of ${op}`);\n const b = this.num(this.unary(), `the right side of ${op}`);\n if (op !== \"*\" && b === 0 && this.skipDepth === 0) {\n this.fail(\"division by zero\");\n }\n left = op === \"*\" ? a * b : op === \"/\" ? a / b : a % b;\n }\n return left;\n }\n\n private unary(): Value {\n if (this.peekOp(\"-\")) {\n this.pos++;\n return -this.num(this.unary(), \"the operand of -\");\n }\n if (this.peekOp(\"!\")) {\n this.pos++;\n return !truthOf(this.unary());\n }\n return this.power();\n }\n\n /** `a ^ b`: binds tighter than `*` and unary minus, right to left. */\n private power(): Value {\n const base = this.primary();\n if (!this.peekOp(\"^\")) return base;\n this.pos++;\n const exponent = this.unary();\n if (this.skipDepth > 0) return null;\n return this.finite(\n this.num(base, \"the left side of ^\") **\n this.num(exponent, \"the right side of ^\"),\n \"^\",\n );\n }\n\n private finite(value: number, what: string): number {\n if (!Number.isFinite(value)) this.fail(`${what} has no finite result`);\n return value;\n }\n\n private primary(): Value {\n const token = this.peek();\n this.pos++;\n switch (token.kind) {\n case \"number\":\n return token.value;\n case \"string\":\n return token.value;\n case \"name\":\n return this.name(token.value);\n case \"op\":\n if (token.value === \"(\") {\n const value = this.ternary();\n this.expectOp(\")\");\n return value;\n }\n return this.fail(`unexpected \"${token.value}\"`);\n case \"end\":\n return this.fail(\"missing value\");\n }\n }\n\n private name(name: string): Value {\n if (name === \"true\") return true;\n if (name === \"false\") return false;\n if (name === \"null\") return null;\n if (this.peekOp(\"(\")) {\n this.pos++;\n const args: number[] = [];\n if (this.peekOp(\")\") === undefined) {\n for (;;) {\n args.push(this.num(this.ternary(), `an argument of ${name}`));\n if (this.peekOp(\",\") === undefined) break;\n this.pos++;\n }\n }\n this.expectOp(\")\");\n if (this.skipDepth > 0) return null;\n const fn = Object.prototype.hasOwnProperty.call(MATH, name)\n ? MATH[name]\n : undefined;\n if (!fn) this.fail(`unknown function ${name}`);\n if (args.length === 0) this.fail(`${name} needs an argument`);\n const [least, most] = ARITY[name] ?? [1, Infinity];\n if (args.length < least || args.length > most) {\n this.fail(\n `${name} takes ${least === most ? least : `${least} or ${most}`} argument${most === 1 ? \"\" : \"s\"}`,\n );\n }\n return this.finite(fn(args), name);\n }\n if (this.skipDepth > 0) return null;\n if (!Object.prototype.hasOwnProperty.call(this.scope, name)) {\n // An own key only: `constructor` or `__proto__` is no constant.\n const constant = Object.prototype.hasOwnProperty.call(CONSTANTS, name)\n ? CONSTANTS[name]\n : undefined;\n if (constant !== undefined) return constant;\n this.fail(`unknown name ${name}; pass it as an arg`);\n }\n const value = this.scope[name];\n if (\n value !== null &&\n typeof value !== \"number\" &&\n typeof value !== \"string\" &&\n typeof value !== \"boolean\"\n ) {\n this.fail(\n `${name} is not a number, text or boolean (${describe(value)})`,\n );\n }\n return value as Value;\n }\n}\n\n/**\n * Evaluates `expression` with the names in `scope`. Gives a number, a\n * string, a boolean or null. Throws an {@link ExpressionError} for a bad\n * expression or a missing name.\n */\nexport function evaluateCalc(expression: unknown, scope: CalcScope): Value {\n if (typeof expression !== \"string\" || expression.trim() === \"\") {\n throw new ExpressionError(\"calc: expression must be a string\");\n }\n return new CalcParser(tokenize(expression), scope, expression).parse();\n}\n\n/** The `calc` function: the expression is `args.expression`, the rest is the scope. */\nexport function calc(args: Record<string, unknown>): Value {\n const { expression, ...scope } = args;\n return evaluateCalc(expression, scope);\n}\n\nconst WHOLE_EXPRESSION = /^\\$\\{([^}]*)\\}$/;\n\n/**\n * Fills `item` for one iteration: a string that is one `${...}` gives the\n * typed value of the expression, a string with `${...}` inside it is\n * interpolated as text, and objects and arrays are walked.\n */\nfunction fillItem(item: unknown, scope: CalcScope): unknown {\n if (typeof item === \"string\") {\n const whole = WHOLE_EXPRESSION.exec(item);\n if (whole) return evaluateCalc(whole[1], scope);\n return item.replace(/\\$\\{([^}]*)\\}/g, (_, expression: string) => {\n const value = evaluateCalc(expression, scope);\n return value === null ? \"\" : String(value);\n });\n }\n if (Array.isArray(item)) return item.map((entry) => fillItem(entry, scope));\n if (typeof item === \"object\" && item !== null) {\n return Object.fromEntries(\n Object.entries(item).map(([key, value]) => [key, fillItem(value, scope)]),\n );\n }\n return item;\n}\n\n/**\n * The `series` function: `count` copies of `item`, with the loop variable\n * (`variable`, default \"i\") counting from `start` (default 1) and the other\n * args in scope of the `${...}` expressions of the item.\n */\nexport function series(args: Record<string, unknown>): unknown[] {\n const { count, item, variable, start, ...scope } = args;\n const length = numberOf(count, \"count\");\n if (!Number.isInteger(length) || length < 0) {\n throw new ExpressionError(\"series: count must be a whole number\");\n }\n if (length > MAX_SERIES) {\n throw new ExpressionError(`series: count is at most ${MAX_SERIES}`);\n }\n if (item === undefined) throw new ExpressionError(\"series: item is required\");\n const name = variable === undefined ? \"i\" : variable;\n if (typeof name !== \"string\" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n throw new ExpressionError(\"series: variable must be a name\");\n }\n const first = start === undefined ? 1 : numberOf(start, \"start\");\n return Array.from({ length }, (_, index) =>\n fillItem(item, { ...scope, [name]: first + index }),\n );\n}\n","import {\n A2UI_INDEX_FUNCTION,\n isActionBinding,\n isCallBinding,\n isPathBinding,\n isValidationResult,\n} from \"@copilotkit/shared\";\nimport { calc, series } from \"./calc\";\nimport {\n BASIC_FUNCTIONS,\n ExpressionError,\n givesValidationResult,\n requiresUserActivation,\n} from \"./functions\";\nimport { isRecord } from \"@copilotkit/shared/generative-ui\";\n\n// The CopilotKit value functions join the registry here, because calc.ts\n// uses the error type and truthOf of functions.ts.\nBASIC_FUNCTIONS.calc = calc;\nBASIC_FUNCTIONS.series = series;\n// formatString needs the resolver. Inside a surface, `call()` below handles\n// it with the surface data; this entry serves the dispatcher, where the\n// agent calls it with literal args and no data model.\nconst NO_DATA: DataReader = { get: () => undefined };\nBASIC_FUNCTIONS.formatString = (args) =>\n resolveDynamicValue(\n { \"@call\": \"formatString\", args },\n { data: NO_DATA, basePath: undefined },\n ).value;\n\n/**\n * Resolves the dynamic values of A2UI 1.0 in a prop, an event context, or\n * a function argument: `{\"@path\"}` bindings read the data model,\n * `{\"@call\"}` values run a basic function, and `formatString` interpolates\n * `${...}` expressions. Objects and arrays are walked, so a binding can sit\n * at any depth. A value with nothing dynamic in it keeps its identity.\n */\n\n/** Reads the data model. The surface data model of web_core fits. */\nexport interface DataReader {\n get(path: string): unknown;\n}\n\nexport interface ResolveContext {\n data: DataReader;\n /**\n * The data model path of the template item this value belongs to, or\n * `undefined` outside of a template. Relative paths resolve against it.\n */\n basePath: string | undefined;\n}\n\nexport interface Resolved<T = unknown> {\n value: T;\n /** The absolute data model paths that the value read. */\n paths: Set<string>;\n}\n\n/** Adds one segment to a JSON pointer: (\"/items\", \"0\") gives \"/items/0\". */\nexport function joinPath(base: string, segment: string) {\n return base === \"/\" ? `/${segment}` : `${base}/${segment}`;\n}\n\n/**\n * The absolute data model path of a binding. A path without a leading \"/\"\n * is relative to the current template item, or to the root outside of one.\n */\nexport function resolvePath(path: string, basePath: string | undefined) {\n if (path.startsWith(\"/\")) return path;\n return joinPath(basePath ?? \"/\", path);\n}\n\n/**\n * The index of the template item at `basePath`: its last segment.\n * `undefined` outside of a template.\n */\nexport function templateIndex(basePath: string | undefined) {\n if (basePath === undefined) return undefined;\n const index = Number(basePath.slice(basePath.lastIndexOf(\"/\") + 1));\n return Number.isInteger(index) ? index : undefined;\n}\n\n/** The value of a ValidationResult where a boolean is expected. */\nfunction coerce(value: unknown, keep: boolean) {\n return !keep && isValidationResult(value) ? value.valid : value;\n}\n\ninterface Walk {\n context: ResolveContext;\n paths: Set<string>;\n}\n\n/**\n * Where a value sits with respect to `checks`: outside, in the `checks`\n * list, or in one check. Only the `condition` of a check keeps a validator\n * result as an object; an arg named `condition` elsewhere does not.\n */\ntype CheckScope = \"outside\" | \"list\" | \"check\";\n\n/**\n * Resolves `value`. `keepValidation` keeps a ValidationResult as it is; by\n * default it becomes its `valid` boolean, which is what every prop except\n * a check condition wants.\n */\nfunction walk(\n value: unknown,\n state: Walk,\n keepValidation: boolean,\n scope: CheckScope = \"outside\",\n): unknown {\n if (Array.isArray(value)) {\n let changed = false;\n const itemScope = scope === \"list\" ? \"check\" : \"outside\";\n const items = value.map((item) => {\n const next = walk(item, state, keepValidation, itemScope);\n if (next !== item) changed = true;\n return next;\n });\n return changed ? items : value;\n }\n if (!isRecord(value)) return value;\n if (isPathBinding(value)) {\n const path = resolvePath(value[\"@path\"], state.context.basePath);\n state.paths.add(path);\n // A data model value is what it is: an object with a `valid` field is\n // not a validator result. Only a validator call is coerced.\n return state.context.data.get(path);\n }\n if (isCallBinding(value)) return call(value, state, keepValidation);\n // An event binding is not a value. It is resolved when the event runs.\n if (isActionBinding(value)) return value;\n let changed = false;\n const entries = Object.entries(value).map(([key, item]) => {\n // Only the condition of a check consumes a ValidationResult as an object.\n const isCondition = scope === \"check\" && key === \"condition\";\n const next = walk(\n item,\n state,\n keepValidation || isCondition,\n key === \"checks\" ? \"list\" : \"outside\",\n );\n if (next !== item) changed = true;\n return [key, next] as const;\n });\n return changed ? Object.fromEntries(entries) : value;\n}\n\nfunction call(\n binding: { \"@call\": string; args?: Record<string, unknown> },\n state: Walk,\n keepValidation: boolean,\n) {\n const name = binding[\"@call\"];\n const rawArgs = binding.args ?? {};\n if (!isRecord(rawArgs)) {\n throw new ExpressionError(`the args of \"${name}\" must be an object`);\n }\n if (name === A2UI_INDEX_FUNCTION) {\n const index = templateIndex(state.context.basePath);\n if (index === undefined) return undefined;\n const offset = walk(rawArgs.offset, state, false);\n return index + (typeof offset === \"number\" ? offset : 0);\n }\n if (name === \"formatString\") {\n const template = walk(rawArgs.value, state, false);\n if (typeof template !== \"string\") {\n throw new ExpressionError(\"formatString takes a string value\");\n }\n return formatString(template, state);\n }\n const fn = Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name)\n ? BASIC_FUNCTIONS[name]\n : undefined;\n if (!fn) throw new ExpressionError(`\"${name}\" is not a basic function`);\n // A value is computed whenever the data changes, never from a gesture. A\n // function that needs one (openUrl) runs only as the functionCall of an\n // event, where the dispatcher checks the gesture.\n if (requiresUserActivation(name)) {\n throw new ExpressionError(\n `\"${name}\" is not a value; bind it as the functionCall of an event`,\n );\n }\n // A validator result in an arg becomes its boolean: `and`, `or`, `not` and\n // `calc` all want one, and a validator reads plain values anyway.\n const args = walk(rawArgs, state, false) as Record<string, unknown>;\n const result = fn(args);\n return givesValidationResult(name) ? coerce(result, keepValidation) : result;\n}\n\n/**\n * Resolves one dynamic value: the value with every binding and function\n * call replaced, plus the data model paths it read. Throws an\n * {@link ExpressionError} for a bad function call.\n */\n/** The options of a resolution. */\nexport interface ResolveOptions {\n /** Keep every validator result as an object. */\n keepValidation?: boolean;\n /**\n * True when `value` is the `checks` prop of a component: the condition\n * of each check then keeps its validator result as an object.\n */\n isChecks?: boolean;\n}\n\nexport function resolveDynamicValue<T = unknown>(\n value: unknown,\n context: ResolveContext,\n options: ResolveOptions = {},\n): Resolved<T> {\n const result = tryResolveDynamicValue<T>(value, context, options);\n if (!result.ok) throw result.error;\n return result;\n}\n\nexport type ResolveAttempt<T = unknown> =\n | ({ ok: true } & Resolved<T>)\n | {\n ok: false;\n error: Error;\n /** The paths read before the failure. A change there may fix it. */\n paths: Set<string>;\n };\n\n/**\n * Like {@link resolveDynamicValue}, but a failure comes back as a result\n * with the paths read so far, so the caller can keep watching them: a\n * function that fails on an empty field works once the user fills it.\n */\nexport function tryResolveDynamicValue<T = unknown>(\n value: unknown,\n context: ResolveContext,\n options: ResolveOptions = {},\n): ResolveAttempt<T> {\n const state: Walk = { context, paths: new Set() };\n try {\n const resolved = walk(\n value,\n state,\n options.keepValidation ?? false,\n options.isChecks ? \"list\" : \"outside\",\n ) as T;\n return { ok: true, value: resolved, paths: state.paths };\n } catch (error) {\n return {\n ok: false,\n error: error instanceof Error ? error : new Error(String(error)),\n paths: state.paths,\n };\n }\n}\n\n/** True when `value` holds a `{\"@path\"}` or `{\"@call\"}` at any depth. */\nexport function containsDynamicValue(value: unknown): boolean {\n if (Array.isArray(value)) return value.some(containsDynamicValue);\n if (!isRecord(value)) return false;\n if (isPathBinding(value) || isCallBinding(value)) return true;\n if (isActionBinding(value)) return false;\n return Object.values(value).some(containsDynamicValue);\n}\n\n// ---- formatString ----\n\n/**\n * The `${...}` grammar of `formatString`:\n *\n * expression := path | literal | call\n * path := \"/\" segments | identifier (\"/\" segments)*\n * literal := 'text' | \"text\" | number | true | false | null\n * call := identifier \"(\" [ name \":\" expression (\",\" name \":\" expression)* ] \")\"\n *\n * A `\\${` in the template is a literal `${`.\n */\nfunction formatString(template: string, state: Walk) {\n let out = \"\";\n let index = 0;\n while (index < template.length) {\n const start = template.indexOf(\"${\", index);\n if (start === -1) {\n out += template.slice(index);\n break;\n }\n if (start > 0 && template[start - 1] === \"\\\\\") {\n out += `${template.slice(index, start - 1)}\\${`;\n index = start + 2;\n continue;\n }\n out += template.slice(index, start);\n const end = matchingBrace(template, start + 2);\n if (end === -1) throw new ExpressionError(\"formatString: unclosed ${\");\n const expression = template.slice(start + 2, end).trim();\n const parser = new ExpressionParser(expression, state);\n const value = parser.parse();\n out += value === undefined || value === null ? \"\" : String(value);\n index = end + 1;\n }\n return out;\n}\n\n/** The index of the `}` that closes the block opened at `from`, or -1. */\nfunction matchingBrace(template: string, from: number) {\n let depth = 1;\n let quote: string | undefined;\n for (let i = from; i < template.length; i++) {\n const char = template[i];\n if (quote) {\n if (char === \"\\\\\") i++;\n else if (char === quote) quote = undefined;\n continue;\n }\n if (char === \"'\" || char === '\"') quote = char;\n else if (char === \"{\") depth++;\n else if (char === \"}\" && --depth === 0) return i;\n }\n return -1;\n}\n\nconst IDENTIFIER = /@?[A-Za-z_][A-Za-z0-9_-]*/y;\nconst NUMBER = /-?\\d+(?:\\.\\d+)?/y;\nconst PATH_SEGMENT = /[^\\s,():'\"]+/y;\n\nclass ExpressionParser {\n private pos = 0;\n\n constructor(\n private readonly source: string,\n private readonly state: Walk,\n ) {}\n\n parse(): unknown {\n const value = this.expression();\n this.skipSpace();\n if (this.pos < this.source.length) {\n throw new ExpressionError(\n `formatString: unexpected \"${this.source.slice(this.pos)}\" in \\${${this.source}}`,\n );\n }\n return value;\n }\n\n private fail(what: string): never {\n throw new ExpressionError(`formatString: ${what} in \\${${this.source}}`);\n }\n\n private skipSpace() {\n while (\n this.pos < this.source.length &&\n /\\s/.test(this.source.charAt(this.pos))\n ) {\n this.pos++;\n }\n }\n\n private match(pattern: RegExp) {\n pattern.lastIndex = this.pos;\n const found = pattern.exec(this.source);\n if (!found) return undefined;\n this.pos = pattern.lastIndex;\n return found[0];\n }\n\n private expression(): unknown {\n this.skipSpace();\n const char = this.source[this.pos];\n if (char === undefined) this.fail(\"missing expression\");\n if (char === \"'\" || char === '\"') return this.quoted(char);\n if (char === \"/\") return this.path(this.match(PATH_SEGMENT) ?? \"/\");\n const number = this.match(NUMBER);\n if (number !== undefined) return Number(number);\n const name = this.match(IDENTIFIER);\n if (name === undefined) this.fail(`unexpected \"${char}\"`);\n if (name === \"true\") return true;\n if (name === \"false\") return false;\n if (name === \"null\") return null;\n this.skipSpace();\n if (this.source[this.pos] === \"(\") return this.call(name);\n // A system function such as @index needs no parentheses.\n if (name.startsWith(\"@\")) return call({ \"@call\": name }, this.state, false);\n // A relative path: \"name\" or \"name/more\".\n const rest = this.source[this.pos] === \"/\" ? this.match(PATH_SEGMENT) : \"\";\n return this.path(`${name}${rest ?? \"\"}`);\n }\n\n private quoted(quote: string) {\n let value = \"\";\n this.pos++;\n while (this.pos < this.source.length) {\n const char = this.source[this.pos++];\n if (char === \"\\\\\" && this.pos < this.source.length) {\n value += this.source[this.pos++];\n } else if (char === quote) {\n return value;\n } else {\n value += char;\n }\n }\n return this.fail(\"unclosed string\");\n }\n\n private path(path: string) {\n const absolute = resolvePath(path, this.state.context.basePath);\n this.state.paths.add(absolute);\n return this.state.context.data.get(absolute);\n }\n\n private call(name: string): unknown {\n this.pos++; // (\n const args: Record<string, unknown> = {};\n this.skipSpace();\n if (this.source[this.pos] === \")\") {\n this.pos++;\n return call({ \"@call\": name, args }, this.state, false);\n }\n for (;;) {\n this.skipSpace();\n const key = this.match(IDENTIFIER);\n if (key === undefined) this.fail(\"expected an argument name\");\n this.skipSpace();\n if (this.source[this.pos] !== \":\") this.fail(`expected \":\" after ${key}`);\n this.pos++;\n args[key] = this.expression();\n this.skipSpace();\n const next = this.source[this.pos++];\n if (next === \")\") break;\n if (next !== \",\") this.fail(`expected \",\" or \")\" after ${key}`);\n }\n return call({ \"@call\": name, args }, this.state, false);\n }\n}\n","import { containsDynamicValue } from \"./resolve\";\nimport {\n Catalog,\n ComponentModel,\n DataModel,\n SurfaceModel,\n} from \"@a2ui/web_core/v0_9\";\nimport { z } from \"zod\";\nimport {\n A2UI_COMPONENT_ENVELOPE_KEYS,\n GENERATIVE_UI_MAX_REJECTION_LENGTH,\n GENERATIVE_UI_MAX_SUMMARY_REJECTIONS,\n getOperationKind,\n getOperationSurfaceId,\n validateOperation,\n} from \"@copilotkit/shared\";\nimport type {\n A2UIComponentNode,\n A2UIOperation,\n GenerativeUIRejectedOperation,\n GenerativeUISurfaceContent,\n GenerativeUISurfaceStatus,\n GenerativeUISurfaceSummary,\n OperationKind,\n} from \"@copilotkit/shared\";\nimport { catalogIdsOf } from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUI } from \"@copilotkit/shared/generative-ui\";\nimport {\n formatIssues,\n isAsyncIssue,\n issueKey,\n validateSchemaSync,\n withoutRejectedNulls,\n} from \"@copilotkit/shared/generative-ui\";\n\nexport function surfaceKey(threadId: string, surfaceId: string): string {\n return `${threadId}::${surfaceId}`;\n}\n\nexport interface ManagedSurface {\n readonly key: string;\n readonly threadId: string;\n readonly surfaceId: string;\n readonly agentId: string | undefined;\n /** Replaced by an empty model when the surface closes, to free its data. */\n model: SurfaceModel<any>;\n readonly createdAt: number;\n target: string;\n status: GenerativeUISurfaceStatus;\n deleted: boolean;\n /** Its first createSurface was rejected, so it never existed. */\n failed: boolean;\n /** Rejections reported by the runtime. */\n serverRejected: GenerativeUIRejectedOperation[];\n /** Rejections detected while applying operations in the browser. */\n clientRejected: GenerativeUIRejectedOperation[];\n /** The committed operations of the latest content, for the inspector. */\n operations: readonly A2UIOperation[];\n}\n\nexport interface GenerativeUISurfaceManagerOptions {\n onOperationRejected?: (info: {\n surfaceId: string;\n index: number;\n reason: string;\n }) => void;\n}\n\n/** Where an operation is in the content of its surface. */\ninterface OperationPosition {\n index: number;\n /** The content also deletes the surface, so it replays all of its life. */\n isReplay: boolean;\n}\n\ninterface Bookkeeping {\n appliedCount: number;\n lastFingerprint: string | undefined;\n}\n\n/** What one mount of a target tells the model. */\nexport interface GenerativeUITargetOptions {\n /** Where the target is on the page and what to show in it. */\n description?: string;\n /**\n * The only components that the surfaces of the target can use. Left out,\n * every component of the UI is allowed.\n */\n components?: readonly string[];\n}\n\n/** One mount of a target. Each mount gets its own object. */\ntype TargetRegistration = Readonly<GenerativeUITargetOptions>;\n\n/** A mounted target, as the manifest lists it. */\nexport interface GenerativeUIMountedTarget {\n id: string;\n description?: string;\n components?: string[];\n}\n\nlet creationCounter = 0;\n\nconst FORBIDDEN_SEGMENTS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** \"/a/b/\" to \"/a/b\". The root stays \"/\". */\nfunction normalizePath(path: string) {\n const trimmed =\n path.length > 1 && path.endsWith(\"/\") ? path.slice(0, -1) : path;\n return trimmed || \"/\";\n}\n\n/** True when `path` is `ancestor` or below it. */\nfunction isAtOrBelow(path: string, ancestor: string) {\n if (ancestor === \"/\") return true;\n return path === ancestor || path.startsWith(`${ancestor}/`);\n}\n\n/**\n * Rejections as `\"operation <index>: <reason>\"` lines, cut to the size that\n * the envelope reader accepts.\n */\nfunction summarizeRejections(rejections: GenerativeUIRejectedOperation[]) {\n return rejections\n .slice(0, GENERATIVE_UI_MAX_SUMMARY_REJECTIONS)\n .map(({ index, reason }) =>\n `operation ${index}: ${reason}`.slice(\n 0,\n GENERATIVE_UI_MAX_REJECTION_LENGTH,\n ),\n );\n}\n\n/**\n * Framework-agnostic store of generated surfaces. One web_core SurfaceModel per\n * (threadId, surfaceId), shared by every mount. Applies only newly committed\n * operations, validates each before applying it, and owns app state and the\n * data model paths that the user wrote, so agent updates cannot overwrite\n * them. App state never goes into a surface's data model. Selectors read it\n * with `getState()`.\n */\nexport class GenerativeUISurfaceManager {\n private readonly surfaces = new Map<string, ManagedSurface>();\n private readonly bookkeeping = new Map<string, Bookkeeping>();\n private readonly listeners = new Set<() => void>();\n /** Mounts of each target id, in mount order. */\n private readonly targets = new Map<string, Set<TargetRegistration>>();\n private state: Readonly<Record<string, unknown>> = {};\n /**\n * User-owned data model values, by surface key, then by path. Kept when a\n * surface is rebuilt. Cleared when the surface is deleted.\n */\n private readonly owned = new Map<string, Map<string, unknown>>();\n /**\n * Keys of the surfaces that a `deleteSurface` removed. A surface id is\n * unique for the life of the page, so a key stays here when its surface is\n * built again.\n */\n private readonly deletedKeys = new Set<string>();\n /**\n * Surfaces that share their data model, by surface key: the parts of a\n * chat surface that the prose lift split. A user write to one part goes\n * to every part, so an input in one part drives a binding in another.\n */\n private readonly linked = new Map<string, ReadonlySet<string>>();\n private readonly webCoreCatalog: Catalog<any>;\n private activeThreadId: string | undefined;\n private version = 0;\n\n constructor(\n private readonly ui: GenerativeUI,\n private readonly options: GenerativeUISurfaceManagerOptions = {},\n ) {\n // `SurfaceModel` only needs component names; it never reads a schema.\n // `Catalog<any>` because web_core types schemas as Zod 3 and this\n // package uses Zod 4.\n this.webCoreCatalog = new Catalog<any>(\n ui.id,\n [...ui.components.keys()].map((name) => ({ name, schema: z.any() })),\n [],\n );\n }\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n getVersion = (): number => this.version;\n\n private notify() {\n this.version++;\n for (const listener of [...this.listeners]) listener();\n }\n\n setActiveThread(threadId: string | undefined) {\n if (threadId === this.activeThreadId) return;\n this.activeThreadId = threadId;\n this.notify();\n }\n\n getActiveThread(): string | undefined {\n return this.activeThreadId;\n }\n\n ingest(\n threadId: string,\n agentId: string | undefined,\n content: GenerativeUISurfaceContent,\n ): void {\n const key = surfaceKey(threadId, content.surfaceId);\n const operations = content.operations ?? [];\n let surface = this.surfaces.get(key);\n let book = this.bookkeeping.get(key);\n let changed = false;\n\n if (surface && book && !this.extendsApplied(book, operations)) {\n this.disposeSurface(key);\n surface = undefined;\n book = undefined;\n }\n if (!surface || !book) {\n surface = this.createSurface(key, threadId, agentId, content);\n this.restoreOwnedValues(surface);\n book = { appliedCount: 0, lastFingerprint: undefined };\n this.surfaces.set(key, surface);\n this.bookkeeping.set(key, book);\n changed = true;\n }\n const serverRejected = content.rejected ?? [];\n // Client rejections describe the latest render_ui call only, like the\n // server's `rejected` list. The runtime starts each call on an existing\n // surface by flipping status back to \"streaming\" and resetting `rejected`\n // to [], so either signal clears them before this ingest's new operations\n // are applied. A rebuild starts empty; since call boundaries are not on the\n // wire, replaying every operation then re-reports earlier calls' rejections.\n if (\n surface.clientRejected.length > 0 &&\n ((surface.status !== \"streaming\" && content.status === \"streaming\") ||\n serverRejected.length < surface.serverRejected.length)\n ) {\n surface.clientRejected = [];\n changed = true;\n }\n if (operations.length > 0) {\n // Fingerprint the pristine operation before applying it.\n const lastFingerprint = JSON.stringify(operations[operations.length - 1]);\n // Content that also deletes the surface replays all of its life, for\n // example when the markdown source builds a surface again. Its\n // createSurface is not a new create.\n const isReplay = operations.some(\n (op) => getOperationKind(op) === \"deleteSurface\",\n );\n for (let index = book.appliedCount; index < operations.length; index++) {\n this.applyOperation(surface, operations[index], { index, isReplay });\n changed = true;\n }\n book.appliedCount = operations.length;\n surface.operations = operations;\n book.lastFingerprint = lastFingerprint;\n }\n if (\n surface.status !== content.status ||\n surface.target !== content.target ||\n surface.serverRejected.length !== serverRejected.length\n ) {\n surface.status = content.status;\n surface.target = content.target;\n surface.serverRejected = serverRejected;\n changed = true;\n }\n if (changed) this.notify();\n }\n\n /** The surface of a `key` (see `surfaceKey`), unless it is deleted. */\n getSurfaceByKey(key: string): ManagedSurface | undefined {\n const surface = this.surfaces.get(key);\n return surface && !surface.deleted ? surface : undefined;\n }\n\n getSurface(threadId: string, surfaceId: string): ManagedSurface | undefined {\n const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));\n return surface && !surface.deleted ? surface : undefined;\n }\n\n getSurfaceForTarget(\n target: string,\n threadId: string | undefined = this.activeThreadId,\n ): ManagedSurface | undefined {\n if (!threadId) return undefined;\n let latest: ManagedSurface | undefined;\n for (const surface of this.surfaces.values()) {\n if (\n surface.threadId !== threadId ||\n surface.target !== target ||\n surface.deleted\n )\n continue;\n if (!latest || surface.createdAt > latest.createdAt) latest = surface;\n }\n return latest;\n }\n\n /**\n * A surface whose first createSurface was rejected, so the chat can show\n * the error where the surface would be. `undefined` for any other surface.\n */\n getFailedSurface(\n threadId: string,\n surfaceId: string,\n ): ManagedSurface | undefined {\n const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));\n return surface?.failed ? surface : undefined;\n }\n\n /**\n * The surfaces of a thread, for the model. A surface with user-owned\n * values lists them in `dataModel`, so the model can read what the user\n * entered. A surface with dropped operations lists them in `rejected`, so\n * the model can fix them on the next run. A deleted surface, or one that\n * was never created, has a `status`, so the model knows that the id is\n * not a live surface.\n */\n describeSurfaces(threadId: string) {\n const described: Record<string, GenerativeUISurfaceSummary> = {};\n for (const surface of this.surfaces.values()) {\n if (surface.threadId !== threadId) continue;\n const owned = this.owned.get(surface.key);\n const rejections = [...surface.serverRejected, ...surface.clientRejected];\n // ponytail: a deleted surface stays listed for the life of the thread, one short line each. Prune the oldest when long threads make the envelope too big.\n // A deleted id stays deleted, also when a later createSurface used it\n // again and failed: it can never be used again.\n const status = this.deletedKeys.has(surface.key)\n ? \"deleted\"\n : surface.failed\n ? \"failed\"\n : undefined;\n described[surface.surfaceId] = {\n target: surface.target,\n ...(owned && owned.size > 0\n ? { dataModel: Object.fromEntries(owned) }\n : {}),\n ...(rejections.length > 0 && status !== \"deleted\"\n ? { rejected: summarizeRejections(rejections) }\n : {}),\n ...(status ? { status } : {}),\n };\n }\n return described;\n }\n\n /** Every surface that is not deleted, oldest first, for the inspector. */\n debugSurfaces() {\n return [...this.surfaces.values()]\n .filter((surface) => !surface.deleted)\n .sort((a, b) => a.createdAt - b.createdAt)\n .map((surface) => ({\n surfaceId: surface.surfaceId,\n threadId: surface.threadId,\n agentId: surface.agentId,\n target: surface.target,\n status: surface.status,\n operations: surface.operations,\n dataModel: surface.model.dataModel.get(\"/\"),\n userValues: Object.fromEntries(this.owned.get(surface.key) ?? []),\n rejected: [\n ...surface.serverRejected.map((r) => ({\n ...r,\n source: \"runtime\" as const,\n })),\n ...surface.clientRejected.map((r) => ({\n ...r,\n source: \"browser\" as const,\n })),\n ],\n }));\n }\n\n /**\n * Marks a target as mounted. Returns the function that unmounts it. Calling\n * that function more than once has no effect.\n *\n * @param id - The target id.\n * @param options - The description and the allowed components of this mount.\n */\n registerTarget(id: string, options: GenerativeUITargetOptions = {}) {\n const registration: TargetRegistration = { ...options };\n const registrations = this.targets.get(id) ?? new Set();\n registrations.add(registration);\n this.targets.set(id, registrations);\n this.notify();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n registrations.delete(registration);\n if (registrations.size === 0) this.targets.delete(id);\n this.notify();\n };\n }\n\n /**\n * The mounted targets. Each has the description and the component list of\n * its earliest mount that has one.\n */\n getMountedTargets() {\n const mounted: GenerativeUIMountedTarget[] = [];\n for (const [id, registrations] of this.targets) {\n // ponytail: when mounts of one id have different descriptions, the earliest mount that is still mounted and has a description wins. A mount without a description does not hide the description of a later mount.\n const description = [...registrations].find(\n (registration) => registration.description !== undefined,\n )?.description;\n const components = this.targetComponents(id);\n mounted.push({\n id,\n ...(description === undefined ? {} : { description }),\n ...(components === undefined ? {} : { components: [...components] }),\n });\n }\n return mounted;\n }\n\n /**\n * The component list of the earliest mount of `id` that has one.\n * `undefined` when no mount of `id` limits its components.\n */\n private targetComponents(id: string) {\n const registrations = this.targets.get(id) ?? new Set<TargetRegistration>();\n return [...registrations].find(\n (registration) => registration.components !== undefined,\n )?.components;\n }\n\n /** The components that `validateOperation` allows on a surface. */\n private allowedComponentsFor(surface: ManagedSurface) {\n const components = this.targetComponents(surface.target);\n return components === undefined\n ? undefined\n : { target: surface.target, names: new Set(components) };\n }\n\n /**\n * The app state object. It is the same object until a key changes, so it\n * can be a `useSyncExternalStore` snapshot.\n */\n getState = () => this.state;\n\n /** Sets one state key. Notifies only when the value changed. */\n setState(key: string, value: unknown) {\n const isUnchanged =\n Object.hasOwn(this.state, key) && Object.is(this.state[key], value);\n if (isUnchanged) return;\n this.state = { ...this.state, [key]: value };\n this.notify();\n }\n\n /** Removes one state key. Notifies only when the key was set. */\n removeState(key: string) {\n if (!Object.hasOwn(this.state, key)) return;\n const { [key]: _removed, ...rest } = this.state;\n this.state = rest;\n this.notify();\n }\n\n /**\n * Makes the surfaces of `surfaceIds` share their data model: a user write\n * to one of them goes to all of them (see `setOwnedValue`). The markdown\n * transport links the parts of a chat surface that the prose lift split.\n * A later call for one of the surfaces replaces its group.\n *\n * @param threadId - The thread of the surfaces.\n * @param surfaceIds - The surface ids of the group. One id clears a link.\n */\n linkSurfaces(threadId: string, surfaceIds: readonly string[]) {\n const keys = new Set(surfaceIds.map((id) => surfaceKey(threadId, id)));\n for (const key of keys) {\n if (keys.size > 1) this.linked.set(key, keys);\n else this.linked.delete(key);\n }\n }\n\n /**\n * Writes a user value into the data model of a surface, and marks `path`\n * as user-owned. Then agent writes to that path, or below it, are ignored.\n * An agent write above it keeps the user value. Ownership ends when the\n * surface is deleted. Does nothing for an unknown or deleted surface. The\n * surfaces linked to it (see `linkSurfaces`) get the same write.\n *\n * @param key - The `key` of the surface.\n * @param path - An absolute JSON pointer, for example \"/form/email\".\n * @param value - The new value. It is copied.\n * @throws Error when a path segment is \"__proto__\", \"constructor\" or\n * \"prototype\", or when the path does not fit the data (for example, a\n * segment above it holds a string).\n */\n setOwnedValue(key: string, path: string, value: unknown): void {\n const normalized = normalizePath(path);\n const segments = normalized.split(\"/\");\n const forbidden = segments.find((segment) =>\n FORBIDDEN_SEGMENTS.has(segment),\n );\n if (forbidden !== undefined) {\n throw new Error(\n `[generativeUI] path segment \"${forbidden}\" is not allowed in \"${path}\".`,\n );\n }\n for (const target of this.linked.get(key) ?? [key]) {\n this.writeOwnedValue(target, normalized, value);\n }\n }\n\n private writeOwnedValue(key: string, path: string, value: unknown) {\n const surface = this.surfaces.get(key);\n if (!surface || surface.deleted) return;\n surface.model.dataModel.set(path, structuredClone(value));\n const owned = this.owned.get(key) ?? new Map<string, unknown>();\n owned.set(path, structuredClone(value));\n this.owned.set(key, owned);\n }\n\n /**\n * Writes the user-owned values into the new, empty data model of a rebuilt\n * surface. The agent operations are applied after it.\n */\n private restoreOwnedValues(surface: ManagedSurface) {\n const owned = this.owned.get(surface.key) ?? new Map<string, unknown>();\n for (const [path, value] of owned) {\n surface.model.dataModel.set(path, structuredClone(value));\n }\n }\n\n /**\n * The value that an agent write puts at `path`, with the user-owned values\n * below `path` written back into it. `undefined` when `path` is user-owned\n * or below a user-owned path, so the agent cannot write it. Throws when a\n * user value does not fit the new value.\n */\n private mergeOwnedValues(key: string, path: string, value: unknown) {\n const merged = { value: structuredClone(value) };\n const owned = this.owned.get(key);\n if (!owned) return merged;\n const ownedPaths = [...owned.keys()];\n const isBlocked = ownedPaths.some((ownedPath) =>\n isAtOrBelow(path, ownedPath),\n );\n if (isBlocked) return undefined;\n const below = ownedPaths.filter((ownedPath) =>\n isAtOrBelow(ownedPath, path),\n );\n if (below.length === 0) return merged;\n // A scratch model under \"/value\", so a root write merges the same way.\n const scratch = new DataModel({ value: merged.value });\n const prefix = path === \"/\" ? \"\" : path;\n for (const ownedPath of below) {\n const relative = ownedPath.slice(prefix.length);\n scratch.set(`/value${relative}`, structuredClone(owned.get(ownedPath)));\n }\n return { value: scratch.get(\"/value\") };\n }\n\n private extendsApplied(\n book: Bookkeeping,\n operations: A2UIOperation[],\n ): boolean {\n if (operations.length < book.appliedCount) return false;\n if (book.appliedCount === 0) return true;\n return (\n JSON.stringify(operations[book.appliedCount - 1]) === book.lastFingerprint\n );\n }\n\n private createSurface(\n key: string,\n threadId: string,\n agentId: string | undefined,\n content: GenerativeUISurfaceContent,\n ): ManagedSurface {\n const surface: ManagedSurface = {\n key,\n threadId,\n surfaceId: content.surfaceId,\n agentId,\n model: new SurfaceModel(content.surfaceId, this.webCoreCatalog),\n createdAt: ++creationCounter,\n target: content.target,\n status: content.status,\n deleted: false,\n failed: false,\n serverRejected: content.rejected ?? [],\n clientRejected: [],\n operations: [],\n };\n return surface;\n }\n\n private disposeSurface(key: string) {\n this.surfaces.get(key)?.model.dispose();\n this.surfaces.delete(key);\n this.bookkeeping.delete(key);\n }\n\n /**\n * Marks a surface deleted and frees its components and data. The record\n * stays, so the model is still told about the id and the bookkeeping does\n * not rebuild the surface for content that was already applied.\n */\n private closeSurface(surface: ManagedSurface) {\n surface.deleted = true;\n surface.model.dispose();\n surface.model = new SurfaceModel(surface.surfaceId, this.webCoreCatalog);\n this.owned.delete(surface.key);\n this.linked.delete(surface.key);\n }\n\n /** The surfaces of a thread that a part of `surfaceId` reads, for tests. */\n getLinkedSurfaceIds(threadId: string, surfaceId: string) {\n const keys = this.linked.get(surfaceKey(threadId, surfaceId));\n if (!keys) return [surfaceId];\n const prefix = `${threadId}::`;\n return [...keys].map((key) => key.slice(prefix.length));\n }\n\n /**\n * Drops the node keys that the app sets: bound props and matched events.\n * The model does not see them, so a model value for one is ignored, not\n * rejected. This runs before validation, because validation rejects keys\n * that are not in the manifest. It never changes the given operation.\n */\n private dropAppSetKeys(op: unknown) {\n const kind = getOperationKind(op);\n if (kind !== \"updateComponents\" && kind !== \"createSurface\") return op;\n // `getOperationKind` found a kind, so `op` is an object. The payload is\n // not checked yet, so every part of it is optional here.\n const record = op as Partial<\n Record<typeof kind, { components?: unknown } | null>\n >;\n const payload = record[kind];\n const nodes = payload?.components;\n if (!Array.isArray(nodes)) return op;\n return {\n ...record,\n [kind]: {\n ...payload,\n components: nodes.map((node) => this.dropAppSetNodeKeys(node)),\n },\n };\n }\n\n private dropAppSetNodeKeys(node: unknown) {\n if (typeof node !== \"object\" || node === null || !(\"component\" in node))\n return node;\n const { component } = node;\n if (typeof component !== \"string\") return node;\n const definition = this.ui.components.get(component);\n if (!definition) return node;\n return Object.fromEntries(\n Object.entries(node).filter(\n ([key]) =>\n !Object.hasOwn(definition.selectors, key) &&\n !Object.hasOwn(definition.eventFunctions, key),\n ),\n );\n }\n\n /**\n * The surfaces that `validateOperation` gets for one operation of the\n * content of `surface`.\n *\n * - `knownSurfaces`: the surface, when it exists before the operation. It\n * does not exist before its first createSurface, or after a delete.\n * - `createdSurfaces`: the surface, when a createSurface at this position\n * uses its id again. That is the case after the first operation, and for\n * a surface that was deleted before, unless the content replays that\n * delete.\n */\n private surfacesFor(\n surface: ManagedSurface,\n kind: OperationKind | undefined,\n position: OperationPosition,\n ) {\n const isFirstCreate = kind === \"createSurface\" && position.index === 0;\n const exists = !surface.deleted && !isFirstCreate;\n const isRecreate = this.deletedKeys.has(surface.key) && !position.isReplay;\n const isUsedAgain = position.index > 0 || isRecreate;\n return {\n knownSurfaces: new Set(exists ? [surface.surfaceId] : []),\n createdSurfaces: new Set(isUsedAgain ? [surface.surfaceId] : []),\n };\n }\n\n private applyOperation(\n surface: ManagedSurface,\n received: unknown,\n position: OperationPosition,\n ) {\n const { index } = position;\n const kind = getOperationKind(received);\n // An agent-called function is not a surface operation. The root runs it.\n if (kind === \"callRendererFunction\") return;\n const reject = (reason: string) => {\n // A surface whose first createSurface fails does not exist.\n if (kind === \"createSurface\" && index === 0) {\n this.closeSurface(surface);\n surface.failed = true;\n }\n surface.clientRejected.push({ index, reason });\n this.options.onOperationRejected?.({\n surfaceId: surface.surfaceId,\n index,\n reason,\n });\n };\n const targetId = getOperationSurfaceId(received);\n if (targetId !== undefined && targetId !== surface.surfaceId) {\n return reject(\n `operation is for surface \"${targetId}\", not \"${surface.surfaceId}\"`,\n );\n }\n const op = this.dropAppSetKeys(received);\n const validation = validateOperation(op, {\n manifest: {\n catalogId: this.ui.id,\n catalogIds: catalogIdsOf(this.ui),\n components: this.ui.manifestComponents,\n },\n ...this.surfacesFor(surface, kind, position),\n allowedComponents: this.allowedComponentsFor(surface),\n });\n if (!validation.ok) return reject(validation.reason);\n\n // validateOperation checked the shape of `op`.\n const typed = op as A2UIOperation;\n if (\"createSurface\" in typed) {\n const { dataModel, components = [] } = typed.createSurface;\n const problem = this.nodesProblem(components);\n if (problem) return reject(problem);\n if (dataModel) {\n const failure = this.writeAgentData(surface, \"/\", dataModel);\n if (failure) return reject(failure);\n }\n for (const node of components) this.upsertNode(surface.model, node);\n return;\n }\n if (\"updateComponents\" in typed) {\n const nodes = typed.updateComponents.components;\n const problem = this.nodesProblem(nodes);\n if (problem) return reject(problem);\n for (const node of nodes) this.upsertNode(surface.model, node);\n return;\n }\n if (\"updateDataModel\" in typed) {\n const { path = \"/\", value } = typed.updateDataModel;\n // A `null` value deletes the key. web_core deletes it for `undefined`.\n const written = value === null ? undefined : value;\n const failure = this.writeAgentData(\n surface,\n normalizePath(path),\n written,\n );\n if (failure) return reject(failure);\n return;\n }\n if (\"deleteSurface\" in typed) {\n this.closeSurface(surface);\n this.deletedKeys.add(surface.key);\n }\n }\n\n /** The first node with props of the wrong type, as a reason. */\n private nodesProblem(nodes: A2UIComponentNode[]) {\n for (const node of nodes) {\n const problem = this.checkNodeProps(node);\n if (problem) return `component \"${node.id}\": ${problem}`;\n }\n return undefined;\n }\n\n /**\n * Writes an agent value at `path` and keeps the user-owned values. A write\n * to a user-owned path is ignored, not rejected. Gives the reason when the\n * value does not fit the data, else `undefined`.\n */\n private writeAgentData(\n surface: ManagedSurface,\n path: string,\n value: unknown,\n ) {\n try {\n // The merge clones, so the agent's content objects are never mutated\n // or aliased.\n const merged = this.mergeOwnedValues(surface.key, path, value);\n if (merged) surface.model.dataModel.set(path, merged.value);\n return undefined;\n } catch (error) {\n return error instanceof Error ? error.message : String(error);\n }\n }\n\n private checkNodeProps(node: A2UIComponentNode): string | undefined {\n const definition = this.ui.components.get(node.component);\n if (!definition) return `unknown component \"${node.component}\"`;\n const { id: _id, component: _component, ...rest } = node;\n const dataProps = Object.fromEntries(\n Object.entries(rest).filter(\n ([key]) =>\n !definition.events?.[key] &&\n !definition.slots?.[key] &&\n !A2UI_COMPONENT_ENVELOPE_KEYS.has(key),\n ),\n );\n if (!definition.props) return undefined;\n // The props schema checks the literal values. A prop with a `{\"@path\"}`\n // or `{\"@call\"}` anywhere in it is known only at render, and so is the\n // value of a bound prop: their issues are left to the render check.\n const unknownNow = new Set(Object.keys(definition.selectors));\n const literals: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(dataProps)) {\n if (containsDynamicValue(value)) unknownNow.add(key);\n else literals[key] = value;\n }\n let result = validateSchemaSync(definition.props, literals);\n if (!result.success) {\n // A null the schema rejects is an unset prop (the render check reads\n // it so too): check again without it.\n const unset = withoutRejectedNulls(literals, result.issues);\n if (unset) result = validateSchemaSync(definition.props, unset);\n }\n if (result.success) return undefined;\n // ponytail: an issue with no path (a check over several props) is left to the render check too, because it can depend on the values above. Only a schema that cannot validate synchronously is reported here.\n const issues = result.issues.filter((issue) => {\n const key = issueKey(issue);\n return key === undefined ? isAsyncIssue(issue) : !unknownNow.has(key);\n });\n return issues.length > 0 ? formatIssues(issues) : undefined;\n }\n\n private upsertNode(model: SurfaceModel<any>, node: A2UIComponentNode) {\n const { id, component, ...rest } = node;\n const properties = structuredClone(rest);\n const existing = model.componentsModel.get(id);\n if (existing && existing.type === component) {\n existing.properties = properties;\n return;\n }\n if (existing) model.componentsModel.removeComponent(id);\n model.componentsModel.addComponent(\n new ComponentModel(id, component, properties),\n );\n }\n}\n","import {\n callerProblem,\n functionCallers,\n GENERATIVE_UI_AGENT_FUNCTION_CALLS,\n GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON,\n GENERATIVE_UI_FUNCTIONS,\n} from \"@copilotkit/shared\";\nimport type {\n A2UIFunctionPermissions,\n A2UIFunctionReturnType,\n GenerativeUIFunctionManifest,\n StandardSchemaV1,\n} from \"@copilotkit/shared\";\nimport { GenerativeUIError } from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUIInvokeResult } from \"@copilotkit/shared/generative-ui\";\nimport { BASIC_FUNCTIONS, ExpressionError } from \"./functions\";\nimport { toJsonSchema } from \"@copilotkit/shared/generative-ui\";\n\n/**\n * A function that generated UI may call, as declared in\n * `createGenerativeUI({ functions })`. Zod schemas fit `parameters`, because\n * they implement Standard Schema.\n */\nexport interface GenerativeUIDeclaredFunction extends A2UIFunctionPermissions {\n description?: string;\n parameters: StandardSchemaV1;\n returnType?: A2UIFunctionReturnType;\n}\n\n/**\n * Holds the latest handler of one mounted `useGenerativeUIFunction`. The hook\n * updates `current` on each render, so it registers only once per mount.\n */\nexport interface GenerativeUIHandlerRef {\n current: (args: any) => unknown;\n}\n\n/** The component of a surface that called a function. */\nexport interface GenerativeUIInvocationOrigin {\n surfaceId: string;\n componentId: string;\n}\n\n/**\n * What called a function: a component of a surface, or the agent with a\n * `callRendererFunction` operation.\n */\nexport type GenerativeUICallOrigin =\n | GenerativeUIInvocationOrigin\n | { functionCallId: string };\n\nexport interface GenerativeUIDispatcher {\n /**\n * Call a declared function with arguments from generated UI or from the\n * agent. Never throws: every failure becomes `{ ok: false, error }`.\n */\n invoke(\n name: string,\n args: unknown,\n origin: GenerativeUICallOrigin,\n ): Promise<GenerativeUIInvokeResult>;\n /** The declared functions that have exactly one mounted handler, as JSON Schema. */\n listExposed(): Record<string, GenerativeUIFunctionManifest>;\n /**\n * Mount a handler for a declared function. Returns the function that\n * unmounts it. Calling the returned function more than once is safe.\n */\n register(name: string, ref: GenerativeUIHandlerRef): () => void;\n /** How many handlers are mounted for `name`, for the inspector. */\n handlerCount(name: string): number;\n}\n\nexport interface GenerativeUIDispatcherOptions {\n /** The functions declared in `createGenerativeUI({ functions })`, read at call time. */\n getDeclared: () => ReadonlyMap<string, GenerativeUIDeclaredFunction>;\n /** Called for each failed `invoke`. A throw from it is ignored. */\n onError?: (info: {\n name: string;\n origin: GenerativeUICallOrigin;\n error: GenerativeUIError;\n }) => void;\n}\n\ntype Resolved =\n | {\n ok: true;\n declared: GenerativeUIDeclaredFunction;\n ref: GenerativeUIHandlerRef;\n }\n | { ok: false; error: GenerativeUIError };\n\nconst messageOf = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/**\n * Creates the registry of functions that generated UI may call.\n *\n * A function is callable when it is declared in `getDeclared()` and exactly\n * one handler is mounted for it with `register`. Names are resolved at call\n * time and fail closed. Nothing is sent to the agent.\n * Neither `invoke` nor `listExposed` throws.\n *\n * @param options.getDeclared - Returns the declared functions.\n * @param options.onError - Gets each failed call.\n *\n * @example\n * ```ts\n * const dispatcher = createGenerativeUIDispatcher({\n * getDeclared: () => new Map(Object.entries(ui.functions)),\n * });\n * const unregister = dispatcher.register(\"addToCart\", handlerRef);\n * await dispatcher.invoke(\"addToCart\", { productId: \"p1\" }, origin);\n * unregister();\n * ```\n */\n/**\n * True while the browser counts the current task as user-activated (a\n * click, a key press). Where the API is missing (older browsers, test\n * environments), the gesture is assumed.\n */\nfunction hasUserActivation() {\n if (typeof navigator === \"undefined\") return true;\n const activation = (\n navigator as Navigator & {\n userActivation?: { isActive: boolean };\n }\n ).userActivation;\n return activation === undefined || activation.isActive;\n}\n\n/**\n * The permissions of a declared function as the manifest states them: the\n * callers always written out, so a reader needs no default.\n */\nfunction permissionsOf(fn: A2UIFunctionPermissions) {\n const callers = functionCallers(fn);\n return {\n allowedCallers:\n callers.renderer && callers.agent\n ? (\"rendererOrAgent\" as const)\n : callers.agent\n ? (\"agentOnly\" as const)\n : (\"rendererOnly\" as const),\n ...(fn.requiresUserActivation ? { requiresUserActivation: true } : {}),\n };\n}\n\nexport function createGenerativeUIDispatcher(\n options: GenerativeUIDispatcherOptions,\n) {\n const handlers = new Map<string, Set<GenerativeUIHandlerRef>>();\n\n const resolveUnchecked = (name: string): Resolved => {\n const declared = options.getDeclared().get(name);\n if (!declared) {\n return {\n ok: false,\n error: new GenerativeUIError(\n \"function_not_found\",\n `No generative UI function named \"${name}\" is declared in createGenerativeUI({ functions })`,\n ),\n };\n }\n const mounted = [...(handlers.get(name) ?? [])];\n const [ref] = mounted;\n if (!ref) {\n return {\n ok: false,\n error: new GenerativeUIError(\n \"function_not_found\",\n `\"${name}\" is declared, but no useGenerativeUIFunction handler is mounted for it`,\n ),\n };\n }\n if (mounted.length > 1) {\n return {\n ok: false,\n error: new GenerativeUIError(\n \"function_conflict\",\n `\"${name}\" has ${mounted.length} useGenerativeUIFunction handlers mounted. Mount exactly one.`,\n ),\n };\n }\n return { ok: true, declared, ref };\n };\n\n const isDeclared = (name: string) => {\n try {\n return options.getDeclared().has(name);\n } catch {\n return false;\n }\n };\n\n // getDeclared is outside code; a throw here becomes a result, not a rejection.\n const resolve = (name: string): Resolved => {\n try {\n return resolveUnchecked(name);\n } catch (error) {\n return {\n ok: false,\n error: new GenerativeUIError(\n \"handler_failed\",\n `\"${name}\" could not be resolved: ${messageOf(error)}`,\n ),\n };\n }\n };\n\n const validateArgs = async (\n name: string,\n schema: StandardSchemaV1,\n args: unknown,\n ): Promise<\n { ok: true; value: unknown } | { ok: false; error: GenerativeUIError }\n > => {\n try {\n const validation = await schema[\"~standard\"].validate(args);\n if (!validation.issues) return { ok: true, value: validation.value };\n const detail = validation.issues\n .map(\n (i) =>\n `${(i.path ?? []).map((p) => (typeof p === \"object\" ? p.key : p)).join(\".\") || \"args\"}: ${i.message}`,\n )\n .join(\"; \");\n return {\n ok: false,\n error: new GenerativeUIError(\n \"invalid_arguments\",\n `Invalid arguments for \"${name}\": ${detail}`,\n ),\n };\n } catch (error) {\n // A schema transform or refinement that throws is a rejection of the arguments.\n return {\n ok: false,\n error: new GenerativeUIError(\n \"invalid_arguments\",\n `Invalid arguments for \"${name}\": ${messageOf(error)}`,\n ),\n };\n }\n };\n\n const failWith = (\n name: string,\n origin: GenerativeUICallOrigin,\n error: GenerativeUIError,\n ): GenerativeUIInvokeResult => {\n try {\n options.onError?.({ name, origin, error });\n } catch {\n // A throwing onError must not turn a failed call into a rejection.\n }\n return { ok: false, error };\n };\n\n /**\n * Why `origin` may not call a function with these permissions now, as an\n * error, or `undefined` when it may. The agent is refused what is for the\n * renderer; a component is refused what is for the agent, and a gesture\n * function when the browser counts no user activation.\n */\n const callerError = (\n name: string,\n fn: A2UIFunctionPermissions,\n origin: GenerativeUICallOrigin,\n ) => {\n const isComponent = \"componentId\" in origin;\n if (!isComponent && !GENERATIVE_UI_AGENT_FUNCTION_CALLS) {\n return new GenerativeUIError(\n \"invalid_function_call\",\n GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON,\n );\n }\n const problem = callerProblem(name, fn, isComponent ? \"renderer\" : \"agent\");\n if (problem !== undefined) {\n return new GenerativeUIError(\"invalid_function_call\", problem);\n }\n // A component event is not always a gesture: onVisible fires from an\n // IntersectionObserver. Browsers track activation themselves.\n if (isComponent && fn.requiresUserActivation && !hasUserActivation()) {\n return new GenerativeUIError(\n \"invalid_function_call\",\n `function \"${name}\" runs only from a user gesture; this event was not one`,\n );\n }\n return undefined;\n };\n\n /**\n * Runs a basic function of the A2UI catalog. They are value functions of\n * the renderer: the agent cannot call them, and one that needs a user\n * gesture runs only from an event binding.\n */\n const invokeBasic = (\n name: string,\n args: unknown,\n origin: GenerativeUICallOrigin,\n ): GenerativeUIInvokeResult => {\n const info = GENERATIVE_UI_FUNCTIONS[name];\n const run = BASIC_FUNCTIONS[name];\n if (!info || !run) {\n return failWith(\n name,\n origin,\n new GenerativeUIError(\n \"function_not_found\",\n `\"${name}\" is not a basic function`,\n ),\n );\n }\n const refused = callerError(name, info, origin);\n if (refused) return failWith(name, origin, refused);\n const isObject =\n typeof args === \"object\" && args !== null && !Array.isArray(args);\n if (args !== undefined && !isObject) {\n return failWith(\n name,\n origin,\n new GenerativeUIError(\n \"invalid_arguments\",\n `Invalid arguments for \"${name}\": args must be an object`,\n ),\n );\n }\n try {\n return {\n ok: true,\n result: run((args ?? {}) as Record<string, unknown>),\n };\n } catch (error) {\n return failWith(\n name,\n origin,\n new GenerativeUIError(\n error instanceof ExpressionError\n ? \"invalid_arguments\"\n : \"handler_failed\",\n `\"${name}\" failed: ${messageOf(error)}`,\n ),\n );\n }\n };\n\n const dispatcher: GenerativeUIDispatcher = {\n async invoke(name, args, origin) {\n const resolved = resolve(name);\n // A declared function wins over a basic one of the same name, also\n // while its handler is not mounted: that is an error of the app, not\n // a call of the basic function.\n if (\n !resolved.ok &&\n resolved.error.code === \"function_not_found\" &&\n !isDeclared(name) &&\n Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name)\n ) {\n return invokeBasic(name, args, origin);\n }\n if (!resolved.ok) return failWith(name, origin, resolved.error);\n const refused = callerError(name, resolved.declared, origin);\n if (refused) return failWith(name, origin, refused);\n const validated = await validateArgs(\n name,\n resolved.declared.parameters,\n args ?? {},\n );\n if (!validated.ok) return failWith(name, origin, validated.error);\n try {\n // Read `current` now, so the latest handler runs.\n return {\n ok: true,\n result: await resolved.ref.current(validated.value),\n };\n } catch (error) {\n return failWith(\n name,\n origin,\n new GenerativeUIError(\n \"handler_failed\",\n `\"${name}\" failed: ${messageOf(error)}`,\n ),\n );\n }\n },\n\n listExposed() {\n let names: string[];\n try {\n names = [...options.getDeclared().keys()];\n } catch {\n // If the declared functions cannot be read, advertise nothing.\n return {};\n }\n // Advertise exactly the names invoke would accept. While the agent\n // path is off, a function for the agent only has no caller at all.\n const listed: Record<string, GenerativeUIFunctionManifest> = {};\n for (const name of names) {\n const resolved = resolve(name);\n if (!resolved.ok) continue;\n const isAgentOnly = !functionCallers(resolved.declared).renderer;\n if (isAgentOnly && !GENERATIVE_UI_AGENT_FUNCTION_CALLS) continue;\n const { description, parameters, returnType } = resolved.declared;\n try {\n listed[name] = {\n ...(description ? { description } : {}),\n parameters: toJsonSchema(parameters),\n ...(returnType ? { returnType } : {}),\n ...permissionsOf(resolved.declared),\n };\n } catch {\n // A schema that cannot be converted to JSON Schema is not advertised.\n }\n }\n return listed;\n },\n\n register(name, ref) {\n const mounted = handlers.get(name) ?? new Set<GenerativeUIHandlerRef>();\n mounted.add(ref);\n handlers.set(name, mounted);\n // An empty set stays in the map. It resolves as \"no handler mounted\".\n return () => {\n mounted.delete(ref);\n };\n },\n\n handlerCount: (name) => handlers.get(name)?.size ?? 0,\n };\n return dispatcher;\n}\n","import type {\n GenerativeUIActionBinding,\n GenerativeUIUserEvent,\n} from \"@copilotkit/shared\";\nimport { GenerativeUIError } from \"@copilotkit/shared/generative-ui\";\nimport { resolveDynamicValue } from \"./resolve\";\nimport type { ResolveContext } from \"./resolve\";\nimport type { GenerativeUIInvokeResult } from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUIInvocationOrigin } from \"./dispatcher\";\nimport { reportErrorSafely } from \"./runtime\";\nimport type { GenerativeUIEngine } from \"./runtime\";\nimport { formatIssues, validateSchema } from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUISchema } from \"@copilotkit/shared/generative-ui\";\nimport type { ManagedSurface } from \"./surface-manager\";\n\n/** One call of an event prop by a component. */\ninterface EventCall {\n runtime: GenerativeUIEngine;\n surface: ManagedSurface;\n componentId: string;\n /** The event prop name, for error messages. */\n name: string;\n /**\n * The event `parameters`. When absent, the args go on unchecked. That is\n * the case for a matched event without `parameters`: the function schema\n * checks them.\n */\n parameters?: GenerativeUISchema;\n args: unknown;\n}\n\n/**\n * The context of a running event binding: it reads the surface data model\n * and resolves relative paths against the template item of the component.\n * A function that needs a user gesture (openUrl) is not a value here\n * either; it runs through the dispatcher as the binding's functionCall.\n */\nfunction eventContext(\n surface: ManagedSurface,\n basePath: string | undefined,\n): ResolveContext {\n return { data: surface.model.dataModel, basePath };\n}\n\n/**\n * A value of an event binding with its dynamic values resolved: `{\"@path\"}`\n * bindings and function values, at any depth.\n */\nfunction resolveValue(\n surface: ManagedSurface,\n basePath: string | undefined,\n value: unknown,\n) {\n return resolveDynamicValue(value, eventContext(surface, basePath)).value;\n}\n\n/**\n * The entries of an args or context record, each resolved on its own. The\n * record is not resolved as a whole, because a record with one `event` or\n * `functionCall` key would look like an action binding and stay as it is.\n */\nfunction resolveValues(\n surface: ManagedSurface,\n basePath: string | undefined,\n values: Record<string, unknown> | undefined,\n) {\n return Object.fromEntries(\n Object.entries(values ?? {}).map(([key, value]) => [\n key,\n resolveValue(surface, basePath, value),\n ]),\n );\n}\n\n/**\n * The `userMessage` of an event binding, as text. A `{\"@path\"}` or a\n * function value is resolved. `undefined` when there is no message, or\n * the value is not a string.\n */\nfunction resolveUserMessage(\n surface: ManagedSurface,\n basePath: string | undefined,\n userMessage: unknown,\n) {\n const value = resolveValue(surface, basePath, userMessage);\n return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * Validates the component's args with the event `parameters`, then runs\n * `send` with them. Never throws: every failure is reported and becomes\n * `{ ok: false, error }`.\n */\nasync function runEvent(\n call: EventCall,\n send: (\n componentArgs: unknown,\n origin: GenerativeUIInvocationOrigin,\n ) => Promise<GenerativeUIInvokeResult>,\n): Promise<GenerativeUIInvokeResult> {\n const { runtime, surface, componentId, name, parameters, args } = call;\n const origin = { surfaceId: surface.surfaceId, componentId };\n try {\n if (!parameters) return await send(args ?? {}, origin);\n // A schema that validates synchronously sends in the same tick.\n const result = validateSchema(parameters, args ?? {});\n const parsed = result instanceof Promise ? await result : result;\n if (!parsed.success) {\n const error = new GenerativeUIError(\n \"invalid_event_args\",\n `${name}: ${formatIssues(parsed.issues, \"args\")}`,\n );\n reportErrorSafely(runtime, { kind: \"event\", ...origin, error });\n return { ok: false, error };\n }\n return await send(parsed.data ?? {}, origin);\n } catch (cause) {\n const error = new GenerativeUIError(\n \"event_forward_failed\",\n `${name}: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n reportErrorSafely(runtime, { kind: \"event\", ...origin, error });\n return { ok: false, error };\n }\n}\n\n/**\n * Runs one call of an event that the model bound: validates the component's\n * args, merges them with the args from the binding (binding literals win),\n * then calls a declared function or forwards an agent event. Never throws.\n */\nexport function invokeBoundEvent(\n params: EventCall & {\n binding: GenerativeUIActionBinding;\n /** The template item path of the component, for relative paths. */\n basePath: string | undefined;\n },\n) {\n const { runtime, surface, binding, basePath } = params;\n return runEvent(params, (args, origin) => {\n // ponytail: the args are spread into the call. Args that are not an object are lost, as before.\n const componentArgs = args as Record<string, unknown>;\n if (\"functionCall\" in binding) {\n return runtime.dispatcher.invoke(\n binding.functionCall[\"@call\"],\n {\n ...componentArgs,\n ...resolveValues(surface, basePath, binding.functionCall.args),\n },\n origin,\n );\n }\n const { event } = binding;\n const forwarded: GenerativeUIUserEvent = {\n name: event.name,\n ...origin,\n timestamp: new Date().toISOString(),\n userMessage: resolveUserMessage(surface, basePath, event.userMessage),\n context: {\n ...componentArgs,\n ...resolveValues(surface, basePath, event.context),\n },\n };\n return runtime.forwardEvent(forwarded, surface.agentId);\n });\n}\n\n/**\n * Runs one call of an event that matches a declared function: validates the\n * component's args with the event `parameters` (if any), then calls the\n * function, which validates them with its own schema. Never throws.\n */\nexport function invokeMatchedEvent(\n params: EventCall & { functionName: string },\n) {\n const { runtime, functionName } = params;\n return runEvent(params, (componentArgs, origin) =>\n runtime.dispatcher.invoke(functionName, componentArgs, origin),\n );\n}\n","import {\n buildGenerativeUIMarkdownGuidelines,\n generativeUIGuideFeatures,\n COPILOTKIT_UI_ENVELOPE_FORMAT,\n GENERATIVE_UI_CHAT_TARGET,\n GENERATIVE_UI_FUNCTIONS,\n applyDescriptionOverrides,\n defaultGenerativeUIPromptSpec,\n} from \"@copilotkit/shared\";\nimport type {\n A2UIActionMessage,\n CopilotKitUIEnvelope,\n GenerativeUIFunctionManifest,\n GenerativeUIManifest,\n GenerativeUISurfaceSummary,\n GenerativeUITarget,\n} from \"@copilotkit/shared\";\nimport { catalogIdsOf } from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUI } from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUIEngine } from \"./runtime\";\n\n/**\n * The built-in functions (the A2UI basic catalog plus calc and series) as\n * manifest entries. Their args are described by the short signature, not\n * by a full JSON Schema: the renderer checks them when they run. An app\n * function of the same name replaces the entry.\n */\nexport function builtInFunctionManifests(): Record<\n string,\n GenerativeUIFunctionManifest\n> {\n return Object.fromEntries(\n Object.entries(GENERATIVE_UI_FUNCTIONS).map(([name, fn]) => [\n name,\n {\n description: fn.description,\n parameters: { type: \"object\", description: fn.parameters },\n returnType: fn.returnType,\n allowedCallers: fn.allowedCallers,\n ...(fn.requiresUserActivation ? { requiresUserActivation: true } : {}),\n },\n ]),\n );\n}\n\n/** What `buildCatalogManifest` adds to the catalog. */\nexport interface CatalogManifestOptions {\n /** The app functions with a mounted handler. A built-in of the same name is left out. */\n functions?: Record<string, GenerativeUIFunctionManifest>;\n /** The inline targets, after the chat target. */\n targets?: GenerativeUITarget[];\n /** The surfaces of the thread. */\n surfaces?: Record<string, GenerativeUISurfaceSummary>;\n}\n\n/**\n * The manifest of a catalog, with no React runtime: the components of `ui`,\n * the built-in functions (minus the names the app declares) and\n * `options.functions`, the chat target and `options.targets`, and\n * `options.surfaces`. `buildGenerativeUIManifest` builds the per-run\n * manifest with it; tools that run outside React use it directly.\n *\n * @example\n * ```ts\n * const manifest = buildCatalogManifest(standardUI);\n * manifest.targets; // [{ id: \"chat\", kind: \"chat\" }]\n * ```\n */\nexport function buildCatalogManifest(\n ui: Pick<GenerativeUI, \"id\" | \"manifestComponents\" | \"functions\">,\n options: CatalogManifestOptions = {},\n): GenerativeUIManifest {\n return {\n catalogId: ui.id,\n catalogIds: catalogIdsOf(ui),\n // The description overrides of the default prompt spec (none today), so\n // the client sends the descriptions that evaluations measure.\n components: applyDescriptionOverrides(\n { components: ui.manifestComponents },\n defaultGenerativeUIPromptSpec().descriptions,\n ).manifest.components,\n // A name the app declares is the app's, also while its handler is not\n // mounted: the dispatcher never runs the built-in in its place.\n functions: {\n ...Object.fromEntries(\n Object.entries(builtInFunctionManifests()).filter(\n ([name]) => !ui.functions.has(name),\n ),\n ),\n ...options.functions,\n },\n targets: [\n { id: GENERATIVE_UI_CHAT_TARGET, kind: \"chat\" },\n ...(options.targets ?? []),\n ],\n surfaces: options.surfaces ?? {},\n };\n}\n\n/**\n * Builds the per-run manifest. Never contains handlers or renderers.\n *\n * - `functions`: the built-in functions, then the declared functions with\n * exactly one mounted handler.\n * - `targets`: the chat first, then each mounted `<GenerativeUISurface>`,\n * with its `description` and its `components` when it has them.\n */\nexport function buildGenerativeUIManifest(\n runtime: Pick<GenerativeUIEngine, \"ui\" | \"manager\" | \"dispatcher\">,\n threadId: string | undefined,\n) {\n const { ui, manager, dispatcher } = runtime;\n const inlineTargets = manager\n .getMountedTargets()\n .filter((target) => target.id !== GENERATIVE_UI_CHAT_TARGET)\n .map(({ id, ...rest }) => ({ id, kind: \"inline\" as const, ...rest }));\n return buildCatalogManifest(ui, {\n functions: dispatcher.listExposed(),\n targets: inlineTargets,\n surfaces: threadId ? manager.describeSurfaces(threadId) : {},\n });\n}\n\n/** How to build the envelope of one run. */\nexport interface GenerativeUIEnvelopeOptions {\n transport: CopilotKitUIEnvelope[\"metadata\"][\"extensions\"][\"copilotkit_transport\"];\n /**\n * Send the component schemas. The tool transport always sends them,\n * because the runtime validates operations with them.\n */\n includeCatalog: boolean;\n /** True when the client also sends the guide as context entries. */\n contextSent: boolean;\n /**\n * The markdown guideline. Left out, the markdown transport builds it from\n * the manifest, with only the rule groups that the manifest uses. The\n * tool transport sends none.\n */\n instructions?: string;\n /** The user action that starts this run, when one does. */\n action?: A2UIActionMessage;\n}\n\n/** The transport options of a framework's generative UI config. */\nexport interface GenerativeUITransportConfig {\n transport?: \"tool\" | \"markdown\";\n /** Markdown only. Default `true`. */\n sendContext?: boolean;\n /** Markdown only. Default `true`. */\n includeCatalog?: boolean;\n}\n\n/** What the envelope of a run says, from the provider config. */\nexport function envelopeOptionsFor(\n config: GenerativeUITransportConfig,\n): GenerativeUIEnvelopeOptions {\n if (config.transport === \"markdown\") {\n return {\n transport: \"markdown\",\n includeCatalog: config.includeCatalog !== false,\n contextSent: config.sendContext !== false,\n };\n }\n return { transport: \"tool\", includeCatalog: true, contextSent: false };\n}\n\n/**\n * Builds the envelope that a run sends as `forwardedProps.copilotkit.ui`,\n * from the per-run manifest. It has the A2UI v1.0 renderer capabilities\n * shape: one inline catalog with the id of the UI, and the CopilotKit data\n * in `metadata.extensions`.\n *\n * The inline catalog has no `components` only for the markdown transport\n * with `includeCatalog: false`. It has `instructions` for the markdown\n * transport, or when given.\n *\n * @param runtime - The generative UI runtime of the provider.\n * @param threadId - The thread of the run. Its surfaces go in `copilotkit_surfaces`.\n * @param options - The transport and what to send.\n *\n * @example\n * ```ts\n * const envelope = buildGenerativeUIEnvelope(runtime, agent.threadId, {\n * transport: \"tool\",\n * includeCatalog: true,\n * contextSent: false,\n * });\n * envelope[\"1.0\"].supportedCatalogIds; // [runtime.ui.id]\n * ```\n */\nexport function buildGenerativeUIEnvelope(\n runtime: Pick<GenerativeUIEngine, \"ui\" | \"manager\" | \"dispatcher\">,\n threadId: string | undefined,\n options: GenerativeUIEnvelopeOptions,\n) {\n const { transport, includeCatalog, contextSent, action } = options;\n const manifest = buildGenerativeUIManifest(runtime, threadId);\n // The markdown guideline has only the rule groups that this manifest uses.\n const instructions =\n options.instructions ??\n (transport === \"markdown\"\n ? buildGenerativeUIMarkdownGuidelines(generativeUIGuideFeatures(manifest))\n : undefined);\n const omitComponents = transport === \"markdown\" && !includeCatalog;\n const envelope: CopilotKitUIEnvelope = {\n \"1.0\": {\n supportedCatalogIds: manifest.catalogIds ?? [manifest.catalogId],\n inlineCatalogs: [\n {\n catalogId: manifest.catalogId,\n protocolVersion: \"1.0\",\n ...(omitComponents ? {} : { components: manifest.components }),\n functions: manifest.functions,\n ...(instructions === undefined ? {} : { instructions }),\n },\n ],\n },\n metadata: {\n extensions: {\n copilotkit_format: COPILOTKIT_UI_ENVELOPE_FORMAT,\n copilotkit_transport: transport,\n copilotkit_targets: manifest.targets,\n copilotkit_surfaces: manifest.surfaces,\n copilotkit_contextSent: contextSent,\n ...(action === undefined ? {} : { copilotkit_action: action }),\n },\n },\n };\n return envelope;\n}\n","import type { ChildRef } from \"@copilotkit/shared\";\nimport type { Message } from \"@ag-ui/client\";\nimport {\n extractFenceOperations,\n flattenInformationalCards,\n getMarkdownOperationSurfaceId,\n prepareSurfaceOperations,\n segmentSurfaceProse,\n splitA2UIMarkdown,\n} from \"../a2ui-markdown\";\nimport type { A2UIMarkdownOperation, ChildIdsOf } from \"../a2ui-markdown\";\nimport {\n A2UI_VERSION,\n GENERATIVE_UI_CHAT_TARGET,\n GENERATIVE_UI_ROOT_ID,\n getOperationKind,\n validateOperation,\n childIdsAtRefs,\n collectChildRefs,\n hasBoundChildRef,\n} from \"@copilotkit/shared\";\nimport type {\n A2UIOperation,\n GenerativeUIFunctionManifest,\n GenerativeUIRejectedOperation,\n GenerativeUISurfaceContent,\n ValidateOperationOptions,\n} from \"@copilotkit/shared\";\nimport { catalogIdsOf } from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUI } from \"@copilotkit/shared/generative-ui\";\nimport { toJsonSchema } from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUISurfaceManager } from \"./surface-manager\";\nimport { isRecord } from \"@copilotkit/shared/generative-ui\";\n\n/** What renders in place of one ```a2ui fence, in order. */\nexport type MarkdownFenceBlock =\n | { kind: \"markdown\"; markdown: string }\n | { kind: \"surface\"; surfaceId: string };\n\n/** The part of a generative UI that the markdown source reads. */\ntype MarkdownSourceUI = Pick<GenerativeUI, \"id\" | \"manifestComponents\">;\n\nexport interface BuildMarkdownSurfacesOptions {\n ui: MarkdownSourceUI;\n /** The declared functions. A `functionCall` must name one of them. */\n functions: Record<string, GenerativeUIFunctionManifest>;\n /**\n * The last message can still grow. Then an open fence in it is still\n * streaming: its last, unfinished operation is left out, and the surface\n * it creates has the status \"streaming\". Else an open fence is final.\n */\n running: boolean;\n /**\n * The results of the earlier builds of the same thread. A build then\n * parses only the fences that changed, and builds only the surfaces whose\n * operations changed. Left out, everything is built again.\n */\n cache?: MarkdownBuildCache;\n}\n\n/**\n * Values by key, from the latest build. A value that a build does not use\n * is dropped at the end of that build, so the cache does not grow.\n */\nclass BuildMemo<V> {\n private previous = new Map<string, V>();\n private current = new Map<string, V>();\n\n /**\n * The value of `key`. It is computed when no earlier value is there, or\n * when `isFresh` says that the earlier value is out of date.\n */\n get(\n key: string,\n compute: () => V,\n isFresh: (value: V) => boolean = () => true,\n ) {\n let value = this.current.get(key) ?? this.previous.get(key);\n if (value === undefined || !isFresh(value)) value = compute();\n this.current.set(key, value);\n return value;\n }\n\n endBuild() {\n this.previous = this.current;\n this.current = new Map();\n }\n}\n\n/** The surfaces that one draft gives, and the operations it was built from. */\ninterface BuiltDraft {\n operations: A2UIMarkdownOperation[];\n target: string;\n streaming: boolean;\n parts: SurfacePart[];\n contents: GenerativeUISurfaceContent[];\n}\n\n/** The results of the builds of one thread. See `BuildMarkdownSurfacesOptions.cache`. */\nexport class MarkdownBuildCache {\n readonly segments = new BuildMemo<ReturnType<typeof splitA2UIMarkdown>>();\n readonly fences = new BuildMemo<{\n operations: A2UIMarkdownOperation[];\n functionCalls: A2UIMarkdownOperation[];\n }>();\n readonly drafts = new BuildMemo<BuiltDraft>();\n /** The copies of an operation for other surface ids, by operation. */\n readonly readdressed = new WeakMap<\n object,\n Map<string, A2UIMarkdownOperation>\n >();\n\n endBuild() {\n this.segments.endBuild();\n this.fences.endBuild();\n this.drafts.endBuild();\n }\n}\n\n/** True when both lists hold the same objects in the same order. */\nfunction sameItems<T>(a: readonly T[], b: readonly T[]) {\n return a.length === b.length && a.every((item, index) => item === b[index]);\n}\n\n/** One surface, collected from the fences of all messages. */\ninterface SurfaceDraft {\n surfaceId: string;\n target: string;\n operations: A2UIMarkdownOperation[];\n /** The fence that created the surface is still streaming. */\n streaming: boolean;\n}\n\n/** The surface content, or one surface of it after the prose lift. */\ntype SurfacePart =\n | { kind: \"markdown\"; markdown: string }\n | {\n kind: \"surface\";\n surfaceId: string;\n operations: A2UIMarkdownOperation[];\n };\n\nfunction isString(value: unknown): value is string {\n return typeof value === \"string\";\n}\n\n/** The key of one fence of one message. */\nexport function fenceKey(messageId: string, fenceIndex: number) {\n return `${messageId}:${fenceIndex}`;\n}\n\n/** One `callRendererFunction` line of a fence, in the order of the fences. */\nexport interface MarkdownFunctionCall {\n messageId: string;\n fenceIndex: number;\n /** The operation as the model wrote it. It is not validated yet. */\n operation: A2UIMarkdownOperation;\n}\n\n/**\n * The operations of a fence body. While the fence streams, the last object\n * can be unfinished. Of an unfinished updateComponents or createSurface, the\n * components that are complete render at once (a createSurface also keeps\n * its data model when all of it arrived). Any other unfinished object is\n * left out, because a part of a data model value can still change. A final\n * fence keeps what can be saved from an unfinished object.\n */\nfunction fenceOperations(text: string, isStreaming: boolean) {\n const parsed = extractFenceOperations(text);\n if (!isStreaming || parsed.partialObject === null) return parsed.operations;\n // The unfinished object is always the end of the text.\n const complete = extractFenceOperations(\n text.slice(0, text.length - parsed.partialObject.length),\n ).operations;\n const partial =\n parsed.operations.length > complete.length\n ? parsed.operations[parsed.operations.length - 1]\n : undefined;\n const canRenderPartial =\n partial !== undefined &&\n (isRecord(partial.updateComponents) || isRecord(partial.createSurface));\n return canRenderPartial ? [...complete, partial] : complete;\n}\n\n/**\n * An inline createSurface becomes a createSurface with only its surfaceId\n * and catalog, then an updateDataModel for its data model, then an\n * updateComponents for its components. The prose lift and the split per\n * component read only updateComponents, so they then work for an inline\n * surface too. A createSurface with a data model or components of a wrong\n * shape does not change, so that validation rejects it with the reason.\n */\nfunction expandInlineCreate(operations: A2UIMarkdownOperation[]) {\n return operations.flatMap((op) => {\n const create = op.createSurface;\n if (!isRecord(create)) return [op];\n const { dataModel, components, ...rest } = create;\n const hasData = isRecord(dataModel);\n const hasComponents = Array.isArray(components) && components.length > 0;\n const isWellFormed =\n (dataModel === undefined || hasData) &&\n (components === undefined || hasComponents);\n if (!isWellFormed || (!hasData && !hasComponents)) return [op];\n const { surfaceId } = create;\n const expanded: A2UIMarkdownOperation[] = [{ ...op, createSurface: rest }];\n if (hasData) {\n expanded.push({\n version: op.version,\n updateDataModel: { surfaceId, path: \"/\", value: dataModel },\n });\n }\n if (hasComponents) {\n expanded.push({\n version: op.version,\n updateComponents: { surfaceId, components },\n });\n }\n return expanded;\n });\n}\n\n/**\n * Each updateComponents becomes one operation per component, in order. The\n * complete components of a streaming line then give the same first\n * operations as the finished line, so the operation list only grows and the\n * manager never has to start the surface again.\n */\nfunction splitComponentUpdates(operations: A2UIMarkdownOperation[]) {\n return operations.flatMap((op) => {\n const update = op.updateComponents;\n if (!isRecord(update) || !Array.isArray(update.components)) return [op];\n if (update.components.length <= 1) return [op];\n return update.components.map((component) => ({\n ...op,\n updateComponents: { ...update, components: [component] },\n }));\n });\n}\n\n/** createSurface first, the other operations after it in their order. */\nfunction createSurfaceFirst(operations: A2UIMarkdownOperation[]) {\n const creates = operations.filter((op) => isRecord(op.createSurface));\n const others = operations.filter((op) => !isRecord(op.createSurface));\n return [...creates, ...others];\n}\n\n/** True when the component of `name` has the prop `prop`. */\nfunction hasProp(ui: MarkdownSourceUI, name: string, prop: string) {\n const properties = ui.manifestComponents[name]?.props.properties;\n return isRecord(properties) && Object.hasOwn(properties, prop);\n}\n\nconst childRefCache = new WeakMap<object, readonly ChildRef[]>();\n\n/** The ids in a slot value: an id, a list of ids, or a template. */\nfunction slotIds(value: unknown): string[] {\n if (typeof value === \"string\") return [value];\n if (Array.isArray(value)) return value.filter(isString);\n return isRecord(value) && isString(value.componentId)\n ? [value.componentId]\n : [];\n}\n\n/**\n * A reader of the ids a component renders beyond `child` and `children`:\n * its declared slots (the `trigger` and `content` of a Modal) and its typed\n * child references (the `child` of each entry of `tabs`), from its catalog\n * entry. The prose lift follows these ids like `children`, so a panel is\n * never cut off from its Tabs. A reference that is bound to the data\n * model is \"unknown\": its ids exist only at render time.\n */\nfunction childIdsReader(ui: MarkdownSourceUI): ChildIdsOf {\n return (component) => {\n const name = component.component;\n // An own property only: \"constructor\" is not a component.\n const entry =\n typeof name === \"string\" && Object.hasOwn(ui.manifestComponents, name)\n ? ui.manifestComponents[name]\n : undefined;\n if (!entry) return [];\n const ids: string[] = [];\n for (const slot of Object.keys(entry.slots ?? {})) {\n if (slot !== \"child\" && slot !== \"children\") {\n ids.push(...slotIds(component[slot]));\n }\n }\n let refs = childRefCache.get(entry.props);\n if (!refs) {\n refs = collectChildRefs(entry.props);\n childRefCache.set(entry.props, refs);\n }\n if (refs.length === 0) return ids;\n if (hasBoundChildRef(component, refs)) return \"unknown\";\n return [...ids, ...childIdsAtRefs(component, refs)];\n };\n}\n\n/** Every component of the operations by id, last definition wins. */\nfunction collectComponents(operations: A2UIMarkdownOperation[]) {\n const byId = new Map<string, Record<string, unknown>>();\n for (const op of operations) {\n const update = op.updateComponents;\n const list = isRecord(update) ? update.components : undefined;\n if (!Array.isArray(list)) continue;\n for (const component of list) {\n if (isRecord(component) && isString(component.id)) {\n byId.set(component.id, component);\n }\n }\n }\n return [...byId.values()];\n}\n\n/**\n * The data model must not be shared between two surfaces. A data model\n * keeps the object it gets, so an input in one surface would change the\n * data of the other one.\n */\nfunction cloneData(value: unknown) {\n return value === undefined ? undefined : structuredClone(value);\n}\n\n/** The operation sent to `surfaceId`, with a copy of its data model value. */\nfunction readdress(op: A2UIMarkdownOperation, surfaceId: string) {\n const kind = getOperationKind(op);\n const payload = kind ? op[kind] : undefined;\n if (!kind || !isRecord(payload)) return op;\n const next: Record<string, unknown> = { ...payload, surfaceId };\n if (kind === \"updateDataModel\" && \"value\" in payload) {\n next.value = cloneData(payload.value);\n }\n return { ...op, [kind]: next };\n}\n\n/**\n * The operations of one sub-surface. Each updateComponents keeps only the\n * components of the sub-surface, with its own root. The other operations\n * are sent to the sub-surface. The order stays the same, so a new operation\n * of the fence only adds operations at the end.\n */\nfunction subSurfaceOperations(\n operations: A2UIMarkdownOperation[],\n components: Record<string, unknown>[],\n surfaceId: string,\n) {\n const root = components.find((c) => c.id === GENERATIVE_UI_ROOT_ID);\n const ids = new Set(components.map((c) => c.id));\n const out: A2UIMarkdownOperation[] = [];\n for (const op of operations) {\n const update = op.updateComponents;\n if (!isRecord(update) || !Array.isArray(update.components)) {\n out.push(readdress(op, surfaceId));\n continue;\n }\n const kept = update.components\n .filter((c) => isRecord(c) && ids.has(c.id))\n .map((c) => (isRecord(c) && c.id === GENERATIVE_UI_ROOT_ID ? root : c));\n if (kept.length === 0) continue;\n out.push({\n ...op,\n updateComponents: { ...update, surfaceId, components: kept },\n });\n }\n return out;\n}\n\n/**\n * Prose lift. Text components in the main stack of the surface (titles,\n * paragraphs, text lists and the dividers between them) become chat\n * markdown. The surface splits around them: the first surface keeps\n * `surfaceId`, the next ones are `<surfaceId>#1`, `<surfaceId>#2`, and so\n * on. A surface with no prose comes back as one part with the same\n * operations.\n */\nfunction liftProse(\n operations: A2UIMarkdownOperation[],\n surfaceId: string,\n childIds: ChildIdsOf,\n) {\n const components = collectComponents(operations);\n const segments = segmentSurfaceProse(components, { childIds });\n const [first] = segments;\n const isUnchanged =\n segments.length === 1 &&\n first?.kind === \"surface\" &&\n first.components === components;\n if (isUnchanged) {\n const whole: SurfacePart[] = [{ kind: \"surface\", surfaceId, operations }];\n return whole;\n }\n let surfaceIndex = 0;\n return segments.map((segment): SurfacePart => {\n if (segment.kind === \"markdown\") return segment;\n const id = surfaceIndex === 0 ? surfaceId : `${surfaceId}#${surfaceIndex}`;\n surfaceIndex++;\n return {\n kind: \"surface\",\n surfaceId: id,\n operations: subSurfaceOperations(operations, segment.components, id),\n };\n });\n}\n\n/** `validateOperation`, with the operation typed when it is valid. */\nfunction checkOperation(\n op: A2UIMarkdownOperation,\n options: ValidateOperationOptions,\n) {\n const validation = validateOperation(op, options);\n if (!validation.ok) return validation;\n // validateOperation checked the shape of `op`.\n return { ok: true as const, operation: op as A2UIOperation };\n}\n\n/**\n * The content of one surface. Each operation is validated against the\n * manifest. A valid operation goes in `operations`. A rejected one goes in\n * `rejected`, with its position and the reason.\n */\nfunction surfaceContent(\n surfaceId: string,\n draft: SurfaceDraft,\n operations: A2UIMarkdownOperation[],\n options: BuildMarkdownSurfacesOptions,\n) {\n const { ui, functions } = options;\n const knownSurfaces = new Set<string>();\n const manifest = {\n catalogId: ui.id,\n catalogIds: catalogIdsOf(ui),\n components: ui.manifestComponents,\n };\n const valid: A2UIOperation[] = [];\n const rejected: GenerativeUIRejectedOperation[] = [];\n operations.forEach((op, index) => {\n const result = checkOperation(op, { manifest, knownSurfaces, functions });\n if (!result.ok) {\n rejected.push({ index, reason: result.reason });\n return;\n }\n valid.push(result.operation);\n const kind = getOperationKind(result.operation);\n if (kind === \"createSurface\") knownSurfaces.add(surfaceId);\n if (kind === \"deleteSurface\") knownSurfaces.delete(surfaceId);\n });\n const create = valid.find(\n (op): op is Extract<A2UIOperation, { createSurface: unknown }> =>\n \"createSurface\" in op,\n );\n const content: GenerativeUISurfaceContent = {\n surfaceId,\n target: draft.target,\n catalogId: create?.createSurface.catalogId ?? ui.id,\n operations: valid,\n status: draft.streaming ? \"streaming\" : \"ready\",\n rejected,\n };\n return content;\n}\n\n/**\n * Builds the surfaces of a thread from the ```a2ui fences of its assistant\n * messages, in message order.\n *\n * - Operations are grouped by surfaceId across all messages. An operation\n * with no surfaceId goes to the first surface of its fence, else to\n * `<messageId>-<fenceIndex>`.\n * - The fence that first writes a surface creates it. The `target=<id>` of\n * that fence sets the target. With no target, the surface goes to the\n * chat.\n * - A later fence of the same reply for the same surfaceId updates it. A\n * later reply that reuses the id of a chat surface gets a surface of its\n * own, `<id>@<messageId>`. A page target is updated from any reply.\n * - The status is \"streaming\" while the creating fence streams, else\n * \"ready\".\n * - Each operation is validated with `validateOperation`. Rejected ones are\n * left out and listed in `rejected`.\n * - Chat surfaces get the prose lift: informational cards lose their box,\n * and prose becomes markdown that renders between sub-surfaces\n * (`<surfaceId>#<n>`). An inline createSurface is split into its\n * createSurface, updateDataModel and updateComponents first.\n * - A `callRendererFunction` line is not part of a surface. It goes to\n * `functionCalls`. A streaming line gives nothing, so a function never\n * runs with a part of its args.\n *\n * The function is pure. Call it again on each stream update. The manager\n * applies only the new operations, so unchanged surfaces do not render\n * again.\n *\n * @param messages - The messages of one thread.\n * @param options - The generative UI, its declared functions, and whether\n * the last message can still grow.\n * @returns `surfaces`, one content for each surface and sub-surface;\n * `fences`, the blocks that each fence renders, by `fenceKey` (a fence\n * that is not in `fences` renders nothing); `functionCalls`, the function\n * calls of the fences in order; and `parts`, the surface ids of the parts\n * of each surface, by surface id.\n *\n * @example\n * ```ts\n * const { surfaces } = buildMarkdownSurfaces(agent.messages, {\n * ui,\n * functions: {},\n * running: agent.isRunning,\n * });\n * for (const content of surfaces) manager.ingest(threadId, agentId, content);\n * ```\n */\nexport function buildMarkdownSurfaces(\n messages: readonly Message[],\n options: BuildMarkdownSurfacesOptions,\n) {\n const { ui, cache } = options;\n const drafts = new Map<string, SurfaceDraft>();\n // The same copy for the same operation and surface, so an unchanged draft\n // holds the same objects as in the last build.\n const readdressOnce = (op: A2UIMarkdownOperation, surfaceId: string) => {\n if (!cache) return readdress(op, surfaceId);\n let copies = cache.readdressed.get(op);\n if (!copies) {\n copies = new Map();\n cache.readdressed.set(op, copies);\n }\n let copy = copies.get(surfaceId);\n if (!copy) {\n copy = readdress(op, surfaceId);\n copies.set(surfaceId, copy);\n }\n return copy;\n };\n /** The surfaces that each fence created, in order. */\n const created = new Map<string, string[]>();\n const functionCalls: MarkdownFunctionCall[] = [];\n /** The message that owns each chat surface id, by the id the model wrote. */\n const chatOwners = new Map<string, string>();\n const lastMessage = messages[messages.length - 1];\n\n /**\n * A chat surface belongs to the reply that wrote it: the chat is a\n * transcript, so a later reply that reuses an id gets a surface of its\n * own (`<id>@<messageId>`) instead of changing the earlier reply. A fence\n * for a page target keeps its id, because a target is a place on the\n * page that a later reply updates on purpose.\n */\n const scopedSurfaceId = (\n requested: string,\n messageId: string,\n target: string | undefined,\n ) => {\n if (target !== undefined) return requested;\n const owner = chatOwners.get(requested);\n if (owner === undefined) {\n chatOwners.set(requested, messageId);\n return requested;\n }\n return owner === messageId ? requested : `${requested}@${messageId}`;\n };\n\n for (const message of messages) {\n if (message.role !== \"assistant\" || !isString(message.content)) continue;\n const isLastMessage = message === lastMessage;\n const content = message.content;\n const segments = cache\n ? cache.segments.get(content, () => splitA2UIMarkdown(content))\n : splitA2UIMarkdown(content);\n for (const segment of segments) {\n if (segment.type !== \"a2ui\") continue;\n const isStreaming = !segment.closed && isLastMessage && options.running;\n const parseFence = () => {\n const parsed = fenceOperations(segment.text, isStreaming);\n // The function calls do not depend on the surface id.\n const { functionCalls } = prepareSurfaceOperations({\n operations: parsed,\n fallbackSurfaceId: \"\",\n catalogId: ui.id,\n });\n return { operations: parsed, functionCalls };\n };\n const fence = cache\n ? cache.fences.get(`${isStreaming}:${segment.text}`, parseFence)\n : parseFence();\n const { operations } = fence;\n const key = fenceKey(message.id, segment.index);\n const fenceSurfaceId =\n operations.map(getMarkdownOperationSurfaceId).find(isString) ??\n `${message.id}-${segment.index}`;\n for (const operation of fence.functionCalls) {\n functionCalls.push({\n messageId: message.id,\n fenceIndex: segment.index,\n operation,\n });\n }\n // A function call is not part of a surface. A fence with only\n // function calls makes no surface and renders nothing.\n const surfaceOperations = operations.filter(\n (op) => getOperationKind(op) !== \"callRendererFunction\",\n );\n for (const op of surfaceOperations) {\n const requested = getMarkdownOperationSurfaceId(op) ?? fenceSurfaceId;\n const surfaceId = scopedSurfaceId(\n requested,\n message.id,\n segment.target,\n );\n let draft = drafts.get(surfaceId);\n if (!draft) {\n draft = {\n surfaceId,\n target: segment.target ?? GENERATIVE_UI_CHAT_TARGET,\n operations: [],\n streaming: isStreaming,\n };\n drafts.set(surfaceId, draft);\n created.set(key, [...(created.get(key) ?? []), surfaceId]);\n }\n draft.operations.push(\n surfaceId === requested ? op : readdressOnce(op, surfaceId),\n );\n }\n }\n }\n\n // Only a Card with a `variant` prop can become a section.\n const canFlattenCards = hasProp(ui, \"Card\", \"variant\");\n const surfaces: GenerativeUISurfaceContent[] = [];\n const partsBySurface = new Map<string, SurfacePart[]>();\n const childIds = childIdsReader(ui);\n const buildDraft = (draft: SurfaceDraft): BuiltDraft => {\n const prepared = prepareSurfaceOperations({\n operations: draft.operations,\n fallbackSurfaceId: draft.surfaceId,\n catalogId: ui.id,\n catalogIds: catalogIdsOf(ui),\n });\n const operations = splitComponentUpdates(\n expandInlineCreate(createSurfaceFirst(prepared.operations)),\n );\n const isChat = draft.target === GENERATIVE_UI_CHAT_TARGET;\n const parts: SurfacePart[] = isChat\n ? liftProse(\n canFlattenCards\n ? flattenInformationalCards(operations, { childIds })\n : operations,\n draft.surfaceId,\n childIds,\n )\n : [{ kind: \"surface\", surfaceId: draft.surfaceId, operations }];\n const contents = parts.flatMap((part) =>\n part.kind === \"surface\"\n ? [surfaceContent(part.surfaceId, draft, part.operations, options)]\n : [],\n );\n return { ...draft, parts, contents };\n };\n for (const draft of drafts.values()) {\n // A draft with the same operations, target and status as in the last\n // build gives the same surfaces, so they are not built again.\n const built = cache\n ? cache.drafts.get(\n draft.surfaceId,\n () => buildDraft(draft),\n (last) =>\n last.target === draft.target &&\n last.streaming === draft.streaming &&\n sameItems(last.operations, draft.operations),\n )\n : buildDraft(draft);\n partsBySurface.set(draft.surfaceId, built.parts);\n surfaces.push(...built.contents);\n }\n cache?.endBuild();\n\n /** The surface ids of the parts of each split surface, by surface id. */\n const parts = new Map<string, string[]>();\n for (const [surfaceId, surfaceParts] of partsBySurface) {\n const ids = surfaceParts.flatMap((part) =>\n part.kind === \"surface\" ? [part.surfaceId] : [],\n );\n parts.set(surfaceId, ids);\n }\n\n const fences = new Map<string, MarkdownFenceBlock[]>();\n for (const [key, surfaceIds] of created) {\n const blocks: MarkdownFenceBlock[] = [];\n for (const surfaceId of surfaceIds) {\n if (drafts.get(surfaceId)?.target !== GENERATIVE_UI_CHAT_TARGET) continue;\n for (const part of partsBySurface.get(surfaceId) ?? []) {\n blocks.push(\n part.kind === \"markdown\"\n ? part\n : { kind: \"surface\", surfaceId: part.surfaceId },\n );\n }\n }\n if (blocks.length > 0) fences.set(key, blocks);\n }\n\n return { surfaces, fences, functionCalls, parts };\n}\n\n/** The declared functions, as `validateOperation` takes them. */\nfunction declaredFunctions(ui: GenerativeUI) {\n const functions: Record<string, GenerativeUIFunctionManifest> = {};\n for (const [name, fn] of ui.functions) {\n try {\n functions[name] = {\n ...(fn.description ? { description: fn.description } : {}),\n parameters: toJsonSchema(fn.parameters),\n };\n } catch {\n // A schema that cannot become JSON Schema still names a function.\n functions[name] = { parameters: {} };\n }\n }\n return functions;\n}\n\n/** True when `list` starts with all the items of `prefix`. */\nfunction startsWith(list: string[], prefix: string[]) {\n return (\n list.length >= prefix.length &&\n prefix.every((item, index) => item === list[index])\n );\n}\n\n/** A content that deletes a surface that the fences no longer write. */\nfunction removalContent(surfaceId: string, catalogId: string) {\n const content: GenerativeUISurfaceContent = {\n surfaceId,\n target: GENERATIVE_UI_CHAT_TARGET,\n catalogId,\n status: \"ready\",\n rejected: [],\n operations: [\n { version: A2UI_VERSION, createSurface: { surfaceId, catalogId } },\n { version: A2UI_VERSION, deleteSurface: { surfaceId } },\n ],\n };\n return content;\n}\n\n/**\n * The markdown transport source of one surface manager. It turns the\n * messages of a thread into surfaces in the manager, and keeps the blocks\n * that each fence renders.\n */\nexport class MarkdownSurfaceSource {\n private readonly functions: Record<string, GenerativeUIFunctionManifest>;\n /** By thread: the blocks of each fence, from the latest sync. */\n private readonly fences = new Map<\n string,\n Map<string, MarkdownFenceBlock[]>\n >();\n /** By thread, then surface: the operations last ingested, as JSON. */\n private readonly ingested = new Map<string, Map<string, string[]>>();\n /** By thread, then surface: the content last ingested. */\n private readonly contents = new Map<\n string,\n Map<string, GenerativeUISurfaceContent>\n >();\n /** By thread: the results of the earlier builds. */\n private readonly caches = new Map<string, MarkdownBuildCache>();\n\n constructor(\n private readonly manager: GenerativeUISurfaceManager,\n private readonly ui: GenerativeUI,\n ) {\n this.functions = declaredFunctions(ui);\n }\n\n /**\n * Builds the surfaces of `threadId` from `messages` and gives them to the\n * manager. A surface that an earlier sync of the thread made, and that the\n * messages no longer write, is deleted. Other threads do not change.\n *\n * @param threadId - The thread of the messages.\n * @param agentId - The agent that owns the thread.\n * @param messages - All messages of the thread.\n * @param options - `running`: the last message can still grow.\n * @returns The function calls of the fences, in order. The source does\n * not run them.\n */\n sync(\n threadId: string,\n agentId: string | undefined,\n messages: readonly Message[],\n options: { running: boolean },\n ) {\n let cache = this.caches.get(threadId);\n if (!cache) {\n cache = new MarkdownBuildCache();\n this.caches.set(threadId, cache);\n }\n const result = buildMarkdownSurfaces(messages, {\n ui: this.ui,\n functions: this.functions,\n running: options.running,\n cache,\n });\n this.fences.set(threadId, result.fences);\n // The parts of a split surface share one data model, so an input in one\n // part drives a binding in another.\n for (const parts of result.parts.values()) {\n this.manager.linkSurfaces(threadId, parts);\n }\n const previous = this.ingested.get(threadId) ?? new Map<string, string[]>();\n const previousContents =\n this.contents.get(threadId) ??\n new Map<string, GenerativeUISurfaceContent>();\n const next = new Map<string, string[]>();\n const nextContents = new Map<string, GenerativeUISurfaceContent>();\n for (const content of result.surfaces) {\n nextContents.set(content.surfaceId, content);\n const before = previous.get(content.surfaceId);\n // The cache gives the same content object for a surface that did not\n // change, and the manager already has it.\n if (before && previousContents.get(content.surfaceId) === content) {\n next.set(content.surfaceId, before);\n continue;\n }\n const fingerprints = content.operations.map((op) => JSON.stringify(op));\n // The manager checks only the last operation that it applied. When an\n // earlier one changed (for example, the prose lift moved a split), an\n // empty content makes it start the surface again.\n if (before && !startsWith(fingerprints, before)) {\n this.manager.ingest(threadId, agentId, { ...content, operations: [] });\n }\n this.manager.ingest(threadId, agentId, content);\n next.set(content.surfaceId, fingerprints);\n }\n for (const surfaceId of previous.keys()) {\n if (next.has(surfaceId)) continue;\n this.manager.ingest(\n threadId,\n agentId,\n removalContent(surfaceId, this.ui.id),\n );\n }\n this.ingested.set(threadId, next);\n this.contents.set(threadId, nextContents);\n return result.functionCalls;\n }\n\n /**\n * The blocks that a fence renders in the chat, from the latest sync of the\n * thread. `undefined` when the fence renders nothing: it updates a surface\n * of an earlier fence, its surface is for a named target, or it has no\n * complete operation yet.\n */\n getFenceBlocks(threadId: string, messageId: string, fenceIndex: number) {\n return this.fences.get(threadId)?.get(fenceKey(messageId, fenceIndex));\n }\n}\n\nconst sources = new WeakMap<\n GenerativeUISurfaceManager,\n MarkdownSurfaceSource\n>();\n\n/**\n * The markdown source of a generative UI runtime. There is one source for\n * each surface manager. The root syncs it, and the chat messages read the\n * fence blocks from it.\n */\nexport function getMarkdownSurfaceSource(runtime: {\n manager: GenerativeUISurfaceManager;\n ui: GenerativeUI;\n}) {\n let source = sources.get(runtime.manager);\n if (!source) {\n source = new MarkdownSurfaceSource(runtime.manager, runtime.ui);\n sources.set(runtime.manager, source);\n }\n return source;\n}\n","import { A2UI_VERSION } from \"@copilotkit/shared\";\nimport type {\n A2UIComponentNode,\n A2UIOperation,\n GenerativeUIUserEvent,\n} from \"@copilotkit/shared\";\nimport type { ManagedSurface } from \"./surface-manager\";\n\n/** Context keys that supply the message's first line, in priority order. */\nconst TEXT_KEYS: readonly string[] = [\"message\", \"label\"];\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\n/** `choose_plan`, `choose-plan` and `choosePlan` all become \"Choose plan\". */\nfunction humanize(name: string) {\n const spaced = name\n .replace(/[_-]+/g, \" \")\n .replace(/([a-z])([A-Z])/g, \"$1 $2\")\n .trim();\n return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();\n}\n\nfunction formatContextValue(value: unknown) {\n return typeof value === \"object\" ? JSON.stringify(value) : String(value);\n}\n\n/**\n * Turns a user event that no function handles into the text of a visible\n * user message.\n *\n * The first line is, in order: `userMessage`, `context.message`,\n * `context.label`, the label of the source component (from `resolveLabel`),\n * or the event name made readable (`choose_plan` becomes \"Choose plan\").\n * Each other context field follows as one `key: value` line. Objects are\n * written as JSON. `null` and `undefined` fields are skipped.\n *\n * @param event - The user event, as sent by a surface.\n * @param resolveLabel - Finds the visible label of a component by id. Build\n * one with {@link createComponentLabelResolver}.\n *\n * @example\n * ```ts\n * buildActionMessageText({\n * name: \"choose_plan\",\n * surfaceId: \"plans\",\n * componentId: \"team-button\",\n * userMessage: \"I pick the Team plan\",\n * context: { seats: 12 },\n * });\n * // \"I pick the Team plan\\n\\nseats: 12\"\n * ```\n */\nexport function buildActionMessageText(\n event: GenerativeUIUserEvent,\n resolveLabel?: (componentId: string) => string | undefined,\n) {\n const { context, userMessage } = event;\n const candidates = [userMessage, ...TEXT_KEYS.map((key) => context[key])];\n const explicit = candidates.find(isNonEmptyString);\n const resolved = explicit ? undefined : resolveLabel?.(event.componentId);\n const head =\n explicit ??\n (isNonEmptyString(resolved) ? resolved.trim() : humanize(event.name));\n\n const fields = Object.entries(context);\n const lines = fields\n .filter(\n ([key, value]) =>\n !TEXT_KEYS.includes(key) && value !== undefined && value !== null,\n )\n .map(([key, value]) => `${key}: ${formatContextValue(value)}`);\n\n return lines.length > 0 ? `${head}\\n\\n${lines.join(\"\\n\")}` : head;\n}\n\nfunction ownText(component: A2UIComponentNode | undefined) {\n if (!component) return undefined;\n if (isNonEmptyString(component.label)) return component.label;\n if (isNonEmptyString(component.text)) return component.text;\n return undefined;\n}\n\nfunction childIds(component: A2UIComponentNode) {\n const { child, children } = component;\n const single = typeof child === \"string\" ? [child] : [];\n const multiple = Array.isArray(children)\n ? children.filter((id): id is string => typeof id === \"string\")\n : [];\n return [...single, ...multiple];\n}\n\n/** The components that an operation adds, inline or in an update. */\nfunction componentsOf(operation: A2UIOperation) {\n if (\"createSurface\" in operation) {\n return operation.createSurface.components ?? [];\n }\n if (\"updateComponents\" in operation) {\n return operation.updateComponents.components;\n }\n return [];\n}\n\n/**\n * Builds a function that finds the visible label of a component on a surface.\n *\n * The label is the component's own string `label`, else its string `text`,\n * else the first `child` or `children` component that has a string `label`\n * or `text`. When a component id is defined more than once, the last\n * definition wins, as in the renderer.\n *\n * @param operations - The committed operations of the surface.\n *\n * @example\n * ```ts\n * const resolveLabel = createComponentLabelResolver(surface.operations);\n * buildActionMessageText(event, resolveLabel);\n * ```\n */\nexport function createComponentLabelResolver(\n operations: readonly A2UIOperation[],\n) {\n const byId = new Map<string, A2UIComponentNode>();\n for (const operation of operations) {\n const components = componentsOf(operation);\n for (const component of components) {\n byId.set(component.id, component);\n }\n }\n\n return (componentId: string) => {\n const component = byId.get(componentId);\n if (!component) return undefined;\n const own = ownText(component);\n if (own) return own;\n const ids = childIds(component);\n for (const id of ids) {\n const text = ownText(byId.get(id));\n if (text) return text;\n }\n return undefined;\n };\n}\n\n/**\n * The label resolver of a rendered surface: the components the surface has\n * now, as one `updateComponents` operation, so that the label of the\n * component that sent an event can be found.\n */\nexport function surfaceLabelResolver(surface: ManagedSurface) {\n const entries = [...surface.model.componentsModel.entries];\n const components = entries.map(([id, model]) => ({\n ...model.properties,\n id,\n component: model.type,\n }));\n return createComponentLabelResolver([\n {\n version: A2UI_VERSION,\n updateComponents: { surfaceId: surface.surfaceId, components },\n },\n ]);\n}\n","import {\n buildGenerativeUIMarkdownGuidelines,\n buildGenerativeUIPrompt,\n envelopeToManifest,\n generativeUIGuideFeatures,\n defaultGenerativeUIPromptSpec,\n renderGenerativeUISchema,\n} from \"@copilotkit/shared\";\nimport type {\n ɵGenerativeUIDebugFunction,\n ɵGenerativeUIDebugRun,\n ɵGenerativeUIDebugSnapshot,\n ɵGenerativeUIDebugSource,\n} from \"../core/generative-ui-debug\";\nimport { componentCatalogIds } from \"@copilotkit/shared/generative-ui\";\nimport { toJsonSchema } from \"@copilotkit/shared/generative-ui\";\nimport {\n buildGenerativeUIEnvelope,\n buildGenerativeUIManifest,\n} from \"./manifest\";\nimport type { GenerativeUIEnvelopeOptions } from \"./manifest\";\nimport type { GenerativeUIEngine } from \"./runtime\";\n\ntype RuntimeParts = Pick<GenerativeUIEngine, \"ui\" | \"manager\" | \"dispatcher\">;\n\n/**\n * What a run of `threadId` sends: its envelope, and the text that goes into\n * the prompt of the model because of it.\n *\n * - Tool transport: the runtime adds the `render_ui` guide. It builds it\n * from the envelope with `buildGenerativeUIPrompt`, as done here.\n * - Markdown transport: the provider sends the guideline and the compact\n * schema as context entries. With `sendContext: false`, the backend builds\n * its own prompt, usually from the `instructions` of the envelope.\n */\n// ponytail: the prompt text is built at every run start, also with no\n// inspector open. It costs about what the runtime pays for the same text.\n// Make it lazy if a profile shows it.\nexport function describeGenerativeUIRun(\n runtime: RuntimeParts,\n threadId: string | undefined,\n options: GenerativeUIEnvelopeOptions,\n): Pick<ɵGenerativeUIDebugRun, \"envelope\" | \"prompt\"> {\n const envelope = buildGenerativeUIEnvelope(runtime, threadId, options);\n if (options.transport === \"tool\") {\n const text = buildGenerativeUIPrompt(envelopeToManifest(envelope));\n return {\n envelope,\n prompt: [{ title: \"render_ui guide\", source: \"runtime\", text }],\n };\n }\n const manifest = buildGenerativeUIManifest(runtime, threadId);\n if (!options.contextSent) {\n const instructions = envelopeToManifest(envelope).instructions ?? \"\";\n return {\n envelope,\n prompt: [\n {\n title: \"Envelope instructions\",\n source: \"backend\",\n text: instructions,\n },\n ],\n };\n }\n const guideline = buildGenerativeUIMarkdownGuidelines(\n generativeUIGuideFeatures(manifest),\n );\n const schema = renderGenerativeUISchema(\n manifest,\n defaultGenerativeUIPromptSpec().schema.markdown,\n );\n return {\n envelope,\n prompt: [\n { title: \"Markdown guideline\", source: \"context\", text: guideline },\n { title: \"Component schema\", source: \"context\", text: schema },\n ],\n };\n}\n\n/** The declared functions, with the JSON Schema of their parameters. */\nfunction debugFunctions(runtime: RuntimeParts) {\n const functions: Record<string, ɵGenerativeUIDebugFunction> = {};\n for (const [name, declared] of runtime.ui.functions) {\n let parameters = {};\n try {\n parameters = toJsonSchema(declared.parameters);\n } catch {\n // A schema with no JSON Schema form shows as empty.\n }\n functions[name] = {\n ...(declared.description ? { description: declared.description } : {}),\n parameters,\n handlers: runtime.dispatcher.handlerCount(name),\n };\n }\n return functions;\n}\n\n/**\n * The debug source that the provider gives core for the inspector. It builds\n * a snapshot only when the inspector reads one.\n *\n * @param runtime - The generative UI parts of the provider.\n * @param getOptions - The envelope options and agent ids of the current config.\n * @returns The source, and `recordRun` for each run start.\n */\nexport function createGenerativeUIDebugSource(\n runtime: RuntimeParts,\n getOptions: () => {\n options: GenerativeUIEnvelopeOptions;\n agentIds: string[] | undefined;\n },\n) {\n const listeners = new Set<() => void>();\n let lastRun: ɵGenerativeUIDebugRun | undefined;\n const notify = () => {\n for (const listener of [...listeners]) listener();\n };\n\n const source: ɵGenerativeUIDebugSource = {\n getSnapshot(): ɵGenerativeUIDebugSnapshot {\n const { options, agentIds } = getOptions();\n const threadId = runtime.manager.getActiveThread();\n const manifest = buildGenerativeUIManifest(runtime, threadId);\n return {\n catalogId: runtime.ui.id,\n transport: options.transport,\n ...(agentIds ? { agentIds } : {}),\n components: runtime.ui.manifestComponents,\n componentCatalogs: Object.fromEntries(componentCatalogIds(runtime.ui)),\n functions: debugFunctions(runtime),\n state: { ...runtime.manager.getState() },\n targets: manifest.targets,\n activeThreadId: threadId,\n surfaces: runtime.manager.debugSurfaces(),\n lastRun,\n nextRun: {\n agentId: undefined,\n threadId,\n ...describeGenerativeUIRun(runtime, threadId, options),\n },\n };\n },\n subscribe(listener) {\n listeners.add(listener);\n const unsubscribe = runtime.manager.subscribe(listener);\n return () => {\n listeners.delete(listener);\n unsubscribe();\n };\n },\n };\n\n return {\n source,\n /** Keeps what a run sent, so the inspector can show it. */\n recordRun(run: ɵGenerativeUIDebugRun) {\n lastRun = run;\n notify();\n },\n };\n}\n","/**\n * The `accessibility` of the A2UI 1.0 component envelope, with its dynamic\n * values resolved. Every component may carry it next to `id` and\n * `component`; it is not a prop of the component.\n */\nexport interface GenerativeUIAccessibility {\n /** A short name for assistive technologies, 1 to 3 words. */\n label?: string;\n /** Instructions, format requirements, or what an action does. */\n description?: string;\n /** How screen readers announce changes (WAI-ARIA `aria-live`). */\n live?: \"off\" | \"polite\" | \"assertive\";\n /** True hides the component and its children from assistive technologies. */\n hidden?: boolean;\n}\n\n/** The ARIA attributes of a resolved `accessibility`, ready to spread. */\nexport interface GenerativeUIAriaAttributes {\n \"aria-label\"?: string;\n \"aria-description\"?: string;\n \"aria-live\"?: \"off\" | \"polite\" | \"assertive\";\n \"aria-hidden\"?: true;\n}\n\nconst LIVE = new Set([\"off\", \"polite\", \"assertive\"]);\n\n/**\n * The accessibility of a component from its resolved `accessibility`\n * value. Fields of the wrong type are left out: a label that is still a\n * binding, or a list, names nothing.\n */\nexport function readAccessibility(\n value: unknown,\n): GenerativeUIAccessibility | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n const { label, description, live, hidden } = value as Record<string, unknown>;\n const result: GenerativeUIAccessibility = {};\n if (typeof label === \"string\" && label !== \"\") result.label = label;\n if (typeof description === \"string\" && description !== \"\") {\n result.description = description;\n }\n if (typeof live === \"string\" && LIVE.has(live)) {\n result.live = live as GenerativeUIAccessibility[\"live\"];\n }\n if (typeof hidden === \"boolean\") result.hidden = hidden;\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\n/**\n * The ARIA attributes for an `accessibility`. `live: \"off\"` is written out:\n * a region inherits the live setting of its ancestors, and a `status` role\n * is live on its own, so only the explicit value silences it.\n *\n * @example\n * ```ts\n * accessibilityAttributes({ label: \"Totals\", live: \"polite\" });\n * // { \"aria-label\": \"Totals\", \"aria-live\": \"polite\" }\n * ```\n */\nexport function accessibilityAttributes(\n accessibility: GenerativeUIAccessibility | undefined,\n): GenerativeUIAriaAttributes {\n if (!accessibility) return {};\n const { label, description, live, hidden } = accessibility;\n return {\n ...(label === undefined ? {} : { \"aria-label\": label }),\n ...(description === undefined ? {} : { \"aria-description\": description }),\n ...(live === undefined ? {} : { \"aria-live\": live }),\n ...(hidden ? { \"aria-hidden\": true as const } : {}),\n };\n}\n\n/**\n * The role of a container that the envelope names. A generic element\n * cannot carry a name, so a label or a description makes it a `group`,\n * unless the component has a role of its own.\n */\nexport function namedRole(\n aria: GenerativeUIAriaAttributes,\n explicit: string | undefined,\n): string | undefined {\n if (explicit !== undefined) return explicit;\n const isNamed =\n aria[\"aria-label\"] !== undefined || aria[\"aria-description\"] !== undefined;\n return isNamed ? \"group\" : undefined;\n}\n\n/**\n * The part of the attributes for the focusable control of a labelled pair:\n * its name and its description. ARIA names are not inherited, so the\n * wrapper of a control cannot name it.\n */\nexport function controlAria(\n aria: GenerativeUIAriaAttributes,\n): Pick<GenerativeUIAriaAttributes, \"aria-label\" | \"aria-description\"> {\n const { \"aria-label\": label, \"aria-description\": description } = aria;\n return {\n ...(label === undefined ? {} : { \"aria-label\": label }),\n ...(description === undefined ? {} : { \"aria-description\": description }),\n };\n}\n\n/**\n * The part of the attributes for the wrapper around a control: hidden and\n * live cover the label and the control together.\n */\nexport function wrapperAria(\n aria: GenerativeUIAriaAttributes,\n): Pick<GenerativeUIAriaAttributes, \"aria-hidden\" | \"aria-live\"> {\n const { \"aria-hidden\": hidden, \"aria-live\": live } = aria;\n return {\n ...(hidden === undefined ? {} : { \"aria-hidden\": hidden }),\n ...(live === undefined ? {} : { \"aria-live\": live }),\n };\n}\n","import { GENERATIVE_UI_MAX_TARGET_COMPONENTS } from \"@copilotkit/shared\";\nimport type { GenerativeUI } from \"@copilotkit/shared/generative-ui\";\n\n/** Scrolls `element` into view, unless it is already fully on screen. */\nexport function scrollToSurface(element: HTMLElement) {\n const { top, bottom } = element.getBoundingClientRect();\n if (top >= 0 && bottom <= window.innerHeight) return;\n const reduceMotion = window.matchMedia?.(\n \"(prefers-reduced-motion: reduce)\",\n ).matches;\n // jsdom has no scrollIntoView.\n element.scrollIntoView?.({\n behavior: reduceMotion ? \"auto\" : \"smooth\",\n block: \"start\",\n });\n}\n\n/**\n * The names of `requested` that `ui` has, without repeats, at most the\n * number that the envelope takes. `warning` tells what was dropped.\n */\nexport function allowedComponents(\n requested: readonly string[],\n ui: GenerativeUI,\n) {\n const unique = [...new Set(requested)];\n const unknown = unique.filter((name) => !ui.components.has(name));\n const known = unique.filter((name) => ui.components.has(name));\n const names = known.slice(0, GENERATIVE_UI_MAX_TARGET_COMPONENTS);\n const problems: string[] = [];\n if (unknown.length > 0) {\n problems.push(\n `these components are not in the UI and are ignored: ${unknown.join(\", \")}`,\n );\n }\n if (known.length > names.length) {\n problems.push(\n `only the first ${GENERATIVE_UI_MAX_TARGET_COMPONENTS} components are used`,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