@copilotkit/react-core 1.50.0-beta.9 → 1.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +180 -0
  2. package/dist/{chunk-YJGPIN3R.mjs → chunk-5J7RRLRO.mjs} +2 -2
  3. package/dist/{chunk-FYMZKPOL.mjs → chunk-CO6V4G7P.mjs} +15 -7
  4. package/dist/chunk-CO6V4G7P.mjs.map +1 -0
  5. package/dist/{chunk-B5ELMVT7.mjs → chunk-HQTDDA6V.mjs} +2 -2
  6. package/dist/{chunk-3775VM7Y.mjs → chunk-LDEWO5XH.mjs} +5 -411
  7. package/dist/chunk-LDEWO5XH.mjs.map +1 -0
  8. package/dist/{chunk-7SHWECGN.mjs → chunk-ZE4JVTEP.mjs} +2 -2
  9. package/dist/components/copilot-provider/copilotkit-props.d.ts +6 -0
  10. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  11. package/dist/components/copilot-provider/copilotkit.js +127 -1150
  12. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  13. package/dist/components/copilot-provider/copilotkit.mjs +3 -6
  14. package/dist/components/copilot-provider/index.js +127 -1150
  15. package/dist/components/copilot-provider/index.js.map +1 -1
  16. package/dist/components/copilot-provider/index.mjs +3 -6
  17. package/dist/components/dev-console/console-trigger.mjs +225 -5
  18. package/dist/components/dev-console/console-trigger.mjs.map +1 -1
  19. package/dist/components/index.js +127 -1150
  20. package/dist/components/index.js.map +1 -1
  21. package/dist/components/index.mjs +3 -6
  22. package/dist/hooks/index.js +3 -405
  23. package/dist/hooks/index.js.map +1 -1
  24. package/dist/hooks/index.mjs +28 -28
  25. package/dist/hooks/use-copilot-chat-headless_c.js +3 -405
  26. package/dist/hooks/use-copilot-chat-headless_c.js.map +1 -1
  27. package/dist/hooks/use-copilot-chat-headless_c.mjs +3 -3
  28. package/dist/hooks/use-copilot-chat.js +3 -405
  29. package/dist/hooks/use-copilot-chat.js.map +1 -1
  30. package/dist/hooks/use-copilot-chat.mjs +3 -3
  31. package/dist/hooks/use-copilot-chat_internal.js +3 -405
  32. package/dist/hooks/use-copilot-chat_internal.js.map +1 -1
  33. package/dist/hooks/use-copilot-chat_internal.mjs +2 -2
  34. package/dist/index.js +276 -1694
  35. package/dist/index.js.map +1 -1
  36. package/dist/index.mjs +34 -37
  37. package/dist/lib/copilot-task.js.map +1 -1
  38. package/dist/lib/copilot-task.mjs +4 -7
  39. package/dist/lib/index.js.map +1 -1
  40. package/dist/lib/index.mjs +4 -7
  41. package/dist/utils/index.mjs +3 -3
  42. package/package.json +6 -6
  43. package/src/components/copilot-provider/copilotkit-props.tsx +7 -0
  44. package/src/components/copilot-provider/copilotkit.tsx +13 -5
  45. package/dist/chunk-3775VM7Y.mjs.map +0 -1
  46. package/dist/chunk-FYMZKPOL.mjs.map +0 -1
  47. package/dist/chunk-PMWUKW3Z.mjs +0 -231
  48. package/dist/chunk-PMWUKW3Z.mjs.map +0 -1
  49. /package/dist/{chunk-YJGPIN3R.mjs.map → chunk-5J7RRLRO.mjs.map} +0 -0
  50. /package/dist/{chunk-B5ELMVT7.mjs.map → chunk-HQTDDA6V.mjs.map} +0 -0
  51. /package/dist/{chunk-7SHWECGN.mjs.map → chunk-ZE4JVTEP.mjs.map} +0 -0
package/dist/index.mjs CHANGED
@@ -5,36 +5,55 @@ import "./chunk-6YOKPWQ7.mjs";
5
5
  import "./chunk-LUGEI4YQ.mjs";
6
6
  import {
7
7
  CopilotTask
8
- } from "./chunk-B5ELMVT7.mjs";
8
+ } from "./chunk-HQTDDA6V.mjs";
9
9
  import "./chunk-4CEQJ2X6.mjs";
10
10
  import "./chunk-A6NKSGH3.mjs";
11
+ import {
12
+ useDefaultTool
13
+ } from "./chunk-U2ZRVVKT.mjs";
11
14
  import {
12
15
  useLangGraphInterrupt
13
16
  } from "./chunk-4RRMC7L2.mjs";
14
17
  import {
15
18
  useMakeCopilotDocumentReadable
16
19
  } from "./chunk-7IBF6RBW.mjs";
20
+ import {
21
+ useCopilotAdditionalInstructions
22
+ } from "./chunk-ABWT4DRT.mjs";
23
+ import {
24
+ useCopilotAuthenticatedAction_c
25
+ } from "./chunk-4HRUQH6U.mjs";
26
+ import {
27
+ useCopilotChatHeadless_c
28
+ } from "./chunk-5J7RRLRO.mjs";
29
+ import {
30
+ useCopilotChatSuggestions
31
+ } from "./chunk-XDFVCQD3.mjs";
32
+ import {
33
+ useCopilotChat
34
+ } from "./chunk-ZE4JVTEP.mjs";
35
+ import {
36
+ useCopilotChatInternal
37
+ } from "./chunk-LDEWO5XH.mjs";
38
+ import {
39
+ useLangGraphInterruptRender
40
+ } from "./chunk-VV56AVPB.mjs";
41
+ import {
42
+ useLazyToolRenderer
43
+ } from "./chunk-ZVF5Q6IH.mjs";
17
44
  import {
18
45
  useCopilotReadable
19
46
  } from "./chunk-Z6JV2LRY.mjs";
20
47
  import {
21
48
  useCopilotRuntimeClient
22
49
  } from "./chunk-6ESSSQ7Q.mjs";
23
- import {
24
- useDefaultTool
25
- } from "./chunk-U2ZRVVKT.mjs";
26
50
  import {
27
51
  useCoAgentStateRender
28
52
  } from "./chunk-YTQHRJUA.mjs";
29
53
  import {
30
54
  useCoAgent
31
55
  } from "./chunk-ZYTXB6HH.mjs";
32
- import {
33
- useCopilotAdditionalInstructions
34
- } from "./chunk-ABWT4DRT.mjs";
35
- import {
36
- useCopilotAuthenticatedAction_c
37
- } from "./chunk-4HRUQH6U.mjs";
56
+ import "./chunk-I76HKHPJ.mjs";
38
57
  import {
39
58
  useCopilotAction
40
59
  } from "./chunk-EG56H77V.mjs";
@@ -47,46 +66,24 @@ import {
47
66
  import {
48
67
  useHumanInTheLoop
49
68
  } from "./chunk-7DTB7S5V.mjs";
50
- import {
51
- useCopilotChatHeadless_c
52
- } from "./chunk-YJGPIN3R.mjs";
53
- import {
54
- useCopilotChatSuggestions
55
- } from "./chunk-XDFVCQD3.mjs";
56
- import {
57
- useCopilotChat
58
- } from "./chunk-7SHWECGN.mjs";
59
- import {
60
- useCopilotChatInternal
61
- } from "./chunk-3775VM7Y.mjs";
62
- import {
63
- useLazyToolRenderer
64
- } from "./chunk-ZVF5Q6IH.mjs";
65
- import {
66
- useLangGraphInterruptRender
67
- } from "./chunk-VV56AVPB.mjs";
68
- import "./chunk-I76HKHPJ.mjs";
69
69
  import "./chunk-JD7BAH7U.mjs";
70
70
  import "./chunk-SPCZTZCY.mjs";
71
71
  import {
72
72
  CopilotKit,
73
73
  defaultCopilotContextCategories
74
- } from "./chunk-FYMZKPOL.mjs";
74
+ } from "./chunk-CO6V4G7P.mjs";
75
75
  import "./chunk-LHERIF3L.mjs";
76
76
  import "./chunk-HE22TZMF.mjs";
77
- import "./chunk-PMWUKW3Z.mjs";
78
- import "./chunk-YCG6SNAU.mjs";
79
- import "./chunk-PIF5KJYI.mjs";
80
77
  import "./chunk-RKTVJRK7.mjs";
78
+ import "./chunk-PMAFHQ7P.mjs";
81
79
  import "./chunk-CYDWEPFL.mjs";
82
- import {
83
- shouldShowDevConsole
84
- } from "./chunk-ICIK2BSB.mjs";
85
80
  import {
86
81
  SUGGESTION_RETRY_CONFIG
87
82
  } from "./chunk-2IDV5OHF.mjs";
83
+ import {
84
+ shouldShowDevConsole
85
+ } from "./chunk-ICIK2BSB.mjs";
88
86
  import "./chunk-YYN33GSG.mjs";
89
- import "./chunk-PMAFHQ7P.mjs";
90
87
  import "./chunk-6PUNP7CD.mjs";
