@copilotkit/react-core 1.1.3-feat-runtime-remote-actions.1 → 1.2.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 (126) hide show
  1. package/CHANGELOG.md +6 -12
  2. package/dist/chunk-5JB4B2SV.mjs +1 -0
  3. package/dist/{chunk-HABY7NLH.mjs → chunk-AIW2RAN2.mjs} +6 -35
  4. package/dist/chunk-AIW2RAN2.mjs.map +1 -0
  5. package/dist/{chunk-RBNULK3U.mjs → chunk-CFCRJA63.mjs} +5 -39
  6. package/dist/chunk-CFCRJA63.mjs.map +1 -0
  7. package/dist/{chunk-3U22BXKC.mjs → chunk-EVK5346D.mjs} +3 -4
  8. package/dist/chunk-EVK5346D.mjs.map +1 -0
  9. package/dist/{chunk-A37GANOW.mjs → chunk-GSL4ZHUB.mjs} +4 -4
  10. package/dist/chunk-GSL4ZHUB.mjs.map +1 -0
  11. package/dist/{chunk-TCZBK3HZ.mjs → chunk-HUC6EZVP.mjs} +4 -7
  12. package/dist/chunk-HUC6EZVP.mjs.map +1 -0
  13. package/dist/{chunk-CODXG6KU.mjs → chunk-LB53QWLY.mjs} +2 -2
  14. package/dist/{chunk-J2YXDQHR.mjs → chunk-LB7ULLSU.mjs} +3 -14
  15. package/dist/chunk-LB7ULLSU.mjs.map +1 -0
  16. package/dist/{chunk-XSZDVRPW.mjs → chunk-PZOEBYWP.mjs} +11 -62
  17. package/dist/chunk-PZOEBYWP.mjs.map +1 -0
  18. package/dist/{chunk-326LK7LX.mjs → chunk-QR4XKQOA.mjs} +2 -2
  19. package/dist/components/copilot-provider/copilotkit-props.d.ts +0 -4
  20. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  21. package/dist/components/copilot-provider/copilotkit.js +5 -50
  22. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  23. package/dist/components/copilot-provider/copilotkit.mjs +2 -2
  24. package/dist/components/copilot-provider/index.js +5 -50
  25. package/dist/components/copilot-provider/index.js.map +1 -1
  26. package/dist/components/copilot-provider/index.mjs +2 -2
  27. package/dist/components/index.js +5 -50
  28. package/dist/components/index.js.map +1 -1
  29. package/dist/components/index.mjs +2 -2
  30. package/dist/context/copilot-context.d.ts +2 -21
  31. package/dist/context/copilot-context.js +2 -13
  32. package/dist/context/copilot-context.js.map +1 -1
  33. package/dist/context/copilot-context.mjs +1 -1
  34. package/dist/context/index.d.ts +0 -2
  35. package/dist/context/index.js +2 -13
  36. package/dist/context/index.js.map +1 -1
  37. package/dist/context/index.mjs +1 -1
  38. package/dist/hooks/index.d.ts +0 -4
  39. package/dist/hooks/index.js +21 -223
  40. package/dist/hooks/index.js.map +1 -1
  41. package/dist/hooks/index.mjs +12 -21
  42. package/dist/hooks/use-chat.d.ts +4 -26
  43. package/dist/hooks/use-chat.js +9 -57
  44. package/dist/hooks/use-chat.js.map +1 -1
  45. package/dist/hooks/use-chat.mjs +1 -1
  46. package/dist/hooks/use-copilot-action.js +4 -15
  47. package/dist/hooks/use-copilot-action.js.map +1 -1
  48. package/dist/hooks/use-copilot-action.mjs +2 -2
  49. package/dist/hooks/use-copilot-chat.js +13 -100
  50. package/dist/hooks/use-copilot-chat.js.map +1 -1
  51. package/dist/hooks/use-copilot-chat.mjs +4 -4
  52. package/dist/hooks/use-copilot-readable.js +2 -13
  53. package/dist/hooks/use-copilot-readable.js.map +1 -1
  54. package/dist/hooks/use-copilot-readable.mjs +2 -2
  55. package/dist/hooks/use-make-copilot-document-readable.js +2 -13
  56. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  57. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  58. package/dist/index.d.ts +0 -4
  59. package/dist/index.js +31 -267
  60. package/dist/index.js.map +1 -1
  61. package/dist/index.mjs +16 -24
  62. package/dist/lib/copilot-task.d.ts +0 -2
  63. package/dist/lib/copilot-task.js +1 -1
  64. package/dist/lib/copilot-task.js.map +1 -1
  65. package/dist/lib/copilot-task.mjs +3 -3
  66. package/dist/lib/index.d.ts +0 -2
  67. package/dist/lib/index.js +1 -1
  68. package/dist/lib/index.js.map +1 -1
  69. package/dist/lib/index.mjs +3 -3
  70. package/dist/utils/extract.d.ts +0 -2
  71. package/dist/utils/extract.js +1 -1
  72. package/dist/utils/extract.js.map +1 -1
  73. package/dist/utils/extract.mjs +3 -3
  74. package/dist/utils/index.d.ts +0 -2
  75. package/dist/utils/index.js +1 -1
  76. package/dist/utils/index.js.map +1 -1
  77. package/dist/utils/index.mjs +3 -3
  78. package/package.json +5 -5
  79. package/src/components/copilot-provider/copilotkit-props.tsx +0 -5
  80. package/src/components/copilot-provider/copilotkit.tsx +3 -45
  81. package/src/context/copilot-context.tsx +2 -39
  82. package/src/hooks/index.ts +0 -2
  83. package/src/hooks/use-chat.ts +11 -106
  84. package/src/hooks/use-copilot-action.ts +2 -2
  85. package/src/hooks/use-copilot-chat.ts +0 -31
  86. package/src/lib/copilot-task.ts +1 -2
  87. package/src/utils/extract.ts +2 -7
  88. package/dist/chunk-3U22BXKC.mjs.map +0 -1
  89. package/dist/chunk-A37GANOW.mjs.map +0 -1
  90. package/dist/chunk-BWYAGPEF.mjs +0 -1
  91. package/dist/chunk-HABY7NLH.mjs.map +0 -1
  92. package/dist/chunk-J2YXDQHR.mjs.map +0 -1
  93. package/dist/chunk-Q4TTTAXQ.mjs +0 -87
  94. package/dist/chunk-Q4TTTAXQ.mjs.map +0 -1
  95. package/dist/chunk-RBNULK3U.mjs.map +0 -1
  96. package/dist/chunk-STUXJ3BN.mjs +0 -44
  97. package/dist/chunk-STUXJ3BN.mjs.map +0 -1
  98. package/dist/chunk-TCZBK3HZ.mjs.map +0 -1
  99. package/dist/chunk-XSZDVRPW.mjs.map +0 -1
  100. package/dist/hooks/use-coagent-action.d.ts +0 -5
  101. package/dist/hooks/use-coagent-action.js +0 -156
  102. package/dist/hooks/use-coagent-action.js.map +0 -1
  103. package/dist/hooks/use-coagent-action.mjs +0 -9
  104. package/dist/hooks/use-coagent-action.mjs.map +0 -1
  105. package/dist/hooks/use-coagent.d.ts +0 -27
  106. package/dist/hooks/use-coagent.js +0 -219
  107. package/dist/hooks/use-coagent.js.map +0 -1
  108. package/dist/hooks/use-coagent.mjs +0 -10
  109. package/dist/hooks/use-coagent.mjs.map +0 -1
  110. package/dist/types/coagent-action.d.ts +0 -17
  111. package/dist/types/coagent-action.js +0 -19
  112. package/dist/types/coagent-action.js.map +0 -1
  113. package/dist/types/coagent-action.mjs +0 -1
  114. package/dist/types/coagent-action.mjs.map +0 -1
  115. package/dist/types/coagent-state.d.ts +0 -11
  116. package/dist/types/coagent-state.js +0 -19
  117. package/dist/types/coagent-state.js.map +0 -1
  118. package/dist/types/coagent-state.mjs +0 -1
  119. package/dist/types/coagent-state.mjs.map +0 -1
  120. package/src/hooks/use-coagent-action.ts +0 -44
  121. package/src/hooks/use-coagent.ts +0 -133
  122. package/src/types/coagent-action.ts +0 -17
  123. package/src/types/coagent-state.ts +0 -9
  124. /package/dist/{chunk-BWYAGPEF.mjs.map → chunk-5JB4B2SV.mjs.map} +0 -0
  125. /package/dist/{chunk-CODXG6KU.mjs.map → chunk-LB53QWLY.mjs.map} +0 -0
  126. /package/dist/{chunk-326LK7LX.mjs.map → chunk-QR4XKQOA.mjs.map} +0 -0
