@copilotkit/shared 2.0.0-rc.5 → 2.0.0-rc.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/index.cjs +0 -13
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +3 -5
  4. package/dist/index.d.cts.map +1 -1
  5. package/dist/index.d.mts +3 -5
  6. package/dist/index.d.mts.map +1 -1
  7. package/dist/index.mjs +3 -5
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/index.umd.js +22 -187
  10. package/dist/index.umd.js.map +1 -1
  11. package/dist/package.cjs +1 -1
  12. package/dist/package.mjs +1 -1
  13. package/dist/telemetry/telemetry-client.cjs +3 -3
  14. package/dist/telemetry/telemetry-client.cjs.map +1 -1
  15. package/dist/telemetry/telemetry-client.mjs +3 -3
  16. package/dist/telemetry/telemetry-client.mjs.map +1 -1
  17. package/dist/utils/errors.cjs +4 -42
  18. package/dist/utils/errors.cjs.map +1 -1
  19. package/dist/utils/errors.d.cts +16 -34
  20. package/dist/utils/errors.d.cts.map +1 -1
  21. package/dist/utils/errors.d.mts +16 -34
  22. package/dist/utils/errors.d.mts.map +1 -1
  23. package/dist/utils/errors.mjs +5 -41
  24. package/dist/utils/errors.mjs.map +1 -1
  25. package/dist/utils/index.cjs +0 -2
  26. package/dist/utils/index.cjs.map +1 -1
  27. package/dist/utils/index.d.cts +2 -4
  28. package/dist/utils/index.d.cts.map +1 -1
  29. package/dist/utils/index.d.mts +2 -4
  30. package/dist/utils/index.d.mts.map +1 -1
  31. package/dist/utils/index.mjs +2 -4
  32. package/dist/utils/index.mjs.map +1 -1
  33. package/dist/utils/random-id.cjs +13 -26
  34. package/dist/utils/random-id.cjs.map +1 -1
  35. package/dist/utils/random-id.d.cts +6 -3
  36. package/dist/utils/random-id.d.cts.map +1 -1
  37. package/dist/utils/random-id.d.mts +6 -3
  38. package/dist/utils/random-id.d.mts.map +1 -1
  39. package/dist/utils/random-id.mjs +14 -25
  40. package/dist/utils/random-id.mjs.map +1 -1
  41. package/package.json +3 -6
  42. package/src/telemetry/telemetry-client.ts +3 -3
  43. package/src/utils/__tests__/errors.test.ts +44 -0
  44. package/src/utils/__tests__/random-id.test.ts +37 -0
  45. package/src/utils/errors.ts +27 -85
  46. package/src/utils/index.ts +0 -2
  47. package/src/utils/random-id.ts +17 -37
  48. package/tsdown.config.ts +1 -10
  49. package/dist/utils/conditions.cjs +0 -32
  50. package/dist/utils/conditions.cjs.map +0 -1
  51. package/dist/utils/conditions.d.cts +0 -31
  52. package/dist/utils/conditions.d.cts.map +0 -1
  53. package/dist/utils/conditions.d.mts +0 -31
  54. package/dist/utils/conditions.d.mts.map +0 -1
  55. package/dist/utils/conditions.mjs +0 -31
  56. package/dist/utils/conditions.mjs.map +0 -1
  57. package/dist/utils/console-styling.cjs +0 -91
  58. package/dist/utils/console-styling.cjs.map +0 -1
  59. package/dist/utils/console-styling.d.cts +0 -65
  60. package/dist/utils/console-styling.d.cts.map +0 -1
  61. package/dist/utils/console-styling.d.mts +0 -65
  62. package/dist/utils/console-styling.d.mts.map +0 -1
  63. package/dist/utils/console-styling.mjs +0 -85
  64. package/dist/utils/console-styling.mjs.map +0 -1
  65. package/src/utils/__tests__/conditions.test.ts +0 -161
  66. package/src/utils/conditions.ts +0 -116
  67. package/src/utils/console-styling.ts +0 -126
@@ -1,6 +1,3 @@
1
- import { COPILOTKIT_VERSION } from "../index.mjs";
2
- import { GraphQLError } from "graphql";
3
-
4
1
  //#region src/utils/errors.ts