91
88
  import "./chunk-O7ARI5CV.mjs";
92
89
  import "./chunk-QNUAXSDP.mjs";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/lib/copilot-task.ts","../../src/types/frontend-action.ts","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n * }\n * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { FrontendAction, processActionsForRuntimeRequest } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: ForwardedParametersInput;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n private forwardedParameters?: ForwardedParametersInput;\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions = config.includeCopilotActions !== false;\n this.forwardedParameters = config.forwardedParameters;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(Object.values(actions)),\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n // if forwardedParameters is provided, use it\n toolChoice: \"required\",\n ...(this.forwardedParameters ?? {}),\n },\n },\n properties: context.copilotApiConfig.properties,\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m.isActionExecutionMessage());\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\n }\n }\n}\n\nfunction taskSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n","import { ActionInputAvailability } from \"@copilotkit/runtime-client-gql\";\nimport {\n Action,\n Parameter,\n MappedParameterTypes,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport React from \"react\";\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingState<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: any;\n}\n\ninterface InProgressStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n}\n\nexport type ActionRenderProps<T extends Parameter[] | [] = []> =\n | CompleteState<T>\n | ExecutingState<T>\n | InProgressState<T>;\n\nexport type ActionRenderPropsNoArgs<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgs<T>\n | ExecutingStateNoArgs<T>\n | InProgressStateNoArgs<T>;\n\nexport type ActionRenderPropsWait<T extends Parameter[] | [] = []> =\n | CompleteStateWait<T>\n | ExecutingStateWait<T>\n | InProgressStateWait<T>;\n\nexport type ActionRenderPropsNoArgsWait<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgsWait<T>\n | ExecutingStateNoArgsWait<T>\n | InProgressStateNoArgsWait<T>;\n\nexport type CatchAllActionRenderProps<T extends Parameter[] | [] = []> =\n | (CompleteState<T> & {\n name: string;\n })\n | (ExecutingState<T> & {\n name: string;\n })\n | (InProgressState<T> & {\n name: string;\n });\n\nexport type FrontendActionAvailability = \"disabled\" | \"enabled\" | \"remote\" | \"frontend\";\n\nexport type FrontendAction<\n T extends Parameter[] | [] = [],\n N extends string = string,\n> = Action<T> & {\n name: Exclude<N, \"*\">;\n /**\n * @deprecated Use `available` instead.\n */\n disabled?: boolean;\n available?: FrontendActionAvailability;\n pairedAction?: string;\n followUp?: boolean;\n} & (\n | {\n render?:\n | string\n | (T extends []\n ? (props: ActionRenderPropsNoArgs<T>) => string | React.ReactElement\n : (props: ActionRenderProps<T>) => string | React.ReactElement);\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: never;\n renderAndWaitForResponse?: never;\n }\n | {\n render?: never;\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n renderAndWaitForResponse?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n handler?: never;\n }\n );\n\nexport type CatchAllFrontendAction = {\n name: \"*\";\n render: (props: CatchAllActionRenderProps<any>) => React.ReactElement;\n};\n\nexport type RenderFunctionStatus = ActionRenderProps<any>[\"status\"];\n\nexport function processActionsForRuntimeRequest(actions: FrontendAction<any>[]) {\n const filteredActions = actions\n .filter(\n (action) =>\n action.available !== ActionInputAvailability.Disabled &&\n action.disabled !== true &&\n action.name !== \"*\" &&\n action.available != \"frontend\" &&\n !action.pairedAction,\n )\n .map((action) => {\n let available: ActionInputAvailability | undefined = ActionInputAvailability.Enabled;\n if (action.disabled) {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"disabled\") {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"remote\") {\n available = ActionInputAvailability.Remote;\n }\n return {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n available,\n };\n });\n return filteredActions;\n}\n","/**\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 * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState, SetStateAction } from \"react\";\nimport { CopilotChatConfigurationProvider, CopilotKitProvider } from \"@copilotkitnext/react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n AuthState,\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 COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n randomUUID,\n ConfigurationError,\n MissingPublicApiKeyError,\n CopilotKitError,\n CopilotErrorEvent,\n CopilotErrorHandler,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages, MessagesTapProvider } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { getErrorActions, UsageBanner } from \"../usage-banner\";\nimport { shouldShowDevConsole } from \"../../utils\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\nimport { Agent, ExtensionsInput } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptRender,\n LangGraphInterruptActionSetterArgs,\n QueuedInterruptEvent,\n} from \"../../types/interrupt-action\";\nimport { ConsoleTrigger } from \"../dev-console/console-trigger\";\nimport { CoAgentStateRendersProvider } from \"../../context/coagent-state-renders-context\";\nimport { CoAgentStateRenderBridge } from \"../../hooks/use-coagent-state-render-bridge\";\nimport { ThreadsProvider, useThreads } from \"../../context/threads-context\";\nimport { CopilotListeners } from \"../CopilotListeners\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const enabled = shouldShowDevConsole(props.showDevConsole);\n\n // Use API key if provided, otherwise use the license key\n const publicApiKey = props.publicApiKey || props.publicLicenseKey;\n\n const renderArr = useMemo(() => [{ render: CoAgentStateRenderBridge }], []);\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary publicApiKey={publicApiKey} showUsageBanner={enabled}>\n <ThreadsProvider threadId={props.threadId}>\n <CopilotKitProvider {...props} renderCustomMessages={renderArr} useSingleEndpoint={true}>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotKitProvider>\n </ThreadsProvider>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal(cpkProps: CopilotKitProps) {\n const { children, ...props } = cpkProps;\n\n /**\n * This will throw an error if the props are invalid.\n */\n validateProps(cpkProps);\n\n // Use license key as API key if provided, otherwise use the API key\n const publicApiKey = props.publicLicenseKey || props.publicApiKey;\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n\n // State for registered actions from useCopilotAction\n const [registeredActionConfigs, setRegisteredActionConfigs] = useState<\n Map<string, { type: string; action: any; component: any }>\n >(new Map());\n\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n\n const { addElement, removeElement, printTree, getAllElements } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});\n const [extensions, setExtensions] = useState<ExtensionsInput>({});\n const [additionalInstructions, setAdditionalInstructions] = useState<string[]>([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n // Compute all the functions and properties that we need to pass\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 getAllContext = useCallback(() => {\n return getAllElements();\n }, [getAllElements]);\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 // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: 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 publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n props.guardrails_c,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const [internalErrorHandlers, _setInternalErrorHandler] = useState<\n Record<string, CopilotErrorHandler>\n >({});\n const setInternalErrorHandler = useCallback((handler: Record<string, CopilotErrorHandler>) => {\n _setInternalErrorHandler((prev: Record<string, CopilotErrorHandler>) => ({\n ...prev,\n ...handler,\n }));\n }, []);\n const removeInternalErrorHandler = useCallback((key: string) => {\n _setInternalErrorHandler((prev) => {\n const { [key]: _removed, ...rest } = prev;\n return rest;\n });\n }, []);\n\n // Keep latest values in refs\n const onErrorRef = useRef<CopilotErrorHandler | undefined>(props.onError);\n useEffect(() => {\n onErrorRef.current = props.onError;\n }, [props.onError]);\n\n const internalHandlersRef = useRef<Record<string, CopilotErrorHandler>>({});\n useEffect(() => {\n internalHandlersRef.current = internalErrorHandlers;\n }, [internalErrorHandlers]);\n\n const handleErrors = useCallback(\n async (error: CopilotErrorEvent) => {\n if (copilotApiConfig.publicApiKey && onErrorRef.current) {\n try {\n await onErrorRef.current(error);\n } catch (e) {\n console.error(\"Error in public onError handler:\", e);\n }\n }\n const handlers = Object.values(internalHandlersRef.current);\n await Promise.all(\n handlers.map((h) =>\n Promise.resolve(h(error)).catch((e) =>\n console.error(\"Error in internal error handler:\", e),\n ),\n ),\n );\n },\n [copilotApiConfig.publicApiKey],\n );\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = useCallback(\n (id: string, suggestion: CopilotChatSuggestionConfiguration) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n },\n [setChatSuggestionConfiguration],\n );\n\n const removeChatSuggestionConfiguration = useCallback(\n (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n },\n [setChatSuggestionConfiguration],\n );\n\n const [availableAgents, setAvailableAgents] = useState<Agent[]>([]);\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => {\n const newValue = typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n\n // Update agentSession when props.agent changes\n useEffect(() => {\n if (props.agent) {\n setAgentSession({\n agentName: props.agent,\n });\n } else {\n setAgentSession(null);\n }\n }, [props.agent]);\n\n const { threadId, setThreadId: setInternalThreadId } = useThreads();\n\n const setThreadId = useCallback(\n (value: SetStateAction<string>) => {\n if (props.threadId) {\n throw new Error(\"Cannot call setThreadId() when threadId is provided via props.\");\n }\n setInternalThreadId(value);\n },\n [props.threadId],\n );\n\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = shouldShowDevConsole(props.showDevConsole);\n\n const [interruptActions, _setInterruptActions] = useState<\n Record<string, LangGraphInterruptRender>\n >({});\n const setInterruptAction = useCallback((action: LangGraphInterruptActionSetterArgs) => {\n _setInterruptActions((prev) => {\n if (action == null || !action.id) {\n // Cannot set action without id\n return prev;\n }\n return {\n ...prev,\n [action.id]: { ...(prev[action.id] ?? {}), ...action } as LangGraphInterruptRender,\n };\n });\n }, []);\n const removeInterruptAction = useCallback((actionId: string): void => {\n _setInterruptActions((prev) => {\n const { [actionId]: _, ...rest } = prev;\n return rest;\n });\n }, []);\n\n const [interruptEventQueue, setInterruptEventQueue] = useState<\n Record<string, QueuedInterruptEvent[]>\n >({});\n\n const addInterruptEvent = useCallback((queuedEvent: QueuedInterruptEvent) => {\n setInterruptEventQueue((prev) => {\n const threadQueue = prev[queuedEvent.threadId] || [];\n return {\n ...prev,\n [queuedEvent.threadId]: [...threadQueue, queuedEvent],\n };\n });\n }, []);\n\n const resolveInterruptEvent = useCallback(\n (threadId: string, eventId: string, response: string) => {\n setInterruptEventQueue((prev) => {\n const threadQueue = prev[threadId] || [];\n return {\n ...prev,\n [threadId]: threadQueue.map((queuedEvent) =>\n queuedEvent.eventId === eventId\n ? { ...queuedEvent, event: { ...queuedEvent.event, response } }\n : queuedEvent,\n ),\n };\n });\n },\n [],\n );\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [bannerError, setBannerError] = useState<CopilotKitError | null>(null);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved = typeof newExtensions === \"function\" ? newExtensions(prev) : newExtensions;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setExtensions],\n );\n\n const updateAuthStates = useCallback(\n (newAuthStates: SetStateAction<Record<string, AuthState>>) => {\n setAuthStates((prev) => {\n const resolved = typeof newAuthStates === \"function\" ? newAuthStates(prev) : newAuthStates;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setAuthStates],\n );\n\n const handleSetRegisteredActions = useCallback((actionConfig: any): string => {\n const key = actionConfig.action.name || randomUUID();\n setRegisteredActionConfigs((prev) => {\n const newMap = new Map(prev);\n newMap.set(key, actionConfig);\n return newMap;\n });\n return key;\n }, []);\n\n const handleRemoveRegisteredAction = useCallback((actionKey: string) => {\n setRegisteredActionConfigs((prev) => {\n const newMap = new Map(prev);\n newMap.delete(actionKey);\n return newMap;\n });\n }, []);\n\n // Component to render all registered actions\n const RegisteredActionsRenderer = useMemo(() => {\n return () => (\n <>\n {Array.from(registeredActionConfigs.entries()).map(([key, config]) => {\n const Component = config.component;\n return <Component key={key} action={config.action} />;\n })}\n </>\n );\n }, [registeredActionConfigs]);\n\n return (\n <CopilotChatConfigurationProvider\n // labels={labels}\n // isModalDefaultOpen={isModalDefaultOpen}\n agentId={props.agent ?? \"default\"}\n threadId={threadId}\n >\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n setRegisteredActions: handleSetRegisteredActions,\n removeRegisteredAction: handleRemoveRegisteredAction,\n getContextString,\n addContext,\n removeContext,\n getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n additionalInstructions,\n setAdditionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n availableAgents,\n authConfig_c: props.authConfig_c,\n authStates_c: authStates,\n setAuthStates_c: updateAuthStates,\n extensions,\n setExtensions: updateExtensions,\n interruptActions,\n setInterruptAction,\n removeInterruptAction,\n interruptEventQueue,\n addInterruptEvent,\n resolveInterruptEvent,\n bannerError,\n setBannerError,\n onError: handleErrors,\n internalErrorHandlers,\n setInternalErrorHandler,\n removeInternalErrorHandler,\n }}\n >\n <CopilotListeners />\n <CoAgentStateRendersProvider>\n <MessagesTapProvider>\n <CopilotMessages>\n {memoizedChildren}\n {showDevConsole && <ConsoleTrigger />}\n <RegisteredActionsRenderer />\n </CopilotMessages>\n </MessagesTapProvider>\n {bannerError && showDevConsole && (\n <UsageBanner\n severity={bannerError.severity}\n message={bannerError.message}\n onClose={() => setBannerError(null)}\n actions={getErrorActions(bannerError)}\n />\n )}\n </CoAgentStateRendersProvider>\n </CopilotContext.Provider>\n </CopilotChatConfigurationProvider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ name, args }: { name: string; args: Record<string, any> }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n\nfunction formatFeatureName(featureName: string): string {\n return featureName\n .replace(/_c$/, \"\")\n .split(\"_\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\" \");\n}\n\nfunction validateProps(props: CopilotKitProps): never | void {\n const cloudFeatures = Object.keys(props).filter((key) => key.endsWith(\"_c\"));\n\n // Check if we have either a runtimeUrl or one of the API keys\n const hasApiKey = props.publicApiKey || props.publicLicenseKey;\n\n if (!props.runtimeUrl && !hasApiKey) {\n throw new ConfigurationError(\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\",\n );\n }\n\n if (cloudFeatures.length > 0 && !hasApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n"],"mappings":"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","names":["import_runtime_client_gql","import_react","import_shared"]}
