@copilotkit/react-core 1.3.16-pre.11 → 1.3.16-pre.13

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 (88) hide show
  1. package/CHANGELOG.md +28 -4
  2. package/dist/{chunk-ZM6HV22S.mjs → chunk-A6THC3F6.mjs} +2 -2
  3. package/dist/{chunk-MX2OYLRS.mjs → chunk-DPWPAGS6.mjs} +36 -6
  4. package/dist/chunk-DPWPAGS6.mjs.map +1 -0
  5. package/dist/{chunk-RYDEG77L.mjs → chunk-FXT6XSUB.mjs} +2 -2
  6. package/dist/{chunk-7DFHFZJT.mjs → chunk-I7XLZC4D.mjs} +2 -2
  7. package/dist/{chunk-TRXKPXDE.mjs → chunk-N57PDRVX.mjs} +2 -2
  8. package/dist/{chunk-27IPQFJP.mjs → chunk-PHP2YMMH.mjs} +2 -2
  9. package/dist/{chunk-XACBOJF5.mjs → chunk-Q3IGIEYP.mjs} +23 -5
  10. package/dist/{chunk-XACBOJF5.mjs.map → chunk-Q3IGIEYP.mjs.map} +1 -1
  11. package/dist/{chunk-6YEMNWKE.mjs → chunk-UFSLLJZY.mjs} +12 -3
  12. package/dist/{chunk-6YEMNWKE.mjs.map → chunk-UFSLLJZY.mjs.map} +1 -1
  13. package/dist/{chunk-G2K6T2QU.mjs → chunk-VUXHWQDJ.mjs} +35 -15
  14. package/dist/chunk-VUXHWQDJ.mjs.map +1 -0
  15. package/dist/{chunk-2MPUQRAY.mjs → chunk-WBBL7MG6.mjs} +10 -2
  16. package/dist/{chunk-2MPUQRAY.mjs.map → chunk-WBBL7MG6.mjs.map} +1 -1
  17. package/dist/{chunk-ANOG3W5S.mjs → chunk-ZDYUMEE5.mjs} +2 -2
  18. package/dist/components/copilot-provider/copilotkit.js +19 -2
  19. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  20. package/dist/components/copilot-provider/copilotkit.mjs +2 -2
  21. package/dist/components/copilot-provider/index.js +19 -2
  22. package/dist/components/copilot-provider/index.js.map +1 -1
  23. package/dist/components/copilot-provider/index.mjs +2 -2
  24. package/dist/components/index.js +19 -2
  25. package/dist/components/index.js.map +1 -1
  26. package/dist/components/index.mjs +2 -2
  27. package/dist/context/copilot-context.d.ts +6 -0
  28. package/dist/context/copilot-context.js +9 -1
  29. package/dist/context/copilot-context.js.map +1 -1
  30. package/dist/context/copilot-context.mjs +1 -1
  31. package/dist/context/index.js +9 -1
  32. package/dist/context/index.js.map +1 -1
  33. package/dist/context/index.mjs +1 -1
  34. package/dist/hooks/index.d.ts +2 -1
  35. package/dist/hooks/index.js +97 -18
  36. package/dist/hooks/index.js.map +1 -1
  37. package/dist/hooks/index.mjs +15 -9
  38. package/dist/hooks/use-chat.d.ts +20 -0
  39. package/dist/hooks/use-chat.js +34 -14
  40. package/dist/hooks/use-chat.js.map +1 -1
  41. package/dist/hooks/use-chat.mjs +1 -1
  42. package/dist/hooks/use-coagent-state-render.js +9 -1
  43. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  44. package/dist/hooks/use-coagent-state-render.mjs +2 -2
  45. package/dist/hooks/use-coagent.d.ts +14 -1
  46. package/dist/hooks/use-coagent.js +97 -18
  47. package/dist/hooks/use-coagent.js.map +1 -1
  48. package/dist/hooks/use-coagent.mjs +11 -5
  49. package/dist/hooks/use-copilot-action.js +9 -1
  50. package/dist/hooks/use-copilot-action.js.map +1 -1
  51. package/dist/hooks/use-copilot-action.mjs +2 -2
  52. package/dist/hooks/use-copilot-chat.d.ts +1 -0
  53. package/dist/hooks/use-copilot-chat.js +75 -17
  54. package/dist/hooks/use-copilot-chat.js.map +1 -1
  55. package/dist/hooks/use-copilot-chat.mjs +4 -4
  56. package/dist/hooks/use-copilot-readable.js +9 -1
  57. package/dist/hooks/use-copilot-readable.js.map +1 -1
  58. package/dist/hooks/use-copilot-readable.mjs +2 -2
  59. package/dist/hooks/use-make-copilot-document-readable.js +9 -1
  60. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  61. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  62. package/dist/index.d.ts +1 -1
  63. package/dist/index.js +107 -19
  64. package/dist/index.js.map +1 -1
  65. package/dist/index.mjs +17 -11
  66. package/dist/lib/copilot-task.js.map +1 -1
  67. package/dist/lib/copilot-task.mjs +3 -3
  68. package/dist/lib/index.js.map +1 -1
  69. package/dist/lib/index.mjs +3 -3
  70. package/dist/utils/extract.js.map +1 -1
  71. package/dist/utils/extract.mjs +3 -3
  72. package/dist/utils/index.js.map +1 -1
  73. package/dist/utils/index.mjs +3 -3
  74. package/package.json +5 -5
  75. package/src/components/copilot-provider/copilotkit.tsx +10 -0
  76. package/src/context/copilot-context.tsx +21 -0
  77. package/src/hooks/index.ts +1 -1
  78. package/src/hooks/use-chat.ts +57 -14
  79. package/src/hooks/use-coagent.ts +21 -4
  80. package/src/hooks/use-copilot-chat.ts +35 -4
  81. package/dist/chunk-G2K6T2QU.mjs.map +0 -1
  82. package/dist/chunk-MX2OYLRS.mjs.map +0 -1
  83. /package/dist/{chunk-ZM6HV22S.mjs.map → chunk-A6THC3F6.mjs.map} +0 -0
  84. /package/dist/{chunk-RYDEG77L.mjs.map → chunk-FXT6XSUB.mjs.map} +0 -0
  85. /package/dist/{chunk-7DFHFZJT.mjs.map → chunk-I7XLZC4D.mjs.map} +0 -0
  86. /package/dist/{chunk-TRXKPXDE.mjs.map → chunk-N57PDRVX.mjs.map} +0 -0
  87. /package/dist/{chunk-27IPQFJP.mjs.map → chunk-PHP2YMMH.mjs.map} +0 -0
  88. /package/dist/{chunk-ANOG3W5S.mjs.map → chunk-ZDYUMEE5.mjs.map} +0 -0
