@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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # ui
2
2
 
3
+ ## 1.1.3-feat-runtime-remote-actions.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Reduce request size by skipping intermediate state
8
+ - Updated dependencies
9
+ - @copilotkit/runtime-client-gql@1.1.3-feat-runtime-remote-actions.1
10
+ - @copilotkit/shared@1.1.3-feat-runtime-remote-actions.1
11
+
12
+ ## 1.1.3-feat-runtime-remote-actions.0
13
+
14
+ ### Patch Changes
15
+
16
+ - 638d51d: appendMessage fix 1
17
+ - Rename hooks and bugfixes
18
+ - faccbe1: state-abuse resistance for useCopilotChat
19
+ - b0cf700: remove unnecessary logging
20
+ - Updated dependencies [638d51d]
21
+ - Updated dependencies
22
+ - Updated dependencies [faccbe1]
23
+ - Updated dependencies [b0cf700]
24
+ - @copilotkit/runtime-client-gql@1.1.3-feat-runtime-remote-actions.0
25
+ - @copilotkit/shared@1.1.3-feat-runtime-remote-actions.0
26
+
3
27
  ## 1.1.2
4
28
 
5
29
  ### Patch Changes
package/README.md CHANGED
@@ -1,50 +1,45 @@
1
1
  <div align="center">
2
- <picture>
3
- <source media="(prefers-color-scheme: dark)" srcset="https://github.com/CopilotKit/CopilotKit/assets/746397/5890217b-524e-49c5-a89e-b8743d2acd51">
4
- <img alt="CopilotKit Logo" src="https://github.com/CopilotKit/CopilotKit/assets/746397/bd5c9079-929b-4d55-bdc9-16d1c8181b71" width="450px" max-width="100%"/>
5
- </picture>
6
- </a>
7
- </div>
8
-
9
- <p align="center">
10
- <a href="https://discord.gg/6dffbvGU3D">
11
- <img src="https://dcbadge.vercel.app/api/server/6dffbvGU3D?compact=true&style=flat" alt="Discord">
12
- </a>
13
- <a href="https://github.com/CopilotKit/CopilotKit/actions/workflows/ci.yml">
14
- <img src="https://github.com/CopilotKit/CopilotKit/actions/workflows/ci.yml/badge.svg" alt="GitHub CI">
2
+ <a href="https://copilotkit.ai" target="_blank">
3
+ <img src="https://github.com/copilotkit/copilotkit/raw/main/assets/banner.png" alt="CopilotKit Logo">
15
4
  </a>
16
5
 
17
- <a href="https://www.npmjs.com/package/@copilotkit/react-core">
18
- <img src="https://img.shields.io/npm/v/@copilotkit/react-core" alt="NPM">
19
- <img src="https://img.shields.io/github/license/CopilotKit/CopilotKit" alt="MIT">
20
-
21
- </p>
6
+ <br/>
22
7
 
23
- <h1 align="center">
24
- The Open-Source Copilot Framework
25
- </h1>
8
+ <strong>
9
+ CopilotKit is the open-source framework for integrating powerful AI Copilots into any application. Easily implement custom AI Chatbots, AI Agents, AI Textareas, and more.
10
+ </strong>
11
+ </div>
26
12
 
27
- <h2 align="center">
28
- Build, deploy, and operate fully custom AI Copilots.
29
- </h2>
13
+ <br/>
30
14
 
31
- <h3 align="center">
32
- in-app AI chatbots, AI agents, and AI Textareas.
33
- </h3>
15
+ <div align="center">
16
+ <a href="https://www.npmjs.com/package/@copilotkit/react-core" target="_blank">
17
+ <img src="https://img.shields.io/npm/v/%40copilotkit%2Freact-core?logo=npm&logoColor=%23FFFFFF&label=Version&color=%236963ff" alt="NPM">
18
+ </a>
19
+ <img src="https://img.shields.io/github/license/copilotkit/copilotkit?color=%236963ff&label=License" alt="MIT">
20
+ <a href="https://discord.gg/6dffbvGU3D" target="_blank">
21
+ <img src="https://img.shields.io/discord/1122926057641742418?logo=discord&logoColor=%23FFFFFF&label=Discord&color=%236963ff" alt="Discord">
22
+ </a>
23
+ </div>
24
+ <br/>
34
25
 
35
- <p align="center">
36
- <a href="https://discord.com/invite/6dffbvGU3D">
37
- <img src="https://github.com/CopilotKit/CopilotKit/assets/131273140/bf8d96ea-3aeb-4c9a-9043-96a868b7ad0f" alt="Join our Discord" height="30">
26
+ <div align="center">
27
+ <a href="https://discord.gg/6dffbvGU3D?ref=github_readme" target="_blank">
28
+ <img src="https://github.com/copilotkit/copilotkit/raw/main/assets/btn_discord.png" alt="CopilotKit Discord" height="40px">
38
29
  </a>
39
- &nbsp;&middot;&nbsp;
40
- <a href="https://docs.copilotkit.ai/getting-started/quickstart-chatbot">
41
- <img src="https://github.com/CopilotKit/CopilotKit/assets/131273140/a4a0fd04-6aee-4e02-9c3e-3f11d60b4e8b" alt="Read the Docs" height="30">
30
+ <a href="https://docs.copilotkit.ai?ref=github_readme" target="_blank">
31
+ <img src="https://github.com/copilotkit/copilotkit/raw/main/assets/btn_docs.png" alt="CopilotKit GitHub" height="40px">
42
32
  </a>
43
- &nbsp;&middot;&nbsp;
44
- <a href="https://cloud.copilotkit.ai">
45
- <img src="https://github.com/CopilotKit/CopilotKit/assets/131273140/28ca62a8-cf93-4d3f-96b0-dc11bf89b734" alt="Try Copilot Cloud" height="30">
33
+ <a href="https://cloud.copilotkit.ai?ref=github_readme" target="_blank">
34
+ <img src="https://github.com/copilotkit/copilotkit/raw/main/assets/btn_cloud.png" alt="CopilotKit GitHub" height="40px">
46
35
  </a>
47
- </p>
36
+ </div>
37
+
38
+ <br />
39
+
40
+ <div align="center">
41
+ <img src="https://github.com/CopilotKit/CopilotKit/raw/main/assets/animated-banner.gif" alt="CopilotKit Screenshot" style="border-radius: 15px;" />
42
+ </div>
48
43
 
49
44
  # Documentation
50
45
 
@@ -1,11 +1,11 @@
1
1
  import {
2
- CopilotContext
3
- } from "./chunk-3NHEWJ4V.mjs";
2
+ useCopilotContext
3
+ } from "./chunk-J2YXDQHR.mjs";
4
4
 
