@copilotkit/react-core 1.10.0-next.0 → 1.10.0-next.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +94 -0
- package/dist/{chunk-YVBDAURK.mjs → chunk-2TSNHEIS.mjs} +6 -6
- package/dist/chunk-2TSNHEIS.mjs.map +1 -0
- package/dist/{chunk-DF4YG4PF.mjs → chunk-3RHHNUVV.mjs} +2 -2
- package/dist/{chunk-LNAQ7JG3.mjs → chunk-6EKLRL7B.mjs} +2 -2
- package/dist/{chunk-O5KV32S5.mjs → chunk-ADZDXHVC.mjs} +2 -2
- package/dist/{chunk-4CFY3CON.mjs → chunk-CLMDRYEN.mjs} +2 -2
- package/dist/{chunk-G35QHAQ6.mjs → chunk-COEUPDRL.mjs} +20 -21
- package/dist/chunk-COEUPDRL.mjs.map +1 -0
- package/dist/{chunk-RGKZCCPA.mjs → chunk-DLEXVOQE.mjs} +5 -5
- package/dist/{chunk-YAF2LATQ.mjs → chunk-EFL5OBKN.mjs} +1 -1
- package/dist/chunk-EFL5OBKN.mjs.map +1 -0
- package/dist/{chunk-JWAXDYOW.mjs → chunk-FAUNHSQU.mjs} +3 -3
- package/dist/chunk-ICIK2BSB.mjs +17 -0
- package/dist/chunk-ICIK2BSB.mjs.map +1 -0
- package/dist/chunk-IHAZJF3V.mjs +34 -0
- package/dist/chunk-IHAZJF3V.mjs.map +1 -0
- package/dist/{chunk-Q6FZZJ5A.mjs → chunk-IN7GE4NO.mjs} +2 -2
- package/dist/{chunk-YSQ5I2AE.mjs → chunk-JBLMXZ3O.mjs} +7 -7
- package/dist/{chunk-PZXTDFMX.mjs → chunk-JJDXTTEN.mjs} +3 -3
- package/dist/chunk-KDAZGZ24.mjs +1 -0
- package/dist/{chunk-LIGLZ53V.mjs → chunk-L6HQIJ74.mjs} +29 -13
- package/dist/chunk-L6HQIJ74.mjs.map +1 -0
- package/dist/{chunk-NAM55D5I.mjs → chunk-LVWV62JZ.mjs} +39 -26
- package/dist/chunk-LVWV62JZ.mjs.map +1 -0
- package/dist/{chunk-3OQM3NEK.mjs → chunk-N4WEHORG.mjs} +2 -2
- package/dist/chunk-OKRZF3DD.mjs +225 -0
- package/dist/chunk-OKRZF3DD.mjs.map +1 -0
- package/dist/{chunk-SJJNFYGQ.mjs → chunk-Q42NJFXR.mjs} +9 -14
- package/dist/chunk-Q42NJFXR.mjs.map +1 -0
- package/dist/chunk-QGE7U4NV.mjs +85 -0
- package/dist/chunk-QGE7U4NV.mjs.map +1 -0
- package/dist/{chunk-XGRBCWK6.mjs → chunk-TEMLWRRT.mjs} +3 -3
- package/dist/chunk-TEMLWRRT.mjs.map +1 -0
- package/dist/{chunk-YBDRISKO.mjs → chunk-TWYUYC4F.mjs} +43 -9
- package/dist/chunk-TWYUYC4F.mjs.map +1 -0
- package/dist/{chunk-LU5JPZ24.mjs → chunk-X2DNXTME.mjs} +6 -6
- package/dist/chunk-X2DNXTME.mjs.map +1 -0
- package/dist/{chunk-DCTJZ742.mjs → chunk-ZLQVRPDS.mjs} +5 -2
- package/dist/chunk-ZLQVRPDS.mjs.map +1 -0
- package/dist/components/copilot-provider/copilot-messages.d.ts +17 -1
- package/dist/components/copilot-provider/copilot-messages.js +46 -7
- package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
- package/dist/components/copilot-provider/copilot-messages.mjs +11 -7
- package/dist/components/copilot-provider/copilotkit-props.d.ts +5 -3
- package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.d.ts +1 -2
- package/dist/components/copilot-provider/copilotkit.js +337 -555
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +11 -11
- package/dist/components/copilot-provider/index.d.ts +1 -2
- package/dist/components/copilot-provider/index.js +337 -555
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +11 -11
- package/dist/components/error-boundary/error-boundary.js +176 -323
- package/dist/components/error-boundary/error-boundary.js.map +1 -1
- package/dist/components/error-boundary/error-boundary.mjs +4 -4
- package/dist/components/error-boundary/error-utils.js.map +1 -1
- package/dist/components/error-boundary/error-utils.mjs +2 -2
- package/dist/components/index.d.ts +1 -2
- package/dist/components/index.js +337 -555
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +11 -11
- package/dist/components/toast/toast-provider.js.map +1 -1
- package/dist/components/toast/toast-provider.mjs +1 -1
- package/dist/components/usage-banner.d.ts +10 -4
- package/dist/components/usage-banner.js +176 -302
- package/dist/components/usage-banner.js.map +1 -1
- package/dist/components/usage-banner.mjs +3 -1
- package/dist/context/copilot-context.d.ts +1 -2
- package/dist/context/copilot-context.js +2 -2
- package/dist/context/copilot-context.js.map +1 -1
- package/dist/context/copilot-context.mjs +1 -1
- package/dist/context/copilot-messages-context.d.ts +11 -15
- package/dist/context/copilot-messages-context.js +4 -1
- package/dist/context/copilot-messages-context.js.map +1 -1
- package/dist/context/copilot-messages-context.mjs +1 -1
- package/dist/context/index.d.ts +2 -2
- package/dist/context/index.js +6 -3
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +2 -2
- package/dist/{copilot-context-bd88d30d.d.ts → copilot-context-256f9020.d.ts} +4 -22
- package/dist/hooks/index.d.ts +7 -5
- package/dist/hooks/index.js +250 -122
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +32 -24
- package/dist/hooks/use-chat.d.ts +1 -2
- package/dist/hooks/use-chat.js +11 -3
- package/dist/hooks/use-chat.js.map +1 -1
- package/dist/hooks/use-chat.mjs +6 -6
- package/dist/hooks/use-coagent-state-render.js +2 -2
- package/dist/hooks/use-coagent-state-render.js.map +1 -1
- package/dist/hooks/use-coagent-state-render.mjs +3 -3
- package/dist/hooks/use-coagent.d.ts +4 -5
- package/dist/hooks/use-coagent.js +114 -81
- package/dist/hooks/use-coagent.js.map +1 -1
- package/dist/hooks/use-coagent.mjs +15 -15
- package/dist/hooks/use-copilot-action.d.ts +1 -1
- package/dist/hooks/use-copilot-action.js +2 -2
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +4 -4
- package/dist/hooks/use-copilot-additional-instructions.js +2 -2
- package/dist/hooks/use-copilot-additional-instructions.js.map +1 -1
- package/dist/hooks/use-copilot-additional-instructions.mjs +2 -2
- package/dist/hooks/use-copilot-authenticated-action.js +2 -2
- package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
- package/dist/hooks/use-copilot-authenticated-action.mjs +5 -5
- package/dist/hooks/use-copilot-chat-headless_c.d.ts +33 -0
- package/dist/hooks/use-copilot-chat-headless_c.js +1837 -0
- package/dist/hooks/use-copilot-chat-headless_c.js.map +1 -0
- package/dist/hooks/use-copilot-chat-headless_c.mjs +31 -0
- package/dist/hooks/use-copilot-chat-headless_c.mjs.map +1 -0
- package/dist/hooks/use-copilot-chat.d.ts +52 -82
- package/dist/hooks/use-copilot-chat.js +60 -13
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +15 -16
- package/dist/hooks/use-copilot-chat_internal.d.ts +177 -0
- package/dist/hooks/use-copilot-chat_internal.js +1770 -0
- package/dist/hooks/use-copilot-chat_internal.js.map +1 -0
- package/dist/hooks/use-copilot-chat_internal.mjs +29 -0
- package/dist/hooks/use-copilot-chat_internal.mjs.map +1 -0
- package/dist/hooks/use-copilot-readable.js +2 -2
- package/dist/hooks/use-copilot-readable.js.map +1 -1
- package/dist/hooks/use-copilot-readable.mjs +2 -2
- package/dist/hooks/use-copilot-runtime-client.js +9 -1
- package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
- package/dist/hooks/use-copilot-runtime-client.mjs +3 -3
- package/dist/hooks/use-langgraph-interrupt-render.js +2 -2
- package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -1
- package/dist/hooks/use-langgraph-interrupt-render.mjs +3 -3
- package/dist/hooks/use-langgraph-interrupt.d.ts +3 -4
- package/dist/hooks/use-langgraph-interrupt.js +32 -11
- package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
- package/dist/hooks/use-langgraph-interrupt.mjs +15 -15
- package/dist/hooks/use-make-copilot-document-readable.js +2 -2
- package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
- package/dist/index-08c43df1.d.ts +36 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js +460 -471
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +34 -26
- package/dist/lib/copilot-task.d.ts +1 -2
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +12 -12
- package/dist/lib/index.d.ts +1 -2
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +12 -12
- package/dist/types/interrupt-action.d.ts +2 -3
- package/dist/utils/dev-console.d.ts +1 -1
- package/dist/utils/dev-console.js +9 -1
- package/dist/utils/dev-console.js.map +1 -1
- package/dist/utils/dev-console.mjs +1 -1
- package/dist/utils/extract.d.ts +2 -2
- package/dist/utils/extract.js.map +1 -1
- package/dist/utils/extract.mjs +11 -11
- package/dist/utils/index.d.ts +3 -3
- package/dist/utils/index.js +9 -1
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +11 -11
- package/dist/utils/suggestions.d.ts +2 -2
- package/dist/utils/suggestions.js.map +1 -1
- package/dist/utils/suggestions.mjs +11 -11
- package/package.json +3 -3
- package/src/components/copilot-provider/copilot-messages.tsx +57 -1
- package/src/components/copilot-provider/copilotkit-props.tsx +4 -1
- package/src/components/copilot-provider/copilotkit.tsx +20 -10
- package/src/components/error-boundary/error-boundary.tsx +5 -15
- package/src/components/toast/toast-provider.tsx +1 -3
- package/src/components/usage-banner.tsx +193 -316
- package/src/context/copilot-context.tsx +12 -6
- package/src/context/copilot-messages-context.tsx +7 -1
- package/src/hooks/__tests__/use-coagent-config.test.ts +8 -1
- package/src/hooks/index.ts +7 -2
- package/src/hooks/use-coagent.ts +18 -20
- package/src/hooks/use-copilot-action.ts +1 -1
- package/src/hooks/use-copilot-chat-headless_c.ts +187 -0
- package/src/hooks/use-copilot-chat.ts +64 -495
- package/src/hooks/use-copilot-chat_internal.ts +543 -0
- package/src/hooks/use-langgraph-interrupt.ts +1 -1
- package/src/utils/dev-console.ts +18 -2
- package/dist/chunk-57K2ZJ5F.mjs +0 -348
- package/dist/chunk-57K2ZJ5F.mjs.map +0 -1
- package/dist/chunk-CQPYJIBH.mjs +0 -1
- package/dist/chunk-DCTJZ742.mjs.map +0 -1
- package/dist/chunk-G35QHAQ6.mjs.map +0 -1
- package/dist/chunk-GFJW4RIM.mjs +0 -9
- package/dist/chunk-GFJW4RIM.mjs.map +0 -1
- package/dist/chunk-LIGLZ53V.mjs.map +0 -1
- package/dist/chunk-LU5JPZ24.mjs.map +0 -1
- package/dist/chunk-NAM55D5I.mjs.map +0 -1
- package/dist/chunk-SJJNFYGQ.mjs.map +0 -1
- package/dist/chunk-XGRBCWK6.mjs.map +0 -1
- package/dist/chunk-YAF2LATQ.mjs.map +0 -1
- package/dist/chunk-YBDRISKO.mjs.map +0 -1
- package/dist/chunk-YVBDAURK.mjs.map +0 -1
- /package/dist/{chunk-DF4YG4PF.mjs.map → chunk-3RHHNUVV.mjs.map} +0 -0
- /package/dist/{chunk-LNAQ7JG3.mjs.map → chunk-6EKLRL7B.mjs.map} +0 -0
- /package/dist/{chunk-O5KV32S5.mjs.map → chunk-ADZDXHVC.mjs.map} +0 -0
- /package/dist/{chunk-4CFY3CON.mjs.map → chunk-CLMDRYEN.mjs.map} +0 -0
- /package/dist/{chunk-RGKZCCPA.mjs.map → chunk-DLEXVOQE.mjs.map} +0 -0
- /package/dist/{chunk-JWAXDYOW.mjs.map → chunk-FAUNHSQU.mjs.map} +0 -0
- /package/dist/{chunk-Q6FZZJ5A.mjs.map → chunk-IN7GE4NO.mjs.map} +0 -0
- /package/dist/{chunk-YSQ5I2AE.mjs.map → chunk-JBLMXZ3O.mjs.map} +0 -0
- /package/dist/{chunk-PZXTDFMX.mjs.map → chunk-JJDXTTEN.mjs.map} +0 -0
- /package/dist/{chunk-CQPYJIBH.mjs.map → chunk-KDAZGZ24.mjs.map} +0 -0
- /package/dist/{chunk-3OQM3NEK.mjs.map → chunk-N4WEHORG.mjs.map} +0 -0
package/dist/chunk-57K2ZJ5F.mjs
DELETED
|
@@ -1,348 +0,0 @@
|
|
|
1
|
-
// src/components/usage-banner.tsx
|
|
2
|
-
import { Severity, ERROR_NAMES, ErrorVisibility } from "@copilotkit/shared";
|
|
3
|
-
import { jsx, jsxs } from "react/jsx-runtime";
|
|
4
|
-
var defaultIcons = {
|
|
5
|
-
[Severity.CRITICAL]: /* @__PURE__ */ jsxs(
|
|
6
|
-
"svg",
|
|
7
|
-
{
|
|
8
|
-
viewBox: "0 0 24 24",
|
|
9
|
-
width: "16",
|
|
10
|
-
height: "16",
|
|
11
|
-
stroke: "currentColor",
|
|
12
|
-
strokeWidth: "2.5",
|
|
13
|
-
fill: "none",
|
|
14
|
-
strokeLinecap: "round",
|
|
15
|
-
strokeLinejoin: "round",
|
|
16
|
-
children: [
|
|
17
|
-
/* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "10" }),
|
|
18
|
-
/* @__PURE__ */ jsx("line", { x1: "15", y1: "9", x2: "9", y2: "15" }),
|
|
19
|
-
/* @__PURE__ */ jsx("line", { x1: "9", y1: "9", x2: "15", y2: "15" })
|
|
20
|
-
]
|
|
21
|
-
}
|
|
22
|
-
),
|
|
23
|
-
[Severity.WARNING]: /* @__PURE__ */ jsxs(
|
|
24
|
-
"svg",
|
|
25
|
-
{
|
|
26
|
-
viewBox: "0 0 24 24",
|
|
27
|
-
width: "16",
|
|
28
|
-
height: "16",
|
|
29
|
-
stroke: "currentColor",
|
|
30
|
-
strokeWidth: "2.5",
|
|
31
|
-
fill: "none",
|
|
32
|
-
strokeLinecap: "round",
|
|
33
|
-
strokeLinejoin: "round",
|
|
34
|
-
children: [
|
|
35
|
-
/* @__PURE__ */ jsx("path", { d: "m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z" }),
|
|
36
|
-
/* @__PURE__ */ jsx("line", { x1: "12", y1: "9", x2: "12", y2: "13" }),
|
|
37
|
-
/* @__PURE__ */ jsx("line", { x1: "12", y1: "17", x2: "12.01", y2: "17" })
|
|
38
|
-
]
|
|
39
|
-
}
|
|
40
|
-
),
|
|
41
|
-
[Severity.INFO]: /* @__PURE__ */ jsxs(
|
|
42
|
-
"svg",
|
|
43
|
-
{
|
|
44
|
-
viewBox: "0 0 24 24",
|
|
45
|
-
width: "16",
|
|
46
|
-
height: "16",
|
|
47
|
-
stroke: "currentColor",
|
|
48
|
-
strokeWidth: "2.5",
|
|
49
|
-
fill: "none",
|
|
50
|
-
strokeLinecap: "round",
|
|
51
|
-
strokeLinejoin: "round",
|
|
52
|
-
children: [
|
|
53
|
-
/* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "10" }),
|
|
54
|
-
/* @__PURE__ */ jsx("line", { x1: "12", y1: "16", x2: "12", y2: "12" }),
|
|
55
|
-
/* @__PURE__ */ jsx("line", { x1: "12", y1: "8", x2: "12.01", y2: "8" })
|
|
56
|
-
]
|
|
57
|
-
}
|
|
58
|
-
)
|
|
59
|
-
};
|
|
60
|
-
function UsageBanner({
|
|
61
|
-
severity = Severity.CRITICAL,
|
|
62
|
-
message = "",
|
|
63
|
-
icon,
|
|
64
|
-
onClose,
|
|
65
|
-
actions
|
|
66
|
-
}) {
|
|
67
|
-
if (!message || !severity) {
|
|
68
|
-
return null;
|
|
69
|
-
}
|
|
70
|
-
const parseMessage = (rawMessage) => {
|
|
71
|
-
if (rawMessage.toLowerCase().includes("authentication") || rawMessage.toLowerCase().includes("api key")) {
|
|
72
|
-
return "Authentication failed. Please check your API key.";
|
|
73
|
-
}
|
|
74
|
-
if (rawMessage.toLowerCase().includes("rate limit")) {
|
|
75
|
-
return "Rate limit exceeded. Please try again later.";
|
|
76
|
-
}
|
|
77
|
-
if (rawMessage.toLowerCase().includes("checkpointer")) {
|
|
78
|
-
return "Agent configuration error. Please check your setup.";
|
|
79
|
-
}
|
|
80
|
-
let cleanMessage2 = rawMessage;
|
|
81
|
-
cleanMessage2 = cleanMessage2.split(" - ")[0];
|
|
82
|
-
cleanMessage2 = cleanMessage2.split(": Error code")[0];
|
|
83
|
-
cleanMessage2 = cleanMessage2.split(": 401")[0];
|
|
84
|
-
cleanMessage2 = cleanMessage2.split(": 403")[0];
|
|
85
|
-
cleanMessage2 = cleanMessage2.split(": 404")[0];
|
|
86
|
-
cleanMessage2 = cleanMessage2.split(": 500")[0];
|
|
87
|
-
cleanMessage2 = cleanMessage2.replace(/See more:.*$/g, "").trim();
|
|
88
|
-
if (cleanMessage2.includes("{") || cleanMessage2.includes("'") || cleanMessage2.length > 60) {
|
|
89
|
-
return "Configuration error. Please check your setup.";
|
|
90
|
-
}
|
|
91
|
-
return cleanMessage2 || "An error occurred. Please check your configuration.";
|
|
92
|
-
};
|
|
93
|
-
const cleanMessage = parseMessage(message);
|
|
94
|
-
const Icon = icon || defaultIcons[severity];
|
|
95
|
-
const themeConfigs = {
|
|
96
|
-
[Severity.INFO]: {
|
|
97
|
-
bg: "rgba(239, 246, 255, 0.95)",
|
|
98
|
-
border: "#93c5fd",
|
|
99
|
-
text: "#1e40af",
|
|
100
|
-
icon: "#3b82f6",
|
|
101
|
-
primaryBtn: "#3b82f6",
|
|
102
|
-
primaryBtnHover: "#2563eb"
|
|
103
|
-
},
|
|
104
|
-
[Severity.WARNING]: {
|
|
105
|
-
bg: "rgba(255, 251, 235, 0.95)",
|
|
106
|
-
border: "#fbbf24",
|
|
107
|
-
text: "#92400e",
|
|
108
|
-
icon: "#f59e0b",
|
|
109
|
-
primaryBtn: "#f59e0b",
|
|
110
|
-
primaryBtnHover: "#d97706"
|
|
111
|
-
},
|
|
112
|
-
[Severity.CRITICAL]: {
|
|
113
|
-
bg: "rgba(254, 242, 242, 0.95)",
|
|
114
|
-
border: "#f87171",
|
|
115
|
-
text: "#991b1b",
|
|
116
|
-
icon: "#ef4444",
|
|
117
|
-
primaryBtn: "#ef4444",
|
|
118
|
-
primaryBtnHover: "#dc2626"
|
|
119
|
-
}
|
|
120
|
-
};
|
|
121
|
-
const themeConfig = themeConfigs[severity] || themeConfigs[Severity.CRITICAL];
|
|
122
|
-
return /* @__PURE__ */ jsxs(
|
|
123
|
-
"div",
|
|
124
|
-
{
|
|
125
|
-
style: {
|
|
126
|
-
position: "fixed",
|
|
127
|
-
bottom: "24px",
|
|
128
|
-
left: "50%",
|
|
129
|
-
transform: "translateX(-50%)",
|
|
130
|
-
width: "400px",
|
|
131
|
-
maxWidth: "90vw",
|
|
132
|
-
zIndex: 1e4,
|
|
133
|
-
animation: "bannerSlideIn 0.3s cubic-bezier(0.16, 1, 0.3, 1)"
|
|
134
|
-
},
|
|
135
|
-
children: [
|
|
136
|
-
/* @__PURE__ */ jsx("style", { children: `
|
|
137
|
-
@keyframes bannerSlideIn {
|
|
138
|
-
from {
|
|
139
|
-
opacity: 0;
|
|
140
|
-
transform: translateX(-50%) translateY(20px);
|
|
141
|
-
scale: 0.95;
|
|
142
|
-
}
|
|
143
|
-
to {
|
|
144
|
-
opacity: 1;
|
|
145
|
-
transform: translateX(-50%) translateY(0);
|
|
146
|
-
scale: 1;
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
` }),
|
|
150
|
-
/* @__PURE__ */ jsxs(
|
|
151
|
-
"div",
|
|
152
|
-
{
|
|
153
|
-
style: {
|
|
154
|
-
borderRadius: "12px",
|
|
155
|
-
border: `1px solid ${themeConfig.border}`,
|
|
156
|
-
background: themeConfig.bg,
|
|
157
|
-
padding: "14px",
|
|
158
|
-
boxShadow: "0 8px 32px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.08)",
|
|
159
|
-
position: "relative",
|
|
160
|
-
backdropFilter: "blur(12px)",
|
|
161
|
-
WebkitBackdropFilter: "blur(12px)",
|
|
162
|
-
boxSizing: "border-box",
|
|
163
|
-
overflow: "hidden"
|
|
164
|
-
},
|
|
165
|
-
children: [
|
|
166
|
-
onClose && /* @__PURE__ */ jsx(
|
|
167
|
-
"button",
|
|
168
|
-
{
|
|
169
|
-
onClick: onClose,
|
|
170
|
-
style: {
|
|
171
|
-
position: "absolute",
|
|
172
|
-
top: "8px",
|
|
173
|
-
right: "8px",
|
|
174
|
-
background: "rgba(255, 255, 255, 0.9)",
|
|
175
|
-
border: "none",
|
|
176
|
-
color: themeConfig.text,
|
|
177
|
-
cursor: "pointer",
|
|
178
|
-
fontSize: "16px",
|
|
179
|
-
lineHeight: "1",
|
|
180
|
-
padding: "4px",
|
|
181
|
-
borderRadius: "4px",
|
|
182
|
-
width: "20px",
|
|
183
|
-
height: "20px",
|
|
184
|
-
display: "flex",
|
|
185
|
-
alignItems: "center",
|
|
186
|
-
justifyContent: "center"
|
|
187
|
-
},
|
|
188
|
-
title: "Close",
|
|
189
|
-
children: "\xD7"
|
|
190
|
-
}
|
|
191
|
-
),
|
|
192
|
-
/* @__PURE__ */ jsx(
|
|
193
|
-
"div",
|
|
194
|
-
{
|
|
195
|
-
style: {
|
|
196
|
-
fontSize: "14px",
|
|
197
|
-
fontWeight: 500,
|
|
198
|
-
color: themeConfig.text,
|
|
199
|
-
lineHeight: "1.4",
|
|
200
|
-
fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
|
|
201
|
-
paddingRight: onClose ? "30px" : "0",
|
|
202
|
-
marginBottom: actions ? "12px" : "0",
|
|
203
|
-
wordBreak: "break-word",
|
|
204
|
-
overflow: "hidden",
|
|
205
|
-
textOverflow: "ellipsis",
|
|
206
|
-
display: "-webkit-box",
|
|
207
|
-
WebkitLineClamp: 2,
|
|
208
|
-
WebkitBoxOrient: "vertical"
|
|
209
|
-
},
|
|
210
|
-
children: cleanMessage
|
|
211
|
-
}
|
|
212
|
-
),
|
|
213
|
-
actions && /* @__PURE__ */ jsxs(
|
|
214
|
-
"div",
|
|
215
|
-
{
|
|
216
|
-
style: {
|
|
217
|
-
display: "flex",
|
|
218
|
-
gap: "8px",
|
|
219
|
-
flexWrap: "wrap"
|
|
220
|
-
},
|
|
221
|
-
children: [
|
|
222
|
-
actions.secondary && /* @__PURE__ */ jsx(
|
|
223
|
-
"button",
|
|
224
|
-
{
|
|
225
|
-
onClick: actions.secondary.onClick,
|
|
226
|
-
style: {
|
|
227
|
-
borderRadius: "8px",
|
|
228
|
-
padding: "6px 12px",
|
|
229
|
-
fontSize: "13px",
|
|
230
|
-
fontWeight: 500,
|
|
231
|
-
color: themeConfig.text,
|
|
232
|
-
backgroundColor: "rgba(255, 255, 255, 0.9)",
|
|
233
|
-
border: `1px solid ${themeConfig.border}`,
|
|
234
|
-
cursor: "pointer",
|
|
235
|
-
transition: "all 0.2s ease",
|
|
236
|
-
fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
|
|
237
|
-
},
|
|
238
|
-
onMouseOver: (e) => {
|
|
239
|
-
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 1)";
|
|
240
|
-
e.currentTarget.style.transform = "translateY(-1px)";
|
|
241
|
-
},
|
|
242
|
-
onMouseOut: (e) => {
|
|
243
|
-
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.9)";
|
|
244
|
-
e.currentTarget.style.transform = "translateY(0)";
|
|
245
|
-
},
|
|
246
|
-
children: actions.secondary.label
|
|
247
|
-
}
|
|
248
|
-
),
|
|
249
|
-
actions.primary && /* @__PURE__ */ jsx(
|
|
250
|
-
"button",
|
|
251
|
-
{
|
|
252
|
-
onClick: actions.primary.onClick,
|
|
253
|
-
style: {
|
|
254
|
-
borderRadius: "8px",
|
|
255
|
-
padding: "6px 12px",
|
|
256
|
-
fontSize: "13px",
|
|
257
|
-
fontWeight: 600,
|
|
258
|
-
color: "#fff",
|
|
259
|
-
backgroundColor: themeConfig.primaryBtn,
|
|
260
|
-
border: "none",
|
|
261
|
-
cursor: "pointer",
|
|
262
|
-
transition: "all 0.2s ease",
|
|
263
|
-
boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)",
|
|
264
|
-
fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
|
|
265
|
-
},
|
|
266
|
-
onMouseOver: (e) => {
|
|
267
|
-
e.currentTarget.style.backgroundColor = themeConfig.primaryBtnHover;
|
|
268
|
-
e.currentTarget.style.transform = "translateY(-1px)";
|
|
269
|
-
e.currentTarget.style.boxShadow = "0 4px 12px rgba(0, 0, 0, 0.2)";
|
|
270
|
-
},
|
|
271
|
-
onMouseOut: (e) => {
|
|
272
|
-
e.currentTarget.style.backgroundColor = themeConfig.primaryBtn;
|
|
273
|
-
e.currentTarget.style.transform = "translateY(0)";
|
|
274
|
-
e.currentTarget.style.boxShadow = "0 2px 8px rgba(0, 0, 0, 0.15)";
|
|
275
|
-
},
|
|
276
|
-
children: actions.primary.label
|
|
277
|
-
}
|
|
278
|
-
)
|
|
279
|
-
]
|
|
280
|
-
}
|
|
281
|
-
)
|
|
282
|
-
]
|
|
283
|
-
}
|
|
284
|
-
)
|
|
285
|
-
]
|
|
286
|
-
}
|
|
287
|
-
);
|
|
288
|
-
}
|
|
289
|
-
function renderCopilotKitUsage(error, onClose) {
|
|
290
|
-
if (error.visibility !== ErrorVisibility.BANNER) {
|
|
291
|
-
return null;
|
|
292
|
-
}
|
|
293
|
-
const extractUrlFromMessage = (message) => {
|
|
294
|
-
const linkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;
|
|
295
|
-
const match = linkRegex.exec(message);
|
|
296
|
-
return match ? match[2] : null;
|
|
297
|
-
};
|
|
298
|
-
const getErrorActions = (error2) => {
|
|
299
|
-
switch (error2.name) {
|
|
300
|
-
case ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR:
|
|
301
|
-
return {
|
|
302
|
-
primary: {
|
|
303
|
-
label: "Sign In",
|
|
304
|
-
onClick: () => window.location.href = "https://cloud.copilotkit.ai"
|
|
305
|
-
}
|
|
306
|
-
};
|
|
307
|
-
case ERROR_NAMES.UPGRADE_REQUIRED_ERROR:
|
|
308
|
-
return {
|
|
309
|
-
primary: {
|
|
310
|
-
label: "Upgrade",
|
|
311
|
-
onClick: () => window.location.href = "https://copilotkit.ai/"
|
|
312
|
-
}
|
|
313
|
-
};
|
|
314
|
-
case ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR:
|
|
315
|
-
case ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR:
|
|
316
|
-
case ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR:
|
|
317
|
-
return {
|
|
318
|
-
primary: {
|
|
319
|
-
label: "View Docs",
|
|
320
|
-
onClick: () => {
|
|
321
|
-
var _a;
|
|
322
|
-
const urlFromMessage = extractUrlFromMessage(error2.message);
|
|
323
|
-
const urlFromExtensions = (_a = error2.extensions) == null ? void 0 : _a.troubleshootingUrl;
|
|
324
|
-
const url = urlFromMessage || urlFromExtensions || "https://docs.copilotkit.ai/troubleshooting/common-issues";
|
|
325
|
-
window.open(url, "_blank");
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
};
|
|
329
|
-
default:
|
|
330
|
-
return void 0;
|
|
331
|
-
}
|
|
332
|
-
};
|
|
333
|
-
return /* @__PURE__ */ jsx(
|
|
334
|
-
UsageBanner,
|
|
335
|
-
{
|
|
336
|
-
severity: error.severity || Severity.CRITICAL,
|
|
337
|
-
message: error.message,
|
|
338
|
-
onClose,
|
|
339
|
-
actions: getErrorActions(error)
|
|
340
|
-
}
|
|
341
|
-
);
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
export {
|
|
345
|
-
UsageBanner,
|
|
346
|
-
renderCopilotKitUsage
|
|
347
|
-
};
|
|
348
|
-
//# sourceMappingURL=chunk-57K2ZJ5F.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/components/usage-banner.tsx"],"sourcesContent":["import { Severity, CopilotKitError, ERROR_NAMES, ErrorVisibility } from \"@copilotkit/shared\";\n\ninterface UsageBannerProps {\n severity?: Severity;\n message?: string;\n icon?: React.ReactNode;\n onClose?: () => void;\n actions?: {\n primary?: {\n label: string;\n onClick: () => void;\n };\n secondary?: {\n label: string;\n onClick: () => void;\n };\n };\n}\n\nconst defaultIcons: Record<Severity, JSX.Element> = {\n [Severity.CRITICAL]: (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"16\"\n height=\"16\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n fill=\"none\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"15\" y1=\"9\" x2=\"9\" y2=\"15\" />\n <line x1=\"9\" y1=\"9\" x2=\"15\" y2=\"15\" />\n </svg>\n ),\n [Severity.WARNING]: (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"16\"\n height=\"16\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n fill=\"none\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z\" />\n <line x1=\"12\" y1=\"9\" x2=\"12\" y2=\"13\" />\n <line x1=\"12\" y1=\"17\" x2=\"12.01\" y2=\"17\" />\n </svg>\n ),\n [Severity.INFO]: (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"16\"\n height=\"16\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n fill=\"none\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"12\" y1=\"16\" x2=\"12\" y2=\"12\" />\n <line x1=\"12\" y1=\"8\" x2=\"12.01\" y2=\"8\" />\n </svg>\n ),\n};\n\nexport function UsageBanner({\n severity = Severity.CRITICAL,\n message = \"\",\n icon,\n onClose,\n actions,\n}: UsageBannerProps) {\n if (!message || !severity) {\n return null;\n }\n\n // Enhanced message parsing to clean up technical details\n const parseMessage = (rawMessage: string) => {\n // console.log(\"Raw message:\", rawMessage); // Debug\n\n // Super aggressive cleaning - handle common error patterns first\n if (\n rawMessage.toLowerCase().includes(\"authentication\") ||\n rawMessage.toLowerCase().includes(\"api key\")\n ) {\n return \"Authentication failed. Please check your API key.\";\n }\n\n if (rawMessage.toLowerCase().includes(\"rate limit\")) {\n return \"Rate limit exceeded. Please try again later.\";\n }\n\n if (rawMessage.toLowerCase().includes(\"checkpointer\")) {\n return \"Agent configuration error. Please check your setup.\";\n }\n\n // For any other error, extract just the main error type\n let cleanMessage = rawMessage;\n\n // Remove everything after the first \" - \" or \":\" followed by technical details\n cleanMessage = cleanMessage.split(\" - \")[0];\n cleanMessage = cleanMessage.split(\": Error code\")[0];\n cleanMessage = cleanMessage.split(\": 401\")[0];\n cleanMessage = cleanMessage.split(\": 403\")[0];\n cleanMessage = cleanMessage.split(\": 404\")[0];\n cleanMessage = cleanMessage.split(\": 500\")[0];\n\n // Remove \"See more\" links\n cleanMessage = cleanMessage.replace(/See more:.*$/g, \"\").trim();\n\n // If still too technical, just show a generic message\n if (cleanMessage.includes(\"{\") || cleanMessage.includes(\"'\") || cleanMessage.length > 60) {\n return \"Configuration error. Please check your setup.\";\n }\n\n return cleanMessage || \"An error occurred. Please check your configuration.\";\n };\n\n const cleanMessage = parseMessage(message);\n const Icon = icon || defaultIcons[severity];\n\n const themeConfigs = {\n [Severity.INFO]: {\n bg: \"rgba(239, 246, 255, 0.95)\",\n border: \"#93c5fd\",\n text: \"#1e40af\",\n icon: \"#3b82f6\",\n primaryBtn: \"#3b82f6\",\n primaryBtnHover: \"#2563eb\",\n },\n [Severity.WARNING]: {\n bg: \"rgba(255, 251, 235, 0.95)\",\n border: \"#fbbf24\",\n text: \"#92400e\",\n icon: \"#f59e0b\",\n primaryBtn: \"#f59e0b\",\n primaryBtnHover: \"#d97706\",\n },\n [Severity.CRITICAL]: {\n bg: \"rgba(254, 242, 242, 0.95)\",\n border: \"#f87171\",\n text: \"#991b1b\",\n icon: \"#ef4444\",\n primaryBtn: \"#ef4444\",\n primaryBtnHover: \"#dc2626\",\n },\n };\n\n const themeConfig = themeConfigs[severity] || themeConfigs[Severity.CRITICAL];\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"24px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n width: \"400px\",\n maxWidth: \"90vw\",\n zIndex: 10000,\n animation: \"bannerSlideIn 0.3s cubic-bezier(0.16, 1, 0.3, 1)\",\n }}\n >\n <style>\n {`\n @keyframes bannerSlideIn {\n from {\n opacity: 0;\n transform: translateX(-50%) translateY(20px);\n scale: 0.95;\n }\n to {\n opacity: 1;\n transform: translateX(-50%) translateY(0);\n scale: 1;\n }\n }\n `}\n </style>\n <div\n style={{\n borderRadius: \"12px\",\n border: `1px solid ${themeConfig.border}`,\n background: themeConfig.bg,\n padding: \"14px\",\n boxShadow: \"0 8px 32px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.08)\",\n position: \"relative\",\n backdropFilter: \"blur(12px)\",\n WebkitBackdropFilter: \"blur(12px)\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n {/* Close button */}\n {onClose && (\n <button\n onClick={onClose}\n style={{\n position: \"absolute\",\n top: \"8px\",\n right: \"8px\",\n background: \"rgba(255, 255, 255, 0.9)\",\n border: \"none\",\n color: themeConfig.text,\n cursor: \"pointer\",\n fontSize: \"16px\",\n lineHeight: \"1\",\n padding: \"4px\",\n borderRadius: \"4px\",\n width: \"20px\",\n height: \"20px\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n }}\n title=\"Close\"\n >\n ×\n </button>\n )}\n\n {/* Message */}\n <div\n style={{\n fontSize: \"14px\",\n fontWeight: 500,\n color: themeConfig.text,\n lineHeight: \"1.4\",\n fontFamily: \"-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif\",\n paddingRight: onClose ? \"30px\" : \"0\",\n marginBottom: actions ? \"12px\" : \"0\",\n wordBreak: \"break-word\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n display: \"-webkit-box\",\n WebkitLineClamp: 2,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {cleanMessage}\n </div>\n\n {/* Actions */}\n {actions && (\n <div\n style={{\n display: \"flex\",\n gap: \"8px\",\n flexWrap: \"wrap\",\n }}\n >\n {actions.secondary && (\n <button\n onClick={actions.secondary.onClick}\n style={{\n borderRadius: \"8px\",\n padding: \"6px 12px\",\n fontSize: \"13px\",\n fontWeight: 500,\n color: themeConfig.text,\n backgroundColor: \"rgba(255, 255, 255, 0.9)\",\n border: `1px solid ${themeConfig.border}`,\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n fontFamily: \"-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif\",\n }}\n onMouseOver={(e) => {\n e.currentTarget.style.backgroundColor = \"rgba(255, 255, 255, 1)\";\n e.currentTarget.style.transform = \"translateY(-1px)\";\n }}\n onMouseOut={(e) => {\n e.currentTarget.style.backgroundColor = \"rgba(255, 255, 255, 0.9)\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {actions.secondary.label}\n </button>\n )}\n {actions.primary && (\n <button\n onClick={actions.primary.onClick}\n style={{\n borderRadius: \"8px\",\n padding: \"6px 12px\",\n fontSize: \"13px\",\n fontWeight: 600,\n color: \"#fff\",\n backgroundColor: themeConfig.primaryBtn,\n border: \"none\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n boxShadow: \"0 2px 8px rgba(0, 0, 0, 0.15)\",\n fontFamily: \"-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif\",\n }}\n onMouseOver={(e) => {\n e.currentTarget.style.backgroundColor = themeConfig.primaryBtnHover;\n e.currentTarget.style.transform = \"translateY(-1px)\";\n e.currentTarget.style.boxShadow = \"0 4px 12px rgba(0, 0, 0, 0.2)\";\n }}\n onMouseOut={(e) => {\n e.currentTarget.style.backgroundColor = themeConfig.primaryBtn;\n e.currentTarget.style.transform = \"translateY(0)\";\n e.currentTarget.style.boxShadow = \"0 2px 8px rgba(0, 0, 0, 0.15)\";\n }}\n >\n {actions.primary.label}\n </button>\n )}\n </div>\n )}\n </div>\n </div>\n );\n}\n\nexport function renderCopilotKitUsage(error: CopilotKitError, onClose?: () => void) {\n // Route based on error visibility level\n if (error.visibility !== ErrorVisibility.BANNER) {\n return null;\n }\n\n // Extract URL from markdown links in the message\n const extractUrlFromMessage = (message: string): string | null => {\n const linkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const match = linkRegex.exec(message);\n return match ? match[2] : null;\n };\n\n // Get action button based on error type\n const getErrorActions = (error: CopilotKitError) => {\n switch (error.name) {\n case ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR:\n return {\n primary: {\n label: \"Sign In\",\n onClick: () => (window.location.href = \"https://cloud.copilotkit.ai\"),\n },\n };\n case ERROR_NAMES.UPGRADE_REQUIRED_ERROR:\n return {\n primary: {\n label: \"Upgrade\",\n onClick: () => (window.location.href = \"https://copilotkit.ai/\"),\n },\n };\n case ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR:\n case ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR:\n case ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR:\n return {\n primary: {\n label: \"View Docs\",\n onClick: () => {\n // Try to get URL from the error message first, then extensions, then default\n const urlFromMessage = extractUrlFromMessage(error.message);\n const urlFromExtensions = (error.extensions as any)?.troubleshootingUrl;\n const url =\n urlFromMessage ||\n urlFromExtensions ||\n \"https://docs.copilotkit.ai/troubleshooting/common-issues\";\n window.open(url, \"_blank\");\n },\n },\n };\n default:\n return undefined;\n }\n };\n\n return (\n <UsageBanner\n severity={error.severity || Severity.CRITICAL}\n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,MAClB,KAAK,YAAY;AACf,eAAO;AAAA,UACL,SAAS;AAAA,YACP,OAAO;AAAA,YACP,SAAS,MAAO,OAAO,SAAS,OAAO;AAAA,UACzC;AAAA,QACF;AAAA,MACF,KAAK,YAAY;AACf,eAAO;AAAA,UACL,SAAS;AAAA,YACP,OAAO;AAAA,YACP,SAAS,MAAO,OAAO,SAAS,OAAO;AAAA,UACzC;AAAA,QACF;AAAA,MACF,KAAK,YAAY;AAAA,MACjB,KAAK,YAAY;AAAA,MACjB,KAAK,YAAY;AACf,eAAO;AAAA,UACL,SAAS;AAAA,YACP,OAAO;AAAA,YACP,SAAS,MAAM;AApW3B;AAsWc,oBAAM,iBAAiB,sBAAsBA,OAAM,OAAO;AAC1D,oBAAM,qBAAqB,KAAAA,OAAM,eAAN,mBAA0B;AACrD,oBAAM,MACJ,kBACA,qBACA;AACF,qBAAO,KAAK,KAAK,QAAQ;AAAA,YAC3B;AAAA,UACF;AAAA,QACF;AAAA,MACF;AACE,eAAO;AAAA,IACX;AAAA,EACF;AAEA,SACE;AAAA,IAAC;AAAA;AAAA,MACC,UAAU,MAAM,YAAY,SAAS;AAAA,MACrC,SAAS,MAAM;AAAA,MACf;AAAA,MACA,SAAS,gBAAgB,KAAK;AAAA;AAAA,EAChC;AAEJ;","names":["cleanMessage","error"]}
|
package/dist/chunk-CQPYJIBH.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
//# sourceMappingURL=chunk-CQPYJIBH.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context/copilot-messages-context.tsx"],"sourcesContent":["/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport React from \"react\";\n\nexport interface CopilotMessagesContextParams {\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n}\n\nconst emptyCopilotContext: CopilotMessagesContextParams = {\n messages: [],\n setMessages: () => [],\n};\n\nexport const CopilotMessagesContext =\n React.createContext<CopilotMessagesContextParams>(emptyCopilotContext);\n\nexport function useCopilotMessagesContext(): CopilotMessagesContextParams {\n const context = React.useContext(CopilotMessagesContext);\n if (context === emptyCopilotContext) {\n throw new Error(\n \"A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`\",\n );\n }\n return context;\n}\n"],"mappings":";AAKA,OAAO,WAAW;AAOlB,IAAM,sBAAoD;AAAA,EACxD,UAAU,CAAC;AAAA,EACX,aAAa,MAAM,CAAC;AACtB;AAEO,IAAM,yBACX,MAAM,cAA4C,mBAAmB;AAEhE,SAAS,4BAA0D;AACxE,QAAM,UAAU,MAAM,WAAW,sBAAsB;AACvD,MAAI,YAAY,qBAAqB;AACnC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-coagent.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport {\n CopilotContextParams,\n CopilotMessagesContextParams,\n useCopilotContext,\n useCopilotMessagesContext,\n} from \"../context\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { useCopilotChat } from \"./use-copilot-chat\";\nimport { Message } from \"@copilotkit/shared\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nimport { parseJson, CopilotKitAgentDiscoveryError } from \"@copilotkit/shared\";\n\ninterface UseCoagentOptionsBase {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * @deprecated - use \"config.configurable\"\n * Config to pass to a LangGraph Agent\n */\n configurable?: Record<string, any>;\n /**\n * Config to pass to a LangGraph Agent\n */\n config?: {\n configurable?: Record<string, any>;\n [key: string]: any;\n };\n}\n\ninterface WithInternalStateManagementAndInitial<T> extends UseCoagentOptionsBase {\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement extends UseCoagentOptionsBase {\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> extends UseCoagentOptionsBase {\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The name of the current LangGraph node.\n */\n nodeName?: string;\n /**\n * The ID of the thread the agent is running in.\n */\n threadId?: string;\n /**\n * A boolean indicating if the agent is currently running.\n */\n running: boolean;\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n /**\n * A function to start the agent.\n */\n start: () => void;\n /**\n * A function to stop the agent.\n */\n stop: () => void;\n /**\n * A function to re-run the agent. The hint function can be used to provide a hint to the agent\n * about why it is being re-run again.\n */\n run: (hint?: HintFunction) => Promise<void>;\n}\n\nexport interface HintFunctionParams {\n /**\n * The previous state of the agent.\n */\n previousState: any;\n /**\n * The current state of the agent.\n */\n currentState: any;\n}\n\nexport type HintFunction = (params: HintFunctionParams) => Message | undefined;\n\n/**\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of the agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences \"agentic copilots\". To get started using agentic copilots, which\n * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.\n */\nexport function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {\n const generalContext = useCopilotContext();\n const { availableAgents } = generalContext;\n const { setBannerError } = useToast();\n const lastLoadedThreadId = useRef<string>();\n const lastLoadedState = useRef<any>();\n\n const { name } = options;\n useEffect(() => {\n if (availableAgents?.length && !availableAgents.some((a) => a.name === name)) {\n const message = `(useCoAgent): Agent \"${name}\" not found. Make sure the agent exists and is properly configured.`;\n console.warn(message);\n\n // Route to banner instead of toast for consistency\n const agentError = new CopilotKitAgentDiscoveryError({\n agentName: name,\n availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id })),\n });\n setBannerError(agentError);\n }\n }, [availableAgents]);\n\n const messagesContext = useCopilotMessagesContext();\n const context = { ...generalContext, ...messagesContext };\n const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } =\n context;\n const { appendMessage, runChatCompletion } = useCopilotChat();\n const headers = {\n ...(copilotApiConfig.headers || {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n showDevConsole: context.showDevConsole,\n });\n\n // if we manage state internally, we need to provide a function to set the state\n const setState = useCallback(\n (newState: T | ((prevState: T | undefined) => T)) => {\n // coagentStatesRef.current || {}\n let coagentState: CoagentState = getCoagentState({ coagentStates, name, options });\n const updatedState =\n typeof newState === \"function\" ? (newState as Function)(coagentState.state) : newState;\n\n setCoagentStatesWithRef({\n ...coagentStatesRef.current,\n [name]: {\n ...coagentState,\n state: updatedState,\n },\n });\n },\n [coagentStates, name],\n );\n\n useEffect(() => {\n const fetchAgentState = async () => {\n if (!threadId || threadId === lastLoadedThreadId.current) return;\n\n const result = await runtimeClient.loadAgentState({\n threadId,\n agentName: name,\n });\n\n // Runtime client handles errors automatically via handleGQLErrors\n if (result.error) {\n return; // Don't process data on error\n }\n\n const newState = result.data?.loadAgentState?.state;\n if (newState === lastLoadedState.current) return;\n\n if (result.data?.loadAgentState?.threadExists && newState && newState != \"{}\") {\n lastLoadedState.current = newState;\n lastLoadedThreadId.current = threadId;\n const fetchedState = parseJson(newState, {});\n isExternalStateManagement(options)\n ? options.setState(fetchedState)\n : setState(fetchedState);\n }\n };\n void fetchAgentState();\n }, [threadId]);\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n setState(options.state);\n } else if (coagentStates[name] === undefined) {\n setState(options.initialState === undefined ? {} : options.initialState);\n }\n }, [\n isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined,\n // reset initialstate on reset\n coagentStates[name] === undefined,\n ]);\n\n // Sync config when runtime configuration changes\n useEffect(() => {\n const newConfig = options.config\n ? options.config\n : options.configurable\n ? { configurable: options.configurable }\n : undefined;\n\n if (newConfig === undefined) return;\n\n setCoagentStatesWithRef((prev) => {\n const existing = prev[name] ?? {\n name,\n state: isInternalStateManagementWithInitial(options) ? options.initialState : {},\n config: {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n\n if (JSON.stringify(existing.config) === JSON.stringify(newConfig)) {\n return prev;\n }\n\n return {\n ...prev,\n [name]: {\n ...existing,\n config: newConfig,\n },\n };\n });\n }, [JSON.stringify(options.config), JSON.stringify(options.configurable)]);\n\n const runAgentCallback = useAsyncCallback(\n async (hint?: HintFunction) => {\n await runAgent(name, context, appendMessage, runChatCompletion, hint);\n },\n [name, context, appendMessage, runChatCompletion],\n );\n\n // Return the state and setState function\n return useMemo(() => {\n const coagentState = getCoagentState({ coagentStates, name, options });\n return {\n name,\n nodeName: coagentState.nodeName,\n threadId: coagentState.threadId,\n running: coagentState.running,\n state: coagentState.state,\n setState: isExternalStateManagement(options) ? options.setState : setState,\n start: () => startAgent(name, context),\n stop: () => stopAgent(name, context),\n run: runAgentCallback,\n };\n }, [name, coagentStates, options, setState, runAgentCallback]);\n}\n\nexport function startAgent(name: string, context: CopilotContextParams) {\n const { setAgentSession } = context;\n setAgentSession({\n agentName: name,\n });\n}\n\nexport function stopAgent(name: string, context: CopilotContextParams) {\n const { agentSession, setAgentSession } = context;\n if (agentSession && agentSession.agentName === name) {\n setAgentSession(null);\n context.setCoagentStates((prevAgentStates) => {\n return {\n ...prevAgentStates,\n [name]: {\n ...prevAgentStates[name],\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n },\n };\n });\n } else {\n console.warn(`No agent session found for ${name}`);\n }\n}\n\nexport async function runAgent(\n name: string,\n context: CopilotContextParams & CopilotMessagesContextParams,\n appendMessage: (message: Message) => Promise<void>,\n runChatCompletion: () => Promise<Message[]>,\n hint?: HintFunction,\n) {\n const { agentSession, setAgentSession } = context;\n if (!agentSession || agentSession.agentName !== name) {\n setAgentSession({\n agentName: name,\n });\n }\n\n let previousState: any = null;\n for (let i = context.messages.length - 1; i >= 0; i--) {\n const message = context.messages[i];\n if (message.isAgentStateMessage() && message.agentName === name) {\n previousState = message.state;\n }\n }\n\n let state = context.coagentStatesRef.current?.[name]?.state || {};\n\n if (hint) {\n const hintMessage = hint({ previousState, currentState: state });\n if (hintMessage) {\n await appendMessage(hintMessage);\n } else {\n await runChatCompletion();\n }\n } else {\n await runChatCompletion();\n }\n}\n\nconst isExternalStateManagement = <T>(\n options: UseCoagentOptions<T>,\n): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n};\n\nconst isInternalStateManagementWithInitial = <T>(\n options: UseCoagentOptions<T>,\n): options is WithInternalStateManagementAndInitial<T> => {\n return \"initialState\" in options;\n};\n\nconst getCoagentState = <T>({\n coagentStates,\n name,\n options,\n}: {\n coagentStates: Record<string, CoagentState>;\n name: string;\n options: UseCoagentOptions<T>;\n}) => {\n if (coagentStates[name]) {\n return coagentStates[name];\n } else {\n return {\n name,\n state: isInternalStateManagementWithInitial<T>(options) ? options.initialState : {},\n config: options.config\n ? options.config\n : options.configurable\n ? { configurable: options.configurable }\n : {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,SAAS,aAAa,WAAW,SAAS,cAAc;AAaxD,SAAS,WAAW,qCAAqC;AA8GlD,SAAS,WAAoB,SAAwD;AAC1F,QAAM,iBAAiB,kBAAkB;AACzC,QAAM,EAAE,gBAAgB,IAAI;AAC5B,QAAM,EAAE,eAAe,IAAI,SAAS;AACpC,QAAM,qBAAqB,OAAe;AAC1C,QAAM,kBAAkB,OAAY;AAEpC,QAAM,EAAE,KAAK,IAAI;AACjB,YAAU,MAAM;AACd,SAAI,mDAAiB,WAAU,CAAC,gBAAgB,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI,GAAG;AAC5E,YAAM,UAAU,wBAAwB;AACxC,cAAQ,KAAK,OAAO;AAGpB,YAAM,aAAa,IAAI,8BAA8B;AAAA,QACnD,WAAW;AAAA,QACX,iBAAiB,gBAAgB,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,EAAE,GAAG,EAAE;AAAA,MAC1E,CAAC;AACD,qBAAe,UAAU;AAAA,IAC3B;AAAA,EACF,GAAG,CAAC,eAAe,CAAC;AAEpB,QAAM,kBAAkB,0BAA0B;AAClD,QAAM,UAAU,kCAAK,iBAAmB;AACxC,QAAM,EAAE,eAAe,kBAAkB,yBAAyB,UAAU,iBAAiB,IAC3F;AACF,QAAM,EAAE,eAAe,kBAAkB,IAAI,eAAe;AAC5D,QAAM,UAAU,mBACV,iBAAiB,WAAW,CAAC;AAGnC,QAAM,gBAAgB,wBAAwB;AAAA,IAC5C,KAAK,iBAAiB;AAAA,IACtB,cAAc,iBAAiB;AAAA,IAC/B;AAAA,IACA,aAAa,iBAAiB;AAAA,IAC9B,gBAAgB,QAAQ;AAAA,EAC1B,CAAC;AAGD,QAAM,WAAW;AAAA,IACf,CAAC,aAAoD;AAEnD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cAAc,WAAW;AAAA,MACjC,OAAO;AACL,cAAM,kBAAkB;AAAA,MAC1B;AAAA,IACF,OAAO;AACL,YAAM,kBAAkB;AAAA,IAC1B;AAAA,EACF;AAAA;AAEA,IAAM,4BAA4B,CAChC,YAC8C;AAC9C,SAAO,WAAW,WAAW,cAAc;AAC7C;AAEA,IAAM,uCAAuC,CAC3C,YACwD;AACxD,SAAO,kBAAkB;AAC3B;AAEA,IAAM,kBAAkB,CAAI;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AACF,MAIM;AACJ,MAAI,cAAc,IAAI,GAAG;AACvB,WAAO,cAAc,IAAI;AAAA,EAC3B,OAAO;AACL,WAAO;AAAA,MACL;AAAA,MACA,OAAO,qCAAwC,OAAO,IAAI,QAAQ,eAAe,CAAC;AAAA,MAClF,QAAQ,QAAQ,SACZ,QAAQ,SACR,QAAQ,eACN,EAAE,cAAc,QAAQ,aAAa,IACrC,CAAC;AAAA,MACP,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,UAAU;AAAA,MACV,UAAU;AAAA,MACV,OAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
|
package/dist/chunk-GFJW4RIM.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/dev-console.ts"],"sourcesContent":["export function shouldShowDevConsole(showDevConsole: boolean): boolean {\n return showDevConsole;\n}\n"],"mappings":";AAAO,SAAS,qBAAqB,gBAAkC;AACrE,SAAO;AACT;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-copilot-chat.ts"],"sourcesContent":["/**\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChat } from \"@copilotkit/react-core\";\n * import { Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\n *\n * export function YourComponent() {\n * const { appendMessage } = useCopilotChat();\n *\n * appendMessage(\n * new TextMessage({\n * content: \"Hello World\",\n * role: Role.User,\n * }),\n * );\n *\n * // optionally, you can append a message without running chat completion\n * appendMessage(yourMessage, { followUp: false });\n * }\n * ```\n *\n * ### Working with Suggestions\n *\n * ```tsx\n * import { useCopilotChat, useCopilotChatSuggestions } from \"@copilotkit/react-core\";\n *\n * export function YourComponent() {\n * const {\n * suggestions,\n * setSuggestions,\n * generateSuggestions,\n * isLoadingSuggestions\n * } = useCopilotChat();\n *\n * // Configure AI suggestion generation\n * useCopilotChatSuggestions({\n * instructions: \"Suggest helpful actions based on the current context\",\n * maxSuggestions: 3\n * });\n *\n * // Manual suggestion control\n * const handleCustomSuggestion = () => {\n * setSuggestions([{ title: \"Custom Action\", message: \"Perform custom action\" }]);\n * };\n *\n * // Trigger AI generation\n * const handleGenerateSuggestions = async () => {\n * await generateSuggestions();\n * };\n * }\n * ```\n *\n * `useCopilotChat` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * visibleMessages, // An array of messages that are currently visible in the chat.\n * appendMessage, // A function to append a message to the chat.\n * setMessages, // A function to set the messages in the chat.\n * deleteMessage, // A function to delete a message from the chat.\n * reloadMessages, // A function to reload the messages from the API.\n * stopGeneration, // A function to stop the generation of the next message.\n * reset, // A function to reset the chat.\n * isLoading, // A boolean indicating if the chat is loading.\n *\n * // Suggestion control (headless UI)\n * suggestions, // Current suggestions array\n * setSuggestions, // Manually set suggestions\n * generateSuggestions, // Trigger AI suggestion generation\n * resetSuggestions, // Clear all suggestions\n * isLoadingSuggestions, // Whether suggestions are being generated\n * } = useCopilotChat();\n * ```\n */\nimport { useRef, useEffect, useCallback, useState, useMemo } from \"react\";\nimport { AgentSession, useCopilotContext, CopilotContextParams } from \"../context/copilot-context\";\nimport { useCopilotMessagesContext, CopilotMessagesContextParams } from \"../context\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat, AppendMessageOptions } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CoAgentStateRenderHandlerArguments } from \"@copilotkit/shared\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { reloadSuggestions as generateSuggestions } from \"../utils\";\nimport type { SuggestionItem } from \"../utils\";\n\nimport { Message } from \"@copilotkit/shared\";\nimport { Role as gqlRole, TextMessage, aguiToGQL, gqlToAGUI } from \"@copilotkit/runtime-client-gql\";\nimport { useLangGraphInterruptRender } from \"./use-langgraph-interrupt-render\";\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * Initial messages to populate the chat with.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface MCPServerConfig {\n endpoint: string;\n apiKey?: string;\n}\n\nexport interface UseCopilotChatReturn {\n /** Array of messages currently visible in the chat interface */\n visibleMessages: Message[];\n\n /** Send a new message to the chat */\n appendMessage: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n\n /** Replace all messages in the chat */\n setMessages: (messages: Message[]) => void;\n\n /** Remove a specific message by ID */\n deleteMessage: (messageId: string) => void;\n\n /** Regenerate the response for a specific message */\n reloadMessages: (messageId: string) => Promise<void>;\n\n /** Stop the current message generation */\n stopGeneration: () => void;\n\n /** Clear all messages and reset chat state */\n reset: () => void;\n\n /** Whether the chat is currently generating a response */\n isLoading: boolean;\n\n /** Manually trigger chat completion (advanced usage) */\n runChatCompletion: () => Promise<Message[]>;\n\n /** MCP (Model Context Protocol) server configurations */\n mcpServers: MCPServerConfig[];\n\n /** Update MCP server configurations */\n setMcpServers: (mcpServers: MCPServerConfig[]) => void;\n\n /**\n * Current suggestions array\n * Use this to read the current suggestions or in conjunction with setSuggestions for manual control\n */\n suggestions: SuggestionItem[];\n\n /**\n * Manually set suggestions\n * Useful for manual mode or custom suggestion workflows\n */\n setSuggestions: (suggestions: SuggestionItem[]) => void;\n\n /**\n * Trigger AI-powered suggestion generation\n * Uses configurations from useCopilotChatSuggestions hooks\n * Respects global debouncing - only one generation can run at a time\n */\n generateSuggestions: () => Promise<void>;\n\n /**\n * Clear all current suggestions\n * Also resets suggestion generation state\n */\n resetSuggestions: () => void;\n\n /** Whether suggestions are currently being generated */\n isLoadingSuggestions: boolean;\n\n /** Interrupt content for human-in-the-loop workflows */\n interrupt: string | React.ReactElement | null;\n}\n\nlet globalSuggestionPromise: Promise<void> | null = null;\n\nexport function useCopilotChat(options: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const makeSystemMessage = options.makeSystemMessage ?? defaultSystemMessage;\n const {\n getContextString,\n getFunctionCallHandler,\n copilotApiConfig,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n coagentStatesRef,\n setCoagentStatesWithRef,\n coAgentStateRenders,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n chatSuggestionConfiguration,\n suggestions,\n setSuggestions,\n runtimeClient,\n } = useCopilotContext();\n const { messages, setMessages } = useCopilotMessagesContext();\n\n // Simple state for MCP servers (keep for interface compatibility)\n const [mcpServers, setLocalMcpServers] = useState<MCPServerConfig[]>([]);\n\n // Basic suggestion state for programmatic control\n const suggestionsAbortControllerRef = useRef<AbortController | null>(null);\n const isLoadingSuggestionsRef = useRef<boolean>(false);\n\n const abortSuggestions = useCallback(\n (clear: boolean = true) => {\n suggestionsAbortControllerRef.current?.abort(\"suggestions aborted by user\");\n suggestionsAbortControllerRef.current = null;\n if (clear) {\n setSuggestions([]);\n }\n },\n [setSuggestions],\n );\n\n // Memoize context with stable dependencies only\n const stableContext = useMemo(() => {\n return {\n actions,\n copilotApiConfig,\n chatSuggestionConfiguration,\n messages,\n setMessages,\n getContextString,\n runtimeClient,\n };\n }, [\n JSON.stringify(Object.keys(actions)),\n copilotApiConfig.chatApiEndpoint,\n messages.length,\n Object.keys(chatSuggestionConfiguration).length,\n ]);\n\n // Programmatic suggestion generation function\n const generateSuggestionsFunc = useCallback(async () => {\n // If a global suggestion is running, ignore this call\n if (globalSuggestionPromise) {\n return globalSuggestionPromise;\n }\n\n globalSuggestionPromise = (async () => {\n try {\n abortSuggestions();\n isLoadingSuggestionsRef.current = true;\n suggestionsAbortControllerRef.current = new AbortController();\n\n setSuggestions([]);\n\n await generateSuggestions(\n stableContext as CopilotContextParams & CopilotMessagesContextParams,\n chatSuggestionConfiguration,\n setSuggestions,\n suggestionsAbortControllerRef,\n );\n } catch (error) {\n // Re-throw to allow caller to handle the error\n throw error;\n } finally {\n isLoadingSuggestionsRef.current = false;\n globalSuggestionPromise = null;\n }\n })();\n\n return globalSuggestionPromise;\n }, [stableContext, chatSuggestionConfiguration, setSuggestions, abortSuggestions]);\n\n const resetSuggestions = useCallback(() => {\n setSuggestions([]);\n }, [setSuggestions]);\n\n // MCP servers logic\n useEffect(() => {\n if (mcpServers.length > 0) {\n const serversCopy = [...mcpServers];\n copilotApiConfig.mcpServers = serversCopy;\n if (!copilotApiConfig.properties) {\n copilotApiConfig.properties = {};\n }\n copilotApiConfig.properties.mcpServers = serversCopy;\n }\n }, [mcpServers, copilotApiConfig]);\n\n const setMcpServers = useCallback((servers: MCPServerConfig[]) => {\n setLocalMcpServers(servers);\n }, []);\n\n // Move these function declarations above the useChat call\n const onCoAgentStateRender = useAsyncCallback(\n async (args: CoAgentStateRenderHandlerArguments) => {\n const { name, nodeName, state } = args;\n let action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && action.nodeName === nodeName,\n );\n if (!action) {\n action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && !action.nodeName,\n );\n }\n if (action) {\n await action.handler?.({ state, nodeName });\n }\n },\n [coAgentStateRenders],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = getContextString([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return new TextMessage({\n content: systemMessageMaker(contextString, chatInstructions),\n role: gqlRole.System,\n });\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n // Get chat helpers with updated config\n const { append, reload, stop, runChatCompletion } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: aguiToGQL(options.initialMessages || []),\n onFunctionCall: getFunctionCallHandler(),\n onCoAgentStateRender,\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n agentLock,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n });\n\n const latestAppend = useUpdatedRef(append);\n const latestAppendFunc = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions) => {\n abortSuggestions(options?.clearSuggestions);\n return await latestAppend.current(aguiToGQL([message])[0], options);\n },\n [latestAppend],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useAsyncCallback(\n async (messageId: string) => {\n return await latestReload.current(messageId);\n },\n [latestReload],\n );\n\n const latestStop = useUpdatedRef(stop);\n const latestStopFunc = useCallback(() => {\n return latestStop.current();\n }, [latestStop]);\n\n const latestDelete = useUpdatedRef(deleteMessage);\n const latestDeleteFunc = useCallback(\n (messageId: string) => {\n return latestDelete.current(messageId);\n },\n [latestDelete],\n );\n\n const latestSetMessages = useUpdatedRef(setMessages);\n const latestSetMessagesFunc = useCallback(\n (messages: Message[]) => {\n return latestSetMessages.current(aguiToGQL(messages));\n },\n [latestSetMessages],\n );\n\n const latestRunChatCompletion = useUpdatedRef(runChatCompletion);\n const latestRunChatCompletionFunc = useAsyncCallback(async () => {\n return await latestRunChatCompletion.current!();\n }, [latestRunChatCompletion]);\n\n const reset = useCallback(() => {\n latestStopFunc();\n setMessages([]);\n setRunId(null);\n setCoagentStatesWithRef({});\n let initialAgentSession: AgentSession | null = null;\n if (agentLock) {\n initialAgentSession = {\n agentName: agentLock,\n };\n }\n setAgentSession(initialAgentSession);\n // Reset suggestions when chat is reset\n resetSuggestions();\n }, [\n latestStopFunc,\n setMessages,\n setThreadId,\n setCoagentStatesWithRef,\n setAgentSession,\n agentLock,\n resetSuggestions,\n ]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n const interrupt = useLangGraphInterruptRender();\n\n return {\n visibleMessages: gqlToAGUI(messages, actions, coAgentStateRenders),\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n reset: latestResetFunc,\n deleteMessage: latestDeleteFunc,\n runChatCompletion: latestRunChatCompletionFunc,\n isLoading,\n mcpServers,\n setMcpServers,\n suggestions,\n setSuggestions,\n generateSuggestions: generateSuggestionsFunc,\n resetSuggestions,\n isLoadingSuggestions: isLoadingSuggestionsRef.current,\n interrupt,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\nIn case of a function error:\n- If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.\n- If the error's source is unclear or seems unrelated to your input, do not attempt further retries.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAkFA,SAAS,QAAQ,WAAW,aAAa,UAAU,eAAe;AAYlE,SAAS,QAAQ,SAAS,aAAa,WAAW,iBAAiB;AAkGnE,IAAI,0BAAgD;AAE7C,SAAS,eAAe,UAAiC,CAAC,GAAyB;AAlM1F;AAmME,QAAM,qBAAoB,aAAQ,sBAAR,YAA6B;AACvD,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,kBAAkB;AACtB,QAAM,EAAE,UAAU,YAAY,IAAI,0BAA0B;AAG5D,QAAM,CAAC,YAAY,kBAAkB,IAAI,SAA4B,CAAC,CAAC;AAGvE,QAAM,gCAAgC,OAA+B,IAAI;AACzE,QAAM,0BAA0B,OAAgB,KAAK;AAErD,QAAM,mBAAmB;AAAA,IACvB,CAAC,QAAiB,SAAS;AA3O/B,UAAAA;AA4OM,OAAAA,MAAA,8BAA8B,YAA9B,gBAAAA,IAAuC,MAAM;AAC7C,oCAA8B,UAAU;AAC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E;","names":["_a","action","options","messages"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-copilot-action.ts"],"sourcesContent":["/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { Parameter, randomId } from \"@copilotkit/shared\";\nimport { createElement, Fragment, useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport {\n ActionRenderProps,\n ActionRenderPropsNoArgsWait,\n ActionRenderPropsWait,\n CatchAllFrontendAction,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();\n const idRef = useRef<string>(randomId());\n const renderAndWaitRef = useRef<RenderAndWaitForResponse | null>(null);\n const activatingMessageIdRef = useRef<string | null>(null);\n const { addToast } = useToast();\n\n // clone the action to avoid mutating the original object\n action = { ...action };\n\n // const { currentlyActivatingHitlActionMessageIdRef } = useCopilotContext() as any; // <-- REMOVE THIS FOR NOW\n\n // If the developer provides a renderAndWaitForResponse function, we transform the action\n // to use a promise internally, so that we can treat it like a normal action.\n if (\n // renderAndWaitForResponse is not available for catch all actions\n isFrontendAction(action) &&\n // check if renderAndWaitForResponse is set\n (action.renderAndWait || action.renderAndWaitForResponse)\n ) {\n (action as any)._isRenderAndWait = true; // Internal flag to identify this action type later\n const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;\n // remove the renderAndWait function from the action\n action.renderAndWait = undefined;\n action.renderAndWaitForResponse = undefined;\n\n // Add a method for use-chat.ts to set the activating message ID.\n // This helps correlate the action instance with the message being processed by use-chat.\n (action as any)._setActivatingMessageId = (id: string | null) => {\n activatingMessageIdRef.current = id;\n };\n\n // add a handler that will be called when the action is executed\n action.handler = useAsyncCallback(async () => {\n const currentActivatingId = activatingMessageIdRef.current;\n // we create a new promise when the handler is called\n let resolve: (result: any) => void;\n let reject: (error: any) => void;\n const promise = new Promise<any>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n renderAndWaitRef.current = {\n promise,\n resolve: resolve!,\n reject: reject!,\n messageId: currentActivatingId,\n };\n // then we await the promise (it will be resolved in the original renderAndWait function)\n const result = await promise;\n return result;\n }, []) as any;\n\n // add a render function that will be called when the action is rendered\n action.render = ((props: ActionRenderProps<T> & { messageId?: string }): React.ReactElement => {\n const currentRenderMessageId = props.messageId;\n // For renderAndWaitForResponse, the 'executing' state might be set by use-chat before\n // this specific action instance's handler (and thus its promise) is ready.\n // This logic adjusts the status to 'inProgress' if the current render\n // isn't for the actively processing HITL action, preventing premature interaction.\n let status = props.status;\n if (props.status === \"executing\") {\n if (!renderAndWaitRef.current || !renderAndWaitRef.current.promise) {\n status = \"inProgress\";\n } else if (\n renderAndWaitRef.current.messageId !== currentRenderMessageId &&\n activatingMessageIdRef.current !== currentRenderMessageId\n ) {\n status = \"inProgress\";\n }\n // If conditions met, status remains 'executing'\n }\n // Create type safe waitProps based on whether T extends empty array or not\n const waitProps = {\n status,\n args: props.args,\n result: props.result,\n // handler and respond should only be provided if this is the truly active instance\n // and its promise infrastructure is ready.\n handler:\n status === \"executing\" &&\n renderAndWaitRef.current &&\n renderAndWaitRef.current.messageId === currentRenderMessageId\n ? renderAndWaitRef.current!.resolve\n : undefined,\n respond:\n status === \"executing\" &&\n renderAndWaitRef.current &&\n renderAndWaitRef.current.messageId === currentRenderMessageId\n ? renderAndWaitRef.current!.resolve\n : undefined,\n } as T extends [] ? ActionRenderPropsNoArgsWait<T> : ActionRenderPropsWait<T>;\n\n // Type guard to check if renderAndWait is for no args case\n const isNoArgsRenderWait = (\n _fn:\n | ((props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement)\n | ((props: ActionRenderPropsWait<T>) => React.ReactElement),\n ): _fn is (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement => {\n return action.parameters?.length === 0;\n };\n\n // Safely call renderAndWait with correct props type\n if (renderAndWait) {\n if (isNoArgsRenderWait(renderAndWait)) {\n return renderAndWait(waitProps as ActionRenderPropsNoArgsWait<T>);\n } else {\n return renderAndWait(waitProps as ActionRenderPropsWait<T>);\n }\n }\n\n // Return empty Fragment instead of null\n return createElement(Fragment);\n }) as any;\n }\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n // catch all actions don't have a handler\n if (isFrontendAction(action)) {\n actions[idRef.current].handler = action.handler as any;\n }\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n // TODO: using as any here because the type definitions are getting to tricky\n // not wasting time on this now - we know the types are compatible\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n }\n }\n }\n\n useEffect(() => {\n const hasDuplicate = Object.values(actions).some(\n (otherAction) => otherAction.name === action.name && otherAction !== actions[idRef.current],\n );\n\n if (hasDuplicate) {\n addToast({\n type: \"warning\",\n message: `Found an already registered action with name ${action.name}.`,\n id: `dup-action-${action.name}`,\n });\n }\n }, [actions]);\n\n useEffect(() => {\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n // see comment about type safety above\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n // UPDATE: We now have access, we should remove the entry if not referenced by any message.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n isFrontendAction(action) ? action.description : undefined,\n action.name,\n isFrontendAction(action) ? action.disabled : undefined,\n isFrontendAction(action) ? action.available : undefined,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(isFrontendAction(action) ? action.parameters : []),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\nfunction isFrontendAction<T extends Parameter[]>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n): action is FrontendAction<T> {\n return action.name !== \"*\";\n}\n\ninterface RenderAndWaitForResponse {\n promise: Promise<any>;\n resolve: (result: any) => void;\n reject: (error: any) => void;\n messageId: string | null;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoIA,SAAoB,gBAAgB;AACpC,SAAS,eAAe,UAAU,WAAW,cAAc;AAqBpD,SAAS,iBACd,QACA,cACM;AACN,QA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