@copilotkit/shared 1.51.4-next.7 → 1.51.4

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 (91) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +18 -12
  3. package/dist/{chunk-64DYJ27R.mjs → chunk-3DK3UMRW.mjs} +22 -6
  4. package/dist/chunk-3DK3UMRW.mjs.map +1 -0
  5. package/dist/{chunk-DT2YLCPE.mjs → chunk-6BE7PM2Q.mjs} +7 -4
  6. package/dist/chunk-6BE7PM2Q.mjs.map +1 -0
  7. package/dist/{chunk-75UMJ5TV.mjs → chunk-BVVLGLFE.mjs} +14 -5
  8. package/dist/chunk-BVVLGLFE.mjs.map +1 -0
  9. package/dist/{chunk-BOKE4OKY.mjs → chunk-GS5BLXSZ.mjs} +1 -1
  10. package/dist/{chunk-BOKE4OKY.mjs.map → chunk-GS5BLXSZ.mjs.map} +1 -1
  11. package/dist/{chunk-QZG33TOC.mjs → chunk-HFJ7Q6KR.mjs} +2 -2
  12. package/dist/chunk-HFJ7Q6KR.mjs.map +1 -0
  13. package/dist/{chunk-6W2UEO2M.mjs → chunk-M2RJI5BZ.mjs} +1 -1
  14. package/dist/{chunk-6W2UEO2M.mjs.map → chunk-M2RJI5BZ.mjs.map} +1 -1
  15. package/dist/{chunk-PL5WNHFZ.mjs → chunk-V7BSERGI.mjs} +19 -7
  16. package/dist/chunk-V7BSERGI.mjs.map +1 -0
  17. package/dist/{chunk-XEMZTHQZ.mjs → chunk-WAZHII6M.mjs} +1 -1
  18. package/dist/chunk-WAZHII6M.mjs.map +1 -0
  19. package/dist/{chunk-GYZIHHE6.mjs → chunk-ZIC6V6S5.mjs} +1 -1
  20. package/dist/{chunk-GYZIHHE6.mjs.map → chunk-ZIC6V6S5.mjs.map} +1 -1
  21. package/dist/{chunk-6QGXWNS5.mjs → chunk-ZUE2VR7D.mjs} +7 -3
  22. package/dist/chunk-ZUE2VR7D.mjs.map +1 -0
  23. package/dist/constants/index.js.map +1 -1
  24. package/dist/constants/index.mjs +1 -1
  25. package/dist/index.js +56 -16
  26. package/dist/index.js.map +1 -1
  27. package/dist/index.mjs +10 -10
  28. package/dist/index.umd.js +1 -1
  29. package/dist/index.umd.js.map +1 -1
  30. package/dist/telemetry/events.js.map +1 -1
  31. package/dist/telemetry/index.js +5 -2
  32. package/dist/telemetry/index.js.map +1 -1
  33. package/dist/telemetry/index.mjs +3 -3
  34. package/dist/telemetry/scarf-client.js +1 -1
  35. package/dist/telemetry/scarf-client.js.map +1 -1
  36. package/dist/telemetry/scarf-client.mjs +1 -1
  37. package/dist/telemetry/telemetry-client.js +5 -2
  38. package/dist/telemetry/telemetry-client.js.map +1 -1
  39. package/dist/telemetry/telemetry-client.mjs +3 -3
  40. package/dist/telemetry/utils.js +6 -2
  41. package/dist/telemetry/utils.js.map +1 -1
  42. package/dist/telemetry/utils.mjs +1 -1
  43. package/dist/types/action.js.map +1 -1
  44. package/dist/types/error.js.map +1 -1
  45. package/dist/types/openai-assistant.js.map +1 -1
  46. package/dist/utils/conditions.js +18 -6
  47. package/dist/utils/conditions.js.map +1 -1
  48. package/dist/utils/conditions.mjs +1 -1
  49. package/dist/utils/console-styling.js.map +1 -1
  50. package/dist/utils/console-styling.mjs +1 -1
  51. package/dist/utils/errors.d.ts +1 -1
  52. package/dist/utils/errors.js +13 -4
  53. package/dist/utils/errors.js.map +1 -1
  54. package/dist/utils/errors.mjs +10 -10
  55. package/dist/utils/index.js +52 -15
  56. package/dist/utils/index.js.map +1 -1
  57. package/dist/utils/index.mjs +10 -10
  58. package/dist/utils/json-schema.js +21 -5
  59. package/dist/utils/json-schema.js.map +1 -1
  60. package/dist/utils/json-schema.mjs +1 -1
  61. package/dist/utils/random-id.js.map +1 -1
  62. package/dist/utils/random-id.mjs +1 -1
  63. package/dist/utils/requests.js.map +1 -1
  64. package/dist/utils/requests.mjs +1 -1
  65. package/dist/utils/types.d.ts +1 -1
  66. package/dist/utils/types.js.map +1 -1
  67. package/package.json +3 -4
  68. package/src/constants/index.ts +2 -1
  69. package/src/telemetry/events.ts +4 -1
  70. package/src/telemetry/telemetry-client.ts +17 -6
  71. package/src/telemetry/utils.ts +6 -2
  72. package/src/types/action.ts +9 -5
  73. package/src/types/error.ts +11 -2
  74. package/src/types/openai-assistant.ts +6 -2
  75. package/src/utils/conditions.ts +27 -9
  76. package/src/utils/console-styling.ts +4 -2
  77. package/src/utils/errors.ts +49 -16
  78. package/src/utils/json-schema.test.ts +29 -5
  79. package/src/utils/json-schema.ts +34 -9
  80. package/src/utils/random-id.ts +5 -2
  81. package/src/utils/requests.ts +3 -1
  82. package/src/utils/types.ts +5 -1
  83. package/tsconfig.json +1 -1
  84. package/tsup.config.ts +5 -1
  85. package/dist/chunk-64DYJ27R.mjs.map +0 -1
  86. package/dist/chunk-6QGXWNS5.mjs.map +0 -1
  87. package/dist/chunk-75UMJ5TV.mjs.map +0 -1
  88. package/dist/chunk-DT2YLCPE.mjs.map +0 -1
  89. package/dist/chunk-PL5WNHFZ.mjs.map +0 -1
  90. package/dist/chunk-QZG33TOC.mjs.map +0 -1
  91. package/dist/chunk-XEMZTHQZ.mjs.map +0 -1
