@copilotkit/react-core
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>
441 lines (432 loc) • 15.6 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
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);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/hooks/use-copilot-authenticated-action.ts
var use_copilot_authenticated_action_exports = {};
__export(use_copilot_authenticated_action_exports, {
useCopilotAuthenticatedAction_c: () => useCopilotAuthenticatedAction_c
});
module.exports = __toCommonJS(use_copilot_authenticated_action_exports);
var import_react5 = require("react");
// src/context/copilot-context.tsx
var import_react = __toESM(require("react"));
var emptyCopilotContext = {
actions: {},
setAction: () => {
},
removeAction: () => {
},
coAgentStateRenders: {},
setCoAgentStateRender: () => {
},
removeCoAgentStateRender: () => {
},
chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
getContextString: (documents, categories) => returnAndThrowInDebug(""),
addContext: () => "",
removeContext: () => {
},
getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
})),
isLoading: false,
setIsLoading: () => returnAndThrowInDebug(false),
chatInstructions: "",
setChatInstructions: () => returnAndThrowInDebug(""),
additionalInstructions: [],
setAdditionalInstructions: () => returnAndThrowInDebug([]),
getDocumentsContext: (categories) => returnAndThrowInDebug([]),
addDocumentContext: () => returnAndThrowInDebug(""),
removeDocumentContext: () => {
},
runtimeClient: {},
copilotApiConfig: new class {
get chatApiEndpoint() {
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
}
get headers() {
return {};
}
get body() {
return {};
}
}(),
chatSuggestionConfiguration: {},
addChatSuggestionConfiguration: () => {
},
removeChatSuggestionConfiguration: () => {
},
showDevConsole: "auto",
coagentStates: {},
setCoagentStates: () => {
},
coagentStatesRef: { current: {} },
setCoagentStatesWithRef: () => {
},
agentSession: null,
setAgentSession: () => {
},
forwardedParameters: {},
agentLock: null,
threadId: "",
setThreadId: () => {
},
runId: null,
setRunId: () => {
},
chatAbortControllerRef: { current: null },
availableAgents: [],
extensions: {},
setExtensions: () => {
},
langGraphInterruptAction: null,
setLangGraphInterruptAction: () => null,
removeLangGraphInterruptAction: () => null
};
var CopilotContext = import_react.default.createContext(emptyCopilotContext);
function useCopilotContext() {
const context = import_react.default.useContext(CopilotContext);
if (context === emptyCopilotContext) {
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
}
return context;
}
function returnAndThrowInDebug(_value) {
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
}
// src/hooks/use-copilot-action.ts
var import_shared = require("@copilotkit/shared");
var import_react4 = require("react");
// src/components/error-boundary/error-utils.tsx
var import_react3 = require("react");
// src/components/toast/toast-provider.tsx
var import_react2 = require("react");
var import_jsx_runtime = require("react/jsx-runtime");
var ToastContext = (0, import_react2.createContext)(void 0);
function useToast() {
const context = (0, import_react2.useContext)(ToastContext);
if (!context) {
throw new Error("useToast must be used within a ToastProvider");
}
return context;
}
// src/components/toast/exclamation-mark-icon.tsx
var import_jsx_runtime2 = require("react/jsx-runtime");
var ExclamationMarkIcon = ({
className,
style
}) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
"svg",
{
xmlns: "http://www.w3.org/2000/svg",
width: "24",
height: "24",
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
strokeWidth: "2",
strokeLinecap: "round",
strokeLinejoin: "round",
className: `lucide lucide-circle-alert ${className ? className : ""}`,
style,
children: [
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("circle", { cx: "12", cy: "12", r: "10" }),
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "12", x2: "12", y1: "8", y2: "12" }),
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "12", x2: "12.01", y1: "16", y2: "16" })
]
}
);
// src/components/error-boundary/error-utils.tsx
var import_react_markdown = __toESM(require("react-markdown"));
var import_jsx_runtime3 = require("react/jsx-runtime");
function ErrorToast({ errors }) {
const errorsToRender = errors.map((error, idx) => {
var _a, _b, _c;
const originalError = "extensions" in error ? (_a = error.extensions) == null ? void 0 : _a.originalError : {};
const message = (_b = originalError == null ? void 0 : originalError.message) != null ? _b : error.message;
const code = "extensions" in error ? (_c = error.extensions) == null ? void 0 : _c.code : null;
return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
"div",
{
style: {
marginTop: idx === 0 ? 0 : 10,
marginBottom: 14
},
children: [
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
code && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
"div",
{
style: {
fontWeight: "600",
marginBottom: 4
},
children: [
"Copilot Cloud Error:",
" ",
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react_markdown.default, { children: message })
]
},
idx
);
});
return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
"div",
{
style: {
fontSize: "13px",
maxWidth: "600px"
},
children: [
errorsToRender,
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This error only displays during local development." })
]
}
);
}
function useErrorToast() {
const { addToast } = useToast();
return (0, import_react3.useCallback)(
(error) => {
const errorId = error.map((err) => {
var _a, _b;
const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
const stack = err.stack || "";
return btoa(message + stack).slice(0, 32);
}).join("|");
addToast({
type: "error",
id: errorId,
// Toast libraries typically dedupe by id
message: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ErrorToast, { errors: error })
});
},
[addToast]
);
}
function useAsyncCallback(callback, deps) {
const addErrorToast = useErrorToast();
return (0, import_react3.useCallback)((...args) => __async(this, null, function* () {
try {
return yield callback(...args);
} catch (error) {
console.error("Error in async callback:", error);
addErrorToast([error]);
throw error;
}
}), deps);
}
// src/hooks/use-copilot-action.ts
function useCopilotAction(action, dependencies) {
const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();
const idRef = (0, import_react4.useRef)((0, import_shared.randomId)());
const renderAndWaitRef = (0, import_react4.useRef)(null);
const { addToast } = useToast();
action = __spreadValues({}, action);
if (
// renderAndWaitForResponse is not available for catch all actions
isFrontendAction(action) && // check if renderAndWaitForResponse is set
(action.renderAndWait || action.renderAndWaitForResponse)
) {
const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;
action.renderAndWait = void 0;
action.renderAndWaitForResponse = void 0;
action.handler = useAsyncCallback(() => __async(this, null, function* () {
let resolve;
let reject;
const promise = new Promise((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
renderAndWaitRef.current = { promise, resolve, reject };
return yield promise;
}), []);
action.render = (props) => {
let status = props.status;
if (props.status === "executing" && !renderAndWaitRef.current) {
status = "inProgress";
}
const waitProps = {
status,
args: props.args,
result: props.result,
handler: status === "executing" ? renderAndWaitRef.current.resolve : void 0,
respond: status === "executing" ? renderAndWaitRef.current.resolve : void 0
};
const isNoArgsRenderWait = (_fn) => {
var _a;
return ((_a = action.parameters) == null ? void 0 : _a.length) === 0;
};
if (renderAndWait) {
if (isNoArgsRenderWait(renderAndWait)) {
return renderAndWait(waitProps);
} else {
return renderAndWait(waitProps);
}
}
return (0, import_react4.createElement)(import_react4.Fragment);
};
}
if (dependencies === void 0) {
if (actions[idRef.current]) {
if (isFrontendAction(action)) {
actions[idRef.current].handler = action.handler;
}
if (typeof action.render === "function") {
if (chatComponentsCache.current !== null) {
chatComponentsCache.current.actions[action.name] = action.render;
}
}
}
}
(0, import_react4.useEffect)(() => {
const hasDuplicate = Object.values(actions).some(
(otherAction) => otherAction.name === action.name && otherAction !== actions[idRef.current]
);
if (hasDuplicate) {
addToast({
type: "warning",
message: `Found an already registered action with name ${action.name}.`,
id: `dup-action-${action.name}`
});
}
}, [actions]);
(0, import_react4.useEffect)(() => {
setAction(idRef.current, action);
if (chatComponentsCache.current !== null && action.render !== void 0) {
chatComponentsCache.current.actions[action.name] = action.render;
}
return () => {
removeAction(idRef.current);
};
}, [
setAction,
removeAction,
isFrontendAction(action) ? action.description : void 0,
action.name,
isFrontendAction(action) ? action.disabled : void 0,
isFrontendAction(action) ? action.available : void 0,
// This should be faster than deep equality checking
// In addition, all major JS engines guarantee the order of object keys
JSON.stringify(isFrontendAction(action) ? action.parameters : []),
// include render only if it's a string
typeof action.render === "string" ? action.render : void 0,
// dependencies set by the developer
...dependencies || []
]);
}
function isFrontendAction(action) {
return action.name !== "*";
}
// src/hooks/use-copilot-authenticated-action.ts
var import_react6 = __toESM(require("react"));
function useCopilotAuthenticatedAction_c(action, dependencies) {
const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();
const pendingActionRef = (0, import_react5.useRef)(null);
const executeAction = (0, import_react5.useCallback)(
(props) => {
if (typeof action.render === "function") {
return action.render(props);
}
return action.render || import_react6.default.createElement(import_react5.Fragment);
},
[action]
);
const wrappedRender = (0, import_react5.useCallback)(
(props) => {
const isAuthenticated = Object.values(authStates_c || {}).some(
(state) => state.status === "authenticated"
);
if (!isAuthenticated) {
pendingActionRef.current = props;
return (authConfig_c == null ? void 0 : authConfig_c.SignInComponent) ? import_react6.default.createElement(authConfig_c.SignInComponent, {
onSignInComplete: (authState) => {
setAuthStates_c == null ? void 0 : setAuthStates_c((prev) => __spreadProps(__spreadValues({}, prev), { [action.name]: authState }));
if (pendingActionRef.current) {
executeAction(pendingActionRef.current);
pendingActionRef.current = null;
}
}
}) : import_react6.default.createElement(import_react5.Fragment);
}
return executeAction(props);
},
[action, authStates_c, setAuthStates_c]
);
useCopilotAction(
__spreadProps(__spreadValues({}, action), {
render: wrappedRender
}),
dependencies
);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
useCopilotAuthenticatedAction_c
});
//# sourceMappingURL=use-copilot-authenticated-action.js.map
;