@copilotkit/react-core 1.9.1-next.0 → 1.9.2-next.0

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 (180) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/{chunk-B5UA5G3E.mjs → chunk-2FW7HH6W.mjs} +12 -8
  3. package/dist/chunk-2FW7HH6W.mjs.map +1 -0
  4. package/dist/{chunk-ERFA53MG.mjs → chunk-6KGEF242.mjs} +2 -2
  5. package/dist/chunk-6KGEF242.mjs.map +1 -0
  6. package/dist/{chunk-2J3SMMGW.mjs → chunk-C6F6EQNA.mjs} +2 -2
  7. package/dist/chunk-CCESTGAM.mjs +102 -0
  8. package/dist/chunk-CCESTGAM.mjs.map +1 -0
  9. package/dist/chunk-GFJW4RIM.mjs +9 -0
  10. package/dist/chunk-GFJW4RIM.mjs.map +1 -0
  11. package/dist/chunk-HD2GE3DK.mjs +359 -0
  12. package/dist/chunk-HD2GE3DK.mjs.map +1 -0
  13. package/dist/{chunk-74AJEJTV.mjs → chunk-HJP2RX5R.mjs} +11 -6
  14. package/dist/chunk-HJP2RX5R.mjs.map +1 -0
  15. package/dist/{chunk-EQ4XLLT4.mjs → chunk-LDACFA2B.mjs} +3 -3
  16. package/dist/{chunk-FGBRHBRR.mjs → chunk-LZDDYZEY.mjs} +2 -2
  17. package/dist/chunk-NNSXCFQO.mjs +154 -0
  18. package/dist/chunk-NNSXCFQO.mjs.map +1 -0
  19. package/dist/{chunk-WZAEVHLK.mjs → chunk-Q5D5XQFA.mjs} +2 -2
  20. package/dist/{chunk-534J55RX.mjs → chunk-QQZLIEXK.mjs} +9 -7
  21. package/dist/chunk-QQZLIEXK.mjs.map +1 -0
  22. package/dist/chunk-RUY6MLHA.mjs +119 -0
  23. package/dist/chunk-RUY6MLHA.mjs.map +1 -0
  24. package/dist/{chunk-MDIIRGJD.mjs → chunk-SGLWMQ2J.mjs} +25 -17
  25. package/dist/chunk-SGLWMQ2J.mjs.map +1 -0
  26. package/dist/{chunk-G27C5EFO.mjs → chunk-T42PN5VN.mjs} +7 -5
  27. package/dist/{chunk-G27C5EFO.mjs.map → chunk-T42PN5VN.mjs.map} +1 -1
  28. package/dist/{chunk-VQ3VTO26.mjs → chunk-UHQMV2CE.mjs} +2 -2
  29. package/dist/{chunk-4DVPRMVH.mjs → chunk-UIT6QMUJ.mjs} +7 -7
  30. package/dist/chunk-VRXANACV.mjs +277 -0
  31. package/dist/chunk-VRXANACV.mjs.map +1 -0
  32. package/dist/{chunk-2FLZLANO.mjs → chunk-XY5BN4HZ.mjs} +19 -12
  33. package/dist/chunk-XY5BN4HZ.mjs.map +1 -0
  34. package/dist/{chunk-7HDYPEWS.mjs → chunk-YDENFEKA.mjs} +2 -2
  35. package/dist/{chunk-4VWM6JNK.mjs → chunk-YZDRMIOM.mjs} +6 -6
  36. package/dist/components/copilot-provider/copilot-messages.js +105 -11
  37. package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
  38. package/dist/components/copilot-provider/copilot-messages.mjs +4 -2
  39. package/dist/components/copilot-provider/copilotkit-props.d.ts +4 -3
  40. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  41. package/dist/components/copilot-provider/copilotkit.d.ts +1 -1
  42. package/dist/components/copilot-provider/copilotkit.js +863 -441
  43. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  44. package/dist/components/copilot-provider/copilotkit.mjs +10 -9
  45. package/dist/components/copilot-provider/index.d.ts +1 -1
  46. package/dist/components/copilot-provider/index.js +863 -441
  47. package/dist/components/copilot-provider/index.js.map +1 -1
  48. package/dist/components/copilot-provider/index.mjs +10 -9
  49. package/dist/components/error-boundary/error-boundary.js +320 -159
  50. package/dist/components/error-boundary/error-boundary.js.map +1 -1
  51. package/dist/components/error-boundary/error-boundary.mjs +4 -3
  52. package/dist/components/error-boundary/error-utils.js +2 -1
  53. package/dist/components/error-boundary/error-utils.js.map +1 -1
  54. package/dist/components/error-boundary/error-utils.mjs +2 -1
  55. package/dist/components/index.d.ts +1 -1
  56. package/dist/components/index.js +863 -441
  57. package/dist/components/index.js.map +1 -1
  58. package/dist/components/index.mjs +10 -9
  59. package/dist/components/toast/toast-provider.d.ts +9 -12
  60. package/dist/components/toast/toast-provider.js +218 -191
  61. package/dist/components/toast/toast-provider.js.map +1 -1
  62. package/dist/components/toast/toast-provider.mjs +1 -2
  63. package/dist/components/usage-banner.d.ts +3 -2
  64. package/dist/components/usage-banner.js +311 -153
  65. package/dist/components/usage-banner.js.map +1 -1
  66. package/dist/components/usage-banner.mjs +1 -1
  67. package/dist/context/copilot-context.d.ts +1 -1
  68. package/dist/context/copilot-context.js +1 -1
  69. package/dist/context/copilot-context.js.map +1 -1
  70. package/dist/context/copilot-context.mjs +1 -1
  71. package/dist/context/index.d.ts +1 -1
  72. package/dist/context/index.js +1 -1
  73. package/dist/context/index.js.map +1 -1
  74. package/dist/context/index.mjs +1 -1
  75. package/dist/{copilot-context-309906bb.d.ts → copilot-context-f9b2b4c3.d.ts} +1 -1
  76. package/dist/hooks/index.d.ts +1 -1
  77. package/dist/hooks/index.js +160 -75
  78. package/dist/hooks/index.js.map +1 -1
  79. package/dist/hooks/index.mjs +33 -32
  80. package/dist/hooks/use-chat.d.ts +1 -1
  81. package/dist/hooks/use-chat.js +243 -68
  82. package/dist/hooks/use-chat.js.map +1 -1
  83. package/dist/hooks/use-chat.mjs +6 -3
  84. package/dist/hooks/use-coagent-state-render.js +10 -5
  85. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  86. package/dist/hooks/use-coagent-state-render.mjs +3 -4
  87. package/dist/hooks/use-coagent.d.ts +1 -1
  88. package/dist/hooks/use-coagent.js +148 -67
  89. package/dist/hooks/use-coagent.js.map +1 -1
  90. package/dist/hooks/use-coagent.mjs +14 -13
  91. package/dist/hooks/use-copilot-action.js +5 -4
  92. package/dist/hooks/use-copilot-action.js.map +1 -1
  93. package/dist/hooks/use-copilot-action.mjs +4 -3
  94. package/dist/hooks/use-copilot-additional-instructions.js +1 -1
  95. package/dist/hooks/use-copilot-additional-instructions.js.map +1 -1
  96. package/dist/hooks/use-copilot-additional-instructions.mjs +2 -2
  97. package/dist/hooks/use-copilot-authenticated-action.js +5 -4
  98. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  99. package/dist/hooks/use-copilot-authenticated-action.mjs +5 -4
  100. package/dist/hooks/use-copilot-chat.d.ts +1 -1
  101. package/dist/hooks/use-copilot-chat.js +138 -62
  102. package/dist/hooks/use-copilot-chat.js.map +1 -1
  103. package/dist/hooks/use-copilot-chat.mjs +13 -12
  104. package/dist/hooks/use-copilot-readable.js +1 -1
  105. package/dist/hooks/use-copilot-readable.js.map +1 -1
  106. package/dist/hooks/use-copilot-readable.mjs +2 -2
  107. package/dist/hooks/use-copilot-runtime-client.d.ts +5 -2
  108. package/dist/hooks/use-copilot-runtime-client.js +101 -128
  109. package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
  110. package/dist/hooks/use-copilot-runtime-client.mjs +3 -3
  111. package/dist/hooks/use-langgraph-interrupt-render.js +1 -1
  112. package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -1
  113. package/dist/hooks/use-langgraph-interrupt-render.mjs +2 -2
  114. package/dist/hooks/use-langgraph-interrupt.d.ts +1 -1
  115. package/dist/hooks/use-langgraph-interrupt.js +140 -64
  116. package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
  117. package/dist/hooks/use-langgraph-interrupt.mjs +14 -13
  118. package/dist/hooks/use-make-copilot-document-readable.js +1 -1
  119. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  120. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  121. package/dist/index.d.ts +1 -1
  122. package/dist/index.js +913 -480
  123. package/dist/index.js.map +1 -1
  124. package/dist/index.mjs +35 -34
  125. package/dist/lib/copilot-task.d.ts +1 -1
  126. package/dist/lib/copilot-task.js.map +1 -1
  127. package/dist/lib/copilot-task.mjs +11 -10
  128. package/dist/lib/index.d.ts +1 -1
  129. package/dist/lib/index.js.map +1 -1
  130. package/dist/lib/index.mjs +11 -10
  131. package/dist/types/interrupt-action.d.ts +1 -1
  132. package/dist/utils/dev-console.d.ts +1 -1
  133. package/dist/utils/dev-console.js +1 -10
  134. package/dist/utils/dev-console.js.map +1 -1
  135. package/dist/utils/dev-console.mjs +1 -1
  136. package/dist/utils/extract.d.ts +1 -1
  137. package/dist/utils/extract.js.map +1 -1
  138. package/dist/utils/extract.mjs +10 -9
  139. package/dist/utils/index.d.ts +1 -1
  140. package/dist/utils/index.js +7 -14
  141. package/dist/utils/index.js.map +1 -1
  142. package/dist/utils/index.mjs +12 -11
  143. package/package.json +3 -3
  144. package/src/components/copilot-provider/copilot-messages.tsx +163 -4
  145. package/src/components/copilot-provider/copilotkit-props.tsx +3 -2
  146. package/src/components/copilot-provider/copilotkit.tsx +8 -2
  147. package/src/components/error-boundary/error-boundary.tsx +6 -5
  148. package/src/components/error-boundary/error-utils.tsx +1 -1
  149. package/src/components/toast/toast-provider.tsx +260 -93
  150. package/src/components/usage-banner.tsx +311 -131
  151. package/src/context/copilot-context.tsx +2 -2
  152. package/src/hooks/use-chat.ts +4 -0
  153. package/src/hooks/use-coagent-state-render.ts +9 -3
  154. package/src/hooks/use-coagent.ts +10 -3
  155. package/src/hooks/use-copilot-runtime-client.ts +153 -12
  156. package/src/utils/dev-console.ts +2 -17
  157. package/dist/chunk-22ENANUU.mjs +0 -250
  158. package/dist/chunk-22ENANUU.mjs.map +0 -1
  159. package/dist/chunk-2FLZLANO.mjs.map +0 -1
  160. package/dist/chunk-534J55RX.mjs.map +0 -1
  161. package/dist/chunk-6PK72HMH.mjs +0 -63
  162. package/dist/chunk-6PK72HMH.mjs.map +0 -1
  163. package/dist/chunk-74AJEJTV.mjs.map +0 -1
  164. package/dist/chunk-B5UA5G3E.mjs.map +0 -1
  165. package/dist/chunk-BKTARDXX.mjs +0 -40
  166. package/dist/chunk-BKTARDXX.mjs.map +0 -1
  167. package/dist/chunk-D34OH4VN.mjs +0 -201
  168. package/dist/chunk-D34OH4VN.mjs.map +0 -1
  169. package/dist/chunk-ERFA53MG.mjs.map +0 -1
  170. package/dist/chunk-MDIIRGJD.mjs.map +0 -1
  171. package/dist/chunk-MLAS4QUR.mjs +0 -18
  172. package/dist/chunk-MLAS4QUR.mjs.map +0 -1
  173. /package/dist/{chunk-2J3SMMGW.mjs.map → chunk-C6F6EQNA.mjs.map} +0 -0
  174. /package/dist/{chunk-EQ4XLLT4.mjs.map → chunk-LDACFA2B.mjs.map} +0 -0
  175. /package/dist/{chunk-FGBRHBRR.mjs.map → chunk-LZDDYZEY.mjs.map} +0 -0
  176. /package/dist/{chunk-WZAEVHLK.mjs.map → chunk-Q5D5XQFA.mjs.map} +0 -0
  177. /package/dist/{chunk-VQ3VTO26.mjs.map → chunk-UHQMV2CE.mjs.map} +0 -0
  178. /package/dist/{chunk-4DVPRMVH.mjs.map → chunk-UIT6QMUJ.mjs.map} +0 -0
  179. /package/dist/{chunk-7HDYPEWS.mjs.map → chunk-YDENFEKA.mjs.map} +0 -0
  180. /package/dist/{chunk-4VWM6JNK.mjs.map → chunk-YZDRMIOM.mjs.map} +0 -0
