@copilotkit/react-core 1.5.1-next.1 → 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 +21 -0
- package/dist/{chunk-SFPANIOY.mjs → chunk-2KCEHGSI.mjs} +49 -99
- package/dist/chunk-2KCEHGSI.mjs.map +1 -0
- package/dist/{chunk-YL6V3QTN.mjs → chunk-6OR25P32.mjs} +15 -42
- package/dist/chunk-6OR25P32.mjs.map +1 -0
- package/dist/{chunk-VQDGBYWQ.mjs → chunk-DDVXFNYA.mjs} +31 -55
- package/dist/chunk-DDVXFNYA.mjs.map +1 -0
- package/dist/{chunk-NYBGR2NK.mjs → chunk-FXHKK52V.mjs} +13 -14
- package/dist/chunk-FXHKK52V.mjs.map +1 -0
- package/dist/{chunk-VPTC36RZ.mjs → chunk-H4VZMKR6.mjs} +2 -2
- package/dist/{chunk-OAF4ASJH.mjs → chunk-H7LSKIDK.mjs} +23 -70
- 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-STZUYPHJ.mjs → chunk-LODRWFMB.mjs} +2 -14
- package/dist/chunk-LODRWFMB.mjs.map +1 -0
- package/dist/{chunk-MKEQ2MJG.mjs → chunk-MWZO6TUR.mjs} +13 -29
- package/dist/chunk-MWZO6TUR.mjs.map +1 -0
- package/dist/{chunk-7LRDVJH5.mjs → chunk-ODN4H66E.mjs} +2 -6
- package/dist/chunk-ODN4H66E.mjs.map +1 -0
- package/dist/{chunk-6KHA5W5R.mjs → chunk-QDGDXRRJ.mjs} +2 -2
- package/dist/{chunk-ODAH4HNG.mjs → chunk-XINZBP3J.mjs} +2 -2
- package/dist/{chunk-ODAH4HNG.mjs.map → chunk-XINZBP3J.mjs.map} +1 -1
- package/dist/components/copilot-provider/copilot-messages.d.ts +0 -1
- package/dist/components/copilot-provider/copilotkit-props.d.ts +0 -5
- package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.d.ts +0 -1
- package/dist/components/copilot-provider/copilotkit.js +91 -191
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +7 -8
- package/dist/components/copilot-provider/index.d.ts +0 -1
- package/dist/components/copilot-provider/index.js +91 -191
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +7 -8
- package/dist/components/index.d.ts +0 -1
- package/dist/components/index.js +91 -191
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +7 -8
- package/dist/components/toast/toast-provider.d.ts +1 -2
- package/dist/components/toast/toast-provider.js +62 -76
- 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 +3 -15
- package/dist/context/copilot-context.js +1 -13
- 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 +1 -13
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +4 -4
- package/dist/hooks/index.d.ts +1 -2
- package/dist/hooks/index.js +293 -624
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +22 -30
- package/dist/hooks/use-chat.d.ts +3 -31
- package/dist/hooks/use-chat.js +205 -443
- 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 +1 -13
- 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 +1 -14
- package/dist/hooks/use-coagent.js +262 -580
- package/dist/hooks/use-coagent.js.map +1 -1
- package/dist/hooks/use-coagent.mjs +11 -19
- package/dist/hooks/use-copilot-action.d.ts +2 -12
- package/dist/hooks/use-copilot-action.js +17 -167
- 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 +238 -532
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +10 -12
- package/dist/hooks/use-copilot-readable.js +1 -13
- 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 +1 -13
- 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 -3
- package/dist/index.js +391 -703
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +30 -38
- 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 +8 -10
- 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 +8 -10
- 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 +7 -8
- 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/src/components/copilot-provider/copilotkit-props.tsx +10 -0
- package/src/components/copilot-provider/copilotkit.tsx +44 -7
- package/src/components/toast/toast-provider.tsx +1 -1
- package/src/context/copilot-context.tsx +28 -2
- package/src/hooks/index.ts +1 -0
- package/src/hooks/use-chat.ts +15 -5
- package/src/hooks/use-coagent-state-render.ts +11 -0
- package/src/hooks/use-coagent.ts +11 -1
- package/src/hooks/use-copilot-authenticated-action.ts +60 -0
- package/src/hooks/use-copilot-chat.ts +1 -0
- package/dist/chunk-7LRDVJH5.mjs.map +0 -1
- package/dist/chunk-M3SYKJ3W.mjs +0 -393
- package/dist/chunk-M3SYKJ3W.mjs.map +0 -1
- package/dist/chunk-MKEQ2MJG.mjs.map +0 -1
- package/dist/chunk-NYBGR2NK.mjs.map +0 -1
- package/dist/chunk-OAF4ASJH.mjs.map +0 -1
- package/dist/chunk-QCUP6HLK.mjs +0 -37
- package/dist/chunk-QCUP6HLK.mjs.map +0 -1
- package/dist/chunk-SFPANIOY.mjs.map +0 -1
- package/dist/chunk-STZUYPHJ.mjs.map +0 -1
- package/dist/chunk-VQDGBYWQ.mjs.map +0 -1
- package/dist/chunk-XERJQUHA.mjs +0 -31
- package/dist/chunk-XERJQUHA.mjs.map +0 -1
- package/dist/chunk-YL6V3QTN.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/{chunk-VPTC36RZ.mjs.map → chunk-H4VZMKR6.mjs.map} +0 -0
- /package/dist/{chunk-6KHA5W5R.mjs.map → chunk-QDGDXRRJ.mjs.map} +0 -0
package/dist/index.mjs
CHANGED
|
@@ -1,59 +1,54 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import "./chunk-LUGEI4YQ.mjs";
|
|
3
|
-
import {
|
|
4
|
-
CopilotTask
|
|
5
|
-
} from "./chunk-NYBGR2NK.mjs";
|
|
6
2
|
import "./chunk-EFZPSZWO.mjs";
|
|
7
3
|
import "./chunk-L34MHAXR.mjs";
|
|
8
4
|
import {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
stopAgent,
|
|
12
|
-
useCoAgent
|
|
13
|
-
} from "./chunk-VQDGBYWQ.mjs";
|
|
5
|
+
useCopilotReadable
|
|
6
|
+
} from "./chunk-QDGDXRRJ.mjs";
|
|
14
7
|
import {
|
|
15
|
-
|
|
16
|
-
} from "./chunk-
|
|
8
|
+
useMakeCopilotDocumentReadable
|
|
9
|
+
} from "./chunk-H4VZMKR6.mjs";
|
|
10
|
+
import {
|
|
11
|
+
useCoAgentStateRender
|
|
12
|
+
} from "./chunk-XINZBP3J.mjs";
|
|
13
|
+
import {
|
|
14
|
+
useCoAgent
|
|
15
|
+
} from "./chunk-DDVXFNYA.mjs";
|
|
17
16
|
import {
|
|
18
17
|
useCopilotChat
|
|
19
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-H7LSKIDK.mjs";
|
|
19
|
+
import "./chunk-JDQCJCAQ.mjs";
|
|
20
20
|
import {
|
|
21
|
-
|
|
22
|
-
} from "./chunk-
|
|
21
|
+
useCopilotAction
|
|
22
|
+
} from "./chunk-MWZO6TUR.mjs";
|
|
23
|
+
import "./chunk-YPSGKPDA.mjs";
|
|
24
|
+
import "./chunk-LUGEI4YQ.mjs";
|
|
23
25
|
import {
|
|
24
|
-
|
|
25
|
-
} from "./chunk-
|
|
26
|
+
CopilotTask
|
|
27
|
+
} from "./chunk-FXHKK52V.mjs";
|
|
26
28
|
import {
|
|
27
29
|
CopilotKit,
|
|
28
30
|
defaultCopilotContextCategories,
|
|
29
31
|
extract
|
|
30
|
-
} from "./chunk-
|
|
31
|
-
import "./chunk-QCUP6HLK.mjs";
|
|
32
|
-
import {
|
|
33
|
-
shouldShowDevConsole
|
|
34
|
-
} from "./chunk-MLAS4QUR.mjs";
|
|
35
|
-
import "./chunk-XXR4QFAQ.mjs";
|
|
32
|
+
} from "./chunk-6OR25P32.mjs";
|
|
36
33
|
import "./chunk-5FHSUKQL.mjs";
|
|
37
34
|
import "./chunk-6U3UH3KO.mjs";
|
|
38
|
-
import "./chunk-
|
|
39
|
-
import {
|
|
40
|
-
CopilotMessagesContext,
|
|
41
|
-
useCopilotMessagesContext
|
|
42
|
-
} from "./chunk-DCTJZ742.mjs";
|
|
43
|
-
import "./chunk-M3SYKJ3W.mjs";
|
|
44
|
-
import "./chunk-XERJQUHA.mjs";
|
|
35
|
+
import "./chunk-XXR4QFAQ.mjs";
|
|
45
36
|
import {
|
|
46
37
|
useCopilotRuntimeClient
|
|
47
|
-
} from "./chunk-
|
|
48
|
-
import "./chunk-
|
|
38
|
+
} from "./chunk-ODN4H66E.mjs";
|
|
39
|
+
import "./chunk-2KCEHGSI.mjs";
|
|
49
40
|
import "./chunk-O7ARI5CV.mjs";
|
|
50
|
-
import {
|
|
51
|
-
useCoAgentStateRender
|
|
52
|
-
} from "./chunk-ODAH4HNG.mjs";
|
|
53
41
|
import {
|
|
54
42
|
CopilotContext,
|
|
55
43
|
useCopilotContext
|
|
56
|
-
} from "./chunk-
|
|
44
|
+
} from "./chunk-LODRWFMB.mjs";
|
|
45
|
+
import {
|
|
46
|
+
CopilotMessagesContext,
|
|
47
|
+
useCopilotMessagesContext
|
|
48
|
+
} from "./chunk-DCTJZ742.mjs";
|
|
49
|
+
import {
|
|
50
|
+
shouldShowDevConsole
|
|
51
|
+
} from "./chunk-MLAS4QUR.mjs";
|
|
57
52
|
import "./chunk-SKC7AJIV.mjs";
|
|
58
53
|
export {
|
|
59
54
|
CopilotContext,
|
|
@@ -62,10 +57,7 @@ export {
|
|
|
62
57
|
CopilotTask,
|
|
63
58
|
defaultCopilotContextCategories,
|
|
64
59
|
extract,
|
|
65
|
-
runAgent,
|
|
66
60
|
shouldShowDevConsole,
|
|
67
|
-
startAgent,
|
|
68
|
-
stopAgent,
|
|
69
61
|
useCoAgent,
|
|
70
62
|
useCoAgentStateRender,
|
|
71
63
|
useCopilotAction,
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { ForwardedParametersInput } from '@copilotkit/runtime-client-gql';
|
|
2
1
|
import { FrontendAction } from '../types/frontend-action.js';
|
|
3
2
|
import { CopilotContextParams } from '../context/copilot-context.js';
|
|
4
3
|
import '@copilotkit/shared';
|
|
@@ -8,6 +7,7 @@ import '../types/document-pointer.js';
|
|
|
8
7
|
import '../types/chat-suggestion-configuration.js';
|
|
9
8
|
import '../types/coagent-action.js';
|
|
10
9
|
import '../types/coagent-state.js';
|
|
10
|
+
import '@copilotkit/runtime-client-gql';
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/hooks/useCopilotAction), or you can provide your own context and actions.
|
|
@@ -74,17 +74,12 @@ interface CopilotTaskConfig {
|
|
|
74
74
|
* Whether to include actions defined via useCopilotAction in the task.
|
|
75
75
|
*/
|
|
76
76
|
includeCopilotActions?: boolean;
|
|
77
|
-
/**
|
|
78
|
-
* The forwarded parameters to use for the task.
|
|
79
|
-
*/
|
|
80
|
-
forwardedParameters?: ForwardedParametersInput;
|
|
81
77
|
}
|
|
82
78
|
declare class CopilotTask<T = any> {
|
|
83
79
|
private instructions;
|
|
84
80
|
private actions;
|
|
85
81
|
private includeCopilotReadable;
|
|
86
82
|
private includeCopilotActions;
|
|
87
|
-
private forwardedParameters?;
|
|
88
83
|
constructor(config: CopilotTaskConfig);
|
|
89
84
|
/**
|
|
90
85
|
* Run the task.
|
package/dist/lib/copilot-task.js
CHANGED
|
@@ -1,25 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
var __defProp = Object.defineProperty;
|
|
3
|
-
var __defProps = Object.defineProperties;
|
|
4
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
6
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
-
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
8
5
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
-
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
10
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
11
|
-
var __spreadValues = (a, b) => {
|
|
12
|
-
for (var prop in b || (b = {}))
|
|
13
|
-
if (__hasOwnProp.call(b, prop))
|
|
14
|
-
__defNormalProp(a, prop, b[prop]);
|
|
15
|
-
if (__getOwnPropSymbols)
|
|
16
|
-
for (var prop of __getOwnPropSymbols(b)) {
|
|
17
|
-
if (__propIsEnum.call(b, prop))
|
|
18
|
-
__defNormalProp(a, prop, b[prop]);
|
|
19
|
-
}
|
|
20
|
-
return a;
|
|
21
|
-
};
|
|
22
|
-
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
23
6
|
var __export = (target, all) => {
|
|
24
7
|
for (var name in all)
|
|
25
8
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -60,48 +43,23 @@ __export(copilot_task_exports, {
|
|
|
60
43
|
CopilotTask: () => CopilotTask
|
|
61
44
|
});
|
|
62
45
|
module.exports = __toCommonJS(copilot_task_exports);
|
|
63
|
-
var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
|
|
64
|
-
|
|
65
|
-
// src/types/frontend-action.ts
|
|
66
46
|
var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
|
|
67
|
-
var import_shared = require("@copilotkit/shared");
|
|
68
|
-
function processActionsForRuntimeRequest(actions) {
|
|
69
|
-
const filteredActions = actions.filter(
|
|
70
|
-
(action) => action.available !== import_runtime_client_gql.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*"
|
|
71
|
-
).map((action) => {
|
|
72
|
-
let available = import_runtime_client_gql.ActionInputAvailability.Enabled;
|
|
73
|
-
if (action.disabled) {
|
|
74
|
-
available = import_runtime_client_gql.ActionInputAvailability.Disabled;
|
|
75
|
-
} else if (action.available === "disabled") {
|
|
76
|
-
available = import_runtime_client_gql.ActionInputAvailability.Disabled;
|
|
77
|
-
} else if (action.available === "remote") {
|
|
78
|
-
available = import_runtime_client_gql.ActionInputAvailability.Remote;
|
|
79
|
-
}
|
|
80
|
-
return {
|
|
81
|
-
name: action.name,
|
|
82
|
-
description: action.description || "",
|
|
83
|
-
jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || [])),
|
|
84
|
-
available
|
|
85
|
-
};
|
|
86
|
-
});
|
|
87
|
-
return filteredActions;
|
|
88
|
-
}
|
|
89
47
|
|
|
90
48
|
// src/components/copilot-provider/copilotkit.tsx
|
|
91
49
|
var import_react = require("react");
|
|
92
50
|
var import_react_dom = require("react-dom");
|
|
93
|
-
var
|
|
51
|
+
var import_shared = require("@copilotkit/shared");
|
|
94
52
|
var import_jsx_runtime = require("react/jsx-runtime");
|
|
95
53
|
var defaultCopilotContextCategories = ["global"];
|
|
96
54
|
|
|
97
55
|
// src/lib/copilot-task.ts
|
|
56
|
+
var import_shared2 = require("@copilotkit/shared");
|
|
98
57
|
var CopilotTask = class {
|
|
99
58
|
constructor(config) {
|
|
100
59
|
this.instructions = config.instructions;
|
|
101
60
|
this.actions = config.actions || [];
|
|
102
61
|
this.includeCopilotReadable = config.includeCopilotReadable !== false;
|
|
103
62
|
this.includeCopilotActions = config.includeCopilotActions !== false;
|
|
104
|
-
this.forwardedParameters = config.forwardedParameters;
|
|
105
63
|
}
|
|
106
64
|
/**
|
|
107
65
|
* Run the task.
|
|
@@ -110,7 +68,7 @@ var CopilotTask = class {
|
|
|
110
68
|
*/
|
|
111
69
|
run(context, data) {
|
|
112
70
|
return __async(this, null, function* () {
|
|
113
|
-
var _a, _b
|
|
71
|
+
var _a, _b;
|
|
114
72
|
const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
|
|
115
73
|
for (const fn of this.actions) {
|
|
116
74
|
actions[fn.name] = fn;
|
|
@@ -122,12 +80,12 @@ var CopilotTask = class {
|
|
|
122
80
|
if (this.includeCopilotReadable) {
|
|
123
81
|
contextString += context.getContextString([], defaultCopilotContextCategories);
|
|
124
82
|
}
|
|
125
|
-
const systemMessage = new
|
|
83
|
+
const systemMessage = new import_runtime_client_gql.TextMessage({
|
|
126
84
|
content: taskSystemMessage(contextString, this.instructions),
|
|
127
|
-
role:
|
|
85
|
+
role: import_runtime_client_gql.Role.System
|
|
128
86
|
});
|
|
129
87
|
const messages = [systemMessage];
|
|
130
|
-
const runtimeClient = new
|
|
88
|
+
const runtimeClient = new import_runtime_client_gql.CopilotRuntimeClient({
|
|
131
89
|
url: context.copilotApiConfig.chatApiEndpoint,
|
|
132
90
|
publicApiKey: context.copilotApiConfig.publicApiKey,
|
|
133
91
|
headers: context.copilotApiConfig.headers,
|
|
@@ -136,22 +94,26 @@ var CopilotTask = class {
|
|
|
136
94
|
const response = yield runtimeClient.generateCopilotResponse({
|
|
137
95
|
data: {
|
|
138
96
|
frontend: {
|
|
139
|
-
actions:
|
|
97
|
+
actions: Object.values(actions).map((action) => ({
|
|
98
|
+
name: action.name,
|
|
99
|
+
description: action.description || "",
|
|
100
|
+
jsonSchema: JSON.stringify((0, import_shared2.actionParametersToJsonSchema)(action.parameters || []))
|
|
101
|
+
})),
|
|
140
102
|
url: window.location.href
|
|
141
103
|
},
|
|
142
|
-
messages: (0,
|
|
104
|
+
messages: (0, import_runtime_client_gql.convertMessagesToGqlInput)((0, import_runtime_client_gql.filterAgentStateMessages)(messages)),
|
|
143
105
|
metadata: {
|
|
144
|
-
requestType:
|
|
106
|
+
requestType: import_runtime_client_gql.CopilotRequestType.Task
|
|
145
107
|
},
|
|
146
|
-
forwardedParameters:
|
|
108
|
+
forwardedParameters: {
|
|
147
109
|
toolChoice: "required"
|
|
148
|
-
}
|
|
110
|
+
}
|
|
149
111
|
},
|
|
150
112
|
properties: context.copilotApiConfig.properties
|
|
151
113
|
}).toPromise();
|
|
152
114
|
const functionCallHandler = context.getFunctionCallHandler(actions);
|
|
153
|
-
const functionCalls = (0,
|
|
154
|
-
((
|
|
115
|
+
const functionCalls = (0, import_runtime_client_gql.convertGqlOutputToMessages)(
|
|
116
|
+
((_b = (_a = response.data) == null ? void 0 : _a.generateCopilotResponse) == null ? void 0 : _b.messages) || []
|
|
155
117
|
).filter((m) => m.isActionExecutionMessage());
|
|
156
118
|
for (const functionCall of functionCalls) {
|
|
157
119
|
yield functionCallHandler({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/lib/copilot-task.ts","../../src/types/frontend-action.ts","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n * }\n * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { FrontendAction, processActionsForRuntimeRequest } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: ForwardedParametersInput;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n private forwardedParameters?: ForwardedParametersInput;\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions = config.includeCopilotActions !== false;\n this.forwardedParameters = config.forwardedParameters;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: processActionsForRuntimeRequest(Object.values(actions)),\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n // if forwardedParameters is provided, use it\n ...(this.forwardedParameters ?? {}),\n toolChoice: \"required\",\n },\n },\n properties: context.copilotApiConfig.properties,\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m.isActionExecutionMessage());\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\n }\n }\n}\n\nfunction taskSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n","import { ActionInputAvailability } from \"@copilotkit/runtime-client-gql\";\nimport {\n Action,\n Parameter,\n MappedParameterTypes,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport React from \"react\";\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingState<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n result: undefined;\n}\n\ninterface CompleteStateNoArgs<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n result: any;\n}\n\ninterface InProgressStateWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: any;\n}\n\ninterface InProgressStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n result: undefined;\n}\n\ninterface ExecutingStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"executing\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: (result: any) => void;\n respond: (result: any) => void;\n result: undefined;\n}\n\ninterface CompleteStateNoArgsWait<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n /** @deprecated use respond instead */\n handler: undefined;\n respond: undefined;\n}\n\nexport type ActionRenderProps<T extends Parameter[] | [] = []> =\n | CompleteState<T>\n | ExecutingState<T>\n | InProgressState<T>;\n\nexport type ActionRenderPropsNoArgs<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgs<T>\n | ExecutingStateNoArgs<T>\n | InProgressStateNoArgs<T>;\n\nexport type ActionRenderPropsWait<T extends Parameter[] | [] = []> =\n | CompleteStateWait<T>\n | ExecutingStateWait<T>\n | InProgressStateWait<T>;\n\nexport type ActionRenderPropsNoArgsWait<T extends Parameter[] | [] = []> =\n | CompleteStateNoArgsWait<T>\n | ExecutingStateNoArgsWait<T>\n | InProgressStateNoArgsWait<T>;\n\nexport type CatchAllActionRenderProps<T extends Parameter[] | [] = []> =\n | (CompleteState<T> & {\n name: string;\n })\n | (ExecutingState<T> & {\n name: string;\n })\n | (InProgressState<T> & {\n name: string;\n });\n\nexport type FrontendActionAvailability = \"disabled\" | \"enabled\" | \"remote\";\n\nexport type FrontendAction<\n T extends Parameter[] | [] = [],\n N extends string = string,\n> = Action<T> & {\n name: Exclude<N, \"*\">;\n /**\n * @deprecated Use `available` instead.\n */\n disabled?: boolean;\n available?: FrontendActionAvailability;\n followUp?: boolean;\n} & (\n | {\n render?:\n | string\n | (T extends []\n ? (props: ActionRenderPropsNoArgs<T>) => string | React.ReactElement\n : (props: ActionRenderProps<T>) => string | React.ReactElement);\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: never;\n renderAndWaitForResponse?: never;\n }\n | {\n render?: never;\n /** @deprecated use renderAndWaitForResponse instead */\n renderAndWait?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n renderAndWaitForResponse?: T extends []\n ? (props: ActionRenderPropsNoArgsWait<T>) => React.ReactElement\n : (props: ActionRenderPropsWait<T>) => React.ReactElement;\n handler?: never;\n }\n );\n\nexport type CatchAllFrontendAction = {\n name: \"*\";\n render: (props: CatchAllActionRenderProps<any>) => React.ReactElement;\n};\n\nexport type RenderFunctionStatus = ActionRenderProps<any>[\"status\"];\n\nexport function processActionsForRuntimeRequest(actions: FrontendAction<any>[]) {\n const filteredActions = actions\n .filter(\n (action) =>\n action.available !== ActionInputAvailability.Disabled &&\n action.disabled !== true &&\n action.name !== \"*\",\n )\n .map((action) => {\n let available: ActionInputAvailability | undefined = ActionInputAvailability.Enabled;\n if (action.disabled) {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"disabled\") {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"remote\") {\n available = ActionInputAvailability.Remote;\n }\n return {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n available,\n };\n });\n return filteredActions;\n}\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n} from \"@copilotkit/shared\";\n\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoAgentStateRender } from \"../../types/coagent-action\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"../../hooks/use-copilot-runtime-client\";\nimport { shouldShowDevConsole } from \"../../utils\";\nimport { CopilotErrorBoundary } from \"../error-boundary/error-boundary\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const showDevConsole = props.showDevConsole === undefined ? \"auto\" : props.showDevConsole;\n const enabled = shouldShowDevConsole(showDevConsole);\n return (\n <ToastProvider enabled={enabled}>\n <CopilotErrorBoundary>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </CopilotErrorBoundary>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n if (!props.runtimeUrl && !props.publicApiKey) {\n throw new Error(\n \"Please provide either a runtimeUrl or a publicApiKey to the CopilotKit component.\",\n );\n }\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n const { addElement, removeElement, printTree } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const setCoAgentStateRender = useCallback((id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => {\n return {\n ...prevPoints,\n [id]: stateRender,\n };\n });\n }, []);\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n if (!props.publicApiKey) {\n if (props.cloudRestrictToTopic) {\n throw new Error(\n \"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide a publicApiKey.\",\n );\n }\n }\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n props.publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n ]);\n\n const headers = {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n });\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n };\n\n const removeChatSuggestionConfiguration = (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n };\n\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n const coagentStatesRef = useRef<Record<string, CoagentState>>({});\n const setCoagentStatesWithRef = useCallback(\n (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => {\n const newValue = typeof value === \"function\" ? value(coagentStatesRef.current) : value;\n coagentStatesRef.current = newValue;\n setCoagentStates((prev) => {\n return newValue;\n });\n },\n [],\n );\n\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n const [threadId, setThreadId] = useState<string | null>(null);\n const [runId, setRunId] = useState<string | null>(null);\n\n const chatAbortControllerRef = useRef<AbortController | null>(null);\n\n const showDevConsole = props.showDevConsole === undefined ? \"auto\" : props.showDevConsole;\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n runtimeClient,\n forwardedParameters: props.forwardedParameters || {},\n agentLock: props.agent || null,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n }}\n >\n <CopilotMessages>{children}</CopilotMessages>\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ messages, name, args }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgDA,IAAAA,6BAWO;;;AC3DP,gCAAwC;AACxC,oBAKO;AAuKA,SAAS,gCAAgC,SAAgC;AAC9E,QAAM,kBAAkB,QACrB;AAAA,IACC,CAAC,WACC,OAAO,cAAc,kDAAwB,YAC7C,OAAO,aAAa,QACpB,OAAO,SAAS;AAAA,EACpB,EACC,IAAI,CAAC,WAAW;AACf,QAAI,YAAiD,kDAAwB;AAC7E,QAAI,OAAO,UAAU;AACnB,kBAAY,kDAAwB;AAAA,IACtC,WAAW,OAAO,cAAc,YAAY;AAC1C,kBAAY,kDAAwB;AAAA,IACtC,WAAW,OAAO,cAAc,UAAU;AACxC,kBAAY,kDAAwB;AAAA,IACtC;AACA,WAAO;AAAA,MACL,MAAM,OAAO;AAAA,MACb,aAAa,OAAO,eAAe;AAAA,MACnC,YAAY,KAAK,cAAU,4CAA6B,OAAO,cAAc,CAAC,CAAC,CAAC;AAAA,MAChF;AAAA,IACF;AAAA,EACF,CAAC;AACH,SAAO;AACT;;;ACtLA,mBAAuD;AASvD,uBAA0B;AAC1B,IAAAC,iBAKO;AAmBC;AA+RD,IAAM,kCAAkC,CAAC,QAAQ;;;AFxPjD,IAAM,cAAN,MAA2B;AAAA,EAMhC,YAAY,QAA2B;AACrC,SAAK,eAAe,OAAO;AAC3B,SAAK,UAAU,OAAO,WAAW,CAAC;AAClC,SAAK,yBAAyB,OAAO,2BAA2B;AAChE,SAAK,wBAAwB,OAAO,0BAA0B;AAC9D,SAAK,sBAAsB,OAAO;AAAA,EACpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOM,IAAI,SAA+B,MAAyB;AAAA;AA5GpE;AA6GI,YAAM,UAAU,KAAK,wBAAwB,OAAO,OAAO,CAAC,GAAG,QAAQ,OAAO,IAAI,CAAC;AAGnF,iBAAW,MAAM,KAAK,SAAS;AAC7B,gBAAQ,GAAG,IAAI,IAAI;AAAA,MACrB;AAEA,UAAI,gBAAgB;AAEpB,UAAI,MAAM;AACR,yBAAiB,OAAO,SAAS,WAAW,OAAO,KAAK,UAAU,IAAI,KAAK;AAAA,MAC7E;AAEA,UAAI,KAAK,wBAAwB;AAC/B,yBAAiB,QAAQ,iBAAiB,CAAC,GAAG,+BAA+B;AAAA,MAC/E;AAEA,YAAM,gBAAgB,IAAI,uCAAY;AAAA,QACpC,SAAS,kBAAkB,eAAe,KAAK,YAAY;AAAA,QAC3D,MAAM,gCAAK;AAAA,MACb,CAAC;AAED,YAAM,WAAsB,CAAC,aAAa;AAE1C,YAAM,gBAAgB,IAAI,gDAAqB;AAAA,QAC7C,KAAK,QAAQ,iBAAiB;AAAA,QAC9B,cAAc,QAAQ,iBAAiB;AAAA,QACvC,SAAS,QAAQ,iBAAiB;AAAA,QAClC,aAAa,QAAQ,iBAAiB;AAAA,MACxC,CAAC;AAED,YAAM,WAAW,MAAM,cACpB,wBAAwB;AAAA,QACvB,MAAM;AAAA,UACJ,UAAU;AAAA,YACR,SAAS,gCAAgC,OAAO,OAAO,OAAO,CAAC;AAAA,YAC/D,KAAK,OAAO,SAAS;AAAA,UACvB;AAAA,UACA,cAAU,0DAA0B,qDAAyB,QAAQ,CAAC;AAAA,UACtE,UAAU;AAAA,YACR,aAAa,8CAAmB;AAAA,UAClC;AAAA,UACA,qBAAqB,kCAEf,UAAK,wBAAL,YAA4B,CAAC,IAFd;AAAA,YAGnB,YAAY;AAAA,UACd;AAAA,QACF;AAAA,QACA,YAAY,QAAQ,iBAAiB;AAAA,MACvC,CAAC,EACA,UAAU;AAEb,YAAM,sBAAsB,QAAQ,uBAAuB,OAAO;AAClE,YAAM,oBAAgB;AAAA,UACpB,oBAAS,SAAT,mBAAe,4BAAf,mBAAwC,aAAY,CAAC;AAAA,MACvD,EAAE,OAAO,CAAC,MAAmC,EAAE,yBAAyB,CAAC;AAEzE,iBAAW,gBAAgB,eAAe;AACxC,cAAM,oBAAoB;AAAA,UACxB;AAAA,UACA,MAAM,aAAa;AAAA,UACnB,MAAM,aAAa;AAAA,QACrB,CAAC;AAAA,MACH;AAAA,IACF;AAAA;AACF;AAEA,SAAS,kBAAkB,eAAuB,cAA8B;AAC9E,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA;AAAA;AAAA;AAGF;","names":["import_runtime_client_gql","import_shared"]}
|
|
1
|
+
{"version":3,"sources":["../../src/lib/copilot-task.ts","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n * }\n * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n} from \"@copilotkit/runtime-client-gql\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { MessageStatusCode } from \"@copilotkit/runtime-client-gql\";\nimport { actionParametersToJsonSchema } from \"@copilotkit/shared\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions = config.includeCopilotActions !== false;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: Object.values(actions).map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n toolChoice: \"required\",\n },\n },\n properties: context.copilotApiConfig.properties,\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m.isActionExecutionMessage());\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\n }\n }\n}\n\nfunction taskSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n","/**\n * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.\n *\n * ## Example\n *\n * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).\n *\n * ```tsx\n * import { CopilotKit } from \"@copilotkit/react-core\";\n *\n * <CopilotKit runtimeUrl=\"<your-runtime-url>\">\n * // ... your app ...\n * </CopilotKit>\n * ```\n */\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n ChatComponentsCache,\n AgentSession,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\nimport { flushSync } from \"react-dom\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n} from \"@copilotkit/shared\";\n\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { CoAgentStateRender } from \"../../types/coagent-action\";\nimport { CoagentState } from \"../../types/coagent-state\";\nimport { CopilotMessages } from \"./copilot-messages\";\nimport { ToastProvider } from \"../toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"../../hooks/use-copilot-runtime-client\";\nimport { shouldShowDevConsole } from \"../../utils\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n const showDevConsole = props.showDevConsole === undefined ? \"auto\" : props.showDevConsole;\n const enabled = shouldShowDevConsole(showDevConsole);\n return (\n <ToastProvider enabled={enabled}>\n <CopilotKitInternal {...props}>{children}</CopilotKitInternal>\n </ToastProvider>\n );\n}\n\nexport function CopilotKitInternal({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n if (!props.runtimeUrl && !props.publicApiKey) {\n throw new Error(\n \"Please provide either a runtimeUrl or a publicApiKey to the CopilotKit component.\",\n );\n }\n\n const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n const chatComponentsCache = useRef<ChatComponentsCache>({\n actions: {},\n coAgentStateRenders: {},\n });\n const { addElement, removeElement, printTree } = useTree();\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const setCoAgentStateRender = useCallback((id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => {\n return {\n ...prevPoints,\n [id]: stateRender,\n };\n });\n }, []);\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n if (!props.publicApiKey) {\n if (props.cloudRestrictToTopic) {\n throw new Error(\n \"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide a publicApiKey.\",\n );\n }\n }\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = useMemo(() => {\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n return {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n }, [\n props.publicApiKey,\n props.headers,\n props.properties,\n props.transcribeAudioUrl,\n props.textToSpeechUrl,\n props.credentials,\n props.cloudRestrictToTopic,\n ]);\n\n const headers = {\n ...(copilotApiConfig.headers || {}),\n ...(copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey }\n : {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotApiConfig.chatApiEndpoint,\n publicApiKey: copilotApiConfig.publicApiKey,\n headers,\n credentials: copilotApiConfig.credentials,\n });\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n };\n\n const removeChatSuggestionConfiguration = (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n };\n\n const [coagentStates, setCoagentStates] = useState<Record<string, CoagentState>>({});\n let initialAgentSession: AgentSession | null = null;\n if (props.agent) {\n initialAgentSession = {\n agentName: props.agent,\n };\n }\n\n const [agentSession, setAgentSession] = useState<AgentSession | null>(initialAgentSession);\n\n const showDevConsole = props.showDevConsole === undefined ? \"auto\" : props.showDevConsole;\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n showDevConsole,\n coagentStates,\n setCoagentStates,\n agentSession,\n setAgentSession,\n runtimeClient,\n }}\n >\n <CopilotMessages>{children}</CopilotMessages>\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ messages, name, args }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n let result: any = undefined;\n if (action) {\n await new Promise<void>((resolve, reject) => {\n flushSync(async () => {\n try {\n result = await action.handler?.(args);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n });\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n return result;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgDA,gCAUO;;;AC1CP,mBAAuD;AASvD,uBAA0B;AAC1B,oBAKO;AAiBD;AAiQC,IAAM,kCAAkC,CAAC,QAAQ;;;ADlPxD,IAAAA,iBAA6C;AAsBtC,IAAM,cAAN,MAA2B;AAAA,EAMhC,YAAY,QAA2B;AACrC,SAAK,eAAe,OAAO;AAC3B,SAAK,UAAU,OAAO,WAAW,CAAC;AAClC,SAAK,yBAAyB,OAAO,2BAA2B;AAChE,SAAK,wBAAwB,OAAO,0BAA0B;AAAA,EAChE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOM,IAAI,SAA+B,MAAyB;AAAA;AAvGpE;AAwGI,YAAM,UAAU,KAAK,wBAAwB,OAAO,OAAO,CAAC,GAAG,QAAQ,OAAO,IAAI,CAAC;AAGnF,iBAAW,MAAM,KAAK,SAAS;AAC7B,gBAAQ,GAAG,IAAI,IAAI;AAAA,MACrB;AAEA,UAAI,gBAAgB;AAEpB,UAAI,MAAM;AACR,yBAAiB,OAAO,SAAS,WAAW,OAAO,KAAK,UAAU,IAAI,KAAK;AAAA,MAC7E;AAEA,UAAI,KAAK,wBAAwB;AAC/B,yBAAiB,QAAQ,iBAAiB,CAAC,GAAG,+BAA+B;AAAA,MAC/E;AAEA,YAAM,gBAAgB,IAAI,sCAAY;AAAA,QACpC,SAAS,kBAAkB,eAAe,KAAK,YAAY;AAAA,QAC3D,MAAM,+BAAK;AAAA,MACb,CAAC;AAED,YAAM,WAAsB,CAAC,aAAa;AAE1C,YAAM,gBAAgB,IAAI,+CAAqB;AAAA,QAC7C,KAAK,QAAQ,iBAAiB;AAAA,QAC9B,cAAc,QAAQ,iBAAiB;AAAA,QACvC,SAAS,QAAQ,iBAAiB;AAAA,QAClC,aAAa,QAAQ,iBAAiB;AAAA,MACxC,CAAC;AAED,YAAM,WAAW,MAAM,cACpB,wBAAwB;AAAA,QACvB,MAAM;AAAA,UACJ,UAAU;AAAA,YACR,SAAS,OAAO,OAAO,OAAO,EAAE,IAAI,CAAC,YAAY;AAAA,cAC/C,MAAM,OAAO;AAAA,cACb,aAAa,OAAO,eAAe;AAAA,cACnC,YAAY,KAAK,cAAU,6CAA6B,OAAO,cAAc,CAAC,CAAC,CAAC;AAAA,YAClF,EAAE;AAAA,YACF,KAAK,OAAO,SAAS;AAAA,UACvB;AAAA,UACA,cAAU,yDAA0B,oDAAyB,QAAQ,CAAC;AAAA,UACtE,UAAU;AAAA,YACR,aAAa,6CAAmB;AAAA,UAClC;AAAA,UACA,qBAAqB;AAAA,YACnB,YAAY;AAAA,UACd;AAAA,QACF;AAAA,QACA,YAAY,QAAQ,iBAAiB;AAAA,MACvC,CAAC,EACA,UAAU;AAEb,YAAM,sBAAsB,QAAQ,uBAAuB,OAAO;AAClE,YAAM,oBAAgB;AAAA,UACpB,oBAAS,SAAT,mBAAe,4BAAf,mBAAwC,aAAY,CAAC;AAAA,MACvD,EAAE,OAAO,CAAC,MAAmC,EAAE,yBAAyB,CAAC;AAEzE,iBAAW,gBAAgB,eAAe;AACxC,cAAM,oBAAoB;AAAA,UACxB;AAAA,UACA,MAAM,aAAa;AAAA,UACnB,MAAM,aAAa;AAAA,QACrB,CAAC;AAAA,MACH;AAAA,IACF;AAAA;AACF;AAEA,SAAS,kBAAkB,eAAuB,cAA8B;AAC9E,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA;AAAA;AAAA;AAGF;","names":["import_shared"]}
|
|
@@ -1,18 +1,16 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CopilotTask
|
|
3
|
-
} from "../chunk-
|
|
4
|
-
import "../chunk-
|
|
5
|
-
import "../chunk-QCUP6HLK.mjs";
|
|
6
|
-
import "../chunk-MLAS4QUR.mjs";
|
|
7
|
-
import "../chunk-XXR4QFAQ.mjs";
|
|
3
|
+
} from "../chunk-FXHKK52V.mjs";
|
|
4
|
+
import "../chunk-6OR25P32.mjs";
|
|
8
5
|
import "../chunk-5FHSUKQL.mjs";
|
|
9
6
|
import "../chunk-6U3UH3KO.mjs";
|
|
10
|
-
import "../chunk-
|
|
11
|
-
import "../chunk-
|
|
12
|
-
import "../chunk-
|
|
13
|
-
import "../chunk-SFPANIOY.mjs";
|
|
7
|
+
import "../chunk-XXR4QFAQ.mjs";
|
|
8
|
+
import "../chunk-ODN4H66E.mjs";
|
|
9
|
+
import "../chunk-2KCEHGSI.mjs";
|
|
14
10
|
import "../chunk-O7ARI5CV.mjs";
|
|
15
|
-
import "../chunk-
|
|
11
|
+
import "../chunk-LODRWFMB.mjs";
|
|
12
|
+
import "../chunk-DCTJZ742.mjs";
|
|
13
|
+
import "../chunk-MLAS4QUR.mjs";
|
|
16
14
|
import "../chunk-SKC7AJIV.mjs";
|
|
17
15
|
export {
|
|
18
16
|
CopilotTask
|
package/dist/lib/index.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
export { CopilotTask, CopilotTaskConfig } from './copilot-task.js';
|
|
2
|
-
import '@copilotkit/runtime-client-gql';
|
|
3
2
|
import '../types/frontend-action.js';
|
|
4
3
|
import '@copilotkit/shared';
|
|
5
4
|
import 'react';
|
|
@@ -9,3 +8,4 @@ import '../types/document-pointer.js';
|
|
|
9
8
|
import '../types/chat-suggestion-configuration.js';
|
|
10
9
|
import '../types/coagent-action.js';
|
|
11
10
|
import '../types/coagent-state.js';
|
|
11
|
+
import '@copilotkit/runtime-client-gql';
|
package/dist/lib/index.js
CHANGED
|
@@ -1,25 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
var __defProp = Object.defineProperty;
|
|
3
|
-
var __defProps = Object.defineProperties;
|
|
4
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
6
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
-
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
8
5
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
-
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
10
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
11
|
-
var __spreadValues = (a, b) => {
|
|
12
|
-
for (var prop in b || (b = {}))
|
|
13
|
-
if (__hasOwnProp.call(b, prop))
|
|
14
|
-
__defNormalProp(a, prop, b[prop]);
|
|
15
|
-
if (__getOwnPropSymbols)
|
|
16
|
-
for (var prop of __getOwnPropSymbols(b)) {
|
|
17
|
-
if (__propIsEnum.call(b, prop))
|
|
18
|
-
__defNormalProp(a, prop, b[prop]);
|
|
19
|
-
}
|
|
20
|
-
return a;
|
|
21
|
-
};
|
|
22
|
-
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
23
6
|
var __export = (target, all) => {
|
|
24
7
|
for (var name in all)
|
|
25
8
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -62,48 +45,23 @@ __export(lib_exports, {
|
|
|
62
45
|
module.exports = __toCommonJS(lib_exports);
|
|
63
46
|
|
|
64
47
|
// src/lib/copilot-task.ts
|
|
65
|
-
var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
|
|
66
|
-
|
|
67
|
-
// src/types/frontend-action.ts
|
|
68
48
|
var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
|
|
69
|
-
var import_shared = require("@copilotkit/shared");
|
|
70
|
-
function processActionsForRuntimeRequest(actions) {
|
|
71
|
-
const filteredActions = actions.filter(
|
|
72
|
-
(action) => action.available !== import_runtime_client_gql.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*"
|
|
73
|
-
).map((action) => {
|
|
74
|
-
let available = import_runtime_client_gql.ActionInputAvailability.Enabled;
|
|
75
|
-
if (action.disabled) {
|
|
76
|
-
available = import_runtime_client_gql.ActionInputAvailability.Disabled;
|
|
77
|
-
} else if (action.available === "disabled") {
|
|
78
|
-
available = import_runtime_client_gql.ActionInputAvailability.Disabled;
|
|
79
|
-
} else if (action.available === "remote") {
|
|
80
|
-
available = import_runtime_client_gql.ActionInputAvailability.Remote;
|
|
81
|
-
}
|
|
82
|
-
return {
|
|
83
|
-
name: action.name,
|
|
84
|
-
description: action.description || "",
|
|
85
|
-
jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || [])),
|
|
86
|
-
available
|
|
87
|
-
};
|
|
88
|
-
});
|
|
89
|
-
return filteredActions;
|
|
90
|
-
}
|
|
91
49
|
|
|
92
50
|
// src/components/copilot-provider/copilotkit.tsx
|
|
93
51
|
var import_react = require("react");
|
|
94
52
|
var import_react_dom = require("react-dom");
|
|
95
|
-
var
|
|
53
|
+
var import_shared = require("@copilotkit/shared");
|
|
96
54
|
var import_jsx_runtime = require("react/jsx-runtime");
|
|
97
55
|
var defaultCopilotContextCategories = ["global"];
|
|
98
56
|
|
|
99
57
|
// src/lib/copilot-task.ts
|
|
58
|
+
var import_shared2 = require("@copilotkit/shared");
|
|
100
59
|
var CopilotTask = class {
|
|
101
60
|
constructor(config) {
|
|
102
61
|
this.instructions = config.instructions;
|
|
103
62
|
this.actions = config.actions || [];
|
|
104
63
|
this.includeCopilotReadable = config.includeCopilotReadable !== false;
|
|
105
64
|
this.includeCopilotActions = config.includeCopilotActions !== false;
|
|
106
|
-
this.forwardedParameters = config.forwardedParameters;
|
|
107
65
|
}
|
|
108
66
|
/**
|
|
109
67
|
* Run the task.
|
|
@@ -112,7 +70,7 @@ var CopilotTask = class {
|
|
|
112
70
|
*/
|
|
113
71
|
run(context, data) {
|
|
114
72
|
return __async(this, null, function* () {
|
|
115
|
-
var _a, _b
|
|
73
|
+
var _a, _b;
|
|
116
74
|
const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
|
|
117
75
|
for (const fn of this.actions) {
|
|
118
76
|
actions[fn.name] = fn;
|
|
@@ -124,12 +82,12 @@ var CopilotTask = class {
|
|
|
124
82
|
if (this.includeCopilotReadable) {
|
|
125
83
|
contextString += context.getContextString([], defaultCopilotContextCategories);
|
|
126
84
|
}
|
|
127
|
-
const systemMessage = new
|
|
85
|
+
const systemMessage = new import_runtime_client_gql.TextMessage({
|
|
128
86
|
content: taskSystemMessage(contextString, this.instructions),
|
|
129
|
-
role:
|
|
87
|
+
role: import_runtime_client_gql.Role.System
|
|
130
88
|
});
|
|
131
89
|
const messages = [systemMessage];
|
|
132
|
-
const runtimeClient = new
|
|
90
|
+
const runtimeClient = new import_runtime_client_gql.CopilotRuntimeClient({
|
|
133
91
|
url: context.copilotApiConfig.chatApiEndpoint,
|
|
134
92
|
publicApiKey: context.copilotApiConfig.publicApiKey,
|
|
135
93
|
headers: context.copilotApiConfig.headers,
|
|
@@ -138,22 +96,26 @@ var CopilotTask = class {
|
|
|
138
96
|
const response = yield runtimeClient.generateCopilotResponse({
|
|
139
97
|
data: {
|
|
140
98
|
frontend: {
|
|
141
|
-
actions:
|
|
99
|
+
actions: Object.values(actions).map((action) => ({
|
|
100
|
+
name: action.name,
|
|
101
|
+
description: action.description || "",
|
|
102
|
+
jsonSchema: JSON.stringify((0, import_shared2.actionParametersToJsonSchema)(action.parameters || []))
|
|
103
|
+
})),
|
|
142
104
|
url: window.location.href
|
|
143
105
|
},
|
|
144
|
-
messages: (0,
|
|
106
|
+
messages: (0, import_runtime_client_gql.convertMessagesToGqlInput)((0, import_runtime_client_gql.filterAgentStateMessages)(messages)),
|
|
145
107
|
metadata: {
|
|
146
|
-
requestType:
|
|
108
|
+
requestType: import_runtime_client_gql.CopilotRequestType.Task
|
|
147
109
|
},
|
|
148
|
-
forwardedParameters:
|
|
110
|
+
forwardedParameters: {
|
|
149
111
|
toolChoice: "required"
|
|
150
|
-
}
|
|
112
|
+
}
|
|
151
113
|
},
|
|
152
114
|
properties: context.copilotApiConfig.properties
|
|
153
115
|
}).toPromise();
|
|
154
116
|
const functionCallHandler = context.getFunctionCallHandler(actions);
|
|
155
|
-
const functionCalls = (0,
|
|
156
|
-
((
|
|
117
|
+
const functionCalls = (0, import_runtime_client_gql.convertGqlOutputToMessages)(
|
|
118
|
+
((_b = (_a = response.data) == null ? void 0 : _a.generateCopilotResponse) == null ? void 0 : _b.messages) || []
|
|
157
119
|
).filter((m) => m.isActionExecutionMessage());
|
|
158
120
|
for (const functionCall of functionCalls) {
|
|
159
121
|
yield functionCallHandler({
|