5
2
  let Severity = /* @__PURE__ */ function(Severity) {
6
3
  Severity["CRITICAL"] = "critical";
@@ -21,7 +18,6 @@ const ERROR_NAMES = {
21
18
  COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR: "CopilotKitRemoteEndpointDiscoveryError",
22
19
  COPILOT_KIT_AGENT_DISCOVERY_ERROR: "CopilotKitAgentDiscoveryError",
23
20
  COPILOT_KIT_LOW_LEVEL_ERROR: "CopilotKitLowLevelError",
24
- COPILOT_KIT_VERSION_MISMATCH_ERROR: "CopilotKitVersionMismatchError",
25
21
  RESOLVED_COPILOT_KIT_ERROR: "ResolvedCopilotKitError",
26
22
  CONFIGURATION_ERROR: "ConfigurationError",
27
23
  MISSING_PUBLIC_API_KEY_ERROR: "MissingPublicApiKeyError",
@@ -126,14 +122,15 @@ const ERROR_CONFIG = {
126
122
  severity: Severity.INFO
127
123
  }
128
124
  };
129
- var CopilotKitError = class extends GraphQLError {
125
+ var CopilotKitError = class extends Error {
130
126
  constructor({ message = "Unknown error occurred", code, severity, visibility }) {
131
127
  const name = ERROR_NAMES.COPILOT_ERROR;
132
128
  const config = ERROR_CONFIG[code];
133
129
  const { statusCode } = config;
134
130
  const resolvedVisibility = visibility ?? config.visibility ?? ErrorVisibility.TOAST;
135
131
  const resolvedSeverity = severity ?? ("severity" in config ? config.severity : void 0);
136
- super(message, { extensions: {
132
+ super(message);
133
+ this.extensions = {
137
134
  name,
138
135
  statusCode,
139
136
  code,
@@ -144,7 +141,7 @@ var CopilotKitError = class extends GraphQLError {
144
141
  message,
145
142
  stack: (/* @__PURE__ */ new Error()).stack
146
143
  }
147
- } });
144
+ };
148
145
  this.code = code;
149
146
  this.name = name;
150
147
  this.statusCode = statusCode;
@@ -169,26 +166,6 @@ var CopilotKitMisuseError = class extends CopilotKitError {
169
166
  this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;
170
167
  }
171
168
  };
172
- const getVersionMismatchErrorMessage = ({ reactCoreVersion, runtimeVersion, runtimeClientGqlVersion }) => `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.`;
173
- /**
174
- * Error thrown when CPK versions does not match
175
- *
176
- * @extends CopilotKitError
177
- */
178
- var CopilotKitVersionMismatchError = class extends CopilotKitError {
179
- constructor({ reactCoreVersion, runtimeVersion, runtimeClientGqlVersion }) {
180
- const code = CopilotKitErrorCode.VERSION_MISMATCH;
181
- super({
182
- message: getVersionMismatchErrorMessage({
183
- reactCoreVersion,
184
- runtimeVersion,
185
- runtimeClientGqlVersion
186
- }),
187
- code
188
- });
189
- this.name = ERROR_NAMES.COPILOT_KIT_VERSION_MISMATCH_ERROR;
190
- }
191
- };
192
169
  /**
193
170
  * Error thrown when the CopilotKit API endpoint cannot be discovered or accessed.
194
171
  * This typically occurs when:
@@ -376,19 +353,6 @@ function isStructuredCopilotKitError(error) {
376
353
  function ensureStructuredError(error, converter) {
377
354
  return isStructuredCopilotKitError(error) ? error : converter(error);
378
355
  }
379
- async function getPossibleVersionMismatch({ runtimeVersion, runtimeClientGqlVersion }) {
380
- if (!runtimeVersion || runtimeVersion === "" || !runtimeClientGqlVersion) return;
381
- if (COPILOTKIT_VERSION !== runtimeVersion || COPILOTKIT_VERSION !== runtimeClientGqlVersion || runtimeVersion !== runtimeClientGqlVersion) return {
382
- runtimeVersion,
383
- runtimeClientGqlVersion,
384
- reactCoreVersion: COPILOTKIT_VERSION,
385
- message: getVersionMismatchErrorMessage({
386
- runtimeVersion,
387
- runtimeClientGqlVersion,
388
- reactCoreVersion: COPILOTKIT_VERSION
389
- })
390
- };
391
- }
392
356
  const resolveLowLevelErrorMessage = ({ errorCode, url }) => {
393
357
  const troubleshootingLink = ERROR_CONFIG[CopilotKitErrorCode.NETWORK_ERROR].troubleshootingUrl;
394
358
  const genericMessage = (description = `Failed to fetch from url ${url}.`) => `${description}.
@@ -414,5 +378,5 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
414
378
  };
415
379
 
416
380
  //#endregion
417
- export { BANNER_ERROR_NAMES, COPILOT_CLOUD_ERROR_NAMES, ConfigurationError, CopilotKitAgentDiscoveryError, CopilotKitApiDiscoveryError, CopilotKitError, CopilotKitErrorCode, CopilotKitLowLevelError, CopilotKitMisuseError, CopilotKitRemoteEndpointDiscoveryError, CopilotKitVersionMismatchError, ERROR_CONFIG, ERROR_NAMES, ErrorVisibility, MissingPublicApiKeyError, ResolvedCopilotKitError, Severity, UpgradeRequiredError, ensureStructuredError, getPossibleVersionMismatch, isStructuredCopilotKitError };
381
+ export { BANNER_ERROR_NAMES, COPILOT_CLOUD_ERROR_NAMES, ConfigurationError, CopilotKitAgentDiscoveryError, CopilotKitApiDiscoveryError, CopilotKitError, CopilotKitErrorCode, CopilotKitLowLevelError, CopilotKitMisuseError, CopilotKitRemoteEndpointDiscoveryError, ERROR_CONFIG, ERROR_NAMES, ErrorVisibility, MissingPublicApiKeyError, ResolvedCopilotKitError, Severity, UpgradeRequiredError, ensureStructuredError, isStructuredCopilotKitError };
418
382
  //# sourceMappingURL=errors.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.mjs","names":[],"sources":["../../src/utils/errors.ts"],"sourcesContent":["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"],"mappings":";;;;AAGA,IAAY,8CAAL;AACL;AACA;AACA;;;AAGF,IAAY,4DAAL;AACL;AACA;AACA;AACA;;;AAGF,MAAa,cAAc;CACzB,eAAe;CACf,6BAA6B;CAC7B,yCACE;CACF,mCAAmC;CACnC,6BAA6B;CAC7B,oCAAoC;CACpC,4BAA4B;CAC5B,qBAAqB;CACrB,8BAA8B;CAC9B,wBAAwB;CACzB;AAGD,MAAa,qBAAqB;CAChC,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACb;AAGD,MAAa,4BAA4B;AAEzC,IAAY,oEAAL;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGF,MAAM,WAAW;AAEjB,MAAM,sBAAsB,SAAiB,cAAc,KAAK,IAAI,KAAK;AAEzE,MAAa,eAAe;EACzB,oBAAoB,gBAAgB;EACnC,YAAY;EACZ,oBAAoB,GAAG,SAAS;EAChC,YAAY,gBAAgB;EAC5B,UAAU,SAAS;EACpB;EACA,oBAAoB,YAAY;EAC/B,YAAY;EACZ,oBAAoB,GAAG,SAAS;EAChC,YAAY,gBAAgB;EAC5B,UAAU,SAAS;EACpB;EACA,oBAAoB,kBAAkB;EACrC,YAAY;EACZ,oBAAoB,GAAG,SAAS;EAChC,YAAY,gBAAgB;EAC5B,UAAU,SAAS;EACpB;EACA,oBAAoB,gBAAgB;EACnC,YAAY;EACZ,oBAAoB,GAAG,SAAS;EAChC,YAAY,gBAAgB;EAC5B,UAAU,SAAS;EACpB;EACA,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QAAO,eACL,iEAAiE,IAAI,GACtE;AACH,KAAI,IAAI,SAAS,mBAAmB,CAClC,QAAO,eAAe,iBAAiB,IAAI,6BAA6B;AAC1E,KAAI,IAAI,SAAS,gBAAgB,CAC/B,QAAO,eAAe,iBAAiB,IAAI,6BAA6B;AAC1E,KAAI,IAAI,SAAS,kBAAkB,CACjC,QAAO,eAAe,iBAAiB,IAAI,8BAA8B;AAE3E,SAAQ,WAAR;EACE,KAAK,eACH,QAAO,iBAAiB,IAAI,gEAAgE,mBAAmB,oBAAoB;EACrI,KAAK,YACH,QAAO,iBAAiB,IAAI,uEAAuE,mBAAmB,aAAa,oBAAoB,WAAW,mBAAmB;EACvL,KAAK,YACH,QAAO,qBAAqB,IAAI,+EAA+E,mBAAmB,oBAAoB;EACxJ,QACE"}
1
+ {"version":3,"file":"errors.mjs","names":[],"sources":["../../src/utils/errors.ts"],"sourcesContent":["export 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 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 interface CopilotKitErrorExtensions {\n name: string;\n statusCode: number;\n code: CopilotKitErrorCode;\n visibility: ErrorVisibility;\n severity?: Severity;\n troubleshootingUrl: string | null;\n originalError: { message: string; stack?: string };\n}\n\nexport class CopilotKitError extends Error {\n /** Structured error details, kept in the shape GraphQL errors used in 1.x. */\n extensions: CopilotKitErrorExtensions;\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\n this.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 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\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\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"],"mappings":";AAAA,IAAY,8CAAL;AACL;AACA;AACA;;;AAGF,IAAY,4DAAL;AACL;AACA;AACA;AACA;;;AAGF,MAAa,cAAc;CACzB,eAAe;CACf,6BAA6B;CAC7B,yCACE;CACF,mCAAmC;CACnC,6BAA6B;CAC7B,4BAA4B;CAC5B,qBAAqB;CACrB,8BAA8B;CAC9B,wBAAwB;CACzB;AAGD,MAAa,qBAAqB;CAChC,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACb;AAGD,MAAa,4BAA4B;AAEzC,IAAY,oEAAL;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGF,MAAM,WAAW;AAEjB,MAAM,sBAAsB,SAAiB,cAAc,KAAK,IAAI,KAAK;AAEzE,MAAa,eAAe;EACzB,oBAAoB,gBAAgB;EACnC,YAAY;EACZ,oBAAoB,GAAG,SAAS;EAChC,YAAY,gBAAgB;EAC5B,UAAU,SAAS;EACpB;EACA,oBAAoB,YAAY;EAC/B,YAAY;EACZ,oBAAoB,GAAG,SAAS;EAChC,YAAY,gBAAgB;EAC5B,U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AAmB,oBAAoB;EACrI,KAAK,YACH,QAAO,iBAAiB,IAAI,uEAAuE,mBAAmB,aAAa,oBAAoB,WAAW,mBAAmB;EACvL,KAAK,YACH,QAAO,qBAAqB,IAAI,+EAA+E,mBAAmB,oBAAoB;EACxJ,QACE"}
@@ -1,7 +1,5 @@
1
1
  const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
2
2
  const require_clipboard = require('./clipboard.cjs');
3
- const require_conditions = require('./conditions.cjs');
4
- const require_console_styling = require('./console-styling.cjs');
5
3
  const require_errors = require('./errors.cjs');
6
4
  const require_json_schema = require('./json-schema.cjs');
7
5
  const require_inspector_metadata = require('./inspector-metadata.cjs');
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["PartialJSON"],"sources":["../../src/utils/index.ts"],"sourcesContent":["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 \"./process-env\";\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,UAAU,MAAc,WAAgB,SAAS;AAC/D,KAAI;AACF,SAAO,KAAK,MAAM,KAAK;SACjB;AACN,SAAO,aAAa,UAAU,OAAO;;;AAQzC,MAAM,qBAAqBA,aAAY,MAAM,MAAM,CAACA,aAAY,MAAM;;;;;AAMtE,SAAgB,iBAAiB,MAAc;AAC7C,KAAI;EACF,MAAM,SAASA,aAAY,MAAM,MAAM,mBAAmB;AAC1D,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,SAAO,EAAE;SACH;AACN,SAAO,EAAE;;;;;;;;;;;;;AAcb,SAAgB,0BACd,QACA,OAC2B;AAC3B,SAAQ,UAAkB,KAAK,IAAI,SAAS,MAAM,QAAQ,IAAI,MAAM;;;;;;;;AAStE,SAAgB,OACd,OACA,UACW;AACX,QAAO,MAAM,QAAmB,KAAK,MAAM,OAAO,UAAU;AAC1D,MAAI;AACF,OAAI,KAAK,SAAS,MAAM,OAAO,MAAM,CAAC;WAC/B,OAAO;AACd,WAAQ,MAAM,MAAM;;AAEtB,SAAO;IACN,EAAE,CAAC;;;;;;AAOR,SAAgB,UAAmB;AACjC,QAAO,sBAAsB,KAAK,UAAU,UAAU;;;;;;;AAQxD,SAAgB,kBAAkB,KAAsC;AACtE,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,UAAQ,KACN,qDAAqD,OAAO,OAAO,iCACpE;AACD,SAAO,EAAE;SACH;AACN,UAAQ,KACN,4EACD;AACD,SAAO,EAAE"}
1
+ {"version":3,"file":"index.cjs","names":["PartialJSON"],"sources":["../../src/utils/index.ts"],"sourcesContent":["export * from \"./clipboard\";\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 \"./process-env\";\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,UAAU,MAAc,WAAgB,SAAS;AAC/D,KAAI;AACF,SAAO,KAAK,MAAM,KAAK;SACjB;AACN,SAAO,aAAa,UAAU,OAAO;;;AAQzC,MAAM,qBAAqBA,aAAY,MAAM,MAAM,CAACA,aAAY,MAAM;;;;;AAMtE,SAAgB,iBAAiB,MAAc;AAC7C,KAAI;EACF,MAAM,SAASA,aAAY,MAAM,MAAM,mBAAmB;AAC1D,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,SAAO,EAAE;SACH;AACN,SAAO,EAAE;;;;;;;;;;;;;AAcb,SAAgB,0BACd,QACA,OAC2B;AAC3B,SAAQ,UAAkB,KAAK,IAAI,SAAS,MAAM,QAAQ,IAAI,MAAM;;;;;;;;AAStE,SAAgB,OACd,OACA,UACW;AACX,QAAO,MAAM,QAAmB,KAAK,MAAM,OAAO,UAAU;AAC1D,MAAI;AACF,OAAI,KAAK,SAAS,MAAM,OAAO,MAAM,CAAC;WAC/B,OAAO;AACd,WAAQ,MAAM,MAAM;;AAEtB,SAAO;IACN,EAAE,CAAC;;;;;;AAOR,SAAgB,UAAmB;AACjC,QAAO,sBAAsB,KAAK,UAAU,UAAU;;;;;;;AAQxD,SAAgB,kBAAkB,KAAsC;AACtE,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,UAAQ,KACN,qDAAqD,OAAO,OAAO,iCACpE;AACD,SAAO,EAAE;SACH;AACN,UAAQ,KACN,4EACD;AACD,SAAO,EAAE"}
@@ -1,13 +1,11 @@
1
1
  import { copyToClipboard } from "./clipboard.cjs";
2
- import { BaseCondition, ComparisonCondition, ComparisonRule, Condition, ExistenceCondition, ExistenceRule, LogicalCondition, LogicalRule, Rule, executeConditions } from "./conditions.cjs";
3
- import { ConsoleColors, ConsoleStyles, logCopilotKitPlatformMessage, logStyled, publicApiKeyRequired, styledConsole } from "./console-styling.cjs";
4
- import { BANNER_ERROR_NAMES, COPILOT_CLOUD_ERROR_NAMES, ConfigurationError, CopilotKitAgentDiscoveryError, CopilotKitApiDiscoveryError, CopilotKitError, CopilotKitErrorCode, CopilotKitLowLevelError, CopilotKitMisuseError, CopilotKitRemoteEndpointDiscoveryError, CopilotKitVersionMismatchError, ERROR_CONFIG, ERROR_NAMES, ErrorVisibility, MissingPublicApiKeyError, ResolvedCopilotKitError, Severity, UpgradeRequiredError, ensureStructuredError, getPossibleVersionMismatch, isStructuredCopilotKitError } from "./errors.cjs";
2
+ import { BANNER_ERROR_NAMES, COPILOT_CLOUD_ERROR_NAMES, ConfigurationError, CopilotKitAgentDiscoveryError, CopilotKitApiDiscoveryError, CopilotKitError, CopilotKitErrorCode, CopilotKitErrorExtensions, CopilotKitLowLevelError, CopilotKitMisuseError, CopilotKitRemoteEndpointDiscoveryError, ERROR_CONFIG, ERROR_NAMES, ErrorVisibility, MissingPublicApiKeyError, ResolvedCopilotKitError, Severity, UpgradeRequiredError, ensureStructuredError, isStructuredCopilotKitError } from "./errors.cjs";
5
3
  import { JSONSchema, JSONSchemaArray, JSONSchemaBoolean, JSONSchemaNumber, JSONSchemaObject, JSONSchemaString, actionParametersToJsonSchema, convertJsonSchemaToZodSchema, getZodParameters, jsonSchemaToActionParameters } from "./json-schema.cjs";
6
4
  import { InspectorMetadataV1, parseInspectorMetadataV1 } from "./inspector-metadata.cjs";
7
5
  import { InspectorLearningEvidence, InspectorLearningInsight, InspectorLearningPage, InspectorLearningRequestV1, InspectorLearningSkill, InspectorLearningSnapshotV1, InspectorLearningTrajectoryEvidence, parseInspectorLearningRequestV1, parseInspectorLearningSnapshotV1, parseInspectorLearningUrl } from "./inspector-learning.cjs";
8
6
  import { InspectorVisibilityOptions, shouldEnableInspector } from "./inspector-visibility.cjs";
9
7
  import { A2UIRuntimeInfo, AgentDescription, IntelligenceRuntimeInfo, MaybePromise, NonEmptyRecord, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, RuntimeEntitlementResponse, RuntimeInfo, RuntimeLicenseStatus, RuntimeMode, SingleRouteRuntimeInfo, ThreadEndpointRuntimeInfo } from "./types.cjs";
10
- import { dataToUUID, isValidUUID, randomId, randomUUID } from "./random-id.cjs";
8
+ import { randomId, randomUUID } from "./random-id.cjs";
11
9
  import { processEnv } from "./process-env.cjs";
12
10
  import { readBody } from "./requests.cjs";
13
11
  import { RowKeyStore, commitRowKeyStore, createRowKeyStore, pruneRowKeyStore, resolveRowRenderKeys, resolveRowRenderKeysById } from "./row-render-keys.cjs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/utils/index.ts"],"mappings":";;;;;;;;;;;;;;;;;AAsBA;;;;iBAAgB,SAAA,CAAU,IAAA,UAAc,QAAA;AAkBxC;;;;AAAA,iBAAgB,gBAAA,CAAiB,IAAA;AAsBjC;;;;;;;;;AAaA;AAbA,iBAAgB,yBAAA,CACd,MAAA,UACA,KAAA,YACE,KAAA;;;;;;;iBAUY,MAAA,gBAAA,CACd,KAAA,EAAO,KAAA,IACP,QAAA,GAAW,IAAA,EAAM,KAAA,EAAO,KAAA,UAAe,KAAA,EAAO,KAAA,OAAY,OAAA,GACzD,OAAA;;;;;iBAea,OAAA,CAAA;;;;;;iBASA,iBAAA,CAAkB,GAAA,WAAc,MAAA"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/utils/index.ts"],"mappings":";;;;;;;;;;;;;;;AAoBA;;;;iBAAgB,SAAA,CAAU,IAAA,UAAc,QAAA;AAkBxC;;;;AAAA,iBAAgB,gBAAA,CAAiB,IAAA;AAsBjC;;;;;;;;;AAaA;AAbA,iBAAgB,yBAAA,CACd,MAAA,UACA,KAAA,YACE,KAAA;;;;;;;iBAUY,MAAA,gBAAA,CACd,KAAA,EAAO,KAAA,IACP,QAAA,GAAW,IAAA,EAAM,KAAA,EAAO,KAAA,UAAe,KAAA,EAAO,KAAA,OAAY,OAAA,GACzD,OAAA;;;;;iBAea,OAAA,CAAA;;;;;;iBASA,iBAAA,CAAkB,GAAA,WAAc,MAAA"}
@@ -1,13 +1,11 @@
1
1
  import { copyToClipboard } from "./clipboard.mjs";
2
- import { BaseCondition, ComparisonCondition, ComparisonRule, Condition, ExistenceCondition, ExistenceRule, LogicalCondition, LogicalRule, Rule, executeConditions } from "./conditions.mjs";
3
- import { ConsoleColors, ConsoleStyles, logCopilotKitPlatformMessage, logStyled, publicApiKeyRequired, styledConsole } from "./console-styling.mjs";
4
- import { BANNER_ERROR_NAMES, COPILOT_CLOUD_ERROR_NAMES, ConfigurationError, CopilotKitAgentDiscoveryError, CopilotKitApiDiscoveryError, CopilotKitError, CopilotKitErrorCode, CopilotKitLowLevelError, CopilotKitMisuseError, CopilotKitRemoteEndpointDiscoveryError, CopilotKitVersionMismatchError, ERROR_CONFIG, ERROR_NAMES, ErrorVisibility, MissingPublicApiKeyError, ResolvedCopilotKitError, Severity, UpgradeRequiredError, ensureStructuredError, getPossibleVersionMismatch, isStructuredCopilotKitError } from "./errors.mjs";
2
+ import { BANNER_ERROR_NAMES, COPILOT_CLOUD_ERROR_NAMES, ConfigurationError, CopilotKitAgentDiscoveryError, CopilotKitApiDiscoveryError, CopilotKitError, CopilotKitErrorCode, CopilotKitErrorExtensions, CopilotKitLowLevelError, CopilotKitMisuseError, CopilotKitRemoteEndpointDiscoveryError, ERROR_CONFIG, ERROR_NAMES, ErrorVisibility, MissingPublicApiKeyError, ResolvedCopilotKitError, Severity, UpgradeRequiredError, ensureStructuredError, isStructuredCopilotKitError } from "./errors.mjs";
5
3
  import { JSONSchema, JSONSchemaArray, JSONSchemaBoolean, JSONSchemaNumber, JSONSchemaObject, JSONSchemaString, actionParametersToJsonSchema, convertJsonSchemaToZodSchema, getZodParameters, jsonSchemaToActionParameters } from "./json-schema.mjs";
6
4
  import { InspectorMetadataV1, parseInspectorMetadataV1 } from "./inspector-metadata.mjs";
7
5
  import { InspectorLearningEvidence, InspectorLearningInsight, InspectorLearningPage, InspectorLearningRequestV1, InspectorLearningSkill, InspectorLearningSnapshotV1, InspectorLearningTrajectoryEvidence, parseInspectorLearningRequestV1, parseInspectorLearningSnapshotV1, parseInspectorLearningUrl } from "./inspector-learning.mjs";
8
6
  import { InspectorVisibilityOptions, shouldEnableInspector } from "./inspector-visibility.mjs";
9
7
  import { A2UIRuntimeInfo, AgentDescription, IntelligenceRuntimeInfo, MaybePromise, NonEmptyRecord, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, RuntimeEntitlementResponse, RuntimeInfo, RuntimeLicenseStatus, RuntimeMode, SingleRouteRuntimeInfo, ThreadEndpointRuntimeInfo } from "./types.mjs";
10
- import { dataToUUID, isValidUUID, randomId, randomUUID } from "./random-id.mjs";
8
+ import { randomId, randomUUID } from "./random-id.mjs";
11
9
  import { processEnv } from "./process-env.mjs";
12
10
  import { readBody } from "./requests.mjs";
13
11
  import { RowKeyStore, commitRowKeyStore, createRowKeyStore, pruneRowKeyStore, resolveRowRenderKeys, resolveRowRenderKeysById } from "./row-render-keys.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/utils/index.ts"],"mappings":";;;;;;;;;;;;;;;;;AAsBA;;;;iBAAgB,SAAA,CAAU,IAAA,UAAc,QAAA;AAkBxC;;;;AAAA,iBAAgB,gBAAA,CAAiB,IAAA;AAsBjC;;;;;;;;;AAaA;AAbA,iBAAgB,yBAAA,CACd,MAAA,UACA,KAAA,YACE,KAAA;;;;;;;iBAUY,MAAA,gBAAA,CACd,KAAA,EAAO,KAAA,IACP,QAAA,GAAW,IAAA,EAAM,KAAA,EAAO,KAAA,UAAe,KAAA,EAAO,KAAA,OAAY,OAAA,GACzD,OAAA;;;;;iBAea,OAAA,CAAA;;;;;;iBASA,iBAAA,CAAkB,GAAA,WAAc,MAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/utils/index.ts"],"mappings":";;;;;;;;;;;;;;;AAoBA;;;;iBAAgB,SAAA,CAAU,IAAA,UAAc,QAAA;AAkBxC;;;;AAAA,iBAAgB,gBAAA,CAAiB,IAAA;AAsBjC;;;;;;;;;AAaA;AAbA,iBAAgB,yBAAA,CACd,MAAA,UACA,KAAA,YACE,KAAA;;;;;;;iBAUY,MAAA,gBAAA,CACd,KAAA,EAAO,KAAA,IACP,QAAA,GAAW,IAAA,EAAM,KAAA,EAAO,KAAA,UAAe,KAAA,EAAO,KAAA,OAAY,OAAA,GACzD,OAAA;;;;;iBAea,OAAA,CAAA;;;;;;iBASA,iBAAA,CAAkB,GAAA,WAAc,MAAA"}