@@ -35,8 +35,6 @@ import {
35
35
  CopilotContext,
36
36
  CopilotApiConfig,
37
37
  InChatRenderFunction,
38
- ChatComponentsCache,
39
- AgentSession,
40
38
  } from "../../context/copilot-context";
41
39
  import useTree from "../../hooks/use-tree";
42
40
  import { CopilotChatSuggestionConfiguration, DocumentPointer } from "../../types";
@@ -46,13 +44,11 @@ import {
46
44
  CopilotCloudConfig,
47
45
  FunctionCallHandler,
48
46
  } from "@copilotkit/shared";
49
- import { AgentStateMessage, Message } from "@copilotkit/runtime-client-gql";
47
+ import { Message } from "@copilotkit/runtime-client-gql";
50
48
 
51
49
  import { FrontendAction } from "../../types/frontend-action";
52
50
  import useFlatCategoryStore from "../../hooks/use-flat-category-store";
53
51
  import { CopilotKitProps } from "./copilotkit-props";
54
- import { CoagentAction } from "../../types/coagent-action";
55
- import { CoagentState } from "../../types/coagent-state";
56
52
 
57
53
  export function CopilotKit({ children, ...props }: CopilotKitProps) {
58
54
  // Compute all the functions and properties that we need to pass
@@ -67,11 +63,7 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
67
63
  const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;
68
64
 
69
65
  const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});
