@copilotkit/react-core 1.8.13 → 1.8.14-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/{chunk-4EXRQ5D5.mjs → chunk-2J3SMMGW.mjs} +2 -2
  3. package/dist/{chunk-AW2AIX74.mjs → chunk-74AJEJTV.mjs} +16 -3
  4. package/dist/chunk-74AJEJTV.mjs.map +1 -0
  5. package/dist/{chunk-B3CERZDI.mjs → chunk-B5UA5G3E.mjs} +2 -2
  6. package/dist/{chunk-XRCQULYN.mjs → chunk-D6CQVQI6.mjs} +2 -2
  7. package/dist/{chunk-W3QHAZKD.mjs → chunk-EQ4XLLT4.mjs} +3 -3
  8. package/dist/{chunk-7WG4MNRX.mjs → chunk-ERFA53MG.mjs} +2 -1
  9. package/dist/chunk-ERFA53MG.mjs.map +1 -0
  10. package/dist/{chunk-2ZKWBDBN.mjs → chunk-FGBRHBRR.mjs} +2 -2
  11. package/dist/{chunk-INRN7B2F.mjs → chunk-G27C5EFO.mjs} +2 -2
  12. package/dist/{chunk-KQPKROYS.mjs → chunk-IHYG57NB.mjs} +4 -4
  13. package/dist/{chunk-D5NLDVW2.mjs → chunk-KID3UPGL.mjs} +5 -3
  14. package/dist/chunk-KID3UPGL.mjs.map +1 -0
  15. package/dist/{chunk-VYSR3S2A.mjs → chunk-NTR5KV42.mjs} +2 -2
  16. package/dist/{chunk-YXPFUKGZ.mjs → chunk-PLA6FXVD.mjs} +3 -3
  17. package/dist/{chunk-6U3UH3KO.mjs → chunk-RKTVJRK7.mjs} +5 -2
  18. package/dist/chunk-RKTVJRK7.mjs.map +1 -0
  19. package/dist/{chunk-GBAZTXPQ.mjs → chunk-VQ3VTO26.mjs} +2 -2
  20. package/dist/{chunk-O54FEOCV.mjs → chunk-WYCLVOYC.mjs} +9 -5
  21. package/dist/chunk-WYCLVOYC.mjs.map +1 -0
  22. package/dist/{chunk-OSVDTMKA.mjs → chunk-WZAEVHLK.mjs} +2 -2
  23. package/dist/components/copilot-provider/copilot-messages.js +1 -0
  24. package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
  25. package/dist/components/copilot-provider/copilot-messages.mjs +2 -2
  26. package/dist/components/copilot-provider/copilotkit-props.d.ts +1 -1
  27. package/dist/components/copilot-provider/copilotkit.d.ts +1 -1
  28. package/dist/components/copilot-provider/copilotkit.js +10 -2
  29. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  30. package/dist/components/copilot-provider/copilotkit.mjs +4 -4
  31. package/dist/components/copilot-provider/index.d.ts +1 -1
  32. package/dist/components/copilot-provider/index.js +10 -2
  33. package/dist/components/copilot-provider/index.js.map +1 -1
  34. package/dist/components/copilot-provider/index.mjs +4 -4
  35. package/dist/components/index.d.ts +1 -1
  36. package/dist/components/index.js +10 -2
  37. package/dist/components/index.js.map +1 -1
  38. package/dist/components/index.mjs +4 -4
  39. package/dist/context/copilot-context.d.ts +1 -1
  40. package/dist/context/copilot-context.js +1 -0
  41. package/dist/context/copilot-context.js.map +1 -1
  42. package/dist/context/copilot-context.mjs +1 -1
  43. package/dist/context/index.d.ts +1 -1
  44. package/dist/context/index.js +1 -0
  45. package/dist/context/index.js.map +1 -1
  46. package/dist/context/index.mjs +1 -1
  47. package/dist/{copilot-context-8fb74a85.d.ts → copilot-context-309906bb.d.ts} +4 -2
  48. package/dist/hooks/index.d.ts +2 -2
  49. package/dist/hooks/index.js +17 -1
  50. package/dist/hooks/index.js.map +1 -1
  51. package/dist/hooks/index.mjs +15 -15
  52. package/dist/hooks/use-chat.d.ts +1 -1
  53. package/dist/hooks/use-chat.js +14 -1
  54. package/dist/hooks/use-chat.js.map +1 -1
  55. package/dist/hooks/use-chat.mjs +1 -1
  56. package/dist/hooks/use-coagent-state-render.js +1 -0
  57. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  58. package/dist/hooks/use-coagent-state-render.mjs +2 -2
  59. package/dist/hooks/use-coagent.d.ts +1 -1
  60. package/dist/hooks/use-coagent.js +17 -1
  61. package/dist/hooks/use-coagent.js.map +1 -1
  62. package/dist/hooks/use-coagent.mjs +7 -7
  63. package/dist/hooks/use-copilot-action.js +1 -0
  64. package/dist/hooks/use-copilot-action.js.map +1 -1
  65. package/dist/hooks/use-copilot-action.mjs +2 -2
  66. package/dist/hooks/use-copilot-additional-instructions.js +1 -0
  67. package/dist/hooks/use-copilot-additional-instructions.js.map +1 -1
  68. package/dist/hooks/use-copilot-additional-instructions.mjs +2 -2
  69. package/dist/hooks/use-copilot-authenticated-action.js +1 -0
  70. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  71. package/dist/hooks/use-copilot-authenticated-action.mjs +3 -3
  72. package/dist/hooks/use-copilot-chat.d.ts +1 -1
  73. package/dist/hooks/use-copilot-chat.js +15 -1
  74. package/dist/hooks/use-copilot-chat.js.map +1 -1
  75. package/dist/hooks/use-copilot-chat.mjs +6 -6
  76. package/dist/hooks/use-copilot-readable.js +1 -0
  77. package/dist/hooks/use-copilot-readable.js.map +1 -1
  78. package/dist/hooks/use-copilot-readable.mjs +2 -2
  79. package/dist/hooks/use-langgraph-interrupt-render.js +1 -0
  80. package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -1
  81. package/dist/hooks/use-langgraph-interrupt-render.mjs +2 -2
  82. package/dist/hooks/use-langgraph-interrupt.d.ts +1 -1
  83. package/dist/hooks/use-langgraph-interrupt.js +15 -1
  84. package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
  85. package/dist/hooks/use-langgraph-interrupt.mjs +7 -7
  86. package/dist/hooks/use-make-copilot-document-readable.js +1 -0
  87. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  88. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  89. package/dist/hooks/use-tree.d.ts +1 -0
  90. package/dist/hooks/use-tree.js +4 -1
  91. package/dist/hooks/use-tree.js.map +1 -1
  92. package/dist/hooks/use-tree.mjs +1 -1
  93. package/dist/index.d.ts +2 -2
  94. package/dist/index.js +26 -3
  95. package/dist/index.js.map +1 -1
  96. package/dist/index.mjs +16 -16
  97. package/dist/lib/copilot-task.d.ts +1 -1
  98. package/dist/lib/copilot-task.js.map +1 -1
  99. package/dist/lib/copilot-task.mjs +5 -5
  100. package/dist/lib/index.d.ts +1 -1
  101. package/dist/lib/index.js.map +1 -1
  102. package/dist/lib/index.mjs +5 -5
  103. package/dist/types/interrupt-action.d.ts +1 -1
  104. package/dist/utils/extract.d.ts +1 -1
  105. package/dist/utils/extract.js.map +1 -1
  106. package/dist/utils/extract.mjs +4 -4
  107. package/dist/utils/index.d.ts +1 -1
  108. package/dist/utils/index.js.map +1 -1
  109. package/dist/utils/index.mjs +4 -4
  110. package/package.json +3 -3
  111. package/src/components/copilot-provider/copilotkit.tsx +6 -1
  112. package/src/context/copilot-context.tsx +4 -1
  113. package/src/hooks/index.ts +1 -0
  114. package/src/hooks/use-chat.ts +17 -2
  115. package/src/hooks/use-coagent.ts +4 -0
  116. package/src/hooks/use-tree.ts +6 -1
  117. package/dist/chunk-6U3UH3KO.mjs.map +0 -1
  118. package/dist/chunk-7WG4MNRX.mjs.map +0 -1
  119. package/dist/chunk-AW2AIX74.mjs.map +0 -1
  120. package/dist/chunk-D5NLDVW2.mjs.map +0 -1
  121. package/dist/chunk-O54FEOCV.mjs.map +0 -1
  122. /package/dist/{chunk-4EXRQ5D5.mjs.map → chunk-2J3SMMGW.mjs.map} +0 -0
  123. /package/dist/{chunk-B3CERZDI.mjs.map → chunk-B5UA5G3E.mjs.map} +0 -0
  124. /package/dist/{chunk-XRCQULYN.mjs.map → chunk-D6CQVQI6.mjs.map} +0 -0
  125. /package/dist/{chunk-W3QHAZKD.mjs.map → chunk-EQ4XLLT4.mjs.map} +0 -0
  126. /package/dist/{chunk-2ZKWBDBN.mjs.map → chunk-FGBRHBRR.mjs.map} +0 -0
  127. /package/dist/{chunk-INRN7B2F.mjs.map → chunk-G27C5EFO.mjs.map} +0 -0
  128. /package/dist/{chunk-KQPKROYS.mjs.map → chunk-IHYG57NB.mjs.map} +0 -0
  129. /package/dist/{chunk-VYSR3S2A.mjs.map → chunk-NTR5KV42.mjs.map} +0 -0
  130. /package/dist/{chunk-YXPFUKGZ.mjs.map → chunk-PLA6FXVD.mjs.map} +0 -0
  131. /package/dist/{chunk-GBAZTXPQ.mjs.map → chunk-VQ3VTO26.mjs.map} +0 -0
  132. /package/dist/{chunk-OSVDTMKA.mjs.map → chunk-WZAEVHLK.mjs.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # ui
2
2
 
3
+ ## 1.8.14-next.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [34a78d8]
8
+ - @copilotkit/shared@1.8.14-next.1
9
+ - @copilotkit/runtime-client-gql@1.8.14-next.1
10
+
11
+ ## 1.8.14-next.0
12
+
13
+ ### Patch Changes
14
+
15
+ - 9cf1fda: - fix append follow-up when actions disable followUp
16
+ - Create stupid-nails-travel.md
17
+ - fixup
18
+ - 9cf1fda: - fix append follow-up when actions disable followUp
19
+ - @copilotkit/runtime-client-gql@1.8.14-next.0
20
+ - @copilotkit/shared@1.8.14-next.0
21
+
3
22
  ## 1.8.13
4
23
 
5
24
  ### Patch Changes
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useCopilotContext
3
- } from "./chunk-7WG4MNRX.mjs";
3
+ } from "./chunk-ERFA53MG.mjs";
4
4
 
