@glodon-aiot/agent-cli-sdk 3.25.0 → 3.25.1-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/es/BotClient.mjs +75 -75
- package/dist/es/Session.mjs +183 -172
- package/dist/es/utils.mjs +16 -9
- package/dist/lib/index.js +5 -4
- package/dist/src/Session.d.ts +1 -0
- package/dist/src/utils.d.ts +5 -0
- package/package.json +2 -2
package/dist/es/BotClient.mjs
CHANGED
|
@@ -2,42 +2,42 @@ var w = Object.defineProperty, k = Object.defineProperties;
|
|
|
2
2
|
var A = Object.getOwnPropertyDescriptors;
|
|
3
3
|
var g = Object.getOwnPropertySymbols;
|
|
4
4
|
var x = Object.prototype.hasOwnProperty, I = Object.prototype.propertyIsEnumerable;
|
|
5
|
-
var u = (
|
|
6
|
-
for (var
|
|
7
|
-
x.call(i,
|
|
5
|
+
var u = (n, i, t) => i in n ? w(n, i, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[i] = t, d = (n, i) => {
|
|
6
|
+
for (var t in i || (i = {}))
|
|
7
|
+
x.call(i, t) && u(n, t, i[t]);
|
|
8
8
|
if (g)
|
|
9
|
-
for (var
|
|
10
|
-
I.call(i,
|
|
11
|
-
return
|
|
12
|
-
}, f = (
|
|
13
|
-
var l = (
|
|
14
|
-
var c = (
|
|
15
|
-
var
|
|
9
|
+
for (var t of g(i))
|
|
10
|
+
I.call(i, t) && u(n, t, i[t]);
|
|
11
|
+
return n;
|
|
12
|
+
}, f = (n, i) => k(n, A(i));
|
|
13
|
+
var l = (n, i, t) => (u(n, typeof i != "symbol" ? i + "" : i, t), t);
|
|
14
|
+
var c = (n, i, t) => new Promise((e, s) => {
|
|
15
|
+
var o = (a) => {
|
|
16
16
|
try {
|
|
17
|
-
r(
|
|
17
|
+
r(t.next(a));
|
|
18
18
|
} catch (h) {
|
|
19
19
|
s(h);
|
|
20
20
|
}
|
|
21
|
-
},
|
|
21
|
+
}, p = (a) => {
|
|
22
22
|
try {
|
|
23
|
-
r(
|
|
23
|
+
r(t.throw(a));
|
|
24
24
|
} catch (h) {
|
|
25
25
|
s(h);
|
|
26
26
|
}
|
|
27
|
-
}, r = (a) => a.done ?
|
|
28
|
-
r((
|
|
27
|
+
}, r = (a) => a.done ? e(a.value) : Promise.resolve(a.value).then(o, p);
|
|
28
|
+
r((t = t.apply(n, i)).next());
|
|
29
29
|
});
|
|
30
30
|
import { parseJWT as m } from "./utils.mjs";
|
|
31
31
|
import R from "./Logger.mjs";
|
|
32
32
|
import { getCVForceService as E } from "./api/index.mjs";
|
|
33
|
-
import { configure as S, configuration as
|
|
34
|
-
import { ApplicationTypes as
|
|
33
|
+
import { configure as S, configuration as v } from "./Config.mjs";
|
|
34
|
+
import { ApplicationTypes as y } from "@glodon-aiot/apis";
|
|
35
35
|
import L from "./AgentSession.mjs";
|
|
36
36
|
import M from "./DialogSession.mjs";
|
|
37
37
|
import C from "./EventBus.mjs";
|
|
38
38
|
const T = new R("[BotClient] ");
|
|
39
39
|
class z {
|
|
40
|
-
constructor(i,
|
|
40
|
+
constructor(i, t, e = !0) {
|
|
41
41
|
l(this, "event", new C());
|
|
42
42
|
l(this, "cvforceApi");
|
|
43
43
|
//从token解析出来的用户信息
|
|
@@ -51,11 +51,11 @@ class z {
|
|
|
51
51
|
//问题长度
|
|
52
52
|
l(this, "_questionContextMaxLength", 4e3);
|
|
53
53
|
l(this, "_promptVariables", []);
|
|
54
|
-
if (this._token = i, this.lazyload =
|
|
54
|
+
if (this._token = i, this.lazyload = e, S(t), this._applicationId = m(i).rid || v.applicationId, !this._applicationId)
|
|
55
55
|
throw "token is not vaild";
|
|
56
56
|
this.cvforceApi = this.getService(), this.loadApplication().then((s) => {
|
|
57
|
-
S(f(
|
|
58
|
-
stream:
|
|
57
|
+
S(f(d({}, t), {
|
|
58
|
+
stream: t.stream === void 0 ? (s == null ? void 0 : s.type) === y.Dialog : t.stream
|
|
59
59
|
})), this.event.emit("ready");
|
|
60
60
|
});
|
|
61
61
|
}
|
|
@@ -87,26 +87,26 @@ class z {
|
|
|
87
87
|
}
|
|
88
88
|
loadApplication() {
|
|
89
89
|
return c(this, null, function* () {
|
|
90
|
-
var
|
|
91
|
-
this._application = yield this.cvforceApi.getApplicationId(this._applicationId).then((
|
|
92
|
-
arrange: [f(
|
|
93
|
-
recommendQuestionOpen:
|
|
90
|
+
var t, e, s;
|
|
91
|
+
this._application = yield this.cvforceApi.getApplicationId(this._applicationId).then((o) => f(d({}, o), {
|
|
92
|
+
arrange: [f(d({}, o.arrange[0]), {
|
|
93
|
+
recommendQuestionOpen: v.loadRelatedQuesions && o.arrange[0].recommendQuestionOpen
|
|
94
94
|
})]
|
|
95
|
-
}))
|
|
96
|
-
const i = (s = (
|
|
97
|
-
return i && (this._questionContextMaxLength = yield this.cvforceApi.getBaseModel(i).then((
|
|
95
|
+
}));
|
|
96
|
+
const i = (s = (e = (t = this._application) == null ? void 0 : t.arrange) == null ? void 0 : e[0]) == null ? void 0 : s.llmModel;
|
|
97
|
+
return i && (this._questionContextMaxLength = yield this.cvforceApi.getBaseModel(i).then((o) => o.maxModelLength)), this._promptVariables = yield this.cvforceApi.getPrompts(this._applicationId), this._ready = !0, this.event.emit("application:loaded"), this._application;
|
|
98
98
|
});
|
|
99
99
|
}
|
|
100
100
|
getService() {
|
|
101
|
-
return this.cvforceApi ? this.cvforceApi : E(
|
|
101
|
+
return this.cvforceApi ? this.cvforceApi : E(v.apiRoot, this.token, (i, t) => T.error(t));
|
|
102
102
|
}
|
|
103
103
|
get token() {
|
|
104
104
|
return this._token;
|
|
105
105
|
}
|
|
106
106
|
set token(i) {
|
|
107
107
|
this.checkReady(), this._token = i, this.ready = !1;
|
|
108
|
-
const
|
|
109
|
-
this._applicationId !==
|
|
108
|
+
const t = m(i).rid;
|
|
109
|
+
this._applicationId !== t && (this._applicationId = t, this._application = null, this.loadApplication().then(() => {
|
|
110
110
|
this.event.emit("ready");
|
|
111
111
|
}), this.clean());
|
|
112
112
|
}
|
|
@@ -121,19 +121,19 @@ class z {
|
|
|
121
121
|
return this.checkReady(), ((i = this._activeSession) == null ? void 0 : i.id) || "";
|
|
122
122
|
}
|
|
123
123
|
set activeSession(i) {
|
|
124
|
-
this.checkReady(), this.loadSession(i).then((
|
|
125
|
-
this._activeSession && this._activeSession.id !== i && this._activeSession.inactivate(), this._activeSession =
|
|
124
|
+
this.checkReady(), this.loadSession(i).then((t) => {
|
|
125
|
+
this._activeSession && this._activeSession.id !== i && this._activeSession.inactivate(), this._activeSession = t;
|
|
126
126
|
});
|
|
127
127
|
}
|
|
128
|
-
createSession(i,
|
|
128
|
+
createSession(i, t, e, s, o) {
|
|
129
129
|
return c(this, null, function* () {
|
|
130
|
-
const
|
|
130
|
+
const p = this;
|
|
131
131
|
return new Promise((r, a) => {
|
|
132
132
|
const h = (_) => c(this, null, function* () {
|
|
133
|
-
if (_ ===
|
|
134
|
-
r(new L(i,
|
|
135
|
-
else if (_ ===
|
|
136
|
-
r(new M(i,
|
|
133
|
+
if (_ === y.Agent)
|
|
134
|
+
r(new L(i, t, e, s, o, p));
|
|
135
|
+
else if (_ === y.Dialog)
|
|
136
|
+
r(new M(i, t, e, s, o, p));
|
|
137
137
|
else
|
|
138
138
|
throw Error(`不支持的应用类型:${_}`);
|
|
139
139
|
});
|
|
@@ -152,44 +152,44 @@ class z {
|
|
|
152
152
|
}
|
|
153
153
|
getSessions(i) {
|
|
154
154
|
return c(this, null, function* () {
|
|
155
|
-
return new Promise((
|
|
156
|
-
const s = () => this.cvforceApi.listSessions(this._applicationId, i).then((
|
|
157
|
-
const
|
|
158
|
-
return
|
|
155
|
+
return new Promise((t, e) => {
|
|
156
|
+
const s = () => this.cvforceApi.listSessions(this._applicationId, i).then((o) => {
|
|
157
|
+
const p = [];
|
|
158
|
+
return o.forEach((r) => c(this, null, function* () {
|
|
159
159
|
const a = this._sessions.find((h) => r.id === h.id);
|
|
160
160
|
if (a)
|
|
161
|
-
a.data = r, this._application ? a.application = this._application : a.loadApplicationInfo(),
|
|
161
|
+
a.data = r, this._application ? a.application = this._application : a.loadApplicationInfo(), p.push(a);
|
|
162
162
|
else {
|
|
163
163
|
const h = yield this.createSession(this.token, r.id, r, this.lazyload, this._application || void 0);
|
|
164
|
-
|
|
164
|
+
p.push(h);
|
|
165
165
|
}
|
|
166
|
-
})), this.sessions =
|
|
166
|
+
})), this.sessions = p, p;
|
|
167
167
|
});
|
|
168
168
|
if (this.ready) {
|
|
169
169
|
if (!this._application)
|
|
170
170
|
throw Error("_application is null");
|
|
171
|
-
|
|
171
|
+
t(s());
|
|
172
172
|
} else
|
|
173
173
|
this.event.on("ready", () => {
|
|
174
174
|
if (!this._application)
|
|
175
175
|
throw Error("_application is null");
|
|
176
|
-
|
|
176
|
+
t(s());
|
|
177
177
|
}, !0);
|
|
178
178
|
});
|
|
179
179
|
});
|
|
180
180
|
}
|
|
181
|
-
loadSession(i = "",
|
|
181
|
+
loadSession(i = "", t) {
|
|
182
182
|
return c(this, null, function* () {
|
|
183
183
|
this.checkReady();
|
|
184
|
-
let
|
|
185
|
-
if (
|
|
186
|
-
if (this._activeSession ===
|
|
187
|
-
return
|
|
184
|
+
let e = this.sessions.find((s) => s.id === i);
|
|
185
|
+
if (e || (e = yield this.createSession(this.token, i, t), this._sessions.push(e)), this._activeSession) {
|
|
186
|
+
if (this._activeSession === e)
|
|
187
|
+
return e;
|
|
188
188
|
this._activeSession.inactivate();
|
|
189
189
|
}
|
|
190
|
-
return
|
|
191
|
-
this._activeSession !==
|
|
192
|
-
}, !0),
|
|
190
|
+
return e.id ? (yield e.activate(), this._activeSession = e) : e.addEventListener("data:loaded", () => {
|
|
191
|
+
this._activeSession !== e && (e == null || e.activate(), this._activeSession = e);
|
|
192
|
+
}, !0), e;
|
|
193
193
|
});
|
|
194
194
|
}
|
|
195
195
|
reload() {
|
|
@@ -200,45 +200,45 @@ class z {
|
|
|
200
200
|
reloadSession(i) {
|
|
201
201
|
return c(this, null, function* () {
|
|
202
202
|
yield this.reload();
|
|
203
|
-
let
|
|
204
|
-
if (!
|
|
203
|
+
let t = this._sessions.find((e) => e.id === i) || this._activeSession;
|
|
204
|
+
if (!t) {
|
|
205
205
|
console.warn("reloadSession session failed.");
|
|
206
206
|
return;
|
|
207
207
|
}
|
|
208
|
-
return yield
|
|
208
|
+
return yield t.reload(), t;
|
|
209
209
|
});
|
|
210
210
|
}
|
|
211
|
-
setTop(i,
|
|
211
|
+
setTop(i, t, e = "top_time desc, sort_status desc, updated_at desc") {
|
|
212
212
|
return c(this, null, function* () {
|
|
213
|
-
let s = i ? this._sessions.find((
|
|
213
|
+
let s = i ? this._sessions.find((o) => o.id === i) : this._activeSession;
|
|
214
214
|
if (!s) {
|
|
215
215
|
console.warn("setTop session failed.");
|
|
216
216
|
return;
|
|
217
217
|
}
|
|
218
|
-
return yield s.setTop(
|
|
219
|
-
order:
|
|
218
|
+
return yield s.setTop(t), this.getSessions({
|
|
219
|
+
order: e
|
|
220
220
|
});
|
|
221
221
|
});
|
|
222
222
|
}
|
|
223
|
-
addEventListener(i,
|
|
224
|
-
if (typeof
|
|
223
|
+
addEventListener(i, t, e = !1) {
|
|
224
|
+
if (typeof t != "function")
|
|
225
225
|
throw Error("event listener is not a function");
|
|
226
|
-
if (
|
|
227
|
-
this.event.once(i,
|
|
226
|
+
if (e) {
|
|
227
|
+
this.event.once(i, t);
|
|
228
228
|
return;
|
|
229
229
|
}
|
|
230
|
-
this.event.on(i,
|
|
230
|
+
this.event.on(i, t);
|
|
231
231
|
}
|
|
232
|
-
removeEventListener(i,
|
|
233
|
-
this.event.off(i,
|
|
232
|
+
removeEventListener(i, t) {
|
|
233
|
+
this.event.off(i, t);
|
|
234
234
|
}
|
|
235
|
-
removeSession(i,
|
|
235
|
+
removeSession(i, t) {
|
|
236
236
|
return c(this, null, function* () {
|
|
237
237
|
this.checkReady();
|
|
238
|
-
let
|
|
239
|
-
if (typeof i == "string" ?
|
|
240
|
-
const s = this._sessions[
|
|
241
|
-
|
|
238
|
+
let e = -1;
|
|
239
|
+
if (typeof i == "string" ? e = this._sessions.findIndex((s) => s.id === i) : e = this._sessions.findIndex((s) => s.id === i.id), e > -1) {
|
|
240
|
+
const s = this._sessions[e];
|
|
241
|
+
t && (yield s.delete()), this._sessions.splice(e, 1);
|
|
242
242
|
} else
|
|
243
243
|
console.warn("session delete failed, session is not exist.");
|
|
244
244
|
});
|
package/dist/es/Session.mjs
CHANGED
|
@@ -1,43 +1,43 @@
|
|
|
1
|
-
var x = Object.defineProperty,
|
|
2
|
-
var
|
|
1
|
+
var x = Object.defineProperty, Q = Object.defineProperties;
|
|
2
|
+
var V = Object.getOwnPropertyDescriptors;
|
|
3
3
|
var S = Object.getOwnPropertySymbols;
|
|
4
|
-
var
|
|
5
|
-
var k = (
|
|
6
|
-
for (var
|
|
7
|
-
|
|
4
|
+
var R = Object.prototype.hasOwnProperty, T = Object.prototype.propertyIsEnumerable;
|
|
5
|
+
var k = (l, e, t) => e in l ? x(l, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : l[e] = t, f = (l, e) => {
|
|
6
|
+
for (var t in e || (e = {}))
|
|
7
|
+
R.call(e, t) && k(l, t, e[t]);
|
|
8
8
|
if (S)
|
|
9
|
-
for (var
|
|
10
|
-
|
|
11
|
-
return
|
|
12
|
-
}, I = (
|
|
13
|
-
var
|
|
14
|
-
var r = (
|
|
9
|
+
for (var t of S(e))
|
|
10
|
+
T.call(e, t) && k(l, t, e[t]);
|
|
11
|
+
return l;
|
|
12
|
+
}, I = (l, e) => Q(l, V(e));
|
|
13
|
+
var p = (l, e, t) => (k(l, typeof e != "symbol" ? e + "" : e, t), t);
|
|
14
|
+
var r = (l, e, t) => new Promise((i, n) => {
|
|
15
15
|
var o = (s) => {
|
|
16
16
|
try {
|
|
17
|
-
|
|
18
|
-
} catch (
|
|
19
|
-
n(
|
|
17
|
+
c(t.next(s));
|
|
18
|
+
} catch (d) {
|
|
19
|
+
n(d);
|
|
20
20
|
}
|
|
21
|
-
},
|
|
21
|
+
}, h = (s) => {
|
|
22
22
|
try {
|
|
23
|
-
|
|
24
|
-
} catch (
|
|
25
|
-
n(
|
|
23
|
+
c(t.throw(s));
|
|
24
|
+
} catch (d) {
|
|
25
|
+
n(d);
|
|
26
26
|
}
|
|
27
|
-
},
|
|
28
|
-
|
|
27
|
+
}, c = (s) => s.done ? i(s.value) : Promise.resolve(s.value).then(o, h);
|
|
28
|
+
c((t = t.apply(l, e)).next());
|
|
29
29
|
});
|
|
30
30
|
import { v4 as M } from "uuid";
|
|
31
|
-
import { parseJWT as z, removeNewlines as O, removeLeadingAndTrailingBackslashes as
|
|
32
|
-
import { ApplicationTypes as E, PromptStatus as
|
|
33
|
-
import
|
|
34
|
-
import { configuration as
|
|
35
|
-
import
|
|
36
|
-
import { getCVForceService as
|
|
31
|
+
import { parseJWT as z, resolveRelatedQuestionContent as C, removeNewlines as O, removeLeadingAndTrailingBackslashes as P } from "./utils.mjs";
|
|
32
|
+
import { ApplicationTypes as E, PromptStatus as q, PromptVariableType as b, ChatMessageRole as A } from "@glodon-aiot/apis";
|
|
33
|
+
import F from "./Logger.mjs";
|
|
34
|
+
import { configuration as L } from "./Config.mjs";
|
|
35
|
+
import N from "./EventBus.mjs";
|
|
36
|
+
import { getCVForceService as U } from "./api/index.mjs";
|
|
37
37
|
import B from "dayjs";
|
|
38
|
-
const u = new
|
|
39
|
-
var
|
|
40
|
-
class
|
|
38
|
+
const u = new F("[Session] ");
|
|
39
|
+
var D = /* @__PURE__ */ ((l) => (l.DataRequestFailed = "data request error", l.SocketConnectionFailed = "socket error", l.IdUndefined = "session id is not defined", l.SendingEmptyContent = "failed at sending empty content", l.Frozen = "session is frozen", l.UserModeError = "failed at setting socket user mode", l.Inactive = "session is inactive", l))(D || {});
|
|
40
|
+
class Z {
|
|
41
41
|
/**
|
|
42
42
|
* Session 类的构造函数,用于初始化会话实例。
|
|
43
43
|
* @param token - 用户的身份验证令牌,用于解析应用 ID。
|
|
@@ -47,69 +47,69 @@ class X {
|
|
|
47
47
|
* @param _application - 应用信息,可选参数。
|
|
48
48
|
* @param client - Bot 客户端实例,可选参数。
|
|
49
49
|
*/
|
|
50
|
-
constructor(e,
|
|
51
|
-
|
|
52
|
-
|
|
50
|
+
constructor(e, t = "", i, n, o, h) {
|
|
51
|
+
p(this, "_id");
|
|
52
|
+
p(this, "_frozen", !1);
|
|
53
53
|
//是否可发送新问题
|
|
54
|
-
|
|
55
|
-
|
|
54
|
+
p(this, "inactivating", !1);
|
|
55
|
+
p(this, "_ready", !1);
|
|
56
56
|
// ready = false;
|
|
57
|
-
|
|
57
|
+
p(this, "event", new N());
|
|
58
58
|
//从token解析出来的用户信息
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
this.token = e, this.lazyload = n, this.client =
|
|
59
|
+
p(this, "_applicationId");
|
|
60
|
+
p(this, "_application", null);
|
|
61
|
+
p(this, "data", null);
|
|
62
|
+
p(this, "client", null);
|
|
63
|
+
p(this, "messages", []);
|
|
64
|
+
p(this, "_loadingMessages", !1);
|
|
65
|
+
p(this, "_loadingMessagesSize", 10);
|
|
66
|
+
p(this, "cvforceApi");
|
|
67
|
+
p(this, "socket", null);
|
|
68
|
+
p(this, "_promptVariables", []);
|
|
69
|
+
p(this, "active", !1);
|
|
70
|
+
p(this, "activing", !1);
|
|
71
|
+
p(this, "_stopAnswer", !1);
|
|
72
|
+
p(this, "_dataLoading", !1);
|
|
73
|
+
p(this, "_dataLoaded", !1);
|
|
74
|
+
p(this, "_mcpServers", null);
|
|
75
|
+
this.token = e, this.lazyload = n, this.client = h || null, this._applicationId = z(e).rid || L.applicationId, this.cvforceApi = this.getService(), o && (this._application = o), this.event.emit("init", {
|
|
76
76
|
applicationId: this._applicationId,
|
|
77
|
-
sessionId:
|
|
77
|
+
sessionId: t
|
|
78
78
|
}), this.loadApplicationInfo().then(() => {
|
|
79
|
-
var
|
|
80
|
-
if (
|
|
81
|
-
this._id =
|
|
82
|
-
this.data = s, this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,
|
|
79
|
+
var c;
|
|
80
|
+
if (t)
|
|
81
|
+
this._id = t, this.event.emit("data:loading"), i ? (this.data = i, n || (this._dataLoading = !0, this.cvforceApi.getSession(this.applicationId, t).then((s) => r(this, null, function* () {
|
|
82
|
+
this.data = s, this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, t);
|
|
83
83
|
})).then(() => r(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,
|
|
86
|
-
this.data = s, this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,
|
|
85
|
+
})))) : (this._dataLoading = !0, this.cvforceApi.getSession(this.applicationId, t).then((s) => r(this, null, function* () {
|
|
86
|
+
this.data = s, this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, t);
|
|
87
87
|
})).then(() => r(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 {
|
|
91
|
-
const s = (
|
|
91
|
+
const s = (i == null ? void 0 : i.name) || "新建会话";
|
|
92
92
|
this.event.emit("data:creating", {
|
|
93
93
|
applicationId: this._applicationId,
|
|
94
94
|
name: s
|
|
95
95
|
}), this.event.emit("data:loading"), this.cvforceApi.postSession(this.applicationId, {
|
|
96
96
|
name: s,
|
|
97
97
|
// @ts-ignore
|
|
98
|
-
netOpen:
|
|
99
|
-
knowledgeIdList: (
|
|
98
|
+
netOpen: i == null ? void 0 : i.netOpen,
|
|
99
|
+
knowledgeIdList: (c = i == null ? void 0 : i.knowledges) == null ? void 0 : c.map((d) => d.id),
|
|
100
100
|
applicationId: this._applicationId
|
|
101
|
-
}).then((
|
|
101
|
+
}).then((d) => r(this, null, function* () {
|
|
102
102
|
var g;
|
|
103
|
-
this._id =
|
|
104
|
-
knowledges:
|
|
103
|
+
this._id = d.id, this.data = I(f({}, d), {
|
|
104
|
+
knowledges: i == null ? void 0 : i.knowledges
|
|
105
105
|
}), this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, this._id), yield (() => r(this, null, function* () {
|
|
106
|
-
if (
|
|
107
|
-
return this.setKnowledges((
|
|
106
|
+
if (i != null && i.knowledges)
|
|
107
|
+
return this.setKnowledges((i == null ? void 0 : i.knowledges) || void 0);
|
|
108
108
|
}))(), yield (() => {
|
|
109
|
-
if (
|
|
109
|
+
if (i != null && i.promptVariables) {
|
|
110
110
|
const y = this._promptVariables.map((m) => {
|
|
111
111
|
var w, v;
|
|
112
|
-
const a = ((v = (w =
|
|
112
|
+
const a = ((v = (w = i.promptVariables) == null ? void 0 : w.find((_) => _.key === m.key && _.type === m.type)) == null ? void 0 : v.value) || "";
|
|
113
113
|
return I(f({}, m), {
|
|
114
114
|
value: a
|
|
115
115
|
});
|
|
@@ -181,28 +181,28 @@ class X {
|
|
|
181
181
|
throw Error("session id is not defined");
|
|
182
182
|
if (!this.data)
|
|
183
183
|
throw Error("session data is not loaded");
|
|
184
|
-
const e = this.promptVariables.filter((
|
|
184
|
+
const e = this.promptVariables.filter((t) => t.status === q.Quoted).filter((t) => !t.value);
|
|
185
185
|
if (e.length)
|
|
186
|
-
throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map((
|
|
186
|
+
throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map((t) => t.key).join(", ")}`);
|
|
187
187
|
}
|
|
188
188
|
get promptVariables() {
|
|
189
189
|
return this._promptVariables.filter((e) => !(e.type === b.User && e.key === "query") && !(e.type === b.System && e.key === "datetime"));
|
|
190
190
|
}
|
|
191
191
|
setPromptVariables(e) {
|
|
192
192
|
return r(this, null, function* () {
|
|
193
|
-
const
|
|
193
|
+
const t = this._promptVariables.map((i) => {
|
|
194
194
|
var o;
|
|
195
|
-
const n = ((o = e == null ? void 0 : e.find((
|
|
196
|
-
return I(f({},
|
|
195
|
+
const n = ((o = e == null ? void 0 : e.find((h) => h.key === i.key && h.type === i.type)) == null ? void 0 : o.value) || i.value;
|
|
196
|
+
return I(f({}, i), {
|
|
197
197
|
value: n
|
|
198
198
|
});
|
|
199
|
-
}).sort((
|
|
200
|
-
if (yield Promise.all(
|
|
199
|
+
}).sort((i, n) => i.key.localeCompare(n.key));
|
|
200
|
+
if (yield Promise.all(t.filter((i) => !(i.type === b.User && i.key === "query") && !(i.type === b.System && i.key === "datetime")).map((i) => {
|
|
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 (!(!i.id || !i.key))
|
|
204
|
+
return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId, this.data.id, i.id, {
|
|
205
|
+
value: i.value
|
|
206
206
|
});
|
|
207
207
|
})), !this.data)
|
|
208
208
|
throw Error("session data is not loaded");
|
|
@@ -223,8 +223,8 @@ class X {
|
|
|
223
223
|
*/
|
|
224
224
|
setNetOpen(e) {
|
|
225
225
|
return r(this, null, function* () {
|
|
226
|
-
var
|
|
227
|
-
if (u.log("setNetOpen:", e), u.log("application arrange setting value: ", (
|
|
226
|
+
var t, i, n;
|
|
227
|
+
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
228
|
console.warn("Agent Application Sessions are disabled to setNetOpen.");
|
|
229
229
|
return;
|
|
230
230
|
}
|
|
@@ -243,27 +243,27 @@ class X {
|
|
|
243
243
|
});
|
|
244
244
|
}
|
|
245
245
|
getService() {
|
|
246
|
-
return
|
|
247
|
-
const
|
|
246
|
+
return U(L.apiRoot, this.token, (e, t) => {
|
|
247
|
+
const i = new Error("data request error", {
|
|
248
248
|
cause: {
|
|
249
249
|
status: e,
|
|
250
|
-
message:
|
|
250
|
+
message: t
|
|
251
251
|
}
|
|
252
252
|
});
|
|
253
|
-
u.error(
|
|
253
|
+
u.error(i), this.event.emit("error", i);
|
|
254
254
|
});
|
|
255
255
|
}
|
|
256
|
-
addEventListener(e,
|
|
257
|
-
if (typeof
|
|
256
|
+
addEventListener(e, t, i = !1) {
|
|
257
|
+
if (typeof t != "function")
|
|
258
258
|
throw Error("event listener is not a function");
|
|
259
|
-
if (
|
|
260
|
-
this.event.once(e,
|
|
259
|
+
if (i) {
|
|
260
|
+
this.event.once(e, t);
|
|
261
261
|
return;
|
|
262
262
|
}
|
|
263
|
-
this.event.on(e,
|
|
263
|
+
this.event.on(e, t);
|
|
264
264
|
}
|
|
265
|
-
removeEventListener(e,
|
|
266
|
-
this.event.off(e,
|
|
265
|
+
removeEventListener(e, t) {
|
|
266
|
+
this.event.off(e, t);
|
|
267
267
|
}
|
|
268
268
|
/**
|
|
269
269
|
* 获取对话记录
|
|
@@ -272,35 +272,35 @@ class X {
|
|
|
272
272
|
*/
|
|
273
273
|
fetchMessages() {
|
|
274
274
|
return r(this, arguments, function* (e = {}) {
|
|
275
|
-
var
|
|
276
|
-
const
|
|
275
|
+
var i, n;
|
|
276
|
+
const t = {
|
|
277
277
|
pageSize: this._loadingMessagesSize
|
|
278
278
|
};
|
|
279
279
|
if (this._id) {
|
|
280
|
-
e = f(f({},
|
|
281
|
-
const o = yield this.cvforceApi.getChatHistorySessionId(this._applicationId, this._id, e),
|
|
280
|
+
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;
|
|
281
|
+
const o = yield this.cvforceApi.getChatHistorySessionId(this._applicationId, this._id, e), h = o.map((s, d) => {
|
|
282
282
|
var m, a;
|
|
283
283
|
let g = [], y;
|
|
284
|
-
return typeof ((m = s.agentHistoryList) == null ? void 0 : m.agentList) == "string" && (g = JSON.parse(s.agentHistoryList.agentList).reduce((v, _) => (v[_.data.step - 1] || (v[_.data.step - 1] = []), v[_.data.step - 1].push(_), v), [])),
|
|
284
|
+
return typeof ((m = s.agentHistoryList) == null ? void 0 : m.agentList) == "string" && (g = JSON.parse(s.agentHistoryList.agentList).reduce((v, _) => (v[_.data.step - 1] || (v[_.data.step - 1] = []), v[_.data.step - 1].push(_), v), [])), d === o.length - 1 && (y = (a = this.data) == null ? void 0 : a.lastRelatedQuestion), I(f({}, s), {
|
|
285
285
|
actions: g,
|
|
286
286
|
relatedQuesion: y
|
|
287
287
|
});
|
|
288
288
|
});
|
|
289
289
|
if (!e.endTime && !e.startTime) {
|
|
290
290
|
const s = this.messages[this.messages.length - 1];
|
|
291
|
-
s && !s.relatedQuesion && (s.relatedQuesion = (
|
|
291
|
+
s && !s.relatedQuesion && (s.relatedQuesion = (i = this.data) == null ? void 0 : i.lastRelatedQuestion), this.messages = [...h, ...this.messages];
|
|
292
292
|
} else if (e.endTime && !e.startTime) {
|
|
293
|
-
const s = this.messages.findIndex((
|
|
294
|
-
this.messages.splice(0, s + 1), this.messages = [...
|
|
293
|
+
const s = this.messages.findIndex((d) => d.ts === e.endTime);
|
|
294
|
+
this.messages.splice(0, s + 1), this.messages = [...h, ...this.messages];
|
|
295
295
|
} else if (!e.endTime && e.startTime) {
|
|
296
|
-
const s = this.messages.findLastIndex((
|
|
297
|
-
this.messages.splice(s, this.messages.length - s - 1), this.messages = [...this.messages, ...
|
|
296
|
+
const s = this.messages.findLastIndex((d) => d.ts === e.endTime);
|
|
297
|
+
this.messages.splice(s, this.messages.length - s - 1), this.messages = [...this.messages, ...h];
|
|
298
298
|
} else {
|
|
299
|
-
const s = this.messages.findIndex((g) => g.ts === e.endTime),
|
|
300
|
-
this.messages.splice(s,
|
|
299
|
+
const s = this.messages.findIndex((g) => g.ts === e.endTime), d = this.messages.findLastIndex((g) => g.ts === e.endTime);
|
|
300
|
+
this.messages.splice(s, d - s + 1, ...h);
|
|
301
301
|
}
|
|
302
|
-
const
|
|
303
|
-
return
|
|
302
|
+
const c = this.messages[this.messages.length - 1];
|
|
303
|
+
return c && !c.relatedQuesion && (c.relatedQuesion = (n = this.data) == null ? void 0 : n.lastRelatedQuestion), this.event.emit("history:moreloaded", h), u.log("history:loaded", this.messages), this.event.emit("history:loaded", this.messages), this._loadingMessages = !1, h;
|
|
304
304
|
} else {
|
|
305
305
|
const o = new Error(
|
|
306
306
|
"session id is not defined"
|
|
@@ -365,17 +365,17 @@ class X {
|
|
|
365
365
|
activate() {
|
|
366
366
|
return r(this, null, function* () {
|
|
367
367
|
if (this.activing)
|
|
368
|
-
return new Promise((
|
|
368
|
+
return new Promise((t) => {
|
|
369
369
|
this.addEventListener("activated", () => {
|
|
370
|
-
|
|
370
|
+
t(!0);
|
|
371
371
|
}, !0);
|
|
372
372
|
});
|
|
373
373
|
if (!this._id)
|
|
374
374
|
throw Error("session is not avalible. id is undefined");
|
|
375
375
|
this.activing = !0;
|
|
376
376
|
const e = this._id;
|
|
377
|
-
return this._dataLoading = !0, this._dataLoaded = !1, this.data = yield this.cvforceApi.getSession(this.applicationId, e).then((
|
|
378
|
-
return this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, e),
|
|
377
|
+
return this._dataLoading = !0, this._dataLoaded = !1, this.data = yield this.cvforceApi.getSession(this.applicationId, e).then((t) => r(this, null, function* () {
|
|
378
|
+
return this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, e), t;
|
|
379
379
|
})), 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;
|
|
380
380
|
});
|
|
381
381
|
}
|
|
@@ -390,9 +390,9 @@ class X {
|
|
|
390
390
|
get messagesLoading() {
|
|
391
391
|
return this._loadingMessages;
|
|
392
392
|
}
|
|
393
|
-
send(
|
|
394
|
-
return r(this, arguments, function* (e,
|
|
395
|
-
stream:
|
|
393
|
+
send(i) {
|
|
394
|
+
return r(this, arguments, function* (e, t = {
|
|
395
|
+
stream: L.stream
|
|
396
396
|
}) {
|
|
397
397
|
var m;
|
|
398
398
|
try {
|
|
@@ -401,10 +401,10 @@ class X {
|
|
|
401
401
|
console.error(a);
|
|
402
402
|
}
|
|
403
403
|
const {
|
|
404
|
-
stream: n =
|
|
404
|
+
stream: n = L.stream,
|
|
405
405
|
referenceFirst: o = !1
|
|
406
|
-
} =
|
|
407
|
-
if (!
|
|
406
|
+
} = t, h = e.uuid || M(), c = ((m = e.text) == null ? void 0 : m.trim()) || "", s = e.fileIds;
|
|
407
|
+
if (!c && /*!files.length &&*/
|
|
408
408
|
!(s != null && s.length)) {
|
|
409
409
|
const a = new Error(
|
|
410
410
|
"failed at sending empty content"
|
|
@@ -436,24 +436,24 @@ class X {
|
|
|
436
436
|
return u.error(a), this.event.emit("error", a), !1;
|
|
437
437
|
}
|
|
438
438
|
this.frozen = !0, this._stopAnswer = !1;
|
|
439
|
-
const
|
|
439
|
+
const d = {
|
|
440
440
|
sessionId: this.id,
|
|
441
441
|
role: 2,
|
|
442
|
-
content:
|
|
443
|
-
messageId:
|
|
442
|
+
content: c,
|
|
443
|
+
messageId: h,
|
|
444
444
|
reference: [],
|
|
445
445
|
searchReference: [],
|
|
446
446
|
messageTime: ""
|
|
447
447
|
}, g = {
|
|
448
|
-
content:
|
|
448
|
+
content: c,
|
|
449
449
|
stream: n,
|
|
450
|
-
requestId:
|
|
450
|
+
requestId: h,
|
|
451
451
|
fileIds: s,
|
|
452
452
|
referenceFirst: o
|
|
453
453
|
};
|
|
454
|
-
this.pushMessage(
|
|
454
|
+
this.pushMessage(d), this.event.emit("question:content", c);
|
|
455
455
|
const y = (a) => r(this, null, function* () {
|
|
456
|
-
if (a.role !==
|
|
456
|
+
if (a.role !== A.Robot)
|
|
457
457
|
return;
|
|
458
458
|
switch (this.removeEventListener("answer:finish", y), this._id && a.content && a.index && a.index < 0 && (this.data = yield this.cvforceApi.patchSessionsId(this.applicationId, this._id, {
|
|
459
459
|
finialMessage: a.content
|
|
@@ -474,77 +474,88 @@ class X {
|
|
|
474
474
|
}
|
|
475
475
|
this.getRelatedQuesion(a), a.isLoading = !1;
|
|
476
476
|
let w = this.messages[this.messages.length - 1];
|
|
477
|
-
if (w && w.role ===
|
|
477
|
+
if (w && w.role === A.Robot) {
|
|
478
478
|
const v = f(f({}, w), a);
|
|
479
479
|
this.messages[this.messages.length - 1] = v, this.event.emit("message:updated", v);
|
|
480
480
|
} else
|
|
481
481
|
this.pushMessage(a);
|
|
482
482
|
this.frozen = !1;
|
|
483
483
|
});
|
|
484
|
-
return this.addEventListener("answer:finish", y), this.sendQuestion(g, I(f({},
|
|
484
|
+
return this.addEventListener("answer:finish", y), this.sendQuestion(g, I(f({}, t), {
|
|
485
485
|
stream: n,
|
|
486
486
|
referenceFirst: o
|
|
487
|
-
})),
|
|
487
|
+
})), d;
|
|
488
488
|
});
|
|
489
489
|
}
|
|
490
|
+
currentUserQuestion() {
|
|
491
|
+
for (let e = this.messages.length - 1; e >= 0; e -= 1) {
|
|
492
|
+
const t = this.messages[e];
|
|
493
|
+
if (t.role === A.User)
|
|
494
|
+
return t.content || "";
|
|
495
|
+
}
|
|
496
|
+
return "";
|
|
497
|
+
}
|
|
490
498
|
getRelatedQuesion(e) {
|
|
491
499
|
return r(this, null, function* () {
|
|
492
|
-
var
|
|
493
|
-
if (!e.content || e.isSensitive || e.code !== 200
|
|
500
|
+
var c, s;
|
|
501
|
+
if (!e.content || e.isSensitive || e.code !== 200)
|
|
502
|
+
return e;
|
|
503
|
+
const t = (c = this.application) == null ? void 0 : c.arrange[0], i = C(t == null ? void 0 : t.recommendQuestionOpen, t == null ? void 0 : t.relatedQuestionApp, e.content, this.currentUserQuestion());
|
|
504
|
+
if (i === null)
|
|
494
505
|
return e;
|
|
495
506
|
this.event.emit("message:relatedQuesion:loading", e);
|
|
496
|
-
const
|
|
497
|
-
content:
|
|
507
|
+
const n = yield this.cvforceApi.postGeneques({
|
|
508
|
+
content: i
|
|
498
509
|
}).catch((d) => null);
|
|
499
|
-
if (!
|
|
500
|
-
const d = [],
|
|
510
|
+
if (!n) {
|
|
511
|
+
const d = [], g = I(f({}, e), {
|
|
501
512
|
relatedQuesion: d,
|
|
502
513
|
index: -3,
|
|
503
514
|
isLoading: !1
|
|
504
515
|
});
|
|
505
516
|
return this.event.emit("message:relatedQuesion:loaded", {
|
|
506
517
|
relatedQuesion: d
|
|
507
|
-
}), this.event.emit("message:updated",
|
|
518
|
+
}), this.event.emit("message:updated", g), g;
|
|
508
519
|
}
|
|
509
|
-
const
|
|
510
|
-
e.relatedQuesion =
|
|
511
|
-
const
|
|
512
|
-
relatedQuesion:
|
|
520
|
+
const o = (s = n.content) == null ? void 0 : s.split("*").map(O).map(P).filter((d) => !!d);
|
|
521
|
+
e.relatedQuesion = o, e.index = -3, e.isLoading = !1;
|
|
522
|
+
const h = I(f({}, e), {
|
|
523
|
+
relatedQuesion: o,
|
|
513
524
|
index: -3,
|
|
514
525
|
isLoading: !1
|
|
515
526
|
});
|
|
516
|
-
return this.event.emit("message:relatedQuesion:loaded",
|
|
517
|
-
lastRelatedQuestion:
|
|
518
|
-
}),
|
|
527
|
+
return this.event.emit("message:relatedQuesion:loaded", h), this.event.emit("message:updated", h), this._id && this.cvforceApi.patchSessionsId(this._applicationId, this._id, {
|
|
528
|
+
lastRelatedQuestion: o
|
|
529
|
+
}), h;
|
|
519
530
|
});
|
|
520
531
|
}
|
|
521
532
|
fillMessageReference(e) {
|
|
522
533
|
return r(this, null, function* () {
|
|
523
|
-
const
|
|
524
|
-
return e.reference = e.reference.map((
|
|
534
|
+
const t = yield Promise.all(e.reference.map((i) => this.cvforceApi.getKnowledgeIdFileId(i.knowledgeId, i.docId)));
|
|
535
|
+
return e.reference = e.reference.map((i, n) => f(f({}, i), t[n])), this.event.emit("message:updated", e), e;
|
|
525
536
|
});
|
|
526
537
|
}
|
|
527
538
|
answerAgain() {
|
|
528
539
|
return r(this, arguments, function* (e = {
|
|
529
|
-
stream:
|
|
540
|
+
stream: L.stream
|
|
530
541
|
}) {
|
|
531
|
-
const
|
|
532
|
-
if (!
|
|
542
|
+
const t = this.messages[this.messages.length - 1];
|
|
543
|
+
if (!t)
|
|
533
544
|
throw Error("message list is empty");
|
|
534
545
|
this.frozen = !0, this._stopAnswer = !1;
|
|
535
546
|
const {
|
|
536
|
-
stream:
|
|
547
|
+
stream: i = L.stream
|
|
537
548
|
} = e;
|
|
538
549
|
let n;
|
|
539
|
-
|
|
540
|
-
const o = this.messages[this.messages.length - 1],
|
|
550
|
+
t.role !== A.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));
|
|
551
|
+
const o = this.messages[this.messages.length - 1], h = {
|
|
541
552
|
content: o.content,
|
|
542
553
|
fileIds: o.fileIds,
|
|
543
554
|
requestId: o.messageId,
|
|
544
|
-
stream:
|
|
555
|
+
stream: i,
|
|
545
556
|
oldMessageId: n
|
|
546
|
-
},
|
|
547
|
-
if (s.role ===
|
|
557
|
+
}, c = (s) => r(this, null, function* () {
|
|
558
|
+
if (s.role === A.Robot && s.index === -1) {
|
|
548
559
|
switch (this._id && s.content && s.index && s.index < 0 && (this.data = yield this.cvforceApi.patchSessionsId(this.applicationId, this._id, {
|
|
549
560
|
finialMessage: s.content
|
|
550
561
|
}), this.event.emit("data:updated", this.data), this.event.emit("data:updated:finialMessage", {
|
|
@@ -562,11 +573,11 @@ class X {
|
|
|
562
573
|
default:
|
|
563
574
|
s.content = s.message || "未知错误", s.isLoading = !1, s.index = -1, this.event.emit("message:error", s);
|
|
564
575
|
}
|
|
565
|
-
this.getRelatedQuesion(s), this.removeEventListener("message:content",
|
|
576
|
+
this.getRelatedQuesion(s), this.removeEventListener("message:content", c), this.frozen = !1;
|
|
566
577
|
}
|
|
567
578
|
});
|
|
568
|
-
this.addEventListener("message:content",
|
|
569
|
-
stream:
|
|
579
|
+
this.addEventListener("message:content", c), this.sendQuestion(h, I(f({}, e), {
|
|
580
|
+
stream: i
|
|
570
581
|
}));
|
|
571
582
|
});
|
|
572
583
|
}
|
|
@@ -588,10 +599,10 @@ class X {
|
|
|
588
599
|
* @returns 返回当前会话实例
|
|
589
600
|
*/
|
|
590
601
|
suspend() {
|
|
591
|
-
var
|
|
602
|
+
var i;
|
|
592
603
|
this.stopAnswer(), this.frozen = !1, this._stopAnswer = !0;
|
|
593
604
|
let e = this.messages[this.messages.length - 1];
|
|
594
|
-
const
|
|
605
|
+
const t = {
|
|
595
606
|
messageId: M(),
|
|
596
607
|
// 生成唯一的消息 ID
|
|
597
608
|
isLoading: !1,
|
|
@@ -602,7 +613,7 @@ class X {
|
|
|
602
613
|
// 消息时间
|
|
603
614
|
content: "",
|
|
604
615
|
// 消息内容
|
|
605
|
-
role:
|
|
616
|
+
role: A.System,
|
|
606
617
|
// 消息角色为系统消息
|
|
607
618
|
sessionId: this.id || "",
|
|
608
619
|
// 会话 ID
|
|
@@ -615,22 +626,22 @@ class X {
|
|
|
615
626
|
if (e.index === -2)
|
|
616
627
|
return;
|
|
617
628
|
if (e.actions) {
|
|
618
|
-
const n = e.actions[((
|
|
629
|
+
const n = e.actions[((i = e.actions) == null ? void 0 : i.length) - 1];
|
|
619
630
|
if (n) {
|
|
620
631
|
const o = n[n.length - 1];
|
|
621
632
|
if (o && (o.type === "BEFORE_CALL" || o.type === "FUNCTION_CALL")) {
|
|
622
633
|
const {
|
|
623
|
-
pluginName:
|
|
624
|
-
pluginCode:
|
|
634
|
+
pluginName: h,
|
|
635
|
+
pluginCode: c,
|
|
625
636
|
funcCode: s,
|
|
626
|
-
funcName:
|
|
637
|
+
funcName: d
|
|
627
638
|
} = o.data;
|
|
628
639
|
n.push({
|
|
629
640
|
data: {
|
|
630
|
-
pluginName:
|
|
631
|
-
pluginCode:
|
|
641
|
+
pluginName: h,
|
|
642
|
+
pluginCode: c,
|
|
632
643
|
funcCode: s,
|
|
633
|
-
funcName:
|
|
644
|
+
funcName: d,
|
|
634
645
|
step: o.data.step + 1
|
|
635
646
|
},
|
|
636
647
|
type: "ABORT"
|
|
@@ -641,9 +652,9 @@ class X {
|
|
|
641
652
|
}
|
|
642
653
|
}
|
|
643
654
|
}
|
|
644
|
-
e = f(f({}, e),
|
|
655
|
+
e = f(f({}, e), t), this.event.emit("message:content", e), this.event.emit("message:updated", e);
|
|
645
656
|
} else
|
|
646
|
-
this.pushMessage(
|
|
657
|
+
this.pushMessage(t), this.event.emit("message:content", t);
|
|
647
658
|
return this;
|
|
648
659
|
}
|
|
649
660
|
/**
|
|
@@ -655,9 +666,9 @@ class X {
|
|
|
655
666
|
return r(this, null, function* () {
|
|
656
667
|
if (!this._applicationId || !this._id)
|
|
657
668
|
throw Error("session is not avalible. id is undefined");
|
|
658
|
-
return this.cvforceApi.postComments(this._applicationId, this._id, e).then((
|
|
659
|
-
const
|
|
660
|
-
return
|
|
669
|
+
return this.cvforceApi.postComments(this._applicationId, this._id, e).then((t) => {
|
|
670
|
+
const i = this.messages.find((n) => n.messageId === e.messageId);
|
|
671
|
+
return i && (i.comment = e, this.event.emit("message:comment", i)), t;
|
|
661
672
|
});
|
|
662
673
|
});
|
|
663
674
|
}
|
|
@@ -684,6 +695,6 @@ class X {
|
|
|
684
695
|
}
|
|
685
696
|
}
|
|
686
697
|
export {
|
|
687
|
-
|
|
688
|
-
|
|
698
|
+
D as SessionErrors,
|
|
699
|
+
Z as default
|
|
689
700
|
};
|
package/dist/es/utils.mjs
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
|
-
import { decode as
|
|
2
|
-
const
|
|
3
|
-
const
|
|
4
|
-
return (/* @__PURE__ */ new Date()).valueOf() / 1e3 >=
|
|
5
|
-
},
|
|
1
|
+
import { decode as o } from "js-base64";
|
|
2
|
+
const t = (n) => JSON.parse(o(n.split(".")[1])), w = (n) => {
|
|
3
|
+
const e = t(n).exp;
|
|
4
|
+
return (/* @__PURE__ */ new Date()).valueOf() / 1e3 >= e;
|
|
5
|
+
}, f = (n) => n == null ? void 0 : n.replace(/[\r\n]+/gm, ""), T = (n) => n.replace(/\\|\\/g, ""), g = (n, e, c, i) => {
|
|
6
|
+
if (n !== !0)
|
|
7
|
+
return null;
|
|
8
|
+
const s = (e == null ? void 0 : e.includeUserQuestion) === !0, u = (e == null ? void 0 : e.includeAiAnswer) === !0 || !s, r = [];
|
|
9
|
+
return s && r.push(`用户问题:${i}`), u && r.push(`AI回答:${c}`), r.join(`
|
|
10
|
+
`);
|
|
11
|
+
};
|
|
6
12
|
export {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
13
|
+
w as isExpired,
|
|
14
|
+
t as parseJWT,
|
|
15
|
+
T as removeLeadingAndTrailingBackslashes,
|
|
16
|
+
f as removeNewlines,
|
|
17
|
+
g as resolveRelatedQuestionContent
|
|
11
18
|
};
|
package/dist/lib/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
"use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var P=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var $=(o,e,t)=>e in o?se(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,u=(o,e)=>{for(var t in e||(e={}))B.call(e,t)&&$(o,t,e[t]);if(P)for(var t of P(e))F.call(e,t)&&$(o,t,e[t]);return o},y=(o,e)=>ie(o,ne(e));var j=(o,e)=>{var t={};for(var s in o)B.call(o,s)&&e.indexOf(s)<0&&(t[s]=o[s]);if(o!=null&&P)for(var s of P(o))e.indexOf(s)<0&&F.call(o,s)&&(t[s]=o[s]);return t};var m=(o,e,t)=>($(o,typeof e!="symbol"?e+"":e,t),t);var p=(o,e,t)=>new Promise((s,a)=>{var r=i=>{try{c(t.next(i))}catch(d){a(d)}},n=i=>{try{c(t.throw(i))}catch(d){a(d)}},c=i=>i.done?s(i.value):Promise.resolve(i.value).then(r,n);c((t=t.apply(o,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),re=require("axios"),w=require("@glodon-aiot/apis"),oe=require("socket.io-client"),J=require("uuid"),K=require("dayjs"),L=class L{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!L.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!L.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!L.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!L.debug||console.warn(this.prefix,...e)}};m(L,"debug",!1);let b=L;const ce=new b("[Config] ");var G=(o=>(o.dev="https://aiot-dev.glodon.com/api/cvforcepd",o.test="https://aiot-dev.glodon.com/api/cvforce",o.prod="https://copilot.glodon.com/api/cvforce",o.local="http://localhost:3000/api/cvforcepd",o))(G||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function z(o){var e,t;b.debug=(o==null?void 0:o.debug)||!1,exports.configuration=y(u(u({},exports.configuration),o),{apiRoot:(o==null?void 0:o.apiRoot)||exports.configuration.apiRoot||(o!=null&&o.env?G[o.env||"prod"]:exports.configuration.apiRoot),plugins:(t=(e=o==null?void 0:o.plugins)!=null?e:exports.configuration.plugins)!=null?t:{}}),b.debug&&ce.log("updated",exports.configuration)}const V=o=>JSON.parse(ae.decode(o.split(".")[1])),de=o=>{const e=V(o).exp;return new Date().valueOf()/1e3>=e},he=o=>o==null?void 0:o.replace(/[\r\n]+/gm,""),le=o=>o.replace(/\\|\\/g,"");function X(o,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(u({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function a(d,f=!0){const l=`${o}${d}`,g=re.create({baseURL:l});return f&&g.interceptors.request.use(s),g}const r=(d,f)=>{d===401&&t(d,"aiotToken is invalid")},n=(d,f)=>{console.log("onAppStatusError",d,f),d!==10001&&d!==10215&&t(d,f)},c=a("/data/v1");return new w.CVForceApi(c,{onHttpStatusError:r,onAppStatusError:n})}var E=(o=>(o[o.Normal=0]="Normal",o[o.Debug=1]="Debug",o))(E||{});const R=new b("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&R.disable()}getEventListenerMap(){return u({},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(a=>{if(typeof a=="function"&&t===a)return!0;if(a=a,a.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 a=0;a<this.eventListenerMap[e].length;a++){const r=this.eventListenerMap[e][a];typeof r=="function"?r(t):s.push(r)}s.forEach(a=>{a&&(a.fn(t),this.off(e,a.fn))}),R.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const S=new b("[Session] ");var x=(o=>(o.DataRequestFailed="data request error",o.SocketConnectionFailed="socket error",o.IdUndefined="session id is not defined",o.SendingEmptyContent="failed at sending empty content",o.Frozen="session is frozen",o.UserModeError="failed at setting socket user mode",o.Inactive="session is inactive",o))(x||{});class q{constructor(e,t="",s,a,r,n){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=n||null,this._applicationId=V(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),r&&(this._application=r),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var c;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(i=>p(this,null,function*(){this.data=i,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(i=>p(this,null,function*(){this.data=i,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 i=(s==null?void 0:s.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:i}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:i,netOpen:s==null?void 0:s.netOpen,knowledgeIdList:(c=s==null?void 0:s.knowledges)==null?void 0:c.map(d=>d.id),applicationId:this._applicationId}).then(d=>p(this,null,function*(){var f;this._id=d.id,this.data=y(u({},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 l=this._promptVariables.map(g=>{var I,v;const h=((v=(I=s.promptVariables)==null?void 0:I.find(_=>_.key===g.key&&_.type===g.type))==null?void 0:v.value)||"";return y(u({},g),{value:h})}).sort((g,h)=>g.key.localeCompare(h.key));return this.setPromptVariables(l||[])}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.type===w.PromptVariableType.User&&e.key==="query")&&!(e.type===w.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return p(this,null,function*(){const t=this._promptVariables.map(s=>{var r;const a=((r=e==null?void 0:e.find(n=>n.key===s.key&&n.type===s.type))==null?void 0:r.value)||s.value;return y(u({},s),{value:a})}).sort((s,a)=>s.key.localeCompare(a.key));if(yield Promise.all(t.filter(s=>!(s.type===w.PromptVariableType.User&&s.key==="query")&&!(s.type===w.PromptVariableType.System&&s.key==="datetime")).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})})),!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(S.log("setNetOpen:",e),S.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,S.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}});S.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=u(u({},t),e),this.event.emit("history:loading"),S.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),S.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),n=r.map((i,d)=>{var g,h;let f=[],l;return typeof((g=i.agentHistoryList)==null?void 0:g.agentList)=="string"&&(f=JSON.parse(i.agentHistoryList.agentList).reduce((v,_)=>(v[_.data.step-1]||(v[_.data.step-1]=[]),v[_.data.step-1].push(_),v),[])),d===r.length-1&&(l=(h=this.data)==null?void 0:h.lastRelatedQuestion),y(u({},i),{actions:f,relatedQuesion:l})});if(!e.endTime&&!e.startTime){const i=this.messages[this.messages.length-1];i&&!i.relatedQuesion&&(i.relatedQuesion=(s=this.data)==null?void 0:s.lastRelatedQuestion),this.messages=[...n,...this.messages]}else if(e.endTime&&!e.startTime){const i=this.messages.findIndex(d=>d.ts===e.endTime);this.messages.splice(0,i+1),this.messages=[...n,...this.messages]}else if(!e.endTime&&e.startTime){const i=this.messages.findLastIndex(d=>d.ts===e.endTime);this.messages.splice(i,this.messages.length-i-1),this.messages=[...this.messages,...n]}else{const i=this.messages.findIndex(f=>f.ts===e.endTime),d=this.messages.findLastIndex(f=>f.ts===e.endTime);this.messages.splice(i,d-i+1,...n)}const c=this.messages[this.messages.length-1];return c&&!c.relatedQuesion&&(c.relatedQuesion=(a=this.data)==null?void 0:a.lastRelatedQuestion),this.event.emit("history:moreloaded",n),S.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,n}else{const r=new Error("session id is not defined");return S.error(r),this.event.emit("error",r),!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}),S.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),S.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),S.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 S.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 g;try{this.validateConfigs()}catch(h){console.error(h)}const{stream:a=exports.configuration.stream,referenceFirst:r=!1}=t,n=e.uuid||J.v4(),c=((g=e.text)==null?void 0:g.trim())||"",i=e.fileIds;if(!c&&!(i!=null&&i.length)){const h=new Error("failed at sending empty content");return S.error(h),this.event.emit("error",h),!1}if(!this._id){const h=new Error("session id is not defined");return S.error(h),this.event.emit("error",h),!1}if(this.frozen){const h=new Error("session is frozen");return S.error(h),this.event.emit("error",h),!1}this.frozen=!0,this._stopAnswer=!1;const d={sessionId:this.id,role:2,content:c,messageId:n,reference:[],searchReference:[],messageTime:""},f={content:c,stream:a,requestId:n,fileIds:i,referenceFirst:r};this.pushMessage(d),this.event.emit("question:content",c);const l=h=>p(this,null,function*(){if(h.role!==w.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",l),this._id&&h.content&&h.index&&h.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:h.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:h.content})),yield this.fillMessageReference(h),h.code){case 11915:h.content="请您换个问题问我吧~",h.index=-1,h.isSensitive=!0,h.isLoading=!1,h.sessionId=this._id||"",this.event.emit("message:error",h);break;case 11916:h.content="尊敬的用户您好,让我们换个话题再聊聊吧。",h.index=-1,h.isSensitive=!0,h.isLoading=!1,h.sessionId=this._id||"",this.event.emit("message:error",h);break;case 200:h.index=-1,h.isLoading=!1;break;default:h.content=h.message||"未知错误",h.isLoading=!1,h.index=-1,this.event.emit("message:error",h)}this.getRelatedQuesion(h),h.isLoading=!1;let I=this.messages[this.messages.length-1];if(I&&I.role===w.ChatMessageRole.Robot){const v=u(u({},I),h);this.messages[this.messages.length-1]=v,this.event.emit("message:updated",v)}else this.pushMessage(h);this.frozen=!1});return this.addEventListener("answer:finish",l),this.sendQuestion(f,y(u({},t),{stream:a,referenceFirst:r})),d})}getRelatedQuesion(e){return p(this,null,function*(){var r,n;if(!e.content||e.isSensitive||e.code!==200||!((r=this.application)!=null&&r.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const t=yield this.cvforceApi.postGeneques({content:e.content}).catch(c=>null);if(!t){const c=[],i=y(u({},e),{relatedQuesion:c,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:c}),this.event.emit("message:updated",i),i}const s=(n=t.content)==null?void 0:n.split("*").map(he).map(le).filter(c=>!!c);e.relatedQuesion=s,e.index=-3,e.isLoading=!1;const a=y(u({},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)=>u(u({},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 r=this.messages[this.messages.length-1],n={content:r.content,fileIds:r.fileIds,requestId:r.messageId,stream:s,oldMessageId:a},c=i=>p(this,null,function*(){if(i.role===w.ChatMessageRole.Robot&&i.index===-1){switch(this._id&&i.content&&i.index&&i.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:i.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:i.content})),yield this.fillMessageReference(i),i.code){case 11915:i.content="请您换个问题问我吧~",i.index=-1,i.isSensitive=!0,i.isLoading=!1,i.sessionId=this._id||"",this.event.emit("message:error",i);break;case 11916:i.content="尊敬的用户您好,让我们换个话题再聊聊吧。",i.index=-1,i.isSensitive=!0,i.isLoading=!1,i.sessionId=this._id||"",this.event.emit("message:error",i);break;case 200:i.index=-1,i.isLoading=!1;break;default:i.content=i.message||"未知错误",i.isLoading=!1,i.index=-1,this.event.emit("message:error",i)}this.getRelatedQuesion(i),this.removeEventListener("message:content",c),this.frozen=!1}});this.addEventListener("message:content",c),this.sendQuestion(n,y(u({},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:J.v4(),isLoading:!1,index:-2,messageTime:K(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 r=a[a.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:n,pluginCode:c,funcCode:i,funcName:d}=r.data;a.push({data:{pluginName:n,pluginCode:c,funcCode:i,funcName:d,step:r.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:a})}}}e=u(u({},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}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 b("[AgentSession] ");class fe extends q{constructor(e,t="",s,a,r,n){super(e,t,s,a,r,n)}prepareConnection(){return new Promise(e=>p(this,null,function*(){this.socket&&e(!0);const t={version:"1.0",stream:JSON.stringify(exports.configuration.stream===void 0?!0:exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?E.Debug:E.Normal},s=new URL(exports.configuration.apiRoot),a=yield oe.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",r=>{if(r.code===200){A.log("ready");const n=exports.configuration.debug?E.Debug:E.Normal;n===E.Debug&&r.userMode,this._ready=!0,this.event.emit("ready"),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const n=new Error(x.SocketConnectionFailed);A.error("error",n),this.event.emit("error",n),e(!1)}}),a.on("action",(r,n)=>p(this,null,function*(){var I;if(this._stopAnswer||!this.id)return;const{type:c,data:{runnerIsClient:i,pluginCode:d,funcCode:f,parameters:l,requestBody:g}}=r,h=this.messages[this.messages.length-1];if(!h.messageId)h.actions||(h.actions=[]),h.actions[r.data.step-1]||(h.actions[r.data.step-1]=[]),h.actions[r.data.step-1].push(r),this.event.emit("message:action",{messageId:h.messageId,action:r}),this.event.emit("message:updated",h);else{const v={messageId:"",content:"",role:w.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[r]],comment:{isAgree:0}};this.pushMessage(v),this.event.emit("message:action",{messageId:v.messageId,action:r})}if(this.inactivating){const v=new Error(x.Inactive);A.warn("error",v),this.event.emit("error",v)}else if(c==="FUNCTION_CALL"&&i){A.log(`calling function ${f} of plugin ${d} with argument:
|
|
2
|
-
${JSON.stringify(l)}`);const v=(I=exports.configuration.plugins)==null?void 0:I[d];if(!v){n({code:404,message:"没有找到插件。"});return}const _=v[f];if(typeof _!="function"){n({code:404,message:"没有找到插件方法。"});return}let M=l==null?void 0:l.query;try{M=JSON.parse(l==null?void 0:l.query)}catch(C){}_(M,(...C)=>{this._stopAnswer||n(...C)})}})),a.on("answer",r=>{if(!this._stopAnswer)if(r.data.code!==200&&(r.data.index=-1,this.event.emit("error",r.data)),r.data.index===-1){let n=this.messages[this.messages.length-1];if(n&&!n.messageId)n=u(u({},n),r.data),this.event.emit("message:content",n),this.event.emit("message:updated",n),this.event.emit("answer:finish",n);else{const c=u({messageId:"",content:"",role:w.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0}},r.data);this.event.emit("message:content",c),this.pushMessage(c),this.event.emit("answer:finish",c)}}else{let n=this.messages[this.messages.length-1];n&&!n.messageId?(n=u(u({},n),r.data),this.messages[this.messages.length-1]=n,this.event.emit("message:content",n),this.event.emit("message:updated",n)):(this.pushMessage(r.data),this.event.emit("message:content",r.data))}}),a.on("reference",r=>p(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const l=new Error(x.IdUndefined);A.error(l),this.event.emit("error",l),this.frozen=!1;return}const{type:n,data:c,requestId:i}=r,d=this.messages.findIndex(l=>l.messageId===i&&l.role===w.ChatMessageRole.User);if(d<0)return;const f=d+1;if(f>=this.messages.length){const l={messageId:"",content:"",role:w.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0}};this.pushMessage(l)}n==="KG"?(this.messages[f]=y(u({},this.messages[f]),{reference:c.knowledgeReference}),yield this.fillMessageReference(this.messages[f]),this.event.emit("message:reference",c.knowledgeReference),this.event.emit("message:updated",this.messages[f])):n==="WEB_SEARCH"&&(this.messages[f]=y(u({},this.messages[f]),{searchReference:c.knowledgeReference}),this.event.emit("message:searchreference",c.searchReference),this.event.emit("message:updated",this.messages[f]))})),this.socket=a,a.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(a=>{s.data[a].code!==200&&console.error(a,"MCP Server 注册失败。",s.data[a])}),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,a=>{a.code===200?(Object.keys(a.data).forEach(r=>{a.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",a.data[r])}),t(!0)):(console.error("MCP Server 注册失败。",a),s(a))})}):(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 a,r,n;let s=y(u({},e),{promptVariables:this.promptVariables.reduce((c,i)=>y(u({},c),{[i.key]:i.value}),{}),knowledges:(a=this.knowledges)==null?void 0:a.map(c=>c.id)});if(!this.active){if(yield this.activate(),!this.socket){const c=new Error(x.SocketConnectionFailed);return A.warn("error",c),this.event.emit("error",c),!1}(r=this.socket)==null||r.emit("question",s);return}(n=this.socket)==null||n.emit("question",s)})}stopAnswer(){var e;(e=this.socket)==null||e.emit("stop_answer")}}function pe(o,e){return p(this,null,function*(){const t=o.getReader();let s;for(;!(s=yield t.read()).done;)e(s.value)})}function ge(o){let e,t,s,a=!1,r;return function(c){e===void 0?(e=c,t=0,s=-1,r=!1):e=me(e,c);const i=e.length;let d=0;for(;t<i;){a&&(e[t]===10&&(d=++t),a=!1);let f=-1;for(;t<i&&f===-1;++t)switch(e[t]){case 58:s===-1&&(s=t-d);break;case 13:a=!1,t+4<i&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(r=!0);case 10:f=t;break}if(f===-1)break;o(e.subarray(d,f),s,r),d=t,s=-1,r=!1}d===i?e=void 0:d!==0&&(e=e.subarray(d),t-=d)}}function ue(o,e,t){let s=H();const a=new TextDecoder;return function(n,c,i){if(n.length===0)t==null||t(s),s=H();else if(c>0){const d=a.decode(n.subarray(0,c)),f=c+(n[c+1]===32?2:1);let l=a.decode(n.subarray(f));switch(i&&(l+=`
|
|
3
|
-
`),d){
|
|
4
|
-
`+l:l;break;case"event":s.event=l;break;case"id":o(s.id=l);break;case"retry":const g=parseInt(l,10);isNaN(g)||e(s.retry=g);break}}}}function me(o,e){const t=new Uint8Array(o.length+e.length);return t.set(o),t.set(e,o.length),t}function H(){return{data:"",event:"",id:"",retry:void 0}}const N="text/event-stream",ve=1e3,Y="last-event-id";function U(o,f){var l=f,{signal:e,headers:t,onopen:s,onmessage:a,onclose:r,onerror:n,openWhenHidden:c,fetch:i}=l,d=j(l,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,h)=>{const I=u({},t);I.accept||(I.accept=N);let v;function _(){v.abort(),document.hidden||Q()}c||document.addEventListener("visibilitychange",_);let M=ve,C=0;function O(){document.removeEventListener("visibilitychange",_),window.clearTimeout(C),v.abort()}e==null||e.addEventListener("abort",()=>{O(),g()});const ee=i!=null?i:window.fetch,te=s!=null?s:ye;function Q(){return p(this,null,function*(){var D;v=new AbortController;try{const T=yield ee(o,y(u({},d),{headers:I,signal:v.signal}));yield te(T),yield pe(T.body,ge(ue(k=>{k?I[Y]=k:delete I[Y]},k=>{M=k},a))),r==null||r(),O(),g()}catch(T){if(!v.signal.aborted)try{const k=(D=n==null?void 0:n(T))!=null?D:M;window.clearTimeout(C),C=window.setTimeout(Q,k)}catch(k){O(),h(k)}}})}Q()})}function ye(o){const e=o.headers.get("content-type");if(!(e!=null&&e.startsWith(N)))throw new Error(`Expected content-type to be ${N}, Actual: ${e}`)}const W=new b("[DialogSession] ");class we extends q{constructor(t,s="",a,r,n,c){super(t,s,a,r,n,c);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,r,n,c){return p(this,null,function*(){const i={code:0,content:"",role:w.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=y(u({},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:r,onopen(f){return f.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(f){if(!f.data.includes('{"code": ')){let g={};try{g=JSON.parse(f.data)}catch(I){}(g==null?void 0:g.mtype)==="search"?i.searchReference.push(g):i.content=i.content+f.data;const h={content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:s,messageTime:K(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(n==null?void 0:n.onmessage)&&n.onmessage(h)}const l=JSON.parse(f.data);if(i.reference=l.data.reference,i.searchReference=l.data.searchReference,i.messageTime=l.data.messageTime,i.messageId=l.data.messageId,i.llmModel=l.data.llmModel,i.content=l.data.content,i.code=l.code,l.code===200){const g={code:i.code,content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:s,messageTime:i.messageTime,isReplying:!0};n!=null&&n.onmessage&&n.onmessage(g)}else return n!=null&&n.onclose&&n.onclose(i),c&&c({code:i.code,message:i.message})},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const f={code:i.code,content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:s,messageTime:i.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};n!=null&&n.onclose&&n.onclose(f)}})})}postChatV3EventSource(t,s,a,r,n,c){return p(this,null,function*(){const i={code:0,content:"",role:w.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},d=y(u({},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(d),openWhenHidden:!0,signal:r,onopen(f){return f.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(f){if(!f.data&&!f.event&&!f.id&&!f.retry)return;let l={};try{l=JSON.parse(f.data)}catch(v){console.error("parse eventData to JSON failed. ",f.data)}if(l.code!==200)return i.index=-1,i.code=l.code,i.message=l.message,n!=null&&n.onmessage&&n.onmessage(i),c&&c({code:l.code,message:l.message});const g=l.data.type,h=l.data.payload;i.isReplying=!0;const I=()=>{if(!i.searchingStatus){i.searchingStatus="start";return}if(i.searchingStatus==="start"){i.searchingStatus="end";return}};if(g==="beforeSearch"&&I(),g==="searchOver"&&I(),g==="search"&&i.searchReference.push(h),g==="thinking"){i.thinkingStatus="start";const _=h.choices[0];i.reasoningContent=i.reasoningContent+_.delta.reasoningContent}if(g==="thinkingOver"){i.thinkingStatus="end";const v=h.thinkingSecs;i.thinkingSecs=v}if(g==="text"){const _=h.choices[0];i.content=i.content+_.delta.content}if(g==="reference"&&(i.reference=h),g==="result"){const v=h.messageId,_=h.llmModel,M=h.messageTime;i.messageId=v,i.llmModel=_,i.messageTime=M,i.sessionId=s}g==="over"?i.index=-1:(i.code=l.code,i.message=l.message),n!=null&&n.onmessage&&n.onmessage(i)},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const f=y(u({},i),{isReplying:!1});n!=null&&n.onclose&&n.onclose(f)}})})}sendQuestion(t,s){return p(this,null,function*(){var d;const{content:a,fileIds:r,oldMessageId:n}=t,{stream:c,referenceFirst:i}=s;if(this.active||(yield this.activate()),this._id){let f={content:a,fileIds:r,referenceFirst:i,oldMessageId:n,promptVariables:this.promptVariables.reduce((l,g)=>y(u({},l),{[g.key]:g.value}),{}),knowledges:(d=this.knowledges)==null?void 0:d.map(l=>l.id)};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,f,this.ctrl.signal,{onopen:()=>{W.log("open",this.ctrl)},onmessage:l=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===w.ChatMessageRole.Robot?(g=u(u({},g),l),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(l),this.event.emit("message:content",l))},onclose:l=>p(this,null,function*(){this._stopAnswer||(W.log(l,"onclose"),this.event.emit("answer:finish",l))}),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=new b("[BotClient] ");class _e{constructor(e,t,s=!0){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,z(t),this._applicationId=V(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(a=>{z(y(u({},t),{stream:t.stream===void 0?(a==null?void 0:a.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;this._application=yield this.cvforceApi.getApplicationId(this._applicationId).then(r=>(typeof r.arrange[0].recommendQuestionOpen!="boolean"&&(r.arrange[0].recommendQuestionOpen=!0),y(u({},r),{arrange:[y(u({},r.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&r.arrange[0].recommendQuestionOpen})]})));const e=(a=(s=(t=this._application)==null?void 0:t.arrange)==null?void 0:s[0])==null?void 0:a.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)=>Ie.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=V(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,r){return p(this,null,function*(){const n=this;return new Promise((c,i)=>{const d=f=>p(this,null,function*(){if(f===w.ApplicationTypes.Agent)c(new fe(e,t,s,a,r,n));else if(f===w.ApplicationTypes.Dialog)c(new we(e,t,s,a,r,n));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(r=>{const n=[];return r.forEach(c=>p(this,null,function*(){const i=this._sessions.find(d=>c.id===d.id);if(i)i.data=c,this._application?i.application=this._application:i.loadApplicationInfo(),n.push(i);else{const d=yield this.createSession(this.token,c.id,c,this.lazyload,this._application||void 0);n.push(d)}})),this.sessions=n,n});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(r=>r.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 Se{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=Se;exports.BotClient=_e;exports.Session=q;exports.configure=z;
|
|
1
|
+
"use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var P=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,j=Object.prototype.propertyIsEnumerable;var Q=(o,e,t)=>e in o?se(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,g=(o,e)=>{for(var t in e||(e={}))B.call(e,t)&&Q(o,t,e[t]);if(P)for(var t of P(e))j.call(e,t)&&Q(o,t,e[t]);return o},w=(o,e)=>ie(o,ne(e));var F=(o,e)=>{var t={};for(var s in o)B.call(o,s)&&e.indexOf(s)<0&&(t[s]=o[s]);if(o!=null&&P)for(var s of P(o))e.indexOf(s)<0&&j.call(o,s)&&(t[s]=o[s]);return t};var m=(o,e,t)=>(Q(o,typeof e!="symbol"?e+"":e,t),t);var p=(o,e,t)=>new Promise((s,a)=>{var r=i=>{try{d(t.next(i))}catch(c){a(c)}},n=i=>{try{d(t.throw(i))}catch(c){a(c)}},d=i=>i.done?s(i.value):Promise.resolve(i.value).then(r,n);d((t=t.apply(o,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),re=require("axios"),y=require("@glodon-aiot/apis"),oe=require("socket.io-client"),J=require("uuid"),K=require("dayjs"),L=class L{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!L.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!L.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!L.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!L.debug||console.warn(this.prefix,...e)}};m(L,"debug",!1);let b=L;const ce=new b("[Config] ");var G=(o=>(o.dev="https://aiot-dev.glodon.com/api/cvforcepd",o.test="https://aiot-dev.glodon.com/api/cvforce",o.prod="https://copilot.glodon.com/api/cvforce",o.local="http://localhost:3000/api/cvforcepd",o))(G||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function z(o){var e,t;b.debug=(o==null?void 0:o.debug)||!1,exports.configuration=w(g(g({},exports.configuration),o),{apiRoot:(o==null?void 0:o.apiRoot)||exports.configuration.apiRoot||(o!=null&&o.env?G[o.env||"prod"]:exports.configuration.apiRoot),plugins:(t=(e=o==null?void 0:o.plugins)!=null?e:exports.configuration.plugins)!=null?t:{}}),b.debug&&ce.log("updated",exports.configuration)}const V=o=>JSON.parse(ae.decode(o.split(".")[1])),de=o=>{const e=V(o).exp;return new Date().valueOf()/1e3>=e},he=o=>o==null?void 0:o.replace(/[\r\n]+/gm,""),le=o=>o.replace(/\\|\\/g,""),fe=(o,e,t,s)=>{if(o!==!0)return null;const a=(e==null?void 0:e.includeUserQuestion)===!0,n=(e==null?void 0:e.includeAiAnswer)===!0||!a,d=[];return a&&d.push(`用户问题:${s}`),n&&d.push(`AI回答:${t}`),d.join(`
|
|
2
|
+
`)};function X(o,e,t){const s=c=>{var l;return e&&(de(e)&&t(403,"aiotToken is timeout"),c.headers=(l=c.headers)!=null?l:{},c.headers=w(g({},c.headers),{Authorization:e?`Bearer ${e}`:""})),c};function a(c,l=!0){const f=`${o}${c}`,u=re.create({baseURL:f});return l&&u.interceptors.request.use(s),u}const r=(c,l)=>{c===401&&t(c,"aiotToken is invalid")},n=(c,l)=>{console.log("onAppStatusError",c,l),c!==10001&&c!==10215&&t(c,l)},d=a("/data/v1");return new y.CVForceApi(d,{onHttpStatusError:r,onAppStatusError:n})}var E=(o=>(o[o.Normal=0]="Normal",o[o.Debug=1]="Debug",o))(E||{});const R=new b("[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(a=>{if(typeof a=="function"&&t===a)return!0;if(a=a,a.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 a=0;a<this.eventListenerMap[e].length;a++){const r=this.eventListenerMap[e][a];typeof r=="function"?r(t):s.push(r)}s.forEach(a=>{a&&(a.fn(t),this.off(e,a.fn))}),R.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const S=new b("[Session] ");var x=(o=>(o.DataRequestFailed="data request error",o.SocketConnectionFailed="socket error",o.IdUndefined="session id is not defined",o.SendingEmptyContent="failed at sending empty content",o.Frozen="session is frozen",o.UserModeError="failed at setting socket user mode",o.Inactive="session is inactive",o))(x||{});class q{constructor(e,t="",s,a,r,n){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=n||null,this._applicationId=V(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),r&&(this._application=r),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var d;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(i=>p(this,null,function*(){this.data=i,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(i=>p(this,null,function*(){this.data=i,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 i=(s==null?void 0:s.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:i}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:i,netOpen:s==null?void 0:s.netOpen,knowledgeIdList:(d=s==null?void 0:s.knowledges)==null?void 0:d.map(c=>c.id),applicationId:this._applicationId}).then(c=>p(this,null,function*(){var l;this._id=c.id,this.data=w(g({},c),{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 f=this._promptVariables.map(u=>{var I,v;const h=((v=(I=s.promptVariables)==null?void 0:I.find(_=>_.key===u.key&&_.type===u.type))==null?void 0:v.value)||"";return w(g({},u),{value:h})}).sort((u,h)=>u.key.localeCompare(h.key));return this.setPromptVariables(f||[])}else return})(),this.event.emit("data:created",this.data),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),((l=this.application)==null?void 0:l.type)!==y.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===y.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.type===y.PromptVariableType.User&&e.key==="query")&&!(e.type===y.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return p(this,null,function*(){const t=this._promptVariables.map(s=>{var r;const a=((r=e==null?void 0:e.find(n=>n.key===s.key&&n.type===s.type))==null?void 0:r.value)||s.value;return w(g({},s),{value:a})}).sort((s,a)=>s.key.localeCompare(a.key));if(yield Promise.all(t.filter(s=>!(s.type===y.PromptVariableType.User&&s.key==="query")&&!(s.type===y.PromptVariableType.System&&s.key==="datetime")).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})})),!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(S.log("setNetOpen:",e),S.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===y.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,S.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}});S.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"),S.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),S.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),n=r.map((i,c)=>{var u,h;let l=[],f;return typeof((u=i.agentHistoryList)==null?void 0:u.agentList)=="string"&&(l=JSON.parse(i.agentHistoryList.agentList).reduce((v,_)=>(v[_.data.step-1]||(v[_.data.step-1]=[]),v[_.data.step-1].push(_),v),[])),c===r.length-1&&(f=(h=this.data)==null?void 0:h.lastRelatedQuestion),w(g({},i),{actions:l,relatedQuesion:f})});if(!e.endTime&&!e.startTime){const i=this.messages[this.messages.length-1];i&&!i.relatedQuesion&&(i.relatedQuesion=(s=this.data)==null?void 0:s.lastRelatedQuestion),this.messages=[...n,...this.messages]}else if(e.endTime&&!e.startTime){const i=this.messages.findIndex(c=>c.ts===e.endTime);this.messages.splice(0,i+1),this.messages=[...n,...this.messages]}else if(!e.endTime&&e.startTime){const i=this.messages.findLastIndex(c=>c.ts===e.endTime);this.messages.splice(i,this.messages.length-i-1),this.messages=[...this.messages,...n]}else{const i=this.messages.findIndex(l=>l.ts===e.endTime),c=this.messages.findLastIndex(l=>l.ts===e.endTime);this.messages.splice(i,c-i+1,...n)}const d=this.messages[this.messages.length-1];return d&&!d.relatedQuesion&&(d.relatedQuesion=(a=this.data)==null?void 0:a.lastRelatedQuestion),this.event.emit("history:moreloaded",n),S.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,n}else{const r=new Error("session id is not defined");return S.error(r),this.event.emit("error",r),!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}),S.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),S.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),S.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 S.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(h){console.error(h)}const{stream:a=exports.configuration.stream,referenceFirst:r=!1}=t,n=e.uuid||J.v4(),d=((u=e.text)==null?void 0:u.trim())||"",i=e.fileIds;if(!d&&!(i!=null&&i.length)){const h=new Error("failed at sending empty content");return S.error(h),this.event.emit("error",h),!1}if(!this._id){const h=new Error("session id is not defined");return S.error(h),this.event.emit("error",h),!1}if(this.frozen){const h=new Error("session is frozen");return S.error(h),this.event.emit("error",h),!1}this.frozen=!0,this._stopAnswer=!1;const c={sessionId:this.id,role:2,content:d,messageId:n,reference:[],searchReference:[],messageTime:""},l={content:d,stream:a,requestId:n,fileIds:i,referenceFirst:r};this.pushMessage(c),this.event.emit("question:content",d);const f=h=>p(this,null,function*(){if(h.role!==y.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",f),this._id&&h.content&&h.index&&h.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:h.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:h.content})),yield this.fillMessageReference(h),h.code){case 11915:h.content="请您换个问题问我吧~",h.index=-1,h.isSensitive=!0,h.isLoading=!1,h.sessionId=this._id||"",this.event.emit("message:error",h);break;case 11916:h.content="尊敬的用户您好,让我们换个话题再聊聊吧。",h.index=-1,h.isSensitive=!0,h.isLoading=!1,h.sessionId=this._id||"",this.event.emit("message:error",h);break;case 200:h.index=-1,h.isLoading=!1;break;default:h.content=h.message||"未知错误",h.isLoading=!1,h.index=-1,this.event.emit("message:error",h)}this.getRelatedQuesion(h),h.isLoading=!1;let I=this.messages[this.messages.length-1];if(I&&I.role===y.ChatMessageRole.Robot){const v=g(g({},I),h);this.messages[this.messages.length-1]=v,this.event.emit("message:updated",v)}else this.pushMessage(h);this.frozen=!1});return this.addEventListener("answer:finish",f),this.sendQuestion(l,w(g({},t),{stream:a,referenceFirst:r})),c})}currentUserQuestion(){for(let e=this.messages.length-1;e>=0;e-=1){const t=this.messages[e];if(t.role===y.ChatMessageRole.User)return t.content||""}return""}getRelatedQuesion(e){return p(this,null,function*(){var d,i;if(!e.content||e.isSensitive||e.code!==200)return e;const t=(d=this.application)==null?void 0:d.arrange[0],s=fe(t==null?void 0:t.recommendQuestionOpen,t==null?void 0:t.relatedQuestionApp,e.content,this.currentUserQuestion());if(s===null)return e;this.event.emit("message:relatedQuesion:loading",e);const a=yield this.cvforceApi.postGeneques({content:s}).catch(c=>null);if(!a){const c=[],l=w(g({},e),{relatedQuesion:c,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:c}),this.event.emit("message:updated",l),l}const r=(i=a.content)==null?void 0:i.split("*").map(he).map(le).filter(c=>!!c);e.relatedQuesion=r,e.index=-3,e.isLoading=!1;const n=w(g({},e),{relatedQuesion:r,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:r}),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,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!==y.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 r=this.messages[this.messages.length-1],n={content:r.content,fileIds:r.fileIds,requestId:r.messageId,stream:s,oldMessageId:a},d=i=>p(this,null,function*(){if(i.role===y.ChatMessageRole.Robot&&i.index===-1){switch(this._id&&i.content&&i.index&&i.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:i.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:i.content})),yield this.fillMessageReference(i),i.code){case 11915:i.content="请您换个问题问我吧~",i.index=-1,i.isSensitive=!0,i.isLoading=!1,i.sessionId=this._id||"",this.event.emit("message:error",i);break;case 11916:i.content="尊敬的用户您好,让我们换个话题再聊聊吧。",i.index=-1,i.isSensitive=!0,i.isLoading=!1,i.sessionId=this._id||"",this.event.emit("message:error",i);break;case 200:i.index=-1,i.isLoading=!1;break;default:i.content=i.message||"未知错误",i.isLoading=!1,i.index=-1,this.event.emit("message:error",i)}this.getRelatedQuesion(i),this.removeEventListener("message:content",d),this.frozen=!1}});this.addEventListener("message:content",d),this.sendQuestion(n,w(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:J.v4(),isLoading:!1,index:-2,messageTime:K(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:y.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 r=a[a.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:n,pluginCode:d,funcCode:i,funcName:c}=r.data;a.push({data:{pluginName:n,pluginCode:d,funcCode:i,funcName:c,step:r.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}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 M=new b("[AgentSession] ");class pe extends q{constructor(e,t="",s,a,r,n){super(e,t,s,a,r,n)}prepareConnection(){return new Promise(e=>p(this,null,function*(){this.socket&&e(!0);const t={version:"1.0",stream:JSON.stringify(exports.configuration.stream===void 0?!0:exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?E.Debug:E.Normal},s=new URL(exports.configuration.apiRoot),a=yield oe.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});a.on("connect",()=>{M.log("socket:connect"),this.event.emit("socket:connect"),a.emit("init")}),a.on("disconnect",()=>{M.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),a.on("ready",r=>{if(r.code===200){M.log("ready");const n=exports.configuration.debug?E.Debug:E.Normal;n===E.Debug&&r.userMode,this._ready=!0,this.event.emit("ready"),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const n=new Error(x.SocketConnectionFailed);M.error("error",n),this.event.emit("error",n),e(!1)}}),a.on("action",(r,n)=>p(this,null,function*(){var I;if(this._stopAnswer||!this.id)return;const{type:d,data:{runnerIsClient:i,pluginCode:c,funcCode:l,parameters:f,requestBody:u}}=r,h=this.messages[this.messages.length-1];if(!h.messageId)h.actions||(h.actions=[]),h.actions[r.data.step-1]||(h.actions[r.data.step-1]=[]),h.actions[r.data.step-1].push(r),this.event.emit("message:action",{messageId:h.messageId,action:r}),this.event.emit("message:updated",h);else{const v={messageId:"",content:"",role:y.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[r]],comment:{isAgree:0}};this.pushMessage(v),this.event.emit("message:action",{messageId:v.messageId,action:r})}if(this.inactivating){const v=new Error(x.Inactive);M.warn("error",v),this.event.emit("error",v)}else if(d==="FUNCTION_CALL"&&i){M.log(`calling function ${l} of plugin ${c} with argument:
|
|
3
|
+
${JSON.stringify(f)}`);const v=(I=exports.configuration.plugins)==null?void 0:I[c];if(!v){n({code:404,message:"没有找到插件。"});return}const _=v[l];if(typeof _!="function"){n({code:404,message:"没有找到插件方法。"});return}let A=f==null?void 0:f.query;try{A=JSON.parse(f==null?void 0:f.query)}catch(C){}_(A,(...C)=>{this._stopAnswer||n(...C)})}})),a.on("answer",r=>{if(!this._stopAnswer)if(r.data.code!==200&&(r.data.index=-1,this.event.emit("error",r.data)),r.data.index===-1){let n=this.messages[this.messages.length-1];if(n&&!n.messageId)n=g(g({},n),r.data),this.event.emit("message:content",n),this.event.emit("message:updated",n),this.event.emit("answer:finish",n);else{const d=g({messageId:"",content:"",role:y.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0}},r.data);this.event.emit("message:content",d),this.pushMessage(d),this.event.emit("answer:finish",d)}}else{let n=this.messages[this.messages.length-1];n&&!n.messageId?(n=g(g({},n),r.data),this.messages[this.messages.length-1]=n,this.event.emit("message:content",n),this.event.emit("message:updated",n)):(this.pushMessage(r.data),this.event.emit("message:content",r.data))}}),a.on("reference",r=>p(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const f=new Error(x.IdUndefined);M.error(f),this.event.emit("error",f),this.frozen=!1;return}const{type:n,data:d,requestId:i}=r,c=this.messages.findIndex(f=>f.messageId===i&&f.role===y.ChatMessageRole.User);if(c<0)return;const l=c+1;if(l>=this.messages.length){const f={messageId:"",content:"",role:y.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0}};this.pushMessage(f)}n==="KG"?(this.messages[l]=w(g({},this.messages[l]),{reference:d.knowledgeReference}),yield this.fillMessageReference(this.messages[l]),this.event.emit("message:reference",d.knowledgeReference),this.event.emit("message:updated",this.messages[l])):n==="WEB_SEARCH"&&(this.messages[l]=w(g({},this.messages[l]),{searchReference:d.knowledgeReference}),this.event.emit("message:searchreference",d.searchReference),this.event.emit("message:updated",this.messages[l]))})),this.socket=a,a.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(a=>{s.data[a].code!==200&&console.error(a,"MCP Server 注册失败。",s.data[a])}),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,a=>{a.code===200?(Object.keys(a.data).forEach(r=>{a.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",a.data[r])}),t(!0)):(console.error("MCP Server 注册失败。",a),s(a))})}):(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 a,r,n;let s=w(g({},e),{promptVariables:this.promptVariables.reduce((d,i)=>w(g({},d),{[i.key]:i.value}),{}),knowledges:(a=this.knowledges)==null?void 0:a.map(d=>d.id)});if(!this.active){if(yield this.activate(),!this.socket){const d=new Error(x.SocketConnectionFailed);return M.warn("error",d),this.event.emit("error",d),!1}(r=this.socket)==null||r.emit("question",s);return}(n=this.socket)==null||n.emit("question",s)})}stopAnswer(){var e;(e=this.socket)==null||e.emit("stop_answer")}}function ue(o,e){return p(this,null,function*(){const t=o.getReader();let s;for(;!(s=yield t.read()).done;)e(s.value)})}function ge(o){let e,t,s,a=!1,r;return function(d){e===void 0?(e=d,t=0,s=-1,r=!1):e=ve(e,d);const i=e.length;let c=0;for(;t<i;){a&&(e[t]===10&&(c=++t),a=!1);let l=-1;for(;t<i&&l===-1;++t)switch(e[t]){case 58:s===-1&&(s=t-c);break;case 13:a=!1,t+4<i&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(r=!0);case 10:l=t;break}if(l===-1)break;o(e.subarray(c,l),s,r),c=t,s=-1,r=!1}c===i?e=void 0:c!==0&&(e=e.subarray(c),t-=c)}}function me(o,e,t){let s=U();const a=new TextDecoder;return function(n,d,i){if(n.length===0)t==null||t(s),s=U();else if(d>0){const c=a.decode(n.subarray(0,d)),l=d+(n[d+1]===32?2:1);let f=a.decode(n.subarray(l));switch(i&&(f+=`
|
|
4
|
+
`),c){case"data":s.data=s.data?s.data+`
|
|
5
|
+
`+f:f;break;case"event":s.event=f;break;case"id":o(s.id=f);break;case"retry":const u=parseInt(f,10);isNaN(u)||e(s.retry=u);break}}}}function ve(o,e){const t=new Uint8Array(o.length+e.length);return t.set(o),t.set(e,o.length),t}function U(){return{data:"",event:"",id:"",retry:void 0}}const N="text/event-stream",ye=1e3,H="last-event-id";function Y(o,l){var f=l,{signal:e,headers:t,onopen:s,onmessage:a,onclose:r,onerror:n,openWhenHidden:d,fetch:i}=f,c=F(f,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((u,h)=>{const I=g({},t);I.accept||(I.accept=N);let v;function _(){v.abort(),document.hidden||$()}d||document.addEventListener("visibilitychange",_);let A=ye,C=0;function O(){document.removeEventListener("visibilitychange",_),window.clearTimeout(C),v.abort()}e==null||e.addEventListener("abort",()=>{O(),u()});const ee=i!=null?i:window.fetch,te=s!=null?s:we;function $(){return p(this,null,function*(){var D;v=new AbortController;try{const T=yield ee(o,w(g({},c),{headers:I,signal:v.signal}));yield te(T),yield ue(T.body,ge(me(k=>{k?I[H]=k:delete I[H]},k=>{A=k},a))),r==null||r(),O(),u()}catch(T){if(!v.signal.aborted)try{const k=(D=n==null?void 0:n(T))!=null?D:A;window.clearTimeout(C),C=window.setTimeout($,k)}catch(k){O(),h(k)}}})}$()})}function we(o){const e=o.headers.get("content-type");if(!(e!=null&&e.startsWith(N)))throw new Error(`Expected content-type to be ${N}, Actual: ${e}`)}const W=new b("[DialogSession] ");class Ie extends q{constructor(t,s="",a,r,n,d){super(t,s,a,r,n,d);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,r,n,d){return p(this,null,function*(){const i={code:0,content:"",role:y.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},c=w(g({},a),{stream:exports.configuration.stream});Y(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(c),openWhenHidden:!0,signal:r,onopen(l){return l.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(l){if(!l.data.includes('{"code": ')){let u={};try{u=JSON.parse(l.data)}catch(I){}(u==null?void 0:u.mtype)==="search"?i.searchReference.push(u):i.content=i.content+l.data;const h={content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:s,messageTime:K(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(n==null?void 0:n.onmessage)&&n.onmessage(h)}const f=JSON.parse(l.data);if(i.reference=f.data.reference,i.searchReference=f.data.searchReference,i.messageTime=f.data.messageTime,i.messageId=f.data.messageId,i.llmModel=f.data.llmModel,i.content=f.data.content,i.code=f.code,f.code===200){const u={code:i.code,content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:s,messageTime:i.messageTime,isReplying:!0};n!=null&&n.onmessage&&n.onmessage(u)}else return n!=null&&n.onclose&&n.onclose(i),d&&d({code:i.code,message:i.message})},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const l={code:i.code,content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:s,messageTime:i.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};n!=null&&n.onclose&&n.onclose(l)}})})}postChatV3EventSource(t,s,a,r,n,d){return p(this,null,function*(){const i={code:0,content:"",role:y.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},c=w(g({},a),{stream:exports.configuration.stream});Y(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(c),openWhenHidden:!0,signal:r,onopen(l){return l.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(l){if(!l.data&&!l.event&&!l.id&&!l.retry)return;let f={};try{f=JSON.parse(l.data)}catch(v){console.error("parse eventData to JSON failed. ",l.data)}if(f.code!==200)return i.index=-1,i.code=f.code,i.message=f.message,n!=null&&n.onmessage&&n.onmessage(i),d&&d({code:f.code,message:f.message});const u=f.data.type,h=f.data.payload;i.isReplying=!0;const I=()=>{if(!i.searchingStatus){i.searchingStatus="start";return}if(i.searchingStatus==="start"){i.searchingStatus="end";return}};if(u==="beforeSearch"&&I(),u==="searchOver"&&I(),u==="search"&&i.searchReference.push(h),u==="thinking"){i.thinkingStatus="start";const _=h.choices[0];i.reasoningContent=i.reasoningContent+_.delta.reasoningContent}if(u==="thinkingOver"){i.thinkingStatus="end";const v=h.thinkingSecs;i.thinkingSecs=v}if(u==="text"){const _=h.choices[0];i.content=i.content+_.delta.content}if(u==="reference"&&(i.reference=h),u==="result"){const v=h.messageId,_=h.llmModel,A=h.messageTime;i.messageId=v,i.llmModel=_,i.messageTime=A,i.sessionId=s}u==="over"?i.index=-1:(i.code=f.code,i.message=f.message),n!=null&&n.onmessage&&n.onmessage(i)},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const l=w(g({},i),{isReplying:!1});n!=null&&n.onclose&&n.onclose(l)}})})}sendQuestion(t,s){return p(this,null,function*(){var c;const{content:a,fileIds:r,oldMessageId:n}=t,{stream:d,referenceFirst:i}=s;if(this.active||(yield this.activate()),this._id){let l={content:a,fileIds:r,referenceFirst:i,oldMessageId:n,promptVariables:this.promptVariables.reduce((f,u)=>w(g({},f),{[u.key]:u.value}),{}),knowledges:(c=this.knowledges)==null?void 0:c.map(f=>f.id)};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,l,this.ctrl.signal,{onopen:()=>{W.log("open",this.ctrl)},onmessage:f=>{if(this._stopAnswer)return;let u=this.messages[this.messages.length-1];u&&u.role===y.ChatMessageRole.Robot?(u=g(g({},u),f),this.messages[this.messages.length-1]=u,this.event.emit("message:content",u),this.event.emit("message:updated",u)):(this.pushMessage(f),this.event.emit("message:content",f))},onclose:f=>p(this,null,function*(){this._stopAnswer||(W.log(f,"onclose"),this.event.emit("answer:finish",f))}),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 _e=new b("[BotClient] ");class Se{constructor(e,t,s=!0){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,z(t),this._applicationId=V(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(a=>{z(w(g({},t),{stream:t.stream===void 0?(a==null?void 0:a.type)===y.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;this._application=yield this.cvforceApi.getApplicationId(this._applicationId).then(r=>w(g({},r),{arrange:[w(g({},r.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&r.arrange[0].recommendQuestionOpen})]}));const e=(a=(s=(t=this._application)==null?void 0:t.arrange)==null?void 0:s[0])==null?void 0:a.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)=>_e.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=V(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,r){return p(this,null,function*(){const n=this;return new Promise((d,i)=>{const c=l=>p(this,null,function*(){if(l===y.ApplicationTypes.Agent)d(new pe(e,t,s,a,r,n));else if(l===y.ApplicationTypes.Dialog)d(new Ie(e,t,s,a,r,n));else throw Error(`不支持的应用类型:${l}`)});if(this.ready){if(!this._application)throw Error("client is not ready");c(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");c(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(r=>{const n=[];return r.forEach(d=>p(this,null,function*(){const i=this._sessions.find(c=>d.id===c.id);if(i)i.data=d,this._application?i.application=this._application:i.loadApplicationInfo(),n.push(i);else{const c=yield this.createSession(this.token,d.id,d,this.lazyload,this._application||void 0);n.push(c)}})),this.sessions=n,n});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(r=>r.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 be{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=be;exports.BotClient=Se;exports.Session=q;exports.configure=z;
|
package/dist/src/Session.d.ts
CHANGED
|
@@ -183,6 +183,7 @@ export default abstract class Session {
|
|
|
183
183
|
searchReference: never[];
|
|
184
184
|
messageTime: string;
|
|
185
185
|
}>;
|
|
186
|
+
protected currentUserQuestion(): string;
|
|
186
187
|
protected getRelatedQuesion(message: IChatMessage): Promise<IChatMessage>;
|
|
187
188
|
protected fillMessageReference(message: IChatMessage): Promise<IChatMessage>;
|
|
188
189
|
answerAgain(configs?: QuestionConfig): Promise<void>;
|
package/dist/src/utils.d.ts
CHANGED
|
@@ -2,3 +2,8 @@ export declare const parseJWT: (token: string) => any;
|
|
|
2
2
|
export declare const isExpired: (token: string) => boolean;
|
|
3
3
|
export declare const removeNewlines: (str: string) => string;
|
|
4
4
|
export declare const removeLeadingAndTrailingBackslashes: (str: string) => string;
|
|
5
|
+
export interface RelatedQuestionAppConfig {
|
|
6
|
+
includeUserQuestion?: boolean;
|
|
7
|
+
includeAiAnswer?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export declare const resolveRelatedQuestionContent: (recommendQuestionOpen: boolean | undefined, relatedQuestionApp: RelatedQuestionAppConfig | undefined, answer: string, userQuestion: string) => string | null;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glodon-aiot/agent-cli-sdk",
|
|
3
|
-
"version": "3.25.0",
|
|
3
|
+
"version": "3.25.1-alpha.0",
|
|
4
4
|
"author": "glodoncv",
|
|
5
5
|
"description": "aiot agent 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.25.0",
|
|
82
|
+
"@glodon-aiot/apis": "^3.25.1-alpha.0",
|
|
83
83
|
"axios": "0.24.0",
|
|
84
84
|
"buffer": "^6.0.3",
|
|
85
85
|
"dayjs": "^1.11.13",
|