@copilotkit/react-core 1.5.1-next.2 → 1.5.1-next.3

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 (146) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/{chunk-LNI2Z45S.mjs → chunk-2KCEHGSI.mjs} +50 -100
  3. package/dist/chunk-2KCEHGSI.mjs.map +1 -0
  4. package/dist/{chunk-2KT73RVG.mjs → chunk-6OR25P32.mjs} +19 -75
  5. package/dist/chunk-6OR25P32.mjs.map +1 -0
  6. package/dist/{chunk-3GQPEN4M.mjs → chunk-DDVXFNYA.mjs} +32 -66
  7. package/dist/chunk-DDVXFNYA.mjs.map +1 -0
  8. package/dist/{chunk-XOQMISG3.mjs → chunk-FXHKK52V.mjs} +13 -14
  9. package/dist/chunk-FXHKK52V.mjs.map +1 -0
  10. package/dist/{chunk-HIUT2NLX.mjs → chunk-H4VZMKR6.mjs} +2 -2
  11. package/dist/{chunk-X36DNILG.mjs → chunk-H7LSKIDK.mjs} +23 -71
  12. package/dist/chunk-H7LSKIDK.mjs.map +1 -0
  13. package/dist/chunk-JDQCJCAQ.mjs +295 -0
  14. package/dist/chunk-JDQCJCAQ.mjs.map +1 -0
  15. package/dist/chunk-L34MHAXR.mjs +1 -0
  16. package/dist/{chunk-WXREY7UP.mjs → chunk-LODRWFMB.mjs} +4 -16
  17. package/dist/chunk-LODRWFMB.mjs.map +1 -0
  18. package/dist/{chunk-EWKJMQOF.mjs → chunk-MWZO6TUR.mjs} +13 -29
  19. package/dist/chunk-MWZO6TUR.mjs.map +1 -0
  20. package/dist/{chunk-6BQVZFNO.mjs → chunk-ODN4H66E.mjs} +2 -6
  21. package/dist/chunk-ODN4H66E.mjs.map +1 -0
  22. package/dist/{chunk-FQ53HQYZ.mjs → chunk-QDGDXRRJ.mjs} +2 -2
  23. package/dist/{chunk-22XKTBPF.mjs → chunk-XINZBP3J.mjs} +3 -15
  24. package/dist/chunk-XINZBP3J.mjs.map +1 -0
  25. package/dist/components/copilot-provider/copilot-messages.d.ts +0 -9
  26. package/dist/components/copilot-provider/copilotkit-props.d.ts +0 -21
  27. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  28. package/dist/components/copilot-provider/copilotkit.d.ts +0 -9
  29. package/dist/components/copilot-provider/copilotkit.js +95 -224
  30. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  31. package/dist/components/copilot-provider/copilotkit.mjs +8 -9
  32. package/dist/components/copilot-provider/index.d.ts +0 -9
  33. package/dist/components/copilot-provider/index.js +95 -224
  34. package/dist/components/copilot-provider/index.js.map +1 -1
  35. package/dist/components/copilot-provider/index.mjs +8 -9
  36. package/dist/components/index.d.ts +0 -9
  37. package/dist/components/index.js +95 -224
  38. package/dist/components/index.js.map +1 -1
  39. package/dist/components/index.mjs +8 -9
  40. package/dist/components/toast/toast-provider.d.ts +1 -2
  41. package/dist/components/toast/toast-provider.js +63 -77
  42. package/dist/components/toast/toast-provider.js.map +1 -1
  43. package/dist/components/toast/toast-provider.mjs +1 -1
  44. package/dist/context/copilot-context.d.ts +4 -37
  45. package/dist/context/copilot-context.js +3 -15
  46. package/dist/context/copilot-context.js.map +1 -1
  47. package/dist/context/copilot-context.mjs +1 -1
  48. package/dist/context/index.d.ts +1 -1
  49. package/dist/context/index.js +3 -15
  50. package/dist/context/index.js.map +1 -1
  51. package/dist/context/index.mjs +4 -4
  52. package/dist/hooks/index.d.ts +1 -3
  53. package/dist/hooks/index.js +297 -703
  54. package/dist/hooks/index.js.map +1 -1
  55. package/dist/hooks/index.mjs +23 -35
  56. package/dist/hooks/use-chat.d.ts +3 -35
  57. package/dist/hooks/use-chat.js +205 -453
  58. package/dist/hooks/use-chat.js.map +1 -1
  59. package/dist/hooks/use-chat.mjs +3 -4
  60. package/dist/hooks/use-coagent-state-render.d.ts +2 -2
  61. package/dist/hooks/use-coagent-state-render.js +8 -43
  62. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  63. package/dist/hooks/use-coagent-state-render.mjs +2 -4
  64. package/dist/hooks/use-coagent.d.ts +1 -14
  65. package/dist/hooks/use-coagent.js +265 -603
  66. package/dist/hooks/use-coagent.js.map +1 -1
  67. package/dist/hooks/use-coagent.mjs +12 -20
  68. package/dist/hooks/use-copilot-action.d.ts +2 -12
  69. package/dist/hooks/use-copilot-action.js +19 -169
  70. package/dist/hooks/use-copilot-action.js.map +1 -1
  71. package/dist/hooks/use-copilot-action.mjs +2 -4
  72. package/dist/hooks/use-copilot-chat.d.ts +0 -2
  73. package/dist/hooks/use-copilot-chat.js +240 -545
  74. package/dist/hooks/use-copilot-chat.js.map +1 -1
  75. package/dist/hooks/use-copilot-chat.mjs +11 -13
  76. package/dist/hooks/use-copilot-readable.js +3 -15
  77. package/dist/hooks/use-copilot-readable.js.map +1 -1
  78. package/dist/hooks/use-copilot-readable.mjs +2 -2
  79. package/dist/hooks/use-copilot-runtime-client.js +4 -110
  80. package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
  81. package/dist/hooks/use-copilot-runtime-client.mjs +2 -2
  82. package/dist/hooks/use-make-copilot-document-readable.js +3 -15
  83. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  84. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  85. package/dist/index.d.ts +3 -4
  86. package/dist/index.js +398 -812
  87. package/dist/index.js.map +1 -1
  88. package/dist/index.mjs +31 -43
  89. package/dist/lib/copilot-task.d.ts +1 -6
  90. package/dist/lib/copilot-task.js +17 -55
  91. package/dist/lib/copilot-task.js.map +1 -1
  92. package/dist/lib/copilot-task.mjs +9 -11
  93. package/dist/lib/index.d.ts +1 -1
  94. package/dist/lib/index.js +17 -55
  95. package/dist/lib/index.js.map +1 -1
  96. package/dist/lib/index.mjs +9 -11
  97. package/dist/types/frontend-action.d.ts +2 -21
  98. package/dist/types/frontend-action.js +0 -34
  99. package/dist/types/frontend-action.js.map +1 -1
  100. package/dist/types/frontend-action.mjs +0 -7
  101. package/dist/types/index.d.ts +1 -2
  102. package/dist/types/index.js.map +1 -1
  103. package/dist/utils/extract.d.ts +2 -3
  104. package/dist/utils/extract.js +3 -21
  105. package/dist/utils/extract.js.map +1 -1
  106. package/dist/utils/extract.mjs +8 -9
  107. package/dist/utils/index.js +3 -21
  108. package/dist/utils/index.js.map +1 -1
  109. package/dist/utils/index.mjs +9 -10
  110. package/package.json +5 -5
  111. package/dist/chunk-22XKTBPF.mjs.map +0 -1
  112. package/dist/chunk-2KT73RVG.mjs.map +0 -1
  113. package/dist/chunk-3GQPEN4M.mjs.map +0 -1
  114. package/dist/chunk-6BQVZFNO.mjs.map +0 -1
  115. package/dist/chunk-EWKJMQOF.mjs.map +0 -1
  116. package/dist/chunk-LHKIIAUQ.mjs +0 -59
  117. package/dist/chunk-LHKIIAUQ.mjs.map +0 -1
  118. package/dist/chunk-LNI2Z45S.mjs.map +0 -1
  119. package/dist/chunk-NR2BTA6Z.mjs +0 -1
  120. package/dist/chunk-VGOFRULA.mjs +0 -401
  121. package/dist/chunk-VGOFRULA.mjs.map +0 -1
  122. package/dist/chunk-VNTDIJSG.mjs +0 -37
  123. package/dist/chunk-VNTDIJSG.mjs.map +0 -1
  124. package/dist/chunk-WXREY7UP.mjs.map +0 -1
  125. package/dist/chunk-X36DNILG.mjs.map +0 -1
  126. package/dist/chunk-XERJQUHA.mjs +0 -31
  127. package/dist/chunk-XERJQUHA.mjs.map +0 -1
  128. package/dist/chunk-XOQMISG3.mjs.map +0 -1
  129. package/dist/components/error-boundary/error-boundary.d.ts +0 -22
  130. package/dist/components/error-boundary/error-boundary.js +0 -183
  131. package/dist/components/error-boundary/error-boundary.js.map +0 -1
  132. package/dist/components/error-boundary/error-boundary.mjs +0 -12
  133. package/dist/components/error-boundary/error-boundary.mjs.map +0 -1
  134. package/dist/components/error-boundary/error-utils.d.ts +0 -11
  135. package/dist/components/error-boundary/error-utils.js +0 -177
  136. package/dist/components/error-boundary/error-utils.js.map +0 -1
  137. package/dist/components/error-boundary/error-utils.mjs +0 -13
  138. package/dist/components/error-boundary/error-utils.mjs.map +0 -1
  139. package/dist/hooks/use-copilot-authenticated-action.d.ts +0 -8
  140. package/dist/hooks/use-copilot-authenticated-action.js +0 -418
  141. package/dist/hooks/use-copilot-authenticated-action.js.map +0 -1
  142. package/dist/hooks/use-copilot-authenticated-action.mjs +0 -12
  143. package/dist/hooks/use-copilot-authenticated-action.mjs.map +0 -1
  144. /package/dist/{chunk-HIUT2NLX.mjs.map → chunk-H4VZMKR6.mjs.map} +0 -0
  145. /package/dist/{chunk-NR2BTA6Z.mjs.map → chunk-L34MHAXR.mjs.map} +0 -0
  146. /package/dist/{chunk-FQ53HQYZ.mjs.map → chunk-QDGDXRRJ.mjs.map} +0 -0