@@ -1,13 +1,11 @@
1
1
  import { copyToClipboard } from "./clipboard.mjs";
2
- import { executeConditions } from "./conditions.mjs";
3
- import { ConsoleColors, ConsoleStyles, logCopilotKitPlatformMessage, logStyled, publicApiKeyRequired, styledConsole } from "./console-styling.mjs";
4
- import { BANNER_ERROR_NAMES, COPILOT_CLOUD_ERROR_NAMES, ConfigurationError, CopilotKitAgentDiscoveryError, CopilotKitApiDiscoveryError, CopilotKitError, CopilotKitErrorCode, CopilotKitLowLevelError, CopilotKitMisuseError, CopilotKitRemoteEndpointDiscoveryError, CopilotKitVersionMismatchError, ERROR_CONFIG, ERROR_NAMES, ErrorVisibility, MissingPublicApiKeyError, ResolvedCopilotKitError, Severity, UpgradeRequiredError, ensureStructuredError, getPossibleVersionMismatch, isStructuredCopilotKitError } from "./errors.mjs";
2
+ import { BANNER_ERROR_NAMES, COPILOT_CLOUD_ERROR_NAMES, ConfigurationError, CopilotKitAgentDiscoveryError, CopilotKitApiDiscoveryError, CopilotKitError, CopilotKitErrorCode, CopilotKitLowLevelError, CopilotKitMisuseError, CopilotKitRemoteEndpointDiscoveryError, ERROR_CONFIG, ERROR_NAMES, ErrorVisibility, MissingPublicApiKeyError, ResolvedCopilotKitError, Severity, UpgradeRequiredError, ensureStructuredError, isStructuredCopilotKitError } from "./errors.mjs";
5
3
  import { actionParametersToJsonSchema, convertJsonSchemaToZodSchema, getZodParameters, jsonSchemaToActionParameters } from "./json-schema.mjs";