@@ -4,30 +4,171 @@ import {
4
4
  GraphQLError,
5
5
  } from "@copilotkit/runtime-client-gql";
6
6
  import { useToast } from "../components/toast/toast-provider";
7
- import { useMemo } from "react";
8
- import { useErrorToast } from "../components/error-boundary/error-utils";
7
+ import { useMemo, useRef } from "react";
8
+ import {
9
+ ErrorVisibility,
10
+ CopilotKitApiDiscoveryError,
11
+ CopilotKitRemoteEndpointDiscoveryError,
12
+ CopilotKitAgentDiscoveryError,
13
+ CopilotKitError,
14
+ CopilotKitErrorCode,
15
+ ERROR_CONFIG,
16
+ } from "@copilotkit/shared";
17
+ import { shouldShowDevConsole } from "../utils/dev-console";
18
+
19
+ export interface CopilotRuntimeClientHookOptions extends CopilotRuntimeClientOptions {
20
+ showDevConsole?: boolean;
21
+ }
22
+
23
+ export const useCopilotRuntimeClient = (options: CopilotRuntimeClientHookOptions) => {
24
+ const { setBannerError } = useToast();
25
+ const { showDevConsole, ...runtimeOptions } = options;
9
26
 
10
- export const useCopilotRuntimeClient = (options: CopilotRuntimeClientOptions) => {
11
- const { addGraphQLErrorsToast } = useToast();
12
- const addErrorToast = useErrorToast();
13
- const { addToast } = useToast();
27
+ // Deduplication state for structured errors
28
+ const lastStructuredErrorRef = useRef<{ message: string; timestamp: number } | null>(null);
14
29
 
15
30
  const runtimeClient = useMemo(() => {
16
31
  return new CopilotRuntimeClient({
17
- ...options,
32
+ ...runtimeOptions,
18
33
  handleGQLErrors: (error) => {
19
- if ((error as any).graphQLErrors.length) {
20
- addGraphQLErrorsToast((error as any).graphQLErrors as GraphQLError[]);
34
+ if ((error as any).graphQLErrors?.length) {
35
+ const graphQLErrors = (error as any).graphQLErrors as GraphQLError[];
36
+
37
+ // Route all errors to banners for consistent UI
38
+ const routeError = (gqlError: GraphQLError) => {
39
+ const extensions = gqlError.extensions;
40
+ const visibility = extensions?.visibility as ErrorVisibility;
41
+ const isDev = shouldShowDevConsole(showDevConsole ?? false);
42
+
43
+ // Silent errors - just log
44
+ if (visibility === ErrorVisibility.SILENT) {
45
+ console.error("CopilotKit Silent Error:", gqlError.message);
46
+ return;
47
+ }
48
+
49
+ // Respect showDevConsole setting for ALL errors
50
+ if (!isDev) {
51
+ console.error("CopilotKit Error (hidden in production):", gqlError.message);
52
+ return;
53
+ }
54
+
55
+ // All errors (including DEV_ONLY) show as banners for consistency
56
+ // Deduplicate to prevent spam
57
+ const now = Date.now();
58
+ const errorMessage = gqlError.message;
59
+ if (
60
+ lastStructuredErrorRef.current &&
61
+ lastStructuredErrorRef.current.message === errorMessage &&
62
+ now - lastStructuredErrorRef.current.timestamp < 150
63
+ ) {
64
+ return; // Skip duplicate
65
+ }
66
+ lastStructuredErrorRef.current = { message: errorMessage, timestamp: now };
67
+
68
+ const ckError = createStructuredError(gqlError);
69
+ if (ckError) {
70
+ setBannerError(ckError);
71
+ } else {
72
+ // Fallback for unstructured errors
73
+ const fallbackError = new CopilotKitError({
74
+ message: gqlError.message,
75
+ code: CopilotKitErrorCode.UNKNOWN,
76
+ });
77
+ setBannerError(fallbackError);
78
+ }
79
+ };
80
+
81
+ // Process all errors as banners
82
+ graphQLErrors.forEach(routeError);
21
83
  } else {
22
- addErrorToast([error]);
84
+ const isDev = shouldShowDevConsole(showDevConsole ?? false);
85
+ if (!isDev) {
86
+ console.error("CopilotKit Error (hidden in production):", error);
87
+ } else {
88
+ // Route non-GraphQL errors to banner as well
89
+ const fallbackError = new CopilotKitError({
90
+ message: error?.message || String(error),
91
+ code: CopilotKitErrorCode.UNKNOWN,
92
+ });
93
+ setBannerError(fallbackError);
94
+ }
23
95
  }
24
96
  },
25
97
  handleGQLWarning: (message: string) => {
26
98
  console.warn(message);
27
- addToast({ type: "warning", message });
99
+ // Show warnings as banners too for consistency
100
+ const warningError = new CopilotKitError({
101
+ message,
102
+ code: CopilotKitErrorCode.UNKNOWN,
103
+ });
104
+ setBannerError(warningError);
28
105
  },
29
106
  });
30
- }, [options, addGraphQLErrorsToast, addToast]);
107
+ }, [runtimeOptions, setBannerError, showDevConsole]);
31
108
 
32
109
  return runtimeClient;
33
110
  };