package/dist/index.mjs CHANGED
@@ -1,62 +1,54 @@
1
1
  "use client";
2
2
  import "./chunk-EFZPSZWO.mjs";
3
- import "./chunk-LUGEI4YQ.mjs";
3
+ import "./chunk-L34MHAXR.mjs";
4
4
  import {
5
- CopilotTask
6
- } from "./chunk-XOQMISG3.mjs";
7
- import "./chunk-NR2BTA6Z.mjs";
5
+ useCopilotReadable
6
+ } from "./chunk-QDGDXRRJ.mjs";
8
7
  import {
9
- runAgent,
10
- startAgent,
11
- stopAgent,
12
- useCoAgent
13
- } from "./chunk-3GQPEN4M.mjs";
8
+ useMakeCopilotDocumentReadable
9
+ } from "./chunk-H4VZMKR6.mjs";
14
10
  import {
15
- useCopilotAuthenticatedAction
16
- } from "./chunk-LHKIIAUQ.mjs";
11
+ useCoAgentStateRender
12
+ } from "./chunk-XINZBP3J.mjs";
17
13
  import {
18
- useCopilotAction
19
- } from "./chunk-EWKJMQOF.mjs";
14
+ useCoAgent
15
+ } from "./chunk-DDVXFNYA.mjs";
20
16
  import {
21
17
  useCopilotChat
22
- } from "./chunk-X36DNILG.mjs";
18
+ } from "./chunk-H7LSKIDK.mjs";
19
+ import "./chunk-JDQCJCAQ.mjs";
23
20
  import {
24
- useCopilotReadable
25
- } from "./chunk-FQ53HQYZ.mjs";
21
+ useCopilotAction
22
+ } from "./chunk-MWZO6TUR.mjs";
23
+ import "./chunk-YPSGKPDA.mjs";
24
+ import "./chunk-LUGEI4YQ.mjs";
26
25
  import {
27
- useMakeCopilotDocumentReadable
28
- } from "./chunk-HIUT2NLX.mjs";
26
+ CopilotTask
27
+ } from "./chunk-FXHKK52V.mjs";
29
28
  import {
30
29
  CopilotKit,
31
30
  defaultCopilotContextCategories,
32
31
  extract
33
- } from "./chunk-2KT73RVG.mjs";
34
- import "./chunk-VNTDIJSG.mjs";
35
- import {
36
- shouldShowDevConsole
37
- } from "./chunk-MLAS4QUR.mjs";
38
- import "./chunk-XXR4QFAQ.mjs";
39
- import "./chunk-6U3UH3KO.mjs";
32
+ } from "./chunk-6OR25P32.mjs";
40
33
  import "./chunk-5FHSUKQL.mjs";
