@copilotkit/shared 0.0.0-0.0.0-max-changeset-10101010101010-20260109191632

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 (185) hide show
  1. package/CHANGELOG.md +1800 -0
  2. package/LICENSE +21 -0
  3. package/README.md +141 -0
  4. package/dist/chunk-2OJ5OJ2D.mjs +1 -0
  5. package/dist/chunk-2OJ5OJ2D.mjs.map +1 -0
  6. package/dist/chunk-5YXKLIUO.mjs +38 -0
  7. package/dist/chunk-5YXKLIUO.mjs.map +1 -0
  8. package/dist/chunk-64DYJ27R.mjs +201 -0
  9. package/dist/chunk-64DYJ27R.mjs.map +1 -0
  10. package/dist/chunk-6QGXWNS5.mjs +34 -0
  11. package/dist/chunk-6QGXWNS5.mjs.map +1 -0
  12. package/dist/chunk-6W2UEO2M.mjs +94 -0
  13. package/dist/chunk-6W2UEO2M.mjs.map +1 -0
  14. package/dist/chunk-BOKE4OKY.mjs +41 -0
  15. package/dist/chunk-BOKE4OKY.mjs.map +1 -0
  16. package/dist/chunk-FCCOSO5L.mjs +1 -0
  17. package/dist/chunk-FCCOSO5L.mjs.map +1 -0
  18. package/dist/chunk-GYZIHHE6.mjs +13 -0
  19. package/dist/chunk-GYZIHHE6.mjs.map +1 -0
  20. package/dist/chunk-IAFBVORQ.mjs +1 -0
  21. package/dist/chunk-IAFBVORQ.mjs.map +1 -0
  22. package/dist/chunk-MSUB6DGR.mjs +1 -0
  23. package/dist/chunk-MSUB6DGR.mjs.map +1 -0
  24. package/dist/chunk-N5EP5OD5.mjs +1 -0
  25. package/dist/chunk-N5EP5OD5.mjs.map +1 -0
  26. package/dist/chunk-NAFEBKSO.mjs +1 -0
  27. package/dist/chunk-NAFEBKSO.mjs.map +1 -0
  28. package/dist/chunk-NBLG4PC5.mjs +426 -0
  29. package/dist/chunk-NBLG4PC5.mjs.map +1 -0
  30. package/dist/chunk-P7STFMPO.mjs +1 -0
  31. package/dist/chunk-P7STFMPO.mjs.map +1 -0
  32. package/dist/chunk-PL5WNHFZ.mjs +50 -0
  33. package/dist/chunk-PL5WNHFZ.mjs.map +1 -0
  34. package/dist/chunk-UYARLQNA.mjs +1 -0
  35. package/dist/chunk-UYARLQNA.mjs.map +1 -0
  36. package/dist/chunk-WUPFNPXO.mjs +107 -0
  37. package/dist/chunk-WUPFNPXO.mjs.map +1 -0
  38. package/dist/chunk-XEMZTHQZ.mjs +67 -0
  39. package/dist/chunk-XEMZTHQZ.mjs.map +1 -0
  40. package/dist/chunk-XTHC46M2.mjs +1 -0
  41. package/dist/chunk-XTHC46M2.mjs.map +1 -0
  42. package/dist/constants/index.d.ts +6 -0
  43. package/dist/constants/index.js +40 -0
  44. package/dist/constants/index.js.map +1 -0
  45. package/dist/constants/index.mjs +13 -0
  46. package/dist/constants/index.mjs.map +1 -0
  47. package/dist/index.d.ts +25 -0
  48. package/dist/index.js +1098 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/index.mjs +124 -0
  51. package/dist/index.mjs.map +1 -0
  52. package/dist/telemetry/events.d.ts +45 -0
  53. package/dist/telemetry/events.js +19 -0
  54. package/dist/telemetry/events.js.map +1 -0
  55. package/dist/telemetry/events.mjs +1 -0
  56. package/dist/telemetry/events.mjs.map +1 -0
  57. package/dist/telemetry/index.d.ts +3 -0
  58. package/dist/telemetry/index.js +188 -0
  59. package/dist/telemetry/index.js.map +1 -0
  60. package/dist/telemetry/index.mjs +12 -0
  61. package/dist/telemetry/index.mjs.map +1 -0
  62. package/dist/telemetry/scarf-client.d.ts +7 -0
  63. package/dist/telemetry/scarf-client.js +59 -0
  64. package/dist/telemetry/scarf-client.js.map +1 -0
  65. package/dist/telemetry/scarf-client.mjs +7 -0
  66. package/dist/telemetry/scarf-client.mjs.map +1 -0
  67. package/dist/telemetry/security-check.d.ts +2 -0
  68. package/dist/telemetry/security-check.js +2 -0
  69. package/dist/telemetry/security-check.js.map +1 -0
  70. package/dist/telemetry/security-check.mjs +1 -0
  71. package/dist/telemetry/security-check.mjs.map +1 -0
  72. package/dist/telemetry/telemetry-client.d.ts +40 -0
  73. package/dist/telemetry/telemetry-client.js +186 -0
  74. package/dist/telemetry/telemetry-client.js.map +1 -0
  75. package/dist/telemetry/telemetry-client.mjs +11 -0
  76. package/dist/telemetry/telemetry-client.mjs.map +1 -0
  77. package/dist/telemetry/utils.d.ts +8 -0
  78. package/dist/telemetry/utils.js +69 -0
  79. package/dist/telemetry/utils.js.map +1 -0
  80. package/dist/telemetry/utils.mjs +9 -0
  81. package/dist/telemetry/utils.mjs.map +1 -0
  82. package/dist/types/action.d.ts +59 -0
  83. package/dist/types/action.js +19 -0
  84. package/dist/types/action.js.map +1 -0
  85. package/dist/types/action.mjs +2 -0
  86. package/dist/types/action.mjs.map +1 -0
  87. package/dist/types/copilot-cloud-config.d.ts +13 -0
  88. package/dist/types/copilot-cloud-config.js +19 -0
  89. package/dist/types/copilot-cloud-config.js.map +1 -0
  90. package/dist/types/copilot-cloud-config.mjs +2 -0
  91. package/dist/types/copilot-cloud-config.mjs.map +1 -0
  92. package/dist/types/error.d.ts +55 -0
  93. package/dist/types/error.js +19 -0
  94. package/dist/types/error.js.map +1 -0
  95. package/dist/types/error.mjs +2 -0
  96. package/dist/types/error.mjs.map +1 -0
  97. package/dist/types/index.d.ts +7 -0
  98. package/dist/types/index.js +19 -0
  99. package/dist/types/index.js.map +1 -0
  100. package/dist/types/index.mjs +8 -0
  101. package/dist/types/index.mjs.map +1 -0
  102. package/dist/types/message.d.ts +26 -0
  103. package/dist/types/message.js +19 -0
  104. package/dist/types/message.js.map +1 -0
  105. package/dist/types/message.mjs +2 -0
  106. package/dist/types/message.mjs.map +1 -0
  107. package/dist/types/openai-assistant.d.ts +53 -0
  108. package/dist/types/openai-assistant.js +19 -0
  109. package/dist/types/openai-assistant.js.map +1 -0
  110. package/dist/types/openai-assistant.mjs +2 -0
  111. package/dist/types/openai-assistant.mjs.map +1 -0
  112. package/dist/types/utility.d.ts +6 -0
  113. package/dist/types/utility.js +19 -0
  114. package/dist/types/utility.js.map +1 -0
  115. package/dist/types/utility.mjs +2 -0
  116. package/dist/types/utility.mjs.map +1 -0
  117. package/dist/utils/conditions.d.ts +26 -0
  118. package/dist/utils/conditions.js +74 -0
  119. package/dist/utils/conditions.js.map +1 -0
  120. package/dist/utils/conditions.mjs +7 -0
  121. package/dist/utils/conditions.mjs.map +1 -0
  122. package/dist/utils/console-styling.d.ts +84 -0
  123. package/dist/utils/console-styling.js +123 -0
  124. package/dist/utils/console-styling.js.map +1 -0
  125. package/dist/utils/console-styling.mjs +17 -0
  126. package/dist/utils/console-styling.mjs.map +1 -0
  127. package/dist/utils/errors.d.ts +280 -0
  128. package/dist/utils/errors.js +443 -0
  129. package/dist/utils/errors.js.map +1 -0
  130. package/dist/utils/errors.mjs +65 -0
  131. package/dist/utils/errors.mjs.map +1 -0
  132. package/dist/utils/index.d.ts +32 -0
  133. package/dist/utils/index.js +927 -0
  134. package/dist/utils/index.js.map +1 -0
  135. package/dist/utils/index.mjs +108 -0
  136. package/dist/utils/index.mjs.map +1 -0
  137. package/dist/utils/json-schema.d.ts +34 -0
  138. package/dist/utils/json-schema.js +228 -0
  139. package/dist/utils/json-schema.js.map +1 -0
  140. package/dist/utils/json-schema.mjs +13 -0
  141. package/dist/utils/json-schema.mjs.map +1 -0
  142. package/dist/utils/random-id.d.ts +6 -0
  143. package/dist/utils/random-id.js +68 -0
  144. package/dist/utils/random-id.js.map +1 -0
  145. package/dist/utils/random-id.mjs +13 -0
  146. package/dist/utils/random-id.mjs.map +1 -0
  147. package/dist/utils/requests.d.ts +10 -0
  148. package/dist/utils/requests.js +91 -0
  149. package/dist/utils/requests.js.map +1 -0
  150. package/dist/utils/requests.mjs +7 -0
  151. package/dist/utils/requests.mjs.map +1 -0
  152. package/dist/utils/types.d.ts +20 -0
  153. package/dist/utils/types.js +19 -0
  154. package/dist/utils/types.js.map +1 -0
  155. package/dist/utils/types.mjs +2 -0
  156. package/dist/utils/types.mjs.map +1 -0
  157. package/jest.config.js +5 -0
  158. package/package.json +68 -0
  159. package/src/constants/index.ts +4 -0
  160. package/src/index.ts +7 -0
  161. package/src/telemetry/events.ts +41 -0
  162. package/src/telemetry/index.ts +1 -0
  163. package/src/telemetry/scarf-client.ts +39 -0
  164. package/src/telemetry/security-check.ts +0 -0
  165. package/src/telemetry/telemetry-client.ts +142 -0
  166. package/src/telemetry/utils.ts +39 -0
  167. package/src/types/action.ts +129 -0
  168. package/src/types/copilot-cloud-config.ts +11 -0
  169. package/src/types/error.ts +70 -0
  170. package/src/types/index.ts +6 -0
  171. package/src/types/message.ts +37 -0
  172. package/src/types/openai-assistant.ts +62 -0
  173. package/src/types/utility.ts +2 -0
  174. package/src/utils/conditions.ts +98 -0
  175. package/src/utils/console-styling.ts +124 -0
  176. package/src/utils/errors.ts +525 -0
  177. package/src/utils/index.ts +49 -0
  178. package/src/utils/json-schema.test.ts +383 -0
  179. package/src/utils/json-schema.ts +258 -0
  180. package/src/utils/random-id.ts +42 -0
  181. package/src/utils/requests.ts +77 -0
  182. package/src/utils/types.ts +22 -0
  183. package/tsconfig.json +9 -0
  184. package/tsup.config.ts +11 -0
  185. package/typedoc.json +4 -0
