@copilotkit/react-core 0.0.0-feat-dynamic-copilotcloud-qa-20250117190454

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 (293) hide show
  1. package/CHANGELOG.md +2001 -0
  2. package/README.md +48 -0
  3. package/dist/chunk-22XKTBPF.mjs +61 -0
  4. package/dist/chunk-22XKTBPF.mjs.map +1 -0
  5. package/dist/chunk-2KT73RVG.mjs +482 -0
  6. package/dist/chunk-2KT73RVG.mjs.map +1 -0
  7. package/dist/chunk-4TDYSNUD.mjs +215 -0
  8. package/dist/chunk-4TDYSNUD.mjs.map +1 -0
  9. package/dist/chunk-5FHSUKQL.mjs +70 -0
  10. package/dist/chunk-5FHSUKQL.mjs.map +1 -0
  11. package/dist/chunk-6BQVZFNO.mjs +35 -0
  12. package/dist/chunk-6BQVZFNO.mjs.map +1 -0
  13. package/dist/chunk-6U3UH3KO.mjs +140 -0
  14. package/dist/chunk-6U3UH3KO.mjs.map +1 -0
  15. package/dist/chunk-DCTJZ742.mjs +22 -0
  16. package/dist/chunk-DCTJZ742.mjs.map +1 -0
  17. package/dist/chunk-EFZPSZWO.mjs +1 -0
  18. package/dist/chunk-EFZPSZWO.mjs.map +1 -0
  19. package/dist/chunk-EWKJMQOF.mjs +107 -0
  20. package/dist/chunk-EWKJMQOF.mjs.map +1 -0
  21. package/dist/chunk-FQ53HQYZ.mjs +28 -0
  22. package/dist/chunk-FQ53HQYZ.mjs.map +1 -0
  23. package/dist/chunk-HIUT2NLX.mjs +23 -0
  24. package/dist/chunk-HIUT2NLX.mjs.map +1 -0
  25. package/dist/chunk-KSPLXKSX.mjs +160 -0
  26. package/dist/chunk-KSPLXKSX.mjs.map +1 -0
  27. package/dist/chunk-LHKIIAUQ.mjs +59 -0
  28. package/dist/chunk-LHKIIAUQ.mjs.map +1 -0
  29. package/dist/chunk-LNI2Z45S.mjs +242 -0
  30. package/dist/chunk-LNI2Z45S.mjs.map +1 -0
  31. package/dist/chunk-LUGEI4YQ.mjs +1 -0
  32. package/dist/chunk-LUGEI4YQ.mjs.map +1 -0
  33. package/dist/chunk-MLAS4QUR.mjs +18 -0
  34. package/dist/chunk-MLAS4QUR.mjs.map +1 -0
  35. package/dist/chunk-NR2BTA6Z.mjs +1 -0
  36. package/dist/chunk-NR2BTA6Z.mjs.map +1 -0
  37. package/dist/chunk-O7ARI5CV.mjs +31 -0
  38. package/dist/chunk-O7ARI5CV.mjs.map +1 -0
  39. package/dist/chunk-SKC7AJIV.mjs +61 -0
  40. package/dist/chunk-SKC7AJIV.mjs.map +1 -0
  41. package/dist/chunk-U6JICUGO.mjs +405 -0
  42. package/dist/chunk-U6JICUGO.mjs.map +1 -0
  43. package/dist/chunk-VNTDIJSG.mjs +37 -0
  44. package/dist/chunk-VNTDIJSG.mjs.map +1 -0
  45. package/dist/chunk-WXREY7UP.mjs +87 -0
  46. package/dist/chunk-WXREY7UP.mjs.map +1 -0
  47. package/dist/chunk-XERJQUHA.mjs +31 -0
  48. package/dist/chunk-XERJQUHA.mjs.map +1 -0
  49. package/dist/chunk-XOQMISG3.mjs +120 -0
  50. package/dist/chunk-XOQMISG3.mjs.map +1 -0
  51. package/dist/chunk-XXR4QFAQ.mjs +29 -0
  52. package/dist/chunk-XXR4QFAQ.mjs.map +1 -0
  53. package/dist/chunk-YPSGKPDA.mjs +1 -0
  54. package/dist/chunk-YPSGKPDA.mjs.map +1 -0
  55. package/dist/components/copilot-provider/copilot-messages.d.ts +16 -0
  56. package/dist/components/copilot-provider/copilot-messages.js +80 -0
  57. package/dist/components/copilot-provider/copilot-messages.js.map +1 -0
  58. package/dist/components/copilot-provider/copilot-messages.mjs +9 -0
  59. package/dist/components/copilot-provider/copilot-messages.mjs.map +1 -0
  60. package/dist/components/copilot-provider/copilotkit-props.d.ts +93 -0
  61. package/dist/components/copilot-provider/copilotkit-props.js +19 -0
  62. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -0
  63. package/dist/components/copilot-provider/copilotkit-props.mjs +1 -0
  64. package/dist/components/copilot-provider/copilotkit-props.mjs.map +1 -0
  65. package/dist/components/copilot-provider/copilotkit.d.ts +18 -0
  66. package/dist/components/copilot-provider/copilotkit.js +990 -0
  67. package/dist/components/copilot-provider/copilotkit.js.map +1 -0
  68. package/dist/components/copilot-provider/copilotkit.mjs +22 -0
  69. package/dist/components/copilot-provider/copilotkit.mjs.map +1 -0
  70. package/dist/components/copilot-provider/index.d.ts +13 -0
  71. package/dist/components/copilot-provider/index.js +990 -0
  72. package/dist/components/copilot-provider/index.js.map +1 -0
  73. package/dist/components/copilot-provider/index.mjs +20 -0
  74. package/dist/components/copilot-provider/index.mjs.map +1 -0
  75. package/dist/components/error-boundary/error-boundary.d.ts +22 -0
  76. package/dist/components/error-boundary/error-boundary.js +183 -0
  77. package/dist/components/error-boundary/error-boundary.js.map +1 -0
  78. package/dist/components/error-boundary/error-boundary.mjs +12 -0
  79. package/dist/components/error-boundary/error-boundary.mjs.map +1 -0
  80. package/dist/components/error-boundary/error-utils.d.ts +11 -0
  81. package/dist/components/error-boundary/error-utils.js +177 -0
  82. package/dist/components/error-boundary/error-utils.js.map +1 -0
  83. package/dist/components/error-boundary/error-utils.mjs +13 -0
  84. package/dist/components/error-boundary/error-utils.mjs.map +1 -0
  85. package/dist/components/index.d.ts +13 -0
  86. package/dist/components/index.js +990 -0
  87. package/dist/components/index.js.map +1 -0
  88. package/dist/components/index.mjs +20 -0
  89. package/dist/components/index.mjs.map +1 -0
  90. package/dist/components/toast/exclamation-mark-icon.d.ts +9 -0
  91. package/dist/components/toast/exclamation-mark-icon.js +55 -0
  92. package/dist/components/toast/exclamation-mark-icon.js.map +1 -0
  93. package/dist/components/toast/exclamation-mark-icon.mjs +8 -0
  94. package/dist/components/toast/exclamation-mark-icon.mjs.map +1 -0
  95. package/dist/components/toast/toast-provider.d.ts +30 -0
  96. package/dist/components/toast/toast-provider.js +269 -0
  97. package/dist/components/toast/toast-provider.js.map +1 -0
  98. package/dist/components/toast/toast-provider.mjs +11 -0
  99. package/dist/components/toast/toast-provider.mjs.map +1 -0
  100. package/dist/context/copilot-context.d.ts +142 -0
  101. package/dist/context/copilot-context.js +138 -0
  102. package/dist/context/copilot-context.js.map +1 -0
  103. package/dist/context/copilot-context.mjs +10 -0
  104. package/dist/context/copilot-context.mjs.map +1 -0
  105. package/dist/context/copilot-messages-context.d.ts +15 -0
  106. package/dist/context/copilot-messages-context.js +57 -0
  107. package/dist/context/copilot-messages-context.js.map +1 -0
  108. package/dist/context/copilot-messages-context.mjs +10 -0
  109. package/dist/context/copilot-messages-context.mjs.map +1 -0
  110. package/dist/context/index.d.ts +11 -0
  111. package/dist/context/index.js +161 -0
  112. package/dist/context/index.js.map +1 -0
  113. package/dist/context/index.mjs +17 -0
  114. package/dist/context/index.mjs.map +1 -0
  115. package/dist/hooks/index.d.ts +21 -0
  116. package/dist/hooks/index.js +1307 -0
  117. package/dist/hooks/index.js.map +1 -0
  118. package/dist/hooks/index.mjs +56 -0
  119. package/dist/hooks/index.mjs.map +1 -0
  120. package/dist/hooks/use-chat.d.ts +130 -0
  121. package/dist/hooks/use-chat.js +612 -0
  122. package/dist/hooks/use-chat.js.map +1 -0
  123. package/dist/hooks/use-chat.mjs +12 -0
  124. package/dist/hooks/use-chat.mjs.map +1 -0
  125. package/dist/hooks/use-coagent-state-render.d.ts +60 -0
  126. package/dist/hooks/use-coagent-state-render.js +195 -0
  127. package/dist/hooks/use-coagent-state-render.js.map +1 -0
  128. package/dist/hooks/use-coagent-state-render.mjs +11 -0
  129. package/dist/hooks/use-coagent-state-render.mjs.map +1 -0
  130. package/dist/hooks/use-coagent.d.ts +199 -0
  131. package/dist/hooks/use-coagent.js +1068 -0
  132. package/dist/hooks/use-coagent.js.map +1 -0
  133. package/dist/hooks/use-coagent.mjs +29 -0
  134. package/dist/hooks/use-coagent.mjs.map +1 -0
  135. package/dist/hooks/use-copilot-action.d.ts +140 -0
  136. package/dist/hooks/use-copilot-action.js +369 -0
  137. package/dist/hooks/use-copilot-action.js.map +1 -0
  138. package/dist/hooks/use-copilot-action.mjs +11 -0
  139. package/dist/hooks/use-copilot-action.mjs.map +1 -0
  140. package/dist/hooks/use-copilot-authenticated-action.d.ts +8 -0
  141. package/dist/hooks/use-copilot-authenticated-action.js +418 -0
  142. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -0
  143. package/dist/hooks/use-copilot-authenticated-action.mjs +12 -0
  144. package/dist/hooks/use-copilot-authenticated-action.mjs.map +1 -0
  145. package/dist/hooks/use-copilot-chat.d.ts +48 -0
  146. package/dist/hooks/use-copilot-chat.js +932 -0
  147. package/dist/hooks/use-copilot-chat.js.map +1 -0
  148. package/dist/hooks/use-copilot-chat.mjs +24 -0
  149. package/dist/hooks/use-copilot-chat.mjs.map +1 -0
  150. package/dist/hooks/use-copilot-readable.d.ts +33 -0
  151. package/dist/hooks/use-copilot-readable.js +158 -0
  152. package/dist/hooks/use-copilot-readable.js.map +1 -0
  153. package/dist/hooks/use-copilot-readable.mjs +9 -0
  154. package/dist/hooks/use-copilot-readable.mjs.map +1 -0
  155. package/dist/hooks/use-copilot-runtime-client.d.ts +5 -0
  156. package/dist/hooks/use-copilot-runtime-client.js +182 -0
  157. package/dist/hooks/use-copilot-runtime-client.js.map +1 -0
  158. package/dist/hooks/use-copilot-runtime-client.mjs +10 -0
  159. package/dist/hooks/use-copilot-runtime-client.mjs.map +1 -0
  160. package/dist/hooks/use-flat-category-store.d.ts +9 -0
  161. package/dist/hooks/use-flat-category-store.js +90 -0
  162. package/dist/hooks/use-flat-category-store.js.map +1 -0
  163. package/dist/hooks/use-flat-category-store.mjs +8 -0
  164. package/dist/hooks/use-flat-category-store.mjs.map +1 -0
  165. package/dist/hooks/use-make-copilot-document-readable.d.ts +12 -0
  166. package/dist/hooks/use-make-copilot-document-readable.js +153 -0
  167. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -0
  168. package/dist/hooks/use-make-copilot-document-readable.mjs +9 -0
  169. package/dist/hooks/use-make-copilot-document-readable.mjs.map +1 -0
  170. package/dist/hooks/use-tree.d.ts +18 -0
  171. package/dist/hooks/use-tree.js +172 -0
  172. package/dist/hooks/use-tree.js.map +1 -0
  173. package/dist/hooks/use-tree.mjs +8 -0
  174. package/dist/hooks/use-tree.mjs.map +1 -0
  175. package/dist/index.d.ts +27 -0
  176. package/dist/index.js +2228 -0
  177. package/dist/index.js.map +1 -0
  178. package/dist/index.mjs +83 -0
  179. package/dist/index.mjs.map +1 -0
  180. package/dist/lib/copilot-task.d.ts +97 -0
  181. package/dist/lib/copilot-task.js +195 -0
  182. package/dist/lib/copilot-task.js.map +1 -0
  183. package/dist/lib/copilot-task.mjs +20 -0
  184. package/dist/lib/copilot-task.mjs.map +1 -0
  185. package/dist/lib/index.d.ts +11 -0
  186. package/dist/lib/index.js +197 -0
  187. package/dist/lib/index.js.map +1 -0
  188. package/dist/lib/index.mjs +21 -0
  189. package/dist/lib/index.mjs.map +1 -0
  190. package/dist/types/chat-suggestion-configuration.d.ts +22 -0
  191. package/dist/types/chat-suggestion-configuration.js +19 -0
  192. package/dist/types/chat-suggestion-configuration.js.map +1 -0
  193. package/dist/types/chat-suggestion-configuration.mjs +1 -0
  194. package/dist/types/chat-suggestion-configuration.mjs.map +1 -0
  195. package/dist/types/coagent-action.d.ts +29 -0
  196. package/dist/types/coagent-action.js +19 -0
  197. package/dist/types/coagent-action.js.map +1 -0
  198. package/dist/types/coagent-action.mjs +1 -0
  199. package/dist/types/coagent-action.mjs.map +1 -0
  200. package/dist/types/coagent-state.d.ts +11 -0
  201. package/dist/types/coagent-state.js +19 -0
  202. package/dist/types/coagent-state.js.map +1 -0
  203. package/dist/types/coagent-state.mjs +1 -0
  204. package/dist/types/coagent-state.mjs.map +1 -0
  205. package/dist/types/document-pointer.d.ts +9 -0
  206. package/dist/types/document-pointer.js +19 -0
  207. package/dist/types/document-pointer.js.map +1 -0
  208. package/dist/types/document-pointer.mjs +1 -0
  209. package/dist/types/document-pointer.mjs.map +1 -0
  210. package/dist/types/frontend-action.d.ts +126 -0
  211. package/dist/types/frontend-action.js +53 -0
  212. package/dist/types/frontend-action.js.map +1 -0
  213. package/dist/types/frontend-action.mjs +8 -0
  214. package/dist/types/frontend-action.mjs.map +1 -0
  215. package/dist/types/index.d.ts +7 -0
  216. package/dist/types/index.js +19 -0
  217. package/dist/types/index.js.map +1 -0
  218. package/dist/types/index.mjs +2 -0
  219. package/dist/types/index.mjs.map +1 -0
  220. package/dist/types/system-message.d.ts +3 -0
  221. package/dist/types/system-message.js +19 -0
  222. package/dist/types/system-message.js.map +1 -0
  223. package/dist/types/system-message.mjs +1 -0
  224. package/dist/types/system-message.mjs.map +1 -0
  225. package/dist/utils/dev-console.d.ts +3 -0
  226. package/dist/utils/dev-console.js +42 -0
  227. package/dist/utils/dev-console.js.map +1 -0
  228. package/dist/utils/dev-console.mjs +8 -0
  229. package/dist/utils/dev-console.mjs.map +1 -0
  230. package/dist/utils/extract.d.ts +43 -0
  231. package/dist/utils/extract.js +208 -0
  232. package/dist/utils/extract.js.map +1 -0
  233. package/dist/utils/extract.mjs +18 -0
  234. package/dist/utils/extract.mjs.map +1 -0
  235. package/dist/utils/index.d.ts +13 -0
  236. package/dist/utils/index.js +226 -0
  237. package/dist/utils/index.js.map +1 -0
  238. package/dist/utils/index.mjs +21 -0
  239. package/dist/utils/index.mjs.map +1 -0
  240. package/dist/utils/utils.d.ts +2 -0
  241. package/dist/utils/utils.js +19 -0
  242. package/dist/utils/utils.js.map +1 -0
  243. package/dist/utils/utils.mjs +1 -0
  244. package/dist/utils/utils.mjs.map +1 -0
  245. package/dist/utils/utils.test.d.ts +2 -0
  246. package/dist/utils/utils.test.js +9 -0
  247. package/dist/utils/utils.test.js.map +1 -0
  248. package/dist/utils/utils.test.mjs +7 -0
  249. package/dist/utils/utils.test.mjs.map +1 -0
  250. package/jest.config.js +5 -0
  251. package/package.json +69 -0
  252. package/src/components/copilot-provider/copilot-messages.tsx +23 -0
  253. package/src/components/copilot-provider/copilotkit-props.tsx +97 -0
  254. package/src/components/copilot-provider/copilotkit.tsx +401 -0
  255. package/src/components/copilot-provider/index.ts +3 -0
  256. package/src/components/error-boundary/error-boundary.tsx +42 -0
  257. package/src/components/error-boundary/error-utils.tsx +95 -0
  258. package/src/components/index.ts +1 -0
  259. package/src/components/toast/exclamation-mark-icon.tsx +27 -0
  260. package/src/components/toast/toast-provider.tsx +170 -0
  261. package/src/context/copilot-context.tsx +271 -0
  262. package/src/context/copilot-messages-context.tsx +29 -0
  263. package/src/context/index.ts +8 -0
  264. package/src/hooks/index.ts +12 -0
  265. package/src/hooks/use-chat.ts +649 -0
  266. package/src/hooks/use-coagent-state-render.ts +118 -0
  267. package/src/hooks/use-coagent.ts +368 -0
  268. package/src/hooks/use-copilot-action.ts +289 -0
  269. package/src/hooks/use-copilot-authenticated-action.ts +60 -0
  270. package/src/hooks/use-copilot-chat.ts +304 -0
  271. package/src/hooks/use-copilot-readable.ts +123 -0
  272. package/src/hooks/use-copilot-runtime-client.ts +28 -0
  273. package/src/hooks/use-flat-category-store.ts +104 -0
  274. package/src/hooks/use-make-copilot-document-readable.ts +30 -0
  275. package/src/hooks/use-tree.ts +202 -0
  276. package/src/index.tsx +7 -0
  277. package/src/lib/copilot-task.ts +201 -0
  278. package/src/lib/index.ts +1 -0
  279. package/src/types/chat-suggestion-configuration.ts +23 -0
  280. package/src/types/coagent-action.ts +31 -0
  281. package/src/types/coagent-state.ts +9 -0
  282. package/src/types/document-pointer.ts +7 -0
  283. package/src/types/frontend-action.ts +199 -0
  284. package/src/types/index.ts +8 -0
  285. package/src/types/system-message.ts +4 -0
  286. package/src/utils/dev-console.ts +18 -0
  287. package/src/utils/extract.ts +215 -0
  288. package/src/utils/index.ts +2 -0
  289. package/src/utils/utils.test.ts +7 -0
  290. package/src/utils/utils.ts +1 -0
  291. package/tsconfig.json +12 -0
  292. package/tsup.config.ts +16 -0
  293. package/typedoc.json +4 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-action.ts"],"sourcesContent":["/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { Parameter, randomId } from \"@copilotkit/shared\";\nimport { createElement, Fragment, useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport {\n ActionRenderProps,\n ActionRenderPropsNoArgsWait,\n ActionRenderPropsWait,\n CatchAllFrontendAction,\n FrontendAction,\n} from \"../types/frontend-action\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();\n const idRef = useRef<string>(randomId());\n const renderAndWaitRef = useRef<RenderAndWaitForResponse | null>(null);\n\n // clone the action to avoid mutating the original object\n action = { ...action };\n\n // If the developer provides a renderAndWaitForResponse function, we transform the action\n // to use a promise internally, so that we can treat it like a normal action.\n if (\n // renderAndWaitForResponse is not available for catch all actions\n isFrontendAction(action) &&\n // check if renderAndWaitForResponse is set\n (action.renderAndWait || action.renderAndWaitForResponse)\n ) {\n const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;\n // remove the renderAndWait function from the action\n action.renderAndWait = undefined;\n action.renderAndWaitForResponse = undefined;\n // add a handler that will be called when the action is executed\n action.handler = useAsyncCallback(async () => {\n // we create a new promise when the handler is called\n let resolve: (result: any) => void;\n let reject: (error: any) => void;\n const promise = new Promise<any>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n renderAndWaitRef.current = { promise, resolve: resolve!, reject: reject! };\n // then we await the promise (it will be resolved in the original renderAndWait function)\n return await promise;\n }, []) as any;\n\n // add a render function that will be called when the action is rendered\n action.render = ((props: ActionRenderProps<T>): React.ReactElement => {\n // Specifically for renderAndWaitForResponse the executing state is set too early, causing a race condition\n // To fit it: we will wait for the handler to be ready\n let status = props.status;\n if (props.status === \"executing\" && !renderAndWaitRef.current) {\n status = \"inProgress\";\n }\n // Create type safe waitProps based on whether T extends empty array or not\n const waitProps = {\n status,\n args: props.args,\n result: props.result,\n handler: status === \"executing\" ? renderAndWaitRef.current!.resolve : undefined,\n respond: status === \"executing\" ? renderAndWaitRef.current!.resolve : undefined,\n } as T extends [] ? ActionRenderPropsNoArgsWait<T> : ActionRenderPropsWait<T>;\n\n // Type guard to check if renderAndWait is for no args case\n const isNoArgsRenderWait = (\n _fn:\n | ((props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement)\n | ((props: ActionRenderPropsWait<T>) => React.ReactElement),\n ): _fn is (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement => {\n return action.parameters?.length === 0;\n };\n\n // Safely call renderAndWait with correct props type\n if (renderAndWait) {\n if (isNoArgsRenderWait(renderAndWait)) {\n return renderAndWait(waitProps as ActionRenderPropsNoArgsWait<T>);\n } else {\n return renderAndWait(waitProps as ActionRenderPropsWait<T>);\n }\n }\n\n // Return empty Fragment instead of null\n return createElement(Fragment);\n }) as any;\n }\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n // catch all actions don't have a handler\n if (isFrontendAction(action)) {\n actions[idRef.current].handler = action.handler as any;\n }\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n // TODO: using as any here because the type definitions are getting to tricky\n // not wasting time on this now - we know the types are compatible\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n }\n }\n }\n\n useEffect(() => {\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n // see comment about type safety above\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n // UPDATE: We now have access, we should remove the entry if not referenced by any message.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n isFrontendAction(action) ? action.description : undefined,\n action.name,\n isFrontendAction(action) ? action.disabled : undefined,\n isFrontendAction(action) ? action.available : undefined,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(isFrontendAction(action) ? action.parameters : []),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\nfunction isFrontendAction<T extends Parameter[]>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n): action is FrontendAction<T> {\n return action.name !== \"*\";\n}\n\ninterface Render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, useRef } from "react";