41
- import "./chunk-YPSGKPDA.mjs";
42
- import {
43
- CopilotMessagesContext,
44
- useCopilotMessagesContext
45
- } from "./chunk-DCTJZ742.mjs";
46
- import "./chunk-VGOFRULA.mjs";
47
- import "./chunk-XERJQUHA.mjs";
34
+ import "./chunk-6U3UH3KO.mjs";
35
+ import "./chunk-XXR4QFAQ.mjs";
48
36
  import {
49
37
  useCopilotRuntimeClient
50
- } from "./chunk-6BQVZFNO.mjs";
51
- import {
52
- useCoAgentStateRender
53
- } from "./chunk-22XKTBPF.mjs";
38
+ } from "./chunk-ODN4H66E.mjs";
39
+ import "./chunk-2KCEHGSI.mjs";
40
+ import "./chunk-O7ARI5CV.mjs";
54
41
  import {
55
42
  CopilotContext,
56
43
  useCopilotContext
57
- } from "./chunk-WXREY7UP.mjs";
58
- import "./chunk-LNI2Z45S.mjs";
59
- import "./chunk-O7ARI5CV.mjs";
44
+ } from "./chunk-LODRWFMB.mjs";
45
+ import {
46
+ CopilotMessagesContext,
47
+ useCopilotMessagesContext
48
+ } from "./chunk-DCTJZ742.mjs";
49
+ import {
50
+ shouldShowDevConsole
51
+ } from "./chunk-MLAS4QUR.mjs";
60
52
  import "./chunk-SKC7AJIV.mjs";