70
- const [coagentActions, setCoagentActions] = useState<Record<string, CoagentAction<any>>>({});
71
- const chatComponentsCache = useRef<ChatComponentsCache>({
72
- actions: {},
73
- coagentActions: {},
74
- });
66
+ const chatComponentsCache = useRef<Record<string, InChatRenderFunction | string>>({});
75
67
  const { addElement, removeElement, printTree } = useTree();
76
68
  const [messages, setMessages] = useState<Message[]>([]);
77
69
  const [isLoading, setIsLoading] = useState(false);
@@ -100,23 +92,6 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
100
92
  });
101
93
  }, []);
102
94
 
103
- const setCoagentAction = useCallback((id: string, action: CoagentAction<any>) => {
104
- setCoagentActions((prevPoints) => {
105
- return {
106
- ...prevPoints,
107
- [id]: action,
108
- };
109
- });
110
- }, []);
111
-
112
- const removeCoagentAction = useCallback((id: string) => {
113
- setCoagentActions((prevPoints) => {
114
- const newPoints = { ...prevPoints };
115
- delete newPoints[id];
116
- return newPoints;
117
- });
118
- }, []);
119
-
120
95
  const getContextString = useCallback(
121
96
  (documents: DocumentPointer[], categories: string[]) => {
122
97
  const documentsString = documents
@@ -231,16 +206,6 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
231
206
  });
232
207
  };
233
208
 
