@copilotkit/react-core 1.5.1-next.2 → 1.5.1-next.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/{chunk-LNI2Z45S.mjs → chunk-2KCEHGSI.mjs} +50 -100
- package/dist/chunk-2KCEHGSI.mjs.map +1 -0
- package/dist/{chunk-2KT73RVG.mjs → chunk-6OR25P32.mjs} +19 -75
- package/dist/chunk-6OR25P32.mjs.map +1 -0
- package/dist/{chunk-3GQPEN4M.mjs → chunk-DDVXFNYA.mjs} +32 -66
- package/dist/chunk-DDVXFNYA.mjs.map +1 -0
- package/dist/{chunk-XOQMISG3.mjs → chunk-FXHKK52V.mjs} +13 -14
- package/dist/chunk-FXHKK52V.mjs.map +1 -0
- package/dist/{chunk-HIUT2NLX.mjs → chunk-H4VZMKR6.mjs} +2 -2
- package/dist/{chunk-X36DNILG.mjs → chunk-H7LSKIDK.mjs} +23 -71
- package/dist/chunk-H7LSKIDK.mjs.map +1 -0
- package/dist/chunk-JDQCJCAQ.mjs +295 -0
- package/dist/chunk-JDQCJCAQ.mjs.map +1 -0
- package/dist/chunk-L34MHAXR.mjs +1 -0
- package/dist/{chunk-WXREY7UP.mjs → chunk-LODRWFMB.mjs} +4 -16
- package/dist/chunk-LODRWFMB.mjs.map +1 -0
- package/dist/{chunk-EWKJMQOF.mjs → chunk-MWZO6TUR.mjs} +13 -29
- package/dist/chunk-MWZO6TUR.mjs.map +1 -0
- package/dist/{chunk-6BQVZFNO.mjs → chunk-ODN4H66E.mjs} +2 -6
- package/dist/chunk-ODN4H66E.mjs.map +1 -0
- package/dist/{chunk-FQ53HQYZ.mjs → chunk-QDGDXRRJ.mjs} +2 -2
- package/dist/{chunk-22XKTBPF.mjs → chunk-XINZBP3J.mjs} +3 -15
- package/dist/chunk-XINZBP3J.mjs.map +1 -0
- package/dist/components/copilot-provider/copilot-messages.d.ts +0 -9
- package/dist/components/copilot-provider/copilotkit-props.d.ts +0 -21
- package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.d.ts +0 -9
- package/dist/components/copilot-provider/copilotkit.js +95 -224
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +8 -9
- package/dist/components/copilot-provider/index.d.ts +0 -9
- package/dist/components/copilot-provider/index.js +95 -224
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +8 -9
- package/dist/components/index.d.ts +0 -9
- package/dist/components/index.js +95 -224
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +8 -9
- package/dist/components/toast/toast-provider.d.ts +1 -2
- package/dist/components/toast/toast-provider.js +63 -77
- package/dist/components/toast/toast-provider.js.map +1 -1
- package/dist/components/toast/toast-provider.mjs +1 -1
- package/dist/context/copilot-context.d.ts +4 -37
- package/dist/context/copilot-context.js +3 -15
- 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 +3 -15
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +4 -4
- package/dist/hooks/index.d.ts +1 -3
- package/dist/hooks/index.js +297 -703
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +23 -35
- package/dist/hooks/use-chat.d.ts +3 -35
- package/dist/hooks/use-chat.js +205 -453
- package/dist/hooks/use-chat.js.map +1 -1
- package/dist/hooks/use-chat.mjs +3 -4
- package/dist/hooks/use-coagent-state-render.d.ts +2 -2
- package/dist/hooks/use-coagent-state-render.js +8 -43
- package/dist/hooks/use-coagent-state-render.js.map +1 -1
- package/dist/hooks/use-coagent-state-render.mjs +2 -4
- package/dist/hooks/use-coagent.d.ts +1 -14
- package/dist/hooks/use-coagent.js +265 -603
- package/dist/hooks/use-coagent.js.map +1 -1
- package/dist/hooks/use-coagent.mjs +12 -20
- package/dist/hooks/use-copilot-action.d.ts +2 -12
- package/dist/hooks/use-copilot-action.js +19 -169
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +2 -4
- package/dist/hooks/use-copilot-chat.d.ts +0 -2
- package/dist/hooks/use-copilot-chat.js +240 -545
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +11 -13
- package/dist/hooks/use-copilot-readable.js +3 -15
- package/dist/hooks/use-copilot-readable.js.map +1 -1
- package/dist/hooks/use-copilot-readable.mjs +2 -2
- package/dist/hooks/use-copilot-runtime-client.js +4 -110
- package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
- package/dist/hooks/use-copilot-runtime-client.mjs +2 -2
- package/dist/hooks/use-make-copilot-document-readable.js +3 -15
- 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 +3 -4
- package/dist/index.js +398 -812
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +31 -43
- package/dist/lib/copilot-task.d.ts +1 -6
- package/dist/lib/copilot-task.js +17 -55
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +9 -11
- package/dist/lib/index.d.ts +1 -1
- package/dist/lib/index.js +17 -55
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +9 -11
- package/dist/types/frontend-action.d.ts +2 -21
- package/dist/types/frontend-action.js +0 -34
- package/dist/types/frontend-action.js.map +1 -1
- package/dist/types/frontend-action.mjs +0 -7
- package/dist/types/index.d.ts +1 -2
- package/dist/types/index.js.map +1 -1
- package/dist/utils/extract.d.ts +2 -3
- package/dist/utils/extract.js +3 -21
- package/dist/utils/extract.js.map +1 -1
- package/dist/utils/extract.mjs +8 -9
- package/dist/utils/index.js +3 -21
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +9 -10
- package/package.json +5 -5
- package/dist/chunk-22XKTBPF.mjs.map +0 -1
- package/dist/chunk-2KT73RVG.mjs.map +0 -1
- package/dist/chunk-3GQPEN4M.mjs.map +0 -1
- package/dist/chunk-6BQVZFNO.mjs.map +0 -1
- package/dist/chunk-EWKJMQOF.mjs.map +0 -1
- package/dist/chunk-LHKIIAUQ.mjs +0 -59
- package/dist/chunk-LHKIIAUQ.mjs.map +0 -1
- package/dist/chunk-LNI2Z45S.mjs.map +0 -1
- package/dist/chunk-NR2BTA6Z.mjs +0 -1
- package/dist/chunk-VGOFRULA.mjs +0 -401
- package/dist/chunk-VGOFRULA.mjs.map +0 -1
- package/dist/chunk-VNTDIJSG.mjs +0 -37
- package/dist/chunk-VNTDIJSG.mjs.map +0 -1
- package/dist/chunk-WXREY7UP.mjs.map +0 -1
- package/dist/chunk-X36DNILG.mjs.map +0 -1
- package/dist/chunk-XERJQUHA.mjs +0 -31
- package/dist/chunk-XERJQUHA.mjs.map +0 -1
- package/dist/chunk-XOQMISG3.mjs.map +0 -1
- package/dist/components/error-boundary/error-boundary.d.ts +0 -22
- package/dist/components/error-boundary/error-boundary.js +0 -183
- package/dist/components/error-boundary/error-boundary.js.map +0 -1
- package/dist/components/error-boundary/error-boundary.mjs +0 -12
- package/dist/components/error-boundary/error-boundary.mjs.map +0 -1
- package/dist/components/error-boundary/error-utils.d.ts +0 -11
- package/dist/components/error-boundary/error-utils.js +0 -177
- package/dist/components/error-boundary/error-utils.js.map +0 -1
- package/dist/components/error-boundary/error-utils.mjs +0 -13
- package/dist/components/error-boundary/error-utils.mjs.map +0 -1
- package/dist/hooks/use-copilot-authenticated-action.d.ts +0 -8
- package/dist/hooks/use-copilot-authenticated-action.js +0 -418
- package/dist/hooks/use-copilot-authenticated-action.js.map +0 -1
- package/dist/hooks/use-copilot-authenticated-action.mjs +0 -12
- package/dist/hooks/use-copilot-authenticated-action.mjs.map +0 -1
- /package/dist/{chunk-HIUT2NLX.mjs.map → chunk-H4VZMKR6.mjs.map} +0 -0
- /package/dist/{chunk-NR2BTA6Z.mjs.map → chunk-L34MHAXR.mjs.map} +0 -0
- /package/dist/{chunk-FQ53HQYZ.mjs.map → chunk-QDGDXRRJ.mjs.map} +0 -0
|
@@ -68,7 +68,7 @@ __export(use_copilot_action_exports, {
|
|
|
68
68
|
});
|
|
69
69
|
module.exports = __toCommonJS(use_copilot_action_exports);
|
|
70
70
|
var import_shared = require("@copilotkit/shared");
|
|
71
|
-
var
|
|
71
|
+
var import_react2 = require("react");
|
|
72
72
|
|
|
73
73
|
// src/context/copilot-context.tsx
|
|
74
74
|
var import_react = __toESM(require("react"));
|
|
@@ -119,22 +119,9 @@ var emptyCopilotContext = {
|
|
|
119
119
|
coagentStates: {},
|
|
120
120
|
setCoagentStates: () => {
|
|
121
121
|
},
|
|
122
|
-
coagentStatesRef: { current: {} },
|
|
123
|
-
setCoagentStatesWithRef: () => {
|
|
124
|
-
},
|
|
125
122
|
agentSession: null,
|
|
126
123
|
setAgentSession: () => {
|
|
127
|
-
}
|
|
128
|
-
forwardedParameters: {},
|
|
129
|
-
agentLock: null,
|
|
130
|
-
threadId: null,
|
|
131
|
-
setThreadId: () => {
|
|
132
|
-
},
|
|
133
|
-
runId: null,
|
|
134
|
-
setRunId: () => {
|
|
135
|
-
},
|
|
136
|
-
chatAbortControllerRef: { current: null },
|
|
137
|
-
availableAgents: []
|
|
124
|
+
}
|
|
138
125
|
};
|
|
139
126
|
var CopilotContext = import_react.default.createContext(emptyCopilotContext);
|
|
140
127
|
function useCopilotContext() {
|
|
@@ -144,150 +131,22 @@ function useCopilotContext() {
|
|
|
144
131
|
}
|
|
145
132
|
return context;
|
|
146
133
|
}
|
|
147
|
-
function returnAndThrowInDebug(
|
|
134
|
+
function returnAndThrowInDebug(value) {
|
|
148
135
|
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
// src/components/error-boundary/error-utils.tsx
|
|
152
|
-
var import_react3 = require("react");
|
|
153
|
-
|
|
154
|
-
// src/components/toast/toast-provider.tsx
|
|
155
|
-
var import_react2 = require("react");
|
|
156
|
-
var import_jsx_runtime = require("react/jsx-runtime");
|
|
157
|
-
var ToastContext = (0, import_react2.createContext)(void 0);
|
|
158
|
-
function useToast() {
|
|
159
|
-
const context = (0, import_react2.useContext)(ToastContext);
|
|
160
|
-
if (!context) {
|
|
161
|
-
throw new Error("useToast must be used within a ToastProvider");
|
|
162
|
-
}
|
|
163
|
-
return context;
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
// src/components/toast/exclamation-mark-icon.tsx
|
|
167
|
-
var import_jsx_runtime2 = require("react/jsx-runtime");
|
|
168
|
-
var ExclamationMarkIcon = ({
|
|
169
|
-
className,
|
|
170
|
-
style
|
|
171
|
-
}) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
|
|
172
|
-
"svg",
|
|
173
|
-
{
|
|
174
|
-
xmlns: "http://www.w3.org/2000/svg",
|
|
175
|
-
width: "24",
|
|
176
|
-
height: "24",
|
|
177
|
-
viewBox: "0 0 24 24",
|
|
178
|
-
fill: "none",
|
|
179
|
-
stroke: "currentColor",
|
|
180
|
-
strokeWidth: "2",
|
|
181
|
-
strokeLinecap: "round",
|
|
182
|
-
strokeLinejoin: "round",
|
|
183
|
-
className: `lucide lucide-circle-alert ${className ? className : ""}`,
|
|
184
|
-
style,
|
|
185
|
-
children: [
|
|
186
|
-
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("circle", { cx: "12", cy: "12", r: "10" }),
|
|
187
|
-
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "12", x2: "12", y1: "8", y2: "12" }),
|
|
188
|
-
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "12", x2: "12.01", y1: "16", y2: "16" })
|
|
189
|
-
]
|
|
190
|
-
}
|
|
191
|
-
);
|
|
192
|
-
|
|
193
|
-
// src/components/error-boundary/error-utils.tsx
|
|
194
|
-
var import_jsx_runtime3 = require("react/jsx-runtime");
|
|
195
|
-
function ErrorToast({ errors }) {
|
|
196
|
-
const errorsToRender = errors.map((error, idx) => {
|
|
197
|
-
var _a, _b, _c;
|
|
198
|
-
const message = "extensions" in error ? (_b = (_a = error.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message : error.message;
|
|
199
|
-
const code = "extensions" in error ? (_c = error.extensions) == null ? void 0 : _c.code : null;
|
|
200
|
-
return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
|
|
201
|
-
"div",
|
|
202
|
-
{
|
|
203
|
-
style: {
|
|
204
|
-
marginTop: idx === 0 ? 0 : 10,
|
|
205
|
-
marginBottom: 14
|
|
206
|
-
},
|
|
207
|
-
children: [
|
|
208
|
-
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
|
|
209
|
-
code && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
|
|
210
|
-
"div",
|
|
211
|
-
{
|
|
212
|
-
style: {
|
|
213
|
-
fontWeight: "600",
|
|
214
|
-
marginBottom: 4
|
|
215
|
-
},
|
|
216
|
-
children: [
|
|
217
|
-
"Copilot Cloud Error:",
|
|
218
|
-
" ",
|
|
219
|
-
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
|
|
220
|
-
]
|
|
221
|
-
}
|
|
222
|
-
),
|
|
223
|
-
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { children: message })
|
|
224
|
-
]
|
|
225
|
-
},
|
|
226
|
-
idx
|
|
227
|
-
);
|
|
228
|
-
});
|
|
229
|
-
return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
|
|
230
|
-
"div",
|
|
231
|
-
{
|
|
232
|
-
style: {
|
|
233
|
-
fontSize: "13px",
|
|
234
|
-
maxWidth: "600px"
|
|
235
|
-
},
|
|
236
|
-
children: [
|
|
237
|
-
errorsToRender,
|
|
238
|
-
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This error only displays during local development." })
|
|
239
|
-
]
|
|
240
|
-
}
|
|
241
|
-
);
|
|
242
|
-
}
|
|
243
|
-
function useErrorToast() {
|
|
244
|
-
const { addToast } = useToast();
|
|
245
|
-
return (0, import_react3.useCallback)(
|
|
246
|
-
(error) => {
|
|
247
|
-
const errorId = error.map((err) => {
|
|
248
|
-
var _a, _b;
|
|
249
|
-
const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
|
|
250
|
-
const stack = err.stack || "";
|
|
251
|
-
return btoa(message + stack).slice(0, 32);
|
|
252
|
-
}).join("|");
|
|
253
|
-
addToast({
|
|
254
|
-
type: "error",
|
|
255
|
-
id: errorId,
|
|
256
|
-
// Toast libraries typically dedupe by id
|
|
257
|
-
message: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ErrorToast, { errors: error })
|
|
258
|
-
});
|
|
259
|
-
},
|
|
260
|
-
[addToast]
|
|
261
|
-
);
|
|
262
|
-
}
|
|
263
|
-
function useAsyncCallback(callback, deps) {
|
|
264
|
-
const addErrorToast = useErrorToast();
|
|
265
|
-
return (0, import_react3.useCallback)((...args) => __async(this, null, function* () {
|
|
266
|
-
try {
|
|
267
|
-
return yield callback(...args);
|
|
268
|
-
} catch (error) {
|
|
269
|
-
console.error("Error in async callback:", error);
|
|
270
|
-
addErrorToast([error]);
|
|
271
|
-
throw error;
|
|
272
|
-
}
|
|
273
|
-
}), deps);
|
|
136
|
+
return value;
|
|
274
137
|
}
|
|
275
138
|
|
|
276
139
|
// src/hooks/use-copilot-action.ts
|
|
277
140
|
function useCopilotAction(action, dependencies) {
|
|
278
141
|
const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();
|
|
279
|
-
const idRef = (0,
|
|
280
|
-
const renderAndWaitRef = (0,
|
|
142
|
+
const idRef = (0, import_react2.useRef)((0, import_shared.randomId)());
|
|
143
|
+
const renderAndWaitRef = (0, import_react2.useRef)(null);
|
|
281
144
|
action = __spreadValues({}, action);
|
|
282
|
-
if (
|
|
283
|
-
// renderAndWaitForResponse is not available for catch all actions
|
|
284
|
-
isFrontendAction(action) && // check if renderAndWaitForResponse is set
|
|
285
|
-
(action.renderAndWait || action.renderAndWaitForResponse)
|
|
286
|
-
) {
|
|
145
|
+
if (action.renderAndWait || action.renderAndWaitForResponse) {
|
|
287
146
|
const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;
|
|
288
147
|
action.renderAndWait = void 0;
|
|
289
148
|
action.renderAndWaitForResponse = void 0;
|
|
290
|
-
action.handler =
|
|
149
|
+
action.handler = () => __async(this, null, function* () {
|
|
291
150
|
let resolve;
|
|
292
151
|
let reject;
|
|
293
152
|
const promise = new Promise((resolvePromise, rejectPromise) => {
|
|
@@ -296,18 +155,14 @@ function useCopilotAction(action, dependencies) {
|
|
|
296
155
|
});
|
|
297
156
|
renderAndWaitRef.current = { promise, resolve, reject };
|
|
298
157
|
return yield promise;
|
|
299
|
-
})
|
|
158
|
+
});
|
|
300
159
|
action.render = (props) => {
|
|
301
|
-
let status = props.status;
|
|
302
|
-
if (props.status === "executing" && !renderAndWaitRef.current) {
|
|
303
|
-
status = "inProgress";
|
|
304
|
-
}
|
|
305
160
|
const waitProps = {
|
|
306
|
-
status,
|
|
161
|
+
status: props.status,
|
|
307
162
|
args: props.args,
|
|
308
163
|
result: props.result,
|
|
309
|
-
handler: status === "executing" ? renderAndWaitRef.current.resolve : void 0,
|
|
310
|
-
respond: status === "executing" ? renderAndWaitRef.current.resolve : void 0
|
|
164
|
+
handler: props.status === "executing" ? renderAndWaitRef.current.resolve : void 0,
|
|
165
|
+
respond: props.status === "executing" ? renderAndWaitRef.current.resolve : void 0
|
|
311
166
|
};
|
|
312
167
|
const isNoArgsRenderWait = (_fn) => {
|
|
313
168
|
var _a;
|
|
@@ -320,14 +175,12 @@ function useCopilotAction(action, dependencies) {
|
|
|
320
175
|
return renderAndWait(waitProps);
|
|
321
176
|
}
|
|
322
177
|
}
|
|
323
|
-
return (0,
|
|
178
|
+
return (0, import_react2.createElement)(import_react2.Fragment);
|
|
324
179
|
};
|
|
325
180
|
}
|
|
326
181
|
if (dependencies === void 0) {
|
|
327
182
|
if (actions[idRef.current]) {
|
|
328
|
-
|
|
329
|
-
actions[idRef.current].handler = action.handler;
|
|
330
|
-
}
|
|
183
|
+
actions[idRef.current].handler = action.handler;
|
|
331
184
|
if (typeof action.render === "function") {
|
|
332
185
|
if (chatComponentsCache.current !== null) {
|
|
333
186
|
chatComponentsCache.current.actions[action.name] = action.render;
|
|
@@ -335,7 +188,7 @@ function useCopilotAction(action, dependencies) {
|
|
|
335
188
|
}
|
|
336
189
|
}
|
|
337
190
|
}
|
|
338
|
-
(0,
|
|
191
|
+
(0, import_react2.useEffect)(() => {
|
|
339
192
|
setAction(idRef.current, action);
|
|
340
193
|
if (chatComponentsCache.current !== null && action.render !== void 0) {
|
|
341
194
|
chatComponentsCache.current.actions[action.name] = action.render;
|
|
@@ -346,22 +199,19 @@ function useCopilotAction(action, dependencies) {
|
|
|
346
199
|
}, [
|
|
347
200
|
setAction,
|
|
348
201
|
removeAction,
|
|
349
|
-
|
|
202
|
+
action.description,
|
|
350
203
|
action.name,
|
|
351
|
-
|
|
352
|
-
|
|
204
|
+
action.disabled,
|
|
205
|
+
action.available,
|
|
353
206
|
// This should be faster than deep equality checking
|
|
354
207
|
// In addition, all major JS engines guarantee the order of object keys
|
|
355
|
-
JSON.stringify(
|
|
208
|
+
JSON.stringify(action.parameters),
|
|
356
209
|
// include render only if it's a string
|
|
357
210
|
typeof action.render === "string" ? action.render : void 0,
|
|
358
211
|
// dependencies set by the developer
|
|
359
212
|
...dependencies || []
|
|
360
213
|
]);
|
|
361
214
|
}
|
|
362
|
-
function isFrontendAction(action) {
|
|
363
|
-
return action.name !== "*";
|
|
364
|
-
}
|
|
365
215
|
// Annotate the CommonJS export names for ESM import in node:
|
|
366
216
|
0 && (module.exports = {
|
|
367
217
|
useCopilotAction
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/use-copilot-action.ts","../../src/context/copilot-context.tsx","../../src/components/error-boundary/error-utils.tsx","../../src/components/toast/toast-provider.tsx","../../src/components/toast/exclamation-mark-icon.tsx"],"sourcesContent":["/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { Parameter, randomId } from \"@copilotkit/shared\";\nimport { createElement, Fragment, useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport {\n ActionRenderProps,\n ActionRenderPropsNoArgsWait,\n ActionRenderPropsWait,\n CatchAllFrontendAction,\n FrontendAction,\n} from \"../types/frontend-action\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();\n const idRef = useRef<string>(randomId());\n const renderAndWaitRef = useRef<RenderAndWaitForResponse | null>(null);\n\n // clone the action to avoid mutating the original object\n action = { ...action };\n\n // If the developer provides a renderAndWaitForResponse function, we transform the action\n // to use a promise internally, so that we can treat it like a normal action.\n if (\n // renderAndWaitForResponse is not available for catch all actions\n isFrontendAction(action) &&\n // check if renderAndWaitForResponse is set\n (action.renderAndWait || action.renderAndWaitForResponse)\n ) {\n const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;\n // remove the renderAndWait function from the action\n action.renderAndWait = undefined;\n action.renderAndWaitForResponse = undefined;\n // add a handler that will be called when the action is executed\n action.handler = useAsyncCallback(async () => {\n // we create a new promise when the handler is called\n let resolve: (result: any) => void;\n let reject: (error: any) => void;\n const promise = new Promise<any>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n renderAndWaitRef.current = { promise, resolve: resolve!, reject: reject! };\n // then we await the promise (it will be resolved in the original renderAndWait function)\n return await promise;\n }, []) as any;\n\n // add a render function that will be called when the action is rendered\n action.render = ((props: ActionRenderProps<T>): React.ReactElement => {\n // Specifically for renderAndWaitForResponse the executing state is set too early, causing a race condition\n // To fit it: we will wait for the handler to be ready\n let status = props.status;\n if (props.status === \"executing\" && !renderAndWaitRef.current) {\n status = \"inProgress\";\n }\n // Create type safe waitProps based on whether T extends empty array or not\n const waitProps = {\n status,\n args: props.args,\n result: props.result,\n handler: status === \"executing\" ? renderAndWaitRef.current!.resolve : undefined,\n respond: status === \"executing\" ? renderAndWaitRef.current!.resolve : undefined,\n } as T extends [] ? ActionRenderPropsNoArgsWait<T> : ActionRenderPropsWait<T>;\n\n // Type guard to check if renderAndWait is for no args case\n const isNoArgsRenderWait = (\n _fn:\n | ((props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement)\n | ((props: ActionRenderPropsWait<T>) => React.ReactElement),\n ): _fn is (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement => {\n return action.parameters?.length === 0;\n };\n\n // Safely call renderAndWait with correct props type\n if (renderAndWait) {\n if (isNoArgsRenderWait(renderAndWait)) {\n return renderAndWait(waitProps as ActionRenderPropsNoArgsWait<T>);\n } else {\n return renderAndWait(waitProps as ActionRenderPropsWait<T>);\n }\n }\n\n // Return empty Fragment instead of null\n return createElement(Fragment);\n }) as any;\n }\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n // catch all actions don't have a handler\n if (isFrontendAction(action)) {\n actions[idRef.current].handler = action.handler as any;\n }\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n // TODO: using as any here because the type definitions are getting to tricky\n // not wasting time on this now - we know the types are compatible\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n }\n }\n }\n\n useEffect(() => {\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n // see comment about type safety above\n chatComponentsCache.current.actions[action.name] = action.render as any;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n // UPDATE: We now have access, we should remove the entry if not referenced by any message.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n isFrontendAction(action) ? action.description : undefined,\n action.name,\n isFrontendAction(action) ? action.disabled : undefined,\n isFrontendAction(action) ? action.available : undefined,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(isFrontendAction(action) ? action.parameters : []),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\nfunction isFrontendAction<T extends Parameter[]>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n): action is FrontendAction<T> {\n return action.name !== \"*\";\n}\n\ninterface RenderAndWaitForResponse {\n promise: Promise<any>;\n resolve: (result: any) => void;\n reject: (error: any) => void;\n}\n","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} 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 { CoAgentStateRender, CoAgentStateRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { CopilotRuntimeClient, ForwardedParametersInput } from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\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 = (\n props: ActionRenderProps<any> | CatchAllActionRenderProps<any>,\n) => string | JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | JSX.Element | undefined | null;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface AuthState {\n status: \"authenticated\" | \"unauthenticated\";\n authHeaders: Record<string, string>;\n userId?: string;\n metadata?: Record<string, any>;\n}\n\nexport type ActionName = string;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // coagent actions\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (id: string, stateRender: CoAgentStateRender<any>) => void;\n removeCoAgentStateRender: (id: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean | \"auto\";\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n setCoagentStatesWithRef: (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => void;\n\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n agentLock: string | null;\n\n threadId: string | null;\n setThreadId: React.Dispatch<React.SetStateAction<string | null>>;\n\n runId: string | null;\n setRunId: React.Dispatch<React.SetStateAction<string | null>>;\n\n // The chat abort controller can be used to stop generation globally,\n // i.e. when using `stop()` from `useChat`\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n\n // runtime\n runtimeClient: CopilotRuntimeClient;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Pick<ForwardedParametersInput, \"temperature\">;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates?: Record<ActionName, AuthState>;\n setAuthStates?: React.Dispatch<React.SetStateAction<Record<ActionName, AuthState>>>;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coAgentStateRenders: {},\n setCoAgentStateRender: () => {},\n removeCoAgentStateRender: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\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 runtimeClient: {} as any,\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: \"auto\",\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n agentSession: null,\n setAgentSession: () => {},\n forwardedParameters: {},\n agentLock: null,\n threadId: null,\n setThreadId: () => {},\n runId: null,\n setRunId: () => {},\n chatAbortControllerRef: { current: null },\n availableAgents: [],\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n}\n","import React, { useCallback, useEffect } from \"react\";\nimport { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport { useToast } from \"../toast/toast-provider\";\nimport { ExclamationMarkIcon } from \"../toast/exclamation-mark-icon\";\n\nexport function ErrorToast({ errors }: { errors: (Error | GraphQLError)[] }) {\n const errorsToRender = errors.map((error, idx) => {\n const message =\n \"extensions\" in error\n ? (error.extensions?.originalError as undefined | { message?: string })?.message\n : error.message;\n const code = \"extensions\" in error ? (error.extensions?.code as string) : null;\n\n return (\n <div\n key={idx}\n style={{\n marginTop: idx === 0 ? 0 : 10,\n marginBottom: 14,\n }}\n >\n <ExclamationMarkIcon style={{ marginBottom: 4 }} />\n\n {code && (\n <div\n style={{\n fontWeight: \"600\",\n marginBottom: 4,\n }}\n >\n Copilot Cloud Error:{\" \"}\n <span style={{ fontFamily: \"monospace\", fontWeight: \"normal\" }}>{code}</span>\n </div>\n )}\n <div>{message}</div>\n </div>\n );\n });\n return (\n <div\n style={{\n fontSize: \"13px\",\n maxWidth: \"600px\",\n }}\n >\n {errorsToRender}\n <div style={{ fontSize: \"11px\", opacity: 0.75 }}>\n NOTE: This error only displays during local development.\n </div>\n </div>\n );\n}\n\nexport function useErrorToast() {\n const { addToast } = useToast();\n\n return useCallback(\n (error: (Error | GraphQLError)[]) => {\n const errorId = error\n .map((err) => {\n const message =\n \"extensions\" in err\n ? (err.extensions?.originalError as any)?.message || err.message\n : err.message;\n const stack = err.stack || \"\";\n return btoa(message + stack).slice(0, 32); // Create hash from message + stack\n })\n .join(\"|\");\n\n addToast({\n type: \"error\",\n id: errorId, // Toast libraries typically dedupe by id\n message: <ErrorToast errors={error} />,\n });\n },\n [addToast],\n );\n}\n\nexport function useAsyncCallback<T extends (...args: any[]) => Promise<any>>(\n callback: T,\n deps: Parameters<typeof useCallback>[1],\n) {\n const addErrorToast = useErrorToast();\n return useCallback(async (...args: Parameters<T>) => {\n try {\n return await callback(...args);\n } catch (error) {\n console.error(\"Error in async callback:\", error);\n // @ts-ignore\n addErrorToast([error]);\n throw error;\n }\n }, deps);\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { ErrorToast } from \"../error-boundary/error-utils\";\nimport { PartialBy } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const addToast = useCallback((toast: PartialBy<Toast, \"id\">) => {\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n }, []);\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // We do not display these errors unless we are in dev mode.\n // if (!showDevConsole) {\n // return;\n // }\n\n addToast({\n type: \"error\",\n message: <ErrorToast errors={errors} />,\n });\n }, []);\n\n const removeToast = useCallback((id: string) => {\n setToasts((currentToasts) => currentToasts.filter((toast) => toast.id !== id));\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n };\n\n return (\n <ToastContext.Provider value={value}>\n <div\n style={{\n position: \"fixed\",\n bottom: \"1rem\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 50,\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"0.5rem\",\n }}\n >\n {toasts.length > 1 && (\n <div style={{ textAlign: \"right\" }}>\n <button\n onClick={() => setToasts([])}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n cursor: \"pointer\",\n background: \"white\",\n border: \"1px solid rgba(0,0,0,0.2)\",\n borderRadius: \"4px\",\n }}\n >\n Close All\n </button>\n </div>\n )}\n {toasts.map((toast) => (\n <Toast\n key={toast.id}\n message={toast.message}\n type={toast.type}\n onClose={() => removeToast(toast.id)}\n />\n ))}\n </div>\n {children}\n </ToastContext.Provider>\n );\n}\n\nfunction Toast({\n message,\n type = \"info\",\n onClose,\n}: {\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n onClose: () => void;\n}) {\n const bgColors = {\n info: \"#3b82f6\",\n success: \"#22c55e\",\n warning: \"#eab308\",\n error: \"#ef4444\",\n };\n\n return (\n <div\n style={{\n backgroundColor: bgColors[type],\n color: \"white\",\n padding: \"0.5rem 1.5rem\",\n borderRadius: \"0.25rem\",\n boxShadow: \"0 2px 4px rgba(0,0,0,0.1)\",\n position: \"relative\",\n minWidth: \"200px\",\n }}\n >\n <div>{message}</div>\n <button\n onClick={onClose}\n style={{\n position: \"absolute\",\n top: \"0\",\n right: \"0\",\n background: \"none\",\n border: \"none\",\n color: \"white\",\n cursor: \"pointer\",\n padding: \"0.5rem\",\n fontSize: \"1rem\",\n }}\n >\n ✕\n </button>\n </div>\n );\n}\n","import React from \"react\";\n\nexport const ExclamationMarkIcon = ({\n className,\n style,\n}: {\n className?: string;\n style?: React.CSSProperties;\n}) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className={`lucide lucide-circle-alert ${className ? className : \"\"}`}\n style={style}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"12\" x2=\"12\" y1=\"8\" y2=\"12\" />\n <line x1=\"12\" x2=\"12.01\" y1=\"16\" y2=\"16\" />\n </svg>\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAoIA,oBAAoC;AACpC,IAAAA,gBAA2D;;;AC/H3D,mBAAkB;AA+LlB,IA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iB,MAAM,IAAI,OAAO,cAAc;AAAA,IAChD,OAAO;AAAA,IACP,iBAAiB,MAAM,IAAI,OAAO,WAAW;AAAA,IAC7C,iBAAiB,MAAM,IAAI,OAAO,YAAY;AAAA;AAAA;AAAA,IAG9C,KAAK,UAAU,iBAAiB,MAAM,IAAI,OAAO,aAAa,CAAC,CAAC;AAAA;AAAA,IAEhE,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;AAEA,SAAS,iBACP,QAC6B;AAC7B,SAAO,OAAO,SAAS;AACzB;","names":["import_react","React","import_react","import_react","import_jsx_runtime","import_jsx_runtime"]}
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/use-copilot-action.ts","../../src/context/copilot-context.tsx"],"sourcesContent":["/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n */\n\n/**\n * <img src=\"/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { Parameter, randomId } from \"@copilotkit/shared\";\nimport { createElement, Fragment, useEffect, useRef } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport {\n ActionRenderProps,\n ActionRenderPropsNoArgsWait,\n ActionRenderPropsWait,\n FrontendAction,\n} from \"../types/frontend-action\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();\n const idRef = useRef<string>(randomId());\n const renderAndWaitRef = useRef<RenderAndWaitForResponse | null>(null);\n\n // clone the action to avoid mutating the original object\n action = { ...action };\n\n // If the developer provides a renderAndWait function, we transform the action\n // to use a promise internally, so that we can treat it like a normal action.\n if (action.renderAndWait || action.renderAndWaitForResponse) {\n const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;\n // remove the renderAndWait function from the action\n action.renderAndWait = undefined;\n action.renderAndWaitForResponse = undefined;\n // add a handler that will be called when the action is executed\n action.handler = (async () => {\n // we create a new promise when the handler is called\n let resolve: (result: any) => void;\n let reject: (error: any) => void;\n const promise = new Promise<any>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n renderAndWaitRef.current = { promise, resolve: resolve!, reject: reject! };\n // then we await the promise (it will be resolved in the original renderAndWait function)\n return await promise;\n }) as any;\n\n // add a render function that will be called when the action is rendered\n action.render = ((props: ActionRenderProps<T>): React.ReactElement => {\n // Create type safe waitProps based on whether T extends empty array or not\n const waitProps = {\n status: props.status,\n args: props.args,\n result: props.result,\n handler: props.status === \"executing\" ? renderAndWaitRef.current!.resolve : undefined,\n respond: props.status === \"executing\" ? renderAndWaitRef.current!.resolve : undefined,\n } as T extends [] ? ActionRenderPropsNoArgsWait<T> : ActionRenderPropsWait<T>;\n\n // Type guard to check if renderAndWait is for no args case\n const isNoArgsRenderWait = (\n _fn:\n | ((props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement)\n | ((props: ActionRenderPropsWait<T>) => React.ReactElement),\n ): _fn is (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement => {\n return action.parameters?.length === 0;\n };\n\n // Safely call renderAndWait with correct props type\n if (renderAndWait) {\n if (isNoArgsRenderWait(renderAndWait)) {\n return renderAndWait(waitProps as ActionRenderPropsNoArgsWait<T>);\n } else {\n return renderAndWait(waitProps as ActionRenderPropsWait<T>);\n }\n }\n\n // Return empty Fragment instead of null\n return createElement(Fragment);\n }) as any;\n }\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n actions[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.actions[action.name] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.actions[action.name] = action.render;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n action.description,\n action.name,\n action.disabled,\n action.available,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(action.parameters),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\ninterface RenderAndWaitForResponse {\n promise: Promise<any>;\n resolve: (result: any) => void;\n reject: (error: any) => void;\n}\n","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\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 { CoAgentStateRender, CoAgentStateRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { CopilotRuntimeClient } from \"@copilotkit/runtime-client-gql\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n}\n\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | JSX.Element | undefined | null;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // coagent actions\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (id: string, stateRender: CoAgentStateRender<any>) => void;\n removeCoAgentStateRender: (id: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean | \"auto\";\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n // runtime\n runtimeClient: CopilotRuntimeClient;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coAgentStateRenders: {},\n setCoAgentStateRender: () => {},\n removeCoAgentStateRender: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\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 runtimeClient: {} as any,\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: \"auto\",\n coagentStates: {},\n setCoagentStates: () => {},\n\n agentSession: null,\n setAgentSession: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n return value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA2HA,oBAAoC;AACpC,IAAAA,gBAA2D;;;AC1H3D,mBAAkB;AA2IlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,CAAC;AAAA,EACtB,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAC9B,0BAA0B,MAAM;AAAA,EAAC;AAAA,EAEjC,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,qBAAqB,CAAC,EAAE,EAAE;AAAA,EACzE,kBAAkB,CAAC,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AAQ,OAAO,IAAI,IAAI,OAAO;AAAA,QAC5D;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,+BAAU,MAAM;AACd,cAAU,MAAM,SAAS,MAAa;AACtC,QAAI,oBAAoB,YAAY,QAAQ,OAAO,WAAW,QAAW;AACvE,0BAAoB,QAAQ,QAAQ,OAAO,IAAI,IAAI,OAAO;AAAA,IAC5D;AACA,WAAO,MAAM;AAGX,mBAAa,MAAM,OAAO;AAAA,IAC5B;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA;AAAA;AAAA,IAGP,KAAK,UAAU,OAAO,UAAU;AAAA;AAAA,IAEhC,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":["import_react","React"]}
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useCopilotAction
|
|
3
|
-
} from "../chunk-
|
|
4
|
-
import "../chunk-
|
|
5
|
-
import "../chunk-LNI2Z45S.mjs";
|
|
6
|
-
import "../chunk-O7ARI5CV.mjs";
|
|
3
|
+
} from "../chunk-MWZO6TUR.mjs";
|
|
4
|
+
import "../chunk-LODRWFMB.mjs";
|
|
7
5
|
import "../chunk-SKC7AJIV.mjs";
|
|
8
6
|
export {
|
|
9
7
|
useCopilotAction
|
|
@@ -28,9 +28,7 @@ interface UseCopilotChatReturn {
|
|
|
28
28
|
deleteMessage: (messageId: string) => void;
|
|
29
29
|
reloadMessages: () => Promise<void>;
|
|
30
30
|
stopGeneration: () => void;
|
|
31
|
-
reset: () => void;
|
|
32
31
|
isLoading: boolean;
|
|
33
|
-
runChatCompletion: () => Promise<Message[]>;
|
|
34
32
|
}
|
|
35
33
|
declare function useCopilotChat({ makeSystemMessage, ...options }?: UseCopilotChatOptions): UseCopilotChatReturn;
|
|
36
34
|
declare function defaultSystemMessage(contextString: string, additionalInstructions?: string): string;
|