@glodon-aiot/bot-client-sdk 3.3.2-beta.15 → 3.3.2-beta.17
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/dist/es/AgentSession.mjs +42 -25
- package/dist/es/Session.mjs +109 -108
- package/dist/es/package.json.mjs +2 -2
- package/dist/lib/index.js +3 -3
- package/dist/src/Session.d.ts +1 -1
- package/dist/src/constant.d.ts +13 -0
- package/package.json +2 -2
package/dist/es/AgentSession.mjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
1
|
+
var A = Object.defineProperty, C = Object.defineProperties;
|
|
2
|
+
var S = Object.getOwnPropertyDescriptors;
|
|
3
3
|
var _ = Object.getOwnPropertySymbols;
|
|
4
4
|
var P = Object.prototype.hasOwnProperty, x = Object.prototype.propertyIsEnumerable;
|
|
5
|
-
var
|
|
5
|
+
var b = (m, t, n) => t in m ? A(m, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : m[t] = n, g = (m, t) => {
|
|
6
6
|
for (var n in t || (t = {}))
|
|
7
|
-
P.call(t, n) &&
|
|
7
|
+
P.call(t, n) && b(m, n, t[n]);
|
|
8
8
|
if (_)
|
|
9
9
|
for (var n of _(t))
|
|
10
|
-
x.call(t, n) &&
|
|
10
|
+
x.call(t, n) && b(m, n, t[n]);
|
|
11
11
|
return m;
|
|
12
|
-
}, k = (m, t) =>
|
|
12
|
+
}, k = (m, t) => C(m, S(t));
|
|
13
13
|
var v = (m, t, n) => new Promise((o, i) => {
|
|
14
14
|
var s = (c) => {
|
|
15
15
|
try {
|
|
@@ -29,12 +29,12 @@ var v = (m, t, n) => new Promise((o, i) => {
|
|
|
29
29
|
import { ChatMessageRole as w } from "@glodon-aiot/apis";
|
|
30
30
|
import E from "./Logger.mjs";
|
|
31
31
|
import { configuration as u } from "./Config.mjs";
|
|
32
|
-
import { io as
|
|
33
|
-
import { UserMode as
|
|
34
|
-
import
|
|
32
|
+
import { io as L } from "socket.io-client";
|
|
33
|
+
import { UserMode as y } from "./PayloadTypes.mjs";
|
|
34
|
+
import q, { SessionErrors as I } from "./Session.mjs";
|
|
35
35
|
import N from "dayjs";
|
|
36
36
|
const p = new E("[AgentSession] ");
|
|
37
|
-
class H extends
|
|
37
|
+
class H extends q {
|
|
38
38
|
constructor(t, n = "", o, i, s, e) {
|
|
39
39
|
super(t, n, o, i, s, e);
|
|
40
40
|
}
|
|
@@ -47,8 +47,8 @@ class H extends L {
|
|
|
47
47
|
appId: this._applicationId,
|
|
48
48
|
sessionId: this.id,
|
|
49
49
|
Authorization: `${this.token}`,
|
|
50
|
-
userMode: u.debug ?
|
|
51
|
-
}, o = new URL(u.apiRoot), i = yield
|
|
50
|
+
userMode: u.debug ? y.Debug : y.Normal
|
|
51
|
+
}, o = new URL(u.apiRoot), i = yield L(o.origin, {
|
|
52
52
|
path: o.pathname.replace("api", "socketio") + "/copilot",
|
|
53
53
|
query: n,
|
|
54
54
|
transports: ["websocket"]
|
|
@@ -60,12 +60,12 @@ class H extends L {
|
|
|
60
60
|
}), i.on("ready", (s) => {
|
|
61
61
|
if (s.code === 200) {
|
|
62
62
|
p.log("ready");
|
|
63
|
-
const e = u.debug ?
|
|
64
|
-
e ===
|
|
63
|
+
const e = u.debug ? y.Debug : y.Normal;
|
|
64
|
+
e === y.Debug && s.userMode, this._ready || (this._ready = !0, this.event.emit("ready")), this.frozen = !1, this.registerMcpFromClientConfig(), t(!0);
|
|
65
65
|
} else {
|
|
66
66
|
this._ready && (this._ready = !1);
|
|
67
67
|
const e = new Error(
|
|
68
|
-
|
|
68
|
+
I.SocketConnectionFailed
|
|
69
69
|
// , {
|
|
70
70
|
// cause: data,
|
|
71
71
|
// }
|
|
@@ -103,7 +103,8 @@ class H extends L {
|
|
|
103
103
|
actions: [[s]],
|
|
104
104
|
comment: {
|
|
105
105
|
isAgree: 0
|
|
106
|
-
}
|
|
106
|
+
},
|
|
107
|
+
isReplying: !0
|
|
107
108
|
};
|
|
108
109
|
this.pushMessage(l), this.event.emit("message:action", {
|
|
109
110
|
messageId: l.messageId,
|
|
@@ -112,7 +113,7 @@ class H extends L {
|
|
|
112
113
|
}
|
|
113
114
|
if (this.inactivating) {
|
|
114
115
|
const l = new Error(
|
|
115
|
-
|
|
116
|
+
I.Inactive
|
|
116
117
|
// {
|
|
117
118
|
// cause: {
|
|
118
119
|
// code: -1,
|
|
@@ -136,12 +137,12 @@ class H extends L {
|
|
|
136
137
|
code: 404,
|
|
137
138
|
message: "对不起,没有找到插件方法。"
|
|
138
139
|
});
|
|
139
|
-
let
|
|
140
|
+
let M = a == null ? void 0 : a.query;
|
|
140
141
|
try {
|
|
141
|
-
|
|
142
|
+
M = JSON.parse(a == null ? void 0 : a.query);
|
|
142
143
|
} catch (R) {
|
|
143
144
|
}
|
|
144
|
-
l(
|
|
145
|
+
l(M, (...R) => {
|
|
145
146
|
this._stopAnswer || e(...R);
|
|
146
147
|
});
|
|
147
148
|
}
|
|
@@ -184,20 +185,35 @@ class H extends L {
|
|
|
184
185
|
actions: [],
|
|
185
186
|
comment: {
|
|
186
187
|
isAgree: 0
|
|
187
|
-
}
|
|
188
|
+
},
|
|
189
|
+
isReplying: !0
|
|
188
190
|
}, s.data);
|
|
189
191
|
this.event.emit("message:content", r), this.pushMessage(r), this.event.emit("answer:finish", r);
|
|
190
192
|
}
|
|
191
193
|
} else {
|
|
192
194
|
let e = this.messages[this.messages.length - 1];
|
|
193
|
-
e && !e.messageId ? (e = g(g({}, e), s.data), this.messages[this.messages.length - 1] = e, this.event.emit("message:content", e), this.event.emit("message:updated", e)) : (this.pushMessage(
|
|
195
|
+
e && !e.messageId ? (e = g(g({}, e), s.data), this.messages[this.messages.length - 1] = e, this.event.emit("message:content", e), this.event.emit("message:updated", e)) : (this.pushMessage(g({
|
|
196
|
+
messageId: "",
|
|
197
|
+
content: "",
|
|
198
|
+
role: w.Robot,
|
|
199
|
+
sessionId: this.id,
|
|
200
|
+
reference: [],
|
|
201
|
+
searchReference: [],
|
|
202
|
+
isLoading: !1,
|
|
203
|
+
messageTime: "",
|
|
204
|
+
actions: [],
|
|
205
|
+
comment: {
|
|
206
|
+
isAgree: 0
|
|
207
|
+
},
|
|
208
|
+
isReplying: !0
|
|
209
|
+
}, s.data)), this.event.emit("message:content", s.data));
|
|
194
210
|
}
|
|
195
211
|
}), i.on("reference", (s) => v(this, null, function* () {
|
|
196
212
|
if (this._stopAnswer)
|
|
197
213
|
return;
|
|
198
214
|
if (!this.id) {
|
|
199
215
|
const a = new Error(
|
|
200
|
-
|
|
216
|
+
I.IdUndefined
|
|
201
217
|
// {
|
|
202
218
|
// cause: SESSION_ERROR_CAUSE[SessionErrors.IdUndefined],
|
|
203
219
|
// }
|
|
@@ -226,7 +242,8 @@ class H extends L {
|
|
|
226
242
|
actions: [],
|
|
227
243
|
comment: {
|
|
228
244
|
isAgree: 0
|
|
229
|
-
}
|
|
245
|
+
},
|
|
246
|
+
isReplying: !0
|
|
230
247
|
};
|
|
231
248
|
this.pushMessage(a);
|
|
232
249
|
}
|
|
@@ -283,7 +300,7 @@ class H extends L {
|
|
|
283
300
|
if (!this.active) {
|
|
284
301
|
if (yield this.activate(), !this.socket) {
|
|
285
302
|
const r = new Error(
|
|
286
|
-
|
|
303
|
+
I.SocketConnectionFailed
|
|
287
304
|
// {
|
|
288
305
|
// cause: { code: -1, message: 'socket is null' },
|
|
289
306
|
// }
|
package/dist/es/Session.mjs
CHANGED
|
@@ -11,21 +11,21 @@ var S = (c, e, t) => e in c ? x(c, e, { enumerable: !0, configurable: !0, writab
|
|
|
11
11
|
return c;
|
|
12
12
|
}, I = (c, e) => V(c, Q(e));
|
|
13
13
|
var l = (c, e, t) => (S(c, typeof e != "symbol" ? e + "" : e, t), t);
|
|
14
|
-
var
|
|
15
|
-
var
|
|
14
|
+
var h = (c, e, t) => new Promise((i, a) => {
|
|
15
|
+
var r = (s) => {
|
|
16
16
|
try {
|
|
17
|
-
|
|
17
|
+
o(t.next(s));
|
|
18
18
|
} catch (p) {
|
|
19
19
|
a(p);
|
|
20
20
|
}
|
|
21
|
-
},
|
|
21
|
+
}, d = (s) => {
|
|
22
22
|
try {
|
|
23
|
-
|
|
23
|
+
o(t.throw(s));
|
|
24
24
|
} catch (p) {
|
|
25
25
|
a(p);
|
|
26
26
|
}
|
|
27
|
-
},
|
|
28
|
-
|
|
27
|
+
}, o = (s) => s.done ? i(s.value) : Promise.resolve(s.value).then(r, d);
|
|
28
|
+
o((t = t.apply(c, e)).next());
|
|
29
29
|
});
|
|
30
30
|
import { v4 as b } from "uuid";
|
|
31
31
|
import { parseJWT as R, removeNewlines as C, removeLeadingAndTrailingBackslashes as O } from "./utils.mjs";
|
|
@@ -47,7 +47,7 @@ class $ {
|
|
|
47
47
|
* @param _application - 应用信息,可选参数。
|
|
48
48
|
* @param client - Bot 客户端实例,可选参数。
|
|
49
49
|
*/
|
|
50
|
-
constructor(e, t = "", i, a,
|
|
50
|
+
constructor(e, t = "", i, a, r, d) {
|
|
51
51
|
l(this, "_id");
|
|
52
52
|
l(this, "_frozen", !1);
|
|
53
53
|
//是否可发送新问题
|
|
@@ -72,19 +72,19 @@ class $ {
|
|
|
72
72
|
l(this, "_dataLoading", !1);
|
|
73
73
|
l(this, "_dataLoaded", !1);
|
|
74
74
|
l(this, "_mcpServers", null);
|
|
75
|
-
this.token = e, this.lazyload = a, this.client =
|
|
75
|
+
this.token = e, this.lazyload = a, this.client = d || null, this._applicationId = R(e).rid || A.applicationId, this.cvforceApi = this.getService(), r && (this._application = r), this.event.emit("init", {
|
|
76
76
|
applicationId: this._applicationId,
|
|
77
77
|
sessionId: t
|
|
78
78
|
}), this.loadApplicationInfo().then(() => {
|
|
79
|
-
var
|
|
79
|
+
var o;
|
|
80
80
|
if (t)
|
|
81
|
-
this._id = t, this.event.emit("data:loading"), i ? (this.data = i, a || (this._dataLoading = !0, this.cvforceApi.getSession(this.applicationId, t).then((s) =>
|
|
81
|
+
this._id = t, this.event.emit("data:loading"), i ? (this.data = i, a || (this._dataLoading = !0, this.cvforceApi.getSession(this.applicationId, t).then((s) => h(this, null, function* () {
|
|
82
82
|
this.data = s, this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, t);
|
|
83
|
-
})).then(() =>
|
|
83
|
+
})).then(() => h(this, null, function* () {
|
|
84
84
|
this.messages = [], yield this.fetchMessages(), this.event.emit("data:loaded", this.data), this.event.emit("data:updated", this.data);
|
|
85
|
-
})))) : (this._dataLoading = !0, this.cvforceApi.getSession(this.applicationId, t).then((s) =>
|
|
85
|
+
})))) : (this._dataLoading = !0, this.cvforceApi.getSession(this.applicationId, t).then((s) => h(this, null, function* () {
|
|
86
86
|
this.data = s, this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, t);
|
|
87
|
-
})).then(() =>
|
|
87
|
+
})).then(() => h(this, null, function* () {
|
|
88
88
|
this.messages = [], yield this.fetchMessages(), this.event.emit("data:loaded", this.data), this.event.emit("data:updated", this.data), this._dataLoading = !1, this._dataLoaded = !0;
|
|
89
89
|
})));
|
|
90
90
|
else {
|
|
@@ -96,13 +96,13 @@ class $ {
|
|
|
96
96
|
name: s,
|
|
97
97
|
// @ts-ignore
|
|
98
98
|
netOpen: i == null ? void 0 : i.netOpen,
|
|
99
|
-
knowledgeIdList: (
|
|
99
|
+
knowledgeIdList: (o = i == null ? void 0 : i.knowledges) == null ? void 0 : o.map((p) => p.id),
|
|
100
100
|
applicationId: this._applicationId
|
|
101
|
-
}).then((p) =>
|
|
101
|
+
}).then((p) => h(this, null, function* () {
|
|
102
102
|
var m;
|
|
103
103
|
this._id = p.id, this.data = I(f({}, p), {
|
|
104
104
|
knowledges: i == null ? void 0 : i.knowledges
|
|
105
|
-
}), this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, this._id), yield (() =>
|
|
105
|
+
}), this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, this._id), yield (() => h(this, null, function* () {
|
|
106
106
|
if (i != null && i.knowledges)
|
|
107
107
|
return this.setKnowledges((i == null ? void 0 : i.knowledges) || void 0);
|
|
108
108
|
}))(), yield (() => {
|
|
@@ -123,10 +123,10 @@ class $ {
|
|
|
123
123
|
});
|
|
124
124
|
}
|
|
125
125
|
fetchData() {
|
|
126
|
-
return
|
|
126
|
+
return h(this, null, function* () {
|
|
127
127
|
if (!this.data)
|
|
128
128
|
throw Error("session data is not loaded");
|
|
129
|
-
return yield this.cvforceApi.getSession(this.applicationId, this.data.id).then((e) =>
|
|
129
|
+
return yield this.cvforceApi.getSession(this.applicationId, this.data.id).then((e) => h(this, null, function* () {
|
|
130
130
|
return this.data = e, this.event.emit("data:updated", this.data), e;
|
|
131
131
|
}));
|
|
132
132
|
});
|
|
@@ -166,7 +166,7 @@ class $ {
|
|
|
166
166
|
return this.data.knowledges || void 0;
|
|
167
167
|
}
|
|
168
168
|
setKnowledges(e) {
|
|
169
|
-
return
|
|
169
|
+
return h(this, null, function* () {
|
|
170
170
|
if (!this.data)
|
|
171
171
|
throw Error("session data is not loaded");
|
|
172
172
|
return yield this.cvforceApi.patchSessionsId(this._applicationId, this.data.id, {
|
|
@@ -189,22 +189,24 @@ class $ {
|
|
|
189
189
|
return this._promptVariables.filter((e) => e.key !== "query");
|
|
190
190
|
}
|
|
191
191
|
setPromptVariables(e) {
|
|
192
|
-
return
|
|
193
|
-
const t = this._promptVariables.map((
|
|
194
|
-
var
|
|
195
|
-
const
|
|
196
|
-
return I(f({},
|
|
197
|
-
value:
|
|
192
|
+
return h(this, null, function* () {
|
|
193
|
+
const t = this._promptVariables.map((a) => {
|
|
194
|
+
var d;
|
|
195
|
+
const r = ((d = e == null ? void 0 : e.find((o) => o.key === a.key)) == null ? void 0 : d.value) || a.value;
|
|
196
|
+
return I(f({}, a), {
|
|
197
|
+
value: r
|
|
198
198
|
});
|
|
199
|
-
}).sort((
|
|
200
|
-
if (yield Promise.all(t.filter((
|
|
199
|
+
}).sort((a, r) => a.key.localeCompare(r.key));
|
|
200
|
+
if (!(yield Promise.all(t.filter((a) => a.key !== "query").map((a) => {
|
|
201
201
|
if (!this.data)
|
|
202
202
|
throw Error("session data is not loaded");
|
|
203
|
-
if (!(!
|
|
204
|
-
return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId, this.data.id,
|
|
205
|
-
value:
|
|
203
|
+
if (!(!a.id || !a.key))
|
|
204
|
+
return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId, this.data.id, a.id, {
|
|
205
|
+
value: a.value
|
|
206
206
|
}).catch(console.error);
|
|
207
|
-
})),
|
|
207
|
+
})).then(() => !0).catch((a) => (u.error(a), this.event.emit("error", a), !1))))
|
|
208
|
+
return !1;
|
|
209
|
+
if (!this.data)
|
|
208
210
|
throw Error("session data is not loaded");
|
|
209
211
|
return this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, this.data.id), this.event.emit("data:updated", this.data), this.event.emit("data:updated:promptVariables", {
|
|
210
212
|
promptVariables: this._promptVariables
|
|
@@ -222,7 +224,7 @@ class $ {
|
|
|
222
224
|
* @returns 如果设置成功,返回最终的网络访问开关状态;若不满足设置条件,则提前返回 undefined
|
|
223
225
|
*/
|
|
224
226
|
setNetOpen(e) {
|
|
225
|
-
return
|
|
227
|
+
return h(this, null, function* () {
|
|
226
228
|
var t, i, a;
|
|
227
229
|
if (u.log("setNetOpen:", e), u.log("application arrange setting value: ", (t = this._application) == null ? void 0 : t.arrange[0].enableNetOpen), ((i = this._application) == null ? void 0 : i.type) === E.Agent) {
|
|
228
230
|
console.warn("Agent Application Sessions are disabled to setNetOpen.");
|
|
@@ -244,13 +246,12 @@ class $ {
|
|
|
244
246
|
}
|
|
245
247
|
getService() {
|
|
246
248
|
return F(A.apiRoot, this.token, (e, t) => {
|
|
247
|
-
const i = new Error(
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
);
|
|
249
|
+
const i = new Error("data request error", {
|
|
250
|
+
cause: {
|
|
251
|
+
status: e,
|
|
252
|
+
message: t
|
|
253
|
+
}
|
|
254
|
+
});
|
|
254
255
|
u.error(i), this.event.emit("error", i);
|
|
255
256
|
});
|
|
256
257
|
}
|
|
@@ -272,50 +273,50 @@ class $ {
|
|
|
272
273
|
* @returns Promise<false|Message[]>
|
|
273
274
|
*/
|
|
274
275
|
fetchMessages() {
|
|
275
|
-
return
|
|
276
|
+
return h(this, arguments, function* (e = {}) {
|
|
276
277
|
var i, a;
|
|
277
278
|
const t = {
|
|
278
279
|
pageSize: this._loadingMessagesSize
|
|
279
280
|
};
|
|
280
281
|
if (this._id) {
|
|
281
282
|
e = f(f({}, t), e), this.event.emit("history:loading"), u.log("history:loading"), (e.endTime || e.startTime) && (this.event.emit("history:moreloading", e), u.log("history:moreloading", e)), this._loadingMessages = !0;
|
|
282
|
-
const
|
|
283
|
+
const r = yield this.cvforceApi.getChatHistorySessionId(this._applicationId, this._id, e), d = r.map((s, p) => {
|
|
283
284
|
var g, n;
|
|
284
285
|
let m = [], w;
|
|
285
|
-
return typeof ((g = s.agentHistoryList) == null ? void 0 : g.agentList) == "string" && (m = JSON.parse(s.agentHistoryList.agentList).reduce((v, _) => (v[_.data.step - 1] || (v[_.data.step - 1] = []), v[_.data.step - 1].push(_), v), [])), p ===
|
|
286
|
+
return typeof ((g = s.agentHistoryList) == null ? void 0 : g.agentList) == "string" && (m = JSON.parse(s.agentHistoryList.agentList).reduce((v, _) => (v[_.data.step - 1] || (v[_.data.step - 1] = []), v[_.data.step - 1].push(_), v), [])), p === r.length - 1 && (w = (n = this.data) == null ? void 0 : n.lastRelatedQuestion), I(f({}, s), {
|
|
286
287
|
actions: m,
|
|
287
288
|
relatedQuesion: w
|
|
288
289
|
});
|
|
289
290
|
});
|
|
290
291
|
if (!e.endTime && !e.startTime) {
|
|
291
292
|
const s = this.messages[this.messages.length - 1];
|
|
292
|
-
s && !s.relatedQuesion && (s.relatedQuesion = (i = this.data) == null ? void 0 : i.lastRelatedQuestion), this.messages = [...
|
|
293
|
+
s && !s.relatedQuesion && (s.relatedQuesion = (i = this.data) == null ? void 0 : i.lastRelatedQuestion), this.messages = [...d, ...this.messages];
|
|
293
294
|
} else if (e.endTime && !e.startTime) {
|
|
294
295
|
const s = this.messages.findIndex((p) => p.ts === e.endTime);
|
|
295
|
-
this.messages.splice(0, s + 1), this.messages = [...
|
|
296
|
+
this.messages.splice(0, s + 1), this.messages = [...d, ...this.messages];
|
|
296
297
|
} else if (!e.endTime && e.startTime) {
|
|
297
298
|
const s = this.messages.findLastIndex((p) => p.ts === e.endTime);
|
|
298
|
-
this.messages.splice(s, this.messages.length - s - 1), this.messages = [...this.messages, ...
|
|
299
|
+
this.messages.splice(s, this.messages.length - s - 1), this.messages = [...this.messages, ...d];
|
|
299
300
|
} else {
|
|
300
301
|
const s = this.messages.findIndex((m) => m.ts === e.endTime), p = this.messages.findLastIndex((m) => m.ts === e.endTime);
|
|
301
|
-
this.messages.splice(s, p - s + 1, ...
|
|
302
|
+
this.messages.splice(s, p - s + 1, ...d);
|
|
302
303
|
}
|
|
303
|
-
const
|
|
304
|
-
return
|
|
304
|
+
const o = this.messages[this.messages.length - 1];
|
|
305
|
+
return o && !o.relatedQuesion && (o.relatedQuesion = (a = this.data) == null ? void 0 : a.lastRelatedQuestion), this.event.emit("history:moreloaded", d), u.log("history:loaded", this.messages), this.event.emit("history:loaded", this.messages), this._loadingMessages = !1, d;
|
|
305
306
|
} else {
|
|
306
|
-
const
|
|
307
|
+
const r = new Error(
|
|
307
308
|
"session id is not defined"
|
|
308
309
|
/* IdUndefined */
|
|
309
310
|
// {
|
|
310
311
|
// cause: SESSION_ERROR_CAUSE[SessionErrors.IdUndefined],
|
|
311
312
|
// }
|
|
312
313
|
);
|
|
313
|
-
return u.error(
|
|
314
|
+
return u.error(r), this.event.emit("error", r), !1;
|
|
314
315
|
}
|
|
315
316
|
});
|
|
316
317
|
}
|
|
317
318
|
rename(e) {
|
|
318
|
-
return
|
|
319
|
+
return h(this, null, function* () {
|
|
319
320
|
if (!this._id)
|
|
320
321
|
throw Error("session is not created yet");
|
|
321
322
|
if (e.trim() === "")
|
|
@@ -328,28 +329,28 @@ class $ {
|
|
|
328
329
|
});
|
|
329
330
|
}
|
|
330
331
|
pushMessage(e) {
|
|
331
|
-
return
|
|
332
|
+
return h(this, null, function* () {
|
|
332
333
|
this.messages.push(e), u.log("history:add", e), this.event.emit("history:add", e), this.event.emit("message:new", e), this.event.emit("message:updated", e);
|
|
333
334
|
});
|
|
334
335
|
}
|
|
335
336
|
reloadSessionInfo() {
|
|
336
337
|
if (!this._id)
|
|
337
338
|
throw Error("session is not created yet");
|
|
338
|
-
return this._dataLoading = !0, this.cvforceApi.getSession(this.applicationId, this._id).then((e) =>
|
|
339
|
+
return this._dataLoading = !0, this.cvforceApi.getSession(this.applicationId, this._id).then((e) => h(this, null, function* () {
|
|
339
340
|
if (this.data = e, !this._id)
|
|
340
341
|
throw Error("session is not created yet");
|
|
341
342
|
return this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, this._id), u.log("data:updated", this.data), this.event.emit("data:updated", this.data), this.data;
|
|
342
|
-
})).then(() =>
|
|
343
|
+
})).then(() => h(this, null, function* () {
|
|
343
344
|
return this.messages = [], yield this.fetchMessages(), this._dataLoading = !1, this._dataLoaded = !0, this.event.emit("data:loaded", this.data), this;
|
|
344
345
|
}));
|
|
345
346
|
}
|
|
346
347
|
reload() {
|
|
347
|
-
return
|
|
348
|
+
return h(this, null, function* () {
|
|
348
349
|
return yield this.reloadSessionInfo(), this.socket ? (this.inactivate(!0), this.activate()) : (this.inactivate(!0), this.activate());
|
|
349
350
|
});
|
|
350
351
|
}
|
|
351
352
|
delete() {
|
|
352
|
-
return
|
|
353
|
+
return h(this, null, function* () {
|
|
353
354
|
if (!this.id) {
|
|
354
355
|
const e = new Error(
|
|
355
356
|
"session id is not defined"
|
|
@@ -364,7 +365,7 @@ class $ {
|
|
|
364
365
|
});
|
|
365
366
|
}
|
|
366
367
|
activate() {
|
|
367
|
-
return
|
|
368
|
+
return h(this, null, function* () {
|
|
368
369
|
if (this.activing)
|
|
369
370
|
return new Promise((t) => {
|
|
370
371
|
this.addEventListener("activated", () => {
|
|
@@ -375,7 +376,7 @@ class $ {
|
|
|
375
376
|
throw Error("session is not avalible. id is undefined");
|
|
376
377
|
this.activing = !0;
|
|
377
378
|
const e = this._id;
|
|
378
|
-
return this._dataLoading = !0, this._dataLoaded = !1, this.data = yield this.cvforceApi.getSession(this.applicationId, e).then((t) =>
|
|
379
|
+
return this._dataLoading = !0, this._dataLoaded = !1, this.data = yield this.cvforceApi.getSession(this.applicationId, e).then((t) => h(this, null, function* () {
|
|
379
380
|
return this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, e), t;
|
|
380
381
|
})), this.messages.length || (this.messages = [], yield this.fetchMessages()), this.event.emit("data:loaded", this.data), this.event.emit("data:updated", this.data), this._dataLoaded = !0, this._dataLoading = !1, this.inactivating = !1, this.frozen = !0, yield this.prepareConnection(), this.event.emit("activated", this.socket), this.active = !0, this.activing = !1, this;
|
|
381
382
|
});
|
|
@@ -392,7 +393,7 @@ class $ {
|
|
|
392
393
|
return this._loadingMessages;
|
|
393
394
|
}
|
|
394
395
|
send(i) {
|
|
395
|
-
return
|
|
396
|
+
return h(this, arguments, function* (e, t = {
|
|
396
397
|
stream: A.stream
|
|
397
398
|
}) {
|
|
398
399
|
var g;
|
|
@@ -403,9 +404,9 @@ class $ {
|
|
|
403
404
|
}
|
|
404
405
|
const {
|
|
405
406
|
stream: a = A.stream,
|
|
406
|
-
referenceFirst:
|
|
407
|
-
} = t,
|
|
408
|
-
if (!
|
|
407
|
+
referenceFirst: r = !1
|
|
408
|
+
} = t, d = e.uuid || b(), o = ((g = e.text) == null ? void 0 : g.trim()) || "", s = e.fileIds;
|
|
409
|
+
if (!o && /*!files.length &&*/
|
|
409
410
|
!(s != null && s.length)) {
|
|
410
411
|
const n = new Error(
|
|
411
412
|
"failed at sending empty content"
|
|
@@ -440,20 +441,20 @@ class $ {
|
|
|
440
441
|
const p = {
|
|
441
442
|
sessionId: this.id,
|
|
442
443
|
role: 2,
|
|
443
|
-
content:
|
|
444
|
-
messageId:
|
|
444
|
+
content: o,
|
|
445
|
+
messageId: d,
|
|
445
446
|
reference: [],
|
|
446
447
|
searchReference: [],
|
|
447
448
|
messageTime: ""
|
|
448
449
|
}, m = {
|
|
449
|
-
content:
|
|
450
|
+
content: o,
|
|
450
451
|
stream: a,
|
|
451
|
-
requestId:
|
|
452
|
+
requestId: d,
|
|
452
453
|
fileIds: s,
|
|
453
|
-
referenceFirst:
|
|
454
|
+
referenceFirst: r
|
|
454
455
|
};
|
|
455
|
-
this.pushMessage(p), this.event.emit("question:content",
|
|
456
|
-
const w = (n) =>
|
|
456
|
+
this.pushMessage(p), this.event.emit("question:content", o);
|
|
457
|
+
const w = (n) => h(this, null, function* () {
|
|
457
458
|
if (n.role !== L.Robot)
|
|
458
459
|
return;
|
|
459
460
|
switch (this.removeEventListener("answer:finish", w), this._id && n.content && n.index && n.index < 0 && (this.data = yield this.cvforceApi.patchSessionsId(this.applicationId, this._id, {
|
|
@@ -481,30 +482,30 @@ class $ {
|
|
|
481
482
|
});
|
|
482
483
|
return this.addEventListener("answer:finish", w), this.sendQuestion(m, I(f({}, t), {
|
|
483
484
|
stream: a,
|
|
484
|
-
referenceFirst:
|
|
485
|
+
referenceFirst: r
|
|
485
486
|
})), p;
|
|
486
487
|
});
|
|
487
488
|
}
|
|
488
489
|
getRelatedQuesion(e) {
|
|
489
|
-
return
|
|
490
|
-
var
|
|
491
|
-
if (!e.content || e.isSensitive || e.code !== 200 || !((
|
|
490
|
+
return h(this, null, function* () {
|
|
491
|
+
var r, d;
|
|
492
|
+
if (!e.content || e.isSensitive || e.code !== 200 || !((r = this.application) != null && r.arrange[0].recommendQuestionOpen))
|
|
492
493
|
return e;
|
|
493
494
|
this.event.emit("message:relatedQuesion:loading", e);
|
|
494
495
|
const t = yield this.cvforceApi.postGeneques({
|
|
495
496
|
content: e.content
|
|
496
|
-
}).catch((
|
|
497
|
+
}).catch((o) => null);
|
|
497
498
|
if (!t) {
|
|
498
|
-
const
|
|
499
|
-
relatedQuesion:
|
|
499
|
+
const o = [], s = I(f({}, e), {
|
|
500
|
+
relatedQuesion: o,
|
|
500
501
|
index: -3,
|
|
501
502
|
isLoading: !1
|
|
502
503
|
});
|
|
503
504
|
return this.event.emit("message:relatedQuesion:loaded", {
|
|
504
|
-
relatedQuesion:
|
|
505
|
+
relatedQuesion: o
|
|
505
506
|
}), this.event.emit("message:updated", s), s;
|
|
506
507
|
}
|
|
507
|
-
const i = (
|
|
508
|
+
const i = (d = t.content) == null ? void 0 : d.split("*").map(C).map(O).filter((o) => !!o);
|
|
508
509
|
e.relatedQuesion = i, e.index = -3, e.isLoading = !1;
|
|
509
510
|
const a = I(f({}, e), {
|
|
510
511
|
relatedQuesion: i,
|
|
@@ -517,13 +518,13 @@ class $ {
|
|
|
517
518
|
});
|
|
518
519
|
}
|
|
519
520
|
fillMessageReference(e) {
|
|
520
|
-
return
|
|
521
|
+
return h(this, null, function* () {
|
|
521
522
|
const t = yield Promise.all(e.reference.map((i) => this.cvforceApi.getKnowledgeIdFileId(i.knowledgeId, i.docId)));
|
|
522
523
|
return e.reference = e.reference.map((i, a) => f(f({}, i), t[a])), this.event.emit("message:updated", e), e;
|
|
523
524
|
});
|
|
524
525
|
}
|
|
525
526
|
answerAgain() {
|
|
526
|
-
return
|
|
527
|
+
return h(this, arguments, function* (e = {
|
|
527
528
|
stream: A.stream
|
|
528
529
|
}) {
|
|
529
530
|
const t = this.messages[this.messages.length - 1];
|
|
@@ -535,13 +536,13 @@ class $ {
|
|
|
535
536
|
} = e;
|
|
536
537
|
let a;
|
|
537
538
|
t.role !== L.User && (a = e.oldMessageId || t.messageId, this.messages.splice(this.messages.length - 1, 1), this.event.emit("message:remove", t), this.event.emit("history:remove", t));
|
|
538
|
-
const
|
|
539
|
-
content:
|
|
540
|
-
fileIds:
|
|
541
|
-
requestId:
|
|
539
|
+
const r = this.messages[this.messages.length - 1], d = {
|
|
540
|
+
content: r.content,
|
|
541
|
+
fileIds: r.fileIds,
|
|
542
|
+
requestId: r.messageId,
|
|
542
543
|
stream: i,
|
|
543
544
|
oldMessageId: a
|
|
544
|
-
},
|
|
545
|
+
}, o = (s) => h(this, null, function* () {
|
|
545
546
|
if (s.role === L.Robot && s.index === -1) {
|
|
546
547
|
switch (this._id && s.content && s.index && s.index < 0 && (this.data = yield this.cvforceApi.patchSessionsId(this.applicationId, this._id, {
|
|
547
548
|
finialMessage: s.content
|
|
@@ -557,16 +558,16 @@ class $ {
|
|
|
557
558
|
default:
|
|
558
559
|
s.content = s.message || "未知错误", s.isLoading = !1, s.index = -1, this.event.emit("message:error", s);
|
|
559
560
|
}
|
|
560
|
-
this.getRelatedQuesion(s), this.removeEventListener("message:content",
|
|
561
|
+
this.getRelatedQuesion(s), this.removeEventListener("message:content", o), this.frozen = !1;
|
|
561
562
|
}
|
|
562
563
|
});
|
|
563
|
-
this.addEventListener("message:content",
|
|
564
|
+
this.addEventListener("message:content", o), this.sendQuestion(d, I(f({}, e), {
|
|
564
565
|
stream: i
|
|
565
566
|
}));
|
|
566
567
|
});
|
|
567
568
|
}
|
|
568
569
|
setTop(e) {
|
|
569
|
-
return
|
|
570
|
+
return h(this, null, function* () {
|
|
570
571
|
if (!this._id)
|
|
571
572
|
throw Error("session is not avalible. id is undefined");
|
|
572
573
|
this.data = yield this.cvforceApi.patchSessionsId(this._applicationId, this._id, {
|
|
@@ -612,21 +613,21 @@ class $ {
|
|
|
612
613
|
if (e.actions) {
|
|
613
614
|
const a = e.actions[((i = e.actions) == null ? void 0 : i.length) - 1];
|
|
614
615
|
if (a) {
|
|
615
|
-
const
|
|
616
|
-
if (
|
|
616
|
+
const r = a[a.length - 1];
|
|
617
|
+
if (r && (r.type === "BEFORE_CALL" || r.type === "FUNCTION_CALL")) {
|
|
617
618
|
const {
|
|
618
|
-
pluginName:
|
|
619
|
-
pluginCode:
|
|
619
|
+
pluginName: d,
|
|
620
|
+
pluginCode: o,
|
|
620
621
|
funcCode: s,
|
|
621
622
|
funcName: p
|
|
622
|
-
} =
|
|
623
|
+
} = r.data;
|
|
623
624
|
a.push({
|
|
624
625
|
data: {
|
|
625
|
-
pluginName:
|
|
626
|
-
pluginCode:
|
|
626
|
+
pluginName: d,
|
|
627
|
+
pluginCode: o,
|
|
627
628
|
funcCode: s,
|
|
628
629
|
funcName: p,
|
|
629
|
-
step:
|
|
630
|
+
step: r.data.step + 1
|
|
630
631
|
},
|
|
631
632
|
type: "ABORT"
|
|
632
633
|
}), this.event.emit("message:action", {
|
|
@@ -651,7 +652,7 @@ class $ {
|
|
|
651
652
|
return;
|
|
652
653
|
const i = e.data.type, a = e.data.payload;
|
|
653
654
|
t.isReplying = !0;
|
|
654
|
-
const
|
|
655
|
+
const r = () => {
|
|
655
656
|
if (!t.searchingStatus) {
|
|
656
657
|
t.searchingStatus = "start";
|
|
657
658
|
return;
|
|
@@ -661,23 +662,23 @@ class $ {
|
|
|
661
662
|
return;
|
|
662
663
|
}
|
|
663
664
|
};
|
|
664
|
-
if (i === "error" && (t.index = -1), i === "beforeSearch" &&
|
|
665
|
+
if (i === "error" && (t.index = -1), i === "beforeSearch" && r(), i === "searchOver" && r(), i === "search" && t.searchReference.push(a), i === "thinking") {
|
|
665
666
|
t.thinkingStatus = "start";
|
|
666
|
-
const
|
|
667
|
-
t.reasoningContent = t.reasoningContent +
|
|
667
|
+
const o = a.choices[0];
|
|
668
|
+
t.reasoningContent = t.reasoningContent + o.delta.reasoningContent;
|
|
668
669
|
}
|
|
669
670
|
if (i === "thinkingOver") {
|
|
670
671
|
t.thinkingStatus = "end";
|
|
671
|
-
const
|
|
672
|
-
t.thinkingSecs =
|
|
672
|
+
const d = a.thinkingSecs;
|
|
673
|
+
t.thinkingSecs = d;
|
|
673
674
|
}
|
|
674
675
|
if (i === "text") {
|
|
675
|
-
const
|
|
676
|
-
t.content = t.content +
|
|
676
|
+
const o = a.choices[0];
|
|
677
|
+
t.content = t.content + o.delta.content;
|
|
677
678
|
}
|
|
678
679
|
if (i === "reference" && (t.reference = a), i === "result") {
|
|
679
|
-
const
|
|
680
|
-
t.messageId =
|
|
680
|
+
const d = a.messageId, o = a.llmModel, s = a.messageTime;
|
|
681
|
+
t.messageId = d, t.llmModel = o, t.messageTime = s;
|
|
681
682
|
}
|
|
682
683
|
i === "over" ? t.index = -1 : (t.code = e.code, t.message = e.message);
|
|
683
684
|
}
|
|
@@ -687,7 +688,7 @@ class $ {
|
|
|
687
688
|
* @returns 返回调用 API 提交评论后的响应结果
|
|
688
689
|
*/
|
|
689
690
|
postMessageComment(e) {
|
|
690
|
-
return
|
|
691
|
+
return h(this, null, function* () {
|
|
691
692
|
if (!this._applicationId || !this._id)
|
|
692
693
|
throw Error("session is not avalible. id is undefined");
|
|
693
694
|
return this.cvforceApi.postComments(this._applicationId, this._id, e).then((t) => {
|
package/dist/es/package.json.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e = "@glodon-aiot/bot-client-sdk", t = "3.3.2-beta.
|
|
1
|
+
const e = "@glodon-aiot/bot-client-sdk", t = "3.3.2-beta.17", i = "glodoncv", s = "aiot bot client js sdk", n = "module", y = !1, o = [
|
|
2
2
|
"aiot",
|
|
3
3
|
"bot",
|
|
4
4
|
"bot client",
|
|
@@ -59,7 +59,7 @@ const e = "@glodon-aiot/bot-client-sdk", t = "3.3.2-beta.15", i = "glodoncv", s
|
|
|
59
59
|
access: "public",
|
|
60
60
|
registry: "https://registry.npmjs.org/"
|
|
61
61
|
}, m = {
|
|
62
|
-
"@glodon-aiot/apis": "^3.3.2-beta.
|
|
62
|
+
"@glodon-aiot/apis": "^3.3.2-beta.17",
|
|
63
63
|
axios: "0.24.0",
|
|
64
64
|
buffer: "^6.0.3",
|
|
65
65
|
dayjs: "^1.11.13",
|
package/dist/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var E=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var $=(c,e,t)=>e in c?se(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t,g=(c,e)=>{for(var t in e||(e={}))B.call(e,t)&&$(c,t,e[t]);if(E)for(var t of E(e))F.call(e,t)&&$(c,t,e[t]);return c},y=(c,e)=>ie(c,ne(e));var J=(c,e)=>{var t={};for(var s in c)B.call(c,s)&&e.indexOf(s)<0&&(t[s]=c[s]);if(c!=null&&E)for(var s of E(c))e.indexOf(s)<0&&F.call(c,s)&&(t[s]=c[s]);return t};var m=(c,e,t)=>($(c,typeof e!="symbol"?e+"":e,t),t);var p=(c,e,t)=>new Promise((s,a)=>{var o=n=>{try{r(t.next(n))}catch(d){a(d)}},i=n=>{try{r(t.throw(n))}catch(d){a(d)}},r=n=>n.done?s(n.value):Promise.resolve(n.value).then(o,i);r((t=t.apply(c,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),oe=require("axios"),w=require("@glodon-aiot/apis"),re=require("socket.io-client"),Y=require("uuid"),j=require("dayjs"),R=class R{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!R.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!R.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!R.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!R.debug||console.warn(this.prefix,...e)}};m(R,"debug",!1);let k=R;const ce=new k("[Config] ");var G=(c=>(c.dev="https://aiot-dev.glodon.com/api/cvforcepd",c.test="https://aiot-dev.glodon.com/api/cvforce",c.prod="https://copilot.glodon.com/api/cvforce",c.local="http://localhost:3000/api/cvforcepd",c))(G||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function Q(c){k.debug=(c==null?void 0:c.debug)||!1,exports.configuration=y(g(g({},exports.configuration),c),{apiRoot:(c==null?void 0:c.apiRoot)||exports.configuration.apiRoot||(c!=null&&c.env?G[c.env||"prod"]:exports.configuration.apiRoot)}),k.debug&&ce.log("updated",exports.configuration)}const T=c=>JSON.parse(ae.decode(c.split(".")[1])),de=c=>{const e=T(c).exp;return new Date().valueOf()/1e3>=e},he=c=>c==null?void 0:c.replace(/[\r\n]+/gm,""),le=c=>c.replace(/\\|\\/g,"");function X(c,e,t){const s=d=>{var f;return e&&(de(e)&&t(403,"aiotToken is timeout"),d.headers=(f=d.headers)!=null?f:{},d.headers=y(g({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function a(d,f=!0){const h=`${c}${d}`,u=oe.create({baseURL:h});return f&&u.interceptors.request.use(s),u}const o=(d,f)=>{d===401&&t(d,"aiotToken is invalid")},i=(d,f)=>{d!==10001&&d!==10215&&t(d,f)},r=a("/data/v1");return new w.CVForceApi(r,{onHttpStatusError:o,onAppStatusError:i})}var x=(c=>(c[c.Normal=0]="Normal",c[c.Debug=1]="Debug",c))(x||{});const M=new k("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&M.disable()}getEventListenerMap(){return g({},this.eventListenerMap)}on(e,t,s=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),s?this.eventListenerMap[e].push({fn:t,once:!0}):this.eventListenerMap[e].push(t),M.log(`add event ${e} listener ${s?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const s=this.eventListenerMap[e].findIndex(a=>{if(typeof a=="function"&&t===a)return!0;if(a=a,a.fn===t)return!0});s<0?M.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),M.log(`remove event ${e} listener`))}else M.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){M.log(`event ${e} listeners is empty`);return}const s=[];for(let a=0;a<this.eventListenerMap[e].length;a++){const o=this.eventListenerMap[e][a];typeof o=="function"?o(t):s.push(o)}s.forEach(a=>{a&&(a.fn(t),this.off(e,a.fn))}),M.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const _=new k("[Session] ");var L=(c=>(c.DataRequestFailed="data request error",c.SocketConnectionFailed="socket error",c.IdUndefined="session id is not defined",c.SendingEmptyContent="failed at sending empty content",c.Frozen="session is frozen",c.UserModeError="failed at setting socket user mode",c.Inactive="session is inactive",c))(L||{});class q{constructor(e,t="",s,a,o,i){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new Z);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);m(this,"_mcpServers",null);this.token=e,this.lazyload=a,this.client=i||null,this._applicationId=T(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),o&&(this._application=o),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var r;if(t)this._id=t,this.event.emit("data:loading"),s?(this.data=s,a||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(n=>p(this,null,function*(){this.data=n,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data)})))):(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(n=>p(this,null,function*(){this.data=n,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoading=!1,this._dataLoaded=!0})));else{const n=(s==null?void 0:s.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:n}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:n,netOpen:s==null?void 0:s.netOpen,knowledgeIdList:(r=s==null?void 0:s.knowledges)==null?void 0:r.map(d=>d.id),applicationId:this._applicationId}).then(d=>p(this,null,function*(){var f;this._id=d.id,this.data=y(g({},d),{knowledges:s==null?void 0:s.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),yield(()=>p(this,null,function*(){if(s!=null&&s.knowledges)return this.setKnowledges((s==null?void 0:s.knowledges)||void 0)}))(),yield(()=>{if(s!=null&&s.promptVariables){const h=this._promptVariables.map(u=>{var v,I;const l=((I=(v=s.promptVariables)==null?void 0:v.find(b=>b.key===u.key))==null?void 0:I.value)||"";return y(g({},u),{value:l})}).sort((u,l)=>u.key.localeCompare(l.key));return this.setPromptVariables(h||[])}else return})(),this.event.emit("data:created",this.data),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),((f=this.application)==null?void 0:f.type)!==w.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}fetchData(){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.getSession(this.applicationId,this.data.id).then(e=>p(this,null,function*(){return this.data=e,this.event.emit("data:updated",this.data),e}))})}get id(){var e;return this._id||((e=this.data)==null?void 0:e.id)||""}get applicationId(){return this._applicationId}get application(){return this._application}set application(e){this._application=e}loadApplicationInfo(){if(this._application)return Promise.resolve(this._application);if(this._applicationId&&!this._application)return this.event.emit("application:data:loading"),this.cvforceApi.getApplicationId(this._applicationId).then(e=>(this._application=e,this.event.emit("application:data:loaded",e),e));throw Error("application id is not defined")}get ready(){return this._ready}get frozen(){return this._frozen}set frozen(e){e===!1&&this.inactivating&&this.socket&&(this.socket.disconnect(),this.socket=null,this.event.emit("inactivated")),this._frozen=e,this.event.emit("frozen",e)}get knowledges(){if(!this.data)throw Error("session data is not loaded");return this.data.knowledges||void 0}setKnowledges(e){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(t=>t.status===w.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>e.key!=="query")}setPromptVariables(e){return p(this,null,function*(){const t=this._promptVariables.map(s=>{var o;const a=((o=e==null?void 0:e.find(i=>i.key===s.key))==null?void 0:o.value)||s.value;return y(g({},s),{value:a})}).sort((s,a)=>s.key.localeCompare(a.key));if(yield Promise.all(t.filter(s=>s.key!=="query").map(s=>{if(!this.data)throw Error("session data is not loaded");if(!(!s.id||!s.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,s.id,{value:s.value}).catch(console.error)})),!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return p(this,null,function*(){var t,s,a;if(_.log("setNetOpen:",e),_.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===w.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((a=this._application)==null?void 0:a.arrange[0].enableNetOpen)===!1){console.warn("This Application is disabled to change netOpen.");return}if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{netOpen:e?1:2}),this.data.netOpen=e,_.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return X(exports.configuration.apiRoot,this.token,(e,t)=>{const s=new Error("data request error");_.error(s),this.event.emit("error",s)})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}fetchMessages(){return p(this,arguments,function*(e={}){var s,a;const t={pageSize:this._loadingMessagesSize};if(this._id){e=g(g({},t),e),this.event.emit("history:loading"),_.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),_.log("history:moreloading",e)),this._loadingMessages=!0;const o=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),i=o.map((n,d)=>{var u,l;let f=[],h;return typeof((u=n.agentHistoryList)==null?void 0:u.agentList)=="string"&&(f=JSON.parse(n.agentHistoryList.agentList).reduce((I,b)=>(I[b.data.step-1]||(I[b.data.step-1]=[]),I[b.data.step-1].push(b),I),[])),d===o.length-1&&(h=(l=this.data)==null?void 0:l.lastRelatedQuestion),y(g({},n),{actions:f,relatedQuesion:h})});if(!e.endTime&&!e.startTime){const n=this.messages[this.messages.length-1];n&&!n.relatedQuesion&&(n.relatedQuesion=(s=this.data)==null?void 0:s.lastRelatedQuestion),this.messages=[...i,...this.messages]}else if(e.endTime&&!e.startTime){const n=this.messages.findIndex(d=>d.ts===e.endTime);this.messages.splice(0,n+1),this.messages=[...i,...this.messages]}else if(!e.endTime&&e.startTime){const n=this.messages.findLastIndex(d=>d.ts===e.endTime);this.messages.splice(n,this.messages.length-n-1),this.messages=[...this.messages,...i]}else{const n=this.messages.findIndex(f=>f.ts===e.endTime),d=this.messages.findLastIndex(f=>f.ts===e.endTime);this.messages.splice(n,d-n+1,...i)}const r=this.messages[this.messages.length-1];return r&&!r.relatedQuesion&&(r.relatedQuesion=(a=this.data)==null?void 0:a.lastRelatedQuestion),this.event.emit("history:moreloaded",i),_.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,i}else{const o=new Error("session id is not defined");return _.error(o),this.event.emit("error",o),!1}})}rename(e){return p(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),_.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return p(this,null,function*(){this.messages.push(e),_.log("history:add",e),this.event.emit("history:add",e),this.event.emit("message:new",e),this.event.emit("message:updated",e)})}reloadSessionInfo(){if(!this._id)throw Error("session is not created yet");return this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,this._id).then(e=>p(this,null,function*(){if(this.data=e,!this._id)throw Error("session is not created yet");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),_.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>p(this,null,function*(){return this.messages=[],yield this.fetchMessages(),this._dataLoading=!1,this._dataLoaded=!0,this.event.emit("data:loaded",this.data),this}))}reload(){return p(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return p(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return _.error(e),this.event.emit("error",e),!1}return this.event.emit("data:deleting"),yield this.cvforceApi.delSessionsId(this.applicationId,this.id),this.event.emit("data:deleted"),this.destroy()})}activate(){return p(this,null,function*(){if(this.activing)return new Promise(t=>{this.addEventListener("activated",()=>{t(!0)},!0)});if(!this._id)throw Error("session is not avalible. id is undefined");this.activing=!0;const e=this._id;return this._dataLoading=!0,this._dataLoaded=!1,this.data=yield this.cvforceApi.getSession(this.applicationId,e).then(t=>p(this,null,function*(){return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,e),t})),this.messages.length||(this.messages=[],yield this.fetchMessages()),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoaded=!0,this._dataLoading=!1,this.inactivating=!1,this.frozen=!0,yield this.prepareConnection(),this.event.emit("activated",this.socket),this.active=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?this._frozen?(e||(this.inactivating=!0),this.activing=!1,!0):(this.socket.close(),this.socket=null,this.event.emit("inactivated"),this.active=!1,this.activing=!1,!0):(this.activing=!1,!0)}get dataLoaded(){return this._dataLoaded}get messagesLoading(){return this._loadingMessages}send(s){return p(this,arguments,function*(e,t={stream:exports.configuration.stream}){var u;try{this.validateConfigs()}catch(l){console.error(l)}const{stream:a=exports.configuration.stream,referenceFirst:o=!1}=t,i=e.uuid||Y.v4(),r=((u=e.text)==null?void 0:u.trim())||"",n=e.fileIds;if(!r&&!(n!=null&&n.length)){const l=new Error("failed at sending empty content");return _.error(l),this.event.emit("error",l),!1}if(!this._id){const l=new Error("session id is not defined");return _.error(l),this.event.emit("error",l),!1}if(this.frozen){const l=new Error("session is frozen");return _.error(l),this.event.emit("error",l),!1}this.frozen=!0,this._stopAnswer=!1;const d={sessionId:this.id,role:2,content:r,messageId:i,reference:[],searchReference:[],messageTime:""},f={content:r,stream:a,requestId:i,fileIds:n,referenceFirst:o};this.pushMessage(d),this.event.emit("question:content",r);const h=l=>p(this,null,function*(){if(l.role!==w.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",h),this._id&&l.content&&l.index&&l.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:l.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:l.content})),yield this.fillMessageReference(l),l.code){case 11915:l.content="请您换个问题问我吧~",l.index=-1,l.isSensitive=!0,l.isLoading=!1,l.sessionId=this._id||"",this.event.emit("message:error",l);break;case 200:l.index=-1,l.isLoading=!1;break;default:l.content=l.message||"未知错误",l.isLoading=!1,l.index=-1,this.event.emit("message:error",l)}this.getRelatedQuesion(l),l.isLoading=!1;let v=this.messages[this.messages.length-1];if(v&&v.role===w.ChatMessageRole.Robot){const I=g(g({},v),l);this.messages[this.messages.length-1]=I,this.event.emit("message:updated",I)}else this.pushMessage(l);this.frozen=!1});return this.addEventListener("answer:finish",h),this.sendQuestion(f,y(g({},t),{stream:a,referenceFirst:o})),d})}getRelatedQuesion(e){return p(this,null,function*(){var o,i;if(!e.content||e.isSensitive||e.code!==200||!((o=this.application)!=null&&o.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const t=yield this.cvforceApi.postGeneques({content:e.content}).catch(r=>null);if(!t){const r=[],n=y(g({},e),{relatedQuesion:r,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:r}),this.event.emit("message:updated",n),n}const s=(i=t.content)==null?void 0:i.split("*").map(he).map(le).filter(r=>!!r);e.relatedQuesion=s,e.index=-3,e.isLoading=!1;const a=y(g({},e),{relatedQuesion:s,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",a),this.event.emit("message:updated",a),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:s}),a})}fillMessageReference(e){return p(this,null,function*(){const t=yield Promise.all(e.reference.map(s=>this.cvforceApi.getKnowledgeIdFileId(s.knowledgeId,s.docId)));return e.reference=e.reference.map((s,a)=>g(g({},s),t[a])),this.event.emit("message:updated",e),e})}answerAgain(){return p(this,arguments,function*(e={stream:exports.configuration.stream}){const t=this.messages[this.messages.length-1];if(!t)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1;const{stream:s=exports.configuration.stream}=e;let a;t.role!==w.ChatMessageRole.User&&(a=e.oldMessageId||t.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",t),this.event.emit("history:remove",t));const o=this.messages[this.messages.length-1],i={content:o.content,fileIds:o.fileIds,requestId:o.messageId,stream:s,oldMessageId:a},r=n=>p(this,null,function*(){if(n.role===w.ChatMessageRole.Robot&&n.index===-1){switch(this._id&&n.content&&n.index&&n.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:n.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:n.content})),yield this.fillMessageReference(n),n.code){case 11915:n.content="请您换个问题问我吧~",n.index=-1,n.isSensitive=!0,n.isLoading=!1,n.sessionId=this._id||"",this.event.emit("message:error",n);break;case 200:n.index=-1,n.isLoading=!1;break;default:n.content=n.message||"未知错误",n.isLoading=!1,n.index=-1,this.event.emit("message:error",n)}this.getRelatedQuesion(n),this.removeEventListener("message:content",r),this.frozen=!1}});this.addEventListener("message:content",r),this.sendQuestion(i,y(g({},e),{stream:s}))})}setTop(e){return p(this,null,function*(){if(!this._id)throw Error("session is not avalible. id is undefined");this.data=yield this.cvforceApi.patchSessionsId(this._applicationId,this._id,{top:e}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:top",{top:e})})}suspend(){var s;this.stopAnswer(),this.frozen=!1,this._stopAnswer=!0;let e=this.messages[this.messages.length-1];const t={messageId:Y.v4(),isLoading:!1,index:-2,messageTime:j(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:w.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const a=e.actions[((s=e.actions)==null?void 0:s.length)-1];if(a){const o=a[a.length-1];if(o&&(o.type==="BEFORE_CALL"||o.type==="FUNCTION_CALL")){const{pluginName:i,pluginCode:r,funcCode:n,funcName:d}=o.data;a.push({data:{pluginName:i,pluginCode:r,funcCode:n,funcName:d,step:o.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:a})}}}e=g(g({},e),t),this.event.emit("message:content",e),this.event.emit("message:updated",e)}else this.pushMessage(t),this.event.emit("message:content",t);return this}handleStreamAnswer(e,t){if(!e.data)return;const s=e.data.type,a=e.data.payload;t.isReplying=!0;const o=()=>{if(!t.searchingStatus){t.searchingStatus="start";return}if(t.searchingStatus==="start"){t.searchingStatus="end";return}};if(s==="error"&&(t.index=-1),s==="beforeSearch"&&o(),s==="searchOver"&&o(),s==="search"&&t.searchReference.push(a),s==="thinking"){t.thinkingStatus="start";const r=a.choices[0];t.reasoningContent=t.reasoningContent+r.delta.reasoningContent}if(s==="thinkingOver"){t.thinkingStatus="end";const i=a.thinkingSecs;t.thinkingSecs=i}if(s==="text"){const r=a.choices[0];t.content=t.content+r.delta.content}if(s==="reference"&&(t.reference=a),s==="result"){const i=a.messageId,r=a.llmModel,n=a.messageTime;t.messageId=i,t.llmModel=r,t.messageTime=n}s==="over"?t.index=-1:(t.code=e.code,t.message=e.message)}postMessageComment(e){return p(this,null,function*(){if(!this._applicationId||!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.postComments(this._applicationId,this._id,e).then(t=>{const s=this.messages.find(a=>a.messageId===e.messageId);return s&&(s.comment=e,this.event.emit("message:comment",s)),t})})}clear(){if(!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.patchApplicationIdSessionsIdContext(this._applicationId,this._id).then(()=>(this.event.emit("context:clear"),!0))}destroy(){var e;return this._ready=!1,this.event.removeAllListeners(),(e=this.socket)==null||e.disconnect(),this.socket=null,this.event.emit("destroy",{applicationId:this._applicationId,sessionId:this._id}),this._id||""}}const A=new k("[AgentSession] ");class fe extends q{constructor(e,t="",s,a,o,i){super(e,t,s,a,o,i)}prepareConnection(){return new Promise(e=>p(this,null,function*(){this.socket&&e(!0);const t={version:"1.0",stream:JSON.stringify(exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?x.Debug:x.Normal},s=new URL(exports.configuration.apiRoot),a=yield re.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});a.on("connect",()=>{A.log("socket:connect"),this.event.emit("socket:connect"),a.emit("init")}),a.on("disconnect",()=>{A.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),a.on("ready",o=>{if(o.code===200){A.log("ready");const i=exports.configuration.debug?x.Debug:x.Normal;i===x.Debug&&o.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const i=new Error(L.SocketConnectionFailed);A.error("error",i),this.event.emit("error",i),e(!1)}}),a.on("action",(o,i)=>p(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:r,data:{runnerIsClient:n,pluginCode:d,funcCode:f,parameters:h,requestBody:u}}=o,l=this.messages[this.messages.length-1];if(!l.messageId)l.actions||(l.actions=[]),l.actions[o.data.step-1]||(l.actions[o.data.step-1]=[]),l.actions[o.data.step-1].push(o),this.event.emit("message:action",{messageId:l.messageId,action:o}),this.event.emit("message:updated",l);else{const v={messageId:"",content:"",role:w.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[o]],comment:{isAgree:0}};this.pushMessage(v),this.event.emit("message:action",{messageId:v.messageId,action:o})}if(this.inactivating){const v=new Error(L.Inactive);A.warn("error",v),this.event.emit("error",v)}else if(r==="FUNCTION_CALL"&&n){if(A.log(`calling function ${f} of plugin ${d} with argument:
|
|
2
|
-
${JSON.stringify(h)}`),!exports.configuration.plugins[d]){i({code:404,message:"对不起,没有找到插件。"});return}const v=exports.configuration.plugins[d][f];typeof v!="function"&&i({code:404,message:"对不起,没有找到插件方法。"});let I=h==null?void 0:h.query;try{I=JSON.parse(h==null?void 0:h.query)}catch(b){}v(I,(...b)=>{this._stopAnswer||i(...b)})}})),
|
|
1
|
+
"use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var E=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var $=(c,e,t)=>e in c?se(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t,g=(c,e)=>{for(var t in e||(e={}))B.call(e,t)&&$(c,t,e[t]);if(E)for(var t of E(e))F.call(e,t)&&$(c,t,e[t]);return c},y=(c,e)=>ie(c,ne(e));var J=(c,e)=>{var t={};for(var s in c)B.call(c,s)&&e.indexOf(s)<0&&(t[s]=c[s]);if(c!=null&&E)for(var s of E(c))e.indexOf(s)<0&&F.call(c,s)&&(t[s]=c[s]);return t};var m=(c,e,t)=>($(c,typeof e!="symbol"?e+"":e,t),t);var p=(c,e,t)=>new Promise((s,n)=>{var o=a=>{try{r(t.next(a))}catch(d){n(d)}},i=a=>{try{r(t.throw(a))}catch(d){n(d)}},r=a=>a.done?s(a.value):Promise.resolve(a.value).then(o,i);r((t=t.apply(c,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),oe=require("axios"),w=require("@glodon-aiot/apis"),re=require("socket.io-client"),Y=require("uuid"),j=require("dayjs"),M=class M{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!M.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!M.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!M.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!M.debug||console.warn(this.prefix,...e)}};m(M,"debug",!1);let k=M;const ce=new k("[Config] ");var G=(c=>(c.dev="https://aiot-dev.glodon.com/api/cvforcepd",c.test="https://aiot-dev.glodon.com/api/cvforce",c.prod="https://copilot.glodon.com/api/cvforce",c.local="http://localhost:3000/api/cvforcepd",c))(G||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function Q(c){k.debug=(c==null?void 0:c.debug)||!1,exports.configuration=y(g(g({},exports.configuration),c),{apiRoot:(c==null?void 0:c.apiRoot)||exports.configuration.apiRoot||(c!=null&&c.env?G[c.env||"prod"]:exports.configuration.apiRoot)}),k.debug&&ce.log("updated",exports.configuration)}const T=c=>JSON.parse(ae.decode(c.split(".")[1])),de=c=>{const e=T(c).exp;return new Date().valueOf()/1e3>=e},he=c=>c==null?void 0:c.replace(/[\r\n]+/gm,""),le=c=>c.replace(/\\|\\/g,"");function X(c,e,t){const s=d=>{var f;return e&&(de(e)&&t(403,"aiotToken is timeout"),d.headers=(f=d.headers)!=null?f:{},d.headers=y(g({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function n(d,f=!0){const h=`${c}${d}`,u=oe.create({baseURL:h});return f&&u.interceptors.request.use(s),u}const o=(d,f)=>{d===401&&t(d,"aiotToken is invalid")},i=(d,f)=>{d!==10001&&d!==10215&&t(d,f)},r=n("/data/v1");return new w.CVForceApi(r,{onHttpStatusError:o,onAppStatusError:i})}var x=(c=>(c[c.Normal=0]="Normal",c[c.Debug=1]="Debug",c))(x||{});const R=new k("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&R.disable()}getEventListenerMap(){return g({},this.eventListenerMap)}on(e,t,s=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),s?this.eventListenerMap[e].push({fn:t,once:!0}):this.eventListenerMap[e].push(t),R.log(`add event ${e} listener ${s?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const s=this.eventListenerMap[e].findIndex(n=>{if(typeof n=="function"&&t===n)return!0;if(n=n,n.fn===t)return!0});s<0?R.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),R.log(`remove event ${e} listener`))}else R.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){R.log(`event ${e} listeners is empty`);return}const s=[];for(let n=0;n<this.eventListenerMap[e].length;n++){const o=this.eventListenerMap[e][n];typeof o=="function"?o(t):s.push(o)}s.forEach(n=>{n&&(n.fn(t),this.off(e,n.fn))}),R.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const _=new k("[Session] ");var L=(c=>(c.DataRequestFailed="data request error",c.SocketConnectionFailed="socket error",c.IdUndefined="session id is not defined",c.SendingEmptyContent="failed at sending empty content",c.Frozen="session is frozen",c.UserModeError="failed at setting socket user mode",c.Inactive="session is inactive",c))(L||{});class q{constructor(e,t="",s,n,o,i){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new Z);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);m(this,"_mcpServers",null);this.token=e,this.lazyload=n,this.client=i||null,this._applicationId=T(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),o&&(this._application=o),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var r;if(t)this._id=t,this.event.emit("data:loading"),s?(this.data=s,n||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(a=>p(this,null,function*(){this.data=a,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data)})))):(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(a=>p(this,null,function*(){this.data=a,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoading=!1,this._dataLoaded=!0})));else{const a=(s==null?void 0:s.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:a}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:a,netOpen:s==null?void 0:s.netOpen,knowledgeIdList:(r=s==null?void 0:s.knowledges)==null?void 0:r.map(d=>d.id),applicationId:this._applicationId}).then(d=>p(this,null,function*(){var f;this._id=d.id,this.data=y(g({},d),{knowledges:s==null?void 0:s.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),yield(()=>p(this,null,function*(){if(s!=null&&s.knowledges)return this.setKnowledges((s==null?void 0:s.knowledges)||void 0)}))(),yield(()=>{if(s!=null&&s.promptVariables){const h=this._promptVariables.map(u=>{var v,I;const l=((I=(v=s.promptVariables)==null?void 0:v.find(b=>b.key===u.key))==null?void 0:I.value)||"";return y(g({},u),{value:l})}).sort((u,l)=>u.key.localeCompare(l.key));return this.setPromptVariables(h||[])}else return})(),this.event.emit("data:created",this.data),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),((f=this.application)==null?void 0:f.type)!==w.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}fetchData(){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.getSession(this.applicationId,this.data.id).then(e=>p(this,null,function*(){return this.data=e,this.event.emit("data:updated",this.data),e}))})}get id(){var e;return this._id||((e=this.data)==null?void 0:e.id)||""}get applicationId(){return this._applicationId}get application(){return this._application}set application(e){this._application=e}loadApplicationInfo(){if(this._application)return Promise.resolve(this._application);if(this._applicationId&&!this._application)return this.event.emit("application:data:loading"),this.cvforceApi.getApplicationId(this._applicationId).then(e=>(this._application=e,this.event.emit("application:data:loaded",e),e));throw Error("application id is not defined")}get ready(){return this._ready}get frozen(){return this._frozen}set frozen(e){e===!1&&this.inactivating&&this.socket&&(this.socket.disconnect(),this.socket=null,this.event.emit("inactivated")),this._frozen=e,this.event.emit("frozen",e)}get knowledges(){if(!this.data)throw Error("session data is not loaded");return this.data.knowledges||void 0}setKnowledges(e){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(t=>t.status===w.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>e.key!=="query")}setPromptVariables(e){return p(this,null,function*(){const t=this._promptVariables.map(n=>{var i;const o=((i=e==null?void 0:e.find(r=>r.key===n.key))==null?void 0:i.value)||n.value;return y(g({},n),{value:o})}).sort((n,o)=>n.key.localeCompare(o.key));if(!(yield Promise.all(t.filter(n=>n.key!=="query").map(n=>{if(!this.data)throw Error("session data is not loaded");if(!(!n.id||!n.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,n.id,{value:n.value}).catch(console.error)})).then(()=>!0).catch(n=>(_.error(n),this.event.emit("error",n),!1))))return!1;if(!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return p(this,null,function*(){var t,s,n;if(_.log("setNetOpen:",e),_.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===w.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((n=this._application)==null?void 0:n.arrange[0].enableNetOpen)===!1){console.warn("This Application is disabled to change netOpen.");return}if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{netOpen:e?1:2}),this.data.netOpen=e,_.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return X(exports.configuration.apiRoot,this.token,(e,t)=>{const s=new Error("data request error",{cause:{status:e,message:t}});_.error(s),this.event.emit("error",s)})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}fetchMessages(){return p(this,arguments,function*(e={}){var s,n;const t={pageSize:this._loadingMessagesSize};if(this._id){e=g(g({},t),e),this.event.emit("history:loading"),_.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),_.log("history:moreloading",e)),this._loadingMessages=!0;const o=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),i=o.map((a,d)=>{var u,l;let f=[],h;return typeof((u=a.agentHistoryList)==null?void 0:u.agentList)=="string"&&(f=JSON.parse(a.agentHistoryList.agentList).reduce((I,b)=>(I[b.data.step-1]||(I[b.data.step-1]=[]),I[b.data.step-1].push(b),I),[])),d===o.length-1&&(h=(l=this.data)==null?void 0:l.lastRelatedQuestion),y(g({},a),{actions:f,relatedQuesion:h})});if(!e.endTime&&!e.startTime){const a=this.messages[this.messages.length-1];a&&!a.relatedQuesion&&(a.relatedQuesion=(s=this.data)==null?void 0:s.lastRelatedQuestion),this.messages=[...i,...this.messages]}else if(e.endTime&&!e.startTime){const a=this.messages.findIndex(d=>d.ts===e.endTime);this.messages.splice(0,a+1),this.messages=[...i,...this.messages]}else if(!e.endTime&&e.startTime){const a=this.messages.findLastIndex(d=>d.ts===e.endTime);this.messages.splice(a,this.messages.length-a-1),this.messages=[...this.messages,...i]}else{const a=this.messages.findIndex(f=>f.ts===e.endTime),d=this.messages.findLastIndex(f=>f.ts===e.endTime);this.messages.splice(a,d-a+1,...i)}const r=this.messages[this.messages.length-1];return r&&!r.relatedQuesion&&(r.relatedQuesion=(n=this.data)==null?void 0:n.lastRelatedQuestion),this.event.emit("history:moreloaded",i),_.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,i}else{const o=new Error("session id is not defined");return _.error(o),this.event.emit("error",o),!1}})}rename(e){return p(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),_.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return p(this,null,function*(){this.messages.push(e),_.log("history:add",e),this.event.emit("history:add",e),this.event.emit("message:new",e),this.event.emit("message:updated",e)})}reloadSessionInfo(){if(!this._id)throw Error("session is not created yet");return this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,this._id).then(e=>p(this,null,function*(){if(this.data=e,!this._id)throw Error("session is not created yet");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),_.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>p(this,null,function*(){return this.messages=[],yield this.fetchMessages(),this._dataLoading=!1,this._dataLoaded=!0,this.event.emit("data:loaded",this.data),this}))}reload(){return p(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return p(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return _.error(e),this.event.emit("error",e),!1}return this.event.emit("data:deleting"),yield this.cvforceApi.delSessionsId(this.applicationId,this.id),this.event.emit("data:deleted"),this.destroy()})}activate(){return p(this,null,function*(){if(this.activing)return new Promise(t=>{this.addEventListener("activated",()=>{t(!0)},!0)});if(!this._id)throw Error("session is not avalible. id is undefined");this.activing=!0;const e=this._id;return this._dataLoading=!0,this._dataLoaded=!1,this.data=yield this.cvforceApi.getSession(this.applicationId,e).then(t=>p(this,null,function*(){return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,e),t})),this.messages.length||(this.messages=[],yield this.fetchMessages()),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoaded=!0,this._dataLoading=!1,this.inactivating=!1,this.frozen=!0,yield this.prepareConnection(),this.event.emit("activated",this.socket),this.active=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?this._frozen?(e||(this.inactivating=!0),this.activing=!1,!0):(this.socket.close(),this.socket=null,this.event.emit("inactivated"),this.active=!1,this.activing=!1,!0):(this.activing=!1,!0)}get dataLoaded(){return this._dataLoaded}get messagesLoading(){return this._loadingMessages}send(s){return p(this,arguments,function*(e,t={stream:exports.configuration.stream}){var u;try{this.validateConfigs()}catch(l){console.error(l)}const{stream:n=exports.configuration.stream,referenceFirst:o=!1}=t,i=e.uuid||Y.v4(),r=((u=e.text)==null?void 0:u.trim())||"",a=e.fileIds;if(!r&&!(a!=null&&a.length)){const l=new Error("failed at sending empty content");return _.error(l),this.event.emit("error",l),!1}if(!this._id){const l=new Error("session id is not defined");return _.error(l),this.event.emit("error",l),!1}if(this.frozen){const l=new Error("session is frozen");return _.error(l),this.event.emit("error",l),!1}this.frozen=!0,this._stopAnswer=!1;const d={sessionId:this.id,role:2,content:r,messageId:i,reference:[],searchReference:[],messageTime:""},f={content:r,stream:n,requestId:i,fileIds:a,referenceFirst:o};this.pushMessage(d),this.event.emit("question:content",r);const h=l=>p(this,null,function*(){if(l.role!==w.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",h),this._id&&l.content&&l.index&&l.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:l.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:l.content})),yield this.fillMessageReference(l),l.code){case 11915:l.content="请您换个问题问我吧~",l.index=-1,l.isSensitive=!0,l.isLoading=!1,l.sessionId=this._id||"",this.event.emit("message:error",l);break;case 200:l.index=-1,l.isLoading=!1;break;default:l.content=l.message||"未知错误",l.isLoading=!1,l.index=-1,this.event.emit("message:error",l)}this.getRelatedQuesion(l),l.isLoading=!1;let v=this.messages[this.messages.length-1];if(v&&v.role===w.ChatMessageRole.Robot){const I=g(g({},v),l);this.messages[this.messages.length-1]=I,this.event.emit("message:updated",I)}else this.pushMessage(l);this.frozen=!1});return this.addEventListener("answer:finish",h),this.sendQuestion(f,y(g({},t),{stream:n,referenceFirst:o})),d})}getRelatedQuesion(e){return p(this,null,function*(){var o,i;if(!e.content||e.isSensitive||e.code!==200||!((o=this.application)!=null&&o.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const t=yield this.cvforceApi.postGeneques({content:e.content}).catch(r=>null);if(!t){const r=[],a=y(g({},e),{relatedQuesion:r,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:r}),this.event.emit("message:updated",a),a}const s=(i=t.content)==null?void 0:i.split("*").map(he).map(le).filter(r=>!!r);e.relatedQuesion=s,e.index=-3,e.isLoading=!1;const n=y(g({},e),{relatedQuesion:s,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",n),this.event.emit("message:updated",n),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:s}),n})}fillMessageReference(e){return p(this,null,function*(){const t=yield Promise.all(e.reference.map(s=>this.cvforceApi.getKnowledgeIdFileId(s.knowledgeId,s.docId)));return e.reference=e.reference.map((s,n)=>g(g({},s),t[n])),this.event.emit("message:updated",e),e})}answerAgain(){return p(this,arguments,function*(e={stream:exports.configuration.stream}){const t=this.messages[this.messages.length-1];if(!t)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1;const{stream:s=exports.configuration.stream}=e;let n;t.role!==w.ChatMessageRole.User&&(n=e.oldMessageId||t.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",t),this.event.emit("history:remove",t));const o=this.messages[this.messages.length-1],i={content:o.content,fileIds:o.fileIds,requestId:o.messageId,stream:s,oldMessageId:n},r=a=>p(this,null,function*(){if(a.role===w.ChatMessageRole.Robot&&a.index===-1){switch(this._id&&a.content&&a.index&&a.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:a.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:a.content})),yield this.fillMessageReference(a),a.code){case 11915:a.content="请您换个问题问我吧~",a.index=-1,a.isSensitive=!0,a.isLoading=!1,a.sessionId=this._id||"",this.event.emit("message:error",a);break;case 200:a.index=-1,a.isLoading=!1;break;default:a.content=a.message||"未知错误",a.isLoading=!1,a.index=-1,this.event.emit("message:error",a)}this.getRelatedQuesion(a),this.removeEventListener("message:content",r),this.frozen=!1}});this.addEventListener("message:content",r),this.sendQuestion(i,y(g({},e),{stream:s}))})}setTop(e){return p(this,null,function*(){if(!this._id)throw Error("session is not avalible. id is undefined");this.data=yield this.cvforceApi.patchSessionsId(this._applicationId,this._id,{top:e}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:top",{top:e})})}suspend(){var s;this.stopAnswer(),this.frozen=!1,this._stopAnswer=!0;let e=this.messages[this.messages.length-1];const t={messageId:Y.v4(),isLoading:!1,index:-2,messageTime:j(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:w.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const n=e.actions[((s=e.actions)==null?void 0:s.length)-1];if(n){const o=n[n.length-1];if(o&&(o.type==="BEFORE_CALL"||o.type==="FUNCTION_CALL")){const{pluginName:i,pluginCode:r,funcCode:a,funcName:d}=o.data;n.push({data:{pluginName:i,pluginCode:r,funcCode:a,funcName:d,step:o.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:n})}}}e=g(g({},e),t),this.event.emit("message:content",e),this.event.emit("message:updated",e)}else this.pushMessage(t),this.event.emit("message:content",t);return this}handleStreamAnswer(e,t){if(!e.data)return;const s=e.data.type,n=e.data.payload;t.isReplying=!0;const o=()=>{if(!t.searchingStatus){t.searchingStatus="start";return}if(t.searchingStatus==="start"){t.searchingStatus="end";return}};if(s==="error"&&(t.index=-1),s==="beforeSearch"&&o(),s==="searchOver"&&o(),s==="search"&&t.searchReference.push(n),s==="thinking"){t.thinkingStatus="start";const r=n.choices[0];t.reasoningContent=t.reasoningContent+r.delta.reasoningContent}if(s==="thinkingOver"){t.thinkingStatus="end";const i=n.thinkingSecs;t.thinkingSecs=i}if(s==="text"){const r=n.choices[0];t.content=t.content+r.delta.content}if(s==="reference"&&(t.reference=n),s==="result"){const i=n.messageId,r=n.llmModel,a=n.messageTime;t.messageId=i,t.llmModel=r,t.messageTime=a}s==="over"?t.index=-1:(t.code=e.code,t.message=e.message)}postMessageComment(e){return p(this,null,function*(){if(!this._applicationId||!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.postComments(this._applicationId,this._id,e).then(t=>{const s=this.messages.find(n=>n.messageId===e.messageId);return s&&(s.comment=e,this.event.emit("message:comment",s)),t})})}clear(){if(!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.patchApplicationIdSessionsIdContext(this._applicationId,this._id).then(()=>(this.event.emit("context:clear"),!0))}destroy(){var e;return this._ready=!1,this.event.removeAllListeners(),(e=this.socket)==null||e.disconnect(),this.socket=null,this.event.emit("destroy",{applicationId:this._applicationId,sessionId:this._id}),this._id||""}}const A=new k("[AgentSession] ");class fe extends q{constructor(e,t="",s,n,o,i){super(e,t,s,n,o,i)}prepareConnection(){return new Promise(e=>p(this,null,function*(){this.socket&&e(!0);const t={version:"1.0",stream:JSON.stringify(exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?x.Debug:x.Normal},s=new URL(exports.configuration.apiRoot),n=yield re.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});n.on("connect",()=>{A.log("socket:connect"),this.event.emit("socket:connect"),n.emit("init")}),n.on("disconnect",()=>{A.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),n.on("ready",o=>{if(o.code===200){A.log("ready");const i=exports.configuration.debug?x.Debug:x.Normal;i===x.Debug&&o.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const i=new Error(L.SocketConnectionFailed);A.error("error",i),this.event.emit("error",i),e(!1)}}),n.on("action",(o,i)=>p(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:r,data:{runnerIsClient:a,pluginCode:d,funcCode:f,parameters:h,requestBody:u}}=o,l=this.messages[this.messages.length-1];if(!l.messageId)l.actions||(l.actions=[]),l.actions[o.data.step-1]||(l.actions[o.data.step-1]=[]),l.actions[o.data.step-1].push(o),this.event.emit("message:action",{messageId:l.messageId,action:o}),this.event.emit("message:updated",l);else{const v={messageId:"",content:"",role:w.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[o]],comment:{isAgree:0},isReplying:!0};this.pushMessage(v),this.event.emit("message:action",{messageId:v.messageId,action:o})}if(this.inactivating){const v=new Error(L.Inactive);A.warn("error",v),this.event.emit("error",v)}else if(r==="FUNCTION_CALL"&&a){if(A.log(`calling function ${f} of plugin ${d} with argument:
|
|
2
|
+
${JSON.stringify(h)}`),!exports.configuration.plugins[d]){i({code:404,message:"对不起,没有找到插件。"});return}const v=exports.configuration.plugins[d][f];typeof v!="function"&&i({code:404,message:"对不起,没有找到插件方法。"});let I=h==null?void 0:h.query;try{I=JSON.parse(h==null?void 0:h.query)}catch(b){}v(I,(...b)=>{this._stopAnswer||i(...b)})}})),n.on("answer",o=>{if(!this._stopAnswer)if(o.data.code!==200&&(o.data.index=-1,this.event.emit("error",o.data)),o.data.stream||o.data.stream===void 0){let i=this.messages[this.messages.length-1];if(i&&i.role===w.ChatMessageRole.Robot)this.handleStreamAnswer(o.data,i),this.messages[this.messages.length-1]=i,this.event.emit("message:content",i),this.event.emit("message:updated",i),i.index===-1&&this.event.emit("answer:finish",i);else{const r={content:"",role:w.ChatMessageRole.Robot,reference:[],searchReference:[],messageId:"",sessionId:this.id,messageTime:j(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};this.handleStreamAnswer(o.data,r),this.pushMessage(r),this.event.emit("message:content",r),r.index===-1&&this.event.emit("answer:finish",r)}}else if(o.data.index===-1){let i=this.messages[this.messages.length-1];if(i&&!i.messageId)i=g(g({},i),o.data),this.event.emit("message:content",i),this.event.emit("message:updated",i),this.event.emit("answer:finish",i);else{const r=g({messageId:"",content:"",role:w.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.data);this.event.emit("message:content",r),this.pushMessage(r),this.event.emit("answer:finish",r)}}else{let i=this.messages[this.messages.length-1];i&&!i.messageId?(i=g(g({},i),o.data),this.messages[this.messages.length-1]=i,this.event.emit("message:content",i),this.event.emit("message:updated",i)):(this.pushMessage(g({messageId:"",content:"",role:w.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.data)),this.event.emit("message:content",o.data))}}),n.on("reference",o=>p(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const h=new Error(L.IdUndefined);A.error(h),this.event.emit("error",h),this.frozen=!1;return}const{type:i,data:r,requestId:a}=o,d=this.messages.findIndex(h=>h.messageId===a&&h.role===w.ChatMessageRole.User);if(d<0)return;const f=d+1;if(f>=this.messages.length){const h={messageId:"",content:"",role:w.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0};this.pushMessage(h)}i==="KG"?(this.messages[f]=y(g({},this.messages[f]),{reference:r.knowledgeReference}),yield this.fillMessageReference(this.messages[f]),this.event.emit("message:reference",r.knowledgeReference),this.event.emit("message:updated",this.messages[f])):i==="WEB_SEARCH"&&(this.messages[f]=y(g({},this.messages[f]),{searchReference:r.knowledgeReference}),this.event.emit("message:searchreference",r.searchReference),this.event.emit("message:updated",this.messages[f]))})),this.socket=n,n.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((e,t)=>{if(!this.socket){t("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,s=>{s.code===200?(Object.keys(s.data).forEach(n=>{s.data[n].code!==200&&console.error(n,"MCP Server 注册失败。",s.data[n])}),e(!0)):(console.error("MCP Server 注册失败。",s),t(s))})}):Promise.resolve(!0)}addMcpServers(e){return p(this,null,function*(){return this.ready?this.socket?new Promise((t,s)=>{this.socket&&this.socket.emit("add_mcp_servers",e,n=>{n.code===200?(Object.keys(n.data).forEach(o=>{n.data[o].code!==200&&console.error(o,"MCP Server 注册失败。",n.data[o])}),t(!0)):(console.error("MCP Server 注册失败。",n),s(n))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return p(this,null,function*(){return this.ready?this.socket?new Promise((e,t)=>{this.socket&&this.socket.emit("list_mcp_servers",s=>{s.code===200?e(s.data):t(s)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(e,t){return p(this,null,function*(){var n,o,i;let s=y(g({},e),{promptVariables:this.promptVariables.reduce((r,a)=>y(g({},r),{[a.key]:a.value}),{}),knowledges:(n=this.knowledges)==null?void 0:n.map(r=>r.id)});if(!this.active){if(yield this.activate(),!this.socket){const r=new Error(L.SocketConnectionFailed);return A.warn("error",r),this.event.emit("error",r),!1}(o=this.socket)==null||o.emit("question",s);return}(i=this.socket)==null||i.emit("question",s)})}stopAnswer(){var e;(e=this.socket)==null||e.emit("stop_answer")}}function pe(c,e){return p(this,null,function*(){const t=c.getReader();let s;for(;!(s=yield t.read()).done;)e(s.value)})}function ue(c){let e,t,s,n=!1,o;return function(r){e===void 0?(e=r,t=0,s=-1,o=!1):e=me(e,r);const a=e.length;let d=0;for(;t<a;){n&&(e[t]===10&&(d=++t),n=!1);let f=-1;for(;t<a&&f===-1;++t)switch(e[t]){case 58:s===-1&&(s=t-d);break;case 13:n=!1,t+4<a&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(o=!0);case 10:f=t;break}if(f===-1)break;c(e.subarray(d,f),s,o),d=t,s=-1,o=!1}d===a?e=void 0:d!==0&&(e=e.subarray(d),t-=d)}}function ge(c,e,t){let s=H();const n=new TextDecoder;return function(i,r,a){if(i.length===0)t==null||t(s),s=H();else if(r>0){const d=n.decode(i.subarray(0,r)),f=r+(i[r+1]===32?2:1);let h=n.decode(i.subarray(f));switch(a&&(h+=`
|
|
3
3
|
`),d){case"data":s.data=s.data?s.data+`
|
|
4
|
-
`+h:h;break;case"event":s.event=h;break;case"id":c(s.id=h);break;case"retry":const u=parseInt(h,10);isNaN(u)||e(s.retry=u);break}}}}function me(c,e){const t=new Uint8Array(c.length+e.length);return t.set(c),t.set(e,c.length),t}function H(){return{data:"",event:"",id:"",retry:void 0}}const z="text/event-stream",ve=1e3,W="last-event-id";function U(c,f){var h=f,{signal:e,headers:t,onopen:s,onmessage:a,onclose:o,onerror:i,openWhenHidden:r,fetch:n}=h,d=J(h,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((u,l)=>{const v=g({},t);v.accept||(v.accept=z);let I;function b(){I.abort(),document.hidden||O()}r||document.addEventListener("visibilitychange",b);let N=ve,P=0;function V(){document.removeEventListener("visibilitychange",b),window.clearTimeout(P),I.abort()}e==null||e.addEventListener("abort",()=>{V(),u()});const ee=n!=null?n:window.fetch,te=s!=null?s:ye;function O(){return p(this,null,function*(){var D;I=new AbortController;try{const C=yield ee(c,y(g({},d),{headers:v,signal:I.signal}));yield te(C),yield pe(C.body,ue(ge(S=>{S?v[W]=S:delete v[W]},S=>{N=S},a))),o==null||o(),V(),u()}catch(C){if(!I.signal.aborted)try{const S=(D=i==null?void 0:i(C))!=null?D:N;window.clearTimeout(P),P=window.setTimeout(O,S)}catch(S){V(),l(S)}}})}O()})}function ye(c){const e=c.headers.get("content-type");if(!(e!=null&&e.startsWith(z)))throw new Error(`Expected content-type to be ${z}, Actual: ${e}`)}const K=new k("[DialogSession] ");class we extends q{constructor(t,s="",a,o,i,r){super(t,s,a,o,i,r);m(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>p(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,s,a,o,i,r){return p(this,null,function*(){const n={code:0,content:"",role:w.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=y(g({},a),{stream:exports.configuration.stream});U(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:o,onopen(f){return f.ok&&i!=null&&i.onopen&&i.onopen(),Promise.resolve()},onmessage(f){if(!f.data.includes('{"code": ')){let u={};try{u=JSON.parse(f.data)}catch(v){}(u==null?void 0:u.mtype)==="search"?n.searchReference.push(u):n.content=n.content+f.data;const l={content:n.content,role:1,reference:n.reference,searchReference:n.searchReference,messageId:n.messageId,sessionId:s,messageTime:j(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(i==null?void 0:i.onmessage)&&i.onmessage(l)}const h=JSON.parse(f.data);if(n.reference=h.data.reference,n.searchReference=h.data.searchReference,n.messageTime=h.data.messageTime,n.messageId=h.data.messageId,n.llmModel=h.data.llmModel,n.content=h.data.content,n.code=h.code,h.code===200){const u={code:n.code,content:n.content,role:1,reference:n.reference,searchReference:n.searchReference,messageId:n.messageId,sessionId:s,messageTime:n.messageTime,isReplying:!0};i!=null&&i.onmessage&&i.onmessage(u)}else return i!=null&&i.onclose&&i.onclose(n),r&&r({code:n.code,message:n.message})},onerror(){i!=null&&i.onerror&&i.onerror()},onclose(){const f={code:n.code,content:n.content,role:1,reference:n.reference,searchReference:n.searchReference,messageId:n.messageId,sessionId:s,messageTime:n.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};i!=null&&i.onclose&&i.onclose(f)}})})}postChatV3EventSource(t,s,a,o,i,r){return p(this,null,function*(){const n=this,d={code:0,content:"",role:w.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},f=y(g({},a),{stream:exports.configuration.stream});U(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(f),openWhenHidden:!0,signal:o,onopen(h){return h.ok&&i!=null&&i.onopen&&i.onopen(),Promise.resolve()},onmessage(h){if(!h.data&&!h.event&&!h.id&&!h.retry)return;let u={};try{u=JSON.parse(h.data)}catch(l){console.error("parse eventData to JSON failed. ",h.data)}if(u.code!==200)return d.index=-1,d.code=u.code,d.message=u.message,i!=null&&i.onmessage&&i.onmessage(d),r&&r({code:u.code,message:u.message});n.handleStreamAnswer(u,d),i!=null&&i.onmessage&&i.onmessage(d)},onerror(){i!=null&&i.onerror&&i.onerror()},onclose(){const h=y(g({},d),{isReplying:!1});i!=null&&i.onclose&&i.onclose(h)}})})}sendQuestion(t,s){return p(this,null,function*(){var d;const{content:a,fileIds:o,oldMessageId:i}=t,{stream:r,referenceFirst:n}=s;if(this.active||(yield this.activate()),this._id){let f={content:a,fileIds:o,referenceFirst:n,oldMessageId:i,promptVariables:this.promptVariables.reduce((h,u)=>y(g({},h),{[u.key]:u.value}),{}),knowledges:(d=this.knowledges)==null?void 0:d.map(h=>h.id)};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,f,this.ctrl.signal,{onopen:()=>{K.log("open",this.ctrl)},onmessage:h=>{if(this._stopAnswer)return;let u=this.messages[this.messages.length-1];u&&u.role===w.ChatMessageRole.Robot?(u=g(g({},u),h),this.messages[this.messages.length-1]=u,this.event.emit("message:content",u),this.event.emit("message:updated",u)):(this.pushMessage(h),this.event.emit("message:content",h))},onclose:h=>p(this,null,function*(){this._stopAnswer||(K.log(h,"onclose"),this.event.emit("answer:finish",h))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}}const Ie="@glodon-aiot/bot-client-sdk",_e="3.3.2-beta.15",be="glodoncv",ke="aiot bot client js sdk",Se="module",Ae=!1,Me=["aiot","bot","bot client","sdk"],Re=["dist"],xe="./dist/es/index.mjs",Le="./dist/lib/index.js",Ce="./dist/src/index.d.ts",Ee={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},Te="MIT",Pe={watch:"yarn build --watch",example:"node ./example/server.js",dev:"npm-run-all -p watch example",start:"vite",build:"tsc && vite build --mode prod && yarn build:cdn","build:npm":"tsc && vite build --mode prod","build:cdn":"tsc && vite build --mode prod --config ./vite.config.cdn.ts",preview:"vite preview",check:"yarn prettier --check .",write:"yarn prettier --write .",lint:"eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js"},Ve={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@types/express":"^4","@types/identity-obj-proxy":"^3","@typescript-eslint/eslint-plugin":"^5.35.1","@typescript-eslint/parser":"^5.35.1","babel-loader":"^8.3.0",eslint:"^8.0.1","eslint-config-prettier":"^8.5.0","eslint-config-standard-with-typescript":"^22.0.0","eslint-plugin-import":"^2.25.2","eslint-plugin-n":"^15.0.0","eslint-plugin-promise":"^6.0.0","eslint-plugin-react":"^7.31.0","eslint-plugin-storybook":"^0.6.10",express:"4","http-proxy-middleware":"^3.0.0","identity-obj-proxy":"^3.0.0","npm-run-all":"^4.1.5",prettier:"2.7.1","rollup-plugin-visualizer":"^6.0.1","socket.io":"^4.7.5","ts-node":"^10.9.2",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0","vite-tsconfig-paths":"^5.1.4"},Oe={access:"public",registry:"https://registry.npmjs.org/"},$e={"@glodon-aiot/apis":"^3.3.2-beta.15",axios:"0.24.0",buffer:"^6.0.3",dayjs:"^1.11.13","js-base64":"^3.7.7","socket.io-client":"^4.7.5",uuid:"^11.1.0"},Qe={name:Ie,version:_e,author:be,description:ke,type:Se,sideEffects:Ae,keywords:Me,files:Re,module:xe,main:Le,typings:Ce,exports:Ee,license:Te,scripts:Pe,devDependencies:Ve,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:Oe,dependencies:$e},ze=new k("[BotClient] ");class je{constructor(e,t,s=!0,a={analytics:{enabled:!1}}){m(this,"event",new Z);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=s,this.sdkConfigs=a,Q(t),this._applicationId=T(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(o=>{Q(y(g({},t),{stream:t.stream===void 0?(o==null?void 0:o.type)===w.ApplicationTypes.Dialog:t.stream})),this.event.emit("ready")})}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return p(this,null,function*(){var t,s,a,o,i;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(s=this.sdkConfigs.ui)==null?void 0:s.version,sdkVersion:Qe.version}).then(r=>(typeof r.arrange[0].recommendQuestionOpen!="boolean"&&(r.arrange[0].recommendQuestionOpen=!0),y(g({},r),{arrange:[y(g({},r.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&r.arrange[0].recommendQuestionOpen})]})));const e=(i=(o=(a=this._application)==null?void 0:a.arrange)==null?void 0:o[0])==null?void 0:i.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(r=>r.maxModelLength)),this._promptVariables=yield this.cvforceApi.getPrompts(this._applicationId),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:X(exports.configuration.apiRoot,this.token,(e,t)=>ze.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=T(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,s,a,o){return p(this,null,function*(){const i=this;return new Promise((r,n)=>{const d=f=>p(this,null,function*(){if(f===w.ApplicationTypes.Agent)r(new fe(e,t,s,a,o,i));else if(f===w.ApplicationTypes.Dialog)r(new we(e,t,s,a,o,i));else throw Error(`不支持的应用类型:${f}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return p(this,null,function*(){return new Promise((t,s)=>{const a=()=>this.cvforceApi.listSessions(this._applicationId,e).then(o=>{const i=[];return o.forEach(r=>p(this,null,function*(){const n=this._sessions.find(d=>r.id===d.id);if(n)n.data=r,this._application?n.application=this._application:n.loadApplicationInfo(),i.push(n);else{const d=yield this.createSession(this.token,r.id,r,this.lazyload,this._application||void 0);i.push(d)}})),this.sessions=i,i});if(this.ready){if(!this._application)throw Error("_application is null");t(a())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(a())},!0)})})}loadSession(e="",t){return p(this,null,function*(){this.checkReady();let s=this.sessions.find(a=>a.id===e);if(s||(s=yield this.createSession(this.token,e,t),this._sessions.push(s)),this._activeSession){if(this._activeSession===s)return s;this._activeSession.inactivate()}return s.id?(yield s.activate(),this._activeSession=s):s.addEventListener("data:loaded",()=>{this._activeSession!==s&&(s==null||s.activate(),this._activeSession=s)},!0),s})}reload(){return this.loadApplication().then(()=>p(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return p(this,null,function*(){yield this.reload();let t=this._sessions.find(s=>s.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,s="top_time desc, sort_status desc, updated_at desc"){return p(this,null,function*(){let a=e?this._sessions.find(o=>o.id===e):this._activeSession;if(!a){console.warn("setTop session failed.");return}return yield a.setTop(t),this.getSessions({order:s})})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return p(this,null,function*(){this.checkReady();let s=-1;if(typeof e=="string"?s=this._sessions.findIndex(a=>a.id===e):s=this._sessions.findIndex(a=>a.id===e.id),s>-1){const a=this._sessions[s];t&&(yield a.delete()),this._sessions.splice(s,1)}else console.warn("session delete failed, session is not exist.")})}clean(){this._sessions.forEach(e=>e.destroy()),this.sessions=[]}}class qe{constructor(e,t={},s){m(this,"code");m(this,"description","");m(this,"loaded",!1);m(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}exports.AgentPlugin=qe;exports.BotClient=je;exports.Session=q;exports.configure=Q;
|
|
4
|
+
`+h:h;break;case"event":s.event=h;break;case"id":c(s.id=h);break;case"retry":const u=parseInt(h,10);isNaN(u)||e(s.retry=u);break}}}}function me(c,e){const t=new Uint8Array(c.length+e.length);return t.set(c),t.set(e,c.length),t}function H(){return{data:"",event:"",id:"",retry:void 0}}const z="text/event-stream",ve=1e3,W="last-event-id";function U(c,f){var h=f,{signal:e,headers:t,onopen:s,onmessage:n,onclose:o,onerror:i,openWhenHidden:r,fetch:a}=h,d=J(h,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((u,l)=>{const v=g({},t);v.accept||(v.accept=z);let I;function b(){I.abort(),document.hidden||O()}r||document.addEventListener("visibilitychange",b);let N=ve,P=0;function V(){document.removeEventListener("visibilitychange",b),window.clearTimeout(P),I.abort()}e==null||e.addEventListener("abort",()=>{V(),u()});const ee=a!=null?a:window.fetch,te=s!=null?s:ye;function O(){return p(this,null,function*(){var D;I=new AbortController;try{const C=yield ee(c,y(g({},d),{headers:v,signal:I.signal}));yield te(C),yield pe(C.body,ue(ge(S=>{S?v[W]=S:delete v[W]},S=>{N=S},n))),o==null||o(),V(),u()}catch(C){if(!I.signal.aborted)try{const S=(D=i==null?void 0:i(C))!=null?D:N;window.clearTimeout(P),P=window.setTimeout(O,S)}catch(S){V(),l(S)}}})}O()})}function ye(c){const e=c.headers.get("content-type");if(!(e!=null&&e.startsWith(z)))throw new Error(`Expected content-type to be ${z}, Actual: ${e}`)}const K=new k("[DialogSession] ");class we extends q{constructor(t,s="",n,o,i,r){super(t,s,n,o,i,r);m(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>p(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,s,n,o,i,r){return p(this,null,function*(){const a={code:0,content:"",role:w.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=y(g({},n),{stream:exports.configuration.stream});U(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:o,onopen(f){return f.ok&&i!=null&&i.onopen&&i.onopen(),Promise.resolve()},onmessage(f){if(!f.data.includes('{"code": ')){let u={};try{u=JSON.parse(f.data)}catch(v){}(u==null?void 0:u.mtype)==="search"?a.searchReference.push(u):a.content=a.content+f.data;const l={content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:s,messageTime:j(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(i==null?void 0:i.onmessage)&&i.onmessage(l)}const h=JSON.parse(f.data);if(a.reference=h.data.reference,a.searchReference=h.data.searchReference,a.messageTime=h.data.messageTime,a.messageId=h.data.messageId,a.llmModel=h.data.llmModel,a.content=h.data.content,a.code=h.code,h.code===200){const u={code:a.code,content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:s,messageTime:a.messageTime,isReplying:!0};i!=null&&i.onmessage&&i.onmessage(u)}else return i!=null&&i.onclose&&i.onclose(a),r&&r({code:a.code,message:a.message})},onerror(){i!=null&&i.onerror&&i.onerror()},onclose(){const f={code:a.code,content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:s,messageTime:a.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};i!=null&&i.onclose&&i.onclose(f)}})})}postChatV3EventSource(t,s,n,o,i,r){return p(this,null,function*(){const a=this,d={code:0,content:"",role:w.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},f=y(g({},n),{stream:exports.configuration.stream});U(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(f),openWhenHidden:!0,signal:o,onopen(h){return h.ok&&i!=null&&i.onopen&&i.onopen(),Promise.resolve()},onmessage(h){if(!h.data&&!h.event&&!h.id&&!h.retry)return;let u={};try{u=JSON.parse(h.data)}catch(l){console.error("parse eventData to JSON failed. ",h.data)}if(u.code!==200)return d.index=-1,d.code=u.code,d.message=u.message,i!=null&&i.onmessage&&i.onmessage(d),r&&r({code:u.code,message:u.message});a.handleStreamAnswer(u,d),i!=null&&i.onmessage&&i.onmessage(d)},onerror(){i!=null&&i.onerror&&i.onerror()},onclose(){const h=y(g({},d),{isReplying:!1});i!=null&&i.onclose&&i.onclose(h)}})})}sendQuestion(t,s){return p(this,null,function*(){var d;const{content:n,fileIds:o,oldMessageId:i}=t,{stream:r,referenceFirst:a}=s;if(this.active||(yield this.activate()),this._id){let f={content:n,fileIds:o,referenceFirst:a,oldMessageId:i,promptVariables:this.promptVariables.reduce((h,u)=>y(g({},h),{[u.key]:u.value}),{}),knowledges:(d=this.knowledges)==null?void 0:d.map(h=>h.id)};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,f,this.ctrl.signal,{onopen:()=>{K.log("open",this.ctrl)},onmessage:h=>{if(this._stopAnswer)return;let u=this.messages[this.messages.length-1];u&&u.role===w.ChatMessageRole.Robot?(u=g(g({},u),h),this.messages[this.messages.length-1]=u,this.event.emit("message:content",u),this.event.emit("message:updated",u)):(this.pushMessage(h),this.event.emit("message:content",h))},onclose:h=>p(this,null,function*(){this._stopAnswer||(K.log(h,"onclose"),this.event.emit("answer:finish",h))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}}const Ie="@glodon-aiot/bot-client-sdk",_e="3.3.2-beta.17",be="glodoncv",ke="aiot bot client js sdk",Se="module",Ae=!1,Re=["aiot","bot","bot client","sdk"],Me=["dist"],xe="./dist/es/index.mjs",Le="./dist/lib/index.js",Ce="./dist/src/index.d.ts",Ee={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},Te="MIT",Pe={watch:"yarn build --watch",example:"node ./example/server.js",dev:"npm-run-all -p watch example",start:"vite",build:"tsc && vite build --mode prod && yarn build:cdn","build:npm":"tsc && vite build --mode prod","build:cdn":"tsc && vite build --mode prod --config ./vite.config.cdn.ts",preview:"vite preview",check:"yarn prettier --check .",write:"yarn prettier --write .",lint:"eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js"},Ve={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@types/express":"^4","@types/identity-obj-proxy":"^3","@typescript-eslint/eslint-plugin":"^5.35.1","@typescript-eslint/parser":"^5.35.1","babel-loader":"^8.3.0",eslint:"^8.0.1","eslint-config-prettier":"^8.5.0","eslint-config-standard-with-typescript":"^22.0.0","eslint-plugin-import":"^2.25.2","eslint-plugin-n":"^15.0.0","eslint-plugin-promise":"^6.0.0","eslint-plugin-react":"^7.31.0","eslint-plugin-storybook":"^0.6.10",express:"4","http-proxy-middleware":"^3.0.0","identity-obj-proxy":"^3.0.0","npm-run-all":"^4.1.5",prettier:"2.7.1","rollup-plugin-visualizer":"^6.0.1","socket.io":"^4.7.5","ts-node":"^10.9.2",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0","vite-tsconfig-paths":"^5.1.4"},Oe={access:"public",registry:"https://registry.npmjs.org/"},$e={"@glodon-aiot/apis":"^3.3.2-beta.17",axios:"0.24.0",buffer:"^6.0.3",dayjs:"^1.11.13","js-base64":"^3.7.7","socket.io-client":"^4.7.5",uuid:"^11.1.0"},Qe={name:Ie,version:_e,author:be,description:ke,type:Se,sideEffects:Ae,keywords:Re,files:Me,module:xe,main:Le,typings:Ce,exports:Ee,license:Te,scripts:Pe,devDependencies:Ve,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:Oe,dependencies:$e},ze=new k("[BotClient] ");class je{constructor(e,t,s=!0,n={analytics:{enabled:!1}}){m(this,"event",new Z);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=s,this.sdkConfigs=n,Q(t),this._applicationId=T(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(o=>{Q(y(g({},t),{stream:t.stream===void 0?(o==null?void 0:o.type)===w.ApplicationTypes.Dialog:t.stream})),this.event.emit("ready")})}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return p(this,null,function*(){var t,s,n,o,i;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(s=this.sdkConfigs.ui)==null?void 0:s.version,sdkVersion:Qe.version}).then(r=>(typeof r.arrange[0].recommendQuestionOpen!="boolean"&&(r.arrange[0].recommendQuestionOpen=!0),y(g({},r),{arrange:[y(g({},r.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&r.arrange[0].recommendQuestionOpen})]})));const e=(i=(o=(n=this._application)==null?void 0:n.arrange)==null?void 0:o[0])==null?void 0:i.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(r=>r.maxModelLength)),this._promptVariables=yield this.cvforceApi.getPrompts(this._applicationId),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:X(exports.configuration.apiRoot,this.token,(e,t)=>ze.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=T(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,s,n,o){return p(this,null,function*(){const i=this;return new Promise((r,a)=>{const d=f=>p(this,null,function*(){if(f===w.ApplicationTypes.Agent)r(new fe(e,t,s,n,o,i));else if(f===w.ApplicationTypes.Dialog)r(new we(e,t,s,n,o,i));else throw Error(`不支持的应用类型:${f}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return p(this,null,function*(){return new Promise((t,s)=>{const n=()=>this.cvforceApi.listSessions(this._applicationId,e).then(o=>{const i=[];return o.forEach(r=>p(this,null,function*(){const a=this._sessions.find(d=>r.id===d.id);if(a)a.data=r,this._application?a.application=this._application:a.loadApplicationInfo(),i.push(a);else{const d=yield this.createSession(this.token,r.id,r,this.lazyload,this._application||void 0);i.push(d)}})),this.sessions=i,i});if(this.ready){if(!this._application)throw Error("_application is null");t(n())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(n())},!0)})})}loadSession(e="",t){return p(this,null,function*(){this.checkReady();let s=this.sessions.find(n=>n.id===e);if(s||(s=yield this.createSession(this.token,e,t),this._sessions.push(s)),this._activeSession){if(this._activeSession===s)return s;this._activeSession.inactivate()}return s.id?(yield s.activate(),this._activeSession=s):s.addEventListener("data:loaded",()=>{this._activeSession!==s&&(s==null||s.activate(),this._activeSession=s)},!0),s})}reload(){return this.loadApplication().then(()=>p(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return p(this,null,function*(){yield this.reload();let t=this._sessions.find(s=>s.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,s="top_time desc, sort_status desc, updated_at desc"){return p(this,null,function*(){let n=e?this._sessions.find(o=>o.id===e):this._activeSession;if(!n){console.warn("setTop session failed.");return}return yield n.setTop(t),this.getSessions({order:s})})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return p(this,null,function*(){this.checkReady();let s=-1;if(typeof e=="string"?s=this._sessions.findIndex(n=>n.id===e):s=this._sessions.findIndex(n=>n.id===e.id),s>-1){const n=this._sessions[s];t&&(yield n.delete()),this._sessions.splice(s,1)}else console.warn("session delete failed, session is not exist.")})}clean(){this._sessions.forEach(e=>e.destroy()),this.sessions=[]}}class qe{constructor(e,t={},s){m(this,"code");m(this,"description","");m(this,"loaded",!1);m(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}exports.AgentPlugin=qe;exports.BotClient=je;exports.Session=q;exports.configure=Q;
|
package/dist/src/Session.d.ts
CHANGED
|
@@ -96,7 +96,7 @@ export default abstract class Session {
|
|
|
96
96
|
setKnowledges(knowledges?: IKnowledge[]): Promise<IKnowledge[] | undefined>;
|
|
97
97
|
validateConfigs(): void;
|
|
98
98
|
get promptVariables(): ISessionPrompt[];
|
|
99
|
-
setPromptVariables(v: ISessionPrompt[]): Promise<ISessionPrompt[]>;
|
|
99
|
+
setPromptVariables(v: ISessionPrompt[]): Promise<false | ISessionPrompt[]>;
|
|
100
100
|
get netOpen(): boolean;
|
|
101
101
|
/**
|
|
102
102
|
* 异步设置会话的网络访问开关状态
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare const SYSTEM_PROMPT_TITLE = "\u89D2\u8272\u8BBE\u5B9A";
|
|
2
|
+
export declare const SYSTEM_PROMPT_PLACEHOLDER = "\u5B9A\u4E49AI\u626E\u6F14\u7684\u89D2\u8272\u4E0E\u56DE\u590D\u903B\u8F91\uFF0C\u793A\u4F8B\uFF1A\n\n# \u89D2\u8272\n\u4F60\u662F\u4E00\u4F4D\u8D44\u6DF1\u7684\u5EFA\u7B51\u9886\u57DF\u77E5\u8BC6\u4E13\u5BB6\uFF0C\u4E13\u4E3A\u5EFA\u7B51\u884C\u4E1A\u4ECE\u4E1A\u8005\u63D0\u4F9B\u4E13\u4E1A\u3001\u51C6\u786E\u7684\u667A\u80FD\u95EE\u7B54\u670D\u52A1\u3002\n\n# \u4EFB\u52A1\n- \u5F53\u7528\u6237\u63D0\u51FA\u5EFA\u7B51\u9886\u57DF\u76F8\u5173\u95EE\u9898\u65F6\uFF0C\u8BF7\u6839\u636E\u4F60\u638C\u63E1\u7684\u77E5\u8BC6\u56DE\u7B54\uFF1B\u00A0\n- \u5982\u679C\u77E5\u8BC6\u4E0D\u5C5E\u4E8E\u5EFA\u7B51\u884C\u4E1A\u6216\u8D85\u51FA\u4F60\u7684\u77E5\u8BC6\u8303\u56F4\uFF0C\u8BF7\u56DE\u7B54\u201C\u6211\u8FD8\u6CA1\u6709\u5B66\u4F1A\u8FD9\u4E2A\u95EE\u9898\u201D\u3002\n\n# \u9650\u5236\uFF1A\n- \u53EA\u56DE\u7B54\u4E0E\u5EFA\u7B51\u9886\u57DF\u76F8\u5173\u7684\u95EE\u9898\uFF0C\u62D2\u7EDD\u56DE\u7B54\u5176\u4ED6\u4E0D\u76F8\u5173\u8BDD\u9898\uFF1B\n- \u56DE\u7B54\u9700\u7B80\u6D01\u660E\u4E86\uFF0C\u786E\u4FDD\u4E13\u4E1A\u6027\u548C\u51C6\u786E\u6027\u3002";
|
|
3
|
+
export declare const SYSTEM_PROMPT_TOOLTIP: string[];
|
|
4
|
+
export declare const DEFAULT_SYSTEM_VARIABLE: {
|
|
5
|
+
key: string;
|
|
6
|
+
}[];
|
|
7
|
+
export declare const USER_PROMPT_TITLE = "\u7528\u6237\u6307\u4EE4";
|
|
8
|
+
export declare const USER_PROMPT_PLACEHOLDER = "\u8BF7\u8F93\u5165\u7528\u6237\u6307\u4EE4";
|
|
9
|
+
export declare const USER_PROMPT_TOOLTIP: string[];
|
|
10
|
+
export declare const DEFAULT_USER_VARIABLE: {
|
|
11
|
+
key: string;
|
|
12
|
+
required: boolean;
|
|
13
|
+
}[];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glodon-aiot/bot-client-sdk",
|
|
3
|
-
"version": "3.3.2-beta.
|
|
3
|
+
"version": "3.3.2-beta.17",
|
|
4
4
|
"author": "glodoncv",
|
|
5
5
|
"description": "aiot bot client js sdk",
|
|
6
6
|
"type": "module",
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
"registry": "https://registry.npmjs.org/"
|
|
80
80
|
},
|
|
81
81
|
"dependencies": {
|
|
82
|
-
"@glodon-aiot/apis": "^3.3.2-beta.
|
|
82
|
+
"@glodon-aiot/apis": "^3.3.2-beta.17",
|
|
83
83
|
"axios": "0.24.0",
|
|
84
84
|
"buffer": "^6.0.3",
|
|
85
85
|
"dayjs": "^1.11.13",
|