@copilotkit/react-core 1.1.2 → 1.1.3-feat-runtime-remote-actions.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 (137) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +32 -37
  3. package/dist/{chunk-T6L4EGTD.mjs → chunk-326LK7LX.mjs} +5 -5
  4. package/dist/chunk-326LK7LX.mjs.map +1 -0
  5. package/dist/{chunk-GE7LAL6V.mjs → chunk-3U22BXKC.mjs} +6 -4
  6. package/dist/chunk-3U22BXKC.mjs.map +1 -0
  7. package/dist/{chunk-VFDR4MIF.mjs → chunk-A37GANOW.mjs} +11 -7
  8. package/dist/chunk-A37GANOW.mjs.map +1 -0
  9. package/dist/chunk-BWYAGPEF.mjs +1 -0
  10. package/dist/{chunk-KONDJRB4.mjs → chunk-CODXG6KU.mjs} +5 -5
  11. package/dist/chunk-CODXG6KU.mjs.map +1 -0
  12. package/dist/{chunk-YYZNR3CS.mjs → chunk-HABY7NLH.mjs} +72 -14
  13. package/dist/chunk-HABY7NLH.mjs.map +1 -0
  14. package/dist/{chunk-3NHEWJ4V.mjs → chunk-J2YXDQHR.mjs} +19 -4
  15. package/dist/chunk-J2YXDQHR.mjs.map +1 -0
  16. package/dist/chunk-Q4TTTAXQ.mjs +87 -0
  17. package/dist/chunk-Q4TTTAXQ.mjs.map +1 -0
  18. package/dist/{chunk-TVR5CJ6E.mjs → chunk-RBNULK3U.mjs} +39 -5
  19. package/dist/chunk-RBNULK3U.mjs.map +1 -0
  20. package/dist/chunk-STUXJ3BN.mjs +44 -0
  21. package/dist/chunk-STUXJ3BN.mjs.map +1 -0
  22. package/dist/{chunk-UQRDVZ2N.mjs → chunk-TCZBK3HZ.mjs} +9 -5
  23. package/dist/chunk-TCZBK3HZ.mjs.map +1 -0
  24. package/dist/{chunk-AGGKI26A.mjs → chunk-XSZDVRPW.mjs} +64 -12
  25. package/dist/chunk-XSZDVRPW.mjs.map +1 -0
  26. package/dist/components/copilot-provider/copilotkit-props.d.ts +4 -0
  27. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  28. package/dist/components/copilot-provider/copilotkit.d.ts +2 -1
  29. package/dist/components/copilot-provider/copilotkit.js +50 -5
  30. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  31. package/dist/components/copilot-provider/copilotkit.mjs +2 -2
  32. package/dist/components/copilot-provider/index.d.ts +1 -0
  33. package/dist/components/copilot-provider/index.js +50 -5
  34. package/dist/components/copilot-provider/index.js.map +1 -1
  35. package/dist/components/copilot-provider/index.mjs +2 -2
  36. package/dist/components/index.d.ts +1 -0
  37. package/dist/components/index.js +50 -5
  38. package/dist/components/index.js.map +1 -1
  39. package/dist/components/index.mjs +2 -2
  40. package/dist/context/copilot-context.d.ts +21 -2
  41. package/dist/context/copilot-context.js +18 -3
  42. package/dist/context/copilot-context.js.map +1 -1
  43. package/dist/context/copilot-context.mjs +1 -1
  44. package/dist/context/index.d.ts +2 -0
  45. package/dist/context/index.js +18 -3
  46. package/dist/context/index.js.map +1 -1
  47. package/dist/context/index.mjs +1 -1
  48. package/dist/hooks/index.d.ts +4 -0
  49. package/dist/hooks/index.js +274 -31
  50. package/dist/hooks/index.js.map +1 -1
  51. package/dist/hooks/index.mjs +21 -12
  52. package/dist/hooks/use-chat.d.ts +26 -4
  53. package/dist/hooks/use-chat.js +59 -10
  54. package/dist/hooks/use-chat.js.map +1 -1
  55. package/dist/hooks/use-chat.mjs +1 -1
  56. package/dist/hooks/use-coagent-action.d.ts +5 -0
  57. package/dist/hooks/use-coagent-action.js +156 -0
  58. package/dist/hooks/use-coagent-action.js.map +1 -0
  59. package/dist/hooks/use-coagent-action.mjs +9 -0
  60. package/dist/hooks/use-coagent-action.mjs.map +1 -0
  61. package/dist/hooks/use-coagent.d.ts +27 -0
  62. package/dist/hooks/use-coagent.js +219 -0
  63. package/dist/hooks/use-coagent.js.map +1 -0
  64. package/dist/hooks/use-coagent.mjs +10 -0
  65. package/dist/hooks/use-coagent.mjs.map +1 -0
  66. package/dist/hooks/use-copilot-action.js +27 -5
  67. package/dist/hooks/use-copilot-action.js.map +1 -1
  68. package/dist/hooks/use-copilot-action.mjs +2 -2
  69. package/dist/hooks/use-copilot-chat.js +144 -20
  70. package/dist/hooks/use-copilot-chat.js.map +1 -1
  71. package/dist/hooks/use-copilot-chat.mjs +4 -4
  72. package/dist/hooks/use-copilot-readable.js +21 -3
  73. package/dist/hooks/use-copilot-readable.js.map +1 -1
  74. package/dist/hooks/use-copilot-readable.mjs +2 -2
  75. package/dist/hooks/use-make-copilot-document-readable.js +21 -3
  76. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  77. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  78. package/dist/index.d.ts +5 -0
  79. package/dist/index.js +320 -44
  80. package/dist/index.js.map +1 -1
  81. package/dist/index.mjs +24 -16
  82. package/dist/lib/copilot-task.d.ts +2 -0
  83. package/dist/lib/copilot-task.js +3 -2
  84. package/dist/lib/copilot-task.js.map +1 -1
  85. package/dist/lib/copilot-task.mjs +3 -3
  86. package/dist/lib/index.d.ts +2 -0
  87. package/dist/lib/index.js +3 -2
  88. package/dist/lib/index.js.map +1 -1
  89. package/dist/lib/index.mjs +3 -3
  90. package/dist/types/coagent-action.d.ts +17 -0
  91. package/dist/types/coagent-action.js +19 -0
  92. package/dist/types/coagent-action.js.map +1 -0
  93. package/dist/types/coagent-action.mjs +1 -0
  94. package/dist/types/coagent-action.mjs.map +1 -0
  95. package/dist/types/coagent-state.d.ts +11 -0
  96. package/dist/types/coagent-state.js +19 -0
  97. package/dist/types/coagent-state.js.map +1 -0
  98. package/dist/types/coagent-state.mjs +1 -0
  99. package/dist/types/coagent-state.mjs.map +1 -0
  100. package/dist/types/frontend-action.d.ts +1 -0
  101. package/dist/types/frontend-action.js.map +1 -1
  102. package/dist/utils/extract.d.ts +2 -0
  103. package/dist/utils/extract.js +3 -2
  104. package/dist/utils/extract.js.map +1 -1
  105. package/dist/utils/extract.mjs +3 -3
  106. package/dist/utils/index.d.ts +2 -0
  107. package/dist/utils/index.js +3 -2
  108. package/dist/utils/index.js.map +1 -1
  109. package/dist/utils/index.mjs +3 -3
  110. package/package.json +5 -5
  111. package/src/components/copilot-provider/copilotkit-props.tsx +5 -0
  112. package/src/components/copilot-provider/copilotkit.tsx +45 -3
  113. package/src/context/copilot-context.tsx +44 -3
  114. package/src/hooks/index.ts +2 -0
  115. package/src/hooks/use-chat.ts +107 -11
  116. package/src/hooks/use-coagent-action.ts +44 -0
  117. package/src/hooks/use-coagent.ts +133 -0
  118. package/src/hooks/use-copilot-action.ts +9 -5
  119. package/src/hooks/use-copilot-chat.ts +80 -8
  120. package/src/hooks/use-copilot-readable.ts +3 -3
  121. package/src/hooks/use-make-copilot-document-readable.ts +3 -3
  122. package/src/lib/copilot-task.ts +3 -1
  123. package/src/types/coagent-action.ts +17 -0
  124. package/src/types/coagent-state.ts +9 -0
  125. package/src/types/frontend-action.ts +1 -0
  126. package/src/utils/extract.ts +8 -2
  127. package/dist/chunk-3NHEWJ4V.mjs.map +0 -1
  128. package/dist/chunk-5JB4B2SV.mjs +0 -1
  129. package/dist/chunk-AGGKI26A.mjs.map +0 -1
  130. package/dist/chunk-GE7LAL6V.mjs.map +0 -1
  131. package/dist/chunk-KONDJRB4.mjs.map +0 -1
  132. package/dist/chunk-T6L4EGTD.mjs.map +0 -1
  133. package/dist/chunk-TVR5CJ6E.mjs.map +0 -1
  134. package/dist/chunk-UQRDVZ2N.mjs.map +0 -1
  135. package/dist/chunk-VFDR4MIF.mjs.map +0 -1
  136. package/dist/chunk-YYZNR3CS.mjs.map +0 -1
  137. /package/dist/{chunk-5JB4B2SV.mjs.map → chunk-BWYAGPEF.mjs.map} +0 -0
