@copilotkit/react-core 1.9.2-next.7 → 1.9.2-next.9

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 (102) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/{chunk-CCESTGAM.mjs → chunk-3OQM3NEK.mjs} +2 -2
  3. package/dist/{chunk-T4ZKC4X4.mjs → chunk-3YHYWAHK.mjs} +2 -2
  4. package/dist/{chunk-ISYBUDL4.mjs → chunk-55QZ2SVJ.mjs} +4 -5
  5. package/dist/chunk-55QZ2SVJ.mjs.map +1 -0
  6. package/dist/chunk-57K2ZJ5F.mjs +348 -0
  7. package/dist/chunk-57K2ZJ5F.mjs.map +1 -0
  8. package/dist/{chunk-ZHEEHGLS.mjs → chunk-ADIITPD2.mjs} +8 -5
  9. package/dist/{chunk-ZHEEHGLS.mjs.map → chunk-ADIITPD2.mjs.map} +1 -1
  10. package/dist/{chunk-S4BOATBG.mjs → chunk-EF5BNM34.mjs} +2 -2
  11. package/dist/{chunk-I4JPQECN.mjs → chunk-EXU7GWLC.mjs} +4 -4
  12. package/dist/{chunk-7G6RR4HE.mjs → chunk-FXK6RQIN.mjs} +2 -2
  13. package/dist/{chunk-JXF732XG.mjs → chunk-G7LYGERN.mjs} +80 -13
  14. package/dist/chunk-G7LYGERN.mjs.map +1 -0
  15. package/dist/{chunk-VJCHRQ7Q.mjs → chunk-JDEWNLNP.mjs} +37 -4
  16. package/dist/chunk-JDEWNLNP.mjs.map +1 -0
  17. package/dist/{chunk-JHIZ5HAI.mjs → chunk-NQVCZQ5T.mjs} +3 -3
  18. package/dist/{chunk-VF6UPRKM.mjs → chunk-OF4SZTLL.mjs} +3 -3
  19. package/dist/{chunk-QQZLIEXK.mjs → chunk-SJJNFYGQ.mjs} +3 -3
  20. package/dist/{chunk-RN3ZRHI7.mjs → chunk-WOGURSAL.mjs} +5 -5
  21. package/dist/chunk-YAF2LATQ.mjs +310 -0
  22. package/dist/chunk-YAF2LATQ.mjs.map +1 -0
  23. package/dist/components/copilot-provider/copilot-messages.js +35 -2
  24. package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
  25. package/dist/components/copilot-provider/copilot-messages.mjs +2 -2
  26. package/dist/components/copilot-provider/copilotkit.js +289 -234
  27. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  28. package/dist/components/copilot-provider/copilotkit.mjs +7 -7
  29. package/dist/components/copilot-provider/index.js +289 -234
  30. package/dist/components/copilot-provider/index.js.map +1 -1
  31. package/dist/components/copilot-provider/index.mjs +7 -7
  32. package/dist/components/error-boundary/error-boundary.js +135 -146
  33. package/dist/components/error-boundary/error-boundary.js.map +1 -1
  34. package/dist/components/error-boundary/error-boundary.mjs +4 -4
  35. package/dist/components/error-boundary/error-utils.js.map +1 -1
  36. package/dist/components/error-boundary/error-utils.mjs +2 -2
  37. package/dist/components/index.js +289 -234
  38. package/dist/components/index.js.map +1 -1
  39. package/dist/components/index.mjs +7 -7
  40. package/dist/components/toast/toast-provider.js +118 -85
  41. package/dist/components/toast/toast-provider.js.map +1 -1
  42. package/dist/components/toast/toast-provider.mjs +1 -1
  43. package/dist/components/usage-banner.js +135 -146
  44. package/dist/components/usage-banner.js.map +1 -1
  45. package/dist/components/usage-banner.mjs +1 -1
  46. package/dist/hooks/index.js +75 -10
  47. package/dist/hooks/index.js.map +1 -1
  48. package/dist/hooks/index.mjs +14 -14
  49. package/dist/hooks/use-chat.js +72 -10
  50. package/dist/hooks/use-chat.js.map +1 -1
  51. package/dist/hooks/use-chat.mjs +4 -4
  52. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  53. package/dist/hooks/use-coagent-state-render.mjs +2 -2
  54. package/dist/hooks/use-coagent.js +75 -10
  55. package/dist/hooks/use-coagent.js.map +1 -1
  56. package/dist/hooks/use-coagent.mjs +10 -10
  57. package/dist/hooks/use-copilot-action.js.map +1 -1
  58. package/dist/hooks/use-copilot-action.mjs +3 -3
  59. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  60. package/dist/hooks/use-copilot-authenticated-action.mjs +4 -4
  61. package/dist/hooks/use-copilot-chat.js +72 -10
  62. package/dist/hooks/use-copilot-chat.js.map +1 -1
  63. package/dist/hooks/use-copilot-chat.mjs +9 -9
  64. package/dist/hooks/use-copilot-runtime-client.js +1 -1
  65. package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
  66. package/dist/hooks/use-copilot-runtime-client.mjs +2 -2
  67. package/dist/hooks/use-langgraph-interrupt.js +72 -10
  68. package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
  69. package/dist/hooks/use-langgraph-interrupt.mjs +10 -10
  70. package/dist/index.js +363 -243
  71. package/dist/index.js.map +1 -1
  72. package/dist/index.mjs +15 -15
  73. package/dist/lib/copilot-task.mjs +8 -8
  74. package/dist/lib/index.mjs +8 -8
  75. package/dist/utils/extract.mjs +7 -7
  76. package/dist/utils/index.mjs +7 -7
  77. package/jest.config.js +7 -3
  78. package/package.json +4 -3
  79. package/src/components/copilot-provider/__tests__/copilotkit-trace.test.tsx +1 -0
  80. package/src/components/copilot-provider/copilot-messages.tsx +42 -3
  81. package/src/components/toast/toast-provider.tsx +49 -24
  82. package/src/components/usage-banner.tsx +144 -147
  83. package/src/hooks/use-chat.ts +106 -6
  84. package/src/hooks/use-coagent.ts +5 -0
  85. package/src/hooks/use-copilot-runtime-client.ts +2 -39
  86. package/tsconfig.json +1 -8
  87. package/dist/chunk-HD2GE3DK.mjs +0 -359
  88. package/dist/chunk-HD2GE3DK.mjs.map +0 -1
  89. package/dist/chunk-ISYBUDL4.mjs.map +0 -1
  90. package/dist/chunk-JXF732XG.mjs.map +0 -1
  91. package/dist/chunk-VJCHRQ7Q.mjs.map +0 -1
  92. package/dist/chunk-VRXANACV.mjs +0 -277
  93. package/dist/chunk-VRXANACV.mjs.map +0 -1
  94. /package/dist/{chunk-CCESTGAM.mjs.map → chunk-3OQM3NEK.mjs.map} +0 -0
  95. /package/dist/{chunk-T4ZKC4X4.mjs.map → chunk-3YHYWAHK.mjs.map} +0 -0
  96. /package/dist/{chunk-S4BOATBG.mjs.map → chunk-EF5BNM34.mjs.map} +0 -0
  97. /package/dist/{chunk-I4JPQECN.mjs.map → chunk-EXU7GWLC.mjs.map} +0 -0
  98. /package/dist/{chunk-7G6RR4HE.mjs.map → chunk-FXK6RQIN.mjs.map} +0 -0
  99. /package/dist/{chunk-JHIZ5HAI.mjs.map → chunk-NQVCZQ5T.mjs.map} +0 -0
  100. /package/dist/{chunk-VF6UPRKM.mjs.map → chunk-OF4SZTLL.mjs.map} +0 -0
  101. /package/dist/{chunk-QQZLIEXK.mjs.map → chunk-SJJNFYGQ.mjs.map} +0 -0
  102. /package/dist/{chunk-RN3ZRHI7.mjs.map → chunk-WOGURSAL.mjs.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # ui
2
2
 
3
+ ## 1.9.2-next.9
4
+
5
+ ### Patch Changes
6
+
7
+ - 1d1c51d: - feat: surface all errors in structured format
8
+ - Updated dependencies [1d1c51d]
9
+ - @copilotkit/runtime-client-gql@1.9.2-next.9
10
+ - @copilotkit/shared@1.9.2-next.9
11
+
12
+ ## 1.9.2-next.8
13
+
14
+ ### Patch Changes
15
+
16
+ - @copilotkit/runtime-client-gql@1.9.2-next.8
17
+ - @copilotkit/shared@1.9.2-next.8
18
+
3
19
  ## 1.9.2-next.7
4
20
 
5
21
  ### Patch Changes
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-O7ARI5CV.mjs";
4
4
  import {
5
5
  useToast
6
- } from "./chunk-VRXANACV.mjs";
6
+ } from "./chunk-YAF2LATQ.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-CCESTGAM.mjs.map
102
+ //# sourceMappingURL=chunk-3OQM3NEK.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useToast
3
- } from "./chunk-VRXANACV.mjs";
3
+ } from "./chunk-YAF2LATQ.mjs";
4
4
  import {
5
5
  CopilotContext
6
6
  } from "./chunk-XFOTNHYA.mjs";