6
4
  import { parseInspectorMetadataV1 } from "./inspector-metadata.mjs";
7
5
  import { parseInspectorLearningRequestV1, parseInspectorLearningSnapshotV1, parseInspectorLearningUrl } from "./inspector-learning.mjs";
8
6
  import { shouldEnableInspector } from "./inspector-visibility.mjs";
9
7
  import { RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE } from "./types.mjs";
10
- import { dataToUUID, isValidUUID, randomId, randomUUID } from "./random-id.mjs";
8
+ import { randomId, randomUUID } from "./random-id.mjs";
11
9
  import { processEnv } from "./process-env.mjs";
12
10
  import { readBody } from "./requests.mjs";
13
11
  import { commitRowKeyStore, createRowKeyStore, pruneRowKeyStore, resolveRowRenderKeys, resolveRowRenderKeysById } from "./row-render-keys.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/utils/index.ts"],"sourcesContent":["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 \"./process-env\";\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,UAAU,MAAc,WAAgB,SAAS;AAC/D,KAAI;AACF,SAAO,KAAK,MAAM,KAAK;SACjB;AACN,SAAO,aAAa,UAAU,OAAO;;;AAQzC,MAAM,qBAAqB,YAAY,MAAM,MAAM,CAAC,YAAY,MAAM;;;;;AAMtE,SAAgB,iBAAiB,MAAc;AAC7C,KAAI;EACF,MAAM,SAAS,YAAY,MAAM,MAAM,mBAAmB;AAC1D,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,SAAO,EAAE;SACH;AACN,SAAO,EAAE;;;;;;;;;;;;;AAcb,SAAgB,0BACd,QACA,OAC2B;AAC3B,SAAQ,UAAkB,KAAK,IAAI,SAAS,MAAM,QAAQ,IAAI,MAAM;;;;;;;;AAStE,SAAgB,OACd,OACA,UACW;AACX,QAAO,MAAM,QAAmB,KAAK,MAAM,OAAO,UAAU;AAC1D,MAAI;AACF,OAAI,KAAK,SAAS,MAAM,OAAO,MAAM,CAAC;WAC/B,OAAO;AACd,WAAQ,MAAM,MAAM;;AAEtB,SAAO;IACN,EAAE,CAAC;;;;;;AAOR,SAAgB,UAAmB;AACjC,QAAO,sBAAsB,KAAK,UAAU,UAAU;;;;;;;AAQxD,SAAgB,kBAAkB,KAAsC;AACtE,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,UAAQ,KACN,qDAAqD,OAAO,OAAO,iCACpE;AACD,SAAO,EAAE;SACH;AACN,UAAQ,KACN,4EACD;AACD,SAAO,EAAE"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/utils/index.ts"],"sourcesContent":["export * from \"./clipboard\";\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 \"./process-env\";\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,UAAU,MAAc,WAAgB,SAAS;AAC/D,KAAI;AACF,SAAO,KAAK,MAAM,KAAK;SACjB;AACN,SAAO,aAAa,UAAU,OAAO;;;AAQzC,MAAM,qBAAqB,YAAY,MAAM,MAAM,CAAC,YAAY,MAAM;;;;;AAMtE,SAAgB,iBAAiB,MAAc;AAC7C,KAAI;EACF,MAAM,SAAS,YAAY,MAAM,MAAM,mBAAmB;AAC1D,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,SAAO,EAAE;SACH;AACN,SAAO,EAAE;;;;;;;;;;;;;AAcb,SAAgB,0BACd,QACA,OAC2B;AAC3B,SAAQ,UAAkB,KAAK,IAAI,SAAS,MAAM,QAAQ,IAAI,MAAM;;;;;;;;AAStE,SAAgB,OACd,OACA,UACW;AACX,QAAO,MAAM,QAAmB,KAAK,MAAM,OAAO,UAAU;AAC1D,MAAI;AACF,OAAI,KAAK,SAAS,MAAM,OAAO,MAAM,CAAC;WAC/B,OAAO;AACd,WAAQ,MAAM,MAAM;;AAEtB,SAAO;IACN,EAAE,CAAC;;;;;;AAOR,SAAgB,UAAmB;AACjC,QAAO,sBAAsB,KAAK,UAAU,UAAU;;;;;;;AAQxD,SAAgB,kBAAkB,KAAsC;AACtE,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,MAAI,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,OAAO,CAChE,QAAO;AAET,UAAQ,KACN,qDAAqD,OAAO,OAAO,iCACpE;AACD,SAAO,EAAE;SACH;AACN,UAAQ,KACN,4EACD;AACD,SAAO,EAAE"}
