@copilotkit/react-core 1.5.1-next.1 → 1.5.1-next.3

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.
Files changed (145) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/{chunk-SFPANIOY.mjs → chunk-2KCEHGSI.mjs} +49 -99
  3. package/dist/chunk-2KCEHGSI.mjs.map +1 -0
  4. package/dist/{chunk-YL6V3QTN.mjs → chunk-6OR25P32.mjs} +15 -42
  5. package/dist/chunk-6OR25P32.mjs.map +1 -0
  6. package/dist/{chunk-VQDGBYWQ.mjs → chunk-DDVXFNYA.mjs} +31 -55
  7. package/dist/chunk-DDVXFNYA.mjs.map +1 -0
  8. package/dist/{chunk-NYBGR2NK.mjs → chunk-FXHKK52V.mjs} +13 -14
  9. package/dist/chunk-FXHKK52V.mjs.map +1 -0
  10. package/dist/{chunk-VPTC36RZ.mjs → chunk-H4VZMKR6.mjs} +2 -2
  11. package/dist/{chunk-OAF4ASJH.mjs → chunk-H7LSKIDK.mjs} +23 -70
  12. package/dist/chunk-H7LSKIDK.mjs.map +1 -0
  13. package/dist/chunk-JDQCJCAQ.mjs +295 -0
  14. package/dist/chunk-JDQCJCAQ.mjs.map +1 -0
  15. package/dist/{chunk-STZUYPHJ.mjs → chunk-LODRWFMB.mjs} +2 -14
  16. package/dist/chunk-LODRWFMB.mjs.map +1 -0
  17. package/dist/{chunk-MKEQ2MJG.mjs → chunk-MWZO6TUR.mjs} +13 -29
  18. package/dist/chunk-MWZO6TUR.mjs.map +1 -0
  19. package/dist/{chunk-7LRDVJH5.mjs → chunk-ODN4H66E.mjs} +2 -6
  20. package/dist/chunk-ODN4H66E.mjs.map +1 -0
  21. package/dist/{chunk-6KHA5W5R.mjs → chunk-QDGDXRRJ.mjs} +2 -2
  22. package/dist/{chunk-ODAH4HNG.mjs → chunk-XINZBP3J.mjs} +2 -2
  23. package/dist/{chunk-ODAH4HNG.mjs.map → chunk-XINZBP3J.mjs.map} +1 -1
  24. package/dist/components/copilot-provider/copilot-messages.d.ts +0 -1
  25. package/dist/components/copilot-provider/copilotkit-props.d.ts +0 -5
  26. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  27. package/dist/components/copilot-provider/copilotkit.d.ts +0 -1
  28. package/dist/components/copilot-provider/copilotkit.js +91 -191
  29. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  30. package/dist/components/copilot-provider/copilotkit.mjs +7 -8
  31. package/dist/components/copilot-provider/index.d.ts +0 -1
  32. package/dist/components/copilot-provider/index.js +91 -191
  33. package/dist/components/copilot-provider/index.js.map +1 -1
  34. package/dist/components/copilot-provider/index.mjs +7 -8
  35. package/dist/components/index.d.ts +0 -1
  36. package/dist/components/index.js +91 -191
  37. package/dist/components/index.js.map +1 -1
  38. package/dist/components/index.mjs +7 -8
  39. package/dist/components/toast/toast-provider.d.ts +1 -2
  40. package/dist/components/toast/toast-provider.js +62 -76
  41. package/dist/components/toast/toast-provider.js.map +1 -1
  42. package/dist/components/toast/toast-provider.mjs +1 -1
  43. package/dist/context/copilot-context.d.ts +3 -15
  44. package/dist/context/copilot-context.js +1 -13
  45. package/dist/context/copilot-context.js.map +1 -1
  46. package/dist/context/copilot-context.mjs +1 -1
  47. package/dist/context/index.d.ts +1 -1
  48. package/dist/context/index.js +1 -13
  49. package/dist/context/index.js.map +1 -1
  50. package/dist/context/index.mjs +4 -4
  51. package/dist/hooks/index.d.ts +1 -2
  52. package/dist/hooks/index.js +293 -624
  53. package/dist/hooks/index.js.map +1 -1
  54. package/dist/hooks/index.mjs +22 -30
  55. package/dist/hooks/use-chat.d.ts +3 -31
  56. package/dist/hooks/use-chat.js +205 -443
  57. package/dist/hooks/use-chat.js.map +1 -1
  58. package/dist/hooks/use-chat.mjs +3 -4
  59. package/dist/hooks/use-coagent-state-render.d.ts +2 -2
  60. package/dist/hooks/use-coagent-state-render.js +1 -13
  61. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  62. package/dist/hooks/use-coagent-state-render.mjs +2 -2
  63. package/dist/hooks/use-coagent.d.ts +1 -14
  64. package/dist/hooks/use-coagent.js +262 -580
  65. package/dist/hooks/use-coagent.js.map +1 -1
  66. package/dist/hooks/use-coagent.mjs +11 -19
  67. package/dist/hooks/use-copilot-action.d.ts +2 -12
  68. package/dist/hooks/use-copilot-action.js +17 -167
  69. package/dist/hooks/use-copilot-action.js.map +1 -1
  70. package/dist/hooks/use-copilot-action.mjs +2 -4
  71. package/dist/hooks/use-copilot-chat.d.ts +0 -2
  72. package/dist/hooks/use-copilot-chat.js +238 -532
  73. package/dist/hooks/use-copilot-chat.js.map +1 -1
  74. package/dist/hooks/use-copilot-chat.mjs +10 -12
  75. package/dist/hooks/use-copilot-readable.js +1 -13
  76. package/dist/hooks/use-copilot-readable.js.map +1 -1
  77. package/dist/hooks/use-copilot-readable.mjs +2 -2
  78. package/dist/hooks/use-copilot-runtime-client.js +4 -110
  79. package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
  80. package/dist/hooks/use-copilot-runtime-client.mjs +2 -2
  81. package/dist/hooks/use-make-copilot-document-readable.js +1 -13
  82. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  83. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  84. package/dist/index.d.ts +3 -3
  85. package/dist/index.js +391 -703
  86. package/dist/index.js.map +1 -1
  87. package/dist/index.mjs +30 -38
  88. package/dist/lib/copilot-task.d.ts +1 -6
  89. package/dist/lib/copilot-task.js +17 -55
  90. package/dist/lib/copilot-task.js.map +1 -1
  91. package/dist/lib/copilot-task.mjs +8 -10
  92. package/dist/lib/index.d.ts +1 -1
  93. package/dist/lib/index.js +17 -55
  94. package/dist/lib/index.js.map +1 -1
  95. package/dist/lib/index.mjs +8 -10
  96. package/dist/types/frontend-action.d.ts +2 -21
  97. package/dist/types/frontend-action.js +0 -34
  98. package/dist/types/frontend-action.js.map +1 -1
  99. package/dist/types/frontend-action.mjs +0 -7
  100. package/dist/types/index.d.ts +1 -2
  101. package/dist/types/index.js.map +1 -1
  102. package/dist/utils/extract.d.ts +2 -3
  103. package/dist/utils/extract.js +3 -21
  104. package/dist/utils/extract.js.map +1 -1
  105. package/dist/utils/extract.mjs +7 -8
  106. package/dist/utils/index.js +3 -21
  107. package/dist/utils/index.js.map +1 -1
  108. package/dist/utils/index.mjs +9 -10
  109. package/package.json +5 -5
  110. package/src/components/copilot-provider/copilotkit-props.tsx +10 -0
  111. package/src/components/copilot-provider/copilotkit.tsx +44 -7
  112. package/src/components/toast/toast-provider.tsx +1 -1
  113. package/src/context/copilot-context.tsx +28 -2
  114. package/src/hooks/index.ts +1 -0
  115. package/src/hooks/use-chat.ts +15 -5
  116. package/src/hooks/use-coagent-state-render.ts +11 -0
  117. package/src/hooks/use-coagent.ts +11 -1
  118. package/src/hooks/use-copilot-authenticated-action.ts +60 -0
  119. package/src/hooks/use-copilot-chat.ts +1 -0
  120. package/dist/chunk-7LRDVJH5.mjs.map +0 -1
  121. package/dist/chunk-M3SYKJ3W.mjs +0 -393
  122. package/dist/chunk-M3SYKJ3W.mjs.map +0 -1
  123. package/dist/chunk-MKEQ2MJG.mjs.map +0 -1
  124. package/dist/chunk-NYBGR2NK.mjs.map +0 -1
  125. package/dist/chunk-OAF4ASJH.mjs.map +0 -1
  126. package/dist/chunk-QCUP6HLK.mjs +0 -37
  127. package/dist/chunk-QCUP6HLK.mjs.map +0 -1
  128. package/dist/chunk-SFPANIOY.mjs.map +0 -1
  129. package/dist/chunk-STZUYPHJ.mjs.map +0 -1
  130. package/dist/chunk-VQDGBYWQ.mjs.map +0 -1
  131. package/dist/chunk-XERJQUHA.mjs +0 -31
  132. package/dist/chunk-XERJQUHA.mjs.map +0 -1
  133. package/dist/chunk-YL6V3QTN.mjs.map +0 -1
  134. package/dist/components/error-boundary/error-boundary.d.ts +0 -22
  135. package/dist/components/error-boundary/error-boundary.js +0 -183
  136. package/dist/components/error-boundary/error-boundary.js.map +0 -1
  137. package/dist/components/error-boundary/error-boundary.mjs +0 -12
  138. package/dist/components/error-boundary/error-boundary.mjs.map +0 -1
  139. package/dist/components/error-boundary/error-utils.d.ts +0 -11
  140. package/dist/components/error-boundary/error-utils.js +0 -177
  141. package/dist/components/error-boundary/error-utils.js.map +0 -1
  142. package/dist/components/error-boundary/error-utils.mjs +0 -13
  143. package/dist/components/error-boundary/error-utils.mjs.map +0 -1
  144. /package/dist/{chunk-VPTC36RZ.mjs.map → chunk-H4VZMKR6.mjs.map} +0 -0
  145. /package/dist/{chunk-6KHA5W5R.mjs.map → chunk-QDGDXRRJ.mjs.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # ui
2
2
 
3
+ ## 1.5.1-next.3
4
+
5
+ ### Patch Changes
6
+
7
+ - test prerelease #3
8
+ - Updated dependencies
9
+ - @copilotkit/runtime-client-gql@1.5.1-next.3
10
+ - @copilotkit/shared@1.5.1-next.3
11
+
12
+ ## 1.5.1-next.2
13
+
14
+ ### Patch Changes
15
+
16
+ - ed39d40: - [CPK-1034] adds `useCopilotAuthenticatedAction`
17
+ - da280ed: Test prerelease script
18
+ - 649ebcc: - fix: add warning when using agents that are not available on agent related hooks
19
+ - Updated dependencies [da280ed]
20
+ - Updated dependencies [649ebcc]
21
+ - @copilotkit/runtime-client-gql@1.5.1-next.2
22
+ - @copilotkit/shared@1.5.1-next.2
23
+
3
24
  ## 1.5.1-next.1
4
25
 
5
26
  ### Patch Changes
@@ -2,14 +2,10 @@ import {
2
2
  ExclamationMarkIcon
3
3
  } from "./chunk-O7ARI5CV.mjs";
4
4
  import {
5
- __async,
6
5
  __spreadProps,
7
6
  __spreadValues
8
7
  } from "./chunk-SKC7AJIV.mjs";
9
8
 
10
- // src/components/error-boundary/error-utils.tsx
11
- import { useCallback as useCallback2 } from "react";
12
-
13
9
  // src/components/toast/toast-provider.tsx
14
10
  import { createContext, useContext, useState, useCallback } from "react";
15
11
  import { jsx, jsxs } from "react/jsx-runtime";
@@ -27,13 +23,8 @@ function ToastProvider({
27
23
  }) {
28
24
  const [toasts, setToasts] = useState([]);
29
25
  const addToast = useCallback((toast) => {
30
- var _a;
31
- const id = (_a = toast.id) != null ? _a : Math.random().toString(36).substring(2, 9);
32
- setToasts((currentToasts) => {
33
- if (currentToasts.find((toast2) => toast2.id === id))
34
- return currentToasts;
35
- return [...currentToasts, __spreadProps(__spreadValues({}, toast), { id })];
36
- });
26
+ const id = Math.random().toString(36).substring(2, 9);
27
+ setToasts((currentToasts) => [...currentToasts, __spreadProps(__spreadValues({}, toast), { id })]);
37
28
  if (toast.duration) {
38
29
  setTimeout(() => {
39
30
  removeToast(id);
@@ -41,9 +32,54 @@ function ToastProvider({
41
32
  }
42
33
  }, []);
43
34
  const addGraphQLErrorsToast = useCallback((errors) => {
35
+ const errorsToRender = errors.map((error, idx) => {
36
+ var _a;
37
+ const message = error.message;
38
+ const code = (_a = error.extensions) == null ? void 0 : _a.code;
39
+ return /* @__PURE__ */ jsxs(
40
+ "div",
41
+ {
42
+ style: {
43
+ marginTop: idx === 0 ? 0 : 10,
44
+ marginBottom: 14
45
+ },
46
+ children: [
47
+ /* @__PURE__ */ jsx(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
48
+ code && /* @__PURE__ */ jsxs(
49
+ "div",
50
+ {
51
+ style: {
52
+ fontWeight: "600",
53
+ marginBottom: 4
54
+ },
55
+ children: [
56
+ "Copilot Cloud Error:",
57
+ " ",
58
+ /* @__PURE__ */ jsx("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
59
+ ]
60
+ }
61
+ ),
62
+ /* @__PURE__ */ jsx("div", { children: message })
63
+ ]
64
+ },
65
+ idx
66
+ );
67
+ });
44
68
  addToast({
45
69
  type: "error",
46
- message: /* @__PURE__ */ jsx(ErrorToast, { errors })
70
+ message: /* @__PURE__ */ jsxs(
71
+ "div",
72
+ {
73
+ style: {
74
+ fontSize: "13px",
75
+ maxWidth: "600px"
76
+ },
77
+ children: [
78
+ errorsToRender,
79
+ /* @__PURE__ */ jsx("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This is a Copilot Cloud error, and it only displays during local development." })
80
+ ]
81
+ }
82
+ )
47
83
  });
48
84
  }, []);
49
85
  const removeToast = useCallback((id) => {
@@ -149,94 +185,8 @@ function Toast({
149
185
  );
150
186
  }
151
187
 
152
- // src/components/error-boundary/error-utils.tsx
153
- import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
154
- function ErrorToast({ errors }) {
155
- const errorsToRender = errors.map((error, idx) => {
156
- var _a, _b, _c;
157
- const message = "extensions" in error ? (_b = (_a = error.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message : error.message;
158
- const code = "extensions" in error ? (_c = error.extensions) == null ? void 0 : _c.code : null;
159
- return /* @__PURE__ */ jsxs2(
160
- "div",
161
- {
162
- style: {
163
- marginTop: idx === 0 ? 0 : 10,
164
- marginBottom: 14
165
- },
166
- children: [
167
- /* @__PURE__ */ jsx2(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
168
- code && /* @__PURE__ */ jsxs2(
169
- "div",
170
- {
171
- style: {
172
- fontWeight: "600",
173
- marginBottom: 4
174
- },
175
- children: [
176
- "Copilot Cloud Error:",
177
- " ",
178
- /* @__PURE__ */ jsx2("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
179
- ]
180
- }
181
- ),
182
- /* @__PURE__ */ jsx2("div", { children: message })
183
- ]
184
- },
185
- idx
186
- );
187
- });
188
- return /* @__PURE__ */ jsxs2(
189
- "div",
190
- {
191
- style: {
192
- fontSize: "13px",
193
- maxWidth: "600px"
194
- },
195
- children: [
196
- errorsToRender,
197
- /* @__PURE__ */ jsx2("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This error only displays during local development." })
198
- ]
199
- }
200
- );
201
- }
202
- function useErrorToast() {
203
- const { addToast } = useToast();
204
- return useCallback2(
205
- (error) => {
206
- const errorId = error.map((err) => {
207
- var _a, _b;
208
- const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
209
- const stack = err.stack || "";
210
- return btoa(message + stack).slice(0, 32);
211
- }).join("|");
212
- addToast({
213
- type: "error",
214
- id: errorId,
215
- // Toast libraries typically dedupe by id
216
- message: /* @__PURE__ */ jsx2(ErrorToast, { errors: error })
217
- });
218
- },
219
- [addToast]
220
- );
221
- }
222
- function useAsyncCallback(callback, deps) {
223
- const addErrorToast = useErrorToast();
224
- return useCallback2((...args) => __async(this, null, function* () {
225
- try {
226
- return yield callback(...args);
227
- } catch (error) {
228
- console.error("Error in async callback:", error);
229
- addErrorToast([error]);
230
- throw error;
231
- }
232
- }), deps);
233
- }
234
-
235
188
  export {
236
- ErrorToast,
237
- useErrorToast,
238
- useAsyncCallback,
239
189
  useToast,
240
190
  ToastProvider
241
191
  };
242
- //# sourceMappingURL=chunk-SFPANIOY.mjs.map
192
+ //# sourceMappingURL=chunk-2KCEHGSI.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/toast/toast-provider.tsx"],"sourcesContent":["import { useCopilotContext } from \"../../context\";\nimport { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { ExclamationMarkIcon } from \"./exclamation-mark-icon\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: Omit<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const addToast = useCallback((toast: Omit<Toast, \"id\">) => {\n const id = Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => [...currentToasts, { ...toast, id }]);\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n }, []);\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // We do not display these errors unless we are in dev mode.\n // if (!showDevConsole) {\n // return;\n // }\n\n const errorsToRender = errors.map((error, idx) => {\n const message = error.message;\n const code = error.extensions?.code as string;\n\n return (\n <div\n key={idx}\n style={{\n marginTop: idx === 0 ? 0 : 10,\n marginBottom: 14,\n }}\n >\n <ExclamationMarkIcon style={{ marginBottom: 4 }} />\n\n {code && (\n <div\n style={{\n fontWeight: \"600\",\n marginBottom: 4,\n }}\n >\n Copilot Cloud Error:{\" \"}\n <span style={{ fontFamily: \"monospace\", fontWeight: \"normal\" }}>{code}</span>\n </div>\n )}\n <div>{message}</div>\n </div>\n );\n });\n\n addToast({\n type: \"error\",\n message: (\n <div\n style={{\n fontSize: \"13px\",\n maxWidth: \"600px\",\n }}\n >\n {errorsToRender}\n <div style={{ fontSize: \"11px\", opacity: 0.75 }}>\n NOTE: This is a Copilot Cloud error, and it only displays during local development.\n </div>\n </div>\n ),\n });\n }, []);\n\n const removeToast = useCallback((id: string) => {\n setToasts((currentToasts) => currentToasts.filter((toast) => toast.id !== id));\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n };\n\n return (\n <ToastContext.Provider value={value}>\n <div\n style={{\n position: \"fixed\",\n bottom: \"1rem\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 50,\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"0.5rem\",\n }}\n >\n {toasts.length > 1 && (\n <div style={{ textAlign: \"right\" }}>\n <button\n onClick={() => setToasts([])}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n cursor: \"pointer\",\n background: \"white\",\n border: \"1px solid rgba(0,0,0,0.2)\",\n borderRadius: \"4px\",\n }}\n >\n Close All\n </button>\n </div>\n )}\n {toasts.map((toast) => (\n <Toast\n key={toast.id}\n message={toast.message}\n type={toast.type}\n onClose={() => removeToast(toast.id)}\n />\n ))}\n </div>\n {children}\n </ToastContext.Provider>\n );\n}\n\nfunction Toast({\n message,\n type = \"info\",\n onClose,\n}: {\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n onClose: () => void;\n}) {\n const bgColors = {\n info: \"#3b82f6\",\n success: \"#22c55e\",\n warning: \"#eab308\",\n error: \"#ef4444\",\n };\n\n return (\n <div\n style={{\n backgroundColor: bgColors[type],\n color: \"white\",\n padding: \"0.5rem 1rem\",\n borderRadius: \"0.25rem\",\n boxShadow: \"0 2px 4px rgba(0,0,0,0.1)\",\n position: \"relative\",\n minWidth: \"200px\",\n }}\n >\n <div>{message}</div>\n <button\n onClick={onClose}\n style={{\n position: \"absolute\",\n top: \"0\",\n right: \"0\",\n background: \"none\",\n border: \"none\",\n color: \"white\",\n cursor: \"pointer\",\n padding: \"0.5rem\",\n fontSize: \"1rem\",\n }}\n >\n ✕\n </button>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;AAEA,SAAgB,eAAe,YAAY,UAAU,mBAAmB;AAkE9D,cAGE,YAHF;AAhDV,IAAM,eAAe,cAA6C,MAAS;AAEpE,SAAS,WAAW;AACzB,QAAM,UAAU,WAAW,YAAY;AACvC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,8CAA8C;AAAA,EAChE;AACA,SAAO;AACT;AAEO,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AACF,GAGG;AACD,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAkB,CAAC,CAAC;AAChD,QAAM,WAAW,YAAY,CAAC,UAA6B;AACzD,UAAM,KAAK,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,UAAU,GAAG,CAAC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S;AAAA,QACT,cAAc;AAAA,QACd,WAAW;AAAA,QACX,UAAU;AAAA,QACV,UAAU;AAAA,MACZ;AAAA,MAEA;AAAA,4BAAC,SAAK,mBAAQ;AAAA,QACd;AAAA,UAAC;AAAA;AAAA,YACC,SAAS;AAAA,YACT,OAAO;AAAA,cACL,UAAU;AAAA,cACV,KAAK;AAAA,cACL,OAAO;AAAA,cACP,YAAY;AAAA,cACZ,QAAQ;AAAA,cACR,OAAO;AAAA,cACP,QAAQ;AAAA,cACR,SAAS;AAAA,cACT,UAAU;AAAA,YACZ;AAAA,YACD;AAAA;AAAA,QAED;AAAA;AAAA;AAAA,EACF;AAEJ;","names":[]}
@@ -1,27 +1,24 @@
1
- import {
2
- CopilotErrorBoundary
3
- } from "./chunk-QCUP6HLK.mjs";
4
- import {
5
- shouldShowDevConsole
6
- } from "./chunk-MLAS4QUR.mjs";
7
- import {
8
- CopilotMessages
9
- } from "./chunk-XXR4QFAQ.mjs";
10
1
  import {
11
2
  use_flat_category_store_default
12
3
  } from "./chunk-5FHSUKQL.mjs";
13
4
  import {
14
5
  use_tree_default
15
6
  } from "./chunk-6U3UH3KO.mjs";
7
+ import {
8
+ CopilotMessages
9
+ } from "./chunk-XXR4QFAQ.mjs";
16
10
  import {
17
11
  useCopilotRuntimeClient
18
- } from "./chunk-7LRDVJH5.mjs";
12
+ } from "./chunk-ODN4H66E.mjs";
19
13
  import {
20
14
  ToastProvider
21
- } from "./chunk-SFPANIOY.mjs";
15
+ } from "./chunk-2KCEHGSI.mjs";
22
16
  import {
23
17
  CopilotContext
24
- } from "./chunk-STZUYPHJ.mjs";
18
+ } from "./chunk-LODRWFMB.mjs";
19
+ import {
20
+ shouldShowDevConsole
21
+ } from "./chunk-MLAS4QUR.mjs";
25
22
  import {
26
23
  __async,
27
24
  __objRest,
@@ -53,7 +50,7 @@ function CopilotKit(_a) {
53
50
  var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
54
51
  const showDevConsole = props.showDevConsole === void 0 ? "auto" : props.showDevConsole;
55
52
  const enabled = shouldShowDevConsole(showDevConsole);
56
- return /* @__PURE__ */ jsx(ToastProvider, { enabled, children: /* @__PURE__ */ jsx(CopilotErrorBoundary, { children: /* @__PURE__ */ jsx(CopilotKitInternal, __spreadProps(__spreadValues({}, props), { children })) }) });
53
+ return /* @__PURE__ */ jsx(ToastProvider, { enabled, children: /* @__PURE__ */ jsx(CopilotKitInternal, __spreadProps(__spreadValues({}, props), { children })) });
57
54
  }
58
55
  function CopilotKitInternal(_a) {
59
56
  var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
@@ -214,17 +211,6 @@ ${nonDocumentStrings}`;
214
211
  });
215
212
  };
216
213
  const [coagentStates, setCoagentStates] = useState({});
217
- const coagentStatesRef = useRef({});
218
- const setCoagentStatesWithRef = useCallback(
219
- (value) => {
220
- const newValue = typeof value === "function" ? value(coagentStatesRef.current) : value;
221
- coagentStatesRef.current = newValue;
222
- setCoagentStates((prev) => {
223
- return newValue;
224
- });
225
- },
226
- []
227
- );
228
214
  let initialAgentSession = null;
229
215
  if (props.agent) {
230
216
  initialAgentSession = {
@@ -232,9 +218,6 @@ ${nonDocumentStrings}`;
232
218
  };
233
219
  }
234
220
  const [agentSession, setAgentSession] = useState(initialAgentSession);
235
- const [threadId, setThreadId] = useState(null);
236
- const [runId, setRunId] = useState(null);
237
- const chatAbortControllerRef = useRef(null);
238
221
  const showDevConsole = props.showDevConsole === void 0 ? "auto" : props.showDevConsole;
239
222
  return /* @__PURE__ */ jsx(
240
223
  CopilotContext.Provider,
@@ -265,18 +248,9 @@ ${nonDocumentStrings}`;
265
248
  showDevConsole,
266
249
  coagentStates,
267
250
  setCoagentStates,
268
- coagentStatesRef,
269
- setCoagentStatesWithRef,
270
251
  agentSession,
271
252
  setAgentSession,
272
- runtimeClient,
273
- forwardedParameters: props.forwardedParameters || {},
274
- agentLock: props.agent || null,
275
- threadId,
276
- setThreadId,
277
- runId,
278
- setRunId,
279
- chatAbortControllerRef
253
+ runtimeClient
280
254
  },
281
255
  children: /* @__PURE__ */ jsx(CopilotMessages, { children })
282
256
  }
@@ -323,8 +297,7 @@ function extract(_0) {
323
297
  data,
324
298
  abortSignal,
325
299
  stream,
326
- requestType = CopilotRequestType.Task,
327
- forwardedParameters
300
+ requestType = CopilotRequestType.Task
328
301
  }) {
329
302
  var _a, _b;
330
303
  const { messages } = context;
@@ -371,10 +344,10 @@ function extract(_0) {
371
344
  metadata: {
372
345
  requestType
373
346
  },
374
- forwardedParameters: __spreadProps(__spreadValues({}, forwardedParameters != null ? forwardedParameters : {}), {
347
+ forwardedParameters: {
375
348
  toolChoice: "function",
376
349
  toolChoiceFunctionName: action.name
377
- })
350
+ }
378
351
  },
379
352
  properties: context.copilotApiConfig.properties,
380
353
  signal: abortSignal
@@ -450,4 +423,4 @@ export {
450
423
  CopilotKitInternal,
451
424
  defaultCopilotContextCategories
452
425
  };
453
- //# sourceMappingURL=chunk-YL6V3QTN.mjs.map
426
+ //# sourceMappingURL=chunk-6OR25P32.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/extract.ts","../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["import {\n Action,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n MappedParameterTypes,\n Parameter,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n ActionExecutionMessage,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n CopilotRequestType,\n} from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CopilotRuntimeClient } from \"@copilotkit/runtime-client-gql\";\nimport {\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n} from \"@copilotkit/runtime-client-gql\";\n\ninterface InitialState<T extends Parameter[] | [] = []> {\n status: \"initial\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n}\n\ntype StreamHandlerArgs<T extends Parameter[] | [] = []> =\n | InitialState<T>\n | InProgressState<T>\n | CompleteState<T>;\n\ninterface ExtractOptions<T extends Parameter[]> {\n context: CopilotContextParams & CopilotMessagesContextParams;\n instructions: string;\n parameters: T;\n include?: IncludeOptions;\n data?: any;\n abortSignal?: AbortSignal;\n stream?: (args: StreamHandlerArgs<T>) => void;\n requestType?: CopilotRequestType;\n}\n\ninterface IncludeOptions {\n readable?: boolean;\n messages?: boolean;\n}\n\nexport async function extract<const T extends Parameter[]>({\n context,\n instructions,\n parameters,\n include,\n data,\n abortSignal,\n stream,\n requestType = CopilotRequestType.Task,\n}: ExtractOptions<T>): Promise<MappedParameterTypes<T>> {\n const { messages } = context;\n\n const action: Action<any> = {\n name: \"extract\",\n description: instructions,\n parameters,\n handler: (args: any) => {},\n };\n\n const includeReadable = include?.readable ?? false;\n const includeMessages = include?.messages ?? false;\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (includeReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage: Message = new TextMessage({\n content: makeSystemMessage(contextString, instructions),\n role: Role.System,\n });\n\n const instructionsMessage: Message = new TextMessage({\n content: makeInstructionsMessage(instructions),\n role: Role.User,\n });\n\n const response = context.runtimeClient.asStream(\n context.runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [\n {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n },\n ],\n url: window.location.href,\n },\n\n messages: convertMessagesToGqlInput(\n includeMessages\n ? [systemMessage, instructionsMessage, ...filterAgentStateMessages(messages)]\n : [systemMessage, instructionsMessage],\n ),\n metadata: {\n requestType: requestType,\n },\n forwardedParameters: {\n toolChoice: \"function\",\n toolChoiceFunctionName: action.name,\n },\n },\n properties: context.copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n\n const reader = response.getReader();\n\n let isInitial = true;\n\n let actionExecutionMessage: ActionExecutionMessage | undefined = undefined;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (abortSignal?.aborted) {\n throw new Error(\"Aborted\");\n }\n\n actionExecutionMessage = convertGqlOutputToMessages(\n value.generateCopilotResponse.messages,\n ).find((msg) => msg.isActionExecutionMessage()) as ActionExecutionMessage | undefined;\n\n if (!actionExecutionMessage) {\n continue;\n }\n\n stream?.({\n status: isInitial ? \"initial\" : \"inProgress\",\n args: actionExecutionMessage.arguments as Partial<MappedParameterTypes<T>>,\n });\n\n isInitial = false;\n }\n\n if (!actionExecutionMessage) {\n throw new Error(\"extract() failed: No function call occurred\");\n }\n\n stream?.({\n status: \"complete\",\n args: actionExecutionMessage.arguments as MappedParameterTypes<T>,\n });\n\n return actionExecutionMessage.arguments as MappedParameterTypes<T>;\n}\n\n// We need to put this in a user message since some LLMs need\n// at least one user message to function\nfunction makeInstructionsMessage(instructions: string): string {\n return `\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n\nAny additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.\n`;\n}\n\nfunction makeSystemMessage(contextString: string, instructions: string): string {\n return `\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 a function called extract you MUST call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call the function without saying anything else.\n`;\n}\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n} from \"@copilotkit/shared\";\n\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoAgentStateRender } from \"../../types/coagent-action\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"../../hooks/use-copilot-runtime-client\";\nimport { shouldShowDevConsole } from \"../../utils\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const showDevConsole = props.showDevConsole === undefined ? \"auto\" : props.showDevConsole;\n const enabled = shouldShowDevConsole(showDevConsole);\n return (\n <ToastProvider enabled={enabled}>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n if (!props.runtimeUrl && !props.publicApiKey) {\n throw new Error(\n \"Please provide either a runtimeUrl or a publicApiKey to the CopilotKit component.\",\n );\n }\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n const { addElement, removeElement, printTree } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const setCoAgentStateRender = useCallback((id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => {\n return {\n ...prevPoints,\n [id]: stateRender,\n };\n });\n }, []);\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n if (!props.publicApiKey) {\n if (props.cloudRestrictToTopic) {\n throw new Error(\n \"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide a publicApiKey.\",\n );\n }\n }\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n props.publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n ]);\n\n const headers = {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n });\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n };\n\n const removeChatSuggestionConfiguration = (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n };\n\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n\n const showDevConsole = props.showDevConsole === undefined ? \"auto\" : props.showDevConsole;\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n agentSession,\n setAgentSession,\n runtimeClient,\n }}\n >\n <CopilotMessages>{children}</CopilotMessages>\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ messages, name, args }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EAKE;AAAA,OACK;AACP;AAAA,EAGE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACEP,SAAS,aAAa,SAAS,QAAQ,gBAAgB;AASvD,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EAGA;AAAA,OACK;AAiBD;AALC,SAAS,WAAW,IAAyC;AAAzC,eAAE,WA3C7B,IA2C2B,IAAe,kBAAf,IAAe,CAAb;AAC3B,QAAM,iBAAiB,MAAM,mBAAmB,SAAY,SAAS,MAAM;AAC3E,QAAM,UAAU,qBAAqB,cAAc;AACnD,SACE,oBAAC,iBAAc,SACb,8BAAC,qDAAuB,QAAvB,EAA+B,WAAS,GAC3C;AAEJ;AAEO,SAAS,mBAAmB,IAAyC;AAAzC,eAAE,WArDrC,IAqDmC,IAAe,kBAAf,IAAe,CAAb;AAInC,MAAI,CAAC,MAAM,cAAc,CAAC,MAAM,cAAc;AAC5C,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,kBAAkB,MAAM,cAAc;AAE5C,QAAM,CAAC,SAAS,UAAU,IAAI,SAA8C,CAAC,CAAC;AAC9E,QAAM,CAAC,qBAAqB,sBAAsB,IAAI,SAEpD,CAAC,CAAC;AACJ,QAAM,sBAAsB,OAA4B;AAAA,IACtD,SAAS,CAAC;AAAA,IACV,qBAAqB,CAAC;AAAA,EACxB,CAAC;AACD,QAAM,EAAE,YAAY,eAAe,UAAU,IAAI,iBAAQ;AACzD,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,CAAC,kBAAkB,mBAAmB,IAAI,SAAS,EAAE;AAE3D,QAAM;AAAA,IACJ,YAAY;AAAA,IACZ,eAAe;AAAA,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AQ,iBAAiB;AAAA,QACrC,QAAQ;AAAA,MACV,CAAC;AAAA,IACH;AAEA,UAAM,SAAS,SAAS,UAAU;AAElC,QAAI,YAAY;AAEhB,QAAI,yBAA6D;AAEjE,WAAO,MAAM;AACX,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAE1C,UAAI,MAAM;AACR;AAAA,MACF;AAEA,UAAI,2CAAa,SAAS;AACxB,cAAM,IAAI,MAAM,SAAS;AAAA,MAC3B;AAEA,+BAAyB;AAAA,QACvB,MAAM,wBAAwB;AAAA,MAChC,EAAE,KAAK,CAAC,QAAQ,IAAI,yBAAyB,CAAC;AAE9C,UAAI,CAAC,wBAAwB;AAC3B;AAAA,MACF;AAEA,uCAAS;AAAA,QACP,QAAQ,YAAY,YAAY;AAAA,QAChC,MAAM,uBAAuB;AAAA,MAC/B;AAEA,kBAAY;AAAA,IACd;AAEA,QAAI,CAAC,wBAAwB;AAC3B,YAAM,IAAI,MAAM,6CAA6C;AAAA,IAC/D;AAEA,qCAAS;AAAA,MACP,QAAQ;AAAA,MACR,MAAM,uBAAuB;AAAA,IAC/B;AAEA,WAAO,uBAAuB;AAAA,EAChC;AAAA;AAIA,SAAS,wBAAwB,cAA8B;AAC7D,SAAO;AAAA;AAAA;AAAA;AAAA,EAIP;AAAA;AAAA;AAAA;AAAA;AAKF;AAEA,SAAS,kBAAkB,eAAuB,cAA8B;AAC9E,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASF;","names":["_a","_b","action"]}
@@ -1,15 +1,12 @@
1
1
  import {
2
2
  useCopilotChat
3
- } from "./chunk-OAF4ASJH.mjs";
3
+ } from "./chunk-H7LSKIDK.mjs";
4
+ import {
5
+ useCopilotContext
6
+ } from "./chunk-LODRWFMB.mjs";
4
7
  import {
5
8
  useCopilotMessagesContext
6
9
  } from "./chunk-DCTJZ742.mjs";
7
- import {
8
- useAsyncCallback
9
- } from "./chunk-SFPANIOY.mjs";
10
- import {
11
- useCopilotContext
12
- } from "./chunk-STZUYPHJ.mjs";
13
10
  import {
14
11
  __async,
15
12
  __spreadProps,
@@ -29,8 +26,8 @@ function useCoAgent(options) {
29
26
  const generalContext = useCopilotContext();
30
27
  const messagesContext = useCopilotMessagesContext();
31
28
  const context = __spreadValues(__spreadValues({}, generalContext), messagesContext);
32
- const { coagentStates, coagentStatesRef, setCoagentStatesWithRef } = context;
33
- const { appendMessage, runChatCompletion } = useCopilotChat();
29
+ const { coagentStates, setCoagentStates } = context;
30
+ const { appendMessage } = useCopilotChat();
34
31
  const getCoagentState = (coagentStates2, name2) => {
35
32
  if (coagentStates2[name2]) {
36
33
  return coagentStates2[name2];
@@ -47,13 +44,15 @@ function useCoAgent(options) {
47
44
  }
48
45
  };
49
46
  const setState = (newState) => {
50
- let coagentState2 = getCoagentState(coagentStatesRef.current || {}, name);
51
- const updatedState = typeof newState === "function" ? newState(coagentState2.state) : newState;
52
- setCoagentStatesWithRef(__spreadProps(__spreadValues({}, coagentStatesRef.current), {
53
- [name]: __spreadProps(__spreadValues({}, coagentState2), {
54
- state: updatedState
55
- })
56
- }));
47
+ setCoagentStates((prevAgentStates) => {
48
+ let coagentState2 = getCoagentState(prevAgentStates, name);
49
+ const updatedState = typeof newState === "function" ? newState(coagentState2.state) : newState;
50
+ return __spreadProps(__spreadValues({}, prevAgentStates), {
51
+ [name]: __spreadProps(__spreadValues({}, coagentState2), {
52
+ state: updatedState
53
+ })
54
+ });
55
+ });
57
56
  };
58
57
  const coagentState = getCoagentState(coagentStates, name);
59
58
  const state = isExternalStateManagement(options) ? options.state : coagentState.state;
@@ -63,27 +62,22 @@ function useCoAgent(options) {
63
62
  } else if (coagentStates[name] === void 0) {
64
63
  setState(options.initialState === void 0 ? {} : options.initialState);
65
64
  }
66
- }, [
67
- isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0,
68
- // reset initialstate on reset
69
- coagentStates[name] === void 0
70
- ]);
71
- const runAgentCallback = useAsyncCallback(
72
- (hint) => __async(this, null, function* () {
73
- yield runAgent(name, context, appendMessage, runChatCompletion, hint);
74
- }),
75
- [name, context, appendMessage, runChatCompletion]
76
- );
65
+ }, [isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0]);
77
66
  return {
78
67
  name,
79
68
  nodeName: coagentState.nodeName,
80
- threadId: coagentState.threadId,
69
+ state,
70
+ setState,
81
71
  running: coagentState.running,
82
- state: coagentState.state,
83
- setState: isExternalStateManagement(options) ? options.setState : setState,
84
- start: () => startAgent(name, context),
85
- stop: () => stopAgent(name, context),
86
- run: runAgentCallback
72
+ start: () => {
73
+ startAgent(name, context);
74
+ },
75
+ stop: () => {
76
+ stopAgent(name, context);
77
+ },
78
+ run: (hint) => {
79
+ return runAgent(name, context, appendMessage, hint);
80
+ }
87
81
  };
88
82
  }
89
83
  function startAgent(name, context) {
@@ -96,22 +90,11 @@ function stopAgent(name, context) {
96
90
  const { agentSession, setAgentSession } = context;
97
91
  if (agentSession && agentSession.agentName === name) {
98
92
  setAgentSession(null);
99
- context.setCoagentStates((prevAgentStates) => {
100
- return __spreadProps(__spreadValues({}, prevAgentStates), {
101
- [name]: __spreadProps(__spreadValues({}, prevAgentStates[name]), {
102
- running: false,
103
- active: false,
104
- threadId: void 0,
105
- nodeName: void 0,
106
- runId: void 0
107
- })
108
- });
109
- });
110
93
  } else {
111
94
  console.warn(`No agent session found for ${name}`);
112
95
  }
113
96
  }
114
- function runAgent(name, context, appendMessage, runChatCompletion, hint) {
97
+ function runAgent(name, context, appendMessage, hint) {
115
98
  return __async(this, null, function* () {
116
99
  var _a, _b;
117
100
  const { agentSession, setAgentSession } = context;
@@ -127,24 +110,17 @@ function runAgent(name, context, appendMessage, runChatCompletion, hint) {
127
110
  previousState = message.state;
128
111
  }
129
112
  }
130
- let state = ((_b = (_a = context.coagentStatesRef.current) == null ? void 0 : _a[name]) == null ? void 0 : _b.state) || {};
113
+ let state = ((_b = (_a = context.coagentStates) == null ? void 0 : _a[name]) == null ? void 0 : _b.state) || {};
131
114
  if (hint) {
132
115
  const hintMessage = hint({ previousState, currentState: state });
133
116
  if (hintMessage) {
134
117
  yield appendMessage(hintMessage);
135
- } else {
136
- yield runChatCompletion();
137
118
  }
138
- } else {
139
- yield runChatCompletion();
140
119
  }
141
120
  });
142
121
  }
143
122
 
144
123
  export {
145
- useCoAgent,
146
- startAgent,
147
- stopAgent,
148
- runAgent
124
+ useCoAgent
149
125
  };
150
- //# sourceMappingURL=chunk-VQDGBYWQ.mjs.map
126
+ //# sourceMappingURL=chunk-DDVXFNYA.mjs.map
@@ -0,0 +1 @@
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)</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 { useEffect } 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 { AgentStateMessage, Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\n\ninterface WithInternalStateManagementAndInitial<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\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.\n */\nexport function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {\n const isExternalStateManagement = (\n options: UseCoagentOptions<T>,\n ): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n };\n\n const { name } = options;\n\n const isInternalStateManagementWithInitial = (\n options: UseCoagentOptions<T>,\n ): options is WithInternalStateManagementAndInitial<T> => {\n return \"initialState\" in options;\n };\n\n const generalContext = useCopilotContext();\n const messagesContext = useCopilotMessagesContext();\n const context = { ...generalContext, ...messagesContext };\n const { coagentStates, setCoagentStates } = context;\n const { appendMessage } = useCopilotChat();\n\n const getCoagentState = (coagentStates: Record<string, CoagentState>, name: string) => {\n if (coagentStates[name]) {\n return coagentStates[name];\n } else {\n return {\n name,\n state: isInternalStateManagementWithInitial(options) ? options.initialState : {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n }\n };\n\n // if we manage state internally, we need to provide a function to set the state\n const setState = (newState: T | ((prevState: T | undefined) => T)) => {\n setCoagentStates((prevAgentStates) => {\n let coagentState: CoagentState = getCoagentState(prevAgentStates, name);\n\n const updatedState =\n typeof newState === \"function\" ? (newState as Function)(coagentState.state) : newState;\n\n return {\n ...prevAgentStates,\n [name]: {\n ...coagentState,\n state: updatedState,\n },\n };\n });\n };\n\n const coagentState = getCoagentState(coagentStates, name);\n\n const state = isExternalStateManagement(options) ? options.state : coagentState.state;\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 }, [isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined]);\n\n // Return the state and setState function\n return {\n name,\n nodeName: coagentState.nodeName,\n state,\n setState,\n running: coagentState.running,\n start: () => {\n startAgent(name, context);\n },\n stop: () => {\n stopAgent(name, context);\n },\n run: (hint?: HintFunction) => {\n return runAgent(name, context, appendMessage, hint);\n },\n };\n}\n\nfunction startAgent(name: string, context: CopilotContextParams) {\n const { setAgentSession } = context;\n setAgentSession({\n agentName: name,\n });\n}\n\nfunction stopAgent(name: string, context: CopilotContextParams) {\n const { agentSession, setAgentSession } = context;\n if (agentSession && agentSession.agentName === name) {\n setAgentSession(null);\n } else {\n console.warn(`No agent session found for ${name}`);\n }\n}\n\nasync function runAgent(\n name: string,\n context: CopilotContextParams & CopilotMessagesContextParams,\n appendMessage: (message: Message) => Promise<void>,\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.coagentStates?.[name]?.state || {};\n\n if (hint) {\n const hintMessage = hint({ previousState, currentState: state });\n if (hintMessage) {\n await appendMessage(hintMessage);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA0FA,SAAS,iBAAiB;AAgHnB,SAAS,WAAoB,SAAwD;AAC1F,QAAM,4BAA4B,CAChCA,aAC8C;AAC9C,WAAO,WAAWA,YAAW,cAAcA;AAAA,EAC7C;AAEA,QAAM,EAAE,KAAK,IAAI;AAEjB,QAAM,uCAAuC,CAC3CA,aACwD;AACxD,WAAO,kBAAkBA;AAAA,EAC3B;AAEA,QAAM,iBAAiB,kBAAkB;AACzC,QAAM,kBAAkB,0BAA0B;AAClD,QAAM,UAAU,kCAAK,iBAAmB;AACxC,QAAM,EAAE,eAAe,iBAAiB,IAAI;AAC5C,QAAM,EAAE,cAAc,IAAI,eAAe;AAEzC,QAAM,kBAAkB,CAACC,gBAA6CC,UAAiB;AACrF,QAAID,eAAcC,KAAI,GAAG;AACvB,aAAOD,eAAcC,KAAI;AAAA,IAC3B,OAAO;AACL,aAAO;AAAA,QACL,MAAAA;AAAA,QACA,OAAO,qCAAqC,OAAO,IAAI,QAAQ,eAAe,CAAC;AAAA,QAC/E,SAAS;AAAA,QACT,QAAQ;AAAA,QACR,UAAU;AAAA,QACV,UAAU;AAAA,QACV,OAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAGA,QAAM,WAAW,CAAC,aAAoD;AACpE,qBAAiB,CAAC,oBAAoB;AACpC,UAAIC,gBAA6B,gBAAgB,iBAAiB,IAAI;AAEtE,YAAM,eACJ,OAAO,aAAa,aAAc,SAAsBA,cAAa,KAAK,IAAI;AAEhF,aAAO,iCACF,kBADE;AAAA,QAEL,CAAC,IAAI,GAAG,iCACHA,gBADG;AAAA,UAEN,OAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF,CAAC;AAAA,E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AAS,IAAI,QAAQ,SAAS,SAAS,GAAG,KAAK,GAAG,KAAK;AACrD,YAAM,UAAU,QAAQ,SAAS,CAAC;AAClC,UAAI,QAAQ,oBAAoB,KAAK,QAAQ,cAAc,MAAM;AAC/D,wBAAgB,QAAQ;AAAA,MAC1B;AAAA,IACF;AAEA,QAAI,UAAQ,mBAAQ,kBAAR,mBAAwB,UAAxB,mBAA+B,UAAS,CAAC;AAErD,QAAI,MAAM;AACR,YAAM,cAAc,KAAK,EAAE,eAAe,cAAc,MAAM,CAAC;AAC/D,UAAI,aAAa;AACf,cAAM,cAAc,WAAW;AAAA,MACjC;AAAA,IACF;AAAA,EACF;AAAA;","names":["options","coagentStates","name","coagentState"]}
@@ -1,13 +1,8 @@
1
1
  import {
2
2
  defaultCopilotContextCategories
3
- } from "./chunk-YL6V3QTN.mjs";
3
+ } from "./chunk-6OR25P32.mjs";
4
4
  import {
5
- processActionsForRuntimeRequest
6
- } from "./chunk-XERJQUHA.mjs";
7
- import {
8
- __async,
9
- __spreadProps,
10
- __spreadValues
5
+ __async
11
6
  } from "./chunk-SKC7AJIV.mjs";
12
7
 
13
8
  // src/lib/copilot-task.ts
@@ -20,13 +15,13 @@ import {
20
15
  filterAgentStateMessages,
21
16
  CopilotRequestType
22
17
  } from "@copilotkit/runtime-client-gql";
18
+ import { actionParametersToJsonSchema } from "@copilotkit/shared";
23
19
  var CopilotTask = class {
24
20
  constructor(config) {
25
21
  this.instructions = config.instructions;
26
22
  this.actions = config.actions || [];
27
23
  this.includeCopilotReadable = config.includeCopilotReadable !== false;
28
24
  this.includeCopilotActions = config.includeCopilotActions !== false;
29
- this.forwardedParameters = config.forwardedParameters;
30
25
  }
31
26
  /**
32
27
  * Run the task.
@@ -35,7 +30,7 @@ var CopilotTask = class {
35
30
  */
36
31
  run(context, data) {
37
32
  return __async(this, null, function* () {
38
- var _a, _b, _c;
33
+ var _a, _b;
39
34
  const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
40
35
  for (const fn of this.actions) {
41
36
  actions[fn.name] = fn;
@@ -61,22 +56,26 @@ var CopilotTask = class {
61
56
  const response = yield runtimeClient.generateCopilotResponse({
62
57
  data: {
63
58
  frontend: {
64
- actions: processActionsForRuntimeRequest(Object.values(actions)),
59
+ actions: Object.values(actions).map((action) => ({
60
+ name: action.name,
61
+ description: action.description || "",
62
+ jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || []))
63
+ })),
65
64
  url: window.location.href
66
65
  },
67
66
  messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),
68
67
  metadata: {
69
68
  requestType: CopilotRequestType.Task
70
69
  },
71
- forwardedParameters: __spreadProps(__spreadValues({}, (_a = this.forwardedParameters) != null ? _a : {}), {
70
+ forwardedParameters: {
72
71
  toolChoice: "required"
73
- })
72
+ }
74
73
  },
75
74
  properties: context.copilotApiConfig.properties
76
75
  }).toPromise();
77
76
  const functionCallHandler = context.getFunctionCallHandler(actions);
78
77
  const functionCalls = convertGqlOutputToMessages(
79
- ((_c = (_b = response.data) == null ? void 0 : _b.generateCopilotResponse) == null ? void 0 : _c.messages) || []
78
+ ((_b = (_a = response.data) == null ? void 0 : _a.generateCopilotResponse) == null ? void 0 : _b.messages) || []
80
79
  ).filter((m) => m.isActionExecutionMessage());
81
80
  for (const functionCall of functionCalls) {
82
81
  yield functionCallHandler({
@@ -117,4 +116,4 @@ ${instructions}
117
116
  export {
118
117
  CopilotTask
119
118
  };
120
- //# sourceMappingURL=chunk-NYBGR2NK.mjs.map
119
+ //# sourceMappingURL=chunk-FXHKK52V.mjs.map