@copilotkit/react-core 1.9.3-next.4 → 1.10.0-next.0
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.
- package/CHANGELOG.md +38 -0
- package/dist/chunk-2IDV5OHF.mjs +11 -0
- package/dist/chunk-2IDV5OHF.mjs.map +1 -0
- package/dist/{chunk-36MGCCPZ.mjs → chunk-4CFY3CON.mjs} +2 -2
- package/dist/{chunk-BVK7PLK6.mjs → chunk-DF4YG4PF.mjs} +2 -2
- package/dist/{chunk-ELU3VLPJ.mjs → chunk-G35QHAQ6.mjs} +8 -8
- package/dist/chunk-G35QHAQ6.mjs.map +1 -0
- package/dist/{chunk-DNHCRVE6.mjs → chunk-LIGLZ53V.mjs} +98 -26
- package/dist/chunk-LIGLZ53V.mjs.map +1 -0
- package/dist/{chunk-5BSUSFHM.mjs → chunk-LNAQ7JG3.mjs} +2 -2
- package/dist/{chunk-NJA5ZLAZ.mjs → chunk-LU5JPZ24.mjs} +2 -2
- package/dist/{chunk-GIMSRCVW.mjs → chunk-NAM55D5I.mjs} +153 -14
- package/dist/chunk-NAM55D5I.mjs.map +1 -0
- package/dist/{chunk-CUAFWKTQ.mjs → chunk-O5KV32S5.mjs} +4 -4
- package/dist/{chunk-FN3UA2ZE.mjs → chunk-PZXTDFMX.mjs} +3 -3
- package/dist/{chunk-VDADWRS3.mjs → chunk-Q6FZZJ5A.mjs} +2 -2
- package/dist/{chunk-KIXKBJUV.mjs → chunk-RGKZCCPA.mjs} +2 -2
- package/dist/{chunk-SGF6C7I6.mjs → chunk-SJJNFYGQ.mjs} +4 -4
- package/dist/{chunk-DKZTPL66.mjs → chunk-XGRBCWK6.mjs} +5 -2
- package/dist/chunk-XGRBCWK6.mjs.map +1 -0
- package/dist/{chunk-BSAVFYRQ.mjs → chunk-YBDRISKO.mjs} +5 -5
- package/dist/{chunk-QPX2JKOR.mjs → chunk-YSQ5I2AE.mjs} +6 -6
- package/dist/chunk-YSQ5I2AE.mjs.map +1 -0
- package/dist/{chunk-5B3NSTQK.mjs → chunk-YVBDAURK.mjs} +3 -3
- package/dist/components/copilot-provider/copilot-messages.js +4 -1
- package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
- package/dist/components/copilot-provider/copilot-messages.mjs +3 -3
- package/dist/components/copilot-provider/copilotkit-props.d.ts +2 -1
- package/dist/components/copilot-provider/copilotkit.d.ts +2 -1
- package/dist/components/copilot-provider/copilotkit.js +8 -2
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +10 -9
- package/dist/components/copilot-provider/index.d.ts +2 -1
- package/dist/components/copilot-provider/index.js +8 -2
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +10 -9
- package/dist/components/error-boundary/error-boundary.mjs +2 -2
- package/dist/components/index.d.ts +2 -1
- package/dist/components/index.js +8 -2
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +10 -9
- package/dist/context/copilot-context.d.ts +2 -1
- package/dist/context/copilot-context.js +4 -1
- package/dist/context/copilot-context.js.map +1 -1
- package/dist/context/copilot-context.mjs +1 -1
- package/dist/context/index.d.ts +1 -1
- package/dist/context/index.js +4 -1
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +4 -4
- package/dist/{copilot-context-3ab4fdf5.d.ts → copilot-context-bd88d30d.d.ts} +21 -1
- package/dist/hooks/index.d.ts +5 -5
- package/dist/hooks/index.js +493 -154
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +32 -31
- package/dist/hooks/use-chat.d.ts +6 -1
- package/dist/hooks/use-chat.js +5 -2
- package/dist/hooks/use-chat.js.map +1 -1
- package/dist/hooks/use-chat.mjs +4 -4
- package/dist/hooks/use-coagent-state-render.js +4 -1
- package/dist/hooks/use-coagent-state-render.js.map +1 -1
- package/dist/hooks/use-coagent-state-render.mjs +2 -2
- package/dist/hooks/use-coagent.d.ts +3 -3
- package/dist/hooks/use-coagent.js +427 -45
- package/dist/hooks/use-coagent.js.map +1 -1
- package/dist/hooks/use-coagent.mjs +16 -14
- package/dist/hooks/use-copilot-action.js +4 -1
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +2 -2
- package/dist/hooks/use-copilot-additional-instructions.js +4 -1
- package/dist/hooks/use-copilot-additional-instructions.js.map +1 -1
- package/dist/hooks/use-copilot-additional-instructions.mjs +2 -2
- package/dist/hooks/use-copilot-authenticated-action.js +4 -1
- package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
- package/dist/hooks/use-copilot-authenticated-action.mjs +3 -3
- package/dist/hooks/use-copilot-chat.d.ts +43 -6
- package/dist/hooks/use-copilot-chat.js +443 -65
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +15 -13
- package/dist/hooks/use-copilot-readable.js +4 -1
- package/dist/hooks/use-copilot-readable.js.map +1 -1
- package/dist/hooks/use-copilot-readable.mjs +2 -2
- package/dist/hooks/use-langgraph-interrupt-render.js +4 -1
- package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -1
- package/dist/hooks/use-langgraph-interrupt-render.mjs +2 -2
- package/dist/hooks/use-langgraph-interrupt.d.ts +4 -3
- package/dist/hooks/use-langgraph-interrupt.js +452 -72
- package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
- package/dist/hooks/use-langgraph-interrupt.mjs +16 -14
- package/dist/hooks/use-make-copilot-document-readable.js +4 -1
- package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
- package/dist/index.d.ts +2 -1
- package/dist/index.js +422 -201
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +42 -36
- package/dist/lib/copilot-task.d.ts +2 -1
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +12 -11
- package/dist/lib/index.d.ts +2 -1
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +12 -11
- package/dist/types/interrupt-action.d.ts +3 -2
- package/dist/utils/extract.d.ts +1 -1
- package/dist/utils/extract.js.map +1 -1
- package/dist/utils/extract.mjs +10 -9
- package/dist/utils/index.d.ts +4 -3
- package/dist/utils/index.js +144 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +16 -10
- package/dist/utils/suggestions-constants.d.ts +9 -0
- package/dist/utils/suggestions-constants.js +35 -0
- package/dist/utils/suggestions-constants.js.map +1 -0
- package/dist/utils/suggestions-constants.mjs +8 -0
- package/dist/utils/suggestions-constants.mjs.map +1 -0
- package/dist/utils/suggestions.d.ts +11 -0
- package/dist/utils/suggestions.js +343 -0
- package/dist/utils/suggestions.js.map +1 -0
- package/dist/utils/suggestions.mjs +22 -0
- package/dist/utils/suggestions.mjs.map +1 -0
- package/package.json +3 -3
- package/src/components/copilot-provider/copilotkit.tsx +4 -0
- package/src/context/copilot-context.tsx +6 -0
- package/src/hooks/use-chat.ts +6 -2
- package/src/hooks/use-coagent.ts +1 -1
- package/src/hooks/use-copilot-chat.ts +197 -21
- package/src/utils/index.ts +3 -0
- package/src/utils/suggestions-constants.ts +8 -0
- package/src/utils/suggestions.ts +208 -0
- package/dist/chunk-DKZTPL66.mjs.map +0 -1
- package/dist/chunk-DNHCRVE6.mjs.map +0 -1
- package/dist/chunk-ELU3VLPJ.mjs.map +0 -1
- package/dist/chunk-GIMSRCVW.mjs.map +0 -1
- package/dist/chunk-QPX2JKOR.mjs.map +0 -1
- /package/dist/{chunk-36MGCCPZ.mjs.map → chunk-4CFY3CON.mjs.map} +0 -0
- /package/dist/{chunk-BVK7PLK6.mjs.map → chunk-DF4YG4PF.mjs.map} +0 -0
- /package/dist/{chunk-5BSUSFHM.mjs.map → chunk-LNAQ7JG3.mjs.map} +0 -0
- /package/dist/{chunk-NJA5ZLAZ.mjs.map → chunk-LU5JPZ24.mjs.map} +0 -0
- /package/dist/{chunk-CUAFWKTQ.mjs.map → chunk-O5KV32S5.mjs.map} +0 -0
- /package/dist/{chunk-FN3UA2ZE.mjs.map → chunk-PZXTDFMX.mjs.map} +0 -0
- /package/dist/{chunk-VDADWRS3.mjs.map → chunk-Q6FZZJ5A.mjs.map} +0 -0
- /package/dist/{chunk-KIXKBJUV.mjs.map → chunk-RGKZCCPA.mjs.map} +0 -0
- /package/dist/{chunk-SGF6C7I6.mjs.map → chunk-SJJNFYGQ.mjs.map} +0 -0
- /package/dist/{chunk-BSAVFYRQ.mjs.map → chunk-YBDRISKO.mjs.map} +0 -0
- /package/dist/{chunk-5B3NSTQK.mjs.map → chunk-YVBDAURK.mjs.map} +0 -0
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __defProps = Object.defineProperties;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
8
|
+
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
|
+
var __export = (target, all) => {
|
|
24
|
+
for (var name in all)
|
|
25
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
26
|
+
};
|
|
27
|
+
var __copyProps = (to, from, except, desc) => {
|
|
28
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
29
|
+
for (let key of __getOwnPropNames(from))
|
|
30
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
31
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
32
|
+
}
|
|
33
|
+
return to;
|
|
34
|
+
};
|
|
35
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
36
|
+
var __async = (__this, __arguments, generator) => {
|
|
37
|
+
return new Promise((resolve, reject) => {
|
|
38
|
+
var fulfilled = (value) => {
|
|
39
|
+
try {
|
|
40
|
+
step(generator.next(value));
|
|
41
|
+
} catch (e) {
|
|
42
|
+
reject(e);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
var rejected = (value) => {
|
|
46
|
+
try {
|
|
47
|
+
step(generator.throw(value));
|
|
48
|
+
} catch (e) {
|
|
49
|
+
reject(e);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
53
|
+
step((generator = generator.apply(__this, __arguments)).next());
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// src/utils/suggestions.ts
|
|
58
|
+
var suggestions_exports = {};
|
|
59
|
+
__export(suggestions_exports, {
|
|
60
|
+
reloadSuggestions: () => reloadSuggestions
|
|
61
|
+
});
|
|
62
|
+
module.exports = __toCommonJS(suggestions_exports);
|
|
63
|
+
|
|
64
|
+
// src/utils/extract.ts
|
|
65
|
+
var import_shared2 = require("@copilotkit/shared");
|
|
66
|
+
var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
|
|
67
|
+
|
|
68
|
+
// src/components/copilot-provider/copilotkit.tsx
|
|
69
|
+
var import_react = require("react");
|
|
70
|
+
var import_react_dom = require("react-dom");
|
|
71
|
+
var import_shared = require("@copilotkit/shared");
|
|
72
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
73
|
+
var defaultCopilotContextCategories = ["global"];
|
|
74
|
+
|
|
75
|
+
// src/utils/extract.ts
|
|
76
|
+
var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
|
|
77
|
+
function extract(_0) {
|
|
78
|
+
return __async(this, arguments, function* ({
|
|
79
|
+
context,
|
|
80
|
+
instructions,
|
|
81
|
+
parameters,
|
|
82
|
+
include,
|
|
83
|
+
data,
|
|
84
|
+
abortSignal,
|
|
85
|
+
stream,
|
|
86
|
+
requestType = import_runtime_client_gql.CopilotRequestType.Task,
|
|
87
|
+
forwardedParameters
|
|
88
|
+
}) {
|
|
89
|
+
var _a, _b;
|
|
90
|
+
const { messages } = context;
|
|
91
|
+
const action = {
|
|
92
|
+
name: "extract",
|
|
93
|
+
description: instructions,
|
|
94
|
+
parameters,
|
|
95
|
+
handler: (args) => {
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
const includeReadable = (_a = include == null ? void 0 : include.readable) != null ? _a : false;
|
|
99
|
+
const includeMessages = (_b = include == null ? void 0 : include.messages) != null ? _b : false;
|
|
100
|
+
let contextString = "";
|
|
101
|
+
if (data) {
|
|
102
|
+
contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
|
|
103
|
+
}
|
|
104
|
+
if (includeReadable) {
|
|
105
|
+
contextString += context.getContextString([], defaultCopilotContextCategories);
|
|
106
|
+
}
|
|
107
|
+
const systemMessage = new import_runtime_client_gql.TextMessage({
|
|
108
|
+
content: makeSystemMessage(contextString, instructions),
|
|
109
|
+
role: import_runtime_client_gql.Role.System
|
|
110
|
+
});
|
|
111
|
+
const instructionsMessage = new import_runtime_client_gql.TextMessage({
|
|
112
|
+
content: makeInstructionsMessage(instructions),
|
|
113
|
+
role: import_runtime_client_gql.Role.User
|
|
114
|
+
});
|
|
115
|
+
const response = context.runtimeClient.asStream(
|
|
116
|
+
context.runtimeClient.generateCopilotResponse({
|
|
117
|
+
data: {
|
|
118
|
+
frontend: {
|
|
119
|
+
actions: [
|
|
120
|
+
{
|
|
121
|
+
name: action.name,
|
|
122
|
+
description: action.description || "",
|
|
123
|
+
jsonSchema: JSON.stringify((0, import_shared2.actionParametersToJsonSchema)(action.parameters || []))
|
|
124
|
+
}
|
|
125
|
+
],
|
|
126
|
+
url: window.location.href
|
|
127
|
+
},
|
|
128
|
+
messages: (0, import_runtime_client_gql2.convertMessagesToGqlInput)(
|
|
129
|
+
includeMessages ? [systemMessage, instructionsMessage, ...(0, import_runtime_client_gql2.filterAgentStateMessages)(messages)] : [systemMessage, instructionsMessage]
|
|
130
|
+
),
|
|
131
|
+
metadata: {
|
|
132
|
+
requestType
|
|
133
|
+
},
|
|
134
|
+
forwardedParameters: __spreadProps(__spreadValues({}, forwardedParameters != null ? forwardedParameters : {}), {
|
|
135
|
+
toolChoice: "function",
|
|
136
|
+
toolChoiceFunctionName: action.name
|
|
137
|
+
})
|
|
138
|
+
},
|
|
139
|
+
properties: context.copilotApiConfig.properties,
|
|
140
|
+
signal: abortSignal
|
|
141
|
+
})
|
|
142
|
+
);
|
|
143
|
+
const reader = response.getReader();
|
|
144
|
+
let isInitial = true;
|
|
145
|
+
let actionExecutionMessage = void 0;
|
|
146
|
+
while (true) {
|
|
147
|
+
const { done, value } = yield reader.read();
|
|
148
|
+
if (done) {
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
if (abortSignal == null ? void 0 : abortSignal.aborted) {
|
|
152
|
+
throw new Error("Aborted");
|
|
153
|
+
}
|
|
154
|
+
actionExecutionMessage = (0, import_runtime_client_gql.convertGqlOutputToMessages)(
|
|
155
|
+
value.generateCopilotResponse.messages
|
|
156
|
+
).find((msg) => msg.isActionExecutionMessage());
|
|
157
|
+
if (!actionExecutionMessage) {
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
stream == null ? void 0 : stream({
|
|
161
|
+
status: isInitial ? "initial" : "inProgress",
|
|
162
|
+
args: actionExecutionMessage.arguments
|
|
163
|
+
});
|
|
164
|
+
isInitial = false;
|
|
165
|
+
}
|
|
166
|
+
if (!actionExecutionMessage) {
|
|
167
|
+
throw new Error("extract() failed: No function call occurred");
|
|
168
|
+
}
|
|
169
|
+
stream == null ? void 0 : stream({
|
|
170
|
+
status: "complete",
|
|
171
|
+
args: actionExecutionMessage.arguments
|
|
172
|
+
});
|
|
173
|
+
return actionExecutionMessage.arguments;
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
function makeInstructionsMessage(instructions) {
|
|
177
|
+
return `
|
|
178
|
+
The user has given you the following task to complete:
|
|
179
|
+
|
|
180
|
+
\`\`\`
|
|
181
|
+
${instructions}
|
|
182
|
+
\`\`\`
|
|
183
|
+
|
|
184
|
+
Any additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.
|
|
185
|
+
`;
|
|
186
|
+
}
|
|
187
|
+
function makeSystemMessage(contextString, instructions) {
|
|
188
|
+
return `
|
|
189
|
+
Please act as an efficient, competent, conscientious, and industrious professional assistant.
|
|
190
|
+
|
|
191
|
+
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.
|
|
192
|
+
Always be polite and respectful, and prefer brevity over verbosity.
|
|
193
|
+
|
|
194
|
+
The user has provided you with the following context:
|
|
195
|
+
\`\`\`
|
|
196
|
+
${contextString}
|
|
197
|
+
\`\`\`
|
|
198
|
+
|
|
199
|
+
They have also provided you with a function called extract you MUST call to initiate actions on their behalf.
|
|
200
|
+
|
|
201
|
+
Please assist them as best you can.
|
|
202
|
+
|
|
203
|
+
This is not a conversation, so please do not ask questions. Just call the function without saying anything else.
|
|
204
|
+
`;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// src/utils/suggestions.ts
|
|
208
|
+
var import_shared3 = require("@copilotkit/shared");
|
|
209
|
+
var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
|
|
210
|
+
var reloadSuggestions = (context, chatSuggestionConfiguration, setCurrentSuggestions, abortControllerRef) => __async(void 0, null, function* () {
|
|
211
|
+
const abortController = abortControllerRef.current;
|
|
212
|
+
if (abortController == null ? void 0 : abortController.signal.aborted) {
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
const setSuggestionsIfNotAborted = (suggestions) => {
|
|
216
|
+
if (!(abortController == null ? void 0 : abortController.signal.aborted) && abortControllerRef.current === abortController) {
|
|
217
|
+
setCurrentSuggestions(suggestions);
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
try {
|
|
221
|
+
const tools = JSON.stringify(
|
|
222
|
+
Object.values(context.actions).map((action) => ({
|
|
223
|
+
name: action.name,
|
|
224
|
+
description: action.description,
|
|
225
|
+
jsonSchema: JSON.stringify((0, import_shared3.actionParametersToJsonSchema)(action.parameters))
|
|
226
|
+
}))
|
|
227
|
+
);
|
|
228
|
+
const allSuggestions = [];
|
|
229
|
+
let hasSuccessfulSuggestions = false;
|
|
230
|
+
let hasErrors = false;
|
|
231
|
+
let lastError = null;
|
|
232
|
+
const enabledConfigs = Object.values(chatSuggestionConfiguration).filter(
|
|
233
|
+
(config) => config.instructions && config.instructions.trim().length > 0
|
|
234
|
+
);
|
|
235
|
+
if (enabledConfigs.length === 0) {
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
setSuggestionsIfNotAborted([]);
|
|
239
|
+
for (const config of enabledConfigs) {
|
|
240
|
+
if (abortController == null ? void 0 : abortController.signal.aborted) {
|
|
241
|
+
setSuggestionsIfNotAborted([]);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
try {
|
|
245
|
+
const result = yield extract({
|
|
246
|
+
context,
|
|
247
|
+
instructions: "Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls. ",
|
|
248
|
+
data: `${config.instructions}
|
|
249
|
+
|
|
250
|
+
Available tools: ${tools}
|
|
251
|
+
|
|
252
|
+
`,
|
|
253
|
+
requestType: import_runtime_client_gql3.CopilotRequestType.Task,
|
|
254
|
+
parameters: [
|
|
255
|
+
{
|
|
256
|
+
name: "suggestions",
|
|
257
|
+
type: "object[]",
|
|
258
|
+
attributes: [
|
|
259
|
+
{
|
|
260
|
+
name: "title",
|
|
261
|
+
description: "The title of the suggestion. This is shown as a button and should be short.",
|
|
262
|
+
type: "string"
|
|
263
|
+
},
|
|
264
|
+
{
|
|
265
|
+
name: "message",
|
|
266
|
+
description: "The message to send when the suggestion is clicked. This should be a clear, complete sentence and will be sent as an instruction to the AI.",
|
|
267
|
+
type: "string"
|
|
268
|
+
}
|
|
269
|
+
]
|
|
270
|
+
}
|
|
271
|
+
],
|
|
272
|
+
include: {
|
|
273
|
+
messages: true,
|
|
274
|
+
readable: true
|
|
275
|
+
},
|
|
276
|
+
abortSignal: abortController == null ? void 0 : abortController.signal,
|
|
277
|
+
stream: ({ status, args }) => {
|
|
278
|
+
if (abortController == null ? void 0 : abortController.signal.aborted) {
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
const suggestions = args.suggestions || [];
|
|
282
|
+
const newSuggestions = [];
|
|
283
|
+
for (let i = 0; i < suggestions.length; i++) {
|
|
284
|
+
if (config.maxSuggestions !== void 0 && i >= config.maxSuggestions) {
|
|
285
|
+
break;
|
|
286
|
+
}
|
|
287
|
+
const suggestion = suggestions[i];
|
|
288
|
+
if (!suggestion || typeof suggestion !== "object") {
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
const { title, message } = suggestion;
|
|
292
|
+
const hasValidTitle = title && typeof title === "string" && title.trim().length > 0;
|
|
293
|
+
const hasValidMessage = message && typeof message === "string" && message.trim().length > 0;
|
|
294
|
+
if (!hasValidTitle) {
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
const partial = i === suggestions.length - 1 && status !== "complete";
|
|
298
|
+
newSuggestions.push({
|
|
299
|
+
title: title.trim(),
|
|
300
|
+
message: hasValidMessage ? message.trim() : "",
|
|
301
|
+
// Use title as fallback
|
|
302
|
+
partial,
|
|
303
|
+
className: config.className
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
setSuggestionsIfNotAborted([...allSuggestions, ...newSuggestions]);
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
if ((result == null ? void 0 : result.suggestions) && Array.isArray(result.suggestions)) {
|
|
310
|
+
const validSuggestions = result.suggestions.filter(
|
|
311
|
+
(suggestion) => suggestion && typeof suggestion.title === "string" && suggestion.title.trim().length > 0
|
|
312
|
+
).map((suggestion) => ({
|
|
313
|
+
title: suggestion.title.trim(),
|
|
314
|
+
message: suggestion.message && typeof suggestion.message === "string" && suggestion.message.trim() ? suggestion.message.trim() : suggestion.title.trim()
|
|
315
|
+
}));
|
|
316
|
+
if (validSuggestions.length > 0) {
|
|
317
|
+
allSuggestions.push(...validSuggestions);
|
|
318
|
+
hasSuccessfulSuggestions = true;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
} catch (error) {
|
|
322
|
+
hasErrors = true;
|
|
323
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
if (hasSuccessfulSuggestions && allSuggestions.length > 0) {
|
|
327
|
+
const uniqueSuggestions = allSuggestions.filter(
|
|
328
|
+
(suggestion, index, self) => index === self.findIndex((s) => s.message === suggestion.message)
|
|
329
|
+
);
|
|
330
|
+
setSuggestionsIfNotAborted(uniqueSuggestions);
|
|
331
|
+
} else if (hasErrors) {
|
|
332
|
+
const errorMessage = lastError ? lastError.message : "Failed to generate suggestions due to API errors";
|
|
333
|
+
throw new Error(errorMessage);
|
|
334
|
+
}
|
|
335
|
+
} catch (error) {
|
|
336
|
+
throw error;
|
|
337
|
+
}
|
|
338
|
+
});
|
|
339
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
340
|
+
0 && (module.exports = {
|
|
341
|
+
reloadSuggestions
|
|
342
|
+
});
|
|
343
|
+
//# sourceMappingURL=suggestions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/suggestions.ts","../../src/utils/extract.ts","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["/**\n * Suggestions utility functions for CopilotKit\n *\n * This module handles the generation of chat suggestions with optimized error handling\n * and streaming validation to prevent infinite retry loops and console spam.\n */\n\nimport { extract } from \"./extract\";\nimport { actionParametersToJsonSchema } from \"@copilotkit/shared\";\nimport { CopilotRequestType } from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { CopilotChatSuggestionConfiguration } from \"../types\";\n\nexport interface SuggestionItem {\n title: string;\n message: string;\n partial?: boolean;\n className?: string;\n}\n\nexport const reloadSuggestions = async (\n context: CopilotContextParams & CopilotMessagesContextParams,\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration },\n setCurrentSuggestions: (suggestions: SuggestionItem[]) => void,\n abortControllerRef: React.MutableRefObject<AbortController | null>,\n): Promise<void> => {\n const abortController = abortControllerRef.current;\n\n // Early abort check\n if (abortController?.signal.aborted) {\n return;\n }\n\n // Abort-aware suggestion setter with safety checks to prevent race conditions\n const setSuggestionsIfNotAborted = (suggestions: SuggestionItem[]) => {\n if (!abortController?.signal.aborted && abortControllerRef.current === abortController) {\n setCurrentSuggestions(suggestions);\n }\n };\n\n try {\n const tools = JSON.stringify(\n Object.values(context.actions).map((action) => ({\n name: action.name,\n description: action.description,\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n })),\n );\n\n const allSuggestions: SuggestionItem[] = [];\n let hasSuccessfulSuggestions = false;\n let hasErrors = false; // Track if any errors occurred\n let lastError: Error | null = null; // Track the last error for better error reporting\n\n // Get enabled configurations\n const enabledConfigs = Object.values(chatSuggestionConfiguration).filter(\n (config) => config.instructions && config.instructions.trim().length > 0,\n );\n\n if (enabledConfigs.length === 0) {\n return;\n }\n\n // Clear existing suggestions\n setSuggestionsIfNotAborted([]);\n\n // Generate suggestions for each configuration\n for (const config of enabledConfigs) {\n // Check if aborted before each configuration\n if (abortController?.signal.aborted) {\n setSuggestionsIfNotAborted([]);\n return;\n }\n\n try {\n const result = await extract({\n context,\n instructions:\n \"Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls. \",\n data: `${config.instructions}\\n\\nAvailable tools: ${tools}\\n\\n`,\n requestType: CopilotRequestType.Task,\n parameters: [\n {\n name: \"suggestions\",\n type: \"object[]\",\n attributes: [\n {\n name: \"title\",\n description:\n \"The title of the suggestion. This is shown as a button and should be short.\",\n type: \"string\",\n },\n {\n name: \"message\",\n description:\n \"The message to send when the suggestion is clicked. This should be a clear, complete sentence and will be sent as an instruction to the AI.\",\n type: \"string\",\n },\n ],\n },\n ],\n include: {\n messages: true,\n readable: true,\n },\n abortSignal: abortController?.signal,\n stream: ({ status, args }: { status: string; args: any }) => {\n // Check abort status in stream callback\n if (abortController?.signal.aborted) {\n return;\n }\n\n const suggestions = args.suggestions || [];\n const newSuggestions: SuggestionItem[] = [];\n\n for (let i = 0; i < suggestions.length; i++) {\n // Respect max suggestions limit\n if (config.maxSuggestions !== undefined && i >= config.maxSuggestions) {\n break;\n }\n\n const suggestion = suggestions[i];\n\n // Skip completely empty or invalid objects during streaming\n if (!suggestion || typeof suggestion !== \"object\") {\n continue;\n }\n\n const { title, message } = suggestion;\n\n // During streaming, be permissive but require at least a meaningful title\n const hasValidTitle = title && typeof title === \"string\" && title.trim().length > 0;\n const hasValidMessage =\n message && typeof message === \"string\" && message.trim().length > 0;\n\n // During streaming, we need at least a title to show something useful\n if (!hasValidTitle) {\n continue;\n }\n\n // Mark as partial if this is the last suggestion and streaming isn't complete\n const partial = i === suggestions.length - 1 && status !== \"complete\";\n\n newSuggestions.push({\n title: title.trim(),\n message: hasValidMessage ? message.trim() : \"\", // Use title as fallback\n partial,\n className: config.className,\n });\n }\n\n // Update suggestions with current batch\n setSuggestionsIfNotAborted([...allSuggestions, ...newSuggestions]);\n },\n });\n\n // Process final results with strict validation\n if (result?.suggestions && Array.isArray(result.suggestions)) {\n const validSuggestions = result.suggestions\n .filter(\n (suggestion: any) =>\n suggestion &&\n typeof suggestion.title === \"string\" &&\n suggestion.title.trim().length > 0,\n )\n .map((suggestion: any) => ({\n title: suggestion.title.trim(),\n message:\n suggestion.message &&\n typeof suggestion.message === \"string\" &&\n suggestion.message.trim()\n ? suggestion.message.trim()\n : suggestion.title.trim(),\n }));\n\n if (validSuggestions.length > 0) {\n allSuggestions.push(...validSuggestions);\n hasSuccessfulSuggestions = true;\n }\n }\n } catch (error) {\n // Simple error handling - just continue with next config, don't log here\n hasErrors = true;\n lastError = error instanceof Error ? error : new Error(String(error));\n }\n }\n\n // Display any successful suggestions we got\n if (hasSuccessfulSuggestions && allSuggestions.length > 0) {\n // Remove duplicates based on message content\n const uniqueSuggestions = allSuggestions.filter(\n (suggestion, index, self) =>\n index === self.findIndex((s) => s.message === suggestion.message),\n );\n\n setSuggestionsIfNotAborted(uniqueSuggestions);\n } else if (hasErrors) {\n // If we had errors but no successful suggestions, throw an error with details\n const errorMessage = lastError\n ? lastError.message\n : \"Failed to generate suggestions due to API errors\";\n throw new Error(errorMessage);\n }\n } catch (error) {\n // Top-level error handler - re-throw to allow caller to handle\n throw error;\n }\n};\n","import {\n Action,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n MappedParameterTypes,\n Parameter,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n ActionExecutionMessage,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams, CopilotMessagesContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CopilotRuntimeClient } from \"@copilotkit/runtime-client-gql\";\nimport {\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n} from \"@copilotkit/runtime-client-gql\";\n\ninterface InitialState<T extends Parameter[] | [] = []> {\n status: \"initial\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n}\n\ntype StreamHandlerArgs<T extends Parameter[] | [] = []> =\n | InitialState<T>\n | InProgressState<T>\n | CompleteState<T>;\n\ninterface ExtractOptions<T extends Parameter[]> {\n context: CopilotContextParams & CopilotMessagesContextParams;\n instructions: string;\n parameters: T;\n include?: IncludeOptions;\n data?: any;\n abortSignal?: AbortSignal;\n stream?: (args: StreamHandlerArgs<T>) => void;\n requestType?: CopilotRequestType;\n forwardedParameters?: ForwardedParametersInput;\n}\n\ninterface IncludeOptions {\n readable?: boolean;\n messages?: boolean;\n}\n\nexport async function extract<const T extends Parameter[]>({\n context,\n instructions,\n parameters,\n include,\n data,\n abortSignal,\n stream,\n requestType = CopilotRequestType.Task,\n forwardedParameters,\n}: ExtractOptions<T>): Promise<MappedParameterTypes<T>> {\n const { messages } = context;\n\n const action: Action<any> = {\n name: \"extract\",\n description: instructions,\n parameters,\n handler: (args: any) => {},\n };\n\n const includeReadable = include?.readable ?? false;\n const includeMessages = include?.messages ?? false;\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (includeReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage: Message = new TextMessage({\n content: makeSystemMessage(contextString, instructions),\n role: Role.System,\n });\n\n const instructionsMessage: Message = new TextMessage({\n content: makeInstructionsMessage(instructions),\n role: Role.User,\n });\n\n const response = context.runtimeClient.asStream(\n context.runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: [\n {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n },\n ],\n url: window.location.href,\n },\n\n messages: convertMessagesToGqlInput(\n includeMessages\n ? [systemMessage, instructionsMessage, ...filterAgentStateMessages(messages)]\n : [systemMessage, instructionsMessage],\n ),\n metadata: {\n requestType: requestType,\n },\n forwardedParameters: {\n ...(forwardedParameters ?? {}),\n toolChoice: \"function\",\n toolChoiceFunctionName: action.name,\n },\n },\n properties: context.copilotApiConfig.properties,\n signal: abortSignal,\n }),\n );\n\n const reader = response.getReader();\n\n let isInitial = true;\n\n let actionExecutionMessage: ActionExecutionMessage | undefined = undefined;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (abortSignal?.aborted) {\n throw new Error(\"Aborted\");\n }\n\n actionExecutionMessage = convertGqlOutputToMessages(\n value.generateCopilotResponse.messages,\n ).find((msg) => msg.isActionExecutionMessage()) as ActionExecutionMessage | undefined;\n\n if (!actionExecutionMessage) {\n continue;\n }\n\n stream?.({\n status: isInitial ? \"initial\" : \"inProgress\",\n args: actionExecutionMessage.arguments as Partial<MappedParameterTypes<T>>,\n });\n\n isInitial = false;\n }\n\n if (!actionExecutionMessage) {\n throw new Error(\"extract() failed: No function call occurred\");\n }\n\n stream?.({\n status: \"complete\",\n args: actionExecutionMessage.arguments as MappedParameterTypes<T>,\n });\n\n return actionExecutionMessage.arguments as MappedParameterTypes<T>;\n}\n\n// We need to put this in a user message since some LLMs need\n// at least one user message to function\nfunction makeInstructionsMessage(instructions: string): string {\n return `\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n\nAny additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.\n`;\n}\n\nfunction makeSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with a function called extract you MUST call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call the function without saying anything else.\n`;\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, SetStateAction } 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 randomUUID,\n ConfigurationError,\n MissingPublicApiKeyError,\n} from \"@copilotkit/shared\";\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, ExtensionsInput } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetterArgs,\n} from \"../../types/interrupt-action\";\nimport { StatusChecker } from \"../../lib/status-checker\";\nimport { SuggestionItem } from \"../../utils/suggestions\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const showDevConsole = props.showDevConsole ?? false;\n const enabled = shouldShowDevConsole(showDevConsole);\n\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary publicApiKey={props.publicApiKey} showUsageBanner={enabled}>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal(cpkProps: CopilotKitProps) {\n const { children, ...props } = cpkProps;\n\n /**\n * This will throw an error if the props are invalid.\n */\n validateProps(cpkProps);\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\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n\n const { addElement, removeElement, printTree, getAllElements } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n const [authStates, setAuthStates] = useState<Record<string, AuthState>>({});\n const [extensions, setExtensions] = useState<ExtensionsInput>({});\n const [additionalInstructions, setAdditionalInstructions] = useState<string[]>([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const statusChecker = useMemo(() => new StatusChecker(), []);\n\n const [usageBannerStatus, setUsageBannerStatus] = useState<any>(null);\n\n // Compute all the functions and properties that we need to pass\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 getAllContext = useCallback(() => {\n return getAllElements();\n }, [getAllElements]);\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 // 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: Boolean(props.guardrails_c),\n validTopics: props.guardrails_c?.validTopics || [],\n invalidTopics: props.guardrails_c?.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 props.guardrails_c,\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 showDevConsole: props.showDevConsole ?? false,\n onError: props.onError,\n });\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = useCallback(\n (id: string, suggestion: CopilotChatSuggestionConfiguration) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n },\n [setChatSuggestionConfiguration],\n );\n\n const removeChatSuggestionConfiguration = useCallback(\n (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n },\n [setChatSuggestionConfiguration],\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 const hasLoadedAgents = useRef(false);\n\n useEffect(() => {\n if (hasLoadedAgents.current) return;\n\n const fetchData = async () => {\n const result = await runtimeClient.availableAgents();\n if (result.data?.availableAgents) {\n setAvailableAgents(result.data.availableAgents.agents);\n }\n hasLoadedAgents.current = true;\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\n // Update agentSession when props.agent changes\n useEffect(() => {\n if (props.agent) {\n setAgentSession({\n agentName: props.agent,\n });\n } else {\n setAgentSession(null);\n }\n }, [props.agent]);\n\n const [internalThreadId, setInternalThreadId] = useState<string>(props.threadId || randomUUID());\n const setThreadId = useCallback(\n (value: SetStateAction<string>) => {\n if (props.threadId) {\n throw new Error(\"Cannot call setThreadId() when threadId is provided via props.\");\n }\n setInternalThreadId(value);\n },\n [props.threadId],\n );\n\n // update the internal threadId if the props.threadId changes\n useEffect(() => {\n if (props.threadId !== undefined) {\n setInternalThreadId(props.threadId);\n }\n }, [props.threadId]);\n\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = props.showDevConsole ?? false;\n\n const [langGraphInterruptAction, _setLangGraphInterruptAction] =\n useState<LangGraphInterruptAction | null>(null);\n const setLangGraphInterruptAction = useCallback((action: LangGraphInterruptActionSetterArgs) => {\n _setLangGraphInterruptAction((prev) => {\n if (prev == null) return action as LangGraphInterruptAction;\n if (action == null) return null;\n let event = prev.event;\n if (action.event) {\n // @ts-ignore\n event = { ...prev.event, ...action.event };\n }\n return { ...prev, ...action, event };\n });\n }, []);\n const removeLangGraphInterruptAction = useCallback((): void => {\n setLangGraphInterruptAction(null);\n }, []);\n\n const memoizedChildren = useMemo(() => children, [children]);\n const [suggestions, setSuggestions] = useState<SuggestionItem[]>([]);\n\n const agentLock = useMemo(() => props.agent ?? null, [props.agent]);\n\n const forwardedParameters = useMemo(\n () => props.forwardedParameters ?? {},\n [props.forwardedParameters],\n );\n\n const updateExtensions = useCallback(\n (newExtensions: SetStateAction<ExtensionsInput>) => {\n setExtensions((prev: ExtensionsInput) => {\n const resolved = typeof newExtensions === \"function\" ? newExtensions(prev) : newExtensions;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setExtensions],\n );\n\n const updateAuthStates = useCallback(\n (newAuthStates: SetStateAction<Record<string, AuthState>>) => {\n setAuthStates((prev) => {\n const resolved = typeof newAuthStates === \"function\" ? newAuthStates(prev) : newAuthStates;\n const isSameLength = Object.keys(resolved).length === Object.keys(prev).length;\n const isEqual =\n isSameLength &&\n // @ts-ignore\n Object.entries(resolved).every(([key, value]) => prev[key] === value);\n\n return isEqual ? prev : resolved;\n });\n },\n [setAuthStates],\n );\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 getAllContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n additionalInstructions,\n setAdditionalInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n runtimeClient,\n forwardedParameters,\n agentLock,\n threadId: internalThreadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n availableAgents,\n authConfig_c: props.authConfig_c,\n authStates_c: authStates,\n setAuthStates_c: updateAuthStates,\n extensions,\n setExtensions: updateExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n removeLangGraphInterruptAction,\n onError: props.onError,\n suggestions,\n setSuggestions,\n }}\n >\n <CopilotMessages>{memoizedChildren}</CopilotMessages>\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ name, args }: { name: string; args: Record<string, any> }) => {\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\nfunction formatFeatureName(featureName: string): string {\n return featureName\n .replace(/_c$/, \"\")\n .split(\"_\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(\" \");\n}\n\nfunction validateProps(props: CopilotKitProps): never | void {\n const cloudFeatures = Object.keys(props).filter((key) => key.endsWith(\"_c\"));\n\n if (!props.runtimeUrl && !props.publicApiKey) {\n throw new ConfigurationError(\"Missing required prop: 'runtimeUrl' or 'publicApiKey'\");\n }\n\n if (cloudFeatures.length > 0 && !props.publicApiKey) {\n throw new MissingPublicApiKeyError(\n `Missing required prop: 'publicApiKey' to use cloud features: ${cloudFeatures\n .map(formatFeatureName)\n .join(\", \")}`,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAMO;AACP,gCAQO;;;ACCP,mBAAkF;AAUlF,uBAA0B;AAC1B,oBAQO;AA0BC;AAobD,IAAM,kCAAkC,CAAC,QAAQ;;;AD9dxD,IAAAC,6BAGO;AAuCP,SAAsB,QAAqC,IAUH;AAAA,6CAVG;AAAA,IACzD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc,6CAAmB;AAAA,IACjC;AAAA,EACF,GAAwD;AAvExD;AAwEE,UAAM,EAAE,SAAS,IAAI;AAErB,UAAM,SAAsB;AAAA,MAC1B,MAAM;AAAA,MACN,aAAa;AAAA,MACb;AAAA,MACA,SAAS,CAAC,SAAc;AAAA,MAAC;AAAA,IAC3B;AAEA,UAAM,mBAAkB,wCAAS,aAAT,YAAqB;AAC7C,UAAM,mBAAkB,wCAAS,aAAT,YAAqB;AAE7C,QAAI,gBAAgB;AAEpB,QAAI,MAAM;AACR,uBAAiB,OAAO,SAAS,WAAW,OAAO,KAAK,UAAU,IAAI,KAAK;AAAA,IAC7E;AAEA,QAAI,iBAAiB;AACnB,uBAAiB,QAAQ,iBAAiB,CAAC,GAAG,+BAA+B;AAAA,IAC/E;AAEA,UAAM,gBAAyB,IAAI,sCAAY;AAAA,MAC7C,SAAS,kBAAkB,eAAe,YAAY;AAAA,MACtD,MAAM,+BAAK;AAAA,IACb,CAAC;AAED,UAAM,sBAA+B,IAAI,sCAAY;AAAA,MACn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YAAM,IAAI,MAAM,YAAY;AAAA,IAC9B;AAAA,EACF,SAAS,OAAP;AAEA,UAAM;AAAA,EACR;AACF;","names":["import_shared","import_runtime_client_gql","import_shared","import_runtime_client_gql"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import {
|
|
2
|
+
reloadSuggestions
|
|
3
|
+
} from "../chunk-NAM55D5I.mjs";
|
|
4
|
+
import "../chunk-YBDRISKO.mjs";
|
|
5
|
+
import "../chunk-SJJNFYGQ.mjs";
|
|
6
|
+
import "../chunk-2IDV5OHF.mjs";
|
|
7
|
+
import "../chunk-PMAFHQ7P.mjs";
|
|
8
|
+
import "../chunk-RKTVJRK7.mjs";
|
|
9
|
+
import "../chunk-5FHSUKQL.mjs";
|
|
10
|
+
import "../chunk-DCTJZ742.mjs";
|
|
11
|
+
import "../chunk-57K2ZJ5F.mjs";
|
|
12
|
+
import "../chunk-3OQM3NEK.mjs";
|
|
13
|
+
import "../chunk-O7ARI5CV.mjs";
|
|
14
|
+
import "../chunk-JWAXDYOW.mjs";
|
|
15
|
+
import "../chunk-GFJW4RIM.mjs";
|
|
16
|
+
import "../chunk-YAF2LATQ.mjs";
|
|
17
|
+
import "../chunk-XGRBCWK6.mjs";
|
|
18
|
+
import "../chunk-SKC7AJIV.mjs";
|
|
19
|
+
export {
|
|
20
|
+
reloadSuggestions
|
|
21
|
+
};
|
|
22
|
+
//# sourceMappingURL=suggestions.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"publishConfig": {
|
|
10
10
|
"access": "public"
|
|
11
11
|
},
|
|
12
|
-
"version": "1.
|
|
12
|
+
"version": "1.10.0-next.0",
|
|
13
13
|
"sideEffects": false,
|
|
14
14
|
"main": "./dist/index.js",
|
|
15
15
|
"module": "./dist/index.mjs",
|
|
@@ -47,8 +47,8 @@
|
|
|
47
47
|
"@scarf/scarf": "^1.3.0",
|
|
48
48
|
"react-markdown": "^8.0.7",
|
|
49
49
|
"untruncate-json": "^0.0.1",
|
|
50
|
-
"@copilotkit/runtime-client-gql": "1.
|
|
51
|
-
"@copilotkit/shared": "1.
|
|
50
|
+
"@copilotkit/runtime-client-gql": "1.10.0-next.0",
|
|
51
|
+
"@copilotkit/shared": "1.10.0-next.0"
|
|
52
52
|
},
|
|
53
53
|
"keywords": [
|
|
54
54
|
"copilotkit",
|
|
@@ -50,6 +50,7 @@ import {
|
|
|
50
50
|
LangGraphInterruptActionSetterArgs,
|
|
51
51
|
} from "../../types/interrupt-action";
|
|
52
52
|
import { StatusChecker } from "../../lib/status-checker";
|
|
53
|
+
import { SuggestionItem } from "../../utils/suggestions";
|
|
53
54
|
|
|
54
55
|
export function CopilotKit({ children, ...props }: CopilotKitProps) {
|
|
55
56
|
const showDevConsole = props.showDevConsole ?? false;
|
|
@@ -391,6 +392,7 @@ export function CopilotKitInternal(cpkProps: CopilotKitProps) {
|
|
|
391
392
|
}, []);
|
|
392
393
|
|
|
393
394
|
const memoizedChildren = useMemo(() => children, [children]);
|
|
395
|
+
const [suggestions, setSuggestions] = useState<SuggestionItem[]>([]);
|
|
394
396
|
|
|
395
397
|
const agentLock = useMemo(() => props.agent ?? null, [props.agent]);
|
|
396
398
|
|
|
@@ -484,6 +486,8 @@ export function CopilotKitInternal(cpkProps: CopilotKitProps) {
|
|
|
484
486
|
setLangGraphInterruptAction,
|
|
485
487
|
removeLangGraphInterruptAction,
|
|
486
488
|
onError: props.onError,
|
|
489
|
+
suggestions,
|
|
490
|
+
setSuggestions,
|
|
487
491
|
}}
|
|
488
492
|
>
|
|
489
493
|
<CopilotMessages>{memoizedChildren}</CopilotMessages>
|
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
LangGraphInterruptAction,
|
|
21
21
|
LangGraphInterruptActionSetter,
|
|
22
22
|
} from "../types/interrupt-action";
|
|
23
|
+
import { SuggestionItem } from "../utils/suggestions";
|
|
23
24
|
|
|
24
25
|
/**
|
|
25
26
|
* Interface for the configuration of the Copilot API.
|
|
@@ -223,6 +224,9 @@ export interface CopilotContextParams {
|
|
|
223
224
|
* Optional trace handler for comprehensive debugging and observability.
|
|
224
225
|
*/
|
|
225
226
|
onError?: CopilotErrorHandler;
|
|
227
|
+
// suggestions state
|
|
228
|
+
suggestions: SuggestionItem[];
|
|
229
|
+
setSuggestions: React.Dispatch<React.SetStateAction<SuggestionItem[]>>;
|
|
226
230
|
}
|
|
227
231
|
|
|
228
232
|
const emptyCopilotContext: CopilotContextParams = {
|
|
@@ -294,6 +298,8 @@ const emptyCopilotContext: CopilotContextParams = {
|
|
|
294
298
|
setLangGraphInterruptAction: () => null,
|
|
295
299
|
removeLangGraphInterruptAction: () => null,
|
|
296
300
|
onError: undefined,
|
|
301
|
+
suggestions: [],
|
|
302
|
+
setSuggestions: () => {},
|
|
297
303
|
};
|
|
298
304
|
|
|
299
305
|
export const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);
|
package/src/hooks/use-chat.ts
CHANGED
|
@@ -190,6 +190,10 @@ export interface AppendMessageOptions {
|
|
|
190
190
|
* Whether to run the chat completion after appending the message. Defaults to `true`.
|
|
191
191
|
*/
|
|
192
192
|
followUp?: boolean;
|
|
193
|
+
/**
|
|
194
|
+
* Whether to clear the suggestions after appending the message. Defaults to `true`.
|
|
195
|
+
*/
|
|
196
|
+
clearSuggestions?: boolean;
|
|
193
197
|
}
|
|
194
198
|
|
|
195
199
|
export function useChat(options: UseChatOptions): UseChatHelpers {
|
|
@@ -734,8 +738,8 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
|
|
|
734
738
|
const action = actions.find(
|
|
735
739
|
(action) => action.name === (message as ActionExecutionMessage).name,
|
|
736
740
|
);
|
|
737
|
-
if (action && action.available === "
|
|
738
|
-
// never execute
|
|
741
|
+
if (action && action.available === "frontend") {
|
|
742
|
+
// never execute frontend actions
|
|
739
743
|
continue;
|
|
740
744
|
}
|
|
741
745
|
const currentResultMessagePairedFeAction = message.isResultMessage()
|
package/src/hooks/use-coagent.ts
CHANGED
|
@@ -97,7 +97,7 @@ import {
|
|
|
97
97
|
} from "../context";
|
|
98
98
|
import { CoagentState } from "../types/coagent-state";
|
|
99
99
|
import { useCopilotChat } from "./use-copilot-chat";
|
|
100
|
-
import { Message } from "@copilotkit/
|
|
100
|
+
import { Message } from "@copilotkit/shared";
|
|
101
101
|
import { useAsyncCallback } from "../components/error-boundary/error-utils";
|
|
102
102
|
import { useToast } from "../components/toast/toast-provider";
|
|
103
103
|
import { useCopilotRuntimeClient } from "./use-copilot-runtime-client";
|