@copilotkit/react-core 1.1.1-feat-runtime-remote-actions.0 → 1.1.1-feat-runtime-remote-actions.2

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 +18 -0
  2. package/dist/{chunk-GGE4PURN.mjs → chunk-2Z3ZSFKF.mjs} +48 -49
  3. package/dist/chunk-2Z3ZSFKF.mjs.map +1 -0
  4. package/dist/{chunk-SAGEPCO4.mjs → chunk-3AU37L37.mjs} +8 -6
  5. package/dist/chunk-3AU37L37.mjs.map +1 -0
  6. package/dist/{chunk-T6L4EGTD.mjs → chunk-3CDEYABN.mjs} +2 -2
  7. package/dist/chunk-FZNMAWL5.mjs +1 -0
  8. package/dist/{chunk-UQRDVZ2N.mjs → chunk-GVMHMHNK.mjs} +2 -2
  9. package/dist/chunk-IR73B34N.mjs +43 -0
  10. package/dist/chunk-IR73B34N.mjs.map +1 -0
  11. package/dist/{chunk-GE7LAL6V.mjs → chunk-OBRQXPO5.mjs} +2 -2
  12. package/dist/{chunk-TVR5CJ6E.mjs → chunk-OW75KEAZ.mjs} +6 -3
  13. package/dist/chunk-OW75KEAZ.mjs.map +1 -0
  14. package/dist/{chunk-3NHEWJ4V.mjs → chunk-R2QNDKDN.mjs} +5 -2
  15. package/dist/chunk-R2QNDKDN.mjs.map +1 -0
  16. package/dist/{chunk-VFDR4MIF.mjs → chunk-RJAQJ722.mjs} +2 -2
  17. package/dist/{chunk-KONDJRB4.mjs → chunk-YRNQU6OZ.mjs} +2 -2
  18. package/dist/components/copilot-provider/copilotkit.js +8 -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 +8 -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 +8 -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 +3 -1
  28. package/dist/context/copilot-context.js +4 -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 +4 -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 +1 -0
  35. package/dist/hooks/index.js +85 -50
  36. package/dist/hooks/index.js.map +1 -1
  37. package/dist/hooks/index.mjs +14 -9
  38. package/dist/hooks/use-agent-state.d.ts +12 -0
  39. package/dist/hooks/use-agent-state.js +486 -0
  40. package/dist/hooks/use-agent-state.js.map +1 -0
  41. package/dist/hooks/use-agent-state.mjs +19 -0
  42. package/dist/hooks/use-agent-state.mjs.map +1 -0
  43. package/dist/hooks/use-chat.d.ts +5 -1
  44. package/dist/hooks/use-chat.js +46 -47
  45. package/dist/hooks/use-chat.js.map +1 -1
  46. package/dist/hooks/use-chat.mjs +1 -1
  47. package/dist/hooks/use-copilot-action.js +4 -1
  48. package/dist/hooks/use-copilot-action.js.map +1 -1
  49. package/dist/hooks/use-copilot-action.mjs +2 -2
  50. package/dist/hooks/use-copilot-chat.js +54 -50
  51. package/dist/hooks/use-copilot-chat.js.map +1 -1
  52. package/dist/hooks/use-copilot-chat.mjs +4 -4
  53. package/dist/hooks/use-copilot-readable.js +4 -1
  54. package/dist/hooks/use-copilot-readable.js.map +1 -1
  55. package/dist/hooks/use-copilot-readable.mjs +2 -2
  56. package/dist/hooks/use-make-copilot-document-readable.js +4 -1
  57. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  58. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  59. package/dist/index.d.ts +1 -0
  60. package/dist/index.js +86 -51
  61. package/dist/index.js.map +1 -1
  62. package/dist/index.mjs +16 -12
  63. package/dist/lib/copilot-task.js.map +1 -1
  64. package/dist/lib/copilot-task.mjs +3 -3
  65. package/dist/lib/index.js.map +1 -1
  66. package/dist/lib/index.mjs +3 -3
  67. package/dist/utils/extract.js.map +1 -1
  68. package/dist/utils/extract.mjs +3 -3
  69. package/dist/utils/index.js.map +1 -1
  70. package/dist/utils/index.mjs +3 -3
  71. package/package.json +5 -5
  72. package/src/components/copilot-provider/copilotkit.tsx +5 -1
  73. package/src/context/copilot-context.tsx +7 -1
  74. package/src/hooks/index.ts +1 -0
  75. package/src/hooks/use-agent-state.ts +51 -0
  76. package/src/hooks/use-chat.ts +70 -74
  77. package/src/hooks/use-copilot-chat.ts +2 -0
  78. package/dist/chunk-3NHEWJ4V.mjs.map +0 -1
  79. package/dist/chunk-5JB4B2SV.mjs +0 -1
  80. package/dist/chunk-GGE4PURN.mjs.map +0 -1
  81. package/dist/chunk-SAGEPCO4.mjs.map +0 -1
  82. package/dist/chunk-TVR5CJ6E.mjs.map +0 -1
  83. /package/dist/{chunk-T6L4EGTD.mjs.map → chunk-3CDEYABN.mjs.map} +0 -0
  84. /package/dist/{chunk-5JB4B2SV.mjs.map → chunk-FZNMAWL5.mjs.map} +0 -0
  85. /package/dist/{chunk-UQRDVZ2N.mjs.map → chunk-GVMHMHNK.mjs.map} +0 -0
  86. /package/dist/{chunk-GE7LAL6V.mjs.map → chunk-OBRQXPO5.mjs.map} +0 -0
  87. /package/dist/{chunk-VFDR4MIF.mjs.map → chunk-RJAQJ722.mjs.map} +0 -0
  88. /package/dist/{chunk-KONDJRB4.mjs.map → chunk-YRNQU6OZ.mjs.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # ui
2
2
 
3
+ ## 1.1.1-feat-runtime-remote-actions.2
4
+
5
+ ### Patch Changes
6
+
7
+ - useAgentState
8
+ - Updated dependencies
9
+ - @copilotkit/runtime-client-gql@1.1.1-feat-runtime-remote-actions.2
10
+ - @copilotkit/shared@1.1.1-feat-runtime-remote-actions.2
11
+
12
+ ## 1.1.1-feat-runtime-remote-actions.1
13
+
14
+ ### Patch Changes
15
+
16
+ - Include agent state
17
+ - Updated dependencies
18
+ - @copilotkit/runtime-client-gql@1.1.1-feat-runtime-remote-actions.1
19
+ - @copilotkit/shared@1.1.1-feat-runtime-remote-actions.1
20
+
3
21
  ## 1.1.1-feat-runtime-remote-actions.0
4
22
 
5
23
  ### Patch Changes
@@ -21,7 +21,7 @@ import {
21
21
  MessageRole,
22
22
  Role,
23
23
  CopilotRequestType,
24
- AgentMessage
24
+ AgentStateMessage
25
25
  } from "@copilotkit/runtime-client-gql";
26
26
  function useChat(options) {
27
27
  const {
@@ -33,11 +33,13 @@ function useChat(options) {
33
33
  initialMessages,
34
34
  isLoading,
35
35
  actions,
36
- onFunctionCall
36
+ onFunctionCall,
37
+ setAgentStates
37
38
  } = options;
38
39
  const abortControllerRef = useRef();
39
40
  const threadIdRef = useRef(null);
40
41
  const runIdRef = useRef(null);
42
+ const agentSessionRef = useRef(null);
41
43
  const publicApiKey = copilotConfig.publicApiKey;
42
44
  const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
43
45
  const runtimeClient = new CopilotRuntimeClient({
@@ -47,7 +49,7 @@ function useChat(options) {
47
49
  credentials: copilotConfig.credentials
48
50
  });
49
51
  const runChatCompletion = (previousMessages) => __async(this, null, function* () {
50
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B;
52
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
51
53
  setIsLoading(true);
52
54
  let newMessages = [
53
55
  new TextMessage({
@@ -62,7 +64,7 @@ function useChat(options) {
62
64
  const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
63
65
  const stream = CopilotRuntimeClient.asStream(
64
66
  runtimeClient.generateCopilotResponse({
65
- data: __spreadProps(__spreadValues({
67
+ data: __spreadValues(__spreadProps(__spreadValues({
66
68
  frontend: {
67
69
  actions: actions.map((action) => ({
68
70
  name: action.name,
@@ -86,7 +88,13 @@ function useChat(options) {
86
88
  metadata: {
87
89
  requestType: CopilotRequestType.Chat
88
90
  }
89
- }),
91
+ }), agentSessionRef.current ? {
92
+ agentSession: {
93
+ threadId: agentSessionRef.current.threadId,
94
+ agentName: agentSessionRef.current.agentName,
95
+ nodeName: agentSessionRef.current.nodeName
96
+ }
97
+ } : {}),
90
98
  properties: copilotConfig.properties,
91
99
  signal: (_d = abortControllerRef.current) == null ? void 0 : _d.signal
92
100
  })
@@ -120,6 +128,25 @@ function useChat(options) {
120
128
  } else {
121
129
  for (const message of messages2) {
122
130
  newMessages.push(message);
131
+ if (message instanceof AgentStateMessage) {
132
+ if (message.running) {
133
+ setAgentStates((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
134
+ [message.agentName]: message
135
+ }));
136
+ agentSessionRef.current = {
137
+ threadId: message.threadId,
138
+ agentName: message.agentName,
139
+ nodeName: message.nodeName
140
+ };
141
+ } else {
142
+ setAgentStates((prevAgentStates) => {
143
+ const newAgentStates = __spreadValues({}, prevAgentStates);
144
+ delete newAgentStates[message.agentName];
145
+ return newAgentStates;
146
+ });
147
+ agentSessionRef.current = null;
148
+ }
149
+ }
123
150
  if (message instanceof ActionExecutionMessage && message.status.code !== MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
124
151
  if (!(message.id in results)) {
125
152
  if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
@@ -143,10 +170,23 @@ function useChat(options) {
143
170
  }
144
171
  }
145
172
  if (newMessages.length > 0) {
146
- setMessages([...previousMessages, ...newMessages]);
173
+ const filteredMessages = [...previousMessages, ...newMessages].reduce(
174
+ (acc, message) => {
175
+ if (message instanceof AgentStateMessage && // Check if the current message is an AgentStateMessage
176
+ acc.length > 0 && // Ensure there is at least one message in the accumulator
177
+ acc[acc.length - 1] instanceof AgentStateMessage && // Check if the last message in the accumulator is also an AgentStateMessage
178
+ acc[acc.length - 1].agentName === message.agentName) {
179
+ acc[acc.length - 1] = message;
180
+ } else {
181
+ acc.push(message);
182
+ }
183
+ return acc;
184
+ },
185
+ []
186
+ );
187
+ setMessages(filteredMessages);
147
188
  }
148
189
  }
149
- const lastMessage = newMessages.at(-1);
150
190
  if (
151
191
  // if we have client side results
152
192
  Object.values(results).length || // or the last message we received is a result
@@ -154,47 +194,6 @@ function useChat(options) {
154
194
  ) {
155
195
  yield new Promise((resolve) => setTimeout(resolve, 10));
156
196
  return yield runChatCompletion([...previousMessages, ...newMessages]);
157
- } else if (lastMessage instanceof AgentMessage) {
158
- if (((_l = (_k = (_j = lastMessage.state) == null ? void 0 : _j.coagent) == null ? void 0 : _k.execute) == null ? void 0 : _l.name) === "ask" && !((_p = (_o = (_n = (_m = lastMessage.state) == null ? void 0 : _m.coagent) == null ? void 0 : _n.execute) == null ? void 0 : _o.result) == null ? void 0 : _p.answer)) {
159
- setMessages([...previousMessages, ...newMessages]);
160
- return newMessages.slice();
161
- } else if (((_s = (_r = (_q = lastMessage.state) == null ? void 0 : _q.coagent) == null ? void 0 : _r.execute) == null ? void 0 : _s.name) && !((_v = (_u = (_t = lastMessage.state) == null ? void 0 : _t.coagent) == null ? void 0 : _u.execute) == null ? void 0 : _v.result) && ((_y = (_x = (_w = lastMessage.state) == null ? void 0 : _w.coagent) == null ? void 0 : _x.execute) == null ? void 0 : _y.name) !== "ask" && ((_B = (_A = (_z = lastMessage.state) == null ? void 0 : _z.coagent) == null ? void 0 : _A.execute) == null ? void 0 : _B.name) !== "message" && onFunctionCall) {
162
- console.log(lastMessage);
163
- const result = yield onFunctionCall({
164
- messages: previousMessages,
165
- name: lastMessage.state.coagent.execute.name,
166
- args: lastMessage.state.coagent.execute.arguments
167
- });
168
- const newState = JSON.parse(JSON.stringify(lastMessage.state));
169
- newState.coagent.execute.result = result;
170
- const message = new AgentMessage({
171
- role: Role.User,
172
- agentName: lastMessage.agentName,
173
- nodeName: lastMessage.nodeName,
174
- state: newState,
175
- running: lastMessage.running,
176
- threadId: lastMessage.threadId
177
- });
178
- newMessages.push(message);
179
- yield new Promise((resolve) => setTimeout(resolve, 10));
180
- return yield runChatCompletion([...previousMessages, ...newMessages]);
181
- } else {
182
- if (lastMessage.running) {
183
- yield new Promise((resolve) => setTimeout(resolve, 10));
184
- return yield runChatCompletion([...previousMessages, ...newMessages]);
185
- } else {
186
- const actionExecutionMessage = previousMessages.slice().reverse().find(
187
- (message) => message instanceof ActionExecutionMessage
188
- );
189
- const resultMessage = new ResultMessage({
190
- actionExecutionId: actionExecutionMessage.id,
191
- actionName: actionExecutionMessage.name,
192
- result: ResultMessage.encodeResult(lastMessage.state)
193
- });
194
- setMessages([...previousMessages, ...newMessages, resultMessage]);
195
- return newMessages.slice();
196
- }
197
- }
198
197
  } else {
199
198
  return newMessages.slice();
200
199
  }
@@ -239,4 +238,4 @@ function useChat(options) {
239
238
  export {
240
239
  useChat
241
240
  };
242
- //# sourceMappingURL=chunk-GGE4PURN.mjs.map
241
+ //# sourceMappingURL=chunk-2Z3ZSFKF.mjs.map
@@ -0,0 +1 @@
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 Action,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ActionExecutionMessage,\n ResultMessage,\n CopilotRuntimeClient,\n convertMessagesToGqlInput,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n AgentStateMessage,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../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 * Function definitions to be sent to the API.\n */\n actions: Action[];\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 * setState-powered method to update the agent states\n */\n setAgentStates: React.Dispatch<React.SetStateAction<Record<string, AgentStateMessage | 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\ninterface AgentSession {\n threadId: string;\n agentName: string;\n nodeName: string;\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 setAgentStates,\n } = options;\n\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n const agentSessionRef = useRef<AgentSession | null>(null);\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.map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\n messages: convertMessagesToGqlInput(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: {\n threadId: agentSessionRef.current.threadId,\n agentName: agentSessionRef.current.agentName,\n nodeName: agentSessionRef.current.nodeName,\n },\n }\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 results: { [id: string]: string } = {};\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(value.generateCopilotResponse.messages);\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\n if (message instanceof AgentStateMessage) {\n if (message.running) {\n setAgentStates((prevAgentStates) => ({\n ...prevAgentStates,\n [message.agentName]: message,\n }));\n agentSessionRef.current = {\n threadId: message.threadId,\n agentName: message.agentName,\n nodeName: message.nodeName,\n };\n } else {\n setAgentStates((prevAgentStates) => {\n const newAgentStates = { ...prevAgentStates };\n delete newAgentStates[message.agentName];\n return newAgentStates;\n });\n agentSessionRef.current = null;\n }\n }\n\n // execute regular action executions\n if (\n message instanceof ActionExecutionMessage &&\n message.status.code !== MessageStatusCode.Pending &&\n message.scope === \"client\" &&\n onFunctionCall\n ) {\n if (!(message.id in results)) {\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 const result = await onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n });\n results[message.id] = result;\n }\n\n // add the result message\n newMessages.push(\n new ResultMessage({\n result: ResultMessage.encodeResult(results[message.id]),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Construct filteredMessages inline to remove adjacent AgentStateMessage instances\n // with the same agentName, keeping only the last one.\n const filteredMessages = [...previousMessages, ...newMessages].reduce(\n (acc: Message[], message: Message) => {\n if (\n message instanceof AgentStateMessage && // Check if the current message is an AgentStateMessage\n acc.length > 0 && // Ensure there is at least one message in the accumulator\n acc[acc.length - 1] instanceof AgentStateMessage && // Check if the last message in the accumulator is also an AgentStateMessage\n (acc[acc.length - 1] as AgentStateMessage).agentName === message.agentName // Check if the agentName is the same\n ) {\n // If the conditions are met, replace the last message in the accumulator with the current message\n acc[acc.length - 1] = message;\n } else {\n // Otherwise, add the current message to the accumulator\n acc.push(message);\n }\n return acc; // Return the accumulator for the next iteration\n },\n [],\n );\n\n // Update the state with the filtered messages\n setMessages(filteredMessages);\n }\n }\n\n if (\n // if we have client side results\n Object.values(results).length ||\n // or the last message we received is a result\n (newMessages.length && newMessages[newMessages.length - 1] instanceof ResultMessage)\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 runChatCompletion([...previousMessages, ...newMessages]);\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletion(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 instanceof TextMessage && 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,EAEA;AAAA,OACK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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Aa,SAAS,WAAW,GAAG;AACtC;AAAA,IACF;AACA,QAAI,cAAc,CAAC,GAAG,QAAQ;AAC9B,UAAM,cAAc,SAAS,SAAS,SAAS,CAAC;AAEhD,QAAI,uBAAuB,eAAe,YAAY,SAAS,aAAa;AAC1E,oBAAc,YAAY,MAAM,GAAG,EAAE;AAAA,IACvC;AAEA,gBAAY,WAAW;AAEvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,OAAO,MAAY;AA9X3B;AA+XI,6BAAmB,YAAnB,mBAA4B;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["messages"]}
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  defaultCopilotContextCategories
3
- } from "./chunk-TVR5CJ6E.mjs";
3
+ } from "./chunk-OW75KEAZ.mjs";
4
4
  import {
5
5
  useChat
6
- } from "./chunk-GGE4PURN.mjs";
6
+ } from "./chunk-2Z3ZSFKF.mjs";
7
7
  import {
8
8
  CopilotContext
9
- } from "./chunk-3NHEWJ4V.mjs";
9
+ } from "./chunk-R2QNDKDN.mjs";
10
10
  import {
11
11
  __objRest,
12
12
  __spreadProps,
@@ -31,7 +31,8 @@ function useCopilotChat(_a = {}) {
31
31
  isLoading,
32
32
  setIsLoading,
33
33
  chatInstructions,
34
- actions
34
+ actions,
35
+ setAgentStates
35
36
  } = useContext(CopilotContext);
36
37
  const latestGetContextString = useUpdatedRef(getContextString);
37
38
  const deleteMessage = useCallback(
@@ -57,7 +58,8 @@ function useCopilotChat(_a = {}) {
57
58
  setMessages,
58
59
  makeSystemMessageCallback,
59
60
  isLoading,
60
- setIsLoading
61
+ setIsLoading,
62
+ setAgentStates
61
63
  }));
62
64
  return {
63
65
  visibleMessages: messages,
@@ -104,4 +106,4 @@ export {
104
106
  useCopilotChat,
105
107
  defaultSystemMessage
106
108
  };
107
- //# sourceMappingURL=chunk-SAGEPCO4.mjs.map
109
+ //# sourceMappingURL=chunk-3AU37L37.mjs.map
@@ -0,0 +1 @@
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 { useContext, useRef, useEffect, useCallback } from \"react\";\nimport { CopilotContext } 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\";\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 setAgentStates,\n } = useContext(CopilotContext);\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 { append, reload, stop } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: options.initialMessages || [],\n onFunctionCall: getFunctionCallHandler(),\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n setAgentStates,\n });\n\n return {\n visibleMessages: messages,\n appendMessage: append,\n setMessages,\n reloadMessages: reload,\n stopGeneration: stop,\n deleteMessage,\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,YAAY,QAAQ,WAAW,mBAAmB;AAE3D,SAAkB,MAAM,mBAAmB;AAuCpC,SAAS,eAAe,KAGJ,CAAC,GAAyB;AAHtB,eAC7B;AAAA;AAAA,EAlFF,IAiF+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,IACA;AAAA,EACF,IAAI,WAAW,cAAc;AAI7B,QAAM,yBAAyB,cAAc,gBAAgB;AAC7D,QAAM,gBAAgB;AAAA,IACpB,CAAC,cAAsB;AACrB,kBAAY,CAAC,SAAS,KAAK,OAAO,CAAC,YAAY,QAAQ,OAAO,SAAS,CAAC;AAAA,IAC1E;AAAA,IACA,CAAC,WAAW;AAAA,EACd;AAEA,QAAM,4BAA4B,YAAY,MAAM;AAClD,UAAM,qBAAqB,qBAAqB;AAEhD,UAAM,gBAAgB,uBAAuB,QAAQ,CAAC,GAAG,+BAA+B;AAExF,WAAO,IAAI,YAAY;AAAA,MACrB,SAAS,mBAAmB,eAAe,gBAAgB;AAAA,MAC3D,MAAM,KAAK;AAAA,IACb,CAAC;AAAA,EACH,GAAG,CAAC,kBAAkB,mBAAmB,gBAAgB,CAAC;AAE1D,QAAM,EAAE,QAAQ,QAAQ,KAAK,IAAI,QAAQ,iCACpC,UADoC;AAAA,IAEvC,SAAS,OAAO,OAAO,OAAO;AAAA,IAC9B,eAAe;AAAA,IACf,iBAAiB,QAAQ,mBAAmB,CAAC;AAAA,IAC7C,gBAAgB,uBAAuB;AAAA,IACvC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAC;AAED,SAAO;AAAA,IACL,iBAAiB;AAAA,IACjB,eAAe;AAAA,IACf;AAAA,IACA,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,EACF;AACF;AAIA,SAAS,cAAiB,OAAU;AAClC,QAAM,MAAM,OAAO,KAAK;AAExB,YAAU,MAAM;AACd,QAAI,UAAU;AAAA,EAChB,GAAG,CAAC,KAAK,CAAC;AAEV,SAAO;AACT;AAEO,SAAS,qBACd,eACA,wBACQ;AACR,SACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAUG,yBAAyB;AAAA;AAAA,EAAO,2BAA2B;AAEhE;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  CopilotContext
3
- } from "./chunk-3NHEWJ4V.mjs";
3
+ } from "./chunk-R2QNDKDN.mjs";
4
4
 
5
5
  // src/hooks/use-make-copilot-document-readable.ts
6
6
  import { useContext, useEffect, useRef } from "react";
@@ -20,4 +20,4 @@ function useMakeCopilotDocumentReadable(document, categories, dependencies = [])
20
20
  export {
21
21
  useMakeCopilotDocumentReadable
22
22
  };
23
- //# sourceMappingURL=chunk-T6L4EGTD.mjs.map
23
+ //# sourceMappingURL=chunk-3CDEYABN.mjs.map
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=chunk-FZNMAWL5.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  defaultCopilotContextCategories
3
- } from "./chunk-TVR5CJ6E.mjs";
3
+ } from "./chunk-OW75KEAZ.mjs";
4
4
  import {
5
5
  __async,
6
6
  __spreadValues
@@ -150,4 +150,4 @@ Any additional messages provided are for providing context only and should not b
150
150
  export {
151
151
  extract
152
152
  };
153
- //# sourceMappingURL=chunk-UQRDVZ2N.mjs.map
153
+ //# sourceMappingURL=chunk-GVMHMHNK.mjs.map
@@ -0,0 +1,43 @@
1
+ import {
2
+ useCopilotChat
3
+ } from "./chunk-3AU37L37.mjs";
4
+ import {
5
+ useCopilotContext
6
+ } from "./chunk-R2QNDKDN.mjs";
7
+ import {
8
+ __spreadProps,
9
+ __spreadValues
10
+ } from "./chunk-SKC7AJIV.mjs";
11
+
12
+ // src/hooks/use-agent-state.ts
13
+ function useAgentState(agentName) {
14
+ const { agentStates, setAgentStates } = useCopilotContext();
15
+ const { appendMessage } = useCopilotChat();
16
+ const setSpecificAgentState = (newState) => {
17
+ setAgentStates((prevAgentStates) => {
18
+ const currentState2 = prevAgentStates[agentName];
19
+ if (!currentState2) {
20
+ throw new Error(`Agent state ${agentName} not found`);
21
+ }
22
+ const updatedState = typeof newState === "function" ? newState(currentState2) : newState;
23
+ const agentStateMessage = __spreadProps(__spreadValues({}, currentState2), { state: updatedState });
24
+ appendMessage(agentStateMessage);
25
+ return __spreadProps(__spreadValues({}, prevAgentStates), {
26
+ [agentName]: agentStateMessage
27
+ });
28
+ });
29
+ };
30
+ const currentState = agentStates[agentName];
31
+ return [
32
+ currentState == null ? void 0 : currentState.state,
33
+ setSpecificAgentState,
34
+ currentState ? { nodeName: currentState.nodeName } : void 0
35
+ ];
36
+ }
37
+ var use_agent_state_default = useAgentState;
38
+
39
+ export {
40
+ useAgentState,
41
+ use_agent_state_default
42
+ };
43
+ //# sourceMappingURL=chunk-IR73B34N.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-agent-state.ts"],"sourcesContent":["import { useCopilotContext } from \"../context\";\nimport { useCopilotChat } from \"./use-copilot-chat\";\n\nexport type AgentStateInfo = {\n nodeName: string;\n};\n\ntype SetAgentStateAction<T = any> = (newState: T | ((prevState: T | undefined) => T)) => void;\n\nexport type UseAgentStateReturnType<T = any> = [\n T | undefined,\n SetAgentStateAction<T>,\n AgentStateInfo | undefined,\n];\n\nexport function useAgentState<T = any>(agentName: string): UseAgentStateReturnType<T> {\n const { agentStates, setAgentStates } = useCopilotContext();\n\n const { appendMessage } = useCopilotChat();\n\n const setSpecificAgentState: SetAgentStateAction<T> = (newState) => {\n setAgentStates((prevAgentStates) => {\n const currentState = prevAgentStates[agentName];\n if (!currentState) {\n throw new Error(`Agent state ${agentName} not found`);\n }\n\n const updatedState =\n typeof newState === \"function\" ? (newState as Function)(currentState) : newState;\n\n const agentStateMessage = { ...currentState, state: updatedState };\n\n appendMessage(agentStateMessage);\n\n return {\n ...prevAgentStates,\n [agentName]: agentStateMessage,\n };\n });\n };\n\n const currentState = agentStates[agentName];\n\n return [\n currentState?.state as T,\n setSpecificAgentState,\n currentState ? { nodeName: currentState.nodeName } : undefined,\n ];\n}\n\nexport default useAgentState;\n"],"mappings":";;;;;;;;;;;;AAeO,SAAS,cAAuB,WAA+C;AACpF,QAAM,EAAE,aAAa,eAAe,IAAI,kBAAkB;AAE1D,QAAM,EAAE,cAAc,IAAI,eAAe;AAEzC,QAAM,wBAAgD,CAAC,aAAa;AAClE,mBAAe,CAAC,oBAAoB;AAClC,YAAMA,gBAAe,gBAAgB,SAAS;AAC9C,UAAI,CAACA,eAAc;AACjB,cAAM,IAAI,MAAM,eAAe,qBAAqB;AAAA,MACtD;AAEA,YAAM,eACJ,OAAO,aAAa,aAAc,SAAsBA,aAAY,IAAI;AAE1E,YAAM,oBAAoB,iCAAKA,gBAAL,EAAmB,OAAO,aAAa;AAEjE,oBAAc,iBAAiB;AAE/B,aAAO,iCACF,kBADE;AAAA,QAEL,CAAC,SAAS,GAAG;AAAA,MACf;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,eAAe,YAAY,SAAS;AAE1C,SAAO;AAAA,IACL,6CAAc;AAAA,IACd;AAAA,IACA,eAAe,EAAE,UAAU,aAAa,SAAS,IAAI;AAAA,EACvD;AACF;AAEA,IAAO,0BAAQ;","names":["currentState"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  defaultCopilotContextCategories
3
- } from "./chunk-TVR5CJ6E.mjs";
3
+ } from "./chunk-OW75KEAZ.mjs";
4
4
  import {
5
5
  __async
6
6
  } from "./chunk-SKC7AJIV.mjs";
@@ -115,4 +115,4 @@ ${instructions}
115
115
  export {
116
116
  CopilotTask
117
117
  };
118
- //# sourceMappingURL=chunk-GE7LAL6V.mjs.map
118
+ //# sourceMappingURL=chunk-OBRQXPO5.mjs.map
@@ -6,7 +6,7 @@ import {
6
6
  } from "./chunk-6U3UH3KO.mjs";
7
7
  import {
8
8
  CopilotContext
9
- } from "./chunk-3NHEWJ4V.mjs";
9
+ } from "./chunk-R2QNDKDN.mjs";
10
10
  import {
11
11
  __async,
12
12
  __objRest,
@@ -146,6 +146,7 @@ ${nonDocumentStrings}`;
146
146
  return rest;
147
147
  });
148
148
  };
149
+ const [agentStates, setAgentStates] = useState({});
149
150
  return /* @__PURE__ */ jsx(
150
151
  CopilotContext.Provider,
151
152
  {
@@ -171,7 +172,9 @@ ${nonDocumentStrings}`;
171
172
  removeChatSuggestionConfiguration,
172
173
  chatInstructions,
173
174
  setChatInstructions,
174
- showDevConsole: props.showDevConsole === void 0 ? "auto" : props.showDevConsole
175
+ showDevConsole: props.showDevConsole === void 0 ? "auto" : props.showDevConsole,
176
+ agentStates,
177
+ setAgentStates
175
178
  },
176
179
  children
177
180
  }
@@ -207,4 +210,4 @@ export {
207
210
  CopilotKit,
208
211
  defaultCopilotContextCategories
209
212
  };
210
- //# sourceMappingURL=chunk-TVR5CJ6E.mjs.map
213
+ //# sourceMappingURL=chunk-OW75KEAZ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * <Tabs items={[\"Copilot Cloud (Recommended)\", \"Self-hosted Runtime\"]}>\n * <Tabs.Tab>\n *\n * You can get your Copilot Cloud API key for free by <LinkToCopilotCloud>signing up here</LinkToCopilotCloud>.\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit publicApiKey=\"<your-public-api-key>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n * </Tabs.Tab>\n *\n * <Tabs.Tab>\n * You can find more information about self-hosting CopilotKit [here](/concepts/copilot-runtime).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n * </Tabs.Tab>\n * </Tabs>\n */\nimport { useCallback, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n InChatRenderFunction,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n} from \"@copilotkit/shared\";\nimport { AgentStateMessage, Message } from \"@copilotkit/runtime-client-gql\";\n\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n if (!props.runtimeUrl && !props.publicApiKey) {\n throw new Error(\n \"Please provide either a runtimeUrl or a publicApiKey to the CopilotKit component.\",\n );\n }\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const chatComponentsCache = useRef<Record<string, InChatRenderFunction | string>>({});\n const { addElement, removeElement, printTree } = useTree();\n const [messages, setMessages] = useState<Message[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n if (!props.publicApiKey) {\n if (props.cloudRestrictToTopic) {\n throw new Error(\n \"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide a publicApiKey.\",\n );\n }\n }\n\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n };\n\n const removeChatSuggestionConfiguration = (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n };\n\n const [agentStates, setAgentStates] = useState<Record<string, AgentStateMessage | null>>({});\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n showDevConsole: props.showDevConsole === undefined ? \"auto\" : props.showDevConsole,\n agentStates,\n setAgentStates,\n }}\n >\n {children}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ messages, name, args }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgCA,SAAS,aAAa,QAAQ,gBAAgB;AAQ9C,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,OAGK;AAsKH;AA/JG,SAAS,WAAW,IAAyC;AAAzC,eAAE,WApD7B,IAoD2B,IAAe,kBAAf,IAAe,CAAb;AApD7B,MAAAA,KAAAC;AAwDE,MAAI,CAAC,MAAM,cAAc,CAAC,MAAM,cAAc;AAC5C,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,kBAAkB,MAAM,cAAc;AAE5C,QAAM,CAAC,SAAS,UAAU,IAAI,SAA8C,CAAC,CAAC;AAC9E,QAAM,sBAAsB,OAAsD,CAAC,CAAC;AACpF,QAAM,EAAE,YAAY,eAAe,UAAU,IAAI,iBAAQ;AACzD,QAAM,CAAC,UAAU,WAAW,IAAI,SAAoB,CAAC,CAAC;AACtD,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,CAAC,kBAAkB,mBAAmB,IAAI,SAAS,EAAE;AAE3D,QAAM;AAAA,IACJ,YAAY;AAAA,IACZ,eAAe;AAAA,IACf,aAAa;AAAA,EACf,IAAI,gCAAsC;AAE1C,QAAM,YAAY,YAAY,CAAC,IAAY,WAAgC;AACzE,eAAW,CAAC,eAAe;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H;AAEA,QAAM,CAAC,aAAa,cAAc,IAAI,SAAmD,CAAC,CAAC;AAE3F,SACE;AAAA,IAAC,eAAe;AAAA,IAAf;AAAA,MACC,OAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,gBAAgB,MAAM,mBAAmB,SAAY,SAAS,MAAM;AAAA,QACpE;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;AAEO,IAAM,kCAAkC,CAAC,QAAQ;AAExD,SAAS,iCAAiC,SAAqD;AAC7F,SAAO,CAAO,OAA6B,eAA7B,KAA6B,WAA7B,EAAE,UAAU,MAAM,KAAK,GAAM;AACzC,QAAI,wBAA6D,CAAC;AAClE,aAASE,WAAU,SAAS;AAC1B,4BAAsBA,QAAO,IAAI,IAAIA;AAAA,IACvC;AAEA,UAAM,SAAS,sBAAsB,IAAI;AACzC,QAAI,SAAc;AAClB,QAAI,QAAQ;AACV,YAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,kBAAU,MAAY;AACpB,cAAI;AACF,qBAAS,MAAM,OAAO,QAAQ,IAAI;AAClC,oBAAQ;AAAA,UACV,SAAS,OAAP;AACA,mBAAO,KAAK;AAAA,UACd;AAAA,QACF,EAAC;AAAA,MACH,CAAC;AACD,YAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAAA,IACxD;AACA,WAAO;AAAA,EACT;AACF;","names":["_a","_b","action"]}
@@ -43,7 +43,10 @@ var emptyCopilotContext = {
43
43
  },
44
44
  removeChatSuggestionConfiguration: () => {
45
45
  },
46
- showDevConsole: "auto"
46
+ showDevConsole: "auto",
47
+ agentStates: {},
48
+ setAgentStates: () => {
49
+ }
47
50
  };
48
51
  var CopilotContext = React.createContext(emptyCopilotContext);
49
52
  function useCopilotContext() {
@@ -58,4 +61,4 @@ export {
58
61
  CopilotContext,
59
62
  useCopilotContext
60
63
  };
61
- //# sourceMappingURL=chunk-3NHEWJ4V.mjs.map
64
+ //# sourceMappingURL=chunk-R2QNDKDN.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context/copilot-context.tsx"],"sourcesContent":["import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { AgentStateMessage, 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\";\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;\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 chatComponentsCache: React.RefObject<Record<string, InChatRenderFunction | string>>;\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 // agent states\n agentStates: Record<string, AgentStateMessage | null>;\n setAgentStates: React.Dispatch<React.SetStateAction<Record<string, AgentStateMessage | null>>>;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n chatComponentsCache: { current: {} },\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 agentStates: {},\n setAgentStates: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\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;AAmHlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,EAAE,SAAS,CAAC,EAAE;AAAA,EACnC,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EAEtB,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,UAAU,CAAC;AAAA,EACX,aAAa,MAAM,sBAAsB,CAAC,CAAC;AAAA,EAE3C,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qBAAqB,MAAM,sBAAsB,EAAE;AAAA,EAEnD,qBAAqB,CAAC,eAAyB,sBAAsB,CAAC,CAAC;AAAA,EACvE,oBAAoB,MAAM,sBAAsB,EAAE;AAAA,EAClD,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAE9B,kBAAkB,IAAK,MAAkC;AAAA,IACvD,IAAI,kBAA0B;AAC5B,YAAM,IAAI,MAAM,uEAAuE;AAAA,IACzF;AAAA,IAEA,IAAI,UAAkC;AACpC,aAAO,CAAC;AAAA,IACV;AAAA,IACA,IAAI,OAA4B;AAC9B,aAAO,CAAC;AAAA,IACV;AAAA,EACF,EAAG;AAAA,EAEH,6BAA6B,CAAC;AAAA,EAC9B,gCAAgC,MAAM;AAAA,EAAC;AAAA,EACvC,mCAAmC,MAAM;AAAA,EAAC;AAAA,EAC1C,gBAAgB;AAAA,EAChB,aAAa,CAAC;AAAA,EACd,gBAAgB,MAAM;AAAA,EAAC;AACzB;AAEO,IAAM,iBAAiB,MAAM,cAAoC,mBAAmB;AAEpF,SAAS,oBAA0C;AACxD,SAAO,MAAM,WAAW,cAAc;AACxC;AAEA,SAAS,sBAAyB,OAAa;AAC7C,QAAM,IAAI,MAAM,uEAAuE;AACvF,SAAO;AACT;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  CopilotContext
3
- } from "./chunk-3NHEWJ4V.mjs";
3
+ } from "./chunk-R2QNDKDN.mjs";
4
4
 
5
5
  // src/hooks/use-copilot-action.ts
6
6
  import { useRef, useContext, useEffect } from "react";
@@ -44,4 +44,4 @@ function useCopilotAction(action, dependencies) {
44
44
  export {
45
45
  useCopilotAction
46
46
  };
47
- //# sourceMappingURL=chunk-VFDR4MIF.mjs.map
47
+ //# sourceMappingURL=chunk-RJAQJ722.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  CopilotContext
3
- } from "./chunk-3NHEWJ4V.mjs";
3
+ } from "./chunk-R2QNDKDN.mjs";
4
4
 
5
5
  // src/hooks/use-copilot-readable.ts
6
6
  import { useContext, useEffect, useRef } from "react";
@@ -25,4 +25,4 @@ function useCopilotReadable({ description, value, parentId, categories, convert
25
25
  export {
26
26
  useCopilotReadable
27
27
  };
28
- //# sourceMappingURL=chunk-KONDJRB4.mjs.map
28
+ //# sourceMappingURL=chunk-YRNQU6OZ.mjs.map
@@ -127,7 +127,10 @@ var emptyCopilotContext = {
127
127
  },
128
128
  removeChatSuggestionConfiguration: () => {
129
129
  },
130
- showDevConsole: "auto"
130
+ showDevConsole: "auto",
131
+ agentStates: {},
132
+ setAgentStates: () => {
133
+ }
131
134
  };
132
135
  var CopilotContext = import_react.default.createContext(emptyCopilotContext);
133
136
  function returnAndThrowInDebug(value) {
@@ -462,6 +465,7 @@ ${nonDocumentStrings}`;
462
465
  return rest;
463
466
  });
464
467
  };
468
+ const [agentStates, setAgentStates] = (0, import_react4.useState)({});
465
469
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
466
470
  CopilotContext.Provider,
467
471
  {
@@ -487,7 +491,9 @@ ${nonDocumentStrings}`;
487
491
  removeChatSuggestionConfiguration,
488
492
  chatInstructions,
489
493
  setChatInstructions,
490
- showDevConsole: props.showDevConsole === void 0 ? "auto" : props.showDevConsole
494
+ showDevConsole: props.showDevConsole === void 0 ? "auto" : props.showDevConsole,
495
+ agentStates,
496
+ setAgentStates
491
497
  },
492
498
  children
493
499
  }