@copilotkit/react-core 0.0.0-feat-dynamic-copilotcloud-qa-20250117190454 → 0.0.0-feat-enable-setting-recursion-limit-20250424165940

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 (228) hide show
  1. package/CHANGELOG.md +796 -3
  2. package/dist/{chunk-LNI2Z45S.mjs → chunk-22ENANUU.mjs} +25 -17
  3. package/dist/chunk-22ENANUU.mjs.map +1 -0
  4. package/dist/{chunk-U6JICUGO.mjs → chunk-42SVH3TY.mjs} +238 -83
  5. package/dist/chunk-42SVH3TY.mjs.map +1 -0
  6. package/dist/{chunk-XERJQUHA.mjs → chunk-4CEQJ2X6.mjs} +2 -2
  7. package/dist/{chunk-XERJQUHA.mjs.map → chunk-4CEQJ2X6.mjs.map} +1 -1
  8. package/dist/chunk-534J55RX.mjs +86 -0
  9. package/dist/chunk-534J55RX.mjs.map +1 -0
  10. package/dist/{chunk-22XKTBPF.mjs → chunk-5TVV6FJD.mjs} +27 -4
  11. package/dist/chunk-5TVV6FJD.mjs.map +1 -0
  12. package/dist/chunk-6YOKPWQ7.mjs +1 -0
  13. package/dist/chunk-7VCWAAWC.mjs +24 -0
  14. package/dist/chunk-7VCWAAWC.mjs.map +1 -0
  15. package/dist/{chunk-6BQVZFNO.mjs → chunk-BKTARDXX.mjs} +8 -3
  16. package/dist/chunk-BKTARDXX.mjs.map +1 -0
  17. package/dist/{chunk-2KT73RVG.mjs → chunk-CMEX33KD.mjs} +100 -38
  18. package/dist/chunk-CMEX33KD.mjs.map +1 -0
  19. package/dist/chunk-CQPYJIBH.mjs +1 -0
  20. package/dist/chunk-D34OH4VN.mjs +201 -0
  21. package/dist/chunk-D34OH4VN.mjs.map +1 -0
  22. package/dist/chunk-DMQB35FC.mjs +47 -0
  23. package/dist/chunk-DMQB35FC.mjs.map +1 -0
  24. package/dist/{chunk-4TDYSNUD.mjs → chunk-EI2J4CP6.mjs} +26 -13
  25. package/dist/chunk-EI2J4CP6.mjs.map +1 -0
  26. package/dist/{chunk-KSPLXKSX.mjs → chunk-FGOCUTAU.mjs} +91 -50
  27. package/dist/chunk-FGOCUTAU.mjs.map +1 -0
  28. package/dist/{chunk-LHKIIAUQ.mjs → chunk-FRRPZKXW.mjs} +10 -10
  29. package/dist/chunk-FRRPZKXW.mjs.map +1 -0
  30. package/dist/chunk-FXVXAJVG.mjs +65 -0
  31. package/dist/chunk-FXVXAJVG.mjs.map +1 -0
  32. package/dist/{chunk-FQ53HQYZ.mjs → chunk-GOK4PDQO.mjs} +13 -4
  33. package/dist/{chunk-FQ53HQYZ.mjs.map → chunk-GOK4PDQO.mjs.map} +1 -1
  34. package/dist/chunk-HGZXDC4Y.mjs +63 -0
  35. package/dist/chunk-HGZXDC4Y.mjs.map +1 -0
  36. package/dist/{chunk-EWKJMQOF.mjs → chunk-JWE4IXSG.mjs} +18 -4
  37. package/dist/chunk-JWE4IXSG.mjs.map +1 -0
  38. package/dist/{chunk-HIUT2NLX.mjs → chunk-KF5SB2VB.mjs} +2 -2
  39. package/dist/chunk-PMAFHQ7P.mjs +65 -0
  40. package/dist/chunk-PMAFHQ7P.mjs.map +1 -0
  41. package/dist/{chunk-XOQMISG3.mjs → chunk-TWWQG3EF.mjs} +3 -3
  42. package/dist/{chunk-WXREY7UP.mjs → chunk-UDUFMGWQ.mjs} +11 -3
  43. package/dist/chunk-UDUFMGWQ.mjs.map +1 -0
  44. package/dist/chunk-YPBKY4KY.mjs +1 -0
  45. package/dist/chunk-YPBKY4KY.mjs.map +1 -0
  46. package/dist/components/copilot-provider/copilot-messages.d.ts +4 -12
  47. package/dist/components/copilot-provider/copilot-messages.js +143 -18
  48. package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
  49. package/dist/components/copilot-provider/copilot-messages.mjs +2 -1
  50. package/dist/components/copilot-provider/copilotkit-props.d.ts +37 -2
  51. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  52. package/dist/components/copilot-provider/copilotkit.d.ts +2 -2
  53. package/dist/components/copilot-provider/copilotkit.js +470 -58
  54. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  55. package/dist/components/copilot-provider/copilotkit.mjs +9 -7
  56. package/dist/components/copilot-provider/index.d.ts +1 -1
  57. package/dist/components/copilot-provider/index.js +470 -58
  58. package/dist/components/copilot-provider/index.js.map +1 -1
  59. package/dist/components/copilot-provider/index.mjs +9 -7
  60. package/dist/components/error-boundary/error-boundary.d.ts +12 -3
  61. package/dist/components/error-boundary/error-boundary.js +333 -19
  62. package/dist/components/error-boundary/error-boundary.js.map +1 -1
  63. package/dist/components/error-boundary/error-boundary.mjs +4 -2
  64. package/dist/components/error-boundary/error-utils.js +14 -2
  65. package/dist/components/error-boundary/error-utils.js.map +1 -1
  66. package/dist/components/error-boundary/error-utils.mjs +1 -1
  67. package/dist/components/index.d.ts +1 -1
  68. package/dist/components/index.js +470 -58
  69. package/dist/components/index.js.map +1 -1
  70. package/dist/components/index.mjs +9 -7
  71. package/dist/components/toast/toast-provider.js +34 -16
  72. package/dist/components/toast/toast-provider.js.map +1 -1
  73. package/dist/components/toast/toast-provider.mjs +1 -1
  74. package/dist/components/usage-banner.d.ts +22 -0
  75. package/dist/components/usage-banner.js +226 -0
  76. package/dist/components/usage-banner.js.map +1 -0
  77. package/dist/components/usage-banner.mjs +10 -0
  78. package/dist/components/usage-banner.mjs.map +1 -0
  79. package/dist/context/copilot-context.d.ts +10 -142
  80. package/dist/context/copilot-context.js +10 -2
  81. package/dist/context/copilot-context.js.map +1 -1
  82. package/dist/context/copilot-context.mjs +1 -1
  83. package/dist/context/index.d.ts +1 -1
  84. package/dist/context/index.js +10 -2
  85. package/dist/context/index.js.map +1 -1
  86. package/dist/context/index.mjs +4 -4
  87. package/dist/copilot-context-0e923eb1.d.ts +194 -0
  88. package/dist/hooks/index.d.ts +5 -2
  89. package/dist/hooks/index.js +513 -145
  90. package/dist/hooks/index.js.map +1 -1
  91. package/dist/hooks/index.mjs +37 -23
  92. package/dist/hooks/use-chat.d.ts +16 -6
  93. package/dist/hooks/use-chat.js +245 -79
  94. package/dist/hooks/use-chat.js.map +1 -1
  95. package/dist/hooks/use-chat.mjs +4 -4
  96. package/dist/hooks/use-coagent-state-render.d.ts +2 -7
  97. package/dist/hooks/use-coagent-state-render.js +34 -3
  98. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  99. package/dist/hooks/use-coagent-state-render.mjs +3 -3
  100. package/dist/hooks/use-coagent.d.ts +20 -14
  101. package/dist/hooks/use-coagent.js +346 -131
  102. package/dist/hooks/use-coagent.js.map +1 -1
  103. package/dist/hooks/use-coagent.mjs +13 -11
  104. package/dist/hooks/use-copilot-action.js +27 -4
  105. package/dist/hooks/use-copilot-action.js.map +1 -1
  106. package/dist/hooks/use-copilot-action.mjs +3 -3
  107. package/dist/hooks/use-copilot-additional-instructions.d.ts +26 -0
  108. package/dist/hooks/use-copilot-additional-instructions.js +162 -0
  109. package/dist/hooks/use-copilot-additional-instructions.js.map +1 -0
  110. package/dist/hooks/use-copilot-additional-instructions.mjs +9 -0
  111. package/dist/hooks/use-copilot-additional-instructions.mjs.map +1 -0
  112. package/dist/hooks/use-copilot-authenticated-action.d.ts +12 -2
  113. package/dist/hooks/use-copilot-authenticated-action.js +35 -12
  114. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  115. package/dist/hooks/use-copilot-authenticated-action.mjs +6 -6
  116. package/dist/hooks/use-copilot-chat.d.ts +3 -3
  117. package/dist/hooks/use-copilot-chat.js +264 -87
  118. package/dist/hooks/use-copilot-chat.js.map +1 -1
  119. package/dist/hooks/use-copilot-chat.mjs +12 -10
  120. package/dist/hooks/use-copilot-readable.d.ts +5 -1
  121. package/dist/hooks/use-copilot-readable.js +21 -4
  122. package/dist/hooks/use-copilot-readable.js.map +1 -1
  123. package/dist/hooks/use-copilot-readable.mjs +2 -2
  124. package/dist/hooks/use-copilot-runtime-client.js +20 -3
  125. package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
  126. package/dist/hooks/use-copilot-runtime-client.mjs +2 -2
  127. package/dist/hooks/use-langgraph-interrupt-render.d.ts +5 -0
  128. package/dist/hooks/use-langgraph-interrupt-render.js +185 -0
  129. package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -0
  130. package/dist/hooks/use-langgraph-interrupt-render.mjs +11 -0
  131. package/dist/hooks/use-langgraph-interrupt-render.mjs.map +1 -0
  132. package/dist/hooks/use-langgraph-interrupt.d.ts +14 -0
  133. package/dist/hooks/use-langgraph-interrupt.js +1154 -0
  134. package/dist/hooks/use-langgraph-interrupt.js.map +1 -0
  135. package/dist/hooks/use-langgraph-interrupt.mjs +25 -0
  136. package/dist/hooks/use-langgraph-interrupt.mjs.map +1 -0
  137. package/dist/hooks/use-make-copilot-document-readable.js +10 -2
  138. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  139. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  140. package/dist/index.d.ts +7 -3
  141. package/dist/index.js +998 -240
  142. package/dist/index.js.map +1 -1
  143. package/dist/index.mjs +43 -28
  144. package/dist/lib/copilot-task.d.ts +1 -1
  145. package/dist/lib/copilot-task.js +1 -1
  146. package/dist/lib/copilot-task.js.map +1 -1
  147. package/dist/lib/copilot-task.mjs +11 -9
  148. package/dist/lib/index.d.ts +1 -1
  149. package/dist/lib/index.js +1 -1
  150. package/dist/lib/index.js.map +1 -1
  151. package/dist/lib/index.mjs +11 -9
  152. package/dist/lib/status-checker.d.ts +17 -0
  153. package/dist/lib/status-checker.js +102 -0
  154. package/dist/lib/status-checker.js.map +1 -0
  155. package/dist/lib/status-checker.mjs +8 -0
  156. package/dist/lib/status-checker.mjs.map +1 -0
  157. package/dist/types/coagent-state.d.ts +4 -0
  158. package/dist/types/coagent-state.js.map +1 -1
  159. package/dist/types/crew.d.ts +79 -0
  160. package/dist/types/crew.js +19 -0
  161. package/dist/types/crew.js.map +1 -0
  162. package/dist/types/crew.mjs +2 -0
  163. package/dist/types/crew.mjs.map +1 -0
  164. package/dist/types/frontend-action.d.ts +2 -1
  165. package/dist/types/frontend-action.js +1 -1
  166. package/dist/types/frontend-action.js.map +1 -1
  167. package/dist/types/frontend-action.mjs +1 -1
  168. package/dist/types/index.d.ts +2 -1
  169. package/dist/types/index.js.map +1 -1
  170. package/dist/types/index.mjs +2 -1
  171. package/dist/types/interrupt-action.d.ts +10 -0
  172. package/dist/types/interrupt-action.js +19 -0
  173. package/dist/types/interrupt-action.js.map +1 -0
  174. package/dist/types/interrupt-action.mjs +1 -0
  175. package/dist/types/interrupt-action.mjs.map +1 -0
  176. package/dist/utils/extract.d.ts +1 -1
  177. package/dist/utils/extract.js.map +1 -1
  178. package/dist/utils/extract.mjs +9 -7
  179. package/dist/utils/index.d.ts +1 -1
  180. package/dist/utils/index.js.map +1 -1
  181. package/dist/utils/index.mjs +9 -7
  182. package/package.json +5 -4
  183. package/src/components/copilot-provider/copilot-messages.tsx +41 -4
  184. package/src/components/copilot-provider/copilotkit-props.tsx +36 -1
  185. package/src/components/copilot-provider/copilotkit.tsx +117 -29
  186. package/src/components/error-boundary/error-boundary.tsx +62 -4
  187. package/src/components/error-boundary/error-utils.tsx +11 -6
  188. package/src/components/toast/toast-provider.tsx +20 -17
  189. package/src/components/usage-banner.tsx +205 -0
  190. package/src/context/copilot-context.tsx +41 -10
  191. package/src/hooks/index.ts +4 -1
  192. package/src/hooks/use-chat.ts +288 -64
  193. package/src/hooks/use-coagent-state-render.ts +39 -8
  194. package/src/hooks/use-coagent.ts +125 -67
  195. package/src/hooks/use-copilot-action.ts +16 -0
  196. package/src/hooks/use-copilot-additional-instructions.ts +85 -0
  197. package/src/hooks/use-copilot-authenticated-action.ts +17 -7
  198. package/src/hooks/use-copilot-chat.ts +19 -5
  199. package/src/hooks/use-copilot-readable.ts +16 -2
  200. package/src/hooks/use-copilot-runtime-client.ts +6 -1
  201. package/src/hooks/use-langgraph-interrupt-render.ts +67 -0
  202. package/src/hooks/use-langgraph-interrupt.ts +61 -0
  203. package/src/lib/status-checker.ts +64 -0
  204. package/src/types/coagent-state.ts +4 -0
  205. package/src/types/crew.ts +89 -0
  206. package/src/types/frontend-action.ts +5 -2
  207. package/src/types/index.ts +8 -0
  208. package/src/types/interrupt-action.ts +39 -0
  209. package/dist/chunk-22XKTBPF.mjs.map +0 -1
  210. package/dist/chunk-2KT73RVG.mjs.map +0 -1
  211. package/dist/chunk-4TDYSNUD.mjs.map +0 -1
  212. package/dist/chunk-6BQVZFNO.mjs.map +0 -1
  213. package/dist/chunk-EFZPSZWO.mjs +0 -1
  214. package/dist/chunk-EWKJMQOF.mjs.map +0 -1
  215. package/dist/chunk-KSPLXKSX.mjs.map +0 -1
  216. package/dist/chunk-LHKIIAUQ.mjs.map +0 -1
  217. package/dist/chunk-LNI2Z45S.mjs.map +0 -1
  218. package/dist/chunk-NR2BTA6Z.mjs +0 -1
  219. package/dist/chunk-U6JICUGO.mjs.map +0 -1
  220. package/dist/chunk-VNTDIJSG.mjs +0 -37
  221. package/dist/chunk-VNTDIJSG.mjs.map +0 -1
  222. package/dist/chunk-WXREY7UP.mjs.map +0 -1
  223. package/dist/chunk-XXR4QFAQ.mjs +0 -29
  224. package/dist/chunk-XXR4QFAQ.mjs.map +0 -1
  225. /package/dist/{chunk-EFZPSZWO.mjs.map → chunk-6YOKPWQ7.mjs.map} +0 -0
  226. /package/dist/{chunk-NR2BTA6Z.mjs.map → chunk-CQPYJIBH.mjs.map} +0 -0
  227. /package/dist/{chunk-HIUT2NLX.mjs.map → chunk-KF5SB2VB.mjs.map} +0 -0
  228. /package/dist/{chunk-XOQMISG3.mjs.map → chunk-TWWQG3EF.mjs.map} +0 -0
