@copilotkit/react-core 1.5.18 → 1.5.19-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/{chunk-MIUILUVX.mjs → chunk-2F6RYBYS.mjs} +2 -2
  3. package/dist/{chunk-5K2FUI34.mjs → chunk-534J55RX.mjs} +19 -13
  4. package/dist/chunk-534J55RX.mjs.map +1 -0
  5. package/dist/{chunk-24PU4QRT.mjs → chunk-6C6ZNKSS.mjs} +2 -2
  6. package/dist/{chunk-DB25UMNI.mjs → chunk-7YXUCWXF.mjs} +2 -2
  7. package/dist/{chunk-CUMF2APV.mjs → chunk-DFNQGERN.mjs} +2 -2
  8. package/dist/{chunk-WSOA4BGM.mjs → chunk-JFCNSGNU.mjs} +2 -2
  9. package/dist/{chunk-HJWT7WXD.mjs → chunk-MNYMDFWD.mjs} +9 -1
  10. package/dist/chunk-MNYMDFWD.mjs.map +1 -0
  11. package/dist/{chunk-2RDVL7EU.mjs → chunk-OBGDZ7BM.mjs} +3 -3
  12. package/dist/{chunk-2VIL3F36.mjs → chunk-PR5R5TTF.mjs} +25 -2
  13. package/dist/chunk-PR5R5TTF.mjs.map +1 -0
  14. package/dist/{chunk-CUSSPNG5.mjs → chunk-T2EFA3D5.mjs} +16 -2
  15. package/dist/chunk-T2EFA3D5.mjs.map +1 -0
  16. package/dist/components/copilot-provider/copilotkit.js +24 -18
  17. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  18. package/dist/components/copilot-provider/copilotkit.mjs +2 -2
  19. package/dist/components/copilot-provider/index.js +24 -18
  20. package/dist/components/copilot-provider/index.js.map +1 -1
  21. package/dist/components/copilot-provider/index.mjs +2 -2
  22. package/dist/components/error-boundary/error-boundary.d.ts +1 -1
  23. package/dist/components/error-boundary/error-boundary.js +18 -12
  24. package/dist/components/error-boundary/error-boundary.js.map +1 -1
  25. package/dist/components/error-boundary/error-boundary.mjs +1 -1
  26. package/dist/components/index.js +24 -18
  27. package/dist/components/index.js.map +1 -1
  28. package/dist/components/index.mjs +2 -2
  29. package/dist/hooks/index.js +45 -1
  30. package/dist/hooks/index.js.map +1 -1
  31. package/dist/hooks/index.mjs +9 -9
  32. package/dist/hooks/use-chat.js +8 -0
  33. package/dist/hooks/use-chat.js.map +1 -1
  34. package/dist/hooks/use-chat.mjs +1 -1
  35. package/dist/hooks/use-coagent-state-render.js +24 -1
  36. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  37. package/dist/hooks/use-coagent-state-render.mjs +1 -1
  38. package/dist/hooks/use-coagent.js +8 -0
  39. package/dist/hooks/use-coagent.js.map +1 -1
  40. package/dist/hooks/use-coagent.mjs +5 -5
  41. package/dist/hooks/use-copilot-action.js +13 -0
  42. package/dist/hooks/use-copilot-action.js.map +1 -1
  43. package/dist/hooks/use-copilot-action.mjs +1 -1
  44. package/dist/hooks/use-copilot-authenticated-action.js +13 -0
  45. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  46. package/dist/hooks/use-copilot-authenticated-action.mjs +2 -2
  47. package/dist/hooks/use-copilot-chat.js +8 -0
  48. package/dist/hooks/use-copilot-chat.js.map +1 -1
  49. package/dist/hooks/use-copilot-chat.mjs +4 -4
  50. package/dist/hooks/use-langgraph-interrupt.js +8 -0
  51. package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
  52. package/dist/hooks/use-langgraph-interrupt.mjs +5 -5
  53. package/dist/index.js +82 -32
  54. package/dist/index.js.map +1 -1
  55. package/dist/index.mjs +10 -10
  56. package/dist/lib/copilot-task.mjs +3 -3
  57. package/dist/lib/index.mjs +3 -3
  58. package/dist/utils/extract.mjs +2 -2
  59. package/dist/utils/index.mjs +2 -2
  60. package/package.json +3 -3
  61. package/src/components/error-boundary/error-boundary.tsx +24 -13
  62. package/src/hooks/use-chat.ts +14 -0
  63. package/src/hooks/use-coagent-state-render.ts +37 -1
  64. package/src/hooks/use-copilot-action.ts +16 -0
  65. package/dist/chunk-2VIL3F36.mjs.map +0 -1
  66. package/dist/chunk-5K2FUI34.mjs.map +0 -1
  67. package/dist/chunk-CUSSPNG5.mjs.map +0 -1
  68. package/dist/chunk-HJWT7WXD.mjs.map +0 -1
  69. /package/dist/{chunk-MIUILUVX.mjs.map → chunk-2F6RYBYS.mjs.map} +0 -0
  70. /package/dist/{chunk-24PU4QRT.mjs.map → chunk-6C6ZNKSS.mjs.map} +0 -0
  71. /package/dist/{chunk-DB25UMNI.mjs.map → chunk-7YXUCWXF.mjs.map} +0 -0
  72. /package/dist/{chunk-CUMF2APV.mjs.map → chunk-DFNQGERN.mjs.map} +0 -0
  73. /package/dist/{chunk-WSOA4BGM.mjs.map → chunk-JFCNSGNU.mjs.map} +0 -0
  74. /package/dist/{chunk-2RDVL7EU.mjs.map → chunk-OBGDZ7BM.mjs.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # ui
2
2
 
3
+ ## 1.5.19-next.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 0dd1ab9: - fix(errors): allow non copilotkit errors to pass to consumer app error boundary
8
+ - Updated dependencies [0dd1ab9]
9
+ - @copilotkit/shared@1.5.19-next.1
10
+ - @copilotkit/runtime-client-gql@1.5.19-next.1
11
+
12
+ ## 1.5.19-next.0
13
+
14
+ ### Patch Changes
15
+
16
+ - 5bc68f8: - fix(actions): warn on action duplication
17
+ - fix(actions): warn on coagent state render duplication
18
+ - @copilotkit/runtime-client-gql@1.5.19-next.0
19
+ - @copilotkit/shared@1.5.19-next.0
20
+
3
21
  ## 1.5.18
4
22
 
5
23
  ### Patch Changes
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useCopilotAction
3
- } from "./chunk-CUSSPNG5.mjs";
3
+ } from "./chunk-T2EFA3D5.mjs";
4
4
  import {
5
5
  useCopilotContext
6
6
  } from "./chunk-ZM56S3LJ.mjs";