@@ -1,38 +1,25 @@
1
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
2
- let uuid = require("uuid");
3
1
 
4
2
  //#region src/utils/random-id.ts
5
3
  function randomId() {
6
- return "ck-" + (0, uuid.v4)();
7
- }
8
- function randomUUID() {
9
- return (0, uuid.v4)();
4
+ return "ck-" + randomUUID();
10
5
  }
11
6
  /**
12
- * Recursively converts an object to a serializable form by converting functions to their string representation.
7
+ * Returns an RFC 4122 version 4 UUID. Uses `crypto.randomUUID()` when it
8
+ * exists, and builds the UUID from `crypto.getRandomValues()` when it does not
9
+ * (React Native's Hermes has no `randomUUID`).
13
10
  */
14
- function toSerializable(value) {
15
- if (typeof value === "function") return value.toString();
16
- if (Array.isArray(value)) return value.map(toSerializable);
17
- if (value !== null && typeof value === "object") {
18
- const result = {};
19
- for (const key of Object.keys(value)) result[key] = toSerializable(value[key]);
20
- return result;
21
- }
22
- return value;
23
- }
24
- function dataToUUID(input, namespace) {
25
- const BASE_NAMESPACE = "e4b01160-ff74-4c6e-9b27-d53cd930fe8e";
26
- const boundNamespace = namespace ? (0, uuid.v5)(namespace, BASE_NAMESPACE) : BASE_NAMESPACE;
27
- return (0, uuid.v5)(typeof input === "string" ? input : JSON.stringify(toSerializable(input)), boundNamespace);
28
- }
29
- function isValidUUID(uuid$1) {
30
- return (0, uuid.validate)(uuid$1);
11
+ function randomUUID() {
12
+ const crypto = globalThis.crypto;
13
+ if (typeof crypto?.randomUUID === "function") return crypto.randomUUID();
14
+ if (typeof crypto?.getRandomValues !== "function") throw new Error("crypto.getRandomValues() is not available. In React Native, install a polyfill such as react-native-get-random-values.");
15
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
16
+ bytes[6] = bytes[6] & 15 | 64;
17
+ bytes[8] = bytes[8] & 63 | 128;
18
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
19
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
31
20
  }
32
21
 
33
22
  //#endregion
34
- exports.dataToUUID = dataToUUID;
35
- exports.isValidUUID = isValidUUID;
36
23
  exports.randomId = randomId;
37
24
  exports.randomUUID = randomUUID;
38
25
  //# sourceMappingURL=random-id.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"random-id.cjs","names":["uuid"],"sources":["../../src/utils/random-id.ts"],"sourcesContent":["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"],"mappings":";;;;AAEA,SAAgB,WAAW;AACzB,QAAO,sBAAgB;;AAGzB,SAAgB,aAAa;AAC3B,sBAAe;;;;;AAMjB,SAAS,eAAe,OAAyB;AAC/C,KAAI,OAAO,UAAU,WACnB,QAAO,MAAM,UAAU;AAEzB,KAAI,MAAM,QAAQ,MAAM,CACtB,QAAO,MAAM,IAAI,eAAe;AAElC,KAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;EAC/C,MAAM,SAAkC,EAAE;AAC1C,OAAK,MAAM,OAAO,OAAO,KAAK,MAAM,CAClC,QAAO,OAAO,eAAgB,MAAkC,KAAK;AAEvE,SAAO;;AAET,QAAO;;AAGT,SAAgB,WAAW,OAAwB,WAA4B;CAC7E,MAAM,iBAAiB;CAEvB,MAAM,iBAAiB,yBACZ,WAAW,eAAe,GACjC;AAIJ,qBADE,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,eAAe,MAAM,CAAC,EAChD,eAAe;;AAG5C,SAAgB,YAAY,QAAc;AACxC,2BAAgBA,OAAK"}
1
+ {"version":3,"file":"random-id.cjs","names":[],"sources":["../../src/utils/random-id.ts"],"sourcesContent":["export function randomId() {\n return \"ck-\" + randomUUID();\n}\n\n/**\n * Returns an RFC 4122 version 4 UUID. Uses `crypto.randomUUID()` when it\n * exists, and builds the UUID from `crypto.getRandomValues()` when it does not\n * (React Native's Hermes has no `randomUUID`).\n */\nexport function randomUUID(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n if (typeof crypto?.getRandomValues !== \"function\") {\n throw new Error(\n \"crypto.getRandomValues() is not available. In React Native, install a polyfill such as react-native-get-random-values.\",\n );\n }\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\"));\n return `${hex.slice(0, 4).join(\"\")}-${hex.slice(4, 6).join(\"\")}-${hex.slice(6, 8).join(\"\")}-${hex.slice(8, 10).join(\"\")}-${hex.slice(10).join(\"\")}`;\n}\n"],"mappings":";;AAAA,SAAgB,WAAW;AACzB,QAAO,QAAQ,YAAY;;;;;;;AAQ7B,SAAgB,aAAqB;CACnC,MAAM,SAAS,WAAW;AAC1B,KAAI,OAAO,QAAQ,eAAe,WAChC,QAAO,OAAO,YAAY;AAE5B,KAAI,OAAO,QAAQ,oBAAoB,WACrC,OAAM,IAAI,MACR,yHACD;CAEH,MAAM,QAAQ,OAAO,gBAAgB,IAAI,WAAW,GAAG,CAAC;AACxD,OAAM,KAAM,MAAM,KAAM,KAAQ;AAChC,OAAM,KAAM,MAAM,KAAM,KAAQ;CAChC,MAAM,MAAM,MAAM,KAAK,QAAQ,SAAS,KAAK,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC;AAC3E,QAAO,GAAG,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,CAAC,KAAK,GAAG"}
@@ -1,8 +1,11 @@
1
1
  //#region src/utils/random-id.d.ts
2
2
  declare function randomId(): string;
3
+ /**
4
+ * Returns an RFC 4122 version 4 UUID. Uses `crypto.randomUUID()` when it
5
+ * exists, and builds the UUID from `crypto.getRandomValues()` when it does not
6
+ * (React Native's Hermes has no `randomUUID`).
7
+ */
3
8
  declare function randomUUID(): string;
4
- declare function dataToUUID(input: string | object, namespace?: string): string;
5
- declare function isValidUUID(uuid: string): boolean;
6
9
  //#endregion
7
- export { dataToUUID, isValidUUID, randomId, randomUUID };
10
+ export { randomId, randomUUID };
8
11
  //# sourceMappingURL=random-id.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"random-id.d.cts","names":[],"sources":["../../src/utils/random-id.ts"],"mappings":";iBAEgB,QAAA,CAAA;AAAA,iBAIA,UAAA,CAAA;AAAA,iBAwBA,UAAA,CAAW,KAAA,mBAAwB,SAAA;AAAA,iBAYnC,WAAA,CAAY,IAAA"}
1
+ {"version":3,"file":"random-id.d.cts","names":[],"sources":["../../src/utils/random-id.ts"],"mappings":";iBAAgB,QAAA,CAAA;AAAhB;;;;;AAAA,iBASgB,UAAA,CAAA"}
@@ -1,8 +1,11 @@
1
1
  //#region src/utils/random-id.d.ts
2
2
  declare function randomId(): string;
3
+ /**
4
+ * Returns an RFC 4122 version 4 UUID. Uses `crypto.randomUUID()` when it
5
+ * exists, and builds the UUID from `crypto.getRandomValues()` when it does not
6
+ * (React Native's Hermes has no `randomUUID`).
7
+ */
3
8
  declare function randomUUID(): string;
4
- declare function dataToUUID(input: string | object, namespace?: string): string;
5
- declare function isValidUUID(uuid: string): boolean;
6
9
  //#endregion
7
- export { dataToUUID, isValidUUID, randomId, randomUUID };
10
+ export { randomId, randomUUID };
8
11
  //# sourceMappingURL=random-id.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"random-id.d.mts","names":[],"sources":["../../src/utils/random-id.ts"],"mappings":";iBAEgB,QAAA,CAAA;AAAA,iBAIA,UAAA,CAAA;AAAA,iBAwBA,UAAA,CAAW,KAAA,mBAAwB,SAAA;AAAA,iBAYnC,WAAA,CAAY,IAAA"}
1
+ {"version":3,"file":"random-id.d.mts","names":[],"sources":["../../src/utils/random-id.ts"],"mappings":";iBAAgB,QAAA,CAAA;AAAhB;;;;;AAAA,iBASgB,UAAA,CAAA"}
@@ -1,34 +1,23 @@
1
- import { v4, v5, validate } from "uuid";
2
-
3
1
  //#region src/utils/random-id.ts
4
2
  function randomId() {
5
- return "ck-" + v4();
6
- }
7
- function randomUUID() {
8
- return v4();
3
+ return "ck-" + randomUUID();
9
4
  }
10
5
  /**
11
- * Recursively converts an object to a serializable form by converting functions to their string representation.
6
+ * Returns an RFC 4122 version 4 UUID. Uses `crypto.randomUUID()` when it
7
+ * exists, and builds the UUID from `crypto.getRandomValues()` when it does not
8
+ * (React Native's Hermes has no `randomUUID`).
12
9
  */
13
- function toSerializable(value) {
14
- if (typeof value === "function") return value.toString();
15
- if (Array.isArray(value)) return value.map(toSerializable);
16
- if (value !== null && typeof value === "object") {
17
- const result = {};
18
- for (const key of Object.keys(value)) result[key] = toSerializable(value[key]);
19
- return result;
20
- }
21
- return value;
22
- }
23
- function dataToUUID(input, namespace) {
24
- const BASE_NAMESPACE = "e4b01160-ff74-4c6e-9b27-d53cd930fe8e";
25
- const boundNamespace = namespace ? v5(namespace, BASE_NAMESPACE) : BASE_NAMESPACE;
26
- return v5(typeof input === "string" ? input : JSON.stringify(toSerializable(input)), boundNamespace);
27
- }
28
- function isValidUUID(uuid) {
29
- return validate(uuid);
10
+ function randomUUID() {
11
+ const crypto = globalThis.crypto;
12
+ if (typeof crypto?.randomUUID === "function") return crypto.randomUUID();
13
+ if (typeof crypto?.getRandomValues !== "function") throw new Error("crypto.getRandomValues() is not available. In React Native, install a polyfill such as react-native-get-random-values.");
14
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
15
+ bytes[6] = bytes[6] & 15 | 64;
16
+ bytes[8] = bytes[8] & 63 | 128;
17
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
18
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
30
19
  }
31
20
 
32
21
  //#endregion
33
- export { dataToUUID, isValidUUID, randomId, randomUUID };
22
+ export { randomId, randomUUID };
34
23
  //# sourceMappingURL=random-id.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"random-id.mjs","names":["uuidv4","uuidv5"],"sources":["../../src/utils/random-id.ts"],"sourcesContent":["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"],"mappings":";;;AAEA,SAAgB,WAAW;AACzB,QAAO,QAAQA,IAAQ;;AAGzB,SAAgB,aAAa;AAC3B,QAAOA,IAAQ;;;;;AAMjB,SAAS,eAAe,OAAyB;AAC/C,KAAI,OAAO,UAAU,WACnB,QAAO,MAAM,UAAU;AAEzB,KAAI,MAAM,QAAQ,MAAM,CACtB,QAAO,MAAM,IAAI,eAAe;AAElC,KAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;EAC/C,MAAM,SAAkC,EAAE;AAC1C,OAAK,MAAM,OAAO,OAAO,KAAK,MAAM,CAClC,QAAO,OAAO,eAAgB,MAAkC,KAAK;AAEvE,SAAO;;AAET,QAAO;;AAGT,SAAgB,WAAW,OAAwB,WAA4B;CAC7E,MAAM,iBAAiB;CAEvB,MAAM,iBAAiB,YACnBC,GAAO,WAAW,eAAe,GACjC;AAIJ,QAAOA,GADL,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,eAAe,MAAM,CAAC,EAChD,eAAe;;AAG5C,SAAgB,YAAY,MAAc;AACxC,QAAO,SAAS,KAAK"}
1
+ {"version":3,"file":"random-id.mjs","names":[],"sources":["../../src/utils/random-id.ts"],"sourcesContent":["export function randomId() {\n return \"ck-\" + randomUUID();\n}\n\n/**\n * Returns an RFC 4122 version 4 UUID. Uses `crypto.randomUUID()` when it\n * exists, and builds the UUID from `crypto.getRandomValues()` when it does not\n * (React Native's Hermes has no `randomUUID`).\n */\nexport function randomUUID(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n if (typeof crypto?.getRandomValues !== \"function\") {\n throw new Error(\n \"crypto.getRandomValues() is not available. In React Native, install a polyfill such as react-native-get-random-values.\",\n );\n }\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\"));\n return `${hex.slice(0, 4).join(\"\")}-${hex.slice(4, 6).join(\"\")}-${hex.slice(6, 8).join(\"\")}-${hex.slice(8, 10).join(\"\")}-${hex.slice(10).join(\"\")}`;\n}\n"],"mappings":";AAAA,SAAgB,WAAW;AACzB,QAAO,QAAQ,YAAY;;;;;;;AAQ7B,SAAgB,aAAqB;CACnC,MAAM,SAAS,WAAW;AAC1B,KAAI,OAAO,QAAQ,eAAe,WAChC,QAAO,OAAO,YAAY;AAE5B,KAAI,OAAO,QAAQ,oBAAoB,WACrC,OAAM,IAAI,MACR,yHACD;CAEH,MAAM,QAAQ,OAAO,gBAAgB,IAAI,WAAW,GAAG,CAAC;AACxD,OAAM,KAAM,MAAM,KAAM,KAAQ;AAChC,OAAM,KAAM,MAAM,KAAM,KAAQ;CAChC,MAAM,MAAM,MAAM,KAAK,QAAQ,SAAS,KAAK,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC;AAC3E,QAAO,GAAG,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC,KAAK,GAAG,CAAC,GAAG,IAAI,MAAM,GAAG,CAAC,KAAK,GAAG"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copilotkit/shared",
3
- "version": "2.0.0-rc.5",
3
+ "version": "2.0.0-rc.6",
4
4
  "private": false,
5
5
  "keywords": [
6
6
  "ai",
@@ -62,17 +62,13 @@
62
62
  "@segment/analytics-node": "^2.1.2",
63
63
  "@standard-schema/spec": "^1.0.0",
64
64
  "clarinet": "^0.12.4",
65
- "graphql": "^16.8.1",
66
65
  "partial-json": "^0.1.7",
67
66
  "rxjs": "7.8.1",
68
- "uuid": "^11.1.0",
69
- "zod": "^3.23.3",
70
- "zod-to-json-schema": "^3.23.5"
67
+ "zod": "^3.23.3"
71
68
  },
72
69
  "devDependencies": {
73
70
  "@ag-ui/core": "1.0.2",
74
71
  "@types/clarinet": "^0.12.3",
75
- "@types/uuid": "^10.0.0",
76
72
  "@valibot/to-json-schema": "^1.5.0",
77
73
  "arktype": "^2.1.29",
78
74
  "eslint": "^8.56.0",
@@ -80,6 +76,7 @@
80
76
  "typescript": "^5.2.3",
81
77
  "valibot": "^1.2.0",
82
78
  "vitest": "^3.2.4",
79
+ "zod-to-json-schema": "^3.23.5",
83
80
  "tsconfig": "1.4.12"
84
81
  },
85
82
  "peerDependencies": {
@@ -1,7 +1,7 @@
1
1
  import { Analytics } from "@segment/analytics-node";
2
2
  import type { AnalyticsEvents } from "./events";
3
3
  import { flattenObject } from "./utils";
4
- import { v4 as uuidv4 } from "uuid";
4
+ import { randomUUID } from "../utils/random-id";
5
5
  import {
6
6
  firstNonBlankTelemetryId,
7
7
  lambdaClient,
@@ -62,7 +62,7 @@ export class TelemetryClient {
62
62
  // Identified events (those whose license token yielded a telemetry_id)
63
63
  // bypass the gate on both wires.
64
64
  private segmentSampleRate: number = 0.05;
65
- private anonymousId = `anon_${uuidv4()}`;
65
+ private anonymousId = `anon_${randomUUID()}`;
66
66
 
67
67
  constructor({
68
68
  packageName,
@@ -165,7 +165,7 @@ export class TelemetryClient {
165
165
  const eventMeta = {
166
166
  telemetry_emitter: TELEMETRY_EMITTER_V1,
167
167
  telemetry_surface: TELEMETRY_SURFACE_V1,
168
- telemetry_event_id: uuidv4(),
168
+ telemetry_event_id: randomUUID(),
169
169
  };
170
170
 
171
171
  const flattenedProperties = flattenObject(properties);