111
+
112
+ // Helper to determine if error should show as banner based on structured error system
113
+ function shouldShowAsBanner(gqlError: GraphQLError): boolean {
114
+ const extensions = gqlError.extensions;
115
+ if (!extensions) return false;
116
+
117
+ // Primary: Check error code and use structured config
118
+ const code = extensions.code as CopilotKitErrorCode;
119
+ if (code && ERROR_CONFIG[code]?.visibility === ErrorVisibility.BANNER) {
120
+ return true;
121
+ }
122
+
123
+ // Fallback: Check for API key errors which should always be banners
124
+ const errorMessage = gqlError.message.toLowerCase();
125
+ if (
126
+ errorMessage.includes("api key") ||
127
+ errorMessage.includes("401") ||
128
+ errorMessage.includes("unauthorized") ||
129
+ errorMessage.includes("authentication") ||
130
+ errorMessage.includes("incorrect api key")
131
+ ) {
132
+ return true;
133
+ }
134
+
135
+ // Legacy: Check by stack trace for discovery errors (for backward compatibility)
136
+ const originalError = extensions.originalError as any;
137
+ if (originalError?.stack) {
138
+ return (
139
+ originalError.stack.includes("CopilotApiDiscoveryError") ||
140
+ originalError.stack.includes("CopilotKitRemoteEndpointDiscoveryError") ||
141
+ originalError.stack.includes("CopilotKitAgentDiscoveryError")
142
+ );
143
+ }
144
+
145
+ return false;
146
+ }
147
+
148
+ // Create appropriate structured error from GraphQL error
149
+ function createStructuredError(gqlError: GraphQLError): CopilotKitError | null {
150
+ const extensions = gqlError.extensions;
151
+ const originalError = extensions?.originalError as any;
152
+ const message = originalError?.message || gqlError.message;
153
+ const code = extensions?.code as CopilotKitErrorCode;
154
+
155
+ if (code) {
156
+ return new CopilotKitError({ message, code });
157
+ }
158
+
159
+ // Legacy error detection by stack trace
160
+ if (originalError?.stack?.includes("CopilotApiDiscoveryError")) {
161
+ return new CopilotKitApiDiscoveryError({ message });
162
+ }
163
+ if (originalError?.stack?.includes("CopilotKitRemoteEndpointDiscoveryError")) {
164
+ return new CopilotKitRemoteEndpointDiscoveryError({ message });
165
+ }
166
+ if (originalError?.stack?.includes("CopilotKitAgentDiscoveryError")) {
167
+ return new CopilotKitAgentDiscoveryError({
168
+ agentName: "",
169
+ availableAgents: [],
170
+ });
171
+ }
172
+
173
+ return null;
174
+ }
@@ -1,18 +1,3 @@
1
- export function shouldShowDevConsole(showDevConsole: boolean | "auto"): boolean {
2
- if (typeof showDevConsole === "boolean") {
3
- return showDevConsole;
4
- }
5
- return (
6
- getHostname() === "localhost" ||
7
- getHostname() === "127.0.0.1" ||
8
- getHostname() === "0.0.0.0" ||
9
- getHostname() === "::1"
10
- );
11
- }
12
-
13
- function getHostname(): string {
14
- if (typeof window !== "undefined" && window.location) {
15
- return window.location.hostname;
16
- }
17
- return "";
1
+ export function shouldShowDevConsole(showDevConsole: boolean): boolean {
2
+ return showDevConsole;
18
3
  }
@@ -1,250 +0,0 @@
1
- import {
2
- ExclamationMarkIcon
3
- } from "./chunk-O7ARI5CV.mjs";
4
- import {
5
- __async,
6
- __spreadProps,
7
- __spreadValues
8
- } from "./chunk-SKC7AJIV.mjs";
9
-
10
- // src/components/error-boundary/error-utils.tsx
11
- import { useCallback as useCallback2 } from "react";
12
-
13
- // src/components/toast/toast-provider.tsx
14
- import { createContext, useContext, useState, useCallback } from "react";
15
- import { jsx, jsxs } from "react/jsx-runtime";
16
- var ToastContext = createContext(void 0);
17
- function useToast() {
18
- const context = useContext(ToastContext);
19
- if (!context) {
20
- throw new Error("useToast must be used within a ToastProvider");
21
- }
22
- return context;
23
- }
24
- function ToastProvider({
25
- enabled,
26
- children
27
- }) {
28
- const [toasts, setToasts] = useState([]);
29
- const addToast = useCallback(
30
- (toast) => {
31
- var _a;
32
- if (!enabled) {
33
- return;
34
- }
35
- const id = (_a = toast.id) != null ? _a : Math.random().toString(36).substring(2, 9);
36
- setToasts((currentToasts) => {
37
- if (currentToasts.find((toast2) => toast2.id === id))
38
- return currentToasts;
39
- return [...currentToasts, __spreadProps(__spreadValues({}, toast), { id })];
40
- });
41
- if (toast.duration) {
42
- setTimeout(() => {
43
- removeToast(id);
44
- }, toast.duration);
45
- }
46
- },
47
- [enabled]
48
- );
49
- const addGraphQLErrorsToast = useCallback((errors) => {
50
- addToast({
51
- type: "error",
52
- message: /* @__PURE__ */ jsx(ErrorToast, { errors })
53
- });
54
- }, []);
55
- const removeToast = useCallback((id) => {
56
- setToasts((currentToasts) => currentToasts.filter((toast) => toast.id !== id));
57
- }, []);
58
- const value = {
59
- toasts,
60
- addToast,
61
- addGraphQLErrorsToast,
62
- removeToast,
63
- enabled
64
- };
65
- return /* @__PURE__ */ jsxs(ToastContext.Provider, { value, children: [
66
- /* @__PURE__ */ jsxs(
67
- "div",
68
- {
69
- style: {
70
- position: "fixed",
71
- bottom: "1rem",
72
- left: "50%",
73
- transform: "translateX(-50%)",
74
- zIndex: 50,
75
- display: "flex",
76
- flexDirection: "column",
77
- gap: "0.5rem"
78
- },
79
- children: [
80
- toasts.length > 1 && /* @__PURE__ */ jsx("div", { style: { textAlign: "right" }, children: /* @__PURE__ */ jsx(
81
- "button",
82
- {
83
- onClick: () => setToasts([]),
84
- style: {
85
- padding: "4px 8px",
86
- fontSize: "12px",
87
- cursor: "pointer",
88
- background: "white",
89
- border: "1px solid rgba(0,0,0,0.2)",
90
- borderRadius: "4px"
91
- },
92
- children: "Close All"
93
- }
94
- ) }),
95
- toasts.map((toast) => /* @__PURE__ */ jsx(
96
- Toast,
97
- {
98
- message: toast.message,
99
- type: toast.type,
100
- onClose: () => removeToast(toast.id)
101
- },
102
- toast.id
103
- ))
104
- ]
105
- }
106
- ),
107
- children
108
- ] });
109
- }
110
- function Toast({
111
- message,
112
- type = "info",
113
- onClose
114
- }) {
115
- const bgColors = {
116
- info: "#3b82f6",
117
- success: "#22c55e",
118
- warning: "#eab308",
119
- error: "#ef4444"
120
- };
121
- return /* @__PURE__ */ jsxs(
122
- "div",
123
- {
124
- style: {
125
- backgroundColor: bgColors[type],
126
- color: "white",
127
- padding: "0.5rem 1.5rem",
128
- borderRadius: "0.25rem",
129
- boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
130
- position: "relative",
131
- minWidth: "200px"
132
- },
133
- children: [
134
- /* @__PURE__ */ jsx("div", { children: message }),
135
- /* @__PURE__ */ jsx(
136
- "button",
137
- {
138
- onClick: onClose,
139
- style: {
140
- position: "absolute",
141
- top: "0",
142
- right: "0",
143
- background: "none",
144
- border: "none",
145
- color: "white",
146
- cursor: "pointer",
147
- padding: "0.5rem",
148
- fontSize: "1rem"
149
- },
150
- children: "\u2715"
151
- }
152
- )
153
- ]
154
- }
155
- );
156
- }
157
-
158
- // src/components/error-boundary/error-utils.tsx
159
- import ReactMarkdown from "react-markdown";
160
- import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
161
- function ErrorToast({ errors }) {
162
- const errorsToRender = errors.map((error, idx) => {
163
- var _a, _b, _c;
164
- const originalError = "extensions" in error ? (_a = error.extensions) == null ? void 0 : _a.originalError : {};
165
- const message = (_b = originalError == null ? void 0 : originalError.message) != null ? _b : error.message;
166
- const code = "extensions" in error ? (_c = error.extensions) == null ? void 0 : _c.code : null;
167
- return /* @__PURE__ */ jsxs2(
168
- "div",
169
- {
170
- style: {
171
- marginTop: idx === 0 ? 0 : 10,
172
- marginBottom: 14
173
- },
174
- children: [
175
- /* @__PURE__ */ jsx2(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
176
- code && /* @__PURE__ */ jsxs2(
177
- "div",
178
- {
179
- style: {
180
- fontWeight: "600",
181
- marginBottom: 4
182
- },
183
- children: [
184
- "Copilot Cloud Error:",
185
- " ",
186
- /* @__PURE__ */ jsx2("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
187
- ]
188
- }
189
- ),
190
- /* @__PURE__ */ jsx2(ReactMarkdown, { children: message })
191
- ]
192
- },
193
- idx
194
- );
195
- });
196
- return /* @__PURE__ */ jsxs2(
197
- "div",
198
- {
199
- style: {
200
- fontSize: "13px",
201
- maxWidth: "600px"
202
- },
203
- children: [
204
- errorsToRender,
205
- /* @__PURE__ */ jsx2("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This error only displays during local development." })
206
- ]
207
- }
208
- );
209
- }
210
- function useErrorToast() {
211
- const { addToast } = useToast();
212
- return useCallback2(
213
- (error) => {
214
- const errorId = error.map((err) => {
215
- var _a, _b;
216
- const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
217
- const stack = err.stack || "";
218
- return btoa(message + stack).slice(0, 32);
219
- }).join("|");
220
- addToast({
221
- type: "error",
222
- id: errorId,
223
- // Toast libraries typically dedupe by id
224
- message: /* @__PURE__ */ jsx2(ErrorToast, { errors: error })
225
- });
226
- },
227
- [addToast]
228
- );
229
- }
230
- function useAsyncCallback(callback, deps) {
231
- const addErrorToast = useErrorToast();
232
- return useCallback2((...args) => __async(this, null, function* () {
233
- try {
234
- return yield callback(...args);
235
- } catch (error) {
236
- console.error("Error in async callback:", error);
237
- addErrorToast([error]);
238
- throw error;
239
- }
240
- }), deps);
241
- }
242
-
243
- export {
244
- ErrorToast,
245
- useErrorToast,
246
- useAsyncCallback,
247
- useToast,
248
- ToastProvider
249
- };
250
- //# sourceMappingURL=chunk-22ENANUU.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/error-boundary/error-utils.tsx","../src/components/toast/toast-provider.tsx"],"sourcesContent":["import React, { useCallback } from \"react\";\nimport { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { ExclamationMarkIcon } from \"../toast/exclamation-mark-icon\";\nimport ReactMarkdown from \"react-markdown\";\n\ninterface OriginalError {\n message?: string;\n stack?: string;\n}\n\nexport function ErrorToast({ errors }: { errors: (Error | GraphQLError)[] }) {\n const errorsToRender = errors.map((error, idx) => {\n const originalError =\n \"extensions\" in error ? (error.extensions?.originalError as undefined | OriginalError) : {};\n const message = originalError?.message ?? error.message;\n const code = \"extensions\" in error ? (error.extensions?.code as string) : null;\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 <ReactMarkdown>{message}</ReactMarkdown>\n </div>\n );\n });\n return (\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 error only displays during local development.\n </div>\n </div>\n );\n}\n\nexport function useErrorToast() {\n const { addToast } = useToast();\n\n return useCallback(\n (error: (Error | GraphQLError)[]) => {\n const errorId = error\n .map((err) => {\n const message =\n \"extensions\" in err\n ? (err.extensions?.originalError as any)?.message || err.message\n : err.message;\n const stack = err.stack || \"\";\n return btoa(message + stack).slice(0, 32); // Create hash from message + stack\n })\n .join(\"|\");\n\n addToast({\n type: \"error\",\n id: errorId, // Toast libraries typically dedupe by id\n message: <ErrorToast errors={error} />,\n });\n },\n [addToast],\n );\n}\n\nexport function useAsyncCallback<T extends (...args: any[]) => Promise<any>>(\n callback: T,\n deps: Parameters<typeof useCallback>[1],\n) {\n const addErrorToast = useErrorToast();\n return useCallback(async (...args: Parameters<T>) => {\n try {\n return await callback(...args);\n } catch (error) {\n console.error(\"Error in async callback:\", error);\n // @ts-ignore\n addErrorToast([error]);\n throw error;\n }\n }, deps);\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { ErrorToast } from \"../error-boundary/error-utils\";\nimport { PartialBy } from \"@copilotkit/shared\";\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: PartialBy<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(\n (toast: PartialBy<Toast, \"id\">) => {\n // We do not display these errors unless we are in dev mode.\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n addToast({\n type: \"error\",\n message: <ErrorToast errors={errors} />,\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 1.5rem\",\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":";;;;;;;;;;AAAA,SAAgB,eAAAA,oBAAmB;;;ACCnC,SAAgB,eAAe,YAAY,UAAU,mBAAmB;AA+DzD,cAkBT,YAlBS;AA5Cf,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;AAAA,IACf,CAAC,UAAkC;AAvCvC;AAyCM,UAAI,CAAC,SAAS;AACZ;AAAA,MACF;AAEA,YAAM,MAAK,WAAM,OAAN,YAAY,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,UAAU,GAAG,CAAC;AAEhE,gBAAU,CAAC,kBAAkB;AAC3B,YAAI,cAAc,KAAK,CAACC,WAAUA,OAAM,OAAO,EAAE;AAAG,iBAAO;AAC3D,eAAO,CAAC,GAAG,eAAe,iCAAK,QAAL,EAAY,GAAG,EAAC;AAAA,MAC5C,CAAC;AAED,UAAI,MAAM,UAAU;AAClB,mBAAW,MAAM;AACf,sBAAY,EAAE;AAAA,QAChB,GAAG,MAAM,QAAQ;AAAA,MACnB;AAAA,IACF;AAAA,IACA,CAAC,OAAO;AAAA,EACV;AAEA,QAAM,wBAAwB,YAAY,CAAC,WAA2B;AACpE,aAAS;AAAA,MACP,MAAM;AAAA,MACN,SAAS,oBAAC,cAAW,QAAgB;AAAA,IACvC,CAAC;AAAA,EACH,GAAG,CAAC,CAAC;AAEL,QAAM,cAAc,YAAY,CAAC,OAAe;AAC9C,cAAU,CAAC,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AA;AAAA,MAnBnB;AAAA,IAoBP;AAAA,EAEJ,CAAC;AACD,SACE,gBAAAC;AAAA,IAAC;AAAA;AAAA,MACC,OAAO;AAAA,QACL,UAAU;AAAA,QACV,UAAU;AAAA,MACZ;AAAA,MAEC;AAAA;AAAA,QACD,gBAAAD,KAAC,SAAI,OAAO,EAAE,UAAU,QAAQ,SAAS,KAAK,GAAG,sEAEjD;AAAA;AAAA;AAAA,EACF;AAEJ;AAEO,SAAS,gBAAgB;AAC9B,QAAM,EAAE,SAAS,IAAI,SAAS;AAE9B,SAAOE;AAAA,IACL,CAAC,UAAoC;AACnC,YAAM,UAAU,MACb,IAAI,CAAC,QAAQ;AAhEtB;AAiEU,cAAM,UACJ,gBAAgB,QACX,eAAI,eAAJ,mBAAgB,kBAAhB,mBAAuC,YAAW,IAAI,UACvD,IAAI;AACV,cAAM,QAAQ,IAAI,SAAS;AAC3B,eAAO,KAAK,UAAU,KAAK,EAAE,MAAM,GAAG,EAAE;AAAA,MAC1C,CAAC,EACA,KAAK,GAAG;AAEX,eAAS;AAAA,QACP,MAAM;AAAA,QACN,IAAI;AAAA;AAAA,QACJ,SAAS,gBAAAF,KAAC,cAAW,QAAQ,OAAO;AAAA,MACtC,CAAC;AAAA,IACH;AAAA,IACA,CAAC,QAAQ;AAAA,EACX;AACF;AAEO,SAAS,iBACd,UACA,MACA;AACA,QAAM,gBAAgB,cAAc;AACpC,SAAOE,aAAY,IAAU,SAAwB;AACnD,QAAI;AACF,aAAO,MAAM,SAAS,GAAG,IAAI;AAAA,IAC/B,SAAS,OAAP;AACA,cAAQ,MAAM,4BAA4B,KAAK;AAE/C,oBAAc,CAAC,KAAK,CAAC;AACrB,YAAM;AAAA,IACR;AAAA,EACF,IAAG,IAAI;AACT;","names":["useCallback","toast","jsx","jsxs","useCallback"]}
@@ -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/runtime-client-gql\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nimport { parseJson } 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 { addToast } = 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 addToast({ type: \"warning\", message });\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 });\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 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 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,\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AQ,oBAAoB,KAAK,QAAQ,cAAc,MAAM;AAC/D,wBAAgB,QAAQ;AAAA,MAC1B;AAAA,IACF;AAEA,QAAI,UAAQ,mBAAQ,iBAAiB,YAAzB,mBAAmC,UAAnC,mBAA0C,UAAS,CAAC;AAEhE,QAAI,MAAM;AACR,YAAM,cAAc,KAAK,EAAE,eAAe,cAAc,MAAM,CAAC;AAC/D,UAAI,aAAa;AACf,cAAM,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":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/error-boundary/error-boundary.tsx"],"sourcesContent":["import React, { useEffect } from \"react\";\nimport { Severity, CopilotKitError } from \"@copilotkit/shared\";\nimport { StatusChecker } from \"../../lib/status-checker\";\nimport { renderCopilotKitUsage, UsageBanner } from \"../usage-banner\";\nimport { useErrorToast } from \"./error-utils\";\nimport { COPILOT_CLOUD_ERROR_NAMES } from \"@copilotkit/shared\";\n\nconst statusChecker = new StatusChecker();\n\ninterface Props {\n children: React.ReactNode;\n publicApiKey?: string;\n showUsageBanner?: boolean;\n}\n\ninterface State {\n hasError: boolean;\n error?: CopilotKitError;\n status?: {\n severity: Severity;\n message: string;\n };\n}\n\nexport class CopilotErrorBoundary extends React.Component<Props, State> {\n constructor(props: Props) {\n super(props);\n this.state = {\n hasError: false,\n };\n }\n\n static getDerivedStateFromError(error: CopilotKitError): State {\n return { hasError: true, error };\n }\n\n componentDidMount() {\n if (this.props.publicApiKey) {\n statusChecker.start(this.props.publicApiKey, (newStatus) => {\n this.setState((prevState) => {\n if (newStatus?.severity !== prevState.status?.severity) {\n return { status: newStatus ?? undefined };\n }\n return null;\n });\n });\n }\n }\n\n componentWillUnmount() {\n statusChecker.stop();\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error(\"CopilotKit Error:\", error, errorInfo);\n }\n\n render() {\n if (this.state.hasError) {\n if (this.state.error instanceof CopilotKitError) {\n // @ts-expect-error -- It's a copilotkit error at this state. Name is valid\n if (COPILOT_CLOUD_ERROR_NAMES.includes(this.state.error.name)) {\n return (\n <ErrorToast error={this.state.error}>\n {renderCopilotKitUsage(this.state.error)}\n </ErrorToast>\n );\n }\n\n return (\n <>\n {this.props.children}\n {this.props.showUsageBanner && (\n <UsageBanner\n severity={this.state.status?.severity}\n message={this.state.status?.message}\n />\n )}\n </>\n );\n }\n throw this.state.error;\n }\n\n return this.props.children;\n }\n}\n\nexport function ErrorToast({ error, children }: { error?: Error; children: React.ReactNode }) {\n const addErrorToast = useErrorToast();\n\n useEffect(() => {\n if (error) {\n addErrorToast([error]);\n }\n }, [error, addErrorToast]);\n\n if (!error) throw error;\n return children;\n}\n"],"mappings":";;;;;;;;;;;;AAAA,OAAO,SAAS,iBAAiB;AACjC,SAAmB,uBAAuB;AAI1C,SAAS,iCAAiC;AA0D9B,SAOF,UAPE,KAOF,YAPE;AAxDZ,IAAM,gBAAgB,IAAI,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EO,SAAS,WAAW,EAAE,OAAO,SAAS,GAAiD;AAC5F,QAAM,gBAAgB,cAAc;AAEpC,YAAU,MAAM;AACd,QAAI,OAAO;AACT,oBAAc,CAAC,KAAK,CAAC;AAAA,IACvB;AAAA,EACF,GAAG,CAAC,OAAO,aAAa,CAAC;AAEzB,MAAI,CAAC;AAAO,UAAM;AAClB,SAAO;AACT;","names":[]}
@@ -1,63 +0,0 @@
1
- import {
2
- CopilotMessagesContext
3
- } from "./chunk-DCTJZ742.mjs";
4
- import {
5
- useCopilotContext
6
- } from "./chunk-ERFA53MG.mjs";
7
- import {
8
- __async
9
- } from "./chunk-SKC7AJIV.mjs";
10
-
11
- // src/components/copilot-provider/copilot-messages.tsx
12
- import { useEffect, useState, useRef } from "react";
13
- import { loadMessagesFromJsonRepresentation } from "@copilotkit/runtime-client-gql";
14
- import { jsx } from "react/jsx-runtime";
15
- function CopilotMessages({ children }) {
16
- const [messages, setMessages] = useState([]);
17
- const lastLoadedThreadId = useRef();
18
- const lastLoadedAgentName = useRef();
19
- const lastLoadedMessages = useRef();
20
- const { threadId, agentSession, runtimeClient } = useCopilotContext();
21
- useEffect(() => {
22
- if (!threadId || threadId === lastLoadedThreadId.current)
23
- return;
24
- if (threadId === lastLoadedThreadId.current && (agentSession == null ? void 0 : agentSession.agentName) === lastLoadedAgentName.current) {
25
- return;
26
- }
27
- const fetchMessages = () => __async(this, null, function* () {
28
- var _a, _b, _c, _d;
29
- if (!(agentSession == null ? void 0 : agentSession.agentName))
30
- return;
31
- const result = yield runtimeClient.loadAgentState({
32
- threadId,
33
- agentName: agentSession == null ? void 0 : agentSession.agentName
34
- });
35
- const newMessages = (_b = (_a = result.data) == null ? void 0 : _a.loadAgentState) == null ? void 0 : _b.messages;
36
- if (newMessages === lastLoadedMessages.current)
37
- return;
38
- if ((_d = (_c = result.data) == null ? void 0 : _c.loadAgentState) == null ? void 0 : _d.threadExists) {
39
- lastLoadedMessages.current = newMessages;
40
- lastLoadedThreadId.current = threadId;
41
- lastLoadedAgentName.current = agentSession == null ? void 0 : agentSession.agentName;
42
- const messages2 = loadMessagesFromJsonRepresentation(JSON.parse(newMessages || "[]"));
43
- setMessages(messages2);
44
- }
45
- });
46
- void fetchMessages();
47
- }, [threadId, agentSession == null ? void 0 : agentSession.agentName]);
48
- return /* @__PURE__ */ jsx(
49
- CopilotMessagesContext.Provider,
50
- {
51
- value: {
52
- messages,
53
- setMessages
54
- },
55
- children
56
- }
57
- );
58
- }
59
-
60
- export {
61
- CopilotMessages
62
- };
63
- //# sourceMappingURL=chunk-6PK72HMH.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/copilot-provider/copilot-messages.tsx"],"sourcesContent":["/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport { ReactNode, useEffect, useState, useRef } from \"react\";\nimport { CopilotMessagesContext } from \"../../context/copilot-messages-context\";\nimport { loadMessagesFromJsonRepresentation, Message } from \"@copilotkit/runtime-client-gql\";\nimport { useCopilotContext } from \"../../context/copilot-context\";\n\nexport function CopilotMessages({ children }: { children: ReactNode }) {\n const [messages, setMessages] = useState<Message[]>([]);\n const lastLoadedThreadId = useRef<string>();\n const lastLoadedAgentName = useRef<string>();\n const lastLoadedMessages = useRef<string>();\n\n const { threadId, agentSession, runtimeClient } = useCopilotContext();\n\n useEffect(() => {\n if (!threadId || threadId === lastLoadedThreadId.current) return;\n if (\n threadId === lastLoadedThreadId.current &&\n agentSession?.agentName === lastLoadedAgentName.current\n ) {\n return;\n }\n\n const fetchMessages = async () => {\n if (!agentSession?.agentName) return;\n\n const result = await runtimeClient.loadAgentState({\n threadId,\n agentName: agentSession?.agentName,\n });\n\n const newMessages = result.data?.loadAgentState?.messages;\n if (newMessages === lastLoadedMessages.current) return;\n\n if (result.data?.loadAgentState?.threadExists) {\n lastLoadedMessages.current = newMessages;\n lastLoadedThreadId.current = threadId;\n lastLoadedAgentName.current = agentSession?.agentName;\n\n const messages = loadMessagesFromJsonRepresentation(JSON.parse(newMessages || \"[]\"));\n setMessages(messages);\n }\n };\n void fetchMessages();\n }, [threadId, agentSession?.agentName]);\n\n return (\n <CopilotMessagesContext.Provider\n value={{\n messages,\n setMessages,\n }}\n >\n {children}\n </CopilotMessagesContext.Provider>\n );\n}\n"],"mappings":";;;;;;;;;;;AAIA,SAAoB,WAAW,UAAU,cAAc;AAEvD,SAAS,0CAAmD;AA4CxD;AAzCG,SAAS,gBAAgB,EAAE,SAAS,GAA4B;AACrE,QAAM,CAAC,UAAU,WAAW,IAAI,SAAoB,CAAC,CAAC;AACtD,QAAM,qBAAqB,OAAe;AAC1C,QAAM,sBAAsB,OAAe;AAC3C,QAAM,qBAAqB,OAAe;AAE1C,QAAM,EAAE,UAAU,cAAc,cAAc,IAAI,kBAAkB;AAEpE,YAAU,MAAM;AACd,QAAI,CAAC,YAAY,aAAa,mBAAmB;AAAS;AAC1D,QACE,aAAa,mBAAmB,YAChC,6CAAc,eAAc,oBAAoB,SAChD;AACA;AAAA,IACF;AAEA,UAAM,gBAAgB,MAAY;AA1BtC;AA2BM,UAAI,EAAC,6CAAc;AAAW;AAE9B,YAAM,SAAS,MAAM,cAAc,eAAe;AAAA,QAChD;AAAA,QACA,WAAW,6CAAc;AAAA,MAC3B,CAAC;AAED,YAAM,eAAc,kBAAO,SAAP,mBAAa,mBAAb,mBAA6B;AACjD,UAAI,gBAAgB,mBAAmB;AAAS;AAEhD,WAAI,kBAAO,SAAP,mBAAa,mBAAb,mBAA6B,cAAc;AAC7C,2BAAmB,UAAU;AAC7B,2BAAmB,UAAU;AAC7B,4BAAoB,UAAU,6CAAc;AAE5C,cAAMA,YAAW,mCAAmC,KAAK,MAAM,eAAe,IAAI,CAAC;AACnF,oBAAYA,SAAQ;AAAA,MACtB;AAAA,IACF;AACA,SAAK,cAAc;AAAA,EACrB,GAAG,CAAC,UAAU,6CAAc,SAAS,CAAC;AAEtC,SACE;AAAA,IAAC,uBAAuB;AAAA,IAAvB;AAAA,MACC,OAAO;AAAA,QACL;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;","names":["messages"]}