@copilotkit/react-core 1.1.1-feat-runtime-remote-actions.4 → 1.1.1-feat-runtime-remote-actions.5

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 (129) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/{chunk-2MQX7BJL.mjs → chunk-6GOM3DN7.mjs} +2 -2
  3. package/dist/{chunk-IF6P5ZXR.mjs → chunk-6UNB66M3.mjs} +38 -10
  4. package/dist/chunk-6UNB66M3.mjs.map +1 -0
  5. package/dist/{chunk-73KBO5JG.mjs → chunk-73YBF52D.mjs} +2 -2
  6. package/dist/chunk-BWYAGPEF.mjs +1 -0
  7. package/dist/{chunk-DZH3HSXW.mjs → chunk-CHOQ5C7K.mjs} +35 -8
  8. package/dist/chunk-CHOQ5C7K.mjs.map +1 -0
  9. package/dist/{chunk-33ERMMNX.mjs → chunk-DU7PVINC.mjs} +2 -2
  10. package/dist/chunk-IQH77T4S.mjs +44 -0
  11. package/dist/chunk-IQH77T4S.mjs.map +1 -0
  12. package/dist/{chunk-DB4VWZ5Q.mjs → chunk-LTA2O5WH.mjs} +11 -6
  13. package/dist/chunk-LTA2O5WH.mjs.map +1 -0
  14. package/dist/chunk-MTOHRBPJ.mjs +87 -0
  15. package/dist/chunk-MTOHRBPJ.mjs.map +1 -0
  16. package/dist/{chunk-52M7642J.mjs → chunk-PPYZB3IY.mjs} +52 -31
  17. package/dist/chunk-PPYZB3IY.mjs.map +1 -0
  18. package/dist/{chunk-H4XENJME.mjs → chunk-SYJIZLOI.mjs} +2 -2
  19. package/dist/{chunk-3K7JAFGM.mjs → chunk-TFSMXQYS.mjs} +2 -2
  20. package/dist/components/copilot-provider/copilotkit-props.d.ts +4 -0
  21. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  22. package/dist/components/copilot-provider/copilotkit.js +46 -13
  23. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  24. package/dist/components/copilot-provider/copilotkit.mjs +2 -2
  25. package/dist/components/copilot-provider/index.js +46 -13
  26. package/dist/components/copilot-provider/index.js.map +1 -1
  27. package/dist/components/copilot-provider/index.mjs +2 -2
  28. package/dist/components/index.js +46 -13
  29. package/dist/components/index.js.map +1 -1
  30. package/dist/components/index.mjs +2 -2
  31. package/dist/context/copilot-context.d.ts +18 -8
  32. package/dist/context/copilot-context.js +10 -5
  33. package/dist/context/copilot-context.js.map +1 -1
  34. package/dist/context/copilot-context.mjs +1 -1
  35. package/dist/context/index.d.ts +2 -1
  36. package/dist/context/index.js +10 -5
  37. package/dist/context/index.js.map +1 -1
  38. package/dist/context/index.mjs +1 -1
  39. package/dist/hooks/index.d.ts +4 -2
  40. package/dist/hooks/index.js +205 -89
  41. package/dist/hooks/index.js.map +1 -1
  42. package/dist/hooks/index.mjs +17 -17
  43. package/dist/hooks/use-chat.d.ts +24 -7
  44. package/dist/hooks/use-chat.js +51 -30
  45. package/dist/hooks/use-chat.js.map +1 -1
  46. package/dist/hooks/use-chat.mjs +1 -1
  47. package/dist/hooks/use-coagent-action.d.ts +5 -0
  48. package/dist/hooks/{use-copilot-chat-ui.js → use-coagent-action.js} +48 -22
  49. package/dist/hooks/use-coagent-action.js.map +1 -0
  50. package/dist/hooks/use-coagent-action.mjs +9 -0
  51. package/dist/hooks/use-coagent.d.ts +14 -18
  52. package/dist/hooks/use-coagent.js +184 -17
  53. package/dist/hooks/use-coagent.js.map +1 -1
  54. package/dist/hooks/use-coagent.mjs +6 -20
  55. package/dist/hooks/use-coagent.mjs.map +1 -1
  56. package/dist/hooks/use-copilot-action.js +10 -5
  57. package/dist/hooks/use-copilot-action.js.map +1 -1
  58. package/dist/hooks/use-copilot-action.mjs +2 -2
  59. package/dist/hooks/use-copilot-chat.js +89 -37
  60. package/dist/hooks/use-copilot-chat.js.map +1 -1
  61. package/dist/hooks/use-copilot-chat.mjs +4 -4
  62. package/dist/hooks/use-copilot-readable.js +10 -5
  63. package/dist/hooks/use-copilot-readable.js.map +1 -1
  64. package/dist/hooks/use-copilot-readable.mjs +2 -2
  65. package/dist/hooks/use-make-copilot-document-readable.js +10 -5
  66. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  67. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  68. package/dist/index.d.ts +4 -2
  69. package/dist/index.js +263 -119
  70. package/dist/index.js.map +1 -1
  71. package/dist/index.mjs +21 -21
  72. package/dist/lib/copilot-task.d.ts +2 -1
  73. package/dist/lib/copilot-task.js.map +1 -1
  74. package/dist/lib/copilot-task.mjs +3 -3
  75. package/dist/lib/index.d.ts +2 -1
  76. package/dist/lib/index.js.map +1 -1
  77. package/dist/lib/index.mjs +3 -3
  78. package/dist/types/coagent-action.d.ts +17 -0
  79. package/dist/types/coagent-action.js +19 -0
  80. package/dist/types/coagent-action.js.map +1 -0
  81. package/dist/types/coagent-action.mjs +1 -0
  82. package/dist/types/coagent-state.d.ts +11 -0
  83. package/dist/types/coagent-state.js +19 -0
  84. package/dist/types/coagent-state.js.map +1 -0
  85. package/dist/types/coagent-state.mjs +1 -0
  86. package/dist/types/coagent-state.mjs.map +1 -0
  87. package/dist/utils/extract.d.ts +2 -1
  88. package/dist/utils/extract.js.map +1 -1
  89. package/dist/utils/extract.mjs +3 -3
  90. package/dist/utils/index.d.ts +2 -1
  91. package/dist/utils/index.js.map +1 -1
  92. package/dist/utils/index.mjs +3 -3
  93. package/package.json +5 -5
  94. package/src/components/copilot-provider/copilotkit-props.tsx +5 -0
  95. package/src/components/copilot-provider/copilotkit.tsx +41 -9
  96. package/src/context/copilot-context.tsx +34 -15
  97. package/src/hooks/index.ts +2 -2
  98. package/src/hooks/use-chat.ts +88 -38
  99. package/src/hooks/use-coagent-action.ts +44 -0
  100. package/src/hooks/use-coagent.ts +111 -38
  101. package/src/hooks/use-copilot-chat.ts +29 -2
  102. package/src/types/coagent-action.ts +17 -0
  103. package/src/types/coagent-state.ts +9 -0
  104. package/dist/chunk-52M7642J.mjs.map +0 -1
  105. package/dist/chunk-6YOQY4WD.mjs +0 -20
  106. package/dist/chunk-6YOQY4WD.mjs.map +0 -1
  107. package/dist/chunk-A47L32JN.mjs +0 -52
  108. package/dist/chunk-A47L32JN.mjs.map +0 -1
  109. package/dist/chunk-AIWDXM7L.mjs +0 -1
  110. package/dist/chunk-DB4VWZ5Q.mjs.map +0 -1
  111. package/dist/chunk-DZH3HSXW.mjs.map +0 -1
  112. package/dist/chunk-IF6P5ZXR.mjs.map +0 -1
  113. package/dist/hooks/use-agent-state.d.ts +0 -12
  114. package/dist/hooks/use-agent-state.js +0 -499
  115. package/dist/hooks/use-agent-state.js.map +0 -1
  116. package/dist/hooks/use-agent-state.mjs +0 -19
  117. package/dist/hooks/use-copilot-chat-ui.d.ts +0 -13
  118. package/dist/hooks/use-copilot-chat-ui.js.map +0 -1
  119. package/dist/hooks/use-copilot-chat-ui.mjs +0 -10
  120. package/src/hooks/use-agent-state.ts +0 -63
  121. package/src/hooks/use-copilot-chat-ui.ts +0 -26
  122. /package/dist/{chunk-2MQX7BJL.mjs.map → chunk-6GOM3DN7.mjs.map} +0 -0
  123. /package/dist/{chunk-73KBO5JG.mjs.map → chunk-73YBF52D.mjs.map} +0 -0
  124. /package/dist/{chunk-AIWDXM7L.mjs.map → chunk-BWYAGPEF.mjs.map} +0 -0
  125. /package/dist/{chunk-33ERMMNX.mjs.map → chunk-DU7PVINC.mjs.map} +0 -0
  126. /package/dist/{chunk-H4XENJME.mjs.map → chunk-SYJIZLOI.mjs.map} +0 -0
  127. /package/dist/{chunk-3K7JAFGM.mjs.map → chunk-TFSMXQYS.mjs.map} +0 -0
  128. /package/dist/hooks/{use-agent-state.mjs.map → use-coagent-action.mjs.map} +0 -0
  129. /package/dist/{hooks/use-copilot-chat-ui.mjs.map → types/coagent-action.mjs.map} +0 -0