@@ -56,4 +56,4 @@ function useCopilotAuthenticatedAction_c(action, dependencies) {
56
56
  export {
57
57
  useCopilotAuthenticatedAction_c
58
58
  };
59
- //# sourceMappingURL=chunk-MIUILUVX.mjs.map
59
+ //# sourceMappingURL=chunk-2F6RYBYS.mjs.map
@@ -12,6 +12,7 @@ import {
12
12
  // src/components/error-boundary/error-boundary.tsx
13
13
  import React, { useEffect } from "react";
14
14
  import { CopilotKitError } from "@copilotkit/shared";
15
+ import { COPILOT_CLOUD_ERROR_NAMES } from "@copilotkit/shared";
15
16
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
16
17
  var statusChecker = new StatusChecker();
17
18
  var CopilotErrorBoundary = class extends React.Component {
@@ -47,20 +48,23 @@ var CopilotErrorBoundary = class extends React.Component {
47
48
  var _a, _b;
48
49
  if (this.state.hasError) {
49
50
  if (this.state.error instanceof CopilotKitError) {
50
- return renderCopilotKitUsage(this.state.error);
51
+ if (COPILOT_CLOUD_ERROR_NAMES.includes(this.state.error.name)) {
52
+ return /* @__PURE__ */ jsx(ErrorToast, { error: this.state.error, children: renderCopilotKitUsage(this.state.error) });
53
+ }
54
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
55
+ this.props.children,
56
+ this.props.showUsageBanner && /* @__PURE__ */ jsx(
57
+ UsageBanner,
58
+ {
59
+ severity: (_a = this.state.status) == null ? void 0 : _a.severity,
60
+ message: (_b = this.state.status) == null ? void 0 : _b.message
61
+ }
62
+ )
63
+ ] });
51
64
  }
52
- return /* @__PURE__ */ jsx(ErrorToast, { error: this.state.error, children: this.props.children });
65
+ throw this.state.error;
53
66
  }
54
- return /* @__PURE__ */ jsxs(Fragment, { children: [
55
- this.props.children,
56
- this.props.showUsageBanner ? /* @__PURE__ */ jsx(
57
- UsageBanner,
58
- {
59
- severity: (_a = this.state.status) == null ? void 0 : _a.severity,
60
- message: (_b = this.state.status) == null ? void 0 : _b.message
61
- }
62
- ) : null
63
- ] });
67
+ return this.props.children;
64
68
  }
65
69
  };
66
70
  function ErrorToast({ error, children }) {
@@ -70,6 +74,8 @@ function ErrorToast({ error, children }) {
70
74
  addErrorToast([error]);
71
75
  }
72
76
  }, [error, addErrorToast]);
77
+ if (!error)
78
+ throw error;
73
79
  return children;
74
80
  }
75
81
 
@@ -77,4 +83,4 @@ export {
77
83
  CopilotErrorBoundary,
78
84
  ErrorToast
79
85
  };
80
- //# sourceMappingURL=chunk-5K2FUI34.mjs.map
86
+ //# sourceMappingURL=chunk-534J55RX.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/error-boundary/error-boundary.tsx"],"sourcesContent":["import React, { useEffect } from \"react\";\nimport { Severity, CopilotKitError } from \"@copilotkit/shared\";\nimport { StatusChecker } from \"../../lib/status-checker\";\nimport { renderCopilotKitUsage, UsageBanner } from \"../usage-banner\";\nimport { useErrorToast } from \"./error-utils\";\nimport { COPILOT_CLOUD_ERROR_NAMES } from \"@copilotkit/shared\";\n\nconst statusChecker = new StatusChecker();\n\ninterface Props {\n children: React.ReactNode;\n publicApiKey?: string;\n showUsageBanner?: boolean;\n}\n\ninterface State {\n hasError: boolean;\n error?: CopilotKitError;\n status?: {\n severity: Severity;\n message: string;\n };\n}\n\nexport class CopilotErrorBoundary extends React.Component<Props, State> {\n constructor(props: Props) {\n super(props);\n this.state = {\n hasError: false,\n };\n }\n\n static getDerivedStateFromError(error: CopilotKitError): State {\n return { hasError: true, error };\n }\n\n componentDidMount() {\n if (this.props.publicApiKey) {\n statusChecker.start(this.props.publicApiKey, (newStatus) => {\n this.setState((prevState) => {\n if (newStatus?.severity !== prevState.status?.severity) {\n return { status: newStatus ?? undefined };\n }\n return null;\n });\n });\n }\n }\n\n componentWillUnmount() {\n statusChecker.stop();\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error(\"CopilotKit Error:\", error, errorInfo);\n }\n\n render() {\n if (this.state.hasError) {\n if (this.state.error instanceof CopilotKitError) {\n // @ts-expect-error -- It's a copilotkit error at this state. Name is valid\n if (COPILOT_CLOUD_ERROR_NAMES.includes(this.state.error.name)) {\n return (\n <ErrorToast error={this.state.error}>\n {renderCopilotKitUsage(this.state.error)}\n </ErrorToast>\n );\n }\n\n return (\n <>\n {this.props.children}\n {this.props.showUsageBanner && (\n <UsageBanner\n severity={this.state.status?.severity}\n message={this.state.status?.message}\n />\n )}\n </>\n );\n }\n throw this.state.error;\n }\n\n return this.props.children;\n }\n}\n\nexport function ErrorToast({ error, children }: { error?: Error; children: React.ReactNode }) {\n const addErrorToast = useErrorToast();\n\n useEffect(() => {\n if (error) {\n addErrorToast([error]);\n }\n }, [error, addErrorToast]);\n\n if (!error) throw error;\n return children;\n}\n"],"mappings":";;;;;;;;;;;;AAAA,OAAO,SAAS,iBAAiB;AACjC,SAAmB,uBAAuB;AAI1C,SAAS,iCAAiC;AA0D9B,SAOF,UAPE,KAOF,YAPE;AAxDZ,IAAM,gBAAgB,IAAI,cAAc;AAiBjC,IAAM,uBAAN,cAAmC,MAAM,UAAwB;AAAA,EACtE,YAAY,OAAc;AACxB,UAAM,KAAK;AACX,SAAK,QAAQ;AAAA,MACX,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EAEA,OAAO,yBAAyB,OAA+B;AAC7D,WAAO,EAAE,UAAU,MAAM,MAAM;AAAA,EACjC;AAAA,EAEA,oBAAoB;AAClB,QAAI,KAAK,MAAM,cAAc;AAC3B,oBAAc,MAAM,KAAK,MAAM,cAAc,CAAC,cAAc;AAC1D,aAAK,SAAS,CAAC,cAAc;AAvCrC;AAwCU,eAAI,uCAAW,gBAAa,eAAU,WAAV,mBAAkB,WAAU;AACtD,mBAAO,EAAE,QAAQ,gCAAa,OAAU;AAAA,UAC1C;AACA,iBAAO;AAAA,QACT,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEA,uBAAuB;AACrB,kBAAc,KAAK;AAAA,EACrB;AAAA,EAEA,kBAAkB,OAAc,WAA4B;AAC1D,YAAQ,MAAM,qBAAqB,OAAO,SAAS;AAAA,EACrD;AAAA,EAEA,SAAS;AAzDX;AA0DI,QAAI,KAAK,MAAM,UAAU;AACvB,UAAI,KAAK,MAAM,iBAAiB,iBAAiB;AAE/C,YAAI,0BAA0B,SAAS,KAAK,MAAM,MAAM,IAAI,GAAG;AAC7D,iBACE,oBAAC,cAAW,OAAO,KAAK,MAAM,OAC3B,gCAAsB,KAAK,MAAM,KAAK,GACzC;AAAA,QAEJ;AAEA,eACE,iCACG;AAAA,eAAK,MAAM;AAAA,UACX,KAAK,MAAM,mBACV;AAAA,YAAC;AAAA;AAAA,cACC,WAAU,UAAK,MAAM,WAAX,mBAAmB;AAAA,cAC7B,UAAS,UAAK,MAAM,WAAX,mBAAmB;AAAA;AAAA,UAC9B;AAAA,WAEJ;AAAA,MAEJ;AACA,YAAM,KAAK,MAAM;AAAA,IACnB;AAEA,WAAO,KAAK,MAAM;AAAA,EACpB;AACF;AAEO,SAAS,WAAW,EAAE,OAAO,SAAS,GAAiD;AAC5F,QAAM,gBAAgB,cAAc;AAEpC,YAAU,MAAM;AACd,QAAI,OAAO;AACT,oBAAc,CAAC,KAAK,CAAC;AAAA,IACvB;AAAA,EACF,GAAG,CAAC,OAAO,aAAa,CAAC;AAEzB,MAAI,CAAC;AAAO,UAAM;AAClB,SAAO;AACT;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useCopilotChat
3
- } from "./chunk-2RDVL7EU.mjs";
3
+ } from "./chunk-OBGDZ7BM.mjs";
4
4
  import {
5
5
  CopilotContext
6
6
  } from "./chunk-ZM56S3LJ.mjs";
