@copilotkit/shared
Version:
<div align="center"> <a href="https://copilotkit.ai" target="_blank"> <img src="https://github.com/copilotkit/copilotkit/raw/main/assets/banner.png" alt="CopilotKit Logo"> </a>
588 lines (568 loc) • 21.3 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/utils/index.ts
var utils_exports = {};
__export(utils_exports, {
COPILOT_CLOUD_ERROR_NAMES: () => COPILOT_CLOUD_ERROR_NAMES,
ConfigurationError: () => ConfigurationError,
CopilotKitAgentDiscoveryError: () => CopilotKitAgentDiscoveryError,
CopilotKitApiDiscoveryError: () => CopilotKitApiDiscoveryError,
CopilotKitError: () => CopilotKitError,
CopilotKitErrorCode: () => CopilotKitErrorCode,
CopilotKitLowLevelError: () => CopilotKitLowLevelError,
CopilotKitMisuseError: () => CopilotKitMisuseError,
CopilotKitRemoteEndpointDiscoveryError: () => CopilotKitRemoteEndpointDiscoveryError,
CopilotKitVersionMismatchError: () => CopilotKitVersionMismatchError,
ERROR_CONFIG: () => ERROR_CONFIG,
ERROR_NAMES: () => ERROR_NAMES,
MissingPublicApiKeyError: () => MissingPublicApiKeyError,
ResolvedCopilotKitError: () => ResolvedCopilotKitError,
Severity: () => Severity,
UpgradeRequiredError: () => UpgradeRequiredError,
actionParametersToJsonSchema: () => actionParametersToJsonSchema,
convertJsonSchemaToZodSchema: () => convertJsonSchemaToZodSchema,
dataToUUID: () => dataToUUID,
executeConditions: () => executeConditions,
getPossibleVersionMismatch: () => getPossibleVersionMismatch,
isValidUUID: () => isValidUUID,
parseJson: () => parseJson,
randomId: () => randomId,
randomUUID: () => randomUUID,
tryMap: () => tryMap
});
module.exports = __toCommonJS(utils_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/errors.ts
var import_graphql = require("graphql");
// package.json
var version = "1.8.9";
// src/index.ts
var COPILOTKIT_VERSION = version;
// src/utils/errors.ts
var Severity = /* @__PURE__ */ ((Severity2) => {
Severity2["Error"] = "error";
return Severity2;
})(Severity || {});
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 COPILOT_CLOUD_ERROR_NAMES = [
ERROR_NAMES.CONFIGURATION_ERROR,
ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR,
ERROR_NAMES.UPGRADE_REQUIRED_ERROR
];
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["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`
},
["NOT_FOUND" /* NOT_FOUND */]: {
statusCode: 404,
troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`
},
["AGENT_NOT_FOUND" /* AGENT_NOT_FOUND */]: {
statusCode: 500,
troubleshootingUrl: `${BASE_URL}/coagents/troubleshooting/common-issues#i-am-getting-agent-not-found-error`
},
["API_NOT_FOUND" /* API_NOT_FOUND */]: {
statusCode: 404,
troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found`
},
["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`
},
["MISUSE" /* MISUSE */]: {
statusCode: 400,
troubleshootingUrl: null
},
["UNKNOWN" /* UNKNOWN */]: {
statusCode: 500
},
["CONFIGURATION_ERROR" /* CONFIGURATION_ERROR */]: {
statusCode: 400,
troubleshootingUrl: null,
severity: "error" /* Error */
},
["MISSING_PUBLIC_API_KEY_ERROR" /* MISSING_PUBLIC_API_KEY_ERROR */]: {
statusCode: 400,
troubleshootingUrl: null,
severity: "error" /* Error */
},
["UPGRADE_REQUIRED_ERROR" /* UPGRADE_REQUIRED_ERROR */]: {
statusCode: 402,
troubleshootingUrl: null,
severity: "error" /* Error */
},
["VERSION_MISMATCH" /* VERSION_MISMATCH */]: {
statusCode: 400,
troubleshootingUrl: null
}
};
var CopilotKitError = class extends import_graphql.GraphQLError {
constructor({
message = "Unknown error occurred",
code,
severity
}) {
const name = ERROR_NAMES.COPILOT_ERROR;
const { statusCode } = ERROR_CONFIG[code];
super(message, {
extensions: {
name,
statusCode
}
});
this.code = code;
this.name = name;
this.statusCode = statusCode;
this.severity = severity;
}
};
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 */;
let message = "Failed to find any agents.";
const configMessage = "Please verify the agent name exists and is properly configured.";
const seeMore = getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl);
if (availableAgents.length) {
message = agentName ? `Failed to find agent '${agentName}'. ${configMessage}` : `Failed to find agent. ${configMessage}`;
const bulletList = availableAgents.map((agent) => `\u2022 ${agent.name} (ID: \`${agent.id}\`)`).join("\n");
message += `
The available agents are:
${bulletList}
${seeMore}`;
} else {
message += `
${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 */;
super({ message, code: resolvedCode });
}
} else {
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 = "error" /* Error */;
}
};
var MissingPublicApiKeyError = class extends ConfigurationError {
constructor(message) {
super(message);
this.name = ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR;
this.severity = "error" /* Error */;
}
};
var UpgradeRequiredError = class extends ConfigurationError {
constructor(message) {
super(message);
this.name = ERROR_NAMES.UPGRADE_REQUIRED_ERROR;
this.severity = "error" /* 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 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");
}
// 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 dataToUUID(input, namespace) {
const BASE_NAMESPACE = "e4b01160-ff74-4c6e-9b27-d53cd930fe8e";
const boundNamespace = namespace ? (0, import_uuid.v5)(namespace, BASE_NAMESPACE) : BASE_NAMESPACE;
return (0, import_uuid.v5)(input, boundNamespace);
}
function isValidUUID(uuid) {
return (0, import_uuid.validate)(uuid);
}
// 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;
}, []);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
COPILOT_CLOUD_ERROR_NAMES,
ConfigurationError,
CopilotKitAgentDiscoveryError,
CopilotKitApiDiscoveryError,
CopilotKitError,
CopilotKitErrorCode,
CopilotKitLowLevelError,
CopilotKitMisuseError,
CopilotKitRemoteEndpointDiscoveryError,
CopilotKitVersionMismatchError,
ERROR_CONFIG,
ERROR_NAMES,
MissingPublicApiKeyError,
ResolvedCopilotKitError,
Severity,
UpgradeRequiredError,
actionParametersToJsonSchema,
convertJsonSchemaToZodSchema,
dataToUUID,
executeConditions,
getPossibleVersionMismatch,
isValidUUID,
parseJson,
randomId,
randomUUID,
tryMap
});
//# sourceMappingURL=index.js.map
;