@@ -85,4 +85,4 @@ function useCoAgentStateRender(action, dependencies) {
85
85
  export {
86
86
  useCoAgentStateRender
87
87
  };
88
- //# sourceMappingURL=chunk-T4ZKC4X4.mjs.map
88
+ //# sourceMappingURL=chunk-3YHYWAHK.mjs.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-GFJW4RIM.mjs";
4
4
  import {
5
5
  useToast
6
- } from "./chunk-VRXANACV.mjs";
6
+ } from "./chunk-YAF2LATQ.mjs";
7
7
  import {
8
8
  __async,
9
9
  __objRest,
@@ -22,8 +22,7 @@ import {
22
22
  CopilotKitRemoteEndpointDiscoveryError,
23
23
  CopilotKitAgentDiscoveryError,
24
24
  CopilotKitError,
25
- CopilotKitErrorCode,
26
- ERROR_CONFIG
25
+ CopilotKitErrorCode
27
26
  } from "@copilotkit/shared";
28
27
  var useCopilotRuntimeClient = (options) => {
29
28
  const { setBannerError } = useToast();
@@ -44,7 +43,7 @@ var useCopilotRuntimeClient = (options) => {
44
43
  startTime: Date.now()
45
44
  },
46
45
  technical: {
47
- environment: process.env.NODE_ENV,
46
+ environment: "browser",
48
47
  userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
49
48
  stackTrace: originalError instanceof Error ? originalError.stack : void 0
50
49
  }
@@ -147,4 +146,4 @@ function createStructuredError(gqlError) {
147
146
  export {
148
147
  useCopilotRuntimeClient
149
148
  };
150
- //# sourceMappingURL=chunk-ISYBUDL4.mjs.map
149
+ //# sourceMappingURL=chunk-55QZ2SVJ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-runtime-client.ts"],"sourcesContent":["import {\n CopilotRuntimeClient,\n CopilotRuntimeClientOptions,\n GraphQLError,\n} from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useMemo, useRef } from \"react\";\nimport {\n ErrorVisibility,\n CopilotKitApiDiscoveryError,\n CopilotKitRemoteEndpointDiscoveryError,\n CopilotKitAgentDiscoveryError,\n CopilotKitError,\n CopilotKitErrorCode,\n ERROR_CONFIG,\n CopilotTraceHandler,\n CopilotTraceEvent,\n} from \"@copilotkit/shared\";\nimport { shouldShowDevConsole } from \"../utils/dev-console\";\n\nexport interface CopilotRuntimeClientHookOptions extends CopilotRuntimeClientOptions {\n showDevConsole?: boolean;\n onTrace?: CopilotTraceHandler;\n}\n\nexport const useCopilotRuntimeClient = (options: CopilotRuntimeClientHookOptions) => {\n const { setBannerError } = useToast();\n const { showDevConsole, onTrace, ...runtimeOptions } = options;\n\n // Deduplication state for structured errors\n const lastStructuredErrorRef = useRef<{ message: string; timestamp: number } | null>(null);\n\n // Helper function to trace UI errors\n const traceUIError = async (error: CopilotKitError, originalError?: any) => {\n // Just check if onTrace and publicApiKey are defined\n if (!onTrace || !runtimeOptions.publicApiKey) return;\n\n try {\n const traceEvent: CopilotTraceEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"ui\",\n request: {\n operation: \"runtimeClient\",\n url: runtimeOptions.url,\n startTime: Date.now(),\n },\n technical: {\n environment: \"browser\",\n userAgent: typeof navigator !== \"undefined\" ? navigator.userAgent : undefined,\n stackTrace: originalError instanceof Error ? originalError.stack : undefined,\n },\n },\n error,\n };\n await onTrace(traceEvent);\n } catch (traceError) {\n console.error(\"Error in onTrace handler:\", traceError);\n }\n };\n\n const runtimeClient = useMemo(() => {\n return new CopilotRuntimeClient({\n ...runtimeOptions,\n handleGQLErrors: (error) => {\n if ((error as any).graphQLErrors?.length) {\n const graphQLErrors = (error as any).graphQLErrors as GraphQLError[];\n\n // Route all errors to banners for consistent UI\n const routeError = (gqlError: GraphQLError) => {\n const extensions = gqlError.extensions;\n const visibility = extensions?.visibility as ErrorVisibility;\n const isDev = shouldShowDevConsole(showDevConsole ?? false);\n\n // Silent errors - just log\n if (visibility === ErrorVisibility.SILENT) {\n console.error(\"CopilotKit Silent Error:\", gqlError.message);\n return;\n }\n\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", gqlError.message);\n return;\n }\n\n // All errors (including DEV_ONLY) show as banners for consistency\n // Deduplicate to prevent spam\n const now = Date.now();\n const errorMessage = gqlError.message;\n if (\n lastStructuredErrorRef.current &&\n lastStructuredErrorRef.current.message === errorMessage &&\n now - lastStructuredErrorRef.current.timestamp < 150\n ) {\n return; // Skip duplicate\n }\n lastStructuredErrorRef.current = { message: errorMessage, timestamp: now };\n\n const ckError = createStructuredError(gqlError);\n if (ckError) {\n setBannerError(ckError);\n // Trace the error\n traceUIError(ckError, gqlError);\n } else {\n // Fallback for unstructured errors\n const fallbackError = new CopilotKitError({\n message: gqlError.message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the fallback error\n traceUIError(fallbackError, gqlError);\n }\n };\n\n // Process all errors as banners\n graphQLErrors.forEach(routeError);\n } else {\n const isDev = shouldShowDevConsole(showDevConsole ?? false);\n if (!isDev) {\n console.error(\"CopilotKit Error (hidden in production):\", error);\n } else {\n // Route non-GraphQL errors to banner as well\n const fallbackError = new CopilotKitError({\n message: error?.message || String(error),\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(fallbackError);\n // Trace the non-GraphQL error\n traceUIError(fallbackError, error);\n }\n }\n },\n handleGQLWarning: (message: string) => {\n console.warn(message);\n // Show warnings as banners too for consistency\n const warningError = new CopilotKitError({\n message,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n setBannerError(warningError);\n },\n });\n }, [runtimeOptions, setBannerError, showDevConsole, onTrace]);\n\n return runtimeClient;\n};\n\n// Create appropriate structured error from GraphQL error\nfunction createStructuredError(gqlError: GraphQLError): CopilotKitError | null {\n const extensions = gqlError.extensions;\n const originalError = extensions?.originalError as any;\n const message = originalError?.message || gqlError.message;\n const code = extensions?.code as CopilotKitErrorCode;\n\n if (code) {\n return new CopilotKitError({ message, code });\n }\n\n // Legacy error detection by stack trace\n if (originalError?.stack?.includes(\"CopilotApiDiscoveryError\")) {\n return new CopilotKitApiDiscoveryError({ message });\n }\n if (originalError?.stack?.includes(\"CopilotKitRemoteEndpointDiscoveryError\")) {\n return new CopilotKitRemoteEndpointDiscoveryError({ message });\n }\n if (originalError?.stack?.includes(\"CopilotKitAgentDiscoveryError\")) {\n return new CopilotKitAgentDiscoveryError({\n agentName: \"\",\n availableAgents: [],\n });\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,OAGK;AAEP,SAAS,SAAS,cAAc;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAQA,IAAM,0BAA0B,CAAC,YAA6C;AACnF,QAAM,EAAE,eAAe,IAAI,SAAS;AACpC,QAAuD,cAA/C,kBAAgB,QA3B1B,IA2ByD,IAAnB,2BAAmB,IAAnB,CAA5B,kBAAgB;AAGxB,QAAM,yBAAyB,OAAsD,IAAI;AAGzF,QAAM,eAAe,CAAO,OAAwB,kBAAwB;AAE1E,QAAI,CAAC,WAAW,CAAC,eAAe;AAAc;AAE9C,QAAI;AACF,YAAM,aAAgC;AAAA,QACpC,MAAM;AAAA,QACN,WAAW,KAAK,IAAI;AAAA,QACpB,SAAS;AAAA,UACP,QAAQ;AAAA,UACR,SAAS;AAAA,YACP,WAAW;AAAA,YACX,KAAK,eAAe;AAAA,YACpB,WAAW,KAAK,IAAI;AAAA,UACtB;AAAA,UACA,WAAW;AAAA,YACT,aAAa;AAAA,YACb,WAAW,OAAO,cAAc,cAAc,UAAU,YAAY;AAAA,YACpE,YAAY,yBAAyB,QAAQ,cAAc,QAAQ;AAAA,UACrE;AAAA,QACF;AAAA,QACA;AAAA,MACF;AACA,YAAM,QAAQ,UAAU;AAAA,IAC1B,SAAS,YAAP;AACA,cA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ACjE,OAAO;AAEL,kBAAM,gBAAgB,IAAI,gBAAgB;AAAA,cACxC,UAAS,+BAAO,YAAW,OAAO,KAAK;AAAA,cACvC,MAAM,oBAAoB;AAAA,YAC5B,CAAC;AACD,2BAAe,aAAa;AAE5B,yBAAa,eAAe,KAAK;AAAA,UACnC;AAAA,QACF;AAAA,MACF;AAAA,MACA,kBAAkB,CAAC,YAAoB;AACrC,gBAAQ,KAAK,OAAO;AAEpB,cAAM,eAAe,IAAI,gBAAgB;AAAA,UACvC;AAAA,UACA,MAAM,oBAAoB;AAAA,QAC5B,CAAC;AACD,uBAAe,YAAY;AAAA,MAC7B;AAAA,IACF,EAAC;AAAA,EACH,GAAG,CAAC,gBAAgB,gBAAgB,gBAAgB,OAAO,CAAC;AAE5D,SAAO;AACT;AAGA,SAAS,sBAAsB,UAAgD;AAtJ/E;AAuJE,QAAM,aAAa,SAAS;AAC5B,QAAM,gBAAgB,yCAAY;AAClC,QAAM,WAAU,+CAAe,YAAW,SAAS;AACnD,QAAM,OAAO,yCAAY;AAEzB,MAAI,MAAM;AACR,WAAO,IAAI,gBAAgB,EAAE,SAAS,KAAK,CAAC;AAAA,EAC9C;AAGA,OAAI,oDAAe,UAAf,mBAAsB,SAAS,6BAA6B;AAC9D,WAAO,IAAI,4BAA4B,EAAE,QAAQ,CAAC;AAAA,EACpD;AACA,OAAI,oDAAe,UAAf,mBAAsB,SAAS,2CAA2C;AAC5E,WAAO,IAAI,uCAAuC,EAAE,QAAQ,CAAC;AAAA,EAC/D;AACA,OAAI,oDAAe,UAAf,mBAAsB,SAAS,kCAAkC;AACnE,WAAO,IAAI,8BAA8B;AAAA,MACvC,WAAW;AAAA,MACX,iBAAiB,CAAC;AAAA,IACpB,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":["_a"]}
@@ -0,0 +1,348 @@
1
+ // src/components/usage-banner.tsx
2
+ import { Severity, ERROR_NAMES, ErrorVisibility } from "@copilotkit/shared";
3
+ import { jsx, jsxs } from "react/jsx-runtime";
4
+ var defaultIcons = {
5
+ [Severity.CRITICAL]: /* @__PURE__ */ jsxs(
6
+ "svg",
7
+ {
8
+ viewBox: "0 0 24 24",
9
+ width: "16",
10
+ height: "16",
11
+ stroke: "currentColor",
12
+ strokeWidth: "2.5",
13
+ fill: "none",
14
+ strokeLinecap: "round",
15
+ strokeLinejoin: "round",
16
+ children: [
17
+ /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "10" }),
18
+ /* @__PURE__ */ jsx("line", { x1: "15", y1: "9", x2: "9", y2: "15" }),
19
+ /* @__PURE__ */ jsx("line", { x1: "9", y1: "9", x2: "15", y2: "15" })
20
+ ]
21
+ }
22
+ ),
23
+ [Severity.WARNING]: /* @__PURE__ */ jsxs(
24
+ "svg",
25
+ {
26
+ viewBox: "0 0 24 24",
27
+ width: "16",
28
+ height: "16",
29
+ stroke: "currentColor",
30
+ strokeWidth: "2.5",
31
+ fill: "none",
32
+ strokeLinecap: "round",
33
+ strokeLinejoin: "round",
34
+ children: [
35
+ /* @__PURE__ */ jsx("path", { d: "m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z" }),
36
+ /* @__PURE__ */ jsx("line", { x1: "12", y1: "9", x2: "12", y2: "13" }),
37
+ /* @__PURE__ */ jsx("line", { x1: "12", y1: "17", x2: "12.01", y2: "17" })
38
+ ]
39
+ }
40
+ ),
41
+ [Severity.INFO]: /* @__PURE__ */ jsxs(
42
+ "svg",
43
+ {
44
+ viewBox: "0 0 24 24",
45
+ width: "16",
46
+ height: "16",
47
+ stroke: "currentColor",
48
+ strokeWidth: "2.5",
49
+ fill: "none",
50
+ strokeLinecap: "round",
51
+ strokeLinejoin: "round",
52
+ children: [
53
+ /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "10" }),
54
+ /* @__PURE__ */ jsx("line", { x1: "12", y1: "16", x2: "12", y2: "12" }),
55
+ /* @__PURE__ */ jsx("line", { x1: "12", y1: "8", x2: "12.01", y2: "8" })
56
+ ]
57
+ }
58
+ )
59
+ };
60
+ function UsageBanner({
61
+ severity = Severity.CRITICAL,
62
+ message = "",
63
+ icon,
64
+ onClose,
65
+ actions
66
+ }) {
67
+ if (!message || !severity) {
68
+ return null;
69
+ }
70
+ const parseMessage = (rawMessage) => {
71
+ if (rawMessage.toLowerCase().includes("authentication") || rawMessage.toLowerCase().includes("api key")) {
72
+ return "Authentication failed. Please check your API key.";
73
+ }
74
+ if (rawMessage.toLowerCase().includes("rate limit")) {
75
+ return "Rate limit exceeded. Please try again later.";
76
+ }
77
+ if (rawMessage.toLowerCase().includes("checkpointer")) {
78
+ return "Agent configuration error. Please check your setup.";
79
+ }
80
+ let cleanMessage2 = rawMessage;
81
+ cleanMessage2 = cleanMessage2.split(" - ")[0];
82
+ cleanMessage2 = cleanMessage2.split(": Error code")[0];
83
+ cleanMessage2 = cleanMessage2.split(": 401")[0];
84
+ cleanMessage2 = cleanMessage2.split(": 403")[0];
85
+ cleanMessage2 = cleanMessage2.split(": 404")[0];
86
+ cleanMessage2 = cleanMessage2.split(": 500")[0];
87
+ cleanMessage2 = cleanMessage2.replace(/See more:.*$/g, "").trim();
88
+ if (cleanMessage2.includes("{") || cleanMessage2.includes("'") || cleanMessage2.length > 60) {
89
+ return "Configuration error. Please check your setup.";
90
+ }
91
+ return cleanMessage2 || "An error occurred. Please check your configuration.";
92
+ };
93
+ const cleanMessage = parseMessage(message);
94
+ const Icon = icon || defaultIcons[severity];
95
+ const themeConfigs = {
96
+ [Severity.INFO]: {
97
+ bg: "rgba(239, 246, 255, 0.95)",
98
+ border: "#93c5fd",
99
+ text: "#1e40af",
100
+ icon: "#3b82f6",
101
+ primaryBtn: "#3b82f6",
102
+ primaryBtnHover: "#2563eb"
103
+ },
104
+ [Severity.WARNING]: {
105
+ bg: "rgba(255, 251, 235, 0.95)",
106
+ border: "#fbbf24",
107
+ text: "#92400e",
108
+ icon: "#f59e0b",
109
+ primaryBtn: "#f59e0b",
110
+ primaryBtnHover: "#d97706"
111
+ },
112
+ [Severity.CRITICAL]: {
113
+ bg: "rgba(254, 242, 242, 0.95)",
114
+ border: "#f87171",
115
+ text: "#991b1b",
116
+ icon: "#ef4444",
117
+ primaryBtn: "#ef4444",
118
+ primaryBtnHover: "#dc2626"
119
+ }
120
+ };
121
+ const themeConfig = themeConfigs[severity] || themeConfigs[Severity.CRITICAL];
122
+ return /* @__PURE__ */ jsxs(
123
+ "div",
124
+ {
125
+ style: {
126
+ position: "fixed",
127
+ bottom: "24px",
128
+ left: "50%",
129
+ transform: "translateX(-50%)",
130
+ width: "400px",
131
+ maxWidth: "90vw",
132
+ zIndex: 1e4,
133
+ animation: "bannerSlideIn 0.3s cubic-bezier(0.16, 1, 0.3, 1)"
134
+ },
135
+ children: [
136
+ /* @__PURE__ */ jsx("style", { children: `
137
+ @keyframes bannerSlideIn {
138
+ from {
139
+ opacity: 0;
140
+ transform: translateX(-50%) translateY(20px);
141
+ scale: 0.95;
142
+ }
143
+ to {
144
+ opacity: 1;
145
+ transform: translateX(-50%) translateY(0);
146
+ scale: 1;
147
+ }
148
+ }
149
+ ` }),
150
+ /* @__PURE__ */ jsxs(
151
+ "div",
152
+ {
153
+ style: {
154
+ borderRadius: "12px",
155
+ border: `1px solid ${themeConfig.border}`,
156
+ background: themeConfig.bg,
157
+ padding: "14px",
158
+ boxShadow: "0 8px 32px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.08)",
159
+ position: "relative",
160
+ backdropFilter: "blur(12px)",
161
+ WebkitBackdropFilter: "blur(12px)",
162
+ boxSizing: "border-box",
163
+ overflow: "hidden"
164
+ },
165
+ children: [
166
+ onClose && /* @__PURE__ */ jsx(
167
+ "button",
168
+ {
169
+ onClick: onClose,
170
+ style: {
171
+ position: "absolute",
172
+ top: "8px",
173
+ right: "8px",
174
+ background: "rgba(255, 255, 255, 0.9)",
175
+ border: "none",
176
+ color: themeConfig.text,
177
+ cursor: "pointer",
178
+ fontSize: "16px",
179
+ lineHeight: "1",
180
+ padding: "4px",
181
+ borderRadius: "4px",
182
+ width: "20px",
183
+ height: "20px",
184
+ display: "flex",
185
+ alignItems: "center",
186
+ justifyContent: "center"
187
+ },
188
+ title: "Close",
189
+ children: "\xD7"
190
+ }
191
+ ),
192
+ /* @__PURE__ */ jsx(
193
+ "div",
194
+ {
195
+ style: {
196
+ fontSize: "14px",
197
+ fontWeight: 500,
198
+ color: themeConfig.text,
199
+ lineHeight: "1.4",
200
+ fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
201
+ paddingRight: onClose ? "30px" : "0",
202
+ marginBottom: actions ? "12px" : "0",
203
+ wordBreak: "break-word",
204
+ overflow: "hidden",
205
+ textOverflow: "ellipsis",
206
+ display: "-webkit-box",
207
+ WebkitLineClamp: 2,
208
+ WebkitBoxOrient: "vertical"
209
+ },
210
+ children: cleanMessage
211
+ }
212
+ ),
213
+ actions && /* @__PURE__ */ jsxs(
214
+ "div",
215
+ {
216
+ style: {
217
+ display: "flex",
218
+ gap: "8px",
219
+ flexWrap: "wrap"
220
+ },
221
+ children: [
222
+ actions.secondary && /* @__PURE__ */ jsx(
223
+ "button",
224
+ {
225
+ onClick: actions.secondary.onClick,
226
+ style: {
227
+ borderRadius: "8px",
228
+ padding: "6px 12px",
229
+ fontSize: "13px",
230
+ fontWeight: 500,
231
+ color: themeConfig.text,
232
+ backgroundColor: "rgba(255, 255, 255, 0.9)",
233
+ border: `1px solid ${themeConfig.border}`,
234
+ cursor: "pointer",
235
+ transition: "all 0.2s ease",
236
+ fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
237
+ },
238
+ onMouseOver: (e) => {
239
+ e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 1)";
240
+ e.currentTarget.style.transform = "translateY(-1px)";
241
+ },
242
+ onMouseOut: (e) => {
243
+ e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.9)";
244
+ e.currentTarget.style.transform = "translateY(0)";
245
+ },
246
+ children: actions.secondary.label
247
+ }
248
+ ),
249
+ actions.primary && /* @__PURE__ */ jsx(
250
+ "button",
251
+ {
252
+ onClick: actions.primary.onClick,
253
+ style: {
254
+ borderRadius: "8px",
255
+ padding: "6px 12px",
256
+ fontSize: "13px",
257
+ fontWeight: 600,
258
+ color: "#fff",
259
+ backgroundColor: themeConfig.primaryBtn,
260
+ border: "none",
261
+ cursor: "pointer",
262
+ transition: "all 0.2s ease",
263
+ boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)",
264
+ fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
265
+ },
266
+ onMouseOver: (e) => {
267
+ e.currentTarget.style.backgroundColor = themeConfig.primaryBtnHover;
268
+ e.currentTarget.style.transform = "translateY(-1px)";
269
+ e.currentTarget.style.boxShadow = "0 4px 12px rgba(0, 0, 0, 0.2)";
270
+ },
271
+ onMouseOut: (e) => {
272
+ e.currentTarget.style.backgroundColor = themeConfig.primaryBtn;
273
+ e.currentTarget.style.transform = "translateY(0)";
274
+ e.currentTarget.style.boxShadow = "0 2px 8px rgba(0, 0, 0, 0.15)";
275
+ },
276
+ children: actions.primary.label
277
+ }
278
+ )
279
+ ]
280
+ }
281
+ )
282
+ ]
283
+ }
284
+ )
285
+ ]
286
+ }
287
+ );
288
+ }
289
+ function renderCopilotKitUsage(error, onClose) {
290
+ if (error.visibility !== ErrorVisibility.BANNER) {
291
+ return null;
292
+ }
293
+ const extractUrlFromMessage = (message) => {
294
+ const linkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;
295
+ const match = linkRegex.exec(message);
296
+ return match ? match[2] : null;
297
+ };
298
+ const getErrorActions = (error2) => {
299
+ switch (error2.name) {
300
+ case ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR:
301
+ return {
302
+ primary: {
303
+ label: "Sign In",
304
+ onClick: () => window.location.href = "https://cloud.copilotkit.ai"
305
+ }
306
+ };
307
+ case ERROR_NAMES.UPGRADE_REQUIRED_ERROR:
308
+ return {
309
+ primary: {
310
+ label: "Upgrade",
311
+ onClick: () => window.location.href = "https://copilotkit.ai/"
312
+ }
313
+ };
314
+ case ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR:
315
+ case ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR:
316
+ case ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR:
317
+ return {
318
+ primary: {
319
+ label: "View Docs",
320
+ onClick: () => {
321
+ var _a;
322
+ const urlFromMessage = extractUrlFromMessage(error2.message);
323
+ const urlFromExtensions = (_a = error2.extensions) == null ? void 0 : _a.troubleshootingUrl;
324
+ const url = urlFromMessage || urlFromExtensions || "https://docs.copilotkit.ai/troubleshooting/common-issues";
325
+ window.open(url, "_blank");
326
+ }
327
+ }
328
+ };
329
+ default:
330
+ return void 0;
331
+ }
332
+ };
333
+ return /* @__PURE__ */ jsx(
334
+ UsageBanner,
335
+ {
336
+ severity: error.severity || Severity.CRITICAL,
337
+ message: error.message,
338
+ onClose,
339
+ actions: getErrorActions(error)
340
+ }
341
+ );
342
+ }
343
+
344
+ export {
345
+ UsageBanner,
346
+ renderCopilotKitUsage
347
+ };
348
+ //# sourceMappingURL=chunk-57K2ZJ5F.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/usage-banner.tsx"],"sourcesContent":["import { Severity, CopilotKitError, ERROR_NAMES, ErrorVisibility } from \"@copilotkit/shared\";\n\ninterface UsageBannerProps {\n severity?: Severity;\n message?: string;\n icon?: React.ReactNode;\n onClose?: () => void;\n actions?: {\n primary?: {\n label: string;\n onClick: () => void;\n };\n secondary?: {\n label: string;\n onClick: () => void;\n };\n };\n}\n\nconst defaultIcons: Record<Severity, JSX.Element> = {\n [Severity.CRITICAL]: (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"16\"\n height=\"16\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n fill=\"none\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"15\" y1=\"9\" x2=\"9\" y2=\"15\" />\n <line x1=\"9\" y1=\"9\" x2=\"15\" y2=\"15\" />\n </svg>\n ),\n [Severity.WARNING]: (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"16\"\n height=\"16\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n fill=\"none\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z\" />\n <line x1=\"12\" y1=\"9\" x2=\"12\" y2=\"13\" />\n <line x1=\"12\" y1=\"17\" x2=\"12.01\" y2=\"17\" />\n </svg>\n ),\n [Severity.INFO]: (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"16\"\n height=\"16\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n fill=\"none\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"12\" y1=\"16\" x2=\"12\" y2=\"12\" />\n <line x1=\"12\" y1=\"8\" x2=\"12.01\" y2=\"8\" />\n </svg>\n ),\n};\n\nexport function UsageBanner({\n severity = Severity.CRITICAL,\n message = \"\",\n icon,\n onClose,\n actions,\n}: UsageBannerProps) {\n if (!message || !severity) {\n return null;\n }\n\n // Enhanced message parsing to clean up technical details\n const parseMessage = (rawMessage: string) => {\n // console.log(\"Raw message:\", rawMessage); // Debug\n\n // Super aggressive cleaning - handle common error patterns first\n if (\n rawMessage.toLowerCase().includes(\"authentication\") ||\n rawMessage.toLowerCase().includes(\"api key\")\n ) {\n return \"Authentication failed. Please check your API key.\";\n }\n\n if (rawMessage.toLowerCase().includes(\"rate limit\")) {\n return \"Rate limit exceeded. Please try again later.\";\n }\n\n if (rawMessage.toLowerCase().includes(\"checkpointer\")) {\n return \"Agent configuration error. Please check your setup.\";\n }\n\n // For any other error, extract just the main error type\n let cleanMessage = rawMessage;\n\n // Remove everything after the first \" - \" or \":\" followed by technical details\n cleanMessage = cleanMessage.split(\" - \")[0];\n cleanMessage = cleanMessage.split(\": Error code\")[0];\n cleanMessage = cleanMessage.split(\": 401\")[0];\n cleanMessage = cleanMessage.split(\": 403\")[0];\n cleanMessage = cleanMessage.split(\": 404\")[0];\n cleanMessage = cleanMessage.split(\": 500\")[0];\n\n // Remove \"See more\" links\n cleanMessage = cleanMessage.replace(/See more:.*$/g, \"\").trim();\n\n // If still too technical, just show a generic message\n if (cleanMessage.includes(\"{\") || cleanMessage.includes(\"'\") || cleanMessage.length > 60) {\n return \"Configuration error. Please check your setup.\";\n }\n\n return cleanMessage || \"An error occurred. Please check your configuration.\";\n };\n\n const cleanMessage = parseMessage(message);\n const Icon = icon || defaultIcons[severity];\n\n const themeConfigs = {\n [Severity.INFO]: {\n bg: \"rgba(239, 246, 255, 0.95)\",\n border: \"#93c5fd\",\n text: \"#1e40af\",\n icon: \"#3b82f6\",\n primaryBtn: \"#3b82f6\",\n primaryBtnHover: \"#2563eb\",\n },\n [Severity.WARNING]: {\n bg: \"rgba(255, 251, 235, 0.95)\",\n border: \"#fbbf24\",\n text: \"#92400e\",\n icon: \"#f59e0b\",\n primaryBtn: \"#f59e0b\",\n primaryBtnHover: \"#d97706\",\n },\n [Severity.CRITICAL]: {\n bg: \"rgba(254, 242, 242, 0.95)\",\n border: \"#f87171\",\n text: \"#991b1b\",\n icon: \"#ef4444\",\n primaryBtn: \"#ef4444\",\n primaryBtnHover: \"#dc2626\",\n },\n };\n\n const themeConfig = themeConfigs[severity] || themeConfigs[Severity.CRITICAL];\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"24px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n width: \"400px\",\n maxWidth: \"90vw\",\n zIndex: 10000,\n animation: \"bannerSlideIn 0.3s cubic-bezier(0.16, 1, 0.3, 1)\",\n }}\n >\n <style>\n {`\n @keyframes bannerSlideIn {\n from {\n opacity: 0;\n transform: translateX(-50%) translateY(20px);\n scale: 0.95;\n }\n to {\n opacity: 1;\n transform: translateX(-50%) translateY(0);\n scale: 1;\n }\n }\n `}\n </style>\n <div\n style={{\n borderRadius: \"12px\",\n border: `1px solid ${themeConfig.border}`,\n background: themeConfig.bg,\n padding: \"14px\",\n boxShadow: \"0 8px 32px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.08)\",\n position: \"relative\",\n backdropFilter: \"blur(12px)\",\n WebkitBackdropFilter: \"blur(12px)\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n {/* Close button */}\n {onClose && (\n <button\n onClick={onClose}\n style={{\n position: \"absolute\",\n top: \"8px\",\n right: \"8px\",\n background: \"rgba(255, 255, 255, 0.9)\",\n border: \"none\",\n color: themeConfig.text,\n cursor: \"pointer\",\n fontSize: \"16px\",\n lineHeight: \"1\",\n padding: \"4px\",\n borderRadius: \"4px\",\n width: \"20px\",\n height: \"20px\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n }}\n title=\"Close\"\n >\n ×\n </button>\n )}\n\n {/* Message */}\n <div\n style={{\n fontSize: \"14px\",\n fontWeight: 500,\n color: themeConfig.text,\n lineHeight: \"1.4\",\n fontFamily: \"-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif\",\n paddingRight: onClose ? \"30px\" : \"0\",\n marginBottom: actions ? \"12px\" : \"0\",\n wordBreak: \"break-word\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n display: \"-webkit-box\",\n WebkitLineClamp: 2,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {cleanMessage}\n </div>\n\n {/* Actions */}\n {actions && (\n <div\n style={{\n display: \"flex\",\n gap: \"8px\",\n flexWrap: \"wrap\",\n }}\n >\n {actions.secondary && (\n <button\n onClick={actions.secondary.onClick}\n style={{\n borderRadius: \"8px\",\n padding: \"6px 12px\",\n fontSize: \"13px\",\n fontWeight: 500,\n color: themeConfig.text,\n backgroundColor: \"rgba(255, 255, 255, 0.9)\",\n border: `1px solid ${themeConfig.border}`,\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n fontFamily: \"-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif\",\n }}\n onMouseOver={(e) => {\n e.currentTarget.style.backgroundColor = \"rgba(255, 255, 255, 1)\";\n e.currentTarget.style.transform = \"translateY(-1px)\";\n }}\n onMouseOut={(e) => {\n e.currentTarget.style.backgroundColor = \"rgba(255, 255, 255, 0.9)\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {actions.secondary.label}\n </button>\n )}\n {actions.primary && (\n <button\n onClick={actions.primary.onClick}\n style={{\n borderRadius: \"8px\",\n padding: \"6px 12px\",\n fontSize: \"13px\",\n fontWeight: 600,\n color: \"#fff\",\n backgroundColor: themeConfig.primaryBtn,\n border: \"none\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n boxShadow: \"0 2px 8px rgba(0, 0, 0, 0.15)\",\n fontFamily: \"-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif\",\n }}\n onMouseOver={(e) => {\n e.currentTarget.style.backgroundColor = themeConfig.primaryBtnHover;\n e.currentTarget.style.transform = \"translateY(-1px)\";\n e.currentTarget.style.boxShadow = \"0 4px 12px rgba(0, 0, 0, 0.2)\";\n }}\n onMouseOut={(e) => {\n e.currentTarget.style.backgroundColor = themeConfig.primaryBtn;\n e.currentTarget.style.transform = \"translateY(0)\";\n e.currentTarget.style.boxShadow = \"0 2px 8px rgba(0, 0, 0, 0.15)\";\n }}\n >\n {actions.primary.label}\n </button>\n )}\n </div>\n )}\n </div>\n </div>\n );\n}\n\nexport function renderCopilotKitUsage(error: CopilotKitError, onClose?: () => void) {\n // Route based on error visibility level\n if (error.visibility !== ErrorVisibility.BANNER) {\n return null;\n }\n\n // Extract URL from markdown links in the message\n const extractUrlFromMessage = (message: string): string | null => {\n const linkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const match = linkRegex.exec(message);\n return match ? match[2] : null;\n };\n\n // Get action button based on error type\n const getErrorActions = (error: CopilotKitError) => {\n switch (error.name) {\n case ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR:\n return {\n primary: {\n label: \"Sign In\",\n onClick: () => (window.location.href = \"https://cloud.copilotkit.ai\"),\n },\n };\n case ERROR_NAMES.UPGRADE_REQUIRED_ERROR:\n return {\n primary: {\n label: \"Upgrade\",\n onClick: () => (window.location.href = \"https://copilotkit.ai/\"),\n },\n };\n case ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR:\n case ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR:\n case ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR:\n return {\n primary: {\n label: \"View Docs\",\n onClick: () => {\n // Try to get URL from the error message first, then extensions, then default\n const urlFromMessage = extractUrlFromMessage(error.message);\n const urlFromExtensions = (error.extensions as any)?.troubleshootingUrl;\n const url =\n urlFromMessage ||\n urlFromExtensions ||\n \"https://docs.copilotkit.ai/troubleshooting/common-issues\";\n window.open(url, \"_blank\");\n },\n },\n };\n default:\n return undefined;\n }\n };\n\n return (\n <UsageBanner\n severity={error.severity || Severity.CRITICAL}\n message={error.message}\n onClose={onClose}\n actions={getErrorActions(error)}\n />\n );\n}\n"],"mappings":";AAAA,SAAS,UAA2B,aAAa,uBAAuB;AAqBpE,SAUE,KAVF;AAFJ,IAAM,eAA8C;AAAA,EAClD,CAAC,SAAS,QAAQ,GAChB;AAAA,IAAC;AAAA;AAAA,MACC,SAAQ;AAAA,MACR,OAAM;AAAA,MACN,QAAO;AAAA,MACP,QAAO;AAAA,MACP,aAAY;AAAA,MACZ,MAAK;AAAA,MACL,eAAc;AAAA,MACd,gBAAe;AAAA,MAEf;AAAA,4BAAC,YAAO,IAAG,MAAK,IAAG,MAAK,GAAE,MAAK;AAAA,QAC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AsWc,oBAAM,iBAAiB,sBAAsBA,OAAM,OAAO;AAC1D,oBAAM,qBAAqB,KAAAA,OAAM,eAAN,mBAA0B;AACrD,oBAAM,MACJ,kBACA,qBACA;AACF,qBAAO,KAAK,KAAK,QAAQ;AAAA,YAC3B;AAAA,UACF;AAAA,QACF;AAAA,MACF;AACE,eAAO;AAAA,IACX;AAAA,EACF;AAEA,SACE;AAAA,IAAC;AAAA;AAAA,MACC,UAAU,MAAM,YAAY,SAAS;AAAA,MACrC,SAAS,MAAM;AAAA,MACf;AAAA,MACA,SAAS,gBAAgB,KAAK;AAAA;AAAA,EAChC;AAEJ;","names":["cleanMessage","error"]}
@@ -1,18 +1,18 @@
1
1
  import {
2
2
  useCopilotChat
3
- } from "./chunk-I4JPQECN.mjs";
3
+ } from "./chunk-EXU7GWLC.mjs";
4
4
  import {
5
5
  useCopilotMessagesContext
6
6
  } from "./chunk-DCTJZ742.mjs";