1
+ {"version":3,"sources":["../../src/lib/copilot-task.ts","../../src/types/frontend-action.ts","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n * }\n * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { FrontendAction, processActionsForRuntimeRequest } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: ForwardedParametersInput;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n private forwardedParameters?: ForwardedParametersInput;\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions = config.includeCopilotActions !== false;\n this.forwardedParameters = config.forwardedParameters;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(Object.values(actions)),\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n // if forwardedParameters is provided, use it\n toolChoice: \"required\",\n ...(this.forwardedParameters ?? {}),\n },\n },\n properties: context.copilotApiConfig.properties,\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m.isActionExecutionMessage());\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\n }\n }\n}\n\nfunction taskSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n","import { ActionInputAvailability } from \"@copilotkit/runtime-client-gql\";\nimport {\n Action,\n Parameter,\n MappedParameterTypes,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport React from \"react\";\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingState<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: any;\n}\n\ninterface InProgressStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n}\n\nexport type ActionRenderProps<T extends Parameter[] | [] = []> =\n | CompleteState<T>\n | ExecutingState<T>\n | InProgressState<T>;\n\nexport type ActionRenderPropsNoArgs<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgs<T>\n | ExecutingStateNoArgs<T>\n | InProgressStateNoArgs<T>;\n\nexport type ActionRenderPropsWait<T extends Parameter[] | [] = []> =\n | CompleteStateWait<T>\n | ExecutingStateWait<T>\n | InProgressStateWait<T>;\n\nexport type ActionRenderPropsNoArgsWait<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgsWait<T>\n | ExecutingStateNoArgsWait<T>\n | InProgressStateNoArgsWait<T>;\n\nexport type CatchAllActionRenderProps<T extends Parameter[] | [] = []> =\n | (CompleteState<T> & {\n name: string;\n })\n | (ExecutingState<T> & {\n name: string;\n })\n | (InProgressState<T> & {\n name: string;\n });\n\nexport type FrontendActionAvailability = \"disabled\" | \"enabled\" | \"remote\" | \"frontend\";\n\nexport type FrontendAction<\n T extends Parameter[] | [] = [],\n N extends string = string,\n> = Action<T> & {\n name: Exclude<N, \"*\">;\n /**\n * @deprecated Use `available` instead.\n */\n disabled?: boolean;\n available?: FrontendActionAvailability;\n pairedAction?: string;\n followUp?: boolean;\n} & (\n | {\n render?:\n | string\n | (T extends []\n ? (props: ActionRenderPropsNoArgs<T>) => string | React.ReactElement\n : (props: ActionRenderProps<T>) => string | React.ReactElement);\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: never;\n renderAndWaitForResponse?: never;\n }\n | {\n render?: never;\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n renderAndWaitForResponse?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n handler?: never;\n }\n );\n\nexport type CatchAllFrontendAction = {\n name: \"*\";\n render: (props: CatchAllActionRenderProps<any>) => React.ReactElement;\n};\n\nexport type RenderFunctionStatus = ActionRenderProps<any>[\"status\"];\n\nexport function processActionsForRuntimeRequest(actions: FrontendAction<any>[]) {\n const filteredActions = actions\n .filter(\n (action) =>\n action.available !== ActionInputAvailability.Disabled &&\n action.disabled !== true &&\n action.name !== \"*\" &&\n action.available != \"frontend\" &&\n !action.pairedAction,\n )\n .map((action) => {\n let available: ActionInputAvailability | undefined = ActionInputAvailability.Enabled;\n if (action.disabled) {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"disabled\") {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"remote\") {\n available = ActionInputAvailability.Remote;\n }\n return {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n available,\n };\n });\n return filteredActions;\n}\n","/**\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 * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState, SetStateAction } from \"react\";\nimport {\n CopilotChatConfigurationProvider,\n CopilotKitInspector,\n CopilotKitProvider as CopilotKitNextProvider,\n} from \"@copilotkitnext/react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n AuthState,\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 COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n randomUUID,\n ConfigurationError,\n MissingPublicApiKeyError,\n CopilotKitError,\n CopilotErrorEvent,\n CopilotErrorHandler,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages, MessagesTapProvider } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { getErrorActions, UsageBanner } from \"../usage-banner\";\nimport { shouldShowDevConsole } from \"../../utils\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\nimport { Agent, ExtensionsInput } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptRender,\n LangGraphInterruptActionSetterArgs,\n QueuedInterruptEvent,\n} from \"../../types/interrupt-action\";\nimport { CoAgentStateRendersProvider } from \"../../context/coagent-state-renders-context\";\nimport { CoAgentStateRenderBridge } from \"../../hooks/use-coagent-state-render-bridge\";\nimport { ThreadsProvider, useThreads } from \"../../context/threads-context\";\nimport { CopilotListeners } from \"../CopilotListeners\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const enabled = shouldShowDevConsole(props.showDevConsole);\n const showInspector = shouldShowDevConsole(props.enableInspector);\n\n // Use API key if provided, otherwise use the license key\n const publicApiKey = props.publicApiKey || props.publicLicenseKey;\n\n const renderArr = useMemo(() => [{ render: CoAgentStateRenderBridge }], []);\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary publicApiKey={publicApiKey} showUsageBanner={enabled}>\n <ThreadsProvider threadId={props.threadId}>\n <CopilotKitNextProvider\n {...props}\n showDevConsole={showInspector}\n renderCustomMessages={renderArr}\n useSingleEndpoint={true}\n >\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotKitNextProvider>\n </ThreadsProvider>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal(cpkProps: CopilotKitProps) {\n const { children, ...props } = cpkProps;\n\n /**\n * This will throw an error if the props are invalid.\n */\n validateProps(cpkProps);\n\n // Use license key as API key if provided, otherwise use the API key\n const publicApiKey = props.publicLicenseKey || props.publicApiKey;\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n\n // State for registered actions from useCopilotAction\n const [registeredActionConfigs, setRegisteredActionConfigs] = useState<\n Map<string, { type: string; action: any; component: any }>\n >(new Map());\n\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n\n const { addElement, removeElement, printTree, getAllElements } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});\n const [extensions, setExtensions] = useState<ExtensionsInput>({});\n const [additionalInstructions, setAdditionalInstructions] = useState<string[]>([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n // Compute all the functions and properties that we need to pass\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 getAllContext = useCallback(() => {\n return getAllElements();\n }, [getAllElements]);\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 // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: 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 publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n props.guardrails_c,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const [internalErrorHandlers, _setInternalErrorHandler] = useState<\n Record<string, CopilotErrorHandler>\n >({});\n const setInternalErrorHandler = useCallback((handler: Record<string, CopilotErrorHandler>) => {\n _setInternalErrorHandler((prev: Record<string, CopilotErrorHandler>) => ({\n ...prev,\n ...handler,\n }));\n }, []);\n const removeInternalErrorHandler = useCallback((key: string) => {\n _setInternalErrorHandler((prev) => {\n const { [key]: _removed, ...rest } = prev;\n return rest;\n });\n }, []);\n\n // Keep latest values in refs\n const onErrorRef = useRef<CopilotErrorHandler | undefined>(props.onError);\n useEffect(() => {\n onErrorRef.current = props.onError;\n }, [props.onError]);\n\n const internalHandlersRef = useRef<Record<string, CopilotErrorHandler>>({});\n useEffect(() => {\n internalHandlersRef.current = internalErrorHandlers;\n }, [internalErrorHandlers]);\n\n const handleErrors = useCallback(\n async (error: CopilotErrorEvent) => {\n if (copilotApiConfig.publicApiKey && onErrorRef.current) {\n try {\n await onErrorRef.current(error);\n } catch (e) {\n console.error(\"Error in public onError handler:\", e);\n }\n }\n const handlers = Object.values(internalHandlersRef.current);\n await Promise.all(\n handlers.map((h) =>\n Promise.resolve(h(error)).catch((e) =>\n console.error(\"Error in internal error handler:\", e),\n ),\n ),\n );\n },\n [copilotApiConfig.publicApiKey],\n );\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = useCallback(\n (id: string, suggestion: CopilotChatSuggestionConfiguration) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n },\n [setChatSuggestionConfiguration],\n );\n\n const removeChatSuggestionConfiguration = useCallback(\n (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n },\n [setChatSuggestionConfiguration],\n );\n\n const [availableAgents, setAvailableAgents] = useState<Agent[]>([]);\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => {\n const newValue = typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n\n // Update agentSession when props.agent changes\n useEffect(() => {\n if (props.agent) {\n setAgentSession({\n agentName: props.agent,\n });\n } else {\n setAgentSession(null);\n }\n }, [props.agent]);\n\n const { threadId, setThreadId: setInternalThreadId } = useThreads();\n\n const setThreadId = useCallback(\n (value: SetStateAction<string>) => {\n if (props.threadId) {\n throw new Error(\"Cannot call setThreadId() when threadId is provided via props.\");\n }\n setInternalThreadId(value);\n },\n [props.threadId],\n );\n\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = shouldShowDevConsole(props.showDevConsole);\n\n const [interruptActions, _setInterruptActions] = useState<\n Record<string, LangGraphInterruptRender>\n >({});\n const setInterruptAction = useCallback((action: LangGraphInterruptActionSetterArgs) => {\n _setInterruptActions((prev) => {\n if (action == null || !action.id) {\n // Cannot set action without id\n return prev;\n }\n return {\n ...prev,\n [action.id]: { ...(prev[action.id] ?? {}), ...action } as LangGraphInterruptRender,\n };\n });\n }, []);\n const removeInterruptAction = useCallback((actionId: string): void => {\n _setInterruptActions((prev) => {\n const { [actionId]: _, ...rest } = prev;\n return rest;\n });\n }, []);\n\n const [interruptEventQueue, setInterruptEventQueue] = useState<\n Record<string, QueuedInterruptEvent[]>\n >({});\n\n const addInterruptEvent = useCallback((queuedEvent: QueuedInterruptEvent) => {\n setInterruptEventQueue((prev) => {\n const threadQueue = prev[queuedEvent.threadId] || [];\n return {\n ...prev,\n [queuedEvent.threadId]: [...threadQueue, queuedEvent],\n };\n });\n }, []);\n\n const resolveInterruptEvent = useCallback(\n (threadId: string, eventId: string, response: string) => {\n setInterruptEventQueue((prev) => {\n const threadQueue = prev[threadId] || [];\n return {\n ...prev,\n [threadId]: threadQueue.map((queuedEvent) =>\n queuedEvent.eventId === eventId\n ? { ...queuedEvent, event: { ...queuedEvent.event, response } }\n : queuedEvent,\n ),\n };\n });\n },\n [],\n );\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [bannerError, setBannerError] = useState<CopilotKitError | null>(null);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved = typeof newExtensions === \"function\" ? newExtensions(prev) : newExtensions;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setExtensions],\n );\n\n const updateAuthStates = useCallback(\n (newAuthStates: SetStateAction<Record<string, AuthState>>) => {\n setAuthStates((prev) => {\n const resolved = typeof newAuthStates === \"function\" ? newAuthStates(prev) : newAuthStates;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setAuthStates],\n );\n\n const handleSetRegisteredActions = useCallback((actionConfig: any): string => {\n const key = actionConfig.action.name || randomUUID();\n setRegisteredActionConfigs((prev) => {\n const newMap = new Map(prev);\n newMap.set(key, actionConfig);\n return newMap;\n });\n return key;\n }, []);\n\n const handleRemoveRegisteredAction = useCallback((actionKey: string) => {\n setRegisteredActionConfigs((prev) => {\n const newMap = new Map(prev);\n newMap.delete(actionKey);\n return newMap;\n });\n }, []);\n\n // Component to render all registered actions\n const RegisteredActionsRenderer = useMemo(() => {\n return () => (\n <>\n {Array.from(registeredActionConfigs.entries()).map(([key, config]) => {\n const Component = config.component;\n return <Component key={key} action={config.action} />;\n })}\n </>\n );\n }, [registeredActionConfigs]);\n\n return (\n <CopilotChatConfigurationProvider\n // labels={labels}\n // isModalDefaultOpen={isModalDefaultOpen}\n agentId={props.agent ?? \"default\"}\n threadId={threadId}\n >\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n setRegisteredActions: handleSetRegisteredActions,\n removeRegisteredAction: handleRemoveRegisteredAction,\n getContextString,\n addContext,\n removeContext,\n getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n additionalInstructions,\n setAdditionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n availableAgents,\n authConfig_c: props.authConfig_c,\n authStates_c: authStates,\n setAuthStates_c: updateAuthStates,\n extensions,\n setExtensions: updateExtensions,\n interruptActions,\n setInterruptAction,\n removeInterruptAction,\n interruptEventQueue,\n addInterruptEvent,\n resolveInterruptEvent,\n bannerError,\n setBannerError,\n onError: handleErrors,\n internalErrorHandlers,\n setInternalErrorHandler,\n removeInternalErrorHandler,\n }}\n >\n <CopilotListeners />\n <CoAgentStateRendersProvider>\n <MessagesTapProvider>\n <CopilotMessages>\n {memoizedChildren}\n <RegisteredActionsRenderer />\n </CopilotMessages>\n </MessagesTapProvider>\n {bannerError && showDevConsole && (\n <UsageBanner\n severity={bannerError.severity}\n message={bannerError.message}\n onClose={() => setBannerError(null)}\n actions={getErrorActions(bannerError)}\n />\n )}\n </CoAgentStateRendersProvider>\n </CopilotContext.Provider>\n </CopilotChatConfigurationProvider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ name, args }: { name: string; args: Record<string, any> }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n\nfunction formatFeatureName(featureName: string): string {\n return featureName\n .replace(/_c$/, \"\")\n .split(\"_\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\" \");\n}\n\nfunction validateProps(props: CopilotKitProps): never | void {\n const cloudFeatures = Object.keys(props).filter((key) => key.endsWith(\"_c\"));\n\n // Check if we have either a runtimeUrl or one of the API keys\n const hasApiKey = props.publicApiKey || props.publicLicenseKey;\n\n if (!props.runtimeUrl && !hasApiKey) {\n throw new ConfigurationError(\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\",\n );\n }\n\n if (cloudFeatures.length > 0 && !hasApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n"],"mappings":"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","names":["import_runtime_client_gql","import_react","import_shared"]}
@@ -1,21 +1,18 @@
1
1
  import {
2
2
  CopilotTask
3
- } from "../chunk-B5ELMVT7.mjs";
3
+ } from "../chunk-HQTDDA6V.mjs";
4
4
  import "../chunk-4CEQJ2X6.mjs";