@@ -0,0 +1,525 @@
1
+ import { GraphQLError } from "graphql";
2
+ import { COPILOTKIT_VERSION } from "../index";
3
+
4
+ export enum Severity {
5
+ CRITICAL = "critical", // Critical errors that block core functionality
6
+ WARNING = "warning", // Configuration/setup issues that need attention
7
+ INFO = "info", // General errors and network issues
8
+ }
9
+
10
+ export enum ErrorVisibility {
11
+ BANNER = "banner", // Critical errors shown as fixed banners
12
+ TOAST = "toast", // Regular errors shown as dismissible toasts
13
+ SILENT = "silent", // Errors logged but not shown to user
14
+ DEV_ONLY = "dev_only", // Errors only shown in development mode
15
+ }
16
+
17
+ export const ERROR_NAMES = {
18
+ COPILOT_ERROR: "CopilotError",
19
+ COPILOT_API_DISCOVERY_ERROR: "CopilotApiDiscoveryError",
20
+ COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR: "CopilotKitRemoteEndpointDiscoveryError",
21
+ COPILOT_KIT_AGENT_DISCOVERY_ERROR: "CopilotKitAgentDiscoveryError",
22
+ COPILOT_KIT_LOW_LEVEL_ERROR: "CopilotKitLowLevelError",
23
+ COPILOT_KIT_VERSION_MISMATCH_ERROR: "CopilotKitVersionMismatchError",
24
+ RESOLVED_COPILOT_KIT_ERROR: "ResolvedCopilotKitError",
25
+ CONFIGURATION_ERROR: "ConfigurationError",
26
+ MISSING_PUBLIC_API_KEY_ERROR: "MissingPublicApiKeyError",
27
+ UPGRADE_REQUIRED_ERROR: "UpgradeRequiredError",
28
+ } as const;
29
+
30
+ // Banner errors - critical configuration/discovery issues
31
+ export const BANNER_ERROR_NAMES = [
32
+ ERROR_NAMES.CONFIGURATION_ERROR,
33
+ ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR,
34
+ ERROR_NAMES.UPGRADE_REQUIRED_ERROR,
35
+ ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR,
36
+ ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR,
37
+ ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR,
38
+ ];
39
+
40
+ // Legacy cloud error names for backward compatibility
41
+ export const COPILOT_CLOUD_ERROR_NAMES = BANNER_ERROR_NAMES;
42
+
43
+ export enum CopilotKitErrorCode {
44
+ NETWORK_ERROR = "NETWORK_ERROR",
45
+ NOT_FOUND = "NOT_FOUND",
46
+ AGENT_NOT_FOUND = "AGENT_NOT_FOUND",
47
+ API_NOT_FOUND = "API_NOT_FOUND",
48
+ REMOTE_ENDPOINT_NOT_FOUND = "REMOTE_ENDPOINT_NOT_FOUND",
49
+ AUTHENTICATION_ERROR = "AUTHENTICATION_ERROR",
50
+ MISUSE = "MISUSE",
51
+ UNKNOWN = "UNKNOWN",
52
+ VERSION_MISMATCH = "VERSION_MISMATCH",
53
+ CONFIGURATION_ERROR = "CONFIGURATION_ERROR",
54
+ MISSING_PUBLIC_API_KEY_ERROR = "MISSING_PUBLIC_API_KEY_ERROR",
55
+ UPGRADE_REQUIRED_ERROR = "UPGRADE_REQUIRED_ERROR",
56
+ }
57
+
58
+ const BASE_URL = "https://docs.copilotkit.ai";
59
+
60
+ const getSeeMoreMarkdown = (link: string) => `See more: [${link}](${link})`;
61
+
62
+ export const ERROR_CONFIG = {
63
+ [CopilotKitErrorCode.NETWORK_ERROR]: {
64
+ statusCode: 503,
65
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,
66
+ visibility: ErrorVisibility.BANNER,
67
+ severity: Severity.CRITICAL,
68
+ },
69
+ [CopilotKitErrorCode.NOT_FOUND]: {
70
+ statusCode: 404,
71
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,
72
+ visibility: ErrorVisibility.BANNER,
73
+ severity: Severity.CRITICAL,
74
+ },
75
+ [CopilotKitErrorCode.AGENT_NOT_FOUND]: {
76
+ statusCode: 500,
77
+ troubleshootingUrl: `${BASE_URL}/coagents/troubleshooting/common-issues#i-am-getting-agent-not-found-error`,
78
+ visibility: ErrorVisibility.BANNER,
79
+ severity: Severity.CRITICAL,
80
+ },
81
+ [CopilotKitErrorCode.API_NOT_FOUND]: {
82
+ statusCode: 404,
83
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,
84
+ visibility: ErrorVisibility.BANNER,
85
+ severity: Severity.CRITICAL,
86
+ },
87
+ [CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND]: {
88
+ statusCode: 404,
89
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#i-am-getting-copilotkits-remote-endpoint-not-found-error`,
90
+ visibility: ErrorVisibility.BANNER,
91
+ severity: Severity.CRITICAL,
92
+ },
93
+ [CopilotKitErrorCode.AUTHENTICATION_ERROR]: {
94
+ statusCode: 401,
95
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#authentication-errors`,
96
+ visibility: ErrorVisibility.BANNER,
97
+ severity: Severity.CRITICAL,
98
+ },
99
+ [CopilotKitErrorCode.MISUSE]: {
100
+ statusCode: 400,
101
+ troubleshootingUrl: null,
102
+ visibility: ErrorVisibility.DEV_ONLY,
103
+ severity: Severity.WARNING,
104
+ },
105
+ [CopilotKitErrorCode.UNKNOWN]: {
106
+ statusCode: 500,
107
+ visibility: ErrorVisibility.TOAST,
108
+ severity: Severity.CRITICAL,
109
+ },
110
+ [CopilotKitErrorCode.CONFIGURATION_ERROR]: {
111
+ statusCode: 400,
112
+ troubleshootingUrl: null,
113
+ severity: Severity.WARNING,
114
+ visibility: ErrorVisibility.BANNER,
115
+ },
116
+ [CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR]: {
117
+ statusCode: 400,
118
+ troubleshootingUrl: null,
119
+ severity: Severity.CRITICAL,
120
+ visibility: ErrorVisibility.BANNER,
121
+ },
122
+ [CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR]: {
123
+ statusCode: 402,
124
+ troubleshootingUrl: null,
125
+ severity: Severity.WARNING,
126
+ visibility: ErrorVisibility.BANNER,
127
+ },
128
+ [CopilotKitErrorCode.VERSION_MISMATCH]: {
129
+ statusCode: 400,
130
+ troubleshootingUrl: null,
131
+ visibility: ErrorVisibility.DEV_ONLY,
132
+ severity: Severity.INFO,
133
+ },
134
+ };
135
+
136
+ export class CopilotKitError extends GraphQLError {
137
+ code: CopilotKitErrorCode;
138
+ statusCode: number;
139
+ severity?: Severity;
140
+ visibility: ErrorVisibility;
141
+
142
+ constructor({
143
+ message = "Unknown error occurred",
144
+ code,
145
+ severity,
146
+ visibility,
147
+ }: {
148
+ message?: string;
149
+ code: CopilotKitErrorCode;
150
+ severity?: Severity;
151
+ visibility?: ErrorVisibility;
152
+ }) {
153
+ const name = ERROR_NAMES.COPILOT_ERROR;
154
+ const config = ERROR_CONFIG[code];
155
+ const { statusCode } = config;
156
+ const resolvedVisibility = visibility ?? config.visibility ?? ErrorVisibility.TOAST;
157
+ const resolvedSeverity = severity ?? ("severity" in config ? config.severity : undefined);
158
+
159
+ super(message, {
160
+ extensions: {
161
+ name,
162
+ statusCode,
163
+ code,
164
+ visibility: resolvedVisibility,
165
+ severity: resolvedSeverity,
166
+ troubleshootingUrl: "troubleshootingUrl" in config ? config.troubleshootingUrl : null,
167
+ originalError: {
168
+ message,
169
+ stack: new Error().stack,
170
+ },
171
+ },
172
+ });
173
+
174
+ this.code = code;
175
+ this.name = name;
176
+ this.statusCode = statusCode;
177
+ this.severity = resolvedSeverity;
178
+ this.visibility = resolvedVisibility;
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Error thrown when we can identify wrong usage of our components.
184
+ * This helps us notify the developer before real errors can happen
185
+ *
186
+ * @extends CopilotKitError
187
+ */
188
+ export class CopilotKitMisuseError extends CopilotKitError {
189
+ constructor({
190
+ message,
191
+ code = CopilotKitErrorCode.MISUSE,
192
+ }: {
193
+ message: string;
194
+ code?: CopilotKitErrorCode;
195
+ }) {
196
+ const docsLink =
197
+ "troubleshootingUrl" in ERROR_CONFIG[code] && ERROR_CONFIG[code].troubleshootingUrl
198
+ ? getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl as string)
199
+ : null;
200
+ const finalMessage = docsLink ? `${message}.\n\n${docsLink}` : message;
201
+ super({ message: finalMessage, code });
202
+ this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;
203
+ }
204
+ }
205
+
206
+ const getVersionMismatchErrorMessage = ({
207
+ reactCoreVersion,
208
+ runtimeVersion,
209
+ runtimeClientGqlVersion,
210
+ }: VersionMismatchResponse) =>
211
+ `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.`;
212
+ /**
213
+ * Error thrown when CPK versions does not match
214
+ *
215
+ * @extends CopilotKitError
216
+ */
217
+ export class CopilotKitVersionMismatchError extends CopilotKitError {
218
+ constructor({
219
+ reactCoreVersion,
220
+ runtimeVersion,
221
+ runtimeClientGqlVersion,
222
+ }: VersionMismatchResponse) {
223
+ const code = CopilotKitErrorCode.VERSION_MISMATCH;
224
+ super({
225
+ message: getVersionMismatchErrorMessage({
226
+ reactCoreVersion,
227
+ runtimeVersion,
228
+ runtimeClientGqlVersion,
229
+ }),
230
+ code,
231
+ });
232
+ this.name = ERROR_NAMES.COPILOT_KIT_VERSION_MISMATCH_ERROR;
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Error thrown when the CopilotKit API endpoint cannot be discovered or accessed.
238
+ * This typically occurs when:
239
+ * - The API endpoint URL is invalid or misconfigured
240
+ * - The API service is not running at the expected location
241
+ * - There are network/firewall issues preventing access
242
+ *
243
+ * @extends CopilotKitError
244
+ */
245
+ export class CopilotKitApiDiscoveryError extends CopilotKitError {
246
+ constructor(
247
+ params: {
248
+ message?: string;
249
+ code?: CopilotKitErrorCode.API_NOT_FOUND | CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND;
250
+ url?: string;
251
+ } = {},
252
+ ) {
253
+ const url = params.url ?? "";
254
+ let operationSuffix = "";
255
+ if (url?.includes("/info")) operationSuffix = `when fetching CopilotKit info`;
256
+ else if (url.includes("/actions/execute"))
257
+ operationSuffix = `when attempting to execute actions.`;
258
+ else if (url.includes("/agents/state")) operationSuffix = `when attempting to get agent state.`;
259
+ else if (url.includes("/agents/execute"))
260
+ operationSuffix = `when attempting to execute agent(s).`;
261
+ const message =
262
+ params.message ??
263
+ (params.url
264
+ ? `Failed to find CopilotKit API endpoint at url ${params.url} ${operationSuffix}`
265
+ : `Failed to find CopilotKit API endpoint.`);
266
+ const code = params.code ?? CopilotKitErrorCode.API_NOT_FOUND;
267
+ const errorMessage = `${message}.\n\n${getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl)}`;
268
+ super({ message: errorMessage, code });
269
+ this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;
270
+ }
271
+ }
272
+
273
+ /**
274
+ * This error is used for endpoints specified in runtime's remote endpoints. If they cannot be contacted
275
+ * This typically occurs when:
276
+ * - The API endpoint URL is invalid or misconfigured
277
+ * - The API service is not running at the expected location
278
+ *
279
+ * @extends CopilotKitApiDiscoveryError
280
+ */
281
+ export class CopilotKitRemoteEndpointDiscoveryError extends CopilotKitApiDiscoveryError {
282
+ constructor(params?: { message?: string; url?: string }) {
283
+ const message =
284
+ params?.message ??
285
+ (params?.url
286
+ ? `Failed to find or contact remote endpoint at url ${params.url}`
287
+ : "Failed to find or contact remote endpoint");
288
+ const code = CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND;
289
+ super({ message, code });
290
+ this.name = ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR;
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Error thrown when a LangGraph agent cannot be found or accessed.
296
+ * This typically occurs when:
297
+ * - The specified agent name does not exist in the deployment
298
+ * - The agent configuration is invalid or missing
299
+ * - The agent service is not properly deployed or initialized
300
+ *
301
+ * @extends CopilotKitError
302
+ */
303
+ export class CopilotKitAgentDiscoveryError extends CopilotKitError {
304
+ constructor(params: { agentName?: string; availableAgents: { name: string; id: string }[] }) {
305
+ const { agentName, availableAgents } = params;
306
+ const code = CopilotKitErrorCode.AGENT_NOT_FOUND;
307
+
308
+ const seeMore = getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl);
309
+ let message;
310
+
311
+ if (availableAgents.length) {
312
+ const agentList = availableAgents.map((agent) => agent.name).join(", ");
313
+
314
+ if (agentName) {
315
+ 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}`;
316
+ } else {
317
+ 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}`;
318
+ }
319
+ } else {
320
+ message = `${agentName ? `Agent '${agentName}'` : "The requested agent"} was not found. Please set up at least one agent before proceeding. ${seeMore}`;
321
+ }
322
+
323
+ super({ message, code });
324
+ this.name = ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR;
325
+ }
326
+ }
327
+
328
+ /**
329
+ * Handles low-level networking errors that occur before a request reaches the server.
330
+ * These errors arise from issues in the underlying communication infrastructure rather than
331
+ * application-level logic or server responses. Typically used to handle "fetch failed" errors
332
+ * where no HTTP status code is available.
333
+ *
334
+ * Common scenarios include:
335
+ * - Connection failures (ECONNREFUSED) when server is down/unreachable
336
+ * - DNS resolution failures (ENOTFOUND) when domain can't be resolved
337
+ * - Timeouts (ETIMEDOUT) when request takes too long
338
+ * - Protocol/transport layer errors like SSL/TLS issues
339
+ */
340
+ export class CopilotKitLowLevelError extends CopilotKitError {
341
+ constructor({ error, url, message }: { error: Error; url: string; message?: string }) {
342
+ let code = CopilotKitErrorCode.NETWORK_ERROR;
343
+
344
+ // @ts-expect-error -- code may exist
345
+ const errorCode = error.code as string;
346
+ const errorMessage = message ?? resolveLowLevelErrorMessage({ errorCode, url });
347
+
348
+ super({ message: errorMessage, code });
349
+
350
+ this.name = ERROR_NAMES.COPILOT_KIT_LOW_LEVEL_ERROR;
351
+ }
352
+ }
353
+
354
+ /**
355
+ * Generic catch-all error handler for HTTP responses from the CopilotKit API where a status code is available.
356
+ * Used when we receive an HTTP error status and wish to handle broad range of them
357
+ *
358
+ * This differs from CopilotKitLowLevelError in that:
359
+ * - ResolvedCopilotKitError: Server was reached and returned an HTTP status
360
+ * - CopilotKitLowLevelError: Error occurred before reaching server (e.g. network failure)
361
+ *
362
+ * @param status - The HTTP status code received from the API response
363
+ * @param message - Optional error message to include
364
+ * @param code - Optional specific CopilotKitErrorCode to override default behavior
365
+ *
366
+ * Default behavior:
367
+ * - 400 Bad Request: Maps to CopilotKitApiDiscoveryError
368
+ * - All other status codes: Maps to UNKNOWN error code if no specific code provided
369
+ */
370
+ export class ResolvedCopilotKitError extends CopilotKitError {
371
+ constructor({
372
+ status,
373
+ message,
374
+ code,
375
+ isRemoteEndpoint,
376
+ url,
377
+ }: {
378
+ status: number;
379
+ message?: string;
380
+ code?: CopilotKitErrorCode;
381
+ isRemoteEndpoint?: boolean;
382
+ url?: string;
383
+ }) {
384
+ let resolvedCode = code;
385
+ if (!resolvedCode) {
386
+ switch (status) {
387
+ case 400:
388
+ throw new CopilotKitApiDiscoveryError({ message, url });
389
+ case 404:
390
+ throw isRemoteEndpoint
391
+ ? new CopilotKitRemoteEndpointDiscoveryError({ message, url })
392
+ : new CopilotKitApiDiscoveryError({ message, url });
393
+ default:
394
+ resolvedCode = CopilotKitErrorCode.UNKNOWN;
395
+ break;
396
+ }
397
+ }
398
+
399
+ super({ message, code: resolvedCode });
400
+ this.name = ERROR_NAMES.RESOLVED_COPILOT_KIT_ERROR;
401
+ }
402
+ }
403
+
404
+ export class ConfigurationError extends CopilotKitError {
405
+ constructor(message: string) {
406
+ super({ message, code: CopilotKitErrorCode.CONFIGURATION_ERROR });
407
+ this.name = ERROR_NAMES.CONFIGURATION_ERROR;
408
+ this.severity = Severity.WARNING;
409
+ }
410
+ }
411
+
412
+ export class MissingPublicApiKeyError extends ConfigurationError {
413
+ constructor(message: string) {
414
+ super(message);
415
+ this.name = ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR;
416
+ this.severity = Severity.CRITICAL;
417
+ }
418
+ }
419
+
420
+ export class UpgradeRequiredError extends ConfigurationError {
421
+ constructor(message: string) {
422
+ super(message);
423
+ this.name = ERROR_NAMES.UPGRADE_REQUIRED_ERROR;
424
+ this.severity = Severity.WARNING;
425
+ }
426
+ }
427
+
428
+ /**
429
+ * Checks if an error is already a structured CopilotKit error.
430
+ * This utility centralizes the logic for detecting structured errors across the codebase.
431
+ *
432
+ * @param error - The error to check
433
+ * @returns true if the error is already structured, false otherwise
434
+ */
435
+ export function isStructuredCopilotKitError(error: any): boolean {
436
+ return (
437
+ error instanceof CopilotKitError ||
438
+ error instanceof CopilotKitLowLevelError ||
439
+ (error?.name && error.name.includes("CopilotKit")) ||
440
+ error?.extensions?.code !== undefined // Check if it has our structured error properties
441
+ );
442
+ }
443
+
444
+ /**
445
+ * Returns the error as-is if it's already structured, otherwise converts it using the provided converter function.
446
+ * This utility centralizes the pattern of preserving structured errors while converting unstructured ones.
447
+ *
448
+ * @param error - The error to process
449
+ * @param converter - Function to convert unstructured errors to structured ones
450
+ * @returns The structured error
451
+ */
452
+ export function ensureStructuredError<T extends CopilotKitError>(
453
+ error: any,
454
+ converter: (error: any) => T,
455
+ ): T | any {
456
+ return isStructuredCopilotKitError(error) ? error : converter(error);
457
+ }
458
+
459
+ interface VersionMismatchResponse {
460
+ runtimeVersion?: string;
461
+ runtimeClientGqlVersion: string;
462
+ reactCoreVersion: string;
463
+ }
464
+
465
+ export async function getPossibleVersionMismatch({
466
+ runtimeVersion,
467
+ runtimeClientGqlVersion,
468
+ }: {
469
+ runtimeVersion?: string;
470
+ runtimeClientGqlVersion: string;
471
+ }) {
472
+ if (!runtimeVersion || runtimeVersion === "" || !runtimeClientGqlVersion) return;
473
+ if (
474
+ COPILOTKIT_VERSION !== runtimeVersion ||
475
+ COPILOTKIT_VERSION !== runtimeClientGqlVersion ||
476
+ runtimeVersion !== runtimeClientGqlVersion
477
+ ) {
478
+ return {
479
+ runtimeVersion,
480
+ runtimeClientGqlVersion,
481
+ reactCoreVersion: COPILOTKIT_VERSION,
482
+ message: getVersionMismatchErrorMessage({
483
+ runtimeVersion,
484
+ runtimeClientGqlVersion,
485
+ reactCoreVersion: COPILOTKIT_VERSION,
486
+ }),
487
+ };
488
+ }
489
+
490
+ return;
491
+ }
492
+
493
+ const resolveLowLevelErrorMessage = ({ errorCode, url }: { errorCode?: string; url: string }) => {
494
+ const troubleshootingLink = ERROR_CONFIG[CopilotKitErrorCode.NETWORK_ERROR].troubleshootingUrl;
495
+ const genericMessage = (description = `Failed to fetch from url ${url}.`) => `${description}.
496
+
497
+ Possible reasons:
498
+ - -The server may have an error preventing it from returning a response (Check the server logs for more info).
499
+ - -The server might be down or unreachable
500
+ - -There might be a network issue (e.g., DNS failure, connection timeout)
501
+ - -The URL might be incorrect
502
+ - -The server is not running on the specified port
503
+
504
+ ${getSeeMoreMarkdown(troubleshootingLink)}`;
505
+
506
+ if (url.includes("/info"))
507
+ return genericMessage(`Failed to fetch CopilotKit agents/action information from url ${url}.`);
508
+ if (url.includes("/actions/execute"))
509
+ return genericMessage(`Fetch call to ${url} to execute actions failed.`);
510
+ if (url.includes("/agents/state"))
511
+ return genericMessage(`Fetch call to ${url} to get agent state failed.`);
512
+ if (url.includes("/agents/execute"))
513
+ return genericMessage(`Fetch call to ${url} to execute agent(s) failed.`);
514
+
515
+ switch (errorCode) {
516
+ case "ECONNREFUSED":
517
+ return `Connection to ${url} was refused. Ensure the server is running and accessible.\n\n${getSeeMoreMarkdown(troubleshootingLink)}`;
518
+ case "ENOTFOUND":
519
+ 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)}`;
520
+ case "ETIMEDOUT":
521
+ return `The connection to ${url} timed out. The server might be overloaded or taking too long to respond.\n\n${getSeeMoreMarkdown(troubleshootingLink)}`;
522
+ default:
523
+ return;
524
+ }
525
+ };
@@ -0,0 +1,49 @@
1
+ export * from "./conditions";
2
+ export * from "./console-styling";
3
+ export * from "./errors";
4
+ export * from "./json-schema";
5
+ export * from "./types";
6
+ export * from "./random-id";
7
+ export * from "./requests";
8
+
9
+ /**
10
+ * Safely parses a JSON string into an object
11
+ * @param json The JSON string to parse
12
+ * @param fallback Optional fallback value to return if parsing fails. If not provided or set to "unset", returns null
13
+ * @returns The parsed JSON object, or the fallback value (or null) if parsing fails
14
+ */
15
+ export function parseJson(json: string, fallback: any = "unset") {
16
+ try {
17
+ return JSON.parse(json);
18
+ } catch (e) {
19
+ return fallback === "unset" ? null : fallback;
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Maps an array of items to a new array, skipping items that throw errors during mapping
25
+ * @param items The array to map
26
+ * @param callback The mapping function to apply to each item
27
+ * @returns A new array containing only the successfully mapped items
28
+ */
29
+ export function tryMap<TItem, TMapped>(
30
+ items: TItem[],
31
+ callback: (item: TItem, index: number, array: TItem[]) => TMapped,
32
+ ): TMapped[] {
33
+ return items.reduce<TMapped[]>((acc, item, index, array) => {
34
+ try {
35
+ acc.push(callback(item, index, array));
36
+ } catch (error) {
37
+ console.error(error);
38
+ }
39
+ return acc;
40
+ }, []);
41
+ }
42
+
43
+ /**
44
+ * Checks if the current environment is macOS
45
+ * @returns {boolean} True if running on macOS, false otherwise
46
+ */
47
+ export function isMacOS(): boolean {
48
+ return /Mac|iMac|Macintosh/i.test(navigator.userAgent);
49
+ }