@copilotkit/react-core 1.10.0-next.2 → 1.10.0-next.4

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 (190) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/{chunk-VOMGRGWT.mjs → chunk-2JAX6WE6.mjs} +7 -7
  3. package/dist/chunk-2JAX6WE6.mjs.map +1 -0
  4. package/dist/{chunk-WUORFPJ7.mjs → chunk-2WYJIO6D.mjs} +4 -4
  5. package/dist/chunk-373NOCJI.mjs +79 -0
  6. package/dist/chunk-373NOCJI.mjs.map +1 -0
  7. package/dist/{chunk-XGRBCWK6.mjs → chunk-47GMU44Z.mjs} +4 -1
  8. package/dist/chunk-47GMU44Z.mjs.map +1 -0
  9. package/dist/{chunk-DF4YG4PF.mjs → chunk-57MBVQPX.mjs} +2 -2
  10. package/dist/{chunk-JZQOCH4A.mjs → chunk-5JL5ELUS.mjs} +2 -2
  11. package/dist/{chunk-LNAQ7JG3.mjs → chunk-AC2GVFW6.mjs} +2 -2
  12. package/dist/{chunk-RGKZCCPA.mjs → chunk-AVMA2MCW.mjs} +3 -3
  13. package/dist/chunk-AWFAFFO5.mjs +221 -0
  14. package/dist/chunk-AWFAFFO5.mjs.map +1 -0
  15. package/dist/{chunk-4XVBXDCX.mjs → chunk-BBK7LXZ6.mjs} +5 -5
  16. package/dist/{chunk-YAF2LATQ.mjs → chunk-EFL5OBKN.mjs} +1 -1
  17. package/dist/chunk-EFL5OBKN.mjs.map +1 -0
  18. package/dist/{chunk-4CFY3CON.mjs → chunk-EQQSE6KM.mjs} +2 -2
  19. package/dist/{chunk-JWAXDYOW.mjs → chunk-FAUNHSQU.mjs} +3 -3
  20. package/dist/{chunk-NXCJELW7.mjs → chunk-G7J6NY5J.mjs} +3 -3
  21. package/dist/chunk-ICIK2BSB.mjs +17 -0
  22. package/dist/chunk-ICIK2BSB.mjs.map +1 -0
  23. package/dist/{chunk-PYULBXCD.mjs → chunk-JLQZVKFX.mjs} +4 -4
  24. package/dist/chunk-KDAZGZ24.mjs +1 -0
  25. package/dist/{chunk-OMVNJ7S3.mjs → chunk-L7CWMU4O.mjs} +34 -19
  26. package/dist/chunk-L7CWMU4O.mjs.map +1 -0
  27. package/dist/{chunk-3OQM3NEK.mjs → chunk-N4WEHORG.mjs} +2 -2
  28. package/dist/{chunk-Q6FZZJ5A.mjs → chunk-OL3VRQKU.mjs} +2 -2
  29. package/dist/chunk-PQ5IXT4Z.mjs +18 -0
  30. package/dist/chunk-PQ5IXT4Z.mjs.map +1 -0
  31. package/dist/{chunk-VM7CVIET.mjs → chunk-PRKL7T7P.mjs} +6 -6
  32. package/dist/chunk-PRKL7T7P.mjs.map +1 -0
  33. package/dist/{chunk-KV25ZRMH.mjs → chunk-XIHAYU6C.mjs} +4 -4
  34. package/dist/chunk-XIHAYU6C.mjs.map +1 -0
  35. package/dist/{chunk-SGF6C7I6.mjs → chunk-ZTZJIDRJ.mjs} +9 -14
  36. package/dist/chunk-ZTZJIDRJ.mjs.map +1 -0
  37. package/dist/components/copilot-provider/copilot-messages.js +12 -1
  38. package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
  39. package/dist/components/copilot-provider/copilot-messages.mjs +4 -4
  40. package/dist/components/copilot-provider/copilotkit-props.d.ts +1 -1
  41. package/dist/components/copilot-provider/copilotkit.d.ts +1 -1
  42. package/dist/components/copilot-provider/copilotkit.js +307 -550
  43. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  44. package/dist/components/copilot-provider/copilotkit.mjs +9 -9
  45. package/dist/components/copilot-provider/index.d.ts +1 -1
  46. package/dist/components/copilot-provider/index.js +307 -550
  47. package/dist/components/copilot-provider/index.js.map +1 -1
  48. package/dist/components/copilot-provider/index.mjs +9 -9
  49. package/dist/components/error-boundary/error-boundary.js +172 -323
  50. package/dist/components/error-boundary/error-boundary.js.map +1 -1
  51. package/dist/components/error-boundary/error-boundary.mjs +4 -4
  52. package/dist/components/error-boundary/error-utils.js.map +1 -1
  53. package/dist/components/error-boundary/error-utils.mjs +2 -2
  54. package/dist/components/index.d.ts +1 -1
  55. package/dist/components/index.js +307 -550
  56. package/dist/components/index.js.map +1 -1
  57. package/dist/components/index.mjs +9 -9
  58. package/dist/components/toast/toast-provider.js.map +1 -1
  59. package/dist/components/toast/toast-provider.mjs +1 -1
  60. package/dist/components/usage-banner.d.ts +8 -3
  61. package/dist/components/usage-banner.js +172 -302
  62. package/dist/components/usage-banner.js.map +1 -1
  63. package/dist/components/usage-banner.mjs +3 -1
  64. package/dist/context/copilot-context.d.ts +1 -1
  65. package/dist/context/copilot-context.js +3 -0
  66. package/dist/context/copilot-context.js.map +1 -1
  67. package/dist/context/copilot-context.mjs +1 -1
  68. package/dist/context/index.d.ts +1 -1
  69. package/dist/context/index.js +3 -0
  70. package/dist/context/index.js.map +1 -1
  71. package/dist/context/index.mjs +1 -1
  72. package/dist/{copilot-context-bd88d30d.d.ts → copilot-context-78fc727c.d.ts} +3 -1
  73. package/dist/hooks/index.d.ts +5 -3
  74. package/dist/hooks/index.js +143 -57
  75. package/dist/hooks/index.js.map +1 -1
  76. package/dist/hooks/index.mjs +32 -24
  77. package/dist/hooks/use-chat.d.ts +1 -1
  78. package/dist/hooks/use-chat.js +12 -1
  79. package/dist/hooks/use-chat.js.map +1 -1
  80. package/dist/hooks/use-chat.mjs +6 -6
  81. package/dist/hooks/use-coagent-state-render.js +3 -0
  82. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  83. package/dist/hooks/use-coagent-state-render.mjs +3 -3
  84. package/dist/hooks/use-coagent.d.ts +1 -1
  85. package/dist/hooks/use-coagent.js +15 -4
  86. package/dist/hooks/use-coagent.js.map +1 -1
  87. package/dist/hooks/use-coagent.mjs +13 -13
  88. package/dist/hooks/use-copilot-action.js +3 -0
  89. package/dist/hooks/use-copilot-action.js.map +1 -1
  90. package/dist/hooks/use-copilot-action.mjs +4 -4
  91. package/dist/hooks/use-copilot-additional-instructions.js +3 -0
  92. package/dist/hooks/use-copilot-additional-instructions.js.map +1 -1
  93. package/dist/hooks/use-copilot-additional-instructions.mjs +2 -2
  94. package/dist/hooks/use-copilot-authenticated-action.js +3 -0
  95. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  96. package/dist/hooks/use-copilot-authenticated-action.mjs +5 -5
  97. package/dist/hooks/use-copilot-chat-light.d.ts +211 -0
  98. package/dist/hooks/use-copilot-chat-light.js +1770 -0
  99. package/dist/hooks/use-copilot-chat-light.js.map +1 -0
  100. package/dist/hooks/use-copilot-chat-light.mjs +28 -0
  101. package/dist/hooks/use-copilot-chat-light.mjs.map +1 -0
  102. package/dist/hooks/use-copilot-chat.d.ts +9 -81
  103. package/dist/hooks/use-copilot-chat.js +77 -5
  104. package/dist/hooks/use-copilot-chat.js.map +1 -1
  105. package/dist/hooks/use-copilot-chat.mjs +15 -13
  106. package/dist/hooks/use-copilot-chat_internal.d.ts +91 -0
  107. package/dist/hooks/use-copilot-chat_internal.js +1760 -0
  108. package/dist/hooks/use-copilot-chat_internal.js.map +1 -0
  109. package/dist/hooks/use-copilot-chat_internal.mjs +29 -0
  110. package/dist/hooks/use-copilot-chat_internal.mjs.map +1 -0
  111. package/dist/hooks/use-copilot-readable.js +3 -0
  112. package/dist/hooks/use-copilot-readable.js.map +1 -1
  113. package/dist/hooks/use-copilot-readable.mjs +2 -2
  114. package/dist/hooks/use-copilot-runtime-client.js +9 -1
  115. package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
  116. package/dist/hooks/use-copilot-runtime-client.mjs +3 -3
  117. package/dist/hooks/use-langgraph-interrupt-render.js +3 -0
  118. package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -1
  119. package/dist/hooks/use-langgraph-interrupt-render.mjs +2 -2
  120. package/dist/hooks/use-langgraph-interrupt.d.ts +1 -1
  121. package/dist/hooks/use-langgraph-interrupt.js +15 -4
  122. package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
  123. package/dist/hooks/use-langgraph-interrupt.mjs +13 -13
  124. package/dist/hooks/use-make-copilot-document-readable.js +3 -0
  125. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  126. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  127. package/dist/index.d.ts +4 -2
  128. package/dist/index.js +384 -449
  129. package/dist/index.js.map +1 -1
  130. package/dist/index.mjs +34 -26
  131. package/dist/lib/copilot-task.d.ts +1 -1
  132. package/dist/lib/copilot-task.js.map +1 -1
  133. package/dist/lib/copilot-task.mjs +10 -10
  134. package/dist/lib/index.d.ts +1 -1
  135. package/dist/lib/index.js.map +1 -1
  136. package/dist/lib/index.mjs +10 -10
  137. package/dist/types/interrupt-action.d.ts +1 -1
  138. package/dist/utils/dev-console.d.ts +1 -1
  139. package/dist/utils/dev-console.js +9 -1
  140. package/dist/utils/dev-console.js.map +1 -1
  141. package/dist/utils/dev-console.mjs +1 -1
  142. package/dist/utils/extract.d.ts +1 -1
  143. package/dist/utils/extract.js.map +1 -1
  144. package/dist/utils/extract.mjs +9 -9
  145. package/dist/utils/index.d.ts +1 -1
  146. package/dist/utils/index.js +9 -1
  147. package/dist/utils/index.js.map +1 -1
  148. package/dist/utils/index.mjs +9 -9
  149. package/dist/utils/suggestions.d.ts +1 -1
  150. package/dist/utils/suggestions.js.map +1 -1
  151. package/dist/utils/suggestions.mjs +9 -9
  152. package/package.json +3 -3
  153. package/src/components/copilot-provider/copilotkit.tsx +16 -5
  154. package/src/components/error-boundary/error-boundary.tsx +5 -15
  155. package/src/components/toast/toast-provider.tsx +1 -3
  156. package/src/components/usage-banner.tsx +187 -315
  157. package/src/context/copilot-context.tsx +12 -1
  158. package/src/hooks/__tests__/use-coagent-config.test.ts +1 -1
  159. package/src/hooks/index.ts +6 -0
  160. package/src/hooks/use-coagent.ts +1 -1
  161. package/src/hooks/use-copilot-chat-light.ts +219 -0
  162. package/src/hooks/use-copilot-chat.ts +89 -430
  163. package/src/hooks/use-copilot-chat_internal.ts +437 -0
  164. package/src/hooks/use-langgraph-interrupt.ts +1 -1
  165. package/src/utils/dev-console.ts +18 -2
  166. package/dist/chunk-57K2ZJ5F.mjs +0 -348
  167. package/dist/chunk-57K2ZJ5F.mjs.map +0 -1
  168. package/dist/chunk-CQPYJIBH.mjs +0 -1
  169. package/dist/chunk-GFJW4RIM.mjs +0 -9
  170. package/dist/chunk-GFJW4RIM.mjs.map +0 -1
  171. package/dist/chunk-KV25ZRMH.mjs.map +0 -1
  172. package/dist/chunk-OMVNJ7S3.mjs.map +0 -1
  173. package/dist/chunk-SGF6C7I6.mjs.map +0 -1
  174. package/dist/chunk-VM7CVIET.mjs.map +0 -1
  175. package/dist/chunk-VOMGRGWT.mjs.map +0 -1
  176. package/dist/chunk-XGRBCWK6.mjs.map +0 -1
  177. package/dist/chunk-YAF2LATQ.mjs.map +0 -1
  178. /package/dist/{chunk-WUORFPJ7.mjs.map → chunk-2WYJIO6D.mjs.map} +0 -0
  179. /package/dist/{chunk-DF4YG4PF.mjs.map → chunk-57MBVQPX.mjs.map} +0 -0
  180. /package/dist/{chunk-JZQOCH4A.mjs.map → chunk-5JL5ELUS.mjs.map} +0 -0
  181. /package/dist/{chunk-LNAQ7JG3.mjs.map → chunk-AC2GVFW6.mjs.map} +0 -0
  182. /package/dist/{chunk-RGKZCCPA.mjs.map → chunk-AVMA2MCW.mjs.map} +0 -0
  183. /package/dist/{chunk-4XVBXDCX.mjs.map → chunk-BBK7LXZ6.mjs.map} +0 -0
  184. /package/dist/{chunk-4CFY3CON.mjs.map → chunk-EQQSE6KM.mjs.map} +0 -0
  185. /package/dist/{chunk-JWAXDYOW.mjs.map → chunk-FAUNHSQU.mjs.map} +0 -0
  186. /package/dist/{chunk-NXCJELW7.mjs.map → chunk-G7J6NY5J.mjs.map} +0 -0
  187. /package/dist/{chunk-PYULBXCD.mjs.map → chunk-JLQZVKFX.mjs.map} +0 -0
  188. /package/dist/{chunk-CQPYJIBH.mjs.map → chunk-KDAZGZ24.mjs.map} +0 -0
  189. /package/dist/{chunk-3OQM3NEK.mjs.map → chunk-N4WEHORG.mjs.map} +0 -0
  190. /package/dist/{chunk-Q6FZZJ5A.mjs.map → chunk-OL3VRQKU.mjs.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/toast/toast-provider.tsx"],"sourcesContent":["import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { PartialBy, CopilotKitError, Severity } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n // Banner management\n bannerError: CopilotKitError | null;\n setBannerError: (error: CopilotKitError | null) => void;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\n// Helper functions for error banner styling\ntype ErrorSeverity = \"critical\" | \"warning\" | \"info\";\n\ninterface ErrorColors {\n background: string;\n border: string;\n text: string;\n icon: string;\n}\n\nfunction getErrorSeverity(error: CopilotKitError): ErrorSeverity {\n // Use structured error severity if available\n if (error.severity) {\n switch (error.severity) {\n case Severity.CRITICAL:\n return \"critical\";\n case Severity.WARNING:\n return \"warning\";\n case Severity.INFO:\n return \"info\";\n default:\n return \"info\";\n }\n }\n\n // Fallback: Check for API key errors which should always be critical\n const message = error.message.toLowerCase();\n if (\n message.includes(\"api key\") ||\n message.includes(\"401\") ||\n message.includes(\"unauthorized\") ||\n message.includes(\"authentication\") ||\n message.includes(\"incorrect api key\")\n ) {\n return \"critical\";\n }\n\n // Default to info level\n return \"info\";\n}\n\nfunction getErrorColors(severity: ErrorSeverity): ErrorColors {\n switch (severity) {\n case \"critical\":\n return {\n background: \"#fee2e2\",\n border: \"#dc2626\",\n text: \"#7f1d1d\",\n icon: \"#dc2626\",\n };\n case \"warning\":\n return {\n background: \"#fef3c7\",\n border: \"#d97706\",\n text: \"#78350f\",\n icon: \"#d97706\",\n };\n case \"info\":\n return {\n background: \"#dbeafe\",\n border: \"#2563eb\",\n text: \"#1e3a8a\",\n icon: \"#2563eb\",\n };\n }\n}\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const [bannerError, setBannerErrorState] = useState<CopilotKitError | null>(null);\n\n const removeToast = useCallback((id: string) => {\n setToasts((prev) => prev.filter((toast) => toast.id !== id));\n }, []);\n\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // Respect the enabled flag for ALL toasts\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled, removeToast],\n );\n\n const setBannerError = useCallback(\n (error: CopilotKitError | null) => {\n // Respect the enabled flag for ALL errors\n if (!enabled && error !== null) {\n return;\n }\n setBannerErrorState(error);\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // DEPRECATED: All errors now route to banners for consistency\n console.warn(\"addGraphQLErrorsToast is deprecated. All errors now show as banners.\");\n // Function kept for backward compatibility - does nothing\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n bannerError,\n setBannerError,\n };\n\n return (\n <ToastContext.Provider value={value}>\n {/* Banner Error Display */}\n {bannerError &&\n (() => {\n const severity = getErrorSeverity(bannerError);\n const colors = getErrorColors(severity);\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"20px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 9999,\n backgroundColor: colors.background,\n border: `1px solid ${colors.border}`,\n borderLeft: `4px solid ${colors.border}`,\n borderRadius: \"8px\",\n padding: \"12px 16px\",\n fontSize: \"13px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n backdropFilter: \"blur(8px)\",\n maxWidth: \"min(90vw, 700px)\",\n width: \"100%\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: \"10px\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n width: \"12px\",\n height: \"12px\",\n borderRadius: \"50%\",\n backgroundColor: colors.border,\n flexShrink: 0,\n }}\n />\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"10px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n color: colors.text,\n lineHeight: \"1.4\",\n fontWeight: \"400\",\n fontSize: \"13px\",\n flex: 1,\n wordBreak: \"break-all\",\n overflowWrap: \"break-word\",\n maxWidth: \"550px\",\n overflow: \"hidden\",\n display: \"-webkit-box\",\n WebkitLineClamp: 10,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {(() => {\n let message = bannerError.message;\n\n // Try to extract the useful message from JSON first\n const jsonMatch = message.match(/'message':\\s*'([^']+)'/);\n if (jsonMatch) {\n return jsonMatch[1]; // Return the actual error message\n }\n\n // Strip technical garbage but keep the meaningful message\n message = message.split(\" - \")[0]; // Remove everything after \" - {\"\n message = message.split(\": Error code\")[0]; // Remove \": Error code: 401\"\n message = message.replace(/:\\s*\\d{3}$/, \"\"); // Remove trailing \": 401\"\n message = message.replace(/See more:.*$/g, \"\"); // Remove \"See more\" links\n message = message.trim();\n\n // If it's still garbage (contains { or '), use fallback\n // if (message.includes(\"{\") || message.includes(\"'\")) {\n // return \"Configuration error.... Please check your setup.\";\n // }\n\n return message || \"Configuration error occurred.\";\n })()}\n </div>\n\n {(() => {\n const message = bannerError.message;\n const markdownLinkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const plainUrlRegex = /(https?:\\/\\/[^\\s)]+)/g;\n\n // Extract the first URL found\n let url = null;\n let buttonText = \"See More\";\n\n // Check for markdown links first\n const markdownMatch = markdownLinkRegex.exec(message);\n if (markdownMatch) {\n url = markdownMatch[2];\n buttonText = \"See More\";\n } else {\n // Check for plain URLs\n const urlMatch = plainUrlRegex.exec(message);\n if (urlMatch) {\n url = urlMatch[0].replace(/[.,;:'\"]*$/, \"\"); // Remove trailing punctuation\n buttonText = \"See More\";\n }\n }\n\n if (!url) return null;\n\n return (\n <button\n onClick={() => window.open(url, \"_blank\", \"noopener,noreferrer\")}\n style={{\n background: colors.border,\n color: \"white\",\n border: \"none\",\n borderRadius: \"5px\",\n padding: \"4px 10px\",\n fontSize: \"11px\",\n fontWeight: \"500\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"0.9\";\n e.currentTarget.style.transform = \"translateY(-1px)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {buttonText}\n </button>\n );\n })()}\n </div>\n </div>\n <button\n onClick={() => setBannerError(null)}\n style={{\n background: \"transparent\",\n border: \"none\",\n color: colors.text,\n cursor: \"pointer\",\n padding: \"2px\",\n borderRadius: \"3px\",\n fontSize: \"14px\",\n lineHeight: \"1\",\n opacity: 0.6,\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n title=\"Dismiss\"\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.05)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"0.6\";\n e.currentTarget.style.background = \"transparent\";\n }}\n >\n ×\n </button>\n </div>\n </div>\n );\n })()}\n\n {/* Toast Display - Deprecated: All errors now show as banners */}\n {children}\n </ToastContext.Provider>\n );\n}\n\n// Toast component removed - all errors now show as banners for consistency\n"],"mappings":";;;;;;AACA,SAAgB,eAAe,YAAY,UAAU,mBAAmB;AACxE,SAAqC,gBAAgB;AAgNnC,cASA,YATA;AA5LlB,IAAM,eAAe,cAA6C,MAAS;AAY3E,SAAS,iBAAiB,OAAuC;AAE/D,MAAI,MAAM,UAAU;AAClB,YAAQ,MAAM,UAAU;AAAA,MACtB,KAAK,SAAS;AACZ,eAAO;AAAA,MACT,KAAK,SAAS;AACZ,eAAO;AAAA,MACT,KAAK,SAAS;AACZ,eAAO;AAAA,MACT;AACE,eAAO;AAAA,IACX;AAAA,EACF;AAGA,QAAM,UAAU,MAAM,QAAQ,YAAY;AAC1C,MACE,QAAQ,SAAS,SAAS,KAC1B,QAAQ,SAAS,KAAK,KACtB,QAAQ,SAAS,cAAc,KAC/B,QAAQ,SAAS,gBAAgB,KACjC,QAAQ,SAAS,mBAAmB,GACpC;AACA,WAAO;AAAA,EACT;AAGA,SAAO;AACT;AAEA,SAAS,eAAe,UAAsC;AAC5D,UAAQ,UAAU;AAAA,IAChB,KAAK;AACH,aAAO;AAAA,QACL,YAAY;AAAA,QACZ,QAAQ;AAAA,QACR,MAAM;AAAA,QACN,MAAM;AAAA,MACR;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,YAAY;AAAA,QACZ,QAAQ;AAAA,QACR,MAAM;AAAA,QACN,MAAM;AAAA,MACR;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,YAAY;AAAA,QACZ,QAAQ;AAAA,QACR,MAAM;AAAA,QACN,MAAM;AAAA,MACR;AAAA,EACJ;AACF;AAEO,SAAS,WAAW;AACzB,QAAM,UAAU,WAAW,YAAY;AACvC,MAAI,CAAC,SA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44Z.mjs";
4
4
 
5
5
  // src/hooks/use-make-copilot-document-readable.ts
6
6
  import { useEffect, useRef } from "react";
@@ -20,4 +20,4 @@ function useMakeCopilotDocumentReadable(document, categories, dependencies = [])
20
20
  export {
21
21
  useMakeCopilotDocumentReadable
22
22
  };
23
- //# sourceMappingURL=chunk-4CFY3CON.mjs.map
23
+ //# sourceMappingURL=chunk-EQQSE6KM.mjs.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  shouldShowDevConsole
3
- } from "./chunk-GFJW4RIM.mjs";
3
+ } from "./chunk-ICIK2BSB.mjs";
4
4
  import {
5
5
  useToast
6
- } from "./chunk-YAF2LATQ.mjs";
6
+ } from "./chunk-EFL5OBKN.mjs";
7
7
  import {
8
8
  __async,
9
9
  __objRest,
@@ -146,4 +146,4 @@ function createStructuredError(gqlError) {
146
146
  export {
147
147
  useCopilotRuntimeClient
148
148
  };
149
- //# sourceMappingURL=chunk-JWAXDYOW.mjs.map
149
+ //# sourceMappingURL=chunk-FAUNHSQU.mjs.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  useCopilotAction
3
- } from "./chunk-WUORFPJ7.mjs";
3
+ } from "./chunk-2WYJIO6D.mjs";
4
4
  import {
5
5
  useCopilotContext
6
- } from "./chunk-XGRBCWK6.mjs";
6
+ } from "./chunk-47GMU44Z.mjs";
7
7
  import {
8
8
  __spreadProps,
9
9
  __spreadValues
@@ -56,4 +56,4 @@ function useCopilotAuthenticatedAction_c(action, dependencies) {
56
56
  export {
57
57
  useCopilotAuthenticatedAction_c
58
58
  };
59
- //# sourceMappingURL=chunk-NXCJELW7.mjs.map
59
+ //# sourceMappingURL=chunk-G7J6NY5J.mjs.map
@@ -0,0 +1,17 @@
1
+ // src/utils/dev-console.ts
2
+ function isLocalhost() {
3
+ if (typeof window === "undefined")
4
+ return false;
5
+ return window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1" || window.location.hostname === "0.0.0.0";
6
+ }
7
+ function shouldShowDevConsole(showDevConsole) {
8
+ if (showDevConsole !== void 0) {
9
+ return showDevConsole;
10
+ }
11
+ return isLocalhost();
12
+ }
13
+
14
+ export {
15
+ shouldShowDevConsole
16
+ };
17
+ //# sourceMappingURL=chunk-ICIK2BSB.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/dev-console.ts"],"sourcesContent":["function isLocalhost(): boolean {\n if (typeof window === \"undefined\") return false;\n\n return (\n window.location.hostname === \"localhost\" ||\n window.location.hostname === \"127.0.0.1\" ||\n window.location.hostname === \"0.0.0.0\"\n );\n}\n\nexport function shouldShowDevConsole(showDevConsole?: boolean): boolean {\n // If explicitly set, use that value\n if (showDevConsole !== undefined) {\n return showDevConsole;\n }\n\n // If not set, default to true on localhost\n return isLocalhost();\n}\n"],"mappings":";AAAA,SAAS,cAAuB;AAC9B,MAAI,OAAO,WAAW;AAAa,WAAO;AAE1C,SACE,OAAO,SAAS,aAAa,eAC7B,OAAO,SAAS,aAAa,eAC7B,OAAO,SAAS,aAAa;AAEjC;AAEO,SAAS,qBAAqB,gBAAmC;AAEtE,MAAI,mBAAmB,QAAW;AAChC,WAAO;AAAA,EACT;AAGA,SAAO,YAAY;AACrB;","names":[]}
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  shouldShowDevConsole
3
- } from "./chunk-GFJW4RIM.mjs";
3
+ } from "./chunk-ICIK2BSB.mjs";
4
4
  import {
5
5
  useToast
6
- } from "./chunk-YAF2LATQ.mjs";
6
+ } from "./chunk-EFL5OBKN.mjs";
7
7
  import {
8
8
  useCopilotContext
9
- } from "./chunk-XGRBCWK6.mjs";
9
+ } from "./chunk-47GMU44Z.mjs";
10
10
  import {
11
11
  CopilotMessagesContext
12
12
  } from "./chunk-DCTJZ742.mjs";
