@copilotkit/react-core 1.1.1-feat-runtime-remote-actions.2 → 1.1.1-feat-runtime-remote-actions.4
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.
- package/CHANGELOG.md +18 -0
- package/dist/{chunk-RJAQJ722.mjs → chunk-2MQX7BJL.mjs} +4 -4
- package/dist/chunk-2MQX7BJL.mjs.map +1 -0
- package/dist/{chunk-YRNQU6OZ.mjs → chunk-33ERMMNX.mjs} +2 -2
- package/dist/{chunk-3CDEYABN.mjs → chunk-3K7JAFGM.mjs} +2 -2
- package/dist/{chunk-2Z3ZSFKF.mjs → chunk-52M7642J.mjs} +3 -2
- package/dist/{chunk-2Z3ZSFKF.mjs.map → chunk-52M7642J.mjs.map} +1 -1
- package/dist/chunk-6YOQY4WD.mjs +20 -0
- package/dist/chunk-6YOQY4WD.mjs.map +1 -0
- package/dist/{chunk-OBRQXPO5.mjs → chunk-73KBO5JG.mjs} +2 -2
- package/dist/{chunk-IR73B34N.mjs → chunk-A47L32JN.mjs} +15 -6
- package/dist/chunk-A47L32JN.mjs.map +1 -0
- package/dist/chunk-AIWDXM7L.mjs +1 -0
- package/dist/{chunk-R2QNDKDN.mjs → chunk-DB4VWZ5Q.mjs} +5 -2
- package/dist/chunk-DB4VWZ5Q.mjs.map +1 -0
- package/dist/{chunk-3AU37L37.mjs → chunk-DZH3HSXW.mjs} +6 -6
- package/dist/{chunk-GVMHMHNK.mjs → chunk-H4XENJME.mjs} +2 -2
- package/dist/{chunk-OW75KEAZ.mjs → chunk-IF6P5ZXR.mjs} +7 -4
- package/dist/chunk-IF6P5ZXR.mjs.map +1 -0
- package/dist/components/copilot-provider/copilotkit.js +9 -3
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +2 -2
- package/dist/components/copilot-provider/index.js +9 -3
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +2 -2
- package/dist/components/index.js +9 -3
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +2 -2
- package/dist/context/copilot-context.d.ts +9 -2
- package/dist/context/copilot-context.js +4 -1
- package/dist/context/copilot-context.js.map +1 -1
- package/dist/context/copilot-context.mjs +1 -1
- package/dist/context/index.d.ts +1 -0
- package/dist/context/index.js +4 -1
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +1 -1
- package/dist/hooks/index.d.ts +1 -0
- package/dist/hooks/index.js +34 -7
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +15 -11
- package/dist/hooks/use-agent-state.js +18 -5
- package/dist/hooks/use-agent-state.js.map +1 -1
- package/dist/hooks/use-agent-state.mjs +5 -5
- package/dist/hooks/use-chat.d.ts +1 -0
- package/dist/hooks/use-chat.js +2 -1
- package/dist/hooks/use-chat.js.map +1 -1
- package/dist/hooks/use-chat.mjs +1 -1
- package/dist/hooks/use-coagent.d.ts +31 -0
- package/dist/hooks/use-coagent.js +48 -0
- package/dist/hooks/use-coagent.js.map +1 -0
- package/dist/hooks/use-coagent.mjs +24 -0
- package/dist/hooks/use-coagent.mjs.map +1 -0
- package/dist/hooks/use-copilot-action.js +6 -3
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +2 -2
- package/dist/hooks/use-copilot-chat-ui.d.ts +13 -0
- package/dist/hooks/use-copilot-chat-ui.js +130 -0
- package/dist/hooks/use-copilot-chat-ui.js.map +1 -0
- package/dist/hooks/use-copilot-chat-ui.mjs +10 -0
- package/dist/hooks/use-copilot-chat-ui.mjs.map +1 -0
- package/dist/hooks/use-copilot-chat.js +6 -2
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +4 -4
- package/dist/hooks/use-copilot-readable.js +4 -1
- package/dist/hooks/use-copilot-readable.js.map +1 -1
- package/dist/hooks/use-copilot-readable.mjs +2 -2
- package/dist/hooks/use-make-copilot-document-readable.js +4 -1
- package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +56 -26
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +18 -14
- package/dist/lib/copilot-task.d.ts +1 -0
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +3 -3
- package/dist/lib/index.d.ts +1 -0
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +3 -3
- package/dist/utils/extract.d.ts +1 -0
- package/dist/utils/extract.js.map +1 -1
- package/dist/utils/extract.mjs +3 -3
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +3 -3
- package/package.json +5 -5
- package/src/components/copilot-provider/copilotkit.tsx +7 -1
- package/src/context/copilot-context.tsx +14 -2
- package/src/hooks/index.ts +1 -0
- package/src/hooks/use-agent-state.ts +15 -3
- package/src/hooks/use-chat.ts +2 -1
- package/src/hooks/use-coagent.ts +60 -0
- package/src/hooks/use-copilot-action.ts +2 -2
- package/src/hooks/use-copilot-chat-ui.ts +26 -0
- package/dist/chunk-FZNMAWL5.mjs +0 -1
- package/dist/chunk-IR73B34N.mjs.map +0 -1
- package/dist/chunk-OW75KEAZ.mjs.map +0 -1
- package/dist/chunk-R2QNDKDN.mjs.map +0 -1
- package/dist/chunk-RJAQJ722.mjs.map +0 -1
- /package/dist/{chunk-YRNQU6OZ.mjs.map → chunk-33ERMMNX.mjs.map} +0 -0
- /package/dist/{chunk-3CDEYABN.mjs.map → chunk-3K7JAFGM.mjs.map} +0 -0
- /package/dist/{chunk-OBRQXPO5.mjs.map → chunk-73KBO5JG.mjs.map} +0 -0
- /package/dist/{chunk-FZNMAWL5.mjs.map → chunk-AIWDXM7L.mjs.map} +0 -0
- /package/dist/{chunk-3AU37L37.mjs.map → chunk-DZH3HSXW.mjs.map} +0 -0
- /package/dist/{chunk-GVMHMHNK.mjs.map → chunk-H4XENJME.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.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Show agent state in the chat window
|
|
8
|
+
- Updated dependencies
|
|
9
|
+
- @copilotkit/runtime-client-gql@1.1.1-feat-runtime-remote-actions.4
|
|
10
|
+
- @copilotkit/shared@1.1.1-feat-runtime-remote-actions.4
|
|
11
|
+
|
|
12
|
+
## 1.1.1-feat-runtime-remote-actions.3
|
|
13
|
+
|
|
14
|
+
### Patch Changes
|
|
15
|
+
|
|
16
|
+
- stream intermediate state
|
|
17
|
+
- Updated dependencies
|
|
18
|
+
- @copilotkit/runtime-client-gql@1.1.1-feat-runtime-remote-actions.3
|
|
19
|
+
- @copilotkit/shared@1.1.1-feat-runtime-remote-actions.3
|
|
20
|
+
|
|
3
21
|
## 1.1.1-feat-runtime-remote-actions.2
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CopilotContext
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-DB4VWZ5Q.mjs";
|
|
4
4
|
|
|
5
5
|
// src/hooks/use-copilot-action.ts
|
|
6
6
|
import { useRef, useContext, useEffect } from "react";
|
|
@@ -13,7 +13,7 @@ function useCopilotAction(action, dependencies) {
|
|
|
13
13
|
actions[idRef.current].handler = action.handler;
|
|
14
14
|
if (typeof action.render === "function") {
|
|
15
15
|
if (chatComponentsCache.current !== null) {
|
|
16
|
-
chatComponentsCache.current[action.name] = action.render;
|
|
16
|
+
chatComponentsCache.current.actions[action.name] = action.render;
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
19
|
}
|
|
@@ -21,7 +21,7 @@ function useCopilotAction(action, dependencies) {
|
|
|
21
21
|
useEffect(() => {
|
|
22
22
|
setAction(idRef.current, action);
|
|
23
23
|
if (chatComponentsCache.current !== null && action.render !== void 0) {
|
|
24
|
-
chatComponentsCache.current[action.name] = action.render;
|
|
24
|
+
chatComponentsCache.current.actions[action.name] = action.render;
|
|
25
25
|
}
|
|
26
26
|
return () => {
|
|
27
27
|
removeAction(idRef.current);
|
|
@@ -44,4 +44,4 @@ function useCopilotAction(action, dependencies) {
|
|
|
44
44
|
export {
|
|
45
45
|
useCopilotAction
|
|
46
46
|
};
|
|
47
|
-
//# sourceMappingURL=chunk-
|
|
47
|
+
//# sourceMappingURL=chunk-2MQX7BJL.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-copilot-action.ts"],"sourcesContent":["import { useRef, useContext, useEffect } from \"react\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CopilotContext } 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 } = useContext(CopilotContext);\n const idRef = useRef<string>(randomId());\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n actions[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.actions[action.name] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n 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 // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(action.parameters),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\n// Usage Example:\n// useCopilotAction({\n// name: \"myAction\",\n// parameters: [\n// { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n// { name: \"arg2\", type: \"number\" },\n// {\n// name: \"arg3\",\n// type: \"object\",\n// attributes: [\n// { name: \"nestedArg1\", type: \"boolean\" },\n// { name: \"xyz\", required: false },\n// ],\n// },\n// { name: \"arg4\", type: \"number[]\" },\n// ],\n// handler: ({ arg1, arg2, arg3, arg4 }) => {\n// const x = arg3.nestedArg1;\n// const z = arg3.xyz;\n// console.log(arg1, arg2, arg3);\n// },\n// });\n\n// useCopilotAction({\n// name: \"myAction\",\n// handler: () => {\n// console.log(\"No parameters provided.\");\n// },\n// });\n"],"mappings":";;;;;AAAA,SAAS,QAAQ,YAAY,iBAAiB;AAG9C,SAAoB,gBAAgB;AAW7B,SAAS,iBACd,QACA,cACM;AACN,QAAM,EAAE,WAAW,cAAc,SAAS,oBAAoB,IAAI,WAAW,cAAc;AAC3F,QAAM,QAAQ,OAAe,SAAS,CAAC;AAKvC,MAAI,iBAAiB,QAAW;AAC9B,QAAI,QAAQ,MAAM,OAAO,GAAG;AAC1B,cAAQ,MAAM,OAAO,EAAE,UAAU,OAAO;AACxC,UAAI,OAAO,OAAO,WAAW,YAAY;AACvC,YAAI,oBAAoB,YAAY,MAAM;AACxC,8BAAoB,QAAQ,QAAQ,OAAO,IAAI,IAAI,OAAO;AAAA,QAC5D;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,YAAU,MAAM;AACd,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;AAAA;AAAA,IAGP,KAAK,UAAU,OAAO,UAAU;AAAA;AAAA,IAEhC,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CopilotContext
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-DB4VWZ5Q.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-
|
|
28
|
+
//# sourceMappingURL=chunk-33ERMMNX.mjs.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CopilotContext
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-DB4VWZ5Q.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-
|
|
23
|
+
//# sourceMappingURL=chunk-3K7JAFGM.mjs.map
|
|
@@ -175,7 +175,8 @@ function useChat(options) {
|
|
|
175
175
|
if (message instanceof AgentStateMessage && // Check if the current message is an AgentStateMessage
|
|
176
176
|
acc.length > 0 && // Ensure there is at least one message in the accumulator
|
|
177
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
|
|
178
|
+
acc[acc.length - 1].agentName === message.agentName && // Check if the agentName is the same
|
|
179
|
+
acc[acc.length - 1].nodeName === message.nodeName) {
|
|
179
180
|
acc[acc.length - 1] = message;
|
|
180
181
|
} else {
|
|
181
182
|
acc.push(message);
|
|
@@ -238,4 +239,4 @@ function useChat(options) {
|
|
|
238
239
|
export {
|
|
239
240
|
useChat
|
|
240
241
|
};
|
|
241
|
-
//# sourceMappingURL=chunk-
|
|
242
|
+
//# sourceMappingURL=chunk-52M7642J.mjs.map
|
|
@@ -1 +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;AAAA,EACA;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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
|
+
{"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 (acc[acc.length - 1] as AgentStateMessage).nodeName === message.nodeName // Check if the nodeName 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;AAAA,EACA;AAAA,OACK;AAgFA,SAAS,QAAQ,SAAyC;AAC/D,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAE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AuB,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;AA/X3B;AAgYI,6BAAmB,YAAnB,mBAA4B;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["messages"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {
|
|
2
|
+
useCopilotContext
|
|
3
|
+
} from "./chunk-DB4VWZ5Q.mjs";
|
|
4
|
+
|
|
5
|
+
// src/hooks/use-copilot-chat-ui.ts
|
|
6
|
+
import { useEffect } from "react";
|
|
7
|
+
function useCopilotChatUI(chatUI, dependencies) {
|
|
8
|
+
const { chatUI: chatUIFromContext, setChatUI } = useCopilotContext();
|
|
9
|
+
useEffect(() => {
|
|
10
|
+
setChatUI([...chatUIFromContext, chatUI]);
|
|
11
|
+
return () => {
|
|
12
|
+
setChatUI(chatUIFromContext.filter((ui) => ui !== chatUI));
|
|
13
|
+
};
|
|
14
|
+
}, [chatUI.agentName, chatUI.nodeName, setChatUI]);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export {
|
|
18
|
+
useCopilotChatUI
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=chunk-6YOQY4WD.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-copilot-chat-ui.ts"],"sourcesContent":["import { randomId } from \"@copilotkit/shared\";\nimport { useCopilotContext } from \"../context\";\nimport { useEffect, useRef } from \"react\";\n\nexport interface UseCopilotChatUIRenderProps<S = any> {\n state: S;\n nodeName: string;\n agentName: string;\n}\n\nexport interface CopilotChatUI<S = any> {\n agentName: string;\n nodeName?: string;\n render: string | ((props: UseCopilotChatUIRenderProps<S>) => string | React.ReactElement);\n}\n\nexport function useCopilotChatUI<S = any>(chatUI: CopilotChatUI<S>, dependencies?: any[]) {\n const { chatUI: chatUIFromContext, setChatUI } = useCopilotContext();\n\n useEffect(() => {\n setChatUI([...chatUIFromContext, chatUI]);\n return () => {\n setChatUI(chatUIFromContext.filter((ui) => ui !== chatUI));\n };\n }, [chatUI.agentName, chatUI.nodeName, setChatUI]);\n}\n"],"mappings":";;;;;AAEA,SAAS,iBAAyB;AAc3B,SAAS,iBAA0B,QAA0B,cAAsB;AACxF,QAAM,EAAE,QAAQ,mBAAmB,UAAU,IAAI,kBAAkB;AAEnE,YAAU,MAAM;AACd,cAAU,CAAC,GAAG,mBAAmB,MAAM,CAAC;AACxC,WAAO,MAAM;AACX,gBAAU,kBAAkB,OAAO,CAAC,OAAO,OAAO,MAAM,CAAC;AAAA,IAC3D;AAAA,EACF,GAAG,CAAC,OAAO,WAAW,OAAO,UAAU,SAAS,CAAC;AACnD;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
defaultCopilotContextCategories
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-IF6P5ZXR.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-
|
|
118
|
+
//# sourceMappingURL=chunk-73KBO5JG.mjs.map
|
|
@@ -1,18 +1,19 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useCopilotChat
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-DZH3HSXW.mjs";
|
|
4
4
|
import {
|
|
5
5
|
useCopilotContext
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-DB4VWZ5Q.mjs";
|
|
7
7
|
import {
|
|
8
8
|
__spreadProps,
|
|
9
9
|
__spreadValues
|
|
10
10
|
} from "./chunk-SKC7AJIV.mjs";
|
|
11
11
|
|
|
12
12
|
// src/hooks/use-agent-state.ts
|
|
13
|
+
import { AgentStateMessage } from "@copilotkit/runtime-client-gql";
|
|
13
14
|
function useAgentState(agentName) {
|
|
14
15
|
const { agentStates, setAgentStates } = useCopilotContext();
|
|
15
|
-
const {
|
|
16
|
+
const { visibleMessages, setMessages } = useCopilotChat();
|
|
16
17
|
const setSpecificAgentState = (newState) => {
|
|
17
18
|
setAgentStates((prevAgentStates) => {
|
|
18
19
|
const currentState2 = prevAgentStates[agentName];
|
|
@@ -20,8 +21,16 @@ function useAgentState(agentName) {
|
|
|
20
21
|
throw new Error(`Agent state ${agentName} not found`);
|
|
21
22
|
}
|
|
22
23
|
const updatedState = typeof newState === "function" ? newState(currentState2) : newState;
|
|
23
|
-
const
|
|
24
|
-
|
|
24
|
+
const lastAgentStateMessage = [...visibleMessages].reverse().find((message) => message instanceof AgentStateMessage);
|
|
25
|
+
const agentStateMessage = new AgentStateMessage({
|
|
26
|
+
agentName,
|
|
27
|
+
nodeName: lastAgentStateMessage.nodeName,
|
|
28
|
+
state: updatedState,
|
|
29
|
+
running: lastAgentStateMessage.running,
|
|
30
|
+
threadId: lastAgentStateMessage.threadId,
|
|
31
|
+
role: lastAgentStateMessage.role
|
|
32
|
+
});
|
|
33
|
+
setMessages([...visibleMessages, agentStateMessage]);
|
|
25
34
|
return __spreadProps(__spreadValues({}, prevAgentStates), {
|
|
26
35
|
[agentName]: agentStateMessage
|
|
27
36
|
});
|
|
@@ -40,4 +49,4 @@ export {
|
|
|
40
49
|
useAgentState,
|
|
41
50
|
use_agent_state_default
|
|
42
51
|
};
|
|
43
|
-
//# sourceMappingURL=chunk-
|
|
52
|
+
//# sourceMappingURL=chunk-A47L32JN.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-agent-state.ts"],"sourcesContent":["import { AgentStateMessage } from \"@copilotkit/runtime-client-gql\";\nimport { 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 { visibleMessages, setMessages } = 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 lastAgentStateMessage = [...visibleMessages]\n .reverse()\n .find((message): message is AgentStateMessage => message instanceof AgentStateMessage)!;\n\n const agentStateMessage = new AgentStateMessage({\n agentName,\n nodeName: lastAgentStateMessage.nodeName,\n state: updatedState,\n running: lastAgentStateMessage.running,\n threadId: lastAgentStateMessage.threadId,\n role: lastAgentStateMessage.role,\n });\n\n setMessages([...visibleMessages, 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":";;;;;;;;;;;;AAAA,SAAS,yBAAyB;AAgB3B,SAAS,cAAuB,WAA+C;AACpF,QAAM,EAAE,aAAa,eAAe,IAAI,kBAAkB;AAE1D,QAAM,EAAE,iBAAiB,YAAY,IAAI,eAAe;AAExD,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,wBAAwB,CAAC,GAAG,eAAe,EAC9C,QAAQ,EACR,KAAK,CAAC,YAA0C,mBAAmB,iBAAiB;AAEvF,YAAM,oBAAoB,IAAI,kBAAkB;AAAA,QAC9C;AAAA,QACA,UAAU,sBAAsB;AAAA,QAChC,OAAO;AAAA,QACP,SAAS,sBAAsB;AAAA,QAC/B,UAAU,sBAAsB;AAAA,QAChC,MAAM,sBAAsB;AAAA,MAC9B,CAAC;AAED,kBAAY,CAAC,GAAG,iBAAiB,iBAAiB,CAAC;AAEnD,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"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=chunk-AIWDXM7L.mjs.map
|
|
@@ -10,7 +10,7 @@ var emptyCopilotContext = {
|
|
|
10
10
|
},
|
|
11
11
|
removeAction: () => {
|
|
12
12
|
},
|
|
13
|
-
chatComponentsCache: { current: {} },
|
|
13
|
+
chatComponentsCache: { current: { actions: {}, chatUI: {} } },
|
|
14
14
|
getContextString: (documents, categories) => returnAndThrowInDebug(""),
|
|
15
15
|
addContext: () => "",
|
|
16
16
|
removeContext: () => {
|
|
@@ -46,6 +46,9 @@ var emptyCopilotContext = {
|
|
|
46
46
|
showDevConsole: "auto",
|
|
47
47
|
agentStates: {},
|
|
48
48
|
setAgentStates: () => {
|
|
49
|
+
},
|
|
50
|
+
chatUI: [],
|
|
51
|
+
setChatUI: () => {
|
|
49
52
|
}
|
|
50
53
|
};
|
|
51
54
|
var CopilotContext = React.createContext(emptyCopilotContext);
|
|
@@ -61,4 +64,4 @@ export {
|
|
|
61
64
|
CopilotContext,
|
|
62
65
|
useCopilotContext
|
|
63
66
|
};
|
|
64
|
-
//# sourceMappingURL=chunk-
|
|
67
|
+
//# sourceMappingURL=chunk-DB4VWZ5Q.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\";\nimport { CopilotChatUI } from \"../hooks/use-copilot-chat-ui\";\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 ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n chatUI: Record<string, Function | string>;\n}\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n // chat\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean | \"auto\";\n\n // agent states\n agentStates: Record<string, AgentStateMessage | null>;\n setAgentStates: React.Dispatch<React.SetStateAction<Record<string, AgentStateMessage | null>>>;\n\n // chat ui\n chatUI: CopilotChatUI[];\n setChatUI: React.Dispatch<React.SetStateAction<CopilotChatUI[]>>;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n chatComponentsCache: { current: { actions: {}, chatUI: {} } },\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 chatUI: [],\n setChatUI: () => {},\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;AA6HlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,QAAQ,CAAC,EAAE,EAAE;AAAA,EAC5D,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;AAAA,EACvB,QAAQ,CAAC;AAAA,EACT,WAAW,MAAM;AAAA,EAAC;AACpB;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,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
defaultCopilotContextCategories
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import {
|
|
5
|
-
useChat
|
|
6
|
-
} from "./chunk-2Z3ZSFKF.mjs";
|
|
3
|
+
} from "./chunk-IF6P5ZXR.mjs";
|
|
7
4
|
import {
|
|
8
5
|
CopilotContext
|
|
9
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-DB4VWZ5Q.mjs";
|
|
7
|
+
import {
|
|
8
|
+
useChat
|
|
9
|
+
} from "./chunk-52M7642J.mjs";
|
|
10
10
|
import {
|
|
11
11
|
__objRest,
|
|
12
12
|
__spreadProps,
|
|
@@ -106,4 +106,4 @@ export {
|
|
|
106
106
|
useCopilotChat,
|
|
107
107
|
defaultSystemMessage
|
|
108
108
|
};
|
|
109
|
-
//# sourceMappingURL=chunk-
|
|
109
|
+
//# sourceMappingURL=chunk-DZH3HSXW.mjs.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
defaultCopilotContextCategories
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-IF6P5ZXR.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-
|
|
153
|
+
//# sourceMappingURL=chunk-H4XENJME.mjs.map
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-6U3UH3KO.mjs";
|
|
7
7
|
import {
|
|
8
8
|
CopilotContext
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-DB4VWZ5Q.mjs";
|
|
10
10
|
import {
|
|
11
11
|
__async,
|
|
12
12
|
__objRest,
|
|
@@ -32,7 +32,7 @@ function CopilotKit(_a) {
|
|
|
32
32
|
}
|
|
33
33
|
const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;
|
|
34
34
|
const [actions, setActions] = useState({});
|
|
35
|
-
const chatComponentsCache = useRef({});
|
|
35
|
+
const chatComponentsCache = useRef({ actions: {}, chatUI: {} });
|
|
36
36
|
const { addElement, removeElement, printTree } = use_tree_default();
|
|
37
37
|
const [messages, setMessages] = useState([]);
|
|
38
38
|
const [isLoading, setIsLoading] = useState(false);
|
|
@@ -147,6 +147,7 @@ ${nonDocumentStrings}`;
|
|
|
147
147
|
});
|
|
148
148
|
};
|
|
149
149
|
const [agentStates, setAgentStates] = useState({});
|
|
150
|
+
const [chatUI, setChatUI] = useState([]);
|
|
150
151
|
return /* @__PURE__ */ jsx(
|
|
151
152
|
CopilotContext.Provider,
|
|
152
153
|
{
|
|
@@ -174,7 +175,9 @@ ${nonDocumentStrings}`;
|
|
|
174
175
|
setChatInstructions,
|
|
175
176
|
showDevConsole: props.showDevConsole === void 0 ? "auto" : props.showDevConsole,
|
|
176
177
|
agentStates,
|
|
177
|
-
setAgentStates
|
|
178
|
+
setAgentStates,
|
|
179
|
+
chatUI,
|
|
180
|
+
setChatUI
|
|
178
181
|
},
|
|
179
182
|
children
|
|
180
183
|
}
|
|
@@ -210,4 +213,4 @@ export {
|
|
|
210
213
|
CopilotKit,
|
|
211
214
|
defaultCopilotContextCategories
|
|
212
215
|
};
|
|
213
|
-
//# sourceMappingURL=chunk-
|
|
216
|
+
//# sourceMappingURL=chunk-IF6P5ZXR.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 ChatComponentsCache,\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\";\nimport { CopilotChatUI } from \"../../hooks/use-copilot-chat-ui\";\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<ChatComponentsCache>({ actions: {}, chatUI: {} });\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 const [chatUI, setChatUI] = useState<CopilotChatUI[]>([]);\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 chatUI,\n setChatUI,\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 Prom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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,QACA;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"]}
|
|
@@ -94,7 +94,7 @@ var emptyCopilotContext = {
|
|
|
94
94
|
},
|
|
95
95
|
removeAction: () => {
|
|
96
96
|
},
|
|
97
|
-
chatComponentsCache: { current: {} },
|
|
97
|
+
chatComponentsCache: { current: { actions: {}, chatUI: {} } },
|
|
98
98
|
getContextString: (documents, categories) => returnAndThrowInDebug(""),
|
|
99
99
|
addContext: () => "",
|
|
100
100
|
removeContext: () => {
|
|
@@ -130,6 +130,9 @@ var emptyCopilotContext = {
|
|
|
130
130
|
showDevConsole: "auto",
|
|
131
131
|
agentStates: {},
|
|
132
132
|
setAgentStates: () => {
|
|
133
|
+
},
|
|
134
|
+
chatUI: [],
|
|
135
|
+
setChatUI: () => {
|
|
133
136
|
}
|
|
134
137
|
};
|
|
135
138
|
var CopilotContext = import_react.default.createContext(emptyCopilotContext);
|
|
@@ -351,7 +354,7 @@ function CopilotKit(_a) {
|
|
|
351
354
|
}
|
|
352
355
|
const chatApiEndpoint = props.runtimeUrl || import_shared3.COPILOT_CLOUD_CHAT_URL;
|
|
353
356
|
const [actions, setActions] = (0, import_react4.useState)({});
|
|
354
|
-
const chatComponentsCache = (0, import_react4.useRef)({});
|
|
357
|
+
const chatComponentsCache = (0, import_react4.useRef)({ actions: {}, chatUI: {} });
|
|
355
358
|
const { addElement, removeElement, printTree } = use_tree_default();
|
|
356
359
|
const [messages, setMessages] = (0, import_react4.useState)([]);
|
|
357
360
|
const [isLoading, setIsLoading] = (0, import_react4.useState)(false);
|
|
@@ -466,6 +469,7 @@ ${nonDocumentStrings}`;
|
|
|
466
469
|
});
|
|
467
470
|
};
|
|
468
471
|
const [agentStates, setAgentStates] = (0, import_react4.useState)({});
|
|
472
|
+
const [chatUI, setChatUI] = (0, import_react4.useState)([]);
|
|
469
473
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
470
474
|
CopilotContext.Provider,
|
|
471
475
|
{
|
|
@@ -493,7 +497,9 @@ ${nonDocumentStrings}`;
|
|
|
493
497
|
setChatInstructions,
|
|
494
498
|
showDevConsole: props.showDevConsole === void 0 ? "auto" : props.showDevConsole,
|
|
495
499
|
agentStates,
|
|
496
|
-
setAgentStates
|
|
500
|
+
setAgentStates,
|
|
501
|
+
chatUI,
|
|
502
|
+
setChatUI
|
|
497
503
|
},
|
|
498
504
|
children
|
|
499
505
|
}
|