@@ -17,7 +17,8 @@ export enum ErrorVisibility {
17
17
  export const ERROR_NAMES = {
18
18
  COPILOT_ERROR: "CopilotError",
19
19
  COPILOT_API_DISCOVERY_ERROR: "CopilotApiDiscoveryError",
20
- COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR: "CopilotKitRemoteEndpointDiscoveryError",
20
+ COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR:
21
+ "CopilotKitRemoteEndpointDiscoveryError",
21
22
  COPILOT_KIT_AGENT_DISCOVERY_ERROR: "CopilotKitAgentDiscoveryError",
22
23
  COPILOT_KIT_LOW_LEVEL_ERROR: "CopilotKitLowLevelError",
23
24
  COPILOT_KIT_VERSION_MISMATCH_ERROR: "CopilotKitVersionMismatchError",
@@ -153,8 +154,10 @@ export class CopilotKitError extends GraphQLError {
153
154
  const name = ERROR_NAMES.COPILOT_ERROR;
154
155
  const config = ERROR_CONFIG[code];
155
156
  const { statusCode } = config;
156
- const resolvedVisibility = visibility ?? config.visibility ?? ErrorVisibility.TOAST;
157
- const resolvedSeverity = severity ?? ("severity" in config ? config.severity : undefined);
157
+ const resolvedVisibility =
158
+ visibility ?? config.visibility ?? ErrorVisibility.TOAST;
159
+ const resolvedSeverity =
160
+ severity ?? ("severity" in config ? config.severity : undefined);
158
161
 
159
162
  super(message, {
160
163
  extensions: {
@@ -163,7 +166,8 @@ export class CopilotKitError extends GraphQLError {
163
166
  code,
164
167
  visibility: resolvedVisibility,
165
168
  severity: resolvedSeverity,
166
- troubleshootingUrl: "troubleshootingUrl" in config ? config.troubleshootingUrl : null,
169
+ troubleshootingUrl:
170
+ "troubleshootingUrl" in config ? config.troubleshootingUrl : null,
167
171
  originalError: {
168
172
  message,
169
173
  stack: new Error().stack,
@@ -194,7 +198,8 @@ export class CopilotKitMisuseError extends CopilotKitError {
194
198
  code?: CopilotKitErrorCode;
195
199
  }) {
196
200
  const docsLink =
197
- "troubleshootingUrl" in ERROR_CONFIG[code] && ERROR_CONFIG[code].troubleshootingUrl
201
+ "troubleshootingUrl" in ERROR_CONFIG[code] &&
202
+ ERROR_CONFIG[code].troubleshootingUrl
198
203
  ? getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl as string)
199
204
  : null;
200
205
  const finalMessage = docsLink ? `${message}.\n\n${docsLink}` : message;
@@ -246,16 +251,20 @@ export class CopilotKitApiDiscoveryError extends CopilotKitError {
246
251
  constructor(
247
252
  params: {
248
253
  message?: string;
249
- code?: CopilotKitErrorCode.API_NOT_FOUND | CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND;
254
+ code?:
255
+ | CopilotKitErrorCode.API_NOT_FOUND
256
+ | CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND;
250
257
  url?: string;
251
258
  } = {},
252
259
  ) {
253
260
  const url = params.url ?? "";
254
261
  let operationSuffix = "";
255
- if (url?.includes("/info")) operationSuffix = `when fetching CopilotKit info`;
262
+ if (url?.includes("/info"))
263
+ operationSuffix = `when fetching CopilotKit info`;
256
264
  else if (url.includes("/actions/execute"))
257
265
  operationSuffix = `when attempting to execute actions.`;
258
- else if (url.includes("/agents/state")) operationSuffix = `when attempting to get agent state.`;
266
+ else if (url.includes("/agents/state"))
267
+ operationSuffix = `when attempting to get agent state.`;
259
268
  else if (url.includes("/agents/execute"))
260
269
  operationSuffix = `when attempting to execute agent(s).`;
261
270
  const message =
@@ -301,7 +310,10 @@ export class CopilotKitRemoteEndpointDiscoveryError extends CopilotKitApiDiscove
301
310
  * @extends CopilotKitError
302
311
  */
303
312
  export class CopilotKitAgentDiscoveryError extends CopilotKitError {
304
- constructor(params: { agentName?: string; availableAgents: { name: string; id: string }[] }) {
313
+ constructor(params: {
314
+ agentName?: string;
315
+ availableAgents: { name: string; id: string }[];
316
+ }) {
305
317
  const { agentName, availableAgents } = params;
306
318
  const code = CopilotKitErrorCode.AGENT_NOT_FOUND;
307
319
 
@@ -338,12 +350,21 @@ export class CopilotKitAgentDiscoveryError extends CopilotKitError {
338
350
  * - Protocol/transport layer errors like SSL/TLS issues
339
351
  */
340
352
  export class CopilotKitLowLevelError extends CopilotKitError {
341
- constructor({ error, url, message }: { error: Error; url: string; message?: string }) {
353
+ constructor({
354
+ error,
355
+ url,
356
+ message,
357
+ }: {
358
+ error: Error;
359
+ url: string;
360
+ message?: string;
361
+ }) {
342
362
  let code = CopilotKitErrorCode.NETWORK_ERROR;
343
363
 
344
364
  // @ts-expect-error -- code may exist
345
365
  const errorCode = error.code as string;
346
- const errorMessage = message ?? resolveLowLevelErrorMessage({ errorCode, url });
366
+ const errorMessage =
367
+ message ?? resolveLowLevelErrorMessage({ errorCode, url });
347
368
 
348
369
  super({ message: errorMessage, code });
349
370
 
@@ -469,7 +490,8 @@ export async function getPossibleVersionMismatch({
469
490
  runtimeVersion?: string;
470
491
  runtimeClientGqlVersion: string;
471
492
  }) {
472
- if (!runtimeVersion || runtimeVersion === "" || !runtimeClientGqlVersion) return;
493
+ if (!runtimeVersion || runtimeVersion === "" || !runtimeClientGqlVersion)
494
+ return;
473
495
  if (
474
496
  COPILOTKIT_VERSION !== runtimeVersion ||
475
497
  COPILOTKIT_VERSION !== runtimeClientGqlVersion ||
@@ -490,9 +512,18 @@ export async function getPossibleVersionMismatch({
490
512
  return;
491
513
  }
492
514
 
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}.
515
+ const resolveLowLevelErrorMessage = ({
516
+ errorCode,
517
+ url,
518
+ }: {
519
+ errorCode?: string;
520
+ url: string;
521
+ }) => {
522
+ const troubleshootingLink =
523
+ ERROR_CONFIG[CopilotKitErrorCode.NETWORK_ERROR].troubleshootingUrl;
524
+ const genericMessage = (
525
+ description = `Failed to fetch from url ${url}.`,
526
+ ) => `${description}.
496
527
 
497
528
  Possible reasons:
498
529
  - -The server may have an error preventing it from returning a response (Check the server logs for more info).
@@ -504,7 +535,9 @@ Possible reasons:
504
535
  ${getSeeMoreMarkdown(troubleshootingLink)}`;
505
536
 
506
537
  if (url.includes("/info"))
507
- return genericMessage(`Failed to fetch CopilotKit agents/action information from url ${url}.`);
538
+ return genericMessage(
539
+ `Failed to fetch CopilotKit agents/action information from url ${url}.`,
540
+ );
508
541
  if (url.includes("/actions/execute"))
509
542
  return genericMessage(`Fetch call to ${url} to execute actions failed.`);
510
543
  if (url.includes("/agents/state"))
@@ -198,13 +198,22 @@ describe("jsonSchemaToActionParameters", () => {
198
198
  const jsonSchema: JSONSchema = {
199
199
  type: "object",
200
200
  properties: {
201
- role: { type: "string", enum: ["admin", "user", "guest"], description: "User role" },
201
+ role: {
202
+ type: "string",
203
+ enum: ["admin", "user", "guest"],
204
+ description: "User role",
205
+ },
202
206
  },
203
207
  required: ["role"],
204
208
  };
205
209
 
206
210
  const expectedParameters: Parameter[] = [
207
- { name: "role", type: "string", enum: ["admin", "user", "guest"], description: "User role" },
211
+ {
212
+ name: "role",
213
+ type: "string",
214
+ enum: ["admin", "user", "guest"],
215
+ description: "User role",
216
+ },
208
217
  ];
209
218
 
210
219
  const result = jsonSchemaToActionParameters(jsonSchema);
@@ -235,7 +244,12 @@ describe("jsonSchemaToActionParameters", () => {
235
244
  description: "User information",
236
245
  attributes: [
237
246
  { name: "name", type: "string", description: "User name" },
238
- { name: "age", type: "number", description: "User age", required: false },
247
+ {
248
+ name: "age",
249
+ type: "number",
250
+ description: "User age",
251
+ required: false,
252
+ },
239
253
  ],
240
254
  },
241
255
  ];
@@ -292,7 +306,12 @@ describe("jsonSchemaToActionParameters", () => {
292
306
  description: "User addresses",
293
307
  attributes: [
294
308
  { name: "street", type: "string", description: "Street name" },
295
- { name: "city", type: "string", description: "City name", required: false },
309
+ {
310
+ name: "city",
311
+ type: "string",
312
+ description: "City name",
313
+ required: false,
314
+ },
296
315
  ],
297
316
  },
298
317
  ];
@@ -354,7 +373,12 @@ describe("jsonSchemaToActionParameters", () => {
354
373
  const originalParameters: Parameter[] = [
355
374
  { name: "name", type: "string", description: "User name" },
356
375
  { name: "age", type: "number", description: "User age", required: false },
357
- { name: "role", type: "string", enum: ["admin", "user"], description: "User role" },
376
+ {
377
+ name: "role",
378
+ type: "string",
379
+ enum: ["admin", "user"],
380
+ description: "User role",
381
+ },
358
382
  {
359
383
  name: "address",
360
384
  type: "object",
@@ -37,7 +37,9 @@ export type JSONSchema =
37
37
  | JSONSchemaObject
38
38
  | JSONSchemaArray;
39
39
 
40
- export function actionParametersToJsonSchema(actionParameters: Parameter[]): JSONSchema {
40
+ export function actionParametersToJsonSchema(
41
+ actionParameters: Parameter[],
42
+ ): JSONSchema {
41
43
  // Create the parameters object based on the argumentAnnotations
42
44
  let parameters: { [key: string]: any } = {};
43
45
  for (let parameter of actionParameters || []) {
@@ -60,7 +62,9 @@ export function actionParametersToJsonSchema(actionParameters: Parameter[]): JSO
60
62
  }
61
63
 
62
64
  // Convert JSONSchema to Parameter[]
63
- export function jsonSchemaToActionParameters(jsonSchema: JSONSchema): Parameter[] {
65
+ export function jsonSchemaToActionParameters(
66
+ jsonSchema: JSONSchema,
67
+ ): Parameter[] {
64
68
  if (jsonSchema.type !== "object" || !jsonSchema.properties) {
65
69
  return [];
66
70
  }
@@ -69,7 +73,11 @@ export function jsonSchemaToActionParameters(jsonSchema: JSONSchema): Parameter[
69
73
  const requiredFields = jsonSchema.required || [];
70
74
 
71
75
  for (const [name, schema] of Object.entries(jsonSchema.properties)) {
72
- const parameter = convertJsonSchemaToParameter(name, schema, requiredFields.includes(name));
76
+ const parameter = convertJsonSchemaToParameter(
77
+ name,
78
+ schema,
79
+ requiredFields.includes(name),
80
+ );
73
81
  parameters.push(parameter);
74
82
  }
75
83
 
@@ -109,9 +117,15 @@ function convertJsonSchemaToParameter(
109
117
  const attributes: Parameter[] = [];
110
118
  const requiredFields = schema.required || [];
111
119
 
112
- for (const [propName, propSchema] of Object.entries(schema.properties)) {
120
+ for (const [propName, propSchema] of Object.entries(
121
+ schema.properties,
122
+ )) {
113
123
  attributes.push(
114
- convertJsonSchemaToParameter(propName, propSchema, requiredFields.includes(propName)),
124
+ convertJsonSchemaToParameter(
125
+ propName,
126
+ propSchema,
127
+ requiredFields.includes(propName),
128
+ ),
115
129
  );
116
130
  }
117
131
 
@@ -130,9 +144,15 @@ function convertJsonSchemaToParameter(
130
144
  const attributes: Parameter[] = [];
131
145
  const requiredFields = schema.items.required || [];
132
146
 
133
- for (const [propName, propSchema] of Object.entries(schema.items.properties || {})) {
147
+ for (const [propName, propSchema] of Object.entries(
148
+ schema.items.properties || {},
149
+ )) {
134
150
  attributes.push(
135
- convertJsonSchemaToParameter(propName, propSchema, requiredFields.includes(propName)),
151
+ convertJsonSchemaToParameter(
152
+ propName,
153
+ propSchema,
154
+ requiredFields.includes(propName),
155
+ ),
136
156
  );
137
157
  }
138
158
 
@@ -218,7 +238,10 @@ function convertAttribute(attribute: Parameter): JSONSchema {
218
238
  }
219
239
  }
220
240
 
221
- export function convertJsonSchemaToZodSchema(jsonSchema: any, required: boolean): z.ZodSchema {
241
+ export function convertJsonSchemaToZodSchema(
242
+ jsonSchema: any,
243
+ required: boolean,
244
+ ): z.ZodSchema {
222
245
  if (jsonSchema.type === "object") {
223
246
  const spec: { [key: string]: z.ZodSchema } = {};
224
247
 
@@ -251,7 +274,9 @@ export function convertJsonSchemaToZodSchema(jsonSchema: any, required: boolean)
251
274
  throw new Error("Invalid JSON schema");
252
275
  }
253
276
 
254
- export function getZodParameters<T extends [] | Parameter[] | undefined>(parameters: T): any {
277
+ export function getZodParameters<T extends [] | Parameter[] | undefined>(
278
+ parameters: T,
279
+ ): any {
255
280
  if (!parameters) return z.object({});
256
281
  const jsonParams = actionParametersToJsonSchema(parameters);
257
282
  return convertJsonSchemaToZodSchema(jsonParams, true);
@@ -31,9 +31,12 @@ function toSerializable(value: unknown): unknown {
31
31
  export function dataToUUID(input: string | object, namespace?: string): string {
32
32
  const BASE_NAMESPACE = "e4b01160-ff74-4c6e-9b27-d53cd930fe8e";
33
33
  // Since namespace needs to be a uuid, we are creating a uuid for it.
34
- const boundNamespace = namespace ? uuidv5(namespace, BASE_NAMESPACE) : BASE_NAMESPACE;
34
+ const boundNamespace = namespace
35
+ ? uuidv5(namespace, BASE_NAMESPACE)
36
+ : BASE_NAMESPACE;
35
37
 
36
- const stringInput = typeof input === "string" ? input : JSON.stringify(toSerializable(input));
38
+ const stringInput =
39
+ typeof input === "string" ? input : JSON.stringify(toSerializable(input));
37
40
  return uuidv5(stringInput, boundNamespace);
38
41
  }
39
42
 
@@ -5,7 +5,9 @@
5
5
  * - Tries JSON first regardless of content-type
6
6
  * - Falls back to text and optionally parses when it "looks" like JSON
7
7
  */
8
- export async function readBody<T extends Response | Request>(r: T): Promise<unknown> {
8
+ export async function readBody<T extends Response | Request>(
9
+ r: T,
10
+ ): Promise<unknown> {
9
11
  // skip GET/HEAD requests (unchanged)
10
12
  const method = "method" in r ? r.method.toUpperCase() : undefined;
11
13
  if (method === "GET" || method === "HEAD") {
@@ -4,7 +4,11 @@ export type MaybePromise<T> = T | PromiseLike<T>;
4
4
  * More specific utility for records with at least one key
5
5
  */
6
6
  export type NonEmptyRecord<T> =
7
- T extends Record<string, unknown> ? (keyof T extends never ? never : T) : never;
7
+ T extends Record<string, unknown>
8
+ ? keyof T extends never
9
+ ? never
10
+ : T
11
+ : never;
8
12
 
9
13
  /**
10
14
  * Type representing an agent's basic information
package/tsconfig.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "extends": "../../utilities/tsconfig/base.json",
2
+ "extends": "../tsconfig/base.json",
3
3
  "include": ["."],
4
4
  "compilerOptions": {
5
5
  "lib": ["es2017", "dom"],
package/tsup.config.ts CHANGED
@@ -1,7 +1,11 @@
1
1
  import { defineConfig, Options } from "tsup";
2
2
 
3
3
  export default defineConfig((options: Options) => ({
4
- entry: ["src/**/*.{ts,tsx}", "!src/**/*.test.{ts,tsx}", "!src/**/__tests__/**/*"],
4
+ entry: [
5
+ "src/**/*.{ts,tsx}",
6
+ "!src/**/*.test.{ts,tsx}",
7
+ "!src/**/__tests__/**/*",
8
+ ],
5
9
  format: ["esm", "cjs"],
6
10
  dts: true,
7
11
  minify: false,
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/json-schema.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { Parameter } from \"../types\";\n\nexport type JSONSchemaString = {\n type: \"string\";\n description?: string;\n enum?: string[];\n};\n\nexport type JSONSchemaNumber = {\n type: \"number\";\n description?: string;\n};\n\nexport type JSONSchemaBoolean = {\n type: \"boolean\";\n description?: string;\n};\n\nexport type JSONSchemaObject = {\n type: \"object\";\n properties?: Record<string, JSONSchema>;\n required?: string[];\n description?: string;\n};\n\nexport type JSONSchemaArray = {\n type: \"array\";\n items: JSONSchema;\n description?: string;\n};\n\nexport type JSONSchema =\n | JSONSchemaString\n | JSONSchemaNumber\n | JSONSchemaBoolean\n | JSONSchemaObject\n | JSONSchemaArray;\n\nexport function actionParametersToJsonSchema(actionParameters: Parameter[]): JSONSchema {\n // Create the parameters object based on the argumentAnnotations\n let parameters: { [key: string]: any } = {};\n for (let parameter of actionParameters || []) {\n parameters[parameter.name] = convertAttribute(parameter);\n }\n\n let requiredParameterNames: string[] = [];\n for (let arg of actionParameters || []) {\n if (arg.required !== false) {\n requiredParameterNames.push(arg.name);\n }\n }\n\n // Create the ChatCompletionFunctions object\n return {\n type: \"object\",\n properties: parameters,\n required: requiredParameterNames,\n };\n}\n\n// Convert JSONSchema to Parameter[]\nexport function jsonSchemaToActionParameters(jsonSchema: JSONSchema): Parameter[] {\n if (jsonSchema.type !== \"object\" || !jsonSchema.properties) {\n return [];\n }\n\n const parameters: Parameter[] = [];\n const requiredFields = jsonSchema.required || [];\n\n for (const [name, schema] of Object.entries(jsonSchema.properties)) {\n const parameter = convertJsonSchemaToParameter(name, schema, requiredFields.includes(name));\n parameters.push(parameter);\n }\n\n return parameters;\n}\n\n// Convert JSONSchema property to Parameter\nfunction convertJsonSchemaToParameter(\n name: string,\n schema: JSONSchema,\n isRequired: boolean,\n): Parameter {\n const baseParameter: Parameter = {\n name,\n description: schema.description,\n };\n\n if (!isRequired) {\n baseParameter.required = false;\n }\n\n switch (schema.type) {\n case \"string\":\n return {\n ...baseParameter,\n type: \"string\",\n ...(schema.enum && { enum: schema.enum }),\n };\n case \"number\":\n case \"boolean\":\n return {\n ...baseParameter,\n type: schema.type,\n };\n case \"object\":\n if (schema.properties) {\n const attributes: Parameter[] = [];\n const requiredFields = schema.required || [];\n\n for (const [propName, propSchema] of Object.entries(schema.properties)) {\n attributes.push(\n convertJsonSchemaToParameter(propName, propSchema, requiredFields.includes(propName)),\n );\n }\n\n return {\n ...baseParameter,\n type: \"object\",\n attributes,\n };\n }\n return {\n ...baseParameter,\n type: \"object\",\n };\n case \"array\":\n if (schema.items.type === \"object\" && \"properties\" in schema.items) {\n const attributes: Parameter[] = [];\n const requiredFields = schema.items.required || [];\n\n for (const [propName, propSchema] of Object.entries(schema.items.properties || {})) {\n attributes.push(\n convertJsonSchemaToParameter(propName, propSchema, requiredFields.includes(propName)),\n );\n }\n\n return {\n ...baseParameter,\n type: \"object[]\",\n attributes,\n };\n } else if (schema.items.type === \"array\") {\n throw new Error(\"Nested arrays are not supported\");\n } else {\n return {\n ...baseParameter,\n type: `${schema.items.type}[]`,\n };\n }\n default:\n return {\n ...baseParameter,\n type: \"string\",\n };\n }\n}\n\nfunction convertAttribute(attribute: Parameter): JSONSchema {\n switch (attribute.type) {\n case \"string\":\n return {\n type: \"string\",\n description: attribute.description,\n ...(attribute.enum && { enum: attribute.enum }),\n };\n case \"number\":\n case \"boolean\":\n return {\n type: attribute.type,\n description: attribute.description,\n };\n case \"object\":\n case \"object[]\":\n const properties = attribute.attributes?.reduce(\n (acc, attr) => {\n acc[attr.name] = convertAttribute(attr);\n return acc;\n },\n {} as Record<string, any>,\n );\n const required = attribute.attributes\n ?.filter((attr) => attr.required !== false)\n .map((attr) => attr.name);\n if (attribute.type === \"object[]\") {\n return {\n type: \"array\",\n items: {\n type: \"object\",\n ...(properties && { properties }),\n ...(required && required.length > 0 && { required }),\n },\n description: attribute.description,\n };\n }\n return {\n type: \"object\",\n description: attribute.description,\n ...(properties && { properties }),\n ...(required && required.length > 0 && { required }),\n };\n default:\n // Handle arrays of primitive types and undefined attribute.type\n if (attribute.type?.endsWith(\"[]\")) {\n const itemType = attribute.type.slice(0, -2);\n return {\n type: \"array\",\n items: { type: itemType as any },\n description: attribute.description,\n };\n }\n // Fallback for undefined type or any other unexpected type\n return {\n type: \"string\",\n description: attribute.description,\n };\n }\n}\n\nexport function convertJsonSchemaToZodSchema(jsonSchema: any, required: boolean): z.ZodSchema {\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(\n value,\n jsonSchema.required ? jsonSchema.required.includes(key) : false,\n );\n }\n let schema = z.object(spec).describe(jsonSchema.description);\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n let schema = z.string().describe(jsonSchema.description);\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\") {\n let schema = z.number().describe(jsonSchema.description);\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n let schema = z.boolean().describe(jsonSchema.description);\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n let schema = z.array(itemSchema).describe(jsonSchema.description);\n return required ? schema : schema.optional();\n }\n throw new Error(\"Invalid JSON schema\");\n}\n\nexport function getZodParameters<T extends [] | Parameter[] | undefined>(parameters: T): any {\n if (!parameters) return z.object({});\n const jsonParams = actionParametersToJsonSchema(parameters);\n return convertJsonSchemaToZodSchema(jsonParams, true);\n}\n"],"mappings":";AAAA,SAAS,SAAS;AAuCX,SAAS,6BAA6B,kBAA2C;AAEtF,MAAI,aAAqC,CAAC;AAC1C,WAAS,aAAa,oBAAoB,CAAC,GAAG;AAC5C,eAAW,UAAU,IAAI,IAAI,iBAAiB,SAAS;AAAA,EACzD;AAEA,MAAI,yBAAmC,CAAC;AACxC,WAAS,OAAO,oBAAoB,CAAC,GAAG;AACtC,QAAI,IAAI,aAAa,OAAO;AAC1B,6BAAuB,KAAK,IAAI,IAAI;AAAA,IACtC;AAAA,EACF;AAGA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,YAAY;AAAA,IACZ,UAAU;AAAA,EACZ;AACF;AAGO,SAAS,6BAA6B,YAAqC;AAChF,MAAI,WAAW,SAAS,YAAY,CAA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AA,EAC7C,WAAW,WAAW,SAAS,UAAU;AACvC,QAAI,SAAS,EAAE,OAAO,EAAE,SAAS,WAAW,WAAW;AACvD,WAAO,WAAW,SAAS,OAAO,SAAS;AAAA,EAC7C,WAAW,WAAW,SAAS,WAAW;AACxC,QAAI,SAAS,EAAE,QAAQ,EAAE,SAAS,WAAW,WAAW;AACxD,WAAO,WAAW,SAAS,OAAO,SAAS;AAAA,EAC7C,WAAW,WAAW,SAAS,SAAS;AACtC,QAAI,aAAa,6BAA6B,WAAW,OAAO,IAAI;AACpE,QAAI,SAAS,EAAE,MAAM,UAAU,EAAE,SAAS,WAAW,WAAW;AAChE,WAAO,WAAW,SAAS,OAAO,SAAS;AAAA,EAC7C;AACA,QAAM,IAAI,MAAM,qBAAqB;AACvC;AAEO,SAAS,iBAAyD,YAAoB;AAC3F,MAAI,CAAC;AAAY,WAAO,EAAE,OAAO,CAAC,CAAC;AACnC,QAAM,aAAa,6BAA6B,UAAU;AAC1D,SAAO,6BAA6B,YAAY,IAAI;AACtD;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/telemetry/utils.ts"],"sourcesContent":["import chalk from \"chalk\";\n\nexport function flattenObject(\n obj: Record<string, any>,\n parentKey = \"\",\n res: Record<string, any> = {},\n): Record<string, any> {\n for (let key in obj) {\n const propName = parentKey ? `${parentKey}.${key}` : key;\n if (typeof obj[key] === \"object\" && obj[key] !== null) {\n flattenObject(obj[key], propName, res);\n } else {\n res[propName] = obj[key];\n }\n }\n return res;\n}\n\nexport function printSecurityNotice(advisory: {\n advisory: string | null;\n message: string;\n severity: \"low\" | \"medium\" | \"high\" | \"none\";\n}) {\n const severityColor =\n {\n low: chalk.blue,\n medium: chalk.yellow,\n high: chalk.red,\n }[advisory.severity.toLowerCase()] || chalk.white;\n\n console.log();\n console.log(`━━━━━━━━━━━━━━━━━━ ${chalk.bold(`CopilotKit`)} ━━━━━━━━━━━━━━━━━━`);\n console.log();\n console.log(`${chalk.bold(`Severity: ${severityColor(advisory.severity.toUpperCase())}`)}`);\n console.log();\n console.log(`${chalk.bold(advisory.message)}`);\n console.log();\n console.log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);\n}\n"],"mappings":";AAAA,OAAO,WAAW;AAEX,SAAS,cACd,KACA,YAAY,IACZ,MAA2B,CAAC,GACP;AACrB,WAAS,OAAO,KAAK;AACnB,UAAM,WAAW,YAAY,GAAG,aAAa,QAAQ;AACrD,QAAI,OAAO,IAAI,GAAG,MAAM,YAAY,IAAI,GAAG,MAAM,MAAM;AACrD,oBAAc,IAAI,GAAG,GAAG,UAAU,GAAG;AAAA,IACvC,OAAO;AACL,UAAI,QAAQ,IAAI,IAAI,GAAG;AAAA,IACzB;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,oBAAoB,UAIjC;AACD,QAAM,gBACJ;AAAA,IACE,KAAK,MAAM;AAAA,IACX,QAAQ,MAAM;AAAA,IACd,MAAM,MAAM;AAAA,EACd,EAAE,SAAS,SAAS,YAAY,CAAC,KAAK,MAAM;AAE9C,UAAQ,IAAI;AACZ,UAAQ,IAAI,gHAAsB,MAAM,KAAK,YAAY,gHAAsB;AAC/E,UAAQ,IAAI;AACZ,UAAQ,IAAI,GAAG,MAAM,KAAK,aAAa,cAAc,SAAS,SAAS,YAAY,CAAC,GAAG,GAAG;AAC1F,UAAQ,IAAI;AACZ,UAAQ,IAAI,GAAG,MAAM,KAAK,SAAS,OAAO,GAAG;AAC7C,UAAQ,IAAI;AACZ,UAAQ,IAAI,kSAAkD;AAChE;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/errors.ts","../src/utils/index.ts","../src/index.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: \"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#i-am-getting-a-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#i-am-getting-a-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}/coagents/troubleshooting/common-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#i-am-getting-a-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#i-am-getting-copilotkits-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#authentication-errors`,\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 = visibility ?? config.visibility ?? ErrorVisibility.TOAST;\n const resolvedSeverity = 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: \"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] && 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?: CopilotKitErrorCode.API_NOT_FOUND | CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND;\n url?: string;\n } = {},\n ) {\n const url = params.url ?? \"\";\n let operationSuffix = \"\";\n if (url?.includes(\"/info\")) 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\")) 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: { agentName?: string; availableAgents: { name: string; id: string }[] }) {\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({ error, url, message }: { error: Error; url: string; message?: string }) {\n let code = CopilotKitErrorCode.NETWORK_ERROR;\n\n // @ts-expect-error -- code may exist\n const errorCode = error.code as string;\n const errorMessage = 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) 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 = ({ errorCode, url }: { errorCode?: string; url: string }) => {\n const troubleshootingLink = ERROR_CONFIG[CopilotKitErrorCode.NETWORK_ERROR].troubleshootingUrl;\n const genericMessage = (description = `Failed to fetch from url ${url}.`) => `${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(`Failed to fetch CopilotKit agents/action information from url ${url}.`);\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","export * from \"./conditions\";\nexport * from \"./console-styling\";\nexport * from \"./errors\";\nexport * from \"./json-schema\";\nexport * from \"./types\";\nexport * from \"./random-id\";\nexport * from \"./requests\";\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 (e) {\n return fallback === \"unset\" ? null : fallback;\n }\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","export * from \"./types\";\nexport * from \"./utils\";\nexport * from \"./constants\";\nexport * from \"./telemetry\";\n\nimport * as packageJson from \"../package.json\";\nexport const COPILOTKIT_VERSION = packageJson.version;\n"],"mappings":";;;;;AAAA,SAAS,oBAAoB;;;ACctB,SAAS,UAAU,MAAc,WAAgB,SAAS;AAC/D,MAAI;AACF,WAAO,KAAK,MAAM,IAAI;AAAA,EACxB,SAAS,GAAP;AACA,WAAO,aAAa,UAAU,OAAO;AAAA,EACvC;AACF;AAQO,SAAS,OACd,OACA,UACW;AACX,SAAO,MAAM,OAAkB,CAAC,KAAK,MAAM,OAAO,UAAU;AAC1D,QAAI;AACF,UAAI,KAAK,SAAS,MAAM,OAAO,KAAK,CAAC;AAAA,IACvC,SAAS,OAAP;AACA,cAAQ,MAAM,KAAK;AAAA,IACrB;AACA,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AACP;AAMO,SAAS,UAAmB;AACjC,SAAO,sBAAsB,KAAK,UAAU,SAAS;AACvD;;;AC1CO,IAAM,qBAAiC;;;AFHvC,IAAK,WAAL,kBAAKA,cAAL;AACL,EAAAA,UAAA,cAAW;AACX,EAAAA,UAAA,aAAU;AACV,EAAAA,UAAA,UAAO;AAHG,SAAAA;AAAA,GAAA;AAML,IAAK,kBAAL,kBAAKC,qBAAL;AACL,EAAAA,iBAAA,YAAS;AACT,EAAAA,iBAAA,WAAQ;AACR,EAAAA,iBAAA,YAAS;AACT,EAAAA,iBAAA,cAAW;AAJD,SAAAA;AAAA,GAAA;AAOL,IAAM,cAAc;AAAA,EACzB,eAAe;AAA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B;AAAA,IACpI,KAAK;AACH,aAAO,iBAAiB;AAAA;AAAA,EAA2E,mBAAmB,aAAa,2BAA6B,EAAE,kBAAkB;AAAA,IACtL,KAAK;AACH,aAAO,qBAAqB;AAAA;AAAA,EAAmF,mBAAmB,mBAAmB;AAAA,IACvJ;AACE;AAAA,EACJ;AACF;","names":["Severity","ErrorVisibility","CopilotKitErrorCode"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/telemetry/telemetry-client.ts"],"sourcesContent":["import { Analytics } from \"@segment/analytics-node\";\nimport { AnalyticsEvents } from \"./events\";\nimport { flattenObject } from \"./utils\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport scarfClient from \"./scarf-client\";\n\n/**\n * Checks if telemetry is disabled via environment variables.\n * Users can opt out by setting:\n * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1\n * - DO_NOT_TRACK=true or DO_NOT_TRACK=1\n */\nexport function isTelemetryDisabled(): boolean {\n return (\n (process.env as Record<string, string | undefined>).COPILOTKIT_TELEMETRY_DISABLED === \"true\" ||\n (process.env as Record<string, string | undefined>).COPILOTKIT_TELEMETRY_DISABLED === \"1\" ||\n (process.env as Record<string, string | undefined>).DO_NOT_TRACK === \"true\" ||\n (process.env as Record<string, string | undefined>).DO_NOT_TRACK === \"1\"\n );\n}\n\nexport class TelemetryClient {\n segment: Analytics | undefined;\n globalProperties: Record<string, any> = {};\n cloudConfiguration: { publicApiKey: string; baseUrl: string } | null = null;\n packageName: string;\n packageVersion: string;\n private telemetryDisabled: boolean = false;\n private sampleRate: number = 0.05;\n private anonymousId = `anon_${uuidv4()}`;\n\n constructor({\n packageName,\n packageVersion,\n telemetryDisabled,\n telemetryBaseUrl,\n sampleRate,\n }: {\n packageName: string;\n packageVersion: string;\n telemetryDisabled?: boolean;\n telemetryBaseUrl?: string;\n sampleRate?: number;\n }) {\n this.packageName = packageName;\n this.packageVersion = packageVersion;\n this.telemetryDisabled = telemetryDisabled || isTelemetryDisabled();\n\n if (this.telemetryDisabled) {\n return;\n }\n\n this.setSampleRate(sampleRate);\n\n // eslint-disable-next-line\n const writeKey = process.env.COPILOTKIT_SEGMENT_WRITE_KEY || \"n7XAZtQCGS2v1vvBy3LgBCv2h3Y8whja\";\n\n this.segment = new Analytics({\n writeKey,\n });\n\n this.setGlobalProperties({\n \"copilotkit.package.name\": packageName,\n \"copilotkit.package.version\": packageVersion,\n });\n }\n\n private shouldSendEvent() {\n const randomNumber = Math.random();\n return randomNumber < this.sampleRate;\n }\n\n async capture<K extends keyof AnalyticsEvents>(event: K, properties: AnalyticsEvents[K]) {\n if (!this.shouldSendEvent() || !this.segment) {\n return;\n }\n\n const flattenedProperties = flattenObject(properties);\n const propertiesWithGlobal = {\n ...this.globalProperties,\n ...flattenedProperties,\n };\n const orderedPropertiesWithGlobal = Object.keys(propertiesWithGlobal)\n .sort()\n .reduce(\n (obj, key) => {\n obj[key] = propertiesWithGlobal[key];\n return obj;\n },\n {} as Record<string, any>,\n );\n\n this.segment.track({\n anonymousId: this.anonymousId,\n event,\n properties: { ...orderedPropertiesWithGlobal },\n });\n\n await scarfClient.logEvent({\n event,\n });\n }\n\n setGlobalProperties(properties: Record<string, any>) {\n const flattenedProperties = flattenObject(properties);\n this.globalProperties = { ...this.globalProperties, ...flattenedProperties };\n }\n\n setCloudConfiguration(properties: { publicApiKey: string; baseUrl: string }) {\n this.cloudConfiguration = properties;\n\n this.setGlobalProperties({\n cloud: {\n publicApiKey: properties.publicApiKey,\n baseUrl: properties.baseUrl,\n },\n });\n }\n\n private setSampleRate(sampleRate: number | undefined) {\n let _sampleRate: number;\n\n _sampleRate = sampleRate ?? 0.05;\n\n // eslint-disable-next-line\n if (process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE) {\n // eslint-disable-next-line\n _sampleRate = parseFloat(process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE);\n }\n\n if (_sampleRate < 0 || _sampleRate > 1) {\n throw new Error(\"Sample rate must be between 0 and 1\");\n }\n\n this.sampleRate = _sampleRate;\n this.setGlobalProperties({\n sampleRate: this.sampleRate,\n sampleRateAdjustmentFactor: 1 - this.sampleRate,\n sampleWeight: 1 / this.sampleRate,\n });\n }\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,iBAAiB;AAG1B,SAAS,MAAM,cAAc;AAStB,SAAS,sBAA+B;AAC7C,SACG,QAAQ,IAA2C,kCAAkC,UACrF,QAAQ,IAA2C,kCAAkC,OACrF,QAAQ,IAA2C,iBAAiB,UACpE,QAAQ,IAA2C,iBAAiB;AAEzE;AAEO,IAAM,kBAAN,MAAsB;AAAA,EAU3B,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAMG;AApBH,4BAAwC,CAAC;AACzC,8BAAuE;AAGvE,SAAQ,oBAA6B;AACrC,SAAQ,aAAqB;AAC7B,SAAQ,cAAc,QAAQ,OAAO;AAenC,SAAK,cAAc;AACnB,SAAK,iBAAiB;AACtB,SAAK,oBAAoB,qBAAqB,oBAAoB;AAElE,QAAI,KAAK,mBAAmB;AAC1B;AAAA,IACF;AAEA,SAAK,cAAc,UAAU;AAG7B,UAAM,WAAW,QAAQ,IAAI,gCAAgC;AAE7D,SAAK,UAAU,IAAI,UAAU;AAAA,MAC3B;AAAA,IACF,CAAC;AAED,SAAK,oBAAoB;AAAA,MACvB,2BAA2B;AAAA,MAC3B,8BAA8B;AAAA,IAChC,CAAC;AAAA,EACH;AAAA,EAEQ,kBAAkB;AACxB,UAAM,eAAe,KAAK,OAAO;AACjC,WAAO,eAAe,KAAK;AAAA,EAC7B;AAAA,EAEA,MAAM,QAAyC,OAAU,YAAgC;AACvF,QAAI,CAAC,KAAK,gBAAgB,KAAK,CAAC,KAAK,SAAS;AAC5C;AAAA,IACF;AAEA,UAAM,sBAAsB,cAAc,UAAU;AACpD,UAAM,uBAAuB;AAAA,MAC3B,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA,UAAM,8BAA8B,OAAO,KAAK,oBAAoB,EACjE,KAAK,EACL;AAAA,MACC,CAAC,KAAK,QAAQ;AACZ,YAAI,GAAG,IAAI,qBAAqB,GAAG;AACnC,eAAO;AAAA,MACT;AAAA,MACA,CAAC;AAAA,IACH;AAEF,SAAK,QAAQ,MAAM;AAAA,MACjB,aAAa,KAAK;AAAA,MAClB;AAAA,MACA,YAAY,EAAE,GAAG,4BAA4B;AAAA,IAC/C,CAAC;AAED,UAAM,qBAAY,SAAS;AAAA,MACzB;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,oBAAoB,YAAiC;AACnD,UAAM,sBAAsB,cAAc,UAAU;AACpD,SAAK,mBAAmB,EAAE,GAAG,KAAK,kBAAkB,GAAG,oBAAoB;AAAA,EAC7E;AAAA,EAEA,sBAAsB,YAAuD;AAC3E,SAAK,qBAAqB;AAE1B,SAAK,oBAAoB;AAAA,MACvB,OAAO;AAAA,QACL,cAAc,WAAW;AAAA,QACzB,SAAS,WAAW;AAAA,MACtB;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEQ,cAAc,YAAgC;AACpD,QAAI;AAEJ,kBAAc,cAAc;AAG5B,QAAI,QAAQ,IAAI,kCAAkC;AAEhD,oBAAc,WAAW,QAAQ,IAAI,gCAAgC;AAAA,IACvE;AAEA,QAAI,cAAc,KAAK,cAAc,GAAG;AACtC,YAAM,IAAI,MAAM,qCAAqC;AAAA,IACvD;AAEA,SAAK,aAAa;AAClB,SAAK,oBAAoB;AAAA,MACvB,YAAY,KAAK;AAAA,MACjB,4BAA4B,IAAI,KAAK;AAAA,MACrC,cAAc,IAAI,KAAK;AAAA,IACzB,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/conditions.ts"],"sourcesContent":["export type ComparisonRule =\n | \"EQUALS\"\n | \"NOT_EQUALS\"\n | \"GREATER_THAN\"\n | \"LESS_THAN\"\n | \"CONTAINS\"\n | \"NOT_CONTAINS\"\n | \"MATCHES\"\n | \"STARTS_WITH\"\n | \"ENDS_WITH\";\nexport type LogicalRule = \"AND\" | \"OR\" | \"NOT\";\nexport type ExistenceRule = \"EXISTS\" | \"NOT_EXISTS\";\n\nexport type Rule = ComparisonRule | LogicalRule | ExistenceRule;\n\nexport interface BaseCondition {\n rule: Rule;\n path?: string;\n}\n\nexport interface ComparisonCondition extends BaseCondition {\n rule: ComparisonRule;\n value: any;\n}\n\nexport interface LogicalCondition extends BaseCondition {\n rule: LogicalRule;\n conditions: Condition[];\n}\n\nexport interface ExistenceCondition extends BaseCondition {\n rule: ExistenceRule;\n}\n\nexport type Condition = ComparisonCondition | LogicalCondition | ExistenceCondition;\n\nexport function executeConditions({\n conditions,\n value,\n}: {\n conditions?: Condition[];\n value: any;\n}): boolean {\n // If no conditions, consider it a pass\n if (!conditions?.length) return true;\n\n // Run all conditions (implicit AND)\n return conditions.every((condition) => executeCondition(condition, value));\n}\n\nfunction executeCondition(condition: Condition, value: any): boolean {\n const targetValue = condition.path ? getValueFromPath(value, condition.path) : value;\n\n switch (condition.rule) {\n // Logical\n case \"AND\":\n return (condition as LogicalCondition).conditions.every((c) => executeCondition(c, value));\n case \"OR\":\n return (condition as LogicalCondition).conditions.some((c) => executeCondition(c, value));\n case \"NOT\":\n return !(condition as LogicalCondition).conditions.every((c) => executeCondition(c, value));\n\n // Comparison\n case \"EQUALS\":\n return targetValue === (condition as ComparisonCondition).value;\n case \"NOT_EQUALS\":\n return targetValue !== (condition as ComparisonCondition).value;\n case \"GREATER_THAN\":\n return targetValue > (condition as ComparisonCondition).value;\n case \"LESS_THAN\":\n return targetValue < (condition as ComparisonCondition).value;\n case \"CONTAINS\":\n return (\n Array.isArray(targetValue) && targetValue.includes((condition as ComparisonCondition).value)\n );\n case \"NOT_CONTAINS\":\n return (\n Array.isArray(targetValue) &&\n !targetValue.includes((condition as ComparisonCondition).value)\n );\n case \"MATCHES\":\n return new RegExp((condition as ComparisonCondition).value).test(String(targetValue));\n case \"STARTS_WITH\":\n return String(targetValue).startsWith((condition as ComparisonCondition).value);\n case \"ENDS_WITH\":\n return String(targetValue).endsWith((condition as ComparisonCondition).value);\n\n // Existence\n case \"EXISTS\":\n return targetValue !== undefined && targetValue !== null;\n case \"NOT_EXISTS\":\n return targetValue === undefined || targetValue === null;\n }\n}\n\nfunction getValueFromPath(obj: any, path: string): any {\n return path.split(\".\").reduce((acc, part) => acc?.[part], obj);\n}\n"],"mappings":";AAoCO,SAAS,kBAAkB;AAAA,EAChC;AAAA,EACA;AACF,GAGY;AAEV,MAAI,EAAC,yCAAY;AAAQ,WAAO;AAGhC,SAAO,WAAW,MAAM,CAAC,cAAc,iBAAiB,WAAW,KAAK,CAAC;AAC3E;AAEA,SAAS,iBAAiB,WAAsB,OAAqB;AACnE,QAAM,cAAc,UAAU,OAAO,iBAAiB,OAAO,UAAU,IAAI,IAAI;AAE/E,UAAQ,UAAU,MAAM;AAAA,IAEtB,KAAK;AACH,aAAQ,UAA+B,WAAW,MAAM,CAAC,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAAA,IAC3F,KAAK;AACH,aAAQ,UAA+B,WAAW,KAAK,CAAC,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAAA,IAC1F,KAAK;AACH,aAAO,CAAE,UAA+B,WAAW,MAAM,CAAC,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAAA,IAG5F,KAAK;AACH,aAAO,gBAAiB,UAAkC;AAAA,IAC5D,KAAK;AACH,aAAO,gBAAiB,UAAkC;AAAA,IAC5D,KAAK;AACH,aAAO,cAAe,UAAkC;AAAA,IAC1D,KAAK;AACH,aAAO,cAAe,UAAkC;AAAA,IAC1D,KAAK;AACH,aACE,MAAM,QAAQ,WAAW,KAAK,YAAY,SAAU,UAAkC,KAAK;AAAA,IAE/F,KAAK;AACH,aACE,MAAM,QAAQ,WAAW,KACzB,CAAC,YAAY,SAAU,UAAkC,KAAK;AAAA,IAElE,KAAK;AACH,aAAO,IAAI,OAAQ,UAAkC,KAAK,EAAE,KAAK,OAAO,WAAW,CAAC;AAAA,IACtF,KAAK;AACH,aAAO,OAAO,WAAW,EAAE,WAAY,UAAkC,KAAK;AAAA,IAChF,KAAK;AACH,aAAO,OAAO,WAAW,EAAE,SAAU,UAAkC,KAAK;AAAA,IAG9E,KAAK;AACH,aAAO,gBAAgB,UAAa,gBAAgB;AAAA,IACtD,KAAK;AACH,aAAO,gBAAgB,UAAa,gBAAgB;AAAA,EACxD;AACF;AAEA,SAAS,iBAAiB,KAAU,MAAmB;AACrD,SAAO,KAAK,MAAM,GAAG,EAAE,OAAO,CAAC,KAAK,SAAS,2BAAM,OAAO,GAAG;AAC/D;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../package.json","../src/telemetry/scarf-client.ts"],"sourcesContent":["{\n \"name\": \"@copilotkit/shared\",\n \"private\": false,\n \"homepage\": \"https://github.com/CopilotKit/CopilotKit\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/CopilotKit/CopilotKit.git\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"version\": \"1.51.4-next.7\",\n \"sideEffects\": false,\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\"\n }\n },\n \"unpkg\": \"./dist/index.umd.js\",\n \"jsdelivr\": \"./dist/index.umd.js\",\n \"types\": \"./dist/index.d.ts\",\n \"license\": \"MIT\",\n \"scripts\": {\n \"build\": \"tsup --clean && rollup -c rollup.config.mjs\",\n \"dev\": \"tsup --watch --no-splitting\",\n \"test\": \"jest --passWithNoTests\",\n \"check-types\": \"tsc --noEmit\",\n \"clean\": \"rm -rf .turbo && rm -rf node_modules && rm -rf dist && rm -rf .next\",\n \"link:global\": \"pnpm link --global\",\n \"unlink:global\": \"pnpm unlink --global\"\n },\n \"devDependencies\": {\n \"@types/jest\": \"^29.5.4\",\n \"@types/uuid\": \"^10.0.0\",\n \"eslint\": \"^8.56.0\",\n \"eslint-config-custom\": \"workspace:*\",\n \"jest\": \"^29.6.4\",\n \"ts-jest\": \"^29.1.1\",\n \"tsconfig\": \"workspace:*\",\n \"tsup\": \"^6.7.0\",\n \"typescript\": \"^5.2.3\",\n \"zod-to-json-schema\": \"^3.23.5\"\n },\n \"dependencies\": {\n \"@segment/analytics-node\": \"^2.1.2\",\n \"chalk\": \"4.1.2\",\n \"graphql\": \"^16.8.1\",\n \"uuid\": \"^10.0.0\",\n \"zod\": \"^3.23.3\"\n },\n \"peerDependencies\": {\n \"@ag-ui/core\": \"^0.0.43\"\n },\n \"keywords\": [\n \"copilotkit\",\n \"copilot\",\n \"react\",\n \"nextjs\",\n \"nodejs\",\n \"ai\",\n \"assistant\",\n \"javascript\",\n \"automation\",\n \"textarea\"\n ]\n}\n","import * as packageJson from \"../../package.json\";\n\nconst SCARF_BASE_URL = `https://copilotkit.gateway.scarf.sh/${packageJson.version}`;\n\nclass ScarfClient {\n constructor() {}\n\n async logEvent(properties: Record<string, any>): Promise<void> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 3000);\n\n const queryParams = new URLSearchParams();\n\n Object.entries(properties).forEach(([key, value]) => {\n if (value !== null && value !== undefined) {\n queryParams.append(key, String(value));\n }\n });\n\n const url = `${SCARF_BASE_URL}?${queryParams.toString()}`;\n\n const response = await fetch(url, {\n method: \"GET\",\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n } catch {\n // Silently fail - telemetry should not break the application\n }\n }\n}\n\nexport default new ScarfClient();\n"],"mappings":";AAWE,cAAW;;;ACTb,IAAM,iBAAiB,uCAAmD;AAE1E,IAAM,cAAN,MAAkB;AAAA,EAChB,cAAc;AAAA,EAAC;AAAA,EAEf,MAAM,SAAS,YAAgD;AAC7D,QAAI;AACF,YAAM,aAAa,IAAI,gBAAgB;AACvC,YAAM,YAAY,WAAW,MAAM,WAAW,MAAM,GAAG,GAAI;AAE3D,YAAM,cAAc,IAAI,gBAAgB;AAExC,aAAO,QAAQ,UAAU,EAAE,QAAQ,CAAC,CAAC,KAAK,KAAK,MAAM;AACnD,YAAI,UAAU,QAAQ,UAAU,QAAW;AACzC,sBAAY,OAAO,KAAK,OAAO,KAAK,CAAC;AAAA,QACvC;AAAA,MACF,CAAC;AAED,YAAM,MAAM,GAAG,kBAAkB,YAAY,SAAS;AAEtD,YAAM,WAAW,MAAM,MAAM,KAAK;AAAA,QAChC,QAAQ;AAAA,QACR,QAAQ,WAAW;AAAA,MACrB,CAAC;AAED,mBAAa,SAAS;AAEtB,UAAI,CAAC,SAAS,IAAI;AAChB,cAAM,IAAI,MAAM,uBAAuB,SAAS,QAAQ;AAAA,MAC1D;AAAA,IACF,QAAE;AAAA,IAEF;AAAA,EACF;AACF;AAEA,IAAO,uBAAQ,IAAI,YAAY;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/requests.ts"],"sourcesContent":["/**\n * Safely read a Response/Request body with sensible defaults:\n * - clones the response/request to avoid consuming the original response/request\n * - Skips GET/HEAD\n * - Tries JSON first regardless of content-type\n * - Falls back to text and optionally parses when it \"looks\" like JSON\n */\nexport async function readBody<T extends Response | Request>(r: T): Promise<unknown> {\n // skip GET/HEAD requests (unchanged)\n const method = \"method\" in r ? r.method.toUpperCase() : undefined;\n if (method === \"GET\" || method === \"HEAD\") {\n return undefined;\n }\n\n // no body at all → undefined (unchanged)\n if (!(\"body\" in r) || r.body == null) {\n return undefined;\n }\n\n // 1) try JSON (unchanged)\n try {\n return await r.clone().json();\n } catch {\n // 2) try text (unchanged + your whitespace/JSON-heuristic)\n try {\n const text = await r.clone().text();\n const trimmed = text.trim();\n\n if (trimmed.length === 0) return text;\n\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return text;\n }\n }\n return text;\n } catch {\n // 3) FINAL FALLBACK: manual read that accepts string or bytes\n try {\n const c = r.clone();\n const stream: ReadableStream | null = c.body ?? null;\n if (!stream) return undefined;\n\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let out = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (typeof value === \"string\") {\n out += value; // accept string chunks\n } else {\n out += decoder.decode(value, { stream: true }); // bytes\n }\n }\n out += decoder.decode(); // flush\n\n const trimmed = out.trim();\n if (trimmed.length === 0) return out;\n\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return out;\n }\n }\n return out;\n } catch {\n return undefined; // same \"give up\" behavior you had\n }\n }\n }\n}\n"],"mappings":";AAOA,eAAsB,SAAuC,GAAwB;AAEnF,QAAM,SAAS,YAAY,IAAI,EAAE,OAAO,YAAY,IAAI;AACxD,MAAI,WAAW,SAAS,WAAW,QAAQ;AACzC,WAAO;AAAA,EACT;AAGA,MAAI,EAAE,UAAU,MAAM,EAAE,QAAQ,MAAM;AACpC,WAAO;AAAA,EACT;AAGA,MAAI;AACF,WAAO,MAAM,EAAE,MAAM,EAAE,KAAK;AAAA,EAC9B,QAAE;AAEA,QAAI;AACF,YAAM,OAAO,MAAM,EAAE,MAAM,EAAE,KAAK;AAClC,YAAM,UAAU,KAAK,KAAK;AAE1B,UAAI,QAAQ,WAAW;AAAG,eAAO;AAEjC,UAAI,QAAQ,WAAW,GAAG,KAAK,QAAQ,WAAW,GAAG,GAAG;AACtD,YAAI;AACF,iBAAO,KAAK,MAAM,OAAO;AAAA,QAC3B,QAAE;AACA,iBAAO;AAAA,QACT;AAAA,MACF;AACA,aAAO;AAAA,IACT,QAAE;AAEA,UAAI;AACF,cAAM,IAAI,EAAE,MAAM;AAClB,cAAM,SAAgC,EAAE,QAAQ;AAChD,YAAI,CAAC;AAAQ,iBAAO;AAEpB,cAAM,SAAS,OAAO,UAAU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