@@ -97,6 +97,31 @@ export type UseChatOptions = {
97
97
  * setState-powered method to update the agent session
98
98
  */
99
99
  setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;
100
+
101
+ /**
102
+ * The current thread ID.
103
+ */
104
+ threadId: string | null;
105
+
106
+ /**
107
+ * set the current thread ID
108
+ */
109
+ setThreadId: (threadId: string | null) => void;
110
+
111
+ /**
112
+ * The current run ID.
113
+ */
114
+ runId: string | null;
115
+
116
+ /**
117
+ * set the current run ID
118
+ */
119
+ setRunId: (runId: string | null) => void;
120
+
121
+ /**
122
+ * The global chat abort controller.
123
+ */
124
+ chatAbortControllerRef: React.MutableRefObject<AbortController | null>;
100
125
  };
101
126
 
102
127
  export type UseChatHelpers = {
@@ -134,12 +159,13 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
134
159
  coagentStates,
135
160
  agentSession,
136
161
  setAgentSession,
162
+ threadId,
163
+ setThreadId,
164
+ runId,
165
+ setRunId,
166
+ chatAbortControllerRef,
137
167
  } = options;
138
168
 
139
- const abortControllerRef = useRef<AbortController>();
140
- const threadIdRef = useRef<string | null>(null);
141
- const runIdRef = useRef<string | null>(null);
142
-
143
169
  const runChatCompletionRef = useRef<(previousMessages: Message[]) => Promise<Message[]>>();
144
170
  // We need to keep a ref of coagent states because of renderAndWait - making sure
145
171
  // the latest state is sent to the API