@@ -63,4 +63,4 @@ function useLangGraphInterrupt(action, dependencies) {
63
63
  export {
64
64
  useLangGraphInterrupt
65
65
  };
66
- //# sourceMappingURL=chunk-24PU4QRT.mjs.map
66
+ //# sourceMappingURL=chunk-6C6ZNKSS.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  CopilotErrorBoundary
3
- } from "./chunk-5K2FUI34.mjs";
3
+ } from "./chunk-534J55RX.mjs";
4
4
  import {
5
5
  CopilotMessages
6
6
  } from "./chunk-5M47BILE.mjs";
@@ -527,4 +527,4 @@ export {
527
527
  CopilotKitInternal,
528
528
  defaultCopilotContextCategories
529
529
  };
530
- //# sourceMappingURL=chunk-DB25UMNI.mjs.map
530
+ //# sourceMappingURL=chunk-7YXUCWXF.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useCopilotChat
3
- } from "./chunk-2RDVL7EU.mjs";
3
+ } from "./chunk-OBGDZ7BM.mjs";
4
4
  import {
5
5
  useCopilotContext
6
6
  } from "./chunk-ZM56S3LJ.mjs";
@@ -187,4 +187,4 @@ export {
187
187
  stopAgent,
188
188
  runAgent
189
189
  };
190
- //# sourceMappingURL=chunk-CUMF2APV.mjs.map
190
+ //# sourceMappingURL=chunk-DFNQGERN.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  defaultCopilotContextCategories
3
- } from "./chunk-DB25UMNI.mjs";
3
+ } from "./chunk-7YXUCWXF.mjs";
4
4
  import {
5
5
  processActionsForRuntimeRequest
6
6
  } from "./chunk-XERJQUHA.mjs";
@@ -117,4 +117,4 @@ ${instructions}
117
117
  export {
118
118
  CopilotTask
119
119
  };