5
5
  // src/hooks/use-copilot-additional-instructions.ts
6
6
  import { useEffect } from "react";
@@ -21,4 +21,4 @@ function useCopilotAdditionalInstructions({ instructions, available = "enabled"
21
21
  export {
22
22
  useCopilotAdditionalInstructions
23
23
  };
24
- //# sourceMappingURL=chunk-4EXRQ5D5.mjs.map
24
+ //# sourceMappingURL=chunk-2J3SMMGW.mjs.map
@@ -15,7 +15,7 @@ import {
15
15
  } from "./chunk-SKC7AJIV.mjs";
16
16
 
17
17
  // src/hooks/use-chat.ts
18
- import { useCallback, useRef } from "react";
18
+ import { useCallback, useEffect, useRef } from "react";
19
19
  import {
20
20
  COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,
21
21
  randomId,
@@ -81,6 +81,7 @@ function useChat(options) {
81
81
  headers,
82
82
  credentials: copilotConfig.credentials
83
83
  });
84
+ const pendingAppendsRef = useRef([]);
84
85
  const runChatCompletion = useAsyncCallback(
85
86
  (previousMessages) => __async(this, null, function* () {
86
87
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
@@ -413,6 +414,17 @@ function useChat(options) {
413
414
  }),
414
415
  [messages]
415
416
  );
417
+ useEffect(() => {
418
+ if (!isLoading && pendingAppendsRef.current.length > 0) {
419
+ const pending = pendingAppendsRef.current.splice(0);
420
+ const followUp = pending.some((p) => p.followUp);
421
+ const newMessages = [...messages, ...pending.map((p) => p.message)];
422
+ setMessages(newMessages);
423
+ if (followUp) {
424
+ runChatCompletionAndHandleFunctionCall(newMessages);
425
+ }
426
+ }
427
+ }, [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);
416
428
  const composeAndFlushMetaEventsInput = useCallback(
417
429
  (metaEvents) => {
418
430
  return metaEvents.reduce((acc, event) => {
@@ -443,12 +455,13 @@ function useChat(options) {
443
455
  const append = useAsyncCallback(
444
456
  (message, options2) => __async(this, null, function* () {
445
457
  var _a;
458
+ const followUp = (_a = options2 == null ? void 0 : options2.followUp) != null ? _a : true;
446
459
  if (isLoading) {
460
+ pendingAppendsRef.current.push({ message, followUp });
447
461
  return;
448
462
  }
449
463
  const newMessages = [...messages, message];
450
464
  setMessages(newMessages);
451
- const followUp = (_a = options2 == null ? void 0 : options2.followUp) != null ? _a : true;
452
465
  if (followUp) {
453
466
  return runChatCompletionAndHandleFunctionCall(newMessages);
454
467
  }
@@ -567,4 +580,4 @@ function getPairedFeAction(actions, message) {
567
580
  export {
568
581
  useChat
569
582
  };
570
- //# sourceMappingURL=chunk-AW2AIX74.mjs.map
583
+ //# sourceMappingURL=chunk-74AJEJTV.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-chat.ts"],"sourcesContent":["import React, { useCallback, useEffect, useRef } from \"react\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n CoAgentStateRenderHandler,\n randomId,\n parseJson,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ResultMessage,\n convertMessagesToGqlInput,\n filterAdjacentAgentStateMessages,\n filterAgentStateMessages,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n ForwardedParametersInput,\n loadMessagesFromJsonRepresentation,\n ExtensionsInput,\n CopilotRuntimeClient,\n langGraphInterruptEvent,\n MetaEvent,\n MetaEventName,\n ActionExecutionMessage,\n CopilotKitLangGraphInterruptEvent,\n LangGraphInterruptEvent,\n MetaEventInput,\n AgentStateInput,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\nimport { FrontendAction, processActionsForRuntimeRequest } from \"../types/frontend-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { AgentSession } from \"../context/copilot-context\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nimport { useAsyncCallback, useErrorToast } from \"../components/error-boundary/error-utils\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetter,\n} from \"../types/interrupt-action\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n\n /**\n * Callback function to be called when a coagent action is received.\n */\n onCoAgentStateRender?: CoAgentStateRenderHandler;\n\n /**\n * Function definitions to be sent to the API.\n */\n actions: FrontendAction<any>[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n /**\n * The current list of coagent states.\n */\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n\n /**\n * setState-powered method to update the agent states\n */\n setCoagentStatesWithRef: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n\n /**\n * The current agent session.\n */\n agentSession: AgentSession | null;\n\n /**\n * setState-powered method to update the agent session\n */\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n /**\n * The forwarded parameters.\n */\n forwardedParameters?: Pick<ForwardedParametersInput, \"temperature\">;\n\n /**\n * The current thread ID.\n */\n threadId: string;\n /**\n * set the current thread ID\n */\n setThreadId: (threadId: string) => void;\n /**\n * The current run ID.\n */\n runId: string | null;\n /**\n * set the current run ID\n */\n setRunId: (runId: string | null) => void;\n /**\n * The global chat abort controller.\n */\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n /**\n * The agent lock.\n */\n agentLock: string | null;\n /**\n * The extensions.\n */\n extensions: ExtensionsInput;\n /**\n * The setState-powered method to update the extensions.\n */\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n\n langGraphInterruptAction: LangGraphInterruptAction | null;\n\n setLangGraphInterruptAction: LangGraphInterruptActionSetter;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (messageId: string) => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * Run the chat completion.\n */\n runChatCompletion: () => Promise<Message[]>;\n};\n\nexport interface AppendMessageOptions {\n /**\n * Whether to run the chat completion after appending the message. Defaults to `true`.\n */\n followUp?: boolean;\n}\n\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoAgentStateRender,\n setCoagentStatesWithRef,\n coagentStatesRef,\n agentSession,\n setAgentSession,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n agentLock,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n } = options;\n const runChatCompletionRef = useRef<(previousMessages: Message[]) => Promise<Message[]>>();\n const addErrorToast = useErrorToast();\n // We need to keep a ref of coagent states and session because of renderAndWait - making sure\n // the latest state is sent to the API\n // This is a workaround and needs to be addressed in the future\n const agentSessionRef = useRef<AgentSession | null>(agentSession);\n agentSessionRef.current = agentSession;\n\n const runIdRef = useRef<string | null>(runId);\n runIdRef.current = runId;\n const extensionsRef = useRef<ExtensionsInput>(extensions);\n extensionsRef.current = extensions;\n\n const publicApiKey = copilotConfig.publicApiKey;\n\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n });\n\n const pendingAppendsRef = useRef<{ message: Message; followUp: boolean }[]>([]);\n\n const runChatCompletion = useAsyncCallback(\n async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n const interruptEvent = langGraphInterruptAction?.event;\n // In case an interrupt event exist and valid but has no response yet, we cannot process further messages to an agent\n if (\n interruptEvent?.name === MetaEventName.LangGraphInterruptEvent &&\n interruptEvent?.value &&\n !interruptEvent?.response &&\n agentSessionRef.current\n ) {\n addErrorToast([\n new Error(\n \"A message was sent while interrupt is active. This will cause failure on the agent side\",\n ),\n ]);\n }\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n\n chatAbortControllerRef.current = new AbortController();\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n // ----- Set mcpServers in properties -----\n // Create a copy of properties to avoid modifying the original object\n const finalProperties = { ...(copilotConfig.properties || {}) };\n\n // Look for mcpServers in either direct property or properties\n let mcpServersToUse = null;\n\n // First check direct mcpServers property\n if (\n copilotConfig.mcpServers &&\n Array.isArray(copilotConfig.mcpServers) &&\n copilotConfig.mcpServers.length > 0\n ) {\n mcpServersToUse = copilotConfig.mcpServers;\n }\n // Then check mcpServers in properties\n else if (\n copilotConfig.properties?.mcpServers &&\n Array.isArray(copilotConfig.properties.mcpServers) &&\n copilotConfig.properties.mcpServers.length > 0\n ) {\n mcpServersToUse = copilotConfig.properties.mcpServers;\n }\n\n // Apply the mcpServers to properties if found\n if (mcpServersToUse) {\n // Set in finalProperties\n finalProperties.mcpServers = mcpServersToUse;\n\n // Also set in copilotConfig directly for future use\n copilotConfig.mcpServers = mcpServersToUse;\n }\n // -------------------------------------------------------------\n\n const isAgentRun = agentSessionRef.current !== null;\n\n const stream = runtimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(actions),\n url: window.location.href,\n },\n threadId: threadId,\n runId: runIdRef.current,\n extensions: extensionsRef.current,\n metaEvents: composeAndFlushMetaEventsInput([langGraphInterruptAction?.event]),\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messagesWithContext)),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n ...(copilotConfig.cloud.guardrails?.input?.restrictToTopic?.enabled\n ? {\n guardrails: {\n inputValidationRules: {\n allowList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n }\n : {}),\n },\n }\n : {}),\n metadata: {\n requestType: CopilotRequestType.Chat,\n },\n ...(agentSessionRef.current\n ? {\n agentSession: agentSessionRef.current,\n }\n : {}),\n agentStates: Object.values(coagentStatesRef.current!).map((state) => {\n const stateObject: AgentStateInput = {\n agentName: state.name,\n state: JSON.stringify(state.state),\n };\n\n if (state.config !== undefined) {\n stateObject.config = JSON.stringify(state.config);\n }\n\n return stateObject;\n }),\n forwardedParameters: options.forwardedParameters || {},\n },\n properties: finalProperties,\n signal: chatAbortControllerRef.current?.signal,\n }),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let executedCoAgentStateRenders: string[] = [];\n let followUp: FrontendAction[\"followUp\"] = undefined;\n\n let messages: Message[] = [];\n let syncedMessages: Message[] = [];\n let interruptMessages: Message[] = [];\n\n try {\n while (true) {\n let done, value;\n\n try {\n const readResult = await reader.read();\n done = readResult.done;\n value = readResult.value;\n } catch (readError) {\n break;\n }\n\n if (done) {\n if (chatAbortControllerRef.current.signal.aborted) {\n return [];\n }\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n // in the output, graphql inserts __typename, which leads to an error when sending it along\n // as input to the next request.\n extensionsRef.current = CopilotRuntimeClient.removeGraphQLTypename(\n value.generateCopilotResponse.extensions || {},\n );\n\n // setThreadId(threadIdRef.current);\n setRunId(runIdRef.current);\n setExtensions(extensionsRef.current);\n let rawMessagesResponse = value.generateCopilotResponse.messages;\n\n const metaEvents: MetaEvent[] | undefined =\n value.generateCopilotResponse?.metaEvents ?? [];\n (metaEvents ?? []).forEach((ev) => {\n if (ev.name === MetaEventName.LangGraphInterruptEvent) {\n let eventValue = langGraphInterruptEvent(ev as LangGraphInterruptEvent).value;\n eventValue = parseJson(eventValue, eventValue);\n setLangGraphInterruptAction({\n event: {\n ...langGraphInterruptEvent(ev as LangGraphInterruptEvent),\n value: eventValue,\n },\n });\n }\n if (ev.name === MetaEventName.CopilotKitLangGraphInterruptEvent) {\n const data = (ev as CopilotKitLangGraphInterruptEvent).data;\n\n // @ts-expect-error -- same type of messages\n rawMessagesResponse = [...rawMessagesResponse, ...data.messages];\n interruptMessages = convertGqlOutputToMessages(\n // @ts-ignore\n filterAdjacentAgentStateMessages(data.messages),\n );\n }\n });\n\n messages = convertGqlOutputToMessages(\n filterAdjacentAgentStateMessages(rawMessagesResponse),\n );\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message and quit\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n setMessages([...previousMessages, ...newMessages]);\n break;\n }\n\n // add messages to the chat\n else {\n newMessages = [...messages];\n\n for (const message of messages) {\n // execute onCoAgentStateRender handler\n if (\n message.isAgentStateMessage() &&\n !message.active &&\n !executedCoAgentStateRenders.includes(message.id) &&\n onCoAgentStateRender\n ) {\n // Do not execute a coagent action if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute coagent action\n await onCoAgentStateRender({\n name: message.agentName,\n nodeName: message.nodeName,\n state: message.state,\n });\n executedCoAgentStateRenders.push(message.id);\n }\n }\n\n const lastAgentStateMessage = [...messages]\n .reverse()\n .find((message) => message.isAgentStateMessage());\n\n if (lastAgentStateMessage) {\n if (\n lastAgentStateMessage.state.messages &&\n lastAgentStateMessage.state.messages.length > 0\n ) {\n syncedMessages = loadMessagesFromJsonRepresentation(\n lastAgentStateMessage.state.messages,\n );\n }\n setCoagentStatesWithRef((prevAgentStates) => ({\n ...prevAgentStates,\n [lastAgentStateMessage.agentName]: {\n name: lastAgentStateMessage.agentName,\n state: lastAgentStateMessage.state,\n running: lastAgentStateMessage.running,\n active: lastAgentStateMessage.active,\n threadId: lastAgentStateMessage.threadId,\n nodeName: lastAgentStateMessage.nodeName,\n runId: lastAgentStateMessage.runId,\n },\n }));\n if (lastAgentStateMessage.running) {\n setAgentSession({\n threadId: lastAgentStateMessage.threadId,\n agentName: lastAgentStateMessage.agentName,\n nodeName: lastAgentStateMessage.nodeName,\n });\n } else {\n if (agentLock) {\n setAgentSession({\n threadId: randomId(),\n agentName: agentLock,\n nodeName: undefined,\n });\n } else {\n setAgentSession(null);\n }\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Update message state\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n let finalMessages = constructFinalMessages(\n [...syncedMessages, ...interruptMessages],\n previousMessages,\n newMessages,\n );\n\n let didExecuteAction = false;\n\n // execute regular action executions that are specific to the frontend (last actions)\n if (onFunctionCall) {\n // Find consecutive action execution messages at the end\n const lastMessages = [];\n\n for (let i = finalMessages.length - 1; i >= 0; i--) {\n const message = finalMessages[i];\n if (\n (message.isActionExecutionMessage() || message.isResultMessage()) &&\n message.status.code !== MessageStatusCode.Pending\n ) {\n lastMessages.unshift(message);\n } else if (!message.isAgentStateMessage()) {\n break;\n }\n }\n\n for (const message of lastMessages) {\n // We update the message state before calling the handler so that the render\n // function can be called with `executing` state\n setMessages(finalMessages);\n\n const action = actions.find(\n (action) => action.name === (message as ActionExecutionMessage).name,\n );\n const currentResultMessagePairedFeAction = message.isResultMessage()\n ? getPairedFeAction(actions, message)\n : null;\n\n const executeActionFromMessage = async (\n action: FrontendAction<any>,\n message: ActionExecutionMessage,\n ) => {\n const isInterruptAction = interruptMessages.find((m) => m.id === message.id);\n followUp = action?.followUp ?? !isInterruptAction;\n const resultMessage = await executeAction({\n onFunctionCall,\n previousMessages,\n message,\n chatAbortControllerRef,\n onError: (error: Error) => {\n addErrorToast([error]);\n console.error(`Failed to execute action ${message.name}: ${error}`);\n },\n });\n didExecuteAction = true;\n const messageIndex = finalMessages.findIndex((msg) => msg.id === message.id);\n finalMessages.splice(messageIndex + 1, 0, resultMessage);\n\n return resultMessage;\n };\n\n // execution message which has an action registered with the hook (remote availability):\n // execute that action first, and then the \"paired FE action\"\n if (action && message.isActionExecutionMessage()) {\n const resultMessage = await executeActionFromMessage(action, message);\n const pairedFeAction = getPairedFeAction(actions, resultMessage);\n\n if (pairedFeAction) {\n const newExecutionMessage = new ActionExecutionMessage({\n name: pairedFeAction.name,\n arguments: parseJson(resultMessage.result, resultMessage.result),\n status: message.status,\n createdAt: message.createdAt,\n parentMessageId: message.parentMessageId,\n });\n await executeActionFromMessage(pairedFeAction, newExecutionMessage);\n }\n } else if (message.isResultMessage() && currentResultMessagePairedFeAction) {\n // Actions which are set up in runtime actions array: Grab the result, executed paired FE action with it as args.\n const newExecutionMessage = new ActionExecutionMessage({\n name: currentResultMessagePairedFeAction.name,\n arguments: parseJson(message.result, message.result),\n status: message.status,\n createdAt: message.createdAt,\n });\n finalMessages.push(newExecutionMessage);\n await executeActionFromMessage(\n currentResultMessagePairedFeAction,\n newExecutionMessage,\n );\n }\n }\n\n setMessages(finalMessages);\n }\n\n if (\n // if followUp is not explicitly false\n followUp !== false &&\n // and we executed an action\n (didExecuteAction ||\n // the last message is a server side result\n (!isAgentRun &&\n finalMessages.length &&\n finalMessages[finalMessages.length - 1].isResultMessage())) &&\n // the user did not stop generation\n !chatAbortControllerRef.current?.signal.aborted\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletionRef.current!(finalMessages);\n } else if (chatAbortControllerRef.current?.signal.aborted) {\n // filter out all the action execution messages that do not have a consecutive matching result message\n const repairedMessages = finalMessages.filter((message, actionExecutionIndex) => {\n if (message.isActionExecutionMessage()) {\n return finalMessages.find(\n (msg, resultIndex) =>\n msg.isResultMessage() &&\n msg.actionExecutionId === message.id &&\n resultIndex === actionExecutionIndex + 1,\n );\n }\n return true;\n });\n const repairedMessageIds = repairedMessages.map((message) => message.id);\n setMessages(repairedMessages);\n\n // LangGraph needs two pieces of information to continue execution:\n // 1. The threadId\n // 2. The nodeName it came from\n // When stopping the agent, we don't know the nodeName the agent would have ended with\n // Therefore, we set the nodeName to the most reasonable thing we can guess, which\n // is \"__end__\"\n if (agentSessionRef.current?.nodeName) {\n setAgentSession({\n threadId: agentSessionRef.current.threadId,\n agentName: agentSessionRef.current.agentName,\n nodeName: \"__end__\",\n });\n }\n // only return new messages that were not filtered out\n return newMessages.filter((message) => repairedMessageIds.includes(message.id));\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n },\n [\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoAgentStateRender,\n setCoagentStatesWithRef,\n coagentStatesRef,\n agentSession,\n setAgentSession,\n ],\n );\n\n runChatCompletionRef.current = runChatCompletion;\n\n const runChatCompletionAndHandleFunctionCall = useAsyncCallback(\n async (messages: Message[]): Promise<void> => {\n await runChatCompletionRef.current!(messages);\n },\n [messages],\n );\n\n useEffect(() => {\n if (!isLoading && pendingAppendsRef.current.length > 0) {\n const pending = pendingAppendsRef.current.splice(0);\n const followUp = pending.some((p) => p.followUp);\n const newMessages = [...messages, ...pending.map((p) => p.message)];\n setMessages(newMessages);\n if (followUp) {\n runChatCompletionAndHandleFunctionCall(newMessages);\n }\n }\n }, [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);\n\n // Go over all events and see that they include data that should be returned to the agent\n const composeAndFlushMetaEventsInput = useCallback(\n (metaEvents: (MetaEvent | undefined | null)[]) => {\n return metaEvents.reduce((acc: MetaEventInput[], event) => {\n if (!event) return acc;\n\n switch (event.name) {\n case MetaEventName.LangGraphInterruptEvent:\n if (event.response) {\n // Flush interrupt event from state\n setLangGraphInterruptAction(null);\n const value = (event as LangGraphInterruptEvent).value;\n return [\n ...acc,\n {\n name: event.name,\n value: typeof value === \"string\" ? value : JSON.stringify(value),\n response:\n typeof event.response === \"string\"\n ? event.response\n : JSON.stringify(event.response),\n },\n ];\n }\n return acc;\n default:\n return acc;\n }\n }, []);\n },\n [setLangGraphInterruptAction],\n );\n\n const append = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions): Promise<void> => {\n const followUp = options?.followUp ?? true;\n if (isLoading) {\n pendingAppendsRef.current.push({ message, followUp });\n return;\n }\n\n const newMessages = [...messages, message];\n setMessages(newMessages);\n if (followUp) {\n return runChatCompletionAndHandleFunctionCall(newMessages);\n }\n },\n [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall],\n );\n\n const reload = useAsyncCallback(\n async (messageId: string): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n\n const index = messages.findIndex((msg) => msg.id === messageId);\n if (index === -1) {\n console.warn(`Message with id ${messageId} not found`);\n return;\n }\n\n let newMessages = messages.slice(0, index); // excludes the message with messageId\n if (newMessages.length > 0 && newMessages[newMessages.length - 1].isAgentStateMessage()) {\n newMessages = newMessages.slice(0, newMessages.length - 1); // remove last one too\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n },\n [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall],\n );\n\n const stop = (): void => {\n chatAbortControllerRef.current?.abort(\"Stop was called\");\n };\n\n return {\n append,\n reload,\n stop,\n runChatCompletion: () => runChatCompletionRef.current!(messages),\n };\n}\n\nfunction constructFinalMessages(\n syncedMessages: Message[],\n previousMessages: Message[],\n newMessages: Message[],\n): Message[] {\n const finalMessages =\n syncedMessages.length > 0 ? [...syncedMessages] : [...previousMessages, ...newMessages];\n\n if (syncedMessages.length > 0) {\n const messagesWithAgentState = [...previousMessages, ...newMessages];\n\n let previousMessageId: string | undefined = undefined;\n\n for (const message of messagesWithAgentState) {\n if (message.isAgentStateMessage()) {\n // insert this message into finalMessages after the position of previousMessageId\n const index = finalMessages.findIndex((msg) => msg.id === previousMessageId);\n if (index !== -1) {\n finalMessages.splice(index + 1, 0, message);\n }\n }\n\n previousMessageId = message.id;\n }\n }\n\n return finalMessages;\n}\n\nasync function executeAction({\n onFunctionCall,\n previousMessages,\n message,\n chatAbortControllerRef,\n onError,\n}: {\n onFunctionCall: FunctionCallHandler;\n previousMessages: Message[];\n message: ActionExecutionMessage;\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n onError: (error: Error) => void;\n}) {\n let result: any;\n let error: Error | null = null;\n try {\n result = await Promise.race([\n onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n }),\n new Promise((resolve) =>\n chatAbortControllerRef.current?.signal.addEventListener(\"abort\", () =>\n resolve(\"Operation was aborted by the user\"),\n ),\n ),\n // if the user stopped generation, we also abort consecutive actions\n new Promise((resolve) => {\n if (chatAbortControllerRef.current?.signal.aborted) {\n resolve(\"Operation was aborted by the user\");\n }\n }),\n ]);\n } catch (e) {\n onError(e as Error);\n }\n return new ResultMessage({\n id: \"result-\" + message.id,\n result: ResultMessage.encodeResult(\n error\n ? {\n content: result,\n error: JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error))),\n }\n : result,\n ),\n actionExecutionId: message.id,\n actionName: message.name,\n });\n}\n\nfunction getPairedFeAction(\n actions: FrontendAction<any>[],\n message: ActionExecutionMessage | ResultMessage,\n) {\n let actionName = null;\n if (message.isActionExecutionMessage()) {\n actionName = message.name;\n } else if (message.isResultMessage()) {\n actionName = message.actionName;\n }\n return actions.find(\n (action) =>\n (action.name === actionName && action.available === \"frontend\") ||\n action.pairedAction === actionName,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;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AA,IACtB,CAAC;AAAA,EACH;AAAA;AAEA,SAAS,kBACP,SACA,SACA;AACA,MAAI,aAAa;AACjB,MAAI,QAAQ,yBAAyB,GAAG;AACtC,iBAAa,QAAQ;AAAA,EACvB,WAAW,QAAQ,gBAAgB,GAAG;AACpC,iBAAa,QAAQ;AAAA,EACvB;AACA,SAAO,QAAQ;AAAA,IACb,CAAC,WACE,OAAO,SAAS,cAAc,OAAO,cAAc,cACpD,OAAO,iBAAiB;AAAA,EAC5B;AACF;","names":["messages","action","message","_a","options"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  CopilotContext
3
- } from "./chunk-7WG4MNRX.mjs";
3
+ } from "./chunk-ERFA53MG.mjs";
4
4
  import {
5
5
  useToast
6
6
  } from "./chunk-22ENANUU.mjs";
@@ -81,4 +81,4 @@ function useCoAgentStateRender(action, dependencies) {
81
81
  export {
82
82
  useCoAgentStateRender
83
83
  };
84
- //# sourceMappingURL=chunk-B3CERZDI.mjs.map
84
+ //# sourceMappingURL=chunk-B5UA5G3E.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  defaultCopilotContextCategories
3
- } from "./chunk-O54FEOCV.mjs";
3
+ } from "./chunk-WYCLVOYC.mjs";
4
4
  import {
5
5
  processActionsForRuntimeRequest
6
6
  } from "./chunk-4CEQJ2X6.mjs";
@@ -117,4 +117,4 @@ ${instructions}
117
117
  export {
118
118
  CopilotTask
119
119
  };
120
- //# sourceMappingURL=chunk-XRCQULYN.mjs.map
120
+ //# sourceMappingURL=chunk-D6CQVQI6.mjs.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  useCopilotAction
3
- } from "./chunk-INRN7B2F.mjs";
3
+ } from "./chunk-G27C5EFO.mjs";
4
4
  import {
5
5
  useCopilotContext
6
- } from "./chunk-7WG4MNRX.mjs";
6
+ } from "./chunk-ERFA53MG.mjs";
7
7
  import {
8
8
  __spreadProps,
9
9
  __spreadValues
@@ -56,4 +56,4 @@ function useCopilotAuthenticatedAction_c(action, dependencies) {
56
56
  export {
57
57
  useCopilotAuthenticatedAction_c
58
58
  };
59
- //# sourceMappingURL=chunk-W3QHAZKD.mjs.map
59
+ //# sourceMappingURL=chunk-EQ4XLLT4.mjs.map
@@ -20,6 +20,7 @@ var emptyCopilotContext = {
20
20
  addContext: () => "",
21
21
  removeContext: () => {
22
22
  },
23
+ getAllContext: () => [],
23
24
  getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
24
25
  })),
25
26
  isLoading: false,
@@ -92,4 +93,4 @@ export {
92
93
  CopilotContext,
93
94
  useCopilotContext
94
95
  };
95
- //# sourceMappingURL=chunk-7WG4MNRX.mjs.map
96
+ //# sourceMappingURL=chunk-ERFA53MG.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context/copilot-context.tsx"],"sourcesContent":["import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId, Tree } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport { CoAgentStateRender, CoAgentStateRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport {\n CopilotRuntimeClient,\n ExtensionsInput,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetter,\n} from \"../types/interrupt-action\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n\n /**\n * Optional configuration for connecting to Model Context Protocol (MCP) servers.\n * This is typically derived from the CopilotKitProps and used internally.\n * @experimental\n */\n mcpServers?: Array<{ endpoint: string; apiKey?: string }>;\n}\n\nexport type InChatRenderFunction<TProps = ActionRenderProps<any> | CatchAllActionRenderProps<any>> =\n (props: TProps) => string | JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | JSX.Element | undefined | null;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface AuthState {\n status: \"authenticated\" | \"unauthenticated\";\n authHeaders: Record<string, string>;\n userId?: string;\n metadata?: Record<string, any>;\n}\n\nexport type ActionName = string;\nexport type ContextTree = Tree;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // coagent actions\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (id: string, stateRender: CoAgentStateRender<any>) => void;\n removeCoAgentStateRender: (id: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getAllContext: () => Tree;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n additionalInstructions?: string[];\n setAdditionalInstructions: React.Dispatch<React.SetStateAction<string[]>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean | \"auto\";\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n setCoagentStatesWithRef: (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => void;\n\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n agentLock: string | null;\n\n threadId: string;\n setThreadId: React.Dispatch<React.SetStateAction<string>>;\n\n runId: string | null;\n setRunId: React.Dispatch<React.SetStateAction<string | null>>;\n\n // The chat abort controller can be used to stop generation globally,\n // i.e. when using `stop()` from `useChat`\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n\n // runtime\n runtimeClient: CopilotRuntimeClient;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Pick<ForwardedParametersInput, \"temperature\">;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates_c?: Record<ActionName, AuthState>;\n setAuthStates_c?: React.Dispatch<React.SetStateAction<Record<ActionName, AuthState>>>;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig_c?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n extensions: ExtensionsInput;\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n langGraphInterruptAction: LangGraphInterruptAction | null;\n setLangGraphInterruptAction: LangGraphInterruptActionSetter;\n removeLangGraphInterruptAction: () => void;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coAgentStateRenders: {},\n setCoAgentStateRender: () => {},\n removeCoAgentStateRender: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n getAllContext: () => [],\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n additionalInstructions: [],\n setAdditionalInstructions: () => returnAndThrowInDebug([]),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n runtimeClient: {} as any,\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: \"auto\",\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n agentSession: null,\n setAgentSession: () => {},\n forwardedParameters: {},\n agentLock: null,\n threadId: \"\",\n setThreadId: () => {},\n runId: null,\n setRunId: () => {},\n chatAbortControllerRef: { current: null },\n availableAgents: [],\n extensions: {},\n setExtensions: () => {},\n langGraphInterruptAction: null,\n setLangGraphInterruptAction: () => null,\n removeLangGraphInterruptAction: () => null,\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n}\n"],"mappings":";;;;;AAMA,OAAO,WAAW;AAwNlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,CAAC;AAAA,EACtB,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAC9B,0BAA0B,MAAM;AAAA,EAAC;AAAA,EAEjC,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,qBAAqB,CAAC,EAAE,EAAE;AAAA,EACzE,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,eAAe,MAAM,CAAC;AAAA,EAEtB,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qBAAqB,MAAM,s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AAM,UAAU,MAAM,WAAW,cAAc;AAC/C,MAAI,YAAY,qBAAqB;AACnC,UAAM,IAAI,MAAM,uEAAuE;AAAA,EACzF;AACA,SAAO;AACT;AAEA,SAAS,sBAAyB,QAAc;AAC9C,QAAM,IAAI,MAAM,uEAAuE;AACzF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useCopilotContext
3
- } from "./chunk-7WG4MNRX.mjs";
3
+ } from "./chunk-ERFA53MG.mjs";
4
4
 
5
5
  // src/hooks/use-copilot-readable.ts
6
6
  import { useEffect, useRef } from "react";
@@ -34,4 +34,4 @@ function useCopilotReadable({
34
34
  export {
35
35
  useCopilotReadable
36
36
  };
37
- //# sourceMappingURL=chunk-2ZKWBDBN.mjs.map
37
+ //# sourceMappingURL=chunk-FGBRHBRR.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useCopilotContext
3
- } from "./chunk-7WG4MNRX.mjs";
3
+ } from "./chunk-ERFA53MG.mjs";
4
4
  import {
5
5
  useAsyncCallback,
6
6
  useToast
@@ -118,4 +118,4 @@ function isFrontendAction(action) {
118
118
  export {
119
119
  useCopilotAction
120
120
  };
121
- //# sourceMappingURL=chunk-INRN7B2F.mjs.map
121
+ //# sourceMappingURL=chunk-G27C5EFO.mjs.map
@@ -1,15 +1,15 @@
1
1
  import {
2
2
  defaultCopilotContextCategories
3
- } from "./chunk-O54FEOCV.mjs";
3
+ } from "./chunk-WYCLVOYC.mjs";
4
4
  import {
5
5
  useCopilotContext
6
- } from "./chunk-7WG4MNRX.mjs";
6
+ } from "./chunk-ERFA53MG.mjs";
7
7
  import {
8
8
  useCopilotMessagesContext
9
9
  } from "./chunk-DCTJZ742.mjs";
10
10
  import {
11
11
  useChat
12
- } from "./chunk-AW2AIX74.mjs";
12
+ } from "./chunk-74AJEJTV.mjs";
13
13
  import {
14
14
  useAsyncCallback
15
15
  } from "./chunk-22ENANUU.mjs";
@@ -240,4 +240,4 @@ export {
240
240
  useCopilotChat,
241
241
  defaultSystemMessage
242
242
  };
243
- //# sourceMappingURL=chunk-KQPKROYS.mjs.map
243
+ //# sourceMappingURL=chunk-IHYG57NB.mjs.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  useCopilotChat
3
- } from "./chunk-KQPKROYS.mjs";
3
+ } from "./chunk-IHYG57NB.mjs";
4
4
  import {
5
5
  useCopilotContext
6
- } from "./chunk-7WG4MNRX.mjs";
6
+ } from "./chunk-ERFA53MG.mjs";
7
7
  import {
8
8
  useCopilotMessagesContext
9
9
  } from "./chunk-DCTJZ742.mjs";
@@ -41,9 +41,11 @@ function useCoAgent(options) {
41
41
  const context = __spreadValues(__spreadValues({}, generalContext), messagesContext);
42
42
  const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } = context;
43
43
  const { appendMessage, runChatCompletion } = useCopilotChat();
44
+ const headers = __spreadValues({}, copilotApiConfig.headers || {});
44
45
  const runtimeClient = useCopilotRuntimeClient({
45
46
  url: copilotApiConfig.chatApiEndpoint,
46
47
  publicApiKey: copilotApiConfig.publicApiKey,
48
+ headers,
47
49
  credentials: copilotApiConfig.credentials
48
50
  });
49
51
  const setState = useCallback(
@@ -198,4 +200,4 @@ export {
198
200
  stopAgent,
199
201
  runAgent
200
202
  };
201
- //# sourceMappingURL=chunk-D5NLDVW2.mjs.map
203
+ //# sourceMappingURL=chunk-KID3UPGL.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-coagent.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport {\n CopilotContextParams,\n CopilotMessagesContextParams,\n useCopilotContext,\n useCopilotMessagesContext,\n} from \"../context\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { useCopilotChat } from \"./use-copilot-chat\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nimport { parseJson } from \"@copilotkit/shared\";\n\ninterface UseCoagentOptionsBase {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * @deprecated - use \"config.configurable\"\n * Config to pass to a LangGraph Agent\n */\n configurable?: Record<string, any>;\n /**\n * Config to pass to a LangGraph Agent\n */\n config?: {\n configurable?: Record<string, any>;\n [key: string]: any;\n };\n}\n\ninterface WithInternalStateManagementAndInitial<T> extends UseCoagentOptionsBase {\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement extends UseCoagentOptionsBase {\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> extends UseCoagentOptionsBase {\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The name of the current LangGraph node.\n */\n nodeName?: string;\n /**\n * The ID of the thread the agent is running in.\n */\n threadId?: string;\n /**\n * A boolean indicating if the agent is currently running.\n */\n running: boolean;\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n /**\n * A function to start the agent.\n */\n start: () => void;\n /**\n * A function to stop the agent.\n */\n stop: () => void;\n /**\n * A function to re-run the agent. The hint function can be used to provide a hint to the agent\n * about why it is being re-run again.\n */\n run: (hint?: HintFunction) => Promise<void>;\n}\n\nexport interface HintFunctionParams {\n /**\n * The previous state of the agent.\n */\n previousState: any;\n /**\n * The current state of the agent.\n */\n currentState: any;\n}\n\nexport type HintFunction = (params: HintFunctionParams) => Message | undefined;\n\n/**\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of the agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences \"agentic copilots\". To get started using agentic copilots, which\n * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.\n */\nexport function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {\n const generalContext = useCopilotContext();\n const { availableAgents } = generalContext;\n const { addToast } = useToast();\n const lastLoadedThreadId = useRef<string>();\n const lastLoadedState = useRef<any>();\n\n const { name } = options;\n useEffect(() => {\n if (availableAgents?.length && !availableAgents.some((a) => a.name === name)) {\n const message = `(useCoAgent): Agent \"${name}\" not found. Make sure the agent exists and is properly configured.`;\n console.warn(message);\n addToast({ type: \"warning\", message });\n }\n }, [availableAgents]);\n\n const messagesContext = useCopilotMessagesContext();\n const context = { ...generalContext, ...messagesContext };\n const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } =\n context;\n const { appendMessage, runChatCompletion } = useCopilotChat();\n const headers = {\n ...(copilotApiConfig.headers || {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n });\n\n // if we manage state internally, we need to provide a function to set the state\n const setState = useCallback(\n (newState: T | ((prevState: T | undefined) => T)) => {\n // coagentStatesRef.current || {}\n let coagentState: CoagentState = getCoagentState({ coagentStates, name, options });\n const updatedState =\n typeof newState === \"function\" ? (newState as Function)(coagentState.state) : newState;\n\n setCoagentStatesWithRef({\n ...coagentStatesRef.current,\n [name]: {\n ...coagentState,\n state: updatedState,\n },\n });\n },\n [coagentStates, name],\n );\n\n useEffect(() => {\n const fetchAgentState = async () => {\n if (!threadId || threadId === lastLoadedThreadId.current) return;\n\n const result = await runtimeClient.loadAgentState({\n threadId,\n agentName: name,\n });\n\n const newState = result.data?.loadAgentState?.state;\n if (newState === lastLoadedState.current) return;\n\n if (result.data?.loadAgentState?.threadExists && newState && newState != \"{}\") {\n lastLoadedState.current = newState;\n lastLoadedThreadId.current = threadId;\n const fetchedState = parseJson(newState, {});\n isExternalStateManagement(options)\n ? options.setState(fetchedState)\n : setState(fetchedState);\n }\n };\n void fetchAgentState();\n }, [threadId]);\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n setState(options.state);\n } else if (coagentStates[name] === undefined) {\n setState(options.initialState === undefined ? {} : options.initialState);\n }\n }, [\n isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined,\n // reset initialstate on reset\n coagentStates[name] === undefined,\n ]);\n\n const runAgentCallback = useAsyncCallback(\n async (hint?: HintFunction) => {\n await runAgent(name, context, appendMessage, runChatCompletion, hint);\n },\n [name, context, appendMessage, runChatCompletion],\n );\n\n // Return the state and setState function\n return useMemo(() => {\n const coagentState = getCoagentState({ coagentStates, name, options });\n return {\n name,\n nodeName: coagentState.nodeName,\n threadId: coagentState.threadId,\n running: coagentState.running,\n state: coagentState.state,\n setState: isExternalStateManagement(options) ? options.setState : setState,\n start: () => startAgent(name, context),\n stop: () => stopAgent(name, context),\n run: runAgentCallback,\n };\n }, [name, coagentStates, options, setState, runAgentCallback]);\n}\n\nexport function startAgent(name: string, context: CopilotContextParams) {\n const { setAgentSession } = context;\n setAgentSession({\n agentName: name,\n });\n}\n\nexport function stopAgent(name: string, context: CopilotContextParams) {\n const { agentSession, setAgentSession } = context;\n if (agentSession && agentSession.agentName === name) {\n setAgentSession(null);\n context.setCoagentStates((prevAgentStates) => {\n return {\n ...prevAgentStates,\n [name]: {\n ...prevAgentStates[name],\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n },\n };\n });\n } else {\n console.warn(`No agent session found for ${name}`);\n }\n}\n\nexport async function runAgent(\n name: string,\n context: CopilotContextParams & CopilotMessagesContextParams,\n appendMessage: (message: Message) => Promise<void>,\n runChatCompletion: () => Promise<Message[]>,\n hint?: HintFunction,\n) {\n const { agentSession, setAgentSession } = context;\n if (!agentSession || agentSession.agentName !== name) {\n setAgentSession({\n agentName: name,\n });\n }\n\n let previousState: any = null;\n for (let i = context.messages.length - 1; i >= 0; i--) {\n const message = context.messages[i];\n if (message.isAgentStateMessage() && message.agentName === name) {\n previousState = message.state;\n }\n }\n\n let state = context.coagentStatesRef.current?.[name]?.state || {};\n\n if (hint) {\n const hintMessage = hint({ previousState, currentState: state });\n if (hintMessage) {\n await appendMessage(hintMessage);\n } else {\n await runChatCompletion();\n }\n } else {\n await runChatCompletion();\n }\n}\n\nconst isExternalStateManagement = <T>(\n options: UseCoagentOptions<T>,\n): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n};\n\nconst isInternalStateManagementWithInitial = <T>(\n options: UseCoagentOptions<T>,\n): options is WithInternalStateManagementAndInitial<T> => {\n return \"initialState\" in options;\n};\n\nconst getCoagentState = <T>({\n coagentStates,\n name,\n options,\n}: {\n coagentStates: Record<string, CoagentState>;\n name: string;\n options: UseCoagentOptions<T>;\n}) => {\n if (coagentStates[name]) {\n return coagentStates[name];\n } else {\n return {\n name,\n state: isInternalStateManagementWithInitial<T>(options) ? options.initialState : {},\n config: options.config\n ? options.config\n : options.configurable\n ? { configurable: options.configurable }\n : {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0FA,SAAS,aAAa,WAAW,SAAS,cAAc;AAaxD,SAAS,iBAAiB;AA8GnB,SAAS,WAAoB,SAAwD;AAC1F,QAAM,iBAAiB,kBAAkB;AACzC,QAAM,EAAE,gBAAgB,IAAI;AAC5B,QAAM,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;AACf,cAAM,cAAc,WAAW;AAAA,MACjC,OAAO;AACL,cAAM,kBAAkB;AAAA,MAC1B;AAAA,IACF,OAAO;AACL,YAAM,kBAAkB;AAAA,IAC1B;AAAA,EACF;AAAA;AAEA,IAAM,4BAA4B,CAChC,YAC8C;AAC9C,SAAO,WAAW,WAAW,cAAc;AAC7C;AAEA,IAAM,uCAAuC,CAC3C,YACwD;AACxD,SAAO,kBAAkB;AAC3B;AAEA,IAAM,kBAAkB,CAAI;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AACF,MAIM;AACJ,MAAI,cAAc,IAAI,GAAG;AACvB,WAAO,cAAc,IAAI;AAAA,EAC3B,OAAO;AACL,WAAO;AAAA,MACL;AAAA,MACA,OAAO,qCAAwC,OAAO,IAAI,QAAQ,eAAe,CAAC;AAAA,MAClF,QAAQ,QAAQ,SACZ,QAAQ,SACR,QAAQ,eACN,EAAE,cAAc,QAAQ,aAAa,IACrC,CAAC;AAAA,MACP,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,UAAU;AAAA,MACV,UAAU;AAAA,MACV,OAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useCopilotContext
3
- } from "./chunk-7WG4MNRX.mjs";
3
+ } from "./chunk-ERFA53MG.mjs";
4
4
  import {
5
5
  CopilotMessagesContext
6
6
  } from "./chunk-DCTJZ742.mjs";