61
53
  export {
62
54
  CopilotContext,
@@ -65,14 +57,10 @@ export {
65
57
  CopilotTask,
66
58
  defaultCopilotContextCategories,
67
59
  extract,
68
- runAgent,
69
60
  shouldShowDevConsole,
70
- startAgent,
71
- stopAgent,
72
61
  useCoAgent,
73
62
  useCoAgentStateRender,
74
63
  useCopilotAction,
75
- useCopilotAuthenticatedAction,
76
64
  useCopilotChat,
77
65
  useCopilotContext,
78
66
  useCopilotMessagesContext,
@@ -1,4 +1,3 @@
1
- import { ForwardedParametersInput } from '@copilotkit/runtime-client-gql';
2
1
  import { FrontendAction } from '../types/frontend-action.js';
3
2
  import { CopilotContextParams } from '../context/copilot-context.js';
4
3
  import '@copilotkit/shared';
@@ -8,6 +7,7 @@ import '../types/document-pointer.js';
8
7
  import '../types/chat-suggestion-configuration.js';
9
8
  import '../types/coagent-action.js';
10
9
  import '../types/coagent-state.js';
10
+ import '@copilotkit/runtime-client-gql';
11
11
 
12
12
  /**
13
13
  * 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.
@@ -74,17 +74,12 @@ interface CopilotTaskConfig {
74
74
  * Whether to include actions defined via useCopilotAction in the task.
75
75
  */
76
76
  includeCopilotActions?: boolean;
77
- /**
78
- * The forwarded parameters to use for the task.
79
- */
80
- forwardedParameters?: ForwardedParametersInput;
81
77
  }
82
78
  declare class CopilotTask<T = any> {
83
79
  private instructions;
84
80
  private actions;
85
81
  private includeCopilotReadable;
86
82
  private includeCopilotActions;
87
- private forwardedParameters?;
88
83
  constructor(config: CopilotTaskConfig);
89
84
  /**
90
85
  * Run the task.
@@ -1,25 +1,8 @@
1
1
  "use strict";
2
2
  var __defProp = Object.defineProperty;
3
- var __defProps = Object.defineProperties;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
- var __spreadValues = (a, b) => {
12
- for (var prop in b || (b = {}))
13
- if (__hasOwnProp.call(b, prop))
14
- __defNormalProp(a, prop, b[prop]);
15
- if (__getOwnPropSymbols)
16
- for (var prop of __getOwnPropSymbols(b)) {
17
- if (__propIsEnum.call(b, prop))
18
- __defNormalProp(a, prop, b[prop]);
19
- }
20
- return a;
21
- };
22
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
6
  var __export = (target, all) => {
24
7
  for (var name in all)
25
8
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -60,48 +43,23 @@ __export(copilot_task_exports, {
60
43
  CopilotTask: () => CopilotTask
61
44
  });
62
45
  module.exports = __toCommonJS(copilot_task_exports);
63
- var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
64
-
65
- // src/types/frontend-action.ts
66
46
  var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
67
- var import_shared = require("@copilotkit/shared");
68
- function processActionsForRuntimeRequest(actions) {
69
- const filteredActions = actions.filter(
70
- (action) => action.available !== import_runtime_client_gql.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*"
71
- ).map((action) => {
72
- let available = import_runtime_client_gql.ActionInputAvailability.Enabled;
73
- if (action.disabled) {
74
- available = import_runtime_client_gql.ActionInputAvailability.Disabled;
75
- } else if (action.available === "disabled") {
76
- available = import_runtime_client_gql.ActionInputAvailability.Disabled;
77
- } else if (action.available === "remote") {
78
- available = import_runtime_client_gql.ActionInputAvailability.Remote;
79
- }
80
- return {
81
- name: action.name,
82
- description: action.description || "",
83
- jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || [])),
84
- available
85
- };
86
- });
87
- return filteredActions;
88
- }
89
47
 
90
48
  // src/components/copilot-provider/copilotkit.tsx
91
49
  var import_react = require("react");
92
50
  var import_react_dom = require("react-dom");
93
- var import_shared2 = require("@copilotkit/shared");
51
+ var import_shared = require("@copilotkit/shared");
94
52
  var import_jsx_runtime = require("react/jsx-runtime");
95
53
  var defaultCopilotContextCategories = ["global"];
96
54
 
97
55
  // src/lib/copilot-task.ts
56
+ var import_shared2 = require("@copilotkit/shared");
98
57
  var CopilotTask = class {
99
58
  constructor(config) {
100
59
  this.instructions = config.instructions;
101
60
  this.actions = config.actions || [];
102
61
  this.includeCopilotReadable = config.includeCopilotReadable !== false;
103
62
  this.includeCopilotActions = config.includeCopilotActions !== false;
104
- this.forwardedParameters = config.forwardedParameters;
105
63
  }
106
64
  /**
107
65
  * Run the task.
@@ -110,7 +68,7 @@ var CopilotTask = class {
110
68
  */
111
69
  run(context, data) {
112
70
  return __async(this, null, function* () {
113
- var _a, _b, _c;
71
+ var _a, _b;
114
72
  const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
115
73
  for (const fn of this.actions) {
116
74
  actions[fn.name] = fn;
@@ -122,12 +80,12 @@ var CopilotTask = class {
122
80
  if (this.includeCopilotReadable) {
123
81
  contextString += context.getContextString([], defaultCopilotContextCategories);
124
82
  }
125
- const systemMessage = new import_runtime_client_gql2.TextMessage({
83
+ const systemMessage = new import_runtime_client_gql.TextMessage({
126
84
  content: taskSystemMessage(contextString, this.instructions),
127
- role: import_runtime_client_gql2.Role.System
85
+ role: import_runtime_client_gql.Role.System
128
86
  });
129
87
  const messages = [systemMessage];
130
- const runtimeClient = new import_runtime_client_gql2.CopilotRuntimeClient({
88
+ const runtimeClient = new import_runtime_client_gql.CopilotRuntimeClient({
131
89
  url: context.copilotApiConfig.chatApiEndpoint,
132
90
  publicApiKey: context.copilotApiConfig.publicApiKey,
133
91
  headers: context.copilotApiConfig.headers,
@@ -136,22 +94,26 @@ var CopilotTask = class {
136
94
  const response = yield runtimeClient.generateCopilotResponse({
137
95
  data: {
138
96
  frontend: {
139
- actions: processActionsForRuntimeRequest(Object.values(actions)),
97
+ actions: Object.values(actions).map((action) => ({
98
+ name: action.name,
99
+ description: action.description || "",
100
+ jsonSchema: JSON.stringify((0, import_shared2.actionParametersToJsonSchema)(action.parameters || []))
101
+ })),
140
102
  url: window.location.href
141
103
  },
142
- messages: (0, import_runtime_client_gql2.convertMessagesToGqlInput)((0, import_runtime_client_gql2.filterAgentStateMessages)(messages)),
104
+ messages: (0, import_runtime_client_gql.convertMessagesToGqlInput)((0, import_runtime_client_gql.filterAgentStateMessages)(messages)),
143
105
  metadata: {
144
- requestType: import_runtime_client_gql2.CopilotRequestType.Task
106
+ requestType: import_runtime_client_gql.CopilotRequestType.Task
145
107
  },
146
- forwardedParameters: __spreadProps(__spreadValues({}, (_a = this.forwardedParameters) != null ? _a : {}), {
108
+ forwardedParameters: {
147
109
  toolChoice: "required"
148
- })
110
+ }
149
111
  },
150
112
  properties: context.copilotApiConfig.properties
151
113
  }).toPromise();
152
114
  const functionCallHandler = context.getFunctionCallHandler(actions);
153
- const functionCalls = (0, import_runtime_client_gql2.convertGqlOutputToMessages)(
154
- ((_c = (_b = response.data) == null ? void 0 : _b.generateCopilotResponse) == null ? void 0 : _c.messages) || []
115
+ const functionCalls = (0, import_runtime_client_gql.convertGqlOutputToMessages)(
116
+ ((_b = (_a = response.data) == null ? void 0 : _a.generateCopilotResponse) == null ? void 0 : _b.messages) || []
155
117
  ).filter((m) => m.isActionExecutionMessage());
156
118
  for (const functionCall of functionCalls) {
157
119
  yield functionCallHandler({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/lib/copilot-task.ts","../../src/types/frontend-action.ts","../../src/components/copilot-provider/copilotkit.tsx"],"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 * ]\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 ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { FrontendAction, processActionsForRuntimeRequest } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\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 /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: ForwardedParametersInput;\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 private forwardedParameters?: ForwardedParametersInput;\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 this.forwardedParameters = config.forwardedParameters;\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: processActionsForRuntimeRequest(Object.values(actions)),\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n // if forwardedParameters is provided, use it\n ...(this.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.isActionExecutionMessage());\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","import { ActionInputAvailability } from \"@copilotkit/runtime-client-gql\";\nimport {\n Action,\n Parameter,\n MappedParameterTypes,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport React from \"react\";\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingState<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: any;\n}\n\ninterface InProgressStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n}\n\nexport type ActionRenderProps<T extends Parameter[] | [] = []> =\n | CompleteState<T>\n | ExecutingState<T>\n | InProgressState<T>;\n\nexport type ActionRenderPropsNoArgs<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgs<T>\n | ExecutingStateNoArgs<T>\n | InProgressStateNoArgs<T>;\n\nexport type ActionRenderPropsWait<T extends Parameter[] | [] = []> =\n | CompleteStateWait<T>\n | ExecutingStateWait<T>\n | InProgressStateWait<T>;\n\nexport type ActionRenderPropsNoArgsWait<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgsWait<T>\n | ExecutingStateNoArgsWait<T>\n | InProgressStateNoArgsWait<T>;\n\nexport type CatchAllActionRenderProps<T extends Parameter[] | [] = []> =\n | (CompleteState<T> & {\n name: string;\n })\n | (ExecutingState<T> & {\n name: string;\n })\n | (InProgressState<T> & {\n name: string;\n });\n\nexport type FrontendActionAvailability = \"disabled\" | \"enabled\" | \"remote\";\n\nexport type FrontendAction<\n T extends Parameter[] | [] = [],\n N extends string = string,\n> = Action<T> & {\n name: Exclude<N, \"*\">;\n /**\n * @deprecated Use `available` instead.\n */\n disabled?: boolean;\n available?: FrontendActionAvailability;\n followUp?: boolean;\n} & (\n | {\n render?:\n | string\n | (T extends []\n ? (props: ActionRenderPropsNoArgs<T>) => string | React.ReactElement\n : (props: ActionRenderProps<T>) => string | React.ReactElement);\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: never;\n renderAndWaitForResponse?: never;\n }\n | {\n render?: never;\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n renderAndWaitForResponse?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n handler?: never;\n }\n );\n\nexport type CatchAllFrontendAction = {\n name: \"*\";\n render: (props: CatchAllActionRenderProps<any>) => React.ReactElement;\n};\n\nexport type RenderFunctionStatus = ActionRenderProps<any>[\"status\"];\n\nexport function processActionsForRuntimeRequest(actions: FrontendAction<any>[]) {\n const filteredActions = actions\n .filter(\n (action) =>\n action.available !== ActionInputAvailability.Disabled &&\n action.disabled !== true &&\n action.name !== \"*\",\n )\n .map((action) => {\n let available: ActionInputAvailability | undefined = ActionInputAvailability.Enabled;\n if (action.disabled) {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"disabled\") {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"remote\") {\n available = ActionInputAvailability.Remote;\n }\n return {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n available,\n };\n });\n return filteredActions;\n}\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n AuthState,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n} from \"@copilotkit/shared\";\n\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoAgentStateRender } from \"../../types/coagent-action\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"../../hooks/use-copilot-runtime-client\";\nimport { shouldShowDevConsole } from \"../../utils\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const showDevConsole = props.showDevConsole === undefined ? \"auto\" : props.showDevConsole;\n const enabled = shouldShowDevConsole(showDevConsole);\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal({ 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 [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n const { addElement, removeElement, printTree } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});\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 setCoAgentStateRender = useCallback((id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => {\n return {\n ...prevPoints,\n [id]: stateRender,\n };\n });\n }, []);\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const 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 // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n props.publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n ]);\n\n const headers = useMemo(() => {\n const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {\n if (state.status === \"authenticated\" && state.authHeaders) {\n return {\n ...acc,\n ...Object.entries(state.authHeaders).reduce(\n (headers, [key, value]) => ({\n ...headers,\n [key.startsWith(\"X-Custom-\") ? key : `X-Custom-${key}`]: value,\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n\n return {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n ...authHeaders,\n };\n }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n });\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 [availableAgents, setAvailableAgents] = useState<Agent[]>([]);\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => {\n const newValue = typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n\n useEffect(() => {\n const fetchData = async () => {\n const result = await runtimeClient.availableAgents();\n if (result.data?.availableAgents) {\n setAvailableAgents(result.data.availableAgents.agents);\n }\n };\n void fetchData();\n }, []);\n\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n const [threadId, setThreadId] = useState<string | null>(null);\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = props.showDevConsole === undefined ? \"auto\" : props.showDevConsole;\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n runtimeClient,\n forwardedParameters: props.forwardedParameters || {},\n agentLock: props.agent || null,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n availableAgents,\n authConfig: props.authConfig,\n authStates,\n setAuthStates,\n }}\n >\n <CopilotMessages>{children}</CopilotMessages>\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgDA,IAAAA,6BAWO;;;AC3DP,gCAAwC;AACxC,oBAKO;AAuKA,SAAS,gCAAgC,SAAgC;AAC9E,QAAM,kBAAkB,QACrB;AAAA,IACC,CAAC,WACC,OAAO,cAAc,kDAAwB,YAC7C,OAAO,aAAa,QACpB,OAAO,SAAS;AAAA,EACpB,EACC,IAAI,CAAC,WAAW;AACf,QAAI,YAAiD,kDAAwB;AAC7E,QAAI,OAAO,UAAU;AACnB,kBAAY,kDAAwB;AAAA,IACtC,WAAW,OAAO,cAAc,YAAY;AAC1C,kBAAY,kDAAwB;AAAA,IACtC,WAAW,OAAO,cAAc,UAAU;AACxC,kBAAY,kDAAwB;AAAA,IACtC;AACA,WAAO;AAAA,MACL,MAAM,OAAO;AAAA,MACb,aAAa,OAAO,eAAe;AAAA,MACnC,YAAY,KAAK,cAAU,4CAA6B,OAAO,cAAc,CAAC,CAAC,CAAC;AAAA,MAChF;AAAA,IACF;AAAA,EACF,CAAC;AACH,SAAO;AACT;;;ACtLA,mBAAkE;AAUlE,uBAA0B;AAC1B,IAAAC,iBAKO;AAoBC;AAkUD,IAAM,kCAAkC,CAAC,QAAQ;;;AF7RjD,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;AAC9D,SAAK,sBAAsB,OAAO;AAAA,EACpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOM,IAAI,SAA+B,MAAyB;AAAA;AA5GpE;AA6GI,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,uCAAY;AAAA,QACpC,SAAS,kBAAkB,eAAe,KAAK,YAAY;AAAA,QAC3D,MAAM,gCAAK;AAAA,MACb,CAAC;AAED,YAAM,WAAsB,CAAC,aAAa;AAE1C,YAAM,gBAAgB,IAAI,gDAAqB;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,gCAAgC,OAAO,OAAO,OAAO,CAAC;AAAA,YAC/D,KAAK,OAAO,SAAS;AAAA,UACvB;AAAA,UACA,cAAU,0DAA0B,qDAAyB,QAAQ,CAAC;AAAA,UACtE,UAAU;AAAA,YACR,aAAa,8CAAmB;AAAA,UAClC;AAAA,UACA,qBAAqB,kCAEf,UAAK,wBAAL,YAA4B,CAAC,IAFd;AAAA,YAGnB,YAAY;AAAA,UACd;AAAA,QACF;AAAA,QACA,YAAY,QAAQ,iBAAiB;AAAA,MACvC,CAAC,EACA,UAAU;AAEb,YAAM,sBAAsB,QAAQ,uBAAuB,OAAO;AAClE,YAAM,oBAAgB;AAAA,UACpB,oBAAS,SAAT,mBAAe,4BAAf,mBAAwC,aAAY,CAAC;AAAA,MACvD,EAAE,OAAO,CAAC,MAAmC,EAAE,yBAAyB,CAAC;AAEzE,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":["import_runtime_client_gql","import_shared"]}
1
+ {"version":3,"sources":["../../src/lib/copilot-task.ts","../../src/components/copilot-provider/copilotkit.tsx"],"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 * ]\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.isActionExecutionMessage());\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","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\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 COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n} from \"@copilotkit/shared\";\n\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoAgentStateRender } from \"../../types/coagent-action\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"../../hooks/use-copilot-runtime-client\";\nimport { shouldShowDevConsole } from \"../../utils\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const showDevConsole = props.showDevConsole === undefined ? \"auto\" : props.showDevConsole;\n const enabled = shouldShowDevConsole(showDevConsole);\n return (\n <ToastProvider enabled={enabled}>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal({ 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 [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n const { addElement, removeElement, printTree } = useTree();\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 setCoAgentStateRender = useCallback((id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => {\n return {\n ...prevPoints,\n [id]: stateRender,\n };\n });\n }, []);\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const 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 // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n props.publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n ]);\n\n const headers = {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.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 const showDevConsole = props.showDevConsole === undefined ? \"auto\" : props.showDevConsole;\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n agentSession,\n setAgentSession,\n runtimeClient,\n }}\n >\n <CopilotMessages>{children}</CopilotMessages>\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgDA,gCAUO;;;AC1CP,mBAAuD;AASvD,uBAA0B;AAC1B,oBAKO;AAiBD;AAiQC,IAAM,kCAAkC,CAAC,QAAQ;;;ADlPxD,IAAAA,iBAA6C;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;AAvGpE;AAwGI,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,sCAAY;AAAA,QACpC,SAAS,kBAAkB,eAAe,KAAK,YAAY;AAAA,QAC3D,MAAM,+BAAK;AAAA,MACb,CAAC;AAED,YAAM,WAAsB,CAAC,aAAa;AAE1C,YAAM,gBAAgB,IAAI,+CAAqB;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,cAAU,6CAA6B,OAAO,cAAc,CAAC,CAAC,CAAC;AAAA,YAClF,EAAE;AAAA,YACF,KAAK,OAAO,SAAS;AAAA,UACvB;AAAA,UACA,cAAU,yDAA0B,oDAAyB,QAAQ,CAAC;AAAA,UACtE,UAAU;AAAA,YACR,aAAa,6CAAmB;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,oBAAgB;AAAA,UACpB,oBAAS,SAAT,mBAAe,4BAAf,mBAAwC,aAAY,CAAC;AAAA,MACvD,EAAE,OAAO,CAAC,MAAmC,EAAE,yBAAyB,CAAC;AAEzE,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":["import_shared"]}
@@ -1,18 +1,16 @@
1
1
  import {
2
2
  CopilotTask
3
- } from "../chunk-XOQMISG3.mjs";
4
- import "../chunk-2KT73RVG.mjs";
5
- import "../chunk-VNTDIJSG.mjs";
6
- import "../chunk-MLAS4QUR.mjs";
7
- import "../chunk-XXR4QFAQ.mjs";
8
- import "../chunk-6U3UH3KO.mjs";
3
+ } from "../chunk-FXHKK52V.mjs";
4
+ import "../chunk-6OR25P32.mjs";
9
5
  import "../chunk-5FHSUKQL.mjs";
10
- import "../chunk-DCTJZ742.mjs";
11
- import "../chunk-XERJQUHA.mjs";
12
- import "../chunk-6BQVZFNO.mjs";
13
- import "../chunk-WXREY7UP.mjs";
14
- import "../chunk-LNI2Z45S.mjs";
6
+ import "../chunk-6U3UH3KO.mjs";
7
+ import "../chunk-XXR4QFAQ.mjs";
8
+ import "../chunk-ODN4H66E.mjs";
9
+ import "../chunk-2KCEHGSI.mjs";
15
10
  import "../chunk-O7ARI5CV.mjs";
11
+ import "../chunk-LODRWFMB.mjs";
12
+ import "../chunk-DCTJZ742.mjs";
13
+ import "../chunk-MLAS4QUR.mjs";
16
14
  import "../chunk-SKC7AJIV.mjs";
17
15
  export {
18
16
  CopilotTask
@@ -1,5 +1,4 @@
1
1
  export { CopilotTask, CopilotTaskConfig } from './copilot-task.js';
2
- import '@copilotkit/runtime-client-gql';
3
2
  import '../types/frontend-action.js';
4
3
  import '@copilotkit/shared';
5
4
  import 'react';
@@ -9,3 +8,4 @@ import '../types/document-pointer.js';
9
8
  import '../types/chat-suggestion-configuration.js';
10
9
  import '../types/coagent-action.js';
11
10
  import '../types/coagent-state.js';
11
+ import '@copilotkit/runtime-client-gql';
package/dist/lib/index.js CHANGED
@@ -1,25 +1,8 @@
1
1
  "use strict";
2
2
  var __defProp = Object.defineProperty;
3
- var __defProps = Object.defineProperties;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
- var __spreadValues = (a, b) => {
12
- for (var prop in b || (b = {}))
13
- if (__hasOwnProp.call(b, prop))
14
- __defNormalProp(a, prop, b[prop]);
15
- if (__getOwnPropSymbols)
16
- for (var prop of __getOwnPropSymbols(b)) {
17
- if (__propIsEnum.call(b, prop))
18
- __defNormalProp(a, prop, b[prop]);
19
- }
20
- return a;
21
- };
22
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
6
  var __export = (target, all) => {
24
7
  for (var name in all)
25
8
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -62,48 +45,23 @@ __export(lib_exports, {
62
45
  module.exports = __toCommonJS(lib_exports);
63
46
 
64
47
  // src/lib/copilot-task.ts
65
- var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
66
-
67
- // src/types/frontend-action.ts
68
48
  var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
69
- var import_shared = require("@copilotkit/shared");
70
- function processActionsForRuntimeRequest(actions) {
71
- const filteredActions = actions.filter(
72
- (action) => action.available !== import_runtime_client_gql.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*"
73
- ).map((action) => {
74
- let available = import_runtime_client_gql.ActionInputAvailability.Enabled;
75
- if (action.disabled) {
76
- available = import_runtime_client_gql.ActionInputAvailability.Disabled;
77
- } else if (action.available === "disabled") {
78
- available = import_runtime_client_gql.ActionInputAvailability.Disabled;
79
- } else if (action.available === "remote") {
80
- available = import_runtime_client_gql.ActionInputAvailability.Remote;
81
- }
82
- return {
83
- name: action.name,
84
- description: action.description || "",
85
- jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || [])),
86
- available
87
- };
88
- });
89
- return filteredActions;
90
- }
91
49
 
92
50
  // src/components/copilot-provider/copilotkit.tsx
93
51
  var import_react = require("react");
94
52
  var import_react_dom = require("react-dom");
95
- var import_shared2 = require("@copilotkit/shared");
53
+ var import_shared = require("@copilotkit/shared");
96
54
  var import_jsx_runtime = require("react/jsx-runtime");
97
55
  var defaultCopilotContextCategories = ["global"];
98
56
 
99
57
  // src/lib/copilot-task.ts
58
+ var import_shared2 = require("@copilotkit/shared");
100
59
  var CopilotTask = class {
101
60
  constructor(config) {
102
61
  this.instructions = config.instructions;
103
62
  this.actions = config.actions || [];
104
63
  this.includeCopilotReadable = config.includeCopilotReadable !== false;
105
64
  this.includeCopilotActions = config.includeCopilotActions !== false;
106
- this.forwardedParameters = config.forwardedParameters;
107
65
  }
108
66
  /**
109
67
  * Run the task.
@@ -112,7 +70,7 @@ var CopilotTask = class {
112
70
  */
113
71
  run(context, data) {
114
72
  return __async(this, null, function* () {
115
- var _a, _b, _c;
73
+ var _a, _b;
116
74
  const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
117
75
  for (const fn of this.actions) {
118
76
  actions[fn.name] = fn;
@@ -124,12 +82,12 @@ var CopilotTask = class {
124
82
  if (this.includeCopilotReadable) {
125
83
  contextString += context.getContextString([], defaultCopilotContextCategories);
126
84
  }
127
- const systemMessage = new import_runtime_client_gql2.TextMessage({
85
+ const systemMessage = new import_runtime_client_gql.TextMessage({
128
86
  content: taskSystemMessage(contextString, this.instructions),
129
- role: import_runtime_client_gql2.Role.System
87
+ role: import_runtime_client_gql.Role.System
130
88
  });
131
89
  const messages = [systemMessage];
132
- const runtimeClient = new import_runtime_client_gql2.CopilotRuntimeClient({
90
+ const runtimeClient = new import_runtime_client_gql.CopilotRuntimeClient({
133
91
  url: context.copilotApiConfig.chatApiEndpoint,
134
92
  publicApiKey: context.copilotApiConfig.publicApiKey,
135
93
  headers: context.copilotApiConfig.headers,
@@ -138,22 +96,26 @@ var CopilotTask = class {
138
96
  const response = yield runtimeClient.generateCopilotResponse({
139
97
  data: {
140
98
  frontend: {
141
- actions: processActionsForRuntimeRequest(Object.values(actions)),
99
+ actions: Object.values(actions).map((action) => ({
100
+ name: action.name,
101
+ description: action.description || "",
102
+ jsonSchema: JSON.stringify((0, import_shared2.actionParametersToJsonSchema)(action.parameters || []))
103
+ })),
142
104
  url: window.location.href
143
105
  },
144
- messages: (0, import_runtime_client_gql2.convertMessagesToGqlInput)((0, import_runtime_client_gql2.filterAgentStateMessages)(messages)),
106
+ messages: (0, import_runtime_client_gql.convertMessagesToGqlInput)((0, import_runtime_client_gql.filterAgentStateMessages)(messages)),
145
107
  metadata: {
146
- requestType: import_runtime_client_gql2.CopilotRequestType.Task
108
+ requestType: import_runtime_client_gql.CopilotRequestType.Task
147
109
  },
148
- forwardedParameters: __spreadProps(__spreadValues({}, (_a = this.forwardedParameters) != null ? _a : {}), {
110
+ forwardedParameters: {
149
111
  toolChoice: "required"
150
- })
112
+ }
151
113
  },
152
114
  properties: context.copilotApiConfig.properties
153
115
  }).toPromise();
154
116
  const functionCallHandler = context.getFunctionCallHandler(actions);
155
- const functionCalls = (0, import_runtime_client_gql2.convertGqlOutputToMessages)(
156
- ((_c = (_b = response.data) == null ? void 0 : _b.generateCopilotResponse) == null ? void 0 : _c.messages) || []
117
+ const functionCalls = (0, import_runtime_client_gql.convertGqlOutputToMessages)(
118
+ ((_b = (_a = response.data) == null ? void 0 : _a.generateCopilotResponse) == null ? void 0 : _b.messages) || []
157
119
  ).filter((m) => m.isActionExecutionMessage());
158
120
  for (const functionCall of functionCalls) {
159
121
  yield functionCallHandler({