@copilotkit/react-core 1.3.1 → 1.3.2-mme-pre.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 (35) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/{chunk-RWPGGPW5.mjs → chunk-A4ZPGH2J.mjs} +22 -11
  3. package/dist/chunk-A4ZPGH2J.mjs.map +1 -0
  4. package/dist/{chunk-VCEOT4GG.mjs → chunk-ADN3YESA.mjs} +2 -2
  5. package/dist/{chunk-NT4LQOL4.mjs → chunk-IRINX3XL.mjs} +2 -2
  6. package/dist/{chunk-A37GANOW.mjs → chunk-MKUT74CS.mjs} +30 -4
  7. package/dist/chunk-MKUT74CS.mjs.map +1 -0
  8. package/dist/hooks/index.js +46 -13
  9. package/dist/hooks/index.js.map +1 -1
  10. package/dist/hooks/index.mjs +7 -7
  11. package/dist/hooks/use-chat.js +21 -10
  12. package/dist/hooks/use-chat.js.map +1 -1
  13. package/dist/hooks/use-chat.mjs +1 -1
  14. package/dist/hooks/use-coagent.js +21 -10
  15. package/dist/hooks/use-coagent.js.map +1 -1
  16. package/dist/hooks/use-coagent.mjs +4 -4
  17. package/dist/hooks/use-copilot-action.js +39 -3
  18. package/dist/hooks/use-copilot-action.js.map +1 -1
  19. package/dist/hooks/use-copilot-action.mjs +1 -1
  20. package/dist/hooks/use-copilot-chat.js +21 -10
  21. package/dist/hooks/use-copilot-chat.js.map +1 -1
  22. package/dist/hooks/use-copilot-chat.mjs +2 -2
  23. package/dist/index.js +46 -13
  24. package/dist/index.js.map +1 -1
  25. package/dist/index.mjs +7 -7
  26. package/dist/types/frontend-action.d.ts +46 -2
  27. package/dist/types/frontend-action.js.map +1 -1
  28. package/package.json +5 -5
  29. package/src/hooks/use-chat.ts +34 -14
  30. package/src/hooks/use-copilot-action.ts +45 -4
  31. package/src/types/frontend-action.ts +69 -6
  32. package/dist/chunk-A37GANOW.mjs.map +0 -1
  33. package/dist/chunk-RWPGGPW5.mjs.map +0 -1
  34. /package/dist/{chunk-VCEOT4GG.mjs.map → chunk-ADN3YESA.mjs.map} +0 -0
  35. /package/dist/{chunk-NT4LQOL4.mjs.map → chunk-IRINX3XL.mjs.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # ui
2
2
 
3
+ ## 1.3.2-mme-pre.0
4
+
5
+ ### Patch Changes
6
+
7
+ - agent Q&A pre
8
+ - Updated dependencies
9
+ - @copilotkit/runtime-client-gql@1.3.2-mme-pre.0
10
+ - @copilotkit/shared@1.3.2-mme-pre.0
11
+
3
12
  ## 1.3.1
4
13
 
5
14
  ### Patch Changes
@@ -45,6 +45,10 @@ function useChat(options) {
45
45
  const abortControllerRef = useRef();
46
46
  const threadIdRef = useRef(null);
47
47
  const runIdRef = useRef(null);
48
+ const coagentStatesRef = useRef(coagentStates);
49
+ coagentStatesRef.current = coagentStates;
50
+ const agentSessionRef = useRef(agentSession);
51
+ agentSessionRef.current = agentSession;
48
52
  const publicApiKey = copilotConfig.publicApiKey;
49
53
  const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
50
54
  const runtimeClient = new CopilotRuntimeClient({
@@ -71,7 +75,7 @@ function useChat(options) {
71
75
  runtimeClient.generateCopilotResponse({
72
76
  data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
73
77
  frontend: {
74
- actions: actions.map((action) => ({
78
+ actions: actions.filter((action) => !action.disabled).map((action) => ({
75
79
  name: action.name,
76
80
  description: action.description || "",
77
81
  jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || []))
@@ -94,10 +98,10 @@ function useChat(options) {
94
98
  metadata: {
95
99
  requestType: CopilotRequestType.Chat
96
100
  }
97
- }), agentSession ? {
98
- agentSession
101
+ }), agentSessionRef.current ? {
102
+ agentSession: agentSessionRef.current
99
103
  } : {}), {
100
- agentStates: Object.values(coagentStates).map((state) => ({
104
+ agentStates: Object.values(coagentStatesRef.current).map((state) => ({
101
105
  agentName: state.name,
102
106
  state: JSON.stringify(state.state)
103
107
  }))
@@ -143,12 +147,18 @@ function useChat(options) {
143
147
  if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
144
148
  break;
145
149
  }
146
- const result = yield onFunctionCall({
147
- messages: previousMessages,
148
- name: message.name,
149
- args: message.arguments
150
- });
151
- actionResults[message.id] = result;
150
+ try {
151
+ setMessages([...previousMessages, ...newMessages]);
152
+ const result = yield onFunctionCall({
153
+ messages: previousMessages,
154
+ name: message.name,
155
+ args: message.arguments
156
+ });
157
+ actionResults[message.id] = result;
158
+ } catch (e) {
159
+ actionResults[message.id] = `Failed to execute action ${message.name}`;
160
+ console.error(`Failed to execute action ${message.name}: ${e}`);
161
+ }
152
162
  }
153
163
  newMessages.push(
154
164
  new ResultMessage({
@@ -172,6 +182,7 @@ function useChat(options) {
172
182
  }
173
183
  const lastAgentStateMessage = [...messages2].reverse().find((message) => message instanceof AgentStateMessage);
174
184
  if (lastAgentStateMessage) {
185
+ console.log(lastAgentStateMessage);
175
186
  if (lastAgentStateMessage.running) {
176
187
  setCoagentStates((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
177
188
  [lastAgentStateMessage.agentName]: {
@@ -249,4 +260,4 @@ function useChat(options) {
249
260
  export {
250
261
  useChat
251
262
  };
252
- //# sourceMappingURL=chunk-RWPGGPW5.mjs.map
263
+ //# sourceMappingURL=chunk-A4ZPGH2J.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 actionParametersToJsonSchema,\n CoagentActionHandler,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ActionExecutionMessage,\n ResultMessage,\n CopilotRuntimeClient,\n convertMessagesToGqlInput,\n filterAdjacentAgentStateMessages,\n filterAgentStateMessages,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n AgentStateMessage,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { AgentSession } from \"../context/copilot-context\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n\n /**\n * Callback function to be called when a coagent action is received.\n */\n onCoagentAction?: CoagentActionHandler;\n\n /**\n * Function definitions to be sent to the API.\n */\n actions: FrontendAction<any>[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n /**\n * The current list of coagent states.\n */\n coagentStates: Record<string, CoagentState>;\n\n /**\n * setState-powered method to update the agent states\n */\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n\n /**\n * The current agent session.\n */\n agentSession: AgentSession | null;\n\n /**\n * setState-powered method to update the agent session\n */\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoagentAction,\n setCoagentStates,\n coagentStates,\n agentSession,\n setAgentSession,\n } = options;\n\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n\n // We need to keep a ref of coagent states because of renderAndWait - making sure\n // the latest state is sent to the API\n // This is a workaround and needs to be addressed in the future\n const coagentStatesRef = useRef<Record<string, CoagentState>>(coagentStates);\n coagentStatesRef.current = coagentStates;\n const agentSessionRef = useRef<AgentSession | null>(agentSession);\n agentSessionRef.current = agentSession;\n\n const publicApiKey = copilotConfig.publicApiKey;\n\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n });\n\n const runChatCompletion = async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n const stream = CopilotRuntimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: actions\n .filter((action) => !action.disabled)\n .map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n url: window.location.href,\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messagesWithContext)),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n ...(copilotConfig.cloud.guardrails?.input?.restrictToTopic?.enabled\n ? {\n guardrails: {\n inputValidationRules: {\n allowList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n }\n : {}),\n },\n }\n : {}),\n metadata: {\n requestType: CopilotRequestType.Chat,\n },\n ...(agentSessionRef.current\n ? {\n agentSession: agentSessionRef.current,\n }\n : {}),\n agentStates: Object.values(coagentStatesRef.current).map((state) => ({\n agentName: state.name,\n state: JSON.stringify(state.state),\n })),\n },\n properties: copilotConfig.properties,\n signal: abortControllerRef.current?.signal,\n }),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let actionResults: { [id: string]: string } = {};\n let executedCoagentActions: 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(\n filterAdjacentAgentStateMessages(value.generateCopilotResponse.messages),\n );\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n }\n\n // add messages to the chat\n else {\n for (const message of messages) {\n newMessages.push(message);\n // execute regular action executions\n if (\n message instanceof ActionExecutionMessage &&\n message.status.code !== MessageStatusCode.Pending &&\n message.scope === \"client\" &&\n onFunctionCall\n ) {\n if (!(message.id in actionResults)) {\n // Do not execute a function call if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute action\n try {\n // We update the message state before calling the handler so that the render\n // function can be called with `executing` state\n setMessages([...previousMessages, ...newMessages]);\n\n const result = await onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n });\n actionResults[message.id] = result;\n } catch (e) {\n actionResults[message.id] = `Failed to execute action ${message.name}`;\n console.error(`Failed to execute action ${message.name}: ${e}`);\n }\n }\n // add the result message\n newMessages.push(\n new ResultMessage({\n result: ResultMessage.encodeResult(actionResults[message.id]),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n // execute coagent actions\n if (\n message instanceof AgentStateMessage &&\n !message.active &&\n !executedCoagentActions.includes(message.id) &&\n onCoagentAction\n ) {\n // Do not execute a coagent action if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute coagent action\n await onCoagentAction({\n name: message.agentName,\n nodeName: message.nodeName,\n state: message.state,\n });\n executedCoagentActions.push(message.id);\n }\n }\n\n const lastAgentStateMessage = [...messages]\n .reverse()\n .find((message) => message instanceof AgentStateMessage);\n\n if (lastAgentStateMessage) {\n console.log(lastAgentStateMessage);\n if (lastAgentStateMessage.running) {\n setCoagentStates((prevAgentStates) => ({\n ...prevAgentStates,\n [lastAgentStateMessage.agentName]: {\n name: lastAgentStateMessage.agentName,\n state: lastAgentStateMessage.state,\n running: lastAgentStateMessage.running,\n active: lastAgentStateMessage.active,\n threadId: lastAgentStateMessage.threadId,\n nodeName: lastAgentStateMessage.nodeName,\n runId: lastAgentStateMessage.runId,\n },\n }));\n setAgentSession({\n threadId: lastAgentStateMessage.threadId,\n agentName: lastAgentStateMessage.agentName,\n nodeName: lastAgentStateMessage.nodeName,\n });\n } else {\n setAgentSession(null);\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Update message state\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n\n if (\n // if we have client side results\n Object.values(actionResults).length ||\n // or the last message we received is a result\n (newMessages.length && newMessages[newMessages.length - 1] 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,EACA;AAAA,OAEK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAkGA,SAAS,QAAQ,SAAyC;AAC/D,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA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AA,QAE5B,YAAY,UAAU,YAAY,YAAY,SAAS,CAAC,aAAa;AAAA,QACtE;AAKA,cAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAEtD,eAAO,MAAM,kBAAkB,CAAC,GAAG,kBAAkB,GAAG,WAAW,CAAC;AAAA,MACtE,OAAO;AACL,eAAO,YAAY,MAAM;AAAA,MAC3B;AAAA,IACF,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF;AAEA,QAAM,yCAAyC,CAAOA,cAAuC;AAC3F,UAAM,kBAAkBA,SAAQ;AAAA,EAClC;AAEA,QAAM,SAAS,CAAO,YAAoC;AACxD,QAAI,WAAW;AACb;AAAA,IACF;AAEA,UAAM,cAAc,CAAC,GAAG,UAAU,OAAO;AACzC,gBAAY,WAAW;AACvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,SAAS,MAA2B;AACxC,QAAI,aAAa,SAAS,WAAW,GAAG;AACtC;AAAA,IACF;AACA,QAAI,cAAc,CAAC,GAAG,QAAQ;AAC9B,UAAM,cAAc,SAAS,SAAS,SAAS,CAAC;AAEhD,QAAI,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;AAhb3B;AAibI,6BAAmB,YAAnB,mBAA4B;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["messages"]}
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-RBNULK3U.mjs";
4
4
  import {
5
5
  useChat
6
- } from "./chunk-RWPGGPW5.mjs";
6
+ } from "./chunk-A4ZPGH2J.mjs";
7
7
  import {
8
8
  useCopilotContext
9
9
  } from "./chunk-J2YXDQHR.mjs";
@@ -162,4 +162,4 @@ export {
162
162
  useCopilotChat,
163
163
  defaultSystemMessage
164
164
  };
165
- //# sourceMappingURL=chunk-VCEOT4GG.mjs.map
165
+ //# sourceMappingURL=chunk-ADN3YESA.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useCopilotChat
3
- } from "./chunk-VCEOT4GG.mjs";
3
+ } from "./chunk-ADN3YESA.mjs";
4
4
  import {
5
5
  useCopilotContext
6
6
  } from "./chunk-J2YXDQHR.mjs";
@@ -133,4 +133,4 @@ ${hint}`;
133
133
  export {
134
134
  useCoAgent
135
135
  };
136
- //# sourceMappingURL=chunk-NT4LQOL4.mjs.map
136
+ //# sourceMappingURL=chunk-IRINX3XL.mjs.map
@@ -1,6 +1,10 @@
1
1
  import {
2
2
  useCopilotContext
3
3
  } from "./chunk-J2YXDQHR.mjs";
4
+ import {
5
+ __async,
6
+ __spreadValues
7
+ } from "./chunk-SKC7AJIV.mjs";
4
8
 
5
9
  // src/hooks/use-copilot-action.ts
6
10
  import { useRef, useEffect } from "react";
@@ -8,6 +12,31 @@ import { randomId } from "@copilotkit/shared";
8
12
  function useCopilotAction(action, dependencies) {
9
13
  const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();
10
14
  const idRef = useRef(randomId());
15
+ const renderAndWaitRef = useRef(null);
16
+ action = __spreadValues({}, action);
17
+ if (action.renderAndWait) {
18
+ const renderAndWait = action.renderAndWait;
19
+ action.renderAndWait = void 0;
20
+ action.handler = () => __async(this, null, function* () {
21
+ let resolve;
22
+ let reject;
23
+ const promise = new Promise((resolvePromise, rejectPromise) => {
24
+ resolve = resolvePromise;
25
+ reject = rejectPromise;
26
+ });
27
+ renderAndWaitRef.current = { promise, resolve, reject };
28
+ return yield promise;
29
+ });
30
+ action.render = (props) => {
31
+ const waitProps = {
32
+ status: props.status,
33
+ args: props.args,
34
+ result: props.result,
35
+ handler: props.status === "executing" ? renderAndWaitRef.current.resolve : void 0
36
+ };
37
+ return renderAndWait(waitProps);
38
+ };
39
+ }
11
40
  if (dependencies === void 0) {
12
41
  if (actions[idRef.current]) {
13
42
  actions[idRef.current].handler = action.handler;
@@ -19,9 +48,6 @@ function useCopilotAction(action, dependencies) {
19
48
  }
20
49
  }
21
50
  useEffect(() => {
22
- if (action.disabled) {
23
- return;
24
- }
25
51
  setAction(idRef.current, action);
26
52
  if (chatComponentsCache.current !== null && action.render !== void 0) {
27
53
  chatComponentsCache.current.actions[action.name] = action.render;
@@ -48,4 +74,4 @@ function useCopilotAction(action, dependencies) {
48
74
  export {
49
75
  useCopilotAction
50
76
  };
51
- //# sourceMappingURL=chunk-A37GANOW.mjs.map
77
+ //# sourceMappingURL=chunk-MKUT74CS.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-action.ts"],"sourcesContent":["import { useRef, useEffect } from \"react\";\nimport { FrontendAction, ActionRenderProps, ActionRenderPropsWait } 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 const renderAndWaitRef = useRef<RenderAndWait | null>(null);\n\n // clone the action to avoid mutating the original object\n action = { ...action };\n\n // If the developer provides a renderAndWait function, we transform the action\n // to use a promise internally, so that we can treat it like a normal action.\n if (action.renderAndWait) {\n const renderAndWait = action.renderAndWait!;\n\n // remove the renderAndWait function from the action\n action.renderAndWait = undefined;\n\n // add a handler that will be called when the action is executed\n action.handler = (async () => {\n // we create a new promise when the handler is called\n let resolve: (result: any) => void;\n let reject: (error: any) => void;\n const promise = new Promise<any>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n renderAndWaitRef.current = { promise, resolve: resolve!, reject: reject! };\n // then we await the promise (it will be resolved in the original renderAndWait function)\n return await promise;\n }) as any;\n\n // add a render function that will be called when the action is rendered\n action.render = ((props: ActionRenderProps<any>): React.ReactElement => {\n const waitProps: ActionRenderPropsWait<any> = {\n status: props.status as any,\n args: props.args,\n result: props.result,\n handler: props.status === \"executing\" ? renderAndWaitRef.current!.resolve : undefined,\n };\n return renderAndWait(waitProps);\n }) as any;\n }\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 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\ninterface RenderAndWait {\n promise: Promise<any>;\n resolve: (result: any) => void;\n reject: (error: any) => void;\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;AACvC,QAAM,mBAAmB,OAA6B,IAAI;AAG1D,WAAS,mBAAK;AAId,MAAI,OAAO,eAAe;AACxB,UAAM,gBAAgB,OAAO;AAG7B,WAAO,gBAAgB;AAGvB,WAAO,UAAW,MAAY;AAE5B,UAAI;AACJ,UAAI;AACJ,YAAM,UAAU,IAAI,QAAa,CAAC,gBAAgB,kBAAkB;AAClE,kBAAU;AACV,iBAAS;AAAA,MACX,CAAC;AACD,uBAAiB,UAAU,EAAE,SAAS,SAAmB,OAAgB;AAEzE,aAAO,MAAM;AAAA,IACf;AAGA,WAAO,SAAU,CAAC,UAAsD;AACtE,YAAM,YAAwC;AAAA,QAC5C,QAAQ,MAAM;AAAA,QACd,MAAM,MAAM;AAAA,QACZ,QAAQ,MAAM;AAAA,QACd,SAAS,MAAM,WAAW,cAAc,iBAAiB,QAAS,UAAU;AAAA,MAC9E;AACA,aAAO,cAAc,SAAS;AAAA,IAChC;AAAA,EACF;AAKA,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,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":[]}
@@ -185,6 +185,10 @@ function useChat(options) {
185
185
  const abortControllerRef = (0, import_react2.useRef)();
186
186
  const threadIdRef = (0, import_react2.useRef)(null);
187
187
  const runIdRef = (0, import_react2.useRef)(null);
188
+ const coagentStatesRef = (0, import_react2.useRef)(coagentStates);
189
+ coagentStatesRef.current = coagentStates;
190
+ const agentSessionRef = (0, import_react2.useRef)(agentSession);
191
+ agentSessionRef.current = agentSession;
188
192
  const publicApiKey = copilotConfig.publicApiKey;
189
193
  const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
190
194
  const runtimeClient = new import_runtime_client_gql.CopilotRuntimeClient({
@@ -211,7 +215,7 @@ function useChat(options) {
211
215
  runtimeClient.generateCopilotResponse({
212
216
  data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
213
217
  frontend: {
214
- actions: actions.map((action) => ({
218
+ actions: actions.filter((action) => !action.disabled).map((action) => ({
215
219
  name: action.name,
216
220
  description: action.description || "",
217
221
  jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || []))
@@ -234,10 +238,10 @@ function useChat(options) {
234
238
  metadata: {
235
239
  requestType: import_runtime_client_gql.CopilotRequestType.Chat
236
240
  }
237
- }), agentSession ? {
238
- agentSession
241
+ }), agentSessionRef.current ? {
242
+ agentSession: agentSessionRef.current
239
243
  } : {}), {
240
- agentStates: Object.values(coagentStates).map((state) => ({
244
+ agentStates: Object.values(coagentStatesRef.current).map((state) => ({
241
245
  agentName: state.name,
242
246
  state: JSON.stringify(state.state)
243
247
  }))
@@ -283,12 +287,18 @@ function useChat(options) {
283
287
  if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
284
288
  break;
285
289
  }
286
- const result = yield onFunctionCall({
287
- messages: previousMessages,
288
- name: message.name,
289
- args: message.arguments
290
- });
291
- actionResults[message.id] = result;
290
+ try {
291
+ setMessages([...previousMessages, ...newMessages]);
292
+ const result = yield onFunctionCall({
293
+ messages: previousMessages,
294
+ name: message.name,
295
+ args: message.arguments
296
+ });
297
+ actionResults[message.id] = result;
298
+ } catch (e) {
299
+ actionResults[message.id] = `Failed to execute action ${message.name}`;
300
+ console.error(`Failed to execute action ${message.name}: ${e}`);
301
+ }
292
302
  }
293
303
  newMessages.push(
294
304
  new import_runtime_client_gql.ResultMessage({
@@ -312,6 +322,7 @@ function useChat(options) {
312
322
  }
313
323
  const lastAgentStateMessage = [...messages2].reverse().find((message) => message instanceof import_runtime_client_gql.AgentStateMessage);
314
324
  if (lastAgentStateMessage) {
325
+ console.log(lastAgentStateMessage);
315
326
  if (lastAgentStateMessage.running) {
316
327
  setCoagentStates((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
317
328
  [lastAgentStateMessage.agentName]: {
@@ -541,6 +552,31 @@ var import_shared3 = require("@copilotkit/shared");
541
552
  function useCopilotAction(action, dependencies) {
542
553
  const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();
543
554
  const idRef = (0, import_react5.useRef)((0, import_shared3.randomId)());
555
+ const renderAndWaitRef = (0, import_react5.useRef)(null);
556
+ action = __spreadValues({}, action);
557
+ if (action.renderAndWait) {
558
+ const renderAndWait = action.renderAndWait;
559
+ action.renderAndWait = void 0;
560
+ action.handler = () => __async(this, null, function* () {
561
+ let resolve;
562
+ let reject;
563
+ const promise = new Promise((resolvePromise, rejectPromise) => {
564
+ resolve = resolvePromise;
565
+ reject = rejectPromise;
566
+ });
567
+ renderAndWaitRef.current = { promise, resolve, reject };
568
+ return yield promise;
569
+ });
570
+ action.render = (props) => {
571
+ const waitProps = {
572
+ status: props.status,
573
+ args: props.args,
574
+ result: props.result,
575
+ handler: props.status === "executing" ? renderAndWaitRef.current.resolve : void 0
576
+ };
577
+ return renderAndWait(waitProps);
578
+ };
579
+ }
544
580
  if (dependencies === void 0) {
545
581
  if (actions[idRef.current]) {
546
582
  actions[idRef.current].handler = action.handler;
@@ -552,9 +588,6 @@ function useCopilotAction(action, dependencies) {
552
588
  }
553
589
  }
554
590
  (0, import_react5.useEffect)(() => {
555
- if (action.disabled) {
556
- return;
557
- }
558
591
  setAction(idRef.current, action);
559
592
  if (chatComponentsCache.current !== null && action.render !== void 0) {
560
593
  chatComponentsCache.current.actions[action.name] = action.render;