@@ -1,18 +1,18 @@
1
1
  import {
2
2
  defaultCopilotContextCategories
3
- } from "./chunk-2KT73RVG.mjs";
3
+ } from "./chunk-CMEX33KD.mjs";
4
+ import {
5
+ useCopilotContext
6
+ } from "./chunk-UDUFMGWQ.mjs";
4
7
  import {
5
8
  useCopilotMessagesContext
6
9
  } from "./chunk-DCTJZ742.mjs";
7
10
  import {
8
11
  useChat
9
- } from "./chunk-U6JICUGO.mjs";
10
- import {
11
- useCopilotContext
12
- } from "./chunk-WXREY7UP.mjs";
12
+ } from "./chunk-42SVH3TY.mjs";
13
13
  import {
14
14
  useAsyncCallback
15
- } from "./chunk-LNI2Z45S.mjs";
15
+ } from "./chunk-22ENANUU.mjs";
16
16
  import {
17
17
  __async,
18
18
  __objRest,
@@ -48,7 +48,11 @@ function useCopilotChat(_a = {}) {
48
48
  setThreadId,
49
49
  runId,
50
50
  setRunId,
51
- chatAbortControllerRef
51
+ chatAbortControllerRef,
52
+ extensions,
53
+ setExtensions,
54
+ langGraphInterruptAction,
55
+ setLangGraphInterruptAction
52
56
  } = useCopilotContext();
53
57
  const { messages, setMessages } = useCopilotMessagesContext();
54
58
  const latestGetContextString = useUpdatedRef(getContextString);
@@ -105,7 +109,11 @@ function useCopilotChat(_a = {}) {
105
109
  runId,
106
110
  setRunId,
107
111
  chatAbortControllerRef,
108
- agentLock
112
+ agentLock,
113
+ extensions,
114
+ setExtensions,
115
+ langGraphInterruptAction,
116
+ setLangGraphInterruptAction
109
117
  }));