5
5
  // src/hooks/use-make-copilot-document-readable.ts
6
- import { useContext, useEffect, useRef } from "react";
6
+ import { useEffect, useRef } from "react";
7
7
  function useMakeCopilotDocumentReadable(document, categories, dependencies = []) {
8
- const { addDocumentContext, removeDocumentContext } = useContext(CopilotContext);
8
+ const { addDocumentContext, removeDocumentContext } = useCopilotContext();
9
9
  const idRef = useRef();
10
10
  useEffect(() => {
11
11
  const id = addDocumentContext(document, categories);
@@ -20,4 +20,4 @@ function useMakeCopilotDocumentReadable(document, categories, dependencies = [])
20
20
  export {
21
21
  useMakeCopilotDocumentReadable
22
22
  };
23
- //# sourceMappingURL=chunk-T6L4EGTD.mjs.map
23
+ //# sourceMappingURL=chunk-326LK7LX.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-make-copilot-document-readable.ts"],"sourcesContent":["import { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Makes a document readable by Copilot.\n * @param document The document to make readable.\n * @param categories The categories to associate with the document.\n * @param dependencies The dependencies to use for the effect.\n * @returns The id of the document.\n */\nexport function useMakeCopilotDocumentReadable(\n document: DocumentPointer,\n categories?: string[],\n dependencies: any[] = [],\n): string | undefined {\n const { addDocumentContext, removeDocumentContext } = useCopilotContext();\n const idRef = useRef<string>();\n\n useEffect(() => {\n const id = addDocumentContext(document, categories);\n idRef.current = id;\n\n return () => {\n removeDocumentContext(id);\n };\n }, [addDocumentContext, removeDocumentContext, ...dependencies]);\n\n return idRef.current;\n}\n"],"mappings":";;;;;AAAA,SAAS,WAAW,cAAc;AAW3B,SAAS,+BACd,UACA,YACA,eAAsB,CAAC,GACH;AACpB,QAAM,EAAE,oBAAoB,sBAAsB,IAAI,kBAAkB;AACxE,QAAM,QAAQ,OAAe;AAE7B,YAAU,MAAM;AACd,UAAM,KAAK,mBAAmB,UAAU,UAAU;AAClD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,4BAAsB,EAAE;AAAA,IAC1B;AAAA,EACF,GAAG,CAAC,oBAAoB,uBAAuB,GAAG,YAAY,CAAC;AAE/D,SAAO,MAAM;AACf;","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
  } from "./chunk-SKC7AJIV.mjs";
@@ -13,6 +13,7 @@ import {
13
13
  TextMessage,
14
14
  convertGqlOutputToMessages,
15
15
  convertMessagesToGqlInput,
16
+ filterAgentStateMessages,
16
17
  CopilotRequestType
17
18
  } from "@copilotkit/runtime-client-gql";
18
19
  import { actionParametersToJsonSchema } from "@copilotkit/shared";
@@ -60,9 +61,10 @@ var CopilotTask = class {
60
61
  name: action.name,
61
62
  description: action.description || "",
62
63
  jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || []))
63
- }))
64
+ })),
65
+ url: window.location.href
64
66
  },
65
- messages: convertMessagesToGqlInput(messages),
67
+ messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),
66
68
  metadata: {
67
69
  requestType: CopilotRequestType.Task
68
70
  },
@@ -115,4 +117,4 @@ ${instructions}
115
117
  export {
116
118
  CopilotTask
117
119
  };
118
- //# sourceMappingURL=chunk-GE7LAL6V.mjs.map
120
+ //# sourceMappingURL=chunk-3U22BXKC.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/copilot-task.ts"],"sourcesContent":["/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n *\n * implementation: async (message) => {\n * // ...\n * },\n * }\n * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n} from \"@copilotkit/runtime-client-gql\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { MessageStatusCode } from \"@copilotkit/runtime-client-gql\";\nimport { actionParametersToJsonSchema } from \"@copilotkit/shared\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions = config.includeCopilotActions !== false;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: Object.values(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 messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n toolChoice: \"required\",\n },\n },\n properties: context.copilotApiConfig.properties,\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m instanceof ActionExecutionMessage);\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\n }\n }\n}\n\nfunction taskSystemMessage(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 functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n"],"mappings":";;;;;;;;AAoDA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKP,SAAS,oCAAoC;AAsBtC,IAAM,cAAN,MAA2B;AAAA,EAMhC,YAAY,QAA2B;AACrC,SAAK,eAAe,OAAO;AAC3B,SAAK,UAAU,OAAO,WAAW,CAAC;AAClC,SAAK,yBAAyB,OAAO,2BAA2B;AAChE,SAAK,wBAAwB,OAAO,0BAA0B;AAAA,EAChE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOM,IAAI,SAA+B,MAAyB;AAAA;AA3GpE;AA4GI,YAAM,UAAU,KAAK,wBAAwB,OAAO,OAAO,CAAC,GAAG,QAAQ,OAAO,IAAI,CAAC;AAGnF,iBAAW,MAAM,KAAK,SAAS;AAC7B,gBAAQ,GAAG,IAAI,IAAI;AAAA,MACrB;AAEA,UAAI,gBAAgB;AAEpB,UAAI,MAAM;AACR,yBAAiB,OAAO,SAAS,WAAW,OAAO,KAAK,UAAU,IAAI,KAAK;AAAA,MAC7E;AAEA,UAAI,KAAK,wBAAwB;AAC/B,yBAAiB,QAAQ,iBAAiB,CAAC,GAAG,+BAA+B;AAAA,MAC/E;AAEA,YAAM,gBAAgB,IAAI,YAAY;AAAA,QACpC,SAAS,kBAAkB,eAAe,KAAK,YAAY;AAAA,QAC3D,MAAM,KAAK;AAAA,MACb,CAAC;AAED,YAAM,WAAsB,CAAC,aAAa;AAE1C,YAAM,gBAAgB,IAAI,qBAAqB;AAAA,QAC7C,KAAK,QAAQ,iBAAiB;AAAA,QAC9B,cAAc,QAAQ,iBAAiB;AAAA,QACvC,SAAS,QAAQ,iBAAiB;AAAA,QAClC,aAAa,QAAQ,iBAAiB;AAAA,MACxC,CAAC;AAED,YAAM,WAAW,MAAM,cACpB,wBAAwB;AAAA,QACvB,MAAM;AAAA,UACJ,UAAU;AAAA,YACR,SAAS,OAAO,OAAO,OAAO,EAAE,IAAI,CAAC,YAAY;AAAA,cAC/C,MAAM,OAAO;AAAA,cACb,aAAa,OAAO,eAAe;AAAA,cACnC,YAAY,KAAK,UAAU,6BAA6B,OAAO,cAAc,CAAC,CAAC,CAAC;AAAA,YAClF,EAAE;AAAA,YACF,KAAK,OAAO,SAAS;AAAA,UACvB;AAAA,UACA,UAAU,0BAA0B,yBAAyB,QAAQ,CAAC;AAAA,UACtE,UAAU;AAAA,YACR,aAAa,mBAAmB;AAAA,UAClC;AAAA,UACA,qBAAqB;AAAA,YACnB,YAAY;AAAA,UACd;AAAA,QACF;AAAA,QACA,YAAY,QAAQ,iBAAiB;AAAA,MACvC,CAAC,EACA,UAAU;AAEb,YAAM,sBAAsB,QAAQ,uBAAuB,OAAO;AAClE,YAAM,gBAAgB;AAAA,UACpB,oBAAS,SAAT,mBAAe,4BAAf,mBAAwC,aAAY,CAAC;AAAA,MACvD,EAAE,OAAO,CAAC,MAAmC,aAAa,sBAAsB;AAEhF,iBAAW,gBAAgB,eAAe;AACxC,cAAM,oBAAoB;AAAA,UACxB;AAAA,UACA,MAAM,aAAa;AAAA,UACnB,MAAM,aAAa;AAAA,QACrB,CAAC;AAAA,MACH;AAAA,IACF;AAAA;AACF;AAEA,SAAS,kBAAkB,eAAuB,cAA8B;AAC9E,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA;AAAA;AAAA;AAGF;","names":[]}
@@ -1,27 +1,30 @@
1
1
  import {
2
- CopilotContext
3
- } from "./chunk-3NHEWJ4V.mjs";
2
+ useCopilotContext
3
+ } from "./chunk-J2YXDQHR.mjs";
4
4
 