120
- //# sourceMappingURL=chunk-WSOA4BGM.mjs.map
120
+ //# sourceMappingURL=chunk-JFCNSGNU.mjs.map
@@ -83,6 +83,14 @@ function useChat(options) {
83
83
  (previousMessages) => __async(this, null, function* () {
84
84
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
85
85
  setIsLoading(true);
86
+ const interruptEvent = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event;
87
+ if ((interruptEvent == null ? void 0 : interruptEvent.name) === MetaEventName.LangGraphInterruptEvent && (interruptEvent == null ? void 0 : interruptEvent.value) && !(interruptEvent == null ? void 0 : interruptEvent.response) && agentSessionRef.current) {
88
+ addErrorToast([
89
+ new Error(
90
+ "A message was sent while interrupt is active. This will cause failure on the agent side"
91
+ )
92
+ ]);
93
+ }
86
94
  let newMessages = [
87
95
  new TextMessage({
88
96
  content: "",
@@ -480,4 +488,4 @@ function constructFinalMessages(syncedMessages, previousMessages, newMessages) {
480
488
  export {
481
489
  useChat
482
490
  };
483
- //# sourceMappingURL=chunk-HJWT7WXD.mjs.map
491
+ //# sourceMappingURL=chunk-MNYMDFWD.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-chat.ts"],"sourcesContent":["import React, { useCallback, useRef } from \"react\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n CoAgentStateRenderHandler,\n randomId,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ResultMessage,\n convertMessagesToGqlInput,\n filterAdjacentAgentStateMessages,\n filterAgentStateMessages,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n ForwardedParametersInput,\n loadMessagesFromJsonRepresentation,\n ExtensionsInput,\n CopilotRuntimeClient,\n langGraphInterruptEvent,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\nimport { FrontendAction, processActionsForRuntimeRequest } from \"../types/frontend-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { AgentSession } from \"../context/copilot-context\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\nimport { useAsyncCallback, useErrorToast } from \"../components/error-boundary/error-utils\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetter,\n} from \"../types/interrupt-action\";\nimport { MetaEvent, MetaEventName } from \"@copilotkit/runtime-client-gql\";\nimport {\n CopilotKitLangGraphInterruptEvent,\n LangGraphInterruptEvent,\n MetaEventInput,\n} from \"@copilotkit/runtime-client-gql\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n\n /**\n * Callback function to be called when a coagent action is received.\n */\n onCoAgentStateRender?: CoAgentStateRenderHandler;\n\n /**\n * Function definitions to be sent to the API.\n */\n actions: FrontendAction<any>[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n /**\n * The current list of coagent states.\n */\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n\n /**\n * setState-powered method to update the agent states\n */\n setCoagentStatesWithRef: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n\n /**\n * The current agent session.\n */\n agentSession: AgentSession | null;\n\n /**\n * setState-powered method to update the agent session\n */\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n /**\n * The forwarded parameters.\n */\n forwardedParameters?: Pick<ForwardedParametersInput, \"temperature\">;\n\n /**\n * The current thread ID.\n */\n threadId: string;\n /**\n * set the current thread ID\n */\n setThreadId: (threadId: string) => void;\n /**\n * The current run ID.\n */\n runId: string | null;\n /**\n * set the current run ID\n */\n setRunId: (runId: string | null) => void;\n /**\n * The global chat abort controller.\n */\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n /**\n * The agent lock.\n */\n agentLock: string | null;\n /**\n * The extensions.\n */\n extensions: ExtensionsInput;\n /**\n * The setState-powered method to update the extensions.\n */\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n\n langGraphInterruptAction: LangGraphInterruptAction | null;\n\n setLangGraphInterruptAction: LangGraphInterruptActionSetter;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n\n /**\n * Run the chat completion.\n */\n runChatCompletion: () => Promise<Message[]>;\n};\n\nexport interface AppendMessageOptions {\n /**\n * Whether to run the chat completion after appending the message. Defaults to `true`.\n */\n followUp?: boolean;\n}\n\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoAgentStateRender,\n setCoagentStatesWithRef,\n coagentStatesRef,\n agentSession,\n setAgentSession,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n agentLock,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n } = options;\n const runChatCompletionRef = useRef<(previousMessages: Message[]) => Promise<Message[]>>();\n const addErrorToast = useErrorToast();\n // We need to keep a ref of coagent states and session because of renderAndWait - making sure\n // the latest state is sent to the API\n // This is a workaround and needs to be addressed in the future\n const agentSessionRef = useRef<AgentSession | null>(agentSession);\n agentSessionRef.current = agentSession;\n\n const runIdRef = useRef<string | null>(runId);\n runIdRef.current = runId;\n const extensionsRef = useRef<ExtensionsInput>(extensions);\n extensionsRef.current = extensions;\n\n const publicApiKey = copilotConfig.publicApiKey;\n\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n });\n\n const runChatCompletion = useAsyncCallback(\n async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n const interruptEvent = langGraphInterruptAction?.event;\n // In case an interrupt event exist and valid but has no response yet, we cannot process further messages to an agent\n if (\n interruptEvent?.name === MetaEventName.LangGraphInterruptEvent &&\n interruptEvent?.value &&\n !interruptEvent?.response &&\n agentSessionRef.current\n ) {\n addErrorToast([\n new Error(\n \"A message was sent while interrupt is active. This will cause failure on the agent side\",\n ),\n ]);\n }\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n\n chatAbortControllerRef.current = new AbortController();\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n const isAgentRun = agentSessionRef.current !== null;\n\n const stream = runtimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(actions),\n url: window.location.href,\n },\n threadId: threadId,\n runId: runIdRef.current,\n extensions: extensionsRef.current,\n metaEvents: composeAndFlushMetaEventsInput([langGraphInterruptAction?.event]),\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messagesWithContext)),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n ...(copilotConfig.cloud.guardrails?.input?.restrictToTopic?.enabled\n ? {\n guardrails: {\n inputValidationRules: {\n allowList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n }\n : {}),\n },\n }\n : {}),\n metadata: {\n requestType: CopilotRequestType.Chat,\n },\n ...(agentSessionRef.current\n ? {\n agentSession: agentSessionRef.current,\n }\n : {}),\n agentStates: Object.values(coagentStatesRef.current!).map((state) => ({\n agentName: state.name,\n state: JSON.stringify(state.state),\n })),\n forwardedParameters: options.forwardedParameters || {},\n },\n properties: copilotConfig.properties,\n signal: chatAbortControllerRef.current?.signal,\n }),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let executedCoAgentStateRenders: string[] = [];\n let followUp: FrontendAction[\"followUp\"] = undefined;\n\n let messages: Message[] = [];\n let syncedMessages: Message[] = [];\n let interruptMessages: Message[] = [];\n\n try {\n while (true) {\n let done, value;\n\n try {\n const readResult = await reader.read();\n done = readResult.done;\n value = readResult.value;\n } catch (readError) {\n break;\n }\n\n if (done) {\n if (chatAbortControllerRef.current.signal.aborted) {\n return [];\n }\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n // in the output, graphql inserts __typename, which leads to an error when sending it along\n // as input to the next request.\n extensionsRef.current = CopilotRuntimeClient.removeGraphQLTypename(\n value.generateCopilotResponse.extensions || {},\n );\n\n // setThreadId(threadIdRef.current);\n setRunId(runIdRef.current);\n setExtensions(extensionsRef.current);\n let rawMessagesResponse = value.generateCopilotResponse.messages;\n (value.generateCopilotResponse?.metaEvents ?? []).forEach((ev) => {\n if (ev.name === MetaEventName.LangGraphInterruptEvent) {\n let eventValue = langGraphInterruptEvent(ev as LangGraphInterruptEvent).value;\n try {\n eventValue = JSON.parse(eventValue);\n // In case of unparsable string, we keep the event as is\n } catch (e) {}\n setLangGraphInterruptAction({\n event: {\n ...langGraphInterruptEvent(ev as LangGraphInterruptEvent),\n value: eventValue,\n },\n });\n }\n if (ev.name === MetaEventName.CopilotKitLangGraphInterruptEvent) {\n const data = (ev as CopilotKitLangGraphInterruptEvent).data;\n\n // @ts-expect-error -- same type of messages\n rawMessagesResponse = [...rawMessagesResponse, ...data.messages];\n interruptMessages = convertGqlOutputToMessages(\n // @ts-ignore\n filterAdjacentAgentStateMessages(data.messages),\n );\n }\n });\n\n messages = convertGqlOutputToMessages(\n filterAdjacentAgentStateMessages(rawMessagesResponse),\n );\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message and quit\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n setMessages([...previousMessages, ...newMessages]);\n break;\n }\n\n // add messages to the chat\n else {\n newMessages = [...messages];\n\n for (const message of messages) {\n // execute onCoAgentStateRender handler\n if (\n message.isAgentStateMessage() &&\n !message.active &&\n !executedCoAgentStateRenders.includes(message.id) &&\n onCoAgentStateRender\n ) {\n // Do not execute a coagent action if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute coagent action\n await onCoAgentStateRender({\n name: message.agentName,\n nodeName: message.nodeName,\n state: message.state,\n });\n executedCoAgentStateRenders.push(message.id);\n }\n }\n\n const lastAgentStateMessage = [...messages]\n .reverse()\n .find((message) => message.isAgentStateMessage());\n\n if (lastAgentStateMessage) {\n if (\n lastAgentStateMessage.state.messages &&\n lastAgentStateMessage.state.messages.length > 0\n ) {\n syncedMessages = loadMessagesFromJsonRepresentation(\n lastAgentStateMessage.state.messages,\n );\n }\n setCoagentStatesWithRef((prevAgentStates) => ({\n ...prevAgentStates,\n [lastAgentStateMessage.agentName]: {\n name: lastAgentStateMessage.agentName,\n state: lastAgentStateMessage.state,\n running: lastAgentStateMessage.running,\n active: lastAgentStateMessage.active,\n threadId: lastAgentStateMessage.threadId,\n nodeName: lastAgentStateMessage.nodeName,\n runId: lastAgentStateMessage.runId,\n },\n }));\n if (lastAgentStateMessage.running) {\n setAgentSession({\n threadId: lastAgentStateMessage.threadId,\n agentName: lastAgentStateMessage.agentName,\n nodeName: lastAgentStateMessage.nodeName,\n });\n } else {\n if (agentLock) {\n setAgentSession({\n threadId: randomId(),\n agentName: agentLock,\n nodeName: undefined,\n });\n } else {\n setAgentSession(null);\n }\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Update message state\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n const finalMessages = constructFinalMessages(\n [...syncedMessages, ...interruptMessages],\n previousMessages,\n newMessages,\n );\n\n let didExecuteAction = false;\n\n // execute regular action executions that are specific to the frontend (last actions)\n if (onFunctionCall) {\n // Find consecutive action execution messages at the end\n const lastMessages = [];\n for (let i = finalMessages.length - 1; i >= 0; i--) {\n const message = finalMessages[i];\n if (\n message.isActionExecutionMessage() &&\n message.status.code !== MessageStatusCode.Pending\n ) {\n lastMessages.unshift(message);\n } else {\n break;\n }\n }\n\n for (const message of lastMessages) {\n // We update the message state before calling the handler so that the render\n // function can be called with `executing` state\n setMessages(finalMessages);\n\n const action = actions.find((action) => action.name === message.name);\n\n if (action) {\n followUp = action.followUp;\n let result: any;\n let error: Error | null = null;\n try {\n result = await Promise.race([\n onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n }),\n new Promise((resolve) =>\n chatAbortControllerRef.current?.signal.addEventListener(\"abort\", () =>\n resolve(\"Operation was aborted by the user\"),\n ),\n ),\n // if the user stopped generation, we also abort consecutive actions\n new Promise((resolve) => {\n if (chatAbortControllerRef.current?.signal.aborted) {\n resolve(\"Operation was aborted by the user\");\n }\n }),\n ]);\n } catch (e) {\n error = e as Error;\n addErrorToast([error]);\n result = `Failed to execute action ${message.name}. ${error.message}`;\n console.error(`Failed to execute action ${message.name}: ${error}`);\n }\n didExecuteAction = true;\n const messageIndex = finalMessages.findIndex((msg) => msg.id === message.id);\n finalMessages.splice(\n messageIndex + 1,\n 0,\n new ResultMessage({\n id: \"result-\" + message.id,\n result: ResultMessage.encodeResult(\n error\n ? {\n content: result,\n error: JSON.parse(\n JSON.stringify(error, Object.getOwnPropertyNames(error)),\n ),\n }\n : result,\n ),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n }\n\n setMessages(finalMessages);\n }\n\n if (\n // if followUp is not explicitly false\n followUp !== false &&\n // and we executed an action\n (didExecuteAction ||\n // the last message is a server side result\n (!isAgentRun &&\n finalMessages.length &&\n finalMessages[finalMessages.length - 1].isResultMessage())) &&\n // the user did not stop generation\n !chatAbortControllerRef.current?.signal.aborted\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletionRef.current!(finalMessages);\n } else if (chatAbortControllerRef.current?.signal.aborted) {\n // filter out all the action execution messages that do not have a consecutive matching result message\n const repairedMessages = finalMessages.filter((message, actionExecutionIndex) => {\n if (message.isActionExecutionMessage()) {\n return finalMessages.find(\n (msg, resultIndex) =>\n msg.isResultMessage() &&\n msg.actionExecutionId === message.id &&\n resultIndex === actionExecutionIndex + 1,\n );\n }\n return true;\n });\n const repairedMessageIds = repairedMessages.map((message) => message.id);\n setMessages(repairedMessages);\n\n // LangGraph needs two pieces of information to continue execution:\n // 1. The threadId\n // 2. The nodeName it came from\n // When stopping the agent, we don't know the nodeName the agent would have ended with\n // Therefore, we set the nodeName to the most reasonable thing we can guess, which\n // is \"__end__\"\n if (agentSessionRef.current?.nodeName) {\n setAgentSession({\n threadId: agentSessionRef.current.threadId,\n agentName: agentSessionRef.current.agentName,\n nodeName: \"__end__\",\n });\n }\n // only return new messages that were not filtered out\n return newMessages.filter((message) => repairedMessageIds.includes(message.id));\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n },\n [\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoAgentStateRender,\n setCoagentStatesWithRef,\n coagentStatesRef,\n agentSession,\n setAgentSession,\n ],\n );\n\n runChatCompletionRef.current = runChatCompletion;\n\n const runChatCompletionAndHandleFunctionCall = useAsyncCallback(\n async (messages: Message[]): Promise<void> => {\n await runChatCompletionRef.current!(messages);\n },\n [messages],\n );\n\n // Go over all events and see that they include data that should be returned to the agent\n const composeAndFlushMetaEventsInput = useCallback(\n (metaEvents: (MetaEvent | undefined | null)[]) => {\n return metaEvents.reduce((acc: MetaEventInput[], event) => {\n if (!event) return acc;\n\n switch (event.name) {\n case MetaEventName.LangGraphInterruptEvent:\n if (event.response) {\n // Flush interrupt event from state\n setLangGraphInterruptAction(null);\n const value = (event as LangGraphInterruptEvent).value;\n return [\n ...acc,\n {\n name: event.name,\n value: typeof value === \"string\" ? value : JSON.stringify(value),\n response:\n typeof event.response === \"string\"\n ? event.response\n : JSON.stringify(event.response),\n },\n ];\n }\n return acc;\n default:\n return acc;\n }\n }, []);\n },\n [setLangGraphInterruptAction],\n );\n\n const append = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions): Promise<void> => {\n if (isLoading) {\n return;\n }\n\n const newMessages = [...messages, message];\n setMessages(newMessages);\n const followUp = options?.followUp ?? true;\n if (followUp) {\n return runChatCompletionAndHandleFunctionCall(newMessages);\n }\n },\n [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall],\n );\n\n const reload = useAsyncCallback(async (): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage.isTextMessage() && lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n }, [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);\n\n const stop = (): void => {\n chatAbortControllerRef.current?.abort(\"Stop was called\");\n };\n\n return {\n append,\n reload,\n stop,\n runChatCompletion: () => runChatCompletionRef.current!(messages),\n };\n}\n\nfunction constructFinalMessages(\n syncedMessages: Message[],\n previousMessages: Message[],\n newMessages: Message[],\n): Message[] {\n const finalMessages =\n syncedMessages.length > 0 ? [...syncedMessages] : [...previousMessages, ...newMessages];\n\n if (syncedMessages.length > 0) {\n const messagesWithAgentState = [...previousMessages, ...newMessages];\n\n let previousMessageId: string | undefined = undefined;\n\n for (const message of messagesWithAgentState) {\n if (message.isAgentStateMessage()) {\n // insert this message into finalMessages after the position of previousMessageId\n const index = finalMessages.findIndex((msg) => msg.id === previousMessageId);\n if (index !== -1) {\n finalMessages.splice(index + 1, 0, message);\n }\n }\n\n previousMessageId = message.id;\n }\n }\n\n return finalMessages;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAAgB,aAAa,cAAc;AAC3C;AAAA,EAEE;AAAA,EAEA;AAAA,OACK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AAYP,SAAoB,qBAAqB;AAwJlC,SAAS,QAAQ,SAAyC;AAC/D,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AACJ,QAAM,uBAAuB,OAA4D;AACzF,QAAM,gBAAgB,cAAc;AAIpC,QAAM,kBAAkB,OAA4B,YAAY;AAChE,kBAAgB,UAAU;AAE1B,QAAM,WAAW,OAAsB,KAAK;AAC5C,WAAS,UAAU;AACnB,QAAM,gBAAgB,OAAwB,UAAU;AACxD,gBAAc,UAAU;AAExB,QAAM,eAAe,cAAc;AAEnC,QAAM,UAAU,kCACV,cAAc,WAAW,CAAC,IAC1B,eAAe,EAAE,CAAC,mCAAmC,GAAG,aAAa,IAAI,CAAC;AAGhF,QAAM,gBAAgB,wBAAwB;AAAA,IAC5C,KAAK,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AAW;AAExF,MAAI,eAAe,SAAS,GAAG;AAC7B,UAAM,yBAAyB,CAAC,GAAG,kBAAkB,GAAG,WAAW;AAEnE,QAAI,oBAAwC;AAE5C,eAAW,WAAW,wBAAwB;AAC5C,UAAI,QAAQ,oBAAoB,GAAG;AAEjC,cAAM,QAAQ,cAAc,UAAU,CAAC,QAAQ,IAAI,OAAO,iBAAiB;AAC3E,YAAI,UAAU,IAAI;AAChB,wBAAc,OAAO,QAAQ,GAAG,GAAG,OAAO;AAAA,QAC5C;AAAA,MACF;AAEA,0BAAoB,QAAQ;AAAA,IAC9B;AAAA,EACF;AAEA,SAAO;AACT;","names":["messages","action","_a","options"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  defaultCopilotContextCategories
3
- } from "./chunk-DB25UMNI.mjs";
3
+ } from "./chunk-7YXUCWXF.mjs";
4
4
  import {
5
5
  useCopilotContext
6
6
  } from "./chunk-ZM56S3LJ.mjs";
@@ -9,7 +9,7 @@ import {
9
9
  } from "./chunk-DCTJZ742.mjs";
10
10
  import {
11
11
  useChat
12
- } from "./chunk-HJWT7WXD.mjs";
12
+ } from "./chunk-MNYMDFWD.mjs";
13
13
  import {
14
14
  useAsyncCallback
15
15
  } from "./chunk-22ENANUU.mjs";
@@ -222,4 +222,4 @@ export {
222
222
  useCopilotChat,
223
223
  defaultSystemMessage
224
224
  };
225
- //# sourceMappingURL=chunk-2RDVL7EU.mjs.map
225
+ //# sourceMappingURL=chunk-OBGDZ7BM.mjs.map
@@ -21,7 +21,6 @@ function useCoAgentStateRender(action, dependencies) {
21
21
  useEffect(() => {
22
22
  if ((availableAgents == null ? void 0 : availableAgents.length) && !availableAgents.some((a) => a.name === action.name)) {
23
23
  const message = `(useCoAgentStateRender): Agent "${action.name}" not found. Make sure the agent exists and is properly configured.`;
24
- console.warn(message);
25
24
  addToast({ type: "warning", message });
26
25
  }
27
26
  }, [availableAgents]);
@@ -36,6 +35,30 @@ function useCoAgentStateRender(action, dependencies) {
36
35
  }
37
36
  }
38
37
  }
38
+ useEffect(() => {
39
+ const currentId = idRef.current;
40
+ const hasDuplicate = Object.entries(coAgentStateRenders).some(([id, otherAction]) => {
41
+ if (id === currentId)
42
+ return false;
43
+ if (otherAction.name !== action.name)
44
+ return false;
45
+ const hasNodeName = !!action.nodeName;
46
+ const hasOtherNodeName = !!otherAction.nodeName;
47
+ if (!hasNodeName && !hasOtherNodeName)
48
+ return true;
49
+ if (hasNodeName !== hasOtherNodeName)
50
+ return false;
51
+ return action.nodeName === otherAction.nodeName;
52
+ });
53
+ if (hasDuplicate) {
54
+ const message = action.nodeName ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden` : `Found multiple state renders for agent ${action.name}. State renders might get overridden`;
55
+ addToast({
56
+ type: "warning",
57
+ message,
58
+ id: `dup-action-${action.name}`
59
+ });
60
+ }
61
+ }, [coAgentStateRenders]);
39
62
  useEffect(() => {
40
63
  setCoAgentStateRender(idRef.current, action);
41
64
  if (chatComponentsCache.current !== null && action.render !== void 0) {
@@ -58,4 +81,4 @@ function useCoAgentStateRender(action, dependencies) {
58
81
  export {
59
82
  useCoAgentStateRender
60
83
  };
61
- //# sourceMappingURL=chunk-2VIL3F36.mjs.map
84
+ //# sourceMappingURL=chunk-PR5R5TTF.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-coagent-state-render.ts"],"sourcesContent":["/**\n * The useCoAgentStateRender hook allows you to render UI components or text based on a Agentic Copilot's state.\n * This is particularly useful for showing intermediate state or progress during Agentic Copilot operations.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgentStateRender } from \"@copilotkit/react-core\";\n *\n * type YourAgentState = {\n * agent_state_property: string;\n * }\n *\n * useCoAgentStateRender<YourAgentState>({\n * name: \"basic_agent\",\n * nodeName: \"optionally_specify_a_specific_node\",\n * render: ({ status, state, nodeName }) => {\n * return (\n * <YourComponent\n * agentStateProperty={state.agent_state_property}\n * status={status}\n * nodeName={nodeName}\n * />\n * );\n * },\n * });\n * ```\n *\n * This allows for you to render UI components or text based on what is happening within the agent.\n *\n * ### Example\n * A great example of this is in our Perplexity Clone where we render the progress of an agent's internet search as it is happening.\n * You can play around with it below or learn how to build it with its [demo](/coagents/videos/perplexity-clone).\n *\n * <Callout type=\"info\">\n * This example is hosted on Vercel and may take a few seconds to load.\n * </Callout>\n *\n * <iframe src=\"https://examples-coagents-ai-researcher-ui.vercel.app/\" className=\"w-full rounded-lg border h-[700px] my-4\" />\n */\n\nimport { useRef, useContext, useEffect } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { randomId } from \"@copilotkit/shared\";\nimport { CoAgentStateRender } from \"../types/coagent-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\n\n/**\n * This hook is used to render agent state with custom UI components or text. This is particularly\n * useful for showing intermediate state or progress during Agentic Copilot operations.\n * To get started using rendering intermediate state through this hook, checkout the documentation.\n *\n * https://docs.copilotkit.ai/coagents/shared-state/predictive-state-updates\n */\n\n// We implement useCoAgentStateRender dependency handling so that\n// the developer has the option to not provide any dependencies.\n// see useCopilotAction for more details about this approach.\nexport function useCoAgentStateRender<T = any>(\n action: CoAgentStateRender<T>,\n dependencies?: any[],\n): void {\n const {\n setCoAgentStateRender,\n removeCoAgentStateRender,\n coAgentStateRenders,\n chatComponentsCache,\n availableAgents,\n } = useContext(CopilotContext);\n const idRef = useRef<string>(randomId());\n const { addToast } = useToast();\n\n useEffect(() => {\n if (availableAgents?.length && !availableAgents.some((a) => a.name === action.name)) {\n const message = `(useCoAgentStateRender): Agent \"${action.name}\" not found. Make sure the agent exists and is properly configured.`;\n addToast({ type: \"warning\", message });\n }\n }, [availableAgents]);\n\n const key = `${action.name}-${action.nodeName || \"global\"}`;\n\n if (dependencies === undefined) {\n if (coAgentStateRenders[idRef.current]) {\n coAgentStateRenders[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n // Check for duplicates by comparing against all other actions\n const currentId = idRef.current;\n const hasDuplicate = Object.entries(coAgentStateRenders).some(([id, otherAction]) => {\n // Skip comparing with self\n if (id === currentId) return false;\n\n // Different agent names are never duplicates\n if (otherAction.name !== action.name) return false;\n\n // Same agent names:\n const hasNodeName = !!action.nodeName;\n const hasOtherNodeName = !!otherAction.nodeName;\n\n // If neither has nodeName, they're duplicates\n if (!hasNodeName && !hasOtherNodeName) return true;\n\n // If one has nodeName and other doesn't, they're not duplicates\n if (hasNodeName !== hasOtherNodeName) return false;\n\n // If both have nodeName, they're duplicates only if the names match\n return action.nodeName === otherAction.nodeName;\n });\n\n if (hasDuplicate) {\n const message = action.nodeName\n ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden`\n : `Found multiple state renders for agent ${action.name}. State renders might get overridden`;\n\n addToast({\n type: \"warning\",\n message,\n id: `dup-action-${action.name}`,\n });\n }\n }, [coAgentStateRenders]);\n\n useEffect(() => {\n setCoAgentStateRender(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n return () => {\n removeCoAgentStateRender(idRef.current);\n };\n }, [\n setCoAgentStateRender,\n removeCoAgentStateRender,\n action.name,\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n"],"mappings":";;;;;;;;AA2CA,SAAS,QAAQ,YAAY,iBAAiB;AAE9C,SAAS,gBAAgB;AAelB,SAAS,sBACd,QACA,cACM;AACN,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,WAAW,cAAc;AAC7B,QAAM,QAAQ,OAAe,SAAS,CAAC;AACvC,QAAM,EAAE,SAAS,IAAI,SAAS;AAE9B,YAAU,MAAM;AACd,SAAI,mDAAiB,W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Q,OAAO,WAAW,QAAW;AACvE,0BAAoB,QAAQ,oBAAoB,GAAG,IAAI,OAAO;AAAA,IAChE;AACA,WAAO,MAAM;AACX,+BAAyB,MAAM,OAAO;AAAA,IACxC;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,OAAO;AAAA;AAAA,IAEP,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":[]}
@@ -2,7 +2,8 @@ import {
2
2
  useCopilotContext
3
3
  } from "./chunk-ZM56S3LJ.mjs";
4
4
  import {
5
- useAsyncCallback
5
+ useAsyncCallback,
6
+ useToast
6
7
  } from "./chunk-22ENANUU.mjs";
7
8
  import {
8
9
  __async,
@@ -16,6 +17,7 @@ function useCopilotAction(action, dependencies) {
16
17
  const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();
17
18
  const idRef = useRef(randomId());
18
19
  const renderAndWaitRef = useRef(null);
20
+ const { addToast } = useToast();
19
21
  action = __spreadValues({}, action);
20
22
  if (
21
23
  // renderAndWaitForResponse is not available for catch all actions
@@ -73,6 +75,18 @@ function useCopilotAction(action, dependencies) {
73
75
  }
74
76
  }
75
77
  }
78
+ useEffect(() => {
79
+ const hasDuplicate = Object.values(actions).some(
80
+ (otherAction) => otherAction.name === action.name && otherAction !== actions[idRef.current]
81
+ );
82
+ if (hasDuplicate) {
83
+ addToast({
84
+ type: "warning",
85
+ message: `Found an already registered action with name ${action.name}.`,
86
+ id: `dup-action-${action.name}`
87
+ });
88
+ }
89
+ }, [actions]);
76
90
  useEffect(() => {
77
91
  setAction(idRef.current, action);
78
92
  if (chatComponentsCache.current !== null && action.render !== void 0) {
@@ -104,4 +118,4 @@ function isFrontendAction(action) {
104
118
  export {
105
119
  useCopilotAction
106
120
  };
107
- //# sourceMappingURL=chunk-CUSSPNG5.mjs.map
121
+ //# sourceMappingURL=chunk-T2EFA3D5.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-action.ts"],"sourcesContent":["/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { Parameter, randomId } from \"@copilotkit/shared\";\nimport { createElement, Fragment, useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport {\n ActionRenderProps,\n ActionRenderPropsNoArgsWait,\n ActionRenderPropsWait,\n CatchAllFrontendAction,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();\n const idRef = useRef<string>(randomId());\n const renderAndWaitRef = useRef<RenderAndWaitForResponse | null>(null);\n const { addToast } = useToast();\n\n // clone the action to avoid mutating the original object\n action = { ...action };\n\n // If the developer provides a renderAndWaitForResponse function, we transform the action\n // to use a promise internally, so that we can treat it like a normal action.\n if (\n // renderAndWaitForResponse is not available for catch all actions\n isFrontendAction(action) &&\n // check if renderAndWaitForResponse is set\n (action.renderAndWait || action.renderAndWaitForResponse)\n ) {\n const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;\n // remove the renderAndWait function from the action\n action.renderAndWait = undefined;\n action.renderAndWaitForResponse = undefined;\n // add a handler that will be called when the action is executed\n action.handler = useAsyncCallback(async () => {\n // we create a new promise when the handler is called\n let resolve: (result: any) => void;\n let reject: (error: any) => void;\n const promise = new Promise<any>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n renderAndWaitRef.current = { promise, resolve: resolve!, reject: reject! };\n // then we await the promise (it will be resolved in the original renderAndWait function)\n return await promise;\n }, []) as any;\n\n // add a render function that will be called when the action is rendered\n action.render = ((props: ActionRenderProps<T>): React.ReactElement => {\n // Specifically for renderAndWaitForResponse the executing state is set too early, causing a race condition\n // To fit it: we will wait for the handler to be ready\n let status = props.status;\n if (props.status === \"executing\" && !renderAndWaitRef.current) {\n status = \"inProgress\";\n }\n // Create type safe waitProps based on whether T extends empty array or not\n const waitProps = {\n status,\n args: props.args,\n result: props.result,\n handler: status === \"executing\" ? renderAndWaitRef.current!.resolve : undefined,\n respond: status === \"executing\" ? renderAndWaitRef.current!.resolve : undefined,\n } as T extends [] ? ActionRenderPropsNoArgsWait<T> : ActionRenderPropsWait<T>;\n\n // Type guard to check if renderAndWait is for no args case\n const isNoArgsRenderWait = (\n _fn:\n | ((props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement)\n | ((props: ActionRenderPropsWait<T>) => React.ReactElement),\n ): _fn is (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement => {\n return action.parameters?.length === 0;\n };\n\n // Safely call renderAndWait with correct props type\n if (renderAndWait) {\n if (isNoArgsRenderWait(renderAndWait)) {\n return renderAndWait(waitProps as ActionRenderPropsNoArgsWait<T>);\n } else {\n return renderAndWait(waitProps as ActionRenderPropsWait<T>);\n }\n }\n\n // Return empty Fragment instead of null\n return createElement(Fragment);\n }) as any;\n }\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n // catch all actions don't have a handler\n if (isFrontendAction(action)) {\n actions[idRef.current].handler = action.handler as any;\n }\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n // TODO: using as any here because the type definitions are getting to tricky\n // not wasting time on this now - we know the types are compatible\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n }\n }\n }\n\n useEffect(() => {\n const hasDuplicate = Object.values(actions).some(\n (otherAction) => otherAction.name === action.name && otherAction !== actions[idRef.current],\n );\n\n if (hasDuplicate) {\n addToast({\n type: \"warning\",\n message: `Found an already registered action with name ${action.name}.`,\n id: `dup-action-${action.name}`,\n });\n }\n }, [actions]);\n\n useEffect(() => {\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n // see comment about type safety above\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n // UPDATE: We now have access, we should remove the entry if not referenced by any message.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n isFrontendAction(action) ? action.description : undefined,\n action.name,\n isFrontendAction(action) ? action.disabled : undefined,\n isFrontendAction(action) ? action.available : undefined,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(isFrontendAction(action) ? action.parameters : []),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\nfunction isFrontendAction<T extends Parameter[]>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n): action is FrontendAction<T> {\n return action.name !== \"*\";\n}\n\ninterface RenderAndWaitForResponse {\n promise: Promise<any>;\n resolve: (result: any) => void;\n reject: (error: any) => void;\n}\n"],"mappings":";;;;;;;;;;;;;AAoIA,SAAoB,gBAAgB;AACpC,SAAS,eAAe,UAAU,WAAW,cAAc;AAqBpD,SAAS,iBACd,QACA,cACM;AACN,QAAM,EAAE,WAAW,cAAc,SAAS,oBAAoB,IAAI,kBAAkB;AACpF,QAAM,QAAQ,OAAe,SAAS,CAAC;AACvC,QAAM,mBAAmB,OAAwC,IAAI;AACrE,QAAM,EAAE,SAAS,IAAI,SAAS;AAG9B,WAAS,mBAAK;AAId;AAAA;AAAA,IAEE,iBAAiB,MAAM;AAAA,KAEtB,OAAO,iBAAiB,OAAO;AAAA,IAChC;AACA,UAAM,gBAAgB,OAAO,iBAAiB,OAAO;AAErD,WAAO,gBAAgB;AACvB,WAAO,2BAA2B;AAElC,WAAO,UAAU,iBAAiB,MAAY;AAE5C,UAAI;AACJ,UAAI;AACJ,YAAM,UAAU,IAAI,QAAa,CAAC,gBAAgB,kBAAkB;AAClE,kBAAU;AACV,iBAAS;AAAA,MACX,CAAC;AACD,uBAAiB,UAAU,EAAE,SAAS,SAAmB,OAAgB;AAEzE,aAAO,MAAM;AAAA,IACf,IAAG,CAAC,CAAC;AAGL,WAAO,SAAU,CAAC,UAAoD;AAGpE,UAAI,SAAS,MAAM;AACnB,UAAI,MAAM,WAAW,eAAe,CAAC,iBAAiB,SAAS;AAC7D,iBAAS;AAAA,MACX;AAEA,YAAM,YAAY;AAAA,QAChB;AAAA,QACA,MAAM,MAAM;AAAA,QACZ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D;AACA,WAAO,MAAM;AAIX,mBAAa,MAAM,OAAO;AAAA,IAC5B;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,iBAAiB,MAAM,IAAI,OAAO,cAAc;AAAA,IAChD,OAAO;AAAA,IACP,iBAAiB,MAAM,IAAI,OAAO,WAAW;AAAA,IAC7C,iBAAiB,MAAM,IAAI,OAAO,YAAY;AAAA;AAAA;AAAA,IAG9C,KAAK,UAAU,iBAAiB,MAAM,IAAI,OAAO,aAAa,CAAC,CAAC;AAAA;AAAA,IAEhE,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;AAEA,SAAS,iBACP,QAC6B;AAC7B,SAAO,OAAO,SAAS;AACzB;","names":[]}
@@ -304,7 +304,7 @@ function setsHaveIntersection(setA, setB) {
304
304
 
305
305
  // src/components/copilot-provider/copilotkit.tsx
306
306
  var import_react_dom = require("react-dom");
307
- var import_shared6 = require("@copilotkit/shared");
307
+ var import_shared7 = require("@copilotkit/shared");
308
308
 
309
309
  // src/hooks/use-flat-category-store.ts
310
310
  var import_react3 = require("react");
@@ -975,6 +975,7 @@ function renderCopilotKitUsage(error) {
975
975
  }
976
976
 
977
977
  // src/components/error-boundary/error-boundary.tsx
978
+ var import_shared6 = require("@copilotkit/shared");
978
979
  var import_jsx_runtime6 = require("react/jsx-runtime");
979
980
  var statusChecker = new StatusChecker();
980
981
  var CopilotErrorBoundary = class extends import_react9.default.Component {
@@ -1010,20 +1011,23 @@ var CopilotErrorBoundary = class extends import_react9.default.Component {
1010
1011
  var _a, _b;
1011
1012
  if (this.state.hasError) {
1012
1013
  if (this.state.error instanceof import_shared5.CopilotKitError) {
1013
- return renderCopilotKitUsage(this.state.error);
1014
+ if (import_shared6.COPILOT_CLOUD_ERROR_NAMES.includes(this.state.error.name)) {
1015
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ErrorToast2, { error: this.state.error, children: renderCopilotKitUsage(this.state.error) });
1016
+ }
1017
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_jsx_runtime6.Fragment, { children: [
1018
+ this.props.children,
1019
+ this.props.showUsageBanner && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1020
+ UsageBanner,
1021
+ {
1022
+ severity: (_a = this.state.status) == null ? void 0 : _a.severity,
1023
+ message: (_b = this.state.status) == null ? void 0 : _b.message
1024
+ }
1025
+ )
1026
+ ] });
1014
1027
  }
1015
- return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ErrorToast2, { error: this.state.error, children: this.props.children });
1028
+ throw this.state.error;
1016
1029
  }
1017
- return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_jsx_runtime6.Fragment, { children: [
1018
- this.props.children,
1019
- this.props.showUsageBanner ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1020
- UsageBanner,
1021
- {
1022
- severity: (_a = this.state.status) == null ? void 0 : _a.severity,
1023
- message: (_b = this.state.status) == null ? void 0 : _b.message
1024
- }
1025
- ) : null
1026
- ] });
1030
+ return this.props.children;
1027
1031
  }
1028
1032
  };
1029
1033
  function ErrorToast2({ error, children }) {
@@ -1033,6 +1037,8 @@ function ErrorToast2({ error, children }) {
1033
1037
  addErrorToast([error]);
1034
1038
  }
1035
1039
  }, [error, addErrorToast]);
1040
+ if (!error)
1041
+ throw error;
1036
1042
  return children;
1037
1043
  }
1038
1044
 
@@ -1047,7 +1053,7 @@ function CopilotKit(_a) {
1047
1053
  function CopilotKitInternal(cpkProps) {
1048
1054
  const _a = cpkProps, { children } = _a, props = __objRest(_a, ["children"]);
1049
1055
  validateProps(cpkProps);
1050
- const chatApiEndpoint = props.runtimeUrl || import_shared6.COPILOT_CLOUD_CHAT_URL;
1056
+ const chatApiEndpoint = props.runtimeUrl || import_shared7.COPILOT_CLOUD_CHAT_URL;
1051
1057
  const [actions, setActions] = (0, import_react10.useState)({});
1052
1058
  const [coAgentStateRenders, setCoAgentStateRenders] = (0, import_react10.useState)({});
1053
1059
  const chatComponentsCache = (0, import_react10.useRef)({
@@ -1189,7 +1195,7 @@ ${nonDocumentStrings}`;
1189
1195
  }
1190
1196
  return acc;
1191
1197
  }, {});
1192
- return __spreadValues(__spreadValues(__spreadValues({}, copilotApiConfig.headers || {}), copilotApiConfig.publicApiKey ? { [import_shared6.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey } : {}), authHeaders);
1198
+ return __spreadValues(__spreadValues(__spreadValues({}, copilotApiConfig.headers || {}), copilotApiConfig.publicApiKey ? { [import_shared7.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey } : {}), authHeaders);
1193
1199
  }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);
1194
1200
  const runtimeClient = useCopilotRuntimeClient({
1195
1201
  url: copilotApiConfig.chatApiEndpoint,
@@ -1241,7 +1247,7 @@ ${nonDocumentStrings}`;
1241
1247
  };
1242
1248
  }
1243
1249
  const [agentSession, setAgentSession] = (0, import_react10.useState)(initialAgentSession);
1244
- const [internalThreadId, setInternalThreadId] = (0, import_react10.useState)(props.threadId || (0, import_shared6.randomUUID)());
1250
+ const [internalThreadId, setInternalThreadId] = (0, import_react10.useState)(props.threadId || (0, import_shared7.randomUUID)());
1245
1251
  const setThreadId = (0, import_react10.useCallback)(
1246
1252
  (value) => {
1247
1253
  if (props.threadId) {
@@ -1363,10 +1369,10 @@ function formatFeatureName(featureName) {
1363
1369
  function validateProps(props) {
1364
1370
  const cloudFeatures = Object.keys(props).filter((key) => key.endsWith("_c"));
1365
1371
  if (!props.runtimeUrl && !props.publicApiKey) {
1366
- throw new import_shared6.ConfigurationError("Missing required prop: 'runtimeUrl' or 'publicApiKey'");
1372
+ throw new import_shared7.ConfigurationError("Missing required prop: 'runtimeUrl' or 'publicApiKey'");
1367
1373
  }
1368
1374
  if (cloudFeatures.length > 0 && !props.publicApiKey) {
1369
- throw new import_shared6.MissingPublicApiKeyError(
1375
+ throw new import_shared7.MissingPublicApiKeyError(
1370
1376
  `Missing required prop: 'publicApiKey' to use cloud features: ${cloudFeatures.map(formatFeatureName).join(", ")}`
1371
1377
  );
1372
1378
  }