110
118
  const latestAppend = useUpdatedRef(append);
111
119
  const latestAppendFunc = useAsyncCallback(
@@ -115,9 +123,12 @@ function useCopilotChat(_a = {}) {
115
123
  [latestAppend]
116
124
  );
117
125
  const latestReload = useUpdatedRef(reload);
118
- const latestReloadFunc = useAsyncCallback(() => __async(this, null, function* () {
119
- return yield latestReload.current();
120
- }), [latestReload]);
126
+ const latestReloadFunc = useAsyncCallback(
127
+ (messageId) => __async(this, null, function* () {
128
+ return yield latestReload.current(messageId);
129
+ }),
130
+ [latestReload]
131
+ );
121
132
  const latestStop = useUpdatedRef(stop);
122
133
  const latestStopFunc = useCallback(() => {
123
134
  return latestStop.current();
@@ -143,7 +154,6 @@ function useCopilotChat(_a = {}) {
143
154
  const reset = useCallback(() => {
144
155
  latestStopFunc();
145
156
  setMessages([]);
146
- setThreadId(null);
147
157
  setRunId(null);
148
158
  setCoagentStatesWithRef({});
149
159
  let initialAgentSession = null;
@@ -203,6 +213,9 @@ Please assist them as best you can.
203
213
  You can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.
204
214
 
205
215
  If you would like to call a function, call it without saying anything else.
216
+ In case of a function error:
217
+ - If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.
218
+ - If the error's source is unclear or seems unrelated to your input, do not attempt further retries.
206
219
  ` + (additionalInstructions ? `
207
220
 
208
221
  ${additionalInstructions}` : "");
@@ -212,4 +225,4 @@ export {
212
225
  useCopilotChat,
213
226
  defaultSystemMessage
214
227
  };
215
- //# sourceMappingURL=chunk-4TDYSNUD.mjs.map
228
+ //# sourceMappingURL=chunk-EI2J4CP6.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-chat.ts"],"sourcesContent":["/**\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChat } from \"@copilotkit/react-core\";\n * import { Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\n *\n * export function YourComponent() {\n * const { appendMessage } = useCopilotChat();\n *\n * appendMessage(\n * new TextMessage({\n * content: \"Hello World\",\n * role: Role.User,\n * }),\n * );\n *\n * // optionally, you can append a message without running chat completion\n * appendMessage(yourMessage, { followUp: false });\n * }\n * ```\n *\n * `useCopilotChat` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * visibleMessages, // An array of messages that are currently visible in the chat.\n * appendMessage, // A function to append a message to the chat.\n * setMessages, // A function to set the messages in the chat.\n * deleteMessage, // A function to delete a message from the chat.\n * reloadMessages, // A function to reload the messages from the API.\n * stopGeneration, // A function to stop the generation of the next message.\n * reset, // A function to reset the chat.\n * isLoading, // A boolean indicating if the chat is loading.\n * } = useCopilotChat();\n * ```\n */\nimport { useRef, useEffect, useCallback } from \"react\";\nimport { AgentSession, useCopilotContext } from \"../context/copilot-context\";\nimport { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat, AppendMessageOptions } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CoAgentStateRenderHandlerArguments } from \"@copilotkit/shared\";\nimport { useCopilotMessagesContext } from \"../context\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n appendMessage: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: (messageId: string) => Promise<void>;\n stopGeneration: () => void;\n reset: () => void;\n isLoading: boolean;\n runChatCompletion: () => Promise<Message[]>;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getFunctionCallHandler,\n copilotApiConfig,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n coagentStatesRef,\n setCoagentStatesWithRef,\n coAgentStateRenders,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n } = useCopilotContext();\n const { messages, setMessages } = useCopilotMessagesContext();\n\n // We need to ensure that makeSystemMessageCallback always uses the latest\n // useCopilotReadable data.\n const latestGetContextString = useUpdatedRef(getContextString);\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = latestGetContextString.current([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return new TextMessage({\n content: systemMessageMaker(contextString, chatInstructions),\n role: Role.System,\n });\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const onCoAgentStateRender = useAsyncCallback(\n async (args: CoAgentStateRenderHandlerArguments) => {\n const { name, nodeName, state } = args;\n let action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && action.nodeName === nodeName,\n );\n if (!action) {\n action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && !action.nodeName,\n );\n }\n if (action) {\n await action.handler?.({ state, nodeName });\n }\n },\n [coAgentStateRenders],\n );\n\n const { append, reload, stop, runChatCompletion } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: options.initialMessages || [],\n onFunctionCall: getFunctionCallHandler(),\n onCoAgentStateRender,\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n agentLock,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n });\n\n // this is a workaround born out of a bug that Athena incessantly ran into.\n // We could not find the origin of the bug, however, it was clear that an outdated version of the append function was being used somehow --\n // it referenced the old state of the messages array, and not the latest one.\n //\n // We want to make copilotkit as abuse-proof as possible, so we are adding this workaround to ensure that the latest version of the append function is always used.\n //\n // How does this work?\n // we store the relevant function in a ref that is always up-to-date, and then we use that ref in the callback.\n const latestAppend = useUpdatedRef(append);\n const latestAppendFunc = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions) => {\n return await latestAppend.current(message, options);\n },\n [latestAppend],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useAsyncCallback(\n async (messageId: string) => {\n return await latestReload.current(messageId);\n },\n [latestReload],\n );\n\n const latestStop = useUpdatedRef(stop);\n const latestStopFunc = useCallback(() => {\n return latestStop.current();\n }, [latestStop]);\n\n const latestDelete = useUpdatedRef(deleteMessage);\n const latestDeleteFunc = useCallback(\n (messageId: string) => {\n return latestDelete.current(messageId);\n },\n [latestDelete],\n );\n\n const latestSetMessages = useUpdatedRef(setMessages);\n const latestSetMessagesFunc = useCallback(\n (messages: Message[]) => {\n return latestSetMessages.current(messages);\n },\n [latestSetMessages],\n );\n\n const latestRunChatCompletion = useUpdatedRef(runChatCompletion);\n const latestRunChatCompletionFunc = useAsyncCallback(async () => {\n return await latestRunChatCompletion.current!();\n }, [latestRunChatCompletion]);\n\n const reset = useCallback(() => {\n latestStopFunc();\n setMessages([]);\n setRunId(null);\n setCoagentStatesWithRef({});\n let initialAgentSession: AgentSession | null = null;\n if (agentLock) {\n initialAgentSession = {\n agentName: agentLock,\n };\n }\n setAgentSession(initialAgentSession);\n }, [\n latestStopFunc,\n setMessages,\n setThreadId,\n setCoagentStatesWithRef,\n setAgentSession,\n agentLock,\n ]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n return {\n visibleMessages: messages,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n reset: latestResetFunc,\n deleteMessage: latestDeleteFunc,\n runChatCompletion: latestRunChatCompletionFunc,\n isLoading,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\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, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\nIn case of a function error:\n- If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.\n- If the error's source is unclear or seems unrelated to your input, do not attempt further retries.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAS,QAAQ,WAAW,mBAAmB;AAE/C,SAAkB,MAAM,mBAAmB;AA2CpC,SAAS,eAAe,KAGJ,CAAC,GAAyB;AAHtB,eAC7B;AAAA;AAAA,EA1FF,IAyF+B,IAE1B,oBAF0B,IAE1B;AAAA,IADH;AAAA;AAGA,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,kBAAkB;AACtB,QAAM,EAAE,UAAU,YAAY,IAAI,0BAA0B;AAI5D,QAAM,yBAAyB,cAAc,gBAAgB;AAC7D,QAAM,gBAAgB;AAAA,IACpB,CAAC,cAAsB;AACrB,kBAAY,CA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b;AAAA,IACF;AACA,oBAAgB,mBAAmB;AAAA,EACrC,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,QAAM,cAAc,cAAc,KAAK;AACvC,QAAM,kBAAkB,YAAY,MAAM;AACxC,WAAO,YAAY,QAAQ;AAAA,EAC7B,GAAG,CAAC,WAAW,CAAC;AAEhB,SAAO;AAAA,IACL,iBAAiB;AAAA,IACjB,eAAe;AAAA,IACf,aAAa;AAAA,IACb,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,OAAO;AAAA,IACP,eAAe;AAAA,IACf,mBAAmB;AAAA,IACnB;AAAA,EACF;AACF;AAIA,SAAS,cAAiB,OAAU;AAClC,QAAM,MAAM,OAAO,KAAK;AAExB,YAAU,MAAM;AACd,QAAI,UAAU;AAAA,EAChB,GAAG,CAAC,KAAK,CAAC;AAEV,SAAO;AACT;AAEO,SAAS,qBACd,eACA,wBACQ;AACR,SACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAaG,yBAAyB;AAAA;AAAA,EAAO,2BAA2B;AAEhE;","names":["_a","action","options","messages"]}
@@ -1,16 +1,19 @@
1
1
  import {
2
2
  useCopilotChat
3
- } from "./chunk-4TDYSNUD.mjs";
3
+ } from "./chunk-EI2J4CP6.mjs";
4
+ import {
5
+ useCopilotContext
6
+ } from "./chunk-UDUFMGWQ.mjs";
4
7
  import {
5
8
  useCopilotMessagesContext
6
9
  } from "./chunk-DCTJZ742.mjs";
7
10
  import {
8
- useCopilotContext
9
- } from "./chunk-WXREY7UP.mjs";
11
+ useCopilotRuntimeClient
12
+ } from "./chunk-BKTARDXX.mjs";
10
13
  import {
11
14
  useAsyncCallback,
12
15
  useToast
13
- } from "./chunk-LNI2Z45S.mjs";
16
+ } from "./chunk-22ENANUU.mjs";
14
17
  import {
15
18
  __async,
16
19
  __spreadProps,
@@ -18,14 +21,14 @@ import {
18
21
  } from "./chunk-SKC7AJIV.mjs";
19
22
 
20
23
  // src/hooks/use-coagent.ts
21
- import { useEffect } from "react";
24
+ import { useCallback, useEffect, useMemo, useRef } from "react";
25
+ import { parseJson } from "@copilotkit/shared";
22
26
  function useCoAgent(options) {
23
27
  const generalContext = useCopilotContext();
24
28
  const { availableAgents } = generalContext;
25
29
  const { addToast } = useToast();
26
- const isExternalStateManagement = (options2) => {
27
- return "state" in options2 && "setState" in options2;
28
- };
30
+ const lastLoadedThreadId = useRef();
31
+ const lastLoadedState = useRef();
29
32
  const { name } = options;
30
33
  useEffect(() => {
31
34
  if ((availableAgents == null ? void 0 : availableAgents.length) && !availableAgents.some((a) => a.name === name)) {
@@ -34,39 +37,48 @@ function useCoAgent(options) {
34
37
  addToast({ type: "warning", message });
35
38
  }
36
39
  }, [availableAgents]);
37
- const isInternalStateManagementWithInitial = (options2) => {
38
- return "initialState" in options2;
39
- };
40
40
  const messagesContext = useCopilotMessagesContext();
41
41
  const context = __spreadValues(__spreadValues({}, generalContext), messagesContext);
42
- const { coagentStates, coagentStatesRef, setCoagentStatesWithRef } = context;
42
+ const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } = context;
43
43
  const { appendMessage, runChatCompletion } = useCopilotChat();
44
- const getCoagentState = (coagentStates2, name2) => {
45
- if (coagentStates2[name2]) {
46
- return coagentStates2[name2];
47
- } else {
48
- return {
49
- name: name2,
50
- state: isInternalStateManagementWithInitial(options) ? options.initialState : {},
51
- running: false,
52
- active: false,
53
- threadId: void 0,
54
- nodeName: void 0,
55
- runId: void 0
56
- };
57
- }
58
- };
59
- const setState = (newState) => {
60
- let coagentState2 = getCoagentState(coagentStatesRef.current || {}, name);
61
- const updatedState = typeof newState === "function" ? newState(coagentState2.state) : newState;
62
- setCoagentStatesWithRef(__spreadProps(__spreadValues({}, coagentStatesRef.current), {
63
- [name]: __spreadProps(__spreadValues({}, coagentState2), {
64
- state: updatedState
65
- })
66
- }));
67
- };
68
- const coagentState = getCoagentState(coagentStates, name);
69
- const state = isExternalStateManagement(options) ? options.state : coagentState.state;
44
+ const runtimeClient = useCopilotRuntimeClient({
45
+ url: copilotApiConfig.chatApiEndpoint,
46
+ publicApiKey: copilotApiConfig.publicApiKey,
47
+ credentials: copilotApiConfig.credentials
48
+ });
49
+ const setState = useCallback(
50
+ (newState) => {
51
+ let coagentState = getCoagentState({ coagentStates, name, options });
52
+ const updatedState = typeof newState === "function" ? newState(coagentState.state) : newState;
53
+ setCoagentStatesWithRef(__spreadProps(__spreadValues({}, coagentStatesRef.current), {
54
+ [name]: __spreadProps(__spreadValues({}, coagentState), {
55
+ state: updatedState
56
+ })
57
+ }));
58
+ },
59
+ [coagentStates, name]
60
+ );
61
+ useEffect(() => {
62
+ const fetchAgentState = () => __async(this, null, function* () {
63
+ var _a, _b, _c, _d;
64
+ if (!threadId || threadId === lastLoadedThreadId.current)
65
+ return;
66
+ const result = yield runtimeClient.loadAgentState({
67
+ threadId,
68
+ agentName: name
69
+ });
70
+ const newState = (_b = (_a = result.data) == null ? void 0 : _a.loadAgentState) == null ? void 0 : _b.state;
71
+ if (newState === lastLoadedState.current)
72
+ return;
73
+ if (((_d = (_c = result.data) == null ? void 0 : _c.loadAgentState) == null ? void 0 : _d.threadExists) && newState && newState != "{}") {
74
+ lastLoadedState.current = newState;
75
+ lastLoadedThreadId.current = threadId;
76
+ const fetchedState = parseJson(newState, {});
77
+ isExternalStateManagement(options) ? options.setState(fetchedState) : setState(fetchedState);
78
+ }
79
+ });
80
+ void fetchAgentState();
81
+ }, [threadId]);
70
82
  useEffect(() => {
71
83
  if (isExternalStateManagement(options)) {
72
84
  setState(options.state);
@@ -84,17 +96,20 @@ function useCoAgent(options) {
84
96
  }),
85
97
  [name, context, appendMessage, runChatCompletion]
86
98
  );
87
- return {
88
- name,
89
- nodeName: coagentState.nodeName,
90
- threadId: coagentState.threadId,
91
- running: coagentState.running,
92
- state: coagentState.state,
93
- setState: isExternalStateManagement(options) ? options.setState : setState,
94
- start: () => startAgent(name, context),
95
- stop: () => stopAgent(name, context),
96
- run: runAgentCallback
97
- };
99
+ return useMemo(() => {
100
+ const coagentState = getCoagentState({ coagentStates, name, options });
101
+ return {
102
+ name,
103
+ nodeName: coagentState.nodeName,
104
+ threadId: coagentState.threadId,
105
+ running: coagentState.running,
106
+ state: coagentState.state,
107
+ setState: isExternalStateManagement(options) ? options.setState : setState,
108
+ start: () => startAgent(name, context),
109
+ stop: () => stopAgent(name, context),
110
+ run: runAgentCallback
111
+ };
112
+ }, [name, coagentStates, options, setState, runAgentCallback]);
98
113
  }
99
114
  function startAgent(name, context) {
100
115
  const { setAgentSession } = context;
@@ -150,6 +165,32 @@ function runAgent(name, context, appendMessage, runChatCompletion, hint) {
150
165
  }
151
166
  });
152
167
  }
168
+ var isExternalStateManagement = (options) => {
169
+ return "state" in options && "setState" in options;
170
+ };
171
+ var isInternalStateManagementWithInitial = (options) => {
172
+ return "initialState" in options;
173
+ };
174
+ var getCoagentState = ({
175
+ coagentStates,
176
+ name,
177
+ options
178
+ }) => {
179
+ if (coagentStates[name]) {
180
+ return coagentStates[name];
181
+ } else {
182
+ return {
183
+ name,
184
+ state: isInternalStateManagementWithInitial(options) ? options.initialState : {},
185
+ config: options.config ? options.config : options.configurable ? { configurable: options.configurable } : {},
186
+ running: false,
187
+ active: false,
188
+ threadId: void 0,
189
+ nodeName: void 0,
190
+ runId: void 0
191
+ };
192
+ }
193
+ };
153
194
 
154
195
  export {
155
196
  useCoAgent,
@@ -157,4 +198,4 @@ export {
157
198
  stopAgent,
158
199
  runAgent
159
200
  };
160
- //# sourceMappingURL=chunk-KSPLXKSX.mjs.map
201
+ //# sourceMappingURL=chunk-FGOCUTAU.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\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\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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1B;AAAA,IACF;AAEA,QAAI,UAAQ,mBAAQ,iBAAiB,YAAzB,mBAAmC,UAAnC,mBAA0C,UAAS,CAAC;AAEhE,QAAI,MAAM;AACR,YAAM,cAAc,KAAK,EAAE,eAAe,cAAc,MAAM,CAAC;AAC/D,UAAI,aAAa;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,9 +1,9 @@
1
1
  import {
2
2
  useCopilotAction
3
- } from "./chunk-EWKJMQOF.mjs";
3
+ } from "./chunk-JWE4IXSG.mjs";
4
4
  import {
5
5
  useCopilotContext
6
- } from "./chunk-WXREY7UP.mjs";
6
+ } from "./chunk-UDUFMGWQ.mjs";
7
7
  import {
8
8
  __spreadProps,
9
9
  __spreadValues
@@ -12,8 +12,8 @@ import {
12
12
  // src/hooks/use-copilot-authenticated-action.ts
13
13
  import { Fragment, useCallback, useRef } from "react";
14
14
  import React from "react";
15
- function useCopilotAuthenticatedAction(action, dependencies) {
16
- const { authConfig, authStates, setAuthStates } = useCopilotContext();
15
+ function useCopilotAuthenticatedAction_c(action, dependencies) {
16
+ const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();
17
17
  const pendingActionRef = useRef(null);
18
18
  const executeAction = useCallback(
19
19
  (props) => {
@@ -26,14 +26,14 @@ function useCopilotAuthenticatedAction(action, dependencies) {
26
26
  );
27
27
  const wrappedRender = useCallback(
28
28
  (props) => {
29
- const isAuthenticated = Object.values(authStates || {}).some(
29
+ const isAuthenticated = Object.values(authStates_c || {}).some(
30
30
  (state) => state.status === "authenticated"
31
31
  );
32
32
  if (!isAuthenticated) {
33
33
  pendingActionRef.current = props;
34
- return (authConfig == null ? void 0 : authConfig.SignInComponent) ? React.createElement(authConfig.SignInComponent, {
34
+ return (authConfig_c == null ? void 0 : authConfig_c.SignInComponent) ? React.createElement(authConfig_c.SignInComponent, {
35
35
  onSignInComplete: (authState) => {
36
- setAuthStates == null ? void 0 : setAuthStates((prev) => __spreadProps(__spreadValues({}, prev), { [action.name]: authState }));
36
+ setAuthStates_c == null ? void 0 : setAuthStates_c((prev) => __spreadProps(__spreadValues({}, prev), { [action.name]: authState }));
37
37
  if (pendingActionRef.current) {
38
38
  executeAction(pendingActionRef.current);
39
39
  pendingActionRef.current = null;
@@ -43,7 +43,7 @@ function useCopilotAuthenticatedAction(action, dependencies) {
43
43
  }
44
44
  return executeAction(props);
45
45
  },
46
- [action, authStates, setAuthStates]
46
+ [action, authStates_c, setAuthStates_c]
47
47
  );
48
48
  useCopilotAction(
49
49
  __spreadProps(__spreadValues({}, action), {
@@ -54,6 +54,6 @@ function useCopilotAuthenticatedAction(action, dependencies) {
54
54
  }
55
55
 
56
56
  export {
57
- useCopilotAuthenticatedAction
57
+ useCopilotAuthenticatedAction_c
58
58
  };
59
- //# sourceMappingURL=chunk-LHKIIAUQ.mjs.map
59
+ //# sourceMappingURL=chunk-FRRPZKXW.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-authenticated-action.ts"],"sourcesContent":["import { Parameter } from \"@copilotkit/shared\";\nimport { Fragment, useCallback, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { FrontendAction, ActionRenderProps } from \"../types/frontend-action\";\nimport { useCopilotAction } from \"./use-copilot-action\";\nimport React from \"react\";\n\n/**\n * Hook to create an authenticated action that requires user sign-in before execution.\n *\n * @remarks\n * This feature is only available when using CopilotKit's hosted cloud service.\n * To use this feature, sign up at https://cloud.copilotkit.ai to get your publicApiKey.\n *\n * @param action - The frontend action to be wrapped with authentication\n * @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed\n */\nexport function useCopilotAuthenticatedAction_c<T extends Parameter[]>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();\n const pendingActionRef = useRef<ActionRenderProps<Parameter[]> | null>(null);\n\n const executeAction = useCallback(\n (props: ActionRenderProps<Parameter[]>) => {\n if (typeof action.render === \"function\") {\n return action.render(props);\n }\n return action.render || React.createElement(Fragment);\n },\n [action],\n );\n\n const wrappedRender = useCallback(\n (props: ActionRenderProps<Parameter[]>): string | React.ReactElement => {\n const isAuthenticated = Object.values(authStates_c || {}).some(\n (state) => state.status === \"authenticated\",\n );\n\n if (!isAuthenticated) {\n // Store action details for later execution\n pendingActionRef.current = props;\n\n return authConfig_c?.SignInComponent\n ? React.createElement(authConfig_c.SignInComponent, {\n onSignInComplete: (authState) => {\n setAuthStates_c?.((prev) => ({ ...prev, [action.name]: authState }));\n if (pendingActionRef.current) {\n executeAction(pendingActionRef.current);\n pendingActionRef.current = null;\n }\n },\n })\n : React.createElement(Fragment);\n }\n\n return executeAction(props);\n },\n [action, authStates_c, setAuthStates_c],\n );\n\n useCopilotAction(\n {\n ...action,\n render: wrappedRender,\n } as FrontendAction<T>,\n dependencies,\n );\n}\n"],"mappings":";;;;;;;;;;;;A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k-22ENANUU.mjs";
10
+ import {
11
+ __spreadProps,
12
+ __spreadValues
13
+ } from "./chunk-SKC7AJIV.mjs";
14
+
15
+ // src/hooks/use-langgraph-interrupt.ts
16
+ import { useContext, useEffect, useMemo } from "react";
17
+ import { dataToUUID } from "@copilotkit/shared";
18
+ function useLangGraphInterrupt(action, dependencies) {
19
+ var _a;
20
+ const { setLangGraphInterruptAction, removeLangGraphInterruptAction, langGraphInterruptAction } = useContext(CopilotContext);
21
+ const { runChatCompletion } = useCopilotChat();
22
+ const { addToast } = useToast();
23
+ const actionId = dataToUUID(JSON.stringify(action), "lgAction");
24
+ const hasAction = useMemo(
25
+ () => Boolean(langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.id),
26
+ [langGraphInterruptAction]
27
+ );
28
+ const isCurrentAction = useMemo(
29
+ () => (langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.id) && (langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.id) === actionId,
30
+ [langGraphInterruptAction]
31
+ );
32
+ useEffect(() => {
33
+ var _a2;
34
+ if (hasAction && isCurrentAction && ((_a2 = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event) == null ? void 0 : _a2.response)) {
35
+ runChatCompletion();
36
+ }
37
+ }, [(_a = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event) == null ? void 0 : _a.response, runChatCompletion, hasAction, isCurrentAction]);
38
+ useEffect(() => {
39
+ if (!action)
40
+ return;
41
+ if (hasAction && !isCurrentAction && !action.enabled) {
42
+ addToast({
43
+ type: "warning",
44
+ message: "An action is already registered for the interrupt event"
45
+ });
46
+ return;
47
+ }
48
+ if (hasAction && isCurrentAction) {
49
+ return;
50
+ }
51
+ setLangGraphInterruptAction(__spreadProps(__spreadValues({}, action), { id: actionId }));
52
+ }, [
53
+ action,
54
+ hasAction,
55
+ isCurrentAction,
56
+ setLangGraphInterruptAction,
57
+ removeLangGraphInterruptAction,
58
+ ...dependencies || []
59
+ ]);
60
+ }
61
+
62
+ export {
63
+ useLangGraphInterrupt
64
+ };
65
+ //# sourceMappingURL=chunk-FXVXAJVG.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-langgraph-interrupt.ts"],"sourcesContent":["import { useContext, useEffect, useMemo } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { LangGraphInterruptRender } from \"../types/interrupt-action\";\nimport { useCopilotChat } from \"./use-copilot-chat\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { dataToUUID } from \"@copilotkit/shared\";\n\nexport function useLangGraphInterrupt<TEventValue = any>(\n action: Omit<LangGraphInterruptRender<TEventValue>, \"id\">,\n dependencies?: any[],\n) {\n const { setLangGraphInterruptAction, removeLangGraphInterruptAction, langGraphInterruptAction } =\n useContext(CopilotContext);\n const { runChatCompletion } = useCopilotChat();\n const { addToast } = useToast();\n\n const actionId = dataToUUID(JSON.stringify(action), \"lgAction\");\n // We only consider action to be defined once the ID is there\n const hasAction = useMemo(\n () => Boolean(langGraphInterruptAction?.id),\n [langGraphInterruptAction],\n );\n\n const isCurrentAction = useMemo(\n () => langGraphInterruptAction?.id && langGraphInterruptAction?.id === actionId,\n [langGraphInterruptAction],\n );\n\n // Run chat completion to submit a response event. Only if it's the current action\n useEffect(() => {\n if (hasAction && isCurrentAction && langGraphInterruptAction?.event?.response) {\n runChatCompletion();\n }\n }, [langGraphInterruptAction?.event?.response, runChatCompletion, hasAction, isCurrentAction]);\n\n useEffect(() => {\n if (!action) return;\n // An action was already set, with no conditions and it's not the action we're using right now.\n // Show a warning, as this action will not be executed\n if (hasAction && !isCurrentAction && !action.enabled) {\n addToast({\n type: \"warning\",\n message: \"An action is already registered for the interrupt event\",\n });\n return;\n }\n\n if (hasAction && isCurrentAction) {\n return;\n }\n\n setLangGraphInterruptAction({ ...action, id: actionId });\n }, [\n action,\n hasAction,\n isCurrentAction,\n setLangGraphInterruptAction,\n removeLangGraphInterruptAction,\n ...(dependencies || []),\n ]);\n}\n"],"mapp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
4
4
 
5
5
  // src/hooks/use-copilot-readable.ts
6
6
  import { useEffect, useRef } from "react";
7
7
  function convertToJSON(description, value) {
8
8
  return `${description}: ${typeof value === "string" ? value : JSON.stringify(value)}`;
9
9
  }
10
- function useCopilotReadable({ description, value, parentId, categories, convert }, dependencies) {
10
+ function useCopilotReadable({
11
+ description,
12
+ value,
13
+ parentId,
14
+ categories,
15
+ convert,
16
+ available = "enabled"
17
+ }, dependencies) {
11
18
  const { addContext, removeContext } = useCopilotContext();
12
19
  const idRef = useRef();
13
20
  convert = convert || convertToJSON;
14
21
  const information = convert(description, value);
15
22
  useEffect(() => {
23
+ if (available === "disabled")
24
+ return;
16
25
  const id = addContext(information, parentId, categories);
17
26
  idRef.current = id;
18
27
  return () => {
19
28
  removeContext(id);
20
29
  };
21
- }, [information, parentId, addContext, removeContext, ...dependencies || []]);
30
+ }, [available, information, parentId, addContext, removeContext, ...dependencies || []]);
22
31
  return idRef.current;
23
32
  }
24
33
 
25
34
  export {
26
35
  useCopilotReadable
27
36
  };
28
- //# sourceMappingURL=chunk-FQ53HQYZ.mjs.map
37
+ //# sourceMappingURL=chunk-GOK4PDQO.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-copilot-readable.ts"],"sourcesContent":["/**\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * In its most basic usage, useCopilotReadable accepts a single string argument\n * representing any piece of app state, making it available for the Copilot to use\n * as context when responding to user input.\n *\n * ```tsx\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const [employees, setEmployees] = useState([]);\n *\n * useCopilotReadable({\n * description: \"The list of employees\",\n * value: employees,\n * });\n * }\n * ```\n *\n * ### Nested Components\n *\n * Optionally, you can maintain the hierarchical structure of information by passing\n * `parentId`. This allows you to use `useCopilotReadable` in nested components:\n *\n * ```tsx /employeeContextId/1 {17,23}\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * function Employee(props: EmployeeProps) {\n * const { employeeName, workProfile, metadata } = props;\n *\n * // propagate any information to copilot\n * const employeeContextId = useCopilotReadable({\n * description: \"Employee name\",\n * value: employeeName\n * });\n *\n * // Pass a parentID to maintain a hierarchical structure.\n * // Especially useful with child React components, list elements, etc.\n * useCopilotReadable({\n * description: \"Work profile\",\n * value: workProfile.description(),\n * parentId: employeeContextId\n * });\n *\n * useCopilotReadable({\n * description: \"Employee metadata\",\n * value: metadata.description(),\n * parentId: employeeContextId\n * });\n *\n * return (\n * // Render as usual...\n * );\n * }\n * ```\n */\nimport { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\n\n/**\n * Options for the useCopilotReadable hook.\n */\nexport interface UseCopilotReadableOptions {\n /**\n * The description of the information to be added to the Copilot context.\n */\n description: string;\n /**\n * The value to be added to the Copilot context. Object values are automatically stringified.\n */\n value: any;\n /**\n * The ID of the parent context, if any.\n */\n parentId?: string;\n /**\n * An array of categories to control which context are visible where. Particularly useful\n * with CopilotTextarea (see `useMakeAutosuggestionFunction`)\n */\n categories?: string[];\n\n /**\n * A custom conversion function to use to serialize the value to a string. If not provided, the value\n * will be serialized using `JSON.stringify`.\n */\n convert?: (description: string, value: any) => string;\n}\n\nfunction convertToJSON(description: string, value: any): string {\n return `${description}: ${typeof value === \"string\" ? value : JSON.stringify(value)}`;\n}\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n */\nexport function useCopilotReadable(\n { description, value, parentId, categories, convert }: UseCopilotReadableOptions,\n dependencies?: any[],\n): string | undefined {\n const { addContext, removeContext } = useCopilotContext();\n const idRef = useRef<string>();\n convert = convert || convertToJSON;\n\n const information = convert(description, value);\n\n useEffect(() => {\n const id = addContext(information, parentId, categories);\n idRef.current = id;\n\n return () => {\n removeContext(id);\n };\n }, [information, parentId, addContext, removeContext, ...(dependencies || [])]);\n\n return idRef.current;\n}\n"],"mappings":";;;;;AA+DA,SAAS,WAAW,cAAc;AAgClC,SAAS,cAAc,aAAqB,OAAoB;AAC9D,SAAO,GAAG,gBAAgB,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,KAAK;AACpF;AAKO,SAAS,mBACd,EAAE,aAAa,OAAO,UAAU,YAAY,QAAQ,GACpD,cACoB;AACpB,QAAM,EAAE,YAAY,cAAc,IAAI,kBAAkB;AACxD,QAAM,QAAQ,OAAe;AAC7B,YAAU,WAAW;AAErB,QAAM,cAAc,QAAQ,aAAa,KAAK;AAE9C,YAAU,MAAM;AACd,UAAM,KAAK,WAAW,aAAa,UAAU,UAAU;AACvD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,oBAAc,EAAE;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,aAAa,UAAU,YAAY,eAAe,GAAI,gBAAgB,CAAC,CAAE,CAAC;AAE9E,SAAO,MAAM;AACf;","names":[]}
1
+ {"version":3,"sources":["../src/hooks/use-copilot-readable.ts"],"sourcesContent":["/**\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * In its most basic usage, useCopilotReadable accepts a single string argument\n * representing any piece of app state, making it available for the Copilot to use\n * as context when responding to user input.\n *\n * ```tsx\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const [employees, setEmployees] = useState([]);\n *\n * useCopilotReadable({\n * description: \"The list of employees\",\n * value: employees,\n * });\n * }\n * ```\n *\n * ### Nested Components\n *\n * Optionally, you can maintain the hierarchical structure of information by passing\n * `parentId`. This allows you to use `useCopilotReadable` in nested components:\n *\n * ```tsx /employeeContextId/1 {17,23}\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * function Employee(props: EmployeeProps) {\n * const { employeeName, workProfile, metadata } = props;\n *\n * // propagate any information to copilot\n * const employeeContextId = useCopilotReadable({\n * description: \"Employee name\",\n * value: employeeName\n * });\n *\n * // Pass a parentID to maintain a hierarchical structure.\n * // Especially useful with child React components, list elements, etc.\n * useCopilotReadable({\n * description: \"Work profile\",\n * value: workProfile.description(),\n * parentId: employeeContextId\n * });\n *\n * useCopilotReadable({\n * description: \"Employee metadata\",\n * value: metadata.description(),\n * parentId: employeeContextId\n * });\n *\n * return (\n * // Render as usual...\n * );\n * }\n * ```\n */\nimport { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\n\n/**\n * Options for the useCopilotReadable hook.\n */\nexport interface UseCopilotReadableOptions {\n /**\n * The description of the information to be added to the Copilot context.\n */\n description: string;\n /**\n * The value to be added to the Copilot context. Object values are automatically stringified.\n */\n value: any;\n /**\n * The ID of the parent context, if any.\n */\n parentId?: string;\n /**\n * An array of categories to control which context are visible where. Particularly useful\n * with CopilotTextarea (see `useMakeAutosuggestionFunction`)\n */\n categories?: string[];\n\n /**\n * Whether the context is available to the Copilot.\n */\n available?: \"enabled\" | \"disabled\";\n\n /**\n * A custom conversion function to use to serialize the value to a string. If not provided, the value\n * will be serialized using `JSON.stringify`.\n */\n convert?: (description: string, value: any) => string;\n}\n\nfunction convertToJSON(description: string, value: any): string {\n return `${description}: ${typeof value === \"string\" ? value : JSON.stringify(value)}`;\n}\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n */\nexport function useCopilotReadable(\n {\n description,\n value,\n parentId,\n categories,\n convert,\n available = \"enabled\",\n }: UseCopilotReadableOptions,\n dependencies?: any[],\n): string | undefined {\n const { addContext, removeContext } = useCopilotContext();\n const idRef = useRef<string>();\n convert = convert || convertToJSON;\n\n const information = convert(description, value);\n\n useEffect(() => {\n if (available === \"disabled\") return;\n\n const id = addContext(information, parentId, categories);\n idRef.current = id;\n\n return () => {\n removeContext(id);\n };\n }, [available, information, parentId, addContext, removeContext, ...(dependencies || [])]);\n\n return idRef.current;\n}\n"],"mappings":";;;;;AA+DA,SAAS,WAAW,cAAc;AAqClC,SAAS,cAAc,aAAqB,OAAoB;AAC9D,SAAO,GAAG,gBAAgB,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,KAAK;AACpF;AAKO,SAAS,mBACd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AACd,GACA,cACoB;AACpB,QAAM,EAAE,YAAY,cAAc,IAAI,kBAAkB;AACxD,QAAM,QAAQ,OAAe;AAC7B,YAAU,WAAW;AAErB,QAAM,cAAc,QAAQ,aAAa,KAAK;AAE9C,YAAU,MAAM;AACd,QAAI,cAAc;AAAY;AAE9B,UAAM,KAAK,WAAW,aAAa,UAAU,UAAU;AACvD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,oBAAc,EAAE;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,WAAW,aAAa,UAAU,YAAY,eAAe,GAAI,gBAAgB,CAAC,CAAE,CAAC;AAEzF,SAAO,MAAM;AACf;","names":[]}
@@ -0,0 +1,63 @@
1
+ import {
2
+ useCopilotContext
3
+ } from "./chunk-UDUFMGWQ.mjs";
4
+ import {
5
+ CopilotMessagesContext
6
+ } from "./chunk-DCTJZ742.mjs";
7
+ import {
8
+ __async
9
+ } from "./chunk-SKC7AJIV.mjs";
10
+
11
+ // src/components/copilot-provider/copilot-messages.tsx
12
+ import { useEffect, useState, useRef } from "react";
13
+ import { loadMessagesFromJsonRepresentation } from "@copilotkit/runtime-client-gql";
14
+ import { jsx } from "react/jsx-runtime";
15
+ function CopilotMessages({ children }) {
16
+ const [messages, setMessages] = useState([]);
17
+ const lastLoadedThreadId = useRef();
18
+ const lastLoadedAgentName = useRef();
19
+ const lastLoadedMessages = useRef();
20
+ const { threadId, agentSession, runtimeClient } = useCopilotContext();
21
+ useEffect(() => {
22
+ if (!threadId || threadId === lastLoadedThreadId.current)
23
+ return;
24
+ if (threadId === lastLoadedThreadId.current && (agentSession == null ? void 0 : agentSession.agentName) === lastLoadedAgentName.current) {
25
+ return;
26
+ }
27
+ const fetchMessages = () => __async(this, null, function* () {
28
+ var _a, _b, _c, _d;
29
+ if (!(agentSession == null ? void 0 : agentSession.agentName))
30
+ return;
31
+ const result = yield runtimeClient.loadAgentState({
32
+ threadId,
33
+ agentName: agentSession == null ? void 0 : agentSession.agentName
34
+ });
35
+ const newMessages = (_b = (_a = result.data) == null ? void 0 : _a.loadAgentState) == null ? void 0 : _b.messages;
36
+ if (newMessages === lastLoadedMessages.current)
37
+ return;
38
+ if ((_d = (_c = result.data) == null ? void 0 : _c.loadAgentState) == null ? void 0 : _d.threadExists) {
39
+ lastLoadedMessages.current = newMessages;
40
+ lastLoadedThreadId.current = threadId;
41
+ lastLoadedAgentName.current = agentSession == null ? void 0 : agentSession.agentName;
42
+ const messages2 = loadMessagesFromJsonRepresentation(JSON.parse(newMessages || "[]"));
43
+ setMessages(messages2);
44
+ }
45
+ });
46
+ void fetchMessages();
47
+ }, [threadId, agentSession == null ? void 0 : agentSession.agentName]);
48
+ return /* @__PURE__ */ jsx(
49
+ CopilotMessagesContext.Provider,
50
+ {
51
+ value: {
52
+ messages,
53
+ setMessages
54
+ },
55
+ children
56
+ }
57
+ );
58
+ }
59
+
60
+ export {
61
+ CopilotMessages
62
+ };
63
+ //# sourceMappingURL=chunk-HGZXDC4Y.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/copilot-provider/copilot-messages.tsx"],"sourcesContent":["/**\n * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context\n */\n\nimport { ReactNode, useEffect, useState, useRef } from \"react\";\nimport { CopilotMessagesContext } from \"../../context/copilot-messages-context\";\nimport { loadMessagesFromJsonRepresentation, Message } from \"@copilotkit/runtime-client-gql\";\nimport { useCopilotContext } from \"../../context/copilot-context\";\n\nexport function CopilotMessages({ children }: { children: ReactNode }) {\n const [messages, setMessages] = useState<Message[]>([]);\n const lastLoadedThreadId = useRef<string>();\n const lastLoadedAgentName = useRef<string>();\n const lastLoadedMessages = useRef<string>();\n\n const { threadId, agentSession, runtimeClient } = useCopilotContext();\n\n useEffect(() => {\n if (!threadId || threadId === lastLoadedThreadId.current) return;\n if (\n threadId === lastLoadedThreadId.current &&\n agentSession?.agentName === lastLoadedAgentName.current\n ) {\n return;\n }\n\n const fetchMessages = async () => {\n if (!agentSession?.agentName) return;\n\n const result = await runtimeClient.loadAgentState({\n threadId,\n agentName: agentSession?.agentName,\n });\n\n const newMessages = result.data?.loadAgentState?.messages;\n if (newMessages === lastLoadedMessages.current) return;\n\n if (result.data?.loadAgentState?.threadExists) {\n lastLoadedMessages.current = newMessages;\n lastLoadedThreadId.current = threadId;\n lastLoadedAgentName.current = agentSession?.agentName;\n\n const messages = loadMessagesFromJsonRepresentation(JSON.parse(newMessages || \"[]\"));\n setMessages(messages);\n }\n };\n void fetchMessages();\n }, [threadId, agentSession?.agentName]);\n\n return (\n <CopilotMessagesContext.Provider\n value={{\n messages,\n setMessages,\n }}\n >\n {children}\n </CopilotMessagesContext.Provider>\n );\n}\n"],"mappings":";;;;;;;;;;;AAIA,SAAoB,WAAW,UAAU,cAAc;AAEvD,SAAS,0CAAmD;AA4CxD;AAzCG,SAAS,gBAAgB,EAAE,SAAS,GAA4B;AACrE,QAAM,CAAC,UAAU,WAAW,IAAI,SAAoB,CAAC,CAAC;AACtD,QAAM,qBAAqB,OAAe;AAC1C,QAAM,sBAAsB,OAAe;AAC3C,QAAM,qBAAqB,OAAe;AAE1C,QAAM,EAAE,UAAU,cAAc,cAAc,IAAI,kBAAkB;AAEpE,YAAU,MAAM;AACd,QAAI,CAAC,YAAY,aAAa,mBAAmB;AAAS;AAC1D,QACE,aAAa,mBAAmB,YAChC,6CAAc,eAAc,oBAAoB,SAChD;AACA;AAAA,IACF;AAEA,UAAM,gBAAgB,MAAY;AA1BtC;AA2BM,UAAI,EAAC,6CAAc;AAAW;AAE9B,YAAM,SAAS,MAAM,cAAc,eAAe;AAAA,QAChD;AAAA,QACA,WAAW,6CAAc;AAAA,MAC3B,CAAC;AAED,YAAM,eAAc,kBAAO,SAAP,mBAAa,mBAAb,mBAA6B;AACjD,UAAI,gBAAgB,mBAAmB;AAAS;AAEhD,WAAI,kBAAO,SAAP,mBAAa,mBAAb,mBAA6B,cAAc;AAC7C,2BAAmB,UAAU;AAC7B,2BAAmB,UAAU;AAC7B,4BAAoB,UAAU,6CAAc;AAE5C,cAAMA,YAAW,mCAAmC,KAAK,MAAM,eAAe,IAAI,CAAC;AACnF,oBAAYA,SAAQ;AAAA,MACtB;AAAA,IACF;AACA,SAAK,cAAc;AAAA,EACrB,GAAG,CAAC,UAAU,6CAAc,SAAS,CAAC;AAEtC,SACE;AAAA,IAAC,uBAAuB;AAAA,IAAvB;AAAA,MACC,OAAO;AAAA,QACL;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;","names":["messages"]}