5
5
  // src/hooks/use-copilot-action.ts
6
- import { useRef, useContext, useEffect } from "react";
6
+ import { useRef, useEffect } from "react";
7
7
  import { randomId } from "@copilotkit/shared";
8
8
  function useCopilotAction(action, dependencies) {
9
- const { setAction, removeAction, actions, chatComponentsCache } = useContext(CopilotContext);
9
+ const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();
10
10
  const idRef = useRef(randomId());
11
11
  if (dependencies === void 0) {
12
12
  if (actions[idRef.current]) {
13
13
  actions[idRef.current].handler = action.handler;
14
14
  if (typeof action.render === "function") {
15
15
  if (chatComponentsCache.current !== null) {
16
- chatComponentsCache.current[action.name] = action.render;
16
+ chatComponentsCache.current.actions[action.name] = action.render;
17
17
  }
18
18
  }
19
19
  }
20
20
  }
21
21
  useEffect(() => {
22
+ if (action.disabled) {
23
+ return;
24
+ }
22
25
  setAction(idRef.current, action);
23
26
  if (chatComponentsCache.current !== null && action.render !== void 0) {
24
- chatComponentsCache.current[action.name] = action.render;
27
+ chatComponentsCache.current.actions[action.name] = action.render;
25
28
  }
26
29
  return () => {
27
30
  removeAction(idRef.current);
@@ -31,6 +34,7 @@ function useCopilotAction(action, dependencies) {
31
34
  removeAction,
32
35
  action.description,
33
36
  action.name,
37
+ action.disabled,
34
38
  // This should be faster than deep equality checking
35
39
  // In addition, all major JS engines guarantee the order of object keys
36
40
  JSON.stringify(action.parameters),
@@ -44,4 +48,4 @@ function useCopilotAction(action, dependencies) {
44
48
  export {
45
49
  useCopilotAction
46
50
  };
47
- //# sourceMappingURL=chunk-VFDR4MIF.mjs.map
51
+ //# sourceMappingURL=chunk-A37GANOW.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-action.ts"],"sourcesContent":["import { useRef, useEffect } from \"react\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { Parameter, randomId } from \"@copilotkit/shared\";\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>,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();\n const idRef = useRef<string>(randomId());\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 actions[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.actions[action.name] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n if (action.disabled) {\n return;\n }\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.actions[action.name] = action.render;\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 removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n action.description,\n action.name,\n action.disabled,\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(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\n// Usage 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// useCopilotAction({\n// name: \"myAction\",\n// handler: () => {\n// console.log(\"No parameters provided.\");\n// },\n// });\n"],"mappings":";;;;;AAAA,SAAS,QAAQ,iBAAiB;AAGlC,SAAoB,gBAAgB;AAW7B,SAAS,iBACd,QACA,cACM;AACN,QAAM,EAAE,WAAW,cAAc,SAAS,oBAAoB,IAAI,kBAAkB;AACpF,QAAM,QAAQ,OAAe,SAAS,CAAC;AAKvC,MAAI,iBAAiB,QAAW;AAC9B,QAAI,QAAQ,MAAM,OAAO,GAAG;AAC1B,cAAQ,MAAM,OAAO,EAAE,UAAU,OAAO;AACxC,UAAI,OAAO,OAAO,WAAW,YAAY;AACvC,YAAI,oBAAoB,YAAY,MAAM;AACxC,8BAAoB,QAAQ,QAAQ,OAAO,IAAI,IAAI,OAAO;AAAA,QAC5D;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,YAAU,MAAM;AACd,QAAI,OAAO,UAAU;AACnB;AAAA,IACF;AACA,cAAU,MAAM,SAAS,MAAa;AACtC,QAAI,oBAAoB,YAAY,QAAQ,OAAO,WAAW,QAAW;AACvE,0BAAoB,QAAQ,QAAQ,OAAO,IAAI,IAAI,OAAO;AAAA,IAC5D;AACA,WAAO,MAAM;AAGX,mBAAa,MAAM,OAAO;AAAA,IAC5B;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA;AAAA;AAAA,IAGP,KAAK,UAAU,OAAO,UAAU;AAAA;AAAA,IAEhC,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":[]}
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=chunk-BWYAGPEF.mjs.map
@@ -1,14 +1,14 @@
1
1
  import {
2
- CopilotContext
3
- } from "./chunk-3NHEWJ4V.mjs";
2
+ useCopilotContext
3
+ } from "./chunk-J2YXDQHR.mjs";
4
4
 
5
5
  // src/hooks/use-copilot-readable.ts
6
- import { useContext, useEffect, useRef } from "react";
6
+ import { useEffect, useRef } from "react";
7
7
  function convertToJSON(description, value) {
8
8
  return `${description}: ${typeof value === "string" ? value : JSON.stringify(value)}`;
9
9
  }
10
10
  function useCopilotReadable({ description, value, parentId, categories, convert }, dependencies) {
11
- const { addContext, removeContext } = useContext(CopilotContext);
11
+ const { addContext, removeContext } = useCopilotContext();
12
12
  const idRef = useRef();
13
13
  convert = convert || convertToJSON;
14
14
  const information = convert(description, value);
@@ -25,4 +25,4 @@ function useCopilotReadable({ description, value, parentId, categories, convert
25
25
  export {
26
26
  useCopilotReadable
27
27
  };
28
- //# sourceMappingURL=chunk-KONDJRB4.mjs.map
28
+ //# sourceMappingURL=chunk-CODXG6KU.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-readable.ts"],"sourcesContent":["/**\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * In its most basic usage, useCopilotReadable accepts a single string argument\n * representing any piece of app state, making it available for the Copilot to use\n * as context when responding to user input.\n *\n * ```tsx\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const [employees, setEmployees] = useState([]);\n *\n * useCopilotReadable({\n * description: \"The list of employees\",\n * value: employees,\n * });\n * }\n * ```\n *\n * ### Nested Components\n *\n * Optionally, you can maintain the hierarchical structure of information by passing\n * `parentId`. This allows you to use `useCopilotReadable` in nested components:\n *\n * ```tsx /employeeContextId/1 {17,23}\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * function Employee(props: EmployeeProps) {\n * const { employeeName, workProfile, metadata } = props;\n *\n * // propagate any information to copilot\n * const employeeContextId = useCopilotReadable({\n * description: \"Employee name\",\n * value: employeeName\n * });\n *\n * // Pass a parentID to maintain a hierarchical structure.\n * // Especially useful with child React components, list elements, etc.\n * useCopilotReadable({\n * description: \"Work profile\",\n * value: workProfile.description(),\n * parentId: employeeContextId\n * });\n *\n * useCopilotReadable({\n * description: \"Employee metadata\",\n * value: metadata.description(),\n * parentId: employeeContextId\n * });\n *\n * return (\n * // Render as usual...\n * );\n * }\n * ```\n */\nimport { useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\n\n/**\n * Options for the useCopilotReadable hook.\n */\nexport interface UseCopilotReadableOptions {\n /**\n * The description of the information to be added to the Copilot context.\n */\n description: string;\n /**\n * The value to be added to the Copilot context. Object values are automatically stringified.\n */\n value: any;\n /**\n * The ID of the parent context, if any.\n */\n parentId?: string;\n /**\n * An array of categories to control which context are visible where. Particularly useful\n * with CopilotTextarea (see `useMakeAutosuggestionFunction`)\n */\n categories?: string[];\n\n /**\n * A custom conversion function to use to serialize the value to a string. If not provided, the value\n * will be serialized using `JSON.stringify`.\n */\n convert?: (description: string, value: any) => string;\n}\n\nfunction convertToJSON(description: string, value: any): string {\n return `${description}: ${typeof value === \"string\" ? value : JSON.stringify(value)}`;\n}\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n */\nexport function useCopilotReadable(\n { description, value, parentId, categories, convert }: UseCopilotReadableOptions,\n dependencies?: any[],\n): string | undefined {\n const { addContext, removeContext } = useCopilotContext();\n const idRef = useRef<string>();\n convert = convert || convertToJSON;\n\n const information = convert(description, value);\n\n useEffect(() => {\n const id = addContext(information, parentId, categories);\n idRef.current = id;\n\n return () => {\n removeContext(id);\n };\n }, [information, parentId, addContext, removeContext, ...(dependencies || [])]);\n\n return idRef.current;\n}\n"],"mappings":";;;;;AA+DA,SAAS,WAAW,cAAc;AAgClC,SAAS,cAAc,aAAqB,OAAoB;AAC9D,SAAO,GAAG,gBAAgB,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,KAAK;AACpF;AAKO,SAAS,mBACd,EAAE,aAAa,OAAO,UAAU,YAAY,QAAQ,GACpD,cACoB;AACpB,QAAM,EAAE,YAAY,cAAc,IAAI,kBAAkB;AACxD,QAAM,QAAQ,OAAe;AAC7B,YAAU,WAAW;AAErB,QAAM,cAAc,QAAQ,aAAa,KAAK;AAE9C,YAAU,MAAM;AACd,UAAM,KAAK,WAAW,aAAa,UAAU,UAAU;AACvD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,oBAAc,EAAE;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,aAAa,UAAU,YAAY,eAAe,GAAI,gBAAgB,CAAC,CAAE,CAAC;AAE9E,SAAO,MAAM;AACf;","names":[]}
@@ -1,20 +1,21 @@
1
1
  import {
2
2
  defaultCopilotContextCategories
3
- } from "./chunk-TVR5CJ6E.mjs";
3
+ } from "./chunk-RBNULK3U.mjs";
4
4
  import {
5
5
  useChat
6
- } from "./chunk-AGGKI26A.mjs";
6
+ } from "./chunk-XSZDVRPW.mjs";
7
7
  import {
8
- CopilotContext
9
- } from "./chunk-3NHEWJ4V.mjs";
8
+ useCopilotContext
9
+ } from "./chunk-J2YXDQHR.mjs";
10
10
  import {
11
+ __async,
11
12
  __objRest,
12
13
  __spreadProps,
13
14
  __spreadValues
14
15
  } from "./chunk-SKC7AJIV.mjs";
15
16
 
16
17
  // src/hooks/use-copilot-chat.ts
17
- import { useContext, useRef, useEffect, useCallback } from "react";
18
+ import { useRef, useEffect, useCallback } from "react";
18
19
  import { Role, TextMessage } from "@copilotkit/runtime-client-gql";
19
20
  function useCopilotChat(_a = {}) {
20
21
  var _b = _a, {
@@ -31,8 +32,13 @@ function useCopilotChat(_a = {}) {
31
32
  isLoading,
32
33
  setIsLoading,
33
34
  chatInstructions,
34
- actions
35
- } = useContext(CopilotContext);
35
+ actions,
36
+ coagentStates,
37
+ setCoagentStates,
38
+ coagentActions,
39
+ agentSession,
40
+ setAgentSession
41
+ } = useCopilotContext();
36
42
  const latestGetContextString = useUpdatedRef(getContextString);
37
43
  const deleteMessage = useCallback(
38
44
  (messageId) => {
@@ -48,24 +54,76 @@ function useCopilotChat(_a = {}) {
48
54
  role: Role.System
49
55
  });
50
56
  }, [getContextString, makeSystemMessage, chatInstructions]);
57
+ const onCoagentAction = useCallback(
58
+ (args) => __async(this, null, function* () {
59
+ var _a2;
60
+ const { name, nodeName, state } = args;
61
+ let action = Object.values(coagentActions).find(
62
+ (action2) => action2.name === name && action2.nodeName === nodeName
63
+ );
64
+ if (!action) {
65
+ action = Object.values(coagentActions).find(
66
+ (action2) => action2.name === name && !action2.nodeName
67
+ );
68
+ }
69
+ if (action) {
70
+ yield (_a2 = action.handler) == null ? void 0 : _a2.call(action, { state, nodeName });
71
+ }
72
+ }),
73
+ [coagentActions]
74
+ );
51
75
  const { append, reload, stop } = useChat(__spreadProps(__spreadValues({}, options), {
52
76
  actions: Object.values(actions),
53
77
  copilotConfig: copilotApiConfig,
54
78
  initialMessages: options.initialMessages || [],
55
79
  onFunctionCall: getFunctionCallHandler(),
80
+ onCoagentAction,
56
81
  messages,
57
82
  setMessages,
58
83
  makeSystemMessageCallback,
59
84
  isLoading,
60
- setIsLoading
85
+ setIsLoading,
86
+ coagentStates,
87
+ setCoagentStates,
88
+ agentSession,
89
+ setAgentSession
61
90
  }));
91
+ const latestAppend = useUpdatedRef(append);
92
+ const latestAppendFunc = useCallback(
93
+ (message) => {
94
+ return latestAppend.current(message);
95
+ },
96
+ [latestAppend]
97
+ );
98
+ const latestReload = useUpdatedRef(reload);
99
+ const latestReloadFunc = useCallback(() => {
100
+ return latestReload.current();
101
+ }, [latestReload]);
102
+ const latestStop = useUpdatedRef(stop);
103
+ const latestStopFunc = useCallback(() => {
104
+ return latestStop.current();
105
+ }, [latestStop]);
106
+ const latestDelete = useUpdatedRef(deleteMessage);
107
+ const latestDeleteFunc = useCallback(
108
+ (messageId) => {
109
+ return latestDelete.current(messageId);
110
+ },
111
+ [latestDelete]
112
+ );
113
+ const latestSetMessages = useUpdatedRef(setMessages);
114
+ const latestSetMessagesFunc = useCallback(
115
+ (messages2) => {
116
+ return latestSetMessages.current(messages2);
117
+ },
118
+ [latestSetMessages]
119
+ );
62
120
  return {
63
121
  visibleMessages: messages,
64
- appendMessage: append,
65
- setMessages,
66
- reloadMessages: reload,
67
- stopGeneration: stop,
68
- deleteMessage,
122
+ appendMessage: latestAppendFunc,
123
+ setMessages: latestSetMessagesFunc,
124
+ reloadMessages: latestReloadFunc,
125
+ stopGeneration: latestStopFunc,
126
+ deleteMessage: latestDeleteFunc,
69
127
  isLoading
70
128
  };
71
129
  }
@@ -104,4 +162,4 @@ export {
104
162
  useCopilotChat,
105
163
  defaultSystemMessage
106
164
  };
107
- //# sourceMappingURL=chunk-YYZNR3CS.mjs.map
165
+ //# sourceMappingURL=chunk-HABY7NLH.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-chat.ts"],"sourcesContent":["/**\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChat } from \"@copilotkit/react-core\";\n * import { Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\n *\n * export function YourComponent() {\n * const { appendMessage } = useCopilotChat();\n *\n * appendMessage(\n * new TextMessage({\n * content: \"Hello World\",\n * role: Role.User,\n * }),\n * );\n * }\n * ```\n *\n * `useCopilotChat` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * visibleMessages, // An array of messages that are currently visible in the chat.\n * appendMessage, // A function to append a message to the chat.\n * setMessages, // A function to set the messages in the chat.\n * deleteMessage, // A function to delete a message from the chat.\n * reloadMessages, // A function to reload the messages from the API.\n * stopGeneration, // A function to stop the generation of the next message.\n * isLoading, // A boolean indicating if the chat is loading.\n * } = useCopilotChat();\n * ```\n */\nimport { useRef, useEffect, useCallback } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { MessageStatusCode } from \"@copilotkit/runtime-client-gql\";\nimport { CoagentActionHandlerArguments } from \"@copilotkit/shared\";\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n appendMessage: (message: Message) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: () => Promise<void>;\n stopGeneration: () => void;\n isLoading: boolean;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getFunctionCallHandler,\n copilotApiConfig,\n messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n\n coagentStates,\n setCoagentStates,\n coagentActions,\n agentSession,\n setAgentSession,\n } = useCopilotContext();\n\n // We need to ensure that makeSystemMessageCallback always uses the latest\n // useCopilotReadable data.\n const latestGetContextString = useUpdatedRef(getContextString);\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = latestGetContextString.current([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return new TextMessage({\n content: systemMessageMaker(contextString, chatInstructions),\n role: Role.System,\n });\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const onCoagentAction = useCallback(\n async (args: CoagentActionHandlerArguments) => {\n const { name, nodeName, state } = args;\n let action = Object.values(coagentActions).find(\n (action) => action.name === name && action.nodeName === nodeName,\n );\n if (!action) {\n action = Object.values(coagentActions).find(\n (action) => action.name === name && !action.nodeName,\n );\n }\n if (action) {\n await action.handler?.({ state, nodeName });\n }\n },\n [coagentActions],\n );\n\n const { append, reload, stop } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: options.initialMessages || [],\n onFunctionCall: getFunctionCallHandler(),\n onCoagentAction,\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n coagentStates,\n setCoagentStates,\n agentSession,\n setAgentSession,\n });\n\n // this is a workaround born out of a bug that Athena insessently ran into.\n // We could not find the origin of the bug, however, it was clear that an outdated version of the append function was being used somehow --\n // it referecned the old state of the messages array, and not the latest one.\n //\n // We want to make copilotkit as abuse-proof as possible, so we are adding this workaround to ensure that the latest version of the append function is always used.\n //\n // How does this work?\n // we store the relevant function in a ref that is always up-to-date, and then we use that ref in the callback.\n const latestAppend = useUpdatedRef(append);\n const latestAppendFunc = useCallback(\n (message: Message) => {\n return latestAppend.current(message);\n },\n [latestAppend],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useCallback(() => {\n return latestReload.current();\n }, [latestReload]);\n\n const latestStop = useUpdatedRef(stop);\n const latestStopFunc = useCallback(() => {\n return latestStop.current();\n }, [latestStop]);\n\n const latestDelete = useUpdatedRef(deleteMessage);\n const latestDeleteFunc = useCallback(\n (messageId: string) => {\n return latestDelete.current(messageId);\n },\n [latestDelete],\n );\n\n const latestSetMessages = useUpdatedRef(setMessages);\n const latestSetMessagesFunc = useCallback(\n (messages: Message[]) => {\n return latestSetMessages.current(messages);\n },\n [latestSetMessages],\n );\n\n return {\n visibleMessages: messages,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n deleteMessage: latestDeleteFunc,\n isLoading,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\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 functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwCA,SAAS,QAAQ,WAAW,mBAAmB;AAE/C,SAAkB,MAAM,mBAAmB;AAwCpC,SAAS,eAAe,KAGJ,CAAC,GAAyB;AAHtB,eAC7B;AAAA;AAAA,EAnFF,IAkF+B,IAE1B,oBAF0B,IAE1B;AAAA,IADH;AAAA;AAGA,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IAEA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,kBAAkB;AAItB,QAAM,yBAAyB,cAAc,gBAAgB;AAC7D,QAAM,gBAAgB;AAAA,IACpB,CAAC,cAAsB;AACrB,kBAAY,CAAC,SAAS,KAAK,OAAO,CAAC,YAAY,QAAQ,OAAO,SAAS,CAAC;AAAA,IAC1E;AAAA,IACA,CAAC,WAAW;AAAA,EACd;AAEA,QAAM,4BAA4B,YAAY,MAAM;AAClD,UAAM,qBAAqB,qBAAqB;AAEhD,UAAM,gBAAgB,uBAAuB,QAAQ,CAAC,GAAG,+BAA+B;AAExF,WAAO,IAAI,YAAY;AAAA,MACrB,SAAS,mBAAmB,eAAe,gBAAgB;AAAA,MAC3D,MAAM,KAAK;AAAA,IACb,CAAC;AAAA,EACH,GAAG,CAAC,kBAAkB,mBAAmB,gBAAgB,CAAC;AAE1D,QAAM,kBAAkB;AAAA,IACtB,CAAO,SAAwC;AA9HnD,UAAAA;AA+HM,YAAM,EAAE,MAAM,UAAU,MAAM,IAAI;AAClC,UAAI,SAAS,OAAO,OAAO,cAAc,EAAE;AAAA,QACzC,CAACC,YAAWA,QAAO,SAAS,QAAQA,QAAO,aAAa;AAAA,MAC1D;AACA,UAAI,CAAC,QAAQ;AACX,iBAAS,OAAO,OAAO,cAAc,EAAE;AAAA,UACrC,CAACA,YAAWA,QAAO,SAAS,QAAQ,CAACA,QAAO;AAAA,QAC9C;AAAA,MACF;AACA,UAAI,QAAQ;AACV,eAAMD,MAAA,OAAO,YAAP,gBAAAA,IAAA,aAAiB,EAAE,OAAO,SAAS;AAAA,MAC3C;AAAA,IACF;AAAA,IACA,CAAC,cAAc;AAAA,EACjB;AAEA,QAAM,EAAE,QAAQ,QAAQ,KAAK,IAAI,QAAQ,iCACpC,UADoC;AAAA,IAEvC,SAAS,OAAO,OAAO,OAAO;AAAA,IAC9B,eAAe;AAAA,IACf,iBAAiB,QAAQ,mBAAmB,CAAC;AAAA,IAC7C,gBAAgB,uBAAuB;AAAA,IACvC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAC;AAUD,QAAM,eAAe,cAAc,MAAM;AACzC,QAAM,mBAAmB;AAAA,IACvB,CAAC,YAAqB;AACpB,aAAO,aAAa,QAAQ,OAAO;AAAA,IACrC;AAAA,IACA,CAAC,YAAY;AAAA,EACf;AAEA,QAAM,eAAe,cAAc,MAAM;AACzC,QAAM,mBAAmB,YAAY,MAAM;AACzC,WAAO,aAAa,QAAQ;AAAA,EAC9B,GAAG,CAAC,YAAY,CAAC;AAEjB,QAAM,aAAa,cAAc,IAAI;AACrC,QAAM,iBAAiB,YAAY,MAAM;AACvC,WAAO,WAAW,QAAQ;AAAA,EAC5B,GAAG,CAAC,UAAU,CAAC;AAEf,QAAM,eAAe,cAAc,aAAa;AAChD,QAAM,mBAAmB;AAAA,IACvB,CAAC,cAAsB;AACrB,aAAO,aAAa,QAAQ,SAAS;AAAA,IACvC;AAAA,IACA,CAAC,YAAY;AAAA,EACf;AAEA,QAAM,oBAAoB,cAAc,WAAW;AACnD,QAAM,wBAAwB;AAAA,IAC5B,CAACE,cAAwB;AACvB,aAAO,kBAAkB,QAAQA,SAAQ;AAAA,IAC3C;AAAA,IACA,CAAC,iBAAiB;AAAA,EACpB;AAEA,SAAO;AAAA,IACL,iBAAiB;AAAA,IACjB,eAAe;AAAA,IACf,aAAa;AAAA,IACb,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,eAAe;AAAA,IACf;AAAA,EACF;AACF;AAIA,SAAS,cAAiB,OAAU;AAClC,QAAM,MAAM,OAAO,KAAK;AAExB,YAAU,MAAM;AACd,QAAI,UAAU;AAAA,EAChB,GAAG,CAAC,KAAK,CAAC;AAEV,SAAO;AACT;AAEO,SAAS,qBACd,eACA,wBACQ;AACR,SACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAUG,yBAAyB;AAAA;AAAA,EAAO,2BAA2B;AAEhE;","names":["_a","action","messages"]}
@@ -10,7 +10,12 @@ var emptyCopilotContext = {
10
10
  },
11
11
  removeAction: () => {
12
12
  },
13
- chatComponentsCache: { current: {} },
13
+ coagentActions: {},
14
+ setCoagentAction: () => {
15
+ },
16
+ removeCoagentAction: () => {
17
+ },
18
+ chatComponentsCache: { current: { actions: {}, coagentActions: {} } },
14
19
  getContextString: (documents, categories) => returnAndThrowInDebug(""),
15
20
  addContext: () => "",
16
21
  removeContext: () => {
@@ -43,11 +48,21 @@ var emptyCopilotContext = {
43
48
  },
44
49
  removeChatSuggestionConfiguration: () => {
45
50
  },
46
- showDevConsole: "auto"
51
+ showDevConsole: "auto",
52
+ coagentStates: {},
53
+ setCoagentStates: () => {
54
+ },
55
+ agentSession: null,
56
+ setAgentSession: () => {
57
+ }
47
58
  };
48
59
  var CopilotContext = React.createContext(emptyCopilotContext);
49
60
  function useCopilotContext() {
50
- return React.useContext(CopilotContext);
61
+ const context = React.useContext(CopilotContext);
62
+ if (context === emptyCopilotContext) {
63
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
64
+ }
65
+ return context;
51
66
  }
52
67
  function returnAndThrowInDebug(value) {
53
68
  throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
@@ -58,4 +73,4 @@ export {
58
73
  CopilotContext,
59
74
  useCopilotContext
60
75
  };
61
- //# sourceMappingURL=chunk-3NHEWJ4V.mjs.map
76
+ //# sourceMappingURL=chunk-J2YXDQHR.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context/copilot-context.tsx"],"sourcesContent":["import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport { CoagentAction, CoagentActionRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: 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 * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_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\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoagentActionRenderProps<any>,\n) => string | JSX.Element;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coagentActions: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // coagent actions\n coagentActions: Record<string, CoagentAction<any>>;\n setCoagentAction: (id: string, action: CoagentAction<any>) => void;\n removeCoagentAction: (id: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n // chat\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean | \"auto\";\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coagentActions: {},\n setCoagentAction: () => {},\n removeCoagentAction: () => {},\n\n chatComponentsCache: { current: { actions: {}, coagentActions: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n messages: [],\n setMessages: () => returnAndThrowInDebug([]),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: \"auto\",\n coagentStates: {},\n setCoagentStates: () => {},\n\n agentSession: null,\n setAgentSession: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n return value;\n}\n"],"mappings":";;;;;AAGA,OAAO,WAAW;AA2IlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,gBAAgB,CAAC;AAAA,EACjB,kBAAkB,MAAM;AAAA,EAAC;AAAA,EACzB,qBAAqB,MAAM;AAAA,EAAC;AAAA,EAE5B,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,gBAAgB,CAAC,EAAE,EAAE;AAAA,EACpE,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EAEtB,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,UAAU,CAAC;AAAA,EACX,aAAa,MAAM,sBAAsB,CAAC,CAAC;AAAA,EAE3C,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qBAAqB,MAAM,sBAAsB,EAAE;AAAA,EAEnD,qBAAqB,CAAC,eAAyB,sBAAsB,CAAC,CAAC;AAAA,EACvE,oBAAoB,MAAM,sBAAsB,EAAE;AAAA,EAClD,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAE9B,kBAAkB,IAAK,MAAkC;AAAA,IACvD,IAAI,kBAA0B;AAC5B,YAAM,IAAI,MAAM,uEAAuE;AAAA,IACzF;AAAA,IAEA,IAAI,UAAkC;AACpC,aAAO,CAAC;AAAA,IACV;AAAA,IACA,IAAI,OAA4B;AAC9B,aAAO,CAAC;AAAA,IACV;AAAA,EACF,EAAG;AAAA,EAEH,6BAA6B,CAAC;AAAA,EAC9B,gCAAgC,MAAM;AAAA,EAAC;AAAA,EACvC,mCAAmC,MAAM;AAAA,EAAC;AAAA,EAC1C,gBAAgB;AAAA,EAChB,eAAe,CAAC;AAAA,EAChB,kBAAkB,MAAM;AAAA,EAAC;AAAA,EAEzB,cAAc;AAAA,EACd,iBAAiB,MAAM;AAAA,EAAC;AAC1B;AAEO,IAAM,iBAAiB,MAAM,cAAoC,mBAAmB;AAEpF,SAAS,oBAA0C;AACxD,QAAM,UAAU,MAAM,WAAW,cAAc;AAC/C,MAAI,YAAY,qBAAqB;AACnC,UAAM,IAAI,MAAM,uEAAuE;AAAA,EACzF;AACA,SAAO;AACT;AAEA,SAAS,sBAAyB,OAAa;AAC7C,QAAM,IAAI,MAAM,uEAAuE;AACvF,SAAO;AACT;","names":[]}
@@ -0,0 +1,87 @@
1
+ import {
2
+ useCopilotContext
3
+ } from "./chunk-J2YXDQHR.mjs";
4
+ import {
5
+ __spreadProps,
6
+ __spreadValues
7
+ } from "./chunk-SKC7AJIV.mjs";
8
+
9
+ // src/hooks/use-coagent.ts
10
+ import { useEffect } from "react";
11
+ function useCoAgent(options) {
12
+ const isExternalStateManagement = (options2) => {
13
+ return "state" in options2 && "setState" in options2;
14
+ };
15
+ const { name } = options;
16
+ const isInternalStateManagementWithInitial = (options2) => {
17
+ return "initialState" in options2;
18
+ };
19
+ const { coagentStates, setCoagentStates } = useCopilotContext();
20
+ const getCoagentState = (coagentStates2, name2) => {
21
+ if (coagentStates2[name2]) {
22
+ return coagentStates2[name2];
23
+ } else {
24
+ return {
25
+ name: name2,
26
+ state: isInternalStateManagementWithInitial(options) ? options.initialState : {},
27
+ running: false,
28
+ active: false,
29
+ threadId: void 0,
30
+ nodeName: void 0,
31
+ runId: void 0
32
+ };
33
+ }
34
+ };
35
+ const setState = (newState) => {
36
+ setCoagentStates((prevAgentStates) => {
37
+ let coagentState2 = getCoagentState(prevAgentStates, name);
38
+ const updatedState = typeof newState === "function" ? newState(coagentState2.state) : newState;
39
+ return __spreadProps(__spreadValues({}, prevAgentStates), {
40
+ [name]: __spreadProps(__spreadValues({}, coagentState2), {
41
+ state: updatedState
42
+ })
43
+ });
44
+ });
45
+ };
46
+ const coagentState = getCoagentState(coagentStates, name);
47
+ const state = isExternalStateManagement(options) ? options.state : coagentState.state;
48
+ useEffect(() => {
49
+ if (isExternalStateManagement(options)) {
50
+ setState(options.state);
51
+ } else if (coagentStates[name] === void 0) {
52
+ setState(options.initialState === void 0 ? {} : options.initialState);
53
+ }
54
+ }, [isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0]);
55
+ return {
56
+ name,
57
+ nodeName: coagentState.nodeName,
58
+ state,
59
+ setState,
60
+ running: coagentState.running,
61
+ start: () => {
62
+ startAgent(name);
63
+ },
64
+ stop: () => {
65
+ stopAgent(name);
66
+ }
67
+ };
68
+ }
69
+ function startAgent(name) {
70
+ const { setAgentSession } = useCopilotContext();
71
+ setAgentSession({
72
+ agentName: name
73
+ });
74
+ }
75
+ function stopAgent(name) {
76
+ const { agentSession, setAgentSession } = useCopilotContext();
77
+ if (agentSession && agentSession.agentName === name) {
78
+ setAgentSession(null);
79
+ } else {
80
+ console.warn(`No agent session found for ${name}`);
81
+ }
82
+ }
83
+
84
+ export {
85
+ useCoAgent
86
+ };
87
+ //# sourceMappingURL=chunk-Q4TTTAXQ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-coagent.ts"],"sourcesContent":["import { useEffect } from \"react\";\nimport { useCopilotContext } from \"../context\";\nimport { CoagentState } from \"../types/coagent-state\";\n\ninterface WithInternalStateManagementAndInitial<T> {\n name: string;\n initialState: T;\n}\n\ninterface WithInternalStateManagement {\n name: string;\n initialState?: any; // Optional initialState with default type any\n}\n\ninterface WithExternalStateManagement<T> {\n name: string;\n state: T;\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n name: string;\n nodeName?: string;\n threadId?: string;\n running: boolean;\n state: T;\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n start: () => void;\n stop: () => void;\n}\n\nexport function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {\n const isExternalStateManagement = (\n options: UseCoagentOptions<T>,\n ): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n };\n\n const { name } = options;\n\n const isInternalStateManagementWithInitial = (\n options: UseCoagentOptions<T>,\n ): options is WithInternalStateManagementAndInitial<T> => {\n return \"initialState\" in options;\n };\n\n const { coagentStates, setCoagentStates } = useCopilotContext();\n\n const getCoagentState = (coagentStates: Record<string, CoagentState>, name: string) => {\n if (coagentStates[name]) {\n return coagentStates[name];\n } else {\n return {\n name,\n state: isInternalStateManagementWithInitial(options) ? options.initialState : {},\n running: false,\n active: false,\n threadId: undefined,\n nodeName: undefined,\n runId: undefined,\n };\n }\n };\n\n // if we manage state internally, we need to provide a function to set the state\n const setState = (newState: T | ((prevState: T | undefined) => T)) => {\n setCoagentStates((prevAgentStates) => {\n let coagentState: CoagentState = getCoagentState(prevAgentStates, name);\n\n const updatedState =\n typeof newState === \"function\" ? (newState as Function)(coagentState.state) : newState;\n\n return {\n ...prevAgentStates,\n [name]: {\n ...coagentState,\n state: updatedState,\n },\n };\n });\n };\n\n const coagentState = getCoagentState(coagentStates, name);\n\n const state = isExternalStateManagement(options) ? options.state : coagentState.state;\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n setState(options.state);\n } else if (coagentStates[name] === undefined) {\n setState(options.initialState === undefined ? {} : options.initialState);\n }\n }, [isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined]);\n\n // Return the state and setState function\n return {\n name,\n nodeName: coagentState.nodeName,\n state,\n setState,\n running: coagentState.running,\n start: () => {\n startAgent(name);\n },\n stop: () => {\n stopAgent(name);\n },\n };\n}\n\nfunction startAgent(name: string) {\n const { setAgentSession } = useCopilotContext();\n setAgentSession({\n agentName: name,\n });\n}\n\nfunction stopAgent(name: string) {\n const { agentSession, setAgentSession } = useCopilotContext();\n if (agentSession && agentSession.agentName === name) {\n setAgentSession(null);\n } else {\n console.warn(`No agent session found for ${name}`);\n }\n}\n\n// <CopilotKit agent=\"lockedInAgentName\" />\n"],"mappings":";;;;;;;;;AAAA,SAAS,iBAAiB;AAoCnB,SAAS,WAAoB,SAAwD;AAC1F,QAAM,4BAA4B,CAChCA,aAC8C;AAC9C,WAAO,WAAWA,YAAW,cAAcA;AAAA,EAC7C;AAEA,QAAM,EAAE,KAAK,IAAI;AAEjB,QAAM,uCAAuC,CAC3CA,aACwD;AACxD,WAAO,kBAAkBA;AAAA,EAC3B;AAEA,QAAM,EAAE,eAAe,iBAAiB,IAAI,kBAAkB;AAE9D,QAAM,kBAAkB,CAACC,gBAA6CC,UAAiB;AACrF,QAAID,eAAcC,KAAI,GAAG;AACvB,aAAOD,eAAcC,KAAI;AAAA,IAC3B,OAAO;AACL,aAAO;AAAA,QACL,MAAAA;AAAA,QACA,OAAO,qCAAqC,OAAO,IAAI,QAAQ,eAAe,CAAC;AAAA,QAC/E,SAAS;AAAA,QACT,QAAQ;AAAA,QACR,UAAU;AAAA,QACV,UAAU;AAAA,QACV,OAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAGA,QAAM,WAAW,CAAC,aAAoD;AACpE,qBAAiB,CAAC,oBAAoB;AACpC,UAAIC,gBAA6B,gBAAgB,iBAAiB,IAAI;AAEtE,YAAM,eACJ,OAAO,aAAa,aAAc,SAAsBA,cAAa,KAAK,IAAI;AAEhF,aAAO,iCACF,kBADE;AAAA,QAEL,CAAC,IAAI,GAAG,iCACHA,gBADG;AAAA,UAEN,OAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,eAAe,gBAAgB,eAAe,IAAI;AAExD,QAAM,QAAQ,0BAA0B,OAAO,IAAI,QAAQ,QAAQ,aAAa;AAGhF,YAAU,MAAM;AACd,QAAI,0BAA0B,OAAO,GAAG;AACtC,eAAS,QAAQ,KAAK;AAAA,IACxB,WAAW,cAAc,IAAI,MAAM,QAAW;AAC5C,eAAS,QAAQ,iBAAiB,SAAY,CAAC,IAAI,QAAQ,YAAY;AAAA,IACzE;AAAA,EACF,GAAG,CAAC,0BAA0B,OAAO,IAAI,KAAK,UAAU,QAAQ,KAAK,IAAI,MAAS,CAAC;AAGnF,SAAO;AAAA,IACL;AAAA,IACA,UAAU,aAAa;AAAA,IACvB;AAAA,IACA;AAAA,IACA,SAAS,aAAa;AAAA,IACtB,OAAO,MAAM;AACX,iBAAW,IAAI;AAAA,IACjB;AAAA,IACA,MAAM,MAAM;AACV,gBAAU,IAAI;AAAA,IAChB;AAAA,EACF;AACF;AAEA,SAAS,WAAW,MAAc;AAChC,QAAM,EAAE,gBAAgB,IAAI,kBAAkB;AAC9C,kBAAgB;AAAA,IACd,WAAW;AAAA,EACb,CAAC;AACH;AAEA,SAAS,UAAU,MAAc;AAC/B,QAAM,EAAE,cAAc,gBAAgB,IAAI,kBAAkB;AAC5D,MAAI,gBAAgB,aAAa,cAAc,MAAM;AACnD,oBAAgB,IAAI;AAAA,EACtB,OAAO;AACL,YAAQ,KAAK,8BAA8B,MAAM;AAAA,EACnD;AACF;","names":["options","coagentStates","name","coagentState"]}