@copilotkit/shared 1.80.0 → 1.81.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/a2ui-envelope.cjs +154 -0
- package/dist/a2ui-envelope.cjs.map +1 -0
- package/dist/a2ui-envelope.d.cts +101 -0
- package/dist/a2ui-envelope.d.cts.map +1 -0
- package/dist/a2ui-envelope.d.mts +101 -0
- package/dist/a2ui-envelope.d.mts.map +1 -0
- package/dist/a2ui-envelope.mjs +151 -0
- package/dist/a2ui-envelope.mjs.map +1 -0
- package/dist/a2ui-prompts.cjs +139 -0
- package/dist/a2ui-prompts.cjs.map +1 -1
- package/dist/a2ui-prompts.d.cts +60 -1
- package/dist/a2ui-prompts.d.cts.map +1 -1
- package/dist/a2ui-prompts.d.mts +60 -1
- package/dist/a2ui-prompts.d.mts.map +1 -1
- package/dist/a2ui-prompts.mjs +134 -1
- package/dist/a2ui-prompts.mjs.map +1 -1
- package/dist/generative-ui/basic-functions.cjs +177 -0
- package/dist/generative-ui/basic-functions.cjs.map +1 -0
- package/dist/generative-ui/basic-functions.d.cts +108 -0
- package/dist/generative-ui/basic-functions.d.cts.map +1 -0
- package/dist/generative-ui/basic-functions.d.mts +108 -0
- package/dist/generative-ui/basic-functions.d.mts.map +1 -0
- package/dist/generative-ui/basic-functions.mjs +167 -0
- package/dist/generative-ui/basic-functions.mjs.map +1 -0
- package/dist/generative-ui/child-refs.cjs +161 -0
- package/dist/generative-ui/child-refs.cjs.map +1 -0
- package/dist/generative-ui/child-refs.d.cts +68 -0
- package/dist/generative-ui/child-refs.d.cts.map +1 -0
- package/dist/generative-ui/child-refs.d.mts +68 -0
- package/dist/generative-ui/child-refs.d.mts.map +1 -0
- package/dist/generative-ui/child-refs.mjs +152 -0
- package/dist/generative-ui/child-refs.mjs.map +1 -0
- package/dist/generative-ui/is-record.cjs +10 -0
- package/dist/generative-ui/is-record.cjs.map +1 -0
- package/dist/generative-ui/is-record.mjs +9 -0
- package/dist/generative-ui/is-record.mjs.map +1 -0
- package/dist/generative-ui/prompt.cjs +91 -0
- package/dist/generative-ui/prompt.cjs.map +1 -0
- package/dist/generative-ui/prompt.d.cts +13 -0
- package/dist/generative-ui/prompt.d.cts.map +1 -0
- package/dist/generative-ui/prompt.d.mts +13 -0
- package/dist/generative-ui/prompt.d.mts.map +1 -0
- package/dist/generative-ui/prompt.mjs +90 -0
- package/dist/generative-ui/prompt.mjs.map +1 -0
- package/dist/generative-ui/render-ui-args.cjs +160 -0
- package/dist/generative-ui/render-ui-args.cjs.map +1 -0
- package/dist/generative-ui/render-ui-args.d.cts +40 -0
- package/dist/generative-ui/render-ui-args.d.cts.map +1 -0
- package/dist/generative-ui/render-ui-args.d.mts +40 -0
- package/dist/generative-ui/render-ui-args.d.mts.map +1 -0
- package/dist/generative-ui/render-ui-args.mjs +159 -0
- package/dist/generative-ui/render-ui-args.mjs.map +1 -0
- package/dist/generative-ui/types.cjs +101 -0
- package/dist/generative-ui/types.cjs.map +1 -0
- package/dist/generative-ui/types.d.cts +270 -0
- package/dist/generative-ui/types.d.cts.map +1 -0
- package/dist/generative-ui/types.d.mts +270 -0
- package/dist/generative-ui/types.d.mts.map +1 -0
- package/dist/generative-ui/types.mjs +86 -0
- package/dist/generative-ui/types.mjs.map +1 -0
- package/dist/generative-ui/validate-operation.cjs +405 -0
- package/dist/generative-ui/validate-operation.cjs.map +1 -0
- package/dist/generative-ui/validate-operation.d.cts +86 -0
- package/dist/generative-ui/validate-operation.d.cts.map +1 -0
- package/dist/generative-ui/validate-operation.d.mts +86 -0
- package/dist/generative-ui/validate-operation.d.mts.map +1 -0
- package/dist/generative-ui/validate-operation.mjs +399 -0
- package/dist/generative-ui/validate-operation.mjs.map +1 -0
- package/dist/index.cjs +63 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +9 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +9 -2
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +1421 -20
- package/dist/index.umd.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.mjs +1 -1
- package/dist/utils/dashboard-url.cjs +19 -0
- package/dist/utils/dashboard-url.cjs.map +1 -0
- package/dist/utils/dashboard-url.mjs +18 -0
- package/dist/utils/dashboard-url.mjs.map +1 -0
- package/dist/utils/index.cjs +2 -1
- package/dist/utils/index.cjs.map +1 -1
- package/dist/utils/index.d.cts.map +1 -1
- package/dist/utils/index.d.mts.map +1 -1
- package/dist/utils/index.mjs +2 -1
- package/dist/utils/index.mjs.map +1 -1
- package/dist/utils/inspector-learning.cjs +10 -7
- package/dist/utils/inspector-learning.cjs.map +1 -1
- package/dist/utils/inspector-learning.d.cts.map +1 -1
- package/dist/utils/inspector-learning.d.mts.map +1 -1
- package/dist/utils/inspector-learning.mjs +11 -7
- package/dist/utils/inspector-learning.mjs.map +1 -1
- package/dist/utils/inspector-metadata.cjs +2 -3
- package/dist/utils/inspector-metadata.cjs.map +1 -1
- package/dist/utils/inspector-metadata.d.cts.map +1 -1
- package/dist/utils/inspector-metadata.d.mts.map +1 -1
- package/dist/utils/inspector-metadata.mjs +3 -3
- package/dist/utils/inspector-metadata.mjs.map +1 -1
- package/package.json +1 -1
- package/src/__tests__/a2ui-envelope.test.ts +434 -0
- package/src/__tests__/a2ui-prompts.test.ts +362 -0
- package/src/a2ui-envelope.ts +309 -0
- package/src/a2ui-prompts.ts +207 -0
- package/src/generative-ui/__tests__/render-ui-args.test.ts +175 -0
- package/src/generative-ui/__tests__/validate-operation.test.ts +977 -0
- package/src/generative-ui/basic-functions.ts +282 -0
- package/src/generative-ui/child-refs.ts +210 -0
- package/src/generative-ui/index.ts +6 -0
- package/src/generative-ui/is-record.ts +4 -0
- package/src/generative-ui/prompt.ts +174 -0
- package/src/generative-ui/render-ui-args.ts +199 -0
- package/src/generative-ui/types.ts +314 -0
- package/src/generative-ui/validate-operation.ts +723 -0
- package/src/index.ts +15 -0
- package/src/utils/dashboard-url.ts +17 -0
- package/src/utils/index.ts +7 -1
- package/src/utils/inspector-learning.test.ts +58 -0
- package/src/utils/inspector-learning.ts +26 -5
- package/src/utils/inspector-metadata.test.ts +2 -1
- package/src/utils/inspector-metadata.ts +3 -13
- package/src/utils.test.ts +71 -0
package/dist/index.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.umd.js","names":["GraphQLError","z","uuid","PartialJSON","EventType","packageJson.version"],"sources":["../src/utils/clipboard.ts","../src/utils/conditions.ts","../src/utils/console-styling.ts","../src/utils/errors.ts","../src/utils/json-schema.ts","../src/utils/inspector-metadata.ts","../src/utils/inspector-learning.ts","../src/utils/inspector-visibility.ts","../src/utils/types.ts","../src/utils/random-id.ts","../src/utils/requests.ts","../src/utils/row-render-keys.ts","../src/utils/index.ts","../src/constants/index.ts","../src/telemetry/telemetry-disabled.ts","../src/telemetry/sampling.ts","../src/telemetry/model-host.ts","../src/telemetry/lambda-client.ts","../src/debug.ts","../src/standard-schema.ts","../src/attachments/content.ts","../src/attachments/utils.ts","../src/logger.ts","../src/finalize-events.ts","../src/intelligence-routing-fields.ts","../src/transcription-errors.ts","../package.json","../src/a2ui-prompts.ts","../src/open-generative-ui-prompts.ts","../src/index.ts"],"sourcesContent":["/**\n * Safely copies text to the clipboard.\n *\n * Checks that the Clipboard API is available before attempting the write,\n * and catches any errors (e.g. permission denied, insecure context).\n *\n * @param text - The text to copy to the clipboard.\n * @returns `true` if the text was successfully copied, `false` otherwise.\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n if (!navigator.clipboard?.writeText) {\n console.error(\"Clipboard API is not available\");\n return false;\n }\n\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch (err) {\n console.error(\"Failed to copy to clipboard:\", err);\n return false;\n }\n}\n","export type ComparisonRule =\n | \"EQUALS\"\n | \"NOT_EQUALS\"\n | \"GREATER_THAN\"\n | \"LESS_THAN\"\n | \"CONTAINS\"\n | \"NOT_CONTAINS\"\n | \"MATCHES\"\n | \"STARTS_WITH\"\n | \"ENDS_WITH\";\nexport type LogicalRule = \"AND\" | \"OR\" | \"NOT\";\nexport type ExistenceRule = \"EXISTS\" | \"NOT_EXISTS\";\n\nexport type Rule = ComparisonRule | LogicalRule | ExistenceRule;\n\nexport interface BaseCondition {\n rule: Rule;\n path?: string;\n}\n\nexport interface ComparisonCondition extends BaseCondition {\n rule: ComparisonRule;\n value: any;\n}\n\nexport interface LogicalCondition extends BaseCondition {\n rule: LogicalRule;\n conditions: Condition[];\n}\n\nexport interface ExistenceCondition extends BaseCondition {\n rule: ExistenceRule;\n}\n\nexport type Condition =\n | ComparisonCondition\n | LogicalCondition\n | ExistenceCondition;\n\nexport function executeConditions({\n conditions,\n value,\n}: {\n conditions?: Condition[];\n value: any;\n}): boolean {\n // If no conditions, consider it a pass\n if (!conditions?.length) return true;\n\n // Run all conditions (implicit AND)\n return conditions.every((condition) => executeCondition(condition, value));\n}\n\nfunction executeCondition(condition: Condition, value: any): boolean {\n const targetValue = condition.path\n ? getValueFromPath(value, condition.path)\n : value;\n\n switch (condition.rule) {\n // Logical\n case \"AND\":\n return (condition as LogicalCondition).conditions.every((c) =>\n executeCondition(c, value),\n );\n case \"OR\":\n return (condition as LogicalCondition).conditions.some((c) =>\n executeCondition(c, value),\n );\n case \"NOT\":\n return !(condition as LogicalCondition).conditions.every((c) =>\n executeCondition(c, value),\n );\n\n // Comparison\n case \"EQUALS\":\n return targetValue === (condition as ComparisonCondition).value;\n case \"NOT_EQUALS\":\n return targetValue !== (condition as ComparisonCondition).value;\n case \"GREATER_THAN\":\n return targetValue > (condition as ComparisonCondition).value;\n case \"LESS_THAN\":\n return targetValue < (condition as ComparisonCondition).value;\n case \"CONTAINS\":\n return (\n Array.isArray(targetValue) &&\n targetValue.includes((condition as ComparisonCondition).value)\n );\n case \"NOT_CONTAINS\":\n return (\n Array.isArray(targetValue) &&\n !targetValue.includes((condition as ComparisonCondition).value)\n );\n case \"MATCHES\":\n return new RegExp((condition as ComparisonCondition).value).test(\n String(targetValue),\n );\n case \"STARTS_WITH\":\n return String(targetValue).startsWith(\n (condition as ComparisonCondition).value,\n );\n case \"ENDS_WITH\":\n return String(targetValue).endsWith(\n (condition as ComparisonCondition).value,\n );\n\n // Existence\n case \"EXISTS\":\n return targetValue !== undefined && targetValue !== null;\n case \"NOT_EXISTS\":\n return targetValue === undefined || targetValue === null;\n }\n}\n\nfunction getValueFromPath(obj: any, path: string): any {\n return path.split(\".\").reduce((acc, part) => acc?.[part], obj);\n}\n","/**\n * Console styling utilities for CopilotKit branded messages\n * Provides consistent, readable colors across light and dark console themes\n */\n\n/**\n * Color palette optimized for console readability\n */\nexport const ConsoleColors = {\n /** Primary brand blue - for titles and links */\n primary: \"#007acc\",\n /** Success green - for positive messaging */\n success: \"#22c55e\",\n /** Purple - for feature highlights */\n feature: \"#a855f7\",\n /** Red - for calls-to-action */\n cta: \"#ef4444\",\n /** Cyan - for closing statements */\n info: \"#06b6d4\",\n /** Inherit console default - for body text */\n inherit: \"inherit\",\n /** Warning style */\n warning: \"#f59e0b\",\n} as const;\n\n/**\n * Console style templates for common patterns\n */\nexport const ConsoleStyles = {\n /** Large header style */\n header: `color: ${ConsoleColors.warning}; font-weight: bold; font-size: 16px;`,\n /** Section header style */\n section: `color: ${ConsoleColors.success}; font-weight: bold;`,\n /** Feature highlight style */\n highlight: `color: ${ConsoleColors.feature}; font-weight: bold;`,\n /** Call-to-action style */\n cta: `color: ${ConsoleColors.success}; font-weight: bold;`,\n /** Info style */\n info: `color: ${ConsoleColors.info}; font-weight: bold;`,\n /** Link style */\n link: `color: ${ConsoleColors.primary}; text-decoration: underline;`,\n /** Body text - inherits console theme */\n body: `color: ${ConsoleColors.inherit};`,\n /** Warning style */\n warning: `color: ${ConsoleColors.cta}; font-weight: bold;`,\n} as const;\n\n/**\n * Styled console message for CopilotKit Platform promotion\n * Displays a beautiful, branded advertisement in the console\n */\nexport function logCopilotKitPlatformMessage() {\n console.log(\n `%cCopilotKit Warning%c\n\nuseCopilotChatHeadless_c provides full compatibility with CopilotKit's newly released Headless UI feature set. Headless UI requires a CopilotKit Intelligence license key, available for free at:\n\n%chttps://dashboard.operations.copilotkit.ai%c\n\nAlternatively, useCopilotChat is available for basic programmatic control, and does not require a license key.\n\nTo learn more about CopilotKit Intelligence, read the documentation here:\n\n%chttps://docs.copilotkit.ai/intelligence/overview%c`,\n ConsoleStyles.header,\n ConsoleStyles.body,\n ConsoleStyles.cta,\n ConsoleStyles.body,\n ConsoleStyles.link,\n ConsoleStyles.body,\n );\n}\n\nexport function publicApiKeyRequired(feature: string) {\n console.log(\n `\n%cCopilotKit Warning%c \\n\nIn order to use ${feature}, you need to add your CopilotKit license key, available for free at https://dashboard.operations.copilotkit.ai.\n `.trim(),\n ConsoleStyles.header,\n ConsoleStyles.body,\n );\n}\n\n/**\n * Create a styled console message with custom content\n *\n * @param template - Template string with %c placeholders\n * @param styles - Array of style strings matching the %c placeholders\n *\n * @example\n * ```typescript\n * logStyled(\n * '%cCopilotKit%c Welcome to the platform!',\n * [ConsoleStyles.header, ConsoleStyles.body]\n * );\n * ```\n */\nexport function logStyled(template: string, styles: string[]) {\n console.log(template, ...styles);\n}\n\n/**\n * Quick styled console methods for common use cases\n */\nexport const styledConsole = {\n /** Log a success message */\n success: (message: string) =>\n logStyled(`%c✅ ${message}`, [ConsoleStyles.section]),\n\n /** Log an info message */\n info: (message: string) => logStyled(`%cℹ️ ${message}`, [ConsoleStyles.info]),\n\n /** Log a feature highlight */\n feature: (message: string) =>\n logStyled(`%c✨ ${message}`, [ConsoleStyles.highlight]),\n\n /** Log a call-to-action */\n cta: (message: string) => logStyled(`%c🚀 ${message}`, [ConsoleStyles.cta]),\n\n /** Log the CopilotKit platform promotion */\n logCopilotKitPlatformMessage: logCopilotKitPlatformMessage,\n\n /** Log a `publicApiKeyRequired` warning */\n publicApiKeyRequired: publicApiKeyRequired,\n} as const;\n","import { GraphQLError } from \"graphql\";\nimport { COPILOTKIT_VERSION } from \"../index\";\n\nexport enum Severity {\n CRITICAL = \"critical\", // Critical errors that block core functionality\n WARNING = \"warning\", // Configuration/setup issues that need attention\n INFO = \"info\", // General errors and network issues\n}\n\nexport enum ErrorVisibility {\n BANNER = \"banner\", // Critical errors shown as fixed banners\n TOAST = \"toast\", // Regular errors shown as dismissible toasts\n SILENT = \"silent\", // Errors logged but not shown to user\n DEV_ONLY = \"dev_only\", // Errors only shown in development mode\n}\n\nexport const ERROR_NAMES = {\n COPILOT_ERROR: \"CopilotError\",\n COPILOT_API_DISCOVERY_ERROR: \"CopilotApiDiscoveryError\",\n COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR:\n \"CopilotKitRemoteEndpointDiscoveryError\",\n COPILOT_KIT_AGENT_DISCOVERY_ERROR: \"CopilotKitAgentDiscoveryError\",\n COPILOT_KIT_LOW_LEVEL_ERROR: \"CopilotKitLowLevelError\",\n COPILOT_KIT_VERSION_MISMATCH_ERROR: \"CopilotKitVersionMismatchError\",\n RESOLVED_COPILOT_KIT_ERROR: \"ResolvedCopilotKitError\",\n CONFIGURATION_ERROR: \"ConfigurationError\",\n MISSING_PUBLIC_API_KEY_ERROR: \"MissingPublicApiKeyError\",\n UPGRADE_REQUIRED_ERROR: \"UpgradeRequiredError\",\n} as const;\n\n// Banner errors - critical configuration/discovery issues\nexport const BANNER_ERROR_NAMES = [\n ERROR_NAMES.CONFIGURATION_ERROR,\n ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR,\n ERROR_NAMES.UPGRADE_REQUIRED_ERROR,\n ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR,\n ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR,\n ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR,\n];\n\n// Legacy cloud error names for backward compatibility\nexport const COPILOT_CLOUD_ERROR_NAMES = BANNER_ERROR_NAMES;\n\nexport enum CopilotKitErrorCode {\n NETWORK_ERROR = \"NETWORK_ERROR\",\n NOT_FOUND = \"NOT_FOUND\",\n AGENT_NOT_FOUND = \"AGENT_NOT_FOUND\",\n API_NOT_FOUND = \"API_NOT_FOUND\",\n REMOTE_ENDPOINT_NOT_FOUND = \"REMOTE_ENDPOINT_NOT_FOUND\",\n AUTHENTICATION_ERROR = \"AUTHENTICATION_ERROR\",\n MISUSE = \"MISUSE\",\n UNKNOWN = \"UNKNOWN\",\n VERSION_MISMATCH = \"VERSION_MISMATCH\",\n CONFIGURATION_ERROR = \"CONFIGURATION_ERROR\",\n MISSING_PUBLIC_API_KEY_ERROR = \"MISSING_PUBLIC_API_KEY_ERROR\",\n UPGRADE_REQUIRED_ERROR = \"UPGRADE_REQUIRED_ERROR\",\n}\n\nconst BASE_URL = \"https://docs.copilotkit.ai\";\n\nconst getSeeMoreMarkdown = (link: string) => `See more: [${link}](${link})`;\n\nexport const ERROR_CONFIG = {\n [CopilotKitErrorCode.NETWORK_ERROR]: {\n statusCode: 503,\n troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#network-errors-api-not-found`,\n visibility: ErrorVisibility.BANNER,\n severity: Severity.CRITICAL,\n },\n [CopilotKitErrorCode.NOT_FOUND]: {\n statusCode: 404,\n troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#network-errors-api-not-found`,\n visibility: ErrorVisibility.BANNER,\n severity: Severity.CRITICAL,\n },\n [CopilotKitErrorCode.AGENT_NOT_FOUND]: {\n statusCode: 500,\n troubleshootingUrl: `${BASE_URL}/langgraph-python/coagent-troubleshooting/common-coagent-issues#i-am-getting-agent-not-found-error`,\n visibility: ErrorVisibility.BANNER,\n severity: Severity.CRITICAL,\n },\n [CopilotKitErrorCode.API_NOT_FOUND]: {\n statusCode: 404,\n troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#network-errors-api-not-found`,\n visibility: ErrorVisibility.BANNER,\n severity: Severity.CRITICAL,\n },\n [CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND]: {\n statusCode: 404,\n troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#remote-endpoint-not-found-error`,\n visibility: ErrorVisibility.BANNER,\n severity: Severity.CRITICAL,\n },\n [CopilotKitErrorCode.AUTHENTICATION_ERROR]: {\n statusCode: 401,\n troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues`,\n visibility: ErrorVisibility.BANNER,\n severity: Severity.CRITICAL,\n },\n [CopilotKitErrorCode.MISUSE]: {\n statusCode: 400,\n troubleshootingUrl: null,\n visibility: ErrorVisibility.DEV_ONLY,\n severity: Severity.WARNING,\n },\n [CopilotKitErrorCode.UNKNOWN]: {\n statusCode: 500,\n visibility: ErrorVisibility.TOAST,\n severity: Severity.CRITICAL,\n },\n [CopilotKitErrorCode.CONFIGURATION_ERROR]: {\n statusCode: 400,\n troubleshootingUrl: null,\n severity: Severity.WARNING,\n visibility: ErrorVisibility.BANNER,\n },\n [CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR]: {\n statusCode: 400,\n troubleshootingUrl: null,\n severity: Severity.CRITICAL,\n visibility: ErrorVisibility.BANNER,\n },\n [CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR]: {\n statusCode: 402,\n troubleshootingUrl: null,\n severity: Severity.WARNING,\n visibility: ErrorVisibility.BANNER,\n },\n [CopilotKitErrorCode.VERSION_MISMATCH]: {\n statusCode: 400,\n troubleshootingUrl: null,\n visibility: ErrorVisibility.DEV_ONLY,\n severity: Severity.INFO,\n },\n};\n\nexport class CopilotKitError extends GraphQLError {\n code: CopilotKitErrorCode;\n statusCode: number;\n severity?: Severity;\n visibility: ErrorVisibility;\n\n constructor({\n message = \"Unknown error occurred\",\n code,\n severity,\n visibility,\n }: {\n message?: string;\n code: CopilotKitErrorCode;\n severity?: Severity;\n visibility?: ErrorVisibility;\n }) {\n const name = ERROR_NAMES.COPILOT_ERROR;\n const config = ERROR_CONFIG[code];\n const { statusCode } = config;\n const resolvedVisibility =\n visibility ?? config.visibility ?? ErrorVisibility.TOAST;\n const resolvedSeverity =\n severity ?? (\"severity\" in config ? config.severity : undefined);\n\n super(message, {\n extensions: {\n name,\n statusCode,\n code,\n visibility: resolvedVisibility,\n severity: resolvedSeverity,\n troubleshootingUrl:\n \"troubleshootingUrl\" in config ? config.troubleshootingUrl : null,\n originalError: {\n message,\n stack: new Error().stack,\n },\n },\n });\n\n this.code = code;\n this.name = name;\n this.statusCode = statusCode;\n this.severity = resolvedSeverity;\n this.visibility = resolvedVisibility;\n }\n}\n\n/**\n * Error thrown when we can identify wrong usage of our components.\n * This helps us notify the developer before real errors can happen\n *\n * @extends CopilotKitError\n */\nexport class CopilotKitMisuseError extends CopilotKitError {\n constructor({\n message,\n code = CopilotKitErrorCode.MISUSE,\n }: {\n message: string;\n code?: CopilotKitErrorCode;\n }) {\n const docsLink =\n \"troubleshootingUrl\" in ERROR_CONFIG[code] &&\n ERROR_CONFIG[code].troubleshootingUrl\n ? getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl as string)\n : null;\n const finalMessage = docsLink ? `${message}.\\n\\n${docsLink}` : message;\n super({ message: finalMessage, code });\n this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;\n }\n}\n\nconst getVersionMismatchErrorMessage = ({\n reactCoreVersion,\n runtimeVersion,\n runtimeClientGqlVersion,\n}: VersionMismatchResponse) =>\n `Version mismatch detected: @copilotkit/runtime@${runtimeVersion ?? \"\"} is not compatible with @copilotkit/react-core@${reactCoreVersion} and @copilotkit/runtime-client-gql@${runtimeClientGqlVersion}. Please ensure all installed copilotkit packages are on the same version.`;\n/**\n * Error thrown when CPK versions does not match\n *\n * @extends CopilotKitError\n */\nexport class CopilotKitVersionMismatchError extends CopilotKitError {\n constructor({\n reactCoreVersion,\n runtimeVersion,\n runtimeClientGqlVersion,\n }: VersionMismatchResponse) {\n const code = CopilotKitErrorCode.VERSION_MISMATCH;\n super({\n message: getVersionMismatchErrorMessage({\n reactCoreVersion,\n runtimeVersion,\n runtimeClientGqlVersion,\n }),\n code,\n });\n this.name = ERROR_NAMES.COPILOT_KIT_VERSION_MISMATCH_ERROR;\n }\n}\n\n/**\n * Error thrown when the CopilotKit API endpoint cannot be discovered or accessed.\n * This typically occurs when:\n * - The API endpoint URL is invalid or misconfigured\n * - The API service is not running at the expected location\n * - There are network/firewall issues preventing access\n *\n * @extends CopilotKitError\n */\nexport class CopilotKitApiDiscoveryError extends CopilotKitError {\n constructor(\n params: {\n message?: string;\n code?:\n | CopilotKitErrorCode.API_NOT_FOUND\n | CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND;\n url?: string;\n } = {},\n ) {\n const url = params.url ?? \"\";\n let operationSuffix = \"\";\n if (url?.includes(\"/info\"))\n operationSuffix = `when fetching CopilotKit info`;\n else if (url.includes(\"/actions/execute\"))\n operationSuffix = `when attempting to execute actions.`;\n else if (url.includes(\"/agents/state\"))\n operationSuffix = `when attempting to get agent state.`;\n else if (url.includes(\"/agents/execute\"))\n operationSuffix = `when attempting to execute agent(s).`;\n const message =\n params.message ??\n (params.url\n ? `Failed to find CopilotKit API endpoint at url ${params.url} ${operationSuffix}`\n : `Failed to find CopilotKit API endpoint.`);\n const code = params.code ?? CopilotKitErrorCode.API_NOT_FOUND;\n const errorMessage = `${message}.\\n\\n${getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl)}`;\n super({ message: errorMessage, code });\n this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;\n }\n}\n\n/**\n * This error is used for endpoints specified in runtime's remote endpoints. If they cannot be contacted\n * This typically occurs when:\n * - The API endpoint URL is invalid or misconfigured\n * - The API service is not running at the expected location\n *\n * @extends CopilotKitApiDiscoveryError\n */\nexport class CopilotKitRemoteEndpointDiscoveryError extends CopilotKitApiDiscoveryError {\n constructor(params?: { message?: string; url?: string }) {\n const message =\n params?.message ??\n (params?.url\n ? `Failed to find or contact remote endpoint at url ${params.url}`\n : \"Failed to find or contact remote endpoint\");\n const code = CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND;\n super({ message, code });\n this.name = ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR;\n }\n}\n\n/**\n * Error thrown when a LangGraph agent cannot be found or accessed.\n * This typically occurs when:\n * - The specified agent name does not exist in the deployment\n * - The agent configuration is invalid or missing\n * - The agent service is not properly deployed or initialized\n *\n * @extends CopilotKitError\n */\nexport class CopilotKitAgentDiscoveryError extends CopilotKitError {\n constructor(params: {\n agentName?: string;\n availableAgents: { name: string; id: string }[];\n }) {\n const { agentName, availableAgents } = params;\n const code = CopilotKitErrorCode.AGENT_NOT_FOUND;\n\n const seeMore = getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl);\n let message;\n\n if (availableAgents.length) {\n const agentList = availableAgents.map((agent) => agent.name).join(\", \");\n\n if (agentName) {\n message = `Agent '${agentName}' was not found. Available agents are: ${agentList}. Please verify the agent name in your configuration and ensure it matches one of the available agents.\\n\\n${seeMore}`;\n } else {\n message = `The requested agent was not found. Available agents are: ${agentList}. Please verify the agent name in your configuration and ensure it matches one of the available agents.\\n\\n${seeMore}`;\n }\n } else {\n message = `${agentName ? `Agent '${agentName}'` : \"The requested agent\"} was not found. Please set up at least one agent before proceeding. ${seeMore}`;\n }\n\n super({ message, code });\n this.name = ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR;\n }\n}\n\n/**\n * Handles low-level networking errors that occur before a request reaches the server.\n * These errors arise from issues in the underlying communication infrastructure rather than\n * application-level logic or server responses. Typically used to handle \"fetch failed\" errors\n * where no HTTP status code is available.\n *\n * Common scenarios include:\n * - Connection failures (ECONNREFUSED) when server is down/unreachable\n * - DNS resolution failures (ENOTFOUND) when domain can't be resolved\n * - Timeouts (ETIMEDOUT) when request takes too long\n * - Protocol/transport layer errors like SSL/TLS issues\n */\nexport class CopilotKitLowLevelError extends CopilotKitError {\n constructor({\n error,\n url,\n message,\n }: {\n error: Error;\n url: string;\n message?: string;\n }) {\n let code = CopilotKitErrorCode.NETWORK_ERROR;\n\n // @ts-expect-error -- code may exist\n const errorCode = error.code as string;\n const errorMessage =\n message ?? resolveLowLevelErrorMessage({ errorCode, url });\n\n super({ message: errorMessage, code });\n\n this.name = ERROR_NAMES.COPILOT_KIT_LOW_LEVEL_ERROR;\n }\n}\n\n/**\n * Generic catch-all error handler for HTTP responses from the CopilotKit API where a status code is available.\n * Used when we receive an HTTP error status and wish to handle broad range of them\n *\n * This differs from CopilotKitLowLevelError in that:\n * - ResolvedCopilotKitError: Server was reached and returned an HTTP status\n * - CopilotKitLowLevelError: Error occurred before reaching server (e.g. network failure)\n *\n * @param status - The HTTP status code received from the API response\n * @param message - Optional error message to include\n * @param code - Optional specific CopilotKitErrorCode to override default behavior\n *\n * Default behavior:\n * - 400 Bad Request: Maps to CopilotKitApiDiscoveryError\n * - All other status codes: Maps to UNKNOWN error code if no specific code provided\n */\nexport class ResolvedCopilotKitError extends CopilotKitError {\n constructor({\n status,\n message,\n code,\n isRemoteEndpoint,\n url,\n }: {\n status: number;\n message?: string;\n code?: CopilotKitErrorCode;\n isRemoteEndpoint?: boolean;\n url?: string;\n }) {\n let resolvedCode = code;\n if (!resolvedCode) {\n switch (status) {\n case 400:\n throw new CopilotKitApiDiscoveryError({ message, url });\n case 404:\n throw isRemoteEndpoint\n ? new CopilotKitRemoteEndpointDiscoveryError({ message, url })\n : new CopilotKitApiDiscoveryError({ message, url });\n default:\n resolvedCode = CopilotKitErrorCode.UNKNOWN;\n break;\n }\n }\n\n super({ message, code: resolvedCode });\n this.name = ERROR_NAMES.RESOLVED_COPILOT_KIT_ERROR;\n }\n}\n\nexport class ConfigurationError extends CopilotKitError {\n constructor(message: string) {\n super({ message, code: CopilotKitErrorCode.CONFIGURATION_ERROR });\n this.name = ERROR_NAMES.CONFIGURATION_ERROR;\n this.severity = Severity.WARNING;\n }\n}\n\nexport class MissingPublicApiKeyError extends ConfigurationError {\n constructor(message: string) {\n super(message);\n this.name = ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR;\n this.severity = Severity.CRITICAL;\n }\n}\n\nexport class UpgradeRequiredError extends ConfigurationError {\n constructor(message: string) {\n super(message);\n this.name = ERROR_NAMES.UPGRADE_REQUIRED_ERROR;\n this.severity = Severity.WARNING;\n }\n}\n\n/**\n * Checks if an error is already a structured CopilotKit error.\n * This utility centralizes the logic for detecting structured errors across the codebase.\n *\n * @param error - The error to check\n * @returns true if the error is already structured, false otherwise\n */\nexport function isStructuredCopilotKitError(error: any): boolean {\n return (\n error instanceof CopilotKitError ||\n error instanceof CopilotKitLowLevelError ||\n (error?.name && error.name.includes(\"CopilotKit\")) ||\n error?.extensions?.code !== undefined // Check if it has our structured error properties\n );\n}\n\n/**\n * Returns the error as-is if it's already structured, otherwise converts it using the provided converter function.\n * This utility centralizes the pattern of preserving structured errors while converting unstructured ones.\n *\n * @param error - The error to process\n * @param converter - Function to convert unstructured errors to structured ones\n * @returns The structured error\n */\nexport function ensureStructuredError<T extends CopilotKitError>(\n error: any,\n converter: (error: any) => T,\n): T | any {\n return isStructuredCopilotKitError(error) ? error : converter(error);\n}\n\ninterface VersionMismatchResponse {\n runtimeVersion?: string;\n runtimeClientGqlVersion: string;\n reactCoreVersion: string;\n}\n\nexport async function getPossibleVersionMismatch({\n runtimeVersion,\n runtimeClientGqlVersion,\n}: {\n runtimeVersion?: string;\n runtimeClientGqlVersion: string;\n}) {\n if (!runtimeVersion || runtimeVersion === \"\" || !runtimeClientGqlVersion)\n return;\n if (\n COPILOTKIT_VERSION !== runtimeVersion ||\n COPILOTKIT_VERSION !== runtimeClientGqlVersion ||\n runtimeVersion !== runtimeClientGqlVersion\n ) {\n return {\n runtimeVersion,\n runtimeClientGqlVersion,\n reactCoreVersion: COPILOTKIT_VERSION,\n message: getVersionMismatchErrorMessage({\n runtimeVersion,\n runtimeClientGqlVersion,\n reactCoreVersion: COPILOTKIT_VERSION,\n }),\n };\n }\n\n return;\n}\n\nconst resolveLowLevelErrorMessage = ({\n errorCode,\n url,\n}: {\n errorCode?: string;\n url: string;\n}) => {\n const troubleshootingLink =\n ERROR_CONFIG[CopilotKitErrorCode.NETWORK_ERROR].troubleshootingUrl;\n const genericMessage = (\n description = `Failed to fetch from url ${url}.`,\n ) => `${description}.\n\nPossible reasons:\n- -The server may have an error preventing it from returning a response (Check the server logs for more info).\n- -The server might be down or unreachable\n- -There might be a network issue (e.g., DNS failure, connection timeout) \n- -The URL might be incorrect\n- -The server is not running on the specified port\n\n${getSeeMoreMarkdown(troubleshootingLink)}`;\n\n if (url.includes(\"/info\"))\n return genericMessage(\n `Failed to fetch CopilotKit agents/action information from url ${url}.`,\n );\n if (url.includes(\"/actions/execute\"))\n return genericMessage(`Fetch call to ${url} to execute actions failed.`);\n if (url.includes(\"/agents/state\"))\n return genericMessage(`Fetch call to ${url} to get agent state failed.`);\n if (url.includes(\"/agents/execute\"))\n return genericMessage(`Fetch call to ${url} to execute agent(s) failed.`);\n\n switch (errorCode) {\n case \"ECONNREFUSED\":\n return `Connection to ${url} was refused. Ensure the server is running and accessible.\\n\\n${getSeeMoreMarkdown(troubleshootingLink)}`;\n case \"ENOTFOUND\":\n return `The server on ${url} could not be found. Check the URL or your network configuration.\\n\\n${getSeeMoreMarkdown(ERROR_CONFIG[CopilotKitErrorCode.NOT_FOUND].troubleshootingUrl)}`;\n case \"ETIMEDOUT\":\n return `The connection to ${url} timed out. The server might be overloaded or taking too long to respond.\\n\\n${getSeeMoreMarkdown(troubleshootingLink)}`;\n default:\n return;\n }\n};\n","import { z } from \"zod\";\nimport { Parameter } from \"../types\";\n\nexport type JSONSchemaString = {\n type: \"string\";\n description?: string;\n enum?: string[];\n};\n\nexport type JSONSchemaNumber = {\n type: \"number\";\n description?: string;\n};\n\nexport type JSONSchemaBoolean = {\n type: \"boolean\";\n description?: string;\n};\n\nexport type JSONSchemaObject = {\n type: \"object\";\n properties?: Record<string, JSONSchema>;\n required?: string[];\n description?: string;\n};\n\nexport type JSONSchemaArray = {\n type: \"array\";\n items: JSONSchema;\n description?: string;\n};\n\nexport type JSONSchema =\n | JSONSchemaString\n | JSONSchemaNumber\n | JSONSchemaBoolean\n | JSONSchemaObject\n | JSONSchemaArray;\n\nexport function actionParametersToJsonSchema(\n actionParameters: Parameter[],\n): JSONSchema {\n // Create the parameters object based on the argumentAnnotations\n let parameters: { [key: string]: any } = {};\n for (let parameter of actionParameters || []) {\n parameters[parameter.name] = convertAttribute(parameter);\n }\n\n let requiredParameterNames: string[] = [];\n for (let arg of actionParameters || []) {\n if (arg.required !== false) {\n requiredParameterNames.push(arg.name);\n }\n }\n\n // Create the ChatCompletionFunctions object\n return {\n type: \"object\",\n properties: parameters,\n required: requiredParameterNames,\n };\n}\n\n// Convert JSONSchema to Parameter[]\nexport function jsonSchemaToActionParameters(\n jsonSchema: JSONSchema,\n): Parameter[] {\n if (jsonSchema.type !== \"object\" || !jsonSchema.properties) {\n return [];\n }\n\n const parameters: Parameter[] = [];\n const requiredFields = jsonSchema.required || [];\n\n for (const [name, schema] of Object.entries(jsonSchema.properties)) {\n const parameter = convertJsonSchemaToParameter(\n name,\n schema,\n requiredFields.includes(name),\n );\n parameters.push(parameter);\n }\n\n return parameters;\n}\n\n// Convert JSONSchema property to Parameter\nfunction convertJsonSchemaToParameter(\n name: string,\n schema: JSONSchema,\n isRequired: boolean,\n): Parameter {\n const baseParameter: Parameter = {\n name,\n description: schema.description,\n };\n\n if (!isRequired) {\n baseParameter.required = false;\n }\n\n // Handle null-union types like [\"string\", \"null\"] by picking the non-null type\n if (Array.isArray(schema.type)) {\n const types = schema.type as string[];\n const hasNull = types.includes(\"null\");\n const nonNullTypes = types.filter((t: string) => t !== \"null\");\n const resolvedType = nonNullTypes.length > 0 ? nonNullTypes[0] : \"string\";\n return convertJsonSchemaToParameter(\n name,\n { ...schema, type: resolvedType } as JSONSchema,\n hasNull ? false : isRequired,\n );\n }\n\n switch (schema.type) {\n case \"string\":\n return {\n ...baseParameter,\n type: \"string\",\n ...(schema.enum && { enum: schema.enum }),\n };\n case \"number\":\n case \"boolean\":\n return {\n ...baseParameter,\n type: schema.type,\n };\n case \"object\":\n if (schema.properties) {\n const attributes: Parameter[] = [];\n const requiredFields = schema.required || [];\n\n for (const [propName, propSchema] of Object.entries(\n schema.properties,\n )) {\n attributes.push(\n convertJsonSchemaToParameter(\n propName,\n propSchema,\n requiredFields.includes(propName),\n ),\n );\n }\n\n return {\n ...baseParameter,\n type: \"object\",\n attributes,\n };\n }\n return {\n ...baseParameter,\n type: \"object\",\n };\n case \"array\":\n if (schema.items.type === \"object\" && \"properties\" in schema.items) {\n const attributes: Parameter[] = [];\n const requiredFields = schema.items.required || [];\n\n for (const [propName, propSchema] of Object.entries(\n schema.items.properties || {},\n )) {\n attributes.push(\n convertJsonSchemaToParameter(\n propName,\n propSchema,\n requiredFields.includes(propName),\n ),\n );\n }\n\n return {\n ...baseParameter,\n type: \"object[]\",\n attributes,\n };\n } else if (schema.items.type === \"array\") {\n throw new Error(\"Nested arrays are not supported\");\n } else {\n return {\n ...baseParameter,\n type: `${schema.items.type}[]`,\n };\n }\n default:\n return {\n ...baseParameter,\n type: \"string\",\n };\n }\n}\n\nfunction convertAttribute(attribute: Parameter): JSONSchema {\n switch (attribute.type) {\n case \"string\":\n return {\n type: \"string\",\n description: attribute.description,\n ...(attribute.enum && { enum: attribute.enum }),\n };\n case \"number\":\n case \"boolean\":\n return {\n type: attribute.type,\n description: attribute.description,\n };\n case \"object\":\n case \"object[]\":\n const properties = attribute.attributes?.reduce(\n (acc, attr) => {\n acc[attr.name] = convertAttribute(attr);\n return acc;\n },\n {} as Record<string, any>,\n );\n const required = attribute.attributes\n ?.filter((attr) => attr.required !== false)\n .map((attr) => attr.name);\n if (attribute.type === \"object[]\") {\n return {\n type: \"array\",\n items: {\n type: \"object\",\n ...(properties && { properties }),\n ...(required && required.length > 0 && { required }),\n },\n description: attribute.description,\n };\n }\n return {\n type: \"object\",\n description: attribute.description,\n ...(properties && { properties }),\n ...(required && required.length > 0 && { required }),\n };\n default:\n // Handle arrays of primitive types and undefined attribute.type\n if (attribute.type?.endsWith(\"[]\")) {\n const itemType = attribute.type.slice(0, -2);\n return {\n type: \"array\",\n items: { type: itemType as any },\n description: attribute.description,\n };\n }\n // Fallback for undefined type or any other unexpected type\n return {\n type: \"string\",\n description: attribute.description,\n };\n }\n}\n\nexport function convertJsonSchemaToZodSchema(\n jsonSchema: any,\n required: boolean,\n definitions?: Record<string, any>,\n visitedRefs?: Set<string>,\n): z.ZodSchema {\n // Resolve $ref references\n if (jsonSchema.$ref && definitions) {\n const refPath = jsonSchema.$ref.replace(\n /^#\\/\\$defs\\/|^#\\/definitions\\//,\n \"\",\n );\n\n // Detect circular $ref cycles\n const refs = visitedRefs ?? new Set<string>();\n if (refs.has(refPath)) {\n console.warn(\n `[CopilotKit] Circular $ref detected for \"${refPath}\" — falling back to z.any()`,\n );\n let schema = z.any();\n if (jsonSchema.description) {\n schema = schema.describe(jsonSchema.description);\n }\n return required ? schema : schema.optional();\n }\n\n const resolved = definitions[refPath];\n if (resolved) {\n // Clone the set so sibling branches don't see each other's visited refs\n const nextRefs = new Set(refs);\n nextRefs.add(refPath);\n return convertJsonSchemaToZodSchema(\n resolved,\n required,\n definitions,\n nextRefs,\n );\n }\n }\n\n // Collect top-level definitions for $ref resolution\n const defs = definitions ?? jsonSchema.$defs ?? jsonSchema.definitions;\n\n // Handle null-union types like [\"string\", \"null\"]\n if (Array.isArray(jsonSchema.type)) {\n const types = jsonSchema.type as string[];\n const hasNull = types.includes(\"null\");\n const nonNullTypes = types.filter((t: string) => t !== \"null\");\n const resolvedType = nonNullTypes.length > 0 ? nonNullTypes[0] : \"string\";\n const innerSchema = convertJsonSchemaToZodSchema(\n { ...jsonSchema, type: resolvedType },\n true,\n defs,\n visitedRefs,\n );\n let schema = hasNull ? z.union([innerSchema, z.null()]) : innerSchema;\n if (jsonSchema.description) {\n schema = schema.describe(jsonSchema.description);\n }\n return required ? schema : schema.optional();\n }\n\n // Handle anyOf / oneOf as z.union\n const unionVariants = jsonSchema.anyOf ?? jsonSchema.oneOf;\n if (Array.isArray(unionVariants) && unionVariants.length > 0) {\n if (unionVariants.length === 1) {\n return convertJsonSchemaToZodSchema(\n unionVariants[0],\n required,\n defs,\n visitedRefs,\n );\n }\n const schemas = unionVariants.map((v: any) =>\n convertJsonSchemaToZodSchema(v, true, defs, visitedRefs),\n );\n let schema = z.union(\n schemas as [z.ZodSchema, z.ZodSchema, ...z.ZodSchema[]],\n );\n if (jsonSchema.description) {\n schema = schema.describe(jsonSchema.description);\n }\n return required ? schema : schema.optional();\n }\n\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(\n value,\n jsonSchema.required ? jsonSchema.required.includes(key) : false,\n defs,\n visitedRefs,\n );\n }\n let schema = z.object(spec).describe(jsonSchema.description);\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n if (jsonSchema.enum && jsonSchema.enum.length > 0) {\n let schema = z\n .enum(jsonSchema.enum as [string, ...string[]])\n .describe(jsonSchema.description);\n return required ? schema : schema.optional();\n }\n let schema = z.string().describe(jsonSchema.description);\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\" || jsonSchema.type === \"integer\") {\n let schema = z.number().describe(jsonSchema.description);\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n let schema = z.boolean().describe(jsonSchema.description);\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n let itemSchema = convertJsonSchemaToZodSchema(\n jsonSchema.items,\n true,\n defs,\n visitedRefs,\n );\n let schema = z.array(itemSchema).describe(jsonSchema.description);\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"null\") {\n let schema = z.null().describe(jsonSchema.description);\n return required ? schema : schema.optional();\n }\n\n // Fallback: accept any value rather than throwing\n console.warn(\n `[CopilotKit] Unsupported JSON schema type \"${jsonSchema.type ?? \"unknown\"}\" — falling back to z.any()`,\n );\n let schema = z.any();\n if (jsonSchema.description) {\n schema = schema.describe(jsonSchema.description);\n }\n return required ? schema : schema.optional();\n}\n\nexport function getZodParameters<T extends [] | Parameter[] | undefined>(\n parameters: T,\n): any {\n if (!parameters) return z.object({});\n const jsonParams = actionParametersToJsonSchema(parameters);\n return convertJsonSchemaToZodSchema(jsonParams, true);\n}\n","/**\n * Inspector metadata supplied by a trusted CopilotKit runtime.\n *\n * Each optional module is independent so clients can render partial metadata\n * from runtimes that do not expose every module.\n */\nexport interface InspectorMetadataV1 {\n readonly schemaVersion: 1;\n readonly identity?: {\n readonly organizationName: string;\n readonly projectName: string;\n };\n readonly plan?: {\n readonly code: string;\n readonly label: string;\n };\n readonly license?: {\n readonly state: \"valid\" | \"none\" | \"expired\" | \"unknown\";\n };\n readonly action?:\n | { readonly kind: \"manage_plan\"; readonly url: string }\n | { readonly kind: \"renew\"; readonly url: string }\n | { readonly kind: \"enable_intelligence\"; readonly url: string };\n readonly usage?: {\n readonly used: number;\n readonly limit:\n | { readonly kind: \"finite\"; readonly value: number }\n | { readonly kind: \"unlimited\" }\n | { readonly kind: \"unknown\" };\n readonly expiringSoonCount?: number;\n };\n}\n\ntype UnknownRecord = Record<string, unknown>;\ntype InspectorIdentity = NonNullable<InspectorMetadataV1[\"identity\"]>;\ntype InspectorPlan = NonNullable<InspectorMetadataV1[\"plan\"]>;\ntype InspectorLicense = NonNullable<InspectorMetadataV1[\"license\"]>;\ntype InspectorAction = NonNullable<InspectorMetadataV1[\"action\"]>;\ntype InspectorUsage = NonNullable<InspectorMetadataV1[\"usage\"]>;\ntype InspectorUsageLimit = InspectorUsage[\"limit\"];\n\nfunction isRecord(value: unknown): value is UnknownRecord {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n\n try {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n } catch {\n return false;\n }\n}\n\nfunction readOwnDataProperty(value: UnknownRecord, key: string): unknown {\n try {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n return descriptor !== undefined && \"value\" in descriptor\n ? descriptor.value\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction parseNonBlankString(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const parsed = value.trim();\n return parsed.length > 0 ? parsed : undefined;\n}\n\nfunction parseIdentity(value: unknown): InspectorIdentity | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const organizationName = parseNonBlankString(value.organizationName);\n const projectName = parseNonBlankString(value.projectName);\n if (organizationName === undefined || projectName === undefined) {\n return undefined;\n }\n\n return { organizationName, projectName };\n}\n\nfunction parsePlan(value: unknown): InspectorPlan | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const code = parseNonBlankString(value.code);\n const label = parseNonBlankString(value.label);\n if (code === undefined || label === undefined) {\n return undefined;\n }\n\n return { code, label };\n}\n\nfunction parseLicense(value: unknown): InspectorLicense | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n switch (value.state) {\n case \"valid\":\n case \"none\":\n case \"expired\":\n case \"unknown\":\n return { state: value.state };\n default:\n return undefined;\n }\n}\n\nfunction parseActionKind(value: unknown): InspectorAction[\"kind\"] | undefined {\n switch (value) {\n case \"manage_plan\":\n case \"renew\":\n case \"enable_intelligence\":\n return value;\n default:\n return undefined;\n }\n}\n\nfunction parseSafeActionUrl(value: unknown): string | undefined {\n const url = parseNonBlankString(value);\n if (url === undefined || url.includes(\"?\") || url.includes(\"#\")) {\n return undefined;\n }\n\n const authorityStart = url.indexOf(\"://\");\n if (authorityStart < 1) {\n return undefined;\n }\n\n const authorityAndPath = url.slice(authorityStart + 3);\n const pathStart = authorityAndPath.indexOf(\"/\");\n const authority =\n pathStart === -1 ? authorityAndPath : authorityAndPath.slice(0, pathStart);\n if (authority.includes(\"@\")) {\n return undefined;\n }\n\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return undefined;\n }\n\n if (parsed.hostname.length === 0 || parsed.username || parsed.password) {\n return undefined;\n }\n\n if (parsed.protocol === \"https:\") {\n return url;\n }\n\n const isLoopbackHost =\n parsed.hostname === \"localhost\" ||\n parsed.hostname === \"127.0.0.1\" ||\n parsed.hostname === \"[::1]\";\n if (parsed.protocol === \"http:\" && isLoopbackHost) {\n return url;\n }\n\n return undefined;\n}\n\nfunction parseAction(value: unknown): InspectorAction | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const kind = parseActionKind(value.kind);\n const url = parseSafeActionUrl(value.url);\n if (kind === undefined || url === undefined) {\n return undefined;\n }\n\n return { kind, url };\n}\n\nfunction isFiniteNonnegativeInteger(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction parseUsageLimit(value: unknown): InspectorUsageLimit | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n if (value.kind === \"finite\") {\n if (\n typeof value.value !== \"number\" ||\n !Number.isSafeInteger(value.value) ||\n value.value < 1\n ) {\n return undefined;\n }\n\n return { kind: \"finite\", value: value.value };\n }\n\n if (value.kind === \"unlimited\") {\n return { kind: \"unlimited\" };\n }\n\n if (value.kind === \"unknown\") {\n return { kind: \"unknown\" };\n }\n\n return undefined;\n}\n\nfunction parseUsage(value: unknown): InspectorUsage | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const limit = parseUsageLimit(value.limit);\n const used = value.used;\n if (!isFiniteNonnegativeInteger(used) || limit === undefined) {\n return undefined;\n }\n\n const rawExpiringSoonCount = readOwnDataProperty(value, \"expiringSoonCount\");\n const expiringSoonCount = isFiniteNonnegativeInteger(rawExpiringSoonCount)\n ? rawExpiringSoonCount\n : undefined;\n\n return {\n used,\n limit,\n ...(expiringSoonCount === undefined ? {} : { expiringSoonCount }),\n };\n}\n\n/**\n * Parses untrusted inspector metadata without letting one invalid optional\n * module hide the other valid modules.\n *\n * @param value - The decoded runtime response body.\n * @returns Normalized version 1 metadata, or `undefined` for an unsupported\n * top-level payload.\n */\nexport function parseInspectorMetadataV1(\n value: unknown,\n): InspectorMetadataV1 | undefined {\n if (!isRecord(value) || value.schemaVersion !== 1) {\n return undefined;\n }\n\n const identity = parseIdentity(value.identity);\n const plan = parsePlan(value.plan);\n const license = parseLicense(value.license);\n const action = parseAction(value.action);\n const usage = parseUsage(value.usage);\n\n return {\n schemaVersion: 1,\n ...(identity === undefined ? {} : { identity }),\n ...(plan === undefined ? {} : { plan }),\n ...(license === undefined ? {} : { license }),\n ...(action === undefined ? {} : { action }),\n ...(usage === undefined ? {} : { usage }),\n };\n}\n","/** A bounded page in the Inspector Learning snapshot. */\nexport interface InspectorLearningPage<T> {\n readonly page: number;\n readonly pageSize: number;\n readonly total: number;\n readonly totalPages: number;\n readonly items: readonly T[];\n}\n\nexport type InspectorLearningEvidence =\n | {\n readonly status: \"available\";\n readonly threadId: string;\n readonly threadName: string | null;\n readonly messageIds: readonly string[];\n readonly updatedAt: string;\n }\n | { readonly status: \"unavailable\" };\n\n/** A cited Trajectory, linked into the Intelligence web app. */\nexport type InspectorLearningTrajectoryEvidence =\n | {\n readonly status: \"available\";\n readonly trajectoryId: string;\n readonly eventCount: number;\n readonly url: string;\n }\n | { readonly status: \"unavailable\" };\n\nexport interface InspectorLearningInsight {\n readonly id: string;\n readonly statement: string;\n readonly impact: string;\n readonly totalThreadCount: number;\n readonly evidenceTruncated: boolean;\n readonly evidence: readonly InspectorLearningEvidence[];\n /** Absent when Intelligence predates Trajectory evidence. */\n readonly totalTrajectoryCount?: number;\n /** Absent when Intelligence predates Trajectory evidence. */\n readonly trajectoryEvidence?: readonly InspectorLearningTrajectoryEvidence[];\n}\n\nexport interface InspectorLearningSkill {\n readonly id: string;\n readonly name: string;\n readonly description: string;\n readonly revision: number;\n readonly skillMd: string;\n readonly sourceInsight: InspectorLearningInsight | null;\n}\n\nexport interface InspectorLearningSnapshotV1 {\n readonly schemaVersion: 1;\n readonly projectKey: string;\n readonly snapshotVersion: string;\n readonly webAppOrigin: string;\n readonly configuration:\n | { readonly state: \"not_configured\" }\n | {\n readonly state: \"invalid\";\n readonly reason: \"container\" | \"instrumentation\";\n }\n | {\n readonly state: \"configured\";\n readonly container: { readonly id: string; readonly name: string };\n }\n | { readonly state: \"selection_required\" };\n readonly pendingThreadCount: number;\n readonly run: {\n readonly hasActiveRun: boolean;\n readonly hasEverSucceeded: boolean;\n readonly latest: {\n readonly completedAt: string | null;\n readonly status:\n | \"queued\"\n | \"freezing\"\n | \"batching\"\n | \"reducing\"\n | \"finalizing\"\n | \"succeeded\"\n | \"failed\";\n } | null;\n };\n readonly pendingCandidateCount: number;\n readonly skillsPage: InspectorLearningPage<InspectorLearningSkill>;\n readonly insightsPage: InspectorLearningPage<InspectorLearningInsight>;\n readonly links: {\n readonly learning: string;\n readonly candidates: string | null;\n readonly runs: string | null;\n };\n}\n\nexport interface InspectorLearningRequestV1 {\n readonly agentId?: string;\n readonly skillsPage?: number;\n readonly insightsPage?: number;\n}\n\ntype RecordValue = Record<string, unknown>;\n\nconst record = (value: unknown): value is RecordValue =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst string = (value: unknown, maximum: number): value is string =>\n typeof value === \"string\" &&\n value.trim().length > 0 &&\n value.length <= maximum;\nconst integer = (value: unknown, minimum = 0): value is number =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value >= minimum;\nconst date = (value: unknown): value is string =>\n typeof value === \"string\" && !Number.isNaN(Date.parse(value));\n\n/**\n * Accepts only the configured Intelligence web-app origin.\n *\n * Learning links are server-authored actions. Treating every HTTPS origin as\n * trusted would let a misconfigured or compromised upstream turn Inspector\n * copy into a navigation primitive for an arbitrary site.\n */\nexport function parseInspectorLearningUrl(\n value: unknown,\n trustedOrigin: unknown,\n): string | undefined {\n if (\n typeof value !== \"string\" ||\n value.length > 4_000 ||\n typeof trustedOrigin !== \"string\" ||\n trustedOrigin.length > 2_000\n ) {\n return undefined;\n }\n try {\n const parsed = new URL(value);\n const configured = new URL(trustedOrigin);\n const loopback = [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(\n configured.hostname,\n );\n if (\n parsed.username ||\n parsed.password ||\n configured.username ||\n configured.password ||\n configured.pathname !== \"/\" ||\n configured.search ||\n configured.hash ||\n (configured.protocol !== \"https:\" &&\n !(configured.protocol === \"http:\" && loopback)) ||\n parsed.origin !== configured.origin\n ) {\n return undefined;\n }\n return parsed.toString();\n } catch {\n return undefined;\n }\n}\n\nfunction parseEvidence(value: unknown): InspectorLearningEvidence | undefined {\n if (record(value) && value.status === \"unavailable\") {\n return Object.keys(value).length === 1\n ? { status: \"unavailable\" }\n : undefined;\n }\n if (\n !record(value) ||\n value.status !== \"available\" ||\n !string(value.threadId, 128) ||\n !date(value.updatedAt)\n ) {\n return undefined;\n }\n if (\n value.threadName !== null &&\n !(typeof value.threadName === \"string\" && value.threadName.length <= 4_000)\n ) {\n return undefined;\n }\n if (\n !Array.isArray(value.messageIds) ||\n value.messageIds.length > 200 ||\n !value.messageIds.every((id) => string(id, 128))\n ) {\n return undefined;\n }\n return {\n status: \"available\",\n threadId: value.threadId,\n threadName: value.threadName,\n messageIds: [...value.messageIds],\n updatedAt: value.updatedAt,\n };\n}\n\nfunction parseTrajectoryEvidence(\n value: unknown,\n webAppOrigin: string,\n): InspectorLearningTrajectoryEvidence | undefined {\n if (record(value) && value.status === \"unavailable\") {\n return Object.keys(value).length === 1\n ? { status: \"unavailable\" }\n : undefined;\n }\n if (\n !record(value) ||\n value.status !== \"available\" ||\n !string(value.trajectoryId, 128) ||\n !integer(value.eventCount)\n ) {\n return undefined;\n }\n const url = parseInspectorLearningUrl(value.url, webAppOrigin);\n if (!url) return undefined;\n return {\n status: \"available\",\n trajectoryId: value.trajectoryId,\n eventCount: value.eventCount,\n url,\n };\n}\n\nfunction parseInsight(\n value: unknown,\n webAppOrigin: string,\n): InspectorLearningInsight | undefined {\n if (\n !record(value) ||\n !string(value.id, 128) ||\n !string(value.statement, 4_000) ||\n !string(value.impact, 4_000) ||\n !integer(value.totalThreadCount) ||\n typeof value.evidenceTruncated !== \"boolean\" ||\n !Array.isArray(value.evidence) ||\n value.evidence.length > 100\n ) {\n return undefined;\n }\n const evidence = value.evidence.map(parseEvidence);\n if (evidence.some((item) => item === undefined)) return undefined;\n const insight: InspectorLearningInsight = {\n id: value.id,\n statement: value.statement,\n impact: value.impact,\n totalThreadCount: value.totalThreadCount,\n evidenceTruncated: value.evidenceTruncated,\n evidence: evidence as InspectorLearningEvidence[],\n };\n // Each Trajectory field is optional on its own; a malformed one rejects\n // the Insight, an absent one leaves the Thread-only shape untouched.\n let totalTrajectoryCount: number | undefined;\n if (value.totalTrajectoryCount !== undefined) {\n if (!integer(value.totalTrajectoryCount)) return undefined;\n totalTrajectoryCount = value.totalTrajectoryCount;\n }\n let trajectoryEvidence: InspectorLearningTrajectoryEvidence[] | undefined;\n if (value.trajectoryEvidence !== undefined) {\n if (\n !Array.isArray(value.trajectoryEvidence) ||\n value.trajectoryEvidence.length > 100\n ) {\n return undefined;\n }\n const parsed = value.trajectoryEvidence.map((item) =>\n parseTrajectoryEvidence(item, webAppOrigin),\n );\n if (parsed.some((item) => item === undefined)) return undefined;\n trajectoryEvidence = parsed as InspectorLearningTrajectoryEvidence[];\n }\n return {\n ...insight,\n ...(totalTrajectoryCount === undefined ? {} : { totalTrajectoryCount }),\n ...(trajectoryEvidence === undefined ? {} : { trajectoryEvidence }),\n };\n}\n\nfunction parseSkill(\n value: unknown,\n webAppOrigin: string,\n): InspectorLearningSkill | undefined {\n if (\n !record(value) ||\n !string(value.id, 128) ||\n !string(value.name, 128) ||\n !string(value.description, 4_000) ||\n !integer(value.revision, 1) ||\n typeof value.skillMd !== \"string\" ||\n value.skillMd.length > 131_072\n ) {\n return undefined;\n }\n const sourceInsight =\n value.sourceInsight === null\n ? null\n : parseInsight(value.sourceInsight, webAppOrigin);\n if (sourceInsight === undefined) return undefined;\n return {\n id: value.id,\n name: value.name,\n description: value.description,\n revision: value.revision,\n skillMd: value.skillMd,\n sourceInsight,\n };\n}\n\nfunction parsePage<T>(\n value: unknown,\n pageSize: 3 | 4,\n parseItem: (item: unknown) => T | undefined,\n): InspectorLearningPage<T> | undefined {\n if (\n !record(value) ||\n !integer(value.page, 1) ||\n value.pageSize !== pageSize ||\n !integer(value.total) ||\n !integer(value.totalPages) ||\n !Array.isArray(value.items) ||\n value.items.length > pageSize\n ) {\n return undefined;\n }\n const items = value.items.map(parseItem);\n if (items.some((item) => item === undefined)) return undefined;\n if (value.total === 0) {\n if (value.page !== 1 || value.totalPages !== 0 || items.length !== 0) {\n return undefined;\n }\n } else {\n const totalPages = Math.ceil(value.total / pageSize);\n const expectedItems = Math.min(\n pageSize,\n value.total - (value.page - 1) * pageSize,\n );\n if (\n value.totalPages !== totalPages ||\n value.page > totalPages ||\n items.length !== expectedItems\n ) {\n return undefined;\n }\n }\n return {\n page: value.page,\n pageSize,\n total: value.total,\n totalPages: value.totalPages,\n items: items as T[],\n };\n}\n\nfunction parseConfiguration(\n value: unknown,\n): InspectorLearningSnapshotV1[\"configuration\"] | undefined {\n if (!record(value)) return undefined;\n if (\n value.state === \"not_configured\" ||\n value.state === \"selection_required\"\n ) {\n return { state: value.state };\n }\n if (\n value.state === \"invalid\" &&\n (value.reason === \"container\" || value.reason === \"instrumentation\")\n ) {\n return { state: value.state, reason: value.reason };\n }\n if (\n value.state === \"configured\" &&\n record(value.container) &&\n string(value.container.id, 128) &&\n string(value.container.name, 128)\n ) {\n return {\n state: \"configured\",\n container: { id: value.container.id, name: value.container.name },\n };\n }\n return undefined;\n}\n\nconst runStatuses = new Set([\n \"queued\",\n \"freezing\",\n \"batching\",\n \"reducing\",\n \"finalizing\",\n \"succeeded\",\n \"failed\",\n]);\n\n/** Validates and copies an untrusted Learning snapshot at each process boundary. */\nexport function parseInspectorLearningSnapshotV1(\n value: unknown,\n): InspectorLearningSnapshotV1 | undefined {\n if (\n !record(value) ||\n value.schemaVersion !== 1 ||\n !string(value.projectKey, 128) ||\n !string(value.snapshotVersion, 128) ||\n !integer(value.pendingThreadCount) ||\n !integer(value.pendingCandidateCount) ||\n !record(value.run) ||\n typeof value.run.hasActiveRun !== \"boolean\" ||\n typeof value.run.hasEverSucceeded !== \"boolean\"\n ) {\n return undefined;\n }\n const originUrl = parseInspectorLearningUrl(\n value.webAppOrigin,\n value.webAppOrigin,\n );\n if (!originUrl || new URL(originUrl).pathname !== \"/\") return undefined;\n const webAppOrigin = new URL(originUrl).origin;\n const configuration = parseConfiguration(value.configuration);\n const skillsPage = parsePage(value.skillsPage, 3, (item) =>\n parseSkill(item, webAppOrigin),\n );\n const insightsPage = parsePage(value.insightsPage, 4, (item) =>\n parseInsight(item, webAppOrigin),\n );\n if (!configuration || !skillsPage || !insightsPage) return undefined;\n let latest: InspectorLearningSnapshotV1[\"run\"][\"latest\"] = null;\n if (value.run.latest !== null) {\n const latestRun = value.run.latest;\n if (!record(latestRun)) {\n return undefined;\n }\n const { status, completedAt } = latestRun;\n if (\n typeof status !== \"string\" ||\n !runStatuses.has(status) ||\n (completedAt !== null && !date(completedAt))\n )\n return undefined;\n latest = {\n status: status as NonNullable<typeof latest>[\"status\"],\n completedAt: completedAt as NonNullable<typeof latest>[\"completedAt\"],\n };\n }\n if (!record(value.links)) return undefined;\n const learning = parseInspectorLearningUrl(\n value.links.learning,\n webAppOrigin,\n );\n const candidates =\n value.links.candidates === null\n ? null\n : parseInspectorLearningUrl(value.links.candidates, webAppOrigin);\n const runs =\n value.links.runs === null\n ? null\n : parseInspectorLearningUrl(value.links.runs, webAppOrigin);\n if (\n !learning ||\n candidates === undefined ||\n runs === undefined ||\n (value.pendingThreadCount > 0 && runs === null) ||\n (value.pendingCandidateCount > 0 && candidates === null)\n )\n return undefined;\n return {\n schemaVersion: 1,\n projectKey: value.projectKey,\n snapshotVersion: value.snapshotVersion,\n webAppOrigin,\n configuration,\n pendingThreadCount: value.pendingThreadCount,\n run: {\n hasActiveRun: value.run.hasActiveRun,\n hasEverSucceeded: value.run.hasEverSucceeded,\n latest,\n },\n pendingCandidateCount: value.pendingCandidateCount,\n skillsPage,\n insightsPage,\n links: { learning, candidates, runs },\n };\n}\n\n/** Normalizes the browser-owned request without accepting container scope. */\nexport function parseInspectorLearningRequestV1(\n value: unknown,\n): InspectorLearningRequestV1 | undefined {\n if (!record(value)) return undefined;\n if (\n Object.keys(value).some(\n (key) => ![\"agentId\", \"skillsPage\", \"insightsPage\"].includes(key),\n )\n ) {\n return undefined;\n }\n const agentId = value.agentId;\n const skillsPage = value.skillsPage;\n const insightsPage = value.insightsPage;\n if (agentId !== undefined && !string(agentId, 128)) return undefined;\n if (skillsPage !== undefined && !integer(skillsPage, 1)) return undefined;\n if (insightsPage !== undefined && !integer(insightsPage, 1)) return undefined;\n return {\n ...(agentId === undefined ? {} : { agentId }),\n ...(skillsPage === undefined ? {} : { skillsPage }),\n ...(insightsPage === undefined ? {} : { insightsPage }),\n };\n}\n","export interface InspectorVisibilityOptions {\n enableInspector?: boolean;\n isBrowser: boolean;\n isDevelopment: boolean;\n}\n\n/**\n * The Inspector is a development-only browser tool. Consumers may disable it,\n * but an explicit `true` never overrides a production or server environment.\n */\nexport function shouldEnableInspector({\n enableInspector,\n isBrowser,\n isDevelopment,\n}: InspectorVisibilityOptions): boolean {\n return isBrowser && isDevelopment && enableInspector !== false;\n}\n","import type { AgentCapabilities } from \"@ag-ui/core\";\n\nexport type MaybePromise<T> = T | PromiseLike<T>;\n\n/**\n * More specific utility for records with at least one key\n */\nexport type NonEmptyRecord<T> =\n T extends Record<string, unknown>\n ? keyof T extends never\n ? never\n : T\n : never;\n\n/**\n * Type representing an agent's basic information\n */\nexport interface AgentDescription {\n name: string;\n className: string;\n description: string;\n capabilities?: AgentCapabilities;\n}\n\nexport type RuntimeMode = \"sse\" | \"intelligence\";\n\nexport const RUNTIME_MODE_SSE = \"sse\" as const;\nexport const RUNTIME_MODE_INTELLIGENCE = \"intelligence\" as const;\n\nexport interface IntelligenceRuntimeInfo {\n wsUrl: string;\n}\n\nexport interface ThreadEndpointRuntimeInfo {\n list: boolean;\n inspect: boolean;\n mutations: boolean;\n realtimeMetadata: boolean;\n}\n\nexport type RuntimeLicenseStatus =\n | \"valid\"\n | \"none\"\n | \"expired\"\n | \"expiring\"\n | \"invalid\"\n | \"unknown\";\n\n/** Runtime entitlement authority resolved by a managed or self-hosted backend. */\ninterface RuntimeEntitlement {\n /** Whether the resolved entitlement currently grants product access. */\n active: boolean;\n /** Deployment authority that produced this entitlement. */\n source:\n | \"managedOrgSubscription\"\n | \"selfHostedDeploymentLicense\"\n | \"awsMarketplaceDeploymentLicense\";\n /** Boolean feature grants keyed by stable feature id. */\n features: Record<string, boolean>;\n /** Numeric limits keyed by stable feature id. */\n limits: Record<string, number>;\n /** Optional catalog plan code supplied by the entitlement authority. */\n planCode?: string;\n /** Optional lower-level source metadata supplied by the authority. */\n entitlementSource?: string;\n}\n\n/** Public diagnostic returned when Runtime entitlement resolution is not ready. */\ninterface RuntimeEntitlementError {\n /** Stable backend or SDK error code. */\n code: string;\n /** Safe human-readable diagnostic. */\n message: string;\n /** Whether a later resolution attempt may succeed without reconfiguration. */\n retryable: boolean;\n /** Optional originating request correlation id. */\n requestId?: string;\n /** Optional originating trace correlation id. */\n traceId?: string;\n}\n\n/** Successfully resolved Runtime entitlement response. */\ninterface RuntimeEntitlementReadyResponse {\n status: \"ready\";\n entitlement: RuntimeEntitlement;\n error?: never;\n}\n\n/** Structured non-ready Runtime entitlement response. */\ninterface RuntimeEntitlementErrorResponse {\n status: \"degraded\" | \"misconfigured\" | \"unavailable\";\n entitlement?: never;\n error: RuntimeEntitlementError;\n}\n\n/** Final structured Runtime entitlement response exposed through `/info`. */\nexport type RuntimeEntitlementResponse =\n | RuntimeEntitlementReadyResponse\n | RuntimeEntitlementErrorResponse;\n\nexport interface A2UIRuntimeInfo {\n enabled: boolean;\n /**\n * Agent ids the runtime applies A2UI to. When omitted, A2UI applies to\n * every agent served by the runtime.\n */\n agents?: string[];\n}\n\n/** Intelligence resource support available through a single runtime route. */\nexport interface SingleRouteRuntimeInfo {\n /** Whether the runtime accepts resource requests through the single route. */\n resourceOperations: boolean;\n /** Thread features available through the single-route resource bridge. */\n threadEndpoints: ThreadEndpointRuntimeInfo;\n}\n\nexport interface RuntimeInfo {\n version: string;\n agents: Record<string, AgentDescription>;\n audioFileTranscriptionEnabled: boolean;\n mode: RuntimeMode;\n intelligence?: IntelligenceRuntimeInfo;\n threadEndpoints?: ThreadEndpointRuntimeInfo;\n /** Optional capabilities exposed by runtimes that use one HTTP route. */\n singleRoute?: SingleRouteRuntimeInfo;\n /** Whether this runtime exposes trusted inspector metadata. */\n inspectorMetadata?: boolean;\n /** Whether this runtime exposes the debug-authorized Learning snapshot. */\n inspectorLearning?: boolean;\n /**\n * When true, the runtime exposes POST /agent/:agentId/suggest for stateless\n * suggestion generation. Absent on older runtimes; clients fall back to a\n * client-side agent run.\n */\n suggestions?: boolean;\n /**\n * @deprecated Use `a2ui` instead, which preserves per-agent scoping.\n * Kept for backward compatibility with older clients.\n */\n a2uiEnabled?: boolean;\n a2ui?: A2UIRuntimeInfo;\n openGenerativeUIEnabled?: boolean;\n /** Structured Runtime-level entitlement authority, when advertised. */\n runtimeEntitlements?: RuntimeEntitlementResponse;\n /** Legacy compatibility diagnostic retained for older Core/Inspector clients. */\n licenseStatus?: RuntimeLicenseStatus;\n telemetryDisabled?: boolean;\n}\n","import { v4 as uuidv4, validate, v5 as uuidv5 } from \"uuid\";\n\nexport function randomId() {\n return \"ck-\" + uuidv4();\n}\n\nexport function randomUUID() {\n return uuidv4();\n}\n\n/**\n * Recursively converts an object to a serializable form by converting functions to their string representation.\n */\nfunction toSerializable(value: unknown): unknown {\n if (typeof value === \"function\") {\n return value.toString();\n }\n if (Array.isArray(value)) {\n return value.map(toSerializable);\n }\n if (value !== null && typeof value === \"object\") {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n result[key] = toSerializable((value as Record<string, unknown>)[key]);\n }\n return result;\n }\n return value;\n}\n\nexport function dataToUUID(input: string | object, namespace?: string): string {\n const BASE_NAMESPACE = \"e4b01160-ff74-4c6e-9b27-d53cd930fe8e\";\n // Since namespace needs to be a uuid, we are creating a uuid for it.\n const boundNamespace = namespace\n ? uuidv5(namespace, BASE_NAMESPACE)\n : BASE_NAMESPACE;\n\n const stringInput =\n typeof input === \"string\" ? input : JSON.stringify(toSerializable(input));\n return uuidv5(stringInput, boundNamespace);\n}\n\nexport function isValidUUID(uuid: string) {\n return validate(uuid);\n}\n","/**\n * Safely read a Response/Request body with sensible defaults:\n * - clones the response/request to avoid consuming the original response/request\n * - Skips GET/HEAD\n * - Tries JSON first regardless of content-type\n * - Falls back to text and optionally parses when it \"looks\" like JSON\n */\nexport async function readBody<T extends Response | Request>(\n r: T,\n): Promise<unknown> {\n // skip GET/HEAD requests (unchanged)\n const method = \"method\" in r ? r.method.toUpperCase() : undefined;\n if (method === \"GET\" || method === \"HEAD\") {\n return undefined;\n }\n\n // no body at all → undefined (unchanged)\n if (!(\"body\" in r) || r.body == null) {\n return undefined;\n }\n\n // 1) try JSON (unchanged)\n try {\n return await r.clone().json();\n } catch {\n // 2) try text (unchanged + your whitespace/JSON-heuristic)\n try {\n const text = await r.clone().text();\n const trimmed = text.trim();\n\n if (trimmed.length === 0) return text;\n\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return text;\n }\n }\n return text;\n } catch {\n // 3) FINAL FALLBACK: manual read that accepts string or bytes\n try {\n const c = r.clone();\n const stream: ReadableStream | null = c.body ?? null;\n if (!stream) return undefined;\n\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let out = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (typeof value === \"string\") {\n out += value; // accept string chunks\n } else {\n out += decoder.decode(value, { stream: true }); // bytes\n }\n }\n out += decoder.decode(); // flush\n\n const trimmed = out.trim();\n if (trimmed.length === 0) return out;\n\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return out;\n }\n }\n return out;\n } catch {\n return undefined; // same \"give up\" behavior you had\n }\n }\n }\n}\n","import type { AssistantMessage, Message } from \"@ag-ui/core\";\n\n/**\n * Stable per-row view keys for chat transcripts, across backends that re-key a\n * message mid-stream. Shared by every frontend package, because the defect and\n * the correlation signal are in the message stream, not in any one framework.\n *\n * ## The problem\n *\n * A message's canonical `id` is not stable within a turn. LangChain stamps a\n * placeholder id on the first streamed chunk when the provider didn't supply\n * one (`chat_models.py`: `if chunk.message.id is None: chunk.message.id =\n * \"lc_run-\" + \"-\" + run_id`), then prefers any provider-assigned id it sees\n * while merging chunks (`messages/ai.py`, \"Ranks are defined by the order of\n * preference\"). The `MESSAGES_SNAPSHOT` therefore carries the provider's final\n * id (e.g. `resp_…`) for a message the client already knows as `lc_run--…`.\n *\n * Every framework destroys and recreates a row whose key changes, so keying\n * rows by `id` turned that swap into the visible HITL chat flash, where a\n * rendered approval card appears to reset during a tool's\n * `executing → complete` transition.\n *\n * This is provider-conditional: providers that stamp an id on every chunk (so\n * `chunk.message.id is None` never holds) never trigger a rename.\n *\n * ## The approach\n *\n * Tool-call ids survive the rename, so they are used as *anchors*: the first\n * message seen carrying a given tool call records the key it was assigned, and\n * any later message carrying that same tool call reuses it. The store is an\n * override table consulted before falling back to `message.id`. Resolving only\n * reads it; each render that reaches the DOM then records what it rendered:\n *\n * ```text\n * render 1 id=lc_run--1 no tools key = message.id = lc_run--1\n * commit 1 store {}\n * render 2 id=lc_run--1 tc call_A key = message.id = lc_run--1\n * commit 2 store { tc:call_A -> lc_run--1 }\n * render 3 id=resp_1 tc call_A key = store[tc:call_A]\n * = lc_run--1 (row survives)\n * commit 3 store unchanged\n * ```\n *\n * Recording the anchor at commit 2 — while the id is still stable — is what\n * makes render 3 resolvable. Note the fix does not depend on render 2\n * existing: a message born already carrying a tool call anchors on the first\n * render that commits it, under whatever id it holds then.\n *\n * ## Why an override table rather than keying rows by tool-call id\n *\n * Deriving the key from the tool call directly (`tc:<id>` whenever a tool call\n * is present) needs no state, but changes the key the moment a tool call\n * *appears* — so an assistant message that streams text and then calls a tool\n * is torn down on that transition, for every provider, whether or not it\n * renames. That trades a conditional flash for an unconditional one. Recording\n * an override keeps the key the row already had.\n *\n * ## Cost\n *\n * The store holds only `tc:<toolCallId>` entries, so a conversation with no\n * tool calls keeps an empty store and behaviour byte-identical to keying by\n * `id`. Size is bounded to the tool calls of the currently-rendered messages\n * (see `pruneRowKeyStore`), not the conversation length. Deleting the store\n * reverts to plain `id` keying.\n *\n * ## Known gaps\n *\n * - A text-only assistant message has no anchor, so it still re-keys. No\n * client-side correlation signal exists for it; the fix is stable ids\n * upstream.\n * - If the tool call's arrival and the id swap land in the same update, the\n * intermediate state never renders, the anchor is never recorded, and the\n * row is recreated as before. Correlating in the event-apply layer (i.e. in\n * the AG-UI client, which observes every intermediate state) would be immune.\n */\n\nconst TOOL_ANCHOR_PREFIX = \"tc:\";\n\nexport interface RowKeyStore {\n /**\n * `tc:<toolCallId>` → the row key first assigned to a message carrying that\n * tool call. Populated only for assistant messages that carry tool calls.\n */\n overrides: Map<string, string>;\n /**\n * Anchors carried by more than one message in the last rendered list. Such\n * an anchor identifies no single row, so it is never used to vend a key.\n */\n ambiguous: Set<string>;\n}\n\nexport function createRowKeyStore(): RowKeyStore {\n return { overrides: new Map(), ambiguous: new Set() };\n}\n\n/**\n * Anchors a message contributes. Only assistant tool calls qualify: LangChain's\n * id preference applies when merging `AIMessageChunk`s, so user message ids are\n * not renamed, and `role: \"tool\"` messages are not rendered as rows. Every tool\n * call is used (not just the first) so the anchor survives tool-call reordering\n * between snapshots.\n */\nfunction toolAnchorsOf(message: Message | undefined): string[] {\n if (message?.role !== \"assistant\") return [];\n const toolCalls = (message as AssistantMessage).toolCalls;\n if (!toolCalls?.length) return [];\n\n const anchors: string[] = [];\n for (const toolCall of toolCalls) {\n if (toolCall?.id) anchors.push(`${TOOL_ANCHOR_PREFIX}${toolCall.id}`);\n }\n return anchors;\n}\n\n/**\n * Resolves the row key for every message, returned by position.\n *\n * Pure: it reads `store` and never writes to it. Every framework here may\n * evaluate a render pass whose result never reaches the DOM — an abandoned\n * concurrent render in React, a discarded `computed` evaluation in Vue or\n * Angular. An anchor recorded by such a pass would vend its key to the pass\n * that does render, re-keying the row the user is looking at, which is the\n * teardown this module exists to prevent. Anchors are recorded by\n * `commitRowKeyStore`, from whichever phase each framework runs after the DOM\n * is updated.\n *\n * Uniqueness is structural rather than assumed: a caller that does not\n * deduplicate can pass two rows with the same id, and an override can vend a\n * key equal to a later message's own id.\n */\nexport function resolveRowRenderKeys(\n store: RowKeyStore,\n messages: readonly (Message | undefined)[],\n): string[] {\n const keys: string[] = [];\n const claimed = new Set<string>();\n\n messages.forEach((message, index) => {\n const anchors = toolAnchorsOf(message);\n\n // Reuse the key recorded for any of this message's anchors. An override\n // pointing at a key another row already claimed this pass is skipped: two\n // messages can share a tool-call id (upstream bug, or replayed state), and\n // the later one falls back to its own id instead.\n let key: string | undefined;\n for (const anchor of anchors) {\n if (store.ambiguous.has(anchor)) continue;\n const recorded = store.overrides.get(anchor);\n if (recorded !== undefined && !claimed.has(recorded)) {\n key = recorded;\n break;\n }\n }\n\n // The index fallback covers a message with no usable id.\n key ??= message?.id || `index-${index}`;\n\n if (claimed.has(key)) {\n let suffix = 2;\n while (claimed.has(`${key}:${suffix}`)) suffix += 1;\n key = `${key}:${suffix}`;\n }\n\n keys.push(key);\n claimed.add(key);\n });\n\n return keys;\n}\n\n/**\n * `message.id` → row key, for callers that render by message rather than by\n * position. `messages` must be deduplicated: duplicate ids would overwrite\n * each other in the returned map.\n */\nexport function resolveRowRenderKeysById(\n store: RowKeyStore,\n messages: readonly Message[],\n): Map<string, string> {\n const keys = resolveRowRenderKeys(store, messages);\n const byId = new Map<string, string>();\n messages.forEach((message, index) => {\n const key = keys[index];\n if (key !== undefined) byId.set(message.id, key);\n });\n return byId;\n}\n\n/**\n * Records the anchors of a rendered list, then bounds the store to it. Call\n * from the phase that runs after the DOM is updated, never while resolving —\n * see `resolveRowRenderKeys`.\n *\n * Re-resolving here reproduces the keys the rows were rendered with, because\n * the store cannot change between a render and its own post-render phase.\n *\n * An anchor carried by two rows in the same list is marked ambiguous rather\n * than recorded. Recording it would give the first row's key to whichever row\n * outlived the other, and with it that row's DOM and component state.\n */\nexport function commitRowKeyStore(\n store: RowKeyStore,\n messages: readonly (Message | undefined)[],\n): void {\n const keys = resolveRowRenderKeys(store, messages);\n\n const anchorCounts = new Map<string, number>();\n for (const message of messages) {\n for (const anchor of toolAnchorsOf(message)) {\n anchorCounts.set(anchor, (anchorCounts.get(anchor) ?? 0) + 1);\n }\n }\n\n // Ambiguity is a property of the rendered list, so it is recomputed rather\n // than accumulated: an anchor left alone by the row that shadowed it becomes\n // usable again.\n store.ambiguous.clear();\n for (const [anchor, count] of anchorCounts) {\n if (count > 1) {\n store.ambiguous.add(anchor);\n store.overrides.delete(anchor);\n }\n }\n\n // First claimant of an anchor owns it, so a re-keyed message resolves to the\n // key the row already had rather than overwriting it.\n messages.forEach((message, index) => {\n const key = keys[index];\n if (key === undefined) return;\n for (const anchor of toolAnchorsOf(message)) {\n if (store.ambiguous.has(anchor)) continue;\n if (!store.overrides.has(anchor)) store.overrides.set(anchor, key);\n }\n });\n\n pruneRowKeyStore(store, messages);\n}\n\n/**\n * Drops anchors no longer present in `messages`, bounding the store to the\n * tool calls of the currently-rendered messages. Called by\n * `commitRowKeyStore`; like it, this writes to the store and so belongs after\n * the DOM is updated, never while resolving.\n *\n * Pruned entries are unreachable by construction: `resolveRowRenderKeys` only\n * looks up anchors belonging to messages in the list it is given.\n */\nexport function pruneRowKeyStore(\n store: RowKeyStore,\n messages: readonly (Message | undefined)[],\n): void {\n const live = new Set<string>();\n for (const message of messages) {\n for (const anchor of toolAnchorsOf(message)) live.add(anchor);\n }\n\n for (const anchor of store.overrides.keys()) {\n if (!live.has(anchor)) store.overrides.delete(anchor);\n }\n for (const anchor of store.ambiguous) {\n if (!live.has(anchor)) store.ambiguous.delete(anchor);\n }\n}\n","export * from \"./clipboard\";\nexport * from \"./conditions\";\nexport * from \"./console-styling\";\nexport * from \"./errors\";\nexport * from \"./json-schema\";\nexport * from \"./inspector-metadata\";\nexport * from \"./inspector-learning\";\nexport * from \"./inspector-visibility\";\nexport * from \"./types\";\nexport * from \"./random-id\";\nexport * from \"./requests\";\nexport * from \"./row-render-keys\";\n\nimport * as PartialJSON from \"partial-json\";\n\n/**\n * Safely parses a JSON string into an object\n * @param json The JSON string to parse\n * @param fallback Optional fallback value to return if parsing fails. If not provided or set to \"unset\", returns null\n * @returns The parsed JSON object, or the fallback value (or null) if parsing fails\n */\nexport function parseJson(json: string, fallback: any = \"unset\") {\n try {\n return JSON.parse(json);\n } catch {\n return fallback === \"unset\" ? null : fallback;\n }\n}\n\n/**\n * Parses a partial/incomplete JSON string, returning as much valid data as possible.\n * Falls back to an empty object if parsing fails entirely.\n */\nexport function partialJSONParse(json: string) {\n try {\n const parsed = PartialJSON.parse(json);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n return {};\n } catch {\n return {};\n }\n}\n\n/**\n * Returns an exponential backoff function suitable for Phoenix.js\n * `reconnectAfterMs` and `rejoinAfterMs` options.\n *\n * @param baseMs - Initial delay for the first retry attempt.\n * @param maxMs - Upper bound — delays are capped at this value.\n *\n * Phoenix calls the returned function with a 1-based `tries` count.\n * The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.\n */\nexport function phoenixExponentialBackoff(\n baseMs: number,\n maxMs: number,\n): (tries: number) => number {\n return (tries: number) => Math.min(baseMs * 2 ** (tries - 1), maxMs);\n}\n\n/**\n * Maps an array of items to a new array, skipping items that throw errors during mapping\n * @param items The array to map\n * @param callback The mapping function to apply to each item\n * @returns A new array containing only the successfully mapped items\n */\nexport function tryMap<TItem, TMapped>(\n items: TItem[],\n callback: (item: TItem, index: number, array: TItem[]) => TMapped,\n): TMapped[] {\n return items.reduce<TMapped[]>((acc, item, index, array) => {\n try {\n acc.push(callback(item, index, array));\n } catch (error) {\n console.error(error);\n }\n return acc;\n }, []);\n}\n\n/**\n * Checks if the current environment is macOS\n * @returns {boolean} True if running on macOS, false otherwise\n */\nexport function isMacOS(): boolean {\n return /Mac|iMac|Macintosh/i.test(navigator.userAgent);\n}\n\n/**\n * Safely parses a JSON string into a tool arguments object.\n * Returns the parsed object only if it's a plain object (not an array, null, etc.).\n * Falls back to an empty object for any non-object JSON value or parse failure.\n */\nexport function safeParseToolArgs(raw: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n console.warn(\n `[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`,\n );\n return {};\n } catch {\n console.warn(\n \"[CopilotKit] Failed to parse tool arguments, falling back to empty object\",\n );\n return {};\n }\n}\n","export const COPILOT_CLOUD_API_URL = \"https://api.cloud.copilotkit.ai\";\nexport const COPILOT_CLOUD_VERSION = \"v1\";\nexport const COPILOT_CLOUD_CHAT_URL = `${COPILOT_CLOUD_API_URL}/copilotkit/${COPILOT_CLOUD_VERSION}`;\nexport const COPILOT_CLOUD_PUBLIC_API_KEY_HEADER =\n \"X-CopilotCloud-Public-Api-Key\";\n\nexport const DEFAULT_AGENT_ID = \"default\";\n\n/**\n * `RUN_ERROR` code the runtime sends when a run is rejected because the\n * thread already has one in flight. CopilotKit core reports it as\n * `agent_thread_locked`.\n */\nexport const THREAD_ALREADY_RUNNING_ERROR_CODE = \"THREAD_ALREADY_RUNNING\";\n\n/** Phoenix channel event name used for all AG-UI events. */\nexport const AG_UI_CHANNEL_EVENT = \"ag-ui\";\n","/**\n * Checks if telemetry is disabled via environment variables.\n * Users can opt out by setting:\n * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1\n * - DO_NOT_TRACK=true or DO_NOT_TRACK=1\n *\n * Lives in its own module so that the browser-facing root entry can\n * re-export it without pulling in `telemetry-client.ts`, whose\n * `@segment/analytics-node` import drags Node built-ins into browser\n * bundler module graphs. See the note in `../index.ts`.\n */\nexport function isTelemetryDisabled(): boolean {\n return (\n (process.env as Record<string, string | undefined>)\n .COPILOTKIT_TELEMETRY_DISABLED === \"true\" ||\n (process.env as Record<string, string | undefined>)\n .COPILOTKIT_TELEMETRY_DISABLED === \"1\" ||\n (process.env as Record<string, string | undefined>).DO_NOT_TRACK ===\n \"true\" ||\n (process.env as Record<string, string | undefined>).DO_NOT_TRACK === \"1\"\n );\n}\n","// Per-event telemetry metadata shared by both TelemetryClients.\n//\n// Two clients emit `oss.runtime.*`: the v1 client in this package and the\n// v2 client in @copilotkit/runtime. Neither samples the lambda sink any\n// more — that sink is ours, so anonymous volume costs us nothing per\n// event and full fidelity beats an extrapolation. One wire is still\n// gated: the Segment copy the v1 client sends, which is billed per event.\n//\n// Every event therefore still carries a sampling block, because the two\n// populations remain distinguishable and a Segment-sourced count still\n// needs sum(sampleWeight) to mean anything. On the lambda wire the block\n// reads sampleRate=1/sampleWeight=1, which is the honest answer rather\n// than a placeholder.\n//\n// The two clients computed this independently and drifted: v2 sampled but\n// stamped nothing, leaving ~24% of runtime volume unweightable from the\n// data alone (OSS-1017). Computing it here is what stops them drifting\n// again.\n\n/** The rate a sink that takes every event is \"gated\" at. */\nexport const UNSAMPLED_RATE = 1;\n\n/** Identifies which client emitted an event. */\nexport const TELEMETRY_EMITTER_V1 = \"v1-shared\";\nexport const TELEMETRY_EMITTER_V2 = \"v2-runtime\";\n\nexport type TelemetryEmitter =\n | typeof TELEMETRY_EMITTER_V1\n | typeof TELEMETRY_EMITTER_V2;\n\n/**\n * Which public API surface the developer built against.\n *\n * Separate from {@link TelemetryEmitter} on purpose. The emitter names a\n * client library, and there are six of them across four languages; the\n * surface answers the question anyone actually asks of this data, which\n * is how much traffic still arrives through the deprecated v1 API. The\n * native runtimes (Go, Python, Ruby, .NET) expose v2 only, so they report\n * `v2` without having a v1 notion of their own.\n */\n// `as const` so the values keep their literal types when they land in a\n// mutable object property, which is how the v1 shim passes the surface\n// into the V2 runtime's options.\nexport const TELEMETRY_SURFACE_V1 = \"v1\" as const;\nexport const TELEMETRY_SURFACE_V2 = \"v2\" as const;\n\nexport type TelemetrySurface =\n | typeof TELEMETRY_SURFACE_V1\n | typeof TELEMETRY_SURFACE_V2;\n\n/**\n * Which wire an event copy travelled on. The v1 client sends each capture\n * to both, so this is what tells the two copies apart downstream\n * (OSS-1019); the v2 client only ever sends to the lambda sink.\n */\nexport type TelemetryTransport = \"segment\" | \"lambda\";\n\nexport interface SamplingMeta {\n /** The rate this event was actually gated at: 1 when unsampled or identified. */\n sampleRate: number;\n sampleRateAdjustmentFactor: number;\n /** Multiply by this to extrapolate the population the event stands for. */\n sampleWeight: number;\n /** Whether the event bypassed the sample gate. */\n telemetry_identified: boolean;\n}\n\n/**\n * Compute the sampling block for one captured event.\n *\n * `telemetryId` is the caller's parsed license telemetry_id, or null when\n * anonymous — it decides the branch, and is deliberately not returned:\n * only the non-PII shape below travels on the event.\n *\n * `sampleRate` is the rate of the wire this copy travels on, so an\n * unsampled sink passes {@link UNSAMPLED_RATE}. Call it once per wire:\n * the v1 client sends one capture to two wires gated differently, and a\n * shared block would misweight one of them.\n */\nexport function computeSamplingMeta({\n telemetryId,\n sampleRate,\n}: {\n telemetryId: string | null;\n sampleRate: number;\n}): SamplingMeta {\n const identified = Boolean(telemetryId);\n // Identified events ship at a 100% effective rate, anonymous ones at\n // sampleRate. Computed per event because a single global weight would\n // overweight identified-customer counts by 1/sampleRate.\n const effectiveSampleRate = identified ? 1 : sampleRate;\n\n return {\n sampleRate: effectiveSampleRate,\n sampleRateAdjustmentFactor: 1 - effectiveSampleRate,\n sampleWeight: 1 / effectiveSampleRate,\n // Stated outright rather than inferred from sampleWeight === 1:\n // under COPILOTKIT_TELEMETRY_SAMPLE_RATE=1 anonymous events also\n // weigh 1, and the two populations stop being distinguishable\n // (OSS-1018).\n telemetry_identified: identified,\n };\n}\n","// Which endpoint the runtime sends completions to, as a closed vocabulary.\n//\n// The AI SDK's provider label cannot answer this. A model built by\n// `createOpenAI` reports only its wire API: `openai.responses` for both\n// api.openai.com and Azure (whose own migration guide tells customers to use\n// exactly that client), and `openai.chat` for OpenRouter and a laptop running\n// Ollama alike. So the provider field reports the wire protocol, and the host\n// reports the vendor.\n//\n// Only the classification travels. A base URL like\n// `myresource.openai.azure.com` carries the customer's Azure resource name,\n// which identifies them, so the raw host must never reach telemetry. That is\n// why this returns a member of a fixed list rather than anything derived from\n// the input.\n\n/**\n * Every value `classifyModelHost` can return.\n *\n * `other` means a host we observed and did not recognize: a gateway, a proxy,\n * or a vendor we have no rule for. `unknown` means we never saw a host at all,\n * which is the case when a caller hands us an already-built LanguageModel.\n * The two are not interchangeable — one is an unrecognized answer, the other\n * is a missing one, and they need different follow-up.\n */\nexport const MODEL_HOST_CLASSES = [\n \"openai\",\n \"azure\",\n \"openrouter\",\n \"anthropic\",\n \"google\",\n \"vertex\",\n \"bedrock\",\n \"groq\",\n \"unify\",\n \"minimax\",\n \"local\",\n \"other\",\n \"unknown\",\n] as const;\n\nexport type ModelHostClass = (typeof MODEL_HOST_CLASSES)[number];\n\n/**\n * Host suffixes mapped to their vendor.\n *\n * Matched on label boundaries, never as substrings, so\n * `myresource.openai.azure.com.attacker.test` does not read as Azure.\n */\nconst HOST_SUFFIXES: ReadonlyArray<readonly [string, ModelHostClass]> = [\n // Azure exposes the same models under three host families: the classic\n // Azure OpenAI host, the Foundry Models host, and the general Cognitive\n // Services host. All three are Azure for our purposes.\n [\"openai.azure.com\", \"azure\"],\n [\"services.ai.azure.com\", \"azure\"],\n [\"cognitiveservices.azure.com\", \"azure\"],\n // API Management fronting an Azure OpenAI deployment, a common enterprise\n // pattern. Reported as azure because that is what sits behind it.\n [\"azure-api.net\", \"azure\"],\n\n [\"api.openai.com\", \"openai\"],\n [\"openrouter.ai\", \"openrouter\"],\n [\"api.anthropic.com\", \"anthropic\"],\n [\"generativelanguage.googleapis.com\", \"google\"],\n // Vertex regional hosts are `<region>-aiplatform.googleapis.com`, which is\n // not a suffix of a single label, so both spellings are listed.\n [\"aiplatform.googleapis.com\", \"vertex\"],\n [\"api.groq.com\", \"groq\"],\n [\"api.unify.ai\", \"unify\"],\n [\"api.minimax.io\", \"minimax\"],\n [\"api.minimaxi.com\", \"minimax\"],\n];\n\n/** Suffixes that mean the model runs on the same machine or private network. */\nconst LOCAL_SUFFIXES = [\"localhost\", \"local\", \"internal\", \"docker.internal\"];\n\n/** Matches `<region>-aiplatform.googleapis.com` and the Bedrock regional hosts. */\nconst REGIONAL_HOST_PATTERNS: ReadonlyArray<readonly [RegExp, ModelHostClass]> =\n [\n [/^[a-z0-9-]+-aiplatform\\.googleapis\\.com$/, \"vertex\"],\n [/^bedrock[a-z0-9.-]*\\.[a-z0-9-]+\\.amazonaws\\.com$/, \"bedrock\"],\n ];\n\n/** True when `host` equals `suffix` or sits directly beneath it. */\nfunction matchesSuffix(host: string, suffix: string): boolean {\n return host === suffix || host.endsWith(`.${suffix}`);\n}\n\n/** True for loopback, unspecified, and RFC 1918 private addresses. */\nfunction isPrivateAddress(host: string): boolean {\n if (host === \"127.0.0.1\" || host === \"0.0.0.0\" || host === \"::1\") {\n return true;\n }\n // 127.0.0.0/8 is entirely loopback.\n if (host.startsWith(\"127.\")) return true;\n // 10.0.0.0/8 and 192.168.0.0/16.\n if (host.startsWith(\"10.\") || host.startsWith(\"192.168.\")) return true;\n // 172.16.0.0/12 is 172.16 through 172.31 only. 172.32 is public, so the\n // second octet is range-checked rather than prefix-matched.\n const privateClassB = /^172\\.(\\d{1,3})\\./.exec(host);\n if (privateClassB) {\n const secondOctet = Number(privateClassB[1]);\n return secondOctet >= 16 && secondOctet <= 31;\n }\n return false;\n}\n\n/**\n * Reduce a model endpoint to one of {@link MODEL_HOST_CLASSES}.\n *\n * @param baseUrl The endpoint the provider was configured with. Absent when\n * the provider was left on its own default, which is why `providerDefault`\n * exists: \"no base URL, provider is openai\" means api.openai.com.\n * @param providerDefault What to report when no base URL was supplied. Callers\n * that genuinely cannot observe a host — a pre-built LanguageModel handed in\n * by the developer — leave this alone and get `unknown`.\n */\nexport function classifyModelHost(\n baseUrl?: string | null,\n providerDefault: ModelHostClass = \"unknown\",\n): ModelHostClass {\n const trimmed = baseUrl?.trim();\n if (!trimmed) {\n return providerDefault;\n }\n\n let host: string;\n try {\n // `hostname` drops the port, the path, the query and any credentials, so\n // nothing but the host can survive into the return value below.\n host = new URL(trimmed).hostname.toLowerCase();\n } catch {\n // We were given something and could not read it. That is a different fact\n // from having been given nothing, so it does not fall back to the default.\n return \"other\";\n }\n\n // IPv6 hostnames arrive bracketed from the URL parser.\n host = host.replace(/^\\[|\\]$/g, \"\");\n\n if (!host) return \"other\";\n\n if (isPrivateAddress(host)) return \"local\";\n for (const suffix of LOCAL_SUFFIXES) {\n if (matchesSuffix(host, suffix)) return \"local\";\n }\n\n for (const [suffix, hostClass] of HOST_SUFFIXES) {\n if (matchesSuffix(host, suffix)) return hostClass;\n }\n\n for (const [pattern, hostClass] of REGIONAL_HOST_PATTERNS) {\n if (pattern.test(host)) return hostClass;\n }\n\n return \"other\";\n}\n","// Telemetry sink client.\n//\n// Posts events to a CopilotKit-controlled telemetry-sink endpoint, which\n// fans out to Scarf, Reo, and any future destinations. Replaces the direct\n// per-vendor calls (formerly a Scarf-specific client) so that vendor changes\n// don't require SDK releases and so that downstream services we don't want\n// exposed to OSS readers (e.g. the email-enrichment service backing Reo) stay\n// private.\n//\n// Two attribution modes:\n// - Identified: a standalone telemetry id or a CopilotKit license token is\n// configured. Standalone identity takes precedence. License tokens are\n// JWTs (header.payload.sig) whose payload carries `telemetry_id`; the SDK\n// base64url-decodes the payload — without verifying the Ed25519 signature,\n// which is the license-verifier's job. The resolved identity is emitted\n// only via `X-CopilotKit-Telemetry-Id`.\n// - Anonymous: no license token, or a malformed/non-JWT one. No\n// telemetry-id header; events still flow, attribution is best-effort\n// from request-level signals (IP, UA).\n//\n// Note: CopilotCloud customer API keys (`ck_<env>_<id>.<secret>`) are\n// unrelated to telemetry attribution. They flow into Segment / PostHog\n// via the v1 shared TelemetryClient and never reach this code path.\n//\n// Best-effort: every error is swallowed. Telemetry must not break the\n// host application.\n\nconst TELEMETRY_SINK_URL =\n (typeof process !== \"undefined\" && process.env?.COPILOTKIT_TELEMETRY_URL) ||\n \"https://telemetry.copilotkit.ai/ingest\";\n\nconst FETCH_TIMEOUT_MS = 3000;\nconst TELEMETRY_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\nexport interface LambdaSendOptions {\n event: string;\n properties?: Record<string, unknown>;\n globalProperties?: Record<string, unknown>;\n packageName?: string;\n packageVersion?: string;\n /** Standalone analytics identity, resolved before any legacy license claim. */\n telemetryId?: string;\n // The CopilotKit license token (Ed25519-signed JWT), when one is\n // configured on the runtime. The sender base64url-decodes the payload\n // segment to extract `telemetry_id`; missing or malformed tokens\n // produce an anonymous send.\n licenseToken?: string;\n}\n\n/**\n * Return the first telemetry identity accepted by the ingest service.\n *\n * Empty and whitespace-only values are unconfigured placeholders and must not\n * suppress a later identity source. Leading and trailing HTTP spaces and tabs\n * are removed before validation. The ingest service accepts 1 to 128 ASCII\n * letters, digits, underscores, and hyphens.\n *\n * @internal\n */\nexport function firstNonBlankTelemetryId(\n ...candidates: ReadonlyArray<string | undefined>\n): string | undefined {\n for (const candidate of candidates) {\n if (candidate === undefined) {\n continue;\n }\n\n const normalized = candidate.replace(/^[\\t ]+|[\\t ]+$/g, \"\");\n if (TELEMETRY_ID_PATTERN.test(normalized)) {\n return normalized;\n }\n }\n\n return undefined;\n}\n\n// These fields aren't used by the telemetry service, so we strip them\n// at the wire boundary rather than rely on every caller to omit them.\n// Both the snake_case and camelCase variants are listed because callers\n// upstream use different conventions.\nconst STRIPPED_KEYS = new Set([\"cloud.public_api_key\", \"cloud.publicApiKey\"]);\n\nfunction stripCloudKeys(\n obj: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n if (!obj) return {};\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n if (!STRIPPED_KEYS.has(k)) out[k] = v;\n }\n return out;\n}\n\n// Pull telemetry_id out of a CopilotKit license token without verifying\n// the signature. The token shape is a standard JWT\n// (`<header>.<payload>.<sig>`) with base64url-encoded segments; the\n// payload is UTF-8 JSON with a telemetry_id accepted by the ingest service.\n//\n// Verification (Ed25519, key rotation, expiry) is the license-verifier\n// package's job. For telemetry attribution we only need the claimed id —\n// the trust model is claim-only on the Lambda side anyway.\n//\n// Exported so TelemetryClient setters can detect unparseable tokens at\n// configuration time and surface a single warning, instead of silently\n// emitting anonymous events on every capture.\nexport function parseTelemetryIdFromLicense(token?: string): string | null {\n if (!token) return null;\n const parts = token.split(\".\");\n if (parts.length !== 3) return null;\n try {\n const payload = parts[1];\n if (!/^[A-Za-z0-9_-]+$/.test(payload) || payload.length % 4 === 1) {\n return null;\n }\n\n let b64 = payload.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = (4 - (b64.length % 4)) % 4;\n b64 += \"=\".repeat(padding);\n const json =\n typeof Buffer !== \"undefined\"\n ? Buffer.from(b64, \"base64\").toString(\"utf8\")\n : new TextDecoder().decode(\n Uint8Array.from(atob(b64), (character) => character.charCodeAt(0)),\n );\n const decoded = JSON.parse(json) as { telemetry_id?: unknown };\n const telemetryId =\n typeof decoded.telemetry_id === \"string\"\n ? decoded.telemetry_id\n : undefined;\n return firstNonBlankTelemetryId(telemetryId) ?? null;\n } catch {\n return null;\n }\n}\n\n// Parse the telemetry_id from a license token AND emit the rollout smoke\n// signal if the parse returned null. Returning the parsed id lets callers\n// cache it in one step (avoiding a second parseTelemetryIdFromLicense\n// pass) while keeping the warn text in lockstep between v1 (shared) and\n// v2 (runtime) TelemetryClient.setLicenseToken.\nexport function parseAndWarnTelemetryId(licenseToken: string): string | null {\n const telemetryId = parseTelemetryIdFromLicense(licenseToken);\n if (!telemetryId) {\n console.warn(\n \"[CopilotKit] License token did not yield a telemetry_id; telemetry events will be sent anonymously.\",\n );\n }\n return telemetryId;\n}\n\nexport async function send(opts: LambdaSendOptions): Promise<void> {\n try {\n const body = JSON.stringify({\n event: opts.event,\n properties: stripCloudKeys(opts.properties),\n global_properties: stripCloudKeys(opts.globalProperties),\n package: {\n name: opts.packageName,\n version: opts.packageVersion,\n },\n ts: Math.floor(Date.now() / 1000),\n });\n\n const telemetryId =\n firstNonBlankTelemetryId(opts.telemetryId) ??\n parseTelemetryIdFromLicense(opts.licenseToken);\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": opts.packageName\n ? `CopilotKit-Runtime/${opts.packageVersion ?? \"unknown\"} (${opts.packageName})`\n : \"CopilotKit-Runtime\",\n };\n if (telemetryId) {\n headers[\"X-CopilotKit-Telemetry-Id\"] = telemetryId;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);\n try {\n await fetch(TELEMETRY_SINK_URL, {\n method: \"POST\",\n headers,\n body,\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timeoutId);\n }\n } catch {\n // Silent failure — telemetry must not break the application.\n }\n}\n\nexport const lambdaClient = { send };\n","/**\n * Granular debug configuration for CopilotKit runtime and client.\n * Pass `true` to enable events + lifecycle logging (but NOT verbose payloads),\n * or an object for granular control including `verbose: true` for full payloads.\n */\nexport type DebugConfig =\n | boolean\n | {\n /** Log every event emitted/received. Default: true */\n events?: boolean;\n /** Log request/run lifecycle. Default: true */\n lifecycle?: boolean;\n /** Log full event payloads instead of summaries. Default: false — must be explicitly opted in */\n verbose?: boolean;\n };\n\n/** Normalized debug configuration — all fields resolved to booleans. */\nexport interface ResolvedDebugConfig {\n enabled: boolean;\n events: boolean;\n lifecycle: boolean;\n verbose: boolean;\n}\n\n/** The all-off config used when debug is falsy. */\nconst DEBUG_OFF: ResolvedDebugConfig = {\n enabled: false,\n events: false,\n lifecycle: false,\n verbose: false,\n};\n\n/**\n * Normalizes a DebugConfig value into a ResolvedDebugConfig.\n *\n * - `false` / `undefined` → all off\n * - `true` → events + lifecycle on, verbose off (no PII in logs)\n * - object → merges with defaults (events: true, lifecycle: true, verbose: false)\n */\nexport function resolveDebugConfig(\n debug: DebugConfig | undefined,\n): ResolvedDebugConfig {\n if (!debug) return DEBUG_OFF;\n\n if (debug === true) {\n return { enabled: true, events: true, lifecycle: true, verbose: false };\n }\n\n const events = debug.events ?? true;\n const lifecycle = debug.lifecycle ?? true;\n const enabled = events || lifecycle;\n const verbose = enabled && (debug.verbose ?? false);\n\n return { enabled, events, lifecycle, verbose };\n}\n","import type {\n StandardSchemaV1,\n StandardJSONSchemaV1,\n} from \"@standard-schema/spec\";\n\nexport type { StandardSchemaV1, StandardJSONSchemaV1 };\n\n/**\n * Extract the Output type from a StandardSchemaV1 schema.\n * Replaces `z.infer<S>` for generic schema inference.\n */\nexport type InferSchemaOutput<S> =\n S extends StandardSchemaV1<any, infer O> ? O : never;\n\nexport interface SchemaToJsonSchemaOptions {\n /**\n * Injected `zodToJsonSchema` function so that `shared` does not depend on\n * `zod-to-json-schema`. Required when the schema is a Zod v3 schema that\n * does not implement Standard JSON Schema V1.\n */\n zodToJsonSchema?: (\n schema: unknown,\n options?: { $refStrategy?: string },\n ) => Record<string, unknown>;\n}\n\n/**\n * Check whether a schema implements the Standard JSON Schema V1 protocol.\n */\nfunction hasStandardJsonSchema(\n schema: StandardSchemaV1,\n): schema is StandardSchemaV1 & StandardJSONSchemaV1 {\n const props = schema[\"~standard\"];\n return (\n props != null &&\n typeof props === \"object\" &&\n \"jsonSchema\" in props &&\n props.jsonSchema != null &&\n typeof props.jsonSchema === \"object\" &&\n \"input\" in props.jsonSchema &&\n typeof props.jsonSchema.input === \"function\"\n );\n}\n\n/**\n * Convert any StandardSchemaV1-compatible schema to a JSON Schema object.\n *\n * Strategy:\n * 1. If the schema implements Standard JSON Schema V1 (`~standard.jsonSchema`),\n * call `schema['~standard'].jsonSchema.input({ target: 'draft-07' })`.\n * 2. If the schema exposes a `toJSONSchema()` method (Zod v4), call it directly.\n * 3. If the schema is a Zod v3 schema (`~standard.vendor === 'zod'`), use the\n * injected `zodToJsonSchema()` function.\n * 4. Otherwise throw a descriptive error.\n */\nexport function schemaToJsonSchema(\n schema: StandardSchemaV1,\n options?: SchemaToJsonSchemaOptions,\n): Record<string, unknown> {\n // 1. Standard JSON Schema V1\n if (hasStandardJsonSchema(schema)) {\n return schema[\"~standard\"].jsonSchema.input({ target: \"draft-07\" });\n }\n\n // 2. Zod v4 native — exposes toJSONSchema() on the schema itself\n if (typeof (schema as any).toJSONSchema === \"function\") {\n return (schema as any).toJSONSchema() as Record<string, unknown>;\n }\n\n // 3. Zod v3 fallback\n const vendor = schema[\"~standard\"].vendor;\n if (vendor === \"zod\" && options?.zodToJsonSchema) {\n return options.zodToJsonSchema(schema, { $refStrategy: \"none\" });\n }\n\n throw new Error(\n `Cannot convert schema to JSON Schema. The schema (vendor: \"${vendor}\") does not implement Standard JSON Schema V1 ` +\n `and no zodToJsonSchema fallback is available. ` +\n `Use a library that supports Standard JSON Schema (e.g., Zod 3.24+, Valibot v1+, ArkType v2+) ` +\n `or pass a zodToJsonSchema function in options.`,\n );\n}\n","import type { InputContent } from \"@ag-ui/core\";\nimport type { Attachment } from \"./types\";\n\n/** Build the AG-UI content part used when sending a ready attachment. */\nexport function createAttachmentContent(\n attachment: Pick<Attachment, \"type\" | \"source\" | \"filename\" | \"metadata\">,\n): InputContent {\n return {\n type: attachment.type,\n source: attachment.source,\n metadata: {\n ...(attachment.filename ? { filename: attachment.filename } : {}),\n ...attachment.metadata,\n },\n };\n}\n","import type { AttachmentModality } from \"./types\";\nimport type { InputContentSource } from \"../types/message\";\n\nconst DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20MB\n\n/**\n * Derive the attachment modality from a MIME type string.\n */\nexport function getModalityFromMimeType(mimeType: string): AttachmentModality {\n if (mimeType.startsWith(\"image/\")) return \"image\";\n if (mimeType.startsWith(\"audio/\")) return \"audio\";\n if (mimeType.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\n/**\n * Format a byte count as a human-readable file size string.\n */\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Check if a file exceeds the maximum allowed size.\n */\nexport function exceedsMaxSize(\n file: File,\n maxSize: number = DEFAULT_MAX_SIZE,\n): boolean {\n return file.size > maxSize;\n}\n\n/**\n * Read a File as a base64 string (without the data URL prefix).\n */\nexport function readFileAsBase64(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = (e) => {\n const result = e.target?.result as string;\n const base64 = result?.split(\",\")[1];\n if (base64) {\n resolve(base64);\n } else {\n reject(new Error(\"Failed to read file as base64\"));\n }\n };\n reader.onerror = reject;\n reader.readAsDataURL(file);\n });\n}\n\n/**\n * Generate a thumbnail data URL from a video file by capturing a frame near the start (at 0.1s).\n * Returns undefined if thumbnail generation fails or if called outside a browser environment.\n */\nexport function generateVideoThumbnail(\n file: File,\n): Promise<string | undefined> {\n if (typeof document === \"undefined\") {\n return Promise.resolve(undefined);\n }\n return new Promise((resolve) => {\n let resolved = false;\n const video = document.createElement(\"video\");\n const canvas = document.createElement(\"canvas\");\n const url = URL.createObjectURL(file);\n\n const cleanup = (result: string | undefined) => {\n if (resolved) return;\n resolved = true;\n URL.revokeObjectURL(url);\n resolve(result);\n };\n\n const timeout = setTimeout(() => {\n console.warn(\n `[CopilotKit] generateVideoThumbnail: timed out for file \"${file.name}\"`,\n );\n cleanup(undefined);\n }, 10000);\n\n video.preload = \"metadata\";\n video.muted = true;\n video.playsInline = true;\n\n video.onloadeddata = () => {\n video.currentTime = 0.1;\n };\n\n video.onseeked = () => {\n clearTimeout(timeout);\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext(\"2d\");\n if (ctx) {\n ctx.drawImage(video, 0, 0);\n const thumbnail = canvas.toDataURL(\"image/jpeg\", 0.7);\n cleanup(thumbnail);\n } else {\n console.warn(\n \"[CopilotKit] generateVideoThumbnail: could not get 2d canvas context\",\n );\n cleanup(undefined);\n }\n };\n\n video.onerror = () => {\n clearTimeout(timeout);\n console.warn(\n `[CopilotKit] generateVideoThumbnail: video element error for file \"${file.name}\"`,\n );\n cleanup(undefined);\n };\n\n video.src = url;\n });\n}\n\n/**\n * Check if a file's MIME type matches an accept filter string.\n * Handles file extensions (e.g. \".pdf\"), MIME wildcards (\"image/*\"), and comma-separated lists.\n */\nexport function matchesAcceptFilter(file: File, accept: string): boolean {\n if (!accept || accept === \"*/*\") return true;\n\n const filters = accept.split(\",\").map((f) => f.trim());\n return filters.some((filter) => {\n if (filter.startsWith(\".\")) {\n return (file.name ?? \"\").toLowerCase().endsWith(filter.toLowerCase());\n }\n if (filter.endsWith(\"/*\")) {\n const prefix = filter.slice(0, -2);\n return file.type.startsWith(prefix + \"/\");\n }\n return file.type === filter;\n });\n}\n\n/**\n * Convert an InputContentSource to a usable URL string.\n * For data sources, returns a base64 data URL; for URL sources, returns the URL directly.\n * A provider file handle (AG-UI 1.0 `file` source) has no address a browser\n * can load, so it returns an empty string and the caller shows no preview.\n */\nexport function getSourceUrl(source: InputContentSource): string {\n if (source.type === \"url\") {\n return source.value;\n }\n if (source.type === \"file\") {\n return \"\";\n }\n return `data:${source.mimeType};base64,${source.value}`;\n}\n\n/**\n * Return a short human-readable label for a document MIME type (e.g. \"PDF\", \"DOC\").\n */\nexport function getDocumentIcon(mimeType: string): string {\n if (mimeType.includes(\"pdf\")) return \"PDF\";\n if (mimeType.includes(\"sheet\") || mimeType.includes(\"excel\")) return \"XLS\";\n if (mimeType.includes(\"presentation\") || mimeType.includes(\"powerpoint\"))\n return \"PPT\";\n if (mimeType.includes(\"word\") || mimeType.includes(\"document\")) return \"DOC\";\n if (mimeType.includes(\"text/\")) return \"TXT\";\n return \"FILE\";\n}\n","export const logger = console;\n","import type { BaseEvent, RunErrorEvent } from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\n\nexport interface FinalizeRunOptions {\n stopRequested?: boolean;\n interruptionMessage?: string;\n /**\n * The `protocolVersion` the client declared on its RunAgentInput. When it is\n * set, a stopped run finishes with the AG-UI 1.0 `cancelled` outcome. A\n * client that declares no version predates 1.0 and cannot parse that\n * outcome, so it gets the plain RUN_FINISHED it always got.\n */\n protocolVersion?: string;\n}\n\nexport interface RunEventFinalizer {\n /** Observe one streamed event. Only the ids of open lifecycles are kept. */\n observe(event: BaseEvent): void;\n /** Return the events that close an interrupted or abruptly ended stream. */\n finalize(options?: FinalizeRunOptions): BaseEvent[];\n}\n\nconst defaultStopMessage = \"Run stopped by user\";\nconst defaultAbruptEndMessage = \"Run ended without emitting a terminal event\";\n\ninterface OpenToolCall {\n hasEnd: boolean;\n hasResult: boolean;\n}\n\n/**\n * Incremental finalizer for a streamed AG-UI run. Feed every event to\n * `observe`; when the stream ends without a terminal event, `finalize` returns\n * the closers for reasoning, text messages and tool calls still open plus a\n * terminal event. AG-UI 1.0 fails a run that ends with reasoning still open,\n * so reasoning is closed too. It also fails a RUN_FINISHED while a subagent\n * is still open, so a stop closes open subagents as well; a RUN_ERROR\n * abandons them, which the protocol allows. Closed lifecycles are forgotten at once and payloads are never kept,\n * so a caller does not have to retain the event array for this purpose.\n */\nexport function createRunEventFinalizer(): RunEventFinalizer {\n const openMessageIds = new Set<string>();\n const openReasoningMessageIds = new Set<string>();\n const openReasoningSpanIds = new Set<string>();\n const openToolCalls = new Map<string, OpenToolCall>();\n // Insertion order is start order, so closing in reverse closes children first.\n const openSubagentRunIds = new Set<string>();\n let runIdentity: { threadId?: string; runId?: string } = {};\n let terminalEventObserved = false;\n\n const clearOpen = () => {\n openMessageIds.clear();\n openReasoningMessageIds.clear();\n openReasoningSpanIds.clear();\n openToolCalls.clear();\n openSubagentRunIds.clear();\n };\n\n const observe = (event: BaseEvent) => {\n if (terminalEventObserved) return;\n\n switch (event.type) {\n case EventType.RUN_STARTED: {\n const { threadId, runId } = event as {\n threadId?: string;\n runId?: string;\n };\n runIdentity = { threadId, runId };\n break;\n }\n case EventType.REASONING_START:\n case EventType.REASONING_END:\n case EventType.REASONING_MESSAGE_START:\n case EventType.REASONING_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId !== \"string\") break;\n const open =\n event.type === EventType.REASONING_START ||\n event.type === EventType.REASONING_END\n ? openReasoningSpanIds\n : openReasoningMessageIds;\n if (\n event.type === EventType.REASONING_START ||\n event.type === EventType.REASONING_MESSAGE_START\n ) {\n open.add(messageId);\n } else {\n open.delete(messageId);\n }\n break;\n }\n case EventType.TEXT_MESSAGE_START: {\n const messageId = (event as { messageId?: string }).messageId;\n if (messageId) openMessageIds.add(messageId);\n break;\n }\n case EventType.TEXT_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") openMessageIds.delete(messageId);\n break;\n }\n case EventType.TOOL_CALL_START: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (toolCallId && !openToolCalls.has(toolCallId)) {\n openToolCalls.set(toolCallId, { hasEnd: false, hasResult: false });\n }\n break;\n }\n case EventType.TOOL_CALL_END:\n case EventType.TOOL_CALL_RESULT: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (!toolCallId) break;\n const info = openToolCalls.get(toolCallId);\n if (!info) break;\n\n if (event.type === EventType.TOOL_CALL_END) info.hasEnd = true;\n else info.hasResult = true;\n if (info.hasEnd && info.hasResult) openToolCalls.delete(toolCallId);\n break;\n }\n case EventType.SUBAGENT_STARTED:\n case EventType.SUBAGENT_FINISHED:\n case EventType.SUBAGENT_ERROR: {\n const subagentRunId = (event as { subagentRunId?: string })\n .subagentRunId;\n if (!subagentRunId) break;\n if (event.type === EventType.SUBAGENT_STARTED) {\n openSubagentRunIds.add(subagentRunId);\n } else {\n openSubagentRunIds.delete(subagentRunId);\n }\n break;\n }\n case EventType.RUN_FINISHED:\n case EventType.RUN_ERROR:\n terminalEventObserved = true;\n clearOpen();\n break;\n default:\n break;\n }\n };\n\n const finalize = (options: FinalizeRunOptions = {}): BaseEvent[] => {\n if (terminalEventObserved) return [];\n\n const { stopRequested = false, interruptionMessage } = options;\n const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;\n const resolvedAbruptMessage =\n interruptionMessage && interruptionMessage !== defaultStopMessage\n ? interruptionMessage\n : defaultAbruptEndMessage;\n const appended: BaseEvent[] = [];\n\n // A reasoning message closes before the span that holds it.\n for (const messageId of openReasoningMessageIds) {\n appended.push({\n type: EventType.REASONING_MESSAGE_END,\n messageId,\n } as BaseEvent);\n }\n for (const messageId of openReasoningSpanIds) {\n appended.push({ type: EventType.REASONING_END, messageId } as BaseEvent);\n }\n\n for (const messageId of openMessageIds) {\n appended.push({\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n } as BaseEvent);\n }\n\n for (const [toolCallId, info] of openToolCalls) {\n if (!info.hasEnd) {\n appended.push({\n type: EventType.TOOL_CALL_END,\n toolCallId,\n } as BaseEvent);\n }\n\n if (!info.hasResult) {\n appended.push({\n type: EventType.TOOL_CALL_RESULT,\n toolCallId,\n messageId: `${toolCallId}-result`,\n role: \"tool\",\n content: JSON.stringify(\n stopRequested\n ? {\n status: \"stopped\",\n reason: \"stop_requested\",\n message: resolvedStopMessage,\n }\n : {\n status: \"error\",\n reason: \"missing_terminal_event\",\n message: resolvedAbruptMessage,\n },\n ),\n } as BaseEvent);\n }\n }\n\n if (stopRequested) {\n // Newest first, so a nested subagent closes before its parent. An index\n // loop, because `toReversed` is ES2023 and this package targets older.\n const openIds = [...openSubagentRunIds];\n for (let index = openIds.length - 1; index >= 0; index -= 1) {\n appended.push({\n type: EventType.SUBAGENT_ERROR,\n subagentRunId: openIds[index],\n message: resolvedStopMessage,\n code: \"CANCELLED\",\n } as BaseEvent);\n }\n appended.push({\n type: EventType.RUN_FINISHED,\n ...(runIdentity.threadId !== undefined\n ? { threadId: runIdentity.threadId }\n : {}),\n ...(runIdentity.runId !== undefined\n ? { runId: runIdentity.runId }\n : {}),\n ...(options.protocolVersion !== undefined\n ? { outcome: { type: \"cancelled\" } }\n : {}),\n } as BaseEvent);\n } else {\n const errorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: resolvedAbruptMessage,\n code: \"INCOMPLETE_STREAM\",\n };\n appended.push(errorEvent);\n }\n\n terminalEventObserved = true;\n clearOpen();\n return appended;\n };\n\n return { observe, finalize };\n}\n\n/**\n * Array form of {@link createRunEventFinalizer} for callers that already keep\n * the run's events (runners persist them). Appends the closers to `events` in\n * place and returns them.\n */\nexport function finalizeRunEvents(\n events: BaseEvent[],\n options: FinalizeRunOptions = {},\n): BaseEvent[] {\n const finalizer = createRunEventFinalizer();\n for (const event of events) finalizer.observe(event);\n\n const appended = finalizer.finalize(options);\n events.push(...appended);\n return appended;\n}\n","import type { BaseEvent } from \"@ag-ui/client\";\n\n/**\n * The only AG-UI 1.0 events whose schema declares `threadId` and `runId`.\n * Plain literals, not `EventType`: a value import of `@ag-ui/client` here put\n * the client and its zod validators into the initial chunk of every app that\n * imports `@copilotkit/shared`.\n */\nconst RUN_IDENTITY_EVENTS = new Set<string>([\"RUN_STARTED\", \"RUN_FINISHED\"]);\n\n/**\n * Removes the routing fields that the Intelligence runner stamps on every\n * event it sends to the gateway (`thread_id`, `run_id`, and `threadId` /\n * `runId` on events that do not declare them).\n *\n * The gateway relays these payloads unchanged. AG-UI 1.0 strips unknown\n * fields before subscribers see them and warns once per field, per event,\n * so a streamed answer would log hundreds of warnings. Call this where a\n * gateway payload enters an AG-UI pipeline. The gateway still receives the\n * fields, because the runner adds them after this point.\n */\nexport function stripIntelligenceRoutingFields<T extends BaseEvent>(\n event: T,\n): T {\n const record = event as T & Record<string, unknown>;\n const keepRunIdentity = RUN_IDENTITY_EVENTS.has(record.type);\n if (\n !(\"thread_id\" in record) &&\n !(\"run_id\" in record) &&\n (keepRunIdentity || (!(\"threadId\" in record) && !(\"runId\" in record)))\n ) {\n return event;\n }\n const { thread_id: _t, run_id: _r, ...rest } = record;\n if (!keepRunIdentity) {\n delete rest.threadId;\n delete rest.runId;\n }\n return rest as unknown as T;\n}\n","/**\n * Error codes for transcription HTTP responses.\n * Uses snake_case to align with existing CopilotKitCoreErrorCode pattern.\n * These codes are returned by the runtime and parsed by the client.\n */\nexport enum TranscriptionErrorCode {\n /** Transcription service not configured in runtime */\n SERVICE_NOT_CONFIGURED = \"service_not_configured\",\n /** Audio format not supported */\n INVALID_AUDIO_FORMAT = \"invalid_audio_format\",\n /** Audio file is too long */\n AUDIO_TOO_LONG = \"audio_too_long\",\n /** Audio file is empty or too short */\n AUDIO_TOO_SHORT = \"audio_too_short\",\n /** Rate limited by transcription provider */\n RATE_LIMITED = \"rate_limited\",\n /** Authentication failed with transcription provider */\n AUTH_FAILED = \"auth_failed\",\n /** Transcription provider returned an error */\n PROVIDER_ERROR = \"provider_error\",\n /** Network error during transcription */\n NETWORK_ERROR = \"network_error\",\n /** Invalid request format */\n INVALID_REQUEST = \"invalid_request\",\n}\n\n/**\n * Error response format returned by the transcription endpoint.\n */\nexport interface TranscriptionErrorResponse {\n error: TranscriptionErrorCode;\n message: string;\n retryable?: boolean;\n}\n\n/**\n * Helper functions to create transcription error responses.\n * Used by the runtime to return consistent error responses.\n */\nexport const TranscriptionErrors = {\n serviceNotConfigured: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.SERVICE_NOT_CONFIGURED,\n message: \"Transcription service is not configured\",\n retryable: false,\n }),\n\n invalidAudioFormat: (\n format: string,\n supported: string[],\n ): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.INVALID_AUDIO_FORMAT,\n message: `Unsupported audio format: ${format}. Supported: ${supported.join(\", \")}`,\n retryable: false,\n }),\n\n invalidRequest: (details: string): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.INVALID_REQUEST,\n message: details,\n retryable: false,\n }),\n\n rateLimited: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.RATE_LIMITED,\n message: \"Rate limited. Please try again later.\",\n retryable: true,\n }),\n\n authFailed: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.AUTH_FAILED,\n message: \"Authentication failed with transcription provider\",\n retryable: false,\n }),\n\n providerError: (message: string): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.PROVIDER_ERROR,\n message,\n retryable: true,\n }),\n\n networkError: (\n message: string = \"Network error during transcription\",\n ): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.NETWORK_ERROR,\n message,\n retryable: true,\n }),\n\n audioTooLong: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.AUDIO_TOO_LONG,\n message: \"Audio file is too long\",\n retryable: false,\n }),\n\n audioTooShort: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.AUDIO_TOO_SHORT,\n message: \"Audio is too short to transcribe\",\n retryable: false,\n }),\n};\n","","/**\n * Default A2UI generation and design guideline prompts.\n *\n * These are the canonical prompt fragments that instruct an LLM how to call\n * the render_a2ui tool, how to bind data, and how to style surfaces.\n */\n\n/**\n * Generation guidelines — protocol rules, tool arguments, path rules,\n * data model format, and form/two-way-binding instructions.\n */\nexport const A2UI_DEFAULT_GENERATION_GUIDELINES = `\\\nGenerate A2UI v0.9 JSON.\n\n## A2UI Protocol Instructions\n\nA2UI (Agent to UI) is a protocol for rendering rich UI surfaces from agent responses.\n\nCRITICAL: You MUST call the render_a2ui tool with ALL of these arguments:\n- surfaceId: A unique ID for the surface (e.g. \"product-comparison\")\n- components: REQUIRED — the A2UI component array. NEVER omit this. Only use\n components listed in the Available Components schema provided as context.\n- data: OPTIONAL — a JSON object written to the root of the surface data model.\n Use for pre-filling form values or providing data for path-bound components.\n- every component must have the \"component\" field specifying the component type.\n ONLY use component names from the Available Components schema — do NOT invent\n component names or use names not in the schema.\n\nCOMPONENT ID RULES:\n- Exactly one component MUST have id=\"root\". This is the surface's entry\n point — the renderer begins at \"root\" and walks the child/children tree\n from there. Every other component must be reachable from \"root\". If no\n component has id=\"root\", the surface renders an empty loading placeholder\n and none of your components will be shown.\n- Every component ID must be unique within the surface.\n- A component MUST NOT reference itself as child/children. This causes a\n circular dependency error. For example, if a component has id=\"avatar\",\n its child must be a DIFFERENT id (e.g. \"avatar-img\"), never \"avatar\".\n- The child/children tree must be a DAG — no cycles allowed.\n\nREPEATING CONTENT (TEMPLATES):\nTo repeat a component for each item in an array, use the structural children format:\n children: { componentId: \"card-id\", path: \"/items\" }\nThis tells the renderer to create one instance of \"card-id\" per item in the \"/items\" array.\n\nPATH RULES FOR TEMPLATES:\nComponents inside a repeating template use RELATIVE paths (no leading slash).\nThe path is resolved relative to each array item automatically.\nIf a container has children: { componentId: \"card\", path: \"/items\" } and each item\nhas a key \"name\", use { \"path\": \"name\" } (NO leading slash — relative to item).\nCRITICAL: Do NOT use \"/name\" (absolute) inside templates — use \"name\" (relative).\nThe container's path (\"/items\") uses a leading slash (absolute), but all\ncomponents INSIDE the template use paths WITHOUT leading slash.\n\nCOMPONENT VALUES — DEFAULT RULE:\nUse inline literal values for ALL component properties. Pass strings, numbers,\narrays, and objects directly on the component. Do NOT use { \"path\": \"...\" }\nobjects unless the property's schema explicitly allows it (see exception below).\nCRITICAL: USING { \"path\": \"...\" } ON A PROPERTY THAT DOES NOT DECLARE PATH\nSUPPORT IN ITS SCHEMA WILL CAUSE A RUNTIME CRASH AND BREAK THE ENTIRE UI.\nALWAYS CHECK THE COMPONENT SCHEMA FIRST — IF THE PROPERTY ONLY ACCEPTS A\nPLAIN TYPE, YOU MUST USE A LITERAL VALUE.\nVERY IMPORTANT: THE APPLICATION WILL BREAK IF YOU DO NOT FOLLOW THIS RULE!\n\nFor example, a chart's \"data\" must always be an inline array:\n \"data\": [{\"label\": \"Jan\", \"value\": 100}, {\"label\": \"Feb\", \"value\": 200}]\nA metric's \"value\" must always be an inline string:\n \"value\": \"$1,200\"\n\nPATH BINDING EXCEPTION — SCHEMA-DRIVEN:\nA few properties accept { \"path\": \"/some/path\" } as an alternative to a literal\nvalue. You can identify these in the Available Components schema: the property\nwill list BOTH a literal type AND an object-with-path option. If a property only\nshows a single type (string, number, array, etc.), it does NOT support path\nbinding — use a literal value only.\n\nPath binding is typically used for editable form inputs so the client can write\nuser input back to the data model. When building forms:\n- Bind input \"value\" to a data model path: \"value\": { \"path\": \"/form/name\" }\n- Pre-fill via the \"data\" tool argument: \"data\": { \"form\": { \"name\": \"Alice\" } }\n- Capture values on submit via button action context:\n \"action\": { \"event\": { \"name\": \"submit\", \"context\": { \"name\": { \"path\": \"/form/name\" } } } }\n\nREPEATING CONTENT uses a structural children format (not the same as value binding):\n children: { componentId: \"card-id\", path: \"/items\" }\nComponents inside templates use RELATIVE paths (no leading slash): { \"path\": \"name\" }.`;\n\n/**\n * Design guidelines — visual design rules, component hierarchy tips,\n * and action handler patterns.\n */\nexport const A2UI_DEFAULT_DESIGN_GUIDELINES = `\\\nCreate polished, visually appealing interfaces. ONLY use components listed in the\nAvailable Components schema — do NOT use component names that are not in the schema.\n\nDesign principles:\n- Create clear visual hierarchy within cards and layouts.\n- Keep cards clean — avoid clutter. Whitespace is good.\n- Use consistent surfaceIds (lowercase, hyphenated).\n- NEVER use the same ID for a component and its child — this creates a\n circular dependency. E.g. if id=\"avatar\", child must NOT be \"avatar\".\n- For side-by-side comparisons, use a container with structural children\n (children: { componentId, path }) to repeat a card template per data item.\n- Include images when relevant (logos, icons, product photos):\n - Prefer company logos via Google favicons: https://www.google.com/s2/favicons?domain=example.com&sz=128\n - Do NOT invent Unsplash photo-IDs — they will 404. Only use real, known URLs.\n- For buttons: action MUST use this exact nested format:\n \"action\": { \"event\": { \"name\": \"myAction\", \"context\": { \"key\": \"value\" } } }\n The \"event\" key holds an OBJECT with \"name\" (required) and \"context\" (optional).\n Do NOT use a flat format like {\"event\": \"name\"} — \"event\" must be an object.\n- For forms: check the component schema — if an input's \"value\" property\n supports path binding, use it for editable fields. The submit button's\n action context should reference the same paths to capture user input.\n\nUse the SAME surfaceId as the main surface. Match action names to button action event names.`;\n","/** Shared generation contract for all Open Generative UI renderers. */\nexport const GENERATE_SANDBOXED_UI_DESCRIPTION =\n \"Generate sandboxed UI. \" +\n \"IMPORTANT: The generated code runs in a sandboxed iframe WITHOUT same-origin access. \" +\n \"Do NOT use localStorage, sessionStorage, document.cookie, IndexedDB, or fetch/XMLHttpRequest to same-origin URLs. \" +\n \"To communicate with the host application, use Websandbox.connection.remote.<functionName>(args) which returns a Promise.\\n\\n\" +\n \"You CAN use external libraries from CDNs by including <script> or <link> tags in the HTML <head> (e.g., Chart.js, D3, Three.js, x-data-spreadsheet, etc.). \" +\n \"CDN resources load normally inside the sandbox.\\n\\n\" +\n \"PARAMETER ORDER IS CRITICAL — generate parameters in exactly this order:\\n\" +\n \"1. initialHeight + placeholderMessages (shown to user while generating)\\n\" +\n \"2. css (all styles FIRST — the user sees a placeholder until CSS is complete)\\n\" +\n \"3. html (streams in live — the user watches the UI build as HTML is generated)\\n\" +\n \"4. jsFunctions (reusable helper functions)\\n\" +\n \"5. jsExpressions (applied one-by-one — the user sees each expression take effect)\" +\n \"\\n\\nINITIALIZATION CONTRACT: jsFunctions and jsExpressions run after the final HTML DOM is ready, in both live generation and saved-thread replay. \" +\n \"Define reusable functions in jsFunctions, then initialize the UI directly in the first jsExpressions entry (for example, initializeCalculator()). \" +\n \"Attach click/keyboard handlers and set initial display values there. Do NOT wait for DOMContentLoaded, window.onload, or the load event in jsFunctions or jsExpressions: these events may already have fired. \" +\n \"Each expression is executed once per rendered sandbox; later expressions must not repeat initialization or reattach the same handlers. \" +\n \"Keep initialization self-contained so a new sandbox can reconstruct the UI when a saved thread is opened. If a library loads asynchronously, initialize from its explicit load promise instead of waiting for document readiness.\\n\\n\" +\n \"INTERACTION CONTRACT: Every visible interactive control needs a working handler, including controls created during initialization. If the handlers are supplied through jsFunctions/jsExpressions, initialize them in the first expression; if supplied by an inline HTML script, ensure it runs when the final sandbox mounts and replays. Every user action must update the visible UI to reflect its completed result, including success and error paths. Changing a JavaScript variable alone does not update the DOM. After changing state, call the rendering function or update the displayed element directly. When delegating clicks from a parent element, resolve the clicked control with closest('button') so clicks on nested labels and values work. For a calculator, pressing = must replace the visible expression with the computed answer; metric shortcuts must visibly insert their values. Trace each button handler through its final display update before emitting the tool call.\";\n","export * from \"./types\";\nexport * from \"./utils\";\nexport * from \"./constants\";\n// Telemetry is split deliberately. `TelemetryClient` imports\n// `@segment/analytics-node`, which imports `node-fetch`, which imports the\n// Node built-ins `stream`, `http`, `https` and `zlib`. Browser bundlers\n// resolve the whole module graph before they tree-shake, so re-exporting\n// that module here made every browser build of a dependent package print\n// \"Module ... has been externalized for browser compatibility\" warnings,\n// even when the consumer never touched telemetry (#4151). Only the\n// browser-safe telemetry surface is re-exported from this entry. Server\n// code that needs the client imports it from `@copilotkit/shared/telemetry`.\n// This mirrors the license-verifier note below.\nexport { isTelemetryDisabled } from \"./telemetry/telemetry-disabled\";\nexport * from \"./telemetry/sampling\";\n// Pure string classification with no imports, so it carries no runtime edge\n// into browser builds — same reasoning as `sampling` above.\nexport * from \"./telemetry/model-host\";\nexport {\n firstNonBlankTelemetryId,\n lambdaClient,\n parseTelemetryIdFromLicense,\n parseAndWarnTelemetryId,\n} from \"./telemetry/lambda-client\";\nexport type { LambdaSendOptions } from \"./telemetry/lambda-client\";\n// Types only: erased at build time, so they add no runtime edge to\n// `telemetry-client.ts` and therefore none to @segment/analytics-node.\nexport type {\n TelemetryCapture,\n TelemetryIdentity,\n} from \"./telemetry/telemetry-client\";\nexport * from \"./debug\";\nexport * from \"./standard-schema\";\nexport * from \"./attachments\";\n\nexport { logger } from \"./logger\";\nexport {\n createRunEventFinalizer,\n finalizeRunEvents,\n type FinalizeRunOptions,\n type RunEventFinalizer,\n} from \"./finalize-events\";\nexport { stripIntelligenceRoutingFields } from \"./intelligence-routing-fields\";\n\nexport {\n TranscriptionErrorCode,\n TranscriptionErrors,\n type TranscriptionErrorResponse,\n} from \"./transcription-errors\";\n\nimport * as packageJson from \"../package.json\";\nexport const COPILOTKIT_VERSION = packageJson.version;\n\n// Re-export only types from license-verifier (types are erased at compile time,\n// so they don't pull in the Node-only `crypto` dependency into client bundles).\n// Server-side packages (e.g. @copilotkit/runtime) should import runtime functions\n// like createLicenseChecker and getLicenseWarningHeader directly from\n// @copilotkit/license-verifier.\nexport type {\n LicenseChecker,\n LicenseStatus,\n LicensePayload,\n LicenseFeatures,\n LicenseTier,\n LicenseOwner,\n} from \"@copilotkit/license-verifier\";\n\nimport type { LicensePayload } from \"@copilotkit/license-verifier\";\nimport type {\n RuntimeEntitlementResponse,\n RuntimeLicenseStatus,\n} from \"./utils/types\";\n\n// LicenseContextValue was dropped from license-verifier's public API in\n// 0.3.0, so it is defined here. The context shape is owned by this package\n// anyway via createLicenseContextValue below.\n\n/**\n * License context value exposed to child components.\n * Frontend providers create their own context using this shape.\n */\nexport interface LicenseContextValue {\n /** Effective license status after structured entitlement precedence. Null until known. */\n status: RuntimeLicenseStatus | null;\n /** The license payload if available. Always null on the client; the payload stays server-side. */\n license: LicensePayload | null;\n /** Whether a feature is licensed. Ready entitlements override legacy status behavior. */\n checkFeature: (feature: string) => boolean;\n /** Get a numeric feature limit. Zero means unlimited; null means not applicable. */\n getLimit: (feature: string) => number | null;\n}\n\n/** Read a record value without traversing its prototype chain. */\nfunction getOwnRecordValue<Value>(\n record: Readonly<Record<string, Value>>,\n key: string,\n): Value | undefined {\n return Object.prototype.hasOwnProperty.call(record, key)\n ? record[key]\n : undefined;\n}\n\n/** Legacy UI surfaces that remain available for every active entitlement. */\nfunction isLegacyUiFeature(feature: string): boolean {\n return feature === \"chat\" || feature === \"popup\" || feature === \"sidebar\";\n}\n\n/**\n * Client-safe license context factory, driven by the license authority the\n * runtime reports via /info.\n *\n * A ready managed entitlement is authoritative in both directions. A ready\n * active self-hosted entitlement is also authoritative, while an inactive\n * self-hosted response preserves the legacy signed-license fallback. Active\n * entitlements supply feature grants and limits; authoritative inactive\n * entitlements deny every feature and limit. Older runtimes that report only a\n * status retain the legacy behavior: features are enabled unless the status is\n * \"expired\" or \"invalid\", and no limits are reported. This is inlined here to\n * avoid importing the full license-verifier bundle (which depends on Node's\n * `crypto`) into browser bundles.\n */\nexport function createLicenseContextValue(\n status: RuntimeLicenseStatus | null | undefined,\n runtimeEntitlements?: RuntimeEntitlementResponse,\n): LicenseContextValue {\n const readyEntitlement =\n runtimeEntitlements?.status === \"ready\"\n ? runtimeEntitlements.entitlement\n : null;\n const hasUsableSelfHostedLegacyFallback =\n readyEntitlement &&\n !readyEntitlement.active &&\n readyEntitlement.source === \"selfHostedDeploymentLicense\" &&\n (status === \"valid\" || status === \"expiring\");\n const featureAuthority =\n readyEntitlement && !hasUsableSelfHostedLegacyFallback\n ? readyEntitlement\n : null;\n const activeEntitlement = featureAuthority?.active ? featureAuthority : null;\n const resolvedStatus = activeEntitlement\n ? \"valid\"\n : readyEntitlement?.source === \"managedOrgSubscription\" ||\n readyEntitlement?.source === \"awsMarketplaceDeploymentLicense\"\n ? \"none\"\n : featureAuthority\n ? (status ?? \"none\")\n : (status ?? null);\n const featuresEnabled =\n resolvedStatus !== \"expired\" && resolvedStatus !== \"invalid\";\n\n return {\n status: resolvedStatus,\n license: null,\n checkFeature: (feature) =>\n featureAuthority\n ? activeEntitlement\n ? feature === \"threads\" &&\n Object.prototype.hasOwnProperty.call(\n activeEntitlement.limits,\n \"threads.max_count\",\n )\n ? true\n : (getOwnRecordValue(activeEntitlement.features, feature) ??\n isLegacyUiFeature(feature))\n : false\n : featuresEnabled,\n getLimit: (feature) =>\n activeEntitlement\n ? (getOwnRecordValue(activeEntitlement.limits, feature) ?? null)\n : null,\n };\n}\n\nexport {\n A2UI_DEFAULT_GENERATION_GUIDELINES,\n A2UI_DEFAULT_DESIGN_GUIDELINES,\n} from \"./a2ui-prompts\";\n\nexport type { DebugEventEnvelope } from \"./debug-event-envelope\";\n\nexport { GENERATE_SANDBOXED_UI_DESCRIPTION } from \"./open-generative-ui-prompts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CASA,eAAsB,gBAAgB,MAAgC;;AACpE,MAAI,0BAAC,UAAU,uFAAW,YAAW;AACnC,WAAQ,MAAM,iCAAiC;AAC/C,UAAO;;AAGT,MAAI;AACF,SAAM,UAAU,UAAU,UAAU,KAAK;AACzC,UAAO;WACA,KAAK;AACZ,WAAQ,MAAM,gCAAgC,IAAI;AAClD,UAAO;;;;;;CCmBX,SAAgB,kBAAkB,EAChC,YACA,SAIU;AAEV,MAAI,0DAAC,WAAY,QAAQ,QAAO;AAGhC,SAAO,WAAW,OAAO,cAAc,iBAAiB,WAAW,MAAM,CAAC;;CAG5E,SAAS,iBAAiB,WAAsB,OAAqB;EACnE,MAAM,cAAc,UAAU,OAC1B,iBAAiB,OAAO,UAAU,KAAK,GACvC;AAEJ,UAAQ,UAAU,MAAlB;GAEE,KAAK,MACH,QAAQ,UAA+B,WAAW,OAAO,MACvD,iBAAiB,GAAG,MAAM,CAC3B;GACH,KAAK,KACH,QAAQ,UAA+B,WAAW,MAAM,MACtD,iBAAiB,GAAG,MAAM,CAC3B;GACH,KAAK,MACH,QAAO,CAAE,UAA+B,WAAW,OAAO,MACxD,iBAAiB,GAAG,MAAM,CAC3B;GAGH,KAAK,SACH,QAAO,gBAAiB,UAAkC;GAC5D,KAAK,aACH,QAAO,gBAAiB,UAAkC;GAC5D,KAAK,eACH,QAAO,cAAe,UAAkC;GAC1D,KAAK,YACH,QAAO,cAAe,UAAkC;GAC1D,KAAK,WACH,QACE,MAAM,QAAQ,YAAY,IAC1B,YAAY,SAAU,UAAkC,MAA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SAAO;GACL,QAAQ;GACR,SAAS;GACT,eAAe,YACb;;8BACI,oBACE,YAAY,aACZ,OAAO,UAAU,eAAe,KAC9B,kBAAkB,QAClB,oBACD,GACC,6BACC,kBAAkB,kBAAkB,UAAU,QAAQ,mEACvD,kBAAkB,QAAQ,GAC5B,QACF;;GACN,WAAW,YACT;;sDACK,kBAAkB,kBAAkB,QAAQ,QAAQ,qEAAI,OACzD;;GACP"}
|
|
1
|
+
{"version":3,"file":"index.umd.js","names":["GraphQLError","z","isRecord","uuid","PartialJSON","EventType","packageJson.version"],"sources":["../src/utils/clipboard.ts","../src/utils/conditions.ts","../src/utils/console-styling.ts","../src/utils/errors.ts","../src/utils/json-schema.ts","../src/utils/dashboard-url.ts","../src/utils/inspector-metadata.ts","../src/utils/inspector-learning.ts","../src/utils/inspector-visibility.ts","../src/utils/types.ts","../src/utils/random-id.ts","../src/utils/requests.ts","../src/utils/row-render-keys.ts","../src/utils/index.ts","../src/constants/index.ts","../src/telemetry/telemetry-disabled.ts","../src/telemetry/sampling.ts","../src/telemetry/model-host.ts","../src/telemetry/lambda-client.ts","../src/debug.ts","../src/standard-schema.ts","../src/attachments/content.ts","../src/attachments/utils.ts","../src/logger.ts","../src/finalize-events.ts","../src/intelligence-routing-fields.ts","../src/transcription-errors.ts","../package.json","../src/generative-ui/basic-functions.ts","../src/generative-ui/is-record.ts","../src/generative-ui/child-refs.ts","../src/generative-ui/types.ts","../src/a2ui-prompts.ts","../src/a2ui-envelope.ts","../src/open-generative-ui-prompts.ts","../src/generative-ui/validate-operation.ts","../src/generative-ui/render-ui-args.ts","../src/generative-ui/prompt.ts","../src/index.ts"],"sourcesContent":["/**\n * Safely copies text to the clipboard.\n *\n * Checks that the Clipboard API is available before attempting the write,\n * and catches any errors (e.g. permission denied, insecure context).\n *\n * @param text - The text to copy to the clipboard.\n * @returns `true` if the text was successfully copied, `false` otherwise.\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n if (!navigator.clipboard?.writeText) {\n console.error(\"Clipboard API is not available\");\n return false;\n }\n\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch (err) {\n console.error(\"Failed to copy to clipboard:\", err);\n return false;\n }\n}\n","export type ComparisonRule =\n | \"EQUALS\"\n | \"NOT_EQUALS\"\n | \"GREATER_THAN\"\n | \"LESS_THAN\"\n | \"CONTAINS\"\n | \"NOT_CONTAINS\"\n | \"MATCHES\"\n | \"STARTS_WITH\"\n | \"ENDS_WITH\";\nexport type LogicalRule = \"AND\" | \"OR\" | \"NOT\";\nexport type ExistenceRule = \"EXISTS\" | \"NOT_EXISTS\";\n\nexport type Rule = ComparisonRule | LogicalRule | ExistenceRule;\n\nexport interface BaseCondition {\n rule: Rule;\n path?: string;\n}\n\nexport interface ComparisonCondition extends BaseCondition {\n rule: ComparisonRule;\n value: any;\n}\n\nexport interface LogicalCondition extends BaseCondition {\n rule: LogicalRule;\n conditions: Condition[];\n}\n\nexport interface ExistenceCondition extends BaseCondition {\n rule: ExistenceRule;\n}\n\nexport type Condition =\n | ComparisonCondition\n | LogicalCondition\n | ExistenceCondition;\n\nexport function executeConditions({\n conditions,\n value,\n}: {\n conditions?: Condition[];\n value: any;\n}): boolean {\n // If no conditions, consider it a pass\n if (!conditions?.length) return true;\n\n // Run all conditions (implicit AND)\n return conditions.every((condition) => executeCondition(condition, value));\n}\n\nfunction executeCondition(condition: Condition, value: any): boolean {\n const targetValue = condition.path\n ? getValueFromPath(value, condition.path)\n : value;\n\n switch (condition.rule) {\n // Logical\n case \"AND\":\n return (condition as LogicalCondition).conditions.every((c) =>\n executeCondition(c, value),\n );\n case \"OR\":\n return (condition as LogicalCondition).conditions.some((c) =>\n executeCondition(c, value),\n );\n case \"NOT\":\n return !(condition as LogicalCondition).conditions.every((c) =>\n executeCondition(c, value),\n );\n\n // Comparison\n case \"EQUALS\":\n return targetValue === (condition as ComparisonCondition).value;\n case \"NOT_EQUALS\":\n return targetValue !== (condition as ComparisonCondition).value;\n case \"GREATER_THAN\":\n return targetValue > (condition as ComparisonCondition).value;\n case \"LESS_THAN\":\n return targetValue < (condition as ComparisonCondition).value;\n case \"CONTAINS\":\n return (\n Array.isArray(targetValue) &&\n targetValue.includes((condition as ComparisonCondition).value)\n );\n case \"NOT_CONTAINS\":\n return (\n Array.isArray(targetValue) &&\n !targetValue.includes((condition as ComparisonCondition).value)\n );\n case \"MATCHES\":\n return new RegExp((condition as ComparisonCondition).value).test(\n String(targetValue),\n );\n case \"STARTS_WITH\":\n return String(targetValue).startsWith(\n (condition as ComparisonCondition).value,\n );\n case \"ENDS_WITH\":\n return String(targetValue).endsWith(\n (condition as ComparisonCondition).value,\n );\n\n // Existence\n case \"EXISTS\":\n return targetValue !== undefined && targetValue !== null;\n case \"NOT_EXISTS\":\n return targetValue === undefined || targetValue === null;\n }\n}\n\nfunction getValueFromPath(obj: any, path: string): any {\n return path.split(\".\").reduce((acc, part) => acc?.[part], obj);\n}\n","/**\n * Console styling utilities for CopilotKit branded messages\n * Provides consistent, readable colors across light and dark console themes\n */\n\n/**\n * Color palette optimized for console readability\n */\nexport const ConsoleColors = {\n /** Primary brand blue - for titles and links */\n primary: \"#007acc\",\n /** Success green - for positive messaging */\n success: \"#22c55e\",\n /** Purple - for feature highlights */\n feature: \"#a855f7\",\n /** Red - for calls-to-action */\n cta: \"#ef4444\",\n /** Cyan - for closing statements */\n info: \"#06b6d4\",\n /** Inherit console default - for body text */\n inherit: \"inherit\",\n /** Warning style */\n warning: \"#f59e0b\",\n} as const;\n\n/**\n * Console style templates for common patterns\n */\nexport const ConsoleStyles = {\n /** Large header style */\n header: `color: ${ConsoleColors.warning}; font-weight: bold; font-size: 16px;`,\n /** Section header style */\n section: `color: ${ConsoleColors.success}; font-weight: bold;`,\n /** Feature highlight style */\n highlight: `color: ${ConsoleColors.feature}; font-weight: bold;`,\n /** Call-to-action style */\n cta: `color: ${ConsoleColors.success}; font-weight: bold;`,\n /** Info style */\n info: `color: ${ConsoleColors.info}; font-weight: bold;`,\n /** Link style */\n link: `color: ${ConsoleColors.primary}; text-decoration: underline;`,\n /** Body text - inherits console theme */\n body: `color: ${ConsoleColors.inherit};`,\n /** Warning style */\n warning: `color: ${ConsoleColors.cta}; font-weight: bold;`,\n} as const;\n\n/**\n * Styled console message for CopilotKit Platform promotion\n * Displays a beautiful, branded advertisement in the console\n */\nexport function logCopilotKitPlatformMessage() {\n console.log(\n `%cCopilotKit Warning%c\n\nuseCopilotChatHeadless_c provides full compatibility with CopilotKit's newly released Headless UI feature set. Headless UI requires a CopilotKit Intelligence license key, available for free at:\n\n%chttps://dashboard.operations.copilotkit.ai%c\n\nAlternatively, useCopilotChat is available for basic programmatic control, and does not require a license key.\n\nTo learn more about CopilotKit Intelligence, read the documentation here:\n\n%chttps://docs.copilotkit.ai/intelligence/overview%c`,\n ConsoleStyles.header,\n ConsoleStyles.body,\n ConsoleStyles.cta,\n ConsoleStyles.body,\n ConsoleStyles.link,\n ConsoleStyles.body,\n );\n}\n\nexport function publicApiKeyRequired(feature: string) {\n console.log(\n `\n%cCopilotKit Warning%c \\n\nIn order to use ${feature}, you need to add your CopilotKit license key, available for free at https://dashboard.operations.copilotkit.ai.\n `.trim(),\n ConsoleStyles.header,\n ConsoleStyles.body,\n );\n}\n\n/**\n * Create a styled console message with custom content\n *\n * @param template - Template string with %c placeholders\n * @param styles - Array of style strings matching the %c placeholders\n *\n * @example\n * ```typescript\n * logStyled(\n * '%cCopilotKit%c Welcome to the platform!',\n * [ConsoleStyles.header, ConsoleStyles.body]\n * );\n * ```\n */\nexport function logStyled(template: string, styles: string[]) {\n console.log(template, ...styles);\n}\n\n/**\n * Quick styled console methods for common use cases\n */\nexport const styledConsole = {\n /** Log a success message */\n success: (message: string) =>\n logStyled(`%c✅ ${message}`, [ConsoleStyles.section]),\n\n /** Log an info message */\n info: (message: string) => logStyled(`%cℹ️ ${message}`, [ConsoleStyles.info]),\n\n /** Log a feature highlight */\n feature: (message: string) =>\n logStyled(`%c✨ ${message}`, [ConsoleStyles.highlight]),\n\n /** Log a call-to-action */\n cta: (message: string) => logStyled(`%c🚀 ${message}`, [ConsoleStyles.cta]),\n\n /** Log the CopilotKit platform promotion */\n logCopilotKitPlatformMessage: logCopilotKitPlatformMessage,\n\n /** Log a `publicApiKeyRequired` warning */\n publicApiKeyRequired: publicApiKeyRequired,\n} as const;\n","import { GraphQLError } from \"graphql\";\nimport { COPILOTKIT_VERSION } from \"../index\";\n\nexport enum Severity {\n CRITICAL = \"critical\", // Critical errors that block core functionality\n WARNING = \"warning\", // Configuration/setup issues that need attention\n INFO = \"info\", // General errors and network issues\n}\n\nexport enum ErrorVisibility {\n BANNER = \"banner\", // Critical errors shown as fixed banners\n TOAST = \"toast\", // Regular errors shown as dismissible toasts\n SILENT = \"silent\", // Errors logged but not shown to user\n DEV_ONLY = \"dev_only\", // Errors only shown in development mode\n}\n\nexport const ERROR_NAMES = {\n COPILOT_ERROR: \"CopilotError\",\n COPILOT_API_DISCOVERY_ERROR: \"CopilotApiDiscoveryError\",\n COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR:\n \"CopilotKitRemoteEndpointDiscoveryError\",\n COPILOT_KIT_AGENT_DISCOVERY_ERROR: \"CopilotKitAgentDiscoveryError\",\n COPILOT_KIT_LOW_LEVEL_ERROR: \"CopilotKitLowLevelError\",\n COPILOT_KIT_VERSION_MISMATCH_ERROR: \"CopilotKitVersionMismatchError\",\n RESOLVED_COPILOT_KIT_ERROR: \"ResolvedCopilotKitError\",\n CONFIGURATION_ERROR: \"ConfigurationError\",\n MISSING_PUBLIC_API_KEY_ERROR: \"MissingPublicApiKeyError\",\n UPGRADE_REQUIRED_ERROR: \"UpgradeRequiredError\",\n} as const;\n\n// Banner errors - critical configuration/discovery issues\nexport const BANNER_ERROR_NAMES = [\n ERROR_NAMES.CONFIGURATION_ERROR,\n ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR,\n ERROR_NAMES.UPGRADE_REQUIRED_ERROR,\n ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR,\n ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR,\n ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR,\n];\n\n// Legacy cloud error names for backward compatibility\nexport const COPILOT_CLOUD_ERROR_NAMES = BANNER_ERROR_NAMES;\n\nexport enum CopilotKitErrorCode {\n NETWORK_ERROR = \"NETWORK_ERROR\",\n NOT_FOUND = \"NOT_FOUND\",\n AGENT_NOT_FOUND = \"AGENT_NOT_FOUND\",\n API_NOT_FOUND = \"API_NOT_FOUND\",\n REMOTE_ENDPOINT_NOT_FOUND = \"REMOTE_ENDPOINT_NOT_FOUND\",\n AUTHENTICATION_ERROR = \"AUTHENTICATION_ERROR\",\n MISUSE = \"MISUSE\",\n UNKNOWN = \"UNKNOWN\",\n VERSION_MISMATCH = \"VERSION_MISMATCH\",\n CONFIGURATION_ERROR = \"CONFIGURATION_ERROR\",\n MISSING_PUBLIC_API_KEY_ERROR = \"MISSING_PUBLIC_API_KEY_ERROR\",\n UPGRADE_REQUIRED_ERROR = \"UPGRADE_REQUIRED_ERROR\",\n}\n\nconst BASE_URL = \"https://docs.copilotkit.ai\";\n\nconst getSeeMoreMarkdown = (link: string) => `See more: [${link}](${link})`;\n\nexport const ERROR_CONFIG = {\n [CopilotKitErrorCode.NETWORK_ERROR]: {\n statusCode: 503,\n troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#network-errors-api-not-found`,\n visibility: ErrorVisibility.BANNER,\n severity: Severity.CRITICAL,\n },\n [CopilotKitErrorCode.NOT_FOUND]: {\n statusCode: 404,\n troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#network-errors-api-not-found`,\n visibility: ErrorVisibility.BANNER,\n severity: Severity.CRITICAL,\n },\n [CopilotKitErrorCode.AGENT_NOT_FOUND]: {\n statusCode: 500,\n troubleshootingUrl: `${BASE_URL}/langgraph-python/coagent-troubleshooting/common-coagent-issues#i-am-getting-agent-not-found-error`,\n visibility: ErrorVisibility.BANNER,\n severity: Severity.CRITICAL,\n },\n [CopilotKitErrorCode.API_NOT_FOUND]: {\n statusCode: 404,\n troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#network-errors-api-not-found`,\n visibility: ErrorVisibility.BANNER,\n severity: Severity.CRITICAL,\n },\n [CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND]: {\n statusCode: 404,\n troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#remote-endpoint-not-found-error`,\n visibility: ErrorVisibility.BANNER,\n severity: Severity.CRITICAL,\n },\n [CopilotKitErrorCode.AUTHENTICATION_ERROR]: {\n statusCode: 401,\n troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues`,\n visibility: ErrorVisibility.BANNER,\n severity: Severity.CRITICAL,\n },\n [CopilotKitErrorCode.MISUSE]: {\n statusCode: 400,\n troubleshootingUrl: null,\n visibility: ErrorVisibility.DEV_ONLY,\n severity: Severity.WARNING,\n },\n [CopilotKitErrorCode.UNKNOWN]: {\n statusCode: 500,\n visibility: ErrorVisibility.TOAST,\n severity: Severity.CRITICAL,\n },\n [CopilotKitErrorCode.CONFIGURATION_ERROR]: {\n statusCode: 400,\n troubleshootingUrl: null,\n severity: Severity.WARNING,\n visibility: ErrorVisibility.BANNER,\n },\n [CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR]: {\n statusCode: 400,\n troubleshootingUrl: null,\n severity: Severity.CRITICAL,\n visibility: ErrorVisibility.BANNER,\n },\n [CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR]: {\n statusCode: 402,\n troubleshootingUrl: null,\n severity: Severity.WARNING,\n visibility: ErrorVisibility.BANNER,\n },\n [CopilotKitErrorCode.VERSION_MISMATCH]: {\n statusCode: 400,\n troubleshootingUrl: null,\n visibility: ErrorVisibility.DEV_ONLY,\n severity: Severity.INFO,\n },\n};\n\nexport class CopilotKitError extends GraphQLError {\n code: CopilotKitErrorCode;\n statusCode: number;\n severity?: Severity;\n visibility: ErrorVisibility;\n\n constructor({\n message = \"Unknown error occurred\",\n code,\n severity,\n visibility,\n }: {\n message?: string;\n code: CopilotKitErrorCode;\n severity?: Severity;\n visibility?: ErrorVisibility;\n }) {\n const name = ERROR_NAMES.COPILOT_ERROR;\n const config = ERROR_CONFIG[code];\n const { statusCode } = config;\n const resolvedVisibility =\n visibility ?? config.visibility ?? ErrorVisibility.TOAST;\n const resolvedSeverity =\n severity ?? (\"severity\" in config ? config.severity : undefined);\n\n super(message, {\n extensions: {\n name,\n statusCode,\n code,\n visibility: resolvedVisibility,\n severity: resolvedSeverity,\n troubleshootingUrl:\n \"troubleshootingUrl\" in config ? config.troubleshootingUrl : null,\n originalError: {\n message,\n stack: new Error().stack,\n },\n },\n });\n\n this.code = code;\n this.name = name;\n this.statusCode = statusCode;\n this.severity = resolvedSeverity;\n this.visibility = resolvedVisibility;\n }\n}\n\n/**\n * Error thrown when we can identify wrong usage of our components.\n * This helps us notify the developer before real errors can happen\n *\n * @extends CopilotKitError\n */\nexport class CopilotKitMisuseError extends CopilotKitError {\n constructor({\n message,\n code = CopilotKitErrorCode.MISUSE,\n }: {\n message: string;\n code?: CopilotKitErrorCode;\n }) {\n const docsLink =\n \"troubleshootingUrl\" in ERROR_CONFIG[code] &&\n ERROR_CONFIG[code].troubleshootingUrl\n ? getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl as string)\n : null;\n const finalMessage = docsLink ? `${message}.\\n\\n${docsLink}` : message;\n super({ message: finalMessage, code });\n this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;\n }\n}\n\nconst getVersionMismatchErrorMessage = ({\n reactCoreVersion,\n runtimeVersion,\n runtimeClientGqlVersion,\n}: VersionMismatchResponse) =>\n `Version mismatch detected: @copilotkit/runtime@${runtimeVersion ?? \"\"} is not compatible with @copilotkit/react-core@${reactCoreVersion} and @copilotkit/runtime-client-gql@${runtimeClientGqlVersion}. Please ensure all installed copilotkit packages are on the same version.`;\n/**\n * Error thrown when CPK versions does not match\n *\n * @extends CopilotKitError\n */\nexport class CopilotKitVersionMismatchError extends CopilotKitError {\n constructor({\n reactCoreVersion,\n runtimeVersion,\n runtimeClientGqlVersion,\n }: VersionMismatchResponse) {\n const code = CopilotKitErrorCode.VERSION_MISMATCH;\n super({\n message: getVersionMismatchErrorMessage({\n reactCoreVersion,\n runtimeVersion,\n runtimeClientGqlVersion,\n }),\n code,\n });\n this.name = ERROR_NAMES.COPILOT_KIT_VERSION_MISMATCH_ERROR;\n }\n}\n\n/**\n * Error thrown when the CopilotKit API endpoint cannot be discovered or accessed.\n * This typically occurs when:\n * - The API endpoint URL is invalid or misconfigured\n * - The API service is not running at the expected location\n * - There are network/firewall issues preventing access\n *\n * @extends CopilotKitError\n */\nexport class CopilotKitApiDiscoveryError extends CopilotKitError {\n constructor(\n params: {\n message?: string;\n code?:\n | CopilotKitErrorCode.API_NOT_FOUND\n | CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND;\n url?: string;\n } = {},\n ) {\n const url = params.url ?? \"\";\n let operationSuffix = \"\";\n if (url?.includes(\"/info\"))\n operationSuffix = `when fetching CopilotKit info`;\n else if (url.includes(\"/actions/execute\"))\n operationSuffix = `when attempting to execute actions.`;\n else if (url.includes(\"/agents/state\"))\n operationSuffix = `when attempting to get agent state.`;\n else if (url.includes(\"/agents/execute\"))\n operationSuffix = `when attempting to execute agent(s).`;\n const message =\n params.message ??\n (params.url\n ? `Failed to find CopilotKit API endpoint at url ${params.url} ${operationSuffix}`\n : `Failed to find CopilotKit API endpoint.`);\n const code = params.code ?? CopilotKitErrorCode.API_NOT_FOUND;\n const errorMessage = `${message}.\\n\\n${getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl)}`;\n super({ message: errorMessage, code });\n this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;\n }\n}\n\n/**\n * This error is used for endpoints specified in runtime's remote endpoints. If they cannot be contacted\n * This typically occurs when:\n * - The API endpoint URL is invalid or misconfigured\n * - The API service is not running at the expected location\n *\n * @extends CopilotKitApiDiscoveryError\n */\nexport class CopilotKitRemoteEndpointDiscoveryError extends CopilotKitApiDiscoveryError {\n constructor(params?: { message?: string; url?: string }) {\n const message =\n params?.message ??\n (params?.url\n ? `Failed to find or contact remote endpoint at url ${params.url}`\n : \"Failed to find or contact remote endpoint\");\n const code = CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND;\n super({ message, code });\n this.name = ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR;\n }\n}\n\n/**\n * Error thrown when a LangGraph agent cannot be found or accessed.\n * This typically occurs when:\n * - The specified agent name does not exist in the deployment\n * - The agent configuration is invalid or missing\n * - The agent service is not properly deployed or initialized\n *\n * @extends CopilotKitError\n */\nexport class CopilotKitAgentDiscoveryError extends CopilotKitError {\n constructor(params: {\n agentName?: string;\n availableAgents: { name: string; id: string }[];\n }) {\n const { agentName, availableAgents } = params;\n const code = CopilotKitErrorCode.AGENT_NOT_FOUND;\n\n const seeMore = getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl);\n let message;\n\n if (availableAgents.length) {\n const agentList = availableAgents.map((agent) => agent.name).join(\", \");\n\n if (agentName) {\n message = `Agent '${agentName}' was not found. Available agents are: ${agentList}. Please verify the agent name in your configuration and ensure it matches one of the available agents.\\n\\n${seeMore}`;\n } else {\n message = `The requested agent was not found. Available agents are: ${agentList}. Please verify the agent name in your configuration and ensure it matches one of the available agents.\\n\\n${seeMore}`;\n }\n } else {\n message = `${agentName ? `Agent '${agentName}'` : \"The requested agent\"} was not found. Please set up at least one agent before proceeding. ${seeMore}`;\n }\n\n super({ message, code });\n this.name = ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR;\n }\n}\n\n/**\n * Handles low-level networking errors that occur before a request reaches the server.\n * These errors arise from issues in the underlying communication infrastructure rather than\n * application-level logic or server responses. Typically used to handle \"fetch failed\" errors\n * where no HTTP status code is available.\n *\n * Common scenarios include:\n * - Connection failures (ECONNREFUSED) when server is down/unreachable\n * - DNS resolution failures (ENOTFOUND) when domain can't be resolved\n * - Timeouts (ETIMEDOUT) when request takes too long\n * - Protocol/transport layer errors like SSL/TLS issues\n */\nexport class CopilotKitLowLevelError extends CopilotKitError {\n constructor({\n error,\n url,\n message,\n }: {\n error: Error;\n url: string;\n message?: string;\n }) {\n let code = CopilotKitErrorCode.NETWORK_ERROR;\n\n // @ts-expect-error -- code may exist\n const errorCode = error.code as string;\n const errorMessage =\n message ?? resolveLowLevelErrorMessage({ errorCode, url });\n\n super({ message: errorMessage, code });\n\n this.name = ERROR_NAMES.COPILOT_KIT_LOW_LEVEL_ERROR;\n }\n}\n\n/**\n * Generic catch-all error handler for HTTP responses from the CopilotKit API where a status code is available.\n * Used when we receive an HTTP error status and wish to handle broad range of them\n *\n * This differs from CopilotKitLowLevelError in that:\n * - ResolvedCopilotKitError: Server was reached and returned an HTTP status\n * - CopilotKitLowLevelError: Error occurred before reaching server (e.g. network failure)\n *\n * @param status - The HTTP status code received from the API response\n * @param message - Optional error message to include\n * @param code - Optional specific CopilotKitErrorCode to override default behavior\n *\n * Default behavior:\n * - 400 Bad Request: Maps to CopilotKitApiDiscoveryError\n * - All other status codes: Maps to UNKNOWN error code if no specific code provided\n */\nexport class ResolvedCopilotKitError extends CopilotKitError {\n constructor({\n status,\n message,\n code,\n isRemoteEndpoint,\n url,\n }: {\n status: number;\n message?: string;\n code?: CopilotKitErrorCode;\n isRemoteEndpoint?: boolean;\n url?: string;\n }) {\n let resolvedCode = code;\n if (!resolvedCode) {\n switch (status) {\n case 400:\n throw new CopilotKitApiDiscoveryError({ message, url });\n case 404:\n throw isRemoteEndpoint\n ? new CopilotKitRemoteEndpointDiscoveryError({ message, url })\n : new CopilotKitApiDiscoveryError({ message, url });\n default:\n resolvedCode = CopilotKitErrorCode.UNKNOWN;\n break;\n }\n }\n\n super({ message, code: resolvedCode });\n this.name = ERROR_NAMES.RESOLVED_COPILOT_KIT_ERROR;\n }\n}\n\nexport class ConfigurationError extends CopilotKitError {\n constructor(message: string) {\n super({ message, code: CopilotKitErrorCode.CONFIGURATION_ERROR });\n this.name = ERROR_NAMES.CONFIGURATION_ERROR;\n this.severity = Severity.WARNING;\n }\n}\n\nexport class MissingPublicApiKeyError extends ConfigurationError {\n constructor(message: string) {\n super(message);\n this.name = ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR;\n this.severity = Severity.CRITICAL;\n }\n}\n\nexport class UpgradeRequiredError extends ConfigurationError {\n constructor(message: string) {\n super(message);\n this.name = ERROR_NAMES.UPGRADE_REQUIRED_ERROR;\n this.severity = Severity.WARNING;\n }\n}\n\n/**\n * Checks if an error is already a structured CopilotKit error.\n * This utility centralizes the logic for detecting structured errors across the codebase.\n *\n * @param error - The error to check\n * @returns true if the error is already structured, false otherwise\n */\nexport function isStructuredCopilotKitError(error: any): boolean {\n return (\n error instanceof CopilotKitError ||\n error instanceof CopilotKitLowLevelError ||\n (error?.name && error.name.includes(\"CopilotKit\")) ||\n error?.extensions?.code !== undefined // Check if it has our structured error properties\n );\n}\n\n/**\n * Returns the error as-is if it's already structured, otherwise converts it using the provided converter function.\n * This utility centralizes the pattern of preserving structured errors while converting unstructured ones.\n *\n * @param error - The error to process\n * @param converter - Function to convert unstructured errors to structured ones\n * @returns The structured error\n */\nexport function ensureStructuredError<T extends CopilotKitError>(\n error: any,\n converter: (error: any) => T,\n): T | any {\n return isStructuredCopilotKitError(error) ? error : converter(error);\n}\n\ninterface VersionMismatchResponse {\n runtimeVersion?: string;\n runtimeClientGqlVersion: string;\n reactCoreVersion: string;\n}\n\nexport async function getPossibleVersionMismatch({\n runtimeVersion,\n runtimeClientGqlVersion,\n}: {\n runtimeVersion?: string;\n runtimeClientGqlVersion: string;\n}) {\n if (!runtimeVersion || runtimeVersion === \"\" || !runtimeClientGqlVersion)\n return;\n if (\n COPILOTKIT_VERSION !== runtimeVersion ||\n COPILOTKIT_VERSION !== runtimeClientGqlVersion ||\n runtimeVersion !== runtimeClientGqlVersion\n ) {\n return {\n runtimeVersion,\n runtimeClientGqlVersion,\n reactCoreVersion: COPILOTKIT_VERSION,\n message: getVersionMismatchErrorMessage({\n runtimeVersion,\n runtimeClientGqlVersion,\n reactCoreVersion: COPILOTKIT_VERSION,\n }),\n };\n }\n\n return;\n}\n\nconst resolveLowLevelErrorMessage = ({\n errorCode,\n url,\n}: {\n errorCode?: string;\n url: string;\n}) => {\n const troubleshootingLink =\n ERROR_CONFIG[CopilotKitErrorCode.NETWORK_ERROR].troubleshootingUrl;\n const genericMessage = (\n description = `Failed to fetch from url ${url}.`,\n ) => `${description}.\n\nPossible reasons:\n- -The server may have an error preventing it from returning a response (Check the server logs for more info).\n- -The server might be down or unreachable\n- -There might be a network issue (e.g., DNS failure, connection timeout) \n- -The URL might be incorrect\n- -The server is not running on the specified port\n\n${getSeeMoreMarkdown(troubleshootingLink)}`;\n\n if (url.includes(\"/info\"))\n return genericMessage(\n `Failed to fetch CopilotKit agents/action information from url ${url}.`,\n );\n if (url.includes(\"/actions/execute\"))\n return genericMessage(`Fetch call to ${url} to execute actions failed.`);\n if (url.includes(\"/agents/state\"))\n return genericMessage(`Fetch call to ${url} to get agent state failed.`);\n if (url.includes(\"/agents/execute\"))\n return genericMessage(`Fetch call to ${url} to execute agent(s) failed.`);\n\n switch (errorCode) {\n case \"ECONNREFUSED\":\n return `Connection to ${url} was refused. Ensure the server is running and accessible.\\n\\n${getSeeMoreMarkdown(troubleshootingLink)}`;\n case \"ENOTFOUND\":\n return `The server on ${url} could not be found. Check the URL or your network configuration.\\n\\n${getSeeMoreMarkdown(ERROR_CONFIG[CopilotKitErrorCode.NOT_FOUND].troubleshootingUrl)}`;\n case \"ETIMEDOUT\":\n return `The connection to ${url} timed out. The server might be overloaded or taking too long to respond.\\n\\n${getSeeMoreMarkdown(troubleshootingLink)}`;\n default:\n return;\n }\n};\n","import { z } from \"zod\";\nimport { Parameter } from \"../types\";\n\nexport type JSONSchemaString = {\n type: \"string\";\n description?: string;\n enum?: string[];\n};\n\nexport type JSONSchemaNumber = {\n type: \"number\";\n description?: string;\n};\n\nexport type JSONSchemaBoolean = {\n type: \"boolean\";\n description?: string;\n};\n\nexport type JSONSchemaObject = {\n type: \"object\";\n properties?: Record<string, JSONSchema>;\n required?: string[];\n description?: string;\n};\n\nexport type JSONSchemaArray = {\n type: \"array\";\n items: JSONSchema;\n description?: string;\n};\n\nexport type JSONSchema =\n | JSONSchemaString\n | JSONSchemaNumber\n | JSONSchemaBoolean\n | JSONSchemaObject\n | JSONSchemaArray;\n\nexport function actionParametersToJsonSchema(\n actionParameters: Parameter[],\n): JSONSchema {\n // Create the parameters object based on the argumentAnnotations\n let parameters: { [key: string]: any } = {};\n for (let parameter of actionParameters || []) {\n parameters[parameter.name] = convertAttribute(parameter);\n }\n\n let requiredParameterNames: string[] = [];\n for (let arg of actionParameters || []) {\n if (arg.required !== false) {\n requiredParameterNames.push(arg.name);\n }\n }\n\n // Create the ChatCompletionFunctions object\n return {\n type: \"object\",\n properties: parameters,\n required: requiredParameterNames,\n };\n}\n\n// Convert JSONSchema to Parameter[]\nexport function jsonSchemaToActionParameters(\n jsonSchema: JSONSchema,\n): Parameter[] {\n if (jsonSchema.type !== \"object\" || !jsonSchema.properties) {\n return [];\n }\n\n const parameters: Parameter[] = [];\n const requiredFields = jsonSchema.required || [];\n\n for (const [name, schema] of Object.entries(jsonSchema.properties)) {\n const parameter = convertJsonSchemaToParameter(\n name,\n schema,\n requiredFields.includes(name),\n );\n parameters.push(parameter);\n }\n\n return parameters;\n}\n\n// Convert JSONSchema property to Parameter\nfunction convertJsonSchemaToParameter(\n name: string,\n schema: JSONSchema,\n isRequired: boolean,\n): Parameter {\n const baseParameter: Parameter = {\n name,\n description: schema.description,\n };\n\n if (!isRequired) {\n baseParameter.required = false;\n }\n\n // Handle null-union types like [\"string\", \"null\"] by picking the non-null type\n if (Array.isArray(schema.type)) {\n const types = schema.type as string[];\n const hasNull = types.includes(\"null\");\n const nonNullTypes = types.filter((t: string) => t !== \"null\");\n const resolvedType = nonNullTypes.length > 0 ? nonNullTypes[0] : \"string\";\n return convertJsonSchemaToParameter(\n name,\n { ...schema, type: resolvedType } as JSONSchema,\n hasNull ? false : isRequired,\n );\n }\n\n switch (schema.type) {\n case \"string\":\n return {\n ...baseParameter,\n type: \"string\",\n ...(schema.enum && { enum: schema.enum }),\n };\n case \"number\":\n case \"boolean\":\n return {\n ...baseParameter,\n type: schema.type,\n };\n case \"object\":\n if (schema.properties) {\n const attributes: Parameter[] = [];\n const requiredFields = schema.required || [];\n\n for (const [propName, propSchema] of Object.entries(\n schema.properties,\n )) {\n attributes.push(\n convertJsonSchemaToParameter(\n propName,\n propSchema,\n requiredFields.includes(propName),\n ),\n );\n }\n\n return {\n ...baseParameter,\n type: \"object\",\n attributes,\n };\n }\n return {\n ...baseParameter,\n type: \"object\",\n };\n case \"array\":\n if (schema.items.type === \"object\" && \"properties\" in schema.items) {\n const attributes: Parameter[] = [];\n const requiredFields = schema.items.required || [];\n\n for (const [propName, propSchema] of Object.entries(\n schema.items.properties || {},\n )) {\n attributes.push(\n convertJsonSchemaToParameter(\n propName,\n propSchema,\n requiredFields.includes(propName),\n ),\n );\n }\n\n return {\n ...baseParameter,\n type: \"object[]\",\n attributes,\n };\n } else if (schema.items.type === \"array\") {\n throw new Error(\"Nested arrays are not supported\");\n } else {\n return {\n ...baseParameter,\n type: `${schema.items.type}[]`,\n };\n }\n default:\n return {\n ...baseParameter,\n type: \"string\",\n };\n }\n}\n\nfunction convertAttribute(attribute: Parameter): JSONSchema {\n switch (attribute.type) {\n case \"string\":\n return {\n type: \"string\",\n description: attribute.description,\n ...(attribute.enum && { enum: attribute.enum }),\n };\n case \"number\":\n case \"boolean\":\n return {\n type: attribute.type,\n description: attribute.description,\n };\n case \"object\":\n case \"object[]\":\n const properties = attribute.attributes?.reduce(\n (acc, attr) => {\n acc[attr.name] = convertAttribute(attr);\n return acc;\n },\n {} as Record<string, any>,\n );\n const required = attribute.attributes\n ?.filter((attr) => attr.required !== false)\n .map((attr) => attr.name);\n if (attribute.type === \"object[]\") {\n return {\n type: \"array\",\n items: {\n type: \"object\",\n ...(properties && { properties }),\n ...(required && required.length > 0 && { required }),\n },\n description: attribute.description,\n };\n }\n return {\n type: \"object\",\n description: attribute.description,\n ...(properties && { properties }),\n ...(required && required.length > 0 && { required }),\n };\n default:\n // Handle arrays of primitive types and undefined attribute.type\n if (attribute.type?.endsWith(\"[]\")) {\n const itemType = attribute.type.slice(0, -2);\n return {\n type: \"array\",\n items: { type: itemType as any },\n description: attribute.description,\n };\n }\n // Fallback for undefined type or any other unexpected type\n return {\n type: \"string\",\n description: attribute.description,\n };\n }\n}\n\nexport function convertJsonSchemaToZodSchema(\n jsonSchema: any,\n required: boolean,\n definitions?: Record<string, any>,\n visitedRefs?: Set<string>,\n): z.ZodSchema {\n // Resolve $ref references\n if (jsonSchema.$ref && definitions) {\n const refPath = jsonSchema.$ref.replace(\n /^#\\/\\$defs\\/|^#\\/definitions\\//,\n \"\",\n );\n\n // Detect circular $ref cycles\n const refs = visitedRefs ?? new Set<string>();\n if (refs.has(refPath)) {\n console.warn(\n `[CopilotKit] Circular $ref detected for \"${refPath}\" — falling back to z.any()`,\n );\n let schema = z.any();\n if (jsonSchema.description) {\n schema = schema.describe(jsonSchema.description);\n }\n return required ? schema : schema.optional();\n }\n\n const resolved = definitions[refPath];\n if (resolved) {\n // Clone the set so sibling branches don't see each other's visited refs\n const nextRefs = new Set(refs);\n nextRefs.add(refPath);\n return convertJsonSchemaToZodSchema(\n resolved,\n required,\n definitions,\n nextRefs,\n );\n }\n }\n\n // Collect top-level definitions for $ref resolution\n const defs = definitions ?? jsonSchema.$defs ?? jsonSchema.definitions;\n\n // Handle null-union types like [\"string\", \"null\"]\n if (Array.isArray(jsonSchema.type)) {\n const types = jsonSchema.type as string[];\n const hasNull = types.includes(\"null\");\n const nonNullTypes = types.filter((t: string) => t !== \"null\");\n const resolvedType = nonNullTypes.length > 0 ? nonNullTypes[0] : \"string\";\n const innerSchema = convertJsonSchemaToZodSchema(\n { ...jsonSchema, type: resolvedType },\n true,\n defs,\n visitedRefs,\n );\n let schema = hasNull ? z.union([innerSchema, z.null()]) : innerSchema;\n if (jsonSchema.description) {\n schema = schema.describe(jsonSchema.description);\n }\n return required ? schema : schema.optional();\n }\n\n // Handle anyOf / oneOf as z.union\n const unionVariants = jsonSchema.anyOf ?? jsonSchema.oneOf;\n if (Array.isArray(unionVariants) && unionVariants.length > 0) {\n if (unionVariants.length === 1) {\n return convertJsonSchemaToZodSchema(\n unionVariants[0],\n required,\n defs,\n visitedRefs,\n );\n }\n const schemas = unionVariants.map((v: any) =>\n convertJsonSchemaToZodSchema(v, true, defs, visitedRefs),\n );\n let schema = z.union(\n schemas as [z.ZodSchema, z.ZodSchema, ...z.ZodSchema[]],\n );\n if (jsonSchema.description) {\n schema = schema.describe(jsonSchema.description);\n }\n return required ? schema : schema.optional();\n }\n\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(\n value,\n jsonSchema.required ? jsonSchema.required.includes(key) : false,\n defs,\n visitedRefs,\n );\n }\n let schema = z.object(spec).describe(jsonSchema.description);\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n if (jsonSchema.enum && jsonSchema.enum.length > 0) {\n let schema = z\n .enum(jsonSchema.enum as [string, ...string[]])\n .describe(jsonSchema.description);\n return required ? schema : schema.optional();\n }\n let schema = z.string().describe(jsonSchema.description);\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\" || jsonSchema.type === \"integer\") {\n let schema = z.number().describe(jsonSchema.description);\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n let schema = z.boolean().describe(jsonSchema.description);\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n let itemSchema = convertJsonSchemaToZodSchema(\n jsonSchema.items,\n true,\n defs,\n visitedRefs,\n );\n let schema = z.array(itemSchema).describe(jsonSchema.description);\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"null\") {\n let schema = z.null().describe(jsonSchema.description);\n return required ? schema : schema.optional();\n }\n\n // Fallback: accept any value rather than throwing\n console.warn(\n `[CopilotKit] Unsupported JSON schema type \"${jsonSchema.type ?? \"unknown\"}\" — falling back to z.any()`,\n );\n let schema = z.any();\n if (jsonSchema.description) {\n schema = schema.describe(jsonSchema.description);\n }\n return required ? schema : schema.optional();\n}\n\nexport function getZodParameters<T extends [] | Parameter[] | undefined>(\n parameters: T,\n): any {\n if (!parameters) return z.object({});\n const jsonParams = actionParametersToJsonSchema(parameters);\n return convertJsonSchemaToZodSchema(jsonParams, true);\n}\n","/**\n * Checks dashboard navigation transport and credentials only.\n * Callers must separately enforce the configured origin and allowed paths.\n * This policy does not authorize server-side requests.\n */\nexport function isSafeDashboardUrl(url: URL): boolean {\n const local =\n [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname) ||\n /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+localhost$/u.test(\n url.hostname,\n );\n return (\n !url.username &&\n !url.password &&\n (url.protocol === \"https:\" || (url.protocol === \"http:\" && local))\n );\n}\n","import { isSafeDashboardUrl } from \"./dashboard-url\";\n\n/**\n * Inspector metadata supplied by a trusted CopilotKit runtime.\n *\n * Each optional module is independent so clients can render partial metadata\n * from runtimes that do not expose every module.\n */\nexport interface InspectorMetadataV1 {\n readonly schemaVersion: 1;\n readonly identity?: {\n readonly organizationName: string;\n readonly projectName: string;\n };\n readonly plan?: {\n readonly code: string;\n readonly label: string;\n };\n readonly license?: {\n readonly state: \"valid\" | \"none\" | \"expired\" | \"unknown\";\n };\n readonly action?:\n | { readonly kind: \"manage_plan\"; readonly url: string }\n | { readonly kind: \"renew\"; readonly url: string }\n | { readonly kind: \"enable_intelligence\"; readonly url: string };\n readonly usage?: {\n readonly used: number;\n readonly limit:\n | { readonly kind: \"finite\"; readonly value: number }\n | { readonly kind: \"unlimited\" }\n | { readonly kind: \"unknown\" };\n readonly expiringSoonCount?: number;\n };\n}\n\ntype UnknownRecord = Record<string, unknown>;\ntype InspectorIdentity = NonNullable<InspectorMetadataV1[\"identity\"]>;\ntype InspectorPlan = NonNullable<InspectorMetadataV1[\"plan\"]>;\ntype InspectorLicense = NonNullable<InspectorMetadataV1[\"license\"]>;\ntype InspectorAction = NonNullable<InspectorMetadataV1[\"action\"]>;\ntype InspectorUsage = NonNullable<InspectorMetadataV1[\"usage\"]>;\ntype InspectorUsageLimit = InspectorUsage[\"limit\"];\n\nfunction isRecord(value: unknown): value is UnknownRecord {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n\n try {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n } catch {\n return false;\n }\n}\n\nfunction readOwnDataProperty(value: UnknownRecord, key: string): unknown {\n try {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n return descriptor !== undefined && \"value\" in descriptor\n ? descriptor.value\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction parseNonBlankString(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const parsed = value.trim();\n return parsed.length > 0 ? parsed : undefined;\n}\n\nfunction parseIdentity(value: unknown): InspectorIdentity | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const organizationName = parseNonBlankString(value.organizationName);\n const projectName = parseNonBlankString(value.projectName);\n if (organizationName === undefined || projectName === undefined) {\n return undefined;\n }\n\n return { organizationName, projectName };\n}\n\nfunction parsePlan(value: unknown): InspectorPlan | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const code = parseNonBlankString(value.code);\n const label = parseNonBlankString(value.label);\n if (code === undefined || label === undefined) {\n return undefined;\n }\n\n return { code, label };\n}\n\nfunction parseLicense(value: unknown): InspectorLicense | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n switch (value.state) {\n case \"valid\":\n case \"none\":\n case \"expired\":\n case \"unknown\":\n return { state: value.state };\n default:\n return undefined;\n }\n}\n\nfunction parseActionKind(value: unknown): InspectorAction[\"kind\"] | undefined {\n switch (value) {\n case \"manage_plan\":\n case \"renew\":\n case \"enable_intelligence\":\n return value;\n default:\n return undefined;\n }\n}\n\nfunction parseSafeActionUrl(value: unknown): string | undefined {\n const url = parseNonBlankString(value);\n if (url === undefined || url.includes(\"?\") || url.includes(\"#\")) {\n return undefined;\n }\n\n const authorityStart = url.indexOf(\"://\");\n if (authorityStart < 1) {\n return undefined;\n }\n\n const authorityAndPath = url.slice(authorityStart + 3);\n const pathStart = authorityAndPath.indexOf(\"/\");\n const authority =\n pathStart === -1 ? authorityAndPath : authorityAndPath.slice(0, pathStart);\n if (authority.includes(\"@\")) {\n return undefined;\n }\n\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return undefined;\n }\n\n if (parsed.hostname.length === 0 || parsed.username || parsed.password) {\n return undefined;\n }\n\n return isSafeDashboardUrl(parsed) ? url : undefined;\n}\n\nfunction parseAction(value: unknown): InspectorAction | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const kind = parseActionKind(value.kind);\n const url = parseSafeActionUrl(value.url);\n if (kind === undefined || url === undefined) {\n return undefined;\n }\n\n return { kind, url };\n}\n\nfunction isFiniteNonnegativeInteger(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction parseUsageLimit(value: unknown): InspectorUsageLimit | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n if (value.kind === \"finite\") {\n if (\n typeof value.value !== \"number\" ||\n !Number.isSafeInteger(value.value) ||\n value.value < 1\n ) {\n return undefined;\n }\n\n return { kind: \"finite\", value: value.value };\n }\n\n if (value.kind === \"unlimited\") {\n return { kind: \"unlimited\" };\n }\n\n if (value.kind === \"unknown\") {\n return { kind: \"unknown\" };\n }\n\n return undefined;\n}\n\nfunction parseUsage(value: unknown): InspectorUsage | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const limit = parseUsageLimit(value.limit);\n const used = value.used;\n if (!isFiniteNonnegativeInteger(used) || limit === undefined) {\n return undefined;\n }\n\n const rawExpiringSoonCount = readOwnDataProperty(value, \"expiringSoonCount\");\n const expiringSoonCount = isFiniteNonnegativeInteger(rawExpiringSoonCount)\n ? rawExpiringSoonCount\n : undefined;\n\n return {\n used,\n limit,\n ...(expiringSoonCount === undefined ? {} : { expiringSoonCount }),\n };\n}\n\n/**\n * Parses untrusted inspector metadata without letting one invalid optional\n * module hide the other valid modules.\n *\n * @param value - The decoded runtime response body.\n * @returns Normalized version 1 metadata, or `undefined` for an unsupported\n * top-level payload.\n */\nexport function parseInspectorMetadataV1(\n value: unknown,\n): InspectorMetadataV1 | undefined {\n if (!isRecord(value) || value.schemaVersion !== 1) {\n return undefined;\n }\n\n const identity = parseIdentity(value.identity);\n const plan = parsePlan(value.plan);\n const license = parseLicense(value.license);\n const action = parseAction(value.action);\n const usage = parseUsage(value.usage);\n\n return {\n schemaVersion: 1,\n ...(identity === undefined ? {} : { identity }),\n ...(plan === undefined ? {} : { plan }),\n ...(license === undefined ? {} : { license }),\n ...(action === undefined ? {} : { action }),\n ...(usage === undefined ? {} : { usage }),\n };\n}\n","import { isSafeDashboardUrl } from \"./dashboard-url\";\n\n/** A bounded page in the Inspector Learning snapshot. */\nexport interface InspectorLearningPage<T> {\n readonly page: number;\n readonly pageSize: number;\n readonly total: number;\n readonly totalPages: number;\n readonly items: readonly T[];\n}\n\nexport type InspectorLearningEvidence =\n | {\n readonly status: \"available\";\n readonly threadId: string;\n readonly threadName: string | null;\n readonly messageIds: readonly string[];\n readonly updatedAt: string;\n }\n | { readonly status: \"unavailable\" };\n\n/** A cited Trajectory, linked into the Intelligence web app. */\nexport type InspectorLearningTrajectoryEvidence =\n | {\n readonly status: \"available\";\n readonly trajectoryId: string;\n readonly eventCount: number;\n readonly url: string;\n }\n | { readonly status: \"unavailable\" };\n\nexport interface InspectorLearningInsight {\n readonly id: string;\n readonly statement: string;\n readonly impact: string;\n readonly totalThreadCount: number;\n readonly evidenceTruncated: boolean;\n readonly evidence: readonly InspectorLearningEvidence[];\n /** Absent when Intelligence predates Trajectory evidence. */\n readonly totalTrajectoryCount?: number;\n /** Absent when Intelligence predates Trajectory evidence. */\n readonly trajectoryEvidence?: readonly InspectorLearningTrajectoryEvidence[];\n}\n\nexport interface InspectorLearningSkill {\n readonly id: string;\n readonly name: string;\n readonly description: string;\n readonly revision: number;\n readonly skillMd: string;\n readonly sourceInsight: InspectorLearningInsight | null;\n}\n\nexport interface InspectorLearningSnapshotV1 {\n readonly schemaVersion: 1;\n readonly projectKey: string;\n readonly snapshotVersion: string;\n readonly webAppOrigin: string;\n readonly configuration:\n | { readonly state: \"not_configured\" }\n | {\n readonly state: \"invalid\";\n readonly reason: \"container\" | \"instrumentation\";\n }\n | {\n readonly state: \"configured\";\n readonly container: { readonly id: string; readonly name: string };\n }\n | { readonly state: \"selection_required\" };\n readonly pendingThreadCount: number;\n readonly run: {\n readonly hasActiveRun: boolean;\n readonly hasEverSucceeded: boolean;\n readonly latest: {\n readonly completedAt: string | null;\n readonly status:\n | \"queued\"\n | \"freezing\"\n | \"batching\"\n | \"reducing\"\n | \"finalizing\"\n | \"succeeded\"\n | \"failed\";\n } | null;\n };\n readonly pendingCandidateCount: number;\n readonly skillsPage: InspectorLearningPage<InspectorLearningSkill>;\n readonly insightsPage: InspectorLearningPage<InspectorLearningInsight>;\n readonly links: {\n readonly learning: string;\n readonly candidates: string | null;\n readonly runs: string | null;\n };\n}\n\nexport interface InspectorLearningRequestV1 {\n readonly agentId?: string;\n readonly skillsPage?: number;\n readonly insightsPage?: number;\n}\n\ntype RecordValue = Record<string, unknown>;\n\nconst record = (value: unknown): value is RecordValue =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst string = (value: unknown, maximum: number): value is string =>\n typeof value === \"string\" &&\n value.trim().length > 0 &&\n value.length <= maximum;\nconst integer = (value: unknown, minimum = 0): value is number =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value >= minimum;\nconst date = (value: unknown): value is string =>\n typeof value === \"string\" && !Number.isNaN(Date.parse(value));\n\n/**\n * Accepts only the configured Intelligence web-app origin.\n *\n * Learning links are server-authored actions. Treating every HTTPS origin as\n * trusted would let a misconfigured or compromised upstream turn Inspector\n * copy into a navigation primitive for an arbitrary site.\n */\nexport function parseInspectorLearningUrl(\n value: unknown,\n trustedOrigin: unknown,\n): string | undefined {\n if (\n typeof value !== \"string\" ||\n value.length > 4_000 ||\n typeof trustedOrigin !== \"string\" ||\n trustedOrigin.length > 2_000\n ) {\n return undefined;\n }\n try {\n const parsed = new URL(value);\n const configured = new URL(trustedOrigin);\n if (\n parsed.username ||\n parsed.password ||\n configured.username ||\n configured.password ||\n configured.pathname !== \"/\" ||\n configured.search ||\n configured.hash ||\n !isSafeDashboardUrl(configured) ||\n parsed.origin !== configured.origin\n ) {\n return undefined;\n }\n return parsed.toString();\n } catch {\n return undefined;\n }\n}\n\n/** Validates the canonical dashboard route after the origin check. */\nfunction validLearningPath(\n value: string,\n kind: \"learning\" | \"candidates\" | \"runs\",\n): boolean {\n const url = new URL(value);\n if (url.search || url.hash) return false;\n if (kind === \"learning\") {\n return (\n url.pathname === \"/learning\" ||\n /^\\/o\\/[^/]+\\/[^/]+\\/learning(?:\\/[^/]+)?$/u.test(url.pathname)\n );\n }\n return kind === \"candidates\"\n ? /^\\/o\\/[^/]+\\/[^/]+\\/learning\\/[^/]+\\/skills$/u.test(url.pathname)\n : /^\\/o\\/[^/]+\\/[^/]+\\/learning\\/[^/]+\\/analysis-results$/u.test(\n url.pathname,\n );\n}\n\nfunction parseEvidence(value: unknown): InspectorLearningEvidence | undefined {\n if (record(value) && value.status === \"unavailable\") {\n return Object.keys(value).length === 1\n ? { status: \"unavailable\" }\n : undefined;\n }\n if (\n !record(value) ||\n value.status !== \"available\" ||\n !string(value.threadId, 128) ||\n !date(value.updatedAt)\n ) {\n return undefined;\n }\n if (\n value.threadName !== null &&\n !(typeof value.threadName === \"string\" && value.threadName.length <= 4_000)\n ) {\n return undefined;\n }\n if (\n !Array.isArray(value.messageIds) ||\n value.messageIds.length > 200 ||\n !value.messageIds.every((id) => string(id, 128))\n ) {\n return undefined;\n }\n return {\n status: \"available\",\n threadId: value.threadId,\n threadName: value.threadName,\n messageIds: [...value.messageIds],\n updatedAt: value.updatedAt,\n };\n}\n\nfunction parseTrajectoryEvidence(\n value: unknown,\n webAppOrigin: string,\n): InspectorLearningTrajectoryEvidence | undefined {\n if (record(value) && value.status === \"unavailable\") {\n return Object.keys(value).length === 1\n ? { status: \"unavailable\" }\n : undefined;\n }\n if (\n !record(value) ||\n value.status !== \"available\" ||\n !string(value.trajectoryId, 128) ||\n !integer(value.eventCount)\n ) {\n return undefined;\n }\n const url = parseInspectorLearningUrl(value.url, webAppOrigin);\n if (!url) return undefined;\n return {\n status: \"available\",\n trajectoryId: value.trajectoryId,\n eventCount: value.eventCount,\n url,\n };\n}\n\nfunction parseInsight(\n value: unknown,\n webAppOrigin: string,\n): InspectorLearningInsight | undefined {\n if (\n !record(value) ||\n !string(value.id, 128) ||\n !string(value.statement, 4_000) ||\n !string(value.impact, 4_000) ||\n !integer(value.totalThreadCount) ||\n typeof value.evidenceTruncated !== \"boolean\" ||\n !Array.isArray(value.evidence) ||\n value.evidence.length > 100\n ) {\n return undefined;\n }\n const evidence = value.evidence.map(parseEvidence);\n if (evidence.some((item) => item === undefined)) return undefined;\n const insight: InspectorLearningInsight = {\n id: value.id,\n statement: value.statement,\n impact: value.impact,\n totalThreadCount: value.totalThreadCount,\n evidenceTruncated: value.evidenceTruncated,\n evidence: evidence as InspectorLearningEvidence[],\n };\n // Each Trajectory field is optional on its own; a malformed one rejects\n // the Insight, an absent one leaves the Thread-only shape untouched.\n let totalTrajectoryCount: number | undefined;\n if (value.totalTrajectoryCount !== undefined) {\n if (!integer(value.totalTrajectoryCount)) return undefined;\n totalTrajectoryCount = value.totalTrajectoryCount;\n }\n let trajectoryEvidence: InspectorLearningTrajectoryEvidence[] | undefined;\n if (value.trajectoryEvidence !== undefined) {\n if (\n !Array.isArray(value.trajectoryEvidence) ||\n value.trajectoryEvidence.length > 100\n ) {\n return undefined;\n }\n const parsed = value.trajectoryEvidence.map((item) =>\n parseTrajectoryEvidence(item, webAppOrigin),\n );\n if (parsed.some((item) => item === undefined)) return undefined;\n trajectoryEvidence = parsed as InspectorLearningTrajectoryEvidence[];\n }\n return {\n ...insight,\n ...(totalTrajectoryCount === undefined ? {} : { totalTrajectoryCount }),\n ...(trajectoryEvidence === undefined ? {} : { trajectoryEvidence }),\n };\n}\n\nfunction parseSkill(\n value: unknown,\n webAppOrigin: string,\n): InspectorLearningSkill | undefined {\n if (\n !record(value) ||\n !string(value.id, 128) ||\n !string(value.name, 128) ||\n !string(value.description, 4_000) ||\n !integer(value.revision, 1) ||\n typeof value.skillMd !== \"string\" ||\n value.skillMd.length > 131_072\n ) {\n return undefined;\n }\n const sourceInsight =\n value.sourceInsight === null\n ? null\n : parseInsight(value.sourceInsight, webAppOrigin);\n if (sourceInsight === undefined) return undefined;\n return {\n id: value.id,\n name: value.name,\n description: value.description,\n revision: value.revision,\n skillMd: value.skillMd,\n sourceInsight,\n };\n}\n\nfunction parsePage<T>(\n value: unknown,\n pageSize: 3 | 4,\n parseItem: (item: unknown) => T | undefined,\n): InspectorLearningPage<T> | undefined {\n if (\n !record(value) ||\n !integer(value.page, 1) ||\n value.pageSize !== pageSize ||\n !integer(value.total) ||\n !integer(value.totalPages) ||\n !Array.isArray(value.items) ||\n value.items.length > pageSize\n ) {\n return undefined;\n }\n const items = value.items.map(parseItem);\n if (items.some((item) => item === undefined)) return undefined;\n if (value.total === 0) {\n if (value.page !== 1 || value.totalPages !== 0 || items.length !== 0) {\n return undefined;\n }\n } else {\n const totalPages = Math.ceil(value.total / pageSize);\n const expectedItems = Math.min(\n pageSize,\n value.total - (value.page - 1) * pageSize,\n );\n if (\n value.totalPages !== totalPages ||\n value.page > totalPages ||\n items.length !== expectedItems\n ) {\n return undefined;\n }\n }\n return {\n page: value.page,\n pageSize,\n total: value.total,\n totalPages: value.totalPages,\n items: items as T[],\n };\n}\n\nfunction parseConfiguration(\n value: unknown,\n): InspectorLearningSnapshotV1[\"configuration\"] | undefined {\n if (!record(value)) return undefined;\n if (\n value.state === \"not_configured\" ||\n value.state === \"selection_required\"\n ) {\n return { state: value.state };\n }\n if (\n value.state === \"invalid\" &&\n (value.reason === \"container\" || value.reason === \"instrumentation\")\n ) {\n return { state: value.state, reason: value.reason };\n }\n if (\n value.state === \"configured\" &&\n record(value.container) &&\n string(value.container.id, 128) &&\n string(value.container.name, 128)\n ) {\n return {\n state: \"configured\",\n container: { id: value.container.id, name: value.container.name },\n };\n }\n return undefined;\n}\n\nconst runStatuses = new Set([\n \"queued\",\n \"freezing\",\n \"batching\",\n \"reducing\",\n \"finalizing\",\n \"succeeded\",\n \"failed\",\n]);\n\n/** Validates and copies an untrusted Learning snapshot at each process boundary. */\nexport function parseInspectorLearningSnapshotV1(\n value: unknown,\n): InspectorLearningSnapshotV1 | undefined {\n if (\n !record(value) ||\n value.schemaVersion !== 1 ||\n !string(value.projectKey, 128) ||\n !string(value.snapshotVersion, 128) ||\n !integer(value.pendingThreadCount) ||\n !integer(value.pendingCandidateCount) ||\n !record(value.run) ||\n typeof value.run.hasActiveRun !== \"boolean\" ||\n typeof value.run.hasEverSucceeded !== \"boolean\"\n ) {\n return undefined;\n }\n const originUrl = parseInspectorLearningUrl(\n value.webAppOrigin,\n value.webAppOrigin,\n );\n if (!originUrl || new URL(originUrl).pathname !== \"/\") return undefined;\n const webAppOrigin = new URL(originUrl).origin;\n const configuration = parseConfiguration(value.configuration);\n const skillsPage = parsePage(value.skillsPage, 3, (item) =>\n parseSkill(item, webAppOrigin),\n );\n const insightsPage = parsePage(value.insightsPage, 4, (item) =>\n parseInsight(item, webAppOrigin),\n );\n if (!configuration || !skillsPage || !insightsPage) return undefined;\n let latest: InspectorLearningSnapshotV1[\"run\"][\"latest\"] = null;\n if (value.run.latest !== null) {\n const latestRun = value.run.latest;\n if (!record(latestRun)) {\n return undefined;\n }\n const { status, completedAt } = latestRun;\n if (\n typeof status !== \"string\" ||\n !runStatuses.has(status) ||\n (completedAt !== null && !date(completedAt))\n )\n return undefined;\n latest = {\n status: status as NonNullable<typeof latest>[\"status\"],\n completedAt: completedAt as NonNullable<typeof latest>[\"completedAt\"],\n };\n }\n if (!record(value.links)) return undefined;\n const learning = parseInspectorLearningUrl(\n value.links.learning,\n webAppOrigin,\n );\n const candidates =\n value.links.candidates === null\n ? null\n : parseInspectorLearningUrl(value.links.candidates, webAppOrigin);\n const runs =\n value.links.runs === null\n ? null\n : parseInspectorLearningUrl(value.links.runs, webAppOrigin);\n if (\n !learning ||\n candidates === undefined ||\n runs === undefined ||\n !validLearningPath(learning, \"learning\") ||\n (candidates !== null && !validLearningPath(candidates, \"candidates\")) ||\n (runs !== null && !validLearningPath(runs, \"runs\")) ||\n (value.pendingThreadCount > 0 && runs === null) ||\n (value.pendingCandidateCount > 0 && candidates === null)\n )\n return undefined;\n return {\n schemaVersion: 1,\n projectKey: value.projectKey,\n snapshotVersion: value.snapshotVersion,\n webAppOrigin,\n configuration,\n pendingThreadCount: value.pendingThreadCount,\n run: {\n hasActiveRun: value.run.hasActiveRun,\n hasEverSucceeded: value.run.hasEverSucceeded,\n latest,\n },\n pendingCandidateCount: value.pendingCandidateCount,\n skillsPage,\n insightsPage,\n links: { learning, candidates, runs },\n };\n}\n\n/** Normalizes the browser-owned request without accepting container scope. */\nexport function parseInspectorLearningRequestV1(\n value: unknown,\n): InspectorLearningRequestV1 | undefined {\n if (!record(value)) return undefined;\n if (\n Object.keys(value).some(\n (key) => ![\"agentId\", \"skillsPage\", \"insightsPage\"].includes(key),\n )\n ) {\n return undefined;\n }\n const agentId = value.agentId;\n const skillsPage = value.skillsPage;\n const insightsPage = value.insightsPage;\n if (agentId !== undefined && !string(agentId, 128)) return undefined;\n if (skillsPage !== undefined && !integer(skillsPage, 1)) return undefined;\n if (insightsPage !== undefined && !integer(insightsPage, 1)) return undefined;\n return {\n ...(agentId === undefined ? {} : { agentId }),\n ...(skillsPage === undefined ? {} : { skillsPage }),\n ...(insightsPage === undefined ? {} : { insightsPage }),\n };\n}\n","export interface InspectorVisibilityOptions {\n enableInspector?: boolean;\n isBrowser: boolean;\n isDevelopment: boolean;\n}\n\n/**\n * The Inspector is a development-only browser tool. Consumers may disable it,\n * but an explicit `true` never overrides a production or server environment.\n */\nexport function shouldEnableInspector({\n enableInspector,\n isBrowser,\n isDevelopment,\n}: InspectorVisibilityOptions): boolean {\n return isBrowser && isDevelopment && enableInspector !== false;\n}\n","import type { AgentCapabilities } from \"@ag-ui/core\";\n\nexport type MaybePromise<T> = T | PromiseLike<T>;\n\n/**\n * More specific utility for records with at least one key\n */\nexport type NonEmptyRecord<T> =\n T extends Record<string, unknown>\n ? keyof T extends never\n ? never\n : T\n : never;\n\n/**\n * Type representing an agent's basic information\n */\nexport interface AgentDescription {\n name: string;\n className: string;\n description: string;\n capabilities?: AgentCapabilities;\n}\n\nexport type RuntimeMode = \"sse\" | \"intelligence\";\n\nexport const RUNTIME_MODE_SSE = \"sse\" as const;\nexport const RUNTIME_MODE_INTELLIGENCE = \"intelligence\" as const;\n\nexport interface IntelligenceRuntimeInfo {\n wsUrl: string;\n}\n\nexport interface ThreadEndpointRuntimeInfo {\n list: boolean;\n inspect: boolean;\n mutations: boolean;\n realtimeMetadata: boolean;\n}\n\nexport type RuntimeLicenseStatus =\n | \"valid\"\n | \"none\"\n | \"expired\"\n | \"expiring\"\n | \"invalid\"\n | \"unknown\";\n\n/** Runtime entitlement authority resolved by a managed or self-hosted backend. */\ninterface RuntimeEntitlement {\n /** Whether the resolved entitlement currently grants product access. */\n active: boolean;\n /** Deployment authority that produced this entitlement. */\n source:\n | \"managedOrgSubscription\"\n | \"selfHostedDeploymentLicense\"\n | \"awsMarketplaceDeploymentLicense\";\n /** Boolean feature grants keyed by stable feature id. */\n features: Record<string, boolean>;\n /** Numeric limits keyed by stable feature id. */\n limits: Record<string, number>;\n /** Optional catalog plan code supplied by the entitlement authority. */\n planCode?: string;\n /** Optional lower-level source metadata supplied by the authority. */\n entitlementSource?: string;\n}\n\n/** Public diagnostic returned when Runtime entitlement resolution is not ready. */\ninterface RuntimeEntitlementError {\n /** Stable backend or SDK error code. */\n code: string;\n /** Safe human-readable diagnostic. */\n message: string;\n /** Whether a later resolution attempt may succeed without reconfiguration. */\n retryable: boolean;\n /** Optional originating request correlation id. */\n requestId?: string;\n /** Optional originating trace correlation id. */\n traceId?: string;\n}\n\n/** Successfully resolved Runtime entitlement response. */\ninterface RuntimeEntitlementReadyResponse {\n status: \"ready\";\n entitlement: RuntimeEntitlement;\n error?: never;\n}\n\n/** Structured non-ready Runtime entitlement response. */\ninterface RuntimeEntitlementErrorResponse {\n status: \"degraded\" | \"misconfigured\" | \"unavailable\";\n entitlement?: never;\n error: RuntimeEntitlementError;\n}\n\n/** Final structured Runtime entitlement response exposed through `/info`. */\nexport type RuntimeEntitlementResponse =\n | RuntimeEntitlementReadyResponse\n | RuntimeEntitlementErrorResponse;\n\nexport interface A2UIRuntimeInfo {\n enabled: boolean;\n /**\n * Agent ids the runtime applies A2UI to. When omitted, A2UI applies to\n * every agent served by the runtime.\n */\n agents?: string[];\n}\n\n/** Intelligence resource support available through a single runtime route. */\nexport interface SingleRouteRuntimeInfo {\n /** Whether the runtime accepts resource requests through the single route. */\n resourceOperations: boolean;\n /** Thread features available through the single-route resource bridge. */\n threadEndpoints: ThreadEndpointRuntimeInfo;\n}\n\nexport interface RuntimeInfo {\n version: string;\n agents: Record<string, AgentDescription>;\n audioFileTranscriptionEnabled: boolean;\n mode: RuntimeMode;\n intelligence?: IntelligenceRuntimeInfo;\n threadEndpoints?: ThreadEndpointRuntimeInfo;\n /** Optional capabilities exposed by runtimes that use one HTTP route. */\n singleRoute?: SingleRouteRuntimeInfo;\n /** Whether this runtime exposes trusted inspector metadata. */\n inspectorMetadata?: boolean;\n /** Whether this runtime exposes the debug-authorized Learning snapshot. */\n inspectorLearning?: boolean;\n /**\n * When true, the runtime exposes POST /agent/:agentId/suggest for stateless\n * suggestion generation. Absent on older runtimes; clients fall back to a\n * client-side agent run.\n */\n suggestions?: boolean;\n /**\n * @deprecated Use `a2ui` instead, which preserves per-agent scoping.\n * Kept for backward compatibility with older clients.\n */\n a2uiEnabled?: boolean;\n a2ui?: A2UIRuntimeInfo;\n openGenerativeUIEnabled?: boolean;\n /** Structured Runtime-level entitlement authority, when advertised. */\n runtimeEntitlements?: RuntimeEntitlementResponse;\n /** Legacy compatibility diagnostic retained for older Core/Inspector clients. */\n licenseStatus?: RuntimeLicenseStatus;\n telemetryDisabled?: boolean;\n}\n","import { v4 as uuidv4, validate, v5 as uuidv5 } from \"uuid\";\n\nexport function randomId() {\n return \"ck-\" + uuidv4();\n}\n\nexport function randomUUID() {\n return uuidv4();\n}\n\n/**\n * Recursively converts an object to a serializable form by converting functions to their string representation.\n */\nfunction toSerializable(value: unknown): unknown {\n if (typeof value === \"function\") {\n return value.toString();\n }\n if (Array.isArray(value)) {\n return value.map(toSerializable);\n }\n if (value !== null && typeof value === \"object\") {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n result[key] = toSerializable((value as Record<string, unknown>)[key]);\n }\n return result;\n }\n return value;\n}\n\nexport function dataToUUID(input: string | object, namespace?: string): string {\n const BASE_NAMESPACE = \"e4b01160-ff74-4c6e-9b27-d53cd930fe8e\";\n // Since namespace needs to be a uuid, we are creating a uuid for it.\n const boundNamespace = namespace\n ? uuidv5(namespace, BASE_NAMESPACE)\n : BASE_NAMESPACE;\n\n const stringInput =\n typeof input === \"string\" ? input : JSON.stringify(toSerializable(input));\n return uuidv5(stringInput, boundNamespace);\n}\n\nexport function isValidUUID(uuid: string) {\n return validate(uuid);\n}\n","/**\n * Safely read a Response/Request body with sensible defaults:\n * - clones the response/request to avoid consuming the original response/request\n * - Skips GET/HEAD\n * - Tries JSON first regardless of content-type\n * - Falls back to text and optionally parses when it \"looks\" like JSON\n */\nexport async function readBody<T extends Response | Request>(\n r: T,\n): Promise<unknown> {\n // skip GET/HEAD requests (unchanged)\n const method = \"method\" in r ? r.method.toUpperCase() : undefined;\n if (method === \"GET\" || method === \"HEAD\") {\n return undefined;\n }\n\n // no body at all → undefined (unchanged)\n if (!(\"body\" in r) || r.body == null) {\n return undefined;\n }\n\n // 1) try JSON (unchanged)\n try {\n return await r.clone().json();\n } catch {\n // 2) try text (unchanged + your whitespace/JSON-heuristic)\n try {\n const text = await r.clone().text();\n const trimmed = text.trim();\n\n if (trimmed.length === 0) return text;\n\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return text;\n }\n }\n return text;\n } catch {\n // 3) FINAL FALLBACK: manual read that accepts string or bytes\n try {\n const c = r.clone();\n const stream: ReadableStream | null = c.body ?? null;\n if (!stream) return undefined;\n\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let out = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (typeof value === \"string\") {\n out += value; // accept string chunks\n } else {\n out += decoder.decode(value, { stream: true }); // bytes\n }\n }\n out += decoder.decode(); // flush\n\n const trimmed = out.trim();\n if (trimmed.length === 0) return out;\n\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return out;\n }\n }\n return out;\n } catch {\n return undefined; // same \"give up\" behavior you had\n }\n }\n }\n}\n","import type { AssistantMessage, Message } from \"@ag-ui/core\";\n\n/**\n * Stable per-row view keys for chat transcripts, across backends that re-key a\n * message mid-stream. Shared by every frontend package, because the defect and\n * the correlation signal are in the message stream, not in any one framework.\n *\n * ## The problem\n *\n * A message's canonical `id` is not stable within a turn. LangChain stamps a\n * placeholder id on the first streamed chunk when the provider didn't supply\n * one (`chat_models.py`: `if chunk.message.id is None: chunk.message.id =\n * \"lc_run-\" + \"-\" + run_id`), then prefers any provider-assigned id it sees\n * while merging chunks (`messages/ai.py`, \"Ranks are defined by the order of\n * preference\"). The `MESSAGES_SNAPSHOT` therefore carries the provider's final\n * id (e.g. `resp_…`) for a message the client already knows as `lc_run--…`.\n *\n * Every framework destroys and recreates a row whose key changes, so keying\n * rows by `id` turned that swap into the visible HITL chat flash, where a\n * rendered approval card appears to reset during a tool's\n * `executing → complete` transition.\n *\n * This is provider-conditional: providers that stamp an id on every chunk (so\n * `chunk.message.id is None` never holds) never trigger a rename.\n *\n * ## The approach\n *\n * Tool-call ids survive the rename, so they are used as *anchors*: the first\n * message seen carrying a given tool call records the key it was assigned, and\n * any later message carrying that same tool call reuses it. The store is an\n * override table consulted before falling back to `message.id`. Resolving only\n * reads it; each render that reaches the DOM then records what it rendered:\n *\n * ```text\n * render 1 id=lc_run--1 no tools key = message.id = lc_run--1\n * commit 1 store {}\n * render 2 id=lc_run--1 tc call_A key = message.id = lc_run--1\n * commit 2 store { tc:call_A -> lc_run--1 }\n * render 3 id=resp_1 tc call_A key = store[tc:call_A]\n * = lc_run--1 (row survives)\n * commit 3 store unchanged\n * ```\n *\n * Recording the anchor at commit 2 — while the id is still stable — is what\n * makes render 3 resolvable. Note the fix does not depend on render 2\n * existing: a message born already carrying a tool call anchors on the first\n * render that commits it, under whatever id it holds then.\n *\n * ## Why an override table rather than keying rows by tool-call id\n *\n * Deriving the key from the tool call directly (`tc:<id>` whenever a tool call\n * is present) needs no state, but changes the key the moment a tool call\n * *appears* — so an assistant message that streams text and then calls a tool\n * is torn down on that transition, for every provider, whether or not it\n * renames. That trades a conditional flash for an unconditional one. Recording\n * an override keeps the key the row already had.\n *\n * ## Cost\n *\n * The store holds only `tc:<toolCallId>` entries, so a conversation with no\n * tool calls keeps an empty store and behaviour byte-identical to keying by\n * `id`. Size is bounded to the tool calls of the currently-rendered messages\n * (see `pruneRowKeyStore`), not the conversation length. Deleting the store\n * reverts to plain `id` keying.\n *\n * ## Known gaps\n *\n * - A text-only assistant message has no anchor, so it still re-keys. No\n * client-side correlation signal exists for it; the fix is stable ids\n * upstream.\n * - If the tool call's arrival and the id swap land in the same update, the\n * intermediate state never renders, the anchor is never recorded, and the\n * row is recreated as before. Correlating in the event-apply layer (i.e. in\n * the AG-UI client, which observes every intermediate state) would be immune.\n */\n\nconst TOOL_ANCHOR_PREFIX = \"tc:\";\n\nexport interface RowKeyStore {\n /**\n * `tc:<toolCallId>` → the row key first assigned to a message carrying that\n * tool call. Populated only for assistant messages that carry tool calls.\n */\n overrides: Map<string, string>;\n /**\n * Anchors carried by more than one message in the last rendered list. Such\n * an anchor identifies no single row, so it is never used to vend a key.\n */\n ambiguous: Set<string>;\n}\n\nexport function createRowKeyStore(): RowKeyStore {\n return { overrides: new Map(), ambiguous: new Set() };\n}\n\n/**\n * Anchors a message contributes. Only assistant tool calls qualify: LangChain's\n * id preference applies when merging `AIMessageChunk`s, so user message ids are\n * not renamed, and `role: \"tool\"` messages are not rendered as rows. Every tool\n * call is used (not just the first) so the anchor survives tool-call reordering\n * between snapshots.\n */\nfunction toolAnchorsOf(message: Message | undefined): string[] {\n if (message?.role !== \"assistant\") return [];\n const toolCalls = (message as AssistantMessage).toolCalls;\n if (!toolCalls?.length) return [];\n\n const anchors: string[] = [];\n for (const toolCall of toolCalls) {\n if (toolCall?.id) anchors.push(`${TOOL_ANCHOR_PREFIX}${toolCall.id}`);\n }\n return anchors;\n}\n\n/**\n * Resolves the row key for every message, returned by position.\n *\n * Pure: it reads `store` and never writes to it. Every framework here may\n * evaluate a render pass whose result never reaches the DOM — an abandoned\n * concurrent render in React, a discarded `computed` evaluation in Vue or\n * Angular. An anchor recorded by such a pass would vend its key to the pass\n * that does render, re-keying the row the user is looking at, which is the\n * teardown this module exists to prevent. Anchors are recorded by\n * `commitRowKeyStore`, from whichever phase each framework runs after the DOM\n * is updated.\n *\n * Uniqueness is structural rather than assumed: a caller that does not\n * deduplicate can pass two rows with the same id, and an override can vend a\n * key equal to a later message's own id.\n */\nexport function resolveRowRenderKeys(\n store: RowKeyStore,\n messages: readonly (Message | undefined)[],\n): string[] {\n const keys: string[] = [];\n const claimed = new Set<string>();\n\n messages.forEach((message, index) => {\n const anchors = toolAnchorsOf(message);\n\n // Reuse the key recorded for any of this message's anchors. An override\n // pointing at a key another row already claimed this pass is skipped: two\n // messages can share a tool-call id (upstream bug, or replayed state), and\n // the later one falls back to its own id instead.\n let key: string | undefined;\n for (const anchor of anchors) {\n if (store.ambiguous.has(anchor)) continue;\n const recorded = store.overrides.get(anchor);\n if (recorded !== undefined && !claimed.has(recorded)) {\n key = recorded;\n break;\n }\n }\n\n // The index fallback covers a message with no usable id.\n key ??= message?.id || `index-${index}`;\n\n if (claimed.has(key)) {\n let suffix = 2;\n while (claimed.has(`${key}:${suffix}`)) suffix += 1;\n key = `${key}:${suffix}`;\n }\n\n keys.push(key);\n claimed.add(key);\n });\n\n return keys;\n}\n\n/**\n * `message.id` → row key, for callers that render by message rather than by\n * position. `messages` must be deduplicated: duplicate ids would overwrite\n * each other in the returned map.\n */\nexport function resolveRowRenderKeysById(\n store: RowKeyStore,\n messages: readonly Message[],\n): Map<string, string> {\n const keys = resolveRowRenderKeys(store, messages);\n const byId = new Map<string, string>();\n messages.forEach((message, index) => {\n const key = keys[index];\n if (key !== undefined) byId.set(message.id, key);\n });\n return byId;\n}\n\n/**\n * Records the anchors of a rendered list, then bounds the store to it. Call\n * from the phase that runs after the DOM is updated, never while resolving —\n * see `resolveRowRenderKeys`.\n *\n * Re-resolving here reproduces the keys the rows were rendered with, because\n * the store cannot change between a render and its own post-render phase.\n *\n * An anchor carried by two rows in the same list is marked ambiguous rather\n * than recorded. Recording it would give the first row's key to whichever row\n * outlived the other, and with it that row's DOM and component state.\n */\nexport function commitRowKeyStore(\n store: RowKeyStore,\n messages: readonly (Message | undefined)[],\n): void {\n const keys = resolveRowRenderKeys(store, messages);\n\n const anchorCounts = new Map<string, number>();\n for (const message of messages) {\n for (const anchor of toolAnchorsOf(message)) {\n anchorCounts.set(anchor, (anchorCounts.get(anchor) ?? 0) + 1);\n }\n }\n\n // Ambiguity is a property of the rendered list, so it is recomputed rather\n // than accumulated: an anchor left alone by the row that shadowed it becomes\n // usable again.\n store.ambiguous.clear();\n for (const [anchor, count] of anchorCounts) {\n if (count > 1) {\n store.ambiguous.add(anchor);\n store.overrides.delete(anchor);\n }\n }\n\n // First claimant of an anchor owns it, so a re-keyed message resolves to the\n // key the row already had rather than overwriting it.\n messages.forEach((message, index) => {\n const key = keys[index];\n if (key === undefined) return;\n for (const anchor of toolAnchorsOf(message)) {\n if (store.ambiguous.has(anchor)) continue;\n if (!store.overrides.has(anchor)) store.overrides.set(anchor, key);\n }\n });\n\n pruneRowKeyStore(store, messages);\n}\n\n/**\n * Drops anchors no longer present in `messages`, bounding the store to the\n * tool calls of the currently-rendered messages. Called by\n * `commitRowKeyStore`; like it, this writes to the store and so belongs after\n * the DOM is updated, never while resolving.\n *\n * Pruned entries are unreachable by construction: `resolveRowRenderKeys` only\n * looks up anchors belonging to messages in the list it is given.\n */\nexport function pruneRowKeyStore(\n store: RowKeyStore,\n messages: readonly (Message | undefined)[],\n): void {\n const live = new Set<string>();\n for (const message of messages) {\n for (const anchor of toolAnchorsOf(message)) live.add(anchor);\n }\n\n for (const anchor of store.overrides.keys()) {\n if (!live.has(anchor)) store.overrides.delete(anchor);\n }\n for (const anchor of store.ambiguous) {\n if (!live.has(anchor)) store.ambiguous.delete(anchor);\n }\n}\n","export * from \"./clipboard\";\nexport * from \"./conditions\";\nexport * from \"./console-styling\";\nexport * from \"./errors\";\nexport * from \"./json-schema\";\nexport * from \"./inspector-metadata\";\nexport * from \"./inspector-learning\";\nexport * from \"./inspector-visibility\";\nexport * from \"./types\";\nexport * from \"./random-id\";\nexport * from \"./requests\";\nexport * from \"./row-render-keys\";\n\nimport * as PartialJSON from \"partial-json\";\n\n/**\n * Safely parses a JSON string into an object\n * @param json The JSON string to parse\n * @param fallback Optional fallback value to return if parsing fails. If not provided or set to \"unset\", returns null\n * @returns The parsed JSON object, or the fallback value (or null) if parsing fails\n */\nexport function parseJson(json: string, fallback: any = \"unset\") {\n try {\n return JSON.parse(json);\n } catch {\n return fallback === \"unset\" ? null : fallback;\n }\n}\n\n// Allow partial values of every type except unterminated numbers. A cut-off\n// number is a *different* number (`{\"max\":1` is about to become 100, not 1),\n// while a cut-off string is still the beginning of the final string. Numbers\n// therefore only appear once terminated by `,`, `}` or `]`.\nconst PARTIAL_JSON_ALLOW = PartialJSON.Allow.ALL & ~PartialJSON.Allow.NUM;\n\n/**\n * Parses a partial/incomplete JSON string, returning as much valid data as possible.\n * Falls back to an empty object if parsing fails entirely.\n */\nexport function partialJSONParse(json: string) {\n try {\n const parsed = PartialJSON.parse(json, PARTIAL_JSON_ALLOW);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n return {};\n } catch {\n return {};\n }\n}\n\n/**\n * Returns an exponential backoff function suitable for Phoenix.js\n * `reconnectAfterMs` and `rejoinAfterMs` options.\n *\n * @param baseMs - Initial delay for the first retry attempt.\n * @param maxMs - Upper bound — delays are capped at this value.\n *\n * Phoenix calls the returned function with a 1-based `tries` count.\n * The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.\n */\nexport function phoenixExponentialBackoff(\n baseMs: number,\n maxMs: number,\n): (tries: number) => number {\n return (tries: number) => Math.min(baseMs * 2 ** (tries - 1), maxMs);\n}\n\n/**\n * Maps an array of items to a new array, skipping items that throw errors during mapping\n * @param items The array to map\n * @param callback The mapping function to apply to each item\n * @returns A new array containing only the successfully mapped items\n */\nexport function tryMap<TItem, TMapped>(\n items: TItem[],\n callback: (item: TItem, index: number, array: TItem[]) => TMapped,\n): TMapped[] {\n return items.reduce<TMapped[]>((acc, item, index, array) => {\n try {\n acc.push(callback(item, index, array));\n } catch (error) {\n console.error(error);\n }\n return acc;\n }, []);\n}\n\n/**\n * Checks if the current environment is macOS\n * @returns {boolean} True if running on macOS, false otherwise\n */\nexport function isMacOS(): boolean {\n return /Mac|iMac|Macintosh/i.test(navigator.userAgent);\n}\n\n/**\n * Safely parses a JSON string into a tool arguments object.\n * Returns the parsed object only if it's a plain object (not an array, null, etc.).\n * Falls back to an empty object for any non-object JSON value or parse failure.\n */\nexport function safeParseToolArgs(raw: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n console.warn(\n `[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`,\n );\n return {};\n } catch {\n console.warn(\n \"[CopilotKit] Failed to parse tool arguments, falling back to empty object\",\n );\n return {};\n }\n}\n","export const COPILOT_CLOUD_API_URL = \"https://api.cloud.copilotkit.ai\";\nexport const COPILOT_CLOUD_VERSION = \"v1\";\nexport const COPILOT_CLOUD_CHAT_URL = `${COPILOT_CLOUD_API_URL}/copilotkit/${COPILOT_CLOUD_VERSION}`;\nexport const COPILOT_CLOUD_PUBLIC_API_KEY_HEADER =\n \"X-CopilotCloud-Public-Api-Key\";\n\nexport const DEFAULT_AGENT_ID = \"default\";\n\n/**\n * `RUN_ERROR` code the runtime sends when a run is rejected because the\n * thread already has one in flight. CopilotKit core reports it as\n * `agent_thread_locked`.\n */\nexport const THREAD_ALREADY_RUNNING_ERROR_CODE = \"THREAD_ALREADY_RUNNING\";\n\n/** Phoenix channel event name used for all AG-UI events. */\nexport const AG_UI_CHANNEL_EVENT = \"ag-ui\";\n","/**\n * Checks if telemetry is disabled via environment variables.\n * Users can opt out by setting:\n * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1\n * - DO_NOT_TRACK=true or DO_NOT_TRACK=1\n *\n * Lives in its own module so that the browser-facing root entry can\n * re-export it without pulling in `telemetry-client.ts`, whose\n * `@segment/analytics-node` import drags Node built-ins into browser\n * bundler module graphs. See the note in `../index.ts`.\n */\nexport function isTelemetryDisabled(): boolean {\n return (\n (process.env as Record<string, string | undefined>)\n .COPILOTKIT_TELEMETRY_DISABLED === \"true\" ||\n (process.env as Record<string, string | undefined>)\n .COPILOTKIT_TELEMETRY_DISABLED === \"1\" ||\n (process.env as Record<string, string | undefined>).DO_NOT_TRACK ===\n \"true\" ||\n (process.env as Record<string, string | undefined>).DO_NOT_TRACK === \"1\"\n );\n}\n","// Per-event telemetry metadata shared by both TelemetryClients.\n//\n// Two clients emit `oss.runtime.*`: the v1 client in this package and the\n// v2 client in @copilotkit/runtime. Neither samples the lambda sink any\n// more — that sink is ours, so anonymous volume costs us nothing per\n// event and full fidelity beats an extrapolation. One wire is still\n// gated: the Segment copy the v1 client sends, which is billed per event.\n//\n// Every event therefore still carries a sampling block, because the two\n// populations remain distinguishable and a Segment-sourced count still\n// needs sum(sampleWeight) to mean anything. On the lambda wire the block\n// reads sampleRate=1/sampleWeight=1, which is the honest answer rather\n// than a placeholder.\n//\n// The two clients computed this independently and drifted: v2 sampled but\n// stamped nothing, leaving ~24% of runtime volume unweightable from the\n// data alone (OSS-1017). Computing it here is what stops them drifting\n// again.\n\n/** The rate a sink that takes every event is \"gated\" at. */\nexport const UNSAMPLED_RATE = 1;\n\n/** Identifies which client emitted an event. */\nexport const TELEMETRY_EMITTER_V1 = \"v1-shared\";\nexport const TELEMETRY_EMITTER_V2 = \"v2-runtime\";\n\nexport type TelemetryEmitter =\n | typeof TELEMETRY_EMITTER_V1\n | typeof TELEMETRY_EMITTER_V2;\n\n/**\n * Which public API surface the developer built against.\n *\n * Separate from {@link TelemetryEmitter} on purpose. The emitter names a\n * client library, and there are six of them across four languages; the\n * surface answers the question anyone actually asks of this data, which\n * is how much traffic still arrives through the deprecated v1 API. The\n * native runtimes (Go, Python, Ruby, .NET) expose v2 only, so they report\n * `v2` without having a v1 notion of their own.\n */\n// `as const` so the values keep their literal types when they land in a\n// mutable object property, which is how the v1 shim passes the surface\n// into the V2 runtime's options.\nexport const TELEMETRY_SURFACE_V1 = \"v1\" as const;\nexport const TELEMETRY_SURFACE_V2 = \"v2\" as const;\n\nexport type TelemetrySurface =\n | typeof TELEMETRY_SURFACE_V1\n | typeof TELEMETRY_SURFACE_V2;\n\n/**\n * Which wire an event copy travelled on. The v1 client sends each capture\n * to both, so this is what tells the two copies apart downstream\n * (OSS-1019); the v2 client only ever sends to the lambda sink.\n */\nexport type TelemetryTransport = \"segment\" | \"lambda\";\n\nexport interface SamplingMeta {\n /** The rate this event was actually gated at: 1 when unsampled or identified. */\n sampleRate: number;\n sampleRateAdjustmentFactor: number;\n /** Multiply by this to extrapolate the population the event stands for. */\n sampleWeight: number;\n /** Whether the event bypassed the sample gate. */\n telemetry_identified: boolean;\n}\n\n/**\n * Compute the sampling block for one captured event.\n *\n * `telemetryId` is the caller's parsed license telemetry_id, or null when\n * anonymous — it decides the branch, and is deliberately not returned:\n * only the non-PII shape below travels on the event.\n *\n * `sampleRate` is the rate of the wire this copy travels on, so an\n * unsampled sink passes {@link UNSAMPLED_RATE}. Call it once per wire:\n * the v1 client sends one capture to two wires gated differently, and a\n * shared block would misweight one of them.\n */\nexport function computeSamplingMeta({\n telemetryId,\n sampleRate,\n}: {\n telemetryId: string | null;\n sampleRate: number;\n}): SamplingMeta {\n const identified = Boolean(telemetryId);\n // Identified events ship at a 100% effective rate, anonymous ones at\n // sampleRate. Computed per event because a single global weight would\n // overweight identified-customer counts by 1/sampleRate.\n const effectiveSampleRate = identified ? 1 : sampleRate;\n\n return {\n sampleRate: effectiveSampleRate,\n sampleRateAdjustmentFactor: 1 - effectiveSampleRate,\n sampleWeight: 1 / effectiveSampleRate,\n // Stated outright rather than inferred from sampleWeight === 1:\n // under COPILOTKIT_TELEMETRY_SAMPLE_RATE=1 anonymous events also\n // weigh 1, and the two populations stop being distinguishable\n // (OSS-1018).\n telemetry_identified: identified,\n };\n}\n","// Which endpoint the runtime sends completions to, as a closed vocabulary.\n//\n// The AI SDK's provider label cannot answer this. A model built by\n// `createOpenAI` reports only its wire API: `openai.responses` for both\n// api.openai.com and Azure (whose own migration guide tells customers to use\n// exactly that client), and `openai.chat` for OpenRouter and a laptop running\n// Ollama alike. So the provider field reports the wire protocol, and the host\n// reports the vendor.\n//\n// Only the classification travels. A base URL like\n// `myresource.openai.azure.com` carries the customer's Azure resource name,\n// which identifies them, so the raw host must never reach telemetry. That is\n// why this returns a member of a fixed list rather than anything derived from\n// the input.\n\n/**\n * Every value `classifyModelHost` can return.\n *\n * `other` means a host we observed and did not recognize: a gateway, a proxy,\n * or a vendor we have no rule for. `unknown` means we never saw a host at all,\n * which is the case when a caller hands us an already-built LanguageModel.\n * The two are not interchangeable — one is an unrecognized answer, the other\n * is a missing one, and they need different follow-up.\n */\nexport const MODEL_HOST_CLASSES = [\n \"openai\",\n \"azure\",\n \"openrouter\",\n \"anthropic\",\n \"google\",\n \"vertex\",\n \"bedrock\",\n \"groq\",\n \"unify\",\n \"minimax\",\n \"local\",\n \"other\",\n \"unknown\",\n] as const;\n\nexport type ModelHostClass = (typeof MODEL_HOST_CLASSES)[number];\n\n/**\n * Host suffixes mapped to their vendor.\n *\n * Matched on label boundaries, never as substrings, so\n * `myresource.openai.azure.com.attacker.test` does not read as Azure.\n */\nconst HOST_SUFFIXES: ReadonlyArray<readonly [string, ModelHostClass]> = [\n // Azure exposes the same models under three host families: the classic\n // Azure OpenAI host, the Foundry Models host, and the general Cognitive\n // Services host. All three are Azure for our purposes.\n [\"openai.azure.com\", \"azure\"],\n [\"services.ai.azure.com\", \"azure\"],\n [\"cognitiveservices.azure.com\", \"azure\"],\n // API Management fronting an Azure OpenAI deployment, a common enterprise\n // pattern. Reported as azure because that is what sits behind it.\n [\"azure-api.net\", \"azure\"],\n\n [\"api.openai.com\", \"openai\"],\n [\"openrouter.ai\", \"openrouter\"],\n [\"api.anthropic.com\", \"anthropic\"],\n [\"generativelanguage.googleapis.com\", \"google\"],\n // Vertex regional hosts are `<region>-aiplatform.googleapis.com`, which is\n // not a suffix of a single label, so both spellings are listed.\n [\"aiplatform.googleapis.com\", \"vertex\"],\n [\"api.groq.com\", \"groq\"],\n [\"api.unify.ai\", \"unify\"],\n [\"api.minimax.io\", \"minimax\"],\n [\"api.minimaxi.com\", \"minimax\"],\n];\n\n/** Suffixes that mean the model runs on the same machine or private network. */\nconst LOCAL_SUFFIXES = [\"localhost\", \"local\", \"internal\", \"docker.internal\"];\n\n/** Matches `<region>-aiplatform.googleapis.com` and the Bedrock regional hosts. */\nconst REGIONAL_HOST_PATTERNS: ReadonlyArray<readonly [RegExp, ModelHostClass]> =\n [\n [/^[a-z0-9-]+-aiplatform\\.googleapis\\.com$/, \"vertex\"],\n [/^bedrock[a-z0-9.-]*\\.[a-z0-9-]+\\.amazonaws\\.com$/, \"bedrock\"],\n ];\n\n/** True when `host` equals `suffix` or sits directly beneath it. */\nfunction matchesSuffix(host: string, suffix: string): boolean {\n return host === suffix || host.endsWith(`.${suffix}`);\n}\n\n/** True for loopback, unspecified, and RFC 1918 private addresses. */\nfunction isPrivateAddress(host: string): boolean {\n if (host === \"127.0.0.1\" || host === \"0.0.0.0\" || host === \"::1\") {\n return true;\n }\n // 127.0.0.0/8 is entirely loopback.\n if (host.startsWith(\"127.\")) return true;\n // 10.0.0.0/8 and 192.168.0.0/16.\n if (host.startsWith(\"10.\") || host.startsWith(\"192.168.\")) return true;\n // 172.16.0.0/12 is 172.16 through 172.31 only. 172.32 is public, so the\n // second octet is range-checked rather than prefix-matched.\n const privateClassB = /^172\\.(\\d{1,3})\\./.exec(host);\n if (privateClassB) {\n const secondOctet = Number(privateClassB[1]);\n return secondOctet >= 16 && secondOctet <= 31;\n }\n return false;\n}\n\n/**\n * Reduce a model endpoint to one of {@link MODEL_HOST_CLASSES}.\n *\n * @param baseUrl The endpoint the provider was configured with. Absent when\n * the provider was left on its own default, which is why `providerDefault`\n * exists: \"no base URL, provider is openai\" means api.openai.com.\n * @param providerDefault What to report when no base URL was supplied. Callers\n * that genuinely cannot observe a host — a pre-built LanguageModel handed in\n * by the developer — leave this alone and get `unknown`.\n */\nexport function classifyModelHost(\n baseUrl?: string | null,\n providerDefault: ModelHostClass = \"unknown\",\n): ModelHostClass {\n const trimmed = baseUrl?.trim();\n if (!trimmed) {\n return providerDefault;\n }\n\n let host: string;\n try {\n // `hostname` drops the port, the path, the query and any credentials, so\n // nothing but the host can survive into the return value below.\n host = new URL(trimmed).hostname.toLowerCase();\n } catch {\n // We were given something and could not read it. That is a different fact\n // from having been given nothing, so it does not fall back to the default.\n return \"other\";\n }\n\n // IPv6 hostnames arrive bracketed from the URL parser.\n host = host.replace(/^\\[|\\]$/g, \"\");\n\n if (!host) return \"other\";\n\n if (isPrivateAddress(host)) return \"local\";\n for (const suffix of LOCAL_SUFFIXES) {\n if (matchesSuffix(host, suffix)) return \"local\";\n }\n\n for (const [suffix, hostClass] of HOST_SUFFIXES) {\n if (matchesSuffix(host, suffix)) return hostClass;\n }\n\n for (const [pattern, hostClass] of REGIONAL_HOST_PATTERNS) {\n if (pattern.test(host)) return hostClass;\n }\n\n return \"other\";\n}\n","// Telemetry sink client.\n//\n// Posts events to a CopilotKit-controlled telemetry-sink endpoint, which\n// fans out to Scarf, Reo, and any future destinations. Replaces the direct\n// per-vendor calls (formerly a Scarf-specific client) so that vendor changes\n// don't require SDK releases and so that downstream services we don't want\n// exposed to OSS readers (e.g. the email-enrichment service backing Reo) stay\n// private.\n//\n// Two attribution modes:\n// - Identified: a standalone telemetry id or a CopilotKit license token is\n// configured. Standalone identity takes precedence. License tokens are\n// JWTs (header.payload.sig) whose payload carries `telemetry_id`; the SDK\n// base64url-decodes the payload — without verifying the Ed25519 signature,\n// which is the license-verifier's job. The resolved identity is emitted\n// only via `X-CopilotKit-Telemetry-Id`.\n// - Anonymous: no license token, or a malformed/non-JWT one. No\n// telemetry-id header; events still flow, attribution is best-effort\n// from request-level signals (IP, UA).\n//\n// Note: CopilotCloud customer API keys (`ck_<env>_<id>.<secret>`) are\n// unrelated to telemetry attribution. They flow into Segment / PostHog\n// via the v1 shared TelemetryClient and never reach this code path.\n//\n// Best-effort: every error is swallowed. Telemetry must not break the\n// host application.\n\nconst TELEMETRY_SINK_URL =\n (typeof process !== \"undefined\" && process.env?.COPILOTKIT_TELEMETRY_URL) ||\n \"https://telemetry.copilotkit.ai/ingest\";\n\nconst FETCH_TIMEOUT_MS = 3000;\nconst TELEMETRY_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\nexport interface LambdaSendOptions {\n event: string;\n properties?: Record<string, unknown>;\n globalProperties?: Record<string, unknown>;\n packageName?: string;\n packageVersion?: string;\n /** Standalone analytics identity, resolved before any legacy license claim. */\n telemetryId?: string;\n // The CopilotKit license token (Ed25519-signed JWT), when one is\n // configured on the runtime. The sender base64url-decodes the payload\n // segment to extract `telemetry_id`; missing or malformed tokens\n // produce an anonymous send.\n licenseToken?: string;\n}\n\n/**\n * Return the first telemetry identity accepted by the ingest service.\n *\n * Empty and whitespace-only values are unconfigured placeholders and must not\n * suppress a later identity source. Leading and trailing HTTP spaces and tabs\n * are removed before validation. The ingest service accepts 1 to 128 ASCII\n * letters, digits, underscores, and hyphens.\n *\n * @internal\n */\nexport function firstNonBlankTelemetryId(\n ...candidates: ReadonlyArray<string | undefined>\n): string | undefined {\n for (const candidate of candidates) {\n if (candidate === undefined) {\n continue;\n }\n\n const normalized = candidate.replace(/^[\\t ]+|[\\t ]+$/g, \"\");\n if (TELEMETRY_ID_PATTERN.test(normalized)) {\n return normalized;\n }\n }\n\n return undefined;\n}\n\n// These fields aren't used by the telemetry service, so we strip them\n// at the wire boundary rather than rely on every caller to omit them.\n// Both the snake_case and camelCase variants are listed because callers\n// upstream use different conventions.\nconst STRIPPED_KEYS = new Set([\"cloud.public_api_key\", \"cloud.publicApiKey\"]);\n\nfunction stripCloudKeys(\n obj: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n if (!obj) return {};\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n if (!STRIPPED_KEYS.has(k)) out[k] = v;\n }\n return out;\n}\n\n// Pull telemetry_id out of a CopilotKit license token without verifying\n// the signature. The token shape is a standard JWT\n// (`<header>.<payload>.<sig>`) with base64url-encoded segments; the\n// payload is UTF-8 JSON with a telemetry_id accepted by the ingest service.\n//\n// Verification (Ed25519, key rotation, expiry) is the license-verifier\n// package's job. For telemetry attribution we only need the claimed id —\n// the trust model is claim-only on the Lambda side anyway.\n//\n// Exported so TelemetryClient setters can detect unparseable tokens at\n// configuration time and surface a single warning, instead of silently\n// emitting anonymous events on every capture.\nexport function parseTelemetryIdFromLicense(token?: string): string | null {\n if (!token) return null;\n const parts = token.split(\".\");\n if (parts.length !== 3) return null;\n try {\n const payload = parts[1];\n if (!/^[A-Za-z0-9_-]+$/.test(payload) || payload.length % 4 === 1) {\n return null;\n }\n\n let b64 = payload.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = (4 - (b64.length % 4)) % 4;\n b64 += \"=\".repeat(padding);\n const json =\n typeof Buffer !== \"undefined\"\n ? Buffer.from(b64, \"base64\").toString(\"utf8\")\n : new TextDecoder().decode(\n Uint8Array.from(atob(b64), (character) => character.charCodeAt(0)),\n );\n const decoded = JSON.parse(json) as { telemetry_id?: unknown };\n const telemetryId =\n typeof decoded.telemetry_id === \"string\"\n ? decoded.telemetry_id\n : undefined;\n return firstNonBlankTelemetryId(telemetryId) ?? null;\n } catch {\n return null;\n }\n}\n\n// Parse the telemetry_id from a license token AND emit the rollout smoke\n// signal if the parse returned null. Returning the parsed id lets callers\n// cache it in one step (avoiding a second parseTelemetryIdFromLicense\n// pass) while keeping the warn text in lockstep between v1 (shared) and\n// v2 (runtime) TelemetryClient.setLicenseToken.\nexport function parseAndWarnTelemetryId(licenseToken: string): string | null {\n const telemetryId = parseTelemetryIdFromLicense(licenseToken);\n if (!telemetryId) {\n console.warn(\n \"[CopilotKit] License token did not yield a telemetry_id; telemetry events will be sent anonymously.\",\n );\n }\n return telemetryId;\n}\n\nexport async function send(opts: LambdaSendOptions): Promise<void> {\n try {\n const body = JSON.stringify({\n event: opts.event,\n properties: stripCloudKeys(opts.properties),\n global_properties: stripCloudKeys(opts.globalProperties),\n package: {\n name: opts.packageName,\n version: opts.packageVersion,\n },\n ts: Math.floor(Date.now() / 1000),\n });\n\n const telemetryId =\n firstNonBlankTelemetryId(opts.telemetryId) ??\n parseTelemetryIdFromLicense(opts.licenseToken);\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": opts.packageName\n ? `CopilotKit-Runtime/${opts.packageVersion ?? \"unknown\"} (${opts.packageName})`\n : \"CopilotKit-Runtime\",\n };\n if (telemetryId) {\n headers[\"X-CopilotKit-Telemetry-Id\"] = telemetryId;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);\n try {\n await fetch(TELEMETRY_SINK_URL, {\n method: \"POST\",\n headers,\n body,\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timeoutId);\n }\n } catch {\n // Silent failure — telemetry must not break the application.\n }\n}\n\nexport const lambdaClient = { send };\n","/**\n * Granular debug configuration for CopilotKit runtime and client.\n * Pass `true` to enable events + lifecycle logging (but NOT verbose payloads),\n * or an object for granular control including `verbose: true` for full payloads.\n */\nexport type DebugConfig =\n | boolean\n | {\n /** Log every event emitted/received. Default: true */\n events?: boolean;\n /** Log request/run lifecycle. Default: true */\n lifecycle?: boolean;\n /** Log full event payloads instead of summaries. Default: false — must be explicitly opted in */\n verbose?: boolean;\n };\n\n/** Normalized debug configuration — all fields resolved to booleans. */\nexport interface ResolvedDebugConfig {\n enabled: boolean;\n events: boolean;\n lifecycle: boolean;\n verbose: boolean;\n}\n\n/** The all-off config used when debug is falsy. */\nconst DEBUG_OFF: ResolvedDebugConfig = {\n enabled: false,\n events: false,\n lifecycle: false,\n verbose: false,\n};\n\n/**\n * Normalizes a DebugConfig value into a ResolvedDebugConfig.\n *\n * - `false` / `undefined` → all off\n * - `true` → events + lifecycle on, verbose off (no PII in logs)\n * - object → merges with defaults (events: true, lifecycle: true, verbose: false)\n */\nexport function resolveDebugConfig(\n debug: DebugConfig | undefined,\n): ResolvedDebugConfig {\n if (!debug) return DEBUG_OFF;\n\n if (debug === true) {\n return { enabled: true, events: true, lifecycle: true, verbose: false };\n }\n\n const events = debug.events ?? true;\n const lifecycle = debug.lifecycle ?? true;\n const enabled = events || lifecycle;\n const verbose = enabled && (debug.verbose ?? false);\n\n return { enabled, events, lifecycle, verbose };\n}\n","import type {\n StandardSchemaV1,\n StandardJSONSchemaV1,\n} from \"@standard-schema/spec\";\n\nexport type { StandardSchemaV1, StandardJSONSchemaV1 };\n\n/**\n * Extract the Output type from a StandardSchemaV1 schema.\n * Replaces `z.infer<S>` for generic schema inference.\n */\nexport type InferSchemaOutput<S> =\n S extends StandardSchemaV1<any, infer O> ? O : never;\n\nexport interface SchemaToJsonSchemaOptions {\n /**\n * Injected `zodToJsonSchema` function so that `shared` does not depend on\n * `zod-to-json-schema`. Required when the schema is a Zod v3 schema that\n * does not implement Standard JSON Schema V1.\n */\n zodToJsonSchema?: (\n schema: unknown,\n options?: { $refStrategy?: string },\n ) => Record<string, unknown>;\n}\n\n/**\n * Check whether a schema implements the Standard JSON Schema V1 protocol.\n */\nfunction hasStandardJsonSchema(\n schema: StandardSchemaV1,\n): schema is StandardSchemaV1 & StandardJSONSchemaV1 {\n const props = schema[\"~standard\"];\n return (\n props != null &&\n typeof props === \"object\" &&\n \"jsonSchema\" in props &&\n props.jsonSchema != null &&\n typeof props.jsonSchema === \"object\" &&\n \"input\" in props.jsonSchema &&\n typeof props.jsonSchema.input === \"function\"\n );\n}\n\n/**\n * Convert any StandardSchemaV1-compatible schema to a JSON Schema object.\n *\n * Strategy:\n * 1. If the schema implements Standard JSON Schema V1 (`~standard.jsonSchema`),\n * call `schema['~standard'].jsonSchema.input({ target: 'draft-07' })`.\n * 2. If the schema exposes a `toJSONSchema()` method (Zod v4), call it directly.\n * 3. If the schema is a Zod v3 schema (`~standard.vendor === 'zod'`), use the\n * injected `zodToJsonSchema()` function.\n * 4. Otherwise throw a descriptive error.\n */\nexport function schemaToJsonSchema(\n schema: StandardSchemaV1,\n options?: SchemaToJsonSchemaOptions,\n): Record<string, unknown> {\n // 1. Standard JSON Schema V1\n if (hasStandardJsonSchema(schema)) {\n return schema[\"~standard\"].jsonSchema.input({ target: \"draft-07\" });\n }\n\n // 2. Zod v4 native — exposes toJSONSchema() on the schema itself\n if (typeof (schema as any).toJSONSchema === \"function\") {\n return (schema as any).toJSONSchema() as Record<string, unknown>;\n }\n\n // 3. Zod v3 fallback\n const vendor = schema[\"~standard\"].vendor;\n if (vendor === \"zod\" && options?.zodToJsonSchema) {\n return options.zodToJsonSchema(schema, { $refStrategy: \"none\" });\n }\n\n throw new Error(\n `Cannot convert schema to JSON Schema. The schema (vendor: \"${vendor}\") does not implement Standard JSON Schema V1 ` +\n `and no zodToJsonSchema fallback is available. ` +\n `Use a library that supports Standard JSON Schema (e.g., Zod 3.24+, Valibot v1+, ArkType v2+) ` +\n `or pass a zodToJsonSchema function in options.`,\n );\n}\n","import type { InputContent } from \"@ag-ui/core\";\nimport type { Attachment } from \"./types\";\n\n/** Build the AG-UI content part used when sending a ready attachment. */\nexport function createAttachmentContent(\n attachment: Pick<Attachment, \"type\" | \"source\" | \"filename\" | \"metadata\">,\n): InputContent {\n return {\n type: attachment.type,\n source: attachment.source,\n metadata: {\n ...(attachment.filename ? { filename: attachment.filename } : {}),\n ...attachment.metadata,\n },\n };\n}\n","import type { AttachmentModality } from \"./types\";\nimport type { InputContentSource } from \"../types/message\";\n\nconst DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20MB\n\n/**\n * Derive the attachment modality from a MIME type string.\n */\nexport function getModalityFromMimeType(mimeType: string): AttachmentModality {\n if (mimeType.startsWith(\"image/\")) return \"image\";\n if (mimeType.startsWith(\"audio/\")) return \"audio\";\n if (mimeType.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\n/**\n * Format a byte count as a human-readable file size string.\n */\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Check if a file exceeds the maximum allowed size.\n */\nexport function exceedsMaxSize(\n file: File,\n maxSize: number = DEFAULT_MAX_SIZE,\n): boolean {\n return file.size > maxSize;\n}\n\n/**\n * Read a File as a base64 string (without the data URL prefix).\n */\nexport function readFileAsBase64(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = (e) => {\n const result = e.target?.result as string;\n const base64 = result?.split(\",\")[1];\n if (base64) {\n resolve(base64);\n } else {\n reject(new Error(\"Failed to read file as base64\"));\n }\n };\n reader.onerror = reject;\n reader.readAsDataURL(file);\n });\n}\n\n/**\n * Generate a thumbnail data URL from a video file by capturing a frame near the start (at 0.1s).\n * Returns undefined if thumbnail generation fails or if called outside a browser environment.\n */\nexport function generateVideoThumbnail(\n file: File,\n): Promise<string | undefined> {\n if (typeof document === \"undefined\") {\n return Promise.resolve(undefined);\n }\n return new Promise((resolve) => {\n let resolved = false;\n const video = document.createElement(\"video\");\n const canvas = document.createElement(\"canvas\");\n const url = URL.createObjectURL(file);\n\n const cleanup = (result: string | undefined) => {\n if (resolved) return;\n resolved = true;\n URL.revokeObjectURL(url);\n resolve(result);\n };\n\n const timeout = setTimeout(() => {\n console.warn(\n `[CopilotKit] generateVideoThumbnail: timed out for file \"${file.name}\"`,\n );\n cleanup(undefined);\n }, 10000);\n\n video.preload = \"metadata\";\n video.muted = true;\n video.playsInline = true;\n\n video.onloadeddata = () => {\n video.currentTime = 0.1;\n };\n\n video.onseeked = () => {\n clearTimeout(timeout);\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext(\"2d\");\n if (ctx) {\n ctx.drawImage(video, 0, 0);\n const thumbnail = canvas.toDataURL(\"image/jpeg\", 0.7);\n cleanup(thumbnail);\n } else {\n console.warn(\n \"[CopilotKit] generateVideoThumbnail: could not get 2d canvas context\",\n );\n cleanup(undefined);\n }\n };\n\n video.onerror = () => {\n clearTimeout(timeout);\n console.warn(\n `[CopilotKit] generateVideoThumbnail: video element error for file \"${file.name}\"`,\n );\n cleanup(undefined);\n };\n\n video.src = url;\n });\n}\n\n/**\n * Check if a file's MIME type matches an accept filter string.\n * Handles file extensions (e.g. \".pdf\"), MIME wildcards (\"image/*\"), and comma-separated lists.\n */\nexport function matchesAcceptFilter(file: File, accept: string): boolean {\n if (!accept || accept === \"*/*\") return true;\n\n const filters = accept.split(\",\").map((f) => f.trim());\n return filters.some((filter) => {\n if (filter.startsWith(\".\")) {\n return (file.name ?? \"\").toLowerCase().endsWith(filter.toLowerCase());\n }\n if (filter.endsWith(\"/*\")) {\n const prefix = filter.slice(0, -2);\n return file.type.startsWith(prefix + \"/\");\n }\n return file.type === filter;\n });\n}\n\n/**\n * Convert an InputContentSource to a usable URL string.\n * For data sources, returns a base64 data URL; for URL sources, returns the URL directly.\n * A provider file handle (AG-UI 1.0 `file` source) has no address a browser\n * can load, so it returns an empty string and the caller shows no preview.\n */\nexport function getSourceUrl(source: InputContentSource): string {\n if (source.type === \"url\") {\n return source.value;\n }\n if (source.type === \"file\") {\n return \"\";\n }\n return `data:${source.mimeType};base64,${source.value}`;\n}\n\n/**\n * Return a short human-readable label for a document MIME type (e.g. \"PDF\", \"DOC\").\n */\nexport function getDocumentIcon(mimeType: string): string {\n if (mimeType.includes(\"pdf\")) return \"PDF\";\n if (mimeType.includes(\"sheet\") || mimeType.includes(\"excel\")) return \"XLS\";\n if (mimeType.includes(\"presentation\") || mimeType.includes(\"powerpoint\"))\n return \"PPT\";\n if (mimeType.includes(\"word\") || mimeType.includes(\"document\")) return \"DOC\";\n if (mimeType.includes(\"text/\")) return \"TXT\";\n return \"FILE\";\n}\n","export const logger = console;\n","import type { BaseEvent, RunErrorEvent } from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\n\nexport interface FinalizeRunOptions {\n stopRequested?: boolean;\n interruptionMessage?: string;\n /**\n * The `protocolVersion` the client declared on its RunAgentInput. When it is\n * set, a stopped run finishes with the AG-UI 1.0 `cancelled` outcome. A\n * client that declares no version predates 1.0 and cannot parse that\n * outcome, so it gets the plain RUN_FINISHED it always got.\n */\n protocolVersion?: string;\n}\n\nexport interface RunEventFinalizer {\n /** Observe one streamed event. Only the ids of open lifecycles are kept. */\n observe(event: BaseEvent): void;\n /** Return the events that close an interrupted or abruptly ended stream. */\n finalize(options?: FinalizeRunOptions): BaseEvent[];\n}\n\nconst defaultStopMessage = \"Run stopped by user\";\nconst defaultAbruptEndMessage = \"Run ended without emitting a terminal event\";\n\ninterface OpenToolCall {\n hasEnd: boolean;\n hasResult: boolean;\n}\n\n/**\n * Incremental finalizer for a streamed AG-UI run. Feed every event to\n * `observe`; when the stream ends without a terminal event, `finalize` returns\n * the closers for reasoning, text messages and tool calls still open plus a\n * terminal event. AG-UI 1.0 fails a run that ends with reasoning still open,\n * so reasoning is closed too. It also fails a RUN_FINISHED while a subagent\n * is still open, so a stop closes open subagents as well; a RUN_ERROR\n * abandons them, which the protocol allows. Closed lifecycles are forgotten at once and payloads are never kept,\n * so a caller does not have to retain the event array for this purpose.\n */\nexport function createRunEventFinalizer(): RunEventFinalizer {\n const openMessageIds = new Set<string>();\n const openReasoningMessageIds = new Set<string>();\n const openReasoningSpanIds = new Set<string>();\n const openToolCalls = new Map<string, OpenToolCall>();\n // Insertion order is start order, so closing in reverse closes children first.\n const openSubagentRunIds = new Set<string>();\n let runIdentity: { threadId?: string; runId?: string } = {};\n let terminalEventObserved = false;\n\n const clearOpen = () => {\n openMessageIds.clear();\n openReasoningMessageIds.clear();\n openReasoningSpanIds.clear();\n openToolCalls.clear();\n openSubagentRunIds.clear();\n };\n\n const observe = (event: BaseEvent) => {\n if (terminalEventObserved) return;\n\n switch (event.type) {\n case EventType.RUN_STARTED: {\n const { threadId, runId } = event as {\n threadId?: string;\n runId?: string;\n };\n runIdentity = { threadId, runId };\n break;\n }\n case EventType.REASONING_START:\n case EventType.REASONING_END:\n case EventType.REASONING_MESSAGE_START:\n case EventType.REASONING_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId !== \"string\") break;\n const open =\n event.type === EventType.REASONING_START ||\n event.type === EventType.REASONING_END\n ? openReasoningSpanIds\n : openReasoningMessageIds;\n if (\n event.type === EventType.REASONING_START ||\n event.type === EventType.REASONING_MESSAGE_START\n ) {\n open.add(messageId);\n } else {\n open.delete(messageId);\n }\n break;\n }\n case EventType.TEXT_MESSAGE_START: {\n const messageId = (event as { messageId?: string }).messageId;\n if (messageId) openMessageIds.add(messageId);\n break;\n }\n case EventType.TEXT_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") openMessageIds.delete(messageId);\n break;\n }\n case EventType.TOOL_CALL_START: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (toolCallId && !openToolCalls.has(toolCallId)) {\n openToolCalls.set(toolCallId, { hasEnd: false, hasResult: false });\n }\n break;\n }\n case EventType.TOOL_CALL_END:\n case EventType.TOOL_CALL_RESULT: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (!toolCallId) break;\n const info = openToolCalls.get(toolCallId);\n if (!info) break;\n\n if (event.type === EventType.TOOL_CALL_END) info.hasEnd = true;\n else info.hasResult = true;\n if (info.hasEnd && info.hasResult) openToolCalls.delete(toolCallId);\n break;\n }\n case EventType.SUBAGENT_STARTED:\n case EventType.SUBAGENT_FINISHED:\n case EventType.SUBAGENT_ERROR: {\n const subagentRunId = (event as { subagentRunId?: string })\n .subagentRunId;\n if (!subagentRunId) break;\n if (event.type === EventType.SUBAGENT_STARTED) {\n openSubagentRunIds.add(subagentRunId);\n } else {\n openSubagentRunIds.delete(subagentRunId);\n }\n break;\n }\n case EventType.RUN_FINISHED:\n case EventType.RUN_ERROR:\n terminalEventObserved = true;\n clearOpen();\n break;\n default:\n break;\n }\n };\n\n const finalize = (options: FinalizeRunOptions = {}): BaseEvent[] => {\n if (terminalEventObserved) return [];\n\n const { stopRequested = false, interruptionMessage } = options;\n const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;\n const resolvedAbruptMessage =\n interruptionMessage && interruptionMessage !== defaultStopMessage\n ? interruptionMessage\n : defaultAbruptEndMessage;\n const appended: BaseEvent[] = [];\n\n // A reasoning message closes before the span that holds it.\n for (const messageId of openReasoningMessageIds) {\n appended.push({\n type: EventType.REASONING_MESSAGE_END,\n messageId,\n } as BaseEvent);\n }\n for (const messageId of openReasoningSpanIds) {\n appended.push({ type: EventType.REASONING_END, messageId } as BaseEvent);\n }\n\n for (const messageId of openMessageIds) {\n appended.push({\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n } as BaseEvent);\n }\n\n for (const [toolCallId, info] of openToolCalls) {\n if (!info.hasEnd) {\n appended.push({\n type: EventType.TOOL_CALL_END,\n toolCallId,\n } as BaseEvent);\n }\n\n if (!info.hasResult) {\n appended.push({\n type: EventType.TOOL_CALL_RESULT,\n toolCallId,\n messageId: `${toolCallId}-result`,\n role: \"tool\",\n content: JSON.stringify(\n stopRequested\n ? {\n status: \"stopped\",\n reason: \"stop_requested\",\n message: resolvedStopMessage,\n }\n : {\n status: \"error\",\n reason: \"missing_terminal_event\",\n message: resolvedAbruptMessage,\n },\n ),\n } as BaseEvent);\n }\n }\n\n if (stopRequested) {\n // Newest first, so a nested subagent closes before its parent. An index\n // loop, because `toReversed` is ES2023 and this package targets older.\n const openIds = [...openSubagentRunIds];\n for (let index = openIds.length - 1; index >= 0; index -= 1) {\n appended.push({\n type: EventType.SUBAGENT_ERROR,\n subagentRunId: openIds[index],\n message: resolvedStopMessage,\n code: \"CANCELLED\",\n } as BaseEvent);\n }\n appended.push({\n type: EventType.RUN_FINISHED,\n ...(runIdentity.threadId !== undefined\n ? { threadId: runIdentity.threadId }\n : {}),\n ...(runIdentity.runId !== undefined\n ? { runId: runIdentity.runId }\n : {}),\n ...(options.protocolVersion !== undefined\n ? { outcome: { type: \"cancelled\" } }\n : {}),\n } as BaseEvent);\n } else {\n const errorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: resolvedAbruptMessage,\n code: \"INCOMPLETE_STREAM\",\n };\n appended.push(errorEvent);\n }\n\n terminalEventObserved = true;\n clearOpen();\n return appended;\n };\n\n return { observe, finalize };\n}\n\n/**\n * Array form of {@link createRunEventFinalizer} for callers that already keep\n * the run's events (runners persist them). Appends the closers to `events` in\n * place and returns them.\n */\nexport function finalizeRunEvents(\n events: BaseEvent[],\n options: FinalizeRunOptions = {},\n): BaseEvent[] {\n const finalizer = createRunEventFinalizer();\n for (const event of events) finalizer.observe(event);\n\n const appended = finalizer.finalize(options);\n events.push(...appended);\n return appended;\n}\n","import type { BaseEvent } from \"@ag-ui/client\";\n\n/**\n * The only AG-UI 1.0 events whose schema declares `threadId` and `runId`.\n * Plain literals, not `EventType`: a value import of `@ag-ui/client` here put\n * the client and its zod validators into the initial chunk of every app that\n * imports `@copilotkit/shared`.\n */\nconst RUN_IDENTITY_EVENTS = new Set<string>([\"RUN_STARTED\", \"RUN_FINISHED\"]);\n\n/**\n * Removes the routing fields that the Intelligence runner stamps on every\n * event it sends to the gateway (`thread_id`, `run_id`, and `threadId` /\n * `runId` on events that do not declare them).\n *\n * The gateway relays these payloads unchanged. AG-UI 1.0 strips unknown\n * fields before subscribers see them and warns once per field, per event,\n * so a streamed answer would log hundreds of warnings. Call this where a\n * gateway payload enters an AG-UI pipeline. The gateway still receives the\n * fields, because the runner adds them after this point.\n */\nexport function stripIntelligenceRoutingFields<T extends BaseEvent>(\n event: T,\n): T {\n const record = event as T & Record<string, unknown>;\n const keepRunIdentity = RUN_IDENTITY_EVENTS.has(record.type);\n if (\n !(\"thread_id\" in record) &&\n !(\"run_id\" in record) &&\n (keepRunIdentity || (!(\"threadId\" in record) && !(\"runId\" in record)))\n ) {\n return event;\n }\n const { thread_id: _t, run_id: _r, ...rest } = record;\n if (!keepRunIdentity) {\n delete rest.threadId;\n delete rest.runId;\n }\n return rest as unknown as T;\n}\n","/**\n * Error codes for transcription HTTP responses.\n * Uses snake_case to align with existing CopilotKitCoreErrorCode pattern.\n * These codes are returned by the runtime and parsed by the client.\n */\nexport enum TranscriptionErrorCode {\n /** Transcription service not configured in runtime */\n SERVICE_NOT_CONFIGURED = \"service_not_configured\",\n /** Audio format not supported */\n INVALID_AUDIO_FORMAT = \"invalid_audio_format\",\n /** Audio file is too long */\n AUDIO_TOO_LONG = \"audio_too_long\",\n /** Audio file is empty or too short */\n AUDIO_TOO_SHORT = \"audio_too_short\",\n /** Rate limited by transcription provider */\n RATE_LIMITED = \"rate_limited\",\n /** Authentication failed with transcription provider */\n AUTH_FAILED = \"auth_failed\",\n /** Transcription provider returned an error */\n PROVIDER_ERROR = \"provider_error\",\n /** Network error during transcription */\n NETWORK_ERROR = \"network_error\",\n /** Invalid request format */\n INVALID_REQUEST = \"invalid_request\",\n}\n\n/**\n * Error response format returned by the transcription endpoint.\n */\nexport interface TranscriptionErrorResponse {\n error: TranscriptionErrorCode;\n message: string;\n retryable?: boolean;\n}\n\n/**\n * Helper functions to create transcription error responses.\n * Used by the runtime to return consistent error responses.\n */\nexport const TranscriptionErrors = {\n serviceNotConfigured: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.SERVICE_NOT_CONFIGURED,\n message: \"Transcription service is not configured\",\n retryable: false,\n }),\n\n invalidAudioFormat: (\n format: string,\n supported: string[],\n ): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.INVALID_AUDIO_FORMAT,\n message: `Unsupported audio format: ${format}. Supported: ${supported.join(\", \")}`,\n retryable: false,\n }),\n\n invalidRequest: (details: string): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.INVALID_REQUEST,\n message: details,\n retryable: false,\n }),\n\n rateLimited: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.RATE_LIMITED,\n message: \"Rate limited. Please try again later.\",\n retryable: true,\n }),\n\n authFailed: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.AUTH_FAILED,\n message: \"Authentication failed with transcription provider\",\n retryable: false,\n }),\n\n providerError: (message: string): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.PROVIDER_ERROR,\n message,\n retryable: true,\n }),\n\n networkError: (\n message: string = \"Network error during transcription\",\n ): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.NETWORK_ERROR,\n message,\n retryable: true,\n }),\n\n audioTooLong: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.AUDIO_TOO_LONG,\n message: \"Audio file is too long\",\n retryable: false,\n }),\n\n audioTooShort: (): TranscriptionErrorResponse => ({\n error: TranscriptionErrorCode.AUDIO_TOO_SHORT,\n message: \"Audio is too short to transcribe\",\n retryable: false,\n }),\n};\n","","/**\n * The functions of the A2UI 1.0 basic catalog, as the model and the\n * validator see them. The renderer implements them (react-core\n * `generative-ui/functions.ts`); this file holds only what both sides share:\n * the names, the short signatures for the schema the model reads, and who\n * may call each one.\n */\n\n/** What a function gives back, as A2UI 1.0 names it. */\nexport type A2UIFunctionReturnType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"array\"\n | \"object\"\n | \"validationResult\"\n | \"any\"\n | \"void\";\n\n/**\n * Who may call a function. The renderer calls it from an event binding or\n * as a prop value; the agent calls it with `callRendererFunction`.\n */\nexport type A2UIAllowedCallers =\n | \"rendererOnly\"\n | \"agentOnly\"\n | \"rendererOrAgent\";\n\n/**\n * The callers of an app function that names none: the renderer only, as\n * in A2UI 1.0. The agent calls a function with `callRendererFunction` only\n * when its declaration allows it (`\"rendererOrAgent\"` or `\"agentOnly\"`).\n * The manifests and the exported catalog write the value out.\n */\nexport const GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS: A2UIAllowedCallers =\n \"rendererOnly\";\n\n/** The A2UI 1.0 interface fields of a function: who calls it, and how. */\nexport interface A2UIFunctionPermissions {\n allowedCallers?: A2UIAllowedCallers;\n /**\n * True for a function that only runs from a user gesture (a click, a key\n * press). It is `rendererOnly`: the agent cannot call it, and a prop\n * cannot be bound to it.\n */\n requiresUserActivation?: boolean;\n}\n\n/**\n * Who may call a function, from its permissions. A function that needs a\n * user gesture is for the renderer only, whatever `allowedCallers` says.\n *\n * @example\n * ```ts\n * functionCallers({}); // { renderer: true, agent: true }\n * functionCallers({ allowedCallers: \"rendererOnly\" }); // { renderer: true, agent: false }\n * functionCallers({ requiresUserActivation: true }); // { renderer: true, agent: false }\n * ```\n */\nexport function functionCallers(fn: A2UIFunctionPermissions) {\n if (fn.requiresUserActivation) return { renderer: true, agent: false };\n const callers = fn.allowedCallers ?? GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS;\n return {\n renderer: callers !== \"agentOnly\",\n agent: callers !== \"rendererOnly\",\n };\n}\n\nexport interface A2UIBasicFunctionInfo extends A2UIFunctionPermissions {\n description: string;\n /** The args, as a short TypeScript-like type for the compact schema. */\n parameters: string;\n returnType: A2UIFunctionReturnType;\n /** Built-in functions are value functions of the renderer. */\n allowedCallers: \"rendererOnly\";\n requiresUserActivation?: true;\n /** True for a CopilotKit function that the A2UI basic catalog lacks. */\n extension?: true;\n}\n\n/** Marks a table of built-in functions as callable by the renderer only. */\nfunction rendererOnly<Name extends string>(\n functions: Record<Name, Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>,\n): Readonly<Record<Name, A2UIBasicFunctionInfo>> {\n return Object.fromEntries(\n Object.entries<Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>(\n functions,\n ).map(([name, info]) => [\n name,\n { ...info, allowedCallers: \"rendererOnly\" },\n ]),\n ) as Record<Name, A2UIBasicFunctionInfo>;\n}\n\n/**\n * The basic functions by name. A `{\"@call\"}` in a prop, in an event\n * binding, or in a `callRendererFunction` may name any of them without a\n * declaration in `createGenerativeUI({ functions })`.\n */\nexport const A2UI_BASIC_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n required: {\n description: \"Valid when the value is not empty\",\n parameters: \"{ value: unknown }\",\n returnType: \"validationResult\",\n },\n regex: {\n description: \"Valid when the value matches the pattern\",\n parameters: \"{ value: string; pattern: string }\",\n returnType: \"validationResult\",\n },\n length: {\n description: \"Valid when the length of the value is within min and max\",\n parameters: \"{ value: string; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n numeric: {\n description: \"Valid when the value is a number within min and max\",\n parameters: \"{ value: number; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n email: {\n description: \"Valid when the value is an email address\",\n parameters: \"{ value: string }\",\n returnType: \"validationResult\",\n },\n formatString: {\n description:\n \"Interpolates ${/path}, ${relative/path} and ${fn(arg: value)} in the value; \\\\${ is a literal\",\n parameters: \"{ value: string }\",\n returnType: \"string\",\n },\n formatNumber: {\n description: \"The number in the locale of the user\",\n parameters: \"{ value: number; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatCurrency: {\n description: \"The amount as money, with an ISO 4217 currency code\",\n parameters:\n \"{ value: number; currency: string; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatDate: {\n description:\n 'A date or ISO string in a TR35 pattern, for example \"MMM d, yyyy\" or \"HH:mm\"',\n parameters: \"{ value: string | number; format: string }\",\n returnType: \"string\",\n },\n pluralize: {\n description: \"The string of the plural category of the value\",\n parameters:\n \"{ value: number; zero?: string; one?: string; two?: string; few?: string; many?: string; other: string }\",\n returnType: \"string\",\n },\n openUrl: {\n description: \"Opens an http(s) URL in a new tab. Only from an event\",\n parameters: \"{ url: string }\",\n returnType: \"void\",\n requiresUserActivation: true,\n },\n and: {\n description: \"True when every value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n or: {\n description: \"True when any value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n not: {\n description: \"The negated value\",\n parameters: \"{ value: boolean }\",\n returnType: \"boolean\",\n },\n});\n\n/**\n * The value functions that CopilotKit adds to the basic catalog, because\n * A2UI 1.0 has no arithmetic: `calc` evaluates an expression over named\n * args, and `series` builds a computed list. A catalog may declare its own\n * functions in A2UI, so these are regular catalog functions to the model;\n * a renderer without them rejects the call instead of misrendering.\n */\nexport const COPILOTKIT_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n calc: {\n description:\n \"The value of an arithmetic expression over the other args, by name: + - * / % ( ), comparisons, && || !, cond ? a : b, min max round floor ceil abs, 'text' + name\",\n parameters:\n \"{ expression: string; [name: string]: number | string | boolean }\",\n returnType: \"any\",\n extension: true,\n },\n // WORKAROUND(a2ui-agent-sdk 0.9.0): examples omit `variable` and use default i\n // because the Express compiler mistakes a literal `variable` key for its AST.\n // Runtime support for custom variable names is unchanged.\n // https://github.com/a2ui-project/a2ui/issues/3410\n series: {\n description:\n 'A list of count copies of item, for chart data and template lists. Put arithmetic in ${expression} strings in item, using the loop variable (default i, counting from start, default 1) and other named args. A whole-expression string retains the result type, so \"${i * monthlyCost}\" yields a number. Arguments, including nested calc or formatString calls in item, resolve before the series loop; those calls cannot use the loop variable. Example: {\"@call\":\"series\",\"args\":{\"count\":6,\"item\":{\"month\":\"${i}\",\"cost\":\"${i * monthlyCost}\"},\"monthlyCost\":{\"@path\":\"/monthlyCost\"}}}. Omit variable to use i.',\n parameters:\n \"{ count: number; item: unknown; variable?: string; start?: number; [name: string]: unknown }\",\n returnType: \"array\",\n extension: true,\n },\n});\n\n/** Every function a `{\"@call\"}` may name without a declaration: basic and CopilotKit. */\nexport const GENERATIVE_UI_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = { ...A2UI_BASIC_FUNCTIONS, ...COPILOTKIT_FUNCTIONS };\n\n/** The name of the system function that gives the index of a template item. */\nexport const A2UI_INDEX_FUNCTION = \"@index\";\n\n/** True for a built-in function name: basic, CopilotKit, or `@index`. */\nexport function isA2UIBasicFunction(name: string) {\n return (\n name === A2UI_INDEX_FUNCTION ||\n Object.prototype.hasOwnProperty.call(GENERATIVE_UI_FUNCTIONS, name)\n );\n}\n\n/**\n * True for a built-in function that a prop or a check may call: every one\n * except the functions that need a user gesture.\n */\nexport function isA2UIValueFunction(name: string) {\n if (name === A2UI_INDEX_FUNCTION) return true;\n const info = Object.prototype.hasOwnProperty.call(\n GENERATIVE_UI_FUNCTIONS,\n name,\n )\n ? GENERATIVE_UI_FUNCTIONS[name]\n : undefined;\n return info !== undefined && !info.requiresUserActivation;\n}\n\n/** `{ \"@call\": \"<name>\", \"args\"?: {...} }`: a function call value. */\nexport function isCallBinding(\n value: unknown,\n): value is { \"@call\": string; args?: Record<string, unknown> } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>)[\"@call\"] === \"string\"\n );\n}\n\n/** How bad a failed check is. `error` is the default; only an error blocks. */\nexport type A2UIValidationSeverity = \"error\" | \"warning\" | \"info\";\n\n/**\n * A2UI's `ValidationResult`: what a check gives. A validator function gives\n * one; a check may also bind a boolean, which the renderer coerces to one.\n * `code` names the failure for programs; `severity` says how bad it is,\n * `\"error\"` when left out. Other keys are allowed, for app validators that\n * carry more (a suggested value, a field path).\n */\nexport interface A2UIValidationResult {\n valid: boolean;\n message?: string;\n code?: string;\n severity?: A2UIValidationSeverity;\n [extra: string]: unknown;\n}\n\nexport function isValidationResult(\n value: unknown,\n): value is A2UIValidationResult {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>).valid === \"boolean\"\n );\n}\n","/** True for a plain object: not null, not an array. Internal, not exported. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import type { GenerativeUIJSONSchema } from \"./types\";\nimport { isRecord } from \"./is-record\";\n\n/**\n * How A2UI 1.0 marks a prop that holds a component reference: the JSON\n * Schema of the prop is a `$ref` to one of these two common types.\n * Validators and renderers find the children of a component by these refs,\n * at any depth of the props schema.\n */\nexport const A2UI_COMPONENT_ID_REF = \"common_types.json#/$defs/ComponentId\";\nexport const A2UI_CHILD_LIST_REF = \"common_types.json#/$defs/ChildList\";\n\n/**\n * The start of the `description` that marks a schema as a component\n * reference before it is turned into JSON Schema. `child()` and\n * `childList()` set it; a schema from another library can set a description\n * that starts with the same mark to get the same effect. What follows the\n * mark (after a space) stays as the description of the reference.\n */\nexport const A2UI_COMPONENT_ID_MARK = \"@a2ui/ComponentId\";\nexport const A2UI_CHILD_LIST_MARK = \"@a2ui/ChildList\";\n\nexport type ChildRefKind = \"single\" | \"multiple\";\n\n/** One component reference in a props schema. */\nexport interface ChildRef {\n /**\n * The keys from the props root to the reference. `\"*\"` stands for the\n * items of an array. `[\"tabs\", \"*\", \"child\"]` is the `child` of each\n * entry of `tabs`.\n */\n path: readonly string[];\n kind: ChildRefKind;\n}\n\n/** The ref kind of a JSON Schema node, or `undefined` for a plain value. */\nexport function childRefKind(\n schema: GenerativeUIJSONSchema,\n): ChildRefKind | undefined {\n const ref = schema.$ref;\n if (ref === A2UI_COMPONENT_ID_REF) return \"single\";\n if (ref === A2UI_CHILD_LIST_REF) return \"multiple\";\n return undefined;\n}\n\n/**\n * Turns the reference marks of a JSON Schema into A2UI `$ref`s, in place of\n * the marked node. The mark is the `description` set by `child()` and\n * `childList()`; after this, the node is `{ \"$ref\": \"common_types.json#/...\" }`.\n */\nexport function applyChildRefMarks(\n schema: GenerativeUIJSONSchema,\n): GenerativeUIJSONSchema {\n const marked = (description: unknown, mark: string, ref: string) => {\n if (typeof description !== \"string\" || !description.startsWith(mark)) {\n return undefined;\n }\n const rest = description.slice(mark.length).trim();\n return rest === \"\" ? { $ref: ref } : { $ref: ref, description: rest };\n };\n const visit = (node: unknown): unknown => {\n if (Array.isArray(node)) return node.map(visit);\n if (!isRecord(node)) return node;\n const reference =\n marked(node.description, A2UI_COMPONENT_ID_MARK, A2UI_COMPONENT_ID_REF) ??\n marked(node.description, A2UI_CHILD_LIST_MARK, A2UI_CHILD_LIST_REF);\n if (reference) return reference;\n return Object.fromEntries(\n Object.entries(node).map(([key, value]) => [key, visit(value)]),\n );\n };\n return visit(schema) as GenerativeUIJSONSchema;\n}\n\n/**\n * Every component reference in a props schema, with its path. Walks\n * `properties`, array `items`, and the variants of `anyOf` / `oneOf` /\n * `allOf`. A union counts as a reference only when every alternative is\n * one of the same kind: a prop that is text in one branch and a child in\n * another cannot be told apart from its value, so it stays data.\n */\nexport function collectChildRefs(schema: GenerativeUIJSONSchema): ChildRef[] {\n const refs: ChildRef[] = [];\n const seen = new Set<string>();\n const add = (path: string[], kind: ChildRefKind) => {\n const key = path.join(\"\\u0000\");\n if (seen.has(key)) return;\n seen.add(key);\n refs.push({ path, kind });\n };\n const visit = (node: unknown, path: string[]) => {\n if (!isRecord(node)) return;\n const kind = childRefKind(node);\n if (kind) return add(path, kind);\n for (const list of [node.anyOf, node.oneOf]) {\n if (!Array.isArray(list) || list.length === 0) continue;\n const kinds = list.map((variant) =>\n isRecord(variant) ? childRefKind(variant) : undefined,\n );\n const [first] = kinds;\n if (first && kinds.every((k) => k === first)) add(path, first);\n else if (kinds.every((k) => k === undefined)) {\n // Objects in a union: a nested reference counts only when every\n // alternative has it at the same path with the same kind.\n const perVariant = list.map((variant) =>\n collectChildRefs(variant as GenerativeUIJSONSchema),\n );\n const key = (ref: ChildRef) =>\n `${ref.kind}\\u0000${ref.path.join(\"\\u0000\")}`;\n const shared = perVariant[0].filter((ref) =>\n perVariant.every((refs) => refs.some((r) => key(r) === key(ref))),\n );\n shared.forEach((ref) => add([...path, ...ref.path], ref.kind));\n }\n }\n if (Array.isArray(node.allOf)) {\n node.allOf.forEach((variant) => visit(variant, path));\n }\n if (isRecord(node.properties)) {\n for (const [key, value] of Object.entries(node.properties)) {\n visit(value, [...path, key]);\n }\n }\n if (isRecord(node.items)) visit(node.items, [...path, \"*\"]);\n };\n visit(schema, []);\n return refs;\n}\n\n/**\n * The component ids at the references of one component node: a string id,\n * a list of ids, or the `componentId` of a template, at every ref path.\n * Bound or computed values are not ids and are left out.\n */\nexport function childIdsAtRefs(\n component: Record<string, unknown>,\n refs: readonly ChildRef[],\n): string[] {\n const ids: string[] = [];\n const collect = (value: unknown) => {\n if (typeof value === \"string\") ids.push(value);\n else if (Array.isArray(value)) {\n value.forEach((id) => typeof id === \"string\" && ids.push(id));\n } else if (isRecord(value) && typeof value.componentId === \"string\") {\n ids.push(value.componentId);\n }\n };\n const visit = (value: unknown, path: readonly string[]) => {\n if (path.length === 0) return collect(value);\n const [head, ...rest] = path;\n if (head === \"*\") {\n if (Array.isArray(value)) value.forEach((item) => visit(item, rest));\n return;\n }\n if (isRecord(value) && Object.prototype.hasOwnProperty.call(value, head)) {\n visit(value[head], rest);\n }\n };\n for (const ref of refs) visit(component, ref.path);\n return ids;\n}\n\n/**\n * True when a reference of the component is bound or computed (`{\"@path\"}`,\n * `{\"@call\"}`) at the ref itself or above it, so its ids are known only\n * at render time.\n */\nexport function hasBoundChildRef(\n component: Record<string, unknown>,\n refs: readonly ChildRef[],\n): boolean {\n const isDynamic = (value: unknown) =>\n isRecord(value) && (\"@path\" in value || \"@call\" in value);\n const visit = (value: unknown, path: readonly string[]): boolean => {\n if (isDynamic(value)) return true;\n if (path.length === 0) return false;\n const [head, ...rest] = path;\n if (head === \"*\") {\n return Array.isArray(value) && value.some((item) => visit(item, rest));\n }\n return (\n isRecord(value) &&\n Object.prototype.hasOwnProperty.call(value, head) &&\n visit(value[head], rest)\n );\n };\n return refs.some((ref) => visit(component, ref.path));\n}\n\n/**\n * Walks `value` along a ref path and replaces what sits at the end with\n * `replace(found)`. Objects and arrays on the way are copied; everything\n * else keeps its identity. Missing keys are left alone.\n */\nexport function mapAtChildRef(\n value: unknown,\n path: readonly string[],\n replace: (found: unknown) => unknown,\n): unknown {\n if (path.length === 0) return replace(value);\n const [head, ...rest] = path;\n if (head === \"*\") {\n if (!Array.isArray(value)) return value;\n return value.map((item) => mapAtChildRef(item, rest, replace));\n }\n if (!isRecord(value) || !Object.prototype.hasOwnProperty.call(value, head)) {\n return value;\n }\n return { ...value, [head]: mapAtChildRef(value[head], rest, replace) };\n}\n","/** A2UI protocol version used on the wire. */\nexport const A2UI_VERSION = \"v1.0\";\n/** Activity type of a generated surface message. */\nexport const GENERATIVE_UI_ACTIVITY_TYPE = \"generative-ui-surface\";\n/** Activity type of a function call that the agent asks the client to run. */\nexport const GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE =\n \"generative-ui-function-call\";\n/** Tool the model calls to render or update surfaces. */\nexport const GENERATIVE_UI_RENDER_TOOL = \"render_ui\";\n/** Target id of the chat transcript. */\nexport const GENERATIVE_UI_CHAT_TARGET = \"chat\";\n/** Component id every surface renders from. */\nexport const GENERATIVE_UI_ROOT_ID = \"root\";\n/**\n * Whether the agent may call renderer functions with `callRendererFunction`.\n * Off for now: the result goes back as a developer message, and not every\n * backend keeps that message where the model reads it in order. While off,\n * the prompts do not mention the operation, the validator rejects it, and\n * the dispatcher refuses the agent, whatever a declaration's\n * `allowedCallers` says. The code and its tests stay for when it is on.\n */\nexport const GENERATIVE_UI_AGENT_FUNCTION_CALLS = false;\n/** The reason an agent function call is rejected while they are off. */\nexport const GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON =\n \"callRendererFunction is not supported in this version: the agent cannot call renderer functions until their results can be sent back to it reliably\";\n\n/** Activity message id of a surface. One message per surface. */\nexport function generativeUISurfaceMessageId(surfaceId: string) {\n return `genui:${surfaceId}`;\n}\n\n/**\n * Activity message id of an agent-called function. One message per\n * `functionCallId`.\n *\n * @param functionCallId - The `functionCallId` of the `callRendererFunction` operation.\n *\n * @example\n * ```ts\n * generativeUIFunctionCallMessageId(\"f1\"); // \"genui-fn:f1\"\n * ```\n */\nexport function generativeUIFunctionCallMessageId(functionCallId: string) {\n return `genui-fn:${functionCallId}`;\n}\n\nimport type {\n A2UIFunctionPermissions,\n A2UIFunctionReturnType,\n} from \"./basic-functions\";\n\n// Named `GenerativeUIJSONSchema` because the package root already exports a\n// `JSONSchema` (utils/json-schema.ts); the bare name would collide.\nexport type GenerativeUIJSONSchema = Record<string, unknown>;\n\nexport type A2UIComponentNode = {\n id: string;\n component: string;\n [prop: string]: unknown;\n};\n\n/**\n * The keys of the A2UI 1.0 component envelope next to `id` and\n * `component`: `catalogId`, `accessibility` and `metadata`. They are not\n * props of the component. The renderer reads `accessibility` and ignores\n * the other two.\n */\nexport const A2UI_COMPONENT_ENVELOPE_KEYS: ReadonlySet<string> = new Set([\n \"catalogId\",\n \"accessibility\",\n \"metadata\",\n]);\n\n/**\n * A call of a named function: `{ \"@call\": \"addToCart\", \"args\": { ... } }`.\n * Without `catalogId`, the function comes from the catalog of the run.\n */\nexport type A2UIFunctionCall = {\n \"@call\": string;\n args?: Record<string, unknown>;\n catalogId?: string;\n};\n\nexport type A2UIOperation =\n | {\n version: \"v1.0\";\n createSurface: {\n surfaceId: string;\n /** Left out by the model. The run's catalog id is filled in. */\n catalogId?: string;\n /** Components to add at once, checked like `updateComponents`. */\n components?: A2UIComponentNode[];\n /** The initial root data model. */\n dataModel?: Record<string, unknown>;\n sendDataModel?: boolean;\n metadata?: { extensions?: Record<string, unknown> };\n };\n }\n | {\n version: \"v1.0\";\n updateComponents: { surfaceId: string; components: A2UIComponentNode[] };\n }\n | {\n version: \"v1.0\";\n /**\n * Sets `value` at `path`. A `null` value deletes the key at `path`.\n * With no `path`, or `\"/\"`, it sets the whole data model.\n */\n updateDataModel: { surfaceId: string; path?: string; value: unknown };\n }\n | { version: \"v1.0\"; deleteSurface: { surfaceId: string } }\n | {\n version: \"v1.0\";\n /** Runs an app function in the browser, with no user interaction. */\n callRendererFunction: {\n functionCallId: string;\n callFunction: A2UIFunctionCall;\n };\n };\n\n/** Value of an event prop: run a host function, or report the event to the agent. */\nexport type GenerativeUIActionBinding =\n | {\n event: {\n name: string;\n /**\n * First line of the user message that the event becomes: text, a\n * data binding, or a function value such as formatString.\n */\n userMessage?: string | { \"@path\": string } | A2UIFunctionCall;\n context?: Record<string, unknown>;\n };\n }\n | { functionCall: A2UIFunctionCall };\n\nexport type GenerativeUISurfaceStatus = \"streaming\" | \"ready\" | \"error\";\n\nexport interface GenerativeUIRejectedOperation {\n /** Position of the operation in the render_ui call, or in the content list. */\n index: number;\n reason: string;\n}\n\n/** Content of a `generative-ui-surface` activity message. */\nexport interface GenerativeUISurfaceContent {\n surfaceId: string;\n target: string;\n catalogId: string;\n /** Committed (validated) operations, cumulative. */\n operations: A2UIOperation[];\n status: GenerativeUISurfaceStatus;\n rejected: GenerativeUIRejectedOperation[];\n}\n\n/** Content of a `generative-ui-function-call` activity message. */\nexport interface GenerativeUIFunctionCallContent {\n functionCallId: string;\n callFunction: A2UIFunctionCall;\n}\n\n/**\n * Value of a \"multiple\" slot that repeats one component for each item of the\n * list at `path`. Paths inside the repeated component are relative to the item.\n */\nexport type GenerativeUITemplateChildren = {\n componentId: string;\n path: string;\n};\n\nexport interface GenerativeUIComponentManifest {\n /** CopilotKit positional order across model-visible props, slots and events.\n * Exporters encode this as JSON Schema property order; it is not an A2UI keyword. */\n parameterOrder?: readonly string[];\n description?: string;\n props: GenerativeUIJSONSchema;\n events?: Record<\n string,\n { description?: string; parameters: GenerativeUIJSONSchema }\n >;\n /**\n * Props that hold child components. A \"single\" slot takes one component id.\n * A \"multiple\" slot takes a `string[]` of component ids, or a\n * {@link GenerativeUITemplateChildren} template.\n */\n slots?: Record<string, \"single\" | \"multiple\">;\n}\n\nexport interface GenerativeUIFunctionManifest extends A2UIFunctionPermissions {\n description?: string;\n parameters: GenerativeUIJSONSchema;\n /** What the function gives back, as A2UI 1.0 names it. */\n returnType?: A2UIFunctionReturnType;\n}\n\n/** Serializable description of what the browser can render and call. */\nexport interface GenerativeUIManifest {\n /** The catalog of the run. A surface with no `catalogId` gets this one. */\n catalogId: string;\n /**\n * Every catalog that a `catalogId` can name: `catalogId` first, then the\n * catalogs of `extends`. Left out, only `catalogId`.\n */\n catalogIds?: string[];\n components: Record<string, GenerativeUIComponentManifest>;\n functions: Record<string, GenerativeUIFunctionManifest>;\n /**\n * Places where the model can render surfaces. Only mounted targets are\n * listed. `description` tells the model where the target is on the page\n * and what to put in it.\n */\n targets: GenerativeUITarget[];\n /** Surfaces the client already holds for the current thread. */\n surfaces: Record<string, GenerativeUISurfaceSummary>;\n}\n\n/** A place where the model can render surfaces. */\nexport interface GenerativeUITarget {\n id: string;\n kind: \"chat\" | \"inline\";\n description?: string;\n /**\n * The only components that the surfaces of this target can use, at most\n * {@link GENERATIVE_UI_MAX_TARGET_COMPONENTS} names. Left out, the target\n * takes every component of the catalog.\n */\n components?: string[];\n}\n\n/** Most component names that one target can list. */\nexport const GENERATIVE_UI_MAX_TARGET_COMPONENTS = 100;\n\n/** Most rejections that a surface summary lists. */\nexport const GENERATIVE_UI_MAX_SUMMARY_REJECTIONS = 20;\n/** Most characters of one rejection in a surface summary. */\nexport const GENERATIVE_UI_MAX_REJECTION_LENGTH = 500;\n\n/** One surface that the client holds, as the model sees it. */\nexport interface GenerativeUISurfaceSummary {\n target: string;\n /** The values that the user set, by path. Left out when there are none. */\n dataModel?: Record<string, unknown>;\n /**\n * Operations that the client dropped, as `\"operation <index>: <reason>\"`.\n * At most {@link GENERATIVE_UI_MAX_SUMMARY_REJECTIONS} entries of at most\n * {@link GENERATIVE_UI_MAX_REJECTION_LENGTH} characters. Left out when\n * there are none.\n */\n rejected?: string[];\n /**\n * Left out while the surface exists. `\"deleted\"`: a deleteSurface removed\n * it, and its id cannot be used again. `\"failed\"`: its createSurface was\n * rejected, so it does not exist; a corrected createSurface can use the id.\n */\n status?: \"deleted\" | \"failed\";\n}\n\n/** A user interaction bound to `{ event }`, sent to the agent. */\nexport interface GenerativeUIUserEvent {\n name: string;\n surfaceId: string;\n componentId: string;\n context: Record<string, unknown>;\n /** The resolved `event.userMessage`: the first line of the user message. */\n userMessage?: string;\n /** When the user acted, as an ISO 8601 string. Filled in when left out. */\n timestamp?: string;\n}\n\n/**\n * The A2UI 1.0 action message of a user event: what a renderer sends to the\n * agent when the user triggers an `{ event }` action. The run that the\n * event starts carries it in the envelope (`copilotkit_action`), next to\n * the visible user message.\n */\nexport interface A2UIActionMessage {\n version: typeof A2UI_VERSION;\n action: {\n name: string;\n surfaceId: string;\n sourceComponentId: string;\n /** ISO 8601. */\n timestamp: string;\n userMessage?: string;\n context: Record<string, unknown>;\n };\n}\n\n/**\n * The action message of a user event, with the A2UI field names. Takes the\n * time of the call when the event has no timestamp.\n *\n * @example\n * ```ts\n * toA2UIActionMessage({ name: \"buy\", surfaceId: \"s1\", componentId: \"b\", context: { sku: \"a\" } });\n * // { version: \"v1.0\", action: { name: \"buy\", surfaceId: \"s1\", sourceComponentId: \"b\", timestamp: \"2026-…\", context: { sku: \"a\" } } }\n * ```\n */\nexport function toA2UIActionMessage(\n event: GenerativeUIUserEvent,\n): A2UIActionMessage {\n return {\n version: A2UI_VERSION,\n action: {\n name: event.name,\n surfaceId: event.surfaceId,\n sourceComponentId: event.componentId,\n timestamp: event.timestamp ?? new Date().toISOString(),\n ...(event.userMessage === undefined\n ? {}\n : { userMessage: event.userMessage }),\n context: event.context,\n },\n };\n}\n","import { isA2UIBasicFunction } from \"./generative-ui/basic-functions\";\nimport { A2UI_CHILD_LIST_REF } from \"./generative-ui/child-refs\";\nimport { GENERATIVE_UI_AGENT_FUNCTION_CALLS } from \"./generative-ui/types\";\nimport type { GenerativeUIManifest } from \"./generative-ui/types\";\n/**\n * Default A2UI generation and design guideline prompts.\n *\n * These are the canonical prompt fragments that instruct an LLM how to call\n * the render_a2ui tool, how to bind data, and how to style surfaces.\n */\n\n/**\n * Generation guidelines — protocol rules, tool arguments, path rules,\n * data model format, and form/two-way-binding instructions.\n */\nexport const A2UI_DEFAULT_GENERATION_GUIDELINES = `\\\nGenerate A2UI v0.9 JSON.\n\n## A2UI Protocol Instructions\n\nA2UI (Agent to UI) is a protocol for rendering rich UI surfaces from agent responses.\n\nCRITICAL: You MUST call the render_a2ui tool with ALL of these arguments:\n- surfaceId: A unique ID for the surface (e.g. \"product-comparison\")\n- components: REQUIRED — the A2UI component array. NEVER omit this. Only use\n components listed in the Available Components schema provided as context.\n- data: OPTIONAL — a JSON object written to the root of the surface data model.\n Use for pre-filling form values or providing data for path-bound components.\n- every component must have the \"component\" field specifying the component type.\n ONLY use component names from the Available Components schema — do NOT invent\n component names or use names not in the schema.\n\nCOMPONENT ID RULES:\n- Exactly one component MUST have id=\"root\". This is the surface's entry\n point — the renderer begins at \"root\" and walks the child/children tree\n from there. Every other component must be reachable from \"root\". If no\n component has id=\"root\", the surface renders an empty loading placeholder\n and none of your components will be shown.\n- Every component ID must be unique within the surface.\n- A component MUST NOT reference itself as child/children. This causes a\n circular dependency error. For example, if a component has id=\"avatar\",\n its child must be a DIFFERENT id (e.g. \"avatar-img\"), never \"avatar\".\n- The child/children tree must be a DAG — no cycles allowed.\n\nREPEATING CONTENT (TEMPLATES):\nTo repeat a component for each item in an array, use the structural children format:\n children: { componentId: \"card-id\", path: \"/items\" }\nThis tells the renderer to create one instance of \"card-id\" per item in the \"/items\" array.\n\nPATH RULES FOR TEMPLATES:\nComponents inside a repeating template use RELATIVE paths (no leading slash).\nThe path is resolved relative to each array item automatically.\nIf a container has children: { componentId: \"card\", path: \"/items\" } and each item\nhas a key \"name\", use { \"path\": \"name\" } (NO leading slash — relative to item).\nCRITICAL: Do NOT use \"/name\" (absolute) inside templates — use \"name\" (relative).\nThe container's path (\"/items\") uses a leading slash (absolute), but all\ncomponents INSIDE the template use paths WITHOUT leading slash.\n\nCOMPONENT VALUES — DEFAULT RULE:\nUse inline literal values for ALL component properties. Pass strings, numbers,\narrays, and objects directly on the component. Do NOT use { \"path\": \"...\" }\nobjects unless the property's schema explicitly allows it (see exception below).\nCRITICAL: USING { \"path\": \"...\" } ON A PROPERTY THAT DOES NOT DECLARE PATH\nSUPPORT IN ITS SCHEMA WILL CAUSE A RUNTIME CRASH AND BREAK THE ENTIRE UI.\nALWAYS CHECK THE COMPONENT SCHEMA FIRST — IF THE PROPERTY ONLY ACCEPTS A\nPLAIN TYPE, YOU MUST USE A LITERAL VALUE.\nVERY IMPORTANT: THE APPLICATION WILL BREAK IF YOU DO NOT FOLLOW THIS RULE!\n\nFor example, a chart's \"data\" must always be an inline array:\n \"data\": [{\"label\": \"Jan\", \"value\": 100}, {\"label\": \"Feb\", \"value\": 200}]\nA metric's \"value\" must always be an inline string:\n \"value\": \"$1,200\"\n\nPATH BINDING EXCEPTION — SCHEMA-DRIVEN:\nA few properties accept { \"path\": \"/some/path\" } as an alternative to a literal\nvalue. You can identify these in the Available Components schema: the property\nwill list BOTH a literal type AND an object-with-path option. If a property only\nshows a single type (string, number, array, etc.), it does NOT support path\nbinding — use a literal value only.\n\nPath binding is typically used for editable form inputs so the client can write\nuser input back to the data model. When building forms:\n- Bind input \"value\" to a data model path: \"value\": { \"path\": \"/form/name\" }\n- Pre-fill via the \"data\" tool argument: \"data\": { \"form\": { \"name\": \"Alice\" } }\n- Capture values on submit via button action context:\n \"action\": { \"event\": { \"name\": \"submit\", \"context\": { \"name\": { \"path\": \"/form/name\" } } } }\n\nREPEATING CONTENT uses a structural children format (not the same as value binding):\n children: { componentId: \"card-id\", path: \"/items\" }\nComponents inside templates use RELATIVE paths (no leading slash): { \"path\": \"name\" }.`;\n\n/**\n * Design guidelines — visual design rules, component hierarchy tips,\n * and action handler patterns.\n */\nexport const A2UI_DEFAULT_DESIGN_GUIDELINES = `\\\nCreate polished, visually appealing interfaces. ONLY use components listed in the\nAvailable Components schema — do NOT use component names that are not in the schema.\n\nDesign principles:\n- Create clear visual hierarchy within cards and layouts.\n- Keep cards clean — avoid clutter. Whitespace is good.\n- Use consistent surfaceIds (lowercase, hyphenated).\n- NEVER use the same ID for a component and its child — this creates a\n circular dependency. E.g. if id=\"avatar\", child must NOT be \"avatar\".\n- For side-by-side comparisons, use a container with structural children\n (children: { componentId, path }) to repeat a card template per data item.\n- Include images when relevant (logos, icons, product photos):\n - Prefer company logos via Google favicons: https://www.google.com/s2/favicons?domain=example.com&sz=128\n - Do NOT invent Unsplash photo-IDs — they will 404. Only use real, known URLs.\n- For buttons: action MUST use this exact nested format:\n \"action\": { \"event\": { \"name\": \"myAction\", \"context\": { \"key\": \"value\" } } }\n The \"event\" key holds an OBJECT with \"name\" (required) and \"context\" (optional).\n Do NOT use a flat format like {\"event\": \"name\"} — \"event\" must be an object.\n- For forms: check the component schema — if an input's \"value\" property\n supports path binding, use it for editable fields. The submit button's\n action context should reference the same paths to capture user input.\n\nUse the SAME surfaceId as the main surface. Match action names to button action event names.`;\n\n/**\n * When UI helps the user, for both transports: a light nudge to reach for UI\n * where it conveys the answer better than prose, and to stay in prose\n * otherwise.\n */\nexport const GENERATIVE_UI_WHEN_TO_SHOW =\n \"Show UI when it conveys the answer better than prose: to illustrate a concept (a diagram, a chart of how something changes), to compare options side by side, to let the user explore or adjust values, or to collect input. A small, focused surface next to your explanation often lands better than a long description. Reply in prose alone for a quick fact, a short answer, or conversation, and never add UI only as decoration.\";\n\n/** Description of the context entry that carries `GENERATIVE_UI_MARKDOWN_GUIDELINES`. */\nexport const GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION =\n \"Generative UI markdown guide: how to write UI surfaces inside ```a2ui code fences in a normal markdown reply.\";\n\n/**\n * Description of the context entry that carries the compact component schema\n * in the markdown transport.\n *\n * It must not equal `A2UI_SCHEMA_CONTEXT_DESCRIPTION` (the key that\n * `@ag-ui/a2ui-middleware` stamps for tool mode). The LangGraph and Strands\n * adapters find that exact string and move the entry into\n * `state[\"ag-ui\"][\"a2ui_schema\"]` for the `render_a2ui` tool, so it never\n * gets to the system prompt. The markdown transport has no tool, so the\n * schema must stay ordinary context that the model reads as App Context.\n */\nexport const GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION =\n \"Generative UI component schema: the components, props, events, slots, functions, and targets that ```a2ui code fences can use, and the surfaces that already exist.\";\n\n/** Which optional parts of A2UI a manifest uses. The guides leave out the rules for the others. */\nexport interface GenerativeUIGuideFeatures {\n /** A function is mounted: function calls and callRendererFunction. */\n functions: boolean;\n /** A component has an event prop. */\n events: boolean;\n /** A component has a \"multiple\" slot, which takes templates and @index. */\n templates: boolean;\n /** A component has a \"checks\" prop: validation rules on inputs. */\n checks: boolean;\n}\n\n/** Every optional rule group. Use it when the manifest is not known. */\nexport const ALL_GENERATIVE_UI_GUIDE_FEATURES: GenerativeUIGuideFeatures = {\n functions: true,\n events: true,\n templates: true,\n checks: true,\n};\n\n/**\n * The optional parts of A2UI that a manifest uses, so that a guide sends only\n * the rules that the model can apply.\n *\n * @param manifest - The components and the mounted functions of a run.\n * @returns Which optional rule groups the guides include.\n *\n * @example\n * ```ts\n * const guide = buildGenerativeUIMarkdownGuidelines(\n * generativeUIGuideFeatures(manifest),\n * );\n * ```\n */\nexport function generativeUIGuideFeatures(\n manifest: Pick<GenerativeUIManifest, \"components\" | \"functions\">,\n): GenerativeUIGuideFeatures {\n const components = Object.values(manifest.components);\n const hasChildList = (schema: unknown): boolean => {\n if (Array.isArray(schema)) return schema.some(hasChildList);\n if (typeof schema !== \"object\" || schema === null) return false;\n const node = schema as Record<string, unknown>;\n if (node.$ref === A2UI_CHILD_LIST_REF) return true;\n return Object.values(node).some(hasChildList);\n };\n return {\n // App functions only: the built-in ones are always there and have\n // their own rules.\n functions: Object.keys(manifest.functions).some(\n (name) => !isA2UIBasicFunction(name),\n ),\n events: components.some((c) => Object.keys(c.events ?? {}).length > 0),\n templates: components.some(\n (c) =>\n Object.values(c.slots ?? {}).includes(\"multiple\") ||\n hasChildList(c.props),\n ),\n checks: components.some((c) => {\n const properties = c.props.properties;\n return (\n typeof properties === \"object\" &&\n properties !== null &&\n Object.prototype.hasOwnProperty.call(properties, \"checks\")\n );\n }),\n };\n}\n\n/** The first rules of every markdown guideline, before the optional groups. */\nconst MARKDOWN_BASE_RULES = [\n \"Write explanations as normal markdown prose outside the fences.\",\n \"Open a fence with ```a2ui to show the surface in the chat, at the place of the fence.\",\n 'Open a fence with ```a2ui target=<id> to show the surface in a named target. Use only target ids from the schema. When a target has \"components\", its surfaces can use only those components.',\n \"Inside a fence, write one JSON object per line and nothing else. No comments, no trailing commas, no pretty-printing.\",\n \"Keep each operation whole on its line.\",\n 'Give every operation \"version\":\"v1.0\".',\n `Start a surface with one createSurface. Put all the initial data in \"dataModel\" and the \"root\" component in \"components\". Then write the children in updateComponents lines, so that they show while you write:\n \\`\\`\\`a2ui\n {\"version\":\"v1.0\",\"createSurface\":{\"surfaceId\":\"plan-picker\",\"dataModel\":{ ...initial data... },\"components\":[{\"id\":\"root\",\"component\":\"<Name>\",\"children\":[\"seats\",\"pick\"]}]}}\n {\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"plan-picker\",\"components\":[ ...the children... ]}}\n \\`\\`\\``,\n 'Keep \"dataModel\" flat: top-level keys such as \"seats\" or \"form\", never one wrapper object around everything. Check that every { and [ you open in a line is closed.',\n 'Every surface renders from the component with id \"root\". Make every other component reachable from \"root\" through slots.',\n \"Use unique ids. Do not make cycles. A component cannot be its own child.\",\n 'Write a component as one flat object: {\"id\":\"title\",\"component\":\"<Name>\",\"text\":\"Hello\"}.',\n 'Put the component name in \"component\" (never \"type\"). Put props next to it, never inside a \"props\" object.',\n 'A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component, and \"live\":\"polite\" only on text that changes by itself.',\n 'Use only the components, props, events, and slots in the schema. A component with \"includesCommonProps\" also takes every prop in \"commonProps\".',\n 'Give a prop a literal value, or bind it to the data model with {\"@path\":\"/x\"}. Never write {\"path\":\"/x\"} as a binding.',\n 'A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Use only the functions under \"functions\" in the schema. Write a literal when the value never changes.',\n 'formatString interpolates ${...}: {\"@call\":\"formatString\",\"args\":{\"value\":\"${/qty} × ${formatCurrency(value: /price, currency: \\'EUR\\')}\"}}. Inside ${...}, a path has no quotes, a string has single quotes, and a function takes named args.',\n '${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}. Inside formatString: ${formatCurrency(value: calc(expression: \\'seats * 29\\', seats: /seats), currency: \\'USD\\')}. The UI then follows the user\\'s input with no round trip.',\n 'For a computed list (chart data, template items) use series. Its description under \"functions\" in the schema gives the rules and an example. Bind the \"data\" of a Chart or the \"items\" of a List to it; a template path stays a literal path.',\n 'Bind a writable prop to let the user edit it: \"value\":{\"@path\":\"/form/email\"}. The user\\'s input goes to that path.',\n 'To change data, write updateDataModel with a \"path\" and a \"value\": {\"version\":\"v1.0\",\"updateDataModel\":{\"surfaceId\":\"plan-picker\",\"path\":\"/seats\",\"value\":12}}. Always give \"value\".',\n 'Set \"value\":null to delete the key at \"path\".',\n];\n\n/** The last rules of every markdown guideline, after the optional groups. */\nconst MARKDOWN_CLOSING_RULES = [\n 'The schema lists the surfaces that already exist under \"surfaces\". \"dataModel\" holds the values that the user entered: read them, and do not write those paths. \"rejected\" lists operations that the client dropped: send corrected operations in a new fence for that surfaceId. \"status\":\"deleted\" means the surface is gone: never use its id again. \"status\":\"failed\" means its createSurface was rejected: send a corrected createSurface with that id.',\n \"Never make a surface that is only prose. Write headings, paragraphs, lists of text, intros, and summaries as markdown outside the fences, also between two fences.\",\n \"Put in a fence only what markdown cannot show: charts, tables, maps, images, badges, inputs, buttons, cards with controls.\",\n \"Use Card only for an interactive panel (controls, a form, a configurator). Put everything else in a plain layout component.\",\n \"Never wrap the whole reply in a fence.\",\n];\n\n/**\n * Builds the markdown-transport guideline. The model writes A2UI v1.0\n * operations inside ```a2ui fences between normal markdown prose. The rules\n * for functions, events, and templates are left out when the manifest has\n * none of them, so the guideline stays small.\n *\n * @param features - The optional rule groups to include. Defaults to all.\n * @returns The guideline text, one rule per line.\n */\nexport function buildGenerativeUIMarkdownGuidelines(\n features: GenerativeUIGuideFeatures = ALL_GENERATIVE_UI_GUIDE_FEATURES,\n) {\n const { functions, events, templates, checks } = features;\n const rules = [...MARKDOWN_BASE_RULES];\n if (events) {\n rules.push(\n 'Give an event prop an object: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} or {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}}. Never a flat {\"event\":\"<name>\"}.',\n functions\n ? 'Use {\"functionCall\": ...} to run a function in the browser when the user clicks: an app function from the schema, or openUrl: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call.'\n : 'Use {\"functionCall\": ...} to open a URL when the user clicks: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call.',\n 'Use {\"event\": ...} to send the interaction back to you as a user message. Put the text of that message in \"userMessage\": {\"event\":{\"name\":\"choose\",\"userMessage\":\"Show me the Team plan\"}}. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\".',\n 'To send input values with an event, bind them in the context: \"context\":{\"email\":{\"@path\":\"/form/email\"}}.',\n \"A button or other event prop without an event or functionCall does nothing.\",\n );\n }\n if (checks) {\n rules.push(\n 'Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email; a condition can also be a boolean {\"@path\"}. A failed check shows the message under the input and disables a Button that has the same checks.',\n );\n }\n rules.push(\n 'A prop typed componentId takes the id of another component, and a childList takes ids [\"a\",\"b\"]: \"child\":\"card\", \"children\":[\"a\",\"b\"], \"tabs\":[{\"title\":\"Specs\",\"child\":\"specs\"}].',\n );\n if (templates) {\n rules.push(\n 'To repeat a component for each item of a list, give a childList a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}.',\n 'Inside a template, paths are relative to the item (\"name\", not \"/name\").',\n 'Inside a template, {\"@call\":\"@index\"} gives the position of the item, from 0. To count from 1, write {\"@call\":\"@index\",\"args\":{\"offset\":1}}.',\n );\n }\n rules.push(\n \"Updating a component replaces all of its props. Send every prop again.\",\n \"To change a surface in this reply, write another fence with the same surfaceId. Do not send createSurface again. The surface changes where it already is. A surface in a target can also be changed from a later reply; a chat surface cannot, because the chat is a transcript: a later reply with the same surfaceId makes a new surface.\",\n \"Use a new surfaceId for a different view. Never use a surfaceId again, also after the surface is deleted.\",\n );\n if (functions && GENERATIVE_UI_AGENT_FUNCTION_CALLS) {\n rules.push(\n 'To run an app function now, with no click, write a callRendererFunction line in a fence: {\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}. It needs no surface.',\n 'Give every callRendererFunction a new functionCallId. Call only a function from the schema with \"callers\": \"UI or agent\" or \"agent only\"; a function without \"callers\" is for the UI only. A function with \"callers\": \"agent only\" is only for callRendererFunction: do not bind an event to it.',\n 'The result of a callRendererFunction comes back to you as a developer message: {\"version\":\"v1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Then you get a new turn.',\n \"Do not guess the result of a callRendererFunction. Wait for the developer message.\",\n );\n }\n rules.push(...MARKDOWN_CLOSING_RULES);\n return `You can show interactive UI in your reply. Write A2UI operations inside a fenced code block tagged a2ui.\n\n${GENERATIVE_UI_WHEN_TO_SHOW}\n\nRULES\n${rules.map((rule) => `- ${rule}`).join(\"\\n\")}\n`;\n}\n\n/**\n * The markdown-transport guideline with every rule group. A run sends\n * `buildGenerativeUIMarkdownGuidelines` for its own manifest instead.\n */\nexport const GENERATIVE_UI_MARKDOWN_GUIDELINES =\n buildGenerativeUIMarkdownGuidelines();\n","/**\n * The generative UI envelope that the client sends on every run as\n * `forwardedProps.copilotkit.ui`. It has the A2UI v1.0 renderer capabilities\n * shape, so a backend that speaks A2UI v1.0 can read the catalog as it is.\n * CopilotKit data goes in `metadata.extensions`, under `copilotkit_` keys.\n * The runtime reads it to pick the transport and to build the guide.\n */\nimport {\n GENERATIVE_UI_MAX_REJECTION_LENGTH,\n GENERATIVE_UI_MAX_SUMMARY_REJECTIONS,\n GENERATIVE_UI_MAX_TARGET_COMPONENTS,\n} from \"./generative-ui/types\";\nimport type {\n A2UIActionMessage,\n GenerativeUIComponentManifest,\n GenerativeUIFunctionManifest,\n GenerativeUIManifest,\n GenerativeUISurfaceSummary,\n GenerativeUITarget,\n} from \"./generative-ui/types\";\nimport { isRecord } from \"./generative-ui/is-record\";\n\n/** Top-level `forwardedProps` key that holds the CopilotKit run properties. */\nexport const COPILOTKIT_FORWARDED_PROPS_KEY = \"copilotkit\";\n\n/** Version of the envelope shape (not of the UI protocol that it carries). */\nexport const COPILOTKIT_UI_ENVELOPE_FORMAT = 3;\n\n/** What the client renders and calls, and how the model must write UI. */\nexport interface CopilotKitUIEnvelope {\n /** The A2UI v1.0 renderer capabilities. */\n \"v1.0\": {\n /**\n * The catalog that the client renders comes first, then the catalogs of\n * its `extends`. An operation can name any of them.\n */\n supportedCatalogIds: string[];\n inlineCatalogs?: Array<{\n catalogId: string;\n protocolVersion: \"1.0\";\n /** Not there when the client is set up with `includeCatalog: false`. */\n components?: Record<string, GenerativeUIComponentManifest>;\n /** The app functions that are mounted now. */\n functions: Record<string, GenerativeUIFunctionManifest>;\n /** The markdown guideline. Only the markdown transport sends it. */\n instructions?: string;\n }>;\n };\n metadata: {\n extensions: {\n /** Envelope shape version. */\n copilotkit_format: typeof COPILOTKIT_UI_ENVELOPE_FORMAT;\n /** \"tool\": the model calls the render tool. \"markdown\": the model writes ```a2ui fences. */\n copilotkit_transport: \"tool\" | \"markdown\";\n copilotkit_targets: GenerativeUIManifest[\"targets\"];\n copilotkit_surfaces: GenerativeUIManifest[\"surfaces\"];\n /** True when the client also sent the guide as context entries on this run. */\n copilotkit_contextSent: boolean;\n /**\n * The A2UI action that started this run, when a user event did: the\n * structured form of the user message that the event added.\n */\n copilotkit_action?: A2UIActionMessage;\n };\n };\n}\n\ntype InlineCatalog = NonNullable<\n CopilotKitUIEnvelope[\"v1.0\"][\"inlineCatalogs\"]\n>[number];\ntype Extensions = CopilotKitUIEnvelope[\"metadata\"][\"extensions\"];\n\nfunction isOptionalString(value: unknown) {\n return value === undefined || typeof value === \"string\";\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value !== \"\";\n}\n\nfunction isRecordOf<T>(\n value: unknown,\n isEntry: (entry: unknown) => entry is T,\n): value is Record<string, T> {\n return isRecord(value) && Object.values(value).every(isEntry);\n}\n\n/** A function, or an event of a component: a description and a parameter schema. */\nfunction isSchemaEntry(value: unknown): value is GenerativeUIFunctionManifest {\n return (\n isRecord(value) &&\n isRecord(value.parameters) &&\n isOptionalString(value.description)\n );\n}\n\nfunction isSlotKind(value: unknown): value is \"single\" | \"multiple\" {\n return value === \"single\" || value === \"multiple\";\n}\n\n/**\n * `validateOperation` reads `properties` and `required` of a props schema,\n * so those two must have the right shape when they are there.\n */\nfunction isPropsSchema(value: unknown): value is Record<string, unknown> {\n return (\n isRecord(value) &&\n (value.properties === undefined || isRecord(value.properties)) &&\n (value.required === undefined ||\n (Array.isArray(value.required) &&\n value.required.every((name) => typeof name === \"string\")))\n );\n}\n\nfunction isComponentManifest(\n value: unknown,\n): value is GenerativeUIComponentManifest {\n if (\n !isRecord(value) ||\n !isPropsSchema(value.props) ||\n !isOptionalString(value.description) ||\n (value.events !== undefined && !isRecordOf(value.events, isSchemaEntry)) ||\n (value.slots !== undefined && !isRecordOf(value.slots, isSlotKind))\n )\n return false;\n const order = value.parameterOrder;\n if (order === undefined) return true;\n const keys = new Set([\n ...Object.keys(value.props.properties ?? {}),\n ...Object.keys(value.slots ?? {}),\n ...Object.keys(value.events ?? {}),\n ]);\n return (\n Array.isArray(order) &&\n new Set(order).size === order.length &&\n order.every((key) => typeof key === \"string\" && keys.has(key))\n );\n}\n\nfunction isInlineCatalog(value: unknown): value is InlineCatalog {\n return (\n isRecord(value) &&\n isNonEmptyString(value.catalogId) &&\n value.protocolVersion === \"1.0\" &&\n (value.components === undefined ||\n isRecordOf(value.components, isComponentManifest)) &&\n isRecordOf(value.functions, isSchemaEntry) &&\n isOptionalString(value.instructions)\n );\n}\n\nfunction isCapabilities(value: unknown): value is CopilotKitUIEnvelope[\"v1.0\"] {\n return (\n isRecord(value) &&\n Array.isArray(value.supportedCatalogIds) &&\n value.supportedCatalogIds.length > 0 &&\n value.supportedCatalogIds.every(isNonEmptyString) &&\n (value.inlineCatalogs === undefined ||\n (Array.isArray(value.inlineCatalogs) &&\n value.inlineCatalogs.every(isInlineCatalog)))\n );\n}\n\n/** A short list of component names. */\nfunction isComponentNameList(value: unknown): value is string[] {\n return (\n Array.isArray(value) &&\n value.length <= GENERATIVE_UI_MAX_TARGET_COMPONENTS &&\n value.every(isNonEmptyString)\n );\n}\n\nfunction isTarget(value: unknown): value is GenerativeUITarget {\n return (\n isRecord(value) &&\n isNonEmptyString(value.id) &&\n (value.kind === \"chat\" || value.kind === \"inline\") &&\n isOptionalString(value.description) &&\n (value.components === undefined || isComponentNameList(value.components))\n );\n}\n\n/** A short list of short strings. The summary limits keep the guide small. */\nfunction isRejectionList(value: unknown): value is string[] {\n return (\n Array.isArray(value) &&\n value.length <= GENERATIVE_UI_MAX_SUMMARY_REJECTIONS &&\n value.every(\n (entry) =>\n typeof entry === \"string\" &&\n entry.length <= GENERATIVE_UI_MAX_REJECTION_LENGTH,\n )\n );\n}\n\nfunction isSurfaceEntry(value: unknown): value is GenerativeUISurfaceSummary {\n return (\n isRecord(value) &&\n isNonEmptyString(value.target) &&\n (value.dataModel === undefined || isRecord(value.dataModel)) &&\n (value.rejected === undefined || isRejectionList(value.rejected)) &&\n (value.status === undefined ||\n value.status === \"deleted\" ||\n value.status === \"failed\")\n );\n}\n\n/** Checks the `copilotkit_` keys only. Other extensions can be there too. */\nfunction isExtensions(value: unknown): value is Extensions {\n return (\n isRecord(value) &&\n value.copilotkit_format === COPILOTKIT_UI_ENVELOPE_FORMAT &&\n (value.copilotkit_transport === \"tool\" ||\n value.copilotkit_transport === \"markdown\") &&\n Array.isArray(value.copilotkit_targets) &&\n value.copilotkit_targets.every(isTarget) &&\n isRecordOf(value.copilotkit_surfaces, isSurfaceEntry) &&\n typeof value.copilotkit_contextSent === \"boolean\"\n );\n}\n\nfunction isEnvelope(value: unknown): value is CopilotKitUIEnvelope {\n return (\n isRecord(value) &&\n isCapabilities(value[\"v1.0\"]) &&\n isRecord(value.metadata) &&\n isExtensions(value.metadata.extensions)\n );\n}\n\n/**\n * Reads the generative UI envelope from the `forwardedProps` of a run.\n *\n * The envelope comes from the client, so it is not trusted: every field is\n * checked. Returns `undefined` when the envelope is not there, or when it is\n * malformed (for example a wrong `copilotkit_format` or\n * `copilotkit_transport`, or no catalog id).\n *\n * @param forwardedProps - The `forwardedProps` of the run input.\n *\n * @example\n * ```ts\n * const envelope = readCopilotKitUIEnvelope(input.forwardedProps);\n * if (envelope?.metadata.extensions.copilotkit_transport === \"markdown\") {\n * // The model writes ```a2ui fences. Add no render tool.\n * }\n * ```\n */\nexport function readCopilotKitUIEnvelope(forwardedProps: unknown) {\n if (!isRecord(forwardedProps)) return undefined;\n const namespace = forwardedProps[COPILOTKIT_FORWARDED_PROPS_KEY];\n if (!isRecord(namespace)) return undefined;\n const envelope = namespace.ui;\n return isEnvelope(envelope) ? envelope : undefined;\n}\n\n/**\n * Turns an envelope into the manifest that the runtime and the prompts use.\n *\n * The catalog is the first of `supportedCatalogIds`, and `catalogIds` lists\n * all of them. The components, functions, and instructions come from the\n * inline catalog of the first id.\n * With no such inline catalog, there are no components and no functions.\n *\n * The result also has:\n * - `transport` and `contextSent`, from the extensions.\n * - `instructions`, when the inline catalog has them.\n * - `hasComponents`: false when the client left the component schemas out.\n * The runtime cannot check operations without them.\n * - `action`: the A2UI action message of the user event that started the\n * run, when one did.\n *\n * @param envelope - An envelope from `readCopilotKitUIEnvelope`.\n *\n * @example\n * ```ts\n * const envelope = readCopilotKitUIEnvelope(input.forwardedProps);\n * const manifest = envelope && envelopeToManifest(envelope);\n * if (manifest?.transport === \"tool\" && manifest.hasComponents) {\n * // Add the render tool and validate operations against manifest.components.\n * }\n * ```\n */\nexport function envelopeToManifest(envelope: CopilotKitUIEnvelope) {\n const { supportedCatalogIds, inlineCatalogs } = envelope[\"v1.0\"];\n const catalogId = supportedCatalogIds[0];\n const catalog = inlineCatalogs?.find(\n (entry) => entry.catalogId === catalogId,\n );\n const extensions = envelope.metadata.extensions;\n const manifest: GenerativeUIManifest = {\n catalogId,\n catalogIds: supportedCatalogIds,\n components: catalog?.components ?? {},\n functions: catalog?.functions ?? {},\n targets: extensions.copilotkit_targets,\n surfaces: extensions.copilotkit_surfaces,\n };\n return {\n ...manifest,\n transport: extensions.copilotkit_transport,\n contextSent: extensions.copilotkit_contextSent,\n instructions: catalog?.instructions,\n hasComponents: catalog?.components !== undefined,\n ...(extensions.copilotkit_action === undefined\n ? {}\n : { action: extensions.copilotkit_action }),\n };\n}\n","/** Shared generation contract for all Open Generative UI renderers. */\nexport const GENERATE_SANDBOXED_UI_DESCRIPTION =\n \"Generate sandboxed UI. \" +\n \"IMPORTANT: The generated code runs in a sandboxed iframe WITHOUT same-origin access. \" +\n \"Do NOT use localStorage, sessionStorage, document.cookie, IndexedDB, or fetch/XMLHttpRequest to same-origin URLs. \" +\n \"To communicate with the host application, use Websandbox.connection.remote.<functionName>(args) which returns a Promise.\\n\\n\" +\n \"You CAN use external libraries from CDNs by including <script> or <link> tags in the HTML <head> (e.g., Chart.js, D3, Three.js, x-data-spreadsheet, etc.). \" +\n \"CDN resources load normally inside the sandbox.\\n\\n\" +\n \"PARAMETER ORDER IS CRITICAL — generate parameters in exactly this order:\\n\" +\n \"1. initialHeight + placeholderMessages (shown to user while generating)\\n\" +\n \"2. css (all styles FIRST — the user sees a placeholder until CSS is complete)\\n\" +\n \"3. html (streams in live — the user watches the UI build as HTML is generated)\\n\" +\n \"4. jsFunctions (reusable helper functions)\\n\" +\n \"5. jsExpressions (applied one-by-one — the user sees each expression take effect)\" +\n \"\\n\\nINITIALIZATION CONTRACT: jsFunctions and jsExpressions run after the final HTML DOM is ready, in both live generation and saved-thread replay. \" +\n \"Define reusable functions in jsFunctions, then initialize the UI directly in the first jsExpressions entry (for example, initializeCalculator()). \" +\n \"Attach click/keyboard handlers and set initial display values there. Do NOT wait for DOMContentLoaded, window.onload, or the load event in jsFunctions or jsExpressions: these events may already have fired. \" +\n \"Each expression is executed once per rendered sandbox; later expressions must not repeat initialization or reattach the same handlers. \" +\n \"Keep initialization self-contained so a new sandbox can reconstruct the UI when a saved thread is opened. If a library loads asynchronously, initialize from its explicit load promise instead of waiting for document readiness.\\n\\n\" +\n \"INTERACTION CONTRACT: Every visible interactive control needs a working handler, including controls created during initialization. If the handlers are supplied through jsFunctions/jsExpressions, initialize them in the first expression; if supplied by an inline HTML script, ensure it runs when the final sandbox mounts and replays. Every user action must update the visible UI to reflect its completed result, including success and error paths. Changing a JavaScript variable alone does not update the DOM. After changing state, call the rendering function or update the displayed element directly. When delegating clicks from a parent element, resolve the clicked control with closest('button') so clicks on nested labels and values work. For a calculator, pressing = must replace the visible expression with the computed answer; metric shortcuts must visibly insert their values. Trace each button handler through its final display update before emitting the tool call.\";\n","import {\n GENERATIVE_UI_FUNCTIONS,\n functionCallers,\n isA2UIBasicFunction,\n isA2UIValueFunction,\n isCallBinding,\n} from \"./basic-functions\";\nimport type { A2UIFunctionPermissions } from \"./basic-functions\";\nimport { collectChildRefs } from \"./child-refs\";\nimport type { ChildRef } from \"./child-refs\";\nimport {\n A2UI_VERSION,\n GENERATIVE_UI_AGENT_FUNCTION_CALLS,\n GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON,\n} from \"./types\";\nimport type {\n GenerativeUIActionBinding,\n GenerativeUIJSONSchema,\n GenerativeUIManifest,\n} from \"./types\";\nimport { isRecord } from \"./is-record\";\n\nexport type OperationValidation = { ok: true } | { ok: false; reason: string };\n\nconst OPERATION_KINDS = [\n \"createSurface\",\n \"updateComponents\",\n \"updateDataModel\",\n \"deleteSurface\",\n \"callRendererFunction\",\n] as const;\nexport type OperationKind = (typeof OPERATION_KINDS)[number];\n\nexport interface ValidateOperationOptions {\n manifest: Pick<\n GenerativeUIManifest,\n \"catalogId\" | \"catalogIds\" | \"components\"\n >;\n /**\n * Surfaces that exist before this operation is applied. `updateComponents`,\n * `updateDataModel`, and `deleteSurface` need their surface in this set.\n */\n knownSurfaces: ReadonlySet<string>;\n /**\n * Surface ids that were created before, also the deleted ones. A surface id\n * is unique for the life of the page, so `createSurface` rejects them.\n */\n createdSurfaces?: ReadonlySet<string>;\n /**\n * UI-callable functions. When provided, `functionCall` bindings and\n * `callRendererFunction` must name one of them. The client omits it:\n * availability is checked when the function runs.\n */\n functions?: GenerativeUIManifest[\"functions\"];\n /**\n * The components that the target of the surface takes. When provided,\n * `updateComponents` and the inline components of `createSurface` can use\n * only these names. Left out, every catalog component is allowed.\n */\n allowedComponents?: AllowedComponents;\n}\n\n/** The component names that one target takes. */\nexport interface AllowedComponents {\n /** The target id, for the reason of a rejection. */\n target: string;\n names: ReadonlySet<string>;\n}\n\nconst OK: OperationValidation = { ok: true };\nconst fail = (reason: string): OperationValidation => ({ ok: false, reason });\n\n/** Models write the v0.9 binding from habit. The reason names the v1.0 form. */\nconst V09_PATH_REASON = 'bind data with {\"@path\": \"/x\"}, not {\"path\": \"/x\"}';\n\nfunction hasOwn(record: object, key: string) {\n return Object.prototype.hasOwnProperty.call(record, key);\n}\n\n/**\n * Reads an own property only. Model-controlled keys such as \"constructor\" or\n * \"toString\" must not resolve to Object.prototype members.\n */\nfunction ownValue<T>(record: Record<string, T> | undefined, key: string) {\n return record && hasOwn(record, key) ? record[key] : undefined;\n}\n\nexport function getOperationKind(op: unknown) {\n if (!isRecord(op)) return undefined;\n const kinds = OPERATION_KINDS.filter((kind) => kind in op);\n return kinds.length === 1 ? kinds[0] : undefined;\n}\n\n/** The `surfaceId` of a surface operation. `callRendererFunction` has none. */\nexport function getOperationSurfaceId(op: unknown) {\n if (!isRecord(op)) return undefined;\n const kind = getOperationKind(op);\n if (!kind) return undefined;\n const payload = op[kind];\n return isRecord(payload) && typeof payload.surfaceId === \"string\"\n ? payload.surfaceId\n : undefined;\n}\n\n/** `{ \"@path\": \"/x\" }`: a data-model binding. */\nexport function isPathBinding(value: unknown): value is { \"@path\": string } {\n return (\n isRecord(value) &&\n typeof value[\"@path\"] === \"string\" &&\n Object.keys(value).length === 1\n );\n}\n\n/** `{ \"path\": \"/x\" }`: the v0.9 binding, which v1.0 does not accept. */\nfunction isV09PathBinding(value: unknown) {\n return (\n isRecord(value) &&\n typeof value.path === \"string\" &&\n Object.keys(value).length === 1\n );\n}\n\n/**\n * `{ \"@call\": \"@index\" }` or `{ \"@call\": \"@index\", \"args\": { \"offset\": 1 } }`:\n * the 0-based position of the item in a template, plus `offset`.\n */\nexport function isIndexCall(\n value: unknown,\n): value is { \"@call\": \"@index\"; args?: { offset?: number } } {\n if (!isRecord(value) || value[\"@call\"] !== \"@index\") return false;\n const hasOnlyCallKeys = Object.keys(value).every(\n (key) => key === \"@call\" || key === \"args\",\n );\n if (!hasOnlyCallKeys) return false;\n const { args } = value;\n if (args === undefined) return true;\n return (\n isRecord(args) &&\n Object.keys(args).every((key) => key === \"offset\") &&\n (args.offset === undefined || Number.isFinite(args.offset))\n );\n}\n\nexport function isActionBinding(\n value: unknown,\n): value is GenerativeUIActionBinding {\n return (\n isRecord(value) &&\n Object.keys(value).length === 1 &&\n (isRecord(value.functionCall) || isRecord(value.event))\n );\n}\n\n/**\n * Checks one A2UI v1.0 operation against the catalog and the surfaces that\n * exist. The operation comes from the model, so nothing in it is trusted.\n *\n * @param op - The operation, as parsed from JSON.\n * @param options - The catalog, the known and created surfaces, the\n * functions that the UI can call, and the components that the target of\n * the surface takes.\n *\n * @example\n * ```ts\n * const result = validateOperation(op, { manifest, knownSurfaces });\n * if (!result.ok) rejected.push({ index, reason: result.reason });\n * ```\n */\nexport function validateOperation(\n op: unknown,\n options: ValidateOperationOptions,\n) {\n if (!isRecord(op)) return fail(\"operation must be a JSON object\");\n if (op.version !== A2UI_VERSION) return fail(versionProblem(op.version));\n const kind = getOperationKind(op);\n if (!kind) {\n return fail(\n `operation must contain exactly one of ${OPERATION_KINDS.join(\", \")}`,\n );\n }\n const payload = op[kind];\n if (kind === \"callRendererFunction\") {\n if (!GENERATIVE_UI_AGENT_FUNCTION_CALLS) {\n return fail(GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON);\n }\n return validateRendererFunctionCall(payload, options);\n }\n if (\n !isRecord(payload) ||\n typeof payload.surfaceId !== \"string\" ||\n !payload.surfaceId\n ) {\n return fail(`${kind}.surfaceId is required`);\n }\n const surfaceId = payload.surfaceId;\n if (kind === \"createSurface\") {\n return validateCreateSurface(payload, surfaceId, options);\n }\n if (!options.knownSurfaces.has(surfaceId)) {\n return fail(\n `surface \"${surfaceId}\" does not exist; send createSurface first`,\n );\n }\n switch (kind) {\n case \"deleteSurface\":\n return OK;\n case \"updateDataModel\":\n return validateDataModelUpdate(payload);\n case \"updateComponents\":\n return validateComponents(\n payload.components,\n \"updateComponents.components\",\n options,\n );\n }\n}\n\nfunction versionProblem(version: unknown) {\n return typeof version === \"string\"\n ? `unsupported version \"${version}\"; use \"${A2UI_VERSION}\"`\n : `operation needs \"version\":\"${A2UI_VERSION}\"`;\n}\n\n/** A `catalogId` can name the catalog of the run or one of its bases. */\nfunction catalogProblem(\n catalogId: unknown,\n manifest: ValidateOperationOptions[\"manifest\"],\n) {\n const ids = manifest.catalogIds ?? [manifest.catalogId];\n if (catalogId === undefined || ids.includes(catalogId as string)) {\n return undefined;\n }\n const names = ids.map((id) => `\"${id}\"`).join(\", \");\n const use = ids.length === 1 ? names : `one of: ${names}`;\n return `unknown catalog \"${String(catalogId)}\"; leave out catalogId or use ${use}`;\n}\n\nfunction validateCreateSurface(\n payload: Record<string, unknown>,\n surfaceId: string,\n options: ValidateOperationOptions,\n) {\n if (options.knownSurfaces.has(surfaceId)) {\n return fail(`surface \"${surfaceId}\" already exists`);\n }\n if (options.createdSurfaces?.has(surfaceId)) {\n return fail(\n `surface id \"${surfaceId}\" was used before; use a new surfaceId`,\n );\n }\n const catalogReason = catalogProblem(payload.catalogId, options.manifest);\n if (catalogReason) return fail(catalogReason);\n const { dataModel, components } = payload;\n if (dataModel !== undefined && !isRecord(dataModel)) {\n return fail(\"createSurface.dataModel must be a JSON object\");\n }\n if (components === undefined) return OK;\n return validateComponents(components, \"createSurface.components\", options);\n}\n\nfunction validateRendererFunctionCall(\n payload: unknown,\n options: ValidateOperationOptions,\n) {\n const hasCallId =\n isRecord(payload) &&\n typeof payload.functionCallId === \"string\" &&\n payload.functionCallId !== \"\";\n if (!hasCallId) {\n return fail(\n \"callRendererFunction.functionCallId must be a non-empty string\",\n );\n }\n const reason = functionCallProblem(\n payload.callFunction,\n \"callRendererFunction.callFunction\",\n options,\n );\n return reason ? fail(reason) : OK;\n}\n\nconst FORBIDDEN_SEGMENTS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction decodeSegment(segment: string) {\n return segment.replace(/~([01])/g, (_, g) => (g === \"1\" ? \"/\" : \"~\"));\n}\n\nfunction validateDataModelUpdate(payload: Record<string, unknown>) {\n if (payload.value === undefined) {\n return fail(\n 'updateDataModel.value is required; use \"value\":null to delete',\n );\n }\n const path = payload.path ?? \"/\";\n if (typeof path !== \"string\" || !path.startsWith(\"/\")) {\n return fail(\"updateDataModel.path must be an absolute JSON pointer\");\n }\n if (path === \"/\") {\n // Paths such as \"/items\" point into the root, so the root must be an object.\n if (!isRecord(payload.value)) {\n return fail(\"a root updateDataModel value must be a JSON object\");\n }\n return OK;\n }\n const reason = pathProblem(path, \"updateDataModel.path\");\n return reason ? fail(reason) : OK;\n}\n\n/**\n * Checks the segments of an absolute JSON pointer (\"/a/b\") or of a path\n * relative to a template item (\"a/b\"). `label` names the field in the reason.\n */\nfunction pathProblem(path: string, label: string) {\n const relative = path.startsWith(\"/\") ? path.slice(1) : path;\n const segments = relative.split(\"/\");\n if (segments.some((segment) => segment === \"\")) {\n return `${label} must not contain empty segments`;\n }\n const decoded = segments.map(decodeSegment);\n const forbidden = decoded.find((segment) => FORBIDDEN_SEGMENTS.has(segment));\n if (forbidden !== undefined) {\n return `path segment \"${forbidden}\" is not allowed in ${label}`;\n }\n return undefined;\n}\n\nfunction validateComponents(\n components: unknown,\n label: string,\n options: ValidateOperationOptions,\n) {\n if (!Array.isArray(components) || components.length === 0) {\n return fail(`${label} must be a non-empty array`);\n }\n const ids = new Set<string>();\n for (const node of components) {\n if (!isRecord(node)) return fail(\"component must be a JSON object\");\n const { id } = node;\n if (typeof id !== \"string\" || !id) return fail(\"id is required\");\n const reason = nodeProblem(node, id, options);\n if (reason) return fail(`component \"${id}\": ${reason}`);\n if (ids.has(id)) {\n return fail(`component \"${id}\" appears twice in one update`);\n }\n ids.add(id);\n }\n return OK;\n}\n\nfunction nodeProblem(\n node: Record<string, unknown>,\n id: string,\n options: ValidateOperationOptions,\n) {\n if (typeof node.component !== \"string\") return \"component type is required\";\n const entry = ownValue(options.manifest.components, node.component);\n if (!entry) return `unknown component \"${node.component}\"`;\n const { allowedComponents } = options;\n if (allowedComponents && !allowedComponents.names.has(node.component)) {\n const names = [...allowedComponents.names].join(\", \") || \"none\";\n return `\"${node.component}\" is not allowed in target \"${allowedComponents.target}\"; use one of: ${names}`;\n }\n const { properties, required } = entry.props;\n const propNames = isRecord(properties) ? Object.keys(properties) : [];\n const props = Object.entries(node);\n for (const [key, value] of props) {\n if (key === \"id\" || key === \"component\") continue;\n if (key === \"catalogId\") {\n const reason = catalogProblem(value, options.manifest);\n if (reason) return `${key}: ${reason}`;\n continue;\n }\n if (key === \"metadata\") {\n const isMetadata =\n isRecord(value) &&\n (value.extensions === undefined || isRecord(value.extensions));\n if (!isMetadata) return 'metadata must be { \"extensions\": { ... } }';\n continue;\n }\n if (key === \"accessibility\") {\n const reason = accessibilityProblem(value);\n if (reason) return `${key}: ${reason}`;\n continue;\n }\n if (ownValue(entry.events, key)) {\n const reason = actionBindingProblem(value, options);\n if (reason) return `${key}: ${reason}`;\n continue;\n }\n const slot = ownValue(entry.slots, key);\n if (slot) {\n const reason = slotProblem(value, slot, id);\n if (reason) return `${key}: ${reason}`;\n continue;\n }\n if (!propNames.includes(key)) return `unknown prop \"${key}\"`;\n if (isV09PathBinding(value)) return `${key}: ${V09_PATH_REASON}`;\n const call = findForbiddenCall(value, { allowValueFunctions: true });\n if (call !== undefined) {\n return `${key}: ${call}; a data prop can call only ${VALUE_FUNCTION_LIST}`;\n }\n }\n for (const ref of childRefsOf(entry.props)) {\n const reason = childRefProblem(node, ref, id);\n if (reason) return reason;\n }\n const requiredNames = Array.isArray(required) ? required : [];\n for (const name of requiredNames) {\n if (typeof name === \"string\" && !(name in node)) {\n return `missing required prop \"${name}\"`;\n }\n }\n return undefined;\n}\n\nconst ACCESSIBILITY_KEYS = [\"label\", \"description\", \"live\", \"hidden\"];\nconst LIVE_VALUES = [\"off\", \"polite\", \"assertive\"];\n\n/**\n * Checks the `accessibility` of a component envelope: `label` and\n * `description` are strings or dynamic values, `live` is one of the ARIA\n * values, `hidden` is a boolean or a dynamic value.\n */\nfunction accessibilityProblem(value: unknown) {\n if (!isRecord(value)) {\n return 'must be { \"label\": \"...\", \"description\": \"...\", \"live\": \"polite\", \"hidden\": false }';\n }\n const isDynamic = (field: unknown) =>\n isPathBinding(field) || isCallBinding(field);\n for (const [key, field] of Object.entries(value)) {\n if (!ACCESSIBILITY_KEYS.includes(key)) return `unknown key \"${key}\"`;\n if (isV09PathBinding(field)) return `${key}: ${V09_PATH_REASON}`;\n if (isDynamic(field)) {\n const call = findForbiddenCall(field, { allowValueFunctions: true });\n if (call !== undefined) return `${key}: ${call}`;\n continue;\n }\n if (key === \"live\") {\n if (typeof field !== \"string\" || !LIVE_VALUES.includes(field)) {\n return `live must be one of ${LIVE_VALUES.join(\", \")}`;\n }\n } else if (key === \"hidden\") {\n if (typeof field !== \"boolean\") return \"hidden must be a boolean\";\n } else if (typeof field !== \"string\") {\n return `${key} must be a string`;\n }\n }\n return undefined;\n}\n\nfunction actionBindingProblem(\n value: unknown,\n options: ValidateOperationOptions,\n) {\n if (!isRecord(value)) return \"must be an action object\";\n const keys = Object.keys(value);\n const isOneAction =\n keys.length === 1 && (keys[0] === \"functionCall\" || keys[0] === \"event\");\n if (!isOneAction) {\n return 'must be { \"event\": ... } or { \"functionCall\": ... }';\n }\n if (keys[0] === \"functionCall\") {\n return functionCallProblem(value.functionCall, \"functionCall\", options);\n }\n return eventProblem(value.event);\n}\n\n/**\n * Checks `{ \"@call\": \"<function>\", \"args\": { ... } }`. `label` names the\n * field in the reason.\n */\nfunction functionCallProblem(\n call: unknown,\n label: string,\n options: ValidateOperationOptions,\n) {\n if (!isRecord(call)) {\n return `${label} must be { \"@call\": \"<function>\", \"args\": { ... } }`;\n }\n const name = call[\"@call\"];\n if (typeof name !== \"string\" || !name) {\n return typeof call.call === \"string\"\n ? `${label} names the function with \"@call\", not \"call\"`\n : `${label}[\"@call\"] must be a function name`;\n }\n const { args } = call;\n if (args !== undefined && !isRecord(args)) {\n return `${label}.args must be an object`;\n }\n const catalogReason = catalogProblem(call.catalogId, options.manifest);\n if (catalogReason) return `${label}: ${catalogReason}`;\n const argEntries = Object.entries(args ?? {});\n for (const [key, arg] of argEntries) {\n if (isV09PathBinding(arg))\n return `${label}.args.${key}: ${V09_PATH_REASON}`;\n }\n // A function the app declares under a built-in name is the app's; the\n // restrictions of the built-in do not apply to it.\n const appFunctions = options.functions;\n const declared =\n appFunctions !== undefined && hasOwn(appFunctions, name)\n ? appFunctions[name]\n : undefined;\n const builtIn =\n declared === undefined && hasOwn(GENERATIVE_UI_FUNCTIONS, name)\n ? GENERATIVE_UI_FUNCTIONS[name]\n : undefined;\n if (declared === undefined && builtIn === undefined) {\n return appFunctions === undefined\n ? undefined\n : `function \"${name}\" is not exposed to generative UI`;\n }\n // Without the list of app functions, a built-in name may be the app's own\n // function, so the dispatcher applies the restriction when the call runs.\n if (declared === undefined && appFunctions === undefined) return undefined;\n return callerProblem(\n name,\n declared ?? builtIn!,\n label.startsWith(\"callRendererFunction\") ? \"agent\" : \"renderer\",\n );\n}\n\n/**\n * Why `caller` may not call a function with these permissions, or\n * `undefined` when it may. The dispatcher gives the same reasons at run\n * time, for the calls that are not validated against a function list.\n */\nexport function callerProblem(\n name: string,\n fn: A2UIFunctionPermissions,\n caller: \"agent\" | \"renderer\",\n) {\n const callers = functionCallers(fn);\n if (caller === \"agent\" && !callers.agent) {\n return fn.requiresUserActivation\n ? `function \"${name}\" runs only from a user gesture; the agent cannot call it`\n : `function \"${name}\" runs only in the UI (allowedCallers \"rendererOnly\"); the agent cannot call it`;\n }\n if (caller === \"renderer\" && !callers.renderer) {\n return `function \"${name}\" runs only for the agent (allowedCallers \"agentOnly\"); the UI cannot call it`;\n }\n return undefined;\n}\n\nfunction eventProblem(event: unknown) {\n if (!isRecord(event) || typeof event.name !== \"string\" || !event.name) {\n return \"event.name is required\";\n }\n const { userMessage, context } = event;\n const isUserMessage =\n userMessage === undefined ||\n typeof userMessage === \"string\" ||\n isPathBinding(userMessage) ||\n (isRecord(userMessage) &&\n typeof userMessage[\"@call\"] === \"string\" &&\n findForbiddenCall(userMessage, { allowValueFunctions: true }) ===\n undefined);\n if (!isUserMessage) {\n return isV09PathBinding(userMessage)\n ? `event.userMessage: ${V09_PATH_REASON}`\n : 'event.userMessage must be a string, {\"@path\": \"/x\"} or a function value';\n }\n if (context === undefined) return undefined;\n if (!isRecord(context)) return \"event.context must be an object\";\n const entries = Object.entries(context);\n for (const [key, entry] of entries) {\n if (isV09PathBinding(entry)) {\n return `event.context.${key}: ${V09_PATH_REASON}`;\n }\n const call = findForbiddenCall(entry, { allowValueFunctions: true });\n if (call !== undefined) {\n return `event.context.${key}: ${call}; a context value can call only ${VALUE_FUNCTION_LIST}`;\n }\n }\n return undefined;\n}\n\nfunction slotProblem(\n value: unknown,\n kind: \"single\" | \"multiple\",\n ownId: string,\n) {\n const isTemplate = isRecord(value) && \"componentId\" in value;\n if (kind === \"single\" && isTemplate) {\n return 'a template { \"componentId\", \"path\" } is only allowed in a \"multiple\" slot';\n }\n if (kind === \"multiple\" && isTemplate) {\n return templateProblem(value, ownId);\n }\n if (kind === \"multiple\" && !Array.isArray(value)) {\n return 'must be an array of component ids or a template { \"componentId\", \"path\" }';\n }\n const ids = kind === \"multiple\" && Array.isArray(value) ? value : [value];\n for (const id of ids) {\n if (typeof id !== \"string\" || !id)\n return \"must reference component ids (strings)\";\n if (id === ownId) return \"a component cannot be its own child\";\n }\n return undefined;\n}\n\nfunction templateProblem(template: Record<string, unknown>, ownId: string) {\n const hasOnlyTemplateKeys = Object.keys(template).every(\n (key) => key === \"componentId\" || key === \"path\",\n );\n if (!hasOnlyTemplateKeys) {\n return 'a template takes only \"componentId\" and \"path\"';\n }\n const { componentId, path } = template;\n if (typeof componentId !== \"string\" || !componentId) {\n return \"template componentId must be a component id\";\n }\n if (componentId === ownId) return \"a component cannot be its own child\";\n if (typeof path !== \"string\" || !path) {\n return \"template path must be a JSON pointer or a relative path\";\n }\n return pathProblem(path, \"template path\");\n}\n\nconst VALUE_FUNCTION_LIST = `@index and the built-in functions (${Object.keys(\n GENERATIVE_UI_FUNCTIONS,\n)\n .filter(isA2UIValueFunction)\n .join(\", \")})`;\n\n/**\n * The reason for the first function call in `value` that a data value may\n * not make, at any depth, or `undefined`. A data value may call `@index`\n * and, with `allowValueFunctions`, the basic functions that need no user\n * gesture; the renderer resolves those. An app function, `openUrl`, or an\n * event binding is not a value.\n */\n// The annotation is needed: the function calls itself in its return.\nfunction findForbiddenCall(\n value: unknown,\n options: { allowValueFunctions: boolean },\n): string | undefined {\n if (Array.isArray(value)) {\n for (const item of value) {\n const reason = findForbiddenCall(item, options);\n if (reason !== undefined) return reason;\n }\n return undefined;\n }\n if (!isRecord(value)) return undefined;\n if (isIndexCall(value)) return undefined;\n if (value[\"@call\"] === \"@index\") return \"@index takes only an offset\";\n if (typeof value.call === \"string\") {\n return 'name the function with \"@call\", not \"call\"';\n }\n if (\"functionCall\" in value) {\n return \"an event binding is not a value\";\n }\n const name = value[\"@call\"];\n if (typeof name === \"string\") {\n if (!options.allowValueFunctions || !isA2UIValueFunction(name)) {\n return isA2UIBasicFunction(name)\n ? `\"${name}\" runs only from an event`\n : `\"${name}\" is not a basic function`;\n }\n const args = value.args;\n if (args !== undefined && !isRecord(args)) {\n return `the args of \"${name}\" must be an object`;\n }\n return args === undefined ? undefined : findForbiddenCall(args, options);\n }\n for (const item of Object.values(value)) {\n const reason = findForbiddenCall(item, options);\n if (reason !== undefined) return reason;\n }\n return undefined;\n}\n\nconst childRefCache = new WeakMap<GenerativeUIJSONSchema, ChildRef[]>();\n\n/** The component references of a props schema, computed once per schema. */\nfunction childRefsOf(props: GenerativeUIJSONSchema) {\n let refs = childRefCache.get(props);\n if (!refs) {\n refs = collectChildRefs(props);\n childRefCache.set(props, refs);\n }\n return refs;\n}\n\n/**\n * Checks the component ids at one reference of a node: a typed `child()`\n * or `childList()` prop, at any depth. A missing key is fine; the props\n * schema reports a required one.\n */\nfunction childRefProblem(\n node: Record<string, unknown>,\n ref: ChildRef,\n ownId: string,\n): string | undefined {\n const label = ref.path.filter((step) => step !== \"*\").join(\".\");\n const isDynamic = (value: unknown) =>\n isPathBinding(value) || (isRecord(value) && \"@call\" in value);\n const visit = (\n value: unknown,\n steps: readonly string[],\n ): string | undefined => {\n // A bound or computed value, at the reference or above it, is known\n // only at render.\n if (isDynamic(value)) return undefined;\n if (steps.length === 0) {\n const reason = slotProblem(value, ref.kind, ownId);\n return reason ? `${label}: ${reason}` : undefined;\n }\n const [head, ...rest] = steps;\n if (head === \"*\") {\n if (!Array.isArray(value)) return undefined;\n for (const item of value) {\n const reason = visit(item, rest);\n if (reason) return reason;\n }\n return undefined;\n }\n if (!isRecord(value) || !hasOwn(value, head)) return undefined;\n return visit(value[head], rest);\n };\n return visit(node, ref.path);\n}\n","import { isRecord } from \"./is-record\";\nexport interface ExtractedRenderUIArgs {\n target?: string;\n /**\n * Complete elements of the `operations` array, in order. A balanced element\n * that is not a valid JSON object is returned as `null`.\n */\n operations: Array<Record<string, unknown> | null>;\n /**\n * Set when an `operations[]` element was opened but its closing brace never\n * arrived: the text ends mid-operation (still streaming, or truncated).\n */\n incompleteOperation?: boolean;\n}\n\n/**\n * Reads `target` and every complete `operations[]` element from a possibly\n * truncated `render_ui` argument string.\n */\nexport function extractRenderUIArgs(text: string) {\n return new RenderUIArgsScanner().scan(text);\n}\n\n/**\n * The parser of {@link extractRenderUIArgs}, with its state kept between\n * calls. Each call scans only the text after the text it scanned before, so\n * a streamed argument string is scanned once in total.\n */\nclass RenderUIArgsScanner {\n private readonly result: ExtractedRenderUIArgs = { operations: [] };\n private readonly stack: Array<\"{\" | \"[\"> = [];\n private inString = false;\n private escaped = false;\n private stringStart = -1;\n private pendingKey: string | null = null;\n private currentKey: string | null = null;\n private expectingValue = false;\n private inOperations = false;\n private elementStart = -1;\n private scanned = 0;\n\n /**\n * Scans `text` from where the last call stopped.\n *\n * @param text - The whole text so far. It starts with the text of the\n * last call.\n * @returns The result so far. It is the same object on each call.\n */\n scan(text: string) {\n const { result, stack } = this;\n let {\n inString,\n escaped,\n stringStart,\n pendingKey,\n currentKey,\n expectingValue,\n inOperations,\n elementStart,\n } = this;\n for (let i = this.scanned; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (ch === \"\\\\\") {\n escaped = true;\n } else if (ch === '\"') {\n inString = false;\n if (stack.length === 1) {\n const literal = text.slice(stringStart, i + 1);\n if (expectingValue) {\n if (currentKey === \"target\") {\n try {\n result.target = JSON.parse(literal);\n } catch {\n // Unreachable for a closed literal; keep scanning.\n }\n }\n expectingValue = false;\n } else {\n pendingKey = literal;\n }\n }\n }\n continue;\n }\n switch (ch) {\n case '\"':\n inString = true;\n stringStart = i;\n break;\n case \":\":\n if (stack.length === 1 && pendingKey !== null) {\n try {\n currentKey = JSON.parse(pendingKey);\n } catch {\n currentKey = null;\n }\n pendingKey = null;\n expectingValue = true;\n }\n break;\n case \",\":\n if (stack.length === 1) {\n expectingValue = false;\n currentKey = null;\n }\n break;\n case \"{\":\n if (inOperations && stack.length === 2) elementStart = i;\n stack.push(\"{\");\n break;\n case \"[\":\n if (\n stack.length === 1 &&\n expectingValue &&\n currentKey === \"operations\"\n ) {\n inOperations = true;\n }\n stack.push(\"[\");\n break;\n case \"}\":\n case \"]\":\n stack.pop();\n if (\n ch === \"}\" &&\n inOperations &&\n stack.length === 2 &&\n elementStart >= 0\n ) {\n result.operations.push(\n parseObject(text.slice(elementStart, i + 1)),\n );\n elementStart = -1;\n }\n if (ch === \"]\" && inOperations && stack.length === 1) {\n inOperations = false;\n expectingValue = false;\n }\n break;\n }\n }\n this.inString = inString;\n this.escaped = escaped;\n this.stringStart = stringStart;\n this.pendingKey = pendingKey;\n this.currentKey = currentKey;\n this.expectingValue = expectingValue;\n this.inOperations = inOperations;\n this.elementStart = elementStart;\n this.scanned = text.length;\n if (elementStart >= 0) result.incompleteOperation = true;\n else delete result.incompleteOperation;\n return result;\n }\n}\n\nfunction parseObject(raw: string) {\n try {\n const value: unknown = JSON.parse(raw);\n return isRecord(value) ? value : null;\n } catch {\n return null;\n }\n}\n\n/** Feeds streamed argument deltas and reports operations not yet seen. */\nexport class RenderUIArgsStream {\n private buffer = \"\";\n private emitted = 0;\n private incomplete = false;\n private readonly scanner = new RenderUIArgsScanner();\n\n push(delta: string) {\n this.buffer += delta;\n const { target, operations, incompleteOperation } = this.scanner.scan(\n this.buffer,\n );\n const newOperations = operations.slice(this.emitted);\n this.emitted = operations.length;\n this.incomplete = incompleteOperation === true;\n return { target, newOperations };\n }\n\n /** Every argument delta received so far, concatenated. */\n get text() {\n return this.buffer;\n }\n\n /**\n * True when the text received so far ends inside an `operations[]` element.\n * Once the tool call has ended, that element was truncated.\n */\n get hasIncompleteOperation() {\n return this.incomplete;\n }\n}\n","import {\n GENERATIVE_UI_WHEN_TO_SHOW,\n generativeUIGuideFeatures,\n} from \"../a2ui-prompts\";\nimport { functionCallers } from \"./basic-functions\";\nimport {\n GENERATIVE_UI_AGENT_FUNCTION_CALLS,\n GENERATIVE_UI_RENDER_TOOL,\n} from \"./types\";\nimport type { GenerativeUIManifest } from \"./types\";\n\nexport const GENERATIVE_UI_CONTEXT_DESCRIPTION =\n \"Generative UI guide: available components, functions, targets, and how to call render_ui.\";\n\n/** Most characters of the user values of one surface in the guide. */\nconst MAX_USER_VALUES_LENGTH = 500;\n\n/** Cuts long text and marks the cut with \"...\". */\nfunction shorten(text: string) {\n return text.length > MAX_USER_VALUES_LENGTH\n ? `${text.slice(0, MAX_USER_VALUES_LENGTH)}...`\n : text;\n}\n\n/**\n * The guide that the runtime adds as a context entry to a tool-transport run:\n * the `render_ui` rules, the targets, components, functions, and surfaces of\n * the manifest. It is in shared so that the inspector shows the same text.\n */\nexport function buildGenerativeUIPrompt(manifest: GenerativeUIManifest) {\n const targets = manifest.targets\n .map((t) => {\n const place =\n t.kind === \"chat\"\n ? \"inside the chat transcript\"\n : \"a named area of the app\";\n const limit = t.components\n ? `; only ${t.components.join(\", \") || \"no components\"}`\n : \"\";\n const description = t.description ? `: ${t.description}` : \"\";\n return `- \"${t.id}\" (${place}${limit})${description}`;\n })\n .join(\"\\n\");\n const components = Object.entries(manifest.components)\n .map(([name, c]) => {\n const lines = [\n `- **${name}**${c.description ? `: ${c.description}` : \"\"}`,\n ` props: ${JSON.stringify(c.props)}`,\n ];\n if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);\n if (c.slots)\n lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);\n return lines.join(\"\\n\");\n })\n .join(\"\\n\");\n const functions = Object.entries(manifest.functions)\n .map(([name, f]) => {\n // A built-in function carries its short signature in the description\n // of its parameters; an app function has a JSON Schema.\n const signature = f.parameters.description;\n const args =\n typeof signature === \"string\" &&\n signature.startsWith(\"{\") &&\n Object.keys(f.parameters).length === 2\n ? signature\n : JSON.stringify(f.parameters);\n // A function is for the UI unless marked: the agent calls only what\n // the mark allows.\n const callers = functionCallers(f);\n const who =\n callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS\n ? callers.renderer\n ? \" (UI or agent)\"\n : \" (agent only)\"\n : \"\";\n return `- **${name}**${who}${f.description ? `: ${f.description}` : \"\"}\\n args: ${args}`;\n })\n .join(\"\\n\");\n const surfaces = Object.entries(manifest.surfaces)\n .map(([id, s]) => {\n const state =\n s.status === \"deleted\"\n ? \", deleted: never use this id again\"\n : s.status === \"failed\"\n ? \", not created: send a corrected createSurface with this id\"\n : \"\";\n const lines = [`- \"${id}\" (target \"${s.target}\"${state})`];\n if (s.dataModel) {\n lines.push(` user values: ${shorten(JSON.stringify(s.dataModel))}`);\n }\n for (const rejection of s.rejected ?? []) {\n lines.push(` rejected: ${rejection}`);\n }\n return lines.join(\"\\n\");\n })\n .join(\"\\n\");\n const hasSurfaceNotes = Object.values(manifest.surfaces).some(\n (s) => s.dataModel !== undefined || (s.rejected?.length ?? 0) > 0,\n );\n const surfaceNotes = hasSurfaceNotes\n ? \"User values are what the user entered, by path. Your writes to those paths are ignored. Rejected operations were dropped: send them again with the problem fixed.\\n\"\n : \"\";\n\n // Rules for functions, events, and templates go only to runs whose manifest\n // has them, so the guide stays small.\n const {\n functions: hasFunctions,\n events,\n templates,\n checks,\n } = generativeUIGuideFeatures(manifest);\n // The agent calls functions only while that path is on.\n const agentCalls = hasFunctions && GENERATIVE_UI_AGENT_FUNCTION_CALLS;\n const operations = [\n '{\"version\":\"v1.0\",\"createSurface\":{\"surfaceId\":\"<new id>\",\"dataModel\":{...},\"components\":[{\"id\":\"root\",\"component\":\"<Name>\",\"children\":[\"<child id>\"]}]}}: the first operation of a new surface. \"dataModel\" and \"components\" are optional.',\n '{\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.',\n '{\"version\":\"v1.0\",\"updateDataModel\":{\"surfaceId\":\"<id>\",\"path\":\"/some/path\",\"value\":<json>}}: set the value at \"path\". Always give \"value\". \"value\":null deletes the key at \"path\".',\n '{\"version\":\"v1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.',\n ...(agentCalls\n ? [\n '{\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}: run an app function now, with no click. It needs no surface.',\n ]\n : []),\n ];\n const eventRule = hasFunctions\n ? 'Event props take an action. {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}} runs an app function in the browser immediately, and you are not told about it. {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} sends the interaction back to you as a user message, with \"userMessage\" as its first line. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\". Only call functions listed below.'\n : 'Event props take an action: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} sends the interaction back to you as a user message, with \"userMessage\" as its first line. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\".';\n const rules = [\n 'Components are flat objects: {\"id\":\"...\",\"component\":\"<Name>\", ...props}. Every surface renders from the component with id \"root\". Reference children by id in slot props.',\n 'A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component, and \"live\":\"polite\" only on text that changes by itself.',\n 'Stream progressively: put the initial data in \"dataModel\" and the root in \"components\" of the createSurface operation, then send one updateComponents operation per child, so the UI appears while you are still writing. The root must already list the ids of its children in its slot props (for example \"children\":[\"card-1\",\"card-2\"]), even though the children come later. A component that no slot references is never shown.',\n \"Updating a component replaces all of its props, so resend every prop.\",\n 'Prop values are literals or data bindings {\"@path\":\"/data/path\"}. Never write {\"path\":\"/data/path\"} as a binding.',\n ...(events ? [eventRule] : []),\n \"To show a different view, create a new surface with a new surfaceId (for example, a checkout form after a cart summary). Update an existing surface only when the user asks to change that same view: then do not send createSurface, use its surfaceId, and pass its existing target. Never reuse an earlier chat surface for a different view, because that replaces the earlier UI and anything the user typed into it.\",\n \"Never use a surfaceId again, also after deleteSurface.\",\n 'A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Only call functions listed below. formatString interpolates ${/path} and ${fn(arg: value)} in its value.',\n '${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}.',\n \"For a computed list (chart data, template items) use series. Its description under Functions gives the rules and an example.\",\n ...(checks\n ? [\n 'Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email. A failed check shows the message under the input and disables a Button that has the same checks.',\n ]\n : []),\n ...(templates\n ? [\n 'To repeat a component for each item of a list, give a multiple slot a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}. Inside the template, paths are relative to the item (\"name\", not \"/name\"). {\"@call\":\"@index\"} gives the position of the item, from 0; {\"@call\":\"@index\",\"args\":{\"offset\":1}} counts from 1.',\n ]\n : []),\n ...(agentCalls\n ? [\n \"Give every callRendererFunction a new functionCallId. Call only a function marked (UI or agent) or (agent only); a function with no mark is for the UI only. A function marked (agent only) is only for callRendererFunction: do not bind an event to it.\",\n 'The result of a callRendererFunction comes back to you in a new turn, as a developer message: {\"version\":\"v1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Do not wait for the result in this reply, and do not guess it.',\n ]\n : []),\n ];\n\n return [\n `## Generative UI\nCall \\`${GENERATIVE_UI_RENDER_TOOL}\\` to show UI. Arguments: \\`target\\` first, then \\`operations\\` (A2UI v1.0 operations, applied in order).\n\n${GENERATIVE_UI_WHEN_TO_SHOW}\n\nEvery operation has \"version\":\"v1.0\" and exactly one of:\n${operations.map((op) => `- ${op}`).join(\"\\n\")}\n\nRules:\n${rules.map((rule, index) => `${index + 1}. ${rule}`).join(\"\\n\")}`,\n `### Targets\\n${targets || \"- none\"}`,\n `### Components\\n${components || \"- none\"}`,\n `### Functions\\n${functions || \"- none\"}`,\n `### Existing surfaces\\n${surfaceNotes}${surfaces || \"- none\"}`,\n ].join(\"\\n\\n\");\n}\n","export * from \"./types\";\nexport * from \"./utils\";\nexport * from \"./constants\";\n// Telemetry is split deliberately. `TelemetryClient` imports\n// `@segment/analytics-node`, which imports `node-fetch`, which imports the\n// Node built-ins `stream`, `http`, `https` and `zlib`. Browser bundlers\n// resolve the whole module graph before they tree-shake, so re-exporting\n// that module here made every browser build of a dependent package print\n// \"Module ... has been externalized for browser compatibility\" warnings,\n// even when the consumer never touched telemetry (#4151). Only the\n// browser-safe telemetry surface is re-exported from this entry. Server\n// code that needs the client imports it from `@copilotkit/shared/telemetry`.\n// This mirrors the license-verifier note below.\nexport { isTelemetryDisabled } from \"./telemetry/telemetry-disabled\";\nexport * from \"./telemetry/sampling\";\n// Pure string classification with no imports, so it carries no runtime edge\n// into browser builds — same reasoning as `sampling` above.\nexport * from \"./telemetry/model-host\";\nexport {\n firstNonBlankTelemetryId,\n lambdaClient,\n parseTelemetryIdFromLicense,\n parseAndWarnTelemetryId,\n} from \"./telemetry/lambda-client\";\nexport type { LambdaSendOptions } from \"./telemetry/lambda-client\";\n// Types only: erased at build time, so they add no runtime edge to\n// `telemetry-client.ts` and therefore none to @segment/analytics-node.\nexport type {\n TelemetryCapture,\n TelemetryIdentity,\n} from \"./telemetry/telemetry-client\";\nexport * from \"./debug\";\nexport * from \"./standard-schema\";\nexport * from \"./attachments\";\n\nexport { logger } from \"./logger\";\nexport {\n createRunEventFinalizer,\n finalizeRunEvents,\n type FinalizeRunOptions,\n type RunEventFinalizer,\n} from \"./finalize-events\";\nexport { stripIntelligenceRoutingFields } from \"./intelligence-routing-fields\";\n\nexport {\n TranscriptionErrorCode,\n TranscriptionErrors,\n type TranscriptionErrorResponse,\n} from \"./transcription-errors\";\n\nimport * as packageJson from \"../package.json\";\nexport const COPILOTKIT_VERSION = packageJson.version;\n\n// Re-export only types from license-verifier (types are erased at compile time,\n// so they don't pull in the Node-only `crypto` dependency into client bundles).\n// Server-side packages (e.g. @copilotkit/runtime) should import runtime functions\n// like createLicenseChecker and getLicenseWarningHeader directly from\n// @copilotkit/license-verifier.\nexport type {\n LicenseChecker,\n LicenseStatus,\n LicensePayload,\n LicenseFeatures,\n LicenseTier,\n LicenseOwner,\n} from \"@copilotkit/license-verifier\";\n\nimport type { LicensePayload } from \"@copilotkit/license-verifier\";\nimport type {\n RuntimeEntitlementResponse,\n RuntimeLicenseStatus,\n} from \"./utils/types\";\n\n// LicenseContextValue was dropped from license-verifier's public API in\n// 0.3.0, so it is defined here. The context shape is owned by this package\n// anyway via createLicenseContextValue below.\n\n/**\n * License context value exposed to child components.\n * Frontend providers create their own context using this shape.\n */\nexport interface LicenseContextValue {\n /** Effective license status after structured entitlement precedence. Null until known. */\n status: RuntimeLicenseStatus | null;\n /** The license payload if available. Always null on the client; the payload stays server-side. */\n license: LicensePayload | null;\n /** Whether a feature is licensed. Ready entitlements override legacy status behavior. */\n checkFeature: (feature: string) => boolean;\n /** Get a numeric feature limit. Zero means unlimited; null means not applicable. */\n getLimit: (feature: string) => number | null;\n}\n\n/** Read a record value without traversing its prototype chain. */\nfunction getOwnRecordValue<Value>(\n record: Readonly<Record<string, Value>>,\n key: string,\n): Value | undefined {\n return Object.prototype.hasOwnProperty.call(record, key)\n ? record[key]\n : undefined;\n}\n\n/** Legacy UI surfaces that remain available for every active entitlement. */\nfunction isLegacyUiFeature(feature: string): boolean {\n return feature === \"chat\" || feature === \"popup\" || feature === \"sidebar\";\n}\n\n/**\n * Client-safe license context factory, driven by the license authority the\n * runtime reports via /info.\n *\n * A ready managed entitlement is authoritative in both directions. A ready\n * active self-hosted entitlement is also authoritative, while an inactive\n * self-hosted response preserves the legacy signed-license fallback. Active\n * entitlements supply feature grants and limits; authoritative inactive\n * entitlements deny every feature and limit. Older runtimes that report only a\n * status retain the legacy behavior: features are enabled unless the status is\n * \"expired\" or \"invalid\", and no limits are reported. This is inlined here to\n * avoid importing the full license-verifier bundle (which depends on Node's\n * `crypto`) into browser bundles.\n */\nexport function createLicenseContextValue(\n status: RuntimeLicenseStatus | null | undefined,\n runtimeEntitlements?: RuntimeEntitlementResponse,\n): LicenseContextValue {\n const readyEntitlement =\n runtimeEntitlements?.status === \"ready\"\n ? runtimeEntitlements.entitlement\n : null;\n const hasUsableSelfHostedLegacyFallback =\n readyEntitlement &&\n !readyEntitlement.active &&\n readyEntitlement.source === \"selfHostedDeploymentLicense\" &&\n (status === \"valid\" || status === \"expiring\");\n const featureAuthority =\n readyEntitlement && !hasUsableSelfHostedLegacyFallback\n ? readyEntitlement\n : null;\n const activeEntitlement = featureAuthority?.active ? featureAuthority : null;\n const resolvedStatus = activeEntitlement\n ? \"valid\"\n : readyEntitlement?.source === \"managedOrgSubscription\" ||\n readyEntitlement?.source === \"awsMarketplaceDeploymentLicense\"\n ? \"none\"\n : featureAuthority\n ? (status ?? \"none\")\n : (status ?? null);\n const featuresEnabled =\n resolvedStatus !== \"expired\" && resolvedStatus !== \"invalid\";\n\n return {\n status: resolvedStatus,\n license: null,\n checkFeature: (feature) =>\n featureAuthority\n ? activeEntitlement\n ? feature === \"threads\" &&\n Object.prototype.hasOwnProperty.call(\n activeEntitlement.limits,\n \"threads.max_count\",\n )\n ? true\n : (getOwnRecordValue(activeEntitlement.features, feature) ??\n isLegacyUiFeature(feature))\n : false\n : featuresEnabled,\n getLimit: (feature) =>\n activeEntitlement\n ? (getOwnRecordValue(activeEntitlement.limits, feature) ?? null)\n : null,\n };\n}\n\nexport {\n A2UI_DEFAULT_GENERATION_GUIDELINES,\n A2UI_DEFAULT_DESIGN_GUIDELINES,\n ALL_GENERATIVE_UI_GUIDE_FEATURES,\n buildGenerativeUIMarkdownGuidelines,\n generativeUIGuideFeatures,\n GENERATIVE_UI_MARKDOWN_GUIDELINES,\n GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,\n GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,\n} from \"./a2ui-prompts\";\nexport type { GenerativeUIGuideFeatures } from \"./a2ui-prompts\";\nexport {\n COPILOTKIT_FORWARDED_PROPS_KEY,\n COPILOTKIT_UI_ENVELOPE_FORMAT,\n envelopeToManifest,\n readCopilotKitUIEnvelope,\n} from \"./a2ui-envelope\";\nexport type { CopilotKitUIEnvelope } from \"./a2ui-envelope\";\n\nexport type { DebugEventEnvelope } from \"./debug-event-envelope\";\n\nexport { GENERATE_SANDBOXED_UI_DESCRIPTION } from \"./open-generative-ui-prompts\";\nexport * from \"./generative-ui\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CASA,eAAsB,gBAAgB,MAAgC;;AACpE,MAAI,0BAAC,UAAU,uFAAW,YAAW;AACnC,WAAQ,MAAM,iCAAiC;AAC/C,UAAO;;AAGT,MAAI;AACF,SAAM,UAAU,UAAU,UAAU,KAAK;AACzC,UAAO;WACA,KAAK;AACZ,WAAQ,MAAM,gCAAgC,IAAI;AAClD,UAAO;;;;;;CCmBX,SAA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