@@ -6,7 +6,7 @@ import {
6
6
  } from "./chunk-6U3UH3KO.mjs";
7
7
  import {
8
8
  CopilotContext
9
- } from "./chunk-3NHEWJ4V.mjs";
9
+ } from "./chunk-J2YXDQHR.mjs";
10
10
  import {
11
11
  __async,
12
12
  __objRest,
@@ -32,7 +32,11 @@ function CopilotKit(_a) {
32
32
  }
33
33
  const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;
34
34
  const [actions, setActions] = useState({});
35
- const chatComponentsCache = useRef({});
35
+ const [coagentActions, setCoagentActions] = useState({});
36
+ const chatComponentsCache = useRef({
37
+ actions: {},
38
+ coagentActions: {}
39
+ });
36
40
  const { addElement, removeElement, printTree } = use_tree_default();
37
41
  const [messages, setMessages] = useState([]);
38
42
  const [isLoading, setIsLoading] = useState(false);
@@ -56,6 +60,20 @@ function CopilotKit(_a) {
56
60
  return newPoints;
57
61
  });
58
62
  }, []);
63
+ const setCoagentAction = useCallback((id, action) => {
64
+ setCoagentActions((prevPoints) => {
65
+ return __spreadProps(__spreadValues({}, prevPoints), {
66
+ [id]: action
67
+ });
68
+ });
69
+ }, []);
70
+ const removeCoagentAction = useCallback((id) => {
71
+ setCoagentActions((prevPoints) => {
72
+ const newPoints = __spreadValues({}, prevPoints);
73
+ delete newPoints[id];
74
+ return newPoints;
75
+ });
76
+ }, []);
59
77
  const getContextString = useCallback(
60
78
  (documents, categories) => {
61
79
  const documentsString = documents.map((document) => {
@@ -146,6 +164,14 @@ ${nonDocumentStrings}`;
146
164
  return rest;
147
165
  });
148
166
  };
167
+ const [coagentStates, setCoagentStates] = useState({});
168
+ let initialAgentSession = null;
169
+ if (props.agent) {
170
+ initialAgentSession = {
171
+ agentName: props.agent
172
+ };
173
+ }
174
+ const [agentSession, setAgentSession] = useState(initialAgentSession);
149
175
  return /* @__PURE__ */ jsx(
150
176
  CopilotContext.Provider,
151
177
  {
@@ -155,6 +181,9 @@ ${nonDocumentStrings}`;
155
181
  getFunctionCallHandler,
156
182
  setAction,
157
183
  removeAction,
184
+ coagentActions,
185
+ setCoagentAction,
186
+ removeCoagentAction,
158
187
  getContextString,
159
188
  addContext,
160
189
  removeContext,
@@ -171,7 +200,11 @@ ${nonDocumentStrings}`;
171
200
  removeChatSuggestionConfiguration,
172
201
  chatInstructions,
173
202
  setChatInstructions,
174
- showDevConsole: props.showDevConsole === void 0 ? "auto" : props.showDevConsole
203
+ showDevConsole: props.showDevConsole === void 0 ? "auto" : props.showDevConsole,
204
+ coagentStates,
205
+ setCoagentStates,
206
+ agentSession,
207
+ setAgentSession
175
208
  },
176
209
  children
177
210
  }
@@ -189,8 +222,9 @@ function entryPointsToFunctionCallHandler(actions) {
189
222
  if (action) {
190
223
  yield new Promise((resolve, reject) => {
191
224
  flushSync(() => __async(this, null, function* () {
225
+ var _a;
192
226
  try {
193
- result = yield action.handler(args);
227
+ result = yield (_a = action.handler) == null ? void 0 : _a.call(action, args);
194
228
  resolve();
195
229
  } catch (error) {
196
230
  reject(error);
@@ -207,4 +241,4 @@ export {
207
241
  CopilotKit,
208
242
  defaultCopilotContextCategories
209
243
  };
210
- //# sourceMappingURL=chunk-TVR5CJ6E.mjs.map
244
+ //# sourceMappingURL=chunk-RBNULK3U.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * <Tabs items={[\"Copilot Cloud (Recommended)\", \"Self-hosted Runtime\"]}>\n * <Tabs.Tab>\n *\n * You can get your Copilot Cloud API key for free by <LinkToCopilotCloud>signing up here</LinkToCopilotCloud>.\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit publicApiKey=\"<your-public-api-key>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n * </Tabs.Tab>\n *\n * <Tabs.Tab>\n * You can find more information about self-hosting CopilotKit [here](/concepts/copilot-runtime).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n * </Tabs.Tab>\n * </Tabs>\n */\nimport { useCallback, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n InChatRenderFunction,\n ChatComponentsCache,\n AgentSession,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n} from \"@copilotkit/shared\";\nimport { AgentStateMessage, Message } from \"@copilotkit/runtime-client-gql\";\n\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoagentAction } from \"../../types/coagent-action\";\nimport { CoagentState } from \"../../types/coagent-state\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n if (!props.runtimeUrl && !props.publicApiKey) {\n throw new Error(\n \"Please provide either a runtimeUrl or a publicApiKey to the CopilotKit component.\",\n );\n }\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const [coagentActions, setCoagentActions] = useState<Record<string, CoagentAction<any>>>({});\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coagentActions: {},\n });\n const { addElement, removeElement, printTree } = useTree();\n const [messages, setMessages] = useState<Message[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const setCoagentAction = useCallback((id: string, action: CoagentAction<any>) => {\n setCoagentActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeCoagentAction = useCallback((id: string) => {\n setCoagentActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n if (!props.publicApiKey) {\n if (props.cloudRestrictToTopic) {\n throw new Error(\n \"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide a publicApiKey.\",\n );\n }\n }\n\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n };\n\n const removeChatSuggestionConfiguration = (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n };\n\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n coagentActions,\n setCoagentAction,\n removeCoagentAction,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n showDevConsole: props.showDevConsole === undefined ? \"auto\" : props.showDevConsole,\n coagentStates,\n setCoagentStates,\n agentSession,\n setAgentSession,\n }}\n >\n {children}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ messages, name, args }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgCA,SAAS,aAAa,QAAQ,gBAAgB;AAU9C,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,OAGK;AAqMH;AA5LG,SAAS,WAAW,IAAyC;AAAzC,eAAE,WAxD7B,IAwD2B,IAAe,kBAAf,IAAe,CAAb;AAxD7B,MAAAA,KAAAC;AA4DE,MAAI,CAAC,MAAM,cAAc,CAAC,MAAM,cAAc;AAC5C,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,kBAAkB,MAAM,cAAc;AAE5C,QAAM,CAAC,SAAS,UAAU,IAAI,SAA8C,CAAC,CAAC;AAC9E,QAAM,CAAC,gBAAgB,iBAAiB,IAAI,SAA6C,CAAC,CAAC;AAC3F,QAAM,sBAAsB,OAA4B;AAAA,IACtD,SAAS,CAAC;AAAA,IACV,gBAAgB,CAAC;AAAA,EACnB,CAAC;AACD,QAAM,EAAE,YAAY,eAAe,UAAU,IAAI,iBAAQ;AACzD,QAAM,CAAC,UAAU,WAAW,IAAI,SAAoB,CAAC,CAAC;AACtD,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,CAAC,kBAAkB,mBAAmB,IAAI,SAAS,EAAE;AAE3D,QAAM;AAAA,IACJ,YAAY;AAAA,IACZ,eAAe;AAAA,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AA6B,WAA7B,EAAE,UAAU,MAAM,KAAK,GAAM;AACzC,QAAI,wBAA6D,CAAC;AAClE,aAASE,WAAU,SAAS;AAC1B,4BAAsBA,QAAO,IAAI,IAAIA;AAAA,IACvC;AAEA,UAAM,SAAS,sBAAsB,IAAI;AACzC,QAAI,SAAc;AAClB,QAAI,QAAQ;AACV,YAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,kBAAU,MAAY;AAvS9B;AAwSU,cAAI;AACF,qBAAS,OAAM,YAAO,YAAP,gCAAiB;AAChC,oBAAQ;AAAA,UACV,SAAS,OAAP;AACA,mBAAO,KAAK;AAAA,UACd;AAAA,QACF,EAAC;AAAA,MACH,CAAC;AACD,YAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAAA,IACxD;AACA,WAAO;AAAA,EACT;AACF;","names":["_a","_b","action"]}
@@ -0,0 +1,44 @@
1
+ import {
2
+ CopilotContext
3
+ } from "./chunk-J2YXDQHR.mjs";
4
+
5
+ // src/hooks/use-coagent-action.ts
6
+ import { useRef, useContext, useEffect } from "react";
7
+ import { randomId } from "@copilotkit/shared";
8
+ function useCoAgentAction(action, dependencies) {
9
+ const { setCoagentAction, removeCoagentAction, coagentActions, chatComponentsCache } = useContext(CopilotContext);
10
+ const idRef = useRef(randomId());
11
+ const key = `${action.name}-${action.nodeName || "global"}`;
12
+ if (dependencies === void 0) {
13
+ if (coagentActions[idRef.current]) {
14
+ coagentActions[idRef.current].handler = action.handler;
15
+ if (typeof action.render === "function") {
16
+ if (chatComponentsCache.current !== null) {
17
+ chatComponentsCache.current.coagentActions[key] = action.render;
18
+ }
19
+ }
20
+ }
21
+ }
22
+ useEffect(() => {
23
+ setCoagentAction(idRef.current, action);
24
+ if (chatComponentsCache.current !== null && action.render !== void 0) {
25
+ chatComponentsCache.current.coagentActions[key] = action.render;
26
+ }
27
+ return () => {
28
+ removeCoagentAction(idRef.current);
29
+ };
30
+ }, [
31
+ setCoagentAction,
32
+ removeCoagentAction,
33
+ action.name,
34
+ // include render only if it's a string
35
+ typeof action.render === "string" ? action.render : void 0,
36
+ // dependencies set by the developer
37
+ ...dependencies || []
38
+ ]);
39
+ }
40
+
41
+ export {
42
+ useCoAgentAction
43
+ };
44
+ //# sourceMappingURL=chunk-STUXJ3BN.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-coagent-action.ts"],"sourcesContent":["import { useRef, useContext, useEffect } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { randomId } from \"@copilotkit/shared\";\nimport { CoagentAction } from \"../types/coagent-action\";\n\n// We implement useCoAgentAction 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 useCoAgentAction<T = any>(action: CoagentAction<T>, dependencies?: any[]): void {\n const { setCoagentAction, removeCoagentAction, coagentActions, chatComponentsCache } =\n useContext(CopilotContext);\n const idRef = useRef<string>(randomId());\n\n const key = `${action.name}-${action.nodeName || \"global\"}`;\n\n if (dependencies === undefined) {\n if (coagentActions[idRef.current]) {\n coagentActions[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.coagentActions[key] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n setCoagentAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.coagentActions[key] = action.render;\n }\n return () => {\n removeCoagentAction(idRef.current);\n };\n }, [\n setCoagentAction,\n removeCoagentAction,\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":";;;;;AAAA,SAAS,QAAQ,YAAY,iBAAiB;AAE9C,SAAS,gBAAgB;AAMlB,SAAS,iBAA0B,QAA0B,cAA4B;AAC9F,QAAM,EAAE,kBAAkB,qBAAqB,gBAAgB,oBAAoB,IACjF,WAAW,cAAc;AAC3B,QAAM,QAAQ,OAAe,SAAS,CAAC;AAEvC,QAAM,MAAM,GAAG,OAAO,QAAQ,OAAO,YAAY;AAEjD,MAAI,iBAAiB,QAAW;AAC9B,QAAI,eAAe,MAAM,OAAO,GAAG;AACjC,qBAAe,MAAM,OAAO,EAAE,UAAU,OAAO;AAC/C,UAAI,OAAO,OAAO,WAAW,YAAY;AACvC,YAAI,oBAAoB,YAAY,MAAM;AACxC,8BAAoB,QAAQ,eAAe,GAAG,IAAI,OAAO;AAAA,QAC3D;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,YAAU,MAAM;AACd,qBAAiB,MAAM,SAAS,MAAa;AAC7C,QAAI,oBAAoB,YAAY,QAAQ,OAAO,WAAW,QAAW;AACvE,0BAAoB,QAAQ,eAAe,GAAG,IAAI,OAAO;AAAA,IAC3D;AACA,WAAO,MAAM;AACX,0BAAoB,MAAM,OAAO;AAAA,IACnC;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":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  defaultCopilotContextCategories
3
- } from "./chunk-TVR5CJ6E.mjs";
3
+ } from "./chunk-RBNULK3U.mjs";
4
4
  import {
5
5
  __async,
6
6
  __spreadValues
@@ -19,7 +19,10 @@ import {
19
19
  CopilotRequestType
20
20
  } from "@copilotkit/runtime-client-gql";
21
21
  import { CopilotRuntimeClient } from "@copilotkit/runtime-client-gql";
22
- import { convertMessagesToGqlInput } from "@copilotkit/runtime-client-gql";
22
+ import {
23
+ convertMessagesToGqlInput,
24
+ filterAgentStateMessages
25
+ } from "@copilotkit/runtime-client-gql";
23
26
  function extract(_0) {
24
27
  return __async(this, arguments, function* ({
25
28
  context,
@@ -69,10 +72,11 @@ function extract(_0) {
69
72
  description: action.description || "",
70
73
  jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || []))
71
74
  }
72
- ]
75
+ ],
76
+ url: window.location.href
73
77
  },
74
78
  messages: convertMessagesToGqlInput(
75
- includeMessages ? [systemMessage, ...messages] : [systemMessage]
79
+ includeMessages ? [systemMessage, ...filterAgentStateMessages(messages)] : [systemMessage]
76
80
  ),
77
81
  metadata: {
78
82
  requestType
@@ -150,4 +154,4 @@ Any additional messages provided are for providing context only and should not b
150
154
  export {
151
155
  extract
152
156
  };
153
- //# sourceMappingURL=chunk-UQRDVZ2N.mjs.map
157
+ //# sourceMappingURL=chunk-TCZBK3HZ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/extract.ts"],"sourcesContent":["import {\n Action,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n MappedParameterTypes,\n Parameter,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n ActionExecutionMessage,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n CopilotRequestType,\n} from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CopilotRuntimeClient } from \"@copilotkit/runtime-client-gql\";\nimport {\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n} from \"@copilotkit/runtime-client-gql\";\n\ninterface InitialState<T extends Parameter[] | [] = []> {\n status: \"initial\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n}\n\ntype StreamHandlerArgs<T extends Parameter[] | [] = []> =\n | InitialState<T>\n | InProgressState<T>\n | CompleteState<T>;\n\ninterface ExtractOptions<T extends Parameter[]> {\n context: CopilotContextParams;\n instructions: string;\n parameters: T;\n include?: IncludeOptions;\n data?: any;\n abortSignal?: AbortSignal;\n stream?: (args: StreamHandlerArgs<T>) => void;\n requestType?: CopilotRequestType;\n}\n\ninterface IncludeOptions {\n readable?: boolean;\n messages?: boolean;\n}\n\nexport async function extract<const T extends Parameter[]>({\n context,\n instructions,\n parameters,\n include,\n data,\n abortSignal,\n stream,\n requestType = CopilotRequestType.Task,\n}: ExtractOptions<T>): Promise<MappedParameterTypes<T>> {\n const { messages } = context;\n\n const action: Action<any> = {\n name: \"extract\",\n parameters,\n handler: (args: any) => {},\n };\n\n const includeReadable = include?.readable ?? false;\n const includeMessages = include?.messages ?? false;\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (includeReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage: Message = new TextMessage({\n content: makeSystemMessage(contextString, instructions),\n role: Role.System,\n });\n\n const headers = {\n ...(context.copilotApiConfig.headers || {}),\n ...(context.copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: context.copilotApiConfig.publicApiKey }\n : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = CopilotRuntimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [\n {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n },\n ],\n url: window.location.href,\n },\n\n messages: convertMessagesToGqlInput(\n includeMessages\n ? [systemMessage, ...filterAgentStateMessages(messages)]\n : [systemMessage],\n ),\n metadata: {\n requestType: requestType,\n },\n forwardedParameters: {\n toolChoice: \"function\",\n toolChoiceFunctionName: action.name,\n },\n },\n properties: context.copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n\n const reader = response.getReader();\n\n let isInitial = true;\n\n let actionExecutionMessage: ActionExecutionMessage | undefined = undefined;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (abortSignal?.aborted) {\n throw new Error(\"Aborted\");\n }\n\n actionExecutionMessage = convertGqlOutputToMessages(\n value.generateCopilotResponse.messages,\n ).find((msg) => msg instanceof ActionExecutionMessage) as ActionExecutionMessage | undefined;\n\n if (!actionExecutionMessage) {\n continue;\n }\n\n stream?.({\n status: isInitial ? \"initial\" : \"inProgress\",\n args: actionExecutionMessage.arguments as Partial<MappedParameterTypes<T>>,\n });\n\n isInitial = false;\n }\n\n if (!actionExecutionMessage) {\n throw new Error(\"extract() failed: No function call occurred\");\n }\n\n stream?.({\n status: \"complete\",\n args: actionExecutionMessage.arguments as MappedParameterTypes<T>,\n });\n\n return actionExecutionMessage.arguments as MappedParameterTypes<T>;\n}\n\nfunction makeSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with a function called extract you MUST call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call the function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n\nAny additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.\n`;\n}\n"],"mappings":";;;;;;;;;AAAA;AAAA,EAEE;AAAA,EAGA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAsCP,SAAsB,QAAqC,IASH;AAAA,6CATG;AAAA,IACzD;AAAA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14 @@ import {
16
16
  ResultMessage,
17
17
  CopilotRuntimeClient,
18
18
  convertMessagesToGqlInput,
19
+ filterAdjacentAgentStateMessages,
20
+ filterAgentStateMessages,
19
21
  convertGqlOutputToMessages,
20
22
  MessageStatusCode,
21
23
  MessageRole,
22
24
  Role,
23
- CopilotRequestType
25
+ CopilotRequestType,
26
+ AgentStateMessage
24
27
  } from "@copilotkit/runtime-client-gql";
25
28
  function useChat(options) {
26
29
  const {
@@ -32,7 +35,12 @@ function useChat(options) {
32
35
  initialMessages,
33
36
  isLoading,
34
37
  actions,
35
- onFunctionCall
38
+ onFunctionCall,
39
+ onCoagentAction,
40
+ setCoagentStates,
41
+ coagentStates,
42
+ agentSession,
43
+ setAgentSession
36
44
  } = options;
37
45
  const abortControllerRef = useRef();
38
46
  const threadIdRef = useRef(null);
@@ -61,17 +69,18 @@ function useChat(options) {
61
69
  const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
62
70
  const stream = CopilotRuntimeClient.asStream(
63
71
  runtimeClient.generateCopilotResponse({
64
- data: __spreadProps(__spreadValues({
72
+ data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
65
73
  frontend: {
66
74
  actions: actions.map((action) => ({
67
75
  name: action.name,
68
76
  description: action.description || "",
69
77
  jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || []))
70
- }))
78
+ })),
79
+ url: window.location.href
71
80
  },
72
81
  threadId: threadIdRef.current,
73
82
  runId: runIdRef.current,
74
- messages: convertMessagesToGqlInput(messagesWithContext)
83
+ messages: convertMessagesToGqlInput(filterAgentStateMessages(messagesWithContext))
75
84
  }, copilotConfig.cloud ? {
76
85
  cloud: __spreadValues({}, ((_c = (_b = (_a = copilotConfig.cloud.guardrails) == null ? void 0 : _a.input) == null ? void 0 : _b.restrictToTopic) == null ? void 0 : _c.enabled) ? {
77
86
  guardrails: {
@@ -85,6 +94,13 @@ function useChat(options) {
85
94
  metadata: {
86
95
  requestType: CopilotRequestType.Chat
87
96
  }
97
+ }), agentSession ? {
98
+ agentSession
99
+ } : {}), {
100
+ agentStates: Object.values(coagentStates).map((state) => ({
101
+ agentName: state.name,
102
+ state: JSON.stringify(state.state)
103
+ }))
88
104
  }),
89
105
  properties: copilotConfig.properties,
90
106
  signal: (_d = abortControllerRef.current) == null ? void 0 : _d.signal
@@ -92,7 +108,8 @@ function useChat(options) {
92
108
  );
93
109
  const guardrailsEnabled = ((_g = (_f = (_e = copilotConfig.cloud) == null ? void 0 : _e.guardrails) == null ? void 0 : _f.input) == null ? void 0 : _g.restrictToTopic.enabled) || false;
94
110
  const reader = stream.getReader();
95
- let results = {};
111
+ let actionResults = {};
112
+ let executedCoagentActions = [];
96
113
  try {
97
114
  while (true) {
98
115
  const { done, value } = yield reader.read();
@@ -104,7 +121,9 @@ function useChat(options) {
104
121
  }
105
122
  threadIdRef.current = value.generateCopilotResponse.threadId || null;
106
123
  runIdRef.current = value.generateCopilotResponse.runId || null;
107
- const messages2 = convertGqlOutputToMessages(value.generateCopilotResponse.messages);
124
+ const messages2 = convertGqlOutputToMessages(
125
+ filterAdjacentAgentStateMessages(value.generateCopilotResponse.messages)
126
+ );
108
127
  if (messages2.length === 0) {
109
128
  continue;
110
129
  }
@@ -119,8 +138,30 @@ function useChat(options) {
119
138
  } else {
120
139
  for (const message of messages2) {
121
140
  newMessages.push(message);
141
+ if (message instanceof AgentStateMessage) {
142
+ if (message.running) {
143
+ setCoagentStates((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
144
+ [message.agentName]: {
145
+ name: message.agentName,
146
+ state: message.state,
147
+ running: message.running,
148
+ active: message.active,
149
+ threadId: message.threadId,
150
+ nodeName: message.nodeName,
151
+ runId: message.runId
152
+ }
153
+ }));
154
+ setAgentSession({
155
+ threadId: message.threadId,
156
+ agentName: message.agentName,
157
+ nodeName: message.nodeName
158
+ });
159
+ } else {
160
+ setAgentSession(null);
161
+ }
162
+ }
122
163
  if (message instanceof ActionExecutionMessage && message.status.code !== MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
123
- if (!(message.id in results)) {
164
+ if (!(message.id in actionResults)) {
124
165
  if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
125
166
  break;
126
167
  }
@@ -129,16 +170,27 @@ function useChat(options) {
129
170
  name: message.name,
130
171
  args: message.arguments
131
172
  });
132
- results[message.id] = result;
173
+ actionResults[message.id] = result;
133
174
  }
134
175
  newMessages.push(
135
176
  new ResultMessage({
136
- result: ResultMessage.encodeResult(results[message.id]),
177
+ result: ResultMessage.encodeResult(actionResults[message.id]),
137
178
  actionExecutionId: message.id,
138
179
  actionName: message.name
139
180
  })
140
181
  );
141
182
  }
183
+ if (message instanceof AgentStateMessage && !message.active && !executedCoagentActions.includes(message.id) && onCoagentAction) {
184
+ if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
185
+ break;
186
+ }
187
+ yield onCoagentAction({
188
+ name: message.agentName,
189
+ nodeName: message.nodeName,
190
+ state: message.state
191
+ });
192
+ executedCoagentActions.push(message.id);
193
+ }
142
194
  }
143
195
  }
144
196
  if (newMessages.length > 0) {
@@ -147,7 +199,7 @@ function useChat(options) {
147
199
  }
148
200
  if (
149
201
  // if we have client side results
150
- Object.values(results).length || // or the last message we received is a result
202
+ Object.values(actionResults).length || // or the last message we received is a result
151
203
  newMessages.length && newMessages[newMessages.length - 1] instanceof ResultMessage
152
204
  ) {
153
205
  yield new Promise((resolve) => setTimeout(resolve, 10));
@@ -196,4 +248,4 @@ function useChat(options) {
196
248
  export {
197
249
  useChat
198
250
  };
199
- //# sourceMappingURL=chunk-AGGKI26A.mjs.map
251
+ //# sourceMappingURL=chunk-XSZDVRPW.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-chat.ts"],"sourcesContent":["import { useRef } from \"react\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n actionParametersToJsonSchema,\n CoagentActionHandler,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ActionExecutionMessage,\n ResultMessage,\n CopilotRuntimeClient,\n convertMessagesToGqlInput,\n filterAdjacentAgentStateMessages,\n filterAgentStateMessages,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n AgentStateMessage,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { AgentSession } from \"../context/copilot-context\";\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 onCoagentAction?: CoagentActionHandler;\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 coagentStates: Record<string, CoagentState>;\n\n /**\n * setState-powered method to update the agent states\n */\n setCoagentStates: 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\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) => 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\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 onCoagentAction,\n setCoagentStates,\n coagentStates,\n agentSession,\n setAgentSession,\n } = options;\n\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\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 = new CopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n });\n\n const runChatCompletion = async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\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 const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n const stream = CopilotRuntimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: actions.map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n url: window.location.href,\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\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 ...(agentSession\n ? {\n agentSession,\n }\n : {}),\n agentStates: Object.values(coagentStates).map((state) => ({\n agentName: state.name,\n state: JSON.stringify(state.state),\n })),\n },\n properties: copilotConfig.properties,\n signal: abortControllerRef.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 actionResults: { [id: string]: string } = {};\n let executedCoagentActions: string[] = [];\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n threadIdRef.current = value.generateCopilotResponse.threadId || null;\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n const messages = convertGqlOutputToMessages(\n filterAdjacentAgentStateMessages(value.generateCopilotResponse.messages),\n );\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message\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 }\n\n // add messages to the chat\n else {\n for (const message of messages) {\n newMessages.push(message);\n if (message instanceof AgentStateMessage) {\n if (message.running) {\n setCoagentStates((prevAgentStates) => ({\n ...prevAgentStates,\n [message.agentName]: {\n name: message.agentName,\n state: message.state,\n running: message.running,\n active: message.active,\n threadId: message.threadId,\n nodeName: message.nodeName,\n runId: message.runId,\n },\n }));\n setAgentSession({\n threadId: message.threadId,\n agentName: message.agentName,\n nodeName: message.nodeName,\n });\n } else {\n setAgentSession(null);\n }\n }\n // execute regular action executions\n if (\n message instanceof ActionExecutionMessage &&\n message.status.code !== MessageStatusCode.Pending &&\n message.scope === \"client\" &&\n onFunctionCall\n ) {\n if (!(message.id in actionResults)) {\n // Do not execute a function call if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute action\n const result = await onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n });\n actionResults[message.id] = result;\n }\n // add the result message\n newMessages.push(\n new ResultMessage({\n result: ResultMessage.encodeResult(actionResults[message.id]),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n // execute coagent actions\n if (\n message instanceof AgentStateMessage &&\n !message.active &&\n !executedCoagentActions.includes(message.id) &&\n onCoagentAction\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 onCoagentAction({\n name: message.agentName,\n nodeName: message.nodeName,\n state: message.state,\n });\n executedCoagentActions.push(message.id);\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Update message state\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n\n if (\n // if we have client side results\n Object.values(actionResults).length ||\n // or the last message we received is a result\n (newMessages.length && newMessages[newMessages.length - 1] instanceof ResultMessage)\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 runChatCompletion([...previousMessages, ...newMessages]);\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletion(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (isLoading) {\n return;\n }\n\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = 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 instanceof TextMessage && lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n"],"mappings":";;;;;;;AAAA,SAAS,cAAc;AACvB;AAAA,EAEE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAkGA,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,EACF,IAAI;AAEJ,QAAM,qBAAqB,OAAwB;AACnD,QAAM,cAAc,OAAsB,IAAI;AAC9C,QAAM,WAAW,OAAsB,IAAI;AAE3C,QAAM,eAAe,cAAc;AAEnC,QAAM,UAAU,kCACV,cAAc,WAAW,CAAC,IAC1B,eAAe,EAAE,CAAC,mCAAmC,GAAG,aAAa,IAAI,CAAC;AAGhF,QAAM,gBAAgB,IAAI,qBAAqB;AAAA,IAC7C,KAAK,cAAc;AAAA,IACnB,cAAc,cAAc;AAAA,IAC5B;AAAA,IACA,aAAa,cAAc;AAAA,EAC7B,CAAC;AAED,QAAM,oBAAoB,CAAO,qBAAoD;AA5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opilotKitProps {
63
63
  * If set to "auto", the dev console will be show on localhost only.
64
64
  */
65
65
  showDevConsole?: boolean | "auto";
66
+ /**
67
+ * The name of the agent to use.
68
+ */
69
+ agent?: string;
66
70
  }
67
71
 
68
72
  export { CopilotKitProps };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/components/copilot-provider/copilotkit-props.tsx"],"sourcesContent":["import { ReactNode } from \"react\";\n\n/**\n * Props for CopilotKit.\n */\n\nexport interface CopilotKitProps {\n /**\n * Your Copilot Cloud API key. Don't have it yet? <LinkToCopilotCloud>Click here to sign up for free</LinkToCopilotCloud>.\n */\n publicApiKey?: string;\n\n /**\n * Restrict input to a specific topic.\n */\n cloudRestrictToTopic?: {\n validTopics?: string[];\n invalidTopics?: string[];\n };\n\n /**\n * The endpoint for the Copilot Runtime instance. [Click here for more information](/concepts/copilot-runtime).\n */\n runtimeUrl?: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * Additional headers to be sent with the request.\n *\n * For example:\n * ```json\n * {\n * \"Authorization\": \"Bearer X\"\n * }\n * ```\n */\n headers?: Record<string, string>;\n\n /**\n * The children to be rendered within the CopilotKit.\n */\n children: ReactNode;\n\n /**\n * Custom properties to be sent with the request\n * For example:\n * ```js\n * {\n * 'user_id': 'users_id',\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n\n /**\n * Whether to show the dev console.\n *\n * If set to \"auto\", the dev console will be show on localhost only.\n */\n showDevConsole?: boolean | \"auto\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
1
+ {"version":3,"sources":["../../../src/components/copilot-provider/copilotkit-props.tsx"],"sourcesContent":["import { ReactNode } from \"react\";\n\n/**\n * Props for CopilotKit.\n */\n\nexport interface CopilotKitProps {\n /**\n * Your Copilot Cloud API key. Don't have it yet? <LinkToCopilotCloud>Click here to sign up for free</LinkToCopilotCloud>.\n */\n publicApiKey?: string;\n\n /**\n * Restrict input to a specific topic.\n */\n cloudRestrictToTopic?: {\n validTopics?: string[];\n invalidTopics?: string[];\n };\n\n /**\n * The endpoint for the Copilot Runtime instance. [Click here for more information](/concepts/copilot-runtime).\n */\n runtimeUrl?: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * Additional headers to be sent with the request.\n *\n * For example:\n * ```json\n * {\n * \"Authorization\": \"Bearer X\"\n * }\n * ```\n */\n headers?: Record<string, string>;\n\n /**\n * The children to be rendered within the CopilotKit.\n */\n children: ReactNode;\n\n /**\n * Custom properties to be sent with the request\n * For example:\n * ```js\n * {\n * 'user_id': 'users_id',\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n\n /**\n * Whether to show the dev console.\n *\n * If set to \"auto\", the dev console will be show on localhost only.\n */\n showDevConsole?: boolean | \"auto\";\n\n /**\n * The name of the agent to use.\n */\n agent?: string;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
@@ -1,7 +1,8 @@
1
1
  import { CopilotKitProps } from './copilotkit-props.js';
2
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
3
  import 'react';
3
4
 
4
- declare function CopilotKit({ children, ...props }: CopilotKitProps): JSX.Element;
5
+ declare function CopilotKit({ children, ...props }: CopilotKitProps): react_jsx_runtime.JSX.Element;
5
6
  declare const defaultCopilotContextCategories: string[];
6
7
 
7
8
  export { CopilotKit, defaultCopilotContextCategories };
@@ -94,7 +94,12 @@ var emptyCopilotContext = {
94
94
  },
95
95
  removeAction: () => {
96
96
  },
97
- chatComponentsCache: { current: {} },
97
+ coagentActions: {},
98
+ setCoagentAction: () => {
99
+ },
100
+ removeCoagentAction: () => {
101
+ },
102
+ chatComponentsCache: { current: { actions: {}, coagentActions: {} } },
98
103
  getContextString: (documents, categories) => returnAndThrowInDebug(""),
99
104
  addContext: () => "",
100
105
  removeContext: () => {
@@ -127,7 +132,13 @@ var emptyCopilotContext = {
127
132
  },
128
133
  removeChatSuggestionConfiguration: () => {
129
134
  },
130
- showDevConsole: "auto"
135
+ showDevConsole: "auto",
136
+ coagentStates: {},
137
+ setCoagentStates: () => {
138
+ },
139
+ agentSession: null,
140
+ setAgentSession: () => {
141
+ }
131
142
  };
132
143
  var CopilotContext = import_react.default.createContext(emptyCopilotContext);
133
144
  function returnAndThrowInDebug(value) {
@@ -348,7 +359,11 @@ function CopilotKit(_a) {
348
359
  }
349
360
  const chatApiEndpoint = props.runtimeUrl || import_shared3.COPILOT_CLOUD_CHAT_URL;
350
361
  const [actions, setActions] = (0, import_react4.useState)({});
351
- const chatComponentsCache = (0, import_react4.useRef)({});
362
+ const [coagentActions, setCoagentActions] = (0, import_react4.useState)({});
363
+ const chatComponentsCache = (0, import_react4.useRef)({
364
+ actions: {},
365
+ coagentActions: {}
366
+ });
352
367
  const { addElement, removeElement, printTree } = use_tree_default();
353
368
  const [messages, setMessages] = (0, import_react4.useState)([]);
354
369
  const [isLoading, setIsLoading] = (0, import_react4.useState)(false);
@@ -372,6 +387,20 @@ function CopilotKit(_a) {
372
387
  return newPoints;
373
388
  });
374
389
  }, []);
390
+ const setCoagentAction = (0, import_react4.useCallback)((id, action) => {
391
+ setCoagentActions((prevPoints) => {
392
+ return __spreadProps(__spreadValues({}, prevPoints), {
393
+ [id]: action
394
+ });
395
+ });
396
+ }, []);
397
+ const removeCoagentAction = (0, import_react4.useCallback)((id) => {
398
+ setCoagentActions((prevPoints) => {
399
+ const newPoints = __spreadValues({}, prevPoints);
400
+ delete newPoints[id];
401
+ return newPoints;
402
+ });
403
+ }, []);
375
404
  const getContextString = (0, import_react4.useCallback)(
376
405
  (documents, categories) => {
377
406
  const documentsString = documents.map((document) => {
@@ -462,6 +491,14 @@ ${nonDocumentStrings}`;
462
491
  return rest;
463
492
  });
464
493
  };
494
+ const [coagentStates, setCoagentStates] = (0, import_react4.useState)({});
495
+ let initialAgentSession = null;
496
+ if (props.agent) {
497
+ initialAgentSession = {
498
+ agentName: props.agent
499
+ };
500
+ }
501
+ const [agentSession, setAgentSession] = (0, import_react4.useState)(initialAgentSession);
465
502
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
466
503
  CopilotContext.Provider,
467
504
  {
@@ -471,6 +508,9 @@ ${nonDocumentStrings}`;
471
508
  getFunctionCallHandler,
472
509
  setAction,
473
510
  removeAction,
511
+ coagentActions,
512
+ setCoagentAction,
513
+ removeCoagentAction,
474
514
  getContextString,
475
515
  addContext,
476
516
  removeContext,
@@ -487,7 +527,11 @@ ${nonDocumentStrings}`;
487
527
  removeChatSuggestionConfiguration,
488
528
  chatInstructions,
489
529
  setChatInstructions,
490
- showDevConsole: props.showDevConsole === void 0 ? "auto" : props.showDevConsole
530
+ showDevConsole: props.showDevConsole === void 0 ? "auto" : props.showDevConsole,
531
+ coagentStates,
532
+ setCoagentStates,
533
+ agentSession,
534
+ setAgentSession
491
535
  },
492
536
  children
493
537
  }
@@ -505,8 +549,9 @@ function entryPointsToFunctionCallHandler(actions) {
505
549
  if (action) {
506
550
  yield new Promise((resolve, reject) => {
507
551
  (0, import_react_dom.flushSync)(() => __async(this, null, function* () {
552
+ var _a;
508
553
  try {
509
- result = yield action.handler(args);
554
+ result = yield (_a = action.handler) == null ? void 0 : _a.call(action, args);
510
555
  resolve();
511
556
  } catch (error) {
512
557
  reject(error);