@@ -185,4 +185,4 @@ function CopilotMessages({ children }) {
185
185
  export {
186
186
  CopilotMessages
187
187
  };
188
- //# sourceMappingURL=chunk-PYULBXCD.mjs.map
188
+ //# sourceMappingURL=chunk-JLQZVKFX.mjs.map
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=chunk-KDAZGZ24.mjs.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  CopilotMessages
3
- } from "./chunk-PYULBXCD.mjs";
3
+ } from "./chunk-JLQZVKFX.mjs";
4
4
  import {
5
5
  CopilotErrorBoundary
6
- } from "./chunk-SGF6C7I6.mjs";
6
+ } from "./chunk-ZTZJIDRJ.mjs";
7
7
  import {
8
8
  StatusChecker
9
9
  } from "./chunk-PMAFHQ7P.mjs";
@@ -15,16 +15,20 @@ import {
15
15
  } from "./chunk-RKTVJRK7.mjs";
16
16
  import {
17
17
  useCopilotRuntimeClient
18
- } from "./chunk-JWAXDYOW.mjs";
18
+ } from "./chunk-FAUNHSQU.mjs";
19
19
  import {
20
20
  shouldShowDevConsole
21
- } from "./chunk-GFJW4RIM.mjs";
21
+ } from "./chunk-ICIK2BSB.mjs";
22
22
  import {
23
23
  ToastProvider
24
- } from "./chunk-YAF2LATQ.mjs";
24
+ } from "./chunk-EFL5OBKN.mjs";
25
+ import {
26
+ UsageBanner,
27
+ getErrorActions
28
+ } from "./chunk-AWFAFFO5.mjs";
25
29
  import {
26
30
  CopilotContext
27
- } from "./chunk-XGRBCWK6.mjs";
31
+ } from "./chunk-47GMU44Z.mjs";
28
32
  import {
29
33
  __async,
30
34
  __objRest,
@@ -189,16 +193,13 @@ Available tools: ${tools}
189
193
  });