5
5
  import "../chunk-JD7BAH7U.mjs";
6
6
  import "../chunk-SPCZTZCY.mjs";
7
- import "../chunk-FYMZKPOL.mjs";
7
+ import "../chunk-CO6V4G7P.mjs";
8
8
  import "../chunk-LHERIF3L.mjs";
9
9
  import "../chunk-HE22TZMF.mjs";
10
- import "../chunk-PMWUKW3Z.mjs";
11
- import "../chunk-YCG6SNAU.mjs";
12
- import "../chunk-PIF5KJYI.mjs";
13
10
  import "../chunk-RKTVJRK7.mjs";
11
+ import "../chunk-PMAFHQ7P.mjs";
14
12
  import "../chunk-CYDWEPFL.mjs";
15
- import "../chunk-ICIK2BSB.mjs";
16
13
  import "../chunk-2IDV5OHF.mjs";
14
+ import "../chunk-ICIK2BSB.mjs";
17
15
  import "../chunk-YYN33GSG.mjs";
18
- import "../chunk-PMAFHQ7P.mjs";
19
16
  import "../chunk-6PUNP7CD.mjs";
20
17
  import "../chunk-O7ARI5CV.mjs";
21
18
  import "../chunk-QNUAXSDP.mjs";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/lib/index.ts","../../src/lib/copilot-task.ts","../../src/types/frontend-action.ts","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["export * from \"./copilot-task\";\n","/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n * }\n * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { FrontendAction, processActionsForRuntimeRequest } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: ForwardedParametersInput;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n private forwardedParameters?: ForwardedParametersInput;\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions = config.includeCopilotActions !== false;\n this.forwardedParameters = config.forwardedParameters;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(Object.values(actions)),\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n // if forwardedParameters is provided, use it\n toolChoice: \"required\",\n ...(this.forwardedParameters ?? {}),\n },\n },\n properties: context.copilotApiConfig.properties,\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m.isActionExecutionMessage());\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\n }\n }\n}\n\nfunction taskSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n","import { ActionInputAvailability } from \"@copilotkit/runtime-client-gql\";\nimport {\n Action,\n Parameter,\n MappedParameterTypes,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport React from \"react\";\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingState<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: any;\n}\n\ninterface InProgressStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n}\n\nexport type ActionRenderProps<T extends Parameter[] | [] = []> =\n | CompleteState<T>\n | ExecutingState<T>\n | InProgressState<T>;\n\nexport type ActionRenderPropsNoArgs<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgs<T>\n | ExecutingStateNoArgs<T>\n | InProgressStateNoArgs<T>;\n\nexport type ActionRenderPropsWait<T extends Parameter[] | [] = []> =\n | CompleteStateWait<T>\n | ExecutingStateWait<T>\n | InProgressStateWait<T>;\n\nexport type ActionRenderPropsNoArgsWait<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgsWait<T>\n | ExecutingStateNoArgsWait<T>\n | InProgressStateNoArgsWait<T>;\n\nexport type CatchAllActionRenderProps<T extends Parameter[] | [] = []> =\n | (CompleteState<T> & {\n name: string;\n })\n | (ExecutingState<T> & {\n name: string;\n })\n | (InProgressState<T> & {\n name: string;\n });\n\nexport type FrontendActionAvailability = \"disabled\" | \"enabled\" | \"remote\" | \"frontend\";\n\nexport type FrontendAction<\n T extends Parameter[] | [] = [],\n N extends string = string,\n> = Action<T> & {\n name: Exclude<N, \"*\">;\n /**\n * @deprecated Use `available` instead.\n */\n disabled?: boolean;\n available?: FrontendActionAvailability;\n pairedAction?: string;\n followUp?: boolean;\n} & (\n | {\n render?:\n | string\n | (T extends []\n ? (props: ActionRenderPropsNoArgs<T>) => string | React.ReactElement\n : (props: ActionRenderProps<T>) => string | React.ReactElement);\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: never;\n renderAndWaitForResponse?: never;\n }\n | {\n render?: never;\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n renderAndWaitForResponse?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n handler?: never;\n }\n );\n\nexport type CatchAllFrontendAction = {\n name: \"*\";\n render: (props: CatchAllActionRenderProps<any>) => React.ReactElement;\n};\n\nexport type RenderFunctionStatus = ActionRenderProps<any>[\"status\"];\n\nexport function processActionsForRuntimeRequest(actions: FrontendAction<any>[]) {\n const filteredActions = actions\n .filter(\n (action) =>\n action.available !== ActionInputAvailability.Disabled &&\n action.disabled !== true &&\n action.name !== \"*\" &&\n action.available != \"frontend\" &&\n !action.pairedAction,\n )\n .map((action) => {\n let available: ActionInputAvailability | undefined = ActionInputAvailability.Enabled;\n if (action.disabled) {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"disabled\") {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"remote\") {\n available = ActionInputAvailability.Remote;\n }\n return {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n available,\n };\n });\n return filteredActions;\n}\n","/**\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 * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState, SetStateAction } from \"react\";\nimport { CopilotChatConfigurationProvider, CopilotKitProvider } from \"@copilotkitnext/react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n AuthState,\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 COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n randomUUID,\n ConfigurationError,\n MissingPublicApiKeyError,\n CopilotKitError,\n CopilotErrorEvent,\n CopilotErrorHandler,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages, MessagesTapProvider } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { getErrorActions, UsageBanner } from \"../usage-banner\";\nimport { shouldShowDevConsole } from \"../../utils\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\nimport { Agent, ExtensionsInput } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptRender,\n LangGraphInterruptActionSetterArgs,\n QueuedInterruptEvent,\n} from \"../../types/interrupt-action\";\nimport { ConsoleTrigger } from \"../dev-console/console-trigger\";\nimport { CoAgentStateRendersProvider } from \"../../context/coagent-state-renders-context\";\nimport { CoAgentStateRenderBridge } from \"../../hooks/use-coagent-state-render-bridge\";\nimport { ThreadsProvider, useThreads } from \"../../context/threads-context\";\nimport { CopilotListeners } from \"../CopilotListeners\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const enabled = shouldShowDevConsole(props.showDevConsole);\n\n // Use API key if provided, otherwise use the license key\n const publicApiKey = props.publicApiKey || props.publicLicenseKey;\n\n const renderArr = useMemo(() => [{ render: CoAgentStateRenderBridge }], []);\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary publicApiKey={publicApiKey} showUsageBanner={enabled}>\n <ThreadsProvider threadId={props.threadId}>\n <CopilotKitProvider {...props} renderCustomMessages={renderArr} useSingleEndpoint={true}>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotKitProvider>\n </ThreadsProvider>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal(cpkProps: CopilotKitProps) {\n const { children, ...props } = cpkProps;\n\n /**\n * This will throw an error if the props are invalid.\n */\n validateProps(cpkProps);\n\n // Use license key as API key if provided, otherwise use the API key\n const publicApiKey = props.publicLicenseKey || props.publicApiKey;\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n\n // State for registered actions from useCopilotAction\n const [registeredActionConfigs, setRegisteredActionConfigs] = useState<\n Map<string, { type: string; action: any; component: any }>\n >(new Map());\n\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n\n const { addElement, removeElement, printTree, getAllElements } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});\n const [extensions, setExtensions] = useState<ExtensionsInput>({});\n const [additionalInstructions, setAdditionalInstructions] = useState<string[]>([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n // Compute all the functions and properties that we need to pass\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 getAllContext = useCallback(() => {\n return getAllElements();\n }, [getAllElements]);\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 // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: 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 publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n props.guardrails_c,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const [internalErrorHandlers, _setInternalErrorHandler] = useState<\n Record<string, CopilotErrorHandler>\n >({});\n const setInternalErrorHandler = useCallback((handler: Record<string, CopilotErrorHandler>) => {\n _setInternalErrorHandler((prev: Record<string, CopilotErrorHandler>) => ({\n ...prev,\n ...handler,\n }));\n }, []);\n const removeInternalErrorHandler = useCallback((key: string) => {\n _setInternalErrorHandler((prev) => {\n const { [key]: _removed, ...rest } = prev;\n return rest;\n });\n }, []);\n\n // Keep latest values in refs\n const onErrorRef = useRef<CopilotErrorHandler | undefined>(props.onError);\n useEffect(() => {\n onErrorRef.current = props.onError;\n }, [props.onError]);\n\n const internalHandlersRef = useRef<Record<string, CopilotErrorHandler>>({});\n useEffect(() => {\n internalHandlersRef.current = internalErrorHandlers;\n }, [internalErrorHandlers]);\n\n const handleErrors = useCallback(\n async (error: CopilotErrorEvent) => {\n if (copilotApiConfig.publicApiKey && onErrorRef.current) {\n try {\n await onErrorRef.current(error);\n } catch (e) {\n console.error(\"Error in public onError handler:\", e);\n }\n }\n const handlers = Object.values(internalHandlersRef.current);\n await Promise.all(\n handlers.map((h) =>\n Promise.resolve(h(error)).catch((e) =>\n console.error(\"Error in internal error handler:\", e),\n ),\n ),\n );\n },\n [copilotApiConfig.publicApiKey],\n );\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = useCallback(\n (id: string, suggestion: CopilotChatSuggestionConfiguration) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n },\n [setChatSuggestionConfiguration],\n );\n\n const removeChatSuggestionConfiguration = useCallback(\n (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n },\n [setChatSuggestionConfiguration],\n );\n\n const [availableAgents, setAvailableAgents] = useState<Agent[]>([]);\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => {\n const newValue = typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n\n // Update agentSession when props.agent changes\n useEffect(() => {\n if (props.agent) {\n setAgentSession({\n agentName: props.agent,\n });\n } else {\n setAgentSession(null);\n }\n }, [props.agent]);\n\n const { threadId, setThreadId: setInternalThreadId } = useThreads();\n\n const setThreadId = useCallback(\n (value: SetStateAction<string>) => {\n if (props.threadId) {\n throw new Error(\"Cannot call setThreadId() when threadId is provided via props.\");\n }\n setInternalThreadId(value);\n },\n [props.threadId],\n );\n\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = shouldShowDevConsole(props.showDevConsole);\n\n const [interruptActions, _setInterruptActions] = useState<\n Record<string, LangGraphInterruptRender>\n >({});\n const setInterruptAction = useCallback((action: LangGraphInterruptActionSetterArgs) => {\n _setInterruptActions((prev) => {\n if (action == null || !action.id) {\n // Cannot set action without id\n return prev;\n }\n return {\n ...prev,\n [action.id]: { ...(prev[action.id] ?? {}), ...action } as LangGraphInterruptRender,\n };\n });\n }, []);\n const removeInterruptAction = useCallback((actionId: string): void => {\n _setInterruptActions((prev) => {\n const { [actionId]: _, ...rest } = prev;\n return rest;\n });\n }, []);\n\n const [interruptEventQueue, setInterruptEventQueue] = useState<\n Record<string, QueuedInterruptEvent[]>\n >({});\n\n const addInterruptEvent = useCallback((queuedEvent: QueuedInterruptEvent) => {\n setInterruptEventQueue((prev) => {\n const threadQueue = prev[queuedEvent.threadId] || [];\n return {\n ...prev,\n [queuedEvent.threadId]: [...threadQueue, queuedEvent],\n };\n });\n }, []);\n\n const resolveInterruptEvent = useCallback(\n (threadId: string, eventId: string, response: string) => {\n setInterruptEventQueue((prev) => {\n const threadQueue = prev[threadId] || [];\n return {\n ...prev,\n [threadId]: threadQueue.map((queuedEvent) =>\n queuedEvent.eventId === eventId\n ? { ...queuedEvent, event: { ...queuedEvent.event, response } }\n : queuedEvent,\n ),\n };\n });\n },\n [],\n );\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [bannerError, setBannerError] = useState<CopilotKitError | null>(null);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved = typeof newExtensions === \"function\" ? newExtensions(prev) : newExtensions;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setExtensions],\n );\n\n const updateAuthStates = useCallback(\n (newAuthStates: SetStateAction<Record<string, AuthState>>) => {\n setAuthStates((prev) => {\n const resolved = typeof newAuthStates === \"function\" ? newAuthStates(prev) : newAuthStates;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setAuthStates],\n );\n\n const handleSetRegisteredActions = useCallback((actionConfig: any): string => {\n const key = actionConfig.action.name || randomUUID();\n setRegisteredActionConfigs((prev) => {\n const newMap = new Map(prev);\n newMap.set(key, actionConfig);\n return newMap;\n });\n return key;\n }, []);\n\n const handleRemoveRegisteredAction = useCallback((actionKey: string) => {\n setRegisteredActionConfigs((prev) => {\n const newMap = new Map(prev);\n newMap.delete(actionKey);\n return newMap;\n });\n }, []);\n\n // Component to render all registered actions\n const RegisteredActionsRenderer = useMemo(() => {\n return () => (\n <>\n {Array.from(registeredActionConfigs.entries()).map(([key, config]) => {\n const Component = config.component;\n return <Component key={key} action={config.action} />;\n })}\n </>\n );\n }, [registeredActionConfigs]);\n\n return (\n <CopilotChatConfigurationProvider\n // labels={labels}\n // isModalDefaultOpen={isModalDefaultOpen}\n agentId={props.agent ?? \"default\"}\n threadId={threadId}\n >\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n setRegisteredActions: handleSetRegisteredActions,\n removeRegisteredAction: handleRemoveRegisteredAction,\n getContextString,\n addContext,\n removeContext,\n getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n additionalInstructions,\n setAdditionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n availableAgents,\n authConfig_c: props.authConfig_c,\n authStates_c: authStates,\n setAuthStates_c: updateAuthStates,\n extensions,\n setExtensions: updateExtensions,\n interruptActions,\n setInterruptAction,\n removeInterruptAction,\n interruptEventQueue,\n addInterruptEvent,\n resolveInterruptEvent,\n bannerError,\n setBannerError,\n onError: handleErrors,\n internalErrorHandlers,\n setInternalErrorHandler,\n removeInternalErrorHandler,\n }}\n >\n <CopilotListeners />\n <CoAgentStateRendersProvider>\n <MessagesTapProvider>\n <CopilotMessages>\n {memoizedChildren}\n {showDevConsole && <ConsoleTrigger />}\n <RegisteredActionsRenderer />\n </CopilotMessages>\n </MessagesTapProvider>\n {bannerError && showDevConsole && (\n <UsageBanner\n severity={bannerError.severity}\n message={bannerError.message}\n onClose={() => setBannerError(null)}\n actions={getErrorActions(bannerError)}\n />\n )}\n </CoAgentStateRendersProvider>\n </CopilotContext.Provider>\n </CopilotChatConfigurationProvider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ name, args }: { name: string; args: Record<string, any> }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n\nfunction formatFeatureName(featureName: string): string {\n return featureName\n .replace(/_c$/, \"\")\n .split(\"_\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\" \");\n}\n\nfunction validateProps(props: CopilotKitProps): never | void {\n const cloudFeatures = Object.keys(props).filter((key) => key.endsWith(\"_c\"));\n\n // Check if we have either a runtimeUrl or one of the API keys\n const hasApiKey = props.publicApiKey || props.publicLicenseKey;\n\n if (!props.runtimeUrl && !hasApiKey) {\n throw new ConfigurationError(\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\",\n );\n }\n\n if (cloudFeatures.length > 0 && !hasApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n"],"mappings":"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","names":["import_runtime_client_gql","import_react","import_shared"]}