7
7
  import {
8
8
  useAsyncCallback
9
- } from "./chunk-CCESTGAM.mjs";
9
+ } from "./chunk-3OQM3NEK.mjs";
10
10
  import {
11
11
  useCopilotRuntimeClient
12
- } from "./chunk-ISYBUDL4.mjs";
12
+ } from "./chunk-55QZ2SVJ.mjs";
13
13
  import {
14
14
  useToast
15
- } from "./chunk-VRXANACV.mjs";
15
+ } from "./chunk-YAF2LATQ.mjs";
16
16
  import {
17
17
  useCopilotContext
18
18
  } from "./chunk-XFOTNHYA.mjs";
@@ -76,6 +76,9 @@ function useCoAgent(options) {
76
76
  threadId,
77
77
  agentName: name
78
78
  });
79
+ if (result.error) {
80
+ return;
81
+ }
79
82
  const newState = (_b = (_a = result.data) == null ? void 0 : _a.loadAgentState) == null ? void 0 : _b.state;
80
83
  if (newState === lastLoadedState.current)
81
84
  return;
@@ -207,4 +210,4 @@ export {
207
210
  stopAgent,
208
211
  runAgent
209
212
  };
210
- //# sourceMappingURL=chunk-ZHEEHGLS.mjs.map
213
+ //# sourceMappingURL=chunk-ADIITPD2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-coagent.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport {\n CopilotContextParams,\n CopilotMessagesContextParams,\n useCopilotContext,\n useCopilotMessagesContext,\n} from \"../context\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { useCopilotChat } from \"./use-copilot-chat\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nimport { parseJson, 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 const newState = result.data?.loadAgentState?.state;\n if (newState === lastLoadedState.current) return;\n\n if (result.data?.loadAgentState?.threadExists && newState && newState != \"{}\") {\n lastLoadedState.current = newState;\n lastLoadedThreadId.current = threadId;\n const fetchedState = parseJson(newState, {});\n isExternalStateManagement(options)\n ? options.setState(fetchedState)\n : setState(fetchedState);\n }\n };\n void fetchAgentState();\n }, [threadId]);\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n setState(options.state);\n } else if (coagentStates[name] === undefined) {\n setState(options.initialState === undefined ? {} : options.initialState);\n }\n }, [\n isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined,\n // reset initialstate on reset\n coagentStates[name] === undefined,\n ]);\n\n const runAgentCallback = useAsyncCallback(\n async (hint?: HintFunction) => {\n await runAgent(name, context, appendMessage, runChatCompletion, hint);\n },\n [name, context, appendMessage, runChatCompletion],\n );\n\n // Return the state and setState function\n return useMemo(() => {\n const coagentState = getCoagentState({ coagentStates, name, options });\n return {\n name,\n nodeName: coagentState.nodeName,\n threadId: coagentState.threadId,\n running: coagentState.running,\n state: coagentState.state,\n setState: isExternalStateManagement(options) ? options.setState : setState,\n start: () => startAgent(name, context),\n stop: () => stopAgent(name, context),\n run: runAgentCallback,\n };\n }, [name, coagentStates, options, setState, runAgentCallback]);\n}\n\nexport function startAgent(name: string, context: CopilotContextParams) {\n const { setAgentSession } = context;\n setAgentSession({\n agentName: name,\n });\n}\n\nexport function stopAgent(name: string, context: CopilotContextParams) {\n const { agentSession, setAgentSession } = context;\n if (agentSession && agentSession.agentName === name) {\n setAgentSession(null);\n context.setCoagentStates((prevAgentStates) => {\n return {\n ...prevAgentStates,\n [name]: {\n ...prevAgentStates[name],\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n },\n };\n });\n } else {\n console.warn(`No agent session found for ${name}`);\n }\n}\n\nexport async function runAgent(\n name: string,\n context: CopilotContextParams & CopilotMessagesContextParams,\n appendMessage: (message: Message) => Promise<void>,\n runChatCompletion: () => Promise<Message[]>,\n hint?: HintFunction,\n) {\n const { agentSession, setAgentSession } = context;\n if (!agentSession || agentSession.agentName !== name) {\n setAgentSession({\n agentName: name,\n });\n }\n\n let previousState: any = null;\n for (let i = context.messages.length - 1; i >= 0; i--) {\n const message = context.messages[i];\n if (message.isAgentStateMessage() && message.agentName === name) {\n previousState = message.state;\n }\n }\n\n let state = context.coagentStatesRef.current?.[name]?.state || {};\n\n if (hint) {\n const hintMessage = hint({ previousState, currentState: state });\n if (hintMessage) {\n await appendMessage(hintMessage);\n } else {\n await runChatCompletion();\n }\n } else {\n await runChatCompletion();\n }\n}\n\nconst isExternalStateManagement = <T>(\n options: UseCoagentOptions<T>,\n): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n};\n\nconst isInternalStateManagementWithInitial = <T>(\n options: UseCoagentOptions<T>,\n): options is WithInternalStateManagementAndInitial<T> => {\n return \"initialState\" in options;\n};\n\nconst getCoagentState = <T>({\n coagentStates,\n name,\n options,\n}: {\n coagentStates: Record<string, CoagentState>;\n name: string;\n options: UseCoagentOptions<T>;\n}) => {\n if (coagentStates[name]) {\n return coagentStates[name];\n } else {\n return {\n name,\n state: isInternalStateManagementWithInitial<T>(options) ? options.initialState : {},\n config: options.config\n ? options.config\n : options.configurable\n ? { configurable: options.configurable }\n : {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,SAAS,aAAa,WAAW,SAAS,cAAc;AAaxD,SAAS,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,wBAAwB;AACxC,cAAQ,KAAK,OAAO;AAGpB,YAAM,aAAa,IAAI,8BAA8B;AAAA,QACnD,WAAW;AAAA,QACX,iBAAiB,gBAAgB,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,EAAE,GAAG,EAAE;AAAA,MAC1E,CAAC;AACD,qBAAe,UAAU;AAAA,IAC3B;AAAA,EACF,GAAG,CAAC,eAAe,CAAC;AAEpB,QAAM,kBAAkB,0BAA0B;AAClD,QAAM,UAAU,kCAAK,iBAAmB;AACxC,QAAM,EAAE,eAAe,kBAAkB,yBAAyB,UAAU,iBAAiB,IAC3F;AACF,QAAM,EAAE,eAAe,kBAAkB,IAAI,eAAe;AAC5D,QAAM,UAAU,mBACV,iBAAiB,WAAW,CAAC;AAGnC,QA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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
+ {"version":3,"sources":["../src/hooks/use-coagent.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport {\n CopilotContextParams,\n CopilotMessagesContextParams,\n useCopilotContext,\n useCopilotMessagesContext,\n} from \"../context\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { useCopilotChat } from \"./use-copilot-chat\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nimport { parseJson, 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 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,wBAAwB;AACxC,cAAQ,KAAK,OAAO;AAGpB,YAAM,aAAa,IAAI,8BAA8B;AAAA,QACnD,WAAW;AAAA,QACX,iBAAiB,gBAAgB,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,EAAE,GAAG,EAAE;AAAA,MAC1E,CAAC;AACD,qBAAe,UAAU;AAAA,IAC3B;AAAA,EACF,GAAG,CAAC,eAAe,CAAC;AAEpB,QAAM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CAAI;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AACF,MAIM;AACJ,MAAI,cAAc,IAAI,GAAG;AACvB,WAAO,cAAc,IAAI;AAAA,EAC3B,OAAO;AACL,WAAO;AAAA,MACL;AAAA,MACA,OAAO,qCAAwC,OAAO,IAAI,QAAQ,eAAe,CAAC;AAAA,MAClF,QAAQ,QAAQ,SACZ,QAAQ,SACR,QAAQ,eACN,EAAE,cAAc,QAAQ,aAAa,IACrC,CAAC;AAAA,MACP,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,UAAU;AAAA,MACV,UAAU;AAAA,MACV,OAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useCopilotAction
3
- } from "./chunk-JHIZ5HAI.mjs";
3
+ } from "./chunk-NQVCZQ5T.mjs";
4
4
  import {
5
5
  useCopilotContext
6
6
  } from "./chunk-XFOTNHYA.mjs";
@@ -56,4 +56,4 @@ function useCopilotAuthenticatedAction_c(action, dependencies) {
56
56
  export {
57
57
  useCopilotAuthenticatedAction_c
58
58
  };
59
- //# sourceMappingURL=chunk-S4BOATBG.mjs.map
59
+ //# sourceMappingURL=chunk-EF5BNM34.mjs.map