190
194
 
191
195
  // src/components/copilot-provider/copilotkit.tsx
192
- import { jsx } from "react/jsx-runtime";
196
+ import { jsx, jsxs } from "react/jsx-runtime";
193
197
  function CopilotKit(_a) {
194
198
  var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
195
- var _a2;
196
- const showDevConsole = (_a2 = props.showDevConsole) != null ? _a2 : false;
197
- const enabled = shouldShowDevConsole(showDevConsole);
199
+ const enabled = shouldShowDevConsole(props.showDevConsole);
198
200
  return /* @__PURE__ */ jsx(ToastProvider, { enabled, children: /* @__PURE__ */ jsx(CopilotErrorBoundary, { publicApiKey: props.publicApiKey, showUsageBanner: enabled, children: /* @__PURE__ */ jsx(CopilotKitInternal, __spreadProps(__spreadValues({}, props), { children })) }) });
199
201
  }
200
202
  function CopilotKitInternal(cpkProps) {
201
- var _b, _c;
202
203
  const _a = cpkProps, { children } = _a, props = __objRest(_a, ["children"]);
203
204
  validateProps(cpkProps);
204
205
  const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;
@@ -302,7 +303,7 @@ ${nonDocumentStrings}`;
302
303
  [removeDocument]
303
304
  );
304
305
  const copilotApiConfig = useMemo(() => {
305
- var _a2, _b2;
306
+ var _a2, _b;
306
307
  let cloud = void 0;
307
308
  if (props.publicApiKey) {
308
309
  cloud = {
@@ -311,7 +312,7 @@ ${nonDocumentStrings}`;
311
312
  restrictToTopic: {
312
313
  enabled: Boolean(props.guardrails_c),
313
314
  validTopics: ((_a2 = props.guardrails_c) == null ? void 0 : _a2.validTopics) || [],
314
- invalidTopics: ((_b2 = props.guardrails_c) == null ? void 0 : _b2.invalidTopics) || []
315
+ invalidTopics: ((_b = props.guardrails_c) == null ? void 0 : _b.invalidTopics) || []
315
316
  }
316
317
  }