@@ -60,4 +60,4 @@ function CopilotMessages({ children }) {
60
60
  export {
61
61
  CopilotMessages
62
62
  };
63
- //# sourceMappingURL=chunk-VYSR3S2A.mjs.map
63
+ //# sourceMappingURL=chunk-NTR5KV42.mjs.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  useCopilotChat
3
- } from "./chunk-KQPKROYS.mjs";
3
+ } from "./chunk-IHYG57NB.mjs";
4
4
  import {
5
5
  CopilotContext
6
- } from "./chunk-7WG4MNRX.mjs";
6
+ } from "./chunk-ERFA53MG.mjs";
7
7
  import {
8
8
  useToast
9
9
  } from "./chunk-22ENANUU.mjs";
@@ -62,4 +62,4 @@ function useLangGraphInterrupt(action, dependencies) {
62
62
  export {
63
63
  useLangGraphInterrupt
64
64
  };
65
- //# sourceMappingURL=chunk-YXPFUKGZ.mjs.map
65
+ //# sourceMappingURL=chunk-PLA6FXVD.mjs.map
@@ -104,6 +104,9 @@ var useTree = () => {
104
104
  const removeElement = useCallback((id) => {
105
105
  dispatch({ type: "REMOVE_NODE", id });
106
106
  }, []);
107
+ const getAllElements = useCallback(() => {
108
+ return tree;
109
+ }, [tree]);
107
110
  const printTree = useCallback(
108
111
  (categories) => {
109
112
  const categoriesSet = new Set(categories);
@@ -121,7 +124,7 @@ var useTree = () => {
121
124
  },
122
125
  [tree]
123
126
  );
124
- return { tree, addElement, printTree, removeElement };
127
+ return { tree, addElement, printTree, removeElement, getAllElements };
125
128
  };
126
129
  var use_tree_default = useTree;
127
130
  function setsHaveIntersection(setA, setB) {
@@ -137,4 +140,4 @@ function setsHaveIntersection(setA, setB) {
137
140
  export {
138
141
  use_tree_default
139
142
  };
140
- //# sourceMappingURL=chunk-6U3UH3KO.mjs.map
143
+ //# sourceMappingURL=chunk-RKTVJRK7.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-tree.ts"],"sourcesContent":["import { randomId } from \"@copilotkit/shared\";\nimport { useCallback, useReducer } from \"react\";\n\nexport type TreeNodeId = string;\n\nexport interface TreeNode {\n id: TreeNodeId;\n value: string;\n children: TreeNode[];\n parentId?: TreeNodeId;\n categories: Set<string>;\n}\n\nexport type Tree = TreeNode[];\n\nexport interface UseTreeReturn {\n tree: Tree;\n addElement: (value: string, categories: string[], parentId?: TreeNodeId) => TreeNodeId;\n printTree: (categories: string[]) => string;\n removeElement: (id: TreeNodeId) => void;\n getAllElements: () => Tree;\n}\n\nconst findNode = (nodes: Tree, id: TreeNodeId): TreeNode | undefined => {\n for (const node of nodes) {\n if (node.id === id) {\n return node;\n }\n const result = findNode(node.children, id);\n if (result) {\n return result;\n }\n }\n return undefined;\n};\n\nconst removeNode = (nodes: Tree, id: TreeNodeId): Tree => {\n return nodes.reduce((result: Tree, node) => {\n if (node.id !== id) {\n const newNode = { ...node, children: removeNode(node.children, id) };\n result.push(newNode);\n }\n return result;\n }, []);\n};\n\nconst addNode = (nodes: Tree, newNode: TreeNode, parentId?: TreeNodeId): Tree => {\n if (!parentId) {\n return [...nodes, newNode];\n }\n return nodes.map((node) => {\n if (node.id === parentId) {\n return { ...node, children: [...node.children, newNode] };\n } else if (node.children.length) {\n return { ...node, children: addNode(node.children, newNode, parentId) };\n }\n return node;\n });\n};\n\nconst treeIndentationRepresentation = (index: number, indentLevel: number): string => {\n if (indentLevel === 0) {\n return (index + 1).toString();\n } else if (indentLevel === 1) {\n return String.fromCharCode(65 + index); // 65 is the ASCII value for 'A'\n } else if (indentLevel === 2) {\n return String.fromCharCode(97 + index); // 97 is the ASCII value for 'a'\n } else {\n return \"-\";\n }\n};\n\nconst printNode = (node: TreeNode, prefix = \"\", indentLevel = 0): string => {\n const indent = \" \".repeat(3).repeat(indentLevel);\n\n const prefixPlusIndentLength = prefix.length + indent.length;\n const subsequentLinesPrefix = \" \".repeat(prefixPlusIndentLength);\n\n const valueLines = node.value.split(\"\\n\");\n\n const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;\n const outputSubsequentLines = valueLines\n .slice(1)\n .map((line) => `${subsequentLinesPrefix}${line}`)\n .join(\"\\n\");\n\n let output = `${outputFirstLine}\\n`;\n if (outputSubsequentLines) {\n output += `${outputSubsequentLines}\\n`;\n }\n\n const childPrePrefix = \" \".repeat(prefix.length);\n\n node.children.forEach(\n (child, index) =>\n (output += printNode(\n child,\n `${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `,\n indentLevel + 1,\n )),\n );\n return output;\n};\n\n// Action types\ntype Action =\n | {\n type: \"ADD_NODE\";\n value: string;\n parentId?: string;\n id: string;\n categories: string[];\n }\n | { type: \"REMOVE_NODE\"; id: string };\n\n// Reducer function\nfunction treeReducer(state: Tree, action: Action): Tree {\n switch (action.type) {\n case \"ADD_NODE\": {\n const { value, parentId, id: newNodeId } = action;\n const newNode: TreeNode = {\n id: newNodeId,\n value,\n children: [],\n categories: new Set(action.categories),\n };\n\n try {\n return addNode(state, newNode, parentId);\n } catch (error) {\n console.error(`Error while adding node with id ${newNodeId}: ${error}`);\n return state;\n }\n }\n case \"REMOVE_NODE\":\n return removeNode(state, action.id);\n default:\n return state;\n }\n}\n\n// useTree hook\nconst useTree = (): UseTreeReturn => {\n const [tree, dispatch] = useReducer(treeReducer, []);\n\n const addElement = useCallback(\n (value: string, categories: string[], parentId?: string): TreeNodeId => {\n const newNodeId = randomId(); // Generate new ID outside of dispatch\n dispatch({\n type: \"ADD_NODE\",\n value,\n parentId,\n id: newNodeId,\n categories: categories,\n });\n return newNodeId; // Return the new ID\n },\n [],\n );\n\n const removeElement = useCallback((id: TreeNodeId): void => {\n dispatch({ type: \"REMOVE_NODE\", id });\n }, []);\n\n const getAllElements = useCallback(() => {\n return tree;\n }, [tree]);\n\n const printTree = useCallback(\n (categories: string[]): string => {\n const categoriesSet = new Set(categories);\n\n let output = \"\";\n tree.forEach((node, index) => {\n // if the node does not have any of the desired categories, continue to the next node\n if (!setsHaveIntersection(categoriesSet, node.categories)) {\n return;\n }\n\n // add a new line before each node except the first one\n if (index !== 0) {\n output += \"\\n\";\n }\n\n output += printNode(node, `${treeIndentationRepresentation(index, 0)}. `);\n });\n return output;\n },\n [tree],\n );\n\n return { tree, addElement, printTree, removeElement, getAllElements };\n};\n\nexport default useTree;\n\nfunction setsHaveIntersection<T>(setA: Set<T>, setB: Set<T>): boolean {\n const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];\n\n for (let item of smallerSet) {\n if (largerSet.has(item)) {\n return true;\n }\n }\n\n return false;\n}\n"],"mappings":";;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,aAAa,kBAAkB;AAmCxC,IAAM,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,gBAAgB,YAAY,CAAC,OAAyB;AAC1D,aAAS,EAAE,MAAM,eAAe,GAAG,CAAC;AAAA,EACtC,GAAG,CAAC,CAAC;AAEL,QAAM,iBAAiB,YAAY,MAAM;AACvC,WAAO;AAAA,EACT,GAAG,CAAC,IAAI,CAAC;AAET,QAAM,YAAY;AAAA,IAChB,CAAC,eAAiC;AAChC,YAAM,gBAAgB,IAAI,IAAI,UAAU;AAExC,UAAI,SAAS;AACb,WAAK,QAAQ,CAAC,MAAM,UAAU;AAE5B,YAAI,CAAC,qBAAqB,eAAe,KAAK,UAAU,GAAG;AACzD;AAAA,QACF;AAGA,YAAI,UAAU,GAAG;AACf,oBAAU;AAAA,QACZ;AAEA,kBAAU,UAAU,MAAM,GAAG,8BAA8B,OAAO,CAAC,KAAK;AAAA,MAC1E,CAAC;AACD,aAAO;AAAA,IACT;AAAA,IACA,CAAC,IAAI;AAAA,EACP;AAEA,SAAO,EAAE,MAAM,YAAY,WAAW,eAAe,eAAe;AACtE;AAEA,IAAO,mBAAQ;AAEf,SAAS,qBAAwB,MAAc,MAAuB;AACpE,QAAM,CAAC,YAAY,SAAS,IAAI,KAAK,QAAQ,KAAK,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,IAAI;AAEnF,WAAS,QAAQ,YAAY;AAC3B,QAAI,UAAU,IAAI,IAAI,GAAG;AACvB,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useCopilotContext
3
- } from "./chunk-7WG4MNRX.mjs";
3
+ } from "./chunk-ERFA53MG.mjs";
4
4
 
5
5
  // src/hooks/use-make-copilot-document-readable.ts
6
6
  import { useEffect, useRef } from "react";
@@ -20,4 +20,4 @@ function useMakeCopilotDocumentReadable(document, categories, dependencies = [])
20
20
  export {
21
21
  useMakeCopilotDocumentReadable
22
22
  };
23
- //# sourceMappingURL=chunk-GBAZTXPQ.mjs.map
23
+ //# sourceMappingURL=chunk-VQ3VTO26.mjs.map
@@ -6,16 +6,16 @@ import {
6
6
  } from "./chunk-MLAS4QUR.mjs";
7
7
  import {
8
8
  CopilotMessages
9
- } from "./chunk-VYSR3S2A.mjs";
9
+ } from "./chunk-NTR5KV42.mjs";
10
10
  import {
11
11
  use_flat_category_store_default
12
12
  } from "./chunk-5FHSUKQL.mjs";
13
13
  import {
14
14
  use_tree_default
15
- } from "./chunk-6U3UH3KO.mjs";
15
+ } from "./chunk-RKTVJRK7.mjs";
16
16
  import {
17
17
  CopilotContext
18
- } from "./chunk-7WG4MNRX.mjs";
18
+ } from "./chunk-ERFA53MG.mjs";
19
19
  import {
20
20
  useCopilotRuntimeClient
21
21
  } from "./chunk-BKTARDXX.mjs";
