@copilotkit/react-core 1.3.2-mme-discover-actions.0 → 1.3.2-mme-pre.1

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 +15 -4
  2. package/dist/{chunk-MJE3JSQX.mjs → chunk-CUVW6DXF.mjs} +11 -5
  3. package/dist/chunk-CUVW6DXF.mjs.map +1 -0
  4. package/dist/{chunk-OB7HD4Z5.mjs → chunk-EGKPQFX5.mjs} +2 -2
  5. package/dist/{chunk-A37GANOW.mjs → chunk-MKUT74CS.mjs} +30 -4
  6. package/dist/chunk-MKUT74CS.mjs.map +1 -0
  7. package/dist/{chunk-CJFMZH36.mjs → chunk-TGAG2RZM.mjs} +2 -2
  8. package/dist/hooks/index.js +35 -7
  9. package/dist/hooks/index.js.map +1 -1
  10. package/dist/hooks/index.mjs +4 -4
  11. package/dist/hooks/use-chat.js +10 -4
  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 +10 -4
  15. package/dist/hooks/use-coagent.js.map +1 -1
  16. package/dist/hooks/use-coagent.mjs +3 -3
  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 +10 -4
  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 +35 -7
  24. package/dist/index.js.map +1 -1
  25. package/dist/index.mjs +4 -4
  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 +23 -8
  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-MJE3JSQX.mjs.map +0 -1
  34. /package/dist/{chunk-OB7HD4Z5.mjs.map → chunk-EGKPQFX5.mjs.map} +0 -0
  35. /package/dist/{chunk-CJFMZH36.mjs.map → chunk-TGAG2RZM.mjs.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,13 +1,24 @@
1
1
  # ui
2
2
 
3
- ## 1.3.2-mme-discover-actions.0
3
+ ## 1.3.2-mme-pre.1
4
4
 
5
5
  ### Patch Changes
6
6
 
7
- - Ensure actions can be discovered on state change
7
+ - Pre-release
8
+ - 30232c0: Ensure actions can be discovered on state change
8
9
  - Updated dependencies
9
- - @copilotkit/runtime-client-gql@1.3.2-mme-discover-actions.0
10
- - @copilotkit/shared@1.3.2-mme-discover-actions.0
10
+ - Updated dependencies [30232c0]
11
+ - @copilotkit/runtime-client-gql@1.3.2-mme-pre.1
12
+ - @copilotkit/shared@1.3.2-mme-pre.1
13
+
14
+ ## 1.3.2-mme-pre.0
15
+
16
+ ### Patch Changes
17
+
18
+ - agent Q&A pre
19
+ - Updated dependencies
20
+ - @copilotkit/runtime-client-gql@1.3.2-mme-pre.0
21
+ - @copilotkit/shared@1.3.2-mme-pre.0
11
22
 
12
23
  ## 1.3.1
13
24
 
@@ -46,6 +46,10 @@ function useChat(options) {
46
46
  const threadIdRef = useRef(null);
47
47
  const runIdRef = useRef(null);
48
48
  const runChatCompletionRef = useRef();
49
+ const coagentStatesRef = useRef(coagentStates);
50
+ coagentStatesRef.current = coagentStates;
51
+ const agentSessionRef = useRef(agentSession);
52
+ agentSessionRef.current = agentSession;
49
53
  const publicApiKey = copilotConfig.publicApiKey;
50
54
  const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
51
55
  const runtimeClient = new CopilotRuntimeClient({
@@ -72,7 +76,7 @@ function useChat(options) {
72
76
  runtimeClient.generateCopilotResponse({
73
77
  data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
74
78
  frontend: {
75
- actions: actions.map((action) => ({
79
+ actions: actions.filter((action) => !action.disabled).map((action) => ({
76
80
  name: action.name,
77
81
  description: action.description || "",
78
82
  jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || []))
@@ -95,10 +99,10 @@ function useChat(options) {
95
99
  metadata: {
96
100
  requestType: CopilotRequestType.Chat
97
101
  }
98
- }), agentSession ? {
99
- agentSession
102
+ }), agentSessionRef.current ? {
103
+ agentSession: agentSessionRef.current
100
104
  } : {}), {
101
- agentStates: Object.values(coagentStates).map((state) => ({
105
+ agentStates: Object.values(coagentStatesRef.current).map((state) => ({
102
106
  agentName: state.name,
103
107
  state: JSON.stringify(state.state)
104
108
  }))
@@ -145,6 +149,7 @@ function useChat(options) {
145
149
  break;
146
150
  }
147
151
  try {
152
+ setMessages([...previousMessages, ...newMessages]);
148
153
  const result = yield onFunctionCall({
149
154
  messages: previousMessages,
150
155
  name: message.name,
@@ -178,6 +183,7 @@ function useChat(options) {
178
183
  }
179
184
  const lastAgentStateMessage = [...messages2].reverse().find((message) => message instanceof AgentStateMessage);
180
185
  if (lastAgentStateMessage) {
186
+ console.log(lastAgentStateMessage);
181
187
  if (lastAgentStateMessage.running) {
182
188
  setCoagentStates((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
183
189
  [lastAgentStateMessage.agentName]: {
@@ -256,4 +262,4 @@ function useChat(options) {
256
262
  export {
257
263
  useChat
258
264
  };
259
- //# sourceMappingURL=chunk-MJE3JSQX.mjs.map
265
+ //# sourceMappingURL=chunk-CUVW6DXF.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\n const runChatCompletionRef = useRef<(previousMessages: Message[]) => Promise<Message[]>>();\n // We need to keep a ref of coagent states because of renderAndWait - making sure\n // the latest state is sent to the API\n // This is a workaround and needs to be addressed in the future\n const coagentStatesRef = useRef<Record<string, CoagentState>>(coagentStates);\n coagentStatesRef.current = coagentStates;\n const agentSessionRef = useRef<AgentSession | null>(agentSession);\n agentSessionRef.current = agentSession;\n\n const publicApiKey = copilotConfig.publicApiKey;\n\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n });\n\n const runChatCompletion = async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n const stream = CopilotRuntimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: actions\n .filter((action) => !action.disabled)\n .map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n url: window.location.href,\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messagesWithContext)),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n ...(copilotConfig.cloud.guardrails?.input?.restrictToTopic?.enabled\n ? {\n guardrails: {\n inputValidationRules: {\n allowList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n }\n : {}),\n },\n }\n : {}),\n metadata: {\n requestType: CopilotRequestType.Chat,\n },\n ...(agentSessionRef.current\n ? {\n agentSession: agentSessionRef.current,\n }\n : {}),\n agentStates: Object.values(coagentStatesRef.current).map((state) => ({\n agentName: state.name,\n state: JSON.stringify(state.state),\n })),\n },\n properties: copilotConfig.properties,\n signal: abortControllerRef.current?.signal,\n }),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let actionResults: { [id: string]: string } = {};\n let 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 runChatCompletionRef.current!([...previousMessages, ...newMessages]);\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n runChatCompletionRef.current = runChatCompletion;\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletionRef.current!(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (isLoading) {\n return;\n }\n\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage 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;AAA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6 @@
1
1
  import {
2
2
  useCopilotChat
3
- } from "./chunk-CJFMZH36.mjs";
3
+ } from "./chunk-TGAG2RZM.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-OB7HD4Z5.mjs.map
136
+ //# sourceMappingURL=chunk-EGKPQFX5.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":[]}
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-RBNULK3U.mjs";
4
4
  import {
5
5
  useChat
6
- } from "./chunk-MJE3JSQX.mjs";
6
+ } from "./chunk-CUVW6DXF.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-CJFMZH36.mjs.map
165
+ //# sourceMappingURL=chunk-TGAG2RZM.mjs.map
@@ -186,6 +186,10 @@ function useChat(options) {
186
186
  const threadIdRef = (0, import_react2.useRef)(null);
187
187
  const runIdRef = (0, import_react2.useRef)(null);
188
188
  const runChatCompletionRef = (0, import_react2.useRef)();
189
+ const coagentStatesRef = (0, import_react2.useRef)(coagentStates);
190
+ coagentStatesRef.current = coagentStates;
191
+ const agentSessionRef = (0, import_react2.useRef)(agentSession);
192
+ agentSessionRef.current = agentSession;
189
193
  const publicApiKey = copilotConfig.publicApiKey;
190
194
  const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
191
195
  const runtimeClient = new import_runtime_client_gql.CopilotRuntimeClient({
@@ -212,7 +216,7 @@ function useChat(options) {
212
216
  runtimeClient.generateCopilotResponse({
213
217
  data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
214
218
  frontend: {
215
- actions: actions.map((action) => ({
219
+ actions: actions.filter((action) => !action.disabled).map((action) => ({
216
220
  name: action.name,
217
221
  description: action.description || "",
218
222
  jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || []))
@@ -235,10 +239,10 @@ function useChat(options) {
235
239
  metadata: {
236
240
  requestType: import_runtime_client_gql.CopilotRequestType.Chat
237
241
  }
238
- }), agentSession ? {
239
- agentSession
242
+ }), agentSessionRef.current ? {
243
+ agentSession: agentSessionRef.current
240
244
  } : {}), {
241
- agentStates: Object.values(coagentStates).map((state) => ({
245
+ agentStates: Object.values(coagentStatesRef.current).map((state) => ({
242
246
  agentName: state.name,
243
247
  state: JSON.stringify(state.state)
244
248
  }))
@@ -285,6 +289,7 @@ function useChat(options) {
285
289
  break;
286
290
  }
287
291
  try {
292
+ setMessages([...previousMessages, ...newMessages]);
288
293
  const result = yield onFunctionCall({
289
294
  messages: previousMessages,
290
295
  name: message.name,
@@ -318,6 +323,7 @@ function useChat(options) {
318
323
  }
319
324
  const lastAgentStateMessage = [...messages2].reverse().find((message) => message instanceof import_runtime_client_gql.AgentStateMessage);
320
325
  if (lastAgentStateMessage) {
326
+ console.log(lastAgentStateMessage);
321
327
  if (lastAgentStateMessage.running) {
322
328
  setCoagentStates((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
323
329
  [lastAgentStateMessage.agentName]: {
@@ -548,6 +554,31 @@ var import_shared3 = require("@copilotkit/shared");
548
554
  function useCopilotAction(action, dependencies) {
549
555
  const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();
550
556
  const idRef = (0, import_react5.useRef)((0, import_shared3.randomId)());
557
+ const renderAndWaitRef = (0, import_react5.useRef)(null);
558
+ action = __spreadValues({}, action);
559
+ if (action.renderAndWait) {
560
+ const renderAndWait = action.renderAndWait;
561
+ action.renderAndWait = void 0;
562
+ action.handler = () => __async(this, null, function* () {
563
+ let resolve;
564
+ let reject;
565
+ const promise = new Promise((resolvePromise, rejectPromise) => {
566
+ resolve = resolvePromise;
567
+ reject = rejectPromise;
568
+ });
569
+ renderAndWaitRef.current = { promise, resolve, reject };
570
+ return yield promise;
571
+ });
572
+ action.render = (props) => {
573
+ const waitProps = {
574
+ status: props.status,
575
+ args: props.args,
576
+ result: props.result,
577
+ handler: props.status === "executing" ? renderAndWaitRef.current.resolve : void 0
578
+ };
579
+ return renderAndWait(waitProps);
580
+ };
581
+ }
551
582
  if (dependencies === void 0) {
552
583
  if (actions[idRef.current]) {
553
584
  actions[idRef.current].handler = action.handler;
@@ -559,9 +590,6 @@ function useCopilotAction(action, dependencies) {
559
590
  }
560
591
  }
561
592
  (0, import_react5.useEffect)(() => {
562
- if (action.disabled) {
563
- return;
564
- }
565
593
  setAction(idRef.current, action);
566
594
  if (chatComponentsCache.current !== null && action.render !== void 0) {
567
595
  chatComponentsCache.current.actions[action.name] = action.render;