1
+ {"version":3,"sources":["../../src/lib/index.ts","../../src/lib/copilot-task.ts","../../src/types/frontend-action.ts","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["export * from \"./copilot-task\";\n","/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n * }\n * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { FrontendAction, processActionsForRuntimeRequest } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: ForwardedParametersInput;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n private forwardedParameters?: ForwardedParametersInput;\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions = config.includeCopilotActions !== false;\n this.forwardedParameters = config.forwardedParameters;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(Object.values(actions)),\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n // if forwardedParameters is provided, use it\n toolChoice: \"required\",\n ...(this.forwardedParameters ?? {}),\n },\n },\n properties: context.copilotApiConfig.properties,\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m.isActionExecutionMessage());\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\n }\n }\n}\n\nfunction taskSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n","import { ActionInputAvailability } from \"@copilotkit/runtime-client-gql\";\nimport {\n Action,\n Parameter,\n MappedParameterTypes,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport React from \"react\";\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingState<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: any;\n}\n\ninterface InProgressStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n}\n\nexport type ActionRenderProps<T extends Parameter[] | [] = []> =\n | CompleteState<T>\n | ExecutingState<T>\n | InProgressState<T>;\n\nexport type ActionRenderPropsNoArgs<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgs<T>\n | ExecutingStateNoArgs<T>\n | InProgressStateNoArgs<T>;\n\nexport type ActionRenderPropsWait<T extends Parameter[] | [] = []> =\n | CompleteStateWait<T>\n | ExecutingStateWait<T>\n | InProgressStateWait<T>;\n\nexport type ActionRenderPropsNoArgsWait<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgsWait<T>\n | ExecutingStateNoArgsWait<T>\n | InProgressStateNoArgsWait<T>;\n\nexport type CatchAllActionRenderProps<T extends Parameter[] | [] = []> =\n | (CompleteState<T> & {\n name: string;\n })\n | (ExecutingState<T> & {\n name: string;\n })\n | (InProgressState<T> & {\n name: string;\n });\n\nexport type FrontendActionAvailability = \"disabled\" | \"enabled\" | \"remote\" | \"frontend\";\n\nexport type FrontendAction<\n T extends Parameter[] | [] = [],\n N extends string = string,\n> = Action<T> & {\n name: Exclude<N, \"*\">;\n /**\n * @deprecated Use `available` instead.\n */\n disabled?: boolean;\n available?: FrontendActionAvailability;\n pairedAction?: string;\n followUp?: boolean;\n} & (\n | {\n render?:\n | string\n | (T extends []\n ? (props: ActionRenderPropsNoArgs<T>) => string | React.ReactElement\n : (props: ActionRenderProps<T>) => string | React.ReactElement);\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: never;\n renderAndWaitForResponse?: never;\n }\n | {\n render?: never;\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n renderAndWaitForResponse?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n handler?: never;\n }\n );\n\nexport type CatchAllFrontendAction = {\n name: \"*\";\n render: (props: CatchAllActionRenderProps<any>) => React.ReactElement;\n};\n\nexport type RenderFunctionStatus = ActionRenderProps<any>[\"status\"];\n\nexport function processActionsForRuntimeRequest(actions: FrontendAction<any>[]) {\n const filteredActions = actions\n .filter(\n (action) =>\n action.available !== ActionInputAvailability.Disabled &&\n action.disabled !== true &&\n action.name !== \"*\" &&\n action.available != \"frontend\" &&\n !action.pairedAction,\n )\n .map((action) => {\n let available: ActionInputAvailability | undefined = ActionInputAvailability.Enabled;\n if (action.disabled) {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"disabled\") {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"remote\") {\n available = ActionInputAvailability.Remote;\n }\n return {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n available,\n };\n });\n return filteredActions;\n}\n","/**\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 * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState, SetStateAction } from \"react\";\nimport {\n CopilotChatConfigurationProvider,\n CopilotKitInspector,\n CopilotKitProvider as CopilotKitNextProvider,\n} from \"@copilotkitnext/react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n AuthState,\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 COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n randomUUID,\n ConfigurationError,\n MissingPublicApiKeyError,\n CopilotKitError,\n CopilotErrorEvent,\n CopilotErrorHandler,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages, MessagesTapProvider } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { getErrorActions, UsageBanner } from \"../usage-banner\";\nimport { shouldShowDevConsole } from \"../../utils\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\nimport { Agent, ExtensionsInput } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptRender,\n LangGraphInterruptActionSetterArgs,\n QueuedInterruptEvent,\n} from \"../../types/interrupt-action\";\nimport { CoAgentStateRendersProvider } from \"../../context/coagent-state-renders-context\";\nimport { CoAgentStateRenderBridge } from \"../../hooks/use-coagent-state-render-bridge\";\nimport { ThreadsProvider, useThreads } from \"../../context/threads-context\";\nimport { CopilotListeners } from \"../CopilotListeners\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const enabled = shouldShowDevConsole(props.showDevConsole);\n const showInspector = shouldShowDevConsole(props.enableInspector);\n\n // Use API key if provided, otherwise use the license key\n const publicApiKey = props.publicApiKey || props.publicLicenseKey;\n\n const renderArr = useMemo(() => [{ render: CoAgentStateRenderBridge }], []);\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary publicApiKey={publicApiKey} showUsageBanner={enabled}>\n <ThreadsProvider threadId={props.threadId}>\n <CopilotKitNextProvider\n {...props}\n showDevConsole={showInspector}\n renderCustomMessages={renderArr}\n useSingleEndpoint={true}\n >\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotKitNextProvider>\n </ThreadsProvider>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal(cpkProps: CopilotKitProps) {\n const { children, ...props } = cpkProps;\n\n /**\n * This will throw an error if the props are invalid.\n */\n validateProps(cpkProps);\n\n // Use license key as API key if provided, otherwise use the API key\n const publicApiKey = props.publicLicenseKey || props.publicApiKey;\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n\n // State for registered actions from useCopilotAction\n const [registeredActionConfigs, setRegisteredActionConfigs] = useState<\n Map<string, { type: string; action: any; component: any }>\n >(new Map());\n\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n\n const { addElement, removeElement, printTree, getAllElements } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});\n const [extensions, setExtensions] = useState<ExtensionsInput>({});\n const [additionalInstructions, setAdditionalInstructions] = useState<string[]>([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n // Compute all the functions and properties that we need to pass\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 getAllContext = useCallback(() => {\n return getAllElements();\n }, [getAllElements]);\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 // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: 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 publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n props.guardrails_c,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const [internalErrorHandlers, _setInternalErrorHandler] = useState<\n Record<string, CopilotErrorHandler>\n >({});\n const setInternalErrorHandler = useCallback((handler: Record<string, CopilotErrorHandler>) => {\n _setInternalErrorHandler((prev: Record<string, CopilotErrorHandler>) => ({\n ...prev,\n ...handler,\n }));\n }, []);\n const removeInternalErrorHandler = useCallback((key: string) => {\n _setInternalErrorHandler((prev) => {\n const { [key]: _removed, ...rest } = prev;\n return rest;\n });\n }, []);\n\n // Keep latest values in refs\n const onErrorRef = useRef<CopilotErrorHandler | undefined>(props.onError);\n useEffect(() => {\n onErrorRef.current = props.onError;\n }, [props.onError]);\n\n const internalHandlersRef = useRef<Record<string, CopilotErrorHandler>>({});\n useEffect(() => {\n internalHandlersRef.current = internalErrorHandlers;\n }, [internalErrorHandlers]);\n\n const handleErrors = useCallback(\n async (error: CopilotErrorEvent) => {\n if (copilotApiConfig.publicApiKey && onErrorRef.current) {\n try {\n await onErrorRef.current(error);\n } catch (e) {\n console.error(\"Error in public onError handler:\", e);\n }\n }\n const handlers = Object.values(internalHandlersRef.current);\n await Promise.all(\n handlers.map((h) =>\n Promise.resolve(h(error)).catch((e) =>\n console.error(\"Error in internal error handler:\", e),\n ),\n ),\n );\n },\n [copilotApiConfig.publicApiKey],\n );\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = useCallback(\n (id: string, suggestion: CopilotChatSuggestionConfiguration) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n },\n [setChatSuggestionConfiguration],\n );\n\n const removeChatSuggestionConfiguration = useCallback(\n (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n },\n [setChatSuggestionConfiguration],\n );\n\n const [availableAgents, setAvailableAgents] = useState<Agent[]>([]);\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => {\n const newValue = typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n\n // Update agentSession when props.agent changes\n useEffect(() => {\n if (props.agent) {\n setAgentSession({\n agentName: props.agent,\n });\n } else {\n setAgentSession(null);\n }\n }, [props.agent]);\n\n const { threadId, setThreadId: setInternalThreadId } = useThreads();\n\n const setThreadId = useCallback(\n (value: SetStateAction<string>) => {\n if (props.threadId) {\n throw new Error(\"Cannot call setThreadId() when threadId is provided via props.\");\n }\n setInternalThreadId(value);\n },\n [props.threadId],\n );\n\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = shouldShowDevConsole(props.showDevConsole);\n\n const [interruptActions, _setInterruptActions] = useState<\n Record<string, LangGraphInterruptRender>\n >({});\n const setInterruptAction = useCallback((action: LangGraphInterruptActionSetterArgs) => {\n _setInterruptActions((prev) => {\n if (action == null || !action.id) {\n // Cannot set action without id\n return prev;\n }\n return {\n ...prev,\n [action.id]: { ...(prev[action.id] ?? {}), ...action } as LangGraphInterruptRender,\n };\n });\n }, []);\n const removeInterruptAction = useCallback((actionId: string): void => {\n _setInterruptActions((prev) => {\n const { [actionId]: _, ...rest } = prev;\n return rest;\n });\n }, []);\n\n const [interruptEventQueue, setInterruptEventQueue] = useState<\n Record<string, QueuedInterruptEvent[]>\n >({});\n\n const addInterruptEvent = useCallback((queuedEvent: QueuedInterruptEvent) => {\n setInterruptEventQueue((prev) => {\n const threadQueue = prev[queuedEvent.threadId] || [];\n return {\n ...prev,\n [queuedEvent.threadId]: [...threadQueue, queuedEvent],\n };\n });\n }, []);\n\n const resolveInterruptEvent = useCallback(\n (threadId: string, eventId: string, response: string) => {\n setInterruptEventQueue((prev) => {\n const threadQueue = prev[threadId] || [];\n return {\n ...prev,\n [threadId]: threadQueue.map((queuedEvent) =>\n queuedEvent.eventId === eventId\n ? { ...queuedEvent, event: { ...queuedEvent.event, response } }\n : queuedEvent,\n ),\n };\n });\n },\n [],\n );\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [bannerError, setBannerError] = useState<CopilotKitError | null>(null);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved = typeof newExtensions === \"function\" ? newExtensions(prev) : newExtensions;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setExtensions],\n );\n\n const updateAuthStates = useCallback(\n (newAuthStates: SetStateAction<Record<string, AuthState>>) => {\n setAuthStates((prev) => {\n const resolved = typeof newAuthStates === \"function\" ? newAuthStates(prev) : newAuthStates;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setAuthStates],\n );\n\n const handleSetRegisteredActions = useCallback((actionConfig: any): string => {\n const key = actionConfig.action.name || randomUUID();\n setRegisteredActionConfigs((prev) => {\n const newMap = new Map(prev);\n newMap.set(key, actionConfig);\n return newMap;\n });\n return key;\n }, []);\n\n const handleRemoveRegisteredAction = useCallback((actionKey: string) => {\n setRegisteredActionConfigs((prev) => {\n const newMap = new Map(prev);\n newMap.delete(actionKey);\n return newMap;\n });\n }, []);\n\n // Component to render all registered actions\n const RegisteredActionsRenderer = useMemo(() => {\n return () => (\n <>\n {Array.from(registeredActionConfigs.entries()).map(([key, config]) => {\n const Component = config.component;\n return <Component key={key} action={config.action} />;\n })}\n </>\n );\n }, [registeredActionConfigs]);\n\n return (\n <CopilotChatConfigurationProvider\n // labels={labels}\n // isModalDefaultOpen={isModalDefaultOpen}\n agentId={props.agent ?? \"default\"}\n threadId={threadId}\n >\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n setRegisteredActions: handleSetRegisteredActions,\n removeRegisteredAction: handleRemoveRegisteredAction,\n getContextString,\n addContext,\n removeContext,\n getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n additionalInstructions,\n setAdditionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n availableAgents,\n authConfig_c: props.authConfig_c,\n authStates_c: authStates,\n setAuthStates_c: updateAuthStates,\n extensions,\n setExtensions: updateExtensions,\n interruptActions,\n setInterruptAction,\n removeInterruptAction,\n interruptEventQueue,\n addInterruptEvent,\n resolveInterruptEvent,\n bannerError,\n setBannerError,\n onError: handleErrors,\n internalErrorHandlers,\n setInternalErrorHandler,\n removeInternalErrorHandler,\n }}\n >\n <CopilotListeners />\n <CoAgentStateRendersProvider>\n <MessagesTapProvider>\n <CopilotMessages>\n {memoizedChildren}\n <RegisteredActionsRenderer />\n </CopilotMessages>\n </MessagesTapProvider>\n {bannerError && showDevConsole && (\n <UsageBanner\n severity={bannerError.severity}\n message={bannerError.message}\n onClose={() => setBannerError(null)}\n actions={getErrorActions(bannerError)}\n />\n )}\n </CoAgentStateRendersProvider>\n </CopilotContext.Provider>\n </CopilotChatConfigurationProvider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ name, args }: { name: string; args: Record<string, any> }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n\nfunction formatFeatureName(featureName: string): string {\n return featureName\n .replace(/_c$/, \"\")\n .split(\"_\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\" \");\n}\n\nfunction validateProps(props: CopilotKitProps): never | void {\n const cloudFeatures = Object.keys(props).filter((key) => key.endsWith(\"_c\"));\n\n // Check if we have either a runtimeUrl or one of the API keys\n const hasApiKey = props.publicApiKey || props.publicLicenseKey;\n\n if (!props.runtimeUrl && !hasApiKey) {\n throw new ConfigurationError(\n \"Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'\",\n );\n }\n\n if (cloudFeatures.length > 0 && !hasApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n"],"mappings":"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","names":["import_runtime_client_gql","import_react","import_shared"]}
@@ -1,22 +1,19 @@
1
1
  import "../chunk-LUGEI4YQ.mjs";