7
+ function convertToJSON(description, value) {
8
+ return `${description}: ${typeof value === "string" ? value : JSON.stringify(value)}`;
9
+ }
10
+ function useCopilotReadable({ description, value, parentId, categories, convert }, dependencies) {
11
+ const { addContext, removeContext } = useCopilotContext();
12
+ const idRef = useRef();
13
+ convert = convert || convertToJSON;
14
+ const information = convert(description, value);
15
+ useEffect(() => {
16
+ const id = addContext(information, parentId, categories);
17
+ idRef.current = id;
18
+ return () => {
19
+ removeContext(id);
20
+ };
21
+ }, [information, parentId, addContext, removeContext, ...dependencies || []]);
22
+ return idRef.current;
23
+ }
24
+
25
+ export {
26
+ useCopilotReadable
27
+ };
28
+ //# sourceMappingURL=chunk-FQ53HQYZ.mjs.map
@@ -0,0 +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":[]}
@@ -0,0 +1,23 @@
1
+ import {
2
+ useCopilotContext
3
+ } from "./chunk-WXREY7UP.mjs";
4
+
5
+ // src/hooks/use-make-copilot-document-readable.ts
6
+ import { useEffect, useRef } from "react";
7
+ function useMakeCopilotDocumentReadable(document, categories, dependencies = []) {
8
+ const { addDocumentContext, removeDocumentContext } = useCopilotContext();
9
+ const idRef = useRef();
10
+ useEffect(() => {
11
+ const id = addDocumentContext(document, categories);
12
+ idRef.current = id;
13
+ return () => {
14
+ removeDocumentContext(id);
15
+ };
16
+ }, [addDocumentContext, removeDocumentContext, ...dependencies]);
17
+ return idRef.current;
18
+ }
19
+
20
+ export {
21
+ useMakeCopilotDocumentReadable
22
+ };
23
+ //# sourceMappingURL=chunk-HIUT2NLX.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-make-copilot-document-readable.ts"],"sourcesContent":["import { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Makes a document readable by Copilot.\n * @param document The document to make readable.\n * @param categories The categories to associate with the document.\n * @param dependencies The dependencies to use for the effect.\n * @returns The id of the document.\n */\nexport function useMakeCopilotDocumentReadable(\n document: DocumentPointer,\n categories?: string[],\n dependencies: any[] = [],\n): string | undefined {\n const { addDocumentContext, removeDocumentContext } = useCopilotContext();\n const idRef = useRef<string>();\n\n useEffect(() => {\n const id = addDocumentContext(document, categories);\n idRef.current = id;\n\n return () => {\n removeDocumentContext(id);\n };\n }, [addDocumentContext, removeDocumentContext, ...dependencies]);\n\n return idRef.current;\n}\n"],"mappings":";;;;;AAAA,SAAS,WAAW,cAAc;AAW3B,SAAS,+BACd,UACA,YACA,eAAsB,CAAC,GACH;AACpB,QAAM,EAAE,oBAAoB,sBAAsB,IAAI,kBAAkB;AACxE,QAAM,QAAQ,OAAe;AAE7B,YAAU,MAAM;AACd,UAAM,KAAK,mBAAmB,UAAU,UAAU;AAClD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,4BAAsB,EAAE;AAAA,IAC1B;AAAA,EACF,GAAG,CAAC,oBAAoB,uBAAuB,GAAG,YAAY,CAAC;AAE/D,SAAO,MAAM;AACf;","names":[]}
@@ -0,0 +1,160 @@
1
+ import {
2
+ useCopilotChat
3
+ } from "./chunk-4TDYSNUD.mjs";
4
+ import {
5
+ useCopilotMessagesContext
6
+ } from "./chunk-DCTJZ742.mjs";
7
+ import {
8
+ useCopilotContext
9
+ } from "./chunk-WXREY7UP.mjs";
10
+ import {
11
+ useAsyncCallback,
12
+ useToast
13
+ } from "./chunk-LNI2Z45S.mjs";
14
+ import {
15
+ __async,
16
+ __spreadProps,
17
+ __spreadValues
18
+ } from "./chunk-SKC7AJIV.mjs";
19
+
20
+ // src/hooks/use-coagent.ts
21
+ import { useEffect } from "react";
22
+ function useCoAgent(options) {
23
+ const generalContext = useCopilotContext();
24
+ const { availableAgents } = generalContext;
25
+ const { addToast } = useToast();
26
+ const isExternalStateManagement = (options2) => {
27
+ return "state" in options2 && "setState" in options2;
28
+ };
29
+ const { name } = options;
30
+ useEffect(() => {
31
+ if ((availableAgents == null ? void 0 : availableAgents.length) && !availableAgents.some((a) => a.name === name)) {
32
+ const message = `(useCoAgent): Agent "${name}" not found. Make sure the agent exists and is properly configured.`;
33
+ console.warn(message);
34
+ addToast({ type: "warning", message });
35
+ }
36
+ }, [availableAgents]);
37
+ const isInternalStateManagementWithInitial = (options2) => {
38
+ return "initialState" in options2;
39
+ };
40
+ const messagesContext = useCopilotMessagesContext();
41
+ const context = __spreadValues(__spreadValues({}, generalContext), messagesContext);
42
+ const { coagentStates, coagentStatesRef, setCoagentStatesWithRef } = context;
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;
70
+ useEffect(() => {
71
+ if (isExternalStateManagement(options)) {
72
+ setState(options.state);
73
+ } else if (coagentStates[name] === void 0) {
74
+ setState(options.initialState === void 0 ? {} : options.initialState);
75
+ }
76
+ }, [
77
+ isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0,
78
+ // reset initialstate on reset
79
+ coagentStates[name] === void 0
80
+ ]);
81
+ const runAgentCallback = useAsyncCallback(
82
+ (hint) => __async(this, null, function* () {
83
+ yield runAgent(name, context, appendMessage, runChatCompletion, hint);
84
+ }),
85
+ [name, context, appendMessage, runChatCompletion]
86
+ );
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
+ };
98
+ }
99
+ function startAgent(name, context) {
100
+ const { setAgentSession } = context;
101
+ setAgentSession({
102
+ agentName: name
103
+ });
104
+ }
105
+ function stopAgent(name, context) {
106
+ const { agentSession, setAgentSession } = context;
107
+ if (agentSession && agentSession.agentName === name) {
108
+ setAgentSession(null);
109
+ context.setCoagentStates((prevAgentStates) => {
110
+ return __spreadProps(__spreadValues({}, prevAgentStates), {
111
+ [name]: __spreadProps(__spreadValues({}, prevAgentStates[name]), {
112
+ running: false,
113
+ active: false,
114
+ threadId: void 0,
115
+ nodeName: void 0,
116
+ runId: void 0
117
+ })
118
+ });
119
+ });
120
+ } else {
121
+ console.warn(`No agent session found for ${name}`);
122
+ }
123
+ }
124
+ function runAgent(name, context, appendMessage, runChatCompletion, hint) {
125
+ return __async(this, null, function* () {
126
+ var _a, _b;
127
+ const { agentSession, setAgentSession } = context;
128
+ if (!agentSession || agentSession.agentName !== name) {
129
+ setAgentSession({
130
+ agentName: name
131
+ });
132
+ }
133
+ let previousState = null;
134
+ for (let i = context.messages.length - 1; i >= 0; i--) {
135
+ const message = context.messages[i];
136
+ if (message.isAgentStateMessage() && message.agentName === name) {
137
+ previousState = message.state;
138
+ }
139
+ }
140
+ let state = ((_b = (_a = context.coagentStatesRef.current) == null ? void 0 : _a[name]) == null ? void 0 : _b.state) || {};
141
+ if (hint) {
142
+ const hintMessage = hint({ previousState, currentState: state });
143
+ if (hintMessage) {
144
+ yield appendMessage(hintMessage);
145
+ } else {
146
+ yield runChatCompletion();
147
+ }
148
+ } else {
149
+ yield runChatCompletion();
150
+ }
151
+ });
152
+ }
153
+
154
+ export {
155
+ useCoAgent,
156
+ startAgent,
157
+ stopAgent,
158
+ runAgent
159
+ };
160
+ //# sourceMappingURL=chunk-KSPLXKSX.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)</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 { useEffect } 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 { flushSync } from \"react-dom\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { useToast } from \"../components/toast/toast-provider\";\n\ninterface WithInternalStateManagementAndInitial<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\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.\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 isExternalStateManagement = (\n options: UseCoagentOptions<T>,\n ): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n };\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 isInternalStateManagementWithInitial = (\n options: UseCoagentOptions<T>,\n ): options is WithInternalStateManagementAndInitial<T> => {\n return \"initialState\" in options;\n };\n\n const messagesContext = useCopilotMessagesContext();\n const context = { ...generalContext, ...messagesContext };\n const { coagentStates, coagentStatesRef, setCoagentStatesWithRef } = context;\n const { appendMessage, runChatCompletion } = useCopilotChat();\n\n const getCoagentState = (coagentStates: Record<string, CoagentState>, name: string) => {\n if (coagentStates[name]) {\n return coagentStates[name];\n } else {\n return {\n name,\n state: isInternalStateManagementWithInitial(options) ? options.initialState : {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n }\n };\n\n // if we manage state internally, we need to provide a function to set the state\n const setState = (newState: T | ((prevState: T | undefined) => T)) => {\n let coagentState: CoagentState = getCoagentState(coagentStatesRef.current || {}, name);\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\n const coagentState = getCoagentState(coagentStates, name);\n\n const state = isExternalStateManagement(options) ? options.state : coagentState.state;\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 {\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}\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AA0FA,SAAS,iBAAiB;AAmHnB,SAAS,WAAoB,SAAwD;AAC1F,QAAM,iBAAiB,kBAAkB;AACzC,QAAM,EAAE,gBAAgB,IAAI;AAC5B,QAAM,EAAE,SAAS,IAAI,SAAS;AAC9B,QAAM,4BAA4B,CAChCA,aAC8C;AAC9C,WAAO,WAAWA,YAAW,cAAcA;AAAA,EAC7C;AAEA,QAAM,EAAE,KAAK,IAAI;AACjB,YAAU,MAAM;AACd,SAAI,mDAAiB,WAAU,CAAC,gBAAgB,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI,GAAG;AAC5E,YAAM,UAAU,wBAAwB;AACxC,cAAQ,KAAK,OAAO;AACpB,eAAS,EAAE,MAAM,WAAW,QAAQ,CAAC;AAAA,IACvC;AAAA,EACF,GAAG,CAAC,eAAe,CAAC;AAEpB,QAAM,uCAAuC,CAC3CA,aACwD;AACxD,WAAO,kBAAkBA;AAAA,EAC3B;AAEA,QAAM,kBAAkB,0BAA0B;AAClD,QAAM,UAAU,kCAAK,iBAAmB;AACxC,QAAM,EAAE,eAAe,kBAAkB,wBAAwB,IAAI;AACrE,QAAM,EAAE,eAAe,kBAAkB,IAAI,eAAe;AAE5D,QAAM,kBAAkB,CAACC,gBAA6CC,UAAiB;AACrF,QAAID,eAAcC,KAAI,GAAG;AACvB,aAAOD,eAAcC,KAAI;AAAA,IAC3B,OAAO;AACL,aAAO;AAAA,QACL,MAAA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,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;","names":["options","coagentStates","name","coagentState"]}
@@ -0,0 +1,59 @@
1
+ import {
2
+ useCopilotAction
3
+ } from "./chunk-EWKJMQOF.mjs";
4
+ import {
5
+ useCopilotContext
6
+ } from "./chunk-WXREY7UP.mjs";
7
+ import {
8
+ __spreadProps,
9
+ __spreadValues
10
+ } from "./chunk-SKC7AJIV.mjs";
11
+
12
+ // src/hooks/use-copilot-authenticated-action.ts
13
+ import { Fragment, useCallback, useRef } from "react";
14
+ import React from "react";
15
+ function useCopilotAuthenticatedAction(action, dependencies) {
16
+ const { authConfig, authStates, setAuthStates } = useCopilotContext();
17
+ const pendingActionRef = useRef(null);
18
+ const executeAction = useCallback(
19
+ (props) => {
20
+ if (typeof action.render === "function") {
21
+ return action.render(props);
22
+ }
23
+ return action.render || React.createElement(Fragment);
24
+ },
25
+ [action]
26
+ );
27
+ const wrappedRender = useCallback(
28
+ (props) => {
29
+ const isAuthenticated = Object.values(authStates || {}).some(
30
+ (state) => state.status === "authenticated"
31
+ );
32
+ if (!isAuthenticated) {
33
+ pendingActionRef.current = props;
34
+ return (authConfig == null ? void 0 : authConfig.SignInComponent) ? React.createElement(authConfig.SignInComponent, {
35
+ onSignInComplete: (authState) => {
36
+ setAuthStates == null ? void 0 : setAuthStates((prev) => __spreadProps(__spreadValues({}, prev), { [action.name]: authState }));
37
+ if (pendingActionRef.current) {
38
+ executeAction(pendingActionRef.current);
39
+ pendingActionRef.current = null;
40
+ }
41
+ }
42
+ }) : React.createElement(Fragment);
43
+ }
44
+ return executeAction(props);
45
+ },
46
+ [action, authStates, setAuthStates]
47
+ );
48
+ useCopilotAction(
49
+ __spreadProps(__spreadValues({}, action), {
50
+ render: wrappedRender
51
+ }),
52
+ dependencies
53
+ );
54
+ }
55
+
56
+ export {
57
+ useCopilotAuthenticatedAction
58
+ };
59
+ //# sourceMappingURL=chunk-LHKIIAUQ.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\nexport function useCopilotAuthenticatedAction<T extends Parameter[]>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { authConfig, authStates, setAuthStates } = 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 || {}).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?.SignInComponent\n ? React.createElement(authConfig.SignInComponent, {\n onSignInComplete: (authState) => {\n setAuthStates?.((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, setAuthStates],\n );\n\n useCopilotAction(\n {\n ...action,\n render: wrappedRender,\n } as FrontendAction<T>,\n dependencies,\n );\n}\n"],"mappings":";;;;;;;;;;;;AACA,SAAS,UAAU,aAAa,cAAc;AAI9C,OAAO,WAAW;AAEX,SAAS,8BACd,QACA,cACM;AACN,QAAM,EAAE,YAAY,YAAY,cAAc,IAAI,kBAAkB;AACpE,QAAM,mBAAmB,OAA8C,IAAI;AAE3E,QAAM,gBAAgB;AAAA,IACpB,CAAC,UAA0C;AACzC,UAAI,OAAO,OAAO,WAAW,YAAY;AACvC,eAAO,OAAO,OAAO,KAAK;AAAA,MAC5B;AACA,aAAO,OAAO,UAAU,MAAM,cAAc,QAAQ;AAAA,IACtD;AAAA,IACA,CAAC,MAAM;AAAA,EACT;AAEA,QAAM,gBAAgB;AAAA,IACpB,CAAC,UAAuE;AACtE,YAAM,kBAAkB,OAAO,OAAO,cAAc,CAAC,CAAC,EAAE;AAAA,QACtD,CAAC,UAAU,MAAM,WAAW;AAAA,MAC9B;AAEA,UAAI,CAAC,iBAAiB;AAEpB,yBAAiB,UAAU;AAE3B,gBAAO,yCAAY,mBACf,MAAM,cAAc,WAAW,iBAAiB;AAAA,UAC9C,kBAAkB,CAAC,cAAc;AAC/B,2DAAgB,CAAC,SAAU,iCAAK,OAAL,EAAW,CAAC,OAAO,IAAI,GAAG,UAAU;AAC/D,gBAAI,iBAAiB,SAAS;AAC5B,4BAAc,iBAAiB,OAAO;AACtC,+BAAiB,UAAU;AAAA,YAC7B;AAAA,UACF;AAAA,QACF,CAAC,IACD,MAAM,cAAc,QAAQ;AAAA,MAClC;AAEA,aAAO,cAAc,KAAK;AAAA,IAC5B;AAAA,IACA,CAAC,QAAQ,YAAY,aAAa;AAAA,EACpC;AAEA;AAAA,IACE,iCACK,SADL;AAAA,MAEE,QAAQ;AAAA,IACV;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,242 @@
1
+ import {
2
+ ExclamationMarkIcon
3
+ } from "./chunk-O7ARI5CV.mjs";
4
+ import {
5
+ __async,
6
+ __spreadProps,
7
+ __spreadValues
8
+ } from "./chunk-SKC7AJIV.mjs";
9
+
10
+ // src/components/error-boundary/error-utils.tsx
11
+ import { useCallback as useCallback2 } from "react";
12
+
13
+ // src/components/toast/toast-provider.tsx
14
+ import { createContext, useContext, useState, useCallback } from "react";
15
+ import { jsx, jsxs } from "react/jsx-runtime";
16
+ var ToastContext = createContext(void 0);
17
+ function useToast() {
18
+ const context = useContext(ToastContext);
19
+ if (!context) {
20
+ throw new Error("useToast must be used within a ToastProvider");
21
+ }
22
+ return context;
23
+ }
24
+ function ToastProvider({
25
+ enabled,
26
+ children
27
+ }) {
28
+ const [toasts, setToasts] = useState([]);
29
+ const addToast = useCallback((toast) => {
30
+ var _a;
31
+ const id = (_a = toast.id) != null ? _a : Math.random().toString(36).substring(2, 9);
32
+ setToasts((currentToasts) => {
33
+ if (currentToasts.find((toast2) => toast2.id === id))
34
+ return currentToasts;
35
+ return [...currentToasts, __spreadProps(__spreadValues({}, toast), { id })];
36
+ });
37
+ if (toast.duration) {
38
+ setTimeout(() => {
39
+ removeToast(id);
40
+ }, toast.duration);
41
+ }
42
+ }, []);
43
+ const addGraphQLErrorsToast = useCallback((errors) => {
44
+ addToast({
45
+ type: "error",
46
+ message: /* @__PURE__ */ jsx(ErrorToast, { errors })
47
+ });
48
+ }, []);
49
+ const removeToast = useCallback((id) => {
50
+ setToasts((currentToasts) => currentToasts.filter((toast) => toast.id !== id));
51
+ }, []);
52
+ const value = {
53
+ toasts,
54
+ addToast,
55
+ addGraphQLErrorsToast,
56
+ removeToast,
57
+ enabled
58
+ };
59
+ return /* @__PURE__ */ jsxs(ToastContext.Provider, { value, children: [
60
+ /* @__PURE__ */ jsxs(
61
+ "div",
62
+ {
63
+ style: {
64
+ position: "fixed",
65
+ bottom: "1rem",
66
+ left: "50%",
67
+ transform: "translateX(-50%)",
68
+ zIndex: 50,
69
+ display: "flex",
70
+ flexDirection: "column",
71
+ gap: "0.5rem"
72
+ },
73
+ children: [
74
+ toasts.length > 1 && /* @__PURE__ */ jsx("div", { style: { textAlign: "right" }, children: /* @__PURE__ */ jsx(
75
+ "button",
76
+ {
77
+ onClick: () => setToasts([]),
78
+ style: {
79
+ padding: "4px 8px",
80
+ fontSize: "12px",
81
+ cursor: "pointer",
82
+ background: "white",
83
+ border: "1px solid rgba(0,0,0,0.2)",
84
+ borderRadius: "4px"
85
+ },
86
+ children: "Close All"
87
+ }
88
+ ) }),
89
+ toasts.map((toast) => /* @__PURE__ */ jsx(
90
+ Toast,
91
+ {
92
+ message: toast.message,
93
+ type: toast.type,
94
+ onClose: () => removeToast(toast.id)
95
+ },
96
+ toast.id
97
+ ))
98
+ ]
99
+ }
100
+ ),
101
+ children
102
+ ] });
103
+ }
104
+ function Toast({
105
+ message,
106
+ type = "info",
107
+ onClose
108
+ }) {
109
+ const bgColors = {
110
+ info: "#3b82f6",
111
+ success: "#22c55e",
112
+ warning: "#eab308",
113
+ error: "#ef4444"
114
+ };
115
+ return /* @__PURE__ */ jsxs(
116
+ "div",
117
+ {
118
+ style: {
119
+ backgroundColor: bgColors[type],
120
+ color: "white",
121
+ padding: "0.5rem 1.5rem",
122
+ borderRadius: "0.25rem",
123
+ boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
124
+ position: "relative",
125
+ minWidth: "200px"
126
+ },
127
+ children: [
128
+ /* @__PURE__ */ jsx("div", { children: message }),
129
+ /* @__PURE__ */ jsx(
130
+ "button",
131
+ {
132
+ onClick: onClose,
133
+ style: {
134
+ position: "absolute",
135
+ top: "0",
136
+ right: "0",
137
+ background: "none",
138
+ border: "none",
139
+ color: "white",
140
+ cursor: "pointer",
141
+ padding: "0.5rem",
142
+ fontSize: "1rem"
143
+ },
144
+ children: "\u2715"
145
+ }
146
+ )
147
+ ]
148
+ }
149
+ );
150
+ }
151
+
152
+ // src/components/error-boundary/error-utils.tsx
153
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
154
+ function ErrorToast({ errors }) {
155
+ const errorsToRender = errors.map((error, idx) => {
156
+ var _a, _b, _c;
157
+ const message = "extensions" in error ? (_b = (_a = error.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message : error.message;
158
+ const code = "extensions" in error ? (_c = error.extensions) == null ? void 0 : _c.code : null;
159
+ return /* @__PURE__ */ jsxs2(
160
+ "div",
161
+ {
162
+ style: {
163
+ marginTop: idx === 0 ? 0 : 10,
164
+ marginBottom: 14
165
+ },
166
+ children: [
167
+ /* @__PURE__ */ jsx2(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
168
+ code && /* @__PURE__ */ jsxs2(
169
+ "div",
170
+ {
171
+ style: {
172
+ fontWeight: "600",
173
+ marginBottom: 4
174
+ },
175
+ children: [
176
+ "Copilot Cloud Error:",
177
+ " ",
178
+ /* @__PURE__ */ jsx2("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
179
+ ]
180
+ }
181
+ ),
182
+ /* @__PURE__ */ jsx2("div", { children: message })
183
+ ]
184
+ },
185
+ idx
186
+ );
187
+ });
188
+ return /* @__PURE__ */ jsxs2(
189
+ "div",
190
+ {
191
+ style: {
192
+ fontSize: "13px",
193
+ maxWidth: "600px"
194
+ },
195
+ children: [
196
+ errorsToRender,
197
+ /* @__PURE__ */ jsx2("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This error only displays during local development." })
198
+ ]
199
+ }
200
+ );
201
+ }
202
+ function useErrorToast() {
203
+ const { addToast } = useToast();
204
+ return useCallback2(
205
+ (error) => {
206
+ const errorId = error.map((err) => {
207
+ var _a, _b;
208
+ const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
209
+ const stack = err.stack || "";
210
+ return btoa(message + stack).slice(0, 32);
211
+ }).join("|");
212
+ addToast({
213
+ type: "error",
214
+ id: errorId,
215
+ // Toast libraries typically dedupe by id
216
+ message: /* @__PURE__ */ jsx2(ErrorToast, { errors: error })
217
+ });
218
+ },
219
+ [addToast]
220
+ );
221
+ }
222
+ function useAsyncCallback(callback, deps) {
223
+ const addErrorToast = useErrorToast();
224
+ return useCallback2((...args) => __async(this, null, function* () {
225
+ try {
226
+ return yield callback(...args);
227
+ } catch (error) {
228
+ console.error("Error in async callback:", error);
229
+ addErrorToast([error]);
230
+ throw error;
231
+ }
232
+ }), deps);
233
+ }
234
+
235
+ export {
236
+ ErrorToast,
237
+ useErrorToast,
238
+ useAsyncCallback,
239
+ useToast,
240
+ ToastProvider
241
+ };
242
+ //# sourceMappingURL=chunk-LNI2Z45S.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/error-boundary/error-utils.tsx","../src/components/toast/toast-provider.tsx"],"sourcesContent":["import React, { useCallback, useEffect } from \"react\";\nimport { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { ExclamationMarkIcon } from \"../toast/exclamation-mark-icon\";\n\nexport function ErrorToast({ errors }: { errors: (Error | GraphQLError)[] }) {\n const errorsToRender = errors.map((error, idx) => {\n const message =\n \"extensions\" in error\n ? (error.extensions?.originalError as undefined | { message?: string })?.message\n : error.message;\n const code = \"extensions\" in error ? (error.extensions?.code as string) : null;\n\n return (\n <div\n key={idx}\n style={{\n marginTop: idx === 0 ? 0 : 10,\n marginBottom: 14,\n }}\n >\n <ExclamationMarkIcon style={{ marginBottom: 4 }} />\n\n {code && (\n <div\n style={{\n fontWeight: \"600\",\n marginBottom: 4,\n }}\n >\n Copilot Cloud Error:{\" \"}\n <span style={{ fontFamily: \"monospace\", fontWeight: \"normal\" }}>{code}</span>\n </div>\n )}\n <div>{message}</div>\n </div>\n );\n });\n return (\n <div\n style={{\n fontSize: \"13px\",\n maxWidth: \"600px\",\n }}\n >\n {errorsToRender}\n <div style={{ fontSize: \"11px\", opacity: 0.75 }}>\n NOTE: This error only displays during local development.\n </div>\n </div>\n );\n}\n\nexport function useErrorToast() {\n const { addToast } = useToast();\n\n return useCallback(\n (error: (Error | GraphQLError)[]) => {\n const errorId = error\n .map((err) => {\n const message =\n \"extensions\" in err\n ? (err.extensions?.originalError as any)?.message || err.message\n : err.message;\n const stack = err.stack || \"\";\n return btoa(message + stack).slice(0, 32); // Create hash from message + stack\n })\n .join(\"|\");\n\n addToast({\n type: \"error\",\n id: errorId, // Toast libraries typically dedupe by id\n message: <ErrorToast errors={error} />,\n });\n },\n [addToast],\n );\n}\n\nexport function useAsyncCallback<T extends (...args: any[]) => Promise<any>>(\n callback: T,\n deps: Parameters<typeof useCallback>[1],\n) {\n const addErrorToast = useErrorToast();\n return useCallback(async (...args: Parameters<T>) => {\n try {\n return await callback(...args);\n } catch (error) {\n console.error(\"Error in async callback:\", error);\n // @ts-ignore\n addErrorToast([error]);\n throw error;\n }\n }, deps);\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { ErrorToast } from \"../error-boundary/error-utils\";\nimport { PartialBy } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const addToast = useCallback((toast: PartialBy<Toast, \"id\">) => {\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n }, []);\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // We do not display these errors unless we are in dev mode.\n // if (!showDevConsole) {\n // return;\n // }\n\n addToast({\n type: \"error\",\n message: <ErrorToast errors={errors} />,\n });\n }, []);\n\n const removeToast = useCallback((id: string) => {\n setToasts((currentToasts) => currentToasts.filter((toast) => toast.id !== id));\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n };\n\n return (\n <ToastContext.Provider value={value}>\n <div\n style={{\n position: \"fixed\",\n bottom: \"1rem\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 50,\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"0.5rem\",\n }}\n >\n {toasts.length > 1 && (\n <div style={{ textAlign: \"right\" }}>\n <button\n onClick={() => setToasts([])}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n cursor: \"pointer\",\n background: \"white\",\n border: \"1px solid rgba(0,0,0,0.2)\",\n borderRadius: \"4px\",\n }}\n >\n Close All\n </button>\n </div>\n )}\n {toasts.map((toast) => (\n <Toast\n key={toast.id}\n message={toast.message}\n type={toast.type}\n onClose={() => removeToast(toast.id)}\n />\n ))}\n </div>\n {children}\n </ToastContext.Provider>\n );\n}\n\nfunction Toast({\n message,\n type = \"info\",\n onClose,\n}: {\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n onClose: () => void;\n}) {\n const bgColors = {\n info: \"#3b82f6\",\n success: \"#22c55e\",\n warning: \"#eab308\",\n error: \"#ef4444\",\n };\n\n return (\n <div\n style={{\n backgroundColor: bgColors[type],\n color: \"white\",\n padding: \"0.5rem 1.5rem\",\n borderRadius: \"0.25rem\",\n boxShadow: \"0 2px 4px rgba(0,0,0,0.1)\",\n position: \"relative\",\n minWidth: \"200px\",\n }}\n >\n <div>{message}</div>\n <button\n onClick={onClose}\n style={{\n position: \"absolute\",\n top: \"0\",\n right: \"0\",\n background: \"none\",\n border: \"none\",\n color: \"white\",\n cursor: \"pointer\",\n padding: \"0.5rem\",\n fontSize: \"1rem\",\n }}\n >\n ✕\n </button>\n </div>\n );\n}\n"],"mappings":";;;;;;;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A;AAAA,EACF;AAEJ;AAEO,SAAS,gBAAgB;AAC9B,QAAM,EAAE,SAAS,IAAI,SAAS;AAE9B,SAAOE;AAAA,IACL,CAAC,UAAoC;AACnC,YAAM,UAAU,MACb,IAAI,CAAC,QAAQ;AA3DtB;AA4DU,cAAM,UACJ,gBAAgB,QACX,eAAI,eAAJ,mBAAgB,kBAAhB,mBAAuC,YAAW,IAAI,UACvD,IAAI;AACV,cAAM,QAAQ,IAAI,SAAS;AAC3B,eAAO,KAAK,UAAU,KAAK,EAAE,MAAM,GAAG,EAAE;AAAA,MAC1C,CAAC,EACA,KAAK,GAAG;AAEX,eAAS;AAAA,QACP,MAAM;AAAA,QACN,IAAI;AAAA;AAAA,QACJ,SAAS,gBAAAF,KAAC,cAAW,QAAQ,OAAO;AAAA,MACtC,CAAC;AAAA,IACH;AAAA,IACA,CAAC,QAAQ;AAAA,EACX;AACF;AAEO,SAAS,iBACd,UACA,MACA;AACA,QAAM,gBAAgB,cAAc;AACpC,SAAOE,aAAY,IAAU,SAAwB;AACnD,QAAI;AACF,aAAO,MAAM,SAAS,GAAG,IAAI;AAAA,IAC/B,SAAS,OAAP;AACA,cAAQ,MAAM,4BAA4B,KAAK;AAE/C,oBAAc,CAAC,KAAK,CAAC;AACrB,YAAM;AAAA,IACR;AAAA,EACF,IAAG,IAAI;AACT;","names":["useCallback","toast","jsx","jsxs","useCallback"]}
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=chunk-LUGEI4YQ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}