317
318
  }
@@ -356,7 +357,7 @@ ${nonDocumentStrings}`;
356
357
  publicApiKey: copilotApiConfig.publicApiKey,
357
358
  headers,
358
359
  credentials: copilotApiConfig.credentials,
359
- showDevConsole: (_b = props.showDevConsole) != null ? _b : false,
360
+ showDevConsole: shouldShowDevConsole(props.showDevConsole),
360
361
  onError: props.onError
361
362
  });
362
363
  const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState({});
@@ -435,7 +436,7 @@ ${nonDocumentStrings}`;
435
436
  }, [props.threadId]);
436
437
  const [runId, setRunId] = useState(null);
437
438
  const chatAbortControllerRef = useRef(null);
438
- const showDevConsole = (_c = props.showDevConsole) != null ? _c : false;
439
+ const showDevConsole = shouldShowDevConsole(props.showDevConsole);
439
440
  const [langGraphInterruptAction, _setLangGraphInterruptAction] = useState(null);
440
441
  const setLangGraphInterruptAction = useCallback((action) => {
441
442
  _setLangGraphInterruptAction((prev) => {
@@ -454,6 +455,7 @@ ${nonDocumentStrings}`;
454
455
  setLangGraphInterruptAction(null);
455
456
  }, []);
456
457
  const memoizedChildren = useMemo(() => children, [children]);
458
+ const [bannerError, setBannerError] = useState(null);
457
459
  const [suggestions, setSuggestions] = useState([]);
458
460
  const agentLock = useMemo(() => {
459
461
  var _a2;
@@ -490,7 +492,7 @@ ${nonDocumentStrings}`;
490
492
  },
491
493
  [setAuthStates]
492
494
  );
493
- return /* @__PURE__ */ jsx(
495
+ return /* @__PURE__ */ jsxs(
494
496
  CopilotContext.Provider,
495
497
  {
496
498
  value: {
@@ -545,9 +547,22 @@ ${nonDocumentStrings}`;
545
547
  removeLangGraphInterruptAction,
546
548
  onError: props.onError,
547
549
  suggestions,
548
- setSuggestions
550
+ setSuggestions,
551
+ bannerError,
552
+ setBannerError
549
553
  },
550
- children: /* @__PURE__ */ jsx(CopilotMessages, { children: memoizedChildren })
554
+ children: [
555
+ /* @__PURE__ */ jsx(CopilotMessages, { children: memoizedChildren }),
556
+ bannerError && showDevConsole && /* @__PURE__ */ jsx(
557
+ UsageBanner,
558
+ {
559
+ severity: bannerError.severity,
560
+ message: bannerError.message,
561
+ onClose: () => setBannerError(null),
562
+ actions: getErrorActions(bannerError)
563
+ }
564
+ )
565
+ ]
551
566
  }
552
567
  );
553
568
  }
@@ -734,4 +749,4 @@ export {
734
749
  CopilotKitInternal,
735
750
  defaultCopilotContextCategories
736
751
  };
737
- //# sourceMappingURL=chunk-OMVNJ7S3.mjs.map
752
+ //# sourceMappingURL=chunk-L7CWMU4O.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/extract.ts","../src/components/copilot-provider/copilotkit.tsx","../src/utils/suggestions.ts"],"sourcesContent":["import {\n Action,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n MappedParameterTypes,\n Parameter,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n ActionExecutionMessage,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CopilotRuntimeClient } from \"@copilotkit/runtime-client-gql\";\nimport {\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n} from \"@copilotkit/runtime-client-gql\";\n\ninterface InitialState<T extends Parameter[] | [] = []> {\n status: \"initial\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n}\n\ntype StreamHandlerArgs<T extends Parameter[] | [] = []> =\n | InitialState<T>\n | InProgressState<T>\n | CompleteState<T>;\n\ninterface ExtractOptions<T extends Parameter[]> {\n context: CopilotContextParams & CopilotMessagesContextParams;\n instructions: string;\n parameters: T;\n include?: IncludeOptions;\n data?: any;\n abortSignal?: AbortSignal;\n stream?: (args: StreamHandlerArgs<T>) => void;\n requestType?: CopilotRequestType;\n forwardedParameters?: ForwardedParametersInput;\n}\n\ninterface IncludeOptions {\n readable?: boolean;\n messages?: boolean;\n}\n\nexport async function extract<const T extends Parameter[]>({\n context,\n instructions,\n parameters,\n include,\n data,\n abortSignal,\n stream,\n requestType = CopilotRequestType.Task,\n forwardedParameters,\n}: ExtractOptions<T>): Promise<MappedParameterTypes<T>> {\n const { messages } = context;\n\n const action: Action<any> = {\n name: \"extract\",\n description: instructions,\n parameters,\n handler: (args: any) => {},\n };\n\n const includeReadable = include?.readable ?? false;\n const includeMessages = include?.messages ?? false;\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (includeReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage: Message = new TextMessage({\n content: makeSystemMessage(contextString, instructions),\n role: Role.System,\n });\n\n const instructionsMessage: Message = new TextMessage({\n content: makeInstructionsMessage(instructions),\n role: Role.User,\n });\n\n const response = context.runtimeClient.asStream(\n context.runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [\n {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n },\n ],\n url: window.location.href,\n },\n\n messages: convertMessagesToGqlInput(\n includeMessages\n ? [systemMessage, instructionsMessage, ...filterAgentStateMessages(messages)]\n : [systemMessage, instructionsMessage],\n ),\n metadata: {\n requestType: requestType,\n },\n forwardedParameters: {\n ...(forwardedParameters ?? {}),\n toolChoice: \"function\",\n toolChoiceFunctionName: action.name,\n },\n },\n properties: context.copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n\n const reader = response.getReader();\n\n let isInitial = true;\n\n let actionExecutionMessage: ActionExecutionMessage | undefined = undefined;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (abortSignal?.aborted) {\n throw new Error(\"Aborted\");\n }\n\n actionExecutionMessage = convertGqlOutputToMessages(\n value.generateCopilotResponse.messages,\n ).find((msg) => msg.isActionExecutionMessage()) as ActionExecutionMessage | undefined;\n\n if (!actionExecutionMessage) {\n continue;\n }\n\n stream?.({\n status: isInitial ? \"initial\" : \"inProgress\",\n args: actionExecutionMessage.arguments as Partial<MappedParameterTypes<T>>,\n });\n\n isInitial = false;\n }\n\n if (!actionExecutionMessage) {\n throw new Error(\"extract() failed: No function call occurred\");\n }\n\n stream?.({\n status: \"complete\",\n args: actionExecutionMessage.arguments as MappedParameterTypes<T>,\n });\n\n return actionExecutionMessage.arguments as MappedParameterTypes<T>;\n}\n\n// We need to put this in a user message since some LLMs need\n// at least one user message to function\nfunction makeInstructionsMessage(instructions: string): string {\n return `\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n\nAny additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.\n`;\n}\n\nfunction makeSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with a function called extract you MUST 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 the function without saying anything else.\n`;\n}\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState, SetStateAction } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n AuthState,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n randomUUID,\n ConfigurationError,\n MissingPublicApiKeyError,\n CopilotKitError,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoAgentStateRender } from \"../../types/coagent-action\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { getErrorActions, UsageBanner } from \"../usage-banner\";\nimport { useCopilotRuntimeClient } from \"../../hooks/use-copilot-runtime-client\";\nimport { shouldShowDevConsole } from \"../../utils\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\nimport { Agent, ExtensionsInput } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetterArgs,\n} from \"../../types/interrupt-action\";\nimport { StatusChecker } from \"../../lib/status-checker\";\nimport { SuggestionItem } from \"../../utils/suggestions\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const enabled = shouldShowDevConsole(props.showDevConsole);\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary publicApiKey={props.publicApiKey} showUsageBanner={enabled}>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal(cpkProps: CopilotKitProps) {\n const { children, ...props } = cpkProps;\n\n /**\n * This will throw an error if the props are invalid.\n */\n validateProps(cpkProps);\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n\n const { addElement, removeElement, printTree, getAllElements } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});\n const [extensions, setExtensions] = useState<ExtensionsInput>({});\n const [additionalInstructions, setAdditionalInstructions] = useState<string[]>([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const statusChecker = useMemo(() => new StatusChecker(), []);\n\n const [usageBannerStatus, setUsageBannerStatus] = useState<any>(null);\n\n // Compute all the functions and properties that we need to pass\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const setCoAgentStateRender = useCallback((id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => {\n return {\n ...prevPoints,\n [id]: stateRender,\n };\n });\n }, []);\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getAllContext = useCallback(() => {\n return getAllElements();\n }, [getAllElements]);\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n props.publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n props.guardrails_c,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n showDevConsole: shouldShowDevConsole(props.showDevConsole),\n onError: props.onError,\n });\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = useCallback(\n (id: string, suggestion: CopilotChatSuggestionConfiguration) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n },\n [setChatSuggestionConfiguration],\n );\n\n const removeChatSuggestionConfiguration = useCallback(\n (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n },\n [setChatSuggestionConfiguration],\n );\n\n const [availableAgents, setAvailableAgents] = useState<Agent[]>([]);\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => {\n const newValue = typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n const hasLoadedAgents = useRef(false);\n\n useEffect(() => {\n if (hasLoadedAgents.current) return;\n\n const fetchData = async () => {\n const result = await runtimeClient.availableAgents();\n if (result.data?.availableAgents) {\n setAvailableAgents(result.data.availableAgents.agents);\n }\n hasLoadedAgents.current = true;\n };\n void fetchData();\n }, []);\n\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n\n // Update agentSession when props.agent changes\n useEffect(() => {\n if (props.agent) {\n setAgentSession({\n agentName: props.agent,\n });\n } else {\n setAgentSession(null);\n }\n }, [props.agent]);\n\n const [internalThreadId, setInternalThreadId] = useState<string>(props.threadId || randomUUID());\n const setThreadId = useCallback(\n (value: SetStateAction<string>) => {\n if (props.threadId) {\n throw new Error(\"Cannot call setThreadId() when threadId is provided via props.\");\n }\n setInternalThreadId(value);\n },\n [props.threadId],\n );\n\n // update the internal threadId if the props.threadId changes\n useEffect(() => {\n if (props.threadId !== undefined) {\n setInternalThreadId(props.threadId);\n }\n }, [props.threadId]);\n\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = shouldShowDevConsole(props.showDevConsole);\n\n const [langGraphInterruptAction, _setLangGraphInterruptAction] =\n useState<LangGraphInterruptAction | null>(null);\n const setLangGraphInterruptAction = useCallback((action: LangGraphInterruptActionSetterArgs) => {\n _setLangGraphInterruptAction((prev) => {\n if (prev == null) return action as LangGraphInterruptAction;\n if (action == null) return null;\n let event = prev.event;\n if (action.event) {\n // @ts-ignore\n event = { ...prev.event, ...action.event };\n }\n return { ...prev, ...action, event };\n });\n }, []);\n const removeLangGraphInterruptAction = useCallback((): void => {\n setLangGraphInterruptAction(null);\n }, []);\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [bannerError, setBannerError] = useState<CopilotKitError | null>(null);\n const [suggestions, setSuggestions] = useState<SuggestionItem[]>([]);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved = typeof newExtensions === \"function\" ? newExtensions(prev) : newExtensions;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setExtensions],\n );\n\n const updateAuthStates = useCallback(\n (newAuthStates: SetStateAction<Record<string, AuthState>>) => {\n setAuthStates((prev) => {\n const resolved = typeof newAuthStates === \"function\" ? newAuthStates(prev) : newAuthStates;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setAuthStates],\n );\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n getContextString,\n addContext,\n removeContext,\n getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n additionalInstructions,\n setAdditionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n runtimeClient,\n forwardedParameters,\n agentLock,\n threadId: internalThreadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n availableAgents,\n authConfig_c: props.authConfig_c,\n authStates_c: authStates,\n setAuthStates_c: updateAuthStates,\n extensions,\n setExtensions: updateExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n removeLangGraphInterruptAction,\n onError: props.onError,\n suggestions,\n setSuggestions,\n bannerError,\n setBannerError,\n }}\n >\n <CopilotMessages>{memoizedChildren}</CopilotMessages>\n {bannerError && showDevConsole && (\n <UsageBanner\n severity={bannerError.severity}\n message={bannerError.message}\n onClose={() => setBannerError(null)}\n actions={getErrorActions(bannerError)}\n />\n )}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ name, args }: { name: string; args: Record<string, any> }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n\nfunction formatFeatureName(featureName: string): string {\n return featureName\n .replace(/_c$/, \"\")\n .split(\"_\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\" \");\n}\n\nfunction validateProps(props: CopilotKitProps): never | void {\n const cloudFeatures = Object.keys(props).filter((key) => key.endsWith(\"_c\"));\n\n if (!props.runtimeUrl && !props.publicApiKey) {\n throw new ConfigurationError(\"Missing required prop: 'runtimeUrl' or 'publicApiKey'\");\n }\n\n if (cloudFeatures.length > 0 && !props.publicApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n","/**\n * Suggestions utility functions for CopilotKit\n *\n * This module handles the generation of chat suggestions with optimized error handling\n * and streaming validation to prevent infinite retry loops and console spam.\n */\n\nimport { extract } from \"./extract\";\nimport { actionParametersToJsonSchema } from \"@copilotkit/shared\";\nimport { CopilotRequestType } from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { CopilotChatSuggestionConfiguration } from \"../types\";\n\nexport interface SuggestionItem {\n title: string;\n message: string;\n partial?: boolean;\n className?: string;\n}\n\nexport const reloadSuggestions = async (\n context: CopilotContextParams & CopilotMessagesContextParams,\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration },\n setCurrentSuggestions: (suggestions: SuggestionItem[]) => void,\n abortControllerRef: React.MutableRefObject<AbortController | null>,\n): Promise<void> => {\n const abortController = abortControllerRef.current;\n\n // Early abort check\n if (abortController?.signal.aborted) {\n return;\n }\n\n // Abort-aware suggestion setter with safety checks to prevent race conditions\n const setSuggestionsIfNotAborted = (suggestions: SuggestionItem[]) => {\n if (!abortController?.signal.aborted && abortControllerRef.current === abortController) {\n setCurrentSuggestions(suggestions);\n }\n };\n\n try {\n const tools = JSON.stringify(\n Object.values(context.actions).map((action) => ({\n name: action.name,\n description: action.description,\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n })),\n );\n\n const allSuggestions: SuggestionItem[] = [];\n let hasSuccessfulSuggestions = false;\n let hasErrors = false; // Track if any errors occurred\n let lastError: Error | null = null; // Track the last error for better error reporting\n\n // Get enabled configurations\n const enabledConfigs = Object.values(chatSuggestionConfiguration).filter(\n (config) => config.instructions && config.instructions.trim().length > 0,\n );\n\n if (enabledConfigs.length === 0) {\n return;\n }\n\n // Clear existing suggestions\n setSuggestionsIfNotAborted([]);\n\n // Generate suggestions for each configuration\n for (const config of enabledConfigs) {\n // Check if aborted before each configuration\n if (abortController?.signal.aborted) {\n setSuggestionsIfNotAborted([]);\n return;\n }\n\n try {\n const result = await extract({\n context,\n instructions:\n \"Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls. \",\n data: `${config.instructions}\\n\\nAvailable tools: ${tools}\\n\\n`,\n requestType: CopilotRequestType.Task,\n parameters: [\n {\n name: \"suggestions\",\n type: \"object[]\",\n attributes: [\n {\n name: \"title\",\n description:\n \"The title of the suggestion. This is shown as a button and should be short.\",\n type: \"string\",\n },\n {\n name: \"message\",\n description:\n \"The message to send when the suggestion is clicked. This should be a clear, complete sentence and will be sent as an instruction to the AI.\",\n type: \"string\",\n },\n ],\n },\n ],\n include: {\n messages: true,\n readable: true,\n },\n abortSignal: abortController?.signal,\n stream: ({ status, args }: { status: string; args: any }) => {\n // Check abort status in stream callback\n if (abortController?.signal.aborted) {\n return;\n }\n\n const suggestions = args.suggestions || [];\n const newSuggestions: SuggestionItem[] = [];\n\n for (let i = 0; i < suggestions.length; i++) {\n // Respect max suggestions limit\n if (config.maxSuggestions !== undefined && i >= config.maxSuggestions) {\n break;\n }\n\n const suggestion = suggestions[i];\n\n // Skip completely empty or invalid objects during streaming\n if (!suggestion || typeof suggestion !== \"object\") {\n continue;\n }\n\n const { title, message } = suggestion;\n\n // During streaming, be permissive but require at least a meaningful title\n const hasValidTitle = title && typeof title === \"string\" && title.trim().length > 0;\n const hasValidMessage =\n message && typeof message === \"string\" && message.trim().length > 0;\n\n // During streaming, we need at least a title to show something useful\n if (!hasValidTitle) {\n continue;\n }\n\n // Mark as partial if this is the last suggestion and streaming isn't complete\n const partial = i === suggestions.length - 1 && status !== \"complete\";\n\n newSuggestions.push({\n title: title.trim(),\n message: hasValidMessage ? message.trim() : \"\", // Use title as fallback\n partial,\n className: config.className,\n });\n }\n\n // Update suggestions with current batch\n setSuggestionsIfNotAborted([...allSuggestions, ...newSuggestions]);\n },\n });\n\n // Process final results with strict validation\n if (result?.suggestions && Array.isArray(result.suggestions)) {\n const validSuggestions = result.suggestions\n .filter(\n (suggestion: any) =>\n suggestion &&\n typeof suggestion.title === \"string\" &&\n suggestion.title.trim().length > 0,\n )\n .map((suggestion: any) => ({\n title: suggestion.title.trim(),\n message:\n suggestion.message &&\n typeof suggestion.message === \"string\" &&\n suggestion.message.trim()\n ? suggestion.message.trim()\n : suggestion.title.trim(),\n }));\n\n if (validSuggestions.length > 0) {\n allSuggestions.push(...validSuggestions);\n hasSuccessfulSuggestions = true;\n }\n }\n } catch (error) {\n // Simple error handling - just continue with next config, don't log here\n hasErrors = true;\n lastError = error instanceof Error ? error : new Error(String(error));\n }\n }\n\n // Display any successful suggestions we got\n if (hasSuccessfulSuggestions && allSuggestions.length > 0) {\n // Remove duplicates based on message content\n const uniqueSuggestions = allSuggestions.filter(\n (suggestion, index, self) =>\n index === self.findIndex((s) => s.message === suggestion.message),\n );\n\n setSuggestionsIfNotAborted(uniqueSuggestions);\n } else if (hasErrors) {\n // If we had errors but no successful suggestions, throw an error with details\n const errorMessage = lastError\n ? lastError.message\n : \"Failed to generate suggestions due to API errors\";\n throw new Error(errorMessage);\n }\n } catch (error) {\n // Top-level error handler - re-throw to allow caller to handle\n throw error;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EAKE,gCAAAA;AAAA,OACK;AACP;AAAA,EAGE;AAAA,EACA;AAAA,EACA;AAAA,EACA,sBAAAC;AAAA,OAEK;;;ACCP,SAAS,aAAa,WAAW,SAAS,QAAQ,gBAAgC;AAUlF,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;;;AC5BP,SAAS,oCAAoC;AAC7C,SAAS,0BAA0B;AAW5B,IAAM,oBAAoB,CAC/B,SACA,6BACA,uBACA,uBACkB;AAClB,QAAM,kBAAkB,mBAAmB;AAG3C,MAAI,mDAAiB,OAAO,SAAS;AACnC;AAAA,EACF;AAGA,QAAM,6BAA6B,CAAC,gBAAkC;AACpE,QAAI,EAAC,mDAAiB,OAAO,YAAW,mBAAmB,YAAY,iBAAiB;AACtF,4BAAsB,WAAW;AAAA,IACnC;AAAA,EACF;AAEA,MAAI;AACF,UAAM,QAAQ,KAAK;AAAA,MACjB,OAAO,OAAO,QAAQ,OAAO,EAAE,IAAI,CAAC,YAAY;AAAA,QAC9C,MAAM,OAAO;AAAA,QACb,aAAa,OAAO;AAAA,QACpB,YAAY,KAAK,UAAU,6BAA6B,OAAO,UAAU,CAAC;AAAA,MAC5E,EAAE;AAAA,IACJ;AAEA,UAAM,iBAAmC,CAAC;AAC1C,QAAI,2BAA2B;AAC/B,QAAI,YAAY;AAChB,QAAI,YAA0B;AAG9B,UAAM,iBAAiB,OAAO,OAAO,2BAA2B,EAAE;AAAA,MAChE,CAAC,WAAW,OAAO,gBAAgB,OAAO,aAAa,KAAK,EAAE,SAAS;AAAA,IACzE;AAEA,QAAI,eAAe,WAAW,GAAG;AAC/B;AAAA,IACF;AAGA,+BAA2B,CAAC,CAAC;AAG7B,e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AAM,IAAI,MAAM,OAAO,KAAK;AAE1C,UAAI,MAAM;AACR;AAAA,MACF;AAEA,UAAI,2CAAa,SAAS;AACxB,cAAM,IAAI,MAAM,SAAS;AAAA,MAC3B;AAEA,+BAAyB;AAAA,QACvB,MAAM,wBAAwB;AAAA,MAChC,EAAE,KAAK,CAAC,QAAQ,IAAI,yBAAyB,CAAC;AAE9C,UAAI,CAAC,wBAAwB;AAC3B;AAAA,MACF;AAEA,uCAAS;AAAA,QACP,QAAQ,YAAY,YAAY;AAAA,QAChC,MAAM,uBAAuB;AAAA,MAC/B;AAEA,kBAAY;AAAA,IACd;AAEA,QAAI,CAAC,wBAAwB;AAC3B,YAAM,IAAI,MAAM,6CAA6C;AAAA,IAC/D;AAEA,qCAAS;AAAA,MACP,QAAQ;AAAA,MACR,MAAM,uBAAuB;AAAA,IAC/B;AAEA,WAAO,uBAAuB;AAAA,EAChC;AAAA;AAIA,SAAS,wBAAwB,cAA8B;AAC7D,SAAO;AAAA;AAAA;AAAA;AAAA,EAIP;AAAA;AAAA;AAAA;AAAA;AAKF;AAEA,SAAS,kBAAkB,eAAuB,cAA8B;AAC9E,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASF;","names":["actionParametersToJsonSchema","CopilotRequestType","_a","headers","action","CopilotRequestType","actionParametersToJsonSchema"]}
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-O7ARI5CV.mjs";
4
4
  import {
5
5
  useToast
6
- } from "./chunk-YAF2LATQ.mjs";
6
+ } from "./chunk-EFL5OBKN.mjs";
7
7
  import {
8
8
  __async
9
9
  } from "./chunk-SKC7AJIV.mjs";
@@ -99,4 +99,4 @@ export {
99
99
  useErrorToast,
100
100
  useAsyncCallback
101
101
  };
102
- //# sourceMappingURL=chunk-3OQM3NEK.mjs.map
102
+ //# sourceMappingURL=chunk-N4WEHORG.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useCopilotContext
3
- } from "./chunk-XGRBCWK6.mjs";
3
+ } from "./chunk-47GMU44Z.mjs";
4
4
 