2
2
  import {
3
3
  CopilotTask
4
- } from "../chunk-B5ELMVT7.mjs";
4
+ } from "../chunk-HQTDDA6V.mjs";
5
5
  import "../chunk-4CEQJ2X6.mjs";
6
6
  import "../chunk-JD7BAH7U.mjs";
7
7
  import "../chunk-SPCZTZCY.mjs";
8
- import "../chunk-FYMZKPOL.mjs";
8
+ import "../chunk-CO6V4G7P.mjs";
9
9
  import "../chunk-LHERIF3L.mjs";
10
10
  import "../chunk-HE22TZMF.mjs";
11
- import "../chunk-PMWUKW3Z.mjs";
12
- import "../chunk-YCG6SNAU.mjs";
13
- import "../chunk-PIF5KJYI.mjs";
14
11
  import "../chunk-RKTVJRK7.mjs";
12
+ import "../chunk-PMAFHQ7P.mjs";
15
13
  import "../chunk-CYDWEPFL.mjs";
16
- import "../chunk-ICIK2BSB.mjs";
17
14
  import "../chunk-2IDV5OHF.mjs";
15
+ import "../chunk-ICIK2BSB.mjs";
18
16
  import "../chunk-YYN33GSG.mjs";
19
- import "../chunk-PMAFHQ7P.mjs";
20
17
  import "../chunk-6PUNP7CD.mjs";
