@copilotkit/shared
Version:
<img src="https://github.com/user-attachments/assets/0a6b64d9-e193-4940-a3f6-60334ac34084" alt="banner" style="border-radius: 12px; border: 2px solid #d6d4fa;" />
1,098 lines (1,067 loc) • 38.5 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
BANNER_ERROR_NAMES: () => BANNER_ERROR_NAMES,
COPILOTKIT_VERSION: () => COPILOTKIT_VERSION,
COPILOT_CLOUD_API_URL: () => COPILOT_CLOUD_API_URL,
COPILOT_CLOUD_CHAT_URL: () => COPILOT_CLOUD_CHAT_URL,
COPILOT_CLOUD_ERROR_NAMES: () => COPILOT_CLOUD_ERROR_NAMES,
COPILOT_CLOUD_PUBLIC_API_KEY_HEADER: () => COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,
COPILOT_CLOUD_VERSION: () => COPILOT_CLOUD_VERSION,
ConfigurationError: () => ConfigurationError,
ConsoleColors: () => ConsoleColors,
ConsoleStyles: () => ConsoleStyles,
CopilotKitAgentDiscoveryError: () => CopilotKitAgentDiscoveryError,
CopilotKitApiDiscoveryError: () => CopilotKitApiDiscoveryError,
CopilotKitError: () => CopilotKitError,
CopilotKitErrorCode: () => CopilotKitErrorCode,
CopilotKitLowLevelError: () => CopilotKitLowLevelError,
CopilotKitMisuseError: () => CopilotKitMisuseError,
CopilotKitRemoteEndpointDiscoveryError: () => CopilotKitRemoteEndpointDiscoveryError,
CopilotKitVersionMismatchError: () => CopilotKitVersionMismatchError,
ERROR_CONFIG: () => ERROR_CONFIG,
ERROR_NAMES: () => ERROR_NAMES,
ErrorVisibility: () => ErrorVisibility,
MissingPublicApiKeyError: () => MissingPublicApiKeyError,
ResolvedCopilotKitError: () => ResolvedCopilotKitError,
Severity: () => Severity,
TelemetryClient: () => TelemetryClient,
UpgradeRequiredError: () => UpgradeRequiredError,
actionParametersToJsonSchema: () => actionParametersToJsonSchema,
convertJsonSchemaToZodSchema: () => convertJsonSchemaToZodSchema,
dataToUUID: () => dataToUUID,
ensureStructuredError: () => ensureStructuredError,
executeConditions: () => executeConditions,
getPossibleVersionMismatch: () => getPossibleVersionMismatch,
getZodParameters: () => getZodParameters,
isMacOS: () => isMacOS,
isStructuredCopilotKitError: () => isStructuredCopilotKitError,
isTelemetryDisabled: () => isTelemetryDisabled,
isValidUUID: () => isValidUUID,
jsonSchemaToActionParameters: () => jsonSchemaToActionParameters,
logCopilotKitPlatformMessage: () => logCopilotKitPlatformMessage,
logStyled: () => logStyled,
parseJson: () => parseJson,
publicApiKeyRequired: () => publicApiKeyRequired,
randomId: () => randomId,
randomUUID: () => randomUUID,
readBody: () => readBody,
styledConsole: () => styledConsole,
tryMap: () => tryMap
});
module.exports = __toCommonJS(src_exports);
// src/utils/conditions.ts
function executeConditions({
conditions,
value
}) {
if (!(conditions == null ? void 0 : conditions.length))
return true;
return conditions.every((condition) => executeCondition(condition, value));
}
function executeCondition(condition, value) {
const targetValue = condition.path ? getValueFromPath(value, condition.path) : value;
switch (condition.rule) {
case "AND":
return condition.conditions.every((c) => executeCondition(c, value));
case "OR":
return condition.conditions.some((c) => executeCondition(c, value));
case "NOT":
return !condition.conditions.every((c) => executeCondition(c, value));
case "EQUALS":
return targetValue === condition.value;
case "NOT_EQUALS":
return targetValue !== condition.value;
case "GREATER_THAN":
return targetValue > condition.value;
case "LESS_THAN":
return targetValue < condition.value;
case "CONTAINS":
return Array.isArray(targetValue) && targetValue.includes(condition.value);
case "NOT_CONTAINS":
return Array.isArray(targetValue) && !targetValue.includes(condition.value);
case "MATCHES":
return new RegExp(condition.value).test(String(targetValue));
case "STARTS_WITH":
return String(targetValue).startsWith(condition.value);
case "ENDS_WITH":
return String(targetValue).endsWith(condition.value);
case "EXISTS":
return targetValue !== void 0 && targetValue !== null;
case "NOT_EXISTS":
return targetValue === void 0 || targetValue === null;
}
}
function getValueFromPath(obj, path) {
return path.split(".").reduce((acc, part) => acc == null ? void 0 : acc[part], obj);
}
// src/utils/console-styling.ts
var ConsoleColors = {
/** Primary brand blue - for titles and links */
primary: "#007acc",
/** Success green - for positive messaging */
success: "#22c55e",
/** Purple - for feature highlights */
feature: "#a855f7",
/** Red - for calls-to-action */
cta: "#ef4444",
/** Cyan - for closing statements */
info: "#06b6d4",
/** Inherit console default - for body text */
inherit: "inherit",
/** Warning style */
warning: "#f59e0b"
};
var ConsoleStyles = {
/** Large header style */
header: `color: ${ConsoleColors.warning}; font-weight: bold; font-size: 16px;`,
/** Section header style */
section: `color: ${ConsoleColors.success}; font-weight: bold;`,
/** Feature highlight style */
highlight: `color: ${ConsoleColors.feature}; font-weight: bold;`,
/** Call-to-action style */
cta: `color: ${ConsoleColors.success}; font-weight: bold;`,
/** Info style */
info: `color: ${ConsoleColors.info}; font-weight: bold;`,
/** Link style */
link: `color: ${ConsoleColors.primary}; text-decoration: underline;`,
/** Body text - inherits console theme */
body: `color: ${ConsoleColors.inherit};`,
/** Warning style */
warning: `color: ${ConsoleColors.cta}; font-weight: bold;`
};
function logCopilotKitPlatformMessage() {
console.log(
`%cCopilotKit Warning%c
useCopilotChatHeadless_c provides full compatibility with CopilotKit's newly released Headless UI feature set. To enable this premium feature, add your public license key, available for free at:
%chttps://cloud.copilotkit.ai%c
Alternatively, useCopilotChat is available for basic programmatic control, and does not require an API key.
To learn more about premium features, read the documentation here:
%chttps://docs.copilotkit.ai/premium%c`,
ConsoleStyles.header,
ConsoleStyles.body,
ConsoleStyles.cta,
ConsoleStyles.body,
ConsoleStyles.link,
ConsoleStyles.body
);
}
function publicApiKeyRequired(feature) {
console.log(
`
%cCopilotKit Warning%c
In order to use ${feature}, you need to add your CopilotKit API key, available for free at https://cloud.copilotkit.ai.
`.trim(),
ConsoleStyles.header,
ConsoleStyles.body
);
}
function logStyled(template, styles) {
console.log(template, ...styles);
}
var styledConsole = {
/** Log a success message */
success: (message) => logStyled(`%c\u2705 ${message}`, [ConsoleStyles.section]),
/** Log an info message */
info: (message) => logStyled(`%c\u2139\uFE0F ${message}`, [ConsoleStyles.info]),
/** Log a feature highlight */
feature: (message) => logStyled(`%c\u2728 ${message}`, [ConsoleStyles.highlight]),
/** Log a call-to-action */
cta: (message) => logStyled(`%c\u{1F680} ${message}`, [ConsoleStyles.cta]),
/** Log the CopilotKit platform promotion */
logCopilotKitPlatformMessage,
/** Log a `publicApiKeyRequired` warning */
publicApiKeyRequired
};
// src/utils/errors.ts
var import_graphql = require("graphql");
var Severity = /* @__PURE__ */ ((Severity2) => {
Severity2["CRITICAL"] = "critical";
Severity2["WARNING"] = "warning";
Severity2["INFO"] = "info";
return Severity2;
})(Severity || {});
var ErrorVisibility = /* @__PURE__ */ ((ErrorVisibility2) => {
ErrorVisibility2["BANNER"] = "banner";
ErrorVisibility2["TOAST"] = "toast";
ErrorVisibility2["SILENT"] = "silent";
ErrorVisibility2["DEV_ONLY"] = "dev_only";
return ErrorVisibility2;
})(ErrorVisibility || {});
var ERROR_NAMES = {
COPILOT_ERROR: "CopilotError",
COPILOT_API_DISCOVERY_ERROR: "CopilotApiDiscoveryError",
COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR: "CopilotKitRemoteEndpointDiscoveryError",
COPILOT_KIT_AGENT_DISCOVERY_ERROR: "CopilotKitAgentDiscoveryError",
COPILOT_KIT_LOW_LEVEL_ERROR: "CopilotKitLowLevelError",
COPILOT_KIT_VERSION_MISMATCH_ERROR: "CopilotKitVersionMismatchError",
RESOLVED_COPILOT_KIT_ERROR: "ResolvedCopilotKitError",
CONFIGURATION_ERROR: "ConfigurationError",
MISSING_PUBLIC_API_KEY_ERROR: "MissingPublicApiKeyError",
UPGRADE_REQUIRED_ERROR: "UpgradeRequiredError"
};
var BANNER_ERROR_NAMES = [
ERROR_NAMES.CONFIGURATION_ERROR,
ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR,
ERROR_NAMES.UPGRADE_REQUIRED_ERROR,
ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR,
ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR,
ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR
];
var COPILOT_CLOUD_ERROR_NAMES = BANNER_ERROR_NAMES;
var CopilotKitErrorCode = /* @__PURE__ */ ((CopilotKitErrorCode2) => {
CopilotKitErrorCode2["NETWORK_ERROR"] = "NETWORK_ERROR";
CopilotKitErrorCode2["NOT_FOUND"] = "NOT_FOUND";
CopilotKitErrorCode2["AGENT_NOT_FOUND"] = "AGENT_NOT_FOUND";
CopilotKitErrorCode2["API_NOT_FOUND"] = "API_NOT_FOUND";
CopilotKitErrorCode2["REMOTE_ENDPOINT_NOT_FOUND"] = "REMOTE_ENDPOINT_NOT_FOUND";
CopilotKitErrorCode2["AUTHENTICATION_ERROR"] = "AUTHENTICATION_ERROR";
CopilotKitErrorCode2["MISUSE"] = "MISUSE";
CopilotKitErrorCode2["UNKNOWN"] = "UNKNOWN";
CopilotKitErrorCode2["VERSION_MISMATCH"] = "VERSION_MISMATCH";
CopilotKitErrorCode2["CONFIGURATION_ERROR"] = "CONFIGURATION_ERROR";
CopilotKitErrorCode2["MISSING_PUBLIC_API_KEY_ERROR"] = "MISSING_PUBLIC_API_KEY_ERROR";
CopilotKitErrorCode2["UPGRADE_REQUIRED_ERROR"] = "UPGRADE_REQUIRED_ERROR";
return CopilotKitErrorCode2;
})(CopilotKitErrorCode || {});
var BASE_URL = "https://docs.copilotkit.ai";
var getSeeMoreMarkdown = (link) => `See more: [${link}](${link})`;
var ERROR_CONFIG = {
["NETWORK_ERROR" /* NETWORK_ERROR */]: {
statusCode: 503,
troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,
visibility: "banner" /* BANNER */,
severity: "critical" /* CRITICAL */
},
["NOT_FOUND" /* NOT_FOUND */]: {
statusCode: 404,
troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,
visibility: "banner" /* BANNER */,
severity: "critical" /* CRITICAL */
},
["AGENT_NOT_FOUND" /* AGENT_NOT_FOUND */]: {
statusCode: 500,
troubleshootingUrl: `${BASE_URL}/coagents/troubleshooting/common-issues#i-am-getting-agent-not-found-error`,
visibility: "banner" /* BANNER */,
severity: "critical" /* CRITICAL */
},
["API_NOT_FOUND" /* API_NOT_FOUND */]: {
statusCode: 404,
troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`,
visibility: "banner" /* BANNER */,
severity: "critical" /* CRITICAL */
},
["REMOTE_ENDPOINT_NOT_FOUND" /* REMOTE_ENDPOINT_NOT_FOUND */]: {
statusCode: 404,
troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#i-am-getting-copilotkits-remote-endpoint-not-found-error`,
visibility: "banner" /* BANNER */,
severity: "critical" /* CRITICAL */
},
["AUTHENTICATION_ERROR" /* AUTHENTICATION_ERROR */]: {
statusCode: 401,
troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#authentication-errors`,
visibility: "banner" /* BANNER */,
severity: "critical" /* CRITICAL */
},
["MISUSE" /* MISUSE */]: {
statusCode: 400,
troubleshootingUrl: null,
visibility: "dev_only" /* DEV_ONLY */,
severity: "warning" /* WARNING */
},
["UNKNOWN" /* UNKNOWN */]: {
statusCode: 500,
visibility: "toast" /* TOAST */,
severity: "critical" /* CRITICAL */
},
["CONFIGURATION_ERROR" /* CONFIGURATION_ERROR */]: {
statusCode: 400,
troubleshootingUrl: null,
severity: "warning" /* WARNING */,
visibility: "banner" /* BANNER */
},
["MISSING_PUBLIC_API_KEY_ERROR" /* MISSING_PUBLIC_API_KEY_ERROR */]: {
statusCode: 400,
troubleshootingUrl: null,
severity: "critical" /* CRITICAL */,
visibility: "banner" /* BANNER */
},
["UPGRADE_REQUIRED_ERROR" /* UPGRADE_REQUIRED_ERROR */]: {
statusCode: 402,
troubleshootingUrl: null,
severity: "warning" /* WARNING */,
visibility: "banner" /* BANNER */
},
["VERSION_MISMATCH" /* VERSION_MISMATCH */]: {
statusCode: 400,
troubleshootingUrl: null,
visibility: "dev_only" /* DEV_ONLY */,
severity: "info" /* INFO */
}
};
var CopilotKitError = class extends import_graphql.GraphQLError {
constructor({
message = "Unknown error occurred",
code,
severity,
visibility
}) {
const name = ERROR_NAMES.COPILOT_ERROR;
const config = ERROR_CONFIG[code];
const { statusCode } = config;
const resolvedVisibility = visibility ?? config.visibility ?? "toast" /* TOAST */;
const resolvedSeverity = severity ?? ("severity" in config ? config.severity : void 0);
super(message, {
extensions: {
name,
statusCode,
code,
visibility: resolvedVisibility,
severity: resolvedSeverity,
troubleshootingUrl: "troubleshootingUrl" in config ? config.troubleshootingUrl : null,
originalError: {
message,
stack: new Error().stack
}
}
});
this.code = code;
this.name = name;
this.statusCode = statusCode;
this.severity = resolvedSeverity;
this.visibility = resolvedVisibility;
}
};
var CopilotKitMisuseError = class extends CopilotKitError {
constructor({
message,
code = "MISUSE" /* MISUSE */
}) {
const docsLink = "troubleshootingUrl" in ERROR_CONFIG[code] && ERROR_CONFIG[code].troubleshootingUrl ? getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl) : null;
const finalMessage = docsLink ? `${message}.
${docsLink}` : message;
super({ message: finalMessage, code });
this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;
}
};
var getVersionMismatchErrorMessage = ({
reactCoreVersion,
runtimeVersion,
runtimeClientGqlVersion
}) => `Version mismatch detected: @copilotkit/runtime@${runtimeVersion ?? ""} is not compatible with @copilotkit/react-core@${reactCoreVersion} and @copilotkit/runtime-client-gql@${runtimeClientGqlVersion}. Please ensure all installed copilotkit packages are on the same version.`;
var CopilotKitVersionMismatchError = class extends CopilotKitError {
constructor({
reactCoreVersion,
runtimeVersion,
runtimeClientGqlVersion
}) {
const code = "VERSION_MISMATCH" /* VERSION_MISMATCH */;
super({
message: getVersionMismatchErrorMessage({
reactCoreVersion,
runtimeVersion,
runtimeClientGqlVersion
}),
code
});
this.name = ERROR_NAMES.COPILOT_KIT_VERSION_MISMATCH_ERROR;
}
};
var CopilotKitApiDiscoveryError = class extends CopilotKitError {
constructor(params = {}) {
const url = params.url ?? "";
let operationSuffix = "";
if (url == null ? void 0 : url.includes("/info"))
operationSuffix = `when fetching CopilotKit info`;
else if (url.includes("/actions/execute"))
operationSuffix = `when attempting to execute actions.`;
else if (url.includes("/agents/state"))
operationSuffix = `when attempting to get agent state.`;
else if (url.includes("/agents/execute"))
operationSuffix = `when attempting to execute agent(s).`;
const message = params.message ?? (params.url ? `Failed to find CopilotKit API endpoint at url ${params.url} ${operationSuffix}` : `Failed to find CopilotKit API endpoint.`);
const code = params.code ?? "API_NOT_FOUND" /* API_NOT_FOUND */;
const errorMessage = `${message}.
${getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl)}`;
super({ message: errorMessage, code });
this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;
}
};
var CopilotKitRemoteEndpointDiscoveryError = class extends CopilotKitApiDiscoveryError {
constructor(params) {
const message = (params == null ? void 0 : params.message) ?? ((params == null ? void 0 : params.url) ? `Failed to find or contact remote endpoint at url ${params.url}` : "Failed to find or contact remote endpoint");
const code = "REMOTE_ENDPOINT_NOT_FOUND" /* REMOTE_ENDPOINT_NOT_FOUND */;
super({ message, code });
this.name = ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR;
}
};
var CopilotKitAgentDiscoveryError = class extends CopilotKitError {
constructor(params) {
const { agentName, availableAgents } = params;
const code = "AGENT_NOT_FOUND" /* AGENT_NOT_FOUND */;
const seeMore = getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl);
let message;
if (availableAgents.length) {
const agentList = availableAgents.map((agent) => agent.name).join(", ");
if (agentName) {
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.
${seeMore}`;
} else {
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.
${seeMore}`;
}
} else {
message = `${agentName ? `Agent '${agentName}'` : "The requested agent"} was not found. Please set up at least one agent before proceeding. ${seeMore}`;
}
super({ message, code });
this.name = ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR;
}
};
var CopilotKitLowLevelError = class extends CopilotKitError {
constructor({ error, url, message }) {
let code = "NETWORK_ERROR" /* NETWORK_ERROR */;
const errorCode = error.code;
const errorMessage = message ?? resolveLowLevelErrorMessage({ errorCode, url });
super({ message: errorMessage, code });
this.name = ERROR_NAMES.COPILOT_KIT_LOW_LEVEL_ERROR;
}
};
var ResolvedCopilotKitError = class extends CopilotKitError {
constructor({
status,
message,
code,
isRemoteEndpoint,
url
}) {
let resolvedCode = code;
if (!resolvedCode) {
switch (status) {
case 400:
throw new CopilotKitApiDiscoveryError({ message, url });
case 404:
throw isRemoteEndpoint ? new CopilotKitRemoteEndpointDiscoveryError({ message, url }) : new CopilotKitApiDiscoveryError({ message, url });
default:
resolvedCode = "UNKNOWN" /* UNKNOWN */;
break;
}
}
super({ message, code: resolvedCode });
this.name = ERROR_NAMES.RESOLVED_COPILOT_KIT_ERROR;
}
};
var ConfigurationError = class extends CopilotKitError {
constructor(message) {
super({ message, code: "CONFIGURATION_ERROR" /* CONFIGURATION_ERROR */ });
this.name = ERROR_NAMES.CONFIGURATION_ERROR;
this.severity = "warning" /* WARNING */;
}
};
var MissingPublicApiKeyError = class extends ConfigurationError {
constructor(message) {
super(message);
this.name = ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR;
this.severity = "critical" /* CRITICAL */;
}
};
var UpgradeRequiredError = class extends ConfigurationError {
constructor(message) {
super(message);
this.name = ERROR_NAMES.UPGRADE_REQUIRED_ERROR;
this.severity = "warning" /* WARNING */;
}
};
function isStructuredCopilotKitError(error) {
var _a;
return error instanceof CopilotKitError || error instanceof CopilotKitLowLevelError || (error == null ? void 0 : error.name) && error.name.includes("CopilotKit") || ((_a = error == null ? void 0 : error.extensions) == null ? void 0 : _a.code) !== void 0;
}
function ensureStructuredError(error, converter) {
return isStructuredCopilotKitError(error) ? error : converter(error);
}
async function getPossibleVersionMismatch({
runtimeVersion,
runtimeClientGqlVersion
}) {
if (!runtimeVersion || runtimeVersion === "" || !runtimeClientGqlVersion)
return;
if (COPILOTKIT_VERSION !== runtimeVersion || COPILOTKIT_VERSION !== runtimeClientGqlVersion || runtimeVersion !== runtimeClientGqlVersion) {
return {
runtimeVersion,
runtimeClientGqlVersion,
reactCoreVersion: COPILOTKIT_VERSION,
message: getVersionMismatchErrorMessage({
runtimeVersion,
runtimeClientGqlVersion,
reactCoreVersion: COPILOTKIT_VERSION
})
};
}
return;
}
var resolveLowLevelErrorMessage = ({ errorCode, url }) => {
const troubleshootingLink = ERROR_CONFIG["NETWORK_ERROR" /* NETWORK_ERROR */].troubleshootingUrl;
const genericMessage = (description = `Failed to fetch from url ${url}.`) => `${description}.
Possible reasons:
- -The server may have an error preventing it from returning a response (Check the server logs for more info).
- -The server might be down or unreachable
- -There might be a network issue (e.g., DNS failure, connection timeout)
- -The URL might be incorrect
- -The server is not running on the specified port
${getSeeMoreMarkdown(troubleshootingLink)}`;
if (url.includes("/info"))
return genericMessage(`Failed to fetch CopilotKit agents/action information from url ${url}.`);
if (url.includes("/actions/execute"))
return genericMessage(`Fetch call to ${url} to execute actions failed.`);
if (url.includes("/agents/state"))
return genericMessage(`Fetch call to ${url} to get agent state failed.`);
if (url.includes("/agents/execute"))
return genericMessage(`Fetch call to ${url} to execute agent(s) failed.`);
switch (errorCode) {
case "ECONNREFUSED":
return `Connection to ${url} was refused. Ensure the server is running and accessible.
${getSeeMoreMarkdown(troubleshootingLink)}`;
case "ENOTFOUND":
return `The server on ${url} could not be found. Check the URL or your network configuration.
${getSeeMoreMarkdown(ERROR_CONFIG["NOT_FOUND" /* NOT_FOUND */].troubleshootingUrl)}`;
case "ETIMEDOUT":
return `The connection to ${url} timed out. The server might be overloaded or taking too long to respond.
${getSeeMoreMarkdown(troubleshootingLink)}`;
default:
return;
}
};
// src/utils/json-schema.ts
var import_zod = require("zod");
function actionParametersToJsonSchema(actionParameters) {
let parameters = {};
for (let parameter of actionParameters || []) {
parameters[parameter.name] = convertAttribute(parameter);
}
let requiredParameterNames = [];
for (let arg of actionParameters || []) {
if (arg.required !== false) {
requiredParameterNames.push(arg.name);
}
}
return {
type: "object",
properties: parameters,
required: requiredParameterNames
};
}
function jsonSchemaToActionParameters(jsonSchema) {
if (jsonSchema.type !== "object" || !jsonSchema.properties) {
return [];
}
const parameters = [];
const requiredFields = jsonSchema.required || [];
for (const [name, schema] of Object.entries(jsonSchema.properties)) {
const parameter = convertJsonSchemaToParameter(name, schema, requiredFields.includes(name));
parameters.push(parameter);
}
return parameters;
}
function convertJsonSchemaToParameter(name, schema, isRequired) {
const baseParameter = {
name,
description: schema.description
};
if (!isRequired) {
baseParameter.required = false;
}
switch (schema.type) {
case "string":
return {
...baseParameter,
type: "string",
...schema.enum && { enum: schema.enum }
};
case "number":
case "boolean":
return {
...baseParameter,
type: schema.type
};
case "object":
if (schema.properties) {
const attributes = [];
const requiredFields = schema.required || [];
for (const [propName, propSchema] of Object.entries(schema.properties)) {
attributes.push(
convertJsonSchemaToParameter(propName, propSchema, requiredFields.includes(propName))
);
}
return {
...baseParameter,
type: "object",
attributes
};
}
return {
...baseParameter,
type: "object"
};
case "array":
if (schema.items.type === "object" && "properties" in schema.items) {
const attributes = [];
const requiredFields = schema.items.required || [];
for (const [propName, propSchema] of Object.entries(schema.items.properties || {})) {
attributes.push(
convertJsonSchemaToParameter(propName, propSchema, requiredFields.includes(propName))
);
}
return {
...baseParameter,
type: "object[]",
attributes
};
} else if (schema.items.type === "array") {
throw new Error("Nested arrays are not supported");
} else {
return {
...baseParameter,
type: `${schema.items.type}[]`
};
}
default:
return {
...baseParameter,
type: "string"
};
}
}
function convertAttribute(attribute) {
var _a, _b, _c;
switch (attribute.type) {
case "string":
return {
type: "string",
description: attribute.description,
...attribute.enum && { enum: attribute.enum }
};
case "number":
case "boolean":
return {
type: attribute.type,
description: attribute.description
};
case "object":
case "object[]":
const properties = (_a = attribute.attributes) == null ? void 0 : _a.reduce(
(acc, attr) => {
acc[attr.name] = convertAttribute(attr);
return acc;
},
{}
);
const required = (_b = attribute.attributes) == null ? void 0 : _b.filter((attr) => attr.required !== false).map((attr) => attr.name);
if (attribute.type === "object[]") {
return {
type: "array",
items: {
type: "object",
...properties && { properties },
...required && required.length > 0 && { required }
},
description: attribute.description
};
}
return {
type: "object",
description: attribute.description,
...properties && { properties },
...required && required.length > 0 && { required }
};
default:
if ((_c = attribute.type) == null ? void 0 : _c.endsWith("[]")) {
const itemType = attribute.type.slice(0, -2);
return {
type: "array",
items: { type: itemType },
description: attribute.description
};
}
return {
type: "string",
description: attribute.description
};
}
}
function convertJsonSchemaToZodSchema(jsonSchema, required) {
if (jsonSchema.type === "object") {
const spec = {};
if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {
return !required ? import_zod.z.object(spec).optional() : import_zod.z.object(spec);
}
for (const [key, value] of Object.entries(jsonSchema.properties)) {
spec[key] = convertJsonSchemaToZodSchema(
value,
jsonSchema.required ? jsonSchema.required.includes(key) : false
);
}
let schema = import_zod.z.object(spec).describe(jsonSchema.description);
return required ? schema : schema.optional();
} else if (jsonSchema.type === "string") {
let schema = import_zod.z.string().describe(jsonSchema.description);
return required ? schema : schema.optional();
} else if (jsonSchema.type === "number") {
let schema = import_zod.z.number().describe(jsonSchema.description);
return required ? schema : schema.optional();
} else if (jsonSchema.type === "boolean") {
let schema = import_zod.z.boolean().describe(jsonSchema.description);
return required ? schema : schema.optional();
} else if (jsonSchema.type === "array") {
let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);
let schema = import_zod.z.array(itemSchema).describe(jsonSchema.description);
return required ? schema : schema.optional();
}
throw new Error("Invalid JSON schema");
}
function getZodParameters(parameters) {
if (!parameters)
return import_zod.z.object({});
const jsonParams = actionParametersToJsonSchema(parameters);
return convertJsonSchemaToZodSchema(jsonParams, true);
}
// src/utils/random-id.ts
var import_uuid = require("uuid");
function randomId() {
return "ck-" + (0, import_uuid.v4)();
}
function randomUUID() {
return (0, import_uuid.v4)();
}
function toSerializable(value) {
if (typeof value === "function") {
return value.toString();
}
if (Array.isArray(value)) {
return value.map(toSerializable);
}
if (value !== null && typeof value === "object") {
const result = {};
for (const key of Object.keys(value)) {
result[key] = toSerializable(value[key]);
}
return result;
}
return value;
}
function dataToUUID(input, namespace) {
const BASE_NAMESPACE = "e4b01160-ff74-4c6e-9b27-d53cd930fe8e";
const boundNamespace = namespace ? (0, import_uuid.v5)(namespace, BASE_NAMESPACE) : BASE_NAMESPACE;
const stringInput = typeof input === "string" ? input : JSON.stringify(toSerializable(input));
return (0, import_uuid.v5)(stringInput, boundNamespace);
}
function isValidUUID(uuid) {
return (0, import_uuid.validate)(uuid);
}
// src/utils/requests.ts
async function readBody(r) {
const method = "method" in r ? r.method.toUpperCase() : void 0;
if (method === "GET" || method === "HEAD") {
return void 0;
}
if (!("body" in r) || r.body == null) {
return void 0;
}
try {
return await r.clone().json();
} catch {
try {
const text = await r.clone().text();
const trimmed = text.trim();
if (trimmed.length === 0)
return text;
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
try {
return JSON.parse(trimmed);
} catch {
return text;
}
}
return text;
} catch {
try {
const c = r.clone();
const stream = c.body ?? null;
if (!stream)
return void 0;
const reader = stream.getReader();
const decoder = new TextDecoder();
let out = "";
while (true) {
const { done, value } = await reader.read();
if (done)
break;
if (typeof value === "string") {
out += value;
} else {
out += decoder.decode(value, { stream: true });
}
}
out += decoder.decode();
const trimmed = out.trim();
if (trimmed.length === 0)
return out;
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
try {
return JSON.parse(trimmed);
} catch {
return out;
}
}
return out;
} catch {
return void 0;
}
}
}
}
// src/utils/index.ts
function parseJson(json, fallback = "unset") {
try {
return JSON.parse(json);
} catch (e) {
return fallback === "unset" ? null : fallback;
}
}
function tryMap(items, callback) {
return items.reduce((acc, item, index, array) => {
try {
acc.push(callback(item, index, array));
} catch (error) {
console.error(error);
}
return acc;
}, []);
}
function isMacOS() {
return /Mac|iMac|Macintosh/i.test(navigator.userAgent);
}
// src/constants/index.ts
var COPILOT_CLOUD_API_URL = "https://api.cloud.copilotkit.ai";
var COPILOT_CLOUD_VERSION = "v1";
var COPILOT_CLOUD_CHAT_URL = `${COPILOT_CLOUD_API_URL}/copilotkit/${COPILOT_CLOUD_VERSION}`;
var COPILOT_CLOUD_PUBLIC_API_KEY_HEADER = "X-CopilotCloud-Public-Api-Key";
// src/telemetry/telemetry-client.ts
var import_analytics_node = require("@segment/analytics-node");
// src/telemetry/utils.ts
var import_chalk = __toESM(require("chalk"));
function flattenObject(obj, parentKey = "", res = {}) {
for (let key in obj) {
const propName = parentKey ? `${parentKey}.${key}` : key;
if (typeof obj[key] === "object" && obj[key] !== null) {
flattenObject(obj[key], propName, res);
} else {
res[propName] = obj[key];
}
}
return res;
}
// src/telemetry/telemetry-client.ts
var import_uuid2 = require("uuid");
// package.json
var version = "1.50.1";
// src/telemetry/scarf-client.ts
var SCARF_BASE_URL = `https://copilotkit.gateway.scarf.sh/${version}`;
var ScarfClient = class {
constructor() {
}
async logEvent(properties) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 3e3);
const queryParams = new URLSearchParams();
Object.entries(properties).forEach(([key, value]) => {
if (value !== null && value !== void 0) {
queryParams.append(key, String(value));
}
});
const url = `${SCARF_BASE_URL}?${queryParams.toString()}`;
const response = await fetch(url, {
method: "GET",
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
} catch {
}
}
};
var scarf_client_default = new ScarfClient();
// src/telemetry/telemetry-client.ts
function isTelemetryDisabled() {
return process.env.COPILOTKIT_TELEMETRY_DISABLED === "true" || process.env.COPILOTKIT_TELEMETRY_DISABLED === "1" || process.env.DO_NOT_TRACK === "true" || process.env.DO_NOT_TRACK === "1";
}
var TelemetryClient = class {
constructor({
packageName,
packageVersion,
telemetryDisabled,
telemetryBaseUrl,
sampleRate
}) {
this.globalProperties = {};
this.cloudConfiguration = null;
this.telemetryDisabled = false;
this.sampleRate = 0.05;
this.anonymousId = `anon_${(0, import_uuid2.v4)()}`;
this.packageName = packageName;
this.packageVersion = packageVersion;
this.telemetryDisabled = telemetryDisabled || isTelemetryDisabled();
if (this.telemetryDisabled) {
return;
}
this.setSampleRate(sampleRate);
const writeKey = process.env.COPILOTKIT_SEGMENT_WRITE_KEY || "n7XAZtQCGS2v1vvBy3LgBCv2h3Y8whja";
this.segment = new import_analytics_node.Analytics({
writeKey
});
this.setGlobalProperties({
"copilotkit.package.name": packageName,
"copilotkit.package.version": packageVersion
});
}
shouldSendEvent() {
const randomNumber = Math.random();
return randomNumber < this.sampleRate;
}
async capture(event, properties) {
if (!this.shouldSendEvent() || !this.segment) {
return;
}
const flattenedProperties = flattenObject(properties);
const propertiesWithGlobal = {
...this.globalProperties,
...flattenedProperties
};
const orderedPropertiesWithGlobal = Object.keys(propertiesWithGlobal).sort().reduce(
(obj, key) => {
obj[key] = propertiesWithGlobal[key];
return obj;
},
{}
);
this.segment.track({
anonymousId: this.anonymousId,
event,
properties: { ...orderedPropertiesWithGlobal }
});
await scarf_client_default.logEvent({
event
});
}
setGlobalProperties(properties) {
const flattenedProperties = flattenObject(properties);
this.globalProperties = { ...this.globalProperties, ...flattenedProperties };
}
setCloudConfiguration(properties) {
this.cloudConfiguration = properties;
this.setGlobalProperties({
cloud: {
publicApiKey: properties.publicApiKey,
baseUrl: properties.baseUrl
}
});
}
setSampleRate(sampleRate) {
let _sampleRate;
_sampleRate = sampleRate ?? 0.05;
if (process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE) {
_sampleRate = parseFloat(process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE);
}
if (_sampleRate < 0 || _sampleRate > 1) {
throw new Error("Sample rate must be between 0 and 1");
}
this.sampleRate = _sampleRate;
this.setGlobalProperties({
sampleRate: this.sampleRate,
sampleRateAdjustmentFactor: 1 - this.sampleRate,
sampleWeight: 1 / this.sampleRate
});
}
};
// src/index.ts
var COPILOTKIT_VERSION = version;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BANNER_ERROR_NAMES,
COPILOTKIT_VERSION,
COPILOT_CLOUD_API_URL,
COPILOT_CLOUD_CHAT_URL,
COPILOT_CLOUD_ERROR_NAMES,
COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,
COPILOT_CLOUD_VERSION,
ConfigurationError,
ConsoleColors,
ConsoleStyles,
CopilotKitAgentDiscoveryError,
CopilotKitApiDiscoveryError,
CopilotKitError,
CopilotKitErrorCode,
CopilotKitLowLevelError,
CopilotKitMisuseError,
CopilotKitRemoteEndpointDiscoveryError,
CopilotKitVersionMismatchError,
ERROR_CONFIG,
ERROR_NAMES,
ErrorVisibility,
MissingPublicApiKeyError,
ResolvedCopilotKitError,
Severity,
TelemetryClient,
UpgradeRequiredError,
actionParametersToJsonSchema,
convertJsonSchemaToZodSchema,
dataToUUID,
ensureStructuredError,
executeConditions,
getPossibleVersionMismatch,
getZodParameters,
isMacOS,
isStructuredCopilotKitError,
isTelemetryDisabled,
isValidUUID,
jsonSchemaToActionParameters,
logCopilotKitPlatformMessage,
logStyled,
parseJson,
publicApiKeyRequired,
randomId,
randomUUID,
readBody,
styledConsole,
tryMap
});
//# sourceMappingURL=index.js.map