@copilotkit/react-core 1.51.4 → 1.51.5-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (474) hide show
  1. package/.attw.json +3 -0
  2. package/CHANGELOG.md +21 -0
  3. package/dist/index.cjs +4010 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +1327 -0
  6. package/dist/index.d.cts.map +1 -0
  7. package/dist/index.d.mts +1327 -0
  8. package/dist/index.d.mts.map +1 -0
  9. package/dist/index.mjs +3944 -148
  10. package/dist/index.mjs.map +1 -1
  11. package/dist/index.umd.js +4075 -39
  12. package/dist/index.umd.js.map +1 -1
  13. package/dist/v2/index.cjs +17 -0
  14. package/dist/v2/index.css +2 -3
  15. package/dist/v2/index.css.map +1 -1
  16. package/dist/v2/index.d.cts +2 -0
  17. package/dist/v2/index.d.mts +2 -0
  18. package/dist/v2/index.mjs +4 -5
  19. package/dist/v2/index.umd.js +24 -2
  20. package/package.json +22 -22
  21. package/src/components/copilot-provider/__tests__/copilotkit-error.test.tsx +3 -3
  22. package/src/hooks/__tests__/use-coagent-config.test.ts +23 -22
  23. package/src/hooks/__tests__/use-coagent-state-render.e2e.test.tsx +33 -35
  24. package/src/hooks/__tests__/use-coagent-state-render.test.tsx +19 -18
  25. package/src/hooks/__tests__/use-frontend-tool-available.test.tsx +72 -0
  26. package/src/hooks/__tests__/use-frontend-tool-remount.e2e.test.tsx +9 -7
  27. package/src/hooks/use-copilot-chat.ts +1 -1
  28. package/src/hooks/use-frontend-tool.ts +2 -1
  29. package/src/lib/copilot-task.ts +1 -1
  30. package/src/setupTests.ts +17 -16
  31. package/tsconfig.json +1 -1
  32. package/tsdown.config.ts +94 -0
  33. package/vitest.config.mjs +30 -0
  34. package/dist/chunk-2IDV5OHF.mjs +0 -11
  35. package/dist/chunk-2IDV5OHF.mjs.map +0 -1
  36. package/dist/chunk-2RSAYTXH.mjs +0 -137
  37. package/dist/chunk-2RSAYTXH.mjs.map +0 -1
  38. package/dist/chunk-36KQV2NA.mjs +0 -1
  39. package/dist/chunk-36KQV2NA.mjs.map +0 -1
  40. package/dist/chunk-3LZZ4RVM.mjs +0 -37
  41. package/dist/chunk-3LZZ4RVM.mjs.map +0 -1
  42. package/dist/chunk-4ZQYMC5F.mjs +0 -36
  43. package/dist/chunk-4ZQYMC5F.mjs.map +0 -1
  44. package/dist/chunk-6ABVYB2U.mjs +0 -95
  45. package/dist/chunk-6ABVYB2U.mjs.map +0 -1
  46. package/dist/chunk-6AWG5FWL.mjs +0 -102
  47. package/dist/chunk-6AWG5FWL.mjs.map +0 -1
  48. package/dist/chunk-6YOKPWQ7.mjs +0 -1
  49. package/dist/chunk-6YOKPWQ7.mjs.map +0 -1
  50. package/dist/chunk-7GIBHX6X.mjs +0 -195
  51. package/dist/chunk-7GIBHX6X.mjs.map +0 -1
  52. package/dist/chunk-7PJKPWMD.mjs +0 -112
  53. package/dist/chunk-7PJKPWMD.mjs.map +0 -1
  54. package/dist/chunk-7U3DNFBF.mjs +0 -20
  55. package/dist/chunk-7U3DNFBF.mjs.map +0 -1
  56. package/dist/chunk-A6NKSGH3.mjs +0 -1
  57. package/dist/chunk-A6NKSGH3.mjs.map +0 -1
  58. package/dist/chunk-AAGMWZCN.mjs +0 -439
  59. package/dist/chunk-AAGMWZCN.mjs.map +0 -1
  60. package/dist/chunk-C7HSVDHD.mjs +0 -116
  61. package/dist/chunk-C7HSVDHD.mjs.map +0 -1
  62. package/dist/chunk-CYDWEPFL.mjs +0 -1
  63. package/dist/chunk-CYDWEPFL.mjs.map +0 -1
  64. package/dist/chunk-CZT7JUIM.mjs +0 -153
  65. package/dist/chunk-CZT7JUIM.mjs.map +0 -1
  66. package/dist/chunk-DMLQZG75.mjs +0 -25
  67. package/dist/chunk-DMLQZG75.mjs.map +0 -1
  68. package/dist/chunk-FD6FGKYY.mjs +0 -1
  69. package/dist/chunk-FD6FGKYY.mjs.map +0 -1
  70. package/dist/chunk-G7SUZGGB.mjs +0 -126
  71. package/dist/chunk-G7SUZGGB.mjs.map +0 -1
  72. package/dist/chunk-GY3FQICF.mjs +0 -23
  73. package/dist/chunk-GY3FQICF.mjs.map +0 -1
  74. package/dist/chunk-I76HKHPJ.mjs +0 -32
  75. package/dist/chunk-I76HKHPJ.mjs.map +0 -1
  76. package/dist/chunk-ICIK2BSB.mjs +0 -17
  77. package/dist/chunk-ICIK2BSB.mjs.map +0 -1
  78. package/dist/chunk-IHMMKEFG.mjs +0 -64
  79. package/dist/chunk-IHMMKEFG.mjs.map +0 -1
  80. package/dist/chunk-JD7BAH7U.mjs +0 -1
  81. package/dist/chunk-JD7BAH7U.mjs.map +0 -1
  82. package/dist/chunk-K5OXUXCG.mjs +0 -76
  83. package/dist/chunk-K5OXUXCG.mjs.map +0 -1
  84. package/dist/chunk-L7GPCF2V.mjs +0 -229
  85. package/dist/chunk-L7GPCF2V.mjs.map +0 -1
  86. package/dist/chunk-LD34IXVT.mjs +0 -86
  87. package/dist/chunk-LD34IXVT.mjs.map +0 -1
  88. package/dist/chunk-LNGBARXE.mjs +0 -86
  89. package/dist/chunk-LNGBARXE.mjs.map +0 -1
  90. package/dist/chunk-LRPWSPXG.mjs +0 -628
  91. package/dist/chunk-LRPWSPXG.mjs.map +0 -1
  92. package/dist/chunk-LUGEI4YQ.mjs +0 -1
  93. package/dist/chunk-LUGEI4YQ.mjs.map +0 -1
  94. package/dist/chunk-MBJ7OLYI.mjs +0 -58
  95. package/dist/chunk-MBJ7OLYI.mjs.map +0 -1
  96. package/dist/chunk-NB2FKV2V.mjs +0 -1
  97. package/dist/chunk-NB2FKV2V.mjs.map +0 -1
  98. package/dist/chunk-O7ARI5CV.mjs +0 -31
  99. package/dist/chunk-O7ARI5CV.mjs.map +0 -1
  100. package/dist/chunk-P6ZPE4XJ.mjs +0 -86
  101. package/dist/chunk-P6ZPE4XJ.mjs.map +0 -1
  102. package/dist/chunk-QXZTCGF4.mjs +0 -163
  103. package/dist/chunk-QXZTCGF4.mjs.map +0 -1
  104. package/dist/chunk-R2DP4APC.mjs +0 -125
  105. package/dist/chunk-R2DP4APC.mjs.map +0 -1
  106. package/dist/chunk-R7BV32X4.mjs +0 -146
  107. package/dist/chunk-R7BV32X4.mjs.map +0 -1
  108. package/dist/chunk-SBRCWA4S.mjs +0 -913
  109. package/dist/chunk-SBRCWA4S.mjs.map +0 -1
  110. package/dist/chunk-SK2XMJUD.mjs +0 -42
  111. package/dist/chunk-SK2XMJUD.mjs.map +0 -1
  112. package/dist/chunk-SKC7AJIV.mjs +0 -61
  113. package/dist/chunk-SKC7AJIV.mjs.map +0 -1
  114. package/dist/chunk-SLM6CLAH.mjs +0 -195
  115. package/dist/chunk-SLM6CLAH.mjs.map +0 -1
  116. package/dist/chunk-SPCZTZCY.mjs +0 -1
  117. package/dist/chunk-SPCZTZCY.mjs.map +0 -1
  118. package/dist/chunk-SYGQHN3H.mjs +0 -27
  119. package/dist/chunk-SYGQHN3H.mjs.map +0 -1
  120. package/dist/chunk-SYMT73HM.mjs +0 -43
  121. package/dist/chunk-SYMT73HM.mjs.map +0 -1
  122. package/dist/chunk-TFZXOEY4.mjs +0 -61
  123. package/dist/chunk-TFZXOEY4.mjs.map +0 -1
  124. package/dist/chunk-TPN7WC53.mjs +0 -33
  125. package/dist/chunk-TPN7WC53.mjs.map +0 -1
  126. package/dist/chunk-UA23VX5J.mjs +0 -65
  127. package/dist/chunk-UA23VX5J.mjs.map +0 -1
  128. package/dist/chunk-V42VL2JR.mjs +0 -136
  129. package/dist/chunk-V42VL2JR.mjs.map +0 -1
  130. package/dist/chunk-VZ4NSOFQ.mjs +0 -80
  131. package/dist/chunk-VZ4NSOFQ.mjs.map +0 -1
  132. package/dist/chunk-WRALJIW5.mjs +0 -79
  133. package/dist/chunk-WRALJIW5.mjs.map +0 -1
  134. package/dist/chunk-WV2EA7SX.mjs +0 -65
  135. package/dist/chunk-WV2EA7SX.mjs.map +0 -1
  136. package/dist/chunk-Z6JV2LRY.mjs +0 -37
  137. package/dist/chunk-Z6JV2LRY.mjs.map +0 -1
  138. package/dist/chunk-ZP2IMXFY.mjs +0 -316
  139. package/dist/chunk-ZP2IMXFY.mjs.map +0 -1
  140. package/dist/chunk-ZVF5Q6IH.mjs +0 -29
  141. package/dist/chunk-ZVF5Q6IH.mjs.map +0 -1
  142. package/dist/components/CopilotListeners.d.ts +0 -3
  143. package/dist/components/CopilotListeners.js +0 -110
  144. package/dist/components/CopilotListeners.js.map +0 -1
  145. package/dist/components/CopilotListeners.mjs +0 -9
  146. package/dist/components/CopilotListeners.mjs.map +0 -1
  147. package/dist/components/copilot-provider/copilot-messages.d.ts +0 -24
  148. package/dist/components/copilot-provider/copilot-messages.js +0 -366
  149. package/dist/components/copilot-provider/copilot-messages.js.map +0 -1
  150. package/dist/components/copilot-provider/copilot-messages.mjs +0 -16
  151. package/dist/components/copilot-provider/copilot-messages.mjs.map +0 -1
  152. package/dist/components/copilot-provider/copilotkit-props.d.ts +0 -180
  153. package/dist/components/copilot-provider/copilotkit-props.js +0 -19
  154. package/dist/components/copilot-provider/copilotkit-props.js.map +0 -1
  155. package/dist/components/copilot-provider/copilotkit-props.mjs +0 -1
  156. package/dist/components/copilot-provider/copilotkit-props.mjs.map +0 -1
  157. package/dist/components/copilot-provider/copilotkit.d.ts +0 -19
  158. package/dist/components/copilot-provider/copilotkit.js +0 -2348
  159. package/dist/components/copilot-provider/copilotkit.js.map +0 -1
  160. package/dist/components/copilot-provider/copilotkit.mjs +0 -33
  161. package/dist/components/copilot-provider/copilotkit.mjs.map +0 -1
  162. package/dist/components/copilot-provider/index.d.ts +0 -14
  163. package/dist/components/copilot-provider/index.js +0 -2348
  164. package/dist/components/copilot-provider/index.js.map +0 -1
  165. package/dist/components/copilot-provider/index.mjs +0 -32
  166. package/dist/components/copilot-provider/index.mjs.map +0 -1
  167. package/dist/components/dev-console/console-trigger.d.ts +0 -8
  168. package/dist/components/dev-console/console-trigger.js +0 -1387
  169. package/dist/components/dev-console/console-trigger.js.map +0 -1
  170. package/dist/components/dev-console/console-trigger.mjs +0 -249
  171. package/dist/components/dev-console/console-trigger.mjs.map +0 -1
  172. package/dist/components/dev-console/developer-console-modal.d.ts +0 -10
  173. package/dist/components/dev-console/developer-console-modal.js +0 -1156
  174. package/dist/components/dev-console/developer-console-modal.js.map +0 -1
  175. package/dist/components/dev-console/developer-console-modal.mjs +0 -12
  176. package/dist/components/dev-console/developer-console-modal.mjs.map +0 -1
  177. package/dist/components/dev-console/icons.d.ts +0 -9
  178. package/dist/components/dev-console/icons.js +0 -140
  179. package/dist/components/dev-console/icons.js.map +0 -1
  180. package/dist/components/dev-console/icons.mjs +0 -16
  181. package/dist/components/dev-console/icons.mjs.map +0 -1
  182. package/dist/components/error-boundary/error-boundary.d.ts +0 -31
  183. package/dist/components/error-boundary/error-boundary.js +0 -507
  184. package/dist/components/error-boundary/error-boundary.js.map +0 -1
  185. package/dist/components/error-boundary/error-boundary.mjs +0 -15
  186. package/dist/components/error-boundary/error-boundary.mjs.map +0 -1
  187. package/dist/components/error-boundary/error-utils.d.ts +0 -11
  188. package/dist/components/error-boundary/error-utils.js +0 -190
  189. package/dist/components/error-boundary/error-utils.js.map +0 -1
  190. package/dist/components/error-boundary/error-utils.mjs +0 -14
  191. package/dist/components/error-boundary/error-utils.mjs.map +0 -1
  192. package/dist/components/index.d.ts +0 -14
  193. package/dist/components/index.js +0 -2348
  194. package/dist/components/index.js.map +0 -1
  195. package/dist/components/index.mjs +0 -33
  196. package/dist/components/index.mjs.map +0 -1
  197. package/dist/components/toast/exclamation-mark-icon.d.ts +0 -9
  198. package/dist/components/toast/exclamation-mark-icon.js +0 -55
  199. package/dist/components/toast/exclamation-mark-icon.js.map +0 -1
  200. package/dist/components/toast/exclamation-mark-icon.mjs +0 -8
  201. package/dist/components/toast/exclamation-mark-icon.mjs.map +0 -1
  202. package/dist/components/toast/toast-provider.d.ts +0 -27
  203. package/dist/components/toast/toast-provider.js +0 -353
  204. package/dist/components/toast/toast-provider.js.map +0 -1
  205. package/dist/components/toast/toast-provider.mjs +0 -10
  206. package/dist/components/toast/toast-provider.mjs.map +0 -1
  207. package/dist/components/usage-banner.d.ts +0 -29
  208. package/dist/components/usage-banner.js +0 -251
  209. package/dist/components/usage-banner.js.map +0 -1
  210. package/dist/components/usage-banner.mjs +0 -12
  211. package/dist/components/usage-banner.mjs.map +0 -1
  212. package/dist/context/coagent-state-renders-context.d.ts +0 -25
  213. package/dist/context/coagent-state-renders-context.js +0 -96
  214. package/dist/context/coagent-state-renders-context.js.map +0 -1
  215. package/dist/context/coagent-state-renders-context.mjs +0 -12
  216. package/dist/context/coagent-state-renders-context.mjs.map +0 -1
  217. package/dist/context/copilot-context.d.ts +0 -10
  218. package/dist/context/copilot-context.js +0 -167
  219. package/dist/context/copilot-context.js.map +0 -1
  220. package/dist/context/copilot-context.mjs +0 -10
  221. package/dist/context/copilot-context.mjs.map +0 -1
  222. package/dist/context/copilot-messages-context.d.ts +0 -18
  223. package/dist/context/copilot-messages-context.js +0 -60
  224. package/dist/context/copilot-messages-context.js.map +0 -1
  225. package/dist/context/copilot-messages-context.mjs +0 -10
  226. package/dist/context/copilot-messages-context.mjs.map +0 -1
  227. package/dist/context/index.d.ts +0 -15
  228. package/dist/context/index.js +0 -301
  229. package/dist/context/index.js.map +0 -1
  230. package/dist/context/index.mjs +0 -33
  231. package/dist/context/index.mjs.map +0 -1
  232. package/dist/context/threads-context.d.ts +0 -16
  233. package/dist/context/threads-context.js +0 -64
  234. package/dist/context/threads-context.js.map +0 -1
  235. package/dist/context/threads-context.mjs +0 -12
  236. package/dist/context/threads-context.mjs.map +0 -1
  237. package/dist/copilot-context-ec77e921.d.ts +0 -209
  238. package/dist/hooks/index.d.ts +0 -33
  239. package/dist/hooks/index.js +0 -2190
  240. package/dist/hooks/index.js.map +0 -1
  241. package/dist/hooks/index.mjs +0 -93
  242. package/dist/hooks/index.mjs.map +0 -1
  243. package/dist/hooks/use-agent-nodename.d.ts +0 -3
  244. package/dist/hooks/use-agent-nodename.js +0 -56
  245. package/dist/hooks/use-agent-nodename.js.map +0 -1
  246. package/dist/hooks/use-agent-nodename.mjs +0 -8
  247. package/dist/hooks/use-agent-nodename.mjs.map +0 -1
  248. package/dist/hooks/use-coagent-state-render-bridge.d.ts +0 -100
  249. package/dist/hooks/use-coagent-state-render-bridge.helpers.d.ts +0 -92
  250. package/dist/hooks/use-coagent-state-render-bridge.helpers.js +0 -237
  251. package/dist/hooks/use-coagent-state-render-bridge.helpers.js.map +0 -1
  252. package/dist/hooks/use-coagent-state-render-bridge.helpers.mjs +0 -24
  253. package/dist/hooks/use-coagent-state-render-bridge.helpers.mjs.map +0 -1
  254. package/dist/hooks/use-coagent-state-render-bridge.js +0 -498
  255. package/dist/hooks/use-coagent-state-render-bridge.js.map +0 -1
  256. package/dist/hooks/use-coagent-state-render-bridge.mjs +0 -17
  257. package/dist/hooks/use-coagent-state-render-bridge.mjs.map +0 -1
  258. package/dist/hooks/use-coagent-state-render-registry.d.ts +0 -25
  259. package/dist/hooks/use-coagent-state-render-registry.js +0 -369
  260. package/dist/hooks/use-coagent-state-render-registry.js.map +0 -1
  261. package/dist/hooks/use-coagent-state-render-registry.mjs +0 -9
  262. package/dist/hooks/use-coagent-state-render-registry.mjs.map +0 -1
  263. package/dist/hooks/use-coagent-state-render.d.ts +0 -55
  264. package/dist/hooks/use-coagent-state-render.js +0 -268
  265. package/dist/hooks/use-coagent-state-render.js.map +0 -1
  266. package/dist/hooks/use-coagent-state-render.mjs +0 -11
  267. package/dist/hooks/use-coagent-state-render.mjs.map +0 -1
  268. package/dist/hooks/use-coagent.d.ts +0 -192
  269. package/dist/hooks/use-coagent.js +0 -235
  270. package/dist/hooks/use-coagent.js.map +0 -1
  271. package/dist/hooks/use-coagent.mjs +0 -9
  272. package/dist/hooks/use-coagent.mjs.map +0 -1
  273. package/dist/hooks/use-configure-chat-suggestions.d.ts +0 -36
  274. package/dist/hooks/use-configure-chat-suggestions.js +0 -79
  275. package/dist/hooks/use-configure-chat-suggestions.js.map +0 -1
  276. package/dist/hooks/use-configure-chat-suggestions.mjs +0 -47
  277. package/dist/hooks/use-configure-chat-suggestions.mjs.map +0 -1
  278. package/dist/hooks/use-copilot-action.d.ts +0 -103
  279. package/dist/hooks/use-copilot-action.js +0 -302
  280. package/dist/hooks/use-copilot-action.js.map +0 -1
  281. package/dist/hooks/use-copilot-action.mjs +0 -11
  282. package/dist/hooks/use-copilot-action.mjs.map +0 -1
  283. package/dist/hooks/use-copilot-additional-instructions.d.ts +0 -26
  284. package/dist/hooks/use-copilot-additional-instructions.js +0 -196
  285. package/dist/hooks/use-copilot-additional-instructions.js.map +0 -1
  286. package/dist/hooks/use-copilot-additional-instructions.mjs +0 -9
  287. package/dist/hooks/use-copilot-additional-instructions.mjs.map +0 -1
  288. package/dist/hooks/use-copilot-authenticated-action.d.ts +0 -18
  289. package/dist/hooks/use-copilot-authenticated-action.js +0 -477
  290. package/dist/hooks/use-copilot-authenticated-action.js.map +0 -1
  291. package/dist/hooks/use-copilot-authenticated-action.mjs +0 -13
  292. package/dist/hooks/use-copilot-authenticated-action.mjs.map +0 -1
  293. package/dist/hooks/use-copilot-chat-headless_c.d.ts +0 -25
  294. package/dist/hooks/use-copilot-chat-headless_c.js +0 -1410
  295. package/dist/hooks/use-copilot-chat-headless_c.js.map +0 -1
  296. package/dist/hooks/use-copilot-chat-headless_c.mjs +0 -26
  297. package/dist/hooks/use-copilot-chat-headless_c.mjs.map +0 -1
  298. package/dist/hooks/use-copilot-chat-suggestions.d.ts +0 -35
  299. package/dist/hooks/use-copilot-chat-suggestions.js +0 -60
  300. package/dist/hooks/use-copilot-chat-suggestions.js.map +0 -1
  301. package/dist/hooks/use-copilot-chat-suggestions.mjs +0 -8
  302. package/dist/hooks/use-copilot-chat-suggestions.mjs.map +0 -1
  303. package/dist/hooks/use-copilot-chat.d.ts +0 -92
  304. package/dist/hooks/use-copilot-chat.js +0 -1344
  305. package/dist/hooks/use-copilot-chat.js.map +0 -1
  306. package/dist/hooks/use-copilot-chat.mjs +0 -23
  307. package/dist/hooks/use-copilot-chat.mjs.map +0 -1
  308. package/dist/hooks/use-copilot-chat_internal.d.ts +0 -244
  309. package/dist/hooks/use-copilot-chat_internal.js +0 -1342
  310. package/dist/hooks/use-copilot-chat_internal.js.map +0 -1
  311. package/dist/hooks/use-copilot-chat_internal.mjs +0 -24
  312. package/dist/hooks/use-copilot-chat_internal.mjs.map +0 -1
  313. package/dist/hooks/use-copilot-readable.d.ts +0 -37
  314. package/dist/hooks/use-copilot-readable.js +0 -61
  315. package/dist/hooks/use-copilot-readable.js.map +0 -1
  316. package/dist/hooks/use-copilot-readable.mjs +0 -8
  317. package/dist/hooks/use-copilot-readable.mjs.map +0 -1
  318. package/dist/hooks/use-copilot-runtime-client.d.ts +0 -10
  319. package/dist/hooks/use-copilot-runtime-client.js +0 -206
  320. package/dist/hooks/use-copilot-runtime-client.js.map +0 -1
  321. package/dist/hooks/use-copilot-runtime-client.mjs +0 -9
  322. package/dist/hooks/use-copilot-runtime-client.mjs.map +0 -1
  323. package/dist/hooks/use-default-tool.d.ts +0 -8
  324. package/dist/hooks/use-default-tool.js +0 -312
  325. package/dist/hooks/use-default-tool.js.map +0 -1
  326. package/dist/hooks/use-default-tool.mjs +0 -12
  327. package/dist/hooks/use-default-tool.mjs.map +0 -1
  328. package/dist/hooks/use-flat-category-store.d.ts +0 -9
  329. package/dist/hooks/use-flat-category-store.js +0 -96
  330. package/dist/hooks/use-flat-category-store.js.map +0 -1
  331. package/dist/hooks/use-flat-category-store.mjs +0 -8
  332. package/dist/hooks/use-flat-category-store.mjs.map +0 -1
  333. package/dist/hooks/use-frontend-tool.d.ts +0 -11
  334. package/dist/hooks/use-frontend-tool.js +0 -107
  335. package/dist/hooks/use-frontend-tool.js.map +0 -1
  336. package/dist/hooks/use-frontend-tool.mjs +0 -8
  337. package/dist/hooks/use-frontend-tool.mjs.map +0 -1
  338. package/dist/hooks/use-human-in-the-loop.d.ts +0 -13
  339. package/dist/hooks/use-human-in-the-loop.js +0 -122
  340. package/dist/hooks/use-human-in-the-loop.js.map +0 -1
  341. package/dist/hooks/use-human-in-the-loop.mjs +0 -8
  342. package/dist/hooks/use-human-in-the-loop.mjs.map +0 -1
  343. package/dist/hooks/use-langgraph-interrupt-render.d.ts +0 -6
  344. package/dist/hooks/use-langgraph-interrupt-render.js +0 -335
  345. package/dist/hooks/use-langgraph-interrupt-render.js.map +0 -1
  346. package/dist/hooks/use-langgraph-interrupt-render.mjs +0 -14
  347. package/dist/hooks/use-langgraph-interrupt-render.mjs.map +0 -1
  348. package/dist/hooks/use-langgraph-interrupt.d.ts +0 -14
  349. package/dist/hooks/use-langgraph-interrupt.js +0 -216
  350. package/dist/hooks/use-langgraph-interrupt.js.map +0 -1
  351. package/dist/hooks/use-langgraph-interrupt.mjs +0 -10
  352. package/dist/hooks/use-langgraph-interrupt.mjs.map +0 -1
  353. package/dist/hooks/use-lazy-tool-renderer.d.ts +0 -6
  354. package/dist/hooks/use-lazy-tool-renderer.js +0 -53
  355. package/dist/hooks/use-lazy-tool-renderer.js.map +0 -1
  356. package/dist/hooks/use-lazy-tool-renderer.mjs +0 -8
  357. package/dist/hooks/use-lazy-tool-renderer.mjs.map +0 -1
  358. package/dist/hooks/use-make-copilot-document-readable.d.ts +0 -12
  359. package/dist/hooks/use-make-copilot-document-readable.js +0 -182
  360. package/dist/hooks/use-make-copilot-document-readable.js.map +0 -1
  361. package/dist/hooks/use-make-copilot-document-readable.mjs +0 -9
  362. package/dist/hooks/use-make-copilot-document-readable.mjs.map +0 -1
  363. package/dist/hooks/use-render-tool-call.d.ts +0 -12
  364. package/dist/hooks/use-render-tool-call.js +0 -94
  365. package/dist/hooks/use-render-tool-call.js.map +0 -1
  366. package/dist/hooks/use-render-tool-call.mjs +0 -8
  367. package/dist/hooks/use-render-tool-call.mjs.map +0 -1
  368. package/dist/hooks/use-tree.d.ts +0 -19
  369. package/dist/hooks/use-tree.js +0 -178
  370. package/dist/hooks/use-tree.js.map +0 -1
  371. package/dist/hooks/use-tree.mjs +0 -8
  372. package/dist/hooks/use-tree.mjs.map +0 -1
  373. package/dist/index.d.ts +0 -43
  374. package/dist/index.js +0 -4064
  375. package/dist/index.js.map +0 -1
  376. package/dist/lib/copilot-task.d.ts +0 -97
  377. package/dist/lib/copilot-task.js +0 -201
  378. package/dist/lib/copilot-task.js.map +0 -1
  379. package/dist/lib/copilot-task.mjs +0 -33
  380. package/dist/lib/copilot-task.mjs.map +0 -1
  381. package/dist/lib/index.d.ts +0 -11
  382. package/dist/lib/index.js +0 -203
  383. package/dist/lib/index.js.map +0 -1
  384. package/dist/lib/index.mjs +0 -34
  385. package/dist/lib/index.mjs.map +0 -1
  386. package/dist/lib/status-checker.d.ts +0 -17
  387. package/dist/lib/status-checker.js +0 -102
  388. package/dist/lib/status-checker.js.map +0 -1
  389. package/dist/lib/status-checker.mjs +0 -8
  390. package/dist/lib/status-checker.mjs.map +0 -1
  391. package/dist/setupTests.d.ts +0 -2
  392. package/dist/setupTests.js +0 -31
  393. package/dist/setupTests.js.map +0 -1
  394. package/dist/setupTests.mjs +0 -29
  395. package/dist/setupTests.mjs.map +0 -1
  396. package/dist/test-helpers/copilot-context.d.ts +0 -14
  397. package/dist/test-helpers/copilot-context.js +0 -128
  398. package/dist/test-helpers/copilot-context.js.map +0 -1
  399. package/dist/test-helpers/copilot-context.mjs +0 -74
  400. package/dist/test-helpers/copilot-context.mjs.map +0 -1
  401. package/dist/types/chat-suggestion-configuration.d.ts +0 -22
  402. package/dist/types/chat-suggestion-configuration.js +0 -19
  403. package/dist/types/chat-suggestion-configuration.js.map +0 -1
  404. package/dist/types/chat-suggestion-configuration.mjs +0 -1
  405. package/dist/types/chat-suggestion-configuration.mjs.map +0 -1
  406. package/dist/types/coagent-action.d.ts +0 -29
  407. package/dist/types/coagent-action.js +0 -19
  408. package/dist/types/coagent-action.js.map +0 -1
  409. package/dist/types/coagent-action.mjs +0 -1
  410. package/dist/types/coagent-action.mjs.map +0 -1
  411. package/dist/types/coagent-state.d.ts +0 -15
  412. package/dist/types/coagent-state.js +0 -19
  413. package/dist/types/coagent-state.js.map +0 -1
  414. package/dist/types/coagent-state.mjs +0 -1
  415. package/dist/types/coagent-state.mjs.map +0 -1
  416. package/dist/types/crew.d.ts +0 -79
  417. package/dist/types/crew.js +0 -19
  418. package/dist/types/crew.js.map +0 -1
  419. package/dist/types/crew.mjs +0 -2
  420. package/dist/types/crew.mjs.map +0 -1
  421. package/dist/types/document-pointer.d.ts +0 -9
  422. package/dist/types/document-pointer.js +0 -19
  423. package/dist/types/document-pointer.js.map +0 -1
  424. package/dist/types/document-pointer.mjs +0 -1
  425. package/dist/types/document-pointer.mjs.map +0 -1
  426. package/dist/types/frontend-action.d.ts +0 -127
  427. package/dist/types/frontend-action.js +0 -55
  428. package/dist/types/frontend-action.js.map +0 -1
  429. package/dist/types/frontend-action.mjs +0 -8
  430. package/dist/types/frontend-action.mjs.map +0 -1
  431. package/dist/types/index.d.ts +0 -12
  432. package/dist/types/index.js +0 -19
  433. package/dist/types/index.js.map +0 -1
  434. package/dist/types/index.mjs +0 -4
  435. package/dist/types/index.mjs.map +0 -1
  436. package/dist/types/interrupt-action.d.ts +0 -10
  437. package/dist/types/interrupt-action.js +0 -19
  438. package/dist/types/interrupt-action.js.map +0 -1
  439. package/dist/types/interrupt-action.mjs +0 -2
  440. package/dist/types/interrupt-action.mjs.map +0 -1
  441. package/dist/types/system-message.d.ts +0 -3
  442. package/dist/types/system-message.js +0 -19
  443. package/dist/types/system-message.js.map +0 -1
  444. package/dist/types/system-message.mjs +0 -1
  445. package/dist/types/system-message.mjs.map +0 -1
  446. package/dist/utils/dev-console.d.ts +0 -3
  447. package/dist/utils/dev-console.js +0 -41
  448. package/dist/utils/dev-console.js.map +0 -1
  449. package/dist/utils/dev-console.mjs +0 -8
  450. package/dist/utils/dev-console.mjs.map +0 -1
  451. package/dist/utils/index.d.ts +0 -2
  452. package/dist/utils/index.js +0 -52
  453. package/dist/utils/index.js.map +0 -1
  454. package/dist/utils/index.mjs +0 -13
  455. package/dist/utils/index.mjs.map +0 -1
  456. package/dist/utils/suggestions-constants.d.ts +0 -9
  457. package/dist/utils/suggestions-constants.js +0 -35
  458. package/dist/utils/suggestions-constants.js.map +0 -1
  459. package/dist/utils/suggestions-constants.mjs +0 -8
  460. package/dist/utils/suggestions-constants.mjs.map +0 -1
  461. package/dist/utils/utils.d.ts +0 -2
  462. package/dist/utils/utils.js +0 -19
  463. package/dist/utils/utils.js.map +0 -1
  464. package/dist/utils/utils.mjs +0 -1
  465. package/dist/utils/utils.mjs.map +0 -1
  466. package/dist/v2/index.d.ts +0 -2
  467. package/dist/v2/index.js +0 -27
  468. package/dist/v2/index.js.map +0 -1
  469. package/dist/v2/index.mjs.map +0 -1
  470. package/dist/v2/index.umd.js.map +0 -1
  471. package/jest.config.js +0 -26
  472. package/rollup.config.mjs +0 -92
  473. package/src/__mocks__/analytics-node.js +0 -9
  474. package/tsup.config.ts +0 -16
package/dist/index.umd.js CHANGED
@@ -1,39 +1,4075 @@
1
- !function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("react"),require("@copilotkitnext/react"),require("@copilotkit/shared"),require("react-dom"),require("@copilotkit/runtime-client-gql"),require("@ag-ui/client"),require("@copilotkitnext/core")):"function"==typeof define&&define.amd?define(["exports","react","@copilotkitnext/react","@copilotkit/shared","react-dom","@copilotkit/runtime-client-gql","@ag-ui/client","@copilotkitnext/core"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self).CopilotKitReactCore={},e.React,e.CopilotKitNextReact,e.CopilotKitShared,e.ReactDOM,e.CopilotKitRuntimeClientGQL,e.AgUIClient,e.CopilotKitNextCore)}(this,function(e,n,t,r,o,i,l,s){"use strict";function a(e,n){var t={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&n.indexOf(r)<0&&(t[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)n.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(t[r[o]]=e[r[o]])}return t}function u(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}"function"==typeof SuppressedError&&SuppressedError;var c,d={exports:{}},f={};var p,h,g={};
2
- /**
3
- * @license React
4
- * react-jsx-runtime.development.js
5
- *
6
- * Copyright (c) Meta Platforms, Inc. and affiliates.
7
- *
8
- * This source code is licensed under the MIT license found in the
9
- * LICENSE file in the root directory of this source tree.
10
- */function m(){return p||(p=1,"production"!==process.env.NODE_ENV&&function(){function e(n){if(null==n)return null;if("function"==typeof n)return n.$$typeof===E?null:n.displayName||n.name||null;if("string"==typeof n)return n;switch(n){case p:return"Fragment";case m:return"Profiler";case h:return"StrictMode";case x:return"Suspense";case k:return"SuspenseList";case w:return"Activity"}if("object"==typeof n)switch("number"==typeof n.tag&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),n.$$typeof){case f:return"Portal";case v:return(n.displayName||"Context")+".Provider";case y:return(n._context.displayName||"Context")+".Consumer";case b:var t=n.render;return(n=n.displayName)||(n=""!==(n=t.displayName||t.name||"")?"ForwardRef("+n+")":"ForwardRef"),n;case C:return null!==(t=n.displayName||null)?t:e(n.type)||"Memo";case S:t=n._payload,n=n._init;try{return e(n(t))}catch(e){}}return null}function t(e){return""+e}function r(e){try{t(e);var n=!1}catch(e){n=!0}if(n){var r=(n=console).error,o="function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return r.call(n,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",o),t(e)}}function o(n){if(n===p)return"<>";if("object"==typeof n&&null!==n&&n.$$typeof===S)return"<...>";try{var t=e(n);return t?"<"+t+">":"<...>"}catch(e){return"<...>"}}function i(){return Error("react-stack-top-frame")}function l(){var n=e(this.type);return T[n]||(T[n]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),void 0!==(n=this.props.ref)?n:null}function s(n,t,o,i,s,c,f,p){var h,g=t.children;if(void 0!==g)if(i)if(O(g)){for(i=0;i<g.length;i++)a(g[i]);Object.freeze&&Object.freeze(g)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else a(g);if(A.call(t,"key")){g=e(n);var m=Object.keys(t).filter(function(e){return"key"!==e});i=0<m.length?"{key: someKey, "+m.join(": ..., ")+": ...}":"{key: someKey}",M[g+i]||(m=0<m.length?"{"+m.join(": ..., ")+": ...}":"{}",console.error('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',i,g,m,g),M[g+i]=!0)}if(g=null,void 0!==o&&(r(o),g=""+o),function(e){if(A.call(e,"key")){var n=Object.getOwnPropertyDescriptor(e,"key").get;if(n&&n.isReactWarning)return!1}return void 0!==e.key}(t)&&(r(t.key),g=""+t.key),"key"in t)for(var y in o={},t)"key"!==y&&(o[y]=t[y]);else o=t;return g&&function(e,n){function t(){u||(u=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",n))}t.isReactWarning=!0,Object.defineProperty(e,"key",{get:t,configurable:!0})}(o,"function"==typeof n?n.displayName||n.name||"Unknown":n),function(e,n,t,r,o,i,s,a){return t=i.ref,e={$$typeof:d,type:e,key:n,props:i,_owner:o},null!==(void 0!==t?t:null)?Object.defineProperty(e,"ref",{enumerable:!1,get:l}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:s}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:a}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}(n,g,c,0,null===(h=I.A)?null:h.getOwner(),o,f,p)}function a(e){"object"==typeof e&&null!==e&&e.$$typeof===d&&e._store&&(e._store.validated=1)}var u,c=n,d=Symbol.for("react.transitional.element"),f=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),h=Symbol.for("react.strict_mode"),m=Symbol.for("react.profiler"),y=Symbol.for("react.consumer"),v=Symbol.for("react.context"),b=Symbol.for("react.forward_ref"),x=Symbol.for("react.suspense"),k=Symbol.for("react.suspense_list"),C=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),w=Symbol.for("react.activity"),E=Symbol.for("react.client.reference"),I=c.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,A=Object.prototype.hasOwnProperty,O=Array.isArray,R=console.createTask?console.createTask:function(){return null},T={},j=(c={"react-stack-bottom-frame":function(e){return e()}})["react-stack-bottom-frame"].bind(c,i)(),P=R(o(i)),M={};g.Fragment=p,g.jsx=function(e,n,t,r,i){var l=1e4>I.recentlyCreatedOwnerStacks++;return s(e,n,t,!1,0,i,l?Error("react-stack-top-frame"):j,l?R(o(e)):P)},g.jsxs=function(e,n,t,r,i){var l=1e4>I.recentlyCreatedOwnerStacks++;return s(e,n,t,!0,0,i,l?Error("react-stack-top-frame"):j,l?R(o(e)):P)}}()),g}var y=(h||(h=1,"production"===process.env.NODE_ENV?d.exports=function(){if(c)return f;c=1;var e=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function t(n,t,r){var o=null;if(void 0!==r&&(o=""+r),void 0!==t.key&&(o=""+t.key),"key"in t)for(var i in r={},t)"key"!==i&&(r[i]=t[i]);else r=t;return t=r.ref,{$$typeof:e,type:n,key:o,ref:void 0!==t?t:null,props:r}}return f.Fragment=n,f.jsx=t,f.jsxs=t,f}():d.exports=m()),d.exports);const v={actions:{},setAction:()=>{},removeAction:()=>{},setRegisteredActions:()=>"",removeRegisteredAction:()=>{},chatComponentsCache:{current:{actions:{},coAgentStateRenders:{}}},getContextString:(e,n)=>k(),addContext:()=>"",removeContext:()=>{},getAllContext:()=>[],getFunctionCallHandler:()=>k(),isLoading:!1,setIsLoading:()=>k(),chatInstructions:"",setChatInstructions:()=>k(),additionalInstructions:[],setAdditionalInstructions:()=>k(),getDocumentsContext:e=>k(),addDocumentContext:()=>k(),removeDocumentContext:()=>{},copilotApiConfig:new class{get chatApiEndpoint(){throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!")}get headers(){return{}}get body(){return{}}},chatSuggestionConfiguration:{},addChatSuggestionConfiguration:()=>{},removeChatSuggestionConfiguration:()=>{},showDevConsole:!1,coagentStates:{},setCoagentStates:()=>{},coagentStatesRef:{current:{}},setCoagentStatesWithRef:()=>{},agentSession:null,setAgentSession:()=>{},forwardedParameters:{},agentLock:null,threadId:"",setThreadId:()=>{},runId:null,setRunId:()=>{},chatAbortControllerRef:{current:null},availableAgents:[],extensions:{},setExtensions:()=>{},interruptActions:{},setInterruptAction:()=>{},removeInterruptAction:()=>{},interruptEventQueue:{},addInterruptEvent:()=>{},resolveInterruptEvent:()=>{},onError:()=>{},bannerError:null,setBannerError:()=>{},internalErrorHandlers:{},setInternalErrorHandler:()=>{},removeInternalErrorHandler:()=>{}},b=n.createContext(v);function x(){const e=n.useContext(b);if(e===v)throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");return e}function k(e){throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!")}const C=(e,n)=>e.reduce((e,t)=>{if(t.id!==n){const r=Object.assign(Object.assign({},t),{children:C(t.children,n)});e.push(r)}return e},[]),S=(e,n,t)=>t?e.map(e=>e.id===t?Object.assign(Object.assign({},e),{children:[...e.children,n]}):e.children.length?Object.assign(Object.assign({},e),{children:S(e.children,n,t)}):e):[...e,n],w=(e,n)=>0===n?(e+1).toString():1===n?String.fromCharCode(65+e):2===n?String.fromCharCode(97+e):"-",E=(e,n="",t=0)=>{const r=" ".repeat(3).repeat(t),o=n.length+r.length,i=" ".repeat(o),l=e.value.split("\n"),s=`${r}${n}${l[0]}`,a=l.slice(1).map(e=>`${i}${e}`).join("\n");let u=`${s}\n`;a&&(u+=`${a}\n`);const c=" ".repeat(n.length);return e.children.forEach((e,n)=>u+=E(e,`${c}${w(n,t+1)}. `,t+1)),u};function I(e,n){switch(n.type){case"ADD_NODE":{const{value:t,parentId:r,id:o}=n,i={id:o,value:t,children:[],categories:new Set(n.categories)};try{return S(e,i,r)}catch(n){return console.error(`Error while adding node with id ${o}: ${n}`),e}}case"REMOVE_NODE":return C(e,n.id);default:return e}}function A(e,n){switch(n.type){case"ADD_ELEMENT":{const{value:t,id:r,categories:o}=n,i={id:r,value:t,categories:new Set(o)},l=new Map(e);return l.set(r,i),l}case"REMOVE_ELEMENT":{const t=new Map(e);return t.delete(n.id),t}default:return e}}const O={messages:[],setMessages:()=>[],suggestions:[],setSuggestions:()=>[]},R=n.createContext(O);const T=n.createContext(void 0);function j(){const e=n.useContext(T);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function P({enabled:e,children:t}){const[o,i]=n.useState([]),[l,s]=n.useState(null),a=n.useCallback(e=>{i(n=>n.filter(n=>n.id!==e))},[]),u=n.useCallback(n=>{var t;if(!e)return;const r=null!==(t=n.id)&&void 0!==t?t:Math.random().toString(36).substring(2,9);i(e=>e.find(e=>e.id===r)?e:[...e,Object.assign(Object.assign({},n),{id:r})]),n.duration&&setTimeout(()=>{a(r)},n.duration)},[e,a]),c=n.useCallback(n=>{(e||null===n)&&s(n)},[e]),d={toasts:o,addToast:u,addGraphQLErrorsToast:n.useCallback(e=>{console.warn("addGraphQLErrorsToast is deprecated. All errors now show as banners.")},[]),removeToast:a,enabled:e,bannerError:l,setBannerError:c};return y.jsxs(T.Provider,{value:d,children:[l&&(()=>{const e=function(e){switch(e){case"critical":return{background:"#fee2e2",border:"#dc2626",text:"#7f1d1d",icon:"#dc2626"};case"warning":return{background:"#fef3c7",border:"#d97706",text:"#78350f",icon:"#d97706"};case"info":return{background:"#dbeafe",border:"#2563eb",text:"#1e3a8a",icon:"#2563eb"}}}(function(e){if(e.severity)switch(e.severity){case r.Severity.CRITICAL:return"critical";case r.Severity.WARNING:return"warning";case r.Severity.INFO:default:return"info"}const n=e.message.toLowerCase();return n.includes("api key")||n.includes("401")||n.includes("unauthorized")||n.includes("authentication")||n.includes("incorrect api key")?"critical":"info"}(l));return y.jsx("div",{style:{position:"fixed",bottom:"20px",left:"50%",transform:"translateX(-50%)",zIndex:9999,backgroundColor:e.background,border:`1px solid ${e.border}`,borderLeft:`4px solid ${e.border}`,borderRadius:"8px",padding:"12px 16px",fontSize:"13px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",backdropFilter:"blur(8px)",maxWidth:"min(90vw, 700px)",width:"100%",boxSizing:"border-box",overflow:"hidden"},children:y.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"10px"},children:[y.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flex:1,minWidth:0},children:[y.jsx("div",{style:{width:"12px",height:"12px",borderRadius:"50%",backgroundColor:e.border,flexShrink:0}}),y.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",flex:1,minWidth:0},children:[y.jsx("div",{style:{color:e.text,lineHeight:"1.4",fontWeight:"400",fontSize:"13px",flex:1,wordBreak:"break-all",overflowWrap:"break-word",maxWidth:"550px",overflow:"hidden",display:"-webkit-box",WebkitLineClamp:10,WebkitBoxOrient:"vertical"},children:(()=>{let e=l.message;const n=e.match(/'message':\s*'([^']+)'/);return n?n[1]:(e=e.split(" - ")[0],e=e.split(": Error code")[0],e=e.replace(/:\s*\d{3}$/,""),e=e.replace(/See more:.*$/g,""),e=e.trim(),e||"Configuration error occurred.")})()}),(()=>{const n=l.message,t=/(https?:\/\/[^\s)]+)/g;let r=null,o="See More";const i=/\[([^\]]+)\]\(([^)]+)\)/g.exec(n);if(i)r=i[2],o="See More";else{const e=t.exec(n);e&&(r=e[0].replace(/[.,;:'"]*$/,""),o="See More")}return r?y.jsx("button",{onClick:()=>window.open(r,"_blank","noopener,noreferrer"),style:{background:e.border,color:"white",border:"none",borderRadius:"5px",padding:"4px 10px",fontSize:"11px",fontWeight:"500",cursor:"pointer",transition:"all 0.2s ease",flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.opacity="0.9",e.currentTarget.style.transform="translateY(-1px)"},onMouseLeave:e=>{e.currentTarget.style.opacity="1",e.currentTarget.style.transform="translateY(0)"},children:o}):null})()]})]}),y.jsx("button",{onClick:()=>c(null),style:{background:"transparent",border:"none",color:e.text,cursor:"pointer",padding:"2px",borderRadius:"3px",fontSize:"14px",lineHeight:"1",opacity:.6,transition:"all 0.2s ease",flexShrink:0},title:"Dismiss",onMouseEnter:e=>{e.currentTarget.style.opacity="1",e.currentTarget.style.background="rgba(0, 0, 0, 0.05)"},onMouseLeave:e=>{e.currentTarget.style.opacity="0.6",e.currentTarget.style.background="transparent"},children:"×"})]})})})(),t]})}function M(e){return void 0!==e?e:"undefined"!=typeof window&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname||"0.0.0.0"===window.location.hostname)}const D=n.createContext(null);function F({children:e}){const t=n.useRef([]),r=n.useRef({getMessagesFromTap:()=>t.current,updateTapMessages:e=>{t.current=e}});return y.jsx(D.Provider,{value:r.current,children:e})}function N({children:e}){const[t,o]=n.useState([]);n.useRef(void 0),n.useRef(void 0),n.useRef(void 0);const{updateTapMessages:i}=function(){const e=n.useContext(D);if(!e)throw new Error("useMessagesTap must be used inside <MessagesTapProvider>");return e}(),{threadId:l,agentSession:s,showDevConsole:a,onError:u,copilotApiConfig:c}=x(),{setBannerError:d}=j(),f=n.useCallback(async(e,n)=>{if(u&&c.publicApiKey)try{const t={type:"error",timestamp:Date.now(),context:{source:"ui",request:{operation:"loadAgentState",url:c.chatApiEndpoint,startTime:Date.now()},technical:{environment:"browser",userAgent:"undefined"!=typeof navigator?navigator.userAgent:void 0,stackTrace:n instanceof Error?n.stack:void 0}},error:e};await u(t)}catch(e){console.error("Error in CopilotMessages onError handler:",e)}},[u,c.publicApiKey,c.chatApiEndpoint]);n.useCallback(e=>{var n;if(null===(n=e.graphQLErrors)||void 0===n?void 0:n.length){const n=e=>{const n=e.extensions,t=null==n?void 0:n.visibility;if(!M(a))return void console.error("CopilotKit Error (hidden in production):",e.message);if(t===r.ErrorVisibility.SILENT)return void console.error("CopilotKit Silent Error:",e.message);const o=(e=>{const n=e.extensions,t=null==n?void 0:n.originalError;if(null==t?void 0:t.stack){if(t.stack.includes("CopilotApiDiscoveryError"))return new r.CopilotKitApiDiscoveryError({message:t.message});if(t.stack.includes("CopilotKitRemoteEndpointDiscoveryError"))return new r.CopilotKitRemoteEndpointDiscoveryError({message:t.message});if(t.stack.includes("CopilotKitAgentDiscoveryError"))return new r.CopilotKitAgentDiscoveryError({agentName:"",availableAgents:[]})}const o=(null==t?void 0:t.message)||e.message,i=null==n?void 0:n.code;return i?new r.CopilotKitError({message:o,code:i}):null})(e);if(o)d(o),f(o,e);else{const n=new r.CopilotKitError({message:e.message,code:r.CopilotKitErrorCode.UNKNOWN});d(n),f(n,e)}};e.graphQLErrors.forEach(n)}else{if(M(a)){const n=new r.CopilotKitError({message:(null==e?void 0:e.message)||String(e),code:r.CopilotKitErrorCode.UNKNOWN});d(n),f(n,e)}else console.error("CopilotKit Error (hidden in production):",e)}},[d,a,f]),n.useEffect(()=>{i(t)},[t,i]);const p=n.useMemo(()=>e,[e]),[h,g]=n.useState([]);return y.jsx(R.Provider,{value:{messages:t,setMessages:o,suggestions:h,setSuggestions:g},children:p})}function L({severity:e=r.Severity.CRITICAL,message:n="",onClose:t,actions:o}){if(!n||!e)return null;const i={[r.Severity.INFO]:{bg:"#f8fafc",border:"#e2e8f0",text:"#475569",accent:"#3b82f6"},[r.Severity.WARNING]:{bg:"#fffbeb",border:"#fbbf24",text:"#92400e",accent:"#f59e0b"},[r.Severity.CRITICAL]:{bg:"#fef2f2",border:"#fecaca",text:"#dc2626",accent:"#ef4444"}}[e];return y.jsxs(y.Fragment,{children:[y.jsx("style",{children:`\n @keyframes slideUp {\n from { opacity: 0; transform: translateX(-50%) translateY(8px); }\n to { opacity: 1; transform: translateX(-50%) translateY(0); }\n }\n \n .usage-banner {\n position: fixed;\n bottom: 24px;\n left: 50%;\n transform: translateX(-50%);\n width: min(600px, calc(100vw - 32px));\n z-index: 10000;\n animation: slideUp 0.2s cubic-bezier(0.16, 1, 0.3, 1);\n }\n \n .banner-content {\n background: linear-gradient(135deg, ${i.bg} 0%, ${i.bg}f5 100%);\n border: 1px solid ${i.border};\n border-radius: 12px;\n padding: 18px 20px;\n box-shadow: \n 0 4px 24px rgba(0, 0, 0, 0.08),\n 0 2px 8px rgba(0, 0, 0, 0.04),\n inset 0 1px 0 rgba(255, 255, 255, 0.7);\n display: flex;\n align-items: center;\n gap: 16px;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;\n backdrop-filter: blur(12px);\n position: relative;\n overflow: hidden;\n }\n \n .banner-content::before {\n content: '';\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n height: 1px;\n background: linear-gradient(90deg, transparent, ${i.accent}40, transparent);\n }\n \n .banner-message {\n color: ${i.text};\n font-size: 14px;\n line-height: 1.5;\n font-weight: 500;\n flex: 1;\n letter-spacing: -0.01em;\n }\n \n .close-btn {\n background: rgba(0, 0, 0, 0.05);\n border: none;\n color: ${i.text};\n cursor: pointer;\n padding: 0;\n border-radius: 6px;\n opacity: 0.6;\n transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);\n font-size: 14px;\n line-height: 1;\n flex-shrink: 0;\n width: 24px;\n height: 24px;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n \n .close-btn:hover {\n opacity: 1;\n background: rgba(0, 0, 0, 0.08);\n transform: scale(1.05);\n }\n \n .btn-primary {\n background: linear-gradient(135deg, ${i.accent} 0%, ${i.accent}e6 100%);\n color: white;\n border: none;\n border-radius: 8px;\n padding: 10px 18px;\n font-size: 13px;\n font-weight: 600;\n cursor: pointer;\n transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);\n font-family: inherit;\n flex-shrink: 0;\n box-shadow: \n 0 2px 8px ${i.accent}30,\n inset 0 1px 0 rgba(255, 255, 255, 0.2);\n letter-spacing: -0.01em;\n }\n \n .btn-primary:hover {\n transform: translateY(-1px) scale(1.02);\n box-shadow: \n 0 4px 12px ${i.accent}40,\n inset 0 1px 0 rgba(255, 255, 255, 0.25);\n }\n \n .btn-primary:active {\n transform: translateY(0) scale(0.98);\n transition: all 0.08s cubic-bezier(0.16, 1, 0.3, 1);\n }\n \n @media (max-width: 640px) {\n .usage-banner {\n width: calc(100vw - 24px);\n }\n \n .banner-content {\n padding: 16px;\n gap: 12px;\n }\n \n .banner-message {\n font-size: 13px;\n line-height: 1.45;\n }\n \n .btn-primary {\n padding: 8px 14px;\n font-size: 12px;\n }\n \n .close-btn {\n width: 22px;\n height: 22px;\n font-size: 12px;\n }\n }\n `}),y.jsx("div",{className:"usage-banner",children:y.jsxs("div",{className:"banner-content",children:[y.jsx("div",{className:"banner-message",children:n}),(null==o?void 0:o.primary)&&y.jsx("button",{className:"btn-primary",onClick:o.primary.onClick,children:o.primary.label}),t&&y.jsx("button",{className:"close-btn",onClick:t,title:"Close",children:"×"})]})})]})}const _=e=>{switch(e.code){case r.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR:return{primary:{label:"Show me how",onClick:()=>window.open("https://docs.copilotkit.ai/premium#how-do-i-get-access-to-premium-features","_blank","noopener,noreferrer")}};case r.CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR:return{primary:{label:"Upgrade",onClick:()=>window.open("https://cloud.copilotkit.ai","_blank","noopener,noreferrer")}};default:return}};const z=({className:e,style:n})=>y.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`lucide lucide-circle-alert ${e||""}`,style:n,children:[y.jsx("circle",{cx:"12",cy:"12",r:"10"}),y.jsx("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),y.jsx("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]}),$=["http","https","mailto","tel"];function B(e){const n=(e||"").trim(),t=n.charAt(0);if("#"===t||"/"===t)return n;const r=n.indexOf(":");if(-1===r)return n;let o=-1;for(;++o<$.length;){const e=$[o];if(r===e.length&&n.slice(0,e.length).toLowerCase()===e)return n}return o=n.indexOf("?"),-1!==o&&r>o?n:(o=n.indexOf("#"),-1!==o&&r>o?n:"javascript:void(0)")}
11
- /*!
12
- * Determine if an object is a Buffer
13
- *
14
- * @author Feross Aboukhadijeh <https://feross.org>
15
- * @license MIT
16
- */var U,K;var H=u(K?U:(K=1,U=function(e){return null!=e&&null!=e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}));function V(e){return e&&"object"==typeof e?"position"in e||"type"in e?W(e.position):"start"in e||"end"in e?W(e):"line"in e||"column"in e?q(e):"":""}function q(e){return J(e&&e.line)+":"+J(e&&e.column)}function W(e){return q(e&&e.start)+"-"+q(e&&e.end)}function J(e){return e&&"number"==typeof e?e:1}class G extends Error{constructor(e,n,t){const r=[null,null];let o={start:{line:null,column:null},end:{line:null,column:null}};if(super(),"string"==typeof n&&(t=n,n=void 0),"string"==typeof t){const e=t.indexOf(":");-1===e?r[1]=t:(r[0]=t.slice(0,e),r[1]=t.slice(e+1))}n&&("type"in n||"position"in n?n.position&&(o=n.position):"start"in n||"end"in n?o=n:("line"in n||"column"in n)&&(o.start=n)),this.name=V(n)||"1:1",this.message="object"==typeof e?e.message:e,this.stack="","object"==typeof e&&e.stack&&(this.stack=e.stack),this.reason=this.message,this.fatal,this.line=o.start.line,this.column=o.start.column,this.position=o,this.source=r[0],this.ruleId=r[1],this.file,this.actual,this.expected,this.url,this.note}}G.prototype.file="",G.prototype.name="",G.prototype.reason="",G.prototype.message="",G.prototype.stack="",G.prototype.fatal=null,G.prototype.column=null,G.prototype.line=null,G.prototype.source=null,G.prototype.ruleId=null,G.prototype.position=null;const Y={basename:function(e,n){if(void 0!==n&&"string"!=typeof n)throw new TypeError('"ext" argument must be a string');Q(e);let t,r=0,o=-1,i=e.length;if(void 0===n||0===n.length||n.length>e.length){for(;i--;)if(47===e.charCodeAt(i)){if(t){r=i+1;break}}else o<0&&(t=!0,o=i+1);return o<0?"":e.slice(r,o)}if(n===e)return"";let l=-1,s=n.length-1;for(;i--;)if(47===e.charCodeAt(i)){if(t){r=i+1;break}}else l<0&&(t=!0,l=i+1),s>-1&&(e.charCodeAt(i)===n.charCodeAt(s--)?s<0&&(o=i):(s=-1,o=l));r===o?o=l:o<0&&(o=e.length);return e.slice(r,o)},dirname:function(e){if(Q(e),0===e.length)return".";let n,t=-1,r=e.length;for(;--r;)if(47===e.charCodeAt(r)){if(n){t=r;break}}else n||(n=!0);return t<0?47===e.charCodeAt(0)?"/":".":1===t&&47===e.charCodeAt(0)?"//":e.slice(0,t)},extname:function(e){Q(e);let n,t=e.length,r=-1,o=0,i=-1,l=0;for(;t--;){const s=e.charCodeAt(t);if(47!==s)r<0&&(n=!0,r=t+1),46===s?i<0?i=t:1!==l&&(l=1):i>-1&&(l=-1);else if(n){o=t+1;break}}if(i<0||r<0||0===l||1===l&&i===r-1&&i===o+1)return"";return e.slice(i,r)},join:function(...e){let n,t=-1;for(;++t<e.length;)Q(e[t]),e[t]&&(n=void 0===n?e[t]:n+"/"+e[t]);return void 0===n?".":function(e){Q(e);const n=47===e.charCodeAt(0);let t=function(e,n){let t,r,o="",i=0,l=-1,s=0,a=-1;for(;++a<=e.length;){if(a<e.length)t=e.charCodeAt(a);else{if(47===t)break;t=47}if(47===t){if(l===a-1||1===s);else if(l!==a-1&&2===s){if(o.length<2||2!==i||46!==o.charCodeAt(o.length-1)||46!==o.charCodeAt(o.length-2))if(o.length>2){if(r=o.lastIndexOf("/"),r!==o.length-1){r<0?(o="",i=0):(o=o.slice(0,r),i=o.length-1-o.lastIndexOf("/")),l=a,s=0;continue}}else if(o.length>0){o="",i=0,l=a,s=0;continue}n&&(o=o.length>0?o+"/..":"..",i=2)}else o.length>0?o+="/"+e.slice(l+1,a):o=e.slice(l+1,a),i=a-l-1;l=a,s=0}else 46===t&&s>-1?s++:s=-1}return o}(e,!n);0!==t.length||n||(t=".");t.length>0&&47===e.charCodeAt(e.length-1)&&(t+="/");return n?"/"+t:t}(n)},sep:"/"};function Q(e){if("string"!=typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const X={cwd:function(){return"/"}};function Z(e){return null!==e&&"object"==typeof e&&e.href&&e.origin}function ee(e){if("string"==typeof e)e=new URL(e);else if(!Z(e)){const n=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw n.code="ERR_INVALID_ARG_TYPE",n}if("file:"!==e.protocol){const e=new TypeError("The URL must be of scheme file");throw e.code="ERR_INVALID_URL_SCHEME",e}return function(e){if(""!==e.hostname){const e=new TypeError('File URL host must be "localhost" or empty on darwin');throw e.code="ERR_INVALID_FILE_URL_HOST",e}const n=e.pathname;let t=-1;for(;++t<n.length;)if(37===n.charCodeAt(t)&&50===n.charCodeAt(t+1)){const e=n.charCodeAt(t+2);if(70===e||102===e){const e=new TypeError("File URL path must not include encoded / characters");throw e.code="ERR_INVALID_FILE_URL_PATH",e}}return decodeURIComponent(n)}(e)}const ne=["history","path","basename","stem","extname","dirname"];class te{constructor(e){let n;n=e?"string"==typeof e||function(e){return H(e)}(e)?{value:e}:Z(e)?{path:e}:e:{},this.data={},this.messages=[],this.history=[],this.cwd=X.cwd(),this.value,this.stored,this.result,this.map;let t,r=-1;for(;++r<ne.length;){const e=ne[r];e in n&&void 0!==n[e]&&null!==n[e]&&(this[e]="history"===e?[...n[e]]:n[e])}for(t in n)ne.includes(t)||(this[t]=n[t])}get path(){return this.history[this.history.length-1]}set path(e){Z(e)&&(e=ee(e)),oe(e,"path"),this.path!==e&&this.history.push(e)}get dirname(){return"string"==typeof this.path?Y.dirname(this.path):void 0}set dirname(e){ie(this.basename,"dirname"),this.path=Y.join(e||"",this.basename)}get basename(){return"string"==typeof this.path?Y.basename(this.path):void 0}set basename(e){oe(e,"basename"),re(e,"basename"),this.path=Y.join(this.dirname||"",e)}get extname(){return"string"==typeof this.path?Y.extname(this.path):void 0}set extname(e){if(re(e,"extname"),ie(this.dirname,"extname"),e){if(46!==e.charCodeAt(0))throw new Error("`extname` must start with `.`");if(e.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Y.join(this.dirname,this.stem+(e||""))}get stem(){return"string"==typeof this.path?Y.basename(this.path,this.extname):void 0}set stem(e){oe(e,"stem"),re(e,"stem"),this.path=Y.join(this.dirname||"",e+(this.extname||""))}toString(e){return(this.value||"").toString(e||void 0)}message(e,n,t){const r=new G(e,n,t);return this.path&&(r.name=this.path+":"+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}info(e,n,t){const r=this.message(e,n,t);return r.fatal=null,r}fail(e,n,t){const r=this.message(e,n,t);throw r.fatal=!0,r}}function re(e,n){if(e&&e.includes(Y.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Y.sep+"`")}function oe(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function ie(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function le(e){if(e)throw e}var se,ae;var ue=function(){if(ae)return se;ae=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,o=function(e){return"function"==typeof Array.isArray?Array.isArray(e):"[object Array]"===n.call(e)},i=function(t){if(!t||"[object Object]"!==n.call(t))return!1;var r,o=e.call(t,"constructor"),i=t.constructor&&t.constructor.prototype&&e.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!o&&!i)return!1;for(r in t);return void 0===r||e.call(t,r)},l=function(e,n){t&&"__proto__"===n.name?t(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},s=function(n,t){if("__proto__"===t){if(!e.call(n,t))return;if(r)return r(n,t).value}return n[t]};return se=function e(){var n,t,r,a,u,c,d=arguments[0],f=1,p=arguments.length,h=!1;for("boolean"==typeof d&&(h=d,d=arguments[1]||{},f=2),(null==d||"object"!=typeof d&&"function"!=typeof d)&&(d={});f<p;++f)if(null!=(n=arguments[f]))for(t in n)r=s(d,t),d!==(a=s(n,t))&&(h&&a&&(i(a)||(u=o(a)))?(u?(u=!1,c=r&&o(r)?r:[]):c=r&&i(r)?r:{},l(d,{name:t,newValue:e(h,c,a)})):void 0!==a&&l(d,{name:t,newValue:a}));return d},se}(),ce=u(ue);function de(e){if("object"!=typeof e||null===e)return!1;const n=Object.getPrototypeOf(e);return!(null!==n&&n!==Object.prototype&&null!==Object.getPrototypeOf(n)||Symbol.toStringTag in e||Symbol.iterator in e)}function fe(){const e=[],n={run:function(...n){let t=-1;const r=n.pop();if("function"!=typeof r)throw new TypeError("Expected function as last argument, not "+r);!function o(i,...l){const s=e[++t];let a=-1;if(i)r(i);else{for(;++a<n.length;)null!==l[a]&&void 0!==l[a]||(l[a]=n[a]);n=l,s?function(e,n){let t;return r;function r(...n){const r=e.length>n.length;let l;r&&n.push(o);try{l=e.apply(this,n)}catch(e){if(r&&t)throw e;return o(e)}r||(l&&l.then&&"function"==typeof l.then?l.then(i,o):l instanceof Error?o(l):i(l))}function o(e,...r){t||(t=!0,n(e,...r))}function i(e){o(null,e)}}(s,o)(...l):r(null,...l)}}(null,...n)},use:function(t){if("function"!=typeof t)throw new TypeError("Expected `middelware` to be a function, not "+t);return e.push(t),n}};return n}const pe=function e(){const n=fe(),t=[];let r,o={},i=-1;return l.data=function(e,n){if("string"==typeof e)return 2===arguments.length?(ve("data",r),o[e]=n,l):he.call(o,e)&&o[e]||null;if(e)return ve("data",r),o=e,l;return o},l.Parser=void 0,l.Compiler=void 0,l.freeze=function(){if(r)return l;for(;++i<t.length;){const[e,...r]=t[i];if(!1===r[0])continue;!0===r[0]&&(r[0]=void 0);const o=e.call(l,...r);"function"==typeof o&&n.use(o)}return r=!0,i=Number.POSITIVE_INFINITY,l},l.attachers=t,l.use=function(e,...n){let i;if(ve("use",r),null==e);else if("function"==typeof e)c(e,...n);else{if("object"!=typeof e)throw new TypeError("Expected usable value, not `"+e+"`");Array.isArray(e)?u(e):a(e)}i&&(o.settings=Object.assign(o.settings||{},i));return l;function s(e){if("function"==typeof e)c(e);else{if("object"!=typeof e)throw new TypeError("Expected usable value, not `"+e+"`");if(Array.isArray(e)){const[n,...t]=e;c(n,...t)}else a(e)}}function a(e){u(e.plugins),e.settings&&(i=Object.assign(i||{},e.settings))}function u(e){let n=-1;if(null==e);else{if(!Array.isArray(e))throw new TypeError("Expected a list of plugins, not `"+e+"`");for(;++n<e.length;){s(e[n])}}}function c(e,n){let r,o=-1;for(;++o<t.length;)if(t[o][0]===e){r=t[o];break}r?(de(r[1])&&de(n)&&(n=ce(!0,r[1],n)),r[1]=n):t.push([...arguments])}},l.parse=function(e){l.freeze();const n=ke(e),t=l.Parser;if(me("parse",t),ge(t,"parse"))return new t(String(n),n).parse();return t(String(n),n)},l.stringify=function(e,n){l.freeze();const t=ke(n),r=l.Compiler;if(ye("stringify",r),be(e),ge(r,"compile"))return new r(e,t).compile();return r(e,t)},l.run=function(e,t,r){be(e),l.freeze(),r||"function"!=typeof t||(r=t,t=void 0);if(!r)return new Promise(o);function o(o,i){function l(n,t,l){t=t||e,n?i(n):o?o(t):r(null,t,l)}n.run(e,ke(t),l)}o(null,r)},l.runSync=function(e,n){let t,r;return l.run(e,n,o),xe("runSync","run",r),t;function o(e,n){le(e),t=n,r=!0}},l.process=function(e,n){if(l.freeze(),me("process",l.Parser),ye("process",l.Compiler),!n)return new Promise(t);function t(t,r){const o=ke(e);function i(e,o){e||!o?r(e):t?t(o):n(null,o)}l.run(l.parse(o),o,(e,n,t)=>{if(!e&&n&&t){const o=l.stringify(n,t);null==o||("string"==typeof(r=o)||H(r)?t.value=o:t.result=o),i(e,t)}else i(e);var r})}t(null,n)},l.processSync=function(e){let n;l.freeze(),me("processSync",l.Parser),ye("processSync",l.Compiler);const t=ke(e);return l.process(t,r),xe("processSync","process",n),t;function r(e){n=!0,le(e)}},l;function l(){const n=e();let r=-1;for(;++r<t.length;)n.use(...t[r]);return n.data(ce(!0,{},o)),n}}().freeze(),he={}.hasOwnProperty;function ge(e,n){return"function"==typeof e&&e.prototype&&(function(e){let n;for(n in e)if(he.call(e,n))return!0;return!1}(e.prototype)||n in e.prototype)}function me(e,n){if("function"!=typeof n)throw new TypeError("Cannot `"+e+"` without `Parser`")}function ye(e,n){if("function"!=typeof n)throw new TypeError("Cannot `"+e+"` without `Compiler`")}function ve(e,n){if(n)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function be(e){if(!de(e)||"string"!=typeof e.type)throw new TypeError("Expected node, got `"+e+"`")}function xe(e,n,t){if(!t)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function ke(e){return function(e){return Boolean(e&&"object"==typeof e&&"message"in e&&"messages"in e)}(e)?e:new te(e)}const Ce={};function Se(e,n,t){if(function(e){return Boolean(e&&"object"==typeof e)}(e)){if("value"in e)return"html"!==e.type||t?e.value:"";if(n&&"alt"in e&&e.alt)return e.alt;if("children"in e)return we(e.children,n,t)}return Array.isArray(e)?we(e,n,t):""}function we(e,n,t){const r=[];let o=-1;for(;++o<e.length;)r[o]=Se(e[o],n,t);return r.join("")}function Ee(e,n,t,r){const o=e.length;let i,l=0;if(n=n<0?-n>o?0:o+n:n>o?o:n,t=t>0?t:0,r.length<1e4)i=Array.from(r),i.unshift(n,t),e.splice(...i);else for(t&&e.splice(n,t);l<r.length;)i=r.slice(l,l+1e4),i.unshift(n,0),e.splice(...i),l+=1e4,n+=1e4}function Ie(e,n){return e.length>0?(Ee(e,e.length,0,n),e):n}const Ae={}.hasOwnProperty;function Oe(e,n){let t;for(t in n){const r=(Ae.call(e,t)?e[t]:void 0)||(e[t]={}),o=n[t];let i;if(o)for(i in o){Ae.call(r,i)||(r[i]=[]);const e=o[i];Re(r[i],Array.isArray(e)?e:e?[e]:[])}}}function Re(e,n){let t=-1;const r=[];for(;++t<n.length;)("after"===n[t].add?e:r).push(n[t]);Ee(e,0,0,r)}const Te=Ue(/[A-Za-z]/),je=Ue(/[\dA-Za-z]/),Pe=Ue(/[#-'*+\--9=?A-Z^-~]/);function Me(e){return null!==e&&(e<32||127===e)}const De=Ue(/\d/),Fe=Ue(/[\dA-Fa-f]/),Ne=Ue(/[!-/:-@[-`{-~]/);function Le(e){return null!==e&&e<-2}function _e(e){return null!==e&&(e<0||32===e)}function ze(e){return-2===e||-1===e||32===e}const $e=Ue(/[!-\/:-@\[-`\{-~\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]/),Be=Ue(/\s/);function Ue(e){return function(n){return null!==n&&e.test(String.fromCharCode(n))}}function Ke(e,n,t,r){const o=r?r-1:Number.POSITIVE_INFINITY;let i=0;return function(r){if(ze(r))return e.enter(t),l(r);return n(r)};function l(r){return ze(r)&&i++<o?(e.consume(r),l):(e.exit(t),n(r))}}const He={tokenize:function(e){const n=e.attempt(this.parser.constructs.contentInitial,function(t){if(null===t)return void e.consume(t);return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),Ke(e,n,"linePrefix")},function(n){return e.enter("paragraph"),r(n)});let t;return n;function r(n){const r=e.enter("chunkText",{contentType:"text",previous:t});return t&&(t.next=r),t=r,o(n)}function o(n){return null===n?(e.exit("chunkText"),e.exit("paragraph"),void e.consume(n)):Le(n)?(e.consume(n),e.exit("chunkText"),r):(e.consume(n),o)}}};const Ve={tokenize:function(e){const n=this,t=[];let r,o,i,l=0;return s;function s(r){if(l<t.length){const o=t[l];return n.containerState=o[1],e.attempt(o[0].continuation,a,u)(r)}return u(r)}function a(e){if(l++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&v();const t=n.events.length;let o,i=t;for(;i--;)if("exit"===n.events[i][0]&&"chunkFlow"===n.events[i][1].type){o=n.events[i][1].end;break}y(l);let s=t;for(;s<n.events.length;)n.events[s][1].end=Object.assign({},o),s++;return Ee(n.events,i+1,0,n.events.slice(t)),n.events.length=s,u(e)}return s(e)}function u(o){if(l===t.length){if(!r)return f(o);if(r.currentConstruct&&r.currentConstruct.concrete)return h(o);n.interrupt=Boolean(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(qe,c,d)(o)}function c(e){return r&&v(),y(l),f(e)}function d(e){return n.parser.lazy[n.now().line]=l!==t.length,i=n.now().offset,h(e)}function f(t){return n.containerState={},e.attempt(qe,p,h)(t)}function p(e){return l++,t.push([n.currentConstruct,n.containerState]),f(e)}function h(t){return null===t?(r&&v(),y(0),void e.consume(t)):(r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{contentType:"flow",previous:o,_tokenizer:r}),g(t))}function g(t){return null===t?(m(e.exit("chunkFlow"),!0),y(0),void e.consume(t)):Le(t)?(e.consume(t),m(e.exit("chunkFlow")),l=0,n.interrupt=void 0,s):(e.consume(t),g)}function m(e,t){const s=n.sliceStream(e);if(t&&s.push(null),e.previous=o,o&&(o.next=e),o=e,r.defineSkip(e.start),r.write(s),n.parser.lazy[e.start.line]){let e=r.events.length;for(;e--;)if(r.events[e][1].start.offset<i&&(!r.events[e][1].end||r.events[e][1].end.offset>i))return;const t=n.events.length;let o,s,a=t;for(;a--;)if("exit"===n.events[a][0]&&"chunkFlow"===n.events[a][1].type){if(o){s=n.events[a][1].end;break}o=!0}for(y(l),e=t;e<n.events.length;)n.events[e][1].end=Object.assign({},s),e++;Ee(n.events,a+1,0,n.events.slice(t)),n.events.length=e}}function y(r){let o=t.length;for(;o-- >r;){const r=t[o];n.containerState=r[1],r[0].exit.call(n,e)}t.length=r}function v(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}},qe={tokenize:function(e,n,t){return Ke(e,e.attempt(this.parser.constructs.document,n,t),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}};function We(e){return null===e||_e(e)||Be(e)?1:$e(e)?2:void 0}function Je(e,n,t){const r=[];let o=-1;for(;++o<e.length;){const i=e[o].resolveAll;i&&!r.includes(i)&&(n=i(n,t),r.push(i))}return n}const Ge={name:"attention",tokenize:function(e,n){const t=this.parser.constructs.attentionMarkers.null,r=this.previous,o=We(r);let i;return function(n){return i=n,e.enter("attentionSequence"),l(n)};function l(s){if(s===i)return e.consume(s),l;const a=e.exit("attentionSequence"),u=We(s),c=!u||2===u&&o||t.includes(s),d=!o||2===o&&u||t.includes(r);return a._open=Boolean(42===i?c:c&&(o||!d)),a._close=Boolean(42===i?d:d&&(u||!c)),n(s)}},resolveAll:function(e,n){let t,r,o,i,l,s,a,u,c=-1;for(;++c<e.length;)if("enter"===e[c][0]&&"attentionSequence"===e[c][1].type&&e[c][1]._close)for(t=c;t--;)if("exit"===e[t][0]&&"attentionSequence"===e[t][1].type&&e[t][1]._open&&n.sliceSerialize(e[t][1]).charCodeAt(0)===n.sliceSerialize(e[c][1]).charCodeAt(0)){if((e[t][1]._close||e[c][1]._open)&&(e[c][1].end.offset-e[c][1].start.offset)%3&&!((e[t][1].end.offset-e[t][1].start.offset+e[c][1].end.offset-e[c][1].start.offset)%3))continue;s=e[t][1].end.offset-e[t][1].start.offset>1&&e[c][1].end.offset-e[c][1].start.offset>1?2:1;const d=Object.assign({},e[t][1].end),f=Object.assign({},e[c][1].start);Ye(d,-s),Ye(f,s),i={type:s>1?"strongSequence":"emphasisSequence",start:d,end:Object.assign({},e[t][1].end)},l={type:s>1?"strongSequence":"emphasisSequence",start:Object.assign({},e[c][1].start),end:f},o={type:s>1?"strongText":"emphasisText",start:Object.assign({},e[t][1].end),end:Object.assign({},e[c][1].start)},r={type:s>1?"strong":"emphasis",start:Object.assign({},i.start),end:Object.assign({},l.end)},e[t][1].end=Object.assign({},i.start),e[c][1].start=Object.assign({},l.end),a=[],e[t][1].end.offset-e[t][1].start.offset&&(a=Ie(a,[["enter",e[t][1],n],["exit",e[t][1],n]])),a=Ie(a,[["enter",r,n],["enter",i,n],["exit",i,n],["enter",o,n]]),a=Ie(a,Je(n.parser.constructs.insideSpan.null,e.slice(t+1,c),n)),a=Ie(a,[["exit",o,n],["enter",l,n],["exit",l,n],["exit",r,n]]),e[c][1].end.offset-e[c][1].start.offset?(u=2,a=Ie(a,[["enter",e[c][1],n],["exit",e[c][1],n]])):u=0,Ee(e,t-1,c-t+3,a),c=t+a.length-u-2;break}c=-1;for(;++c<e.length;)"attentionSequence"===e[c][1].type&&(e[c][1].type="data");return e}};function Ye(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const Qe={name:"autolink",tokenize:function(e,n,t){let r=0;return function(n){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(n),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o};function o(n){return Te(n)?(e.consume(n),i):a(n)}function i(e){return 43===e||45===e||46===e||je(e)?(r=1,l(e)):a(e)}function l(n){return 58===n?(e.consume(n),r=0,s):(43===n||45===n||46===n||je(n))&&r++<32?(e.consume(n),l):(r=0,a(n))}function s(r){return 62===r?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(r),e.exit("autolinkMarker"),e.exit("autolink"),n):null===r||32===r||60===r||Me(r)?t(r):(e.consume(r),s)}function a(n){return 64===n?(e.consume(n),u):Pe(n)?(e.consume(n),a):t(n)}function u(e){return je(e)?c(e):t(e)}function c(t){return 46===t?(e.consume(t),r=0,u):62===t?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(t),e.exit("autolinkMarker"),e.exit("autolink"),n):d(t)}function d(n){if((45===n||je(n))&&r++<63){const t=45===n?d:c;return e.consume(n),t}return t(n)}}};const Xe={tokenize:function(e,n,t){return function(n){return ze(n)?Ke(e,r,"linePrefix")(n):r(n)};function r(e){return null===e||Le(e)?n(e):t(e)}},partial:!0};const Ze={name:"blockQuote",tokenize:function(e,n,t){const r=this;return function(n){if(62===n){const t=r.containerState;return t.open||(e.enter("blockQuote",{_container:!0}),t.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(n),e.exit("blockQuoteMarker"),o}return t(n)};function o(t){return ze(t)?(e.enter("blockQuotePrefixWhitespace"),e.consume(t),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(t))}},continuation:{tokenize:function(e,n,t){const r=this;return function(n){if(ze(n))return Ke(e,o,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(n);return o(n)};function o(r){return e.attempt(Ze,n,t)(r)}}},exit:function(e){e.exit("blockQuote")}};const en={name:"characterEscape",tokenize:function(e,n,t){return function(n){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(n),e.exit("escapeMarker"),r};function r(r){return Ne(r)?(e.enter("characterEscapeValue"),e.consume(r),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):t(r)}}};const nn=document.createElement("i");function tn(e){const n="&"+e+";";nn.innerHTML=n;const t=nn.textContent;return(59!==t.charCodeAt(t.length-1)||"semi"===e)&&(t!==n&&t)}const rn={name:"characterReference",tokenize:function(e,n,t){const r=this;let o,i,l=0;return function(n){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(n),e.exit("characterReferenceMarker"),s};function s(n){return 35===n?(e.enter("characterReferenceMarkerNumeric"),e.consume(n),e.exit("characterReferenceMarkerNumeric"),a):(e.enter("characterReferenceValue"),o=31,i=je,u(n))}function a(n){return 88===n||120===n?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(n),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,i=Fe,u):(e.enter("characterReferenceValue"),o=7,i=De,u(n))}function u(s){if(59===s&&l){const o=e.exit("characterReferenceValue");return i!==je||tn(r.sliceSerialize(o))?(e.enter("characterReferenceMarker"),e.consume(s),e.exit("characterReferenceMarker"),e.exit("characterReference"),n):t(s)}return i(s)&&l++<o?(e.consume(s),u):t(s)}}};const on={tokenize:function(e,n,t){const r=this;return function(n){if(null===n)return t(n);return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),o};function o(e){return r.parser.lazy[r.now().line]?t(e):n(e)}},partial:!0},ln={name:"codeFenced",tokenize:function(e,n,t){const r=this,o={tokenize:function(e,n,t){let o=0;return l;function l(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),a}function a(n){return e.enter("codeFencedFence"),ze(n)?Ke(e,u,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(n):u(n)}function u(n){return n===i?(e.enter("codeFencedFenceSequence"),c(n)):t(n)}function c(n){return n===i?(o++,e.consume(n),c):o>=s?(e.exit("codeFencedFenceSequence"),ze(n)?Ke(e,d,"whitespace")(n):d(n)):t(n)}function d(r){return null===r||Le(r)?(e.exit("codeFencedFence"),n(r)):t(r)}},partial:!0};let i,l=0,s=0;return function(n){return function(n){const t=r.events[r.events.length-1];return l=t&&"linePrefix"===t[1].type?t[2].sliceSerialize(t[1],!0).length:0,i=n,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),a(n)}(n)};function a(n){return n===i?(s++,e.consume(n),a):s<3?t(n):(e.exit("codeFencedFenceSequence"),ze(n)?Ke(e,u,"whitespace")(n):u(n))}function u(t){return null===t||Le(t)?(e.exit("codeFencedFence"),r.interrupt?n(t):e.check(on,p,v)(t)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),c(t))}function c(n){return null===n||Le(n)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),u(n)):ze(n)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Ke(e,d,"whitespace")(n)):96===n&&n===i?t(n):(e.consume(n),c)}function d(n){return null===n||Le(n)?u(n):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),f(n))}function f(n){return null===n||Le(n)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),u(n)):96===n&&n===i?t(n):(e.consume(n),f)}function p(n){return e.attempt(o,v,h)(n)}function h(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),g}function g(n){return l>0&&ze(n)?Ke(e,m,"linePrefix",l+1)(n):m(n)}function m(n){return null===n||Le(n)?e.check(on,p,v)(n):(e.enter("codeFlowValue"),y(n))}function y(n){return null===n||Le(n)?(e.exit("codeFlowValue"),m(n)):(e.consume(n),y)}function v(t){return e.exit("codeFenced"),n(t)}},concrete:!0};const sn={name:"codeIndented",tokenize:function(e,n,t){const r=this;return function(n){return e.enter("codeIndented"),Ke(e,o,"linePrefix",5)(n)};function o(e){const n=r.events[r.events.length-1];return n&&"linePrefix"===n[1].type&&n[2].sliceSerialize(n[1],!0).length>=4?i(e):t(e)}function i(n){return null===n?s(n):Le(n)?e.attempt(an,i,s)(n):(e.enter("codeFlowValue"),l(n))}function l(n){return null===n||Le(n)?(e.exit("codeFlowValue"),i(n)):(e.consume(n),l)}function s(t){return e.exit("codeIndented"),n(t)}}},an={tokenize:function(e,n,t){const r=this;return o;function o(n){return r.parser.lazy[r.now().line]?t(n):Le(n)?(e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),o):Ke(e,i,"linePrefix",5)(n)}function i(e){const i=r.events[r.events.length-1];return i&&"linePrefix"===i[1].type&&i[2].sliceSerialize(i[1],!0).length>=4?n(e):Le(e)?o(e):t(e)}},partial:!0};const un={name:"codeText",tokenize:function(e,n,t){let r,o,i=0;return function(n){return e.enter("codeText"),e.enter("codeTextSequence"),l(n)};function l(n){return 96===n?(e.consume(n),i++,l):(e.exit("codeTextSequence"),s(n))}function s(n){return null===n?t(n):32===n?(e.enter("space"),e.consume(n),e.exit("space"),s):96===n?(o=e.enter("codeTextSequence"),r=0,u(n)):Le(n)?(e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),s):(e.enter("codeTextData"),a(n))}function a(n){return null===n||32===n||96===n||Le(n)?(e.exit("codeTextData"),s(n)):(e.consume(n),a)}function u(t){return 96===t?(e.consume(t),r++,u):r===i?(e.exit("codeTextSequence"),e.exit("codeText"),n(t)):(o.type="codeTextData",a(t))}},resolve:function(e){let n,t,r=e.length-4,o=3;if(!("lineEnding"!==e[o][1].type&&"space"!==e[o][1].type||"lineEnding"!==e[r][1].type&&"space"!==e[r][1].type))for(n=o;++n<r;)if("codeTextData"===e[n][1].type){e[o][1].type="codeTextPadding",e[r][1].type="codeTextPadding",o+=2,r-=2;break}n=o-1,r++;for(;++n<=r;)void 0===t?n!==r&&"lineEnding"!==e[n][1].type&&(t=n):n!==r&&"lineEnding"!==e[n][1].type||(e[t][1].type="codeTextData",n!==t+2&&(e[t][1].end=e[n-1][1].end,e.splice(t+2,n-t-2),r-=n-t-2,n=t+2),t=void 0);return e},previous:function(e){return 96!==e||"characterEscape"===this.events[this.events.length-1][1].type}};function cn(e){const n={};let t,r,o,i,l,s,a,u=-1;for(;++u<e.length;){for(;u in n;)u=n[u];if(t=e[u],u&&"chunkFlow"===t[1].type&&"listItemPrefix"===e[u-1][1].type&&(s=t[1]._tokenizer.events,o=0,o<s.length&&"lineEndingBlank"===s[o][1].type&&(o+=2),o<s.length&&"content"===s[o][1].type))for(;++o<s.length&&"content"!==s[o][1].type;)"chunkText"===s[o][1].type&&(s[o][1]._isInFirstContentOfListItem=!0,o++);if("enter"===t[0])t[1].contentType&&(Object.assign(n,dn(e,u)),u=n[u],a=!0);else if(t[1]._container){for(o=u,r=void 0;o--&&(i=e[o],"lineEnding"===i[1].type||"lineEndingBlank"===i[1].type);)"enter"===i[0]&&(r&&(e[r][1].type="lineEndingBlank"),i[1].type="lineEnding",r=o);r&&(t[1].end=Object.assign({},e[r][1].start),l=e.slice(r,u),l.unshift(t),Ee(e,r,u-r+1,l))}}return!a}function dn(e,n){const t=e[n][1],r=e[n][2];let o=n-1;const i=[],l=t._tokenizer||r.parser[t.contentType](t.start),s=l.events,a=[],u={};let c,d,f=-1,p=t,h=0,g=0;const m=[g];for(;p;){for(;e[++o][1]!==p;);i.push(o),p._tokenizer||(c=r.sliceStream(p),p.next||c.push(null),d&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(c),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),d=p,p=p.next}for(p=t;++f<s.length;)"exit"===s[f][0]&&"enter"===s[f-1][0]&&s[f][1].type===s[f-1][1].type&&s[f][1].start.line!==s[f][1].end.line&&(g=f+1,m.push(g),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):m.pop(),f=m.length;f--;){const n=s.slice(m[f],m[f+1]),t=i.pop();a.unshift([t,t+n.length-1]),Ee(e,t,2,n)}for(f=-1;++f<a.length;)u[h+a[f][0]]=h+a[f][1],h+=a[f][1]-a[f][0]-1;return u}const fn={tokenize:function(e,n){let t;return function(n){return e.enter("content"),t=e.enter("chunkContent",{contentType:"content"}),r(n)};function r(n){return null===n?o(n):Le(n)?e.check(pn,i,o)(n):(e.consume(n),r)}function o(t){return e.exit("chunkContent"),e.exit("content"),n(t)}function i(n){return e.consume(n),e.exit("chunkContent"),t.next=e.enter("chunkContent",{contentType:"content",previous:t}),t=t.next,r}},resolve:function(e){return cn(e),e}},pn={tokenize:function(e,n,t){const r=this;return function(n){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),Ke(e,o,"linePrefix")};function o(o){if(null===o||Le(o))return t(o);const i=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&i&&"linePrefix"===i[1].type&&i[2].sliceSerialize(i[1],!0).length>=4?n(o):e.interrupt(r.parser.constructs.flow,t,n)(o)}},partial:!0};function hn(e,n,t,r,o,i,l,s,a){const u=a||Number.POSITIVE_INFINITY;let c=0;return function(n){if(60===n)return e.enter(r),e.enter(o),e.enter(i),e.consume(n),e.exit(i),d;if(null===n||32===n||41===n||Me(n))return t(n);return e.enter(r),e.enter(l),e.enter(s),e.enter("chunkString",{contentType:"string"}),h(n)};function d(t){return 62===t?(e.enter(i),e.consume(t),e.exit(i),e.exit(o),e.exit(r),n):(e.enter(s),e.enter("chunkString",{contentType:"string"}),f(t))}function f(n){return 62===n?(e.exit("chunkString"),e.exit(s),d(n)):null===n||60===n||Le(n)?t(n):(e.consume(n),92===n?p:f)}function p(n){return 60===n||62===n||92===n?(e.consume(n),f):f(n)}function h(o){return c||null!==o&&41!==o&&!_e(o)?c<u&&40===o?(e.consume(o),c++,h):41===o?(e.consume(o),c--,h):null===o||32===o||40===o||Me(o)?t(o):(e.consume(o),92===o?g:h):(e.exit("chunkString"),e.exit(s),e.exit(l),e.exit(r),n(o))}function g(n){return 40===n||41===n||92===n?(e.consume(n),h):h(n)}}function gn(e,n,t,r,o,i){const l=this;let s,a=0;return function(n){return e.enter(r),e.enter(o),e.consume(n),e.exit(o),e.enter(i),u};function u(d){return a>999||null===d||91===d||93===d&&!s||94===d&&!a&&"_hiddenFootnoteSupport"in l.parser.constructs?t(d):93===d?(e.exit(i),e.enter(o),e.consume(d),e.exit(o),e.exit(r),n):Le(d)?(e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),u):(e.enter("chunkString",{contentType:"string"}),c(d))}function c(n){return null===n||91===n||93===n||Le(n)||a++>999?(e.exit("chunkString"),u(n)):(e.consume(n),s||(s=!ze(n)),92===n?d:c)}function d(n){return 91===n||92===n||93===n?(e.consume(n),a++,c):c(n)}}function mn(e,n,t,r,o,i){let l;return function(n){if(34===n||39===n||40===n)return e.enter(r),e.enter(o),e.consume(n),e.exit(o),l=40===n?41:n,s;return t(n)};function s(t){return t===l?(e.enter(o),e.consume(t),e.exit(o),e.exit(r),n):(e.enter(i),a(t))}function a(n){return n===l?(e.exit(i),s(l)):null===n?t(n):Le(n)?(e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),Ke(e,a,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),u(n))}function u(n){return n===l||null===n||Le(n)?(e.exit("chunkString"),a(n)):(e.consume(n),92===n?c:u)}function c(n){return n===l||92===n?(e.consume(n),u):u(n)}}function yn(e,n){let t;return function r(o){if(Le(o))return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),t=!0,r;if(ze(o))return Ke(e,r,t?"linePrefix":"lineSuffix")(o);return n(o)}}function vn(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const bn={name:"definition",tokenize:function(e,n,t){const r=this;let o;return function(n){return e.enter("definition"),function(n){return gn.call(r,e,i,t,"definitionLabel","definitionLabelMarker","definitionLabelString")(n)}(n)};function i(n){return o=vn(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),58===n?(e.enter("definitionMarker"),e.consume(n),e.exit("definitionMarker"),l):t(n)}function l(n){return _e(n)?yn(e,s)(n):s(n)}function s(n){return hn(e,a,t,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(n)}function a(n){return e.attempt(xn,u,u)(n)}function u(n){return ze(n)?Ke(e,c,"whitespace")(n):c(n)}function c(i){return null===i||Le(i)?(e.exit("definition"),r.parser.defined.push(o),n(i)):t(i)}}},xn={tokenize:function(e,n,t){return function(n){return _e(n)?yn(e,r)(n):t(n)};function r(n){return mn(e,o,t,"definitionTitle","definitionTitleMarker","definitionTitleString")(n)}function o(n){return ze(n)?Ke(e,i,"whitespace")(n):i(n)}function i(e){return null===e||Le(e)?n(e):t(e)}},partial:!0};const kn={name:"hardBreakEscape",tokenize:function(e,n,t){return function(n){return e.enter("hardBreakEscape"),e.consume(n),r};function r(r){return Le(r)?(e.exit("hardBreakEscape"),n(r)):t(r)}}};const Cn={name:"headingAtx",tokenize:function(e,n,t){let r=0;return function(n){return e.enter("atxHeading"),function(n){return e.enter("atxHeadingSequence"),o(n)}(n)};function o(n){return 35===n&&r++<6?(e.consume(n),o):null===n||_e(n)?(e.exit("atxHeadingSequence"),i(n)):t(n)}function i(t){return 35===t?(e.enter("atxHeadingSequence"),l(t)):null===t||Le(t)?(e.exit("atxHeading"),n(t)):ze(t)?Ke(e,i,"whitespace")(t):(e.enter("atxHeadingText"),s(t))}function l(n){return 35===n?(e.consume(n),l):(e.exit("atxHeadingSequence"),i(n))}function s(n){return null===n||35===n||_e(n)?(e.exit("atxHeadingText"),i(n)):(e.consume(n),s)}},resolve:function(e,n){let t,r,o=e.length-2,i=3;"whitespace"===e[i][1].type&&(i+=2);o-2>i&&"whitespace"===e[o][1].type&&(o-=2);"atxHeadingSequence"===e[o][1].type&&(i===o-1||o-4>i&&"whitespace"===e[o-2][1].type)&&(o-=i+1===o?2:4);o>i&&(t={type:"atxHeadingText",start:e[i][1].start,end:e[o][1].end},r={type:"chunkText",start:e[i][1].start,end:e[o][1].end,contentType:"text"},Ee(e,i,o-i+1,[["enter",t,n],["enter",r,n],["exit",r,n],["exit",t,n]]));return e}};const Sn=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],wn=["pre","script","style","textarea"],En={name:"htmlFlow",tokenize:function(e,n,t){const r=this;let o,i,l,s,a;return function(n){return function(n){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(n),u}(n)};function u(s){return 33===s?(e.consume(s),c):47===s?(e.consume(s),i=!0,p):63===s?(e.consume(s),o=3,r.interrupt?n:D):Te(s)?(e.consume(s),l=String.fromCharCode(s),h):t(s)}function c(i){return 45===i?(e.consume(i),o=2,d):91===i?(e.consume(i),o=5,s=0,f):Te(i)?(e.consume(i),o=4,r.interrupt?n:D):t(i)}function d(o){return 45===o?(e.consume(o),r.interrupt?n:D):t(o)}function f(o){const i="CDATA[";return o===i.charCodeAt(s++)?(e.consume(o),6===s?r.interrupt?n:I:f):t(o)}function p(n){return Te(n)?(e.consume(n),l=String.fromCharCode(n),h):t(n)}function h(s){if(null===s||47===s||62===s||_e(s)){const a=47===s,u=l.toLowerCase();return a||i||!wn.includes(u)?Sn.includes(l.toLowerCase())?(o=6,a?(e.consume(s),g):r.interrupt?n(s):I(s)):(o=7,r.interrupt&&!r.parser.lazy[r.now().line]?t(s):i?m(s):y(s)):(o=1,r.interrupt?n(s):I(s))}return 45===s||je(s)?(e.consume(s),l+=String.fromCharCode(s),h):t(s)}function g(o){return 62===o?(e.consume(o),r.interrupt?n:I):t(o)}function m(n){return ze(n)?(e.consume(n),m):w(n)}function y(n){return 47===n?(e.consume(n),w):58===n||95===n||Te(n)?(e.consume(n),v):ze(n)?(e.consume(n),y):w(n)}function v(n){return 45===n||46===n||58===n||95===n||je(n)?(e.consume(n),v):b(n)}function b(n){return 61===n?(e.consume(n),x):ze(n)?(e.consume(n),b):y(n)}function x(n){return null===n||60===n||61===n||62===n||96===n?t(n):34===n||39===n?(e.consume(n),a=n,k):ze(n)?(e.consume(n),x):C(n)}function k(n){return n===a?(e.consume(n),a=null,S):null===n||Le(n)?t(n):(e.consume(n),k)}function C(n){return null===n||34===n||39===n||47===n||60===n||61===n||62===n||96===n||_e(n)?b(n):(e.consume(n),C)}function S(e){return 47===e||62===e||ze(e)?y(e):t(e)}function w(n){return 62===n?(e.consume(n),E):t(n)}function E(n){return null===n||Le(n)?I(n):ze(n)?(e.consume(n),E):t(n)}function I(n){return 45===n&&2===o?(e.consume(n),T):60===n&&1===o?(e.consume(n),j):62===n&&4===o?(e.consume(n),F):63===n&&3===o?(e.consume(n),D):93===n&&5===o?(e.consume(n),M):!Le(n)||6!==o&&7!==o?null===n||Le(n)?(e.exit("htmlFlowData"),A(n)):(e.consume(n),I):(e.exit("htmlFlowData"),e.check(In,N,A)(n))}function A(n){return e.check(An,O,N)(n)}function O(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),R}function R(n){return null===n||Le(n)?A(n):(e.enter("htmlFlowData"),I(n))}function T(n){return 45===n?(e.consume(n),D):I(n)}function j(n){return 47===n?(e.consume(n),l="",P):I(n)}function P(n){if(62===n){const t=l.toLowerCase();return wn.includes(t)?(e.consume(n),F):I(n)}return Te(n)&&l.length<8?(e.consume(n),l+=String.fromCharCode(n),P):I(n)}function M(n){return 93===n?(e.consume(n),D):I(n)}function D(n){return 62===n?(e.consume(n),F):45===n&&2===o?(e.consume(n),D):I(n)}function F(n){return null===n||Le(n)?(e.exit("htmlFlowData"),N(n)):(e.consume(n),F)}function N(t){return e.exit("htmlFlow"),n(t)}},resolveTo:function(e){let n=e.length;for(;n--&&("enter"!==e[n][0]||"htmlFlow"!==e[n][1].type););n>1&&"linePrefix"===e[n-2][1].type&&(e[n][1].start=e[n-2][1].start,e[n+1][1].start=e[n-2][1].start,e.splice(n-2,2));return e},concrete:!0},In={tokenize:function(e,n,t){return function(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(Xe,n,t)}},partial:!0},An={tokenize:function(e,n,t){const r=this;return function(n){if(Le(n))return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),o;return t(n)};function o(e){return r.parser.lazy[r.now().line]?t(e):n(e)}},partial:!0};const On={name:"htmlText",tokenize:function(e,n,t){const r=this;let o,i,l;return function(n){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(n),s};function s(n){return 33===n?(e.consume(n),a):47===n?(e.consume(n),x):63===n?(e.consume(n),v):Te(n)?(e.consume(n),S):t(n)}function a(n){return 45===n?(e.consume(n),u):91===n?(e.consume(n),i=0,p):Te(n)?(e.consume(n),y):t(n)}function u(n){return 45===n?(e.consume(n),f):t(n)}function c(n){return null===n?t(n):45===n?(e.consume(n),d):Le(n)?(l=c,P(n)):(e.consume(n),c)}function d(n){return 45===n?(e.consume(n),f):c(n)}function f(e){return 62===e?j(e):45===e?d(e):c(e)}function p(n){const r="CDATA[";return n===r.charCodeAt(i++)?(e.consume(n),6===i?h:p):t(n)}function h(n){return null===n?t(n):93===n?(e.consume(n),g):Le(n)?(l=h,P(n)):(e.consume(n),h)}function g(n){return 93===n?(e.consume(n),m):h(n)}function m(n){return 62===n?j(n):93===n?(e.consume(n),m):h(n)}function y(n){return null===n||62===n?j(n):Le(n)?(l=y,P(n)):(e.consume(n),y)}function v(n){return null===n?t(n):63===n?(e.consume(n),b):Le(n)?(l=v,P(n)):(e.consume(n),v)}function b(e){return 62===e?j(e):v(e)}function x(n){return Te(n)?(e.consume(n),k):t(n)}function k(n){return 45===n||je(n)?(e.consume(n),k):C(n)}function C(n){return Le(n)?(l=C,P(n)):ze(n)?(e.consume(n),C):j(n)}function S(n){return 45===n||je(n)?(e.consume(n),S):47===n||62===n||_e(n)?w(n):t(n)}function w(n){return 47===n?(e.consume(n),j):58===n||95===n||Te(n)?(e.consume(n),E):Le(n)?(l=w,P(n)):ze(n)?(e.consume(n),w):j(n)}function E(n){return 45===n||46===n||58===n||95===n||je(n)?(e.consume(n),E):I(n)}function I(n){return 61===n?(e.consume(n),A):Le(n)?(l=I,P(n)):ze(n)?(e.consume(n),I):w(n)}function A(n){return null===n||60===n||61===n||62===n||96===n?t(n):34===n||39===n?(e.consume(n),o=n,O):Le(n)?(l=A,P(n)):ze(n)?(e.consume(n),A):(e.consume(n),R)}function O(n){return n===o?(e.consume(n),o=void 0,T):null===n?t(n):Le(n)?(l=O,P(n)):(e.consume(n),O)}function R(n){return null===n||34===n||39===n||60===n||61===n||96===n?t(n):47===n||62===n||_e(n)?w(n):(e.consume(n),R)}function T(e){return 47===e||62===e||_e(e)?w(e):t(e)}function j(r){return 62===r?(e.consume(r),e.exit("htmlTextData"),e.exit("htmlText"),n):t(r)}function P(n){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),M}function M(n){return ze(n)?Ke(e,D,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(n):D(n)}function D(n){return e.enter("htmlTextData"),l(n)}}};const Rn={name:"labelEnd",tokenize:function(e,n,t){const r=this;let o,i,l=r.events.length;for(;l--;)if(("labelImage"===r.events[l][1].type||"labelLink"===r.events[l][1].type)&&!r.events[l][1]._balanced){o=r.events[l][1];break}return function(n){if(!o)return t(n);if(o._inactive)return c(n);return i=r.parser.defined.includes(vn(r.sliceSerialize({start:o.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(n),e.exit("labelMarker"),e.exit("labelEnd"),s};function s(n){return 40===n?e.attempt(Tn,u,i?u:c)(n):91===n?e.attempt(jn,u,i?a:c)(n):i?u(n):c(n)}function a(n){return e.attempt(Pn,u,c)(n)}function u(e){return n(e)}function c(e){return o._balanced=!0,t(e)}},resolveTo:function(e,n){let t,r,o,i,l=e.length,s=0;for(;l--;)if(t=e[l][1],r){if("link"===t.type||"labelLink"===t.type&&t._inactive)break;"enter"===e[l][0]&&"labelLink"===t.type&&(t._inactive=!0)}else if(o){if("enter"===e[l][0]&&("labelImage"===t.type||"labelLink"===t.type)&&!t._balanced&&(r=l,"labelLink"!==t.type)){s=2;break}}else"labelEnd"===t.type&&(o=l);const a={type:"labelLink"===e[r][1].type?"link":"image",start:Object.assign({},e[r][1].start),end:Object.assign({},e[e.length-1][1].end)},u={type:"label",start:Object.assign({},e[r][1].start),end:Object.assign({},e[o][1].end)},c={type:"labelText",start:Object.assign({},e[r+s+2][1].end),end:Object.assign({},e[o-2][1].start)};return i=[["enter",a,n],["enter",u,n]],i=Ie(i,e.slice(r+1,r+s+3)),i=Ie(i,[["enter",c,n]]),i=Ie(i,Je(n.parser.constructs.insideSpan.null,e.slice(r+s+4,o-3),n)),i=Ie(i,[["exit",c,n],e[o-2],e[o-1],["exit",u,n]]),i=Ie(i,e.slice(o+1)),i=Ie(i,[["exit",a,n]]),Ee(e,r,e.length,i),e},resolveAll:function(e){let n=-1;for(;++n<e.length;){const t=e[n][1];"labelImage"!==t.type&&"labelLink"!==t.type&&"labelEnd"!==t.type||(e.splice(n+1,"labelImage"===t.type?4:2),t.type="data",n++)}return e}},Tn={tokenize:function(e,n,t){return function(n){return e.enter("resource"),e.enter("resourceMarker"),e.consume(n),e.exit("resourceMarker"),r};function r(n){return _e(n)?yn(e,o)(n):o(n)}function o(n){return 41===n?u(n):hn(e,i,l,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(n)}function i(n){return _e(n)?yn(e,s)(n):u(n)}function l(e){return t(e)}function s(n){return 34===n||39===n||40===n?mn(e,a,t,"resourceTitle","resourceTitleMarker","resourceTitleString")(n):u(n)}function a(n){return _e(n)?yn(e,u)(n):u(n)}function u(r){return 41===r?(e.enter("resourceMarker"),e.consume(r),e.exit("resourceMarker"),e.exit("resource"),n):t(r)}}},jn={tokenize:function(e,n,t){const r=this;return function(n){return gn.call(r,e,o,i,"reference","referenceMarker","referenceString")(n)};function o(e){return r.parser.defined.includes(vn(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?n(e):t(e)}function i(e){return t(e)}}},Pn={tokenize:function(e,n,t){return function(n){return e.enter("reference"),e.enter("referenceMarker"),e.consume(n),e.exit("referenceMarker"),r};function r(r){return 93===r?(e.enter("referenceMarker"),e.consume(r),e.exit("referenceMarker"),e.exit("reference"),n):t(r)}}};const Mn={name:"labelStartImage",tokenize:function(e,n,t){const r=this;return function(n){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(n),e.exit("labelImageMarker"),o};function o(n){return 91===n?(e.enter("labelMarker"),e.consume(n),e.exit("labelMarker"),e.exit("labelImage"),i):t(n)}function i(e){return 94===e&&"_hiddenFootnoteSupport"in r.parser.constructs?t(e):n(e)}},resolveAll:Rn.resolveAll};const Dn={name:"labelStartLink",tokenize:function(e,n,t){const r=this;return function(n){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(n),e.exit("labelMarker"),e.exit("labelLink"),o};function o(e){return 94===e&&"_hiddenFootnoteSupport"in r.parser.constructs?t(e):n(e)}},resolveAll:Rn.resolveAll};const Fn={name:"lineEnding",tokenize:function(e,n){return function(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),Ke(e,n,"linePrefix")}}};const Nn={name:"thematicBreak",tokenize:function(e,n,t){let r,o=0;return function(n){return e.enter("thematicBreak"),function(e){return r=e,i(e)}(n)};function i(i){return i===r?(e.enter("thematicBreakSequence"),l(i)):o>=3&&(null===i||Le(i))?(e.exit("thematicBreak"),n(i)):t(i)}function l(n){return n===r?(e.consume(n),o++,l):(e.exit("thematicBreakSequence"),ze(n)?Ke(e,i,"whitespace")(n):i(n))}}};const Ln={name:"list",tokenize:function(e,n,t){const r=this,o=r.events[r.events.length-1];let i=o&&"linePrefix"===o[1].type?o[2].sliceSerialize(o[1],!0).length:0,l=0;return function(n){const o=r.containerState.type||(42===n||43===n||45===n?"listUnordered":"listOrdered");if("listUnordered"===o?!r.containerState.marker||n===r.containerState.marker:De(n)){if(r.containerState.type||(r.containerState.type=o,e.enter(o,{_container:!0})),"listUnordered"===o)return e.enter("listItemPrefix"),42===n||45===n?e.check(Nn,t,a)(n):a(n);if(!r.interrupt||49===n)return e.enter("listItemPrefix"),e.enter("listItemValue"),s(n)}return t(n)};function s(n){return De(n)&&++l<10?(e.consume(n),s):(!r.interrupt||l<2)&&(r.containerState.marker?n===r.containerState.marker:41===n||46===n)?(e.exit("listItemValue"),a(n)):t(n)}function a(n){return e.enter("listItemMarker"),e.consume(n),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||n,e.check(Xe,r.interrupt?t:u,e.attempt(_n,d,c))}function u(e){return r.containerState.initialBlankLine=!0,i++,d(e)}function c(n){return ze(n)?(e.enter("listItemPrefixWhitespace"),e.consume(n),e.exit("listItemPrefixWhitespace"),d):t(n)}function d(t){return r.containerState.size=i+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(t)}},continuation:{tokenize:function(e,n,t){const r=this;return r.containerState._closeFlow=void 0,e.check(Xe,o,i);function o(t){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Ke(e,n,"listItemIndent",r.containerState.size+1)(t)}function i(t){return r.containerState.furtherBlankLines||!ze(t)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,l(t)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(zn,n,l)(t))}function l(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,Ke(e,e.attempt(Ln,n,t),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}},exit:function(e){e.exit(this.containerState.type)}},_n={tokenize:function(e,n,t){const r=this;return Ke(e,function(e){const o=r.events[r.events.length-1];return!ze(e)&&o&&"listItemPrefixWhitespace"===o[1].type?n(e):t(e)},"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5)},partial:!0},zn={tokenize:function(e,n,t){const r=this;return Ke(e,function(e){const o=r.events[r.events.length-1];return o&&"listItemIndent"===o[1].type&&o[2].sliceSerialize(o[1],!0).length===r.containerState.size?n(e):t(e)},"listItemIndent",r.containerState.size+1)},partial:!0};const $n={name:"setextUnderline",tokenize:function(e,n,t){const r=this;let o;return function(n){let l,s=r.events.length;for(;s--;)if("lineEnding"!==r.events[s][1].type&&"linePrefix"!==r.events[s][1].type&&"content"!==r.events[s][1].type){l="paragraph"===r.events[s][1].type;break}if(!r.parser.lazy[r.now().line]&&(r.interrupt||l))return e.enter("setextHeadingLine"),o=n,function(n){return e.enter("setextHeadingLineSequence"),i(n)}(n);return t(n)};function i(n){return n===o?(e.consume(n),i):(e.exit("setextHeadingLineSequence"),ze(n)?Ke(e,l,"lineSuffix")(n):l(n))}function l(r){return null===r||Le(r)?(e.exit("setextHeadingLine"),n(r)):t(r)}},resolveTo:function(e,n){let t,r,o,i=e.length;for(;i--;)if("enter"===e[i][0]){if("content"===e[i][1].type){t=i;break}"paragraph"===e[i][1].type&&(r=i)}else"content"===e[i][1].type&&e.splice(i,1),o||"definition"!==e[i][1].type||(o=i);const l={type:"setextHeading",start:Object.assign({},e[r][1].start),end:Object.assign({},e[e.length-1][1].end)};e[r][1].type="setextHeadingText",o?(e.splice(r,0,["enter",l,n]),e.splice(o+1,0,["exit",e[t][1],n]),e[t][1].end=Object.assign({},e[o][1].end)):e[t][1]=l;return e.push(["exit",l,n]),e}};const Bn={tokenize:function(e){const n=this,t=e.attempt(Xe,function(r){if(null===r)return void e.consume(r);return e.enter("lineEndingBlank"),e.consume(r),e.exit("lineEndingBlank"),n.currentConstruct=void 0,t},e.attempt(this.parser.constructs.flowInitial,r,Ke(e,e.attempt(this.parser.constructs.flow,r,e.attempt(fn,r)),"linePrefix")));return t;function r(r){if(null!==r)return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),n.currentConstruct=void 0,t;e.consume(r)}}};const Un={resolveAll:qn()},Kn=Vn("string"),Hn=Vn("text");function Vn(e){return{tokenize:function(n){const t=this,r=this.parser.constructs[e],o=n.attempt(r,i,l);return i;function i(e){return a(e)?o(e):l(e)}function l(e){if(null!==e)return n.enter("data"),n.consume(e),s;n.consume(e)}function s(e){return a(e)?(n.exit("data"),o(e)):(n.consume(e),s)}function a(e){if(null===e)return!0;const n=r[e];let o=-1;if(n)for(;++o<n.length;){const e=n[o];if(!e.previous||e.previous.call(t,t.previous))return!0}return!1}},resolveAll:qn("text"===e?Wn:void 0)}}function qn(e){return function(n,t){let r,o=-1;for(;++o<=n.length;)void 0===r?n[o]&&"data"===n[o][1].type&&(r=o,o++):n[o]&&"data"===n[o][1].type||(o!==r+2&&(n[r][1].end=n[o-1][1].end,n.splice(r+2,o-r-2),o=r+2),r=void 0);return e?e(n,t):n}}function Wn(e,n){let t=0;for(;++t<=e.length;)if((t===e.length||"lineEnding"===e[t][1].type)&&"data"===e[t-1][1].type){const r=e[t-1][1],o=n.sliceStream(r);let i,l=o.length,s=-1,a=0;for(;l--;){const e=o[l];if("string"==typeof e){for(s=e.length;32===e.charCodeAt(s-1);)a++,s--;if(s)break;s=-1}else if(-2===e)i=!0,a++;else if(-1!==e){l++;break}}if(a){const o={type:t===e.length||i||a<2?"lineSuffix":"hardBreakTrailing",start:{line:r.end.line,column:r.end.column-a,offset:r.end.offset-a,_index:r.start._index+l,_bufferIndex:l?s:r.start._bufferIndex+s},end:Object.assign({},r.end)};r.end=Object.assign({},o.start),r.start.offset===r.end.offset?Object.assign(r,o):(e.splice(t,0,["enter",o,n],["exit",o,n]),t+=2)}t++}return e}function Jn(e,n,t){let r=Object.assign(t?Object.assign({},t):{line:1,column:1,offset:0},{_index:0,_bufferIndex:-1});const o={},i=[];let l=[],s=[];const a={consume:function(e){Le(e)?(r.line++,r.column=1,r.offset+=-3===e?2:1,v()):-1!==e&&(r.column++,r.offset++);r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===l[r._index].length&&(r._bufferIndex=-1,r._index++));u.previous=e},enter:function(e,n){const t=n||{};return t.type=e,t.start=f(),u.events.push(["enter",t,u]),s.push(t),t},exit:function(e){const n=s.pop();return n.end=f(),u.events.push(["exit",n,u]),n},attempt:m(function(e,n){y(e,n.from)}),check:m(g),interrupt:m(g,{interrupt:!0})},u={previous:null,code:null,containerState:{},events:[],parser:e,sliceStream:d,sliceSerialize:function(e,n){return function(e,n){let t=-1;const r=[];let o;for(;++t<e.length;){const i=e[t];let l;if("string"==typeof i)l=i;else switch(i){case-5:l="\r";break;case-4:l="\n";break;case-3:l="\r\n";break;case-2:l=n?" ":"\t";break;case-1:if(!n&&o)continue;l=" ";break;default:l=String.fromCharCode(i)}o=-2===i,r.push(l)}return r.join("")}(d(e),n)},now:f,defineSkip:function(e){o[e.line]=e.column,v()},write:function(e){if(l=Ie(l,e),p(),null!==l[l.length-1])return[];return y(n,0),u.events=Je(i,u.events,u),u.events}};let c=n.tokenize.call(u,a);return n.resolveAll&&i.push(n),u;function d(e){return function(e,n){const t=n.start._index,r=n.start._bufferIndex,o=n.end._index,i=n.end._bufferIndex;let l;if(t===o)l=[e[t].slice(r,i)];else{if(l=e.slice(t,o),r>-1){const e=l[0];"string"==typeof e?l[0]=e.slice(r):l.shift()}i>0&&l.push(e[o].slice(0,i))}return l}(l,e)}function f(){const{line:e,column:n,offset:t,_index:o,_bufferIndex:i}=r;return{line:e,column:n,offset:t,_index:o,_bufferIndex:i}}function p(){let e;for(;r._index<l.length;){const n=l[r._index];if("string"==typeof n)for(e=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===e&&r._bufferIndex<n.length;)h(n.charCodeAt(r._bufferIndex));else h(n)}}function h(e){c=c(e)}function g(e,n){n.restore()}function m(e,n){return function(t,o,i){let l,c,d,p;return Array.isArray(t)?h(t):"tokenize"in t?h([t]):function(e){return n;function n(n){const t=null!==n&&e[n],r=null!==n&&e.null;return h([...Array.isArray(t)?t:t?[t]:[],...Array.isArray(r)?r:r?[r]:[]])(n)}}(t);function h(e){return l=e,c=0,0===e.length?i:g(e[c])}function g(e){return function(t){p=function(){const e=f(),n=u.previous,t=u.currentConstruct,o=u.events.length,i=Array.from(s);return{restore:l,from:o};function l(){r=e,u.previous=n,u.currentConstruct=t,u.events.length=o,s=i,v()}}(),d=e,e.partial||(u.currentConstruct=e);if(e.name&&u.parser.constructs.disable.null.includes(e.name))return y();return e.tokenize.call(n?Object.assign(Object.create(u),n):u,a,m,y)(t)}}function m(n){return e(d,p),o}function y(e){return p.restore(),++c<l.length?g(l[c]):i}}}function y(e,n){e.resolveAll&&!i.includes(e)&&i.push(e),e.resolve&&Ee(u.events,n,u.events.length-n,e.resolve(u.events.slice(n),u)),e.resolveTo&&(u.events=e.resolveTo(u.events,u))}function v(){r.line in o&&r.column<2&&(r.column=o[r.line],r.offset+=o[r.line]-1)}}const Gn={42:Ln,43:Ln,45:Ln,48:Ln,49:Ln,50:Ln,51:Ln,52:Ln,53:Ln,54:Ln,55:Ln,56:Ln,57:Ln,62:Ze},Yn={91:bn},Qn={[-2]:sn,[-1]:sn,32:sn},Xn={35:Cn,42:Nn,45:[$n,Nn],60:En,61:$n,95:Nn,96:ln,126:ln},Zn={38:rn,92:en},et={[-5]:Fn,[-4]:Fn,[-3]:Fn,33:Mn,38:rn,42:Ge,60:[Qe,On],91:Dn,92:[kn,en],93:Rn,95:Ge,96:un},nt={null:[Ge,Un]};var tt=Object.freeze({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:Yn,disable:{null:[]},document:Gn,flow:Xn,flowInitial:Qn,insideSpan:nt,string:Zn,text:et});function rt(e){const n=function(e){const n={};let t=-1;for(;++t<e.length;)Oe(n,e[t]);return n}([tt,...(e||{}).extensions||[]]),t={defined:[],lazy:{},constructs:n,content:r(He),document:r(Ve),flow:r(Bn),string:r(Kn),text:r(Hn)};return t;function r(e){return function(n){return Jn(t,e,n)}}}const ot=/[\0\t\n\r]/g;function it(e,n){const t=Number.parseInt(e,n);return t<9||11===t||t>13&&t<32||t>126&&t<160||t>55295&&t<57344||t>64975&&t<65008||!(65535&~t)||65534==(65535&t)||t>1114111?"�":String.fromCharCode(t)}const lt=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function st(e,n,t){if(n)return n;if(35===t.charCodeAt(0)){const e=t.charCodeAt(1),n=120===e||88===e;return it(t.slice(n?2:1),n?16:10)}return tn(t)||e}const at={}.hasOwnProperty,ut=function(e,n,t){return"string"!=typeof n&&(t=n,n=void 0),function(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:s(re),autolinkProtocol:A,autolinkEmail:A,atxHeading:s(Z),blockQuote:s(J),characterEscape:A,characterReference:A,codeFenced:s(G),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:s(G,a),codeText:s(Y,a),codeTextData:A,data:A,codeFlowValue:A,definition:s(Q),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:s(X),hardBreakEscape:s(ee),hardBreakTrailing:s(ee),htmlFlow:s(ne,a),htmlFlowData:A,htmlText:s(ne,a),htmlTextData:A,image:s(te),label:a,link:s(re),listItem:s(ie),listItemValue:h,listOrdered:s(oe,p),listUnordered:s(oe),paragraph:s(le),reference:B,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:s(Z),strong:s(se),thematicBreak:s(ue)},exit:{atxHeading:c(),atxHeadingSequence:S,autolink:c(),autolinkEmail:W,autolinkProtocol:q,blockQuote:c(),characterEscapeValue:O,characterReferenceMarkerHexadecimal:K,characterReferenceMarkerNumeric:K,characterReferenceValue:H,codeFenced:c(v),codeFencedFence:y,codeFencedFenceInfo:g,codeFencedFenceMeta:m,codeFlowValue:O,codeIndented:c(b),codeText:c(M),codeTextData:O,data:O,definition:c(),definitionDestinationString:C,definitionLabelString:x,definitionTitleString:k,emphasis:c(),hardBreakEscape:c(T),hardBreakTrailing:c(T),htmlFlow:c(j),htmlFlowData:O,htmlText:c(P),htmlTextData:O,image:c(F),label:L,labelText:N,lineEnding:R,link:c(D),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:U,resourceDestinationString:_,resourceTitleString:z,resource:$,setextHeading:c(I),setextHeadingLineSequence:E,setextHeadingText:w,strong:c(),thematicBreak:c()}};dt(n,(e||{}).mdastExtensions||[]);const t={};return r;function r(e){let t={type:"root",children:[]};const r={stack:[t],tokenStack:[],config:n,enter:u,exit:d,buffer:a,resume:f,setData:i,getData:l},s=[];let c=-1;for(;++c<e.length;)if("listOrdered"===e[c][1].type||"listUnordered"===e[c][1].type)if("enter"===e[c][0])s.push(c);else{c=o(e,s.pop(),c)}for(c=-1;++c<e.length;){const t=n[e[c][0]];at.call(t,e[c][1].type)&&t[e[c][1].type].call(Object.assign({sliceSerialize:e[c][2].sliceSerialize},r),e[c][1])}if(r.tokenStack.length>0){const e=r.tokenStack[r.tokenStack.length-1];(e[1]||pt).call(r,void 0,e[0])}for(t.position={start:ct(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:ct(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},c=-1;++c<n.transforms.length;)t=n.transforms[c](t)||t;return t}function o(e,n,t){let r,o,i,l,s=n-1,a=-1,u=!1;for(;++s<=t;){const n=e[s];if("listUnordered"===n[1].type||"listOrdered"===n[1].type||"blockQuote"===n[1].type?("enter"===n[0]?a++:a--,l=void 0):"lineEndingBlank"===n[1].type?"enter"===n[0]&&(!r||l||a||i||(i=s),l=void 0):"linePrefix"===n[1].type||"listItemValue"===n[1].type||"listItemMarker"===n[1].type||"listItemPrefix"===n[1].type||"listItemPrefixWhitespace"===n[1].type||(l=void 0),!a&&"enter"===n[0]&&"listItemPrefix"===n[1].type||-1===a&&"exit"===n[0]&&("listUnordered"===n[1].type||"listOrdered"===n[1].type)){if(r){let l=s;for(o=void 0;l--;){const n=e[l];if("lineEnding"===n[1].type||"lineEndingBlank"===n[1].type){if("exit"===n[0])continue;o&&(e[o][1].type="lineEndingBlank",u=!0),n[1].type="lineEnding",o=l}else if("linePrefix"!==n[1].type&&"blockQuotePrefix"!==n[1].type&&"blockQuotePrefixWhitespace"!==n[1].type&&"blockQuoteMarker"!==n[1].type&&"listItemIndent"!==n[1].type)break}i&&(!o||i<o)&&(r._spread=!0),r.end=Object.assign({},o?e[o][1].start:n[1].end),e.splice(o||s,0,["exit",r,n[2]]),s++,t++}"listItemPrefix"===n[1].type&&(r={type:"listItem",_spread:!1,start:Object.assign({},n[1].start),end:void 0},e.splice(s,0,["enter",r,n[2]]),s++,t++,i=void 0,l=!0)}}return e[n][1]._spread=u,t}function i(e,n){t[e]=n}function l(e){return t[e]}function s(e,n){return t;function t(t){u.call(this,e(t),t),n&&n.call(this,t)}}function a(){this.stack.push({type:"fragment",children:[]})}function u(e,n,t){return this.stack[this.stack.length-1].children.push(e),this.stack.push(e),this.tokenStack.push([n,t]),e.position={start:ct(n.start)},e}function c(e){return n;function n(n){e&&e.call(this,n),d.call(this,n)}}function d(e,n){const t=this.stack.pop(),r=this.tokenStack.pop();if(!r)throw new Error("Cannot close `"+e.type+"` ("+V({start:e.start,end:e.end})+"): it’s not open");if(r[0].type!==e.type)if(n)n.call(this,e,r[0]);else{(r[1]||pt).call(this,e,r[0])}return t.position.end=ct(e.end),t}function f(){return function(e){return Se(e,"boolean"!=typeof Ce.includeImageAlt||Ce.includeImageAlt,"boolean"!=typeof Ce.includeHtml||Ce.includeHtml)}(this.stack.pop())}function p(){i("expectingFirstListItemValue",!0)}function h(e){if(l("expectingFirstListItemValue")){this.stack[this.stack.length-2].start=Number.parseInt(this.sliceSerialize(e),10),i("expectingFirstListItemValue")}}function g(){const e=this.resume();this.stack[this.stack.length-1].lang=e}function m(){const e=this.resume();this.stack[this.stack.length-1].meta=e}function y(){l("flowCodeInside")||(this.buffer(),i("flowCodeInside",!0))}function v(){const e=this.resume();this.stack[this.stack.length-1].value=e.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),i("flowCodeInside")}function b(){const e=this.resume();this.stack[this.stack.length-1].value=e.replace(/(\r?\n|\r)$/g,"")}function x(e){const n=this.resume(),t=this.stack[this.stack.length-1];t.label=n,t.identifier=vn(this.sliceSerialize(e)).toLowerCase()}function k(){const e=this.resume();this.stack[this.stack.length-1].title=e}function C(){const e=this.resume();this.stack[this.stack.length-1].url=e}function S(e){const n=this.stack[this.stack.length-1];if(!n.depth){const t=this.sliceSerialize(e).length;n.depth=t}}function w(){i("setextHeadingSlurpLineEnding",!0)}function E(e){this.stack[this.stack.length-1].depth=61===this.sliceSerialize(e).charCodeAt(0)?1:2}function I(){i("setextHeadingSlurpLineEnding")}function A(e){const n=this.stack[this.stack.length-1];let t=n.children[n.children.length-1];t&&"text"===t.type||(t=ae(),t.position={start:ct(e.start)},n.children.push(t)),this.stack.push(t)}function O(e){const n=this.stack.pop();n.value+=this.sliceSerialize(e),n.position.end=ct(e.end)}function R(e){const t=this.stack[this.stack.length-1];if(l("atHardBreak")){return t.children[t.children.length-1].position.end=ct(e.end),void i("atHardBreak")}!l("setextHeadingSlurpLineEnding")&&n.canContainEols.includes(t.type)&&(A.call(this,e),O.call(this,e))}function T(){i("atHardBreak",!0)}function j(){const e=this.resume();this.stack[this.stack.length-1].value=e}function P(){const e=this.resume();this.stack[this.stack.length-1].value=e}function M(){const e=this.resume();this.stack[this.stack.length-1].value=e}function D(){const e=this.stack[this.stack.length-1];if(l("inReference")){const n=l("referenceType")||"shortcut";e.type+="Reference",e.referenceType=n,delete e.url,delete e.title}else delete e.identifier,delete e.label;i("referenceType")}function F(){const e=this.stack[this.stack.length-1];if(l("inReference")){const n=l("referenceType")||"shortcut";e.type+="Reference",e.referenceType=n,delete e.url,delete e.title}else delete e.identifier,delete e.label;i("referenceType")}function N(e){const n=this.sliceSerialize(e),t=this.stack[this.stack.length-2];t.label=function(e){return e.replace(lt,st)}(n),t.identifier=vn(n).toLowerCase()}function L(){const e=this.stack[this.stack.length-1],n=this.resume(),t=this.stack[this.stack.length-1];if(i("inReference",!0),"link"===t.type){const n=e.children;t.children=n}else t.alt=n}function _(){const e=this.resume();this.stack[this.stack.length-1].url=e}function z(){const e=this.resume();this.stack[this.stack.length-1].title=e}function $(){i("inReference")}function B(){i("referenceType","collapsed")}function U(e){const n=this.resume(),t=this.stack[this.stack.length-1];t.label=n,t.identifier=vn(this.sliceSerialize(e)).toLowerCase(),i("referenceType","full")}function K(e){i("characterReferenceType",e.type)}function H(e){const n=this.sliceSerialize(e),t=l("characterReferenceType");let r;if(t)r=it(n,"characterReferenceMarkerNumeric"===t?10:16),i("characterReferenceType");else{r=tn(n)}const o=this.stack.pop();o.value+=r,o.position.end=ct(e.end)}function q(e){O.call(this,e);this.stack[this.stack.length-1].url=this.sliceSerialize(e)}function W(e){O.call(this,e);this.stack[this.stack.length-1].url="mailto:"+this.sliceSerialize(e)}function J(){return{type:"blockquote",children:[]}}function G(){return{type:"code",lang:null,meta:null,value:""}}function Y(){return{type:"inlineCode",value:""}}function Q(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function X(){return{type:"emphasis",children:[]}}function Z(){return{type:"heading",depth:void 0,children:[]}}function ee(){return{type:"break"}}function ne(){return{type:"html",value:""}}function te(){return{type:"image",title:null,url:"",alt:null}}function re(){return{type:"link",title:null,url:"",children:[]}}function oe(e){return{type:"list",ordered:"listOrdered"===e.type,start:null,spread:e._spread,children:[]}}function ie(e){return{type:"listItem",spread:e._spread,checked:null,children:[]}}function le(){return{type:"paragraph",children:[]}}function se(){return{type:"strong",children:[]}}function ae(){return{type:"text",value:""}}function ue(){return{type:"thematicBreak"}}}(t)(function(e){for(;!cn(e););return e}(rt(t).document().write(function(){let e,n=1,t="",r=!0;return function(o,i,l){const s=[];let a,u,c,d,f;for(o=t+o.toString(i),c=0,t="",r&&(65279===o.charCodeAt(0)&&c++,r=void 0);c<o.length;){if(ot.lastIndex=c,a=ot.exec(o),d=a&&void 0!==a.index?a.index:o.length,f=o.charCodeAt(d),!a){t=o.slice(c);break}if(10===f&&c===d&&e)s.push(-3),e=void 0;else switch(e&&(s.push(-5),e=void 0),c<d&&(s.push(o.slice(c,d)),n+=d-c),f){case 0:s.push(65533),n++;break;case 9:for(u=4*Math.ceil(n/4),s.push(-2);n++<u;)s.push(-1);break;case 10:s.push(-4),n=1;break;default:e=!0,n=1}c=d+1}return l&&(e&&s.push(-5),t&&s.push(t),s.push(null)),s}}()(e,n,!0))))};function ct(e){return{line:e.line,column:e.column,offset:e.offset}}function dt(e,n){let t=-1;for(;++t<n.length;){const r=n[t];Array.isArray(r)?dt(e,r):ft(e,r)}}function ft(e,n){let t;for(t in n)if(at.call(n,t))if("canContainEols"===t){const r=n[t];r&&e[t].push(...r)}else if("transforms"===t){const r=n[t];r&&e[t].push(...r)}else if("enter"===t||"exit"===t){const r=n[t];r&&Object.assign(e[t],r)}}function pt(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+V({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+V({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+V({start:n.start,end:n.end})+") is still open")}function ht(e){Object.assign(this,{Parser:n=>{const t=this.data("settings");return ut(n,Object.assign({},t,e,{extensions:this.data("micromarkExtensions")||[],mdastExtensions:this.data("fromMarkdownExtensions")||[]}))}})}function gt(e){const n=[];let t=-1,r=0,o=0;for(;++t<e.length;){const i=e.charCodeAt(t);let l="";if(37===i&&je(e.charCodeAt(t+1))&&je(e.charCodeAt(t+2)))o=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(l=String.fromCharCode(i));else if(i>55295&&i<57344){const n=e.charCodeAt(t+1);i<56320&&n>56319&&n<57344?(l=String.fromCharCode(i,n),o=1):l="�"}else l=String.fromCharCode(i);l&&(n.push(e.slice(r,t),encodeURIComponent(l)),r=t+o+1,l=""),o&&(t+=o,o=0)}return n.join("")+e.slice(r)}function mt(e,n){const t=String(n.identifier).toUpperCase(),r=gt(t.toLowerCase()),o=e.footnoteOrder.indexOf(t);let i;-1===o?(e.footnoteOrder.push(t),e.footnoteCounts[t]=1,i=e.footnoteOrder.length):(e.footnoteCounts[t]++,i=o+1);const l=e.footnoteCounts[t],s={type:"element",tagName:"a",properties:{href:"#"+e.clobberPrefix+"fn-"+r,id:e.clobberPrefix+"fnref-"+r+(l>1?"-"+l:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(i)}]};e.patch(n,s);const a={type:"element",tagName:"sup",properties:{},children:[s]};return e.patch(n,a),e.applyData(n,a)}function yt(e,n){const t=n.referenceType;let r="]";if("collapsed"===t?r+="[]":"full"===t&&(r+="["+(n.label||n.identifier)+"]"),"imageReference"===n.type)return{type:"text",value:"!["+n.alt+r};const o=e.all(n),i=o[0];i&&"text"===i.type?i.value="["+i.value:o.unshift({type:"text",value:"["});const l=o[o.length-1];return l&&"text"===l.type?l.value+=r:o.push({type:"text",value:r}),o}function vt(e){const n=e.spread;return null==n?e.children.length>1:n}const bt=kt("start"),xt=kt("end");function kt(e){return function(n){const t=n&&n.position&&n.position[e]||{};return{line:t.line||null,column:t.column||null,offset:t.offset>-1?t.offset:null}}}function Ct(e){const n=String(e),t=/\r?\n|\r/g;let r=t.exec(n),o=0;const i=[];for(;r;)i.push(St(n.slice(o,r.index),o>0,!0),r[0]),o=r.index+r[0].length,r=t.exec(n);return i.push(St(n.slice(o),o>0,!1)),i.join("")}function St(e,n,t){let r=0,o=e.length;if(n){let n=e.codePointAt(r);for(;9===n||32===n;)r++,n=e.codePointAt(r)}if(t){let n=e.codePointAt(o-1);for(;9===n||32===n;)o--,n=e.codePointAt(o-1)}return o>r?e.slice(r,o):""}const wt={blockquote:function(e,n){const t={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(n),!0)};return e.patch(n,t),e.applyData(n,t)},break:function(e,n){const t={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,t),[e.applyData(n,t),{type:"text",value:"\n"}]},code:function(e,n){const t=n.value?n.value+"\n":"",r=n.lang?n.lang.match(/^[^ \t]+(?=[ \t]|$)/):null,o={};r&&(o.className=["language-"+r]);let i={type:"element",tagName:"code",properties:o,children:[{type:"text",value:t}]};return n.meta&&(i.data={meta:n.meta}),e.patch(n,i),i=e.applyData(n,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(n,i),i},delete:function(e,n){const t={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,t),e.applyData(n,t)},emphasis:function(e,n){const t={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,t),e.applyData(n,t)},footnoteReference:mt,footnote:function(e,n){const t=e.footnoteById;let r=1;for(;r in t;)r++;const o=String(r);return t[o]={type:"footnoteDefinition",identifier:o,children:[{type:"paragraph",children:n.children}],position:n.position},mt(e,{type:"footnoteReference",identifier:o,position:n.position})},heading:function(e,n){const t={type:"element",tagName:"h"+n.depth,properties:{},children:e.all(n)};return e.patch(n,t),e.applyData(n,t)},html:function(e,n){if(e.dangerous){const t={type:"raw",value:n.value};return e.patch(n,t),e.applyData(n,t)}return null},imageReference:function(e,n){const t=e.definition(n.identifier);if(!t)return yt(e,n);const r={src:gt(t.url||""),alt:n.alt};null!==t.title&&void 0!==t.title&&(r.title=t.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(n,o),e.applyData(n,o)},image:function(e,n){const t={src:gt(n.url)};null!==n.alt&&void 0!==n.alt&&(t.alt=n.alt),null!==n.title&&void 0!==n.title&&(t.title=n.title);const r={type:"element",tagName:"img",properties:t,children:[]};return e.patch(n,r),e.applyData(n,r)},inlineCode:function(e,n){const t={type:"text",value:n.value.replace(/\r?\n|\r/g," ")};e.patch(n,t);const r={type:"element",tagName:"code",properties:{},children:[t]};return e.patch(n,r),e.applyData(n,r)},linkReference:function(e,n){const t=e.definition(n.identifier);if(!t)return yt(e,n);const r={href:gt(t.url||"")};null!==t.title&&void 0!==t.title&&(r.title=t.title);const o={type:"element",tagName:"a",properties:r,children:e.all(n)};return e.patch(n,o),e.applyData(n,o)},link:function(e,n){const t={href:gt(n.url)};null!==n.title&&void 0!==n.title&&(t.title=n.title);const r={type:"element",tagName:"a",properties:t,children:e.all(n)};return e.patch(n,r),e.applyData(n,r)},listItem:function(e,n,t){const r=e.all(n),o=t?function(e){let n=!1;if("list"===e.type){n=e.spread||!1;const t=e.children;let r=-1;for(;!n&&++r<t.length;)n=vt(t[r])}return n}(t):vt(n),i={},l=[];if("boolean"==typeof n.checked){const e=r[0];let t;e&&"element"===e.type&&"p"===e.tagName?t=e:(t={type:"element",tagName:"p",properties:{},children:[]},r.unshift(t)),t.children.length>0&&t.children.unshift({type:"text",value:" "}),t.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:n.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let s=-1;for(;++s<r.length;){const e=r[s];(o||0!==s||"element"!==e.type||"p"!==e.tagName)&&l.push({type:"text",value:"\n"}),"element"!==e.type||"p"!==e.tagName||o?l.push(e):l.push(...e.children)}const a=r[r.length-1];a&&(o||"element"!==a.type||"p"!==a.tagName)&&l.push({type:"text",value:"\n"});const u={type:"element",tagName:"li",properties:i,children:l};return e.patch(n,u),e.applyData(n,u)},list:function(e,n){const t={},r=e.all(n);let o=-1;for("number"==typeof n.start&&1!==n.start&&(t.start=n.start);++o<r.length;){const e=r[o];if("element"===e.type&&"li"===e.tagName&&e.properties&&Array.isArray(e.properties.className)&&e.properties.className.includes("task-list-item")){t.className=["contains-task-list"];break}}const i={type:"element",tagName:n.ordered?"ol":"ul",properties:t,children:e.wrap(r,!0)};return e.patch(n,i),e.applyData(n,i)},paragraph:function(e,n){const t={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,t),e.applyData(n,t)},root:function(e,n){const t={type:"root",children:e.wrap(e.all(n))};return e.patch(n,t),e.applyData(n,t)},strong:function(e,n){const t={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,t),e.applyData(n,t)},table:function(e,n){const t=e.all(n),r=t.shift(),o=[];if(r){const t={type:"element",tagName:"thead",properties:{},children:e.wrap([r],!0)};e.patch(n.children[0],t),o.push(t)}if(t.length>0){const r={type:"element",tagName:"tbody",properties:{},children:e.wrap(t,!0)},i=bt(n.children[1]),l=xt(n.children[n.children.length-1]);i.line&&l.line&&(r.position={start:i,end:l}),o.push(r)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(o,!0)};return e.patch(n,i),e.applyData(n,i)},tableCell:function(e,n){const t={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,t),e.applyData(n,t)},tableRow:function(e,n,t){const r=t?t.children:void 0,o=0===(r?r.indexOf(n):1)?"th":"td",i=t&&"table"===t.type?t.align:void 0,l=i?i.length:n.children.length;let s=-1;const a=[];for(;++s<l;){const t=n.children[s],r={},l=i?i[s]:void 0;l&&(r.align=l);let u={type:"element",tagName:o,properties:r,children:[]};t&&(u.children=e.all(t),e.patch(t,u),u=e.applyData(n,u)),a.push(u)}const u={type:"element",tagName:"tr",properties:{},children:e.wrap(a,!0)};return e.patch(n,u),e.applyData(n,u)},text:function(e,n){const t={type:"text",value:Ct(String(n.value))};return e.patch(n,t),e.applyData(n,t)},thematicBreak:function(e,n){const t={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,t),e.applyData(n,t)},toml:Et,yaml:Et,definition:Et,footnoteDefinition:Et};function Et(){return null}const It=function(e){if(null==e)return Ot;if("string"==typeof e)return function(e){return At(n);function n(n){return n&&n.type===e}}(e);if("object"==typeof e)return Array.isArray(e)?function(e){const n=[];let t=-1;for(;++t<e.length;)n[t]=It(e[t]);return At(r);function r(...e){let t=-1;for(;++t<n.length;)if(n[t].call(this,...e))return!0;return!1}}(e):function(e){return At(n);function n(n){let t;for(t in e)if(n[t]!==e[t])return!1;return!0}}(e);if("function"==typeof e)return At(e);throw new Error("Expected function, string, or object as test")};function At(e){return function(n,...t){return Boolean(n&&"object"==typeof n&&"type"in n&&Boolean(e.call(this,n,...t)))}}function Ot(){return!0}const Rt=!0,Tt=!1,jt=function(e,n,t,r){"function"==typeof n&&"function"!=typeof t&&(r=t,t=n,n=null);const o=It(n),i=r?-1:1;!function e(l,s,a){const u=l&&"object"==typeof l?l:{};if("string"==typeof u.type){const e="string"==typeof u.tagName?u.tagName:"string"==typeof u.name?u.name:void 0;Object.defineProperty(c,"name",{value:"node ("+l.type+(e?"<"+e+">":"")+")"})}return c;function c(){let u,c,d,f=[];if((!n||o(l,s,a[a.length-1]||null))&&(f=function(e){if(Array.isArray(e))return e;if("number"==typeof e)return[Rt,e];return[e]}(t(l,a)),f[0]===Tt))return f;if(l.children&&"skip"!==f[0])for(c=(r?l.children.length:-1)+i,d=a.concat(l);c>-1&&c<l.children.length;){if(u=e(l.children[c],c,d)(),u[0]===Tt)return u;c="number"==typeof u[1]?u[1]:c+i}return f}}(e,void 0,[])()};const Pt=function(e,n,t,r){"function"==typeof n&&"function"!=typeof t&&(r=t,t=n,n=null),jt(e,n,function(e,n){const r=n[n.length-1];return t(e,r?r.children.indexOf(e):null,r)},r)};const Mt={}.hasOwnProperty;function Dt(e){return String(e||"").toUpperCase()}const Ft={}.hasOwnProperty;function Nt(e,n){const t=n||{},r=t.allowDangerousHtml||!1,o={};return l.dangerous=r,l.clobberPrefix=void 0===t.clobberPrefix||null===t.clobberPrefix?"user-content-":t.clobberPrefix,l.footnoteLabel=t.footnoteLabel||"Footnotes",l.footnoteLabelTagName=t.footnoteLabelTagName||"h2",l.footnoteLabelProperties=t.footnoteLabelProperties||{className:["sr-only"]},l.footnoteBackLabel=t.footnoteBackLabel||"Back to content",l.unknownHandler=t.unknownHandler,l.passThrough=t.passThrough,l.handlers={...wt,...t.handlers},l.definition=function(e){const n=Object.create(null);if(!e||!e.type)throw new Error("mdast-util-definitions expected node");return Pt(e,"definition",e=>{const t=Dt(e.identifier);t&&!Mt.call(n,t)&&(n[t]=e)}),function(e){const t=Dt(e);return t&&Mt.call(n,t)?n[t]:null}}(e),l.footnoteById=o,l.footnoteOrder=[],l.footnoteCounts={},l.patch=Lt,l.applyData=_t,l.one=function(e,n){return zt(l,e,n)},l.all=function(e){return $t(l,e)},l.wrap=Bt,l.augment=i,Pt(e,"footnoteDefinition",e=>{const n=String(e.identifier).toUpperCase();Ft.call(o,n)||(o[n]=e)}),l;function i(e,n){if(e&&"data"in e&&e.data){const t=e.data;t.hName&&("element"!==n.type&&(n={type:"element",tagName:"",properties:{},children:[]}),n.tagName=t.hName),"element"===n.type&&t.hProperties&&(n.properties={...n.properties,...t.hProperties}),"children"in n&&n.children&&t.hChildren&&(n.children=t.hChildren)}if(e){const t="type"in e?e:{position:e};(function(e){return!(e&&e.position&&e.position.start&&e.position.start.line&&e.position.start.column&&e.position.end&&e.position.end.line&&e.position.end.column)})(t)||(n.position={start:bt(t),end:xt(t)})}return n}function l(e,n,t,r){return Array.isArray(t)&&(r=t,t={}),i(e,{type:"element",tagName:n,properties:t||{},children:r||[]})}}function Lt(e,n){e.position&&(n.position=function(e){return{start:bt(e),end:xt(e)}}(e))}function _t(e,n){let t=n;if(e&&e.data){const n=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;"string"==typeof n&&("element"===t.type?t.tagName=n:t={type:"element",tagName:n,properties:{},children:[]}),"element"===t.type&&o&&(t.properties={...t.properties,...o}),"children"in t&&t.children&&null!=r&&(t.children=r)}return t}function zt(e,n,t){const r=n&&n.type;if(!r)throw new Error("Expected node, got `"+n+"`");return Ft.call(e.handlers,r)?e.handlers[r](e,n,t):e.passThrough&&e.passThrough.includes(r)?"children"in n?{...n,children:$t(e,n)}:n:e.unknownHandler?e.unknownHandler(e,n,t):function(e,n){const t=n.data||{},r=!("value"in n)||Ft.call(t,"hProperties")||Ft.call(t,"hChildren")?{type:"element",tagName:"div",properties:{},children:$t(e,n)}:{type:"text",value:n.value};return e.patch(n,r),e.applyData(n,r)}(e,n)}function $t(e,n){const t=[];if("children"in n){const r=n.children;let o=-1;for(;++o<r.length;){const i=zt(e,r[o],n);if(i){if(o&&"break"===r[o-1].type&&(Array.isArray(i)||"text"!==i.type||(i.value=i.value.replace(/^\s+/,"")),!Array.isArray(i)&&"element"===i.type)){const e=i.children[0];e&&"text"===e.type&&(e.value=e.value.replace(/^\s+/,""))}Array.isArray(i)?t.push(...i):t.push(i)}}}return t}function Bt(e,n){const t=[];let r=-1;for(n&&t.push({type:"text",value:"\n"});++r<e.length;)r&&t.push({type:"text",value:"\n"}),t.push(e[r]);return n&&e.length>0&&t.push({type:"text",value:"\n"}),t}function Ut(e,n){const t=Nt(e,n),r=t.one(e,null),o=function(e){const n=[];let t=-1;for(;++t<e.footnoteOrder.length;){const r=e.footnoteById[e.footnoteOrder[t]];if(!r)continue;const o=e.all(r),i=String(r.identifier).toUpperCase(),l=gt(i.toLowerCase());let s=0;const a=[];for(;++s<=e.footnoteCounts[i];){const n={type:"element",tagName:"a",properties:{href:"#"+e.clobberPrefix+"fnref-"+l+(s>1?"-"+s:""),dataFootnoteBackref:!0,className:["data-footnote-backref"],ariaLabel:e.footnoteBackLabel},children:[{type:"text",value:"↩"}]};s>1&&n.children.push({type:"element",tagName:"sup",children:[{type:"text",value:String(s)}]}),a.length>0&&a.push({type:"text",value:" "}),a.push(n)}const u=o[o.length-1];if(u&&"element"===u.type&&"p"===u.tagName){const e=u.children[u.children.length-1];e&&"text"===e.type?e.value+=" ":u.children.push({type:"text",value:" "}),u.children.push(...a)}else o.push(...a);const c={type:"element",tagName:"li",properties:{id:e.clobberPrefix+"fn-"+l},children:e.wrap(o,!0)};e.patch(r,c),n.push(c)}if(0!==n.length)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:e.footnoteLabelTagName,properties:{...JSON.parse(JSON.stringify(e.footnoteLabelProperties)),id:"footnote-label"},children:[{type:"text",value:e.footnoteLabel}]},{type:"text",value:"\n"},{type:"element",tagName:"ol",properties:{},children:e.wrap(n,!0)},{type:"text",value:"\n"}]}}(t);return o&&r.children.push({type:"text",value:"\n"},o),Array.isArray(r)?{type:"root",children:r}:r}const Kt=function(e,n){return e&&"run"in e?function(e,n){return(t,r,o)=>{e.run(Ut(t,n),r,e=>{o(e)})}}(e,n):function(e){return n=>Ut(n,e)}(e||n)};var Ht,Vt={exports:{}},qt={exports:{}},Wt={};var Jt,Gt,Yt,Qt,Xt,Zt,er,nr,tr,rr,or,ir,lr,sr,ar,ur={};
17
- /** @license React v16.13.1
18
- * react-is.development.js
19
- *
20
- * Copyright (c) Facebook, Inc. and its affiliates.
21
- *
22
- * This source code is licensed under the MIT license found in the
23
- * LICENSE file in the root directory of this source tree.
24
- */function cr(){return Gt||(Gt=1,"production"===process.env.NODE_ENV?qt.exports=function(){if(Ht)return Wt;Ht=1;var e="function"==typeof Symbol&&Symbol.for,n=e?Symbol.for("react.element"):60103,t=e?Symbol.for("react.portal"):60106,r=e?Symbol.for("react.fragment"):60107,o=e?Symbol.for("react.strict_mode"):60108,i=e?Symbol.for("react.profiler"):60114,l=e?Symbol.for("react.provider"):60109,s=e?Symbol.for("react.context"):60110,a=e?Symbol.for("react.async_mode"):60111,u=e?Symbol.for("react.concurrent_mode"):60111,c=e?Symbol.for("react.forward_ref"):60112,d=e?Symbol.for("react.suspense"):60113,f=e?Symbol.for("react.suspense_list"):60120,p=e?Symbol.for("react.memo"):60115,h=e?Symbol.for("react.lazy"):60116,g=e?Symbol.for("react.block"):60121,m=e?Symbol.for("react.fundamental"):60117,y=e?Symbol.for("react.responder"):60118,v=e?Symbol.for("react.scope"):60119;function b(e){if("object"==typeof e&&null!==e){var f=e.$$typeof;switch(f){case n:switch(e=e.type){case a:case u:case r:case i:case o:case d:return e;default:switch(e=e&&e.$$typeof){case s:case c:case h:case p:case l:return e;default:return f}}case t:return f}}}function x(e){return b(e)===u}return Wt.AsyncMode=a,Wt.ConcurrentMode=u,Wt.ContextConsumer=s,Wt.ContextProvider=l,Wt.Element=n,Wt.ForwardRef=c,Wt.Fragment=r,Wt.Lazy=h,Wt.Memo=p,Wt.Portal=t,Wt.Profiler=i,Wt.StrictMode=o,Wt.Suspense=d,Wt.isAsyncMode=function(e){return x(e)||b(e)===a},Wt.isConcurrentMode=x,Wt.isContextConsumer=function(e){return b(e)===s},Wt.isContextProvider=function(e){return b(e)===l},Wt.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===n},Wt.isForwardRef=function(e){return b(e)===c},Wt.isFragment=function(e){return b(e)===r},Wt.isLazy=function(e){return b(e)===h},Wt.isMemo=function(e){return b(e)===p},Wt.isPortal=function(e){return b(e)===t},Wt.isProfiler=function(e){return b(e)===i},Wt.isStrictMode=function(e){return b(e)===o},Wt.isSuspense=function(e){return b(e)===d},Wt.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===r||e===u||e===i||e===o||e===d||e===f||"object"==typeof e&&null!==e&&(e.$$typeof===h||e.$$typeof===p||e.$$typeof===l||e.$$typeof===s||e.$$typeof===c||e.$$typeof===m||e.$$typeof===y||e.$$typeof===v||e.$$typeof===g)},Wt.typeOf=b,Wt}():qt.exports=(Jt||(Jt=1,"production"!==process.env.NODE_ENV&&function(){var e="function"==typeof Symbol&&Symbol.for,n=e?Symbol.for("react.element"):60103,t=e?Symbol.for("react.portal"):60106,r=e?Symbol.for("react.fragment"):60107,o=e?Symbol.for("react.strict_mode"):60108,i=e?Symbol.for("react.profiler"):60114,l=e?Symbol.for("react.provider"):60109,s=e?Symbol.for("react.context"):60110,a=e?Symbol.for("react.async_mode"):60111,u=e?Symbol.for("react.concurrent_mode"):60111,c=e?Symbol.for("react.forward_ref"):60112,d=e?Symbol.for("react.suspense"):60113,f=e?Symbol.for("react.suspense_list"):60120,p=e?Symbol.for("react.memo"):60115,h=e?Symbol.for("react.lazy"):60116,g=e?Symbol.for("react.block"):60121,m=e?Symbol.for("react.fundamental"):60117,y=e?Symbol.for("react.responder"):60118,v=e?Symbol.for("react.scope"):60119;function b(e){if("object"==typeof e&&null!==e){var f=e.$$typeof;switch(f){case n:var g=e.type;switch(g){case a:case u:case r:case i:case o:case d:return g;default:var m=g&&g.$$typeof;switch(m){case s:case c:case h:case p:case l:return m;default:return f}}case t:return f}}}var x=a,k=u,C=s,S=l,w=n,E=c,I=r,A=h,O=p,R=t,T=i,j=o,P=d,M=!1;function D(e){return b(e)===u}ur.AsyncMode=x,ur.ConcurrentMode=k,ur.ContextConsumer=C,ur.ContextProvider=S,ur.Element=w,ur.ForwardRef=E,ur.Fragment=I,ur.Lazy=A,ur.Memo=O,ur.Portal=R,ur.Profiler=T,ur.StrictMode=j,ur.Suspense=P,ur.isAsyncMode=function(e){return M||(M=!0,console.warn("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.")),D(e)||b(e)===a},ur.isConcurrentMode=D,ur.isContextConsumer=function(e){return b(e)===s},ur.isContextProvider=function(e){return b(e)===l},ur.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===n},ur.isForwardRef=function(e){return b(e)===c},ur.isFragment=function(e){return b(e)===r},ur.isLazy=function(e){return b(e)===h},ur.isMemo=function(e){return b(e)===p},ur.isPortal=function(e){return b(e)===t},ur.isProfiler=function(e){return b(e)===i},ur.isStrictMode=function(e){return b(e)===o},ur.isSuspense=function(e){return b(e)===d},ur.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===r||e===u||e===i||e===o||e===d||e===f||"object"==typeof e&&null!==e&&(e.$$typeof===h||e.$$typeof===p||e.$$typeof===l||e.$$typeof===s||e.$$typeof===c||e.$$typeof===m||e.$$typeof===y||e.$$typeof===v||e.$$typeof===g)},ur.typeOf=b}()),ur)),qt.exports}
25
- /*
26
- object-assign
27
- (c) Sindre Sorhus
28
- @license MIT
29
- */function dr(){if(Qt)return Yt;Qt=1;var e=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,t=Object.prototype.propertyIsEnumerable;return Yt=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var n={},t=0;t<10;t++)n["_"+String.fromCharCode(t)]=t;if("0123456789"!==Object.getOwnPropertyNames(n).map(function(e){return n[e]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(e){r[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}}()?Object.assign:function(r,o){for(var i,l,s=function(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(r),a=1;a<arguments.length;a++){for(var u in i=Object(arguments[a]))n.call(i,u)&&(s[u]=i[u]);if(e){l=e(i);for(var c=0;c<l.length;c++)t.call(i,l[c])&&(s[l[c]]=i[l[c]])}}return s},Yt}function fr(){if(Zt)return Xt;Zt=1;return Xt="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"}function pr(){return nr?er:(nr=1,er=Function.call.bind(Object.prototype.hasOwnProperty))}function hr(){if(rr)return tr;rr=1;var e=function(){};if("production"!==process.env.NODE_ENV){var n=fr(),t={},r=pr();e=function(e){var n="Warning: "+e;"undefined"!=typeof console&&console.error(n);try{throw new Error(n)}catch(e){}}}function o(o,i,l,s,a){if("production"!==process.env.NODE_ENV)for(var u in o)if(r(o,u)){var c;try{if("function"!=typeof o[u]){var d=Error((s||"React class")+": "+l+" type `"+u+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof o[u]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw d.name="Invariant Violation",d}c=o[u](i,u,s,l,null,n)}catch(e){c=e}if(!c||c instanceof Error||e((s||"React class")+": type specification of "+l+" `"+u+"` is invalid; the type checker function must return `null` or an `Error` but returned a "+typeof c+". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."),c instanceof Error&&!(c.message in t)){t[c.message]=!0;var f=a?a():"";e("Failed "+l+" type: "+c.message+(null!=f?f:""))}}}return o.resetWarningCache=function(){"production"!==process.env.NODE_ENV&&(t={})},tr=o}function gr(){if(ir)return or;ir=1;var e=cr(),n=dr(),t=fr(),r=pr(),o=hr(),i=function(){};function l(){return null}return"production"!==process.env.NODE_ENV&&(i=function(e){var n="Warning: "+e;"undefined"!=typeof console&&console.error(n);try{throw new Error(n)}catch(e){}}),or=function(s,a){var u="function"==typeof Symbol&&Symbol.iterator;var c="<<anonymous>>",d={array:g("array"),bigint:g("bigint"),bool:g("boolean"),func:g("function"),number:g("number"),object:g("object"),string:g("string"),symbol:g("symbol"),any:h(l),arrayOf:function(e){return h(function(n,r,o,i,l){if("function"!=typeof e)return new p("Property `"+l+"` of component `"+o+"` has invalid PropType notation inside arrayOf.");var s=n[r];if(!Array.isArray(s))return new p("Invalid "+i+" `"+l+"` of type `"+v(s)+"` supplied to `"+o+"`, expected an array.");for(var a=0;a<s.length;a++){var u=e(s,a,o,i,l+"["+a+"]",t);if(u instanceof Error)return u}return null})},element:h(function(e,n,t,r,o){var i=e[n];return s(i)?null:new p("Invalid "+r+" `"+o+"` of type `"+v(i)+"` supplied to `"+t+"`, expected a single ReactElement.")}),elementType:h(function(n,t,r,o,i){var l=n[t];return e.isValidElementType(l)?null:new p("Invalid "+o+" `"+i+"` of type `"+v(l)+"` supplied to `"+r+"`, expected a single ReactElement type.")}),instanceOf:function(e){return h(function(n,t,r,o,i){if(!(n[t]instanceof e)){var l=e.name||c;return new p("Invalid "+o+" `"+i+"` of type `"+(((s=n[t]).constructor&&s.constructor.name?s.constructor.name:c)+"` supplied to `")+r+"`, expected instance of `"+l+"`.")}var s;return null})},node:h(function(e,n,t,r,o){return y(e[n])?null:new p("Invalid "+r+" `"+o+"` supplied to `"+t+"`, expected a ReactNode.")}),objectOf:function(e){return h(function(n,o,i,l,s){if("function"!=typeof e)return new p("Property `"+s+"` of component `"+i+"` has invalid PropType notation inside objectOf.");var a=n[o],u=v(a);if("object"!==u)return new p("Invalid "+l+" `"+s+"` of type `"+u+"` supplied to `"+i+"`, expected an object.");for(var c in a)if(r(a,c)){var d=e(a,c,i,l,s+"."+c,t);if(d instanceof Error)return d}return null})},oneOf:function(e){if(!Array.isArray(e))return"production"!==process.env.NODE_ENV&&i(arguments.length>1?"Invalid arguments supplied to oneOf, expected an array, got "+arguments.length+" arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).":"Invalid argument supplied to oneOf, expected an array."),l;return h(function(n,t,r,o,i){for(var l=n[t],s=0;s<e.length;s++)if(f(l,e[s]))return null;var a=JSON.stringify(e,function(e,n){return"symbol"===b(n)?String(n):n});return new p("Invalid "+o+" `"+i+"` of value `"+String(l)+"` supplied to `"+r+"`, expected one of "+a+".")})},oneOfType:function(e){if(!Array.isArray(e))return"production"!==process.env.NODE_ENV&&i("Invalid argument supplied to oneOfType, expected an instance of array."),l;for(var n=0;n<e.length;n++){var o=e[n];if("function"!=typeof o)return i("Invalid argument supplied to oneOfType. Expected an array of check functions, but received "+x(o)+" at index "+n+"."),l}return h(function(n,o,i,l,s){for(var a=[],u=0;u<e.length;u++){var c=(0,e[u])(n,o,i,l,s,t);if(null==c)return null;c.data&&r(c.data,"expectedType")&&a.push(c.data.expectedType)}return new p("Invalid "+l+" `"+s+"` supplied to `"+i+"`"+(a.length>0?", expected one of type ["+a.join(", ")+"]":"")+".")})},shape:function(e){return h(function(n,r,o,i,l){var s=n[r],a=v(s);if("object"!==a)return new p("Invalid "+i+" `"+l+"` of type `"+a+"` supplied to `"+o+"`, expected `object`.");for(var u in e){var c=e[u];if("function"!=typeof c)return m(o,i,l,u,b(c));var d=c(s,u,o,i,l+"."+u,t);if(d)return d}return null})},exact:function(e){return h(function(o,i,l,s,a){var u=o[i],c=v(u);if("object"!==c)return new p("Invalid "+s+" `"+a+"` of type `"+c+"` supplied to `"+l+"`, expected `object`.");var d=n({},o[i],e);for(var f in d){var h=e[f];if(r(e,f)&&"function"!=typeof h)return m(l,s,a,f,b(h));if(!h)return new p("Invalid "+s+" `"+a+"` key `"+f+"` supplied to `"+l+"`.\nBad object: "+JSON.stringify(o[i],null," ")+"\nValid keys: "+JSON.stringify(Object.keys(e),null," "));var g=h(u,f,l,s,a+"."+f,t);if(g)return g}return null})}};function f(e,n){return e===n?0!==e||1/e==1/n:e!=e&&n!=n}function p(e,n){this.message=e,this.data=n&&"object"==typeof n?n:{},this.stack=""}function h(e){if("production"!==process.env.NODE_ENV)var n={},r=0;function o(o,l,s,u,d,f,h){if(u=u||c,f=f||s,h!==t){if(a){var g=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types");throw g.name="Invariant Violation",g}if("production"!==process.env.NODE_ENV&&"undefined"!=typeof console){var m=u+":"+s;!n[m]&&r<3&&(i("You are manually calling a React.PropTypes validation function for the `"+f+"` prop on `"+u+"`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."),n[m]=!0,r++)}}return null==l[s]?o?null===l[s]?new p("The "+d+" `"+f+"` is marked as required in `"+u+"`, but its value is `null`."):new p("The "+d+" `"+f+"` is marked as required in `"+u+"`, but its value is `undefined`."):null:e(l,s,u,d,f)}var l=o.bind(null,!1);return l.isRequired=o.bind(null,!0),l}function g(e){return h(function(n,t,r,o,i,l){var s=n[t];return v(s)!==e?new p("Invalid "+o+" `"+i+"` of type `"+b(s)+"` supplied to `"+r+"`, expected `"+e+"`.",{expectedType:e}):null})}function m(e,n,t,r,o){return new p((e||"React class")+": "+n+" type `"+t+"."+r+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+o+"`.")}function y(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(y);if(null===e||s(e))return!0;var n=function(e){var n=e&&(u&&e[u]||e["@@iterator"]);if("function"==typeof n)return n}(e);if(!n)return!1;var t,r=n.call(e);if(n!==e.entries){for(;!(t=r.next()).done;)if(!y(t.value))return!1}else for(;!(t=r.next()).done;){var o=t.value;if(o&&!y(o[1]))return!1}return!0;default:return!1}}function v(e){var n=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":function(e,n){return"symbol"===e||!!n&&("Symbol"===n["@@toStringTag"]||"function"==typeof Symbol&&n instanceof Symbol)}(n,e)?"symbol":n}function b(e){if(null==e)return""+e;var n=v(e);if("object"===n){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return n}function x(e){var n=b(e);switch(n){case"array":case"object":return"an "+n;case"boolean":case"date":case"regexp":return"a "+n;default:return n}}return p.prototype=Error.prototype,d.checkPropTypes=o,d.resetWarningCache=o.resetWarningCache,d.PropTypes=d,d},or}function mr(){if(sr)return lr;sr=1;var e=fr();function n(){}function t(){}return t.resetWarningCache=n,lr=function(){function r(n,t,r,o,i,l){if(l!==e){var s=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw s.name="Invariant Violation",s}}function o(){return r}r.isRequired=r;var i={array:r,bigint:r,bool:r,func:r,number:r,object:r,string:r,symbol:r,any:r,arrayOf:o,element:r,elementType:r,instanceOf:o,node:r,objectOf:o,oneOf:o,oneOfType:o,shape:o,exact:o,checkPropTypes:t,resetWarningCache:n};return i.PropTypes=i,i}}function yr(){if(ar)return Vt.exports;if(ar=1,"production"!==process.env.NODE_ENV){var e=cr();Vt.exports=gr()(e.isElement,true)}else Vt.exports=mr()();return Vt.exports}var vr=u(yr());class br{constructor(e,n,t){this.property=e,this.normal=n,t&&(this.space=t)}}function xr(e,n){const t={},r={};let o=-1;for(;++o<e.length;)Object.assign(t,e[o].property),Object.assign(r,e[o].normal);return new br(t,r,n)}function kr(e){return e.toLowerCase()}br.prototype.property={},br.prototype.normal={},br.prototype.space=null;class Cr{constructor(e,n){this.property=e,this.attribute=n}}Cr.prototype.space=null,Cr.prototype.boolean=!1,Cr.prototype.booleanish=!1,Cr.prototype.overloadedBoolean=!1,Cr.prototype.number=!1,Cr.prototype.commaSeparated=!1,Cr.prototype.spaceSeparated=!1,Cr.prototype.commaOrSpaceSeparated=!1,Cr.prototype.mustUseProperty=!1,Cr.prototype.defined=!1;let Sr=0;const wr=jr(),Er=jr(),Ir=jr(),Ar=jr(),Or=jr(),Rr=jr(),Tr=jr();function jr(){return 2**++Sr}var Pr=Object.freeze({__proto__:null,boolean:wr,booleanish:Er,commaOrSpaceSeparated:Tr,commaSeparated:Rr,number:Ar,overloadedBoolean:Ir,spaceSeparated:Or});const Mr=Object.keys(Pr);class Dr extends Cr{constructor(e,n,t,r){let o=-1;if(super(e,n),Fr(this,"space",r),"number"==typeof t)for(;++o<Mr.length;){const e=Mr[o];Fr(this,Mr[o],(t&Pr[e])===Pr[e])}}}function Fr(e,n,t){t&&(e[n]=t)}Dr.prototype.defined=!0;const Nr={}.hasOwnProperty;function Lr(e){const n={},t={};let r;for(r in e.properties)if(Nr.call(e.properties,r)){const o=e.properties[r],i=new Dr(r,e.transform(e.attributes||{},r),o,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(i.mustUseProperty=!0),n[r]=i,t[kr(r)]=r,t[kr(i.attribute)]=r}return new br(n,t,e.space)}const _r=Lr({space:"xlink",transform:(e,n)=>"xlink:"+n.slice(5).toLowerCase(),properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null}}),zr=Lr({space:"xml",transform:(e,n)=>"xml:"+n.slice(3).toLowerCase(),properties:{xmlLang:null,xmlBase:null,xmlSpace:null}});function $r(e,n){return n in e?e[n]:n}function Br(e,n){return $r(e,n.toLowerCase())}const Ur=Lr({space:"xmlns",attributes:{xmlnsxlink:"xmlns:xlink"},transform:Br,properties:{xmlns:null,xmlnsXLink:null}}),Kr=Lr({transform:(e,n)=>"role"===n?n:"aria-"+n.slice(4).toLowerCase(),properties:{ariaActiveDescendant:null,ariaAtomic:Er,ariaAutoComplete:null,ariaBusy:Er,ariaChecked:Er,ariaColCount:Ar,ariaColIndex:Ar,ariaColSpan:Ar,ariaControls:Or,ariaCurrent:null,ariaDescribedBy:Or,ariaDetails:null,ariaDisabled:Er,ariaDropEffect:Or,ariaErrorMessage:null,ariaExpanded:Er,ariaFlowTo:Or,ariaGrabbed:Er,ariaHasPopup:null,ariaHidden:Er,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Or,ariaLevel:Ar,ariaLive:null,ariaModal:Er,ariaMultiLine:Er,ariaMultiSelectable:Er,ariaOrientation:null,ariaOwns:Or,ariaPlaceholder:null,ariaPosInSet:Ar,ariaPressed:Er,ariaReadOnly:Er,ariaRelevant:null,ariaRequired:Er,ariaRoleDescription:Or,ariaRowCount:Ar,ariaRowIndex:Ar,ariaRowSpan:Ar,ariaSelected:Er,ariaSetSize:Ar,ariaSort:null,ariaValueMax:Ar,ariaValueMin:Ar,ariaValueNow:Ar,ariaValueText:null,role:null}}),Hr=Lr({space:"html",attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},transform:Br,mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Rr,acceptCharset:Or,accessKey:Or,action:null,allow:null,allowFullScreen:wr,allowPaymentRequest:wr,allowUserMedia:wr,alt:null,as:null,async:wr,autoCapitalize:null,autoComplete:Or,autoFocus:wr,autoPlay:wr,blocking:Or,capture:null,charSet:null,checked:wr,cite:null,className:Or,cols:Ar,colSpan:null,content:null,contentEditable:Er,controls:wr,controlsList:Or,coords:Ar|Rr,crossOrigin:null,data:null,dateTime:null,decoding:null,default:wr,defer:wr,dir:null,dirName:null,disabled:wr,download:Ir,draggable:Er,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:wr,formTarget:null,headers:Or,height:Ar,hidden:wr,high:Ar,href:null,hrefLang:null,htmlFor:Or,httpEquiv:Or,id:null,imageSizes:null,imageSrcSet:null,inert:wr,inputMode:null,integrity:null,is:null,isMap:wr,itemId:null,itemProp:Or,itemRef:Or,itemScope:wr,itemType:Or,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:wr,low:Ar,manifest:null,max:null,maxLength:Ar,media:null,method:null,min:null,minLength:Ar,multiple:wr,muted:wr,name:null,nonce:null,noModule:wr,noValidate:wr,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:wr,optimum:Ar,pattern:null,ping:Or,placeholder:null,playsInline:wr,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:wr,referrerPolicy:null,rel:Or,required:wr,reversed:wr,rows:Ar,rowSpan:Ar,sandbox:Or,scope:null,scoped:wr,seamless:wr,selected:wr,shadowRootClonable:wr,shadowRootDelegatesFocus:wr,shadowRootMode:null,shape:null,size:Ar,sizes:null,slot:null,span:Ar,spellCheck:Er,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Ar,step:null,style:null,tabIndex:Ar,target:null,title:null,translate:null,type:null,typeMustMatch:wr,useMap:null,value:Er,width:Ar,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Or,axis:null,background:null,bgColor:null,border:Ar,borderColor:null,bottomMargin:Ar,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:wr,declare:wr,event:null,face:null,frame:null,frameBorder:null,hSpace:Ar,leftMargin:Ar,link:null,longDesc:null,lowSrc:null,marginHeight:Ar,marginWidth:Ar,noResize:wr,noHref:wr,noShade:wr,noWrap:wr,object:null,profile:null,prompt:null,rev:null,rightMargin:Ar,rules:null,scheme:null,scrolling:Er,standby:null,summary:null,text:null,topMargin:Ar,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Ar,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:wr,disableRemotePlayback:wr,prefix:null,property:null,results:Ar,security:null,unselectable:null}}),Vr=Lr({space:"svg",attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},transform:$r,properties:{about:Tr,accentHeight:Ar,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Ar,amplitude:Ar,arabicForm:null,ascent:Ar,attributeName:null,attributeType:null,azimuth:Ar,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Ar,by:null,calcMode:null,capHeight:Ar,className:Or,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:Ar,diffuseConstant:Ar,direction:null,display:null,dur:null,divisor:Ar,dominantBaseline:null,download:wr,dx:null,dy:null,edgeMode:null,editable:null,elevation:Ar,enableBackground:null,end:null,event:null,exponent:Ar,externalResourcesRequired:null,fill:null,fillOpacity:Ar,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Rr,g2:Rr,glyphName:Rr,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Ar,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Ar,horizOriginX:Ar,horizOriginY:Ar,id:null,ideographic:Ar,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Ar,k:Ar,k1:Ar,k2:Ar,k3:Ar,k4:Ar,kernelMatrix:Tr,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Ar,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:Ar,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:Ar,overlineThickness:Ar,paintOrder:null,panose1:null,path:null,pathLength:Ar,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Or,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Ar,pointsAtY:Ar,pointsAtZ:Ar,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Tr,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Tr,rev:Tr,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Tr,requiredFeatures:Tr,requiredFonts:Tr,requiredFormats:Tr,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:Ar,specularExponent:Ar,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Ar,strikethroughThickness:Ar,string:null,stroke:null,strokeDashArray:Tr,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Ar,strokeOpacity:Ar,strokeWidth:null,style:null,surfaceScale:Ar,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Tr,tabIndex:Ar,tableValues:null,target:null,targetX:Ar,targetY:Ar,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Tr,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Ar,underlineThickness:Ar,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Ar,values:null,vAlphabetic:Ar,vMathematical:Ar,vectorEffect:null,vHanging:Ar,vIdeographic:Ar,version:null,vertAdvY:Ar,vertOriginX:Ar,vertOriginY:Ar,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Ar,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null}}),qr=/^data[-\w.:]+$/i,Wr=/-[a-z]/g,Jr=/[A-Z]/g;function Gr(e){return"-"+e.toLowerCase()}function Yr(e){return e.charAt(1).toUpperCase()}const Qr={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},Xr=xr([zr,_r,Ur,Kr,Hr],"html"),Zr=xr([zr,_r,Ur,Kr,Vr],"svg");function eo(e){if(e.allowedElements&&e.disallowedElements)throw new TypeError("Only one of `allowedElements` and `disallowedElements` should be defined");if(e.allowedElements||e.disallowedElements||e.allowElement)return n=>{Pt(n,"element",(n,t,r)=>{const o=r;let i;if(e.allowedElements?i=!e.allowedElements.includes(n.tagName):e.disallowedElements&&(i=e.disallowedElements.includes(n.tagName)),!i&&e.allowElement&&"number"==typeof t&&(i=!e.allowElement(n,t,o)),i&&"number"==typeof t)return e.unwrapDisallowed&&n.children?o.children.splice(t,1,...n.children):o.children.splice(t,1),t})}}var no,to={exports:{}},ro={};var oo,io,lo={};
30
- /**
31
- * @license React
32
- * react-is.development.js
33
- *
34
- * Copyright (c) Facebook, Inc. and its affiliates.
35
- *
36
- * This source code is licensed under the MIT license found in the
37
- * LICENSE file in the root directory of this source tree.
38
- */var so=u((io||(io=1,"production"===process.env.NODE_ENV?to.exports=function(){if(no)return ro;no=1;var e,n=Symbol.for("react.element"),t=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),s=Symbol.for("react.context"),a=Symbol.for("react.server_context"),u=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),h=Symbol.for("react.offscreen");function g(e){if("object"==typeof e&&null!==e){var h=e.$$typeof;switch(h){case n:switch(e=e.type){case r:case i:case o:case c:case d:return e;default:switch(e=e&&e.$$typeof){case a:case s:case u:case p:case f:case l:return e;default:return h}}case t:return h}}}return e=Symbol.for("react.module.reference"),ro.ContextConsumer=s,ro.ContextProvider=l,ro.Element=n,ro.ForwardRef=u,ro.Fragment=r,ro.Lazy=p,ro.Memo=f,ro.Portal=t,ro.Profiler=i,ro.StrictMode=o,ro.Suspense=c,ro.SuspenseList=d,ro.isAsyncMode=function(){return!1},ro.isConcurrentMode=function(){return!1},ro.isContextConsumer=function(e){return g(e)===s},ro.isContextProvider=function(e){return g(e)===l},ro.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===n},ro.isForwardRef=function(e){return g(e)===u},ro.isFragment=function(e){return g(e)===r},ro.isLazy=function(e){return g(e)===p},ro.isMemo=function(e){return g(e)===f},ro.isPortal=function(e){return g(e)===t},ro.isProfiler=function(e){return g(e)===i},ro.isStrictMode=function(e){return g(e)===o},ro.isSuspense=function(e){return g(e)===c},ro.isSuspenseList=function(e){return g(e)===d},ro.isValidElementType=function(n){return"string"==typeof n||"function"==typeof n||n===r||n===i||n===o||n===c||n===d||n===h||"object"==typeof n&&null!==n&&(n.$$typeof===p||n.$$typeof===f||n.$$typeof===l||n.$$typeof===s||n.$$typeof===u||n.$$typeof===e||void 0!==n.getModuleId)},ro.typeOf=g,ro}():to.exports=(oo||(oo=1,"production"!==process.env.NODE_ENV&&function(){var e,n=Symbol.for("react.element"),t=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),s=Symbol.for("react.context"),a=Symbol.for("react.server_context"),u=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),h=Symbol.for("react.offscreen");function g(e){if("object"==typeof e&&null!==e){var h=e.$$typeof;switch(h){case n:var g=e.type;switch(g){case r:case i:case o:case c:case d:return g;default:var m=g&&g.$$typeof;switch(m){case a:case s:case u:case p:case f:case l:return m;default:return h}}case t:return h}}}e=Symbol.for("react.module.reference");var m=s,y=l,v=n,b=u,x=r,k=p,C=f,S=t,w=i,E=o,I=c,A=d,O=!1,R=!1;lo.ContextConsumer=m,lo.ContextProvider=y,lo.Element=v,lo.ForwardRef=b,lo.Fragment=x,lo.Lazy=k,lo.Memo=C,lo.Portal=S,lo.Profiler=w,lo.StrictMode=E,lo.Suspense=I,lo.SuspenseList=A,lo.isAsyncMode=function(e){return O||(O=!0,console.warn("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 18+.")),!1},lo.isConcurrentMode=function(e){return R||(R=!0,console.warn("The ReactIs.isConcurrentMode() alias has been deprecated, and will be removed in React 18+.")),!1},lo.isContextConsumer=function(e){return g(e)===s},lo.isContextProvider=function(e){return g(e)===l},lo.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===n},lo.isForwardRef=function(e){return g(e)===u},lo.isFragment=function(e){return g(e)===r},lo.isLazy=function(e){return g(e)===p},lo.isMemo=function(e){return g(e)===f},lo.isPortal=function(e){return g(e)===t},lo.isProfiler=function(e){return g(e)===i},lo.isStrictMode=function(e){return g(e)===o},lo.isSuspense=function(e){return g(e)===c},lo.isSuspenseList=function(e){return g(e)===d},lo.isValidElementType=function(n){return"string"==typeof n||"function"==typeof n||n===r||n===i||n===o||n===c||n===d||n===h||"object"==typeof n&&null!==n&&(n.$$typeof===p||n.$$typeof===f||n.$$typeof===l||n.$$typeof===s||n.$$typeof===u||n.$$typeof===e||void 0!==n.getModuleId)},lo.typeOf=g}()),lo)),to.exports));function ao(e){const n=e&&"object"==typeof e&&"text"===e.type?e.value||"":e;return"string"==typeof n&&""===n.replace(/[ \t\n\f\r]/g,"")}var uo,co,fo,po={exports:{}};var ho=function(){if(fo)return po.exports;fo=1;var e=function(){if(co)return uo;co=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,t=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,l=/^[;\s]*/,s=/^\s+|\s+$/g,a="";function u(e){return e?e.replace(s,a):a}return uo=function(s,c){if("string"!=typeof s)throw new TypeError("First argument must be a string");if(!s)return[];c=c||{};var d=1,f=1;function p(e){var t=e.match(n);t&&(d+=t.length);var r=e.lastIndexOf("\n");f=~r?e.length-r:f+e.length}function h(){var e={line:d,column:f};return function(n){return n.position=new g(e),v(),n}}function g(e){this.start=e,this.end={line:d,column:f},this.source=c.source}function m(e){var n=new Error(c.source+":"+d+":"+f+": "+e);if(n.reason=e,n.filename=c.source,n.line=d,n.column=f,n.source=s,!c.silent)throw n}function y(e){var n=e.exec(s);if(n){var t=n[0];return p(t),s=s.slice(t.length),n}}function v(){y(t)}function b(e){var n;for(e=e||[];n=x();)!1!==n&&e.push(n);return e}function x(){var e=h();if("/"==s.charAt(0)&&"*"==s.charAt(1)){for(var n=2;a!=s.charAt(n)&&("*"!=s.charAt(n)||"/"!=s.charAt(n+1));)++n;if(n+=2,a===s.charAt(n-1))return m("End of comment missing");var t=s.slice(2,n-2);return f+=2,p(t),s=s.slice(n),f+=2,e({type:"comment",comment:t})}}function k(){var n=h(),t=y(r);if(t){if(x(),!y(o))return m("property missing ':'");var s=y(i),c=n({type:"declaration",property:u(t[0].replace(e,a)),value:s?u(s[0].replace(e,a)):a});return y(l),c}}return g.prototype.content=s,v(),function(){var e,n=[];for(b(n);e=k();)!1!==e&&(n.push(e),b(n));return n}()},uo}();function n(n,t){var r,o=null;if(!n||"string"!=typeof n)return o;for(var i,l,s=e(n),a="function"==typeof t,u=0,c=s.length;u<c;u++)i=(r=s[u]).property,l=r.value,a?t(i,l,r):l&&(o||(o={}),o[i]=l);return o}return po.exports=n,po.exports.default=n,po.exports}(),go=u(ho);const mo={}.hasOwnProperty,yo=new Set(["table","thead","tbody","tfoot","tr"]);function vo(e,n){const t=[];let r,o=-1;for(;++o<n.children.length;)r=n.children[o],"element"===r.type?t.push(bo(e,r,o,n)):"text"===r.type?"element"===n.type&&yo.has(n.tagName)&&ao(r)||t.push(r.value):"raw"!==r.type||e.options.skipHtml||t.push(r.value);return t}function bo(e,t,r,o){const i=e.options,l=void 0===i.transformLinkUri?B:i.transformLinkUri,s=e.schema,a=t.tagName,u={};let c,d=s;if("html"===s.space&&"svg"===a&&(d=Zr,e.schema=d),t.properties)for(c in t.properties)mo.call(t.properties,c)&&ko(u,c,t.properties[c],e);"ol"!==a&&"ul"!==a||e.listDepth++;const f=vo(e,t);"ol"!==a&&"ul"!==a||e.listDepth--,e.schema=s;const p=t.position||{start:{line:null,column:null,offset:null},end:{line:null,column:null,offset:null}},h=i.components&&mo.call(i.components,a)?i.components[a]:a,g="string"==typeof h||h===n.Fragment;if(!so.isValidElementType(h))throw new TypeError(`Component for name \`${a}\` not defined or is not renderable`);if(u.key=r,"a"===a&&i.linkTarget&&(u.target="function"==typeof i.linkTarget?i.linkTarget(String(u.href||""),t.children,"string"==typeof u.title?u.title:null):i.linkTarget),"a"===a&&l&&(u.href=l(String(u.href||""),t.children,"string"==typeof u.title?u.title:null)),g||"code"!==a||"element"!==o.type||"pre"===o.tagName||(u.inline=!0),g||"h1"!==a&&"h2"!==a&&"h3"!==a&&"h4"!==a&&"h5"!==a&&"h6"!==a||(u.level=Number.parseInt(a.charAt(1),10)),"img"===a&&i.transformImageUri&&(u.src=i.transformImageUri(String(u.src||""),String(u.alt||""),"string"==typeof u.title?u.title:null)),!g&&"li"===a&&"element"===o.type){const e=function(e){let n=-1;for(;++n<e.children.length;){const t=e.children[n];if("element"===t.type&&"input"===t.tagName)return t}return null}(t);u.checked=e&&e.properties?Boolean(e.properties.checked):null,u.index=xo(o,t),u.ordered="ol"===o.tagName}var m;return g||"ol"!==a&&"ul"!==a||(u.ordered="ol"===a,u.depth=e.listDepth),"td"!==a&&"th"!==a||(u.align&&(u.style||(u.style={}),u.style.textAlign=u.align,delete u.align),g||(u.isHeader="th"===a)),g||"tr"!==a||"element"!==o.type||(u.isHeader=Boolean("thead"===o.tagName)),i.sourcePos&&(u["data-sourcepos"]=[(m=p).start.line,":",m.start.column,"-",m.end.line,":",m.end.column].map(String).join("")),!g&&i.rawSourcePos&&(u.sourcePosition=t.position),!g&&i.includeElementIndex&&(u.index=xo(o,t),u.siblingCount=xo(o)),g||(u.node=t),f.length>0?n.createElement(h,u,f):n.createElement(h,u)}function xo(e,n){let t=-1,r=0;for(;++t<e.children.length&&e.children[t]!==n;)"element"===e.children[t].type&&r++;return r}function ko(e,n,t,r){const o=function(e,n){const t=kr(n);let r=n,o=Cr;if(t in e.normal)return e.property[e.normal[t]];if(t.length>4&&"data"===t.slice(0,4)&&qr.test(n)){if("-"===n.charAt(4)){const e=n.slice(5).replace(Wr,Yr);r="data"+e.charAt(0).toUpperCase()+e.slice(1)}else{const e=n.slice(4);if(!Wr.test(e)){let t=e.replace(Jr,Gr);"-"!==t.charAt(0)&&(t="-"+t),n="data"+t}}o=Dr}return new o(r,n)}(r.schema,n);let i=t;null!=i&&i==i&&(Array.isArray(i)&&(i=o.commaSeparated?function(e){const n={};return(""===e[e.length-1]?[...e,""]:e).join((n.padRight?" ":"")+","+(!1===n.padLeft?"":" ")).trim()}(i):i.join(" ").trim()),"style"===o.property&&"string"==typeof i&&(i=function(e){const n={};try{go(e,t)}catch{}return n;function t(e,t){const r="-ms-"===e.slice(0,4)?`ms-${e.slice(4)}`:e;n[r.replace(/-([a-z])/g,Co)]=t}}(i)),o.space&&o.property?e[mo.call(Qr,o.property)?Qr[o.property]:o.property]=i:o.attribute&&(e[o.attribute]=i))}function Co(e,n){return n.toUpperCase()}const So={}.hasOwnProperty,wo={plugins:{to:"remarkPlugins",id:"change-plugins-to-remarkplugins"},renderers:{to:"components",id:"change-renderers-to-components"},astPlugins:{id:"remove-buggy-html-in-markdown-parser"},allowDangerousHtml:{id:"remove-buggy-html-in-markdown-parser"},escapeHtml:{id:"remove-buggy-html-in-markdown-parser"},source:{to:"children",id:"change-source-to-children"},allowNode:{to:"allowElement",id:"replace-allownode-allowedtypes-and-disallowedtypes"},allowedTypes:{to:"allowedElements",id:"replace-allownode-allowedtypes-and-disallowedtypes"},disallowedTypes:{to:"disallowedElements",id:"replace-allownode-allowedtypes-and-disallowedtypes"},includeNodeIndex:{to:"includeElementIndex",id:"change-includenodeindex-to-includeelementindex"}};function Eo(e){for(const n in wo)if(So.call(wo,n)&&So.call(e,n)){const e=wo[n];console.warn(`[react-markdown] Warning: please ${e.to?`use \`${e.to}\` instead of`:"remove"} \`${n}\` (see <https://github.com/remarkjs/react-markdown/blob/main/changelog.md#${e.id}> for more info)`),delete wo[n]}const t=pe().use(ht).use(e.remarkPlugins||[]).use(Kt,{...e.remarkRehypeOptions,allowDangerousHtml:!0}).use(e.rehypePlugins||[]).use(eo,e),r=new te;"string"==typeof e.children?r.value=e.children:void 0!==e.children&&null!==e.children&&console.warn(`[react-markdown] Warning: please pass a string as \`children\` (not: \`${e.children}\`)`);const o=t.runSync(t.parse(r),r);if("root"!==o.type)throw new TypeError("Expected a `root` node");let i=n.createElement(n.Fragment,{},vo({options:e,schema:Xr,listDepth:0},o));return e.className&&(i=n.createElement("div",{className:e.className},i)),i}function Io({errors:e}){const n=e.map((e,n)=>{var t,r,o;const i="extensions"in e?null===(t=e.extensions)||void 0===t?void 0:t.originalError:{},l=null!==(r=null==i?void 0:i.message)&&void 0!==r?r:e.message,s="extensions"in e?null===(o=e.extensions)||void 0===o?void 0:o.code:null;return y.jsxs("div",{style:{marginTop:0===n?0:10,marginBottom:14},children:[y.jsx(z,{style:{marginBottom:4}}),s&&y.jsxs("div",{style:{fontWeight:"600",marginBottom:4},children:["Copilot Runtime Error:"," ",y.jsx("span",{style:{fontFamily:"monospace",fontWeight:"normal"},children:s})]}),y.jsx(Eo,{children:l})]},n)});return y.jsxs("div",{style:{fontSize:"13px",maxWidth:"600px"},children:[n,y.jsx("div",{style:{fontSize:"11px",opacity:.75},children:"NOTE: This error only displays during local development."})]})}function Ao(e,t){const r=function(){const{addToast:e}=j();return n.useCallback(n=>{const t=n.map(e=>{var n,t;const r="extensions"in e&&(null===(t=null===(n=e.extensions)||void 0===n?void 0:n.originalError)||void 0===t?void 0:t.message)||e.message,o=e.stack||"";return btoa(r+o).slice(0,32)}).join("|");e({type:"error",id:t,message:y.jsx(Io,{errors:n})})},[e])}();return n.useCallback(async(...n)=>{try{return await e(...n)}catch(e){throw console.error("Error in async callback:",e),r([e]),e}},t)}Eo.propTypes={children:vr.string,className:vr.string,allowElement:vr.func,allowedElements:vr.arrayOf(vr.string),disallowedElements:vr.arrayOf(vr.string),unwrapDisallowed:vr.bool,remarkPlugins:vr.arrayOf(vr.oneOfType([vr.object,vr.func,vr.arrayOf(vr.oneOfType([vr.bool,vr.string,vr.object,vr.func,vr.arrayOf(vr.any)]))])),rehypePlugins:vr.arrayOf(vr.oneOfType([vr.object,vr.func,vr.arrayOf(vr.oneOfType([vr.bool,vr.string,vr.object,vr.func,vr.arrayOf(vr.any)]))])),sourcePos:vr.bool,rawSourcePos:vr.bool,skipHtml:vr.bool,includeElementIndex:vr.bool,transformLinkUri:vr.oneOfType([vr.func,vr.bool]),linkTarget:vr.oneOfType([vr.func,vr.string]),transformImageUri:vr.func,components:vr.object};const Oo=new class{constructor(){this.activeKey=null,this.intervalId=null,this.instanceCount=0,this.lastResponse=null}async start(e,n){if(this.instanceCount++,this.activeKey===e)return;this.intervalId&&clearInterval(this.intervalId);const t=async()=>{try{const t=await fetch(`${r.COPILOT_CLOUD_API_URL}/ciu`,{method:"GET",headers:{[r.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]:e}}).then(e=>e.json());return this.lastResponse=t,null==n||n(t),t}catch(e){return null}},o=await t();return this.intervalId=setInterval(t,3e5),this.activeKey=e,o}getLastResponse(){return this.lastResponse}stop(){this.instanceCount--,0===this.instanceCount&&this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,this.activeKey=null,this.lastResponse=null)}};class Ro extends n.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidMount(){this.props.publicApiKey&&Oo.start(this.props.publicApiKey,e=>{this.setState(n=>{var t;return(null==e?void 0:e.severity)!==(null===(t=n.status)||void 0===t?void 0:t.severity)?{status:null!=e?e:void 0}:null})})}componentWillUnmount(){Oo.stop()}componentDidCatch(e,n){console.error("CopilotKit Error:",e,n)}render(){var e,n,t,o;if(this.state.hasError){if(this.state.error instanceof r.CopilotKitError)return y.jsxs(y.Fragment,{children:[this.props.children,this.props.showUsageBanner&&y.jsx(L,{severity:null!==(n=null===(e=this.state.status)||void 0===e?void 0:e.severity)&&void 0!==n?n:this.state.error.severity,message:null!==(o=null===(t=this.state.status)||void 0===t?void 0:t.message)&&void 0!==o?o:this.state.error.message,actions:_(this.state.error)})]});throw this.state.error}return this.props.children}}const To=n.createContext(void 0);function jo({children:e}){const[t,r]=n.useState({}),o=n.useCallback((e,n)=>{r(t=>Object.assign(Object.assign({},t),{[e]:n}))},[]),i=n.useCallback(e=>{r(n=>{const t=Object.assign({},n);return delete t[e],t})},[]),l=n.useRef({});return y.jsx(To.Provider,{value:{coAgentStateRenders:t,setCoAgentStateRender:o,removeCoAgentStateRender:i,claimsRef:l},children:e})}function Po(){const e=n.useContext(To);if(!e)throw new Error("useCoAgentStateRenders must be used within CoAgentStateRendersProvider");return e}const Mo=n.createContext(void 0);function Do({children:e,threadId:t}){const[o,i]=n.useState(()=>r.randomUUID()),l=null!=t?t:o;return y.jsx(Mo.Provider,{value:{threadId:l,setThreadId:i},children:e})}function Fo(){const e=n.useContext(Mo);if(!e)throw new Error("useThreads must be used within ThreadsProvider");return e}var No,Lo;function _o(e){if(!e)return{};const{messages:n,tools:t,copilotkit:r}=e;return a(e,["messages","tools","copilotkit"])}function zo(e,n){if(e&&!n||!e&&n)return!1;const{messages:t,tools:r,copilotkit:o}=e,i=a(e,["messages","tools","copilotkit"]),{messages:l,tools:s,copilotkit:u}=n,c=a(n,["messages","tools","copilotkit"]);return JSON.stringify(i)===JSON.stringify(c)}function $o(e){return!!e&&e.startsWith("coagent-state-render-")}function Bo(e){return"coagent-state-render"===e}function Uo(e){if(!e||"object"!=typeof e)return{snapshot:e,runId:void 0};return{snapshot:"snapshot"in e?e.snapshot:e,runId:"runId"in e?e.runId:void 0}}!function(e){e.InProgress="inProgress",e.Complete="complete"}(No||(No={})),function(e){e.Create="create",e.Override="override",e.Existing="existing",e.Block="block"}(Lo||(Lo={}));const Ko="__lastSnapshotsByStateRenderIdAndRun",Ho="__lastSnapshotsByMessageId";function Vo(e){return e.current}function qo({agentId:e,stateRenderId:t,message:o,messageIndex:i,stateSnapshot:l,agentState:s,agentMessages:a,claimsRef:u}){var c,d,f,p,h,g;const m=Vo(u),y=o.runId,v=null===(c=m[Ho])||void 0===c?void 0:c[o.id],{runId:b}=Uo(v),x=function({existingClaimRunId:e,cachedMessageRunId:n,runId:t}){return e||n||t||"pending"}({existingClaimRunId:null===(d=u.current[o.id])||void 0===d?void 0:d.runId,cachedMessageRunId:b,runId:y});if(n.useEffect(()=>()=>{var e,n,t,r;const i=u.current[o.id];if((null==i?void 0:i.stateSnapshot)&&Object.keys(i.stateSnapshot).length>0){const l=Object.assign({},null!==(e=m[Ko])&&void 0!==e?e:{});l[`${i.stateRenderId}::${null!==(n=i.runId)&&void 0!==n?n:"pending"}`]=i.stateSnapshot,l[`${i.stateRenderId}::latest`]=i.stateSnapshot,m[Ko]=l;const s=Object.assign({},null!==(t=m[Ho])&&void 0!==t?t:{});s[o.id]={snapshot:i.stateSnapshot,runId:null!==(r=i.runId)&&void 0!==r?r:x},m[Ho]=s}delete u.current[o.id]},[u,x,o.id]),!t)return{canRender:!1};const k=function(e){var n,t;const r=Vo(e);return{byStateRenderAndRun:null!==(n=r[Ko])&&void 0!==n?n:{},byMessageId:null!==(t=r[Ho])&&void 0!==t?t:{}}}(u),C=u.current[o.id],{snapshot:S,hasSnapshotKeys:w,allowEmptySnapshot:E,snapshotForClaim:I}=function({messageId:e,messageName:n,allowLiveState:t,skipLatestCache:o,stateRenderId:i,effectiveRunId:l,stateSnapshotProp:s,agentState:a,agentMessages:u,existingClaim:c,caches:d}){var f,p,h,g,m,y;const v=u?null===(f=[...u].reverse().find(e=>"assistant"===e.role))||void 0===f?void 0:f.id:void 0,b=void 0!==i?d.byStateRenderAndRun[`${i}::latest`]:void 0,x=u?u.findIndex(n=>n.id===e):-1,k=x>=0&&u?null===(p=u[x])||void 0===p?void 0:p.role:void 0;let C;if(x>0&&u)for(let e=x-1;e>=0;e-=1)if("user"===(null===(h=u[e])||void 0===h?void 0:h.role)){C=null===(g=u[e])||void 0===g?void 0:g.id;break}const S=void 0===s&&void 0!==b&&void 0!==a&&zo(b,a),w=(Boolean(t)||!v||e===v)&&!S,E=s?r.parseJson(s,s):w?a:void 0,I=!!(E&&Object.keys(E).length>0),A=void 0!==E&&!I&&(void 0!==s||w),O=Uo(d.byMessageId[e]).snapshot,R=void 0!==i?`${i}::${l}`:void 0;let T=null!=O?O:d.byMessageId[e];return void 0===T&&R&&void 0!==d.byStateRenderAndRun[R]&&(T=d.byStateRenderAndRun[R]),void 0===T&&i&&C&&void 0!==d.byStateRenderAndRun[`${i}::pending:${C}`]&&(T=d.byStateRenderAndRun[`${i}::pending:${C}`]),void 0===T&&!o&&i&&"assistant"!==k&&(void 0!==s||a&&Object.keys(a).length>0)&&(T=d.byStateRenderAndRun[`${i}::latest`]),{snapshot:E,hasSnapshotKeys:I,cachedSnapshot:T,allowEmptySnapshot:A,snapshotForClaim:(null==c?void 0:c.locked)?null!==(m=c.stateSnapshot)&&void 0!==m?m:T:I?E:null!==(y=null==c?void 0:c.stateSnapshot)&&void 0!==y?y:T}}({messageId:o.id,messageName:o.name,allowLiveState:Bo(o.name)||$o(o.id),skipLatestCache:Bo(o.name)||$o(o.id),stateRenderId:t,effectiveRunId:x,stateSnapshotProp:l,agentState:s,agentMessages:a,existingClaim:C,caches:k}),A=function({claims:e,context:n,stateSnapshot:t}){const{messageId:o,stateRenderId:i,runId:l,messageIndex:s}=n,a=e[o];if(a){const e=a.stateRenderId===i,n=e&&l&&(!a.runId||"pending"===a.runId);return{canRender:e,action:e?Lo.Existing:Lo.Block,updateRunId:n?l:void 0}}const u=null!=l?l:"pending",c=Object.entries(e).find(([,e])=>{var n;return e.stateRenderId===i&&(null!==(n=e.runId)&&void 0!==n?n:"pending")===u&&r.dataToUUID(_o(e.stateSnapshot))===r.dataToUUID(_o(t))}),d=null==c?void 0:c[1],f=null==c?void 0:c[0];return d?void 0!==s&&void 0!==d.messageIndex&&s>d.messageIndex?{canRender:!0,action:Lo.Override,nextClaim:{stateRenderId:i,runId:l,messageIndex:s},lockOthers:l===d.runId||$o(f)}:l&&d.runId&&l!==d.runId?{canRender:!0,action:Lo.Override,nextClaim:{stateRenderId:i,runId:l,messageIndex:s},lockOthers:$o(f)}:$o(f)?{canRender:!0,action:Lo.Override,nextClaim:{stateRenderId:i,runId:l,messageIndex:s},lockOthers:!0}:t&&d.stateSnapshot&&!zo(d.stateSnapshot,t)?{canRender:!0,action:Lo.Override,nextClaim:{stateRenderId:i,runId:l}}:{canRender:!1,action:Lo.Block}:l?{canRender:!0,action:Lo.Create,nextClaim:{stateRenderId:i,runId:l,messageIndex:s}}:{canRender:!1,action:Lo.Block}}({claims:u.current,context:{messageId:o.id,stateRenderId:t,runId:x,messageIndex:i},stateSnapshot:I});if(A.action===Lo.Block)return{canRender:!1};if(A.updateRunId&&u.current[o.id]&&(u.current[o.id].runId=A.updateRunId),A.nextClaim&&(u.current[o.id]=A.nextClaim),A.lockOthers&&Object.entries(u.current).forEach(([e,n])=>{e!==o.id&&n.stateRenderId===t&&(n.locked=!0)}),C&&!C.locked&&(null==a?void 0:a.length)){const e=a.findIndex(e=>e.id===o.id);e>=0&&e<a.length-1&&(C.locked=!0)}const O=u.current[o.id].stateSnapshot,R=l&&void 0!==O&&!zo(O,S);if(S&&(l||w||E)&&(!u.current[o.id].locked||R)){if(!u.current[o.id].locked||R){u.current[o.id].stateSnapshot=S;const e=Object.assign({},null!==(f=m[Ko])&&void 0!==f?f:{});e[`${t}::${x}`]=S,e[`${t}::latest`]=S,m[Ko]=e;const n=Object.assign({},null!==(p=m[Ho])&&void 0!==p?p:{});n[o.id]={snapshot:S,runId:x},m[Ho]=n,l&&(u.current[o.id].locked=!0)}}else if(I){if(!u.current[o.id].stateSnapshot){u.current[o.id].stateSnapshot=I;const e=Object.assign({},null!==(h=m[Ko])&&void 0!==h?h:{});e[`${t}::${x}`]=I,e[`${t}::latest`]=I,m[Ko]=e;const n=Object.assign({},null!==(g=m[Ho])&&void 0!==g?g:{});n[o.id]={snapshot:I,runId:x},m[Ho]=n}}return{canRender:!0}}function Wo(e){return function(e,o){var i;const{stateSnapshot:l,message:s}=o,{coAgentStateRenders:a,claimsRef:u}=Po(),{agent:c}=t.useAgent({agentId:e}),[d,f]=n.useState(void 0),[,p]=n.useState(0);n.useEffect(()=>{if(!c)return;const e={onStateChanged:()=>{p(e=>e+1)},onStepStartedEvent:({event:e})=>{e.stepName!==d&&f(e.stepName)},onStepFinishedEvent:({event:e})=>{e.stepName===d&&f(void 0)}},{unsubscribe:n}=c.subscribe(e);return()=>{n()}},[e,d]);const h=n.useCallback(n=>Object.entries(a).find(([t,r])=>{if(u.current[n])return t===u.current[n].stateRenderId;const o=r.name===e,i=!r.nodeName||r.nodeName===d;return o&&i}),[a,d,e]),g=n.useMemo(()=>h(s.id),[h,s.id]),m=null==g?void 0:g[0],y=null==g?void 0:g[1],v=Object.assign(Object.assign({},s),{runId:null!==(i=o.runId)&&void 0!==i?i:s.runId}),{canRender:b}=qo({agentId:e,stateRenderId:m,message:v,messageIndex:o.messageIndex,stateSnapshot:l,agentState:null==c?void 0:c.state,agentMessages:null==c?void 0:c.messages,claimsRef:u});return n.useMemo(()=>{var e,n;if(!y||!m)return null;if(!b)return null;if(y.handler&&y.handler({state:l?r.parseJson(l,l):null!==(e=null==c?void 0:c.state)&&void 0!==e?e:{},nodeName:null!=d?d:""}),y.render){const e=(null==c?void 0:c.isRunning)?No.InProgress:No.Complete;return"string"==typeof y.render?y.render:y.render({status:e,state:null!==(n=u.current[s.id].stateSnapshot)&&void 0!==n?n:{},nodeName:null!=d?d:""})}},[y,m,null==c?void 0:c.state,null==c?void 0:c.isRunning,d,s.id,l,b])}(e.agentId,e)}function Jo(){const{copilotkit:e}=t.useCopilotKit(),o=t.useCopilotChatConfiguration(),i=null==o?void 0:o.agentId,{setBannerError:l}=j(),{agent:s}=t.useAgent({agentId:i});return(e=>{const t=n.useRef([]),o=n.useCallback(e=>({onCustomEvent:({event:e})=>{"PredictState"===e.name&&(t.current=e.value)},onToolCallArgsEvent:({partialToolCallArgs:n,toolCallName:o})=>{t.current.forEach(t=>{if((null==t?void 0:t.tool)!==o)return;const i="string"==typeof n?r.parseJson(n,n):n;e.setState({[t.state_key]:i[t.state_key]})})}}),[]);n.useEffect(()=>{if(!e)return;const n=o(e),{unsubscribe:t}=e.subscribe(n);return()=>{t()}},[e,o])})(s),n.useEffect(()=>{const n={onError:({error:e})=>{l(new r.CopilotKitLowLevelError({error:e,message:e.message,url:"undefined"!=typeof window?window.location.href:""}))}},t=e.subscribe(n);return()=>{t.unsubscribe()}},[null==e?void 0:e.subscribe]),null}function Go(){const{copilotkit:e}=t.useCopilotKit(),{onError:r,copilotApiConfig:o}=x();return n.useEffect(()=>{if(!e)return;const n=e.subscribe({onError:async e=>{const n={type:"error",timestamp:Date.now(),context:Object.assign({source:"agent",request:{operation:e.code||"unknown",url:null==o?void 0:o.chatApiEndpoint,startTime:Date.now()},technical:{environment:"browser",userAgent:"undefined"!=typeof navigator?navigator.userAgent:void 0,stackTrace:e.error.stack}},e.context),error:e.error};try{await r(n)}catch(e){console.error("Error in onError handler:",e)}}});return()=>{n.unsubscribe()}},[e,r,o]),null}function Yo(e){var i;const{children:l}=e,s=a(e,["children"]);!function(e){const n=Object.keys(e).filter(e=>e.endsWith("_c")),t=e.publicApiKey||e.publicLicenseKey;if(!e.runtimeUrl&&!t)throw new r.ConfigurationError("Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'");if(n.length>0&&!t)throw new r.MissingPublicApiKeyError(`Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${n.map(Xo).join(", ")}`)}(e);const u=s.publicLicenseKey||s.publicApiKey,c=s.runtimeUrl||r.COPILOT_CLOUD_CHAT_URL,[d,f]=n.useState({}),[p,h]=n.useState(new Map),g=n.useRef({actions:{},coAgentStateRenders:{}}),{addElement:m,removeElement:v,printTree:x,getAllElements:k}=(()=>{const[e,t]=n.useReducer(I,[]),o=n.useCallback((e,n,o)=>{const i=r.randomId();return t({type:"ADD_NODE",value:e,parentId:o,id:i,categories:n}),i},[]),i=n.useCallback(e=>{t({type:"REMOVE_NODE",id:e})},[]),l=n.useCallback(()=>e,[e]),s=n.useCallback(n=>{const t=new Set(n);let r="";return e.forEach((e,n)=>{(function(e,n){const[t,r]=e.size<=n.size?[e,n]:[n,e];for(let e of t)if(r.has(e))return!0;return!1})(t,e.categories)&&(0!==n&&(r+="\n"),r+=E(e,`${w(n,0)}. `))}),r},[e]);return{tree:e,addElement:o,printTree:s,removeElement:i,getAllElements:l}})(),[C,S]=n.useState(!1),[O,R]=n.useState(""),[T,j]=n.useState({}),[P,D]=n.useState({}),[z,$]=n.useState([]),{addElement:B,removeElement:U,allElements:K}=(()=>{const[e,t]=n.useReducer(A,new Map),o=n.useCallback((e,n)=>{const o=r.randomId();return t({type:"ADD_ELEMENT",value:e,id:o,categories:n}),o},[]),i=n.useCallback(e=>{t({type:"REMOVE_ELEMENT",id:e})},[]),l=n.useCallback(n=>{const t=new Set(n),r=[];return e.forEach(e=>{(function(e,n){const[t,r]=e.size<=n.size?[e,n]:[n,e];for(let e of t)if(r.has(e))return!0;return!1})(t,e.categories)&&r.push(e.value)}),r},[e]);return{addElement:o,removeElement:i,allElements:l}})(),H=n.useCallback((e,n)=>{f(t=>Object.assign(Object.assign({},t),{[e]:n}))},[]),V=n.useCallback(e=>{f(n=>{const t=Object.assign({},n);return delete t[e],t})},[]),q=n.useCallback((e,n)=>`${e.map(e=>`${e.name} (${e.sourceApplication}):\n${e.getContents()}`).join("\n\n")}\n\n${x(n)}`,[x]),W=n.useCallback((e,n,t=Qo)=>m(e,t,n),[m]),J=n.useCallback(e=>{v(e)},[v]),G=n.useCallback(()=>k(),[k]),Y=n.useCallback(e=>function(e){return async({name:n,args:t})=>{let r={};for(let n of e)r[n.name]=n;const i=r[n];let l;return i&&(await new Promise((e,n)=>{o.flushSync(async()=>{var r;try{l=await(null===(r=i.handler)||void 0===r?void 0:r.call(i,t)),e()}catch(e){n(e)}})}),await new Promise(e=>setTimeout(e,20))),l}}(Object.values(e||d)),[d]),Q=n.useCallback(e=>K(e),[K]),X=n.useCallback((e,n=Qo)=>B(e,n),[B]),Z=n.useCallback(e=>{U(e)},[U]),ee=n.useMemo(()=>{var e,n;let t;return u&&(t={guardrails:{input:{restrictToTopic:{enabled:Boolean(s.guardrails_c),validTopics:(null===(e=s.guardrails_c)||void 0===e?void 0:e.validTopics)||[],invalidTopics:(null===(n=s.guardrails_c)||void 0===n?void 0:n.invalidTopics)||[]}}}}),Object.assign(Object.assign({publicApiKey:u},t?{cloud:t}:{}),{chatApiEndpoint:c,headers:s.headers||{},properties:s.properties||{},transcribeAudioUrl:s.transcribeAudioUrl,textToSpeechUrl:s.textToSpeechUrl,credentials:s.credentials})},[u,s.headers,s.properties,s.transcribeAudioUrl,s.textToSpeechUrl,s.credentials,s.cloudRestrictToTopic,s.guardrails_c]);n.useMemo(()=>{const e=Object.values(T||{}).reduce((e,n)=>"authenticated"===n.status&&n.authHeaders?Object.assign(Object.assign({},e),Object.entries(n.authHeaders).reduce((e,[n,t])=>Object.assign(Object.assign({},e),{[n.startsWith("X-Custom-")?n:`X-Custom-${n}`]:t}),{})):e,{});return Object.assign(Object.assign(Object.assign({},ee.headers||{}),ee.publicApiKey?{[r.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]:ee.publicApiKey}:{}),e)},[ee.headers,ee.publicApiKey,T]);const[ne,te]=n.useState({}),re=n.useCallback(e=>{te(n=>Object.assign(Object.assign({},n),e))},[]),oe=n.useCallback(e=>{te(n=>{const t=n,r=e;t[r];return a(t,["symbol"==typeof r?r:r+""])})},[]),ie=n.useRef(s.onError);n.useEffect(()=>{ie.current=s.onError},[s.onError]);const le=n.useRef({});n.useEffect(()=>{le.current=ne},[ne]);const se=n.useCallback(async e=>{if(ee.publicApiKey&&ie.current)try{await ie.current(e)}catch(e){console.error("Error in public onError handler:",e)}const n=Object.values(le.current);await Promise.all(n.map(n=>Promise.resolve(n(e)).catch(e=>console.error("Error in internal error handler:",e))))},[ee.publicApiKey]),[ae,ue]=n.useState({}),ce=n.useCallback((e,n)=>{ue(t=>Object.assign(Object.assign({},t),{[e]:n}))},[ue]),de=n.useCallback(e=>{ue(n=>{const t=n,r=e;t[r];return a(t,["symbol"==typeof r?r:r+""])})},[ue]),[fe,pe]=n.useState([]),[he,ge]=n.useState({}),me=n.useRef({}),ye=n.useCallback(e=>{const n="function"==typeof e?e(me.current):e;me.current=n,ge(e=>n)},[]);let ve=null;s.agent&&(ve={agentName:s.agent});const[be,xe]=n.useState(ve);n.useEffect(()=>{s.agent?xe({agentName:s.agent}):xe(null)},[s.agent]);const{threadId:ke,setThreadId:Ce}=Fo(),Se=n.useCallback(e=>{if(s.threadId)throw new Error("Cannot call setThreadId() when threadId is provided via props.");Ce(e)},[s.threadId]),[we,Ee]=n.useState(null),Ie=n.useRef(null),Ae=M(s.showDevConsole),[Oe,Re]=n.useState({}),Te=n.useCallback(e=>{Re(n=>{var t;return null!=e&&e.id?Object.assign(Object.assign({},n),{[e.id]:Object.assign(Object.assign({},null!==(t=n[e.id])&&void 0!==t?t:{}),e)}):n})},[]),je=n.useCallback(e=>{Re(n=>{const t=n,r=e;t[r];return a(t,["symbol"==typeof r?r:r+""])})},[]),[Pe,Me]=n.useState({}),De=n.useCallback(e=>{Me(n=>{const t=n[e.threadId]||[];return Object.assign(Object.assign({},n),{[e.threadId]:[...t,e]})})},[]),Fe=n.useCallback((e,n,t)=>{Me(r=>{const o=r[e]||[];return Object.assign(Object.assign({},r),{[e]:o.map(e=>e.eventId===n?Object.assign(Object.assign({},e),{event:Object.assign(Object.assign({},e.event),{response:t})}):e)})})},[]),Ne=n.useMemo(()=>l,[l]),[Le,_e]=n.useState(null),ze=n.useMemo(()=>{var e;return null!==(e=s.agent)&&void 0!==e?e:null},[s.agent]),$e=n.useMemo(()=>{var e;return null!==(e=s.forwardedParameters)&&void 0!==e?e:{}},[s.forwardedParameters]),Be=n.useCallback(e=>{D(n=>{const t="function"==typeof e?e(n):e;return Object.keys(t).length===Object.keys(n).length&&Object.entries(t).every(([e,t])=>n[e]===t)?n:t})},[D]),Ue=n.useCallback(e=>{j(n=>{const t="function"==typeof e?e(n):e;return Object.keys(t).length===Object.keys(n).length&&Object.entries(t).every(([e,t])=>n[e]===t)?n:t})},[j]),Ke=n.useCallback(e=>{const n=e.action.name||r.randomUUID();return h(t=>{const r=new Map(t);return r.set(n,e),r}),n},[]),He=n.useCallback(e=>{h(n=>{const t=new Map(n);return t.delete(e),t})},[]),Ve=n.useMemo(()=>()=>y.jsx(y.Fragment,{children:Array.from(p.entries()).map(([e,n])=>{const t=n.component;return y.jsx(t,{action:n.action},e)})}),[p]);return y.jsx(t.CopilotChatConfigurationProvider,{agentId:null!==(i=s.agent)&&void 0!==i?i:"default",threadId:ke,children:y.jsxs(b.Provider,{value:{actions:d,chatComponentsCache:g,getFunctionCallHandler:Y,setAction:H,removeAction:V,setRegisteredActions:Ke,removeRegisteredAction:He,getContextString:q,addContext:W,removeContext:J,getAllContext:G,getDocumentsContext:Q,addDocumentContext:X,removeDocumentContext:Z,copilotApiConfig:ee,isLoading:C,setIsLoading:S,chatSuggestionConfiguration:ae,addChatSuggestionConfiguration:ce,removeChatSuggestionConfiguration:de,chatInstructions:O,setChatInstructions:R,additionalInstructions:z,setAdditionalInstructions:$,showDevConsole:Ae,coagentStates:he,setCoagentStates:ge,coagentStatesRef:me,setCoagentStatesWithRef:ye,agentSession:be,setAgentSession:xe,forwardedParameters:$e,agentLock:ze,threadId:ke,setThreadId:Se,runId:we,setRunId:Ee,chatAbortControllerRef:Ie,availableAgents:fe,authConfig_c:s.authConfig_c,authStates_c:T,setAuthStates_c:Ue,extensions:P,setExtensions:Be,interruptActions:Oe,setInterruptAction:Te,removeInterruptAction:je,interruptEventQueue:Pe,addInterruptEvent:De,resolveInterruptEvent:Fe,bannerError:Le,setBannerError:_e,onError:se,internalErrorHandlers:ne,setInternalErrorHandler:re,removeInternalErrorHandler:oe},children:[y.jsx(Jo,{}),y.jsx(Go,{}),y.jsxs(jo,{children:[y.jsx(F,{children:y.jsxs(N,{children:[Ne,y.jsx(Ve,{})]})}),Le&&Ae&&y.jsx(L,{severity:Le.severity,message:Le.message,onClose:()=>_e(null),actions:_(Le)})]})]})})}const Qo=["global"];function Xo(e){return e.replace(/_c$/,"").split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}function Zo(e){const{agent:r}=t.useAgent({agentId:e}),o=n.useRef("start");return n.useEffect(()=>{if(!r)return;const e={onStepStartedEvent:({event:e})=>{o.current=e.stepName},onRunStartedEvent:()=>{o.current="start"},onRunFinishedEvent:()=>{o.current="end"}},n=r.subscribe(e);return()=>{n.unsubscribe()}},[r]),o.current}const ei=({event:e,result:n,render:t,resolve:r})=>t({event:e,result:n,resolve:r});function ni(e){var o;const{interruptActions:l,agentSession:s,threadId:a,interruptEventQueue:u,addInterruptEvent:c,resolveInterruptEvent:d}=x(),f=t.useCopilotChatConfiguration(),p=Zo(null!==(o=null==f?void 0:f.agentId)&&void 0!==o?o:"default");n.useEffect(()=>{if(!e)return;let n=null;const t={onCustomEvent:({event:e})=>{if("on_interrupt"===e.name){const t={name:i.MetaEventName.LangGraphInterruptEvent,type:e.type,value:r.parseJson(e.value,e.value)},o=r.dataToUUID(t,"interruptEvents");n={eventId:o,threadId:a,event:t}}},onRunStartedEvent:()=>{n=null},onRunFinalized:()=>{n&&(c(n),n=null)}},{unsubscribe:o}=e.subscribe(t);return()=>{o()}},[e,a]);const h=n.useCallback((n,t)=>{null==e||e.runAgent({forwardedProps:{command:{resume:t}}}),d(a,n,null!=t?t:"")},[e,a]);return n.useMemo(()=>{const e=(u[a]||[]).find(e=>!e.event.response);if(!e||!s)return null;const t=Object.values(l).find(n=>!n.enabled||n.enabled({eventValue:e.event.value,agentMetadata:Object.assign(Object.assign({},s),{nodeName:p})}));if(!t)return null;const{render:r,handler:o}=t,i=n=>{h(e.eventId,n)};let c=null;return o&&(c=o({event:e.event,resolve:i})),r?n.createElement(ei,{event:e.event,result:c,render:r,resolve:i}):null},[l,u,a,s,h])}function ti(){const e=t.useRenderToolCall();return n.useCallback((n,t)=>{var r;if(!(null===(r=null==n?void 0:n.toolCalls)||void 0===r?void 0:r.length))return null;const o=n.toolCalls[0];if(!o)return null;const i=null==t?void 0:t.find(e=>"tool"===e.role&&e.toolCallId===o.id);return()=>e({toolCall:o,toolMessage:i})},[e])}function ri({suggestions:e,onInProgress:r,onSubmitMessage:o,onStopGeneration:s,onReloadMessages:a}={}){var u,c,d;const{copilotkit:f}=t.useCopilotKit(),{threadId:p,agentSession:h}=x(),g=t.useCopilotChatConfiguration(),[m,y]=n.useState(!1),v=null!==(u=null==g?void 0:g.agentId)&&void 0!==u?u:"default",{agent:b}=t.useAgent({agentId:v});n.useEffect(()=>(b&&(null==g?void 0:g.threadId)&&b.threadId!==g.threadId&&(b.threadId=g.threadId,(async e=>{y(!1);try{await f.connectAgent({agent:e}),y(!0)}catch(e){e instanceof l.AGUIConnectNotImplementedError||console.error("CopilotChat: connectAgent failed",e)}})(b)),()=>{}),[null==g?void 0:g.threadId,b,f,v]),n.useEffect(()=>{null==r||r(Boolean(null==b?void 0:b.isRunning))},[null==b?void 0:b.isRunning,r]);const k=ni(b),C=n.useCallback(e=>{var n;const t=(null!==(n=null==b?void 0:b.messages)&&void 0!==n?n:[]).filter(n=>n.id!==e);null==b||b.setMessages(t)},[null==b?void 0:b.setMessages,null==b?void 0:b.messages]),S=oi(C),w=n.useCallback(e=>S.current(e),[S]),E=t.useSuggestions({agentId:v}),I=Ao(async e=>{var n;if(!b)return;const t=null!==(n=null==b?void 0:b.messages)&&void 0!==n?n:[];if(b.isRunning||0===t.length)return;const r=t.findIndex(n=>n.id===e);if(-1===r)return void console.warn(`Message with id ${e} not found`);const o=t[r].role;if("assistant"!==o)return void console.warn(`Regenerate cannot be performed on ${o} role`);let i=[t[0]];if(t.length>2&&0!==r){const e=t.slice(0,r).reverse().find(e=>"user"===e.role);if(e){const n=t.findIndex(n=>n.id===e.id);i=t.slice(0,n+1)}else i=[t[0]]}else t.length>2&&0===r&&(i=[t[0],t[1]]);if(null==b||b.setMessages(i),b)try{await f.runAgent({agent:b})}catch(e){console.error("CopilotChat: runAgent failed during reload",e)}},[null==b?void 0:b.messages.length,null==b?void 0:b.isRunning,null==b?void 0:b.setMessages,null==f?void 0:f.runAgent]),A=Ao(async(e,n)=>{var t;if(!b)return;const r=null===(t=null==n?void 0:n.followUp)||void 0===t||t;if((null==n?void 0:n.clearSuggestions)&&f.clearSuggestions(v),o){const n="string"==typeof e.content?e.content:e.content&&"text"in e.content?e.content.text:e.content&&"filename"in e.content?e.content.filename:"";try{await o(n)}catch(e){console.error("Error in onSubmitMessage:",e)}}if(null==b||b.addMessage(e),r)try{await f.runAgent({agent:b})}catch(e){console.error("CopilotChat: runAgent failed",e)}},[b,f,v,o]),O=Ao(async(e,n)=>A(i.gqlToAGUI([e])[0],n),[A]),R=n.useCallback(e=>{var n,t;return e.every(e=>e instanceof i.Message)?null===(n=null==b?void 0:b.setMessages)||void 0===n?void 0:n.call(b,i.gqlToAGUI(e)):null===(t=null==b?void 0:b.setMessages)||void 0===t?void 0:t.call(b,e)},[null==b?void 0:b.setMessages,b]),T=oi(I),j=Ao(async e=>{var n;return null==a||a({messageId:e,currentAgentName:null==b?void 0:b.agentId,messages:null!==(n=null==b?void 0:b.messages)&&void 0!==n?n:[]}),await T.current(e)},[T,b,a]),P=n.useCallback(()=>{var e,n;return null==s||s({currentAgentName:null==b?void 0:b.agentId,messages:null!==(e=null==b?void 0:b.messages)&&void 0!==e?e:[]}),null===(n=null==b?void 0:b.abortRun)||void 0===n?void 0:n.call(b)},[s,b]),M=oi(()=>{null==b||b.setMessages([]),null==b||b.setState(null)}),D=n.useCallback(()=>M.current(),[M]),F=ti(),N=t.useRenderCustomMessages(),L=function({copilotkit:e,agent:t,agentId:r,threadId:o}){return n.useMemo(()=>e&&t?({message:i,position:l})=>{var s;const a=null!==(s=null!=o?o:t.threadId)&&void 0!==s?s:"default",u=i.runId,c=u||e.getRunIdForMessage(r,a,i.id)||`pending:${i.id}`,d=Math.max(t.messages.findIndex(e=>e.id===i.id),0),f={message:i,position:l,runId:c,messageIndex:d,messageIndexInRun:0,numberOfMessagesInRun:1,agentId:r,stateSnapshot:i.state};return n.createElement(Wo,f)}:null,[t,r,e,o])}({copilotkit:f,agent:b,agentId:v,threadId:null!==(c=null==g?void 0:g.threadId)&&void 0!==c?c:p}),_=null!==(d=null==b?void 0:b.messages)&&void 0!==d?d:[],z=n.useMemo(()=>{var e,n;let t=_.map(e=>{if("assistant"!==e.role)return e;const n=F(e,_);if(n){const t=n();if(t)return Object.assign(Object.assign({},e),{generativeUI:()=>t})}const t=L||N?()=>{var n;if(L)return L({message:e,position:"before"});try{return null!==(n=null==N?void 0:N({message:e,position:"before"}))&&void 0!==n?n:null}catch(e){return console.warn("[CopilotKit] renderCustomMessages failed, falling back to legacy renderer",e),null}}:null;return t?Object.assign(Object.assign({},e),{generativeUI:t,generativeUIPosition:"before"}):e});const r=t.some(e=>"assistant"===e.role),o=Boolean(N&&(null===(e=null==f?void 0:f.getAgent)||void 0===e?void 0:e.call(f,v))),i=L||(o?N:null),l=Boolean(null==b?void 0:b.isRunning)||Boolean((null==b?void 0:b.state)&&Object.keys(b.state).length),s=null!==(n=null!=p?p:null==b?void 0:b.threadId)&&void 0!==n?n:"default";let a=-1;for(let e=t.length-1;e>=0;e-=1)if("user"===t[e].role){a=e;break}const u=a>=0?t[a].id:void 0,c=u?f.getRunIdForMessage(v,s,u)||`pending:${u}`:void 0,d=a>=0?t.slice(a+1).some(e=>"assistant"===e.role):r;if(i&&l&&!d){const e={id:c?`coagent-state-render-${v}-${c}`:`coagent-state-render-${v}`,role:"assistant",content:"",name:"coagent-state-render",runId:c};t=[...t,Object.assign(Object.assign({},e),{generativeUIPosition:"before",generativeUI:()=>i({message:e,position:"before"})})]}return t},[null==b?void 0:b.messages,F,_,N,L,v,f,null==b?void 0:b.isRunning,null==b?void 0:b.state]),$=n.useMemo(()=>Array.isArray(e)?{suggestions:e.map(e=>Object.assign(Object.assign({},e),{isLoading:!1})),isLoading:!1}:E,[e,E]);return{messages:z,sendMessage:A,appendMessage:O,setMessages:R,reloadMessages:j,stopGeneration:P,reset:D,deleteMessage:w,isAvailable:m,isLoading:Boolean(null==b?void 0:b.isRunning),suggestions:$.suggestions,setSuggestions:e=>f.addSuggestionsConfig({suggestions:e}),generateSuggestions:async()=>f.reloadSuggestions(v),resetSuggestions:()=>f.clearSuggestions(v),isLoadingSuggestions:$.isLoading,interrupt:k,agent:b,threadId:p}}function oi(e){const t=n.useRef(e);return n.useEffect(()=>{t.current=e},[e]),t}function ii(e,o){const{name:i,description:l,parameters:s,render:a,followUp:u}=e,c=r.getZodParameters(s),d=n.useRef(a);n.useEffect(()=>{d.current=a},[a,...null!=o?o:[]]);const f=n.useMemo(()=>{if(void 0!==a)return e=>{const t=d.current;if(void 0===t)return null;if("string"==typeof t)return n.createElement(n.Fragment,null,t);const o=t(Object.assign(Object.assign({},e),{result:"string"==typeof e.result?r.parseJson(e.result,e.result):e.result}));return"string"==typeof o?n.createElement(n.Fragment,null,o):null!=o?o:null}},[]),p=n.useRef(e.handler);n.useEffect(()=>{p.current=e.handler},[e.handler,...null!=o?o:[]]);const h=e.handler?e=>{var n;return null===(n=p.current)||void 0===n?void 0:n.call(p,e)}:void 0;t.useFrontendTool({name:i,description:l,parameters:c,handler:h,followUp:u,render:f})}function li(e,o){const{copilotkit:i}=t.useCopilotKit(),l=n.useRef(!1);n.useEffect(()=>{const{name:n,parameters:o,render:s}=e,a=r.getZodParameters(o),u="*"===n?t.defineToolCallRenderer({name:"*",render:e=>s(Object.assign(Object.assign({},e),{result:e.result?r.parseJson(e.result,e.result):e.result}))}):t.defineToolCallRenderer({name:n,args:a,render:e=>s(Object.assign(Object.assign({},e),{result:e.result?r.parseJson(e.result,e.result):e.result}))}),c=i.renderToolCalls.findIndex(e=>e.name===n);return-1!==c&&i.renderToolCalls.splice(c,1),i.renderToolCalls.push(u),l.current=!0,()=>{if(l.current){const e=i.renderToolCalls.findIndex(e=>e.name===n);-1!==e&&i.renderToolCalls.splice(e,1),l.current=!1}}},[e,...null!=o?o:[]])}function si(e,o){const{render:i}=e,l=a(e,["render"]),{name:u,description:c,parameters:d,followUp:f}=l,p=r.getZodParameters(d),h=n.useRef(null);n.useEffect(()=>{h.current=e=>{if("string"==typeof i)return n.createElement(n.Fragment,null,i);if(!i)return null;const t=(()=>{const n=e.args;switch(e.status){case s.ToolCallStatus.InProgress:return{args:n,respond:e.respond,status:e.status,handler:void 0};case s.ToolCallStatus.Executing:return{args:n,respond:e.respond,status:e.status,handler:()=>{}};case s.ToolCallStatus.Complete:return{args:n,respond:e.respond,status:e.status,result:e.result?r.parseJson(e.result,e.result):e.result,handler:void 0};default:throw new r.CopilotKitError({code:r.CopilotKitErrorCode.UNKNOWN,message:`Invalid tool call status: ${e.status}`})}})(),o=i(t);return"string"==typeof o?n.createElement(n.Fragment,null,o):null!=o?o:null}},[i,...null!=o?o:[]]),t.useHumanInTheLoop({name:u,description:c,followUp:f,parameters:p,render:e=>{var n,t;return null!==(t=null===(n=h.current)||void 0===n?void 0:n.call(h,e))&&void 0!==t?t:null}})}function ai(e){if("*"===e.name)return{type:"render",action:e};if("renderAndWaitForResponse"in e||"renderAndWait"in e){let n=e.render;return!n&&"renderAndWaitForResponse"in e&&(n=e.renderAndWaitForResponse),!n&&"renderAndWait"in e&&(n=e.renderAndWait),{type:"hitl",action:Object.assign(Object.assign({},e),{render:n})}}if("available"in e){if("enabled"===e.available||"remote"===e.available)return{type:"frontend",action:e};if("frontend"===e.available||"disabled"===e.available)return{type:"render",action:e}}if("handler"in e)return{type:"frontend",action:e};throw new Error("Invalid action configuration")}function ui(e,t){const[r]=n.useState(ai(e)),o=ai(e);if(r.type!==o.type)throw new Error("Action configuration changed between renders");switch(o.type){case"render":return li(o.action,t);case"hitl":return si(o.action,t);case"frontend":return ii(o.action,t);default:throw new Error("Invalid action configuration")}}const ci=e=>"state"in e&&"setState"in e;function di(e){return e.filter(e=>e.available!==i.ActionInputAvailability.Disabled&&!0!==e.disabled&&"*"!==e.name&&"frontend"!=e.available&&!e.pairedAction).map(e=>{let n=i.ActionInputAvailability.Enabled;return e.disabled||"disabled"===e.available?n=i.ActionInputAvailability.Disabled:"remote"===e.available&&(n=i.ActionInputAvailability.Remote),{name:e.name,description:e.description||"",jsonSchema:JSON.stringify(r.actionParametersToJsonSchema(e.parameters||[])),available:n}})}function fi(e,n){return`\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\`\`\`\n${e}\n\`\`\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\`\`\`\n${n}\n\`\`\`\n`}e.CoAgentStateRendersContext=To,e.CoAgentStateRendersProvider=jo,e.CopilotContext=b,e.CopilotKit=function(e){var{children:r}=e,o=a(e,["children"]);const i=M(o.showDevConsole),l=M(o.enableInspector),s=o.publicApiKey||o.publicLicenseKey,u=n.useMemo(()=>[{render:Wo}],[]);return y.jsx(P,{enabled:i,children:y.jsx(Ro,{publicApiKey:s,showUsageBanner:i,children:y.jsx(Do,{threadId:o.threadId,children:y.jsx(t.CopilotKitProvider,Object.assign({},o,{showDevConsole:l,renderCustomMessages:u,useSingleEndpoint:!0,children:y.jsx(Yo,Object.assign({},o,{children:r}))}))})})})},e.CopilotMessagesContext=R,e.CopilotTask=class{constructor(e){this.instructions=e.instructions,this.actions=e.actions||[],this.includeCopilotReadable=!1!==e.includeCopilotReadable,this.includeCopilotActions=!1!==e.includeCopilotActions,this.forwardedParameters=e.forwardedParameters}async run(e,n){var t,r,o;const l=this.includeCopilotActions?Object.assign({},e.actions):{};for(const e of this.actions)l[e.name]=e;let s="";n&&(s=("string"==typeof n?n:JSON.stringify(n))+"\n\n"),this.includeCopilotReadable&&(s+=e.getContextString([],Qo));const a=[new i.TextMessage({content:fi(s,this.instructions),role:i.Role.System})],u=new i.CopilotRuntimeClient({url:e.copilotApiConfig.chatApiEndpoint,publicApiKey:e.copilotApiConfig.publicApiKey,headers:e.copilotApiConfig.headers,credentials:e.copilotApiConfig.credentials}),c=await u.generateCopilotResponse({data:{frontend:{actions:di(Object.values(l)),url:window.location.href},messages:i.convertMessagesToGqlInput(i.filterAgentStateMessages(a)),metadata:{requestType:i.CopilotRequestType.Task},forwardedParameters:Object.assign({toolChoice:"required"},null!==(t=this.forwardedParameters)&&void 0!==t?t:{})},properties:e.copilotApiConfig.properties}).toPromise(),d=e.getFunctionCallHandler(l),f=i.convertGqlOutputToMessages((null===(o=null===(r=c.data)||void 0===r?void 0:r.generateCopilotResponse)||void 0===o?void 0:o.messages)||[]).filter(e=>e.isActionExecutionMessage());for(const e of f)await d({messages:a,name:e.name,args:e.arguments})}},e.SUGGESTION_RETRY_CONFIG={MAX_RETRIES:3,COOLDOWN_MS:5e3},e.ThreadsContext=Mo,e.ThreadsProvider=Do,e.defaultCopilotContextCategories=Qo,e.shouldShowDevConsole=M,e.useCoAgent=function(e){const{agent:r}=t.useAgent({agentId:e.name}),{copilotkit:o}=t.useCopilotKit(),i=Zo(e.name),l=n.useCallback(e=>{if(r)if("function"==typeof e){const n=e;r.setState(n(r.state))}else r.setState(Object.assign(Object.assign({},r.state),e))},[null==r?void 0:r.state,null==r?void 0:r.setState]);n.useEffect(()=>{var n;if(!e.config&&!e.configurable)return;let t=null!==(n=e.config)&&void 0!==n?n:{};e.configurable&&(t=Object.assign(Object.assign({},t),{configurable:Object.assign(Object.assign({},e.configurable),t.configurable)})),o.setProperties(t)},[e.config,e.configurable]);const s=n.useMemo(()=>ci(e)?JSON.stringify(e.state):void 0,[ci(e)?JSON.stringify(e.state):void 0]);n.useEffect(()=>{(null==r?void 0:r.state)&&ci(e)&&JSON.stringify(e.state)!==JSON.stringify(r.state)&&l(e.state)},[r,s,l]);const a=n.useCallback(e=>Boolean(e&&Object.keys(e).length),[]),u=n.useRef(ci(e)?e.state:"initialState"in e?e.initialState:void 0);return n.useEffect(()=>{ci(e)?u.current=e.state:"initialState"in e&&(u.current=e.initialState)},[ci(e)?JSON.stringify(e.state):"initialState"in e?JSON.stringify(e.initialState):void 0]),n.useEffect(()=>{if(!r)return;const n={onStateChanged:n=>{ci(e)&&e.setState(n.state)},onRunInitialized:e=>{a(e.state)?l(e.state):a(r.state)||void 0!==u.current&&l(u.current)}},t=r.subscribe(n);return()=>{t.unsubscribe()}},[r,l,a]),n.useMemo(()=>{var n,t,o;if(!r){const r=()=>{},o=async()=>{},l=null!==(t=null!==(n="state"in e&&e.state)&&void 0!==n?n:"initialState"in e&&e.initialState)&&void 0!==t?t:{};return{name:e.name,nodeName:i,threadId:void 0,running:!1,state:l,setState:r,start:r,stop:r,run:o}}return{name:null!==(o=null==r?void 0:r.agentId)&&void 0!==o?o:e.name,nodeName:i,threadId:r.threadId,running:r.isRunning,state:r.state,setState:l,start:r.runAgent,stop:r.abortRun,run:r.runAgent}},[null==r?void 0:r.state,null==r?void 0:r.runAgent,null==r?void 0:r.abortRun,null==r?void 0:r.runAgent,null==r?void 0:r.threadId,null==r?void 0:r.isRunning,null==r?void 0:r.agentId,l,e.name])},e.useCoAgentStateRender=function(e,t){const{chatComponentsCache:o,availableAgents:i}=n.useContext(b),{setCoAgentStateRender:l,removeCoAgentStateRender:s,coAgentStateRenders:a}=Po(),u=n.useRef(r.randomId()),{setBannerError:c,addToast:d}=j();n.useEffect(()=>{if((null==i?void 0:i.length)&&!i.some(n=>n.name===e.name)){e.name;const n=new r.CopilotKitAgentDiscoveryError({agentName:e.name,availableAgents:i.map(e=>({name:e.name,id:e.id}))});c(n)}},[i]);const f=`${e.name}-${e.nodeName||"global"}`;void 0===t&&a[u.current]&&(a[u.current].handler=e.handler,"function"==typeof e.render&&null!==o.current&&(o.current.coAgentStateRenders[f]=e.render)),n.useEffect(()=>{const n=u.current;if(Object.entries(a).some(([t,r])=>{if(t===n)return!1;if(r.name!==e.name)return!1;const o=!!e.nodeName,i=!!r.nodeName;return!o&&!i||o===i&&e.nodeName===r.nodeName})){const n=e.nodeName?`Found multiple state renders for agent ${e.name} and node ${e.nodeName}. State renders might get overridden`:`Found multiple state renders for agent ${e.name}. State renders might get overridden`;d({type:"warning",message:n,id:`dup-action-${e.name}`})}},[a]),n.useEffect(()=>(l(u.current,e),null!==o.current&&void 0!==e.render&&(o.current.coAgentStateRenders[f]=e.render),()=>{s(u.current)}),[l,s,e.name,"string"==typeof e.render?e.render:void 0,...t||[]])},e.useCoAgentStateRenders=Po,e.useCopilotAction=ui,e.useCopilotAdditionalInstructions=function({instructions:e,available:t="enabled"},r){const{setAdditionalInstructions:o}=x();n.useEffect(()=>{if("disabled"!==t)return o(n=>[...n||[],e]),()=>{o(n=>(null==n?void 0:n.filter(n=>n!==e))||[])}},[t,e,o,...r||[]])},e.useCopilotAuthenticatedAction_c=function(e,t){const{authConfig_c:r,authStates_c:o,setAuthStates_c:i}=x(),l=n.useRef(null),s=n.useCallback(t=>"function"==typeof e.render?e.render(t):e.render||n.createElement(n.Fragment),[e]),a=n.useCallback(t=>Object.values(o||{}).some(e=>"authenticated"===e.status)?s(t):(l.current=t,(null==r?void 0:r.SignInComponent)?n.createElement(r.SignInComponent,{onSignInComplete:n=>{null==i||i(t=>Object.assign(Object.assign({},t),{[e.name]:n})),l.current&&(s(l.current),l.current=null)}}):n.createElement(n.Fragment)),[e,o,i]);ui(Object.assign(Object.assign({},e),{render:a}),t)},e.useCopilotChat=function(e={}){const{visibleMessages:n,appendMessage:t,reloadMessages:r,stopGeneration:o,reset:i,isLoading:l,isAvailable:s,runChatCompletion:a,mcpServers:u,setMcpServers:c}=ri(e);return{visibleMessages:n,appendMessage:t,reloadMessages:r,stopGeneration:o,reset:i,isLoading:l,isAvailable:s,runChatCompletion:a,mcpServers:u,setMcpServers:c}},e.useCopilotChatHeadless_c=function(e={}){const{copilotApiConfig:t,setBannerError:o}=x(),i=Boolean(t.publicApiKey),l=ri(e);return n.useEffect(()=>{i?o(null):(o(new r.CopilotKitError({message:"You're using useCopilotChatHeadless_c, a premium-only feature, which offers extensive headless chat capabilities. To continue, you'll need to provide a free public license key.",code:r.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,severity:r.Severity.WARNING,visibility:r.ErrorVisibility.BANNER})),r.styledConsole.logCopilotKitPlatformMessage())},[i]),i?l:{visibleMessages:[],messages:[],sendMessage:async()=>{},appendMessage:async()=>{},setMessages:()=>{},deleteMessage:()=>{},reloadMessages:async()=>{},stopGeneration:()=>{},reset:()=>{},isLoading:!1,isAvailable:!1,runChatCompletion:async()=>[],mcpServers:[],setMcpServers:()=>{},suggestions:[],setSuggestions:()=>{},generateSuggestions:async()=>{},resetSuggestions:()=>{},isLoadingSuggestions:!1,interrupt:null}},e.useCopilotChatInternal=ri,e.useCopilotChatSuggestions=function(e,n=[]){var r,o;const i=t.useCopilotChatConfiguration(),l=null!==(r=null==i?void 0:i.agentId)&&void 0!==r?r:"default",s=null!==(o="enabled"===e.available?"always":e.available)&&void 0!==o?o:"before-first-message",a=Object.assign(Object.assign({},e),{available:s,consumerAgentId:l});t.useConfigureSuggestions(a,n)},e.useCopilotContext=x,e.useCopilotMessagesContext=function(){const e=n.useContext(R);if(e===O)throw new Error("A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`");return e},e.useCopilotReadable=function({description:e,value:r,convert:o,available:i},l){const{copilotkit:s}=t.useCopilotKit(),a=n.useRef(void 0);return n.useEffect(()=>{if(!s)return;const n=Object.entries(s.context).find(([n,t])=>JSON.stringify({description:e,value:r})==JSON.stringify(t));return n?(a.current=n[0],void("disabled"===i&&s.removeContext(a.current))):n||"disabled"!==i?(a.current=s.addContext({description:e,value:(null!=o?o:JSON.stringify)(r)}),()=>{a.current&&s.removeContext(a.current)}):void 0},[e,r,o]),a.current},e.useCopilotRuntimeClient=e=>{const{setBannerError:t}=j(),{showDevConsole:o,onError:l}=e,s=a(e,["showDevConsole","onError"]),u=n.useRef(null),c=async(e,n)=>{try{const t={type:"error",timestamp:Date.now(),context:{source:"ui",request:{operation:"runtimeClient",url:s.url,startTime:Date.now()},technical:{environment:"browser",userAgent:"undefined"!=typeof navigator?navigator.userAgent:void 0,stackTrace:n instanceof Error?n.stack:void 0}},error:e};await l(t)}catch(e){console.error("Error in onError handler:",e)}},d=n.useMemo(()=>new i.CopilotRuntimeClient(Object.assign(Object.assign({},s),{handleGQLErrors:e=>{var n;if(null===(n=e.graphQLErrors)||void 0===n?void 0:n.length){const n=e=>{const n=e.extensions;if((null==n?void 0:n.visibility)===r.ErrorVisibility.SILENT)return void console.error("CopilotKit Silent Error:",e.message);const o=Date.now(),i=e.message;if(u.current&&u.current.message===i&&o-u.current.timestamp<150)return;u.current={message:i,timestamp:o};const l=function(e){var n,t,o;const i=e.extensions,l=null==i?void 0:i.originalError,s=(null==l?void 0:l.message)||e.message,a=null==i?void 0:i.code;if(a)return new r.CopilotKitError({message:s,code:a});if(null===(n=null==l?void 0:l.stack)||void 0===n?void 0:n.includes("CopilotApiDiscoveryError"))return new r.CopilotKitApiDiscoveryError({message:s});if(null===(t=null==l?void 0:l.stack)||void 0===t?void 0:t.includes("CopilotKitRemoteEndpointDiscoveryError"))return new r.CopilotKitRemoteEndpointDiscoveryError({message:s});if(null===(o=null==l?void 0:l.stack)||void 0===o?void 0:o.includes("CopilotKitAgentDiscoveryError"))return new r.CopilotKitAgentDiscoveryError({agentName:"",availableAgents:[]});return null}(e);if(l)t(l),c(l,e);else{const n=new r.CopilotKitError({message:e.message,code:r.CopilotKitErrorCode.UNKNOWN});t(n),c(n,e)}};e.graphQLErrors.forEach(n)}else{const n=new r.CopilotKitError({message:(null==e?void 0:e.message)||String(e),code:r.CopilotKitErrorCode.UNKNOWN});t(n),c(n,e)}},handleGQLWarning:e=>{console.warn(e);const n=new r.CopilotKitError({message:e,code:r.CopilotKitErrorCode.UNKNOWN});t(n)}})),[s,t,l]);return d},e.useDefaultTool=function(e,n){ui(Object.assign(Object.assign({},e),{name:"*"}),n)},e.useFrontendTool=ii,e.useHumanInTheLoop=si,e.useLangGraphInterrupt=function(e,t){const{setInterruptAction:o,removeInterruptAction:i,interruptActions:l,threadId:s}=n.useContext(b),{addToast:a}=j(),u=r.dataToUUID(e,"lgAction");n.useEffect(()=>{if(e)return o(Object.assign(Object.assign({},e),{id:u})),()=>{i(u)}},[o,i,s,u,...t||[]])},e.useLangGraphInterruptRender=ni,e.useLazyToolRenderer=ti,e.useMakeCopilotDocumentReadable=function(e,t,r=[]){const{addDocumentContext:o,removeDocumentContext:i}=x(),l=n.useRef(void 0);return n.useEffect(()=>{const n=o(e,t);return l.current=n,()=>{i(n)}},[o,i,...r]),l.current},e.useRenderToolCall=li,e.useThreads=Fo});
39
- //# sourceMappingURL=index.umd.js.map
1
+ "use client";
2
+
3
+ (function(global, factory) {
4
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('@copilotkitnext/react'), require('@copilotkit/shared'), require('react-dom'), require('react/jsx-runtime'), require('react-markdown'), require('@copilotkit/runtime-client-gql'), require('@ag-ui/client'), require('@copilotkitnext/core')) :
5
+ typeof define === 'function' && define.amd ? define(['exports', 'react', '@copilotkitnext/react', '@copilotkit/shared', 'react-dom', 'react/jsx-runtime', 'react-markdown', '@copilotkit/runtime-client-gql', '@ag-ui/client', '@copilotkitnext/core'], factory) :
6
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitReactCore = {}), global.React,global.CopilotKitNextReact,global.CopilotKitShared,global.ReactDOM,global.ReactJsxRuntime,global.ReactMarkdown,global.CopilotKitRuntimeClientGQL,global.AgUIClient,global.CopilotKitNextCore));
7
+ })(this, function(exports, react, _copilotkitnext_react, _copilotkit_shared, react_dom, react_jsx_runtime, react_markdown, _copilotkit_runtime_client_gql, _ag_ui_client, _copilotkitnext_core) {
8
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
9
+ //#region \0rolldown/runtime.js
10
+ var __create = Object.create;
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __getProtoOf = Object.getPrototypeOf;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
19
+ key = keys[i];
20
+ if (!__hasOwnProp.call(to, key) && key !== except) {
21
+ __defProp(to, key, {
22
+ get: ((k) => from[k]).bind(null, key),
23
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
24
+ });
25
+ }
26
+ }
27
+ }
28
+ return to;
29
+ };
30
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
31
+ value: mod,
32
+ enumerable: true
33
+ }) : target, mod));
34
+
35
+ //#endregion
36
+ react = __toESM(react);
37
+ react_markdown = __toESM(react_markdown);
38
+
39
+ //#region src/context/copilot-context.tsx
40
+ const emptyCopilotContext$1 = {
41
+ actions: {},
42
+ setAction: () => {},
43
+ removeAction: () => {},
44
+ setRegisteredActions: () => "",
45
+ removeRegisteredAction: () => {},
46
+ chatComponentsCache: { current: {
47
+ actions: {},
48
+ coAgentStateRenders: {}
49
+ } },
50
+ getContextString: (documents, categories) => returnAndThrowInDebug(""),
51
+ addContext: () => "",
52
+ removeContext: () => {},
53
+ getAllContext: () => [],
54
+ getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),
55
+ isLoading: false,
56
+ setIsLoading: () => returnAndThrowInDebug(false),
57
+ chatInstructions: "",
58
+ setChatInstructions: () => returnAndThrowInDebug(""),
59
+ additionalInstructions: [],
60
+ setAdditionalInstructions: () => returnAndThrowInDebug([]),
61
+ getDocumentsContext: (categories) => returnAndThrowInDebug([]),
62
+ addDocumentContext: () => returnAndThrowInDebug(""),
63
+ removeDocumentContext: () => {},
64
+ copilotApiConfig: new class {
65
+ get chatApiEndpoint() {
66
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
67
+ }
68
+ get headers() {
69
+ return {};
70
+ }
71
+ get body() {
72
+ return {};
73
+ }
74
+ }(),
75
+ chatSuggestionConfiguration: {},
76
+ addChatSuggestionConfiguration: () => {},
77
+ removeChatSuggestionConfiguration: () => {},
78
+ showDevConsole: false,
79
+ coagentStates: {},
80
+ setCoagentStates: () => {},
81
+ coagentStatesRef: { current: {} },
82
+ setCoagentStatesWithRef: () => {},
83
+ agentSession: null,
84
+ setAgentSession: () => {},
85
+ forwardedParameters: {},
86
+ agentLock: null,
87
+ threadId: "",
88
+ setThreadId: () => {},
89
+ runId: null,
90
+ setRunId: () => {},
91
+ chatAbortControllerRef: { current: null },
92
+ availableAgents: [],
93
+ extensions: {},
94
+ setExtensions: () => {},
95
+ interruptActions: {},
96
+ setInterruptAction: () => {},
97
+ removeInterruptAction: () => {},
98
+ interruptEventQueue: {},
99
+ addInterruptEvent: () => {},
100
+ resolveInterruptEvent: () => {},
101
+ onError: () => {},
102
+ bannerError: null,
103
+ setBannerError: () => {},
104
+ internalErrorHandlers: {},
105
+ setInternalErrorHandler: () => {},
106
+ removeInternalErrorHandler: () => {}
107
+ };
108
+ const CopilotContext = react.default.createContext(emptyCopilotContext$1);
109
+ function useCopilotContext() {
110
+ const context = react.default.useContext(CopilotContext);
111
+ if (context === emptyCopilotContext$1) throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
112
+ return context;
113
+ }
114
+ function returnAndThrowInDebug(_value) {
115
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
116
+ }
117
+
118
+ //#endregion
119
+ //#region src/hooks/use-tree.ts
120
+ const removeNode = (nodes, id) => {
121
+ return nodes.reduce((result, node) => {
122
+ if (node.id !== id) {
123
+ const newNode = {
124
+ ...node,
125
+ children: removeNode(node.children, id)
126
+ };
127
+ result.push(newNode);
128
+ }
129
+ return result;
130
+ }, []);
131
+ };
132
+ const addNode = (nodes, newNode, parentId) => {
133
+ if (!parentId) return [...nodes, newNode];
134
+ return nodes.map((node) => {
135
+ if (node.id === parentId) return {
136
+ ...node,
137
+ children: [...node.children, newNode]
138
+ };
139
+ else if (node.children.length) return {
140
+ ...node,
141
+ children: addNode(node.children, newNode, parentId)
142
+ };
143
+ return node;
144
+ });
145
+ };
146
+ const treeIndentationRepresentation = (index, indentLevel) => {
147
+ if (indentLevel === 0) return (index + 1).toString();
148
+ else if (indentLevel === 1) return String.fromCharCode(65 + index);
149
+ else if (indentLevel === 2) return String.fromCharCode(97 + index);
150
+ else return "-";
151
+ };
152
+ const printNode = (node, prefix = "", indentLevel = 0) => {
153
+ const indent = " ".repeat(3).repeat(indentLevel);
154
+ const prefixPlusIndentLength = prefix.length + indent.length;
155
+ const subsequentLinesPrefix = " ".repeat(prefixPlusIndentLength);
156
+ const valueLines = node.value.split("\n");
157
+ const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;
158
+ const outputSubsequentLines = valueLines.slice(1).map((line) => `${subsequentLinesPrefix}${line}`).join("\n");
159
+ let output = `${outputFirstLine}\n`;
160
+ if (outputSubsequentLines) output += `${outputSubsequentLines}\n`;
161
+ const childPrePrefix = " ".repeat(prefix.length);
162
+ node.children.forEach((child, index) => output += printNode(child, `${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `, indentLevel + 1));
163
+ return output;
164
+ };
165
+ function treeReducer(state, action) {
166
+ switch (action.type) {
167
+ case "ADD_NODE": {
168
+ const { value, parentId, id: newNodeId } = action;
169
+ const newNode = {
170
+ id: newNodeId,
171
+ value,
172
+ children: [],
173
+ categories: new Set(action.categories)
174
+ };
175
+ try {
176
+ return addNode(state, newNode, parentId);
177
+ } catch (error) {
178
+ console.error(`Error while adding node with id ${newNodeId}: ${error}`);
179
+ return state;
180
+ }
181
+ }
182
+ case "REMOVE_NODE": return removeNode(state, action.id);
183
+ default: return state;
184
+ }
185
+ }
186
+ const useTree = () => {
187
+ const [tree, dispatch] = (0, react.useReducer)(treeReducer, []);
188
+ const addElement = (0, react.useCallback)((value, categories, parentId) => {
189
+ const newNodeId = (0, _copilotkit_shared.randomId)();
190
+ dispatch({
191
+ type: "ADD_NODE",
192
+ value,
193
+ parentId,
194
+ id: newNodeId,
195
+ categories
196
+ });
197
+ return newNodeId;
198
+ }, []);
199
+ const removeElement = (0, react.useCallback)((id) => {
200
+ dispatch({
201
+ type: "REMOVE_NODE",
202
+ id
203
+ });
204
+ }, []);
205
+ const getAllElements = (0, react.useCallback)(() => {
206
+ return tree;
207
+ }, [tree]);
208
+ return {
209
+ tree,
210
+ addElement,
211
+ printTree: (0, react.useCallback)((categories) => {
212
+ const categoriesSet = new Set(categories);
213
+ let output = "";
214
+ tree.forEach((node, index) => {
215
+ if (!setsHaveIntersection$1(categoriesSet, node.categories)) return;
216
+ if (index !== 0) output += "\n";
217
+ output += printNode(node, `${treeIndentationRepresentation(index, 0)}. `);
218
+ });
219
+ return output;
220
+ }, [tree]),
221
+ removeElement,
222
+ getAllElements
223
+ };
224
+ };
225
+ function setsHaveIntersection$1(setA, setB) {
226
+ const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
227
+ for (let item of smallerSet) if (largerSet.has(item)) return true;
228
+ return false;
229
+ }
230
+
231
+ //#endregion
232
+ //#region src/hooks/use-flat-category-store.ts
233
+ const useFlatCategoryStore = () => {
234
+ const [elements, dispatch] = (0, react.useReducer)(flatCategoryStoreReducer, /* @__PURE__ */ new Map());
235
+ return {
236
+ addElement: (0, react.useCallback)((value, categories) => {
237
+ const newId = (0, _copilotkit_shared.randomId)();
238
+ dispatch({
239
+ type: "ADD_ELEMENT",
240
+ value,
241
+ id: newId,
242
+ categories
243
+ });
244
+ return newId;
245
+ }, []),
246
+ removeElement: (0, react.useCallback)((id) => {
247
+ dispatch({
248
+ type: "REMOVE_ELEMENT",
249
+ id
250
+ });
251
+ }, []),
252
+ allElements: (0, react.useCallback)((categories) => {
253
+ const categoriesSet = new Set(categories);
254
+ const result = [];
255
+ elements.forEach((element) => {
256
+ if (setsHaveIntersection(categoriesSet, element.categories)) result.push(element.value);
257
+ });
258
+ return result;
259
+ }, [elements])
260
+ };
261
+ };
262
+ function flatCategoryStoreReducer(state, action) {
263
+ switch (action.type) {
264
+ case "ADD_ELEMENT": {
265
+ const { value, id, categories } = action;
266
+ const newElement = {
267
+ id,
268
+ value,
269
+ categories: new Set(categories)
270
+ };
271
+ const newState = new Map(state);
272
+ newState.set(id, newElement);
273
+ return newState;
274
+ }
275
+ case "REMOVE_ELEMENT": {
276
+ const newState = new Map(state);
277
+ newState.delete(action.id);
278
+ return newState;
279
+ }
280
+ default: return state;
281
+ }
282
+ }
283
+ function setsHaveIntersection(setA, setB) {
284
+ const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
285
+ for (let item of smallerSet) if (largerSet.has(item)) return true;
286
+ return false;
287
+ }
288
+
289
+ //#endregion
290
+ //#region src/context/copilot-messages-context.tsx
291
+ const emptyCopilotContext = {
292
+ messages: [],
293
+ setMessages: () => [],
294
+ suggestions: [],
295
+ setSuggestions: () => []
296
+ };
297
+ const CopilotMessagesContext = react.default.createContext(emptyCopilotContext);
298
+ function useCopilotMessagesContext() {
299
+ const context = react.default.useContext(CopilotMessagesContext);
300
+ if (context === emptyCopilotContext) throw new Error("A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`");
301
+ return context;
302
+ }
303
+
304
+ //#endregion
305
+ //#region src/components/toast/toast-provider.tsx
306
+ const ToastContext = (0, react.createContext)(void 0);
307
+ function getErrorSeverity(error) {
308
+ if (error.severity) switch (error.severity) {
309
+ case _copilotkit_shared.Severity.CRITICAL: return "critical";
310
+ case _copilotkit_shared.Severity.WARNING: return "warning";
311
+ case _copilotkit_shared.Severity.INFO: return "info";
312
+ default: return "info";
313
+ }
314
+ const message = error.message.toLowerCase();
315
+ if (message.includes("api key") || message.includes("401") || message.includes("unauthorized") || message.includes("authentication") || message.includes("incorrect api key")) return "critical";
316
+ return "info";
317
+ }
318
+ function getErrorColors(severity) {
319
+ switch (severity) {
320
+ case "critical": return {
321
+ background: "#fee2e2",
322
+ border: "#dc2626",
323
+ text: "#7f1d1d",
324
+ icon: "#dc2626"
325
+ };
326
+ case "warning": return {
327
+ background: "#fef3c7",
328
+ border: "#d97706",
329
+ text: "#78350f",
330
+ icon: "#d97706"
331
+ };
332
+ case "info": return {
333
+ background: "#dbeafe",
334
+ border: "#2563eb",
335
+ text: "#1e3a8a",
336
+ icon: "#2563eb"
337
+ };
338
+ }
339
+ }
340
+ function useToast() {
341
+ const context = (0, react.useContext)(ToastContext);
342
+ if (!context) throw new Error("useToast must be used within a ToastProvider");
343
+ return context;
344
+ }
345
+ function ToastProvider({ enabled, children }) {
346
+ const [toasts, setToasts] = (0, react.useState)([]);
347
+ const [bannerError, setBannerErrorState] = (0, react.useState)(null);
348
+ const removeToast = (0, react.useCallback)((id) => {
349
+ setToasts((prev) => prev.filter((toast) => toast.id !== id));
350
+ }, []);
351
+ const addToast = (0, react.useCallback)((toast) => {
352
+ var _toast$id;
353
+ if (!enabled) return;
354
+ const id = (_toast$id = toast.id) !== null && _toast$id !== void 0 ? _toast$id : Math.random().toString(36).substring(2, 9);
355
+ setToasts((currentToasts) => {
356
+ if (currentToasts.find((toast) => toast.id === id)) return currentToasts;
357
+ return [...currentToasts, {
358
+ ...toast,
359
+ id
360
+ }];
361
+ });
362
+ if (toast.duration) setTimeout(() => {
363
+ removeToast(id);
364
+ }, toast.duration);
365
+ }, [enabled, removeToast]);
366
+ const setBannerError = (0, react.useCallback)((error) => {
367
+ if (!enabled && error !== null) return;
368
+ setBannerErrorState(error);
369
+ }, [enabled]);
370
+ const value = {
371
+ toasts,
372
+ addToast,
373
+ addGraphQLErrorsToast: (0, react.useCallback)((errors) => {
374
+ console.warn("addGraphQLErrorsToast is deprecated. All errors now show as banners.");
375
+ }, []),
376
+ removeToast,
377
+ enabled,
378
+ bannerError,
379
+ setBannerError
380
+ };
381
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(ToastContext.Provider, {
382
+ value,
383
+ children: [bannerError && (() => {
384
+ const colors = getErrorColors(getErrorSeverity(bannerError));
385
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
386
+ style: {
387
+ position: "fixed",
388
+ bottom: "20px",
389
+ left: "50%",
390
+ transform: "translateX(-50%)",
391
+ zIndex: 9999,
392
+ backgroundColor: colors.background,
393
+ border: `1px solid ${colors.border}`,
394
+ borderLeft: `4px solid ${colors.border}`,
395
+ borderRadius: "8px",
396
+ padding: "12px 16px",
397
+ fontSize: "13px",
398
+ boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
399
+ backdropFilter: "blur(8px)",
400
+ maxWidth: "min(90vw, 700px)",
401
+ width: "100%",
402
+ boxSizing: "border-box",
403
+ overflow: "hidden"
404
+ },
405
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
406
+ style: {
407
+ display: "flex",
408
+ justifyContent: "space-between",
409
+ alignItems: "center",
410
+ gap: "10px"
411
+ },
412
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
413
+ style: {
414
+ display: "flex",
415
+ alignItems: "center",
416
+ gap: "8px",
417
+ flex: 1,
418
+ minWidth: 0
419
+ },
420
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: {
421
+ width: "12px",
422
+ height: "12px",
423
+ borderRadius: "50%",
424
+ backgroundColor: colors.border,
425
+ flexShrink: 0
426
+ } }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
427
+ style: {
428
+ display: "flex",
429
+ alignItems: "center",
430
+ gap: "10px",
431
+ flex: 1,
432
+ minWidth: 0
433
+ },
434
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
435
+ style: {
436
+ color: colors.text,
437
+ lineHeight: "1.4",
438
+ fontWeight: "400",
439
+ fontSize: "13px",
440
+ flex: 1,
441
+ wordBreak: "break-all",
442
+ overflowWrap: "break-word",
443
+ maxWidth: "550px",
444
+ overflow: "hidden",
445
+ display: "-webkit-box",
446
+ WebkitLineClamp: 10,
447
+ WebkitBoxOrient: "vertical"
448
+ },
449
+ children: (() => {
450
+ let message = bannerError.message;
451
+ const jsonMatch = message.match(/'message':\s*'([^']+)'/);
452
+ if (jsonMatch) return jsonMatch[1];
453
+ message = message.split(" - ")[0];
454
+ message = message.split(": Error code")[0];
455
+ message = message.replace(/:\s*\d{3}$/, "");
456
+ message = message.replace(/See more:.*$/g, "");
457
+ message = message.trim();
458
+ return message || "Configuration error occurred.";
459
+ })()
460
+ }), (() => {
461
+ const message = bannerError.message;
462
+ const markdownLinkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;
463
+ const plainUrlRegex = /(https?:\/\/[^\s)]+)/g;
464
+ let url = null;
465
+ let buttonText = "See More";
466
+ const markdownMatch = markdownLinkRegex.exec(message);
467
+ if (markdownMatch) {
468
+ url = markdownMatch[2];
469
+ buttonText = "See More";
470
+ } else {
471
+ const urlMatch = plainUrlRegex.exec(message);
472
+ if (urlMatch) {
473
+ url = urlMatch[0].replace(/[.,;:'"]*$/, "");
474
+ buttonText = "See More";
475
+ }
476
+ }
477
+ if (!url) return null;
478
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
479
+ onClick: () => window.open(url, "_blank", "noopener,noreferrer"),
480
+ style: {
481
+ background: colors.border,
482
+ color: "white",
483
+ border: "none",
484
+ borderRadius: "5px",
485
+ padding: "4px 10px",
486
+ fontSize: "11px",
487
+ fontWeight: "500",
488
+ cursor: "pointer",
489
+ transition: "all 0.2s ease",
490
+ flexShrink: 0
491
+ },
492
+ onMouseEnter: (e) => {
493
+ e.currentTarget.style.opacity = "0.9";
494
+ e.currentTarget.style.transform = "translateY(-1px)";
495
+ },
496
+ onMouseLeave: (e) => {
497
+ e.currentTarget.style.opacity = "1";
498
+ e.currentTarget.style.transform = "translateY(0)";
499
+ },
500
+ children: buttonText
501
+ });
502
+ })()]
503
+ })]
504
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
505
+ onClick: () => setBannerError(null),
506
+ style: {
507
+ background: "transparent",
508
+ border: "none",
509
+ color: colors.text,
510
+ cursor: "pointer",
511
+ padding: "2px",
512
+ borderRadius: "3px",
513
+ fontSize: "14px",
514
+ lineHeight: "1",
515
+ opacity: .6,
516
+ transition: "all 0.2s ease",
517
+ flexShrink: 0
518
+ },
519
+ title: "Dismiss",
520
+ onMouseEnter: (e) => {
521
+ e.currentTarget.style.opacity = "1";
522
+ e.currentTarget.style.background = "rgba(0, 0, 0, 0.05)";
523
+ },
524
+ onMouseLeave: (e) => {
525
+ e.currentTarget.style.opacity = "0.6";
526
+ e.currentTarget.style.background = "transparent";
527
+ },
528
+ children: "×"
529
+ })]
530
+ })
531
+ });
532
+ })(), children]
533
+ });
534
+ }
535
+
536
+ //#endregion
537
+ //#region src/utils/dev-console.ts
538
+ function isLocalhost() {
539
+ if (typeof window === "undefined") return false;
540
+ return window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1" || window.location.hostname === "0.0.0.0";
541
+ }
542
+ function shouldShowDevConsole(showDevConsole) {
543
+ if (showDevConsole !== void 0) return showDevConsole;
544
+ return isLocalhost();
545
+ }
546
+
547
+ //#endregion
548
+ //#region src/components/copilot-provider/copilot-messages.tsx
549
+ /**
550
+ * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context
551
+ */
552
+ const MessagesTapContext = (0, react.createContext)(null);
553
+ function useMessagesTap() {
554
+ const tap = (0, react.useContext)(MessagesTapContext);
555
+ if (!tap) throw new Error("useMessagesTap must be used inside <MessagesTapProvider>");
556
+ return tap;
557
+ }
558
+ function MessagesTapProvider({ children }) {
559
+ const messagesRef = (0, react.useRef)([]);
560
+ const tapRef = (0, react.useRef)({
561
+ getMessagesFromTap: () => messagesRef.current,
562
+ updateTapMessages: (messages) => {
563
+ messagesRef.current = messages;
564
+ }
565
+ });
566
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MessagesTapContext.Provider, {
567
+ value: tapRef.current,
568
+ children
569
+ });
570
+ }
571
+ /**
572
+ * CopilotKit messages context.
573
+ */
574
+ function CopilotMessages({ children }) {
575
+ const [messages, setMessages] = (0, react.useState)([]);
576
+ (0, react.useRef)(void 0);
577
+ (0, react.useRef)(void 0);
578
+ (0, react.useRef)(void 0);
579
+ const { updateTapMessages } = useMessagesTap();
580
+ const { threadId, agentSession, showDevConsole, onError, copilotApiConfig } = useCopilotContext();
581
+ const { setBannerError } = useToast();
582
+ const traceUIError = (0, react.useCallback)(async (error, originalError) => {
583
+ if (!onError || !copilotApiConfig.publicApiKey) return;
584
+ try {
585
+ await onError({
586
+ type: "error",
587
+ timestamp: Date.now(),
588
+ context: {
589
+ source: "ui",
590
+ request: {
591
+ operation: "loadAgentState",
592
+ url: copilotApiConfig.chatApiEndpoint,
593
+ startTime: Date.now()
594
+ },
595
+ technical: {
596
+ environment: "browser",
597
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
598
+ stackTrace: originalError instanceof Error ? originalError.stack : void 0
599
+ }
600
+ },
601
+ error
602
+ });
603
+ } catch (traceError) {
604
+ console.error("Error in CopilotMessages onError handler:", traceError);
605
+ }
606
+ }, [
607
+ onError,
608
+ copilotApiConfig.publicApiKey,
609
+ copilotApiConfig.chatApiEndpoint
610
+ ]);
611
+ const createStructuredError = (gqlError) => {
612
+ const extensions = gqlError.extensions;
613
+ const originalError = extensions === null || extensions === void 0 ? void 0 : extensions.originalError;
614
+ if (originalError === null || originalError === void 0 ? void 0 : originalError.stack) {
615
+ if (originalError.stack.includes("CopilotApiDiscoveryError")) return new _copilotkit_shared.CopilotKitApiDiscoveryError({ message: originalError.message });
616
+ if (originalError.stack.includes("CopilotKitRemoteEndpointDiscoveryError")) return new _copilotkit_shared.CopilotKitRemoteEndpointDiscoveryError({ message: originalError.message });
617
+ if (originalError.stack.includes("CopilotKitAgentDiscoveryError")) return new _copilotkit_shared.CopilotKitAgentDiscoveryError({
618
+ agentName: "",
619
+ availableAgents: []
620
+ });
621
+ }
622
+ const message = (originalError === null || originalError === void 0 ? void 0 : originalError.message) || gqlError.message;
623
+ const code = extensions === null || extensions === void 0 ? void 0 : extensions.code;
624
+ if (code) return new _copilotkit_shared.CopilotKitError({
625
+ message,
626
+ code
627
+ });
628
+ return null;
629
+ };
630
+ (0, react.useCallback)((error) => {
631
+ var _error$graphQLErrors;
632
+ if ((_error$graphQLErrors = error.graphQLErrors) === null || _error$graphQLErrors === void 0 ? void 0 : _error$graphQLErrors.length) {
633
+ const graphQLErrors = error.graphQLErrors;
634
+ const routeError = (gqlError) => {
635
+ const extensions = gqlError.extensions;
636
+ const visibility = extensions === null || extensions === void 0 ? void 0 : extensions.visibility;
637
+ if (!shouldShowDevConsole(showDevConsole)) {
638
+ console.error("CopilotKit Error (hidden in production):", gqlError.message);
639
+ return;
640
+ }
641
+ if (visibility === _copilotkit_shared.ErrorVisibility.SILENT) {
642
+ console.error("CopilotKit Silent Error:", gqlError.message);
643
+ return;
644
+ }
645
+ const ckError = createStructuredError(gqlError);
646
+ if (ckError) {
647
+ setBannerError(ckError);
648
+ traceUIError(ckError, gqlError);
649
+ } else {
650
+ const fallbackError = new _copilotkit_shared.CopilotKitError({
651
+ message: gqlError.message,
652
+ code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
653
+ });
654
+ setBannerError(fallbackError);
655
+ traceUIError(fallbackError, gqlError);
656
+ }
657
+ };
658
+ graphQLErrors.forEach(routeError);
659
+ } else if (!shouldShowDevConsole(showDevConsole)) console.error("CopilotKit Error (hidden in production):", error);
660
+ else {
661
+ const fallbackError = new _copilotkit_shared.CopilotKitError({
662
+ message: (error === null || error === void 0 ? void 0 : error.message) || String(error),
663
+ code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
664
+ });
665
+ setBannerError(fallbackError);
666
+ traceUIError(fallbackError, error);
667
+ }
668
+ }, [
669
+ setBannerError,
670
+ showDevConsole,
671
+ traceUIError
672
+ ]);
673
+ (0, react.useEffect)(() => {
674
+ updateTapMessages(messages);
675
+ }, [messages, updateTapMessages]);
676
+ const memoizedChildren = (0, react.useMemo)(() => children, [children]);
677
+ const [suggestions, setSuggestions] = (0, react.useState)([]);
678
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotMessagesContext.Provider, {
679
+ value: {
680
+ messages,
681
+ setMessages,
682
+ suggestions,
683
+ setSuggestions
684
+ },
685
+ children: memoizedChildren
686
+ });
687
+ }
688
+
689
+ //#endregion
690
+ //#region src/components/usage-banner.tsx
691
+ function UsageBanner({ severity = _copilotkit_shared.Severity.CRITICAL, message = "", onClose, actions }) {
692
+ if (!message || !severity) return null;
693
+ const theme = {
694
+ [_copilotkit_shared.Severity.INFO]: {
695
+ bg: "#f8fafc",
696
+ border: "#e2e8f0",
697
+ text: "#475569",
698
+ accent: "#3b82f6"
699
+ },
700
+ [_copilotkit_shared.Severity.WARNING]: {
701
+ bg: "#fffbeb",
702
+ border: "#fbbf24",
703
+ text: "#92400e",
704
+ accent: "#f59e0b"
705
+ },
706
+ [_copilotkit_shared.Severity.CRITICAL]: {
707
+ bg: "#fef2f2",
708
+ border: "#fecaca",
709
+ text: "#dc2626",
710
+ accent: "#ef4444"
711
+ }
712
+ }[severity];
713
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { children: `
714
+ @keyframes slideUp {
715
+ from { opacity: 0; transform: translateX(-50%) translateY(8px); }
716
+ to { opacity: 1; transform: translateX(-50%) translateY(0); }
717
+ }
718
+
719
+ .usage-banner {
720
+ position: fixed;
721
+ bottom: 24px;
722
+ left: 50%;
723
+ transform: translateX(-50%);
724
+ width: min(600px, calc(100vw - 32px));
725
+ z-index: 10000;
726
+ animation: slideUp 0.2s cubic-bezier(0.16, 1, 0.3, 1);
727
+ }
728
+
729
+ .banner-content {
730
+ background: linear-gradient(135deg, ${theme.bg} 0%, ${theme.bg}f5 100%);
731
+ border: 1px solid ${theme.border};
732
+ border-radius: 12px;
733
+ padding: 18px 20px;
734
+ box-shadow:
735
+ 0 4px 24px rgba(0, 0, 0, 0.08),
736
+ 0 2px 8px rgba(0, 0, 0, 0.04),
737
+ inset 0 1px 0 rgba(255, 255, 255, 0.7);
738
+ display: flex;
739
+ align-items: center;
740
+ gap: 16px;
741
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
742
+ backdrop-filter: blur(12px);
743
+ position: relative;
744
+ overflow: hidden;
745
+ }
746
+
747
+ .banner-content::before {
748
+ content: '';
749
+ position: absolute;
750
+ top: 0;
751
+ left: 0;
752
+ right: 0;
753
+ height: 1px;
754
+ background: linear-gradient(90deg, transparent, ${theme.accent}40, transparent);
755
+ }
756
+
757
+ .banner-message {
758
+ color: ${theme.text};
759
+ font-size: 14px;
760
+ line-height: 1.5;
761
+ font-weight: 500;
762
+ flex: 1;
763
+ letter-spacing: -0.01em;
764
+ }
765
+
766
+ .close-btn {
767
+ background: rgba(0, 0, 0, 0.05);
768
+ border: none;
769
+ color: ${theme.text};
770
+ cursor: pointer;
771
+ padding: 0;
772
+ border-radius: 6px;
773
+ opacity: 0.6;
774
+ transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);
775
+ font-size: 14px;
776
+ line-height: 1;
777
+ flex-shrink: 0;
778
+ width: 24px;
779
+ height: 24px;
780
+ display: flex;
781
+ align-items: center;
782
+ justify-content: center;
783
+ }
784
+
785
+ .close-btn:hover {
786
+ opacity: 1;
787
+ background: rgba(0, 0, 0, 0.08);
788
+ transform: scale(1.05);
789
+ }
790
+
791
+ .btn-primary {
792
+ background: linear-gradient(135deg, ${theme.accent} 0%, ${theme.accent}e6 100%);
793
+ color: white;
794
+ border: none;
795
+ border-radius: 8px;
796
+ padding: 10px 18px;
797
+ font-size: 13px;
798
+ font-weight: 600;
799
+ cursor: pointer;
800
+ transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);
801
+ font-family: inherit;
802
+ flex-shrink: 0;
803
+ box-shadow:
804
+ 0 2px 8px ${theme.accent}30,
805
+ inset 0 1px 0 rgba(255, 255, 255, 0.2);
806
+ letter-spacing: -0.01em;
807
+ }
808
+
809
+ .btn-primary:hover {
810
+ transform: translateY(-1px) scale(1.02);
811
+ box-shadow:
812
+ 0 4px 12px ${theme.accent}40,
813
+ inset 0 1px 0 rgba(255, 255, 255, 0.25);
814
+ }
815
+
816
+ .btn-primary:active {
817
+ transform: translateY(0) scale(0.98);
818
+ transition: all 0.08s cubic-bezier(0.16, 1, 0.3, 1);
819
+ }
820
+
821
+ @media (max-width: 640px) {
822
+ .usage-banner {
823
+ width: calc(100vw - 24px);
824
+ }
825
+
826
+ .banner-content {
827
+ padding: 16px;
828
+ gap: 12px;
829
+ }
830
+
831
+ .banner-message {
832
+ font-size: 13px;
833
+ line-height: 1.45;
834
+ }
835
+
836
+ .btn-primary {
837
+ padding: 8px 14px;
838
+ font-size: 12px;
839
+ }
840
+
841
+ .close-btn {
842
+ width: 22px;
843
+ height: 22px;
844
+ font-size: 12px;
845
+ }
846
+ }
847
+ ` }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
848
+ className: "usage-banner",
849
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
850
+ className: "banner-content",
851
+ children: [
852
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
853
+ className: "banner-message",
854
+ children: message
855
+ }),
856
+ (actions === null || actions === void 0 ? void 0 : actions.primary) && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
857
+ className: "btn-primary",
858
+ onClick: actions.primary.onClick,
859
+ children: actions.primary.label
860
+ }),
861
+ onClose && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
862
+ className: "close-btn",
863
+ onClick: onClose,
864
+ title: "Close",
865
+ children: "×"
866
+ })
867
+ ]
868
+ })
869
+ })] });
870
+ }
871
+ const getErrorActions = (error) => {
872
+ switch (error.code) {
873
+ case _copilotkit_shared.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR: return { primary: {
874
+ label: "Show me how",
875
+ onClick: () => window.open("https://docs.copilotkit.ai/premium#how-do-i-get-access-to-premium-features", "_blank", "noopener,noreferrer")
876
+ } };
877
+ case _copilotkit_shared.CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR: return { primary: {
878
+ label: "Upgrade",
879
+ onClick: () => window.open("https://cloud.copilotkit.ai", "_blank", "noopener,noreferrer")
880
+ } };
881
+ default: return;
882
+ }
883
+ };
884
+
885
+ //#endregion
886
+ //#region src/utils/suggestions-constants.ts
887
+ /**
888
+ * Constants for suggestions retry logic
889
+ */
890
+ const SUGGESTION_RETRY_CONFIG = {
891
+ MAX_RETRIES: 3,
892
+ COOLDOWN_MS: 5e3
893
+ };
894
+
895
+ //#endregion
896
+ //#region src/lib/status-checker.ts
897
+ const STATUS_CHECK_INTERVAL = 1e3 * 60 * 5;
898
+ var StatusChecker = class {
899
+ constructor() {
900
+ this.activeKey = null;
901
+ this.intervalId = null;
902
+ this.instanceCount = 0;
903
+ this.lastResponse = null;
904
+ }
905
+ async start(publicApiKey, onUpdate) {
906
+ this.instanceCount++;
907
+ if (this.activeKey === publicApiKey) return;
908
+ if (this.intervalId) clearInterval(this.intervalId);
909
+ const checkStatus = async () => {
910
+ try {
911
+ const response = await fetch(`${_copilotkit_shared.COPILOT_CLOUD_API_URL}/ciu`, {
912
+ method: "GET",
913
+ headers: { [_copilotkit_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey }
914
+ }).then((response) => response.json());
915
+ this.lastResponse = response;
916
+ onUpdate === null || onUpdate === void 0 || onUpdate(response);
917
+ return response;
918
+ } catch (error) {
919
+ return null;
920
+ }
921
+ };
922
+ const initialResponse = await checkStatus();
923
+ this.intervalId = setInterval(checkStatus, STATUS_CHECK_INTERVAL);
924
+ this.activeKey = publicApiKey;
925
+ return initialResponse;
926
+ }
927
+ getLastResponse() {
928
+ return this.lastResponse;
929
+ }
930
+ stop() {
931
+ this.instanceCount--;
932
+ if (this.instanceCount === 0) {
933
+ if (this.intervalId) {
934
+ clearInterval(this.intervalId);
935
+ this.intervalId = null;
936
+ this.activeKey = null;
937
+ this.lastResponse = null;
938
+ }
939
+ }
940
+ }
941
+ };
942
+
943
+ //#endregion
944
+ //#region src/components/toast/exclamation-mark-icon.tsx
945
+ const ExclamationMarkIcon = ({ className, style }) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
946
+ xmlns: "http://www.w3.org/2000/svg",
947
+ width: "24",
948
+ height: "24",
949
+ viewBox: "0 0 24 24",
950
+ fill: "none",
951
+ stroke: "currentColor",
952
+ strokeWidth: "2",
953
+ strokeLinecap: "round",
954
+ strokeLinejoin: "round",
955
+ className: `lucide lucide-circle-alert ${className ? className : ""}`,
956
+ style,
957
+ children: [
958
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
959
+ cx: "12",
960
+ cy: "12",
961
+ r: "10"
962
+ }),
963
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("line", {
964
+ x1: "12",
965
+ x2: "12",
966
+ y1: "8",
967
+ y2: "12"
968
+ }),
969
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("line", {
970
+ x1: "12",
971
+ x2: "12.01",
972
+ y1: "16",
973
+ y2: "16"
974
+ })
975
+ ]
976
+ });
977
+
978
+ //#endregion
979
+ //#region src/components/error-boundary/error-utils.tsx
980
+ function ErrorToast({ errors }) {
981
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
982
+ style: {
983
+ fontSize: "13px",
984
+ maxWidth: "600px"
985
+ },
986
+ children: [errors.map((error, idx) => {
987
+ var _error$extensions, _originalError$messag, _error$extensions2;
988
+ const originalError = "extensions" in error ? (_error$extensions = error.extensions) === null || _error$extensions === void 0 ? void 0 : _error$extensions.originalError : {};
989
+ const message = (_originalError$messag = originalError === null || originalError === void 0 ? void 0 : originalError.message) !== null && _originalError$messag !== void 0 ? _originalError$messag : error.message;
990
+ const code = "extensions" in error ? (_error$extensions2 = error.extensions) === null || _error$extensions2 === void 0 ? void 0 : _error$extensions2.code : null;
991
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
992
+ style: {
993
+ marginTop: idx === 0 ? 0 : 10,
994
+ marginBottom: 14
995
+ },
996
+ children: [
997
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
998
+ code && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
999
+ style: {
1000
+ fontWeight: "600",
1001
+ marginBottom: 4
1002
+ },
1003
+ children: [
1004
+ "Copilot Runtime Error:",
1005
+ " ",
1006
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1007
+ style: {
1008
+ fontFamily: "monospace",
1009
+ fontWeight: "normal"
1010
+ },
1011
+ children: code
1012
+ })
1013
+ ]
1014
+ }),
1015
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_markdown.default, { children: message })
1016
+ ]
1017
+ }, idx);
1018
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1019
+ style: {
1020
+ fontSize: "11px",
1021
+ opacity: .75
1022
+ },
1023
+ children: "NOTE: This error only displays during local development."
1024
+ })]
1025
+ });
1026
+ }
1027
+ function useErrorToast() {
1028
+ const { addToast } = useToast();
1029
+ return (0, react.useCallback)((errors) => {
1030
+ addToast({
1031
+ type: "error",
1032
+ id: errors.map((err) => {
1033
+ var _err$extensions;
1034
+ const message = "extensions" in err ? ((_err$extensions = err.extensions) === null || _err$extensions === void 0 || (_err$extensions = _err$extensions.originalError) === null || _err$extensions === void 0 ? void 0 : _err$extensions.message) || err.message : err.message;
1035
+ const stack = err.stack || "";
1036
+ return btoa(message + stack).slice(0, 32);
1037
+ }).join("|"),
1038
+ message: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ErrorToast, { errors })
1039
+ });
1040
+ }, [addToast]);
1041
+ }
1042
+ function useAsyncCallback(callback, deps) {
1043
+ const addErrorToast = useErrorToast();
1044
+ return (0, react.useCallback)(async (...args) => {
1045
+ try {
1046
+ return await callback(...args);
1047
+ } catch (error) {
1048
+ console.error("Error in async callback:", error);
1049
+ addErrorToast([error]);
1050
+ throw error;
1051
+ }
1052
+ }, deps);
1053
+ }
1054
+
1055
+ //#endregion
1056
+ //#region src/components/error-boundary/error-boundary.tsx
1057
+ const statusChecker = new StatusChecker();
1058
+ var CopilotErrorBoundary = class extends react.default.Component {
1059
+ constructor(props) {
1060
+ super(props);
1061
+ this.state = { hasError: false };
1062
+ }
1063
+ static getDerivedStateFromError(error) {
1064
+ return {
1065
+ hasError: true,
1066
+ error
1067
+ };
1068
+ }
1069
+ componentDidMount() {
1070
+ if (this.props.publicApiKey) statusChecker.start(this.props.publicApiKey, (newStatus) => {
1071
+ this.setState((prevState) => {
1072
+ var _prevState$status;
1073
+ if ((newStatus === null || newStatus === void 0 ? void 0 : newStatus.severity) !== ((_prevState$status = prevState.status) === null || _prevState$status === void 0 ? void 0 : _prevState$status.severity)) return { status: newStatus !== null && newStatus !== void 0 ? newStatus : void 0 };
1074
+ return null;
1075
+ });
1076
+ });
1077
+ }
1078
+ componentWillUnmount() {
1079
+ statusChecker.stop();
1080
+ }
1081
+ componentDidCatch(error, errorInfo) {
1082
+ console.error("CopilotKit Error:", error, errorInfo);
1083
+ }
1084
+ render() {
1085
+ if (this.state.hasError) {
1086
+ if (this.state.error instanceof _copilotkit_shared.CopilotKitError) {
1087
+ var _this$state$status$se, _this$state$status, _this$state$status$me, _this$state$status2;
1088
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [this.props.children, this.props.showUsageBanner && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(UsageBanner, {
1089
+ severity: (_this$state$status$se = (_this$state$status = this.state.status) === null || _this$state$status === void 0 ? void 0 : _this$state$status.severity) !== null && _this$state$status$se !== void 0 ? _this$state$status$se : this.state.error.severity,
1090
+ message: (_this$state$status$me = (_this$state$status2 = this.state.status) === null || _this$state$status2 === void 0 ? void 0 : _this$state$status2.message) !== null && _this$state$status$me !== void 0 ? _this$state$status$me : this.state.error.message,
1091
+ actions: getErrorActions(this.state.error)
1092
+ })] });
1093
+ }
1094
+ throw this.state.error;
1095
+ }
1096
+ return this.props.children;
1097
+ }
1098
+ };
1099
+
1100
+ //#endregion
1101
+ //#region src/context/coagent-state-renders-context.tsx
1102
+ const CoAgentStateRendersContext = (0, react.createContext)(void 0);
1103
+ function CoAgentStateRendersProvider({ children }) {
1104
+ const [coAgentStateRenders, setCoAgentStateRenders] = (0, react.useState)({});
1105
+ const setCoAgentStateRender = (0, react.useCallback)((id, stateRender) => {
1106
+ setCoAgentStateRenders((prevPoints) => ({
1107
+ ...prevPoints,
1108
+ [id]: stateRender
1109
+ }));
1110
+ }, []);
1111
+ const removeCoAgentStateRender = (0, react.useCallback)((id) => {
1112
+ setCoAgentStateRenders((prevPoints) => {
1113
+ const newPoints = { ...prevPoints };
1114
+ delete newPoints[id];
1115
+ return newPoints;
1116
+ });
1117
+ }, []);
1118
+ const claimsRef = (0, react.useRef)({});
1119
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CoAgentStateRendersContext.Provider, {
1120
+ value: {
1121
+ coAgentStateRenders,
1122
+ setCoAgentStateRender,
1123
+ removeCoAgentStateRender,
1124
+ claimsRef
1125
+ },
1126
+ children
1127
+ });
1128
+ }
1129
+ function useCoAgentStateRenders() {
1130
+ const context = (0, react.useContext)(CoAgentStateRendersContext);
1131
+ if (!context) throw new Error("useCoAgentStateRenders must be used within CoAgentStateRendersProvider");
1132
+ return context;
1133
+ }
1134
+
1135
+ //#endregion
1136
+ //#region src/context/threads-context.tsx
1137
+ const ThreadsContext = (0, react.createContext)(void 0);
1138
+ function ThreadsProvider({ children, threadId: explicitThreadId }) {
1139
+ const [internalThreadId, setThreadId] = (0, react.useState)(() => (0, _copilotkit_shared.randomUUID)());
1140
+ const threadId = explicitThreadId !== null && explicitThreadId !== void 0 ? explicitThreadId : internalThreadId;
1141
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ThreadsContext.Provider, {
1142
+ value: {
1143
+ threadId,
1144
+ setThreadId
1145
+ },
1146
+ children
1147
+ });
1148
+ }
1149
+ function useThreads() {
1150
+ const context = (0, react.useContext)(ThreadsContext);
1151
+ if (!context) throw new Error("useThreads must be used within ThreadsProvider");
1152
+ return context;
1153
+ }
1154
+
1155
+ //#endregion
1156
+ //#region src/hooks/use-coagent-state-render-bridge.helpers.ts
1157
+ let RenderStatus = /* @__PURE__ */ function(RenderStatus) {
1158
+ RenderStatus["InProgress"] = "inProgress";
1159
+ RenderStatus["Complete"] = "complete";
1160
+ return RenderStatus;
1161
+ }({});
1162
+ let ClaimAction = /* @__PURE__ */ function(ClaimAction) {
1163
+ ClaimAction["Create"] = "create";
1164
+ ClaimAction["Override"] = "override";
1165
+ ClaimAction["Existing"] = "existing";
1166
+ ClaimAction["Block"] = "block";
1167
+ return ClaimAction;
1168
+ }({});
1169
+ function getStateWithoutConstantKeys(state) {
1170
+ if (!state) return {};
1171
+ const { messages, tools, copilotkit, ...stateWithoutConstantKeys } = state;
1172
+ return stateWithoutConstantKeys;
1173
+ }
1174
+ function areStatesEquals(a, b) {
1175
+ if (a && !b || !a && b) return false;
1176
+ const { messages, tools, copilotkit, ...aWithoutConstantKeys } = a;
1177
+ const { messages: bMessages, tools: bTools, copilotkit: bCopilotkit, ...bWithoutConstantKeys } = b;
1178
+ return JSON.stringify(aWithoutConstantKeys) === JSON.stringify(bWithoutConstantKeys);
1179
+ }
1180
+ function isPlaceholderMessageId(messageId) {
1181
+ return !!messageId && messageId.startsWith("coagent-state-render-");
1182
+ }
1183
+ function isPlaceholderMessageName(messageName) {
1184
+ return messageName === "coagent-state-render";
1185
+ }
1186
+ function readCachedMessageEntry(entry) {
1187
+ if (!entry || typeof entry !== "object") return {
1188
+ snapshot: entry,
1189
+ runId: void 0
1190
+ };
1191
+ return {
1192
+ snapshot: "snapshot" in entry ? entry.snapshot : entry,
1193
+ runId: "runId" in entry ? entry.runId : void 0
1194
+ };
1195
+ }
1196
+ function getEffectiveRunId({ existingClaimRunId, cachedMessageRunId, runId }) {
1197
+ return existingClaimRunId || cachedMessageRunId || runId || "pending";
1198
+ }
1199
+ /**
1200
+ * Resolve whether a message can claim a render slot.
1201
+ * This is a pure decision function; the caller applies claim mutations.
1202
+ */
1203
+ function resolveClaim({ claims, context, stateSnapshot }) {
1204
+ const { messageId, stateRenderId, runId, messageIndex } = context;
1205
+ const existing = claims[messageId];
1206
+ if (existing) {
1207
+ const canRender = existing.stateRenderId === stateRenderId;
1208
+ const shouldUpdateRunId = canRender && runId && (!existing.runId || existing.runId === "pending");
1209
+ return {
1210
+ canRender,
1211
+ action: canRender ? ClaimAction.Existing : ClaimAction.Block,
1212
+ updateRunId: shouldUpdateRunId ? runId : void 0
1213
+ };
1214
+ }
1215
+ const normalizedRunId = runId !== null && runId !== void 0 ? runId : "pending";
1216
+ const renderClaimedByOtherMessageEntry = Object.entries(claims).find(([, claim]) => {
1217
+ var _claim$runId;
1218
+ return claim.stateRenderId === stateRenderId && ((_claim$runId = claim.runId) !== null && _claim$runId !== void 0 ? _claim$runId : "pending") === normalizedRunId && (0, _copilotkit_shared.dataToUUID)(getStateWithoutConstantKeys(claim.stateSnapshot)) === (0, _copilotkit_shared.dataToUUID)(getStateWithoutConstantKeys(stateSnapshot));
1219
+ });
1220
+ const renderClaimedByOtherMessage = renderClaimedByOtherMessageEntry === null || renderClaimedByOtherMessageEntry === void 0 ? void 0 : renderClaimedByOtherMessageEntry[1];
1221
+ const claimedMessageId = renderClaimedByOtherMessageEntry === null || renderClaimedByOtherMessageEntry === void 0 ? void 0 : renderClaimedByOtherMessageEntry[0];
1222
+ if (renderClaimedByOtherMessage) {
1223
+ if (messageIndex !== void 0 && renderClaimedByOtherMessage.messageIndex !== void 0 && messageIndex > renderClaimedByOtherMessage.messageIndex) return {
1224
+ canRender: true,
1225
+ action: ClaimAction.Override,
1226
+ nextClaim: {
1227
+ stateRenderId,
1228
+ runId,
1229
+ messageIndex
1230
+ },
1231
+ lockOthers: runId === renderClaimedByOtherMessage.runId || isPlaceholderMessageId(claimedMessageId)
1232
+ };
1233
+ if (runId && renderClaimedByOtherMessage.runId && runId !== renderClaimedByOtherMessage.runId) return {
1234
+ canRender: true,
1235
+ action: ClaimAction.Override,
1236
+ nextClaim: {
1237
+ stateRenderId,
1238
+ runId,
1239
+ messageIndex
1240
+ },
1241
+ lockOthers: isPlaceholderMessageId(claimedMessageId)
1242
+ };
1243
+ if (isPlaceholderMessageId(claimedMessageId)) return {
1244
+ canRender: true,
1245
+ action: ClaimAction.Override,
1246
+ nextClaim: {
1247
+ stateRenderId,
1248
+ runId,
1249
+ messageIndex
1250
+ },
1251
+ lockOthers: true
1252
+ };
1253
+ if (stateSnapshot && renderClaimedByOtherMessage.stateSnapshot && !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, stateSnapshot)) return {
1254
+ canRender: true,
1255
+ action: ClaimAction.Override,
1256
+ nextClaim: {
1257
+ stateRenderId,
1258
+ runId
1259
+ }
1260
+ };
1261
+ return {
1262
+ canRender: false,
1263
+ action: ClaimAction.Block
1264
+ };
1265
+ }
1266
+ if (!runId) return {
1267
+ canRender: false,
1268
+ action: ClaimAction.Block
1269
+ };
1270
+ return {
1271
+ canRender: true,
1272
+ action: ClaimAction.Create,
1273
+ nextClaim: {
1274
+ stateRenderId,
1275
+ runId,
1276
+ messageIndex
1277
+ }
1278
+ };
1279
+ }
1280
+ /**
1281
+ * Select the best snapshot to render for this message.
1282
+ * Priority order is:
1283
+ * 1) explicit message snapshot
1284
+ * 2) live agent state (latest assistant only)
1285
+ * 3) cached snapshot for message
1286
+ * 4) cached snapshot for stateRenderId+runId
1287
+ * 5) last cached snapshot for stateRenderId
1288
+ */
1289
+ function selectSnapshot({ messageId, messageName, allowLiveState, skipLatestCache, stateRenderId, effectiveRunId, stateSnapshotProp, agentState, agentMessages, existingClaim, caches }) {
1290
+ var _reverse$find, _agentMessages$messag, _existingClaim$stateS, _existingClaim$stateS2;
1291
+ const lastAssistantId = agentMessages ? (_reverse$find = [...agentMessages].reverse().find((msg) => msg.role === "assistant")) === null || _reverse$find === void 0 ? void 0 : _reverse$find.id : void 0;
1292
+ const latestSnapshot = stateRenderId !== void 0 ? caches.byStateRenderAndRun[`${stateRenderId}::latest`] : void 0;
1293
+ const messageIndex = agentMessages ? agentMessages.findIndex((msg) => msg.id === messageId) : -1;
1294
+ const messageRole = messageIndex >= 0 && agentMessages ? (_agentMessages$messag = agentMessages[messageIndex]) === null || _agentMessages$messag === void 0 ? void 0 : _agentMessages$messag.role : void 0;
1295
+ let previousUserMessageId;
1296
+ if (messageIndex > 0 && agentMessages) for (let i = messageIndex - 1; i >= 0; i -= 1) {
1297
+ var _agentMessages$i;
1298
+ if (((_agentMessages$i = agentMessages[i]) === null || _agentMessages$i === void 0 ? void 0 : _agentMessages$i.role) === "user") {
1299
+ var _agentMessages$i2;
1300
+ previousUserMessageId = (_agentMessages$i2 = agentMessages[i]) === null || _agentMessages$i2 === void 0 ? void 0 : _agentMessages$i2.id;
1301
+ break;
1302
+ }
1303
+ }
1304
+ const liveStateIsStale = stateSnapshotProp === void 0 && latestSnapshot !== void 0 && agentState !== void 0 && areStatesEquals(latestSnapshot, agentState);
1305
+ const shouldUseLiveState = (Boolean(allowLiveState) || !lastAssistantId || messageId === lastAssistantId) && !liveStateIsStale;
1306
+ const snapshot = stateSnapshotProp ? (0, _copilotkit_shared.parseJson)(stateSnapshotProp, stateSnapshotProp) : shouldUseLiveState ? agentState : void 0;
1307
+ const hasSnapshotKeys = !!(snapshot && Object.keys(snapshot).length > 0);
1308
+ const allowEmptySnapshot = snapshot !== void 0 && !hasSnapshotKeys && (stateSnapshotProp !== void 0 || shouldUseLiveState);
1309
+ const messageCacheEntry = caches.byMessageId[messageId];
1310
+ const cachedMessageSnapshot = readCachedMessageEntry(messageCacheEntry).snapshot;
1311
+ const cacheKey = stateRenderId !== void 0 ? `${stateRenderId}::${effectiveRunId}` : void 0;
1312
+ let cachedSnapshot = cachedMessageSnapshot !== null && cachedMessageSnapshot !== void 0 ? cachedMessageSnapshot : caches.byMessageId[messageId];
1313
+ if (cachedSnapshot === void 0 && cacheKey && caches.byStateRenderAndRun[cacheKey] !== void 0) cachedSnapshot = caches.byStateRenderAndRun[cacheKey];
1314
+ if (cachedSnapshot === void 0 && stateRenderId && previousUserMessageId && caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`] !== void 0) cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`];
1315
+ if (cachedSnapshot === void 0 && !skipLatestCache && stateRenderId && messageRole !== "assistant" && (stateSnapshotProp !== void 0 || agentState && Object.keys(agentState).length > 0)) cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::latest`];
1316
+ const snapshotForClaim = (existingClaim === null || existingClaim === void 0 ? void 0 : existingClaim.locked) ? (_existingClaim$stateS = existingClaim.stateSnapshot) !== null && _existingClaim$stateS !== void 0 ? _existingClaim$stateS : cachedSnapshot : hasSnapshotKeys ? snapshot : (_existingClaim$stateS2 = existingClaim === null || existingClaim === void 0 ? void 0 : existingClaim.stateSnapshot) !== null && _existingClaim$stateS2 !== void 0 ? _existingClaim$stateS2 : cachedSnapshot;
1317
+ return {
1318
+ snapshot,
1319
+ hasSnapshotKeys,
1320
+ cachedSnapshot,
1321
+ allowEmptySnapshot,
1322
+ snapshotForClaim
1323
+ };
1324
+ }
1325
+
1326
+ //#endregion
1327
+ //#region src/hooks/use-coagent-state-render-registry.ts
1328
+ const LAST_SNAPSHOTS_BY_RENDER_AND_RUN = "__lastSnapshotsByStateRenderIdAndRun";
1329
+ const LAST_SNAPSHOTS_BY_MESSAGE = "__lastSnapshotsByMessageId";
1330
+ function getClaimsStore(claimsRef) {
1331
+ return claimsRef.current;
1332
+ }
1333
+ function getSnapshotCaches(claimsRef) {
1334
+ var _store$LAST_SNAPSHOTS, _store$LAST_SNAPSHOTS2;
1335
+ const store = getClaimsStore(claimsRef);
1336
+ return {
1337
+ byStateRenderAndRun: (_store$LAST_SNAPSHOTS = store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN]) !== null && _store$LAST_SNAPSHOTS !== void 0 ? _store$LAST_SNAPSHOTS : {},
1338
+ byMessageId: (_store$LAST_SNAPSHOTS2 = store[LAST_SNAPSHOTS_BY_MESSAGE]) !== null && _store$LAST_SNAPSHOTS2 !== void 0 ? _store$LAST_SNAPSHOTS2 : {}
1339
+ };
1340
+ }
1341
+ function useStateRenderRegistry({ agentId, stateRenderId, message, messageIndex, stateSnapshot, agentState, agentMessages, claimsRef }) {
1342
+ var _store$LAST_SNAPSHOTS3, _claimsRef$current$me;
1343
+ const store = getClaimsStore(claimsRef);
1344
+ const runId = message.runId;
1345
+ const { runId: cachedMessageRunId } = readCachedMessageEntry((_store$LAST_SNAPSHOTS3 = store[LAST_SNAPSHOTS_BY_MESSAGE]) === null || _store$LAST_SNAPSHOTS3 === void 0 ? void 0 : _store$LAST_SNAPSHOTS3[message.id]);
1346
+ const effectiveRunId = getEffectiveRunId({
1347
+ existingClaimRunId: (_claimsRef$current$me = claimsRef.current[message.id]) === null || _claimsRef$current$me === void 0 ? void 0 : _claimsRef$current$me.runId,
1348
+ cachedMessageRunId,
1349
+ runId
1350
+ });
1351
+ (0, react.useEffect)(() => {
1352
+ return () => {
1353
+ const existingClaim = claimsRef.current[message.id];
1354
+ if ((existingClaim === null || existingClaim === void 0 ? void 0 : existingClaim.stateSnapshot) && Object.keys(existingClaim.stateSnapshot).length > 0) {
1355
+ var _store$LAST_SNAPSHOTS4, _existingClaim$runId, _store$LAST_SNAPSHOTS5, _existingClaim$runId2;
1356
+ const snapshotCache = { ...(_store$LAST_SNAPSHOTS4 = store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN]) !== null && _store$LAST_SNAPSHOTS4 !== void 0 ? _store$LAST_SNAPSHOTS4 : {} };
1357
+ const cacheKey = `${existingClaim.stateRenderId}::${(_existingClaim$runId = existingClaim.runId) !== null && _existingClaim$runId !== void 0 ? _existingClaim$runId : "pending"}`;
1358
+ snapshotCache[cacheKey] = existingClaim.stateSnapshot;
1359
+ snapshotCache[`${existingClaim.stateRenderId}::latest`] = existingClaim.stateSnapshot;
1360
+ store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
1361
+ const messageCache = { ...(_store$LAST_SNAPSHOTS5 = store[LAST_SNAPSHOTS_BY_MESSAGE]) !== null && _store$LAST_SNAPSHOTS5 !== void 0 ? _store$LAST_SNAPSHOTS5 : {} };
1362
+ messageCache[message.id] = {
1363
+ snapshot: existingClaim.stateSnapshot,
1364
+ runId: (_existingClaim$runId2 = existingClaim.runId) !== null && _existingClaim$runId2 !== void 0 ? _existingClaim$runId2 : effectiveRunId
1365
+ };
1366
+ store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
1367
+ }
1368
+ delete claimsRef.current[message.id];
1369
+ };
1370
+ }, [
1371
+ claimsRef,
1372
+ effectiveRunId,
1373
+ message.id
1374
+ ]);
1375
+ if (!stateRenderId) return { canRender: false };
1376
+ const caches = getSnapshotCaches(claimsRef);
1377
+ const existingClaim = claimsRef.current[message.id];
1378
+ const { snapshot, hasSnapshotKeys, allowEmptySnapshot, snapshotForClaim } = selectSnapshot({
1379
+ messageId: message.id,
1380
+ messageName: message.name,
1381
+ allowLiveState: isPlaceholderMessageName(message.name) || isPlaceholderMessageId(message.id),
1382
+ skipLatestCache: isPlaceholderMessageName(message.name) || isPlaceholderMessageId(message.id),
1383
+ stateRenderId,
1384
+ effectiveRunId,
1385
+ stateSnapshotProp: stateSnapshot,
1386
+ agentState,
1387
+ agentMessages,
1388
+ existingClaim,
1389
+ caches
1390
+ });
1391
+ const resolution = resolveClaim({
1392
+ claims: claimsRef.current,
1393
+ context: {
1394
+ agentId,
1395
+ messageId: message.id,
1396
+ stateRenderId,
1397
+ runId: effectiveRunId,
1398
+ messageIndex
1399
+ },
1400
+ stateSnapshot: snapshotForClaim
1401
+ });
1402
+ if (resolution.action === ClaimAction.Block) return { canRender: false };
1403
+ if (resolution.updateRunId && claimsRef.current[message.id]) claimsRef.current[message.id].runId = resolution.updateRunId;
1404
+ if (resolution.nextClaim) claimsRef.current[message.id] = resolution.nextClaim;
1405
+ if (resolution.lockOthers) Object.entries(claimsRef.current).forEach(([id, claim]) => {
1406
+ if (id !== message.id && claim.stateRenderId === stateRenderId) claim.locked = true;
1407
+ });
1408
+ if (existingClaim && !existingClaim.locked && (agentMessages === null || agentMessages === void 0 ? void 0 : agentMessages.length)) {
1409
+ const indexInAgentMessages = agentMessages.findIndex((msg) => msg.id === message.id);
1410
+ if (indexInAgentMessages >= 0 && indexInAgentMessages < agentMessages.length - 1) existingClaim.locked = true;
1411
+ }
1412
+ const existingSnapshot = claimsRef.current[message.id].stateSnapshot;
1413
+ const snapshotChanged = stateSnapshot && existingSnapshot !== void 0 && !areStatesEquals(existingSnapshot, snapshot);
1414
+ if (snapshot && (stateSnapshot || hasSnapshotKeys || allowEmptySnapshot) && (!claimsRef.current[message.id].locked || snapshotChanged)) {
1415
+ if (!claimsRef.current[message.id].locked || snapshotChanged) {
1416
+ var _store$LAST_SNAPSHOTS6, _store$LAST_SNAPSHOTS7;
1417
+ claimsRef.current[message.id].stateSnapshot = snapshot;
1418
+ const snapshotCache = { ...(_store$LAST_SNAPSHOTS6 = store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN]) !== null && _store$LAST_SNAPSHOTS6 !== void 0 ? _store$LAST_SNAPSHOTS6 : {} };
1419
+ const cacheKey = `${stateRenderId}::${effectiveRunId}`;
1420
+ snapshotCache[cacheKey] = snapshot;
1421
+ snapshotCache[`${stateRenderId}::latest`] = snapshot;
1422
+ store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
1423
+ const messageCache = { ...(_store$LAST_SNAPSHOTS7 = store[LAST_SNAPSHOTS_BY_MESSAGE]) !== null && _store$LAST_SNAPSHOTS7 !== void 0 ? _store$LAST_SNAPSHOTS7 : {} };
1424
+ messageCache[message.id] = {
1425
+ snapshot,
1426
+ runId: effectiveRunId
1427
+ };
1428
+ store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
1429
+ if (stateSnapshot) claimsRef.current[message.id].locked = true;
1430
+ }
1431
+ } else if (snapshotForClaim) {
1432
+ if (!claimsRef.current[message.id].stateSnapshot) {
1433
+ var _store$LAST_SNAPSHOTS8, _store$LAST_SNAPSHOTS9;
1434
+ claimsRef.current[message.id].stateSnapshot = snapshotForClaim;
1435
+ const snapshotCache = { ...(_store$LAST_SNAPSHOTS8 = store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN]) !== null && _store$LAST_SNAPSHOTS8 !== void 0 ? _store$LAST_SNAPSHOTS8 : {} };
1436
+ const cacheKey = `${stateRenderId}::${effectiveRunId}`;
1437
+ snapshotCache[cacheKey] = snapshotForClaim;
1438
+ snapshotCache[`${stateRenderId}::latest`] = snapshotForClaim;
1439
+ store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
1440
+ const messageCache = { ...(_store$LAST_SNAPSHOTS9 = store[LAST_SNAPSHOTS_BY_MESSAGE]) !== null && _store$LAST_SNAPSHOTS9 !== void 0 ? _store$LAST_SNAPSHOTS9 : {} };
1441
+ messageCache[message.id] = {
1442
+ snapshot: snapshotForClaim,
1443
+ runId: effectiveRunId
1444
+ };
1445
+ store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
1446
+ }
1447
+ }
1448
+ return { canRender: true };
1449
+ }
1450
+
1451
+ //#endregion
1452
+ //#region src/hooks/use-coagent-state-render-bridge.tsx
1453
+ function useCoagentStateRenderBridge(agentId, props) {
1454
+ var _props$runId;
1455
+ const { stateSnapshot, message } = props;
1456
+ const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();
1457
+ const { agent } = (0, _copilotkitnext_react.useAgent)({ agentId });
1458
+ const [nodeName, setNodeName] = (0, react.useState)(void 0);
1459
+ const [, forceUpdate] = (0, react.useState)(0);
1460
+ (0, react.useEffect)(() => {
1461
+ if (!agent) return;
1462
+ const { unsubscribe } = agent.subscribe({
1463
+ onStateChanged: () => {
1464
+ forceUpdate((value) => value + 1);
1465
+ },
1466
+ onStepStartedEvent: ({ event }) => {
1467
+ if (event.stepName !== nodeName) setNodeName(event.stepName);
1468
+ },
1469
+ onStepFinishedEvent: ({ event }) => {
1470
+ if (event.stepName === nodeName) setNodeName(void 0);
1471
+ }
1472
+ });
1473
+ return () => {
1474
+ unsubscribe();
1475
+ };
1476
+ }, [agentId, nodeName]);
1477
+ const getStateRender = (0, react.useCallback)((messageId) => {
1478
+ return Object.entries(coAgentStateRenders).find(([stateRenderId, stateRender]) => {
1479
+ if (claimsRef.current[messageId]) return stateRenderId === claimsRef.current[messageId].stateRenderId;
1480
+ const matchingAgentName = stateRender.name === agentId;
1481
+ const matchesNodeContext = stateRender.nodeName ? stateRender.nodeName === nodeName : true;
1482
+ return matchingAgentName && matchesNodeContext;
1483
+ });
1484
+ }, [
1485
+ coAgentStateRenders,
1486
+ nodeName,
1487
+ agentId
1488
+ ]);
1489
+ const stateRenderEntry = (0, react.useMemo)(() => getStateRender(message.id), [getStateRender, message.id]);
1490
+ const stateRenderId = stateRenderEntry === null || stateRenderEntry === void 0 ? void 0 : stateRenderEntry[0];
1491
+ const stateRender = stateRenderEntry === null || stateRenderEntry === void 0 ? void 0 : stateRenderEntry[1];
1492
+ const { canRender } = useStateRenderRegistry({
1493
+ agentId,
1494
+ stateRenderId,
1495
+ message: {
1496
+ ...message,
1497
+ runId: (_props$runId = props.runId) !== null && _props$runId !== void 0 ? _props$runId : message.runId
1498
+ },
1499
+ messageIndex: props.messageIndex,
1500
+ stateSnapshot,
1501
+ agentState: agent === null || agent === void 0 ? void 0 : agent.state,
1502
+ agentMessages: agent === null || agent === void 0 ? void 0 : agent.messages,
1503
+ claimsRef
1504
+ });
1505
+ return (0, react.useMemo)(() => {
1506
+ if (!stateRender || !stateRenderId) return null;
1507
+ if (!canRender) return null;
1508
+ if (stateRender.handler) {
1509
+ var _agent$state;
1510
+ stateRender.handler({
1511
+ state: stateSnapshot ? (0, _copilotkit_shared.parseJson)(stateSnapshot, stateSnapshot) : (_agent$state = agent === null || agent === void 0 ? void 0 : agent.state) !== null && _agent$state !== void 0 ? _agent$state : {},
1512
+ nodeName: nodeName !== null && nodeName !== void 0 ? nodeName : ""
1513
+ });
1514
+ }
1515
+ if (stateRender.render) {
1516
+ var _claimsRef$current$me;
1517
+ const status = (agent === null || agent === void 0 ? void 0 : agent.isRunning) ? RenderStatus.InProgress : RenderStatus.Complete;
1518
+ if (typeof stateRender.render === "string") return stateRender.render;
1519
+ return stateRender.render({
1520
+ status,
1521
+ state: (_claimsRef$current$me = claimsRef.current[message.id].stateSnapshot) !== null && _claimsRef$current$me !== void 0 ? _claimsRef$current$me : {},
1522
+ nodeName: nodeName !== null && nodeName !== void 0 ? nodeName : ""
1523
+ });
1524
+ }
1525
+ }, [
1526
+ stateRender,
1527
+ stateRenderId,
1528
+ agent === null || agent === void 0 ? void 0 : agent.state,
1529
+ agent === null || agent === void 0 ? void 0 : agent.isRunning,
1530
+ nodeName,
1531
+ message.id,
1532
+ stateSnapshot,
1533
+ canRender
1534
+ ]);
1535
+ }
1536
+ function CoAgentStateRenderBridge(props) {
1537
+ return useCoagentStateRenderBridge(props.agentId, props);
1538
+ }
1539
+
1540
+ //#endregion
1541
+ //#region src/components/CopilotListeners.tsx
1542
+ const usePredictStateSubscription = (agent) => {
1543
+ const predictStateToolsRef = (0, react.useRef)([]);
1544
+ const getSubscriber = (0, react.useCallback)((agent) => ({
1545
+ onCustomEvent: ({ event }) => {
1546
+ if (event.name === "PredictState") predictStateToolsRef.current = event.value;
1547
+ },
1548
+ onToolCallArgsEvent: ({ partialToolCallArgs, toolCallName }) => {
1549
+ predictStateToolsRef.current.forEach((t) => {
1550
+ if ((t === null || t === void 0 ? void 0 : t.tool) !== toolCallName) return;
1551
+ const emittedState = typeof partialToolCallArgs === "string" ? (0, _copilotkit_shared.parseJson)(partialToolCallArgs, partialToolCallArgs) : partialToolCallArgs;
1552
+ agent.setState({ [t.state_key]: emittedState[t.state_key] });
1553
+ });
1554
+ }
1555
+ }), []);
1556
+ (0, react.useEffect)(() => {
1557
+ if (!agent) return;
1558
+ const subscriber = getSubscriber(agent);
1559
+ const { unsubscribe } = agent.subscribe(subscriber);
1560
+ return () => {
1561
+ unsubscribe();
1562
+ };
1563
+ }, [agent, getSubscriber]);
1564
+ };
1565
+ function CopilotListeners() {
1566
+ const { copilotkit } = (0, _copilotkitnext_react.useCopilotKit)();
1567
+ const existingConfig = (0, _copilotkitnext_react.useCopilotChatConfiguration)();
1568
+ const resolvedAgentId = existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.agentId;
1569
+ const { setBannerError } = useToast();
1570
+ const { agent } = (0, _copilotkitnext_react.useAgent)({ agentId: resolvedAgentId });
1571
+ usePredictStateSubscription(agent);
1572
+ (0, react.useEffect)(() => {
1573
+ const subscription = copilotkit.subscribe({ onError: ({ error }) => {
1574
+ setBannerError(new _copilotkit_shared.CopilotKitLowLevelError({
1575
+ error,
1576
+ message: error.message,
1577
+ url: typeof window !== "undefined" ? window.location.href : ""
1578
+ }));
1579
+ } });
1580
+ return () => {
1581
+ subscription.unsubscribe();
1582
+ };
1583
+ }, [copilotkit === null || copilotkit === void 0 ? void 0 : copilotkit.subscribe]);
1584
+ return null;
1585
+ }
1586
+
1587
+ //#endregion
1588
+ //#region src/components/copilot-provider/copilotkit.tsx
1589
+ /**
1590
+ * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.
1591
+ *
1592
+ * ## Example
1593
+ *
1594
+ * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).
1595
+ *
1596
+ * ```tsx
1597
+ * import { CopilotKit } from "@copilotkit/react-core";
1598
+ *
1599
+ * <CopilotKit runtimeUrl="<your-runtime-url>">
1600
+ * // ... your app ...
1601
+ * </CopilotKit>
1602
+ * ```
1603
+ */
1604
+ function CopilotKit({ children, ...props }) {
1605
+ const enabled = shouldShowDevConsole(props.showDevConsole);
1606
+ const showInspector = shouldShowDevConsole(props.enableInspector);
1607
+ const publicApiKey = props.publicApiKey || props.publicLicenseKey;
1608
+ const renderArr = (0, react.useMemo)(() => [{ render: CoAgentStateRenderBridge }], []);
1609
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToastProvider, {
1610
+ enabled,
1611
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotErrorBoundary, {
1612
+ publicApiKey,
1613
+ showUsageBanner: enabled,
1614
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ThreadsProvider, {
1615
+ threadId: props.threadId,
1616
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_copilotkitnext_react.CopilotKitProvider, {
1617
+ ...props,
1618
+ showDevConsole: showInspector,
1619
+ renderCustomMessages: renderArr,
1620
+ useSingleEndpoint: true,
1621
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitInternal, {
1622
+ ...props,
1623
+ children
1624
+ })
1625
+ })
1626
+ })
1627
+ })
1628
+ });
1629
+ }
1630
+ /**
1631
+ * Bridge component that subscribes to v2.x copilotkit core error events
1632
+ * and forwards them to v1.x error handling system.
1633
+ * This ensures only ONE subscription exists regardless of how many times
1634
+ * Chat components are rendered.
1635
+ */
1636
+ function CopilotKitErrorBridge() {
1637
+ const { copilotkit } = (0, _copilotkitnext_react.useCopilotKit)();
1638
+ const { onError, copilotApiConfig } = useCopilotContext();
1639
+ (0, react.useEffect)(() => {
1640
+ if (!copilotkit) return;
1641
+ const subscription = copilotkit.subscribe({ onError: async (event) => {
1642
+ const errorEvent = {
1643
+ type: "error",
1644
+ timestamp: Date.now(),
1645
+ context: {
1646
+ source: "agent",
1647
+ request: {
1648
+ operation: event.code || "unknown",
1649
+ url: copilotApiConfig === null || copilotApiConfig === void 0 ? void 0 : copilotApiConfig.chatApiEndpoint,
1650
+ startTime: Date.now()
1651
+ },
1652
+ technical: {
1653
+ environment: "browser",
1654
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
1655
+ stackTrace: event.error.stack
1656
+ },
1657
+ ...event.context
1658
+ },
1659
+ error: event.error
1660
+ };
1661
+ try {
1662
+ await onError(errorEvent);
1663
+ } catch (handlerError) {
1664
+ console.error("Error in onError handler:", handlerError);
1665
+ }
1666
+ } });
1667
+ return () => {
1668
+ subscription.unsubscribe();
1669
+ };
1670
+ }, [
1671
+ copilotkit,
1672
+ onError,
1673
+ copilotApiConfig
1674
+ ]);
1675
+ return null;
1676
+ }
1677
+ function CopilotKitInternal(cpkProps) {
1678
+ var _props$agent2;
1679
+ const { children, ...props } = cpkProps;
1680
+ /**
1681
+ * This will throw an error if the props are invalid.
1682
+ */
1683
+ validateProps(cpkProps);
1684
+ const publicApiKey = props.publicLicenseKey || props.publicApiKey;
1685
+ const chatApiEndpoint = props.runtimeUrl || _copilotkit_shared.COPILOT_CLOUD_CHAT_URL;
1686
+ const [actions, setActions] = (0, react.useState)({});
1687
+ const [registeredActionConfigs, setRegisteredActionConfigs] = (0, react.useState)(/* @__PURE__ */ new Map());
1688
+ const chatComponentsCache = (0, react.useRef)({
1689
+ actions: {},
1690
+ coAgentStateRenders: {}
1691
+ });
1692
+ const { addElement, removeElement, printTree, getAllElements } = useTree();
1693
+ const [isLoading, setIsLoading] = (0, react.useState)(false);
1694
+ const [chatInstructions, setChatInstructions] = (0, react.useState)("");
1695
+ const [authStates, setAuthStates] = (0, react.useState)({});
1696
+ const [extensions, setExtensions] = (0, react.useState)({});
1697
+ const [additionalInstructions, setAdditionalInstructions] = (0, react.useState)([]);
1698
+ const { addElement: addDocument, removeElement: removeDocument, allElements: allDocuments } = useFlatCategoryStore();
1699
+ const setAction = (0, react.useCallback)((id, action) => {
1700
+ setActions((prevPoints) => {
1701
+ return {
1702
+ ...prevPoints,
1703
+ [id]: action
1704
+ };
1705
+ });
1706
+ }, []);
1707
+ const removeAction = (0, react.useCallback)((id) => {
1708
+ setActions((prevPoints) => {
1709
+ const newPoints = { ...prevPoints };
1710
+ delete newPoints[id];
1711
+ return newPoints;
1712
+ });
1713
+ }, []);
1714
+ const getContextString = (0, react.useCallback)((documents, categories) => {
1715
+ return `${documents.map((document) => {
1716
+ return `${document.name} (${document.sourceApplication}):\n${document.getContents()}`;
1717
+ }).join("\n\n")}\n\n${printTree(categories)}`;
1718
+ }, [printTree]);
1719
+ const addContext = (0, react.useCallback)((context, parentId, categories = defaultCopilotContextCategories) => {
1720
+ return addElement(context, categories, parentId);
1721
+ }, [addElement]);
1722
+ const removeContext = (0, react.useCallback)((id) => {
1723
+ removeElement(id);
1724
+ }, [removeElement]);
1725
+ const getAllContext = (0, react.useCallback)(() => {
1726
+ return getAllElements();
1727
+ }, [getAllElements]);
1728
+ const getFunctionCallHandler = (0, react.useCallback)((customEntryPoints) => {
1729
+ return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));
1730
+ }, [actions]);
1731
+ const getDocumentsContext = (0, react.useCallback)((categories) => {
1732
+ return allDocuments(categories);
1733
+ }, [allDocuments]);
1734
+ const addDocumentContext = (0, react.useCallback)((documentPointer, categories = defaultCopilotContextCategories) => {
1735
+ return addDocument(documentPointer, categories);
1736
+ }, [addDocument]);
1737
+ const removeDocumentContext = (0, react.useCallback)((documentId) => {
1738
+ removeDocument(documentId);
1739
+ }, [removeDocument]);
1740
+ const copilotApiConfig = (0, react.useMemo)(() => {
1741
+ let cloud = void 0;
1742
+ if (publicApiKey) {
1743
+ var _props$guardrails_c, _props$guardrails_c2;
1744
+ cloud = { guardrails: { input: { restrictToTopic: {
1745
+ enabled: Boolean(props.guardrails_c),
1746
+ validTopics: ((_props$guardrails_c = props.guardrails_c) === null || _props$guardrails_c === void 0 ? void 0 : _props$guardrails_c.validTopics) || [],
1747
+ invalidTopics: ((_props$guardrails_c2 = props.guardrails_c) === null || _props$guardrails_c2 === void 0 ? void 0 : _props$guardrails_c2.invalidTopics) || []
1748
+ } } } };
1749
+ }
1750
+ return {
1751
+ publicApiKey,
1752
+ ...cloud ? { cloud } : {},
1753
+ chatApiEndpoint,
1754
+ headers: props.headers || {},
1755
+ properties: props.properties || {},
1756
+ transcribeAudioUrl: props.transcribeAudioUrl,
1757
+ textToSpeechUrl: props.textToSpeechUrl,
1758
+ credentials: props.credentials
1759
+ };
1760
+ }, [
1761
+ publicApiKey,
1762
+ props.headers,
1763
+ props.properties,
1764
+ props.transcribeAudioUrl,
1765
+ props.textToSpeechUrl,
1766
+ props.credentials,
1767
+ props.cloudRestrictToTopic,
1768
+ props.guardrails_c
1769
+ ]);
1770
+ (0, react.useMemo)(() => {
1771
+ const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {
1772
+ if (state.status === "authenticated" && state.authHeaders) return {
1773
+ ...acc,
1774
+ ...Object.entries(state.authHeaders).reduce((headers, [key, value]) => ({
1775
+ ...headers,
1776
+ [key.startsWith("X-Custom-") ? key : `X-Custom-${key}`]: value
1777
+ }), {})
1778
+ };
1779
+ return acc;
1780
+ }, {});
1781
+ return {
1782
+ ...copilotApiConfig.headers || {},
1783
+ ...copilotApiConfig.publicApiKey ? { [_copilotkit_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey } : {},
1784
+ ...authHeaders
1785
+ };
1786
+ }, [
1787
+ copilotApiConfig.headers,
1788
+ copilotApiConfig.publicApiKey,
1789
+ authStates
1790
+ ]);
1791
+ const [internalErrorHandlers, _setInternalErrorHandler] = (0, react.useState)({});
1792
+ const setInternalErrorHandler = (0, react.useCallback)((handler) => {
1793
+ _setInternalErrorHandler((prev) => ({
1794
+ ...prev,
1795
+ ...handler
1796
+ }));
1797
+ }, []);
1798
+ const removeInternalErrorHandler = (0, react.useCallback)((key) => {
1799
+ _setInternalErrorHandler((prev) => {
1800
+ const { [key]: _removed, ...rest } = prev;
1801
+ return rest;
1802
+ });
1803
+ }, []);
1804
+ const onErrorRef = (0, react.useRef)(props.onError);
1805
+ (0, react.useEffect)(() => {
1806
+ onErrorRef.current = props.onError;
1807
+ }, [props.onError]);
1808
+ const internalHandlersRef = (0, react.useRef)({});
1809
+ (0, react.useEffect)(() => {
1810
+ internalHandlersRef.current = internalErrorHandlers;
1811
+ }, [internalErrorHandlers]);
1812
+ const handleErrors = (0, react.useCallback)(async (error) => {
1813
+ if (copilotApiConfig.publicApiKey && onErrorRef.current) try {
1814
+ await onErrorRef.current(error);
1815
+ } catch (e) {
1816
+ console.error("Error in public onError handler:", e);
1817
+ }
1818
+ const handlers = Object.values(internalHandlersRef.current);
1819
+ await Promise.all(handlers.map((h) => Promise.resolve(h(error)).catch((e) => console.error("Error in internal error handler:", e))));
1820
+ }, [copilotApiConfig.publicApiKey]);
1821
+ const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = (0, react.useState)({});
1822
+ const addChatSuggestionConfiguration = (0, react.useCallback)((id, suggestion) => {
1823
+ setChatSuggestionConfiguration((prev) => ({
1824
+ ...prev,
1825
+ [id]: suggestion
1826
+ }));
1827
+ }, [setChatSuggestionConfiguration]);
1828
+ const removeChatSuggestionConfiguration = (0, react.useCallback)((id) => {
1829
+ setChatSuggestionConfiguration((prev) => {
1830
+ const { [id]: _, ...rest } = prev;
1831
+ return rest;
1832
+ });
1833
+ }, [setChatSuggestionConfiguration]);
1834
+ const [availableAgents, setAvailableAgents] = (0, react.useState)([]);
1835
+ const [coagentStates, setCoagentStates] = (0, react.useState)({});
1836
+ const coagentStatesRef = (0, react.useRef)({});
1837
+ const setCoagentStatesWithRef = (0, react.useCallback)((value) => {
1838
+ const newValue = typeof value === "function" ? value(coagentStatesRef.current) : value;
1839
+ coagentStatesRef.current = newValue;
1840
+ setCoagentStates((prev) => {
1841
+ return newValue;
1842
+ });
1843
+ }, []);
1844
+ let initialAgentSession = null;
1845
+ if (props.agent) initialAgentSession = { agentName: props.agent };
1846
+ const [agentSession, setAgentSession] = (0, react.useState)(initialAgentSession);
1847
+ (0, react.useEffect)(() => {
1848
+ if (props.agent) setAgentSession({ agentName: props.agent });
1849
+ else setAgentSession(null);
1850
+ }, [props.agent]);
1851
+ const { threadId, setThreadId: setInternalThreadId } = useThreads();
1852
+ const setThreadId = (0, react.useCallback)((value) => {
1853
+ if (props.threadId) throw new Error("Cannot call setThreadId() when threadId is provided via props.");
1854
+ setInternalThreadId(value);
1855
+ }, [props.threadId]);
1856
+ const [runId, setRunId] = (0, react.useState)(null);
1857
+ const chatAbortControllerRef = (0, react.useRef)(null);
1858
+ const showDevConsole = shouldShowDevConsole(props.showDevConsole);
1859
+ const [interruptActions, _setInterruptActions] = (0, react.useState)({});
1860
+ const setInterruptAction = (0, react.useCallback)((action) => {
1861
+ _setInterruptActions((prev) => {
1862
+ var _prev$action$id;
1863
+ if (action == null || !action.id) return prev;
1864
+ return {
1865
+ ...prev,
1866
+ [action.id]: {
1867
+ ...(_prev$action$id = prev[action.id]) !== null && _prev$action$id !== void 0 ? _prev$action$id : {},
1868
+ ...action
1869
+ }
1870
+ };
1871
+ });
1872
+ }, []);
1873
+ const removeInterruptAction = (0, react.useCallback)((actionId) => {
1874
+ _setInterruptActions((prev) => {
1875
+ const { [actionId]: _, ...rest } = prev;
1876
+ return rest;
1877
+ });
1878
+ }, []);
1879
+ const [interruptEventQueue, setInterruptEventQueue] = (0, react.useState)({});
1880
+ const addInterruptEvent = (0, react.useCallback)((queuedEvent) => {
1881
+ setInterruptEventQueue((prev) => {
1882
+ const threadQueue = prev[queuedEvent.threadId] || [];
1883
+ return {
1884
+ ...prev,
1885
+ [queuedEvent.threadId]: [...threadQueue, queuedEvent]
1886
+ };
1887
+ });
1888
+ }, []);
1889
+ const resolveInterruptEvent = (0, react.useCallback)((threadId, eventId, response) => {
1890
+ setInterruptEventQueue((prev) => {
1891
+ const threadQueue = prev[threadId] || [];
1892
+ return {
1893
+ ...prev,
1894
+ [threadId]: threadQueue.map((queuedEvent) => queuedEvent.eventId === eventId ? {
1895
+ ...queuedEvent,
1896
+ event: {
1897
+ ...queuedEvent.event,
1898
+ response
1899
+ }
1900
+ } : queuedEvent)
1901
+ };
1902
+ });
1903
+ }, []);
1904
+ const memoizedChildren = (0, react.useMemo)(() => children, [children]);
1905
+ const [bannerError, setBannerError] = (0, react.useState)(null);
1906
+ const agentLock = (0, react.useMemo)(() => {
1907
+ var _props$agent;
1908
+ return (_props$agent = props.agent) !== null && _props$agent !== void 0 ? _props$agent : null;
1909
+ }, [props.agent]);
1910
+ const forwardedParameters = (0, react.useMemo)(() => {
1911
+ var _props$forwardedParam;
1912
+ return (_props$forwardedParam = props.forwardedParameters) !== null && _props$forwardedParam !== void 0 ? _props$forwardedParam : {};
1913
+ }, [props.forwardedParameters]);
1914
+ const updateExtensions = (0, react.useCallback)((newExtensions) => {
1915
+ setExtensions((prev) => {
1916
+ const resolved = typeof newExtensions === "function" ? newExtensions(prev) : newExtensions;
1917
+ return Object.keys(resolved).length === Object.keys(prev).length && Object.entries(resolved).every(([key, value]) => prev[key] === value) ? prev : resolved;
1918
+ });
1919
+ }, [setExtensions]);
1920
+ const updateAuthStates = (0, react.useCallback)((newAuthStates) => {
1921
+ setAuthStates((prev) => {
1922
+ const resolved = typeof newAuthStates === "function" ? newAuthStates(prev) : newAuthStates;
1923
+ return Object.keys(resolved).length === Object.keys(prev).length && Object.entries(resolved).every(([key, value]) => prev[key] === value) ? prev : resolved;
1924
+ });
1925
+ }, [setAuthStates]);
1926
+ const handleSetRegisteredActions = (0, react.useCallback)((actionConfig) => {
1927
+ const key = actionConfig.action.name || (0, _copilotkit_shared.randomUUID)();
1928
+ setRegisteredActionConfigs((prev) => {
1929
+ const newMap = new Map(prev);
1930
+ newMap.set(key, actionConfig);
1931
+ return newMap;
1932
+ });
1933
+ return key;
1934
+ }, []);
1935
+ const handleRemoveRegisteredAction = (0, react.useCallback)((actionKey) => {
1936
+ setRegisteredActionConfigs((prev) => {
1937
+ const newMap = new Map(prev);
1938
+ newMap.delete(actionKey);
1939
+ return newMap;
1940
+ });
1941
+ }, []);
1942
+ const RegisteredActionsRenderer = (0, react.useMemo)(() => {
1943
+ return () => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: Array.from(registeredActionConfigs.entries()).map(([key, config]) => {
1944
+ const Component = config.component;
1945
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Component, { action: config.action }, key);
1946
+ }) });
1947
+ }, [registeredActionConfigs]);
1948
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_copilotkitnext_react.CopilotChatConfigurationProvider, {
1949
+ agentId: (_props$agent2 = props.agent) !== null && _props$agent2 !== void 0 ? _props$agent2 : "default",
1950
+ threadId,
1951
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CopilotContext.Provider, {
1952
+ value: {
1953
+ actions,
1954
+ chatComponentsCache,
1955
+ getFunctionCallHandler,
1956
+ setAction,
1957
+ removeAction,
1958
+ setRegisteredActions: handleSetRegisteredActions,
1959
+ removeRegisteredAction: handleRemoveRegisteredAction,
1960
+ getContextString,
1961
+ addContext,
1962
+ removeContext,
1963
+ getAllContext,
1964
+ getDocumentsContext,
1965
+ addDocumentContext,
1966
+ removeDocumentContext,
1967
+ copilotApiConfig,
1968
+ isLoading,
1969
+ setIsLoading,
1970
+ chatSuggestionConfiguration,
1971
+ addChatSuggestionConfiguration,
1972
+ removeChatSuggestionConfiguration,
1973
+ chatInstructions,
1974
+ setChatInstructions,
1975
+ additionalInstructions,
1976
+ setAdditionalInstructions,
1977
+ showDevConsole,
1978
+ coagentStates,
1979
+ setCoagentStates,
1980
+ coagentStatesRef,
1981
+ setCoagentStatesWithRef,
1982
+ agentSession,
1983
+ setAgentSession,
1984
+ forwardedParameters,
1985
+ agentLock,
1986
+ threadId,
1987
+ setThreadId,
1988
+ runId,
1989
+ setRunId,
1990
+ chatAbortControllerRef,
1991
+ availableAgents,
1992
+ authConfig_c: props.authConfig_c,
1993
+ authStates_c: authStates,
1994
+ setAuthStates_c: updateAuthStates,
1995
+ extensions,
1996
+ setExtensions: updateExtensions,
1997
+ interruptActions,
1998
+ setInterruptAction,
1999
+ removeInterruptAction,
2000
+ interruptEventQueue,
2001
+ addInterruptEvent,
2002
+ resolveInterruptEvent,
2003
+ bannerError,
2004
+ setBannerError,
2005
+ onError: handleErrors,
2006
+ internalErrorHandlers,
2007
+ setInternalErrorHandler,
2008
+ removeInternalErrorHandler
2009
+ },
2010
+ children: [
2011
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotListeners, {}),
2012
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitErrorBridge, {}),
2013
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CoAgentStateRendersProvider, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(MessagesTapProvider, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CopilotMessages, { children: [memoizedChildren, /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RegisteredActionsRenderer, {})] }) }), bannerError && showDevConsole && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(UsageBanner, {
2014
+ severity: bannerError.severity,
2015
+ message: bannerError.message,
2016
+ onClose: () => setBannerError(null),
2017
+ actions: getErrorActions(bannerError)
2018
+ })] })
2019
+ ]
2020
+ })
2021
+ });
2022
+ }
2023
+ const defaultCopilotContextCategories = ["global"];
2024
+ function entryPointsToFunctionCallHandler(actions) {
2025
+ return async ({ name, args }) => {
2026
+ let actionsByFunctionName = {};
2027
+ for (let action of actions) actionsByFunctionName[action.name] = action;
2028
+ const action = actionsByFunctionName[name];
2029
+ let result = void 0;
2030
+ if (action) {
2031
+ await new Promise((resolve, reject) => {
2032
+ (0, react_dom.flushSync)(async () => {
2033
+ try {
2034
+ var _action$handler;
2035
+ result = await ((_action$handler = action.handler) === null || _action$handler === void 0 ? void 0 : _action$handler.call(action, args));
2036
+ resolve();
2037
+ } catch (error) {
2038
+ reject(error);
2039
+ }
2040
+ });
2041
+ });
2042
+ await new Promise((resolve) => setTimeout(resolve, 20));
2043
+ }
2044
+ return result;
2045
+ };
2046
+ }
2047
+ function formatFeatureName(featureName) {
2048
+ return featureName.replace(/_c$/, "").split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
2049
+ }
2050
+ function validateProps(props) {
2051
+ const cloudFeatures = Object.keys(props).filter((key) => key.endsWith("_c"));
2052
+ const hasApiKey = props.publicApiKey || props.publicLicenseKey;
2053
+ if (!props.runtimeUrl && !hasApiKey) throw new _copilotkit_shared.ConfigurationError("Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'");
2054
+ if (cloudFeatures.length > 0 && !hasApiKey) throw new _copilotkit_shared.MissingPublicApiKeyError(`Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures.map(formatFeatureName).join(", ")}`);
2055
+ }
2056
+
2057
+ //#endregion
2058
+ //#region src/hooks/use-agent-nodename.ts
2059
+ function useAgentNodeName(agentName) {
2060
+ const { agent } = (0, _copilotkitnext_react.useAgent)({ agentId: agentName });
2061
+ const nodeNameRef = (0, react.useRef)("start");
2062
+ (0, react.useEffect)(() => {
2063
+ if (!agent) return;
2064
+ const subscription = agent.subscribe({
2065
+ onStepStartedEvent: ({ event }) => {
2066
+ nodeNameRef.current = event.stepName;
2067
+ },
2068
+ onRunStartedEvent: () => {
2069
+ nodeNameRef.current = "start";
2070
+ },
2071
+ onRunFinishedEvent: () => {
2072
+ nodeNameRef.current = "end";
2073
+ }
2074
+ });
2075
+ return () => {
2076
+ subscription.unsubscribe();
2077
+ };
2078
+ }, [agent]);
2079
+ return nodeNameRef.current;
2080
+ }
2081
+
2082
+ //#endregion
2083
+ //#region src/hooks/use-langgraph-interrupt-render.ts
2084
+ const InterruptRenderer = ({ event, result, render, resolve }) => {
2085
+ return render({
2086
+ event,
2087
+ result,
2088
+ resolve
2089
+ });
2090
+ };
2091
+ function useLangGraphInterruptRender(agent) {
2092
+ var _existingConfig$agent;
2093
+ const { interruptActions, agentSession, threadId, interruptEventQueue, addInterruptEvent, resolveInterruptEvent } = useCopilotContext();
2094
+ const existingConfig = (0, _copilotkitnext_react.useCopilotChatConfiguration)();
2095
+ const nodeName = useAgentNodeName((_existingConfig$agent = existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.agentId) !== null && _existingConfig$agent !== void 0 ? _existingConfig$agent : "default");
2096
+ (0, react.useEffect)(() => {
2097
+ if (!agent) return;
2098
+ let localInterrupt = null;
2099
+ const { unsubscribe } = agent.subscribe({
2100
+ onCustomEvent: ({ event }) => {
2101
+ if (event.name === "on_interrupt") {
2102
+ const eventData = {
2103
+ name: _copilotkit_runtime_client_gql.MetaEventName.LangGraphInterruptEvent,
2104
+ type: event.type,
2105
+ value: (0, _copilotkit_shared.parseJson)(event.value, event.value)
2106
+ };
2107
+ localInterrupt = {
2108
+ eventId: (0, _copilotkit_shared.dataToUUID)(eventData, "interruptEvents"),
2109
+ threadId,
2110
+ event: eventData
2111
+ };
2112
+ }
2113
+ },
2114
+ onRunStartedEvent: () => {
2115
+ localInterrupt = null;
2116
+ },
2117
+ onRunFinalized: () => {
2118
+ if (localInterrupt) {
2119
+ addInterruptEvent(localInterrupt);
2120
+ localInterrupt = null;
2121
+ }
2122
+ }
2123
+ });
2124
+ return () => {
2125
+ unsubscribe();
2126
+ };
2127
+ }, [agent, threadId]);
2128
+ const handleResolve = (0, react.useCallback)((eventId, response) => {
2129
+ agent === null || agent === void 0 || agent.runAgent({ forwardedProps: { command: { resume: response } } });
2130
+ resolveInterruptEvent(threadId, eventId, response !== null && response !== void 0 ? response : "");
2131
+ }, [agent, threadId]);
2132
+ return (0, react.useMemo)(() => {
2133
+ const currentQueuedEvent = (interruptEventQueue[threadId] || []).find((qe) => !qe.event.response);
2134
+ if (!currentQueuedEvent || !agentSession) return null;
2135
+ const matchingAction = Object.values(interruptActions).find((action) => {
2136
+ if (!action.enabled) return true;
2137
+ return action.enabled({
2138
+ eventValue: currentQueuedEvent.event.value,
2139
+ agentMetadata: {
2140
+ ...agentSession,
2141
+ nodeName
2142
+ }
2143
+ });
2144
+ });
2145
+ if (!matchingAction) return null;
2146
+ const { render, handler } = matchingAction;
2147
+ const resolveInterrupt = (response) => {
2148
+ handleResolve(currentQueuedEvent.eventId, response);
2149
+ };
2150
+ let result = null;
2151
+ if (handler) result = handler({
2152
+ event: currentQueuedEvent.event,
2153
+ resolve: resolveInterrupt
2154
+ });
2155
+ if (!render) return null;
2156
+ return react.default.createElement(InterruptRenderer, {
2157
+ event: currentQueuedEvent.event,
2158
+ result,
2159
+ render,
2160
+ resolve: resolveInterrupt
2161
+ });
2162
+ }, [
2163
+ interruptActions,
2164
+ interruptEventQueue,
2165
+ threadId,
2166
+ agentSession,
2167
+ handleResolve
2168
+ ]);
2169
+ }
2170
+
2171
+ //#endregion
2172
+ //#region src/hooks/use-lazy-tool-renderer.tsx
2173
+ function useLazyToolRenderer() {
2174
+ const renderToolCall = (0, _copilotkitnext_react.useRenderToolCall)();
2175
+ return (0, react.useCallback)((message, messages) => {
2176
+ var _message$toolCalls;
2177
+ if (!(message === null || message === void 0 || (_message$toolCalls = message.toolCalls) === null || _message$toolCalls === void 0 ? void 0 : _message$toolCalls.length)) return null;
2178
+ const toolCall = message.toolCalls[0];
2179
+ if (!toolCall) return null;
2180
+ const toolMessage = messages === null || messages === void 0 ? void 0 : messages.find((m) => m.role === "tool" && m.toolCallId === toolCall.id);
2181
+ return () => renderToolCall({
2182
+ toolCall,
2183
+ toolMessage
2184
+ });
2185
+ }, [renderToolCall]);
2186
+ }
2187
+
2188
+ //#endregion
2189
+ //#region src/hooks/use-copilot-chat_internal.ts
2190
+ function useCopilotChatInternal({ suggestions, onInProgress, onSubmitMessage, onStopGeneration, onReloadMessages } = {}) {
2191
+ var _existingConfig$agent, _existingConfig$threa, _agent$messages5;
2192
+ const { copilotkit } = (0, _copilotkitnext_react.useCopilotKit)();
2193
+ const { threadId, agentSession } = useCopilotContext();
2194
+ const existingConfig = (0, _copilotkitnext_react.useCopilotChatConfiguration)();
2195
+ const [agentAvailable, setAgentAvailable] = (0, react.useState)(false);
2196
+ const resolvedAgentId = (_existingConfig$agent = existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.agentId) !== null && _existingConfig$agent !== void 0 ? _existingConfig$agent : "default";
2197
+ const { agent } = (0, _copilotkitnext_react.useAgent)({ agentId: resolvedAgentId });
2198
+ (0, react.useEffect)(() => {
2199
+ const connect = async (agent) => {
2200
+ setAgentAvailable(false);
2201
+ try {
2202
+ await copilotkit.connectAgent({ agent });
2203
+ setAgentAvailable(true);
2204
+ } catch (error) {
2205
+ if (error instanceof _ag_ui_client.AGUIConnectNotImplementedError) {} else console.error("CopilotChat: connectAgent failed", error);
2206
+ }
2207
+ };
2208
+ if (agent && (existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.threadId) && agent.threadId !== existingConfig.threadId) {
2209
+ agent.threadId = existingConfig.threadId;
2210
+ connect(agent);
2211
+ }
2212
+ return () => {};
2213
+ }, [
2214
+ existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.threadId,
2215
+ agent,
2216
+ copilotkit,
2217
+ resolvedAgentId
2218
+ ]);
2219
+ (0, react.useEffect)(() => {
2220
+ onInProgress === null || onInProgress === void 0 || onInProgress(Boolean(agent === null || agent === void 0 ? void 0 : agent.isRunning));
2221
+ }, [agent === null || agent === void 0 ? void 0 : agent.isRunning, onInProgress]);
2222
+ const interrupt = useLangGraphInterruptRender(agent);
2223
+ const reset = () => {
2224
+ agent === null || agent === void 0 || agent.setMessages([]);
2225
+ agent === null || agent === void 0 || agent.setState(null);
2226
+ };
2227
+ const latestDelete = useUpdatedRef((0, react.useCallback)((messageId) => {
2228
+ var _agent$messages;
2229
+ const filteredMessages = ((_agent$messages = agent === null || agent === void 0 ? void 0 : agent.messages) !== null && _agent$messages !== void 0 ? _agent$messages : []).filter((message) => message.id !== messageId);
2230
+ agent === null || agent === void 0 || agent.setMessages(filteredMessages);
2231
+ }, [agent === null || agent === void 0 ? void 0 : agent.setMessages, agent === null || agent === void 0 ? void 0 : agent.messages]));
2232
+ const latestDeleteFunc = (0, react.useCallback)((messageId) => {
2233
+ return latestDelete.current(messageId);
2234
+ }, [latestDelete]);
2235
+ const currentSuggestions = (0, _copilotkitnext_react.useSuggestions)({ agentId: resolvedAgentId });
2236
+ const reload = useAsyncCallback(async (reloadMessageId) => {
2237
+ var _agent$messages2;
2238
+ if (!agent) return;
2239
+ const messages = (_agent$messages2 = agent === null || agent === void 0 ? void 0 : agent.messages) !== null && _agent$messages2 !== void 0 ? _agent$messages2 : [];
2240
+ if (agent.isRunning || messages.length === 0) return;
2241
+ const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);
2242
+ if (reloadMessageIndex === -1) {
2243
+ console.warn(`Message with id ${reloadMessageId} not found`);
2244
+ return;
2245
+ }
2246
+ const reloadMessageRole = messages[reloadMessageIndex].role;
2247
+ if (reloadMessageRole !== "assistant") {
2248
+ console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);
2249
+ return;
2250
+ }
2251
+ let historyCutoff = [messages[0]];
2252
+ if (messages.length > 2 && reloadMessageIndex !== 0) {
2253
+ const lastUserMessageBeforeRegenerate = messages.slice(0, reloadMessageIndex).reverse().find((msg) => msg.role === "user");
2254
+ if (!lastUserMessageBeforeRegenerate) historyCutoff = [messages[0]];
2255
+ else {
2256
+ const indexOfLastUserMessageBeforeRegenerate = messages.findIndex((msg) => msg.id === lastUserMessageBeforeRegenerate.id);
2257
+ historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);
2258
+ }
2259
+ } else if (messages.length > 2 && reloadMessageIndex === 0) historyCutoff = [messages[0], messages[1]];
2260
+ agent === null || agent === void 0 || agent.setMessages(historyCutoff);
2261
+ if (agent) try {
2262
+ await copilotkit.runAgent({ agent });
2263
+ } catch (error) {
2264
+ console.error("CopilotChat: runAgent failed during reload", error);
2265
+ }
2266
+ }, [
2267
+ agent === null || agent === void 0 ? void 0 : agent.messages.length,
2268
+ agent === null || agent === void 0 ? void 0 : agent.isRunning,
2269
+ agent === null || agent === void 0 ? void 0 : agent.setMessages,
2270
+ copilotkit === null || copilotkit === void 0 ? void 0 : copilotkit.runAgent
2271
+ ]);
2272
+ const latestSendMessageFunc = useAsyncCallback(async (message, options) => {
2273
+ var _options$followUp;
2274
+ if (!agent) return;
2275
+ const followUp = (_options$followUp = options === null || options === void 0 ? void 0 : options.followUp) !== null && _options$followUp !== void 0 ? _options$followUp : true;
2276
+ if (options === null || options === void 0 ? void 0 : options.clearSuggestions) copilotkit.clearSuggestions(resolvedAgentId);
2277
+ if (onSubmitMessage) {
2278
+ const content = typeof message.content === "string" ? message.content : message.content && "text" in message.content ? message.content.text : message.content && "filename" in message.content ? message.content.filename : "";
2279
+ try {
2280
+ await onSubmitMessage(content);
2281
+ } catch (error) {
2282
+ console.error("Error in onSubmitMessage:", error);
2283
+ }
2284
+ }
2285
+ agent === null || agent === void 0 || agent.addMessage(message);
2286
+ if (followUp) try {
2287
+ await copilotkit.runAgent({ agent });
2288
+ } catch (error) {
2289
+ console.error("CopilotChat: runAgent failed", error);
2290
+ }
2291
+ }, [
2292
+ agent,
2293
+ copilotkit,
2294
+ resolvedAgentId,
2295
+ onSubmitMessage
2296
+ ]);
2297
+ const latestAppendFunc = useAsyncCallback(async (message, options) => {
2298
+ return latestSendMessageFunc((0, _copilotkit_runtime_client_gql.gqlToAGUI)([message])[0], options);
2299
+ }, [latestSendMessageFunc]);
2300
+ const latestSetMessagesFunc = (0, react.useCallback)((messages) => {
2301
+ var _agent$setMessages2;
2302
+ if (messages.every((message) => message instanceof _copilotkit_runtime_client_gql.Message)) {
2303
+ var _agent$setMessages;
2304
+ return agent === null || agent === void 0 || (_agent$setMessages = agent.setMessages) === null || _agent$setMessages === void 0 ? void 0 : _agent$setMessages.call(agent, (0, _copilotkit_runtime_client_gql.gqlToAGUI)(messages));
2305
+ }
2306
+ return agent === null || agent === void 0 || (_agent$setMessages2 = agent.setMessages) === null || _agent$setMessages2 === void 0 ? void 0 : _agent$setMessages2.call(agent, messages);
2307
+ }, [agent === null || agent === void 0 ? void 0 : agent.setMessages, agent]);
2308
+ const latestReload = useUpdatedRef(reload);
2309
+ const latestReloadFunc = useAsyncCallback(async (messageId) => {
2310
+ var _agent$messages3;
2311
+ onReloadMessages === null || onReloadMessages === void 0 || onReloadMessages({
2312
+ messageId,
2313
+ currentAgentName: agent === null || agent === void 0 ? void 0 : agent.agentId,
2314
+ messages: (_agent$messages3 = agent === null || agent === void 0 ? void 0 : agent.messages) !== null && _agent$messages3 !== void 0 ? _agent$messages3 : []
2315
+ });
2316
+ return await latestReload.current(messageId);
2317
+ }, [
2318
+ latestReload,
2319
+ agent,
2320
+ onReloadMessages
2321
+ ]);
2322
+ const latestStopFunc = (0, react.useCallback)(() => {
2323
+ var _agent$messages4, _agent$abortRun;
2324
+ onStopGeneration === null || onStopGeneration === void 0 || onStopGeneration({
2325
+ currentAgentName: agent === null || agent === void 0 ? void 0 : agent.agentId,
2326
+ messages: (_agent$messages4 = agent === null || agent === void 0 ? void 0 : agent.messages) !== null && _agent$messages4 !== void 0 ? _agent$messages4 : []
2327
+ });
2328
+ return agent === null || agent === void 0 || (_agent$abortRun = agent.abortRun) === null || _agent$abortRun === void 0 ? void 0 : _agent$abortRun.call(agent);
2329
+ }, [onStopGeneration, agent]);
2330
+ const latestReset = useUpdatedRef(reset);
2331
+ const latestResetFunc = (0, react.useCallback)(() => {
2332
+ return latestReset.current();
2333
+ }, [latestReset]);
2334
+ const lazyToolRendered = useLazyToolRenderer();
2335
+ const renderCustomMessage = (0, _copilotkitnext_react.useRenderCustomMessages)();
2336
+ const legacyCustomMessageRenderer = useLegacyCoagentRenderer({
2337
+ copilotkit,
2338
+ agent,
2339
+ agentId: resolvedAgentId,
2340
+ threadId: (_existingConfig$threa = existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.threadId) !== null && _existingConfig$threa !== void 0 ? _existingConfig$threa : threadId
2341
+ });
2342
+ const allMessages = (_agent$messages5 = agent === null || agent === void 0 ? void 0 : agent.messages) !== null && _agent$messages5 !== void 0 ? _agent$messages5 : [];
2343
+ const resolvedMessages = (0, react.useMemo)(() => {
2344
+ var _copilotkit$getAgent, _ref;
2345
+ let processedMessages = allMessages.map((message) => {
2346
+ if (message.role !== "assistant") return message;
2347
+ const lazyRendered = lazyToolRendered(message, allMessages);
2348
+ if (lazyRendered) {
2349
+ const renderedGenUi = lazyRendered();
2350
+ if (renderedGenUi) return {
2351
+ ...message,
2352
+ generativeUI: () => renderedGenUi
2353
+ };
2354
+ }
2355
+ const bridgeRenderer = legacyCustomMessageRenderer || renderCustomMessage ? () => {
2356
+ if (legacyCustomMessageRenderer) return legacyCustomMessageRenderer({
2357
+ message,
2358
+ position: "before"
2359
+ });
2360
+ try {
2361
+ var _renderCustomMessage;
2362
+ return (_renderCustomMessage = renderCustomMessage === null || renderCustomMessage === void 0 ? void 0 : renderCustomMessage({
2363
+ message,
2364
+ position: "before"
2365
+ })) !== null && _renderCustomMessage !== void 0 ? _renderCustomMessage : null;
2366
+ } catch (error) {
2367
+ console.warn("[CopilotKit] renderCustomMessages failed, falling back to legacy renderer", error);
2368
+ return null;
2369
+ }
2370
+ } : null;
2371
+ if (bridgeRenderer) return {
2372
+ ...message,
2373
+ generativeUI: bridgeRenderer,
2374
+ generativeUIPosition: "before"
2375
+ };
2376
+ return message;
2377
+ });
2378
+ const hasAssistantMessages = processedMessages.some((msg) => msg.role === "assistant");
2379
+ const canUseCustomRenderer = Boolean(renderCustomMessage && (copilotkit === null || copilotkit === void 0 || (_copilotkit$getAgent = copilotkit.getAgent) === null || _copilotkit$getAgent === void 0 ? void 0 : _copilotkit$getAgent.call(copilotkit, resolvedAgentId)));
2380
+ const placeholderRenderer = legacyCustomMessageRenderer ? legacyCustomMessageRenderer : canUseCustomRenderer ? renderCustomMessage : null;
2381
+ const shouldRenderPlaceholder = Boolean(agent === null || agent === void 0 ? void 0 : agent.isRunning) || Boolean((agent === null || agent === void 0 ? void 0 : agent.state) && Object.keys(agent.state).length);
2382
+ const effectiveThreadId = (_ref = threadId !== null && threadId !== void 0 ? threadId : agent === null || agent === void 0 ? void 0 : agent.threadId) !== null && _ref !== void 0 ? _ref : "default";
2383
+ let latestUserIndex = -1;
2384
+ for (let i = processedMessages.length - 1; i >= 0; i -= 1) if (processedMessages[i].role === "user") {
2385
+ latestUserIndex = i;
2386
+ break;
2387
+ }
2388
+ const latestUserMessageId = latestUserIndex >= 0 ? processedMessages[latestUserIndex].id : void 0;
2389
+ const currentRunId = latestUserMessageId ? copilotkit.getRunIdForMessage(resolvedAgentId, effectiveThreadId, latestUserMessageId) || `pending:${latestUserMessageId}` : void 0;
2390
+ const hasAssistantForCurrentRun = latestUserIndex >= 0 ? processedMessages.slice(latestUserIndex + 1).some((msg) => msg.role === "assistant") : hasAssistantMessages;
2391
+ if (placeholderRenderer && shouldRenderPlaceholder && !hasAssistantForCurrentRun) {
2392
+ const placeholderMessage = {
2393
+ id: currentRunId ? `coagent-state-render-${resolvedAgentId}-${currentRunId}` : `coagent-state-render-${resolvedAgentId}`,
2394
+ role: "assistant",
2395
+ content: "",
2396
+ name: "coagent-state-render",
2397
+ runId: currentRunId
2398
+ };
2399
+ processedMessages = [...processedMessages, {
2400
+ ...placeholderMessage,
2401
+ generativeUIPosition: "before",
2402
+ generativeUI: () => placeholderRenderer({
2403
+ message: placeholderMessage,
2404
+ position: "before"
2405
+ })
2406
+ }];
2407
+ }
2408
+ return processedMessages;
2409
+ }, [
2410
+ agent === null || agent === void 0 ? void 0 : agent.messages,
2411
+ lazyToolRendered,
2412
+ allMessages,
2413
+ renderCustomMessage,
2414
+ legacyCustomMessageRenderer,
2415
+ resolvedAgentId,
2416
+ copilotkit,
2417
+ agent === null || agent === void 0 ? void 0 : agent.isRunning,
2418
+ agent === null || agent === void 0 ? void 0 : agent.state
2419
+ ]);
2420
+ const renderedSuggestions = (0, react.useMemo)(() => {
2421
+ if (Array.isArray(suggestions)) return {
2422
+ suggestions: suggestions.map((s) => ({
2423
+ ...s,
2424
+ isLoading: false
2425
+ })),
2426
+ isLoading: false
2427
+ };
2428
+ return currentSuggestions;
2429
+ }, [suggestions, currentSuggestions]);
2430
+ return {
2431
+ messages: resolvedMessages,
2432
+ sendMessage: latestSendMessageFunc,
2433
+ appendMessage: latestAppendFunc,
2434
+ setMessages: latestSetMessagesFunc,
2435
+ reloadMessages: latestReloadFunc,
2436
+ stopGeneration: latestStopFunc,
2437
+ reset: latestResetFunc,
2438
+ deleteMessage: latestDeleteFunc,
2439
+ isAvailable: agentAvailable,
2440
+ isLoading: Boolean(agent === null || agent === void 0 ? void 0 : agent.isRunning),
2441
+ suggestions: renderedSuggestions.suggestions,
2442
+ setSuggestions: (suggestions) => copilotkit.addSuggestionsConfig({ suggestions }),
2443
+ generateSuggestions: async () => copilotkit.reloadSuggestions(resolvedAgentId),
2444
+ resetSuggestions: () => copilotkit.clearSuggestions(resolvedAgentId),
2445
+ isLoadingSuggestions: renderedSuggestions.isLoading,
2446
+ interrupt,
2447
+ agent,
2448
+ threadId
2449
+ };
2450
+ }
2451
+ function useUpdatedRef(value) {
2452
+ const ref = (0, react.useRef)(value);
2453
+ (0, react.useEffect)(() => {
2454
+ ref.current = value;
2455
+ }, [value]);
2456
+ return ref;
2457
+ }
2458
+ function useLegacyCoagentRenderer({ copilotkit, agent, agentId, threadId }) {
2459
+ return (0, react.useMemo)(() => {
2460
+ if (!copilotkit || !agent) return null;
2461
+ return ({ message, position }) => {
2462
+ var _ref2;
2463
+ const effectiveThreadId = (_ref2 = threadId !== null && threadId !== void 0 ? threadId : agent.threadId) !== null && _ref2 !== void 0 ? _ref2 : "default";
2464
+ const providedRunId = message.runId;
2465
+ return (0, react.createElement)(CoAgentStateRenderBridge, {
2466
+ message,
2467
+ position,
2468
+ runId: (providedRunId ? providedRunId : copilotkit.getRunIdForMessage(agentId, effectiveThreadId, message.id)) || `pending:${message.id}`,
2469
+ messageIndex: Math.max(agent.messages.findIndex((msg) => msg.id === message.id), 0),
2470
+ messageIndexInRun: 0,
2471
+ numberOfMessagesInRun: 1,
2472
+ agentId,
2473
+ stateSnapshot: message.state
2474
+ });
2475
+ };
2476
+ }, [
2477
+ agent,
2478
+ agentId,
2479
+ copilotkit,
2480
+ threadId
2481
+ ]);
2482
+ }
2483
+
2484
+ //#endregion
2485
+ //#region src/hooks/use-copilot-chat.ts
2486
+ /**
2487
+ * `useCopilotChat` is a lightweight React hook for headless chat interactions.
2488
+ * Perfect for controlling the prebuilt chat components programmatically.
2489
+ *
2490
+ * **Open Source Friendly** - Works without requiring a free public license key.
2491
+ *
2492
+ * <Callout title="Looking for fully headless UI?">
2493
+ * Get started with [useCopilotChatHeadless_c](https://docs.copilotkit.ai/reference/v1/hooks/useCopilotChatHeadless_c).
2494
+ * </Callout>
2495
+ *
2496
+ * ## Use Cases
2497
+ *
2498
+ * - **Programmatic Messaging**: Send messages without displaying chat UI
2499
+ * - **Programmatic control**: Control prebuilt component programmatically
2500
+ * - **Background Operations**: Trigger AI interactions in the background
2501
+ * - **Fire-and-Forget**: Send messages without needing to read responses
2502
+ *
2503
+ * ## Usage
2504
+ *
2505
+ * ```tsx
2506
+ * import { TextMessage, MessageRole } from "@copilotkit/runtime-client-gql";
2507
+ *
2508
+ * const { appendMessage } = useCopilotChat();
2509
+ *
2510
+ * // Example usage without naming conflicts
2511
+ * const handleSendMessage = async (content: string) => {
2512
+ * await appendMessage(
2513
+ * new TextMessage({
2514
+ * role: MessageRole.User,
2515
+ * content,
2516
+ * })
2517
+ * );
2518
+ * };
2519
+ * ```
2520
+ *
2521
+ * ## Return Values
2522
+ * The following properties are returned from the hook:
2523
+ *
2524
+ * <PropertyReference name="visibleMessages" type="DeprecatedGqlMessage[]" deprecated>
2525
+ * Array of messages in old non-AG-UI format, use for compatibility only
2526
+ * </PropertyReference>
2527
+ *
2528
+ * <PropertyReference name="appendMessage" type="(message: DeprecatedGqlMessage, options?) => Promise<void>" deprecated>
2529
+ * Append message using old format, use `sendMessage` instead
2530
+ * </PropertyReference>
2531
+ *
2532
+ * <PropertyReference name="reloadMessages" type="(messageId: string) => Promise<void>">
2533
+ * Regenerate the response for a specific message by ID
2534
+ * </PropertyReference>
2535
+ *
2536
+ * <PropertyReference name="stopGeneration" type="() => void">
2537
+ * Stop the current message generation process
2538
+ * </PropertyReference>
2539
+ *
2540
+ * <PropertyReference name="reset" type="() => void">
2541
+ * Clear all messages and reset chat state completely
2542
+ * </PropertyReference>
2543
+ *
2544
+ * <PropertyReference name="isLoading" type="boolean">
2545
+ * Whether the chat is currently generating a response
2546
+ * </PropertyReference>
2547
+ *
2548
+ * <PropertyReference name="runChatCompletion" type="() => Promise<Message[]>">
2549
+ * Manually trigger chat completion for advanced usage
2550
+ * </PropertyReference>
2551
+ *
2552
+ * <PropertyReference name="mcpServers" type="MCPServerConfig[]">
2553
+ * Array of Model Context Protocol server configurations
2554
+ * </PropertyReference>
2555
+ *
2556
+ * <PropertyReference name="setMcpServers" type="(servers: MCPServerConfig[]) => void">
2557
+ * Update MCP server configurations for enhanced context
2558
+ * </PropertyReference>
2559
+ */
2560
+ /**
2561
+ * A lightweight React hook for headless chat interactions.
2562
+ * Perfect for programmatic messaging, background operations, and custom UI implementations.
2563
+ *
2564
+ * **Open Source Friendly** - Works without requiring a `publicApiKey`.
2565
+ */
2566
+ function useCopilotChat(options = {}) {
2567
+ const { visibleMessages, appendMessage, reloadMessages, stopGeneration, reset, isLoading, isAvailable, runChatCompletion, mcpServers, setMcpServers } = useCopilotChatInternal(options);
2568
+ return {
2569
+ visibleMessages,
2570
+ appendMessage,
2571
+ reloadMessages,
2572
+ stopGeneration,
2573
+ reset,
2574
+ isLoading,
2575
+ isAvailable,
2576
+ runChatCompletion,
2577
+ mcpServers,
2578
+ setMcpServers
2579
+ };
2580
+ }
2581
+
2582
+ //#endregion
2583
+ //#region src/hooks/use-copilot-chat-headless_c.ts
2584
+ /**
2585
+ * `useCopilotChatHeadless_c` is for building fully custom UI (headless UI) implementations.
2586
+ *
2587
+ * <Callout title="This is a premium-only feature">
2588
+ * Sign up for free on [Copilot Cloud](https://cloud.copilotkit.ai) to get your public license key or read more about <a href="/premium/overview">premium features</a>.
2589
+ *
2590
+ * Usage is generous, **free** to get started, and works with **either self-hosted or Copilot Cloud** environments.
2591
+ * </Callout>
2592
+ *
2593
+ * ## Key Features
2594
+ *
2595
+ * - **Fully headless**: Build your own fully custom UI's for your agentic applications.
2596
+ * - **Advanced Suggestions**: Direct access to suggestions array with full control
2597
+ * - **Interrupt Handling**: Support for advanced interrupt functionality
2598
+ * - **MCP Server Support**: Model Context Protocol server configurations
2599
+ * - **Chat Controls**: Complete set of chat management functions
2600
+ * - **Loading States**: Comprehensive loading state management
2601
+ *
2602
+ *
2603
+ * ## Usage
2604
+ *
2605
+ * ### Basic Setup
2606
+ *
2607
+ * ```tsx
2608
+ * import { CopilotKit } from "@copilotkit/react-core";
2609
+ * import { useCopilotChatHeadless_c } from "@copilotkit/react-core";
2610
+ *
2611
+ * export function App() {
2612
+ * return (
2613
+ * <CopilotKit publicApiKey="your-free-public-license-key">
2614
+ * <YourComponent />
2615
+ * </CopilotKit>
2616
+ * );
2617
+ * }
2618
+ *
2619
+ * export function YourComponent() {
2620
+ * const { messages, sendMessage, isLoading } = useCopilotChatHeadless_c();
2621
+ *
2622
+ * const handleSendMessage = async () => {
2623
+ * await sendMessage({
2624
+ * id: "123",
2625
+ * role: "user",
2626
+ * content: "Hello World",
2627
+ * });
2628
+ * };
2629
+ *
2630
+ * return (
2631
+ * <div>
2632
+ * {messages.map(msg => <div key={msg.id}>{msg.content}</div>)}
2633
+ * <button onClick={handleSendMessage} disabled={isLoading}>
2634
+ * Send Message
2635
+ * </button>
2636
+ * </div>
2637
+ * );
2638
+ * }
2639
+ * ```
2640
+ *
2641
+ * ### Working with Suggestions
2642
+ *
2643
+ * ```tsx
2644
+ * import { useCopilotChatHeadless_c, useCopilotChatSuggestions } from "@copilotkit/react-core";
2645
+ *
2646
+ * export function SuggestionExample() {
2647
+ * const {
2648
+ * suggestions,
2649
+ * setSuggestions,
2650
+ * generateSuggestions,
2651
+ * isLoadingSuggestions
2652
+ * } = useCopilotChatHeadless_c();
2653
+ *
2654
+ * // Configure AI suggestion generation
2655
+ * useCopilotChatSuggestions({
2656
+ * instructions: "Suggest helpful actions based on the current context",
2657
+ * maxSuggestions: 3
2658
+ * });
2659
+ *
2660
+ * return (
2661
+ * <div>
2662
+ * {suggestions.map(suggestion => (
2663
+ * <button key={suggestion.title}>{suggestion.title}</button>
2664
+ * ))}
2665
+ * <button onClick={generateSuggestions} disabled={isLoadingSuggestions}>
2666
+ * Generate Suggestions
2667
+ * </button>
2668
+ * </div>
2669
+ * );
2670
+ * }
2671
+ * ```
2672
+ *
2673
+ * ## Return Values
2674
+ * The following properties are returned from the hook:
2675
+ *
2676
+ * <PropertyReference name="messages" type="Message[]">
2677
+ * The messages currently in the chat in AG-UI format
2678
+ * </PropertyReference>
2679
+ *
2680
+ * <PropertyReference name="sendMessage" type="(message: Message, options?) => Promise<void>">
2681
+ * Send a new message to the chat and trigger AI response
2682
+ * </PropertyReference>
2683
+ *
2684
+ * <PropertyReference name="setMessages" type="(messages: Message[] | DeprecatedGqlMessage[]) => void">
2685
+ * Replace all messages in the chat with new array
2686
+ * </PropertyReference>
2687
+ *
2688
+ * <PropertyReference name="deleteMessage" type="(messageId: string) => void">
2689
+ * Remove a specific message by ID from the chat
2690
+ * </PropertyReference>
2691
+ *
2692
+ * <PropertyReference name="reloadMessages" type="(messageId: string) => Promise<void>">
2693
+ * Regenerate the response for a specific message by ID
2694
+ * </PropertyReference>
2695
+ *
2696
+ * <PropertyReference name="stopGeneration" type="() => void">
2697
+ * Stop the current message generation process
2698
+ * </PropertyReference>
2699
+ *
2700
+ * <PropertyReference name="reset" type="() => void">
2701
+ * Clear all messages and reset chat state completely
2702
+ * </PropertyReference>
2703
+ *
2704
+ * <PropertyReference name="isLoading" type="boolean">
2705
+ * Whether the chat is currently generating a response
2706
+ * </PropertyReference>
2707
+ *
2708
+ * <PropertyReference name="runChatCompletion" type="() => Promise<Message[]>">
2709
+ * Manually trigger chat completion for advanced usage
2710
+ * </PropertyReference>
2711
+ *
2712
+ * <PropertyReference name="mcpServers" type="MCPServerConfig[]">
2713
+ * Array of Model Context Protocol server configurations
2714
+ * </PropertyReference>
2715
+ *
2716
+ * <PropertyReference name="setMcpServers" type="(servers: MCPServerConfig[]) => void">
2717
+ * Update MCP server configurations for enhanced context
2718
+ * </PropertyReference>
2719
+ *
2720
+ * <PropertyReference name="suggestions" type="SuggestionItem[]">
2721
+ * Current suggestions array for reading or manual control
2722
+ * </PropertyReference>
2723
+ *
2724
+ * <PropertyReference name="setSuggestions" type="(suggestions: SuggestionItem[]) => void">
2725
+ * Manually set suggestions for custom workflows
2726
+ * </PropertyReference>
2727
+ *
2728
+ * <PropertyReference name="generateSuggestions" type="() => Promise<void>">
2729
+ * Trigger AI-powered suggestion generation using configured settings
2730
+ * </PropertyReference>
2731
+ *
2732
+ * <PropertyReference name="resetSuggestions" type="() => void">
2733
+ * Clear all current suggestions and reset generation state
2734
+ * </PropertyReference>
2735
+ *
2736
+ * <PropertyReference name="isLoadingSuggestions" type="boolean">
2737
+ * Whether suggestions are currently being generated
2738
+ * </PropertyReference>
2739
+ *
2740
+ * <PropertyReference name="interrupt" type="string | React.ReactElement | null">
2741
+ * Interrupt content for human-in-the-loop workflows
2742
+ * </PropertyReference>
2743
+ */
2744
+ const createNonFunctionalReturn = () => ({
2745
+ visibleMessages: [],
2746
+ messages: [],
2747
+ sendMessage: async () => {},
2748
+ appendMessage: async () => {},
2749
+ setMessages: () => {},
2750
+ deleteMessage: () => {},
2751
+ reloadMessages: async () => {},
2752
+ stopGeneration: () => {},
2753
+ reset: () => {},
2754
+ isLoading: false,
2755
+ isAvailable: false,
2756
+ runChatCompletion: async () => [],
2757
+ mcpServers: [],
2758
+ setMcpServers: () => {},
2759
+ suggestions: [],
2760
+ setSuggestions: () => {},
2761
+ generateSuggestions: async () => {},
2762
+ resetSuggestions: () => {},
2763
+ isLoadingSuggestions: false,
2764
+ interrupt: null
2765
+ });
2766
+ /**
2767
+ * Enterprise React hook that provides complete chat functionality for fully custom UI implementations.
2768
+ * Includes all advanced features like direct message access, suggestions array, interrupt handling, and MCP support.
2769
+ *
2770
+ * **Requires a publicApiKey** - Sign up for free at https://cloud.copilotkit.ai/
2771
+ *
2772
+ * @param options - Configuration options for the chat
2773
+ * @returns Complete chat interface with all enterprise features
2774
+ *
2775
+ * @example
2776
+ * ```tsx
2777
+ * const { messages, sendMessage, suggestions, interrupt } = useCopilotChatHeadless_c();
2778
+ * ```
2779
+ */
2780
+ function useCopilotChatHeadless_c(options = {}) {
2781
+ const { copilotApiConfig, setBannerError } = useCopilotContext();
2782
+ const hasPublicApiKey = Boolean(copilotApiConfig.publicApiKey);
2783
+ const internalResult = useCopilotChatInternal(options);
2784
+ (0, react.useEffect)(() => {
2785
+ if (!hasPublicApiKey) {
2786
+ setBannerError(new _copilotkit_shared.CopilotKitError({
2787
+ message: "You're using useCopilotChatHeadless_c, a premium-only feature, which offers extensive headless chat capabilities. To continue, you'll need to provide a free public license key.",
2788
+ code: _copilotkit_shared.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
2789
+ severity: _copilotkit_shared.Severity.WARNING,
2790
+ visibility: _copilotkit_shared.ErrorVisibility.BANNER
2791
+ }));
2792
+ _copilotkit_shared.styledConsole.logCopilotKitPlatformMessage();
2793
+ } else setBannerError(null);
2794
+ }, [hasPublicApiKey]);
2795
+ if (hasPublicApiKey) return internalResult;
2796
+ return createNonFunctionalReturn();
2797
+ }
2798
+
2799
+ //#endregion
2800
+ //#region src/hooks/use-frontend-tool.ts
2801
+ function useFrontendTool(tool, dependencies) {
2802
+ const { name, description, parameters, render, followUp, available } = tool;
2803
+ const zodParameters = (0, _copilotkit_shared.getZodParameters)(parameters);
2804
+ const renderRef = (0, react.useRef)(render);
2805
+ (0, react.useEffect)(() => {
2806
+ renderRef.current = render;
2807
+ }, [render, ...dependencies !== null && dependencies !== void 0 ? dependencies : []]);
2808
+ const normalizedRender = (0, react.useMemo)(() => {
2809
+ if (typeof render === "undefined") return;
2810
+ return ((args) => {
2811
+ const currentRender = renderRef.current;
2812
+ if (typeof currentRender === "undefined") return null;
2813
+ if (typeof currentRender === "string") return react.default.createElement(react.default.Fragment, null, currentRender);
2814
+ const rendered = currentRender({
2815
+ ...args,
2816
+ result: typeof args.result === "string" ? (0, _copilotkit_shared.parseJson)(args.result, args.result) : args.result
2817
+ });
2818
+ if (typeof rendered === "string") return react.default.createElement(react.default.Fragment, null, rendered);
2819
+ return rendered !== null && rendered !== void 0 ? rendered : null;
2820
+ });
2821
+ }, []);
2822
+ const handlerRef = (0, react.useRef)(tool.handler);
2823
+ (0, react.useEffect)(() => {
2824
+ handlerRef.current = tool.handler;
2825
+ }, [tool.handler, ...dependencies !== null && dependencies !== void 0 ? dependencies : []]);
2826
+ (0, _copilotkitnext_react.useFrontendTool)({
2827
+ name,
2828
+ description,
2829
+ parameters: zodParameters,
2830
+ handler: tool.handler ? (args) => {
2831
+ var _handlerRef$current;
2832
+ return (_handlerRef$current = handlerRef.current) === null || _handlerRef$current === void 0 ? void 0 : _handlerRef$current.call(handlerRef, args);
2833
+ } : void 0,
2834
+ followUp,
2835
+ render: normalizedRender,
2836
+ available: available === void 0 ? void 0 : available !== "disabled"
2837
+ });
2838
+ }
2839
+
2840
+ //#endregion
2841
+ //#region src/hooks/use-render-tool-call.ts
2842
+ function useRenderToolCall(tool, dependencies) {
2843
+ const { copilotkit } = (0, _copilotkitnext_react.useCopilotKit)();
2844
+ const hasAddedRef = (0, react.useRef)(false);
2845
+ (0, react.useEffect)(() => {
2846
+ const { name, parameters, render } = tool;
2847
+ const zodParameters = (0, _copilotkit_shared.getZodParameters)(parameters);
2848
+ const renderToolCall = name === "*" ? (0, _copilotkitnext_react.defineToolCallRenderer)({
2849
+ name: "*",
2850
+ render: ((args) => {
2851
+ return render({
2852
+ ...args,
2853
+ result: args.result ? (0, _copilotkit_shared.parseJson)(args.result, args.result) : args.result
2854
+ });
2855
+ })
2856
+ }) : (0, _copilotkitnext_react.defineToolCallRenderer)({
2857
+ name,
2858
+ args: zodParameters,
2859
+ render: ((args) => {
2860
+ return render({
2861
+ ...args,
2862
+ result: args.result ? (0, _copilotkit_shared.parseJson)(args.result, args.result) : args.result
2863
+ });
2864
+ })
2865
+ });
2866
+ const existingIndex = copilotkit.renderToolCalls.findIndex((r) => r.name === name);
2867
+ if (existingIndex !== -1) copilotkit.renderToolCalls.splice(existingIndex, 1);
2868
+ copilotkit.renderToolCalls.push(renderToolCall);
2869
+ hasAddedRef.current = true;
2870
+ return () => {
2871
+ if (hasAddedRef.current) {
2872
+ const index = copilotkit.renderToolCalls.findIndex((r) => r.name === name);
2873
+ if (index !== -1) copilotkit.renderToolCalls.splice(index, 1);
2874
+ hasAddedRef.current = false;
2875
+ }
2876
+ };
2877
+ }, [tool, ...dependencies !== null && dependencies !== void 0 ? dependencies : []]);
2878
+ }
2879
+
2880
+ //#endregion
2881
+ //#region src/hooks/use-human-in-the-loop.ts
2882
+ function useHumanInTheLoop(tool, dependencies) {
2883
+ const { render, ...toolRest } = tool;
2884
+ const { name, description, parameters, followUp } = toolRest;
2885
+ const zodParameters = (0, _copilotkit_shared.getZodParameters)(parameters);
2886
+ const renderRef = (0, react.useRef)(null);
2887
+ (0, react.useEffect)(() => {
2888
+ renderRef.current = (args) => {
2889
+ if (typeof render === "string") return react.default.createElement(react.default.Fragment, null, render);
2890
+ if (!render) return null;
2891
+ const rendered = render((() => {
2892
+ const mappedArgs = args.args;
2893
+ switch (args.status) {
2894
+ case _copilotkitnext_core.ToolCallStatus.InProgress: return {
2895
+ args: mappedArgs,
2896
+ respond: args.respond,
2897
+ status: args.status,
2898
+ handler: void 0
2899
+ };
2900
+ case _copilotkitnext_core.ToolCallStatus.Executing: return {
2901
+ args: mappedArgs,
2902
+ respond: args.respond,
2903
+ status: args.status,
2904
+ handler: () => {}
2905
+ };
2906
+ case _copilotkitnext_core.ToolCallStatus.Complete: return {
2907
+ args: mappedArgs,
2908
+ respond: args.respond,
2909
+ status: args.status,
2910
+ result: args.result ? (0, _copilotkit_shared.parseJson)(args.result, args.result) : args.result,
2911
+ handler: void 0
2912
+ };
2913
+ default: throw new _copilotkit_shared.CopilotKitError({
2914
+ code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN,
2915
+ message: `Invalid tool call status: ${args.status}`
2916
+ });
2917
+ }
2918
+ })());
2919
+ if (typeof rendered === "string") return react.default.createElement(react.default.Fragment, null, rendered);
2920
+ return rendered !== null && rendered !== void 0 ? rendered : null;
2921
+ };
2922
+ }, [render, ...dependencies !== null && dependencies !== void 0 ? dependencies : []]);
2923
+ (0, _copilotkitnext_react.useHumanInTheLoop)({
2924
+ name,
2925
+ description,
2926
+ followUp,
2927
+ parameters: zodParameters,
2928
+ render: ((args) => {
2929
+ var _renderRef$current, _renderRef$current2;
2930
+ return (_renderRef$current = (_renderRef$current2 = renderRef.current) === null || _renderRef$current2 === void 0 ? void 0 : _renderRef$current2.call(renderRef, args)) !== null && _renderRef$current !== void 0 ? _renderRef$current : null;
2931
+ })
2932
+ });
2933
+ }
2934
+
2935
+ //#endregion
2936
+ //#region src/hooks/use-copilot-action.ts
2937
+ /**
2938
+ * Example usage of useCopilotAction with complex parameters:
2939
+ *
2940
+ * @example
2941
+ * useCopilotAction({
2942
+ * name: "myAction",
2943
+ * parameters: [
2944
+ * { name: "arg1", type: "string", enum: ["option1", "option2", "option3"], required: false },
2945
+ * { name: "arg2", type: "number" },
2946
+ * {
2947
+ * name: "arg3",
2948
+ * type: "object",
2949
+ * attributes: [
2950
+ * { name: "nestedArg1", type: "boolean" },
2951
+ * { name: "xyz", required: false },
2952
+ * ],
2953
+ * },
2954
+ * { name: "arg4", type: "number[]" },
2955
+ * ],
2956
+ * handler: ({ arg1, arg2, arg3, arg4 }) => {
2957
+ * const x = arg3.nestedArg1;
2958
+ * const z = arg3.xyz;
2959
+ * console.log(arg1, arg2, arg3);
2960
+ * },
2961
+ * });
2962
+ *
2963
+ * @example
2964
+ * // Simple action without parameters
2965
+ * useCopilotAction({
2966
+ * name: "myAction",
2967
+ * handler: () => {
2968
+ * console.log("No parameters provided.");
2969
+ * },
2970
+ * });
2971
+ *
2972
+ * @example
2973
+ * // Interactive action with UI rendering and response handling
2974
+ * useCopilotAction({
2975
+ * name: "handleMeeting",
2976
+ * description: "Handle a meeting by booking or canceling",
2977
+ * parameters: [
2978
+ * {
2979
+ * name: "meeting",
2980
+ * type: "string",
2981
+ * description: "The meeting to handle",
2982
+ * required: true,
2983
+ * },
2984
+ * {
2985
+ * name: "date",
2986
+ * type: "string",
2987
+ * description: "The date of the meeting",
2988
+ * required: true,
2989
+ * },
2990
+ * {
2991
+ * name: "title",
2992
+ * type: "string",
2993
+ * description: "The title of the meeting",
2994
+ * required: true,
2995
+ * },
2996
+ * ],
2997
+ * renderAndWaitForResponse: ({ args, respond, status }) => {
2998
+ * const { meeting, date, title } = args;
2999
+ * return (
3000
+ * <MeetingConfirmationDialog
3001
+ * meeting={meeting}
3002
+ * date={date}
3003
+ * title={title}
3004
+ * onConfirm={() => respond('meeting confirmed')}
3005
+ * onCancel={() => respond('meeting canceled')}
3006
+ * />
3007
+ * );
3008
+ * },
3009
+ * });
3010
+ *
3011
+ * @example
3012
+ * // Catch all action allows you to render actions that are not defined in the frontend
3013
+ * useCopilotAction({
3014
+ * name: "*",
3015
+ * render: ({ name, args, status, result, handler, respond }) => {
3016
+ * return <div>Rendering action: {name}</div>;
3017
+ * },
3018
+ * });
3019
+ */
3020
+ /**
3021
+ * <img src="https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif" width="500" />
3022
+ * `useCopilotAction` is a React hook that you can use in your application to provide
3023
+ * custom actions that can be called by the AI. Essentially, it allows the Copilot to
3024
+ * execute these actions contextually during a chat, based on the user's interactions
3025
+ * and needs.
3026
+ *
3027
+ * Here's how it works:
3028
+ *
3029
+ * Use `useCopilotAction` to set up actions that the Copilot can call. To provide
3030
+ * more context to the Copilot, you can provide it with a `description` (for example to explain
3031
+ * what the action does, under which conditions it can be called, etc.).
3032
+ *
3033
+ * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,
3034
+ * or complex, e.g. objects or arrays.
3035
+ *
3036
+ * Finally, you provide a `handler` function that receives the parameters and returns a result.
3037
+ * CopilotKit takes care of automatically inferring the parameter types, so you get type safety
3038
+ * and autocompletion for free.
3039
+ *
3040
+ * To render a custom UI for the action, you can provide a `render()` function. This function
3041
+ * lets you render a custom component or return a string to display.
3042
+ *
3043
+ * ## Usage
3044
+ *
3045
+ * ### Simple Usage
3046
+ *
3047
+ * ```tsx
3048
+ * useCopilotAction({
3049
+ * name: "sayHello",
3050
+ * description: "Say hello to someone.",
3051
+ * parameters: [
3052
+ * {
3053
+ * name: "name",
3054
+ * type: "string",
3055
+ * description: "name of the person to say greet",
3056
+ * },
3057
+ * ],
3058
+ * handler: async ({ name }) => {
3059
+ * alert(`Hello, ${name}!`);
3060
+ * },
3061
+ * });
3062
+ * ```
3063
+ *
3064
+ * ## Generative UI
3065
+ *
3066
+ * 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.
3067
+ */
3068
+ function getActionConfig(action) {
3069
+ if (action.name === "*") return {
3070
+ type: "render",
3071
+ action
3072
+ };
3073
+ if ("renderAndWaitForResponse" in action || "renderAndWait" in action) {
3074
+ let render = action.render;
3075
+ if (!render && "renderAndWaitForResponse" in action) render = action.renderAndWaitForResponse;
3076
+ if (!render && "renderAndWait" in action) render = action.renderAndWait;
3077
+ return {
3078
+ type: "hitl",
3079
+ action: {
3080
+ ...action,
3081
+ render
3082
+ }
3083
+ };
3084
+ }
3085
+ if ("available" in action) {
3086
+ if (action.available === "enabled" || action.available === "remote") return {
3087
+ type: "frontend",
3088
+ action
3089
+ };
3090
+ if (action.available === "frontend" || action.available === "disabled") return {
3091
+ type: "render",
3092
+ action
3093
+ };
3094
+ }
3095
+ if ("handler" in action) return {
3096
+ type: "frontend",
3097
+ action
3098
+ };
3099
+ throw new Error("Invalid action configuration");
3100
+ }
3101
+ /**
3102
+ * useCopilotAction is a legacy hook maintained for backwards compatibility.
3103
+ *
3104
+ * To avoid violating React's Rules of Hooks (which prohibit conditional hook calls),
3105
+ * we use a registration pattern:
3106
+ * 1. This hook registers the action configuration with the CopilotContext
3107
+ * 2. A renderer component in CopilotKit actually renders the appropriate hook wrapper
3108
+ * 3. React properly manages hook state since components are rendered, not conditionally called
3109
+ *
3110
+ * This allows action types to change between renders without corrupting React's hook state.
3111
+ */
3112
+ function useCopilotAction(action, dependencies) {
3113
+ const [initialActionConfig] = (0, react.useState)(getActionConfig(action));
3114
+ const currentActionConfig = getActionConfig(action);
3115
+ /**
3116
+ * Calling hooks conditionally violates React's Rules of Hooks. This rule exists because
3117
+ * React maintains the call stack for hooks like useEffect or useState, and conditionally
3118
+ * calling a hook would result in inconsistent call stacks between renders.
3119
+ *
3120
+ * Unfortunately, useCopilotAction _has_ to conditionally call a hook based on the
3121
+ * supplied parameters. In order to avoid breaking React's call stack tracking, while
3122
+ * breaking the Rule of Hooks, we use a ref to store the initial action configuration
3123
+ * and throw an error if the _configuration_ changes such that we would call a different hook.
3124
+ */
3125
+ if (initialActionConfig.type !== currentActionConfig.type) throw new Error("Action configuration changed between renders");
3126
+ switch (currentActionConfig.type) {
3127
+ case "render": return useRenderToolCall(currentActionConfig.action, dependencies);
3128
+ case "hitl": return useHumanInTheLoop(currentActionConfig.action, dependencies);
3129
+ case "frontend": return useFrontendTool(currentActionConfig.action, dependencies);
3130
+ default: throw new Error("Invalid action configuration");
3131
+ }
3132
+ }
3133
+
3134
+ //#endregion
3135
+ //#region src/hooks/use-coagent-state-render.ts
3136
+ /**
3137
+ * The useCoAgentStateRender hook allows you to render UI or text based components on a Agentic Copilot's state in the chat.
3138
+ * This is particularly useful for showing intermediate state or progress during Agentic Copilot operations.
3139
+ *
3140
+ * ## Usage
3141
+ *
3142
+ * ### Simple Usage
3143
+ *
3144
+ * ```tsx
3145
+ * import { useCoAgentStateRender } from "@copilotkit/react-core";
3146
+ *
3147
+ * type YourAgentState = {
3148
+ * agent_state_property: string;
3149
+ * }
3150
+ *
3151
+ * useCoAgentStateRender<YourAgentState>({
3152
+ * name: "basic_agent",
3153
+ * nodeName: "optionally_specify_a_specific_node",
3154
+ * render: ({ status, state, nodeName }) => {
3155
+ * return (
3156
+ * <YourComponent
3157
+ * agentStateProperty={state.agent_state_property}
3158
+ * status={status}
3159
+ * nodeName={nodeName}
3160
+ * />
3161
+ * );
3162
+ * },
3163
+ * });
3164
+ * ```
3165
+ *
3166
+ * This allows for you to render UI components or text based on what is happening within the agent.
3167
+ *
3168
+ * ### Example
3169
+ * A great example of this is in our Perplexity Clone where we render the progress of an agent's internet search as it is happening.
3170
+ * You can play around with it below or learn how to build it with its [demo](/coagents/videos/perplexity-clone).
3171
+ *
3172
+ * <Callout type="info">
3173
+ * This example is hosted on Vercel and may take a few seconds to load.
3174
+ * </Callout>
3175
+ *
3176
+ * <iframe src="https://examples-coagents-ai-researcher-ui.vercel.app/" className="w-full rounded-lg border h-[700px] my-4" />
3177
+ */
3178
+ /**
3179
+ * This hook is used to render agent state with custom UI components or text. This is particularly
3180
+ * useful for showing intermediate state or progress during Agentic Copilot operations.
3181
+ * To get started using rendering intermediate state through this hook, checkout the documentation.
3182
+ *
3183
+ * https://docs.copilotkit.ai/coagents/shared-state/predictive-state-updates
3184
+ */
3185
+ function useCoAgentStateRender(action, dependencies) {
3186
+ const { chatComponentsCache, availableAgents } = (0, react.useContext)(CopilotContext);
3187
+ const { setCoAgentStateRender, removeCoAgentStateRender, coAgentStateRenders } = useCoAgentStateRenders();
3188
+ const idRef = (0, react.useRef)((0, _copilotkit_shared.randomId)());
3189
+ const { setBannerError, addToast } = useToast();
3190
+ (0, react.useEffect)(() => {
3191
+ if ((availableAgents === null || availableAgents === void 0 ? void 0 : availableAgents.length) && !availableAgents.some((a) => a.name === action.name)) {
3192
+ `${action.name}`;
3193
+ setBannerError(new _copilotkit_shared.CopilotKitAgentDiscoveryError({
3194
+ agentName: action.name,
3195
+ availableAgents: availableAgents.map((a) => ({
3196
+ name: a.name,
3197
+ id: a.id
3198
+ }))
3199
+ }));
3200
+ }
3201
+ }, [availableAgents]);
3202
+ const key = `${action.name}-${action.nodeName || "global"}`;
3203
+ if (dependencies === void 0) {
3204
+ if (coAgentStateRenders[idRef.current]) {
3205
+ coAgentStateRenders[idRef.current].handler = action.handler;
3206
+ if (typeof action.render === "function") {
3207
+ if (chatComponentsCache.current !== null) chatComponentsCache.current.coAgentStateRenders[key] = action.render;
3208
+ }
3209
+ }
3210
+ }
3211
+ (0, react.useEffect)(() => {
3212
+ const currentId = idRef.current;
3213
+ if (Object.entries(coAgentStateRenders).some(([id, otherAction]) => {
3214
+ if (id === currentId) return false;
3215
+ if (otherAction.name !== action.name) return false;
3216
+ const hasNodeName = !!action.nodeName;
3217
+ const hasOtherNodeName = !!otherAction.nodeName;
3218
+ if (!hasNodeName && !hasOtherNodeName) return true;
3219
+ if (hasNodeName !== hasOtherNodeName) return false;
3220
+ return action.nodeName === otherAction.nodeName;
3221
+ })) addToast({
3222
+ type: "warning",
3223
+ message: action.nodeName ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden` : `Found multiple state renders for agent ${action.name}. State renders might get overridden`,
3224
+ id: `dup-action-${action.name}`
3225
+ });
3226
+ }, [coAgentStateRenders]);
3227
+ (0, react.useEffect)(() => {
3228
+ setCoAgentStateRender(idRef.current, action);
3229
+ if (chatComponentsCache.current !== null && action.render !== void 0) chatComponentsCache.current.coAgentStateRenders[key] = action.render;
3230
+ return () => {
3231
+ removeCoAgentStateRender(idRef.current);
3232
+ };
3233
+ }, [
3234
+ setCoAgentStateRender,
3235
+ removeCoAgentStateRender,
3236
+ action.name,
3237
+ typeof action.render === "string" ? action.render : void 0,
3238
+ ...dependencies || []
3239
+ ]);
3240
+ }
3241
+
3242
+ //#endregion
3243
+ //#region src/hooks/use-make-copilot-document-readable.ts
3244
+ /**
3245
+ * Makes a document readable by Copilot.
3246
+ * @param document The document to make readable.
3247
+ * @param categories The categories to associate with the document.
3248
+ * @param dependencies The dependencies to use for the effect.
3249
+ * @returns The id of the document.
3250
+ */
3251
+ function useMakeCopilotDocumentReadable(document, categories, dependencies = []) {
3252
+ const { addDocumentContext, removeDocumentContext } = useCopilotContext();
3253
+ const idRef = (0, react.useRef)(void 0);
3254
+ (0, react.useEffect)(() => {
3255
+ const id = addDocumentContext(document, categories);
3256
+ idRef.current = id;
3257
+ return () => {
3258
+ removeDocumentContext(id);
3259
+ };
3260
+ }, [
3261
+ addDocumentContext,
3262
+ removeDocumentContext,
3263
+ ...dependencies
3264
+ ]);
3265
+ return idRef.current;
3266
+ }
3267
+
3268
+ //#endregion
3269
+ //#region src/hooks/use-copilot-readable.ts
3270
+ /**
3271
+ * `useCopilotReadable` is a React hook that provides app-state and other information
3272
+ * to the Copilot. Optionally, the hook can also handle hierarchical state within your
3273
+ * application, passing these parent-child relationships to the Copilot.
3274
+ *
3275
+ * ## Usage
3276
+ *
3277
+ * ### Simple Usage
3278
+ *
3279
+ * In its most basic usage, useCopilotReadable accepts a single string argument
3280
+ * representing any piece of app state, making it available for the Copilot to use
3281
+ * as context when responding to user input.
3282
+ *
3283
+ * ```tsx
3284
+ * import { useCopilotReadable } from "@copilotkit/react-core";
3285
+ *
3286
+ * export function MyComponent() {
3287
+ * const [employees, setEmployees] = useState([]);
3288
+ *
3289
+ * useCopilotReadable({
3290
+ * description: "The list of employees",
3291
+ * value: employees,
3292
+ * });
3293
+ * }
3294
+ * ```
3295
+ *
3296
+ * ### Nested Components
3297
+ *
3298
+ * Optionally, you can maintain the hierarchical structure of information by passing
3299
+ * `parentId`. This allows you to use `useCopilotReadable` in nested components:
3300
+ *
3301
+ * ```tsx /employeeContextId/1 {17,23}
3302
+ * import { useCopilotReadable } from "@copilotkit/react-core";
3303
+ *
3304
+ * function Employee(props: EmployeeProps) {
3305
+ * const { employeeName, workProfile, metadata } = props;
3306
+ *
3307
+ * // propagate any information to copilot
3308
+ * const employeeContextId = useCopilotReadable({
3309
+ * description: "Employee name",
3310
+ * value: employeeName
3311
+ * });
3312
+ *
3313
+ * // Pass a parentID to maintain a hierarchical structure.
3314
+ * // Especially useful with child React components, list elements, etc.
3315
+ * useCopilotReadable({
3316
+ * description: "Work profile",
3317
+ * value: workProfile.description(),
3318
+ * parentId: employeeContextId
3319
+ * });
3320
+ *
3321
+ * useCopilotReadable({
3322
+ * description: "Employee metadata",
3323
+ * value: metadata.description(),
3324
+ * parentId: employeeContextId
3325
+ * });
3326
+ *
3327
+ * return (
3328
+ * // Render as usual...
3329
+ * );
3330
+ * }
3331
+ * ```
3332
+ */
3333
+ /**
3334
+ * Adds the given information to the Copilot context to make it readable by Copilot.
3335
+ */
3336
+ function useCopilotReadable({ description, value, convert, available }, dependencies) {
3337
+ const { copilotkit } = (0, _copilotkitnext_react.useCopilotKit)();
3338
+ const ctxIdRef = (0, react.useRef)(void 0);
3339
+ (0, react.useEffect)(() => {
3340
+ if (!copilotkit) return;
3341
+ const found = Object.entries(copilotkit.context).find(([id, ctxItem]) => {
3342
+ return JSON.stringify({
3343
+ description,
3344
+ value
3345
+ }) == JSON.stringify(ctxItem);
3346
+ });
3347
+ if (found) {
3348
+ ctxIdRef.current = found[0];
3349
+ if (available === "disabled") copilotkit.removeContext(ctxIdRef.current);
3350
+ return;
3351
+ }
3352
+ if (!found && available === "disabled") return;
3353
+ ctxIdRef.current = copilotkit.addContext({
3354
+ description,
3355
+ value: (convert !== null && convert !== void 0 ? convert : JSON.stringify)(value)
3356
+ });
3357
+ return () => {
3358
+ if (!ctxIdRef.current) return;
3359
+ copilotkit.removeContext(ctxIdRef.current);
3360
+ };
3361
+ }, [
3362
+ description,
3363
+ value,
3364
+ convert
3365
+ ]);
3366
+ return ctxIdRef.current;
3367
+ }
3368
+
3369
+ //#endregion
3370
+ //#region src/hooks/use-coagent.ts
3371
+ /**
3372
+ * <Callout type="info">
3373
+ * Usage of this hook assumes some additional setup in your application, for more information
3374
+ * on that see the CoAgents <span className="text-blue-500">[getting started guide](/coagents/quickstart/langgraph)</span>.
3375
+ * </Callout>
3376
+ * <Frame className="my-12">
3377
+ * <img
3378
+ * src="https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif"
3379
+ * alt="CoAgents demonstration"
3380
+ * className="w-auto"
3381
+ * />
3382
+ * </Frame>
3383
+ *
3384
+ * This hook is used to integrate an agent into your application. With its use, you can
3385
+ * render and update the state of an agent, allowing for a dynamic and interactive experience.
3386
+ * We call these shared state experiences agentic copilots, or CoAgents for short.
3387
+ *
3388
+ * ## Usage
3389
+ *
3390
+ * ### Simple Usage
3391
+ *
3392
+ * ```tsx
3393
+ * import { useCoAgent } from "@copilotkit/react-core";
3394
+ *
3395
+ * type AgentState = {
3396
+ * count: number;
3397
+ * }
3398
+ *
3399
+ * const agent = useCoAgent<AgentState>({
3400
+ * name: "my-agent",
3401
+ * initialState: {
3402
+ * count: 0,
3403
+ * },
3404
+ * });
3405
+ *
3406
+ * ```
3407
+ *
3408
+ * `useCoAgent` returns an object with the following properties:
3409
+ *
3410
+ * ```tsx
3411
+ * const {
3412
+ * name, // The name of the agent currently being used.
3413
+ * nodeName, // The name of the current LangGraph node.
3414
+ * state, // The current state of the agent.
3415
+ * setState, // A function to update the state of the agent.
3416
+ * running, // A boolean indicating if the agent is currently running.
3417
+ * start, // A function to start the agent.
3418
+ * stop, // A function to stop the agent.
3419
+ * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.
3420
+ * } = agent;
3421
+ * ```
3422
+ *
3423
+ * Finally we can leverage these properties to create reactive experiences with the agent!
3424
+ *
3425
+ * ```tsx
3426
+ * const { state, setState } = useCoAgent<AgentState>({
3427
+ * name: "my-agent",
3428
+ * initialState: {
3429
+ * count: 0,
3430
+ * },
3431
+ * });
3432
+ *
3433
+ * return (
3434
+ * <div>
3435
+ * <p>Count: {state.count}</p>
3436
+ * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>
3437
+ * </div>
3438
+ * );
3439
+ * ```
3440
+ *
3441
+ * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.
3442
+ *
3443
+ * ## Parameters
3444
+ * <PropertyReference name="options" type="UseCoagentOptions<T>" required>
3445
+ * The options to use when creating the coagent.
3446
+ * <PropertyReference name="name" type="string" required>
3447
+ * The name of the agent to use.
3448
+ * </PropertyReference>
3449
+ * <PropertyReference name="initialState" type="T | any">
3450
+ * The initial state of the agent.
3451
+ * </PropertyReference>
3452
+ * <PropertyReference name="state" type="T | any">
3453
+ * State to manage externally if you are using this hook with external state management.
3454
+ * </PropertyReference>
3455
+ * <PropertyReference name="setState" type="(newState: T | ((prevState: T | undefined) => T)) => void">
3456
+ * A function to update the state of the agent if you are using this hook with external state management.
3457
+ * </PropertyReference>
3458
+ * </PropertyReference>
3459
+ */
3460
+ /**
3461
+ * This hook is used to integrate an agent into your application. With its use, you can
3462
+ * render and update the state of the agent, allowing for a dynamic and interactive experience.
3463
+ * We call these shared state experiences "agentic copilots". To get started using agentic copilots, which
3464
+ * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.
3465
+ */
3466
+ function useCoAgent(options) {
3467
+ const { agent } = (0, _copilotkitnext_react.useAgent)({ agentId: options.name });
3468
+ const { copilotkit } = (0, _copilotkitnext_react.useCopilotKit)();
3469
+ const nodeName = useAgentNodeName(options.name);
3470
+ const handleStateUpdate = (0, react.useCallback)((newState) => {
3471
+ if (!agent) return;
3472
+ if (typeof newState === "function") {
3473
+ const updater = newState;
3474
+ agent.setState(updater(agent.state));
3475
+ } else agent.setState({
3476
+ ...agent.state,
3477
+ ...newState
3478
+ });
3479
+ }, [agent === null || agent === void 0 ? void 0 : agent.state, agent === null || agent === void 0 ? void 0 : agent.setState]);
3480
+ (0, react.useEffect)(() => {
3481
+ var _options$config;
3482
+ if (!options.config && !options.configurable) return;
3483
+ let config = (_options$config = options.config) !== null && _options$config !== void 0 ? _options$config : {};
3484
+ if (options.configurable) config = {
3485
+ ...config,
3486
+ configurable: {
3487
+ ...options.configurable,
3488
+ ...config.configurable
3489
+ }
3490
+ };
3491
+ copilotkit.setProperties(config);
3492
+ }, [options.config, options.configurable]);
3493
+ (0, react.useEffect)(() => {
3494
+ if ((agent === null || agent === void 0 ? void 0 : agent.state) && isExternalStateManagement(options) && JSON.stringify(options.state) !== JSON.stringify(agent.state)) handleStateUpdate(options.state);
3495
+ }, [
3496
+ agent,
3497
+ (0, react.useMemo)(() => isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0, [isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0]),
3498
+ handleStateUpdate
3499
+ ]);
3500
+ const hasStateValues = (0, react.useCallback)((value) => {
3501
+ return Boolean(value && Object.keys(value).length);
3502
+ }, []);
3503
+ const initialStateRef = (0, react.useRef)(isExternalStateManagement(options) ? options.state : "initialState" in options ? options.initialState : void 0);
3504
+ (0, react.useEffect)(() => {
3505
+ if (isExternalStateManagement(options)) initialStateRef.current = options.state;
3506
+ else if ("initialState" in options) initialStateRef.current = options.initialState;
3507
+ }, [isExternalStateManagement(options) ? JSON.stringify(options.state) : "initialState" in options ? JSON.stringify(options.initialState) : void 0]);
3508
+ (0, react.useEffect)(() => {
3509
+ if (!agent) return;
3510
+ const subscription = agent.subscribe({
3511
+ onStateChanged: (args) => {
3512
+ if (isExternalStateManagement(options)) options.setState(args.state);
3513
+ },
3514
+ onRunInitialized: (args) => {
3515
+ if (hasStateValues(args.state)) {
3516
+ handleStateUpdate(args.state);
3517
+ return;
3518
+ }
3519
+ if (hasStateValues(agent.state)) return;
3520
+ if (initialStateRef.current !== void 0) handleStateUpdate(initialStateRef.current);
3521
+ }
3522
+ });
3523
+ return () => {
3524
+ subscription.unsubscribe();
3525
+ };
3526
+ }, [
3527
+ agent,
3528
+ handleStateUpdate,
3529
+ hasStateValues
3530
+ ]);
3531
+ return (0, react.useMemo)(() => {
3532
+ var _agent$agentId;
3533
+ if (!agent) {
3534
+ var _ref, _ref2;
3535
+ const noop = () => {};
3536
+ const noopAsync = async () => {};
3537
+ const initialState = (_ref = (_ref2 = "state" in options && options.state) !== null && _ref2 !== void 0 ? _ref2 : "initialState" in options && options.initialState) !== null && _ref !== void 0 ? _ref : {};
3538
+ return {
3539
+ name: options.name,
3540
+ nodeName,
3541
+ threadId: void 0,
3542
+ running: false,
3543
+ state: initialState,
3544
+ setState: noop,
3545
+ start: noop,
3546
+ stop: noop,
3547
+ run: noopAsync
3548
+ };
3549
+ }
3550
+ return {
3551
+ name: (_agent$agentId = agent === null || agent === void 0 ? void 0 : agent.agentId) !== null && _agent$agentId !== void 0 ? _agent$agentId : options.name,
3552
+ nodeName,
3553
+ threadId: agent.threadId,
3554
+ running: agent.isRunning,
3555
+ state: agent.state,
3556
+ setState: handleStateUpdate,
3557
+ start: agent.runAgent,
3558
+ stop: agent.abortRun,
3559
+ run: agent.runAgent
3560
+ };
3561
+ }, [
3562
+ agent === null || agent === void 0 ? void 0 : agent.state,
3563
+ agent === null || agent === void 0 ? void 0 : agent.runAgent,
3564
+ agent === null || agent === void 0 ? void 0 : agent.abortRun,
3565
+ agent === null || agent === void 0 ? void 0 : agent.runAgent,
3566
+ agent === null || agent === void 0 ? void 0 : agent.threadId,
3567
+ agent === null || agent === void 0 ? void 0 : agent.isRunning,
3568
+ agent === null || agent === void 0 ? void 0 : agent.agentId,
3569
+ handleStateUpdate,
3570
+ options.name
3571
+ ]);
3572
+ }
3573
+ const isExternalStateManagement = (options) => {
3574
+ return "state" in options && "setState" in options;
3575
+ };
3576
+
3577
+ //#endregion
3578
+ //#region src/hooks/use-copilot-runtime-client.ts
3579
+ const useCopilotRuntimeClient = (options) => {
3580
+ const { setBannerError } = useToast();
3581
+ const { showDevConsole, onError, ...runtimeOptions } = options;
3582
+ const lastStructuredErrorRef = (0, react.useRef)(null);
3583
+ const traceUIError = async (error, originalError) => {
3584
+ try {
3585
+ await onError({
3586
+ type: "error",
3587
+ timestamp: Date.now(),
3588
+ context: {
3589
+ source: "ui",
3590
+ request: {
3591
+ operation: "runtimeClient",
3592
+ url: runtimeOptions.url,
3593
+ startTime: Date.now()
3594
+ },
3595
+ technical: {
3596
+ environment: "browser",
3597
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
3598
+ stackTrace: originalError instanceof Error ? originalError.stack : void 0
3599
+ }
3600
+ },
3601
+ error
3602
+ });
3603
+ } catch (error) {
3604
+ console.error("Error in onError handler:", error);
3605
+ }
3606
+ };
3607
+ return (0, react.useMemo)(() => {
3608
+ return new _copilotkit_runtime_client_gql.CopilotRuntimeClient({
3609
+ ...runtimeOptions,
3610
+ handleGQLErrors: (error) => {
3611
+ var _graphQLErrors;
3612
+ if ((_graphQLErrors = error.graphQLErrors) === null || _graphQLErrors === void 0 ? void 0 : _graphQLErrors.length) {
3613
+ const graphQLErrors = error.graphQLErrors;
3614
+ const routeError = (gqlError) => {
3615
+ const extensions = gqlError.extensions;
3616
+ if ((extensions === null || extensions === void 0 ? void 0 : extensions.visibility) === _copilotkit_shared.ErrorVisibility.SILENT) {
3617
+ console.error("CopilotKit Silent Error:", gqlError.message);
3618
+ return;
3619
+ }
3620
+ const now = Date.now();
3621
+ const errorMessage = gqlError.message;
3622
+ if (lastStructuredErrorRef.current && lastStructuredErrorRef.current.message === errorMessage && now - lastStructuredErrorRef.current.timestamp < 150) return;
3623
+ lastStructuredErrorRef.current = {
3624
+ message: errorMessage,
3625
+ timestamp: now
3626
+ };
3627
+ const ckError = createStructuredError(gqlError);
3628
+ if (ckError) {
3629
+ setBannerError(ckError);
3630
+ traceUIError(ckError, gqlError);
3631
+ } else {
3632
+ const fallbackError = new _copilotkit_shared.CopilotKitError({
3633
+ message: gqlError.message,
3634
+ code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
3635
+ });
3636
+ setBannerError(fallbackError);
3637
+ traceUIError(fallbackError, gqlError);
3638
+ }
3639
+ };
3640
+ graphQLErrors.forEach(routeError);
3641
+ } else {
3642
+ const fallbackError = new _copilotkit_shared.CopilotKitError({
3643
+ message: (error === null || error === void 0 ? void 0 : error.message) || String(error),
3644
+ code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
3645
+ });
3646
+ setBannerError(fallbackError);
3647
+ traceUIError(fallbackError, error);
3648
+ }
3649
+ },
3650
+ handleGQLWarning: (message) => {
3651
+ console.warn(message);
3652
+ setBannerError(new _copilotkit_shared.CopilotKitError({
3653
+ message,
3654
+ code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
3655
+ }));
3656
+ }
3657
+ });
3658
+ }, [
3659
+ runtimeOptions,
3660
+ setBannerError,
3661
+ onError
3662
+ ]);
3663
+ };
3664
+ function createStructuredError(gqlError) {
3665
+ var _originalError$stack, _originalError$stack2, _originalError$stack3;
3666
+ const extensions = gqlError.extensions;
3667
+ const originalError = extensions === null || extensions === void 0 ? void 0 : extensions.originalError;
3668
+ const message = (originalError === null || originalError === void 0 ? void 0 : originalError.message) || gqlError.message;
3669
+ const code = extensions === null || extensions === void 0 ? void 0 : extensions.code;
3670
+ if (code) return new _copilotkit_shared.CopilotKitError({
3671
+ message,
3672
+ code
3673
+ });
3674
+ if (originalError === null || originalError === void 0 || (_originalError$stack = originalError.stack) === null || _originalError$stack === void 0 ? void 0 : _originalError$stack.includes("CopilotApiDiscoveryError")) return new _copilotkit_shared.CopilotKitApiDiscoveryError({ message });
3675
+ if (originalError === null || originalError === void 0 || (_originalError$stack2 = originalError.stack) === null || _originalError$stack2 === void 0 ? void 0 : _originalError$stack2.includes("CopilotKitRemoteEndpointDiscoveryError")) return new _copilotkit_shared.CopilotKitRemoteEndpointDiscoveryError({ message });
3676
+ if (originalError === null || originalError === void 0 || (_originalError$stack3 = originalError.stack) === null || _originalError$stack3 === void 0 ? void 0 : _originalError$stack3.includes("CopilotKitAgentDiscoveryError")) return new _copilotkit_shared.CopilotKitAgentDiscoveryError({
3677
+ agentName: "",
3678
+ availableAgents: []
3679
+ });
3680
+ return null;
3681
+ }
3682
+
3683
+ //#endregion
3684
+ //#region src/hooks/use-copilot-authenticated-action.ts
3685
+ /**
3686
+ * Hook to create an authenticated action that requires user sign-in before execution.
3687
+ *
3688
+ * @remarks
3689
+ * This feature is only available when using CopilotKit's hosted cloud service.
3690
+ * To use this feature, sign up at https://cloud.copilotkit.ai to get your publicApiKey.
3691
+ *
3692
+ * @param action - The frontend action to be wrapped with authentication
3693
+ * @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed
3694
+ */
3695
+ function useCopilotAuthenticatedAction_c(action, dependencies) {
3696
+ const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();
3697
+ const pendingActionRef = (0, react.useRef)(null);
3698
+ const executeAction = (0, react.useCallback)((props) => {
3699
+ if (typeof action.render === "function") return action.render(props);
3700
+ return action.render || react.default.createElement(react.Fragment);
3701
+ }, [action]);
3702
+ const wrappedRender = (0, react.useCallback)((props) => {
3703
+ if (!Object.values(authStates_c || {}).some((state) => state.status === "authenticated")) {
3704
+ pendingActionRef.current = props;
3705
+ return (authConfig_c === null || authConfig_c === void 0 ? void 0 : authConfig_c.SignInComponent) ? react.default.createElement(authConfig_c.SignInComponent, { onSignInComplete: (authState) => {
3706
+ setAuthStates_c === null || setAuthStates_c === void 0 || setAuthStates_c((prev) => ({
3707
+ ...prev,
3708
+ [action.name]: authState
3709
+ }));
3710
+ if (pendingActionRef.current) {
3711
+ executeAction(pendingActionRef.current);
3712
+ pendingActionRef.current = null;
3713
+ }
3714
+ } }) : react.default.createElement(react.Fragment);
3715
+ }
3716
+ return executeAction(props);
3717
+ }, [
3718
+ action,
3719
+ authStates_c,
3720
+ setAuthStates_c
3721
+ ]);
3722
+ useCopilotAction({
3723
+ ...action,
3724
+ render: wrappedRender
3725
+ }, dependencies);
3726
+ }
3727
+
3728
+ //#endregion
3729
+ //#region src/hooks/use-langgraph-interrupt.ts
3730
+ function useLangGraphInterrupt(action, dependencies) {
3731
+ const { setInterruptAction, removeInterruptAction, interruptActions, threadId } = (0, react.useContext)(CopilotContext);
3732
+ const { addToast } = useToast();
3733
+ const actionId = (0, _copilotkit_shared.dataToUUID)(action, "lgAction");
3734
+ (0, react.useEffect)(() => {
3735
+ if (!action) return;
3736
+ setInterruptAction({
3737
+ ...action,
3738
+ id: actionId
3739
+ });
3740
+ return () => {
3741
+ removeInterruptAction(actionId);
3742
+ };
3743
+ }, [
3744
+ setInterruptAction,
3745
+ removeInterruptAction,
3746
+ threadId,
3747
+ actionId,
3748
+ ...dependencies || []
3749
+ ]);
3750
+ }
3751
+
3752
+ //#endregion
3753
+ //#region src/hooks/use-copilot-additional-instructions.ts
3754
+ /**
3755
+ * `useCopilotAdditionalInstructions` is a React hook that provides additional instructions
3756
+ * to the Copilot.
3757
+ *
3758
+ * ## Usage
3759
+ *
3760
+ * ### Simple Usage
3761
+ *
3762
+ * In its most basic usage, useCopilotAdditionalInstructions accepts a single string argument
3763
+ * representing the instructions to be added to the Copilot.
3764
+ *
3765
+ * ```tsx
3766
+ * import { useCopilotAdditionalInstructions } from "@copilotkit/react-core";
3767
+ *
3768
+ * export function MyComponent() {
3769
+ * useCopilotAdditionalInstructions({
3770
+ * instructions: "Do not answer questions about the weather.",
3771
+ * });
3772
+ * }
3773
+ * ```
3774
+ *
3775
+ * ### Conditional Usage
3776
+ *
3777
+ * You can also conditionally add instructions based on the state of your app.
3778
+ *
3779
+ * ```tsx
3780
+ * import { useCopilotAdditionalInstructions } from "@copilotkit/react-core";
3781
+ *
3782
+ * export function MyComponent() {
3783
+ * const [showInstructions, setShowInstructions] = useState(false);
3784
+ *
3785
+ * useCopilotAdditionalInstructions({
3786
+ * available: showInstructions ? "enabled" : "disabled",
3787
+ * instructions: "Do not answer questions about the weather.",
3788
+ * });
3789
+ * }
3790
+ * ```
3791
+ */
3792
+ /**
3793
+ * Adds the given instructions to the Copilot context.
3794
+ */
3795
+ function useCopilotAdditionalInstructions({ instructions, available = "enabled" }, dependencies) {
3796
+ const { setAdditionalInstructions } = useCopilotContext();
3797
+ (0, react.useEffect)(() => {
3798
+ if (available === "disabled") return;
3799
+ setAdditionalInstructions((prevInstructions) => [...prevInstructions || [], instructions]);
3800
+ return () => {
3801
+ setAdditionalInstructions((prevInstructions) => (prevInstructions === null || prevInstructions === void 0 ? void 0 : prevInstructions.filter((instruction) => instruction !== instructions)) || []);
3802
+ };
3803
+ }, [
3804
+ available,
3805
+ instructions,
3806
+ setAdditionalInstructions,
3807
+ ...dependencies || []
3808
+ ]);
3809
+ }
3810
+
3811
+ //#endregion
3812
+ //#region src/hooks/use-default-tool.ts
3813
+ function useDefaultTool(tool, dependencies) {
3814
+ useCopilotAction({
3815
+ ...tool,
3816
+ name: "*"
3817
+ }, dependencies);
3818
+ }
3819
+
3820
+ //#endregion
3821
+ //#region src/hooks/use-copilot-chat-suggestions.tsx
3822
+ /**
3823
+ * <Callout type="warning">
3824
+ * useCopilotChatSuggestions is experimental. The interface is not final and
3825
+ * can change without notice.
3826
+ * </Callout>
3827
+ *
3828
+ * `useCopilotReadable` is a React hook that provides app-state and other information
3829
+ * to the Copilot. Optionally, the hook can also handle hierarchical state within your
3830
+ * application, passing these parent-child relationships to the Copilot.
3831
+ *
3832
+ * <br/>
3833
+ * <img src="https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-chat-suggestions/use-copilot-chat-suggestions.gif" width="500" />
3834
+ *
3835
+ * ## Usage
3836
+ *
3837
+ * ### Install Dependencies
3838
+ *
3839
+ * This component is part of the [@copilotkit/react-ui](https://npmjs.com/package/@copilotkit/react-ui) package.
3840
+ *
3841
+ * ```shell npm2yarn \"@copilotkit/react-ui"\
3842
+ * npm install @copilotkit/react-core @copilotkit/react-ui
3843
+ * ```
3844
+ *
3845
+ * ### Simple Usage
3846
+ *
3847
+ * ```tsx
3848
+ * import { useCopilotChatSuggestions } from "@copilotkit/react-ui";
3849
+ *
3850
+ * export function MyComponent() {
3851
+ * const [employees, setEmployees] = useState([]);
3852
+ *
3853
+ * useCopilotChatSuggestions({
3854
+ * instructions: `The following employees are on duty: ${JSON.stringify(employees)}`,
3855
+ * });
3856
+ * }
3857
+ * ```
3858
+ *
3859
+ * ### Dependency Management
3860
+ *
3861
+ * ```tsx
3862
+ * import { useCopilotChatSuggestions } from "@copilotkit/react-ui";
3863
+ *
3864
+ * export function MyComponent() {
3865
+ * useCopilotChatSuggestions(
3866
+ * {
3867
+ * instructions: "Suggest the most relevant next actions.",
3868
+ * },
3869
+ * [appState],
3870
+ * );
3871
+ * }
3872
+ * ```
3873
+ *
3874
+ * In the example above, the suggestions are generated based on the given instructions.
3875
+ * The hook monitors `appState`, and updates suggestions accordingly whenever it changes.
3876
+ *
3877
+ * ### Behavior and Lifecycle
3878
+ *
3879
+ * The hook registers the configuration with the chat context upon component mount and
3880
+ * removes it on unmount, ensuring a clean and efficient lifecycle management.
3881
+ */
3882
+ function useCopilotChatSuggestions(config, dependencies = []) {
3883
+ var _existingConfig$agent, _ref;
3884
+ const existingConfig = (0, _copilotkitnext_react.useCopilotChatConfiguration)();
3885
+ const resolvedAgentId = (_existingConfig$agent = existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.agentId) !== null && _existingConfig$agent !== void 0 ? _existingConfig$agent : "default";
3886
+ const available = (_ref = config.available === "enabled" ? "always" : config.available) !== null && _ref !== void 0 ? _ref : "before-first-message";
3887
+ (0, _copilotkitnext_react.useConfigureSuggestions)({
3888
+ ...config,
3889
+ available,
3890
+ consumerAgentId: resolvedAgentId
3891
+ }, dependencies);
3892
+ }
3893
+
3894
+ //#endregion
3895
+ //#region src/types/frontend-action.ts
3896
+ function processActionsForRuntimeRequest(actions) {
3897
+ return actions.filter((action) => action.available !== _copilotkit_runtime_client_gql.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*" && action.available != "frontend" && !action.pairedAction).map((action) => {
3898
+ let available = _copilotkit_runtime_client_gql.ActionInputAvailability.Enabled;
3899
+ if (action.disabled) available = _copilotkit_runtime_client_gql.ActionInputAvailability.Disabled;
3900
+ else if (action.available === "disabled") available = _copilotkit_runtime_client_gql.ActionInputAvailability.Disabled;
3901
+ else if (action.available === "remote") available = _copilotkit_runtime_client_gql.ActionInputAvailability.Remote;
3902
+ return {
3903
+ name: action.name,
3904
+ description: action.description || "",
3905
+ jsonSchema: JSON.stringify((0, _copilotkit_shared.actionParametersToJsonSchema)(action.parameters || [])),
3906
+ available
3907
+ };
3908
+ });
3909
+ }
3910
+
3911
+ //#endregion
3912
+ //#region src/lib/copilot-task.ts
3913
+ /**
3914
+ * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/v1/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/v1/hooks/useCopilotAction), or you can provide your own context and actions.
3915
+ *
3916
+ * ## Example
3917
+ * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.
3918
+ *
3919
+ * ```tsx
3920
+ * import { CopilotTask, useCopilotContext } from "@copilotkit/react-core";
3921
+ *
3922
+ * export function MyComponent() {
3923
+ * const context = useCopilotContext();
3924
+ *
3925
+ * const task = new CopilotTask({
3926
+ * instructions: "Set a random message",
3927
+ * actions: [
3928
+ * {
3929
+ * name: "setMessage",
3930
+ * description: "Set the message.",
3931
+ * argumentAnnotations: [
3932
+ * {
3933
+ * name: "message",
3934
+ * type: "string",
3935
+ * description:
3936
+ * "A message to display.",
3937
+ * required: true,
3938
+ * },
3939
+ * ],
3940
+ * }
3941
+ * ]
3942
+ * });
3943
+ *
3944
+ * const executeTask = async () => {
3945
+ * await task.run(context, action);
3946
+ * }
3947
+ *
3948
+ * return (
3949
+ * <>
3950
+ * <button onClick={executeTask}>
3951
+ * Execute task
3952
+ * </button>
3953
+ * </>
3954
+ * )
3955
+ * }
3956
+ * ```
3957
+ *
3958
+ * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/src/v1.x/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.
3959
+ */
3960
+ var CopilotTask = class {
3961
+ constructor(config) {
3962
+ this.instructions = config.instructions;
3963
+ this.actions = config.actions || [];
3964
+ this.includeCopilotReadable = config.includeCopilotReadable !== false;
3965
+ this.includeCopilotActions = config.includeCopilotActions !== false;
3966
+ this.forwardedParameters = config.forwardedParameters;
3967
+ }
3968
+ /**
3969
+ * Run the task.
3970
+ * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.
3971
+ * @param data The data to use for the task.
3972
+ */
3973
+ async run(context, data) {
3974
+ var _this$forwardedParame, _response$data;
3975
+ const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
3976
+ for (const fn of this.actions) actions[fn.name] = fn;
3977
+ let contextString = "";
3978
+ if (data) contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
3979
+ if (this.includeCopilotReadable) contextString += context.getContextString([], defaultCopilotContextCategories);
3980
+ const messages = [new _copilotkit_runtime_client_gql.TextMessage({
3981
+ content: taskSystemMessage(contextString, this.instructions),
3982
+ role: _copilotkit_runtime_client_gql.Role.System
3983
+ })];
3984
+ const response = await new _copilotkit_runtime_client_gql.CopilotRuntimeClient({
3985
+ url: context.copilotApiConfig.chatApiEndpoint,
3986
+ publicApiKey: context.copilotApiConfig.publicApiKey,
3987
+ headers: context.copilotApiConfig.headers,
3988
+ credentials: context.copilotApiConfig.credentials
3989
+ }).generateCopilotResponse({
3990
+ data: {
3991
+ frontend: {
3992
+ actions: processActionsForRuntimeRequest(Object.values(actions)),
3993
+ url: window.location.href
3994
+ },
3995
+ messages: (0, _copilotkit_runtime_client_gql.convertMessagesToGqlInput)((0, _copilotkit_runtime_client_gql.filterAgentStateMessages)(messages)),
3996
+ metadata: { requestType: _copilotkit_runtime_client_gql.CopilotRequestType.Task },
3997
+ forwardedParameters: {
3998
+ toolChoice: "required",
3999
+ ...(_this$forwardedParame = this.forwardedParameters) !== null && _this$forwardedParame !== void 0 ? _this$forwardedParame : {}
4000
+ }
4001
+ },
4002
+ properties: context.copilotApiConfig.properties
4003
+ }).toPromise();
4004
+ const functionCallHandler = context.getFunctionCallHandler(actions);
4005
+ const functionCalls = (0, _copilotkit_runtime_client_gql.convertGqlOutputToMessages)(((_response$data = response.data) === null || _response$data === void 0 || (_response$data = _response$data.generateCopilotResponse) === null || _response$data === void 0 ? void 0 : _response$data.messages) || []).filter((m) => m.isActionExecutionMessage());
4006
+ for (const functionCall of functionCalls) await functionCallHandler({
4007
+ messages,
4008
+ name: functionCall.name,
4009
+ args: functionCall.arguments
4010
+ });
4011
+ }
4012
+ };
4013
+ function taskSystemMessage(contextString, instructions) {
4014
+ return `
4015
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
4016
+
4017
+ Help 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.
4018
+ Always be polite and respectful, and prefer brevity over verbosity.
4019
+
4020
+ The user has provided you with the following context:
4021
+ \`\`\`
4022
+ ${contextString}
4023
+ \`\`\`
4024
+
4025
+ They have also provided you with functions you can call to initiate actions on their behalf.
4026
+
4027
+ Please assist them as best you can.
4028
+
4029
+ This is not a conversation, so please do not ask questions. Just call a function without saying anything else.
4030
+
4031
+ The user has given you the following task to complete:
4032
+
4033
+ \`\`\`
4034
+ ${instructions}
4035
+ \`\`\`
4036
+ `;
4037
+ }
4038
+
4039
+ //#endregion
4040
+ exports.CoAgentStateRendersContext = CoAgentStateRendersContext;
4041
+ exports.CoAgentStateRendersProvider = CoAgentStateRendersProvider;
4042
+ exports.CopilotContext = CopilotContext;
4043
+ exports.CopilotKit = CopilotKit;
4044
+ exports.CopilotMessagesContext = CopilotMessagesContext;
4045
+ exports.CopilotTask = CopilotTask;
4046
+ exports.SUGGESTION_RETRY_CONFIG = SUGGESTION_RETRY_CONFIG;
4047
+ exports.ThreadsContext = ThreadsContext;
4048
+ exports.ThreadsProvider = ThreadsProvider;
4049
+ exports.defaultCopilotContextCategories = defaultCopilotContextCategories;
4050
+ exports.shouldShowDevConsole = shouldShowDevConsole;
4051
+ exports.useCoAgent = useCoAgent;
4052
+ exports.useCoAgentStateRender = useCoAgentStateRender;
4053
+ exports.useCoAgentStateRenders = useCoAgentStateRenders;
4054
+ exports.useCopilotAction = useCopilotAction;
4055
+ exports.useCopilotAdditionalInstructions = useCopilotAdditionalInstructions;
4056
+ exports.useCopilotAuthenticatedAction_c = useCopilotAuthenticatedAction_c;
4057
+ exports.useCopilotChat = useCopilotChat;
4058
+ exports.useCopilotChatHeadless_c = useCopilotChatHeadless_c;
4059
+ exports.useCopilotChatInternal = useCopilotChatInternal;
4060
+ exports.useCopilotChatSuggestions = useCopilotChatSuggestions;
4061
+ exports.useCopilotContext = useCopilotContext;
4062
+ exports.useCopilotMessagesContext = useCopilotMessagesContext;
4063
+ exports.useCopilotReadable = useCopilotReadable;
4064
+ exports.useCopilotRuntimeClient = useCopilotRuntimeClient;
4065
+ exports.useDefaultTool = useDefaultTool;
4066
+ exports.useFrontendTool = useFrontendTool;
4067
+ exports.useHumanInTheLoop = useHumanInTheLoop;
4068
+ exports.useLangGraphInterrupt = useLangGraphInterrupt;
4069
+ exports.useLangGraphInterruptRender = useLangGraphInterruptRender;
4070
+ exports.useLazyToolRenderer = useLazyToolRenderer;
4071
+ exports.useMakeCopilotDocumentReadable = useMakeCopilotDocumentReadable;
4072
+ exports.useRenderToolCall = useRenderToolCall;
4073
+ exports.useThreads = useThreads;
4074
+ });
4075
+ //# sourceMappingURL=index.umd.js.map