5
5
  // src/hooks/use-langgraph-interrupt-render.ts
6
6
  import React, { useCallback } from "react";
@@ -44,4 +44,4 @@ function useLangGraphInterruptRender() {
44
44
  export {
45
45
  useLangGraphInterruptRender
46
46
  };
47
- //# sourceMappingURL=chunk-Q6FZZJ5A.mjs.map
47
+ //# sourceMappingURL=chunk-OL3VRQKU.mjs.map
@@ -0,0 +1,18 @@
1
+ import {
2
+ useCopilotChat
3
+ } from "./chunk-2JAX6WE6.mjs";
4
+
5
+ // src/hooks/use-copilot-chat-light.ts
6
+ function useCopilotChatLight(options = {}) {
7
+ const { appendMessage, setSuggestions, generateSuggestions } = useCopilotChat(options);
8
+ return {
9
+ appendMessage,
10
+ setSuggestions,
11
+ generateSuggestions
12
+ };
13
+ }
14
+
15
+ export {
16
+ useCopilotChatLight
17
+ };
18
+ //# sourceMappingURL=chunk-PQ5IXT4Z.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-chat-light.ts"],"sourcesContent":["/**\n * `useCopilotChatLight` is a lightweight React hook for headless chat interactions.\n * Perfect for programmatic messaging, background operations, and custom UI implementations.\n *\n * **Open Source Friendly** - Works without requiring a `publicApiKey`.\n *\n * ## Use Cases:\n *\n * - **Programmatic Messaging**: Send messages without displaying chat UI\n * - **Background Operations**: Trigger AI interactions in the background\n * - **Custom UI**: Build your own chat interface using CopilotKit's messaging infrastructure\n * - **Testing & Automation**: Programmatic chat interactions for testing\n * - **Fire-and-Forget**: Send messages without needing to read responses\n * - **Suggestion Management**: Control chat suggestions programmatically\n *\n * ## What's Included:\n *\n * - `appendMessage` - Send messages to the chat\n * - `setSuggestions` - Manually control suggestions\n * - `generateSuggestions` - Trigger AI-powered suggestion generation\n *\n * ## What's NOT Included:\n *\n * - Message reading (`visibleMessages`)\n * - Loading states (`isLoading`, `isLoadingSuggestions`)\n * - Message management (`setMessages`, `deleteMessage`, `reloadMessages`)\n * - Chat controls (`reset`, `stopGeneration`)\n * - Advanced features (`mcpServers`, `runChatCompletion`, `interrupt`)\n *\n * ## Usage:\n *\n * ### Basic Messaging\n *\n * ```tsx\n * import { useCopilotChatLite } from \"@copilotkit/react-core\";\n * import { TextMessage, Role } from \"@copilotkit/runtime-client-gql\";\n *\n * export function BackgroundMessaging() {\n * const { appendMessage } = useCopilotChatLite();\n *\n * const sendBackgroundMessage = async () => {\n * await appendMessage(new TextMessage({\n * content: \"Process this data in the background\",\n * role: Role.User,\n * }));\n * };\n *\n * return <button onClick={sendBackgroundMessage}>Process Data</button>;\n * }\n * ```\n *\n * ### Suggestion Management\n *\n * ```tsx\n * import { useCopilotChatLight } from \"@copilotkit/react-core\";\n *\n * export function SuggestionController() {\n * const { setSuggestions, generateSuggestions } = useCopilotChatLight();\n *\n * const setCustomSuggestions = () => {\n * setSuggestions([\n * { title: \"Analyze Data\", message: \"Analyze the current dataset\" },\n * { title: \"Generate Report\", message: \"Create a summary report\" }\n * ]);\n * };\n *\n * const triggerAISuggestions = async () => {\n * await generateSuggestions();\n * };\n *\n * return (\n * <div>\n * <button onClick={setCustomSuggestions}>Set Custom Suggestions</button>\n * <button onClick={triggerAISuggestions}>Generate AI Suggestions</button>\n * </div>\n * );\n * }\n * ```\n *\n * ### Automated Workflows\n *\n * ```tsx\n * import { useCopilotChatLight } from \"@copilotkit/react-core\";\n *\n * export function AutomatedWorkflow() {\n * const { appendMessage, setSuggestions } = useCopilotChatLight();\n *\n * const runWorkflow = async () => {\n * // Step 1: Send initial message\n * await appendMessage(new TextMessage({\n * content: \"Start workflow analysis\",\n * role: Role.User,\n * }));\n *\n * // Step 2: Set contextual suggestions\n * setSuggestions([\n * { title: \"Continue\", message: \"Continue to next step\" },\n * { title: \"Stop\", message: \"Stop the workflow\" }\n * ]);\n * };\n *\n * return <button onClick={runWorkflow}>Run Automated Workflow</button>;\n * }\n * ```\n *\n * ## Return Type:\n *\n * ```tsx\n * const {\n * appendMessage, // Send messages programmatically\n * setSuggestions, // Set custom suggestions array\n * generateSuggestions, // Trigger AI suggestion generation\n * } = useCopilotChatLight();\n * ```\n */\n\nimport { Message } from \"@copilotkit/shared\";\nimport { AppendMessageOptions } from \"./use-chat\";\nimport { useCopilotChat as useCopilotChatInternal } from \"./use-copilot-chat_internal\";\nimport type { SuggestionItem } from \"../utils\";\n\nexport interface UseCopilotChatLightOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the chat instance with the same `id` will\n * have shared state across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * Initial messages to populate the chat with.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: (contextString: string, additionalInstructions?: string) => string;\n}\n\nexport interface UseCopilotChatLightReturn {\n /**\n * Send a new message to the chat programmatically.\n *\n * @param message - The message to send\n * @param options - Optional configuration for the message\n *\n * @example\n * ```tsx\n * await appendMessage(new TextMessage({\n * content: \"Hello, process this request\",\n * role: Role.User,\n * }));\n * ```\n */\n appendMessage: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n\n /**\n * Manually set the suggestions array.\n * Useful for custom suggestion workflows and manual control.\n *\n * @param suggestions - Array of suggestion items to display\n *\n * @example\n * ```tsx\n * setSuggestions([\n * { title: \"Continue\", message: \"Continue the process\" },\n * { title: \"Stop\", message: \"Stop the current operation\" }\n * ]);\n * ```\n */\n setSuggestions: (suggestions: SuggestionItem[]) => void;\n\n /**\n * Trigger AI-powered suggestion generation.\n * Uses configurations from `useCopilotChatSuggestions` hooks.\n * Respects global debouncing - only one generation can run at a time.\n *\n * @returns Promise that resolves when suggestions are generated\n *\n * @example\n * ```tsx\n * await generateSuggestions();\n * ```\n */\n generateSuggestions: () => Promise<void>;\n}\n\n/**\n * A lightweight React hook for headless chat interactions.\n * Perfect for programmatic messaging, background operations, and custom UI implementations.\n *\n * **Open Source Friendly** - Works without requiring a `publicApiKey`.\n *\n * @param options - Configuration options for the chat\n * @returns Object containing appendMessage, setSuggestions, and generateSuggestions functions\n *\n * @example\n * ```tsx\n * const { appendMessage, setSuggestions, generateSuggestions } = useCopilotChatLite();\n * ```\n */\nexport function useCopilotChatLight(\n options: UseCopilotChatLightOptions = {},\n): UseCopilotChatLightReturn {\n // Use the internal implementation (no API key required)\n const { appendMessage, setSuggestions, generateSuggestions } = useCopilotChatInternal(options);\n\n return {\n appendMessage,\n setSuggestions,\n generateSuggestions,\n };\n}\n"],"mappings":";;;;;AA+MO,SAAS,oBACd,UAAsC,CAAC,GACZ;AAE3B,QAAM,EAAE,eAAe,gBAAgB,oBAAoB,IAAI,eAAuB,OAAO;AAE7F,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -1,18 +1,18 @@
1
1
  import {
2
2
  useCopilotChat
3
- } from "./chunk-VOMGRGWT.mjs";
3
+ } from "./chunk-2JAX6WE6.mjs";
4
4
  import {
5
5
  useCopilotRuntimeClient
6
- } from "./chunk-JWAXDYOW.mjs";
6
+ } from "./chunk-FAUNHSQU.mjs";
7
7
  import {
8
8
  useAsyncCallback
9
- } from "./chunk-3OQM3NEK.mjs";
9
+ } from "./chunk-N4WEHORG.mjs";
10
10
  import {
11
11
  useToast
12
- } from "./chunk-YAF2LATQ.mjs";
12
+ } from "./chunk-EFL5OBKN.mjs";
13
13
  import {
14
14
  useCopilotContext
15
- } from "./chunk-XGRBCWK6.mjs";
15
+ } from "./chunk-47GMU44Z.mjs";
16
16
  import {
17
17
  useCopilotMessagesContext
18
18
  } from "./chunk-DCTJZ742.mjs";