@@ -148,6 +174,10 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
148
174
  coagentStatesRef.current = coagentStates;
149
175
  const agentSessionRef = useRef<AgentSession | null>(agentSession);
150
176
  agentSessionRef.current = agentSession;
177
+ const threadIdRef = useRef<string | null>(threadId);
178
+ threadIdRef.current = threadId;
179
+ const runIdRef = useRef<string | null>(runId);
180
+ runIdRef.current = runId;
151
181
 
152
182
  const publicApiKey = copilotConfig.publicApiKey;
153
183
 
@@ -174,8 +204,8 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
174
204
  role: Role.Assistant,
175
205
  }),
176
206
  ];
177
- const abortController = new AbortController();
178
- abortControllerRef.current = abortController;
207
+
208
+ chatAbortControllerRef.current = new AbortController();
179
209
 
180
210
  setMessages([...previousMessages, ...newMessages]);
181
211
 
@@ -231,7 +261,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
231
261
  })),
232
262
  },
233
263
  properties: copilotConfig.properties,
234
- signal: abortControllerRef.current?.signal,
264
+ signal: chatAbortControllerRef.current?.signal,
235
265
  }),
236
266
  );
237
267
 
@@ -249,6 +279,9 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
249
279
  const { done, value } = await reader.read();
250
280
 
251
281
  if (done) {
282
+ if (chatAbortControllerRef.current.signal.aborted) {
283
+ return newMessages.slice();
284
+ }
252
285
  break;
253
286
  }
254
287
 
@@ -259,6 +292,9 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
259
292
  threadIdRef.current = value.generateCopilotResponse.threadId || null;
260
293
  runIdRef.current = value.generateCopilotResponse.runId || null;
261
294
 
295
+ setThreadId(threadIdRef.current);
296
+ setRunId(runIdRef.current);
297
+
262
298
  const messages = convertGqlOutputToMessages(
263
299
  filterAdjacentAgentStateMessages(value.generateCopilotResponse.messages),
264
300
  );
@@ -310,12 +346,19 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
310
346
  followUp = action.followUp;
311
347
  }
312
348
 
313
- const result = await onFunctionCall({
314
- messages: previousMessages,
315
- name: message.name,
316
- args: message.arguments,
317
- });
318
- actionResults[message.id] = result;
349
+ const result = await Promise.race([
350
+ onFunctionCall({
351
+ messages: previousMessages,
352
+ name: message.name,
353
+ args: message.arguments,
354
+ }),
355
+ new Promise((_, reject) => chatAbortControllerRef.current?.signal.addEventListener('abort', () => reject(new Error('Operation was aborted'))))
356
+ ])
357
+ if (chatAbortControllerRef.current.signal.aborted){
358
+ actionResults[message.id] = "";
359
+ } else {
360
+ actionResults[message.id] = result;
361
+ }
319
362
  } catch (e) {
320
363
  actionResults[message.id] = `Failed to execute action ${message.name}`;
321
364
  console.error(`Failed to execute action ${message.name}: ${e}`);
@@ -442,7 +485,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
442
485
  };
443
486
 
444
487
  const stop = (): void => {
445
- abortControllerRef.current?.abort();
488
+ chatAbortControllerRef.current?.abort("Stop was called");
446
489
  };
447
490
 
448
491
  return {
@@ -266,7 +266,11 @@ export function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentRe
266
266
  } else if (coagentStates[name] === undefined) {
267
267
  setState(options.initialState === undefined ? {} : options.initialState);
268
268
  }
269
- }, [isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined]);
269
+ }, [
270
+ isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined,
271
+ // reset initial state on reset
272
+ coagentStates[name] === undefined,
273
+ ]);
270
274
 
271
275
  // Return the state and setState function
272
276
  return {
@@ -287,23 +291,36 @@ export function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentRe
287
291
  };
288
292
  }
289
293
 