@@ -1,499 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __defProps = Object.defineProperties;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
- var __getOwnPropNames = Object.getOwnPropertyNames;
8
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
- var __getProtoOf = Object.getPrototypeOf;
10
- var __hasOwnProp = Object.prototype.hasOwnProperty;
11
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
- var __spreadValues = (a, b) => {
14
- for (var prop in b || (b = {}))
15
- if (__hasOwnProp.call(b, prop))
16
- __defNormalProp(a, prop, b[prop]);
17
- if (__getOwnPropSymbols)
18
- for (var prop of __getOwnPropSymbols(b)) {
19
- if (__propIsEnum.call(b, prop))
20
- __defNormalProp(a, prop, b[prop]);
21
- }
22
- return a;
23
- };
24
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
- var __objRest = (source, exclude) => {
26
- var target = {};
27
- for (var prop in source)
28
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
29
- target[prop] = source[prop];
30
- if (source != null && __getOwnPropSymbols)
31
- for (var prop of __getOwnPropSymbols(source)) {
32
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
33
- target[prop] = source[prop];
34
- }
35
- return target;
36
- };
37
- var __export = (target, all) => {
38
- for (var name in all)
39
- __defProp(target, name, { get: all[name], enumerable: true });
40
- };
41
- var __copyProps = (to, from, except, desc) => {
42
- if (from && typeof from === "object" || typeof from === "function") {
43
- for (let key of __getOwnPropNames(from))
44
- if (!__hasOwnProp.call(to, key) && key !== except)
45
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
46
- }
47
- return to;
48
- };
49
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
50
- // If the importer is in node compatibility mode or this is not an ESM
51
- // file that has been converted to a CommonJS file using a Babel-
52
- // compatible transform (i.e. "__esModule" has not been set), then set
53
- // "default" to the CommonJS "module.exports" for node compatibility.
54
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
55
- mod
56
- ));
57
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
58
- var __async = (__this, __arguments, generator) => {
59
- return new Promise((resolve, reject) => {
60
- var fulfilled = (value) => {
61
- try {
62
- step(generator.next(value));
63
- } catch (e) {
64
- reject(e);
65
- }
66
- };
67
- var rejected = (value) => {
68
- try {
69
- step(generator.throw(value));
70
- } catch (e) {
71
- reject(e);
72
- }
73
- };
74
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
75
- step((generator = generator.apply(__this, __arguments)).next());
76
- });
77
- };
78
-
79
- // src/hooks/use-agent-state.ts
80
- var use_agent_state_exports = {};
81
- __export(use_agent_state_exports, {
82
- default: () => use_agent_state_default,
83
- useAgentState: () => useAgentState
84
- });
85
- module.exports = __toCommonJS(use_agent_state_exports);
86
- var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
87
-
88
- // src/context/copilot-context.tsx
89
- var import_react = __toESM(require("react"));
90
- var emptyCopilotContext = {
91
- actions: {},
92
- setAction: () => {
93
- },
94
- removeAction: () => {
95
- },
96
- chatComponentsCache: { current: { actions: {}, chatUI: {} } },
97
- getContextString: (documents, categories) => returnAndThrowInDebug(""),
98
- addContext: () => "",
99
- removeContext: () => {
100
- },
101
- getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
102
- })),
103
- messages: [],
104
- setMessages: () => returnAndThrowInDebug([]),
105
- isLoading: false,
106
- setIsLoading: () => returnAndThrowInDebug(false),
107
- chatInstructions: "",
108
- setChatInstructions: () => returnAndThrowInDebug(""),
109
- getDocumentsContext: (categories) => returnAndThrowInDebug([]),
110
- addDocumentContext: () => returnAndThrowInDebug(""),
111
- removeDocumentContext: () => {
112
- },
113
- copilotApiConfig: new class {
114
- get chatApiEndpoint() {
115
- throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
116
- }
117
- get headers() {
118
- return {};
119
- }
120
- get body() {
121
- return {};
122
- }
123
- }(),
124
- chatSuggestionConfiguration: {},
125
- addChatSuggestionConfiguration: () => {
126
- },
127
- removeChatSuggestionConfiguration: () => {
128
- },
129
- showDevConsole: "auto",
130
- agentStates: {},
131
- setAgentStates: () => {
132
- },
133
- chatUI: [],
134
- setChatUI: () => {
135
- }
136
- };
137
- var CopilotContext = import_react.default.createContext(emptyCopilotContext);
138
- function useCopilotContext() {
139
- return import_react.default.useContext(CopilotContext);
140
- }
141
- function returnAndThrowInDebug(value) {
142
- throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
143
- return value;
144
- }
145
-
146
- // src/hooks/use-copilot-chat.ts
147
- var import_react4 = require("react");
148
- var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
149
-
150
- // src/hooks/use-chat.ts
151
- var import_react2 = require("react");
152
- var import_shared = require("@copilotkit/shared");
153
- var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
154
- function useChat(options) {
155
- const {
156
- messages,
157
- setMessages,
158
- makeSystemMessageCallback,
159
- copilotConfig,
160
- setIsLoading,
161
- initialMessages,
162
- isLoading,
163
- actions,
164
- onFunctionCall,
165
- setAgentStates
166
- } = options;
167
- const abortControllerRef = (0, import_react2.useRef)();
168
- const threadIdRef = (0, import_react2.useRef)(null);
169
- const runIdRef = (0, import_react2.useRef)(null);
170
- const agentSessionRef = (0, import_react2.useRef)(null);
171
- const publicApiKey = copilotConfig.publicApiKey;
172
- const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
173
- const runtimeClient = new import_runtime_client_gql.CopilotRuntimeClient({
174
- url: copilotConfig.chatApiEndpoint,
175
- publicApiKey: copilotConfig.publicApiKey,
176
- headers,
177
- credentials: copilotConfig.credentials
178
- });
179
- const runChatCompletion = (previousMessages) => __async(this, null, function* () {
180
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
181
- setIsLoading(true);
182
- let newMessages = [
183
- new import_runtime_client_gql.TextMessage({
184
- content: "",
185
- role: import_runtime_client_gql.Role.Assistant
186
- })
187
- ];
188
- const abortController = new AbortController();
189
- abortControllerRef.current = abortController;
190
- setMessages([...previousMessages, ...newMessages]);
191
- const systemMessage = makeSystemMessageCallback();
192
- const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
193
- const stream = import_runtime_client_gql.CopilotRuntimeClient.asStream(
194
- runtimeClient.generateCopilotResponse({
195
- data: __spreadValues(__spreadProps(__spreadValues({
196
- frontend: {
197
- actions: actions.map((action) => ({
198
- name: action.name,
199
- description: action.description || "",
200
- jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || []))
201
- }))
202
- },
203
- threadId: threadIdRef.current,
204
- runId: runIdRef.current,
205
- messages: (0, import_runtime_client_gql.convertMessagesToGqlInput)(messagesWithContext)
206
- }, copilotConfig.cloud ? {
207
- cloud: __spreadValues({}, ((_c = (_b = (_a = copilotConfig.cloud.guardrails) == null ? void 0 : _a.input) == null ? void 0 : _b.restrictToTopic) == null ? void 0 : _c.enabled) ? {
208
- guardrails: {
209
- inputValidationRules: {
210
- allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
211
- denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
212
- }
213
- }
214
- } : {})
215
- } : {}), {
216
- metadata: {
217
- requestType: import_runtime_client_gql.CopilotRequestType.Chat
218
- }
219
- }), agentSessionRef.current ? {
220
- agentSession: {
221
- threadId: agentSessionRef.current.threadId,
222
- agentName: agentSessionRef.current.agentName,
223
- nodeName: agentSessionRef.current.nodeName
224
- }
225
- } : {}),
226
- properties: copilotConfig.properties,
227
- signal: (_d = abortControllerRef.current) == null ? void 0 : _d.signal
228
- })
229
- );
230
- const guardrailsEnabled = ((_g = (_f = (_e = copilotConfig.cloud) == null ? void 0 : _e.guardrails) == null ? void 0 : _f.input) == null ? void 0 : _g.restrictToTopic.enabled) || false;
231
- const reader = stream.getReader();
232
- let results = {};
233
- try {
234
- while (true) {
235
- const { done, value } = yield reader.read();
236
- if (done) {
237
- break;
238
- }
239
- if (!(value == null ? void 0 : value.generateCopilotResponse)) {
240
- continue;
241
- }
242
- threadIdRef.current = value.generateCopilotResponse.threadId || null;
243
- runIdRef.current = value.generateCopilotResponse.runId || null;
244
- const messages2 = (0, import_runtime_client_gql.convertGqlOutputToMessages)(value.generateCopilotResponse.messages);
245
- if (messages2.length === 0) {
246
- continue;
247
- }
248
- newMessages = [];
249
- if (((_h = value.generateCopilotResponse.status) == null ? void 0 : _h.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
250
- newMessages = [
251
- new import_runtime_client_gql.TextMessage({
252
- role: import_runtime_client_gql.MessageRole.Assistant,
253
- content: ((_i = value.generateCopilotResponse.status.details) == null ? void 0 : _i.guardrailsReason) || ""
254
- })
255
- ];
256
- } else {
257
- for (const message of messages2) {
258
- newMessages.push(message);
259
- if (message instanceof import_runtime_client_gql.AgentStateMessage) {
260
- if (message.running) {
261
- setAgentStates((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
262
- [message.agentName]: message
263
- }));
264
- agentSessionRef.current = {
265
- threadId: message.threadId,
266
- agentName: message.agentName,
267
- nodeName: message.nodeName
268
- };
269
- } else {
270
- setAgentStates((prevAgentStates) => {
271
- const newAgentStates = __spreadValues({}, prevAgentStates);
272
- delete newAgentStates[message.agentName];
273
- return newAgentStates;
274
- });
275
- agentSessionRef.current = null;
276
- }
277
- }
278
- if (message instanceof import_runtime_client_gql.ActionExecutionMessage && message.status.code !== import_runtime_client_gql.MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
279
- if (!(message.id in results)) {
280
- if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
281
- break;
282
- }
283
- const result = yield onFunctionCall({
284
- messages: previousMessages,
285
- name: message.name,
286
- args: message.arguments
287
- });
288
- results[message.id] = result;
289
- }
290
- newMessages.push(
291
- new import_runtime_client_gql.ResultMessage({
292
- result: import_runtime_client_gql.ResultMessage.encodeResult(results[message.id]),
293
- actionExecutionId: message.id,
294
- actionName: message.name
295
- })
296
- );
297
- }
298
- }
299
- }
300
- if (newMessages.length > 0) {
301
- const filteredMessages = [...previousMessages, ...newMessages].reduce(
302
- (acc, message) => {
303
- if (message instanceof import_runtime_client_gql.AgentStateMessage && // Check if the current message is an AgentStateMessage
304
- acc.length > 0 && // Ensure there is at least one message in the accumulator
305
- acc[acc.length - 1] instanceof import_runtime_client_gql.AgentStateMessage && // Check if the last message in the accumulator is also an AgentStateMessage
306
- acc[acc.length - 1].agentName === message.agentName && // Check if the agentName is the same
307
- acc[acc.length - 1].nodeName === message.nodeName) {
308
- acc[acc.length - 1] = message;
309
- } else {
310
- acc.push(message);
311
- }
312
- return acc;
313
- },
314
- []
315
- );
316
- setMessages(filteredMessages);
317
- }
318
- }
319
- if (
320
- // if we have client side results
321
- Object.values(results).length || // or the last message we received is a result
322
- newMessages.length && newMessages[newMessages.length - 1] instanceof import_runtime_client_gql.ResultMessage
323
- ) {
324
- yield new Promise((resolve) => setTimeout(resolve, 10));
325
- return yield runChatCompletion([...previousMessages, ...newMessages]);
326
- } else {
327
- return newMessages.slice();
328
- }
329
- } finally {
330
- setIsLoading(false);
331
- }
332
- });
333
- const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
334
- yield runChatCompletion(messages2);
335
- });
336
- const append = (message) => __async(this, null, function* () {
337
- if (isLoading) {
338
- return;
339
- }
340
- const newMessages = [...messages, message];
341
- setMessages(newMessages);
342
- return runChatCompletionAndHandleFunctionCall(newMessages);
343
- });
344
- const reload = () => __async(this, null, function* () {
345
- if (isLoading || messages.length === 0) {
346
- return;
347
- }
348
- let newMessages = [...messages];
349
- const lastMessage = messages[messages.length - 1];
350
- if (lastMessage instanceof import_runtime_client_gql.TextMessage && lastMessage.role === "assistant") {
351
- newMessages = newMessages.slice(0, -1);
352
- }
353
- setMessages(newMessages);
354
- return runChatCompletionAndHandleFunctionCall(newMessages);
355
- });
356
- const stop = () => {
357
- var _a;
358
- (_a = abortControllerRef.current) == null ? void 0 : _a.abort();
359
- };
360
- return {
361
- append,
362
- reload,
363
- stop
364
- };
365
- }
366
-
367
- // src/components/copilot-provider/copilotkit.tsx
368
- var import_react3 = require("react");
369
- var import_react_dom = require("react-dom");
370
- var import_shared2 = require("@copilotkit/shared");
371
- var import_jsx_runtime = require("react/jsx-runtime");
372
- var defaultCopilotContextCategories = ["global"];
373
-
374
- // src/hooks/use-copilot-chat.ts
375
- function useCopilotChat(_a = {}) {
376
- var _b = _a, {
377
- makeSystemMessage
378
- } = _b, options = __objRest(_b, [
379
- "makeSystemMessage"
380
- ]);
381
- const {
382
- getContextString,
383
- getFunctionCallHandler,
384
- copilotApiConfig,
385
- messages,
386
- setMessages,
387
- isLoading,
388
- setIsLoading,
389
- chatInstructions,
390
- actions,
391
- setAgentStates
392
- } = (0, import_react4.useContext)(CopilotContext);
393
- const latestGetContextString = useUpdatedRef(getContextString);
394
- const deleteMessage = (0, import_react4.useCallback)(
395
- (messageId) => {
396
- setMessages((prev) => prev.filter((message) => message.id !== messageId));
397
- },
398
- [setMessages]
399
- );
400
- const makeSystemMessageCallback = (0, import_react4.useCallback)(() => {
401
- const systemMessageMaker = makeSystemMessage || defaultSystemMessage;
402
- const contextString = latestGetContextString.current([], defaultCopilotContextCategories);
403
- return new import_runtime_client_gql2.TextMessage({
404
- content: systemMessageMaker(contextString, chatInstructions),
405
- role: import_runtime_client_gql2.Role.System
406
- });
407
- }, [getContextString, makeSystemMessage, chatInstructions]);
408
- const { append, reload, stop } = useChat(__spreadProps(__spreadValues({}, options), {
409
- actions: Object.values(actions),
410
- copilotConfig: copilotApiConfig,
411
- initialMessages: options.initialMessages || [],
412
- onFunctionCall: getFunctionCallHandler(),
413
- messages,
414
- setMessages,
415
- makeSystemMessageCallback,
416
- isLoading,
417
- setIsLoading,
418
- setAgentStates
419
- }));
420
- return {
421
- visibleMessages: messages,
422
- appendMessage: append,
423
- setMessages,
424
- reloadMessages: reload,
425
- stopGeneration: stop,
426
- deleteMessage,
427
- isLoading
428
- };
429
- }
430
- function useUpdatedRef(value) {
431
- const ref = (0, import_react4.useRef)(value);
432
- (0, import_react4.useEffect)(() => {
433
- ref.current = value;
434
- }, [value]);
435
- return ref;
436
- }
437
- function defaultSystemMessage(contextString, additionalInstructions) {
438
- return `
439
- Please act as an efficient, competent, conscientious, and industrious professional assistant.
440
-
441
- Help 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.
442
- Always be polite and respectful, and prefer brevity over verbosity.
443
-
444
- The user has provided you with the following context:
445
- \`\`\`
446
- ${contextString}
447
- \`\`\`
448
-
449
- They have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.
450
-
451
- Please assist them as best you can.
452
-
453
- You 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.
454
-
455
- If you would like to call a function, call it without saying anything else.
456
- ` + (additionalInstructions ? `
457
-
458
- ${additionalInstructions}` : "");
459
- }
460
-
461
- // src/hooks/use-agent-state.ts
462
- function useAgentState(agentName) {
463
- const { agentStates, setAgentStates } = useCopilotContext();
464
- const { visibleMessages, setMessages } = useCopilotChat();
465
- const setSpecificAgentState = (newState) => {
466
- setAgentStates((prevAgentStates) => {
467
- const currentState2 = prevAgentStates[agentName];
468
- if (!currentState2) {
469
- throw new Error(`Agent state ${agentName} not found`);
470
- }
471
- const updatedState = typeof newState === "function" ? newState(currentState2) : newState;
472
- const lastAgentStateMessage = [...visibleMessages].reverse().find((message) => message instanceof import_runtime_client_gql3.AgentStateMessage);
473
- const agentStateMessage = new import_runtime_client_gql3.AgentStateMessage({
474
- agentName,
475
- nodeName: lastAgentStateMessage.nodeName,
476
- state: updatedState,
477
- running: lastAgentStateMessage.running,
478
- threadId: lastAgentStateMessage.threadId,
479
- role: lastAgentStateMessage.role
480
- });
481
- setMessages([...visibleMessages, agentStateMessage]);
482
- return __spreadProps(__spreadValues({}, prevAgentStates), {
483
- [agentName]: agentStateMessage
484
- });
485
- });
486
- };
487
- const currentState = agentStates[agentName];
488
- return [
489
- currentState == null ? void 0 : currentState.state,
490
- setSpecificAgentState,
491
- currentState ? { nodeName: currentState.nodeName } : void 0
492
- ];
493
- }
494
- var use_agent_state_default = useAgentState;
495
- // Annotate the CommonJS export names for ESM import in node:
496
- 0 && (module.exports = {
497
- useAgentState
498
- });
499
- //# sourceMappingURL=use-agent-state.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/hooks/use-agent-state.ts","../../src/context/copilot-context.tsx","../../src/hooks/use-copilot-chat.ts","../../src/hooks/use-chat.ts","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["import { AgentStateMessage } from \"@copilotkit/runtime-client-gql\";\nimport { useCopilotContext } from \"../context\";\nimport { useCopilotChat } from \"./use-copilot-chat\";\n\nexport type AgentStateInfo = {\n nodeName: string;\n};\n\ntype SetAgentStateAction<T = any> = (newState: T | ((prevState: T | undefined) => T)) => void;\n\nexport type UseAgentStateReturnType<T = any> = [\n T | undefined,\n SetAgentStateAction<T>,\n AgentStateInfo | undefined,\n];\n\nexport function useAgentState<T = any>(agentName: string): UseAgentStateReturnType<T> {\n const { agentStates, setAgentStates } = useCopilotContext();\n\n const { visibleMessages, setMessages } = useCopilotChat();\n\n const setSpecificAgentState: SetAgentStateAction<T> = (newState) => {\n setAgentStates((prevAgentStates) => {\n const currentState = prevAgentStates[agentName];\n if (!currentState) {\n throw new Error(`Agent state ${agentName} not found`);\n }\n\n const updatedState =\n typeof newState === \"function\" ? (newState as Function)(currentState) : newState;\n\n const lastAgentStateMessage = [...visibleMessages]\n .reverse()\n .find((message): message is AgentStateMessage => message instanceof AgentStateMessage)!;\n\n const agentStateMessage = new AgentStateMessage({\n agentName,\n nodeName: lastAgentStateMessage.nodeName,\n state: updatedState,\n running: lastAgentStateMessage.running,\n threadId: lastAgentStateMessage.threadId,\n role: lastAgentStateMessage.role,\n });\n\n setMessages([...visibleMessages, agentStateMessage]);\n\n return {\n ...prevAgentStates,\n [agentName]: agentStateMessage,\n };\n });\n };\n\n const currentState = agentStates[agentName];\n\n return [\n currentState?.state as T,\n setSpecificAgentState,\n currentState ? { nodeName: currentState.nodeName } : undefined,\n ];\n}\n\nexport default useAgentState;\n","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { AgentStateMessage, 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 { CopilotChatUI } from \"../hooks/use-copilot-chat-ui\";\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;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n chatUI: Record<string, Function | 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 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 // agent states\n agentStates: Record<string, AgentStateMessage | null>;\n setAgentStates: React.Dispatch<React.SetStateAction<Record<string, AgentStateMessage | null>>>;\n\n // chat ui\n chatUI: CopilotChatUI[];\n setChatUI: React.Dispatch<React.SetStateAction<CopilotChatUI[]>>;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n chatComponentsCache: { current: { actions: {}, chatUI: {} } },\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 agentStates: {},\n setAgentStates: () => {},\n chatUI: [],\n setChatUI: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\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","/**\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 { useContext, useRef, useEffect, useCallback } from \"react\";\nimport { CopilotContext } 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\";\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 setAgentStates,\n } = useContext(CopilotContext);\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 { append, reload, stop } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: options.initialMessages || [],\n onFunctionCall: getFunctionCallHandler(),\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n setAgentStates,\n });\n\n return {\n visibleMessages: messages,\n appendMessage: append,\n setMessages,\n reloadMessages: reload,\n stopGeneration: stop,\n deleteMessage,\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","import { useRef } from \"react\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n Action,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ActionExecutionMessage,\n ResultMessage,\n CopilotRuntimeClient,\n convertMessagesToGqlInput,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n AgentStateMessage,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n /**\n * Function definitions to be sent to the API.\n */\n actions: Action[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n /**\n * setState-powered method to update the agent states\n */\n setAgentStates: React.Dispatch<React.SetStateAction<Record<string, AgentStateMessage | null>>>;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\ninterface AgentSession {\n threadId: string;\n agentName: string;\n nodeName: string;\n}\n\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n setAgentStates,\n } = options;\n\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n const agentSessionRef = useRef<AgentSession | null>(null);\n\n const publicApiKey = copilotConfig.publicApiKey;\n\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n });\n\n const runChatCompletion = async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n const stream = CopilotRuntimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: actions.map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\n messages: convertMessagesToGqlInput(messagesWithContext),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n ...(copilotConfig.cloud.guardrails?.input?.restrictToTopic?.enabled\n ? {\n guardrails: {\n inputValidationRules: {\n allowList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n }\n : {}),\n },\n }\n : {}),\n metadata: {\n requestType: CopilotRequestType.Chat,\n },\n ...(agentSessionRef.current\n ? {\n agentSession: {\n threadId: agentSessionRef.current.threadId,\n agentName: agentSessionRef.current.agentName,\n nodeName: agentSessionRef.current.nodeName,\n },\n }\n : {}),\n },\n properties: copilotConfig.properties,\n signal: abortControllerRef.current?.signal,\n }),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let results: { [id: string]: string } = {};\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n threadIdRef.current = value.generateCopilotResponse.threadId || null;\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n const messages = convertGqlOutputToMessages(value.generateCopilotResponse.messages);\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n }\n\n // add messages to the chat\n else {\n for (const message of messages) {\n newMessages.push(message);\n\n if (message instanceof AgentStateMessage) {\n if (message.running) {\n setAgentStates((prevAgentStates) => ({\n ...prevAgentStates,\n [message.agentName]: message,\n }));\n agentSessionRef.current = {\n threadId: message.threadId,\n agentName: message.agentName,\n nodeName: message.nodeName,\n };\n } else {\n setAgentStates((prevAgentStates) => {\n const newAgentStates = { ...prevAgentStates };\n delete newAgentStates[message.agentName];\n return newAgentStates;\n });\n agentSessionRef.current = null;\n }\n }\n\n // execute regular action executions\n if (\n message instanceof ActionExecutionMessage &&\n message.status.code !== MessageStatusCode.Pending &&\n message.scope === \"client\" &&\n onFunctionCall\n ) {\n if (!(message.id in results)) {\n // Do not execute a function call if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute action\n const result = await onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n });\n results[message.id] = result;\n }\n\n // add the result message\n newMessages.push(\n new ResultMessage({\n result: ResultMessage.encodeResult(results[message.id]),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Construct filteredMessages inline to remove adjacent AgentStateMessage instances\n // with the same agentName, keeping only the last one.\n const filteredMessages = [...previousMessages, ...newMessages].reduce(\n (acc: Message[], message: Message) => {\n if (\n message instanceof AgentStateMessage && // Check if the current message is an AgentStateMessage\n acc.length > 0 && // Ensure there is at least one message in the accumulator\n acc[acc.length - 1] instanceof AgentStateMessage && // Check if the last message in the accumulator is also an AgentStateMessage\n (acc[acc.length - 1] as AgentStateMessage).agentName === message.agentName && // Check if the agentName is the same\n (acc[acc.length - 1] as AgentStateMessage).nodeName === message.nodeName // Check if the nodeName is the same\n ) {\n // If the conditions are met, replace the last message in the accumulator with the current message\n acc[acc.length - 1] = message;\n } else {\n // Otherwise, add the current message to the accumulator\n acc.push(message);\n }\n return acc; // Return the accumulator for the next iteration\n },\n [],\n );\n\n // Update the state with the filtered messages\n setMessages(filteredMessages);\n }\n }\n\n if (\n // if we have client side results\n Object.values(results).length ||\n // or the last message we received is a result\n (newMessages.length && newMessages[newMessages.length - 1] instanceof ResultMessage)\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletion([...previousMessages, ...newMessages]);\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletion(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (isLoading) {\n return;\n }\n\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage instanceof TextMessage && lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * <Tabs items={[\"Copilot Cloud (Recommended)\", \"Self-hosted Runtime\"]}>\n * <Tabs.Tab>\n *\n * You can get your Copilot Cloud API key for free by <LinkToCopilotCloud>signing up here</LinkToCopilotCloud>.\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit publicApiKey=\"<your-public-api-key>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n * </Tabs.Tab>\n *\n * <Tabs.Tab>\n * You can find more information about self-hosting CopilotKit [here](/concepts/copilot-runtime).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n * </Tabs.Tab>\n * </Tabs>\n */\nimport { useCallback, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n InChatRenderFunction,\n ChatComponentsCache,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n} from \"@copilotkit/shared\";\nimport { AgentStateMessage, Message } from \"@copilotkit/runtime-client-gql\";\n\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CopilotChatUI } from \"../../hooks/use-copilot-chat-ui\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n if (!props.runtimeUrl && !props.publicApiKey) {\n throw new Error(\n \"Please provide either a runtimeUrl or a publicApiKey to the CopilotKit component.\",\n );\n }\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const chatComponentsCache = useRef<ChatComponentsCache>({ actions: {}, chatUI: {} });\n const { addElement, removeElement, printTree } = useTree();\n const [messages, setMessages] = useState<Message[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n if (!props.publicApiKey) {\n if (props.cloudRestrictToTopic) {\n throw new Error(\n \"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide a publicApiKey.\",\n );\n }\n }\n\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n };\n\n const removeChatSuggestionConfiguration = (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n };\n\n const [agentStates, setAgentStates] = useState<Record<string, AgentStateMessage | null>>({});\n\n const [chatUI, setChatUI] = useState<CopilotChatUI[]>([]);\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n showDevConsole: props.showDevConsole === undefined ? \"auto\" : props.showDevConsole,\n agentStates,\n setAgentStates,\n chatUI,\n setChatUI,\n }}\n >\n {children}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ messages, name, args }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,6BAAkC;;;ACGlC,mBAAkB;AA6HlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,QAAQ,CAAC,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,aAAa,aAAc,SAAsBA,aAAY,IAAI;AAE1E,YAAM,wBAAwB,CAAC,GAAG,eAAe,EAC9C,QAAQ,EACR,KAAK,CAAC,YAA0C,mBAAmB,4CAAiB;AAEvF,YAAM,oBAAoB,IAAI,6CAAkB;AAAA,QAC9C;AAAA,QACA,UAAU,sBAAsB;AAAA,QAChC,OAAO;AAAA,QACP,SAAS,sBAAsB;AAAA,QAC/B,UAAU,sBAAsB;AAAA,QAChC,MAAM,sBAAsB;AAAA,MAC9B,CAAC;AAED,kBAAY,CAAC,GAAG,iBAAiB,iBAAiB,CAAC;AAEnD,aAAO,iCACF,kBADE;AAAA,QAEL,CAAC,SAAS,GAAG;AAAA,MACf;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,eAAe,YAAY,SAAS;AAE1C,SAAO;AAAA,IACL,6CAAc;AAAA,IACd;AAAA,IACA,eAAe,EAAE,UAAU,aAAa,SAAS,IAAI;AAAA,EACvD;AACF;AAEA,IAAO,0BAAQ;","names":["import_runtime_client_gql","React","import_react","import_runtime_client_gql","import_react","messages","import_react","import_shared","currentState"]}
@@ -1,19 +0,0 @@
1
- import {
2
- useAgentState,
3
- use_agent_state_default
4
- } from "../chunk-A47L32JN.mjs";
5
- import "../chunk-DZH3HSXW.mjs";
6
- import "../chunk-JD7BAH7U.mjs";
7
- import "../chunk-SPCZTZCY.mjs";
8
- import "../chunk-IF6P5ZXR.mjs";
9
- import "../chunk-5FHSUKQL.mjs";
10
- import "../chunk-6U3UH3KO.mjs";
11
- import "../chunk-VNRDQJXW.mjs";
12
- import "../chunk-DB4VWZ5Q.mjs";
13
- import "../chunk-52M7642J.mjs";
14
- import "../chunk-SKC7AJIV.mjs";
15
- export {
16
- use_agent_state_default as default,
17
- useAgentState
18
- };
19
- //# sourceMappingURL=use-agent-state.mjs.map
@@ -1,13 +0,0 @@
1
- interface UseCopilotChatUIRenderProps<S = any> {
2
- state: S;
3
- nodeName: string;
4
- agentName: string;
5
- }
6
- interface CopilotChatUI<S = any> {
7
- agentName: string;
8
- nodeName?: string;
9
- render: string | ((props: UseCopilotChatUIRenderProps<S>) => string | React.ReactElement);
10
- }
11
- declare function useCopilotChatUI<S = any>(chatUI: CopilotChatUI<S>, dependencies?: any[]): void;
12
-
13
- export { CopilotChatUI, UseCopilotChatUIRenderProps, useCopilotChatUI };
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/hooks/use-copilot-chat-ui.ts","../../src/context/copilot-context.tsx"],"sourcesContent":["import { randomId } from \"@copilotkit/shared\";\nimport { useCopilotContext } from \"../context\";\nimport { useEffect, useRef } from \"react\";\n\nexport interface UseCopilotChatUIRenderProps<S = any> {\n state: S;\n nodeName: string;\n agentName: string;\n}\n\nexport interface CopilotChatUI<S = any> {\n agentName: string;\n nodeName?: string;\n render: string | ((props: UseCopilotChatUIRenderProps<S>) => string | React.ReactElement);\n}\n\nexport function useCopilotChatUI<S = any>(chatUI: CopilotChatUI<S>, dependencies?: any[]) {\n const { chatUI: chatUIFromContext, setChatUI } = useCopilotContext();\n\n useEffect(() => {\n setChatUI([...chatUIFromContext, chatUI]);\n return () => {\n setChatUI(chatUIFromContext.filter((ui) => ui !== chatUI));\n };\n }, [chatUI.agentName, chatUI.nodeName, setChatUI]);\n}\n","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { AgentStateMessage, 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 { CopilotChatUI } from \"../hooks/use-copilot-chat-ui\";\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;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n chatUI: Record<string, Function | 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 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 // agent states\n agentStates: Record<string, AgentStateMessage | null>;\n setAgentStates: React.Dispatch<React.SetStateAction<Record<string, AgentStateMessage | null>>>;\n\n // chat ui\n chatUI: CopilotChatUI[];\n setChatUI: React.Dispatch<React.SetStateAction<CopilotChatUI[]>>;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n chatComponentsCache: { current: { actions: {}, chatUI: {} } },\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 agentStates: {},\n setAgentStates: () => {},\n chatUI: [],\n setChatUI: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\n}\n\nfunction returnAndThrowInDebug<T>(value: T): T {\n throw new Error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;AAAA,EAChB,aAAa,CAAC;AAAA,EACd,gBAAgB,MAAM;AAAA,EAAC;AAAA,EACvB,QAAQ,CAAC;AAAA,EACT,WAAW,MAAM;AAAA,EAAC;AACpB;AAEO,IAAM,iBAAiB,aAAAA,QAAM,cAAoC,mBAAmB;AAEpF,SAAS,oBAA0C;AACxD,SAAO,aAAAA,QAAM,WAAW,cAAc;AACxC;AAEA,SAAS,sBAAyB,OAAa;AAC7C,QAAM,IAAI,MAAM,uEAAuE;AACvF,SAAO;AACT;;;ADxLA,IAAAC,gBAAkC;AAc3B,SAAS,iBAA0B,QAA0B,cAAsB;AACxF,QAAM,EAAE,QAAQ,mBAAmB,UAAU,IAAI,kBAAkB;AAEnE,+BAAU,MAAM;AACd,cAAU,CAAC,GAAG,mBAAmB,MAAM,CAAC;AACxC,WAAO,MAAM;AACX,gBAAU,kBAAkB,OAAO,CAAC,OAAO,OAAO,MAAM,CAAC;AAAA,IAC3D;AAAA,EACF,GAAG,CAAC,OAAO,WAAW,OAAO,UAAU,SAAS,CAAC;AACnD;","names":["React","import_react"]}
@@ -1,10 +0,0 @@
1
- import {
2
- useCopilotChatUI
3
- } from "../chunk-6YOQY4WD.mjs";
4
- import "../chunk-VNRDQJXW.mjs";
5
- import "../chunk-DB4VWZ5Q.mjs";
6
- import "../chunk-SKC7AJIV.mjs";
7
- export {
8
- useCopilotChatUI
9
- };
10
- //# sourceMappingURL=use-copilot-chat-ui.mjs.map