21
18
  import "../chunk-O7ARI5CV.mjs";
22
19
  import "../chunk-QNUAXSDP.mjs";
@@ -1,10 +1,10 @@
1
1
  import "../chunk-CYDWEPFL.mjs";
2
- import {
3
- shouldShowDevConsole
4
- } from "../chunk-ICIK2BSB.mjs";
5
2
  import {
6
3
  SUGGESTION_RETRY_CONFIG
7
4
  } from "../chunk-2IDV5OHF.mjs";
5
+ import {
6
+ shouldShowDevConsole
7
+ } from "../chunk-ICIK2BSB.mjs";
8
8
  import "../chunk-SKC7AJIV.mjs";
9
9
  export {
10
10
  SUGGESTION_RETRY_CONFIG,
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "publishConfig": {
10
10
  "access": "public"
11
11
  },
12
- "version": "1.50.0-beta.9",
12
+ "version": "1.50.0",
13
13
  "sideEffects": [
14
14
  "**/*.css"
15
15
  ],
@@ -36,7 +36,6 @@
36
36
  "zod": ">=3.0.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@ag-ui/client": "^0.0.42",
40
39
  "@testing-library/react": "^16.3.0",
41
40
  "@testing-library/react-hooks": "^8.0.1",
42
41
  "@types/jest": "^29.5.4",
@@ -56,13 +55,14 @@
56
55
  "tsconfig": "1.4.6"
57
56
  },