@@ -68,7 +68,7 @@ function CopilotKitInternal(cpkProps) {
68
68
  actions: {},
69
69
  coAgentStateRenders: {}
70
70
  });
71
- const { addElement, removeElement, printTree } = use_tree_default();
71
+ const { addElement, removeElement, printTree, getAllElements } = use_tree_default();
72
72
  const [isLoading, setIsLoading] = useState(false);
73
73
  const [chatInstructions, setChatInstructions] = useState("");
74
74
  const [authStates, setAuthStates] = useState({});
@@ -132,6 +132,9 @@ ${nonDocumentStrings}`;
132
132
  },
133
133
  [removeElement]
134
134
  );
135
+ const getAllContext = useCallback(() => {
136
+ return getAllElements();
137
+ }, [getAllElements]);
135
138
  const getFunctionCallHandler = useCallback(
136
139
  (customEntryPoints) => {
137
140
  return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));
@@ -315,6 +318,7 @@ ${nonDocumentStrings}`;
315
318
  getContextString,
316
319
  addContext,
317
320
  removeContext,
321
+ getAllContext,
318
322
  getDocumentsContext,
319
323
  addDocumentContext,
320
324
  removeDocumentContext,
@@ -539,4 +543,4 @@ export {
539
543
  CopilotKitInternal,
540
544
  defaultCopilotContextCategories
541
545
  };
542
- //# sourceMappingURL=chunk-O54FEOCV.mjs.map
546
+ //# sourceMappingURL=chunk-WYCLVOYC.mjs.map