@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,219 lines (1,196 loc) • 72.4 kB
JavaScript
(function(global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('graphql'), require('zod'), require('uuid'), require('partial-json'), require('@segment/analytics-node'), require('chalk'), require('@ag-ui/client')) :
typeof define === 'function' && define.amd ? define(['exports', 'graphql', 'zod', 'uuid', 'partial-json', '@segment/analytics-node', 'chalk', '@ag-ui/client'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitShared = {}), global.GraphQL,global.Zod,global.UUID,global.PartialJSON,global.SegmentAnalyticsNode,global.chalk,global.AgUIClient));
})(this, function(exports, graphql, zod, uuid, partial_json, _segment_analytics_node, chalk, _ag_ui_client) {
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
//#region \0rolldown/runtime.js
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 __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) {
__defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
}
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
partial_json = __toESM(partial_json);
//#region src/utils/clipboard.ts
/**
* Safely copies text to the clipboard.
*
* Checks that the Clipboard API is available before attempting the write,
* and catches any errors (e.g. permission denied, insecure context).
*
* @param text - The text to copy to the clipboard.
* @returns `true` if the text was successfully copied, `false` otherwise.
*/
async function copyToClipboard(text) {
var _navigator$clipboard;
if (!((_navigator$clipboard = navigator.clipboard) === null || _navigator$clipboard === void 0 ? void 0 : _navigator$clipboard.writeText)) {
console.error("Clipboard API is not available");
return false;
}
try {
await navigator.clipboard.writeText(text);
return true;
} catch (err) {
console.error("Failed to copy to clipboard:", err);
return false;
}
}
//#endregion
//#region src/utils/conditions.ts
function executeConditions({ conditions, value }) {
if (!(conditions === null || conditions === void 0 ? 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 || acc === void 0 ? void 0 : acc[part], obj);
}
//#endregion
//#region src/utils/console-styling.ts
/**
* Console styling utilities for CopilotKit branded messages
* Provides consistent, readable colors across light and dark console themes
*/
/**
* Color palette optimized for console readability
*/
const ConsoleColors = {
primary: "#007acc",
success: "#22c55e",
feature: "#a855f7",
cta: "#ef4444",
info: "#06b6d4",
inherit: "inherit",
warning: "#f59e0b"
};
/**
* Console style templates for common patterns
*/
const ConsoleStyles = {
header: `color: ${ConsoleColors.warning}; font-weight: bold; font-size: 16px;`,
section: `color: ${ConsoleColors.success}; font-weight: bold;`,
highlight: `color: ${ConsoleColors.feature}; font-weight: bold;`,
cta: `color: ${ConsoleColors.success}; font-weight: bold;`,
info: `color: ${ConsoleColors.info}; font-weight: bold;`,
link: `color: ${ConsoleColors.primary}; text-decoration: underline;`,
body: `color: ${ConsoleColors.inherit};`,
warning: `color: ${ConsoleColors.cta}; font-weight: bold;`
};
/**
* Styled console message for CopilotKit Platform promotion
* Displays a beautiful, branded advertisement in the console
*/
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://dashboard.operations.copilotkit.ai%c
Alternatively, useCopilotChat is available for basic programmatic control, and does not require a license key.
To learn more about premium features, read the documentation here:
%chttps://docs.copilotkit.ai/premium/overview%c`, ConsoleStyles.header, ConsoleStyles.body, ConsoleStyles.cta, ConsoleStyles.body, ConsoleStyles.link, ConsoleStyles.body);
}
function publicApiKeyRequired(feature) {
console.log(`
%cCopilotKit Warning%c \n
In order to use ${feature}, you need to add your CopilotKit license key, available for free at https://dashboard.operations.copilotkit.ai.
`.trim(), ConsoleStyles.header, ConsoleStyles.body);
}
/**
* Create a styled console message with custom content
*
* @param template - Template string with %c placeholders
* @param styles - Array of style strings matching the %c placeholders
*
* @example
* ```typescript
* logStyled(
* '%cCopilotKit%c Welcome to the platform!',
* [ConsoleStyles.header, ConsoleStyles.body]
* );
* ```
*/
function logStyled(template, styles) {
console.log(template, ...styles);
}
/**
* Quick styled console methods for common use cases
*/
const styledConsole = {
success: (message) => logStyled(`%c✅ ${message}`, [ConsoleStyles.section]),
info: (message) => logStyled(`%cℹ️ ${message}`, [ConsoleStyles.info]),
feature: (message) => logStyled(`%c✨ ${message}`, [ConsoleStyles.highlight]),
cta: (message) => logStyled(`%c🚀 ${message}`, [ConsoleStyles.cta]),
logCopilotKitPlatformMessage,
publicApiKeyRequired
};
//#endregion
//#region src/utils/errors.ts
let Severity = /* @__PURE__ */ function(Severity) {
Severity["CRITICAL"] = "critical";
Severity["WARNING"] = "warning";
Severity["INFO"] = "info";
return Severity;
}({});
let ErrorVisibility = /* @__PURE__ */ function(ErrorVisibility) {
ErrorVisibility["BANNER"] = "banner";
ErrorVisibility["TOAST"] = "toast";
ErrorVisibility["SILENT"] = "silent";
ErrorVisibility["DEV_ONLY"] = "dev_only";
return ErrorVisibility;
}({});
const 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"
};
const 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
];
const COPILOT_CLOUD_ERROR_NAMES = BANNER_ERROR_NAMES;
let CopilotKitErrorCode = /* @__PURE__ */ function(CopilotKitErrorCode) {
CopilotKitErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR";
CopilotKitErrorCode["NOT_FOUND"] = "NOT_FOUND";
CopilotKitErrorCode["AGENT_NOT_FOUND"] = "AGENT_NOT_FOUND";
CopilotKitErrorCode["API_NOT_FOUND"] = "API_NOT_FOUND";
CopilotKitErrorCode["REMOTE_ENDPOINT_NOT_FOUND"] = "REMOTE_ENDPOINT_NOT_FOUND";
CopilotKitErrorCode["AUTHENTICATION_ERROR"] = "AUTHENTICATION_ERROR";
CopilotKitErrorCode["MISUSE"] = "MISUSE";
CopilotKitErrorCode["UNKNOWN"] = "UNKNOWN";
CopilotKitErrorCode["VERSION_MISMATCH"] = "VERSION_MISMATCH";
CopilotKitErrorCode["CONFIGURATION_ERROR"] = "CONFIGURATION_ERROR";
CopilotKitErrorCode["MISSING_PUBLIC_API_KEY_ERROR"] = "MISSING_PUBLIC_API_KEY_ERROR";
CopilotKitErrorCode["UPGRADE_REQUIRED_ERROR"] = "UPGRADE_REQUIRED_ERROR";
return CopilotKitErrorCode;
}({});
const BASE_URL = "https://docs.copilotkit.ai";
const getSeeMoreMarkdown = (link) => `See more: [${link}](${link})`;
const ERROR_CONFIG = {
[CopilotKitErrorCode.NETWORK_ERROR]: {
statusCode: 503,
troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#network-errors-api-not-found`,
visibility: ErrorVisibility.BANNER,
severity: Severity.CRITICAL
},
[CopilotKitErrorCode.NOT_FOUND]: {
statusCode: 404,
troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#network-errors-api-not-found`,
visibility: ErrorVisibility.BANNER,
severity: Severity.CRITICAL
},
[CopilotKitErrorCode.AGENT_NOT_FOUND]: {
statusCode: 500,
troubleshootingUrl: `${BASE_URL}/langgraph-python/coagent-troubleshooting/common-coagent-issues#i-am-getting-agent-not-found-error`,
visibility: ErrorVisibility.BANNER,
severity: Severity.CRITICAL
},
[CopilotKitErrorCode.API_NOT_FOUND]: {
statusCode: 404,
troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#network-errors-api-not-found`,
visibility: ErrorVisibility.BANNER,
severity: Severity.CRITICAL
},
[CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND]: {
statusCode: 404,
troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#remote-endpoint-not-found-error`,
visibility: ErrorVisibility.BANNER,
severity: Severity.CRITICAL
},
[CopilotKitErrorCode.AUTHENTICATION_ERROR]: {
statusCode: 401,
troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues`,
visibility: ErrorVisibility.BANNER,
severity: Severity.CRITICAL
},
[CopilotKitErrorCode.MISUSE]: {
statusCode: 400,
troubleshootingUrl: null,
visibility: ErrorVisibility.DEV_ONLY,
severity: Severity.WARNING
},
[CopilotKitErrorCode.UNKNOWN]: {
statusCode: 500,
visibility: ErrorVisibility.TOAST,
severity: Severity.CRITICAL
},
[CopilotKitErrorCode.CONFIGURATION_ERROR]: {
statusCode: 400,
troubleshootingUrl: null,
severity: Severity.WARNING,
visibility: ErrorVisibility.BANNER
},
[CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR]: {
statusCode: 400,
troubleshootingUrl: null,
severity: Severity.CRITICAL,
visibility: ErrorVisibility.BANNER
},
[CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR]: {
statusCode: 402,
troubleshootingUrl: null,
severity: Severity.WARNING,
visibility: ErrorVisibility.BANNER
},
[CopilotKitErrorCode.VERSION_MISMATCH]: {
statusCode: 400,
troubleshootingUrl: null,
visibility: ErrorVisibility.DEV_ONLY,
severity: Severity.INFO
}
};
var CopilotKitError = class extends graphql.GraphQLError {
constructor({ message = "Unknown error occurred", code, severity, visibility }) {
var _ref;
const name = ERROR_NAMES.COPILOT_ERROR;
const config = ERROR_CONFIG[code];
const { statusCode } = config;
const resolvedVisibility = (_ref = visibility !== null && visibility !== void 0 ? visibility : config.visibility) !== null && _ref !== void 0 ? _ref : ErrorVisibility.TOAST;
const resolvedSeverity = severity !== null && severity !== void 0 ? 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: (/* @__PURE__ */ new Error()).stack
}
} });
this.code = code;
this.name = name;
this.statusCode = statusCode;
this.severity = resolvedSeverity;
this.visibility = resolvedVisibility;
}
};
/**
* Error thrown when we can identify wrong usage of our components.
* This helps us notify the developer before real errors can happen
*
* @extends CopilotKitError
*/
var CopilotKitMisuseError = class extends CopilotKitError {
constructor({ message, code = CopilotKitErrorCode.MISUSE }) {
const docsLink = "troubleshootingUrl" in ERROR_CONFIG[code] && ERROR_CONFIG[code].troubleshootingUrl ? getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl) : null;
const finalMessage = docsLink ? `${message}.\n\n${docsLink}` : message;
super({
message: finalMessage,
code
});
this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;
}
};
const getVersionMismatchErrorMessage = ({ reactCoreVersion, runtimeVersion, runtimeClientGqlVersion }) => `Version mismatch detected: @copilotkit/runtime@${runtimeVersion !== null && runtimeVersion !== void 0 ? 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.`;
/**
* Error thrown when CPK versions does not match
*
* @extends CopilotKitError
*/
var CopilotKitVersionMismatchError = class extends CopilotKitError {
constructor({ reactCoreVersion, runtimeVersion, runtimeClientGqlVersion }) {
const code = CopilotKitErrorCode.VERSION_MISMATCH;
super({
message: getVersionMismatchErrorMessage({
reactCoreVersion,
runtimeVersion,
runtimeClientGqlVersion
}),
code
});
this.name = ERROR_NAMES.COPILOT_KIT_VERSION_MISMATCH_ERROR;
}
};
/**
* Error thrown when the CopilotKit API endpoint cannot be discovered or accessed.
* This typically occurs when:
* - The API endpoint URL is invalid or misconfigured
* - The API service is not running at the expected location
* - There are network/firewall issues preventing access
*
* @extends CopilotKitError
*/
var CopilotKitApiDiscoveryError = class extends CopilotKitError {
constructor(params = {}) {
var _params$url, _params$message, _params$code;
const url = (_params$url = params.url) !== null && _params$url !== void 0 ? _params$url : "";
let operationSuffix = "";
if (url === null || url === void 0 ? 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.message) !== null && _params$message !== void 0 ? _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 = params.code) !== null && _params$code !== void 0 ? _params$code : CopilotKitErrorCode.API_NOT_FOUND;
const errorMessage = `${message}.\n\n${getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl)}`;
super({
message: errorMessage,
code
});
this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;
}
};
/**
* This error is used for endpoints specified in runtime's remote endpoints. If they cannot be contacted
* This typically occurs when:
* - The API endpoint URL is invalid or misconfigured
* - The API service is not running at the expected location
*
* @extends CopilotKitApiDiscoveryError
*/
var CopilotKitRemoteEndpointDiscoveryError = class extends CopilotKitApiDiscoveryError {
constructor(params) {
var _params$message2;
const message = (_params$message2 = params === null || params === void 0 ? void 0 : params.message) !== null && _params$message2 !== void 0 ? _params$message2 : (params === null || params === void 0 ? void 0 : params.url) ? `Failed to find or contact remote endpoint at url ${params.url}` : "Failed to find or contact remote endpoint";
const code = CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND;
super({
message,
code
});
this.name = ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR;
}
};
/**
* Error thrown when a LangGraph agent cannot be found or accessed.
* This typically occurs when:
* - The specified agent name does not exist in the deployment
* - The agent configuration is invalid or missing
* - The agent service is not properly deployed or initialized
*
* @extends CopilotKitError
*/
var CopilotKitAgentDiscoveryError = class extends CopilotKitError {
constructor(params) {
const { agentName, availableAgents } = params;
const code = CopilotKitErrorCode.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.\n\n${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.\n\n${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;
}
};
/**
* Handles low-level networking errors that occur before a request reaches the server.
* These errors arise from issues in the underlying communication infrastructure rather than
* application-level logic or server responses. Typically used to handle "fetch failed" errors
* where no HTTP status code is available.
*
* Common scenarios include:
* - Connection failures (ECONNREFUSED) when server is down/unreachable
* - DNS resolution failures (ENOTFOUND) when domain can't be resolved
* - Timeouts (ETIMEDOUT) when request takes too long
* - Protocol/transport layer errors like SSL/TLS issues
*/
var CopilotKitLowLevelError = class extends CopilotKitError {
constructor({ error, url, message }) {
let code = CopilotKitErrorCode.NETWORK_ERROR;
const errorCode = error.code;
const errorMessage = message !== null && message !== void 0 ? message : resolveLowLevelErrorMessage({
errorCode,
url
});
super({
message: errorMessage,
code
});
this.name = ERROR_NAMES.COPILOT_KIT_LOW_LEVEL_ERROR;
}
};
/**
* Generic catch-all error handler for HTTP responses from the CopilotKit API where a status code is available.
* Used when we receive an HTTP error status and wish to handle broad range of them
*
* This differs from CopilotKitLowLevelError in that:
* - ResolvedCopilotKitError: Server was reached and returned an HTTP status
* - CopilotKitLowLevelError: Error occurred before reaching server (e.g. network failure)
*
* @param status - The HTTP status code received from the API response
* @param message - Optional error message to include
* @param code - Optional specific CopilotKitErrorCode to override default behavior
*
* Default behavior:
* - 400 Bad Request: Maps to CopilotKitApiDiscoveryError
* - All other status codes: Maps to UNKNOWN error code if no specific code provided
*/
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 = CopilotKitErrorCode.UNKNOWN;
break;
}
super({
message,
code: resolvedCode
});
this.name = ERROR_NAMES.RESOLVED_COPILOT_KIT_ERROR;
}
};
var ConfigurationError = class extends CopilotKitError {
constructor(message) {
super({
message,
code: CopilotKitErrorCode.CONFIGURATION_ERROR
});
this.name = ERROR_NAMES.CONFIGURATION_ERROR;
this.severity = Severity.WARNING;
}
};
var MissingPublicApiKeyError = class extends ConfigurationError {
constructor(message) {
super(message);
this.name = ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR;
this.severity = Severity.CRITICAL;
}
};
var UpgradeRequiredError = class extends ConfigurationError {
constructor(message) {
super(message);
this.name = ERROR_NAMES.UPGRADE_REQUIRED_ERROR;
this.severity = Severity.WARNING;
}
};
/**
* Checks if an error is already a structured CopilotKit error.
* This utility centralizes the logic for detecting structured errors across the codebase.
*
* @param error - The error to check
* @returns true if the error is already structured, false otherwise
*/
function isStructuredCopilotKitError(error) {
var _error$extensions;
return error instanceof CopilotKitError || error instanceof CopilotKitLowLevelError || (error === null || error === void 0 ? void 0 : error.name) && error.name.includes("CopilotKit") || (error === null || error === void 0 || (_error$extensions = error.extensions) === null || _error$extensions === void 0 ? void 0 : _error$extensions.code) !== void 0;
}
/**
* Returns the error as-is if it's already structured, otherwise converts it using the provided converter function.
* This utility centralizes the pattern of preserving structured errors while converting unstructured ones.
*
* @param error - The error to process
* @param converter - Function to convert unstructured errors to structured ones
* @returns The structured error
*/
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
})
};
}
const resolveLowLevelErrorMessage = ({ errorCode, url }) => {
const troubleshootingLink = ERROR_CONFIG[CopilotKitErrorCode.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.\n\n${getSeeMoreMarkdown(troubleshootingLink)}`;
case "ENOTFOUND": 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)}`;
case "ETIMEDOUT": return `The connection to ${url} timed out. The server might be overloaded or taking too long to respond.\n\n${getSeeMoreMarkdown(troubleshootingLink)}`;
default: return;
}
};
//#endregion
//#region src/utils/json-schema.ts
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;
if (Array.isArray(schema.type)) {
const types = schema.type;
const hasNull = types.includes("null");
const nonNullTypes = types.filter((t) => t !== "null");
const resolvedType = nonNullTypes.length > 0 ? nonNullTypes[0] : "string";
return convertJsonSchemaToParameter(name, {
...schema,
type: resolvedType
}, hasNull ? false : isRequired);
}
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) {
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[]":
var _attribute$attributes, _attribute$attributes2;
const properties = (_attribute$attributes = attribute.attributes) === null || _attribute$attributes === void 0 ? void 0 : _attribute$attributes.reduce((acc, attr) => {
acc[attr.name] = convertAttribute(attr);
return acc;
}, {});
const required = (_attribute$attributes2 = attribute.attributes) === null || _attribute$attributes2 === void 0 ? void 0 : _attribute$attributes2.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:
var _attribute$type;
if ((_attribute$type = attribute.type) === null || _attribute$type === void 0 ? void 0 : _attribute$type.endsWith("[]")) return {
type: "array",
items: { type: attribute.type.slice(0, -2) },
description: attribute.description
};
return {
type: "string",
description: attribute.description
};
}
}
function convertJsonSchemaToZodSchema(jsonSchema, required, definitions, visitedRefs) {
var _ref, _jsonSchema$anyOf, _jsonSchema$type;
if (jsonSchema.$ref && definitions) {
const refPath = jsonSchema.$ref.replace(/^#\/\$defs\/|^#\/definitions\//, "");
const refs = visitedRefs !== null && visitedRefs !== void 0 ? visitedRefs : /* @__PURE__ */ new Set();
if (refs.has(refPath)) {
console.warn(`[CopilotKit] Circular $ref detected for "${refPath}" — falling back to z.any()`);
let schema = zod.z.any();
if (jsonSchema.description) schema = schema.describe(jsonSchema.description);
return required ? schema : schema.optional();
}
const resolved = definitions[refPath];
if (resolved) {
const nextRefs = new Set(refs);
nextRefs.add(refPath);
return convertJsonSchemaToZodSchema(resolved, required, definitions, nextRefs);
}
}
const defs = (_ref = definitions !== null && definitions !== void 0 ? definitions : jsonSchema.$defs) !== null && _ref !== void 0 ? _ref : jsonSchema.definitions;
if (Array.isArray(jsonSchema.type)) {
const types = jsonSchema.type;
const hasNull = types.includes("null");
const nonNullTypes = types.filter((t) => t !== "null");
const resolvedType = nonNullTypes.length > 0 ? nonNullTypes[0] : "string";
const innerSchema = convertJsonSchemaToZodSchema({
...jsonSchema,
type: resolvedType
}, true, defs, visitedRefs);
let schema = hasNull ? zod.z.union([innerSchema, zod.z.null()]) : innerSchema;
if (jsonSchema.description) schema = schema.describe(jsonSchema.description);
return required ? schema : schema.optional();
}
const unionVariants = (_jsonSchema$anyOf = jsonSchema.anyOf) !== null && _jsonSchema$anyOf !== void 0 ? _jsonSchema$anyOf : jsonSchema.oneOf;
if (Array.isArray(unionVariants) && unionVariants.length > 0) {
if (unionVariants.length === 1) return convertJsonSchemaToZodSchema(unionVariants[0], required, defs, visitedRefs);
const schemas = unionVariants.map((v) => convertJsonSchemaToZodSchema(v, true, defs, visitedRefs));
let schema = zod.z.union(schemas);
if (jsonSchema.description) schema = schema.describe(jsonSchema.description);
return required ? schema : schema.optional();
}
if (jsonSchema.type === "object") {
const spec = {};
if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) return !required ? zod.z.object(spec).optional() : zod.z.object(spec);
for (const [key, value] of Object.entries(jsonSchema.properties)) spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false, defs, visitedRefs);
let schema = zod.z.object(spec).describe(jsonSchema.description);
return required ? schema : schema.optional();
} else if (jsonSchema.type === "string") {
if (jsonSchema.enum && jsonSchema.enum.length > 0) {
let schema = zod.z.enum(jsonSchema.enum).describe(jsonSchema.description);
return required ? schema : schema.optional();
}
let schema = zod.z.string().describe(jsonSchema.description);
return required ? schema : schema.optional();
} else if (jsonSchema.type === "number" || jsonSchema.type === "integer") {
let schema = zod.z.number().describe(jsonSchema.description);
return required ? schema : schema.optional();
} else if (jsonSchema.type === "boolean") {
let schema = zod.z.boolean().describe(jsonSchema.description);
return required ? schema : schema.optional();
} else if (jsonSchema.type === "array") {
let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true, defs, visitedRefs);
let schema = zod.z.array(itemSchema).describe(jsonSchema.description);
return required ? schema : schema.optional();
} else if (jsonSchema.type === "null") {
let schema = zod.z.null().describe(jsonSchema.description);
return required ? schema : schema.optional();
}
console.warn(`[CopilotKit] Unsupported JSON schema type "${(_jsonSchema$type = jsonSchema.type) !== null && _jsonSchema$type !== void 0 ? _jsonSchema$type : "unknown"}" — falling back to z.any()`);
let schema = zod.z.any();
if (jsonSchema.description) schema = schema.describe(jsonSchema.description);
return required ? schema : schema.optional();
}
function getZodParameters(parameters) {
if (!parameters) return zod.z.object({});
return convertJsonSchemaToZodSchema(actionParametersToJsonSchema(parameters), true);
}
//#endregion
//#region src/utils/types.ts
const RUNTIME_MODE_SSE = "sse";
const RUNTIME_MODE_INTELLIGENCE = "intelligence";
//#endregion
//#region src/utils/random-id.ts
function randomId() {
return "ck-" + (0, uuid.v4)();
}
function randomUUID() {
return (0, uuid.v4)();
}
/**
* Recursively converts an object to a serializable form by converting functions to their string representation.
*/
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, uuid.v5)(namespace, BASE_NAMESPACE) : BASE_NAMESPACE;
return (0, uuid.v5)(typeof input === "string" ? input : JSON.stringify(toSerializable(input)), boundNamespace);
}
function isValidUUID(uuid$1) {
return (0, uuid.validate)(uuid$1);
}
//#endregion
//#region src/utils/requests.ts
/**
* Safely read a Response/Request body with sensible defaults:
* - clones the response/request to avoid consuming the original response/request
* - Skips GET/HEAD
* - Tries JSON first regardless of content-type
* - Falls back to text and optionally parses when it "looks" like JSON
*/
async function readBody(r) {
const method = "method" in r ? r.method.toUpperCase() : void 0;
if (method === "GET" || method === "HEAD") return;
if (!("body" in r) || r.body == null) return;
try {
return await r.clone().json();
} catch (_unused) {
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 (_unused2) {
return text;
}
return text;
} catch (_unused3) {
try {
var _c$body;
const stream = (_c$body = r.clone().body) !== null && _c$body !== void 0 ? _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 (_unused4) {
return out;
}
return out;
} catch (_unused5) {
return;
}
}
}
}
//#endregion
//#region src/utils/index.ts
/**
* Safely parses a JSON string into an object
* @param json The JSON string to parse
* @param fallback Optional fallback value to return if parsing fails. If not provided or set to "unset", returns null
* @returns The parsed JSON object, or the fallback value (or null) if parsing fails
*/
function parseJson(json, fallback = "unset") {
try {
return JSON.parse(json);
} catch (e) {
return fallback === "unset" ? null : fallback;
}
}
/**
* Parses a partial/incomplete JSON string, returning as much valid data as possible.
* Falls back to an empty object if parsing fails entirely.
*/
function partialJSONParse(json) {
try {
const parsed = partial_json.parse(json);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
return {};
} catch (error) {
return {};
}
}
/**
* Returns an exponential backoff function suitable for Phoenix.js
* `reconnectAfterMs` and `rejoinAfterMs` options.
*
* @param baseMs - Initial delay for the first retry attempt.
* @param maxMs - Upper bound — delays are capped at this value.
*
* Phoenix calls the returned function with a 1-based `tries` count.
* The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.
*/
function phoenixExponentialBackoff(baseMs, maxMs) {
return (tries) => Math.min(baseMs * 2 ** (tries - 1), maxMs);
}
/**
* Maps an array of items to a new array, skipping items that throw errors during mapping
* @param items The array to map
* @param callback The mapping function to apply to each item
* @returns A new array containing only the successfully mapped items
*/
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;
}, []);
}
/**
* Checks if the current environment is macOS
* @returns {boolean} True if running on macOS, false otherwise
*/
function isMacOS() {
return /Mac|iMac|Macintosh/i.test(navigator.userAgent);
}
/**
* Safely parses a JSON string into a tool arguments object.
* Returns the parsed object only if it's a plain object (not an array, null, etc.).
* Falls back to an empty object for any non-object JSON value or parse failure.
*/
function safeParseToolArgs(raw) {
try {
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
console.warn(`[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`);
return {};
} catch (_unused) {
console.warn("[CopilotKit] Failed to parse tool arguments, falling back to empty object");
return {};
}
}
//#endregion
//#region src/constants/index.ts
const COPILOT_CLOUD_API_URL = "https://api.cloud.copilotkit.ai";
const COPILOT_CLOUD_VERSION = "v1";
const COPILOT_CLOUD_CHAT_URL = `${COPILOT_CLOUD_API_URL}/copilotkit/${COPILOT_CLOUD_VERSION}`;
const COPILOT_CLOUD_PUBLIC_API_KEY_HEADER = "X-CopilotCloud-Public-Api-Key";
const DEFAULT_AGENT_ID = "default";
/** Phoenix channel event name used for all AG-UI events. */
const AG_UI_CHANNEL_EVENT = "ag-ui";
//#endregion
//#region src/telemetry/utils.ts
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;
}
//#endregion
//#region src/telemetry/lambda-client.ts
var _process$env;
const TELEMETRY_SINK_URL = typeof process !== "undefined" && ((_process$env = process.env) === null || _process$env === void 0 ? void 0 : _process$env.COPILOTKIT_TELEMETRY_URL) || "https://telemetry.copilotkit.ai/ingest";
const FETCH_TIMEOUT_MS = 3e3;
const STRIPPED_KEYS = new Set(["cloud.public_api_key", "cloud.publicApiKey"]);
function stripCloudKeys(obj) {
if (!obj) return {};
const out = {};
for (const [k, v] of Object.entries(obj)) if (!STRIPPED_KEYS.has(k)) out[k] = v;
return out;
}
function parseTelemetryIdFromLicense(token) {
if (!token) return null;
const parts = token.split(".");
if (parts.length !== 3) return null;
try {
let b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
const padding = (4 - b64.length % 4) % 4;
b64 += "=".repeat(padding);
const json = typeof atob === "function" ? atob(b64) : Buffer.from(b64, "base64").toString("utf8");
const decoded = JSON.parse(json);
return typeof decoded.telemetry_id === "string" ? decoded.telemetry_id : null;
} catch (_unused) {
return null;
}
}
function parseAndWarnTelemetryId(licenseToken) {
const telemetryId = parseTelemetryIdFromLicense(licenseToken);
if (!telemetryId) console.warn("[CopilotKit] License token did not yield a telemetry_id; telemetry events will be sent anonymously.");
return telemetryId;
}
async function send(opts) {
try {
var _opts$packageVersion;
const body = JSON.stringify({
event: opts.event,
properties: stripCloudKeys(opts.properties),
global_properties: stripCloudKeys(opts.globalProperties),
package: {
name: opts.packageName,
version: opts.packageVersion
},
ts: Math.floor(Date.now() / 1e3)
});
const telemetryId = parseTelemetryIdFromLicense(opts.licenseToken);
const headers = {
"Content-Type": "application/json",
"User-Agent": opts.packageName ? `CopilotKit-Runtime/${(_opts$packageVersion = opts.packageVersion) !== null && _opts$packageVersion !== void 0 ? _opts$packageVersion : "unknown"} (${opts.packageName})` : "CopilotKit-Runtime"
};
if (telemetryId) headers["X-CopilotKit-Telemetry-Id"] = telemetryId;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
await fetch(TELEMETRY_SINK_URL, {
method: "POST",
headers,
body,
signal: controller.signal
});
} finally {
clearTimeout(timeoutId);
}
} catch (_unused2) {}
}
const lambdaClient = { send };
//#endregion
//#region src/telemetry/telemetry-client.ts
/**
* Checks if telemetry is disabled via environment variables.
* Users can opt out by setting:
* - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1
* - DO_NOT_TRACK=true or DO_NOT_TRACK=1
*/
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.licenseToken = null;
this.telemetryId = null;
this.telemetryDisabled = false;
this.sampleRate = .05;
this.anonymousId = `anon_${(0, uuid.v4)()}`;
this.packageName = packageName;
this.packageVersion = packageVersion;
this.telemetryDisabled = telemetryDisabled || isTelemetryDisabled();
if (this.telemetryDisabled) return;
this.setSampleRate(sampleRate);
this.segment = new _segment_analytics_node.Analytics({ writeKey: process.env.COPILOTKIT_SEGMENT_WRITE_KEY || "n7XAZtQCGS2v1vvBy3LgBCv2h3Y8whja" });
this.setGlobalProperties({
"copilotkit.package.name": packageName,
"copilotkit.package.version": packageVersion
});
}
shouldSendEvent() {
return Math.random() < this.sampleRate;
}
async capture(event, properties) {
var _this$licenseToken;
if (this.telemetryDisabled) return;
if (!this.telemetryId && !this.shouldSendEvent()) return;
const effectiveSampleRate = this.telemetryId ? 1 : this.sampleRate;
const samplingMeta = {
sampleRate: effectiveSampleRate,
sampleRateAdjustmentFactor: 1 - effectiveSampleRate,
sampleWeight: 1 / effectiveSampleRate
};
const flattenedProperties = flattenObject(properties);
const propertiesWithGlobal = {
...this.globalProperties,
...samplingMeta,
...flattenedProperties
};
const orderedPropertiesWithGlobal = Object.keys(propertiesWithGlobal).sort().reduce((obj, key) => {
obj[key] = propertiesWithGlobal[key];
return obj;
}, {});
await lambdaClient.send({
event,
properties: flattenedProperties,
globalProperties: {
...this.globalProperties,
...samplingMeta
},
packageName: this.packageName,
packageVersion: this.packageVersion,
licenseToken: (_this$licenseToken = this.licenseToken) !== null && _this$licenseToken !== void 0 ? _this$licenseToken : void 0
});
if (this.segment) this.segment.track({
anonymousId: this.anonymousId,
event,
properties: { ...orderedPropertiesWithGlobal }
});
}
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
} });
}
setLicenseToken(licenseToken) {
this.licenseToken = licenseToken;
this.telemetryId = parseAndWarnTelemetryId(licenseToken);
}
setSampleRate(sampleRate) {
let _sampleRate;
_sampleRate = sampleRate !== null && sampleRate !== void 0 ? sampleRate : .05;
if (process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE) _sampleRate = parseFloat(process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE);
if (Number.isNaN(_sampleRate) || _sampleRate < 0 || _sampleRate > 1) throw new Error("Sample rate must be between 0 and 1");
this.sampleRate = _sampleRate;
}
};
//#endregion
//#region src/debug.ts
/** The all-off config used when debug is falsy. */
const DEBUG_OFF = {
enabled: false,
events: false,
lifecycle: false,
verbose: false
};
/**
* Normalizes a DebugConfig value into a ResolvedDebugConfig.
*
* - `false` / `undefined` → all off
* - `true` → events + lifecycle on, verbose off (no PII in logs)
* - object → merges with defaults (events: true, lifecycle: true, verbose: false)
*/
function resolveDebugConfig(debug) {
var _debug$events, _debug$lifecycle, _debug$verbose;
if (!debug) return DEBUG_OFF;
if (debug === true) return {
enabled: true,
events: true,
lifecycle: true,
verbose: false
};
const events = (_debug$events = debug.events) !== null && _debug$events !== void 0 ? _debug$events : true;
const lifecycle = (_debug$lifecycle = debug.lifecycle) !== null && _debug$lifecycle !== void 0 ? _debug$lifecycle : true;
const enabled = events || lifecycle;
return {
enabled,
events,
lifecycle,
verbose: enabled && ((_debug$verbose = debug.verbose) !== null && _debug$verbose !== void 0 ? _debug$verbose : false)
};
}
//#endregion
//#region src/standard-schema.ts
/**
* Check whether a schema implements the Standard JSON Schema V1 protocol.
*/
function hasStandardJsonSchema(schema) {
const props = schema["~standard"];
return props != null && typeof props === "object" && "jsonSchema" in props && props.jsonSchema != null && typeof props.jsonSchema === "object" && "input" in props.jsonSchema && typeof props.jsonSchema.input === "function";
}
/**
* Convert any StandardSchemaV1-compatible schema to a JSON Schema object.
*
* Strategy:
* 1. If the schema implements Standard JSON Schema V1 (`~standard.jsonSchema`),
* call `schema['~standard'].jsonSchema.input({ target: 'draft-07' })`.
* 2. If the schema exposes a `toJSONSchema()` method (Zod v4), call it directly.
* 3. If the schema is a Zod v3 schema (`~standard.vendor === 'zod'`), use the
* injected `zodToJsonSchema()` function.
* 4. Otherwise throw a descriptive error.
*/
function schemaToJsonSchema(schema, options) {
if (hasStandardJsonSchema(schema)) return schema["~standard"].jsonSchema.input({ target: "draft-07" });
if (typeof schema.toJSONSchema === "function") return schema.toJSONSchema();
const vendor = schema["~standard"].vendor;
if (vendor === "zod" && (options === null || options === void 0 ? void 0 : options.zodToJsonSchema)) return options.zodToJsonSchema(schema, { $refStrategy: "none" });
throw new Error(`Cannot convert schema to JSON Schema. The schema (vendor: "${vendor}") does not implement Standard JS