290
- function startAgent(name: string, context: CopilotContextParams) {
294
+ export function startAgent(name: string, context: CopilotContextParams) {
291
295
  const { setAgentSession } = context;
292
296
  setAgentSession({
293
297
  agentName: name,
294
298
  });
295
299
  }
296
300
 
297
- function stopAgent(name: string, context: CopilotContextParams) {
301
+ export function stopAgent(name: string, context: CopilotContextParams) {
298
302
  const { agentSession, setAgentSession } = context;
299
303
  if (agentSession && agentSession.agentName === name) {
300
304
  setAgentSession(null);
305
+ context.setCoagentStates((prevAgentStates) => {
306
+ return {
307
+ ...prevAgentStates,
308
+ [name]: {
309
+ ...prevAgentStates[name],
310
+ running: false,
311
+ active: false,
312
+ threadId: undefined,
313
+ nodeName: undefined,
314
+ runId: undefined,
315
+ },
316
+ };
317
+ });
301
318
  } else {
302
319
  console.warn(`No agent session found for ${name}`);
303
320
  }
304
321
  }
305
322
 
306
- async function runAgent(
323
+ export async function runAgent(
307
324
  name: string,
308
325
  context: CopilotContextParams & CopilotMessagesContextParams,
309
326
  appendMessage: (message: Message) => Promise<void>,
@@ -39,12 +39,11 @@
39
39
  * ```
40
40
  */
41
41
  import { useRef, useEffect, useCallback } from "react";
42
- import { useCopilotContext } from "../context/copilot-context";
42
+ import { AgentSession, useCopilotContext } from "../context/copilot-context";
43
43
  import { Message, Role, TextMessage } from "@copilotkit/runtime-client-gql";
44
44
  import { SystemMessageFunction } from "../types";
45
45
  import { useChat } from "./use-chat";
46
46
  import { defaultCopilotContextCategories } from "../components";
47
- import { MessageStatusCode } from "@copilotkit/runtime-client-gql";
48
47
  import { CoAgentStateRenderHandlerArguments } from "@copilotkit/shared";
49
48
  import { useCopilotMessagesContext } from "../context";
50
49
 
@@ -78,6 +77,7 @@ export interface UseCopilotChatReturn {
78
77
  deleteMessage: (messageId: string) => void;
79
78
  reloadMessages: () => Promise<void>;
80
79
  stopGeneration: () => void;
80
+ reset: () => void;
81
81
  isLoading: boolean;
82
82
  }
83
83
 
@@ -99,6 +99,12 @@ export function useCopilotChat({
99
99
  coAgentStateRenders,
100
100
  agentSession,
101
101
  setAgentSession,
102
+ agentLock,
103
+ threadId,
104
+ setThreadId,
105
+ runId,
106
+ setRunId,
107
+ chatAbortControllerRef,
102
108
  } = useCopilotContext();
103
109
  const { messages, setMessages } = useCopilotMessagesContext();
104
110
 
@@ -157,11 +163,16 @@ export function useCopilotChat({
157
163
  setCoagentStates,
158
164
  agentSession,
159
165
  setAgentSession,
166
+ threadId,
167
+ setThreadId,
168
+ runId,
169
+ setRunId,
170
+ chatAbortControllerRef,
160
171
  });
161
172
 
162
- // this is a workaround born out of a bug that Athena insessently ran into.
173
+ // this is a workaround born out of a bug that Athena incessantly ran into.
163
174
  // We could not find the origin of the bug, however, it was clear that an outdated version of the append function was being used somehow --
164
- // it referecned the old state of the messages array, and not the latest one.
175
+ // it referenced the old state of the messages array, and not the latest one.
165
176
  //
166
177
  // We want to make copilotkit as abuse-proof as possible, so we are adding this workaround to ensure that the latest version of the append function is always used.
167
178
  //
@@ -200,6 +211,25 @@ export function useCopilotChat({
200
211
  },
201
212
  [latestSetMessages],
202
213
  );
214
+ const reset = useCallback(() => {
215
+ latestStopFunc();
216
+ setMessages([]);
217
+ setThreadId(null);
218
+ setRunId(null);
219
+ setCoagentStates({});
220
+ let initialAgentSession: AgentSession | null = null;
221
+ if (agentLock) {
222
+ initialAgentSession = {
223
+ agentName: agentLock,
224
+ };
225
+ }
226
+ setAgentSession(initialAgentSession);
227
+ }, [latestStopFunc, setMessages, setThreadId, setCoagentStates, setAgentSession, agentLock]);
228
+
229
+ const latestReset = useUpdatedRef(reset);
230
+ const latestResetFunc = useCallback(() => {
231
+ return latestReset.current();
232
+ }, [latestReset]);
203
233
 
204
234
  return {
205
235
  visibleMessages: messages,
@@ -208,6 +238,7 @@ export function useCopilotChat({
208
238
  reloadMessages: latestReloadFunc,
209
239
  stopGeneration: latestStopFunc,
210
240
  deleteMessage: latestDeleteFunc,
241
+ reset: latestResetFunc,
211
242
  isLoading,
212
243
  };
213
244
  }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/use-chat.ts"],"sourcesContent":["import { useRef } from \"react\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n actionParametersToJsonSchema,\n CoAgentStateRenderHandler,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ActionExecutionMessage,\n ResultMessage,\n CopilotRuntimeClient,\n convertMessagesToGqlInput,\n filterAdjacentAgentStateMessages,\n filterAgentStateMessages,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n AgentStateMessage,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { AgentSession } from \"../context/copilot-context\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n\n /**\n * Callback function to be called when a coagent action is received.\n */\n onCoAgentStateRender?: CoAgentStateRenderHandler;\n\n /**\n * Function definitions to be sent to the API.\n */\n actions: FrontendAction<any>[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n /**\n * The current list of coagent states.\n */\n coagentStates: Record<string, CoagentState>;\n\n /**\n * setState-powered method to update the agent states\n */\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n\n /**\n * The current agent session.\n */\n agentSession: AgentSession | null;\n\n /**\n * setState-powered method to update the agent session\n */\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoAgentStateRender,\n setCoagentStates,\n coagentStates,\n agentSession,\n setAgentSession,\n } = options;\n\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n\n const runChatCompletionRef = useRef<(previousMessages: Message[]) => Promise<Message[]>>();\n // We need to keep a ref of coagent states because of renderAndWait - making sure\n // the latest state is sent to the API\n // This is a workaround and needs to be addressed in the future\n const coagentStatesRef = useRef<Record<string, CoagentState>>(coagentStates);\n coagentStatesRef.current = coagentStates;\n const agentSessionRef = useRef<AgentSession | null>(agentSession);\n agentSessionRef.current = agentSession;\n\n const publicApiKey = copilotConfig.publicApiKey;\n\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n });\n\n const runChatCompletion = async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n const stream = CopilotRuntimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: actions\n .filter((action) => !action.disabled)\n .map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n url: window.location.href,\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messagesWithContext)),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n ...(copilotConfig.cloud.guardrails?.input?.restrictToTopic?.enabled\n ? {\n guardrails: {\n inputValidationRules: {\n allowList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n }\n : {}),\n },\n }\n : {}),\n metadata: {\n requestType: CopilotRequestType.Chat,\n },\n ...(agentSessionRef.current\n ? {\n agentSession: agentSessionRef.current,\n }\n : {}),\n agentStates: Object.values(coagentStatesRef.current).map((state) => ({\n agentName: state.name,\n state: JSON.stringify(state.state),\n })),\n },\n properties: copilotConfig.properties,\n signal: abortControllerRef.current?.signal,\n }),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let actionResults: { [id: string]: string } = {};\n let executedCoAgentStateRenders: string[] = [];\n let followUp: FrontendAction[\"followUp\"] = undefined;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n threadIdRef.current = value.generateCopilotResponse.threadId || null;\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n const messages = convertGqlOutputToMessages(\n filterAdjacentAgentStateMessages(value.generateCopilotResponse.messages),\n );\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n }\n\n // add messages to the chat\n else {\n for (const message of messages) {\n newMessages.push(message);\n // execute regular action executions\n if (\n message.isActionExecutionMessage() &&\n message.status.code !== MessageStatusCode.Pending &&\n message.scope === \"client\" &&\n onFunctionCall\n ) {\n if (!(message.id in actionResults)) {\n // Do not execute a function call if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute action\n try {\n // We update the message state before calling the handler so that the render\n // function can be called with `executing` state\n setMessages([...previousMessages, ...newMessages]);\n\n const action = actions.find((action) => action.name === message.name);\n\n if (action) {\n followUp = action.followUp;\n }\n\n const result = await onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n });\n actionResults[message.id] = result;\n } catch (e) {\n actionResults[message.id] = `Failed to execute action ${message.name}`;\n console.error(`Failed to execute action ${message.name}: ${e}`);\n }\n }\n // add the result message\n newMessages.push(\n new ResultMessage({\n result: ResultMessage.encodeResult(actionResults[message.id]),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n // execute coagent actions\n if (\n message.isAgentStateMessage() &&\n !message.active &&\n !executedCoAgentStateRenders.includes(message.id) &&\n onCoAgentStateRender\n ) {\n // Do not execute a coagent action if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute coagent action\n await onCoAgentStateRender({\n name: message.agentName,\n nodeName: message.nodeName,\n state: message.state,\n });\n executedCoAgentStateRenders.push(message.id);\n }\n }\n\n const lastAgentStateMessage = [...messages]\n .reverse()\n .find((message) => message.isAgentStateMessage());\n\n if (lastAgentStateMessage) {\n setCoagentStates((prevAgentStates) => ({\n ...prevAgentStates,\n [lastAgentStateMessage.agentName]: {\n name: lastAgentStateMessage.agentName,\n state: lastAgentStateMessage.state,\n running: lastAgentStateMessage.running,\n active: lastAgentStateMessage.active,\n threadId: lastAgentStateMessage.threadId,\n nodeName: lastAgentStateMessage.nodeName,\n runId: lastAgentStateMessage.runId,\n },\n }));\n if (lastAgentStateMessage.running) {\n setAgentSession({\n threadId: lastAgentStateMessage.threadId,\n agentName: lastAgentStateMessage.agentName,\n nodeName: lastAgentStateMessage.nodeName,\n });\n } else {\n setAgentSession(null);\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Update message state\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n\n if (\n // if followUp is not explicitly false\n followUp !== false &&\n // if we have client side results\n (Object.values(actionResults).length ||\n // or the last message we received is a result\n (newMessages.length && newMessages[newMessages.length - 1].isResultMessage()))\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletionRef.current!([...previousMessages, ...newMessages]);\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n runChatCompletionRef.current = runChatCompletion;\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletionRef.current!(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (isLoading) {\n return;\n }\n\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage.isTextMessage() && lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n"],"mappings":";;;;;;;AAAA,SAAS,cAAc;AACvB;AAAA,EAEE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EAEE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAkGA,SAAS,QAAQ,SAAyC;AAC/D,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,QAAM,qBAAqB,OAAwB;AACnD,QAAM,cAAc,OAAsB,IAAI;AAC9C,QAAM,WAAW,OAAsB,IAAI;AAE3C,QAAM,uBAAuB,OAA4D;AAIzF,QAAM,mBAAmB,OAAqC,aAAa;AAC3E,mBAAiB,UAAU;AAC3B,QAAM,kBAAkB,OAA4B,YAAY;AAChE,kBAAgB,UAAU;AAE1B,QAAM,eAAe,cAAc;AAEnC,QAAM,UAAU,kCAC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F,OAAO;AACL,eAAO,YAAY,MAAM;AAAA,MAC3B;AAAA,IACF,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF;AAEA,uBAAqB,UAAU;AAE/B,QAAM,yCAAyC,CAAOA,cAAuC;AAC3F,UAAM,qBAAqB,QAASA,SAAQ;AAAA,EAC9C;AAEA,QAAM,SAAS,CAAO,YAAoC;AACxD,QAAI,WAAW;AACb;AAAA,IACF;AAEA,UAAM,cAAc,CAAC,GAAG,UAAU,OAAO;AACzC,gBAAY,WAAW;AACvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,SAAS,MAA2B;AACxC,QAAI,aAAa,SAAS,WAAW,GAAG;AACtC;AAAA,IACF;AACA,QAAI,cAAc,CAAC,GAAG,QAAQ;AAC9B,UAAM,cAAc,SAAS,SAAS,SAAS,CAAC;AAEhD,QAAI,YAAY,cAAc,KAAK,YAAY,SAAS,aAAa;AACnE,oBAAc,YAAY,MAAM,GAAG,EAAE;AAAA,IACvC;AAEA,gBAAY,WAAW;AAEvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,OAAO,MAAY;AA3b3B;AA4bI,6BAAmB,YAAnB,mBAA4B;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["messages","action"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/use-copilot-chat.ts"],"sourcesContent":["/**\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChat } from \"@copilotkit/react-core\";\n * import { Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\n *\n * export function YourComponent() {\n * const { appendMessage } = useCopilotChat();\n *\n * appendMessage(\n * new TextMessage({\n * content: \"Hello World\",\n * role: Role.User,\n * }),\n * );\n * }\n * ```\n *\n * `useCopilotChat` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * visibleMessages, // An array of messages that are currently visible in the chat.\n * appendMessage, // A function to append a message to the chat.\n * setMessages, // A function to set the messages in the chat.\n * deleteMessage, // A function to delete a message from the chat.\n * reloadMessages, // A function to reload the messages from the API.\n * stopGeneration, // A function to stop the generation of the next message.\n * isLoading, // A boolean indicating if the chat is loading.\n * } = useCopilotChat();\n * ```\n */\nimport { useRef, useEffect, useCallback } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { MessageStatusCode } from \"@copilotkit/runtime-client-gql\";\nimport { CoAgentStateRenderHandlerArguments } from \"@copilotkit/shared\";\nimport { useCopilotMessagesContext } from \"../context\";\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n appendMessage: (message: Message) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: () => Promise<void>;\n stopGeneration: () => void;\n isLoading: boolean;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getFunctionCallHandler,\n copilotApiConfig,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n\n coagentStates,\n setCoagentStates,\n coAgentStateRenders,\n agentSession,\n setAgentSession,\n } = useCopilotContext();\n const { messages, setMessages } = useCopilotMessagesContext();\n\n // We need to ensure that makeSystemMessageCallback always uses the latest\n // useCopilotReadable data.\n const latestGetContextString = useUpdatedRef(getContextString);\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = latestGetContextString.current([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return new TextMessage({\n content: systemMessageMaker(contextString, chatInstructions),\n role: Role.System,\n });\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const onCoAgentStateRender = useCallback(\n async (args: CoAgentStateRenderHandlerArguments) => {\n const { name, nodeName, state } = args;\n let action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && action.nodeName === nodeName,\n );\n if (!action) {\n action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && !action.nodeName,\n );\n }\n if (action) {\n await action.handler?.({ state, nodeName });\n }\n },\n [coAgentStateRenders],\n );\n\n const { append, reload, stop } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: options.initialMessages || [],\n onFunctionCall: getFunctionCallHandler(),\n onCoAgentStateRender,\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n coagentStates,\n setCoagentStates,\n agentSession,\n setAgentSession,\n });\n\n // this is a workaround born out of a bug that Athena insessently ran into.\n // We could not find the origin of the bug, however, it was clear that an outdated version of the append function was being used somehow --\n // it referecned the old state of the messages array, and not the latest one.\n //\n // We want to make copilotkit as abuse-proof as possible, so we are adding this workaround to ensure that the latest version of the append function is always used.\n //\n // How does this work?\n // we store the relevant function in a ref that is always up-to-date, and then we use that ref in the callback.\n const latestAppend = useUpdatedRef(append);\n const latestAppendFunc = useCallback(\n (message: Message) => {\n return latestAppend.current(message);\n },\n [latestAppend],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useCallback(() => {\n return latestReload.current();\n }, [latestReload]);\n\n const latestStop = useUpdatedRef(stop);\n const latestStopFunc = useCallback(() => {\n return latestStop.current();\n }, [latestStop]);\n\n const latestDelete = useUpdatedRef(deleteMessage);\n const latestDeleteFunc = useCallback(\n (messageId: string) => {\n return latestDelete.current(messageId);\n },\n [latestDelete],\n );\n\n const latestSetMessages = useUpdatedRef(setMessages);\n const latestSetMessagesFunc = useCallback(\n (messages: Message[]) => {\n return latestSetMessages.current(messages);\n },\n [latestSetMessages],\n );\n\n return {\n visibleMessages: messages,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n deleteMessage: latestDeleteFunc,\n isLoading,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,QAAQ,WAAW,mBAAmB;AAE/C,SAAkB,MAAM,mBAAmB;AAyCpC,SAAS,eA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