@@ -236,4 +236,4 @@ export {
236
236
  stopAgent,
237
237
  runAgent
238
238
  };
239
- //# sourceMappingURL=chunk-VM7CVIET.mjs.map
239
+ //# sourceMappingURL=chunk-PRKL7T7P.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-coagent.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport {\n CopilotContextParams,\n CopilotMessagesContextParams,\n useCopilotContext,\n useCopilotMessagesContext,\n} from \"../context\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { useCopilotChat } from \"./use-copilot-chat_internal\";\nimport { Message } from \"@copilotkit/shared\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nimport { parseJson, CopilotKitAgentDiscoveryError } from \"@copilotkit/shared\";\n\ninterface UseCoagentOptionsBase {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * @deprecated - use \"config.configurable\"\n * Config to pass to a LangGraph Agent\n */\n configurable?: Record<string, any>;\n /**\n * Config to pass to a LangGraph Agent\n */\n config?: {\n configurable?: Record<string, any>;\n [key: string]: any;\n };\n}\n\ninterface WithInternalStateManagementAndInitial<T> extends UseCoagentOptionsBase {\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement extends UseCoagentOptionsBase {\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> extends UseCoagentOptionsBase {\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The name of the current LangGraph node.\n */\n nodeName?: string;\n /**\n * The ID of the thread the agent is running in.\n */\n threadId?: string;\n /**\n * A boolean indicating if the agent is currently running.\n */\n running: boolean;\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n /**\n * A function to start the agent.\n */\n start: () => void;\n /**\n * A function to stop the agent.\n */\n stop: () => void;\n /**\n * A function to re-run the agent. The hint function can be used to provide a hint to the agent\n * about why it is being re-run again.\n */\n run: (hint?: HintFunction) => Promise<void>;\n}\n\nexport interface HintFunctionParams {\n /**\n * The previous state of the agent.\n */\n previousState: any;\n /**\n * The current state of the agent.\n */\n currentState: any;\n}\n\nexport type HintFunction = (params: HintFunctionParams) => Message | undefined;\n\n/**\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of the agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences \"agentic copilots\". To get started using agentic copilots, which\n * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.\n */\nexport function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {\n const generalContext = useCopilotContext();\n const { availableAgents } = generalContext;\n const { setBannerError } = useToast();\n const lastLoadedThreadId = useRef<string>();\n const lastLoadedState = useRef<any>();\n\n const { name } = options;\n useEffect(() => {\n if (availableAgents?.length && !availableAgents.some((a) => a.name === name)) {\n const message = `(useCoAgent): Agent \"${name}\" not found. Make sure the agent exists and is properly configured.`;\n console.warn(message);\n\n // Route to banner instead of toast for consistency\n const agentError = new CopilotKitAgentDiscoveryError({\n agentName: name,\n availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id })),\n });\n setBannerError(agentError);\n }\n }, [availableAgents]);\n\n const messagesContext = useCopilotMessagesContext();\n const context = { ...generalContext, ...messagesContext };\n const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } =\n context;\n const { appendMessage, runChatCompletion } = useCopilotChat();\n const headers = {\n ...(copilotApiConfig.headers || {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n showDevConsole: context.showDevConsole,\n });\n\n // if we manage state internally, we need to provide a function to set the state\n const setState = useCallback(\n (newState: T | ((prevState: T | undefined) => T)) => {\n // coagentStatesRef.current || {}\n let coagentState: CoagentState = getCoagentState({ coagentStates, name, options });\n const updatedState =\n typeof newState === \"function\" ? (newState as Function)(coagentState.state) : newState;\n\n setCoagentStatesWithRef({\n ...coagentStatesRef.current,\n [name]: {\n ...coagentState,\n state: updatedState,\n },\n });\n },\n [coagentStates, name],\n );\n\n useEffect(() => {\n const fetchAgentState = async () => {\n if (!threadId || threadId === lastLoadedThreadId.current) return;\n\n const result = await runtimeClient.loadAgentState({\n threadId,\n agentName: name,\n });\n\n // Runtime client handles errors automatically via handleGQLErrors\n if (result.error) {\n return; // Don't process data on error\n }\n\n const newState = result.data?.loadAgentState?.state;\n if (newState === lastLoadedState.current) return;\n\n if (result.data?.loadAgentState?.threadExists && newState && newState != \"{}\") {\n lastLoadedState.current = newState;\n lastLoadedThreadId.current = threadId;\n const fetchedState = parseJson(newState, {});\n isExternalStateManagement(options)\n ? options.setState(fetchedState)\n : setState(fetchedState);\n }\n };\n void fetchAgentState();\n }, [threadId]);\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n setState(options.state);\n } else if (coagentStates[name] === undefined) {\n setState(options.initialState === undefined ? {} : options.initialState);\n }\n }, [\n isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined,\n // reset initialstate on reset\n coagentStates[name] === undefined,\n ]);\n\n // Sync config when runtime configuration changes\n useEffect(() => {\n const newConfig = options.config\n ? options.config\n : options.configurable\n ? { configurable: options.configurable }\n : undefined;\n\n if (newConfig === undefined) return;\n\n setCoagentStatesWithRef((prev) => {\n const existing = prev[name] ?? {\n name,\n state: isInternalStateManagementWithInitial(options) ? options.initialState : {},\n config: {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n\n if (JSON.stringify(existing.config) === JSON.stringify(newConfig)) {\n return prev;\n }\n\n return {\n ...prev,\n [name]: {\n ...existing,\n config: newConfig,\n },\n };\n });\n }, [JSON.stringify(options.config), JSON.stringify(options.configurable)]);\n\n const runAgentCallback = useAsyncCallback(\n async (hint?: HintFunction) => {\n await runAgent(name, context, appendMessage, runChatCompletion, hint);\n },\n [name, context, appendMessage, runChatCompletion],\n );\n\n // Return the state and setState function\n return useMemo(() => {\n const coagentState = getCoagentState({ coagentStates, name, options });\n return {\n name,\n nodeName: coagentState.nodeName,\n threadId: coagentState.threadId,\n running: coagentState.running,\n state: coagentState.state,\n setState: isExternalStateManagement(options) ? options.setState : setState,\n start: () => startAgent(name, context),\n stop: () => stopAgent(name, context),\n run: runAgentCallback,\n };\n }, [name, coagentStates, options, setState, runAgentCallback]);\n}\n\nexport function startAgent(name: string, context: CopilotContextParams) {\n const { setAgentSession } = context;\n setAgentSession({\n agentName: name,\n });\n}\n\nexport function stopAgent(name: string, context: CopilotContextParams) {\n const { agentSession, setAgentSession } = context;\n if (agentSession && agentSession.agentName === name) {\n setAgentSession(null);\n context.setCoagentStates((prevAgentStates) => {\n return {\n ...prevAgentStates,\n [name]: {\n ...prevAgentStates[name],\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n },\n };\n });\n } else {\n console.warn(`No agent session found for ${name}`);\n }\n}\n\nexport async function runAgent(\n name: string,\n context: CopilotContextParams & CopilotMessagesContextParams,\n appendMessage: (message: Message) => Promise<void>,\n runChatCompletion: () => Promise<Message[]>,\n hint?: HintFunction,\n) {\n const { agentSession, setAgentSession } = context;\n if (!agentSession || agentSession.agentName !== name) {\n setAgentSession({\n agentName: name,\n });\n }\n\n let previousState: any = null;\n for (let i = context.messages.length - 1; i >= 0; i--) {\n const message = context.messages[i];\n if (message.isAgentStateMessage() && message.agentName === name) {\n previousState = message.state;\n }\n }\n\n let state = context.coagentStatesRef.current?.[name]?.state || {};\n\n if (hint) {\n const hintMessage = hint({ previousState, currentState: state });\n if (hintMessage) {\n await appendMessage(hintMessage);\n } else {\n await runChatCompletion();\n }\n } else {\n await runChatCompletion();\n }\n}\n\nconst isExternalStateManagement = <T>(\n options: UseCoagentOptions<T>,\n): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n};\n\nconst isInternalStateManagementWithInitial = <T>(\n options: UseCoagentOptions<T>,\n): options is WithInternalStateManagementAndInitial<T> => {\n return \"initialState\" in options;\n};\n\nconst getCoagentState = <T>({\n coagentStates,\n name,\n options,\n}: {\n coagentStates: Record<string, CoagentState>;\n name: string;\n options: UseCoagentOptions<T>;\n}) => {\n if (coagentStates[name]) {\n return coagentStates[name];\n } else {\n return {\n name,\n state: isInternalStateManagementWithInitial<T>(options) ? options.initialState : {},\n config: options.config\n ? options.config\n : options.configurable\n ? { configurable: options.configurable }\n : {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,SAAS,aAAa,WAAW,SAAS,cAAc;AAaxD,SAAS,WAAW,qCAAqC;AA8GlD,SAAS,WAAoB,SAAwD;AAC1F,QAAM,iBAAiB,kBAAkB;AACzC,QAAM,EAAE,gBAAgB,IAAI;AAC5B,QAAM,EAAE,eAAe,IAAI,SAAS;AACpC,QAAM,qBAAqB,OAAe;AAC1C,QAAM,kBAAkB,OAAY;AAEpC,QAAM,EAAE,KAAK,IAAI;AACjB,YAAU,MAAM;AACd,SAAI,mDAAiB,WAAU,CAAC,gBAAgB,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI,GAAG;AAC5E,YAAM,UAAU,wBA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,eACN,EAAE,cAAc,QAAQ,aAAa,IACrC,CAAC;AAAA,MACP,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,UAAU;AAAA,MACV,UAAU;AAAA,MACV,OAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  useCopilotChat
3
- } from "./chunk-VOMGRGWT.mjs";
3
+ } from "./chunk-2JAX6WE6.mjs";
4
4
  import {
5
5
  useToast
6
- } from "./chunk-YAF2LATQ.mjs";
6
+ } from "./chunk-EFL5OBKN.mjs";
7
7
  import {
8
8
  CopilotContext
9
- } from "./chunk-XGRBCWK6.mjs";
9
+ } from "./chunk-47GMU44Z.mjs";
10
10
  import {
11
11
  __spreadProps,
12
12
  __spreadValues
@@ -62,4 +62,4 @@ function useLangGraphInterrupt(action, dependencies) {
62
62
  export {
63
63
  useLangGraphInterrupt
64
64
  };
65
- //# sourceMappingURL=chunk-KV25ZRMH.mjs.map
65
+ //# sourceMappingURL=chunk-XIHAYU6C.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-langgraph-interrupt.ts"],"sourcesContent":["import { useContext, useEffect, useMemo } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { LangGraphInterruptRender } from \"../types/interrupt-action\";\nimport { useCopilotChat } from \"./use-copilot-chat_internal\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { dataToUUID } from \"@copilotkit/shared\";\n\nexport function useLangGraphInterrupt<TEventValue = any>(\n action: Omit<LangGraphInterruptRender<TEventValue>, \"id\">,\n dependencies?: any[],\n) {\n const { setLangGraphInterruptAction, removeLangGraphInterruptAction, langGraphInterruptAction } =\n useContext(CopilotContext);\n const { runChatCompletion } = useCopilotChat();\n const { addToast } = useToast();\n\n const actionId = dataToUUID(JSON.stringify(action), \"lgAction\");\n // We only consider action to be defined once the ID is there\n const hasAction = useMemo(\n () => Boolean(langGraphInterruptAction?.id),\n [langGraphInterruptAction],\n );\n\n const isCurrentAction = useMemo(\n () => langGraphInterruptAction?.id && langGraphInterruptAction?.id === actionId,\n [langGraphInterruptAction],\n );\n\n // Run chat completion to submit a response event. Only if it's the current action\n useEffect(() => {\n if (hasAction && isCurrentAction && langGraphInterruptAction?.event?.response) {\n runChatCompletion();\n }\n }, [langGraphInterruptAction?.event?.response, runChatCompletion, hasAction, isCurrentAction]);\n\n useEffect(() => {\n if (!action) return;\n // An action was already set, with no conditions and it's not the action we're using right now.\n // Show a warning, as this action will not be executed\n if (hasAction && !isCurrentAction && !action.enabled) {\n addToast({\n type: \"warning\",\n message: \"An action is already registered for the interrupt event\",\n });\n return;\n }\n\n if (hasAction && isCurrentAction) {\n return;\n }\n\n setLangGraphInterruptAction({ ...action, id: actionId });\n }, [\n action,\n hasAction,\n isCurrentAction,\n setLangGraphInterruptAction,\n removeLangGraphInterruptAction,\n ...(dependencies || []),\n ]);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,YAAY,WAAW,eAAe;AAK/C,SAAS,kBAAkB;AAEpB,SAAS,sBACd,QACA,cACA;AAVF;AAWE,QAAM,EAAE,6BAA6B,gCAAgC,yBAAyB,IAC5F,WAAW,cAAc;AAC3B,QAAM,EAAE,kBAAkB,IAAI,eAAe;AAC7C,QAAM,EAAE,SAAS,IAAI,SAAS;AAE9B,QAAM,WAAW,WAAW,KAAK,UAAU,MAAM,GAAG,UAAU;AAE9D,QAAM,YAAY;AAAA,IAChB,MAAM,QAAQ,qEAA0B,EAAE;AAAA,IAC1C,CAAC,wBAAwB;AAAA,EAC3B;AAEA,QAAM,kBAAkB;AAAA,IACtB,OAAM,qEAA0B,QAAM,qEAA0B,QAAO;AAAA,IACvE,CAAC,wBAAwB;AAAA,EAC3B;AAGA,YAAU,MAAM;AA7BlB,QAAAA;AA8BI,QAAI,aAAa,qBAAmBA,MAAA,qEAA0B,UAA1B,gBAAAA,IAAiC,WAAU;AAC7E,wBAAkB;AAAA,IACpB;AAAA,EACF,GAAG,EAAC,0EAA0B,UAA1B,mBAAiC,UAAU,mBAAmB,WAAW,eAAe,CAAC;AAE7F,YAAU,MAAM;AACd,QAAI,CAAC;AAAQ;AAGb,QAAI,aAAa,CAAC,mBAAmB,CAAC,OAAO,SAAS;AACpD,eAAS;AAAA,QACP,MAAM;AAAA,QACN,SAAS;AAAA,MACX,CAAC;AACD;AAAA,IACF;AAEA,QAAI,aAAa,iBAAiB;AAChC;AAAA,IACF;AAEA,gCAA4B,iCAAK,SAAL,EAAa,IAAI,SAAS,EAAC;AAAA,EACzD,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":["_a"]}