58
57
  "dependencies": {
59
- "@copilotkitnext/core": "0.0.28",
60
- "@copilotkitnext/react": "0.0.28",
58
+ "@ag-ui/client": "^0.0.42",
59
+ "@copilotkitnext/core": "0.0.31",
60
+ "@copilotkitnext/react": "0.0.31",
61
61
  "@scarf/scarf": "^1.3.0",
62
62
  "react-markdown": "^8.0.7",
63
63
  "untruncate-json": "^0.0.1",
64
- "@copilotkit/runtime-client-gql": "1.50.0-beta.9",
65
- "@copilotkit/shared": "1.50.0-beta.9"
64
+ "@copilotkit/runtime-client-gql": "1.50.0",
65
+ "@copilotkit/shared": "1.50.0"
66
66
  },
67
67
  "keywords": [
68
68
  "copilotkit",
@@ -159,4 +159,11 @@ export interface CopilotKitProps extends Omit<CopilotKitProviderProps, "children
159
159
  * ```
160
160
  */
161
161
  onError?: CopilotErrorHandler;
162
+
163
+ /**
164
+ * Enable or disable the CopilotKit Inspector, letting you inspect AG-UI events,
165
+ * view agent messages, check agent state, and visualize agent context. Defaults
166
+ * to enabled.
167
+ */
168
+ enableInspector?: boolean;
162
169
  }