234
- const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});
235
- let initialAgentSession: AgentSession | null = null;
236
- if (props.agent) {
237
- initialAgentSession = {
238
- agentName: props.agent,
239
- };
240
- }
241
-
242
- const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);
243
-
244
209
  return (
245
210
  <CopilotContext.Provider
246
211
  value={{
@@ -249,9 +214,6 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
249
214
  getFunctionCallHandler,
250
215
  setAction,
251
216
  removeAction,
252
- coagentActions,
253
- setCoagentAction,
254
- removeCoagentAction,
255
217
  getContextString,
256
218
  addContext,
257
219
  removeContext,
@@ -269,10 +231,6 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
269
231
  chatInstructions,
270
232
  setChatInstructions,
271
233
  showDevConsole: props.showDevConsole === undefined ? "auto" : props.showDevConsole,
272
- coagentStates,
273
- setCoagentStates,
274
- agentSession,
275
- setAgentSession,
276
234
  }}
277
235
  >
278
236
  {children}
@@ -295,7 +253,7 @@ function entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): Funct
295
253
  await new Promise<void>((resolve, reject) => {
296
254
  flushSync(async () => {
297
255
  try {
298
- result = await action.handler?.(args);
256
+ result = await action.handler(args);
299
257
  resolve();
300
258
  } catch (error) {
301
259
  reject(error);
@@ -5,8 +5,6 @@ import React from "react";
5
5
  import { TreeNodeId } from "../hooks/use-tree";
6
6
  import { DocumentPointer } from "../types";
7
7
  import { CopilotChatSuggestionConfiguration } from "../types/chat-suggestion-configuration";
8
- import { CoagentAction, CoagentActionRenderProps } from "../types/coagent-action";
9
- import { CoagentState } from "../types/coagent-state";
10
8
 
11
9
  /**
12
10
  * Interface for the configuration of the Copilot API.
@@ -69,33 +67,13 @@ export interface CopilotApiConfig {
69
67
  }
70
68
 
71
69
  export type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;
72
- export type CoagentInChatRenderFunction = (
73
- props: CoagentActionRenderProps<any>,
74
- ) => string | JSX.Element;
75
-
76
- export interface ChatComponentsCache {
77
- actions: Record<string, InChatRenderFunction | string>;
78
- coagentActions: Record<string, CoagentInChatRenderFunction | string>;
79
- }
80
-
81
- export interface AgentSession {
82
- agentName: string;
83
- threadId?: string;
84
- nodeName?: string;
85
- }
86
70
 
87
71
  export interface CopilotContextParams {
88
72
  // function-calling
89
73
  actions: Record<string, FrontendAction<any>>;
90
74
  setAction: (id: string, action: FrontendAction<any>) => void;
91
75
  removeAction: (id: string) => void;
92
-
93
- // coagent actions
94
- coagentActions: Record<string, CoagentAction<any>>;
95
- setCoagentAction: (id: string, action: CoagentAction<any>) => void;
96
- removeCoagentAction: (id: string) => void;
97
-
98
- chatComponentsCache: React.RefObject<ChatComponentsCache>;
76
+ chatComponentsCache: React.RefObject<Record<string, InChatRenderFunction | string>>;
99
77
 
100
78
  getFunctionCallHandler: (
101
79
  customEntryPoints?: Record<string, FrontendAction<any>>,
@@ -132,12 +110,6 @@ export interface CopilotContextParams {
132
110
  copilotApiConfig: CopilotApiConfig;
133
111
 
134
112
  showDevConsole: boolean | "auto";
135
-
136
- // agents
137
- coagentStates: Record<string, CoagentState>;
138
- setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;
139
- agentSession: AgentSession | null;
140
- setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;
141
113
  }
142
114
 
143
115
  const emptyCopilotContext: CopilotContextParams = {
@@ -145,11 +117,7 @@ const emptyCopilotContext: CopilotContextParams = {
145
117
  setAction: () => {},
146
118
  removeAction: () => {},
147
119
 
148
- coagentActions: {},
149
- setCoagentAction: () => {},
150
- removeCoagentAction: () => {},
151
-
152
- chatComponentsCache: { current: { actions: {}, coagentActions: {} } },
120
+ chatComponentsCache: { current: {} },
153
121
  getContextString: (documents: DocumentPointer[], categories: string[]) =>
154
122
  returnAndThrowInDebug(""),
155
123
  addContext: () => "",
@@ -187,11 +155,6 @@ const emptyCopilotContext: CopilotContextParams = {
187
155
  addChatSuggestionConfiguration: () => {},
188
156
  removeChatSuggestionConfiguration: () => {},
189
157
  showDevConsole: "auto",
190
- coagentStates: {},
191
- setCoagentStates: () => {},
192
-
193
- agentSession: null,
194
- setAgentSession: () => {},
195
158
  };
196
159
 
197
160
  export const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);
@@ -3,8 +3,6 @@ export type { UseCopilotChatOptions } from "./use-copilot-chat";
3
3
  export type { UseCopilotChatReturn } from "./use-copilot-chat";
4
4
 
5
5
  export { useCopilotAction } from "./use-copilot-action";
6
- export { useCoAgentAction } from "./use-coagent-action";
7
6
  export { useMakeCopilotDocumentReadable } from "./use-make-copilot-document-readable";
8
7
  export { type UseChatHelpers } from "./use-chat";
9
8
  export { useCopilotReadable } from "./use-copilot-readable";
10
- export { useCoAgent } from "./use-coagent";
@@ -2,8 +2,8 @@ import { useRef } from "react";
2
2
  import {
3
3
  FunctionCallHandler,
4
4
  COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,
5
+ Action,
5
6
  actionParametersToJsonSchema,
6
- CoagentActionHandler,
7
7
  } from "@copilotkit/shared";
8
8
  import {
9
9
  Message,
@@ -12,20 +12,14 @@ import {
12
12
  ResultMessage,
13
13
  CopilotRuntimeClient,
14
14
  convertMessagesToGqlInput,
15
- filterAdjacentAgentStateMessages,
16
- filterAgentStateMessages,
17
15
  convertGqlOutputToMessages,
18
16
  MessageStatusCode,
19
17
  MessageRole,
20
18
  Role,
21
19
  CopilotRequestType,
22
- AgentStateMessage,
23
20
  } from "@copilotkit/runtime-client-gql";
24
21
 
25
22
  import { CopilotApiConfig } from "../context";
26
- import { FrontendAction } from "../types/frontend-action";
27
- import { CoagentState } from "../types/coagent-state";
28
- import { AgentSession } from "../context/copilot-context";
29
23
 
30
24
  export type UseChatOptions = {
31
25
  /**
@@ -38,16 +32,10 @@ export type UseChatOptions = {
38
32
  * automatically to the API and will be used to update the chat.
39
33
  */
40
34
  onFunctionCall?: FunctionCallHandler;
41
-
42
- /**
43
- * Callback function to be called when a coagent action is received.
44
- */
45
- onCoagentAction?: CoagentActionHandler;
46
-
47
35
  /**
48
36
  * Function definitions to be sent to the API.
49
37
  */
50
- actions: FrontendAction<any>[];
38
+ actions: Action[];
51
39
 
52
40
  /**
53
41
  * The CopilotKit API configuration.
@@ -77,26 +65,6 @@ export type UseChatOptions = {
77
65
  * setState-powered method to update the isChatLoading value
78
66
  */
79
67
  setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;
80
-
81
- /**
82
- * The current list of coagent states.
83
- */
84
- coagentStates: Record<string, CoagentState>;
85
-
86
- /**
87
- * setState-powered method to update the agent states
88
- */
89
- setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;
90
-
91
- /**
92
- * The current agent session.
93
- */
94
- agentSession: AgentSession | null;
95
-
96
- /**
97
- * setState-powered method to update the agent session
98
- */
99
- setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;
100
68
  };
101
69
 
102
70
  export type UseChatHelpers = {
@@ -129,19 +97,11 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
129
97
  isLoading,
130
98
  actions,
131
99
  onFunctionCall,
132
- onCoagentAction,
133
- setCoagentStates,
134
- coagentStates,
135
- agentSession,
136
- setAgentSession,
137
100
  } = options;
138
-
139
101
  const abortControllerRef = useRef<AbortController>();
140
102
  const threadIdRef = useRef<string | null>(null);
141
103
  const runIdRef = useRef<string | null>(null);
142
-
143
104
  const publicApiKey = copilotConfig.publicApiKey;
144
-
145
105
  const headers = {
146
106
  ...(copilotConfig.headers || {}),
147
107
  ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),
@@ -187,7 +147,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
187
147
  },
188
148
  threadId: threadIdRef.current,
189
149
  runId: runIdRef.current,
190
- messages: convertMessagesToGqlInput(filterAgentStateMessages(messagesWithContext)),
150
+ messages: convertMessagesToGqlInput(messagesWithContext),
191
151
  ...(copilotConfig.cloud
192
152
  ? {
193
153
  cloud: {
@@ -209,15 +169,6 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
209
169
  metadata: {
210
170
  requestType: CopilotRequestType.Chat,
211
171
  },
212
- ...(agentSession
213
- ? {
214
- agentSession,
215
- }
216
- : {}),
217
- agentStates: Object.values(coagentStates).map((state) => ({
218
- agentName: state.name,
219
- state: JSON.stringify(state.state),
220
- })),
221
172
  },
222
173
  properties: copilotConfig.properties,
223
174
  signal: abortControllerRef.current?.signal,
@@ -229,8 +180,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
229
180
 
230
181
  const reader = stream.getReader();
231
182
 
232
- let actionResults: { [id: string]: string } = {};
233
- let executedCoagentActions: string[] = [];
183
+ let results: { [id: string]: string } = {};
234
184
 
235
185
  try {
236
186
  while (true) {
@@ -247,9 +197,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
247
197
  threadIdRef.current = value.generateCopilotResponse.threadId || null;
248
198
  runIdRef.current = value.generateCopilotResponse.runId || null;
249
199
 
250
- const messages = convertGqlOutputToMessages(
251
- filterAdjacentAgentStateMessages(value.generateCopilotResponse.messages),
252
- );
200
+ const messages = convertGqlOutputToMessages(value.generateCopilotResponse.messages);
253
201
 
254
202
  if (messages.length === 0) {
255
203
  continue;
@@ -274,37 +222,14 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
274
222
  else {
275
223
  for (const message of messages) {
276
224
  newMessages.push(message);
277
- if (message instanceof AgentStateMessage) {
278
- if (message.running) {
279
- setCoagentStates((prevAgentStates) => ({
280
- ...prevAgentStates,
281
- [message.agentName]: {
282
- name: message.agentName,
283
- state: message.state,
284
- running: message.running,
285
- active: message.active,
286
- threadId: message.threadId,
287
- nodeName: message.nodeName,
288
- runId: message.runId,
289
- },
290
- }));
291
- setAgentSession({
292
- threadId: message.threadId,
293
- agentName: message.agentName,
294
- nodeName: message.nodeName,
295
- });
296
- } else {
297
- setAgentSession(null);
298
- }
299
- }
300
- // execute regular action executions
225
+
301
226
  if (
302
227
  message instanceof ActionExecutionMessage &&
303
228
  message.status.code !== MessageStatusCode.Pending &&
304
229
  message.scope === "client" &&
305
230
  onFunctionCall
306
231
  ) {
307
- if (!(message.id in actionResults)) {
232
+ if (!(message.id in results)) {
308
233
  // Do not execute a function call if guardrails are enabled but the status is not known
309
234
  if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {
310
235
  break;
@@ -315,48 +240,29 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
315
240
  name: message.name,
316
241
  args: message.arguments,
317
242
  });
318
- actionResults[message.id] = result;
243
+ results[message.id] = result;
319
244
  }
245
+
320
246
  // add the result message
321
247
  newMessages.push(
322
248
  new ResultMessage({
323
- result: ResultMessage.encodeResult(actionResults[message.id]),
249
+ result: ResultMessage.encodeResult(results[message.id]),
324
250
  actionExecutionId: message.id,
325
251
  actionName: message.name,
326
252
  }),
327
253
  );
328
254
  }
329
- // execute coagent actions
330
- if (
331
- message instanceof AgentStateMessage &&
332
- !message.active &&
333
- !executedCoagentActions.includes(message.id) &&
334
- onCoagentAction
335
- ) {
336
- // Do not execute a coagent action if guardrails are enabled but the status is not known
337
- if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {
338
- break;
339
- }
340
- // execute coagent action
341
- await onCoagentAction({
342
- name: message.agentName,
343
- nodeName: message.nodeName,
344
- state: message.state,
345
- });
346
- executedCoagentActions.push(message.id);
347
- }
348
255
  }
349
256
  }
350
257
 
351
258
  if (newMessages.length > 0) {
352
- // Update message state
353
259
  setMessages([...previousMessages, ...newMessages]);
354
260
  }
355
261
  }
356
262
 
357
263
  if (
358
264
  // if we have client side results
359
- Object.values(actionResults).length ||
265
+ Object.values(results).length ||
360
266
  // or the last message we received is a result
361
267
  (newMessages.length && newMessages[newMessages.length - 1] instanceof ResultMessage)
362
268
  ) {
@@ -383,7 +289,6 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
383
289
  if (isLoading) {
384
290
  return;
385
291
  }
386
-
387
292
  const newMessages = [...messages, message];
388
293
  setMessages(newMessages);
389
294
  return runChatCompletionAndHandleFunctionCall(newMessages);
@@ -27,7 +27,7 @@ export function useCopilotAction<const T extends Parameter[] | [] = []>(
27
27
  actions[idRef.current].handler = action.handler as any;
28
28
  if (typeof action.render === "function") {
29
29
  if (chatComponentsCache.current !== null) {
30
- chatComponentsCache.current.actions[action.name] = action.render;
30
+ chatComponentsCache.current[action.name] = action.render;
31
31
  }
32
32
  }
33
33
  }
@@ -39,7 +39,7 @@ export function useCopilotAction<const T extends Parameter[] | [] = []>(
39
39
  }
40
40
  setAction(idRef.current, action as any);
41
41
  if (chatComponentsCache.current !== null && action.render !== undefined) {
42
- chatComponentsCache.current.actions[action.name] = action.render;
42
+ chatComponentsCache.current[action.name] = action.render;
43
43
  }
44
44
  return () => {
45
45
  // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.
@@ -44,8 +44,6 @@ 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
- import { CoagentActionHandlerArguments } from "@copilotkit/shared";
49
47
 
50
48
  export interface UseCopilotChatOptions {
51
49
  /**
@@ -94,12 +92,6 @@ export function useCopilotChat({
94
92
  setIsLoading,
95
93
  chatInstructions,
96
94
  actions,
97
-
98
- coagentStates,
99
- setCoagentStates,
100
- coagentActions,
101
- agentSession,
102
- setAgentSession,
103
95
  } = useCopilotContext();
104
96
 
105
97
  // We need to ensure that makeSystemMessageCallback always uses the latest
@@ -123,40 +115,17 @@ export function useCopilotChat({
123
115
  });
124
116
  }, [getContextString, makeSystemMessage, chatInstructions]);
125
117
 
126
- const onCoagentAction = useCallback(
127
- async (args: CoagentActionHandlerArguments) => {
128
- const { name, nodeName, state } = args;
129
- let action = Object.values(coagentActions).find(
130
- (action) => action.name === name && action.nodeName === nodeName,
131
- );
132
- if (!action) {
133
- action = Object.values(coagentActions).find(
134
- (action) => action.name === name && !action.nodeName,
135
- );
136
- }
137
- if (action) {
138
- await action.handler?.({ state, nodeName });
139
- }
140
- },
141
- [coagentActions],
142
- );
143
-
144
118
  const { append, reload, stop } = useChat({
145
119
  ...options,
146
120
  actions: Object.values(actions),
147
121
  copilotConfig: copilotApiConfig,
148
122
  initialMessages: options.initialMessages || [],
149
123
  onFunctionCall: getFunctionCallHandler(),
150
- onCoagentAction,
151
124
  messages,
152
125
  setMessages,
153
126
  makeSystemMessageCallback,
154
127
  isLoading,
155
128
  setIsLoading,
156
- coagentStates,
157
- setCoagentStates,
158
- agentSession,
159
- setAgentSession,
160
129
  });
161
130
 
162
131
  // this is a workaround born out of a bug that Athena insessently ran into.
@@ -58,7 +58,6 @@ import {
58
58
  TextMessage,
59
59
  convertGqlOutputToMessages,
60
60
  convertMessagesToGqlInput,
61
- filterAgentStateMessages,
62
61
  CopilotRequestType,
63
62
  } from "@copilotkit/runtime-client-gql";
64
63
  import { FrontendAction } from "../types/frontend-action";
@@ -148,7 +147,7 @@ export class CopilotTask<T = any> {
148
147
  })),
149
148
  url: window.location.href,
150
149
  },
151
- messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),
150
+ messages: convertMessagesToGqlInput(messages),
152
151
  metadata: {
153
152
  requestType: CopilotRequestType.Task,
154
153
  },
@@ -16,10 +16,7 @@ import {
16
16
  import { CopilotContextParams } from "../context";
17
17
  import { defaultCopilotContextCategories } from "../components";
18
18
  import { CopilotRuntimeClient } from "@copilotkit/runtime-client-gql";
19
- import {
20
- convertMessagesToGqlInput,
21
- filterAgentStateMessages,
22
- } from "@copilotkit/runtime-client-gql";
19
+ import { convertMessagesToGqlInput } from "@copilotkit/runtime-client-gql";
23
20
 
24
21
  interface InitialState<T extends Parameter[] | [] = []> {
25
22
  status: "initial";
@@ -122,9 +119,7 @@ export async function extract<const T extends Parameter[]>({
122
119
  },
123
120
 
124
121
  messages: convertMessagesToGqlInput(
125
- includeMessages
126
- ? [systemMessage, ...filterAgentStateMessages(messages)]
127
- : [systemMessage],
122
+ includeMessages ? [systemMessage, ...messages] : [systemMessage],
128
123
  ),
129
124
  metadata: {
130
125
  requestType: requestType,
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/copilot-task.ts"],"sourcesContent":["/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n *\n * implementation: async (message) => {\n * // ...\n * },\n * }\n * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n} from \"@copilotkit/runtime-client-gql\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { MessageStatusCode } from \"@copilotkit/runtime-client-gql\";\nimport { actionParametersToJsonSchema } from \"@copilotkit/shared\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions = config.includeCopilotActions !== false;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: Object.values(actions).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 messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n toolChoice: \"required\",\n },\n },\n properties: context.copilotApiConfig.properties,\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m instanceof ActionExecutionMessage);\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\n }\n }\n}\n\nfunction taskSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n"],"mappings":";;;;;;;;AAoDA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKP,SAAS,oCAAoC;AAsBtC,IAAM,cAAN,MAA2B;AAAA,EAMhC,YAAY,QAA2B;AACrC,SAAK,eAAe,OAAO;AAC3B,SAAK,UAAU,OAAO,WAAW,CAAC;AAClC,SAAK,yBAAyB,OAAO,2BAA2B;AAChE,SAAK,wBAAwB,OAAO,0BAA0B;AAAA,EAChE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOM,IAAI,SAA+B,MAAyB;AAAA;AA3GpE;AA4GI,YAAM,UAAU,KAAK,wBAAwB,OAAO,OAAO,CAAC,GAAG,QAAQ,OAAO,IAAI,CAAC;AAGnF,iBAAW,MAAM,KAAK,SAAS;AAC7B,gBAAQ,GAAG,IAAI,IAAI;AAAA,MACrB;AAEA,UAAI,gBAAgB;AAEpB,UAAI,MAAM;AACR,yBAAiB,OAAO,SAAS,WAAW,OAAO,KAAK,UAAU,IAAI,KAAK;AAAA,MA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AAAA,UACnB,MAAM,aAAa;AAAA,QACrB,CAAC;AAAA,MACH;AAAA,IACF;AAAA;AACF;AAEA,SAAS,kBAAkB,eAAuB,cAA8B;AAC9E,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA;AAAA;AAAA;AAGF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/use-copilot-action.ts"],"sourcesContent":["import { useRef, useEffect } from \"react\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { Parameter, randomId } from \"@copilotkit/shared\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();\n const idRef = useRef<string>(randomId());\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n actions[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.actions[action.name] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n if (action.disabled) {\n return;\n }\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.actions[action.name] = action.render;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n action.description,\n action.name,\n action.disabled,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(action.parameters),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\n// Usage Example:\n// useCopilotAction({\n// name: \"myAction\",\n// parameters: [\n// { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n// { name: \"arg2\", type: \"number\" },\n// {\n// name: \"arg3\",\n// type: \"object\",\n// attributes: [\n// { name: \"nestedArg1\", type: \"boolean\" },\n// { name: \"xyz\", required: false },\n// ],\n// },\n// { name: \"arg4\", type: \"number[]\" },\n// ],\n// handler: ({ arg1, arg2, arg3, arg4 }) => {\n// const x = arg3.nestedArg1;\n// const z = arg3.xyz;\n// console.log(arg1, arg2, arg3);\n// },\n// });\n\n// useCopilotAction({\n// name: \"myAction\",\n// handler: () => {\n// console.log(\"No parameters provided.\");\n// },\n// });\n"],"mappings":";;;;;AAAA,SAAS,QAAQ,iBAAiB;AAGlC,SAAoB,gBAAgB;AAW7B,SAAS,iBACd,QACA,cACM;AACN,QAAM,EAAE,WAAW,cAAc,SAAS,oBAAoB,IAAI,kBAAkB;AACpF,QAAM,QAAQ,OAAe,SAAS,CAAC;AAKvC,MAAI,iBAAiB,QAAW;AAC9B,QAAI,QAAQ,MAAM,OAAO,GAAG;AAC1B,cAAQ,MAAM,OAAO,EAAE,UAAU,OAAO;AACxC,UAAI,OAAO,OAAO,WAAW,YAAY;AACvC,YAAI,oBAAoB,YAAY,MAAM;AACxC,8BAAoB,QAAQ,QAAQ,OAAO,IAAI,IAAI,OAAO;AAAA,QAC5D;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,YAAU,MAAM;AACd,QAAI,OAAO,UAAU;AACnB;AAAA,IACF;AACA,cAAU,MAAM,SAAS,MAAa;AACtC,QAAI,oBAAoB,YAAY,QAAQ,OAAO,WAAW,QAAW;AACvE,0BAAoB,QAAQ,QAAQ,OAAO,IAAI,IAAI,OAAO;AAAA,IAC5D;AACA,WAAO,MAAM;AAGX,mBAAa,MAAM,OAAO;AAAA,IAC5B;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA;AAAA;AAAA,IAGP,KAAK,UAAU,OAAO,UAAU;AAAA;AAAA,IAEhC,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":[]}
@@ -1 +0,0 @@
1
- //# sourceMappingURL=chunk-BWYAGPEF.mjs.map
@@ -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 { CoagentActionHandlerArguments } from \"@copilotkit/shared\";\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 messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n\n coagentStates,\n setCoagentStates,\n coagentActions,\n agentSession,\n setAgentSession,\n } = useCopilotContext();\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 onCoagentAction = useCallback(\n async (args: CoagentActionHandlerArguments) => {\n const { name, nodeName, state } = args;\n let action = Object.values(coagentActions).find(\n (action) => action.name === name && action.nodeName === nodeName,\n );\n if (!action) {\n action = Object.values(coagentActions).find(\n (action) => action.name === name && !action.nodeName,\n );\n }\n if (action) {\n await action.handler?.({ state, nodeName });\n }\n },\n [coagentActions],\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 onCoagentAction,\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;AAwCpC,SAAS,eAAe,KAGJ,CAAC,GAAyB;AAHtB,eAC7B;AAAA;AAAA,EAnFF,IAkF+B,IAE1B,oBAF0B,IAE1B;AAAA,IADH;AAAA;AAGA,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IAEA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,kBAAkB;AAItB,QAAM,yBAAyB,cAAc,gBAAgB;AAC7D,QAAM,gBAAgB;AAAA,IACpB,CAAC,cAAsB;AACrB,kBAAY,CAAC,SAAS,KAAK,OAAO,CAAC,YAAY,QAAQ,OAA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["import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport { CoagentAction, CoagentActionRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n}\n\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoagentActionRenderProps<any>,\n) => string | JSX.Element;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coagentActions: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // coagent actions\n coagentActions: Record<string, CoagentAction<any>>;\n setCoagentAction: (id: string, action: CoagentAction<any>) => void;\n removeCoagentAction: (id: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n // chat\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean | \"auto\";\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coagentActions: {},\n setCoagentAction: () => {},\n removeCoagentAction: () => {},\n\n chatComponentsCache: { current: { actions: {}, coagentActions: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n messages: [],\n setMessages: () => returnAndThrowInDebug([]),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: \"auto\",\n coagentStates: {},\n setCoagentStates: () => {},\n\n agentSession: null,\n setAgentSession: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n return value;\n}\n"],"mappings":";;;;;AAGA,OAAO,WAAW;AA2IlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,gBAAgB,CAAC;AAAA,EACjB,kBAAkB,MAAM;AAAA,EAAC;AAAA,EACzB,qBAAqB,MAAM;AAAA,EAAC;AAAA,EAE5B,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,gBAAgB,CAAC,EAAE,EAAE;AAAA,EAC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