@glodon-aiot/agent-cli-sdk 3.2.2-beta.4 → 3.2.10-beta.1
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 +80 -80
- package/dist/es/Session.mjs +20 -18
- package/dist/lib/index.js +2 -2
- package/dist/src/Session.d.ts +0 -1
- package/package.json +2 -2
package/dist/es/BotClient.mjs
CHANGED
|
@@ -2,56 +2,56 @@ var S = Object.defineProperty, w = Object.defineProperties;
|
|
|
2
2
|
var k = Object.getOwnPropertyDescriptors;
|
|
3
3
|
var v = Object.getOwnPropertySymbols;
|
|
4
4
|
var A = Object.prototype.hasOwnProperty, x = Object.prototype.propertyIsEnumerable;
|
|
5
|
-
var f = (o,
|
|
6
|
-
for (var
|
|
7
|
-
A.call(
|
|
5
|
+
var f = (o, e, i) => e in o ? S(o, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : o[e] = i, _ = (o, e) => {
|
|
6
|
+
for (var i in e || (e = {}))
|
|
7
|
+
A.call(e, i) && f(o, i, e[i]);
|
|
8
8
|
if (v)
|
|
9
|
-
for (var
|
|
10
|
-
x.call(
|
|
9
|
+
for (var i of v(e))
|
|
10
|
+
x.call(e, i) && f(o, i, e[i]);
|
|
11
11
|
return o;
|
|
12
|
-
}, u = (o,
|
|
13
|
-
var
|
|
14
|
-
var c = (o,
|
|
12
|
+
}, u = (o, e) => w(o, k(e));
|
|
13
|
+
var l = (o, e, i) => (f(o, typeof e != "symbol" ? e + "" : e, i), i);
|
|
14
|
+
var c = (o, e, i) => new Promise((t, s) => {
|
|
15
15
|
var n = (a) => {
|
|
16
16
|
try {
|
|
17
|
-
r(
|
|
17
|
+
r(i.next(a));
|
|
18
18
|
} catch (h) {
|
|
19
19
|
s(h);
|
|
20
20
|
}
|
|
21
|
-
},
|
|
21
|
+
}, p = (a) => {
|
|
22
22
|
try {
|
|
23
|
-
r(
|
|
23
|
+
r(i.throw(a));
|
|
24
24
|
} catch (h) {
|
|
25
25
|
s(h);
|
|
26
26
|
}
|
|
27
|
-
}, r = (a) => a.done ? t(a.value) : Promise.resolve(a.value).then(n,
|
|
28
|
-
r((
|
|
27
|
+
}, r = (a) => a.done ? t(a.value) : Promise.resolve(a.value).then(n, p);
|
|
28
|
+
r((i = i.apply(o, e)).next());
|
|
29
29
|
});
|
|
30
30
|
import { parseJWT as g } from "./utils.mjs";
|
|
31
|
-
import
|
|
32
|
-
import { getCVForceService as
|
|
33
|
-
import { configure as
|
|
31
|
+
import R from "./Logger.mjs";
|
|
32
|
+
import { getCVForceService as E } from "./api/index.mjs";
|
|
33
|
+
import { configure as I, configuration as y } from "./Config.mjs";
|
|
34
34
|
import { ApplicationTypes as m } 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
|
-
const T = new
|
|
38
|
+
const T = new R("[BotClient] ");
|
|
39
39
|
class z {
|
|
40
|
-
constructor(
|
|
41
|
-
|
|
42
|
-
|
|
40
|
+
constructor(e, i, t = !0) {
|
|
41
|
+
l(this, "event", new C());
|
|
42
|
+
l(this, "cvforceApi");
|
|
43
43
|
//从token解析出来的用户信息
|
|
44
|
-
|
|
45
|
-
|
|
44
|
+
l(this, "_applicationId");
|
|
45
|
+
l(this, "_application", null);
|
|
46
46
|
//session列表,被加载过的session将会被缓存到这个列表中
|
|
47
|
-
|
|
47
|
+
l(this, "_sessions", []);
|
|
48
48
|
//活跃的session,只支持一个活跃的session
|
|
49
|
-
|
|
50
|
-
|
|
49
|
+
l(this, "_activeSession");
|
|
50
|
+
l(this, "_ready", !1);
|
|
51
51
|
//问题长度
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
if (this._token =
|
|
52
|
+
l(this, "_questionContextMaxLength", 4e3);
|
|
53
|
+
l(this, "_promptVariables", []);
|
|
54
|
+
if (this._token = e, this.lazyload = t, I(i), this._applicationId = g(e).rid || y.applicationId, !this._applicationId)
|
|
55
55
|
throw "token is not vaild";
|
|
56
56
|
this.cvforceApi = this.getService(), this.loadApplication().then(() => {
|
|
57
57
|
this.event.emit("ready");
|
|
@@ -64,8 +64,8 @@ class z {
|
|
|
64
64
|
get ready() {
|
|
65
65
|
return this._ready;
|
|
66
66
|
}
|
|
67
|
-
set ready(
|
|
68
|
-
this._ready =
|
|
67
|
+
set ready(e) {
|
|
68
|
+
this._ready = e;
|
|
69
69
|
}
|
|
70
70
|
get questionContextMaxLength() {
|
|
71
71
|
return this.checkReady(), this._questionContextMaxLength;
|
|
@@ -74,37 +74,37 @@ class z {
|
|
|
74
74
|
return this.checkReady(), this._promptVariables;
|
|
75
75
|
}
|
|
76
76
|
get knowledges() {
|
|
77
|
-
var
|
|
78
|
-
return this.checkReady(), (
|
|
77
|
+
var e;
|
|
78
|
+
return this.checkReady(), (e = this._application) == null ? void 0 : e.arrange[0].knowledges;
|
|
79
79
|
}
|
|
80
80
|
get sessions() {
|
|
81
81
|
return this.checkReady(), this._sessions;
|
|
82
82
|
}
|
|
83
|
-
set sessions(
|
|
84
|
-
this.checkReady(), this._sessions =
|
|
83
|
+
set sessions(e) {
|
|
84
|
+
this.checkReady(), this._sessions = e, this.event.emit("sessions:updated", e);
|
|
85
85
|
}
|
|
86
86
|
loadApplication() {
|
|
87
87
|
return c(this, null, function* () {
|
|
88
|
-
var
|
|
88
|
+
var i, t, s;
|
|
89
89
|
this._application = yield this.cvforceApi.getApplicationId(this._applicationId).then((n) => (typeof n.arrange[0].recommendQuestionOpen != "boolean" && (n.arrange[0].recommendQuestionOpen = !0), u(_({}, n), {
|
|
90
90
|
arrange: [u(_({}, n.arrange[0]), {
|
|
91
91
|
recommendQuestionOpen: y.loadRelatedQuesions && n.arrange[0].recommendQuestionOpen
|
|
92
92
|
})]
|
|
93
93
|
})));
|
|
94
|
-
const
|
|
95
|
-
return
|
|
94
|
+
const e = (s = (t = (i = this._application) == null ? void 0 : i.arrange) == null ? void 0 : t[0]) == null ? void 0 : s.llmModel;
|
|
95
|
+
return e && (this._questionContextMaxLength = yield this.cvforceApi.getBaseModel(e).then((n) => n.maxModelLength)), this._promptVariables = yield this.cvforceApi.getPrompts(this._applicationId), this._ready = !0, this.event.emit("application:loaded"), this._application;
|
|
96
96
|
});
|
|
97
97
|
}
|
|
98
98
|
getService() {
|
|
99
|
-
return this.cvforceApi ? this.cvforceApi :
|
|
99
|
+
return this.cvforceApi ? this.cvforceApi : E(y.apiRoot, this.token, (e, i) => T.error(i));
|
|
100
100
|
}
|
|
101
101
|
get token() {
|
|
102
102
|
return this._token;
|
|
103
103
|
}
|
|
104
|
-
set token(
|
|
105
|
-
this.checkReady(), this._token =
|
|
106
|
-
const
|
|
107
|
-
this._applicationId !==
|
|
104
|
+
set token(e) {
|
|
105
|
+
this.checkReady(), this._token = e, this.ready = !1;
|
|
106
|
+
const i = g(e).rid;
|
|
107
|
+
this._applicationId !== i && (this._applicationId = i, this._application = null, this.loadApplication().then(() => {
|
|
108
108
|
this.event.emit("ready");
|
|
109
109
|
}), this.clean());
|
|
110
110
|
}
|
|
@@ -115,23 +115,23 @@ class z {
|
|
|
115
115
|
return this.checkReady(), this._application;
|
|
116
116
|
}
|
|
117
117
|
get activeSession() {
|
|
118
|
-
var
|
|
119
|
-
return this.checkReady(), ((
|
|
118
|
+
var e;
|
|
119
|
+
return this.checkReady(), ((e = this._activeSession) == null ? void 0 : e.id) || "";
|
|
120
120
|
}
|
|
121
|
-
set activeSession(
|
|
122
|
-
this.checkReady(), this.loadSession(
|
|
123
|
-
this._activeSession && this._activeSession.id !==
|
|
121
|
+
set activeSession(e) {
|
|
122
|
+
this.checkReady(), this.loadSession(e).then((i) => {
|
|
123
|
+
this._activeSession && this._activeSession.id !== e && this._activeSession.inactivate(), this._activeSession = i;
|
|
124
124
|
});
|
|
125
125
|
}
|
|
126
|
-
createSession(
|
|
126
|
+
createSession(e, i, t, s, n) {
|
|
127
127
|
return c(this, null, function* () {
|
|
128
|
-
const
|
|
128
|
+
const p = this;
|
|
129
129
|
return new Promise((r, a) => {
|
|
130
130
|
const h = (d) => c(this, null, function* () {
|
|
131
131
|
if (d === m.Agent)
|
|
132
|
-
r(new L(
|
|
132
|
+
r(new L(e, i, t, s, n, p));
|
|
133
133
|
else if (d === m.Dialog)
|
|
134
|
-
r(new M(
|
|
134
|
+
r(new M(e, i, t, s, n, p));
|
|
135
135
|
else
|
|
136
136
|
throw Error(`不支持的应用类型:${d}`);
|
|
137
137
|
});
|
|
@@ -148,39 +148,39 @@ class z {
|
|
|
148
148
|
});
|
|
149
149
|
});
|
|
150
150
|
}
|
|
151
|
-
getSessions(
|
|
151
|
+
getSessions(e) {
|
|
152
152
|
return c(this, null, function* () {
|
|
153
|
-
return new Promise((
|
|
154
|
-
const s = () => this.cvforceApi.listSessions(this._applicationId,
|
|
155
|
-
const
|
|
153
|
+
return new Promise((i, t) => {
|
|
154
|
+
const s = () => this.cvforceApi.listSessions(this._applicationId, e).then((n) => {
|
|
155
|
+
const p = [];
|
|
156
156
|
return n.forEach((r) => c(this, null, function* () {
|
|
157
157
|
const a = this._sessions.find((h) => r.id === h.id);
|
|
158
158
|
if (a)
|
|
159
|
-
a.data = r,
|
|
159
|
+
a.data = r, p.push(a);
|
|
160
160
|
else {
|
|
161
161
|
const h = yield this.createSession(this.token, r.id, r, this.lazyload, this._application || void 0);
|
|
162
|
-
|
|
162
|
+
p.push(h);
|
|
163
163
|
}
|
|
164
|
-
})), this.sessions =
|
|
164
|
+
})), this.sessions = p, p;
|
|
165
165
|
});
|
|
166
166
|
if (this.ready) {
|
|
167
167
|
if (!this._application)
|
|
168
168
|
throw Error("_application is null");
|
|
169
|
-
|
|
169
|
+
i(s());
|
|
170
170
|
} else
|
|
171
171
|
this.event.on("ready", () => {
|
|
172
172
|
if (!this._application)
|
|
173
173
|
throw Error("_application is null");
|
|
174
|
-
|
|
174
|
+
i(s());
|
|
175
175
|
}, !0);
|
|
176
176
|
});
|
|
177
177
|
});
|
|
178
178
|
}
|
|
179
|
-
loadSession(
|
|
179
|
+
loadSession(e = "", i) {
|
|
180
180
|
return c(this, null, function* () {
|
|
181
181
|
this.checkReady();
|
|
182
|
-
let t = this.sessions.find((s) => s.id ===
|
|
183
|
-
if (t || (t = yield this.createSession(this.token,
|
|
182
|
+
let t = this.sessions.find((s) => s.id === e);
|
|
183
|
+
if (t || (t = yield this.createSession(this.token, e, i), this._sessions.push(t)), this._activeSession) {
|
|
184
184
|
if (this._activeSession === t)
|
|
185
185
|
return t;
|
|
186
186
|
this._activeSession.inactivate();
|
|
@@ -195,54 +195,54 @@ class z {
|
|
|
195
195
|
return yield this.getSessions(), this.event.emit("ready"), this;
|
|
196
196
|
}));
|
|
197
197
|
}
|
|
198
|
-
reloadSession(
|
|
198
|
+
reloadSession(e) {
|
|
199
199
|
return c(this, null, function* () {
|
|
200
200
|
yield this.reload();
|
|
201
|
-
let
|
|
202
|
-
if (!
|
|
201
|
+
let i = this._sessions.find((t) => t.id === e) || this._activeSession;
|
|
202
|
+
if (!i) {
|
|
203
203
|
console.warn("reloadSession session failed.");
|
|
204
204
|
return;
|
|
205
205
|
}
|
|
206
|
-
return yield
|
|
206
|
+
return yield i.reload(), i;
|
|
207
207
|
});
|
|
208
208
|
}
|
|
209
|
-
setTop(
|
|
209
|
+
setTop(e, i, t = "top_time desc, sort_status desc, updated_at desc") {
|
|
210
210
|
return c(this, null, function* () {
|
|
211
|
-
let s =
|
|
211
|
+
let s = e ? this._sessions.find((n) => n.id === e) : this._activeSession;
|
|
212
212
|
if (!s) {
|
|
213
213
|
console.warn("setTop session failed.");
|
|
214
214
|
return;
|
|
215
215
|
}
|
|
216
|
-
return yield s.setTop(
|
|
216
|
+
return yield s.setTop(i), this.getSessions({
|
|
217
217
|
order: t
|
|
218
218
|
});
|
|
219
219
|
});
|
|
220
220
|
}
|
|
221
|
-
addEventListener(
|
|
222
|
-
if (typeof
|
|
221
|
+
addEventListener(e, i, t = !1) {
|
|
222
|
+
if (typeof i != "function")
|
|
223
223
|
throw Error("event listener is not a function");
|
|
224
224
|
if (t) {
|
|
225
|
-
this.event.once(
|
|
225
|
+
this.event.once(e, i);
|
|
226
226
|
return;
|
|
227
227
|
}
|
|
228
|
-
this.event.on(
|
|
228
|
+
this.event.on(e, i);
|
|
229
229
|
}
|
|
230
|
-
removeEventListener(
|
|
231
|
-
this.event.off(
|
|
230
|
+
removeEventListener(e, i) {
|
|
231
|
+
this.event.off(e, i);
|
|
232
232
|
}
|
|
233
|
-
removeSession(
|
|
233
|
+
removeSession(e, i) {
|
|
234
234
|
return c(this, null, function* () {
|
|
235
235
|
this.checkReady();
|
|
236
236
|
let t = -1;
|
|
237
|
-
if (typeof
|
|
237
|
+
if (typeof e == "string" ? t = this._sessions.findIndex((s) => s.id === e) : t = this._sessions.findIndex((s) => s.id === e.id), t > -1) {
|
|
238
238
|
const s = this._sessions[t];
|
|
239
|
-
|
|
239
|
+
i && (yield s.delete()), this._sessions.splice(t, 1);
|
|
240
240
|
} else
|
|
241
241
|
console.warn("session delete failed, session is not exist.");
|
|
242
242
|
});
|
|
243
243
|
}
|
|
244
244
|
clean() {
|
|
245
|
-
this._sessions.forEach((
|
|
245
|
+
this._sessions.forEach((e) => e.destroy()), this.sessions = [];
|
|
246
246
|
}
|
|
247
247
|
}
|
|
248
248
|
export {
|
package/dist/es/Session.mjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
1
|
+
var E = Object.defineProperty, V = Object.defineProperties;
|
|
2
|
+
var x = Object.getOwnPropertyDescriptors;
|
|
3
3
|
var b = Object.getOwnPropertySymbols;
|
|
4
|
-
var
|
|
5
|
-
var L = (h, e, t) => e in h ?
|
|
4
|
+
var Q = Object.prototype.hasOwnProperty, R = Object.prototype.propertyIsEnumerable;
|
|
5
|
+
var L = (h, e, t) => e in h ? E(h, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : h[e] = t, f = (h, e) => {
|
|
6
6
|
for (var t in e || (e = {}))
|
|
7
|
-
|
|
7
|
+
Q.call(e, t) && L(h, t, e[t]);
|
|
8
8
|
if (b)
|
|
9
9
|
for (var t of b(e))
|
|
10
|
-
|
|
10
|
+
R.call(e, t) && L(h, t, e[t]);
|
|
11
11
|
return h;
|
|
12
|
-
}, w = (h, e) =>
|
|
12
|
+
}, w = (h, e) => V(h, x(e));
|
|
13
13
|
var p = (h, e, t) => (L(h, typeof e != "symbol" ? e + "" : e, t), t);
|
|
14
14
|
var r = (h, e, t) => new Promise((i, n) => {
|
|
15
15
|
var o = (s) => {
|
|
@@ -28,10 +28,10 @@ var r = (h, e, t) => new Promise((i, n) => {
|
|
|
28
28
|
d((t = t.apply(h, e)).next());
|
|
29
29
|
});
|
|
30
30
|
import { v4 as M } from "uuid";
|
|
31
|
-
import { parseJWT as
|
|
32
|
-
import {
|
|
31
|
+
import { parseJWT as T, removeNewlines as z, removeLeadingAndTrailingBackslashes as O } from "./utils.mjs";
|
|
32
|
+
import { ApplicationTypes as S, PromptStatus as C, ChatMessageRole as _ } from "@glodon-aiot/apis";
|
|
33
33
|
import P from "./Logger.mjs";
|
|
34
|
-
import { configuration as
|
|
34
|
+
import { configuration as k } from "./Config.mjs";
|
|
35
35
|
import q from "./EventBus.mjs";
|
|
36
36
|
import { getCVForceService as F } from "./api/index.mjs";
|
|
37
37
|
import N from "dayjs";
|
|
@@ -71,7 +71,7 @@ class $ {
|
|
|
71
71
|
p(this, "_stopAnswer", !1);
|
|
72
72
|
p(this, "_dataLoading", !1);
|
|
73
73
|
p(this, "_dataLoaded", !1);
|
|
74
|
-
this.token = e, this.lazyload = n, this.client = l || null, this._applicationId =
|
|
74
|
+
this.token = e, this.lazyload = n, this.client = l || null, this._applicationId = T(e).rid || k.applicationId, this.cvforceApi = this.getService(), o && (this._application = o), this.event.emit("init", {
|
|
75
75
|
applicationId: this._applicationId,
|
|
76
76
|
sessionId: t
|
|
77
77
|
}), this.loadApplicationInfo().then(() => {
|
|
@@ -137,9 +137,6 @@ class $ {
|
|
|
137
137
|
get application() {
|
|
138
138
|
return this._application;
|
|
139
139
|
}
|
|
140
|
-
set application(e) {
|
|
141
|
-
this._application = e;
|
|
142
|
-
}
|
|
143
140
|
loadApplicationInfo() {
|
|
144
141
|
if (this._application)
|
|
145
142
|
return Promise.resolve(this._application);
|
|
@@ -163,6 +160,11 @@ class $ {
|
|
|
163
160
|
}
|
|
164
161
|
setKnowledges(e) {
|
|
165
162
|
return r(this, null, function* () {
|
|
163
|
+
var t;
|
|
164
|
+
if (((t = this._application) == null ? void 0 : t.type) === S.Agent) {
|
|
165
|
+
console.warn("Agent Application Sessions are disabled to setKnowledges.");
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
166
168
|
if (!this.data)
|
|
167
169
|
throw Error("session data is not loaded");
|
|
168
170
|
return yield this.cvforceApi.patchSessionsId(this._applicationId, this.data.id, {
|
|
@@ -177,7 +179,7 @@ class $ {
|
|
|
177
179
|
throw Error("session id is not defined");
|
|
178
180
|
if (!this.data)
|
|
179
181
|
throw Error("session data is not loaded");
|
|
180
|
-
const e = this.promptVariables.filter((t) => t.status ===
|
|
182
|
+
const e = this.promptVariables.filter((t) => t.status === C.Quoted).filter((t) => !t.value);
|
|
181
183
|
if (e.length)
|
|
182
184
|
throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map((t) => t.key).join(", ")}`);
|
|
183
185
|
}
|
|
@@ -220,7 +222,7 @@ class $ {
|
|
|
220
222
|
setNetOpen(e) {
|
|
221
223
|
return r(this, null, function* () {
|
|
222
224
|
var t, i, n;
|
|
223
|
-
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) ===
|
|
225
|
+
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) === S.Agent) {
|
|
224
226
|
console.warn("Agent Application Sessions are disabled to setNetOpen.");
|
|
225
227
|
return;
|
|
226
228
|
}
|
|
@@ -239,7 +241,7 @@ class $ {
|
|
|
239
241
|
});
|
|
240
242
|
}
|
|
241
243
|
getService() {
|
|
242
|
-
return F(
|
|
244
|
+
return F(k.apiRoot, this.token, (e, t) => {
|
|
243
245
|
const i = new Error(
|
|
244
246
|
"data request error"
|
|
245
247
|
/* DataRequestFailed */
|
|
@@ -498,7 +500,7 @@ class $ {
|
|
|
498
500
|
relatedQuesion: d
|
|
499
501
|
}), this.event.emit("message:updated", s), s;
|
|
500
502
|
}
|
|
501
|
-
const i = (l = t.content) == null ? void 0 : l.split("*").map(
|
|
503
|
+
const i = (l = t.content) == null ? void 0 : l.split("*").map(z).map(O).filter((d) => !!d);
|
|
502
504
|
e.relatedQuesion = i, e.index = -3, e.isLoading = !1;
|
|
503
505
|
const n = w(f({}, e), {
|
|
504
506
|
relatedQuesion: i,
|
package/dist/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var T=Object.getOwnPropertySymbols;var D=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var P=(r,e,t)=>e in r?se(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,u=(r,e)=>{for(var t in e||(e={}))D.call(e,t)&&P(r,t,e[t]);if(T)for(var t of T(e))B.call(e,t)&&P(r,t,e[t]);return r},w=(r,e)=>ie(r,ne(e));var F=(r,e)=>{var t={};for(var s in r)D.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&T)for(var s of T(r))e.indexOf(s)<0&&B.call(r,s)&&(t[s]=r[s]);return t};var m=(r,e,t)=>(P(r,typeof e!="symbol"?e+"":e,t),t);var p=(r,e,t)=>new Promise((s,a)=>{var o=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(o,n);c((t=t.apply(r,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),oe=require("axios"),I=require("@glodon-aiot/apis"),re=require("socket.io-client"),J=require("uuid"),U=require("dayjs"),R=class R{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!R.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!R.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!R.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!R.debug||console.warn(this.prefix,...e)}};m(R,"debug",!1);let S=R;const ce=new S("[Config] ");var K=(r=>(r.dev="https://aiot-dev.glodon.com/api/cvforcepd",r.test="https://aiot-dev.glodon.com/api/cvforce",r.prod="https://copilot.glodon.com/api/cvforce",r.local="http://localhost:3000/api/cvforcepd",r))(K||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},loadRelatedQuesions:!0};function G(r){S.debug=(r==null?void 0:r.debug)||!1,exports.configuration=w(u(u({},exports.configuration),r),{apiRoot:(r==null?void 0:r.apiRoot)||exports.configuration.apiRoot||(r!=null&&r.env?K[r.env||"prod"]:exports.configuration.apiRoot)}),S.debug&&ce.log("updated",exports.configuration)}const V=r=>JSON.parse(ae.decode(r.split(".")[1])),de=r=>{const e=V(r).exp;return new Date().valueOf()/1e3>=e},he=r=>r==null?void 0:r.replace(/[\r\n]+/gm,""),le=r=>r.replace(/\\|\\/g,"");function X(r,e,t){const s=d=>{var l;return e&&(de(e)&&t(403,"aiotToken is timeout"),d.headers=(l=d.headers)!=null?l:{},d.headers=w(u({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function a(d,l=!0){const h=`${r}${d}`,g=oe.create({baseURL:h});return l&&g.interceptors.request.use(s),g}const o=(d,l)=>{d===401&&t(d,"aiotToken is invalid")},n=(d,l)=>{d!==10001&&d!==10215&&t(d,l)},c=a("/data/v1");return new I.CVForceApi(c,{onHttpStatusError:o,onAppStatusError:n})}var L=(r=>(r[r.Normal=0]="Normal",r[r.Debug=1]="Debug",r))(L||{});const M=new S("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&M.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),M.log(`add event ${e} listener ${s?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const s=this.eventListenerMap[e].findIndex(a=>{if(typeof a=="function"&&t===a)return!0;if(a=a,a.fn===t)return!0});s<0?M.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),M.log(`remove event ${e} listener`))}else M.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){M.log(`event ${e} listeners is empty`);return}const s=[];for(let a=0;a<this.eventListenerMap[e].length;a++){const o=this.eventListenerMap[e][a];typeof o=="function"?o(t):s.push(o)}s.forEach(a=>{a&&(a.fn(t),this.off(e,a.fn))}),M.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const A=new S("[Session] ");var E=(r=>(r.DataRequestFailed="data request error",r.SocketConnectionFailed="socket error",r.IdUndefined="session id is not defined",r.SendingEmptyContent="failed at sending empty content",r.Frozen="session is frozen",r.UserModeError="failed at setting socket user mode",r.Inactive="session is inactive",r))(E||{});class q{constructor(e,t="",s,a,o,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);this.token=e,this.lazyload=a,this.client=n||null,this._applicationId=V(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),o&&(this._application=o),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var 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,knowledgeList:(c=s==null?void 0:s.knowledges)==null?void 0:c.map(d=>d.id),applicationId:this._applicationId}).then(d=>p(this,null,function*(){this._id=d.id,this.data=d,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),yield(()=>{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(h=>{var f,v;const g=((v=(f=s.promptVariables)==null?void 0:f.find(y=>y.key===h.key))==null?void 0:v.value)||"";return w(u({},h),{value:g})}).sort((h,g)=>h.key.localeCompare(g.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),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===I.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>e.key!=="query")}setPromptVariables(e){return p(this,null,function*(){const t=this._promptVariables.map(s=>{var o;const a=((o=e==null?void 0:e.find(n=>n.key===s.key))==null?void 0:o.value)||s.value;return w(u({},s),{value:a})}).sort((s,a)=>s.key.localeCompare(a.key));if(yield Promise.all(t.filter(s=>s.key!=="query").map(s=>{if(!this.data)throw Error("session data is not loaded");if(!(!s.id||!s.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,s.id,{value:s.value}).catch(console.error)})),!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return p(this,null,function*(){var t,s,a;if(A.log("setNetOpen:",e),A.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===I.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,A.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");A.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"),A.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),A.log("history:moreloading",e)),this._loadingMessages=!0;const o=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),n=o.map((i,d)=>{var g,f;let l=[],h;return typeof((g=i.agentHistoryList)==null?void 0:g.agentList)=="string"&&(l=JSON.parse(i.agentHistoryList.agentList).reduce((y,_)=>(y[_.data.step-1]||(y[_.data.step-1]=[]),y[_.data.step-1].push(_),y),[])),d===o.length-1&&(h=(f=this.data)==null?void 0:f.lastRelatedQuestion),w(u({},i),{actions:l,relatedQuesion:h})});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(l=>l.ts===e.endTime),d=this.messages.findLastIndex(l=>l.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),A.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,n}else{const o=new Error("session id is not defined");return A.error(o),this.event.emit("error",o),!1}})}rename(e){return p(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),A.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),A.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),A.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 A.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:!1}){var g;try{this.validateConfigs()}catch(f){console.error(f)}const{stream:a=!1,referenceFirst:o=!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 f=new Error("failed at sending empty content");return A.error(f),this.event.emit("error",f),!1}if(!this._id){const f=new Error("session id is not defined");return A.error(f),this.event.emit("error",f),!1}if(this.frozen){const f=new Error("session is frozen");return A.error(f),this.event.emit("error",f),!1}this.frozen=!0,this._stopAnswer=!1;const d={sessionId:this.id,role:2,content:c,messageId:n,reference:[],searchReference:[],messageTime:""},l={content:c,stream:a,requestId:n,fileIds:i,referenceFirst:o};this.pushMessage(d),this.event.emit("question:content",c);const h=f=>p(this,null,function*(){if(f.role!==I.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",h),this._id&&f.content&&f.index&&f.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:f.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:f.content})),this.fillMessageReference(f),f.code){case 11915:f.content="请您换个问题问我吧~",f.index=-1,f.isSensitive=!0,f.isLoading=!1,f.sessionId=this._id||"",this.event.emit("message:error",f);break;case 200:f.index=-1,f.isLoading=!1;break;default:f.content=f.message||"未知错误",f.isLoading=!1,f.index=-1,this.event.emit("message:error",f)}this.getRelatedQuesion(f),f.isLoading=!1;let v=this.messages[this.messages.length-1];if(v&&v.role===I.ChatMessageRole.Robot){const y=u(u({},v),f);this.messages[this.messages.length-1]=y,this.event.emit("message:updated",y)}else this.pushMessage(f);this.frozen=!1});return this.addEventListener("answer:finish",h),this.sendQuestion(l,w(u({},t),{stream:a,referenceFirst:o})),d})}getRelatedQuesion(e){return p(this,null,function*(){var o,n;if(!e.content||e.isSensitive||e.code!==200||!((o=this.application)!=null&&o.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const t=yield this.cvforceApi.postGeneques({content:e.content}).catch(c=>null);if(!t){const c=[],i=w(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=w(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:!1}){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=!1}=e;let a;t.role!==I.ChatMessageRole.User&&(a=e.oldMessageId||t.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",t),this.event.emit("history:remove",t));const o=this.messages[this.messages.length-1],n={content:o.content,fileIds:o.fileIds,requestId:o.messageId,stream:s,oldMessageId:a},c=i=>p(this,null,function*(){if(i.role===I.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})),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 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,w(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:U(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:I.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const a=e.actions[((s=e.actions)==null?void 0:s.length)-1];if(a){const o=a[a.length-1];if(o&&(o.type==="BEFORE_CALL"||o.type==="FUNCTION_CALL")){const{pluginName:n,pluginCode:c,funcCode:i,funcName:d}=o.data;a.push({data:{pluginName:n,pluginCode:c,funcCode:i,funcName:d,step:o.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 k=new S("[AgentSession] ");class fe extends q{constructor(e,t="",s,a,o,n){super(e,t,s,a,o,n)}prepareConnection(){return new Promise(e=>p(this,null,function*(){this.socket&&e(!0);const t={version:"1.0",stream:"false",appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?L.Debug:L.Normal},s=new URL(exports.configuration.apiRoot),a=yield re.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});a.on("connect",()=>{k.log("socket:connect"),this.event.emit("socket:connect"),a.emit("init")}),a.on("disconnect",()=>{k.log("socket:disconnect"),this.event.emit("socket:disconnect")}),a.on("ready",o=>{if(o.code===200){k.log("ready");const n=exports.configuration.debug?L.Debug:L.Normal;n===L.Debug&&o.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,e(!0)}else{this._ready&&(this._ready=!1);const n=new Error(E.SocketConnectionFailed);k.error("error",n),this.event.emit("error",n),e(!1)}}),a.on("action",(o,n)=>p(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:c,data:{runnerIsClient:i,pluginCode:d,funcCode:l,parameters:h,requestBody:g}}=o,f=this.messages[this.messages.length-1];if(!f.messageId)f.actions||(f.actions=[]),f.actions[o.data.step-1]||(f.actions[o.data.step-1]=[]),f.actions[o.data.step-1].push(o),this.event.emit("message:action",{messageId:f.messageId,action:o}),this.event.emit("message:updated",f);else{const v={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[o]],comment:{isAgree:0}};this.pushMessage(v),this.event.emit("message:action",{messageId:v.messageId,action:o})}if(this.inactivating){const v=new Error(E.Inactive);k.warn("error",v),this.event.emit("error",v)}else if(c==="FUNCTION_CALL"&&i){if(k.log(`calling function ${l} of plugin ${d} with argument:
|
|
1
|
+
"use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var T=Object.getOwnPropertySymbols;var D=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var P=(r,e,t)=>e in r?se(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,u=(r,e)=>{for(var t in e||(e={}))D.call(e,t)&&P(r,t,e[t]);if(T)for(var t of T(e))B.call(e,t)&&P(r,t,e[t]);return r},w=(r,e)=>ie(r,ne(e));var F=(r,e)=>{var t={};for(var s in r)D.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&T)for(var s of T(r))e.indexOf(s)<0&&B.call(r,s)&&(t[s]=r[s]);return t};var m=(r,e,t)=>(P(r,typeof e!="symbol"?e+"":e,t),t);var p=(r,e,t)=>new Promise((s,a)=>{var o=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(o,n);c((t=t.apply(r,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),oe=require("axios"),I=require("@glodon-aiot/apis"),re=require("socket.io-client"),J=require("uuid"),K=require("dayjs"),R=class R{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!R.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!R.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!R.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!R.debug||console.warn(this.prefix,...e)}};m(R,"debug",!1);let S=R;const ce=new S("[Config] ");var U=(r=>(r.dev="https://aiot-dev.glodon.com/api/cvforcepd",r.test="https://aiot-dev.glodon.com/api/cvforce",r.prod="https://copilot.glodon.com/api/cvforce",r.local="http://localhost:3000/api/cvforcepd",r))(U||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},loadRelatedQuesions:!0};function G(r){S.debug=(r==null?void 0:r.debug)||!1,exports.configuration=w(u(u({},exports.configuration),r),{apiRoot:(r==null?void 0:r.apiRoot)||exports.configuration.apiRoot||(r!=null&&r.env?U[r.env||"prod"]:exports.configuration.apiRoot)}),S.debug&&ce.log("updated",exports.configuration)}const V=r=>JSON.parse(ae.decode(r.split(".")[1])),de=r=>{const e=V(r).exp;return new Date().valueOf()/1e3>=e},he=r=>r==null?void 0:r.replace(/[\r\n]+/gm,""),le=r=>r.replace(/\\|\\/g,"");function X(r,e,t){const s=d=>{var l;return e&&(de(e)&&t(403,"aiotToken is timeout"),d.headers=(l=d.headers)!=null?l:{},d.headers=w(u({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function a(d,l=!0){const h=`${r}${d}`,g=oe.create({baseURL:h});return l&&g.interceptors.request.use(s),g}const o=(d,l)=>{d===401&&t(d,"aiotToken is invalid")},n=(d,l)=>{d!==10001&&d!==10215&&t(d,l)},c=a("/data/v1");return new I.CVForceApi(c,{onHttpStatusError:o,onAppStatusError:n})}var L=(r=>(r[r.Normal=0]="Normal",r[r.Debug=1]="Debug",r))(L||{});const M=new S("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&M.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),M.log(`add event ${e} listener ${s?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const s=this.eventListenerMap[e].findIndex(a=>{if(typeof a=="function"&&t===a)return!0;if(a=a,a.fn===t)return!0});s<0?M.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),M.log(`remove event ${e} listener`))}else M.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){M.log(`event ${e} listeners is empty`);return}const s=[];for(let a=0;a<this.eventListenerMap[e].length;a++){const o=this.eventListenerMap[e][a];typeof o=="function"?o(t):s.push(o)}s.forEach(a=>{a&&(a.fn(t),this.off(e,a.fn))}),M.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const A=new S("[Session] ");var E=(r=>(r.DataRequestFailed="data request error",r.SocketConnectionFailed="socket error",r.IdUndefined="session id is not defined",r.SendingEmptyContent="failed at sending empty content",r.Frozen="session is frozen",r.UserModeError="failed at setting socket user mode",r.Inactive="session is inactive",r))(E||{});class q{constructor(e,t="",s,a,o,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);this.token=e,this.lazyload=a,this.client=n||null,this._applicationId=V(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),o&&(this._application=o),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var 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,knowledgeList:(c=s==null?void 0:s.knowledges)==null?void 0:c.map(d=>d.id),applicationId:this._applicationId}).then(d=>p(this,null,function*(){this._id=d.id,this.data=d,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),yield(()=>{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(h=>{var f,v;const g=((v=(f=s.promptVariables)==null?void 0:f.find(y=>y.key===h.key))==null?void 0:v.value)||"";return w(u({},h),{value:g})}).sort((h,g)=>h.key.localeCompare(g.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),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}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*(){var t;if(((t=this._application)==null?void 0:t.type)===I.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setKnowledges.");return}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===I.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>e.key!=="query")}setPromptVariables(e){return p(this,null,function*(){const t=this._promptVariables.map(s=>{var o;const a=((o=e==null?void 0:e.find(n=>n.key===s.key))==null?void 0:o.value)||s.value;return w(u({},s),{value:a})}).sort((s,a)=>s.key.localeCompare(a.key));if(yield Promise.all(t.filter(s=>s.key!=="query").map(s=>{if(!this.data)throw Error("session data is not loaded");if(!(!s.id||!s.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,s.id,{value:s.value}).catch(console.error)})),!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return p(this,null,function*(){var t,s,a;if(A.log("setNetOpen:",e),A.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===I.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,A.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");A.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"),A.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),A.log("history:moreloading",e)),this._loadingMessages=!0;const o=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),n=o.map((i,d)=>{var g,f;let l=[],h;return typeof((g=i.agentHistoryList)==null?void 0:g.agentList)=="string"&&(l=JSON.parse(i.agentHistoryList.agentList).reduce((y,_)=>(y[_.data.step-1]||(y[_.data.step-1]=[]),y[_.data.step-1].push(_),y),[])),d===o.length-1&&(h=(f=this.data)==null?void 0:f.lastRelatedQuestion),w(u({},i),{actions:l,relatedQuesion:h})});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(l=>l.ts===e.endTime),d=this.messages.findLastIndex(l=>l.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),A.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,n}else{const o=new Error("session id is not defined");return A.error(o),this.event.emit("error",o),!1}})}rename(e){return p(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),A.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),A.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),A.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 A.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:!1}){var g;try{this.validateConfigs()}catch(f){console.error(f)}const{stream:a=!1,referenceFirst:o=!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 f=new Error("failed at sending empty content");return A.error(f),this.event.emit("error",f),!1}if(!this._id){const f=new Error("session id is not defined");return A.error(f),this.event.emit("error",f),!1}if(this.frozen){const f=new Error("session is frozen");return A.error(f),this.event.emit("error",f),!1}this.frozen=!0,this._stopAnswer=!1;const d={sessionId:this.id,role:2,content:c,messageId:n,reference:[],searchReference:[],messageTime:""},l={content:c,stream:a,requestId:n,fileIds:i,referenceFirst:o};this.pushMessage(d),this.event.emit("question:content",c);const h=f=>p(this,null,function*(){if(f.role!==I.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",h),this._id&&f.content&&f.index&&f.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:f.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:f.content})),this.fillMessageReference(f),f.code){case 11915:f.content="请您换个问题问我吧~",f.index=-1,f.isSensitive=!0,f.isLoading=!1,f.sessionId=this._id||"",this.event.emit("message:error",f);break;case 200:f.index=-1,f.isLoading=!1;break;default:f.content=f.message||"未知错误",f.isLoading=!1,f.index=-1,this.event.emit("message:error",f)}this.getRelatedQuesion(f),f.isLoading=!1;let v=this.messages[this.messages.length-1];if(v&&v.role===I.ChatMessageRole.Robot){const y=u(u({},v),f);this.messages[this.messages.length-1]=y,this.event.emit("message:updated",y)}else this.pushMessage(f);this.frozen=!1});return this.addEventListener("answer:finish",h),this.sendQuestion(l,w(u({},t),{stream:a,referenceFirst:o})),d})}getRelatedQuesion(e){return p(this,null,function*(){var o,n;if(!e.content||e.isSensitive||e.code!==200||!((o=this.application)!=null&&o.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const t=yield this.cvforceApi.postGeneques({content:e.content}).catch(c=>null);if(!t){const c=[],i=w(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=w(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:!1}){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=!1}=e;let a;t.role!==I.ChatMessageRole.User&&(a=e.oldMessageId||t.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",t),this.event.emit("history:remove",t));const o=this.messages[this.messages.length-1],n={content:o.content,fileIds:o.fileIds,requestId:o.messageId,stream:s,oldMessageId:a},c=i=>p(this,null,function*(){if(i.role===I.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})),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 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,w(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:I.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const a=e.actions[((s=e.actions)==null?void 0:s.length)-1];if(a){const o=a[a.length-1];if(o&&(o.type==="BEFORE_CALL"||o.type==="FUNCTION_CALL")){const{pluginName:n,pluginCode:c,funcCode:i,funcName:d}=o.data;a.push({data:{pluginName:n,pluginCode:c,funcCode:i,funcName:d,step:o.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 k=new S("[AgentSession] ");class fe extends q{constructor(e,t="",s,a,o,n){super(e,t,s,a,o,n)}prepareConnection(){return new Promise(e=>p(this,null,function*(){this.socket&&e(!0);const t={version:"1.0",stream:"false",appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?L.Debug:L.Normal},s=new URL(exports.configuration.apiRoot),a=yield re.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});a.on("connect",()=>{k.log("socket:connect"),this.event.emit("socket:connect"),a.emit("init")}),a.on("disconnect",()=>{k.log("socket:disconnect"),this.event.emit("socket:disconnect")}),a.on("ready",o=>{if(o.code===200){k.log("ready");const n=exports.configuration.debug?L.Debug:L.Normal;n===L.Debug&&o.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,e(!0)}else{this._ready&&(this._ready=!1);const n=new Error(E.SocketConnectionFailed);k.error("error",n),this.event.emit("error",n),e(!1)}}),a.on("action",(o,n)=>p(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:c,data:{runnerIsClient:i,pluginCode:d,funcCode:l,parameters:h,requestBody:g}}=o,f=this.messages[this.messages.length-1];if(!f.messageId)f.actions||(f.actions=[]),f.actions[o.data.step-1]||(f.actions[o.data.step-1]=[]),f.actions[o.data.step-1].push(o),this.event.emit("message:action",{messageId:f.messageId,action:o}),this.event.emit("message:updated",f);else{const v={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[o]],comment:{isAgree:0}};this.pushMessage(v),this.event.emit("message:action",{messageId:v.messageId,action:o})}if(this.inactivating){const v=new Error(E.Inactive);k.warn("error",v),this.event.emit("error",v)}else if(c==="FUNCTION_CALL"&&i){if(k.log(`calling function ${l} of plugin ${d} with argument:
|
|
2
2
|
${JSON.stringify(h)}`),!exports.configuration.plugins[d]){n({code:404,message:"对不起,没有找到插件。"});return}const v=exports.configuration.plugins[d][l];typeof v!="function"&&n({code:404,message:"对不起,没有找到插件方法。"});let y=h==null?void 0:h.query;try{y=JSON.parse(h==null?void 0:h.query)}catch(_){}v(y,(..._)=>{this._stopAnswer||n(..._)})}})),a.on("answer",o=>{if(!this._stopAnswer)if(o.data.code!==200&&(o.data.index=-1,this.event.emit("error",o.data)),o.data.index===-1){let n=this.messages[this.messages.length-1];if(n&&!n.messageId)n=u(u({},n),o.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:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0}},o.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),o.data),this.messages[this.messages.length-1]=n,this.event.emit("message:content",n),this.event.emit("message:updated",n)):(this.pushMessage(o.data),this.event.emit("message:content",o.data))}}),a.on("reference",o=>p(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const h=new Error(E.IdUndefined);k.error(h),this.event.emit("error",h),this.frozen=!1;return}const{type:n,data:c,requestId:i}=o,d=this.messages.findIndex(h=>h.messageId===i&&h.role===I.ChatMessageRole.User);if(d<0)return;const l=d+1;if(l>=this.messages.length){const h={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0}};this.pushMessage(h)}n==="KG"?(this.messages[l]=w(u({},this.messages[l]),{reference:c.knowledgeReference}),yield this.fillMessageReference(this.messages[l]),this.event.emit("message:reference",c.knowledgeReference),this.event.emit("message:updated",this.messages[l])):n==="WEB_SEARCH"&&(this.messages[l]=w(u({},this.messages[l]),{searchReference:c.knowledgeReference}),this.event.emit("message:searchreference",c.searchReference),this.event.emit("message:updated",this.messages[l]))})),this.socket=a,a.open()}))}sendQuestion(e,t){return p(this,null,function*(){var a,o,n;let s=w(u({},e),{promptVariables:this.promptVariables.reduce((c,i)=>w(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(E.SocketConnectionFailed);return k.warn("error",c),this.event.emit("error",c),!1}(o=this.socket)==null||o.emit("question",s);return}(n=this.socket)==null||n.emit("question",s)})}stopAnswer(){var e;(e=this.socket)==null||e.emit("stop_answer")}}function ge(r,e){return p(this,null,function*(){const t=r.getReader();let s;for(;!(s=yield t.read()).done;)e(s.value)})}function pe(r){let e,t,s,a=!1,o;return function(c){e===void 0?(e=c,t=0,s=-1,o=!1):e=me(e,c);const i=e.length;let d=0;for(;t<i;){a&&(e[t]===10&&(d=++t),a=!1);let l=-1;for(;t<i&&l===-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&&(o=!0);case 10:l=t;break}if(l===-1)break;r(e.subarray(d,l),s,o),d=t,s=-1,o=!1}d===i?e=void 0:d!==0&&(e=e.subarray(d),t-=d)}}function ue(r,e,t){let s=j();const a=new TextDecoder;return function(n,c,i){if(n.length===0)t==null||t(s),s=j();else if(c>0){const d=a.decode(n.subarray(0,c)),l=c+(n[c+1]===32?2:1);let h=a.decode(n.subarray(l));switch(i&&(h+=`
|
|
3
3
|
`),d){case"data":s.data=s.data?s.data+`
|
|
4
|
-
`+h:h;break;case"event":s.event=h;break;case"id":r(s.id=h);break;case"retry":const g=parseInt(h,10);isNaN(g)||e(s.retry=g);break}}}}function me(r,e){const t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function j(){return{data:"",event:"",id:"",retry:void 0}}const z="text/event-stream",ve=1e3,H="last-event-id";function Y(r,l){var h=l,{signal:e,headers:t,onopen:s,onmessage:a,onclose:o,onerror:n,openWhenHidden:c,fetch:i}=h,d=F(h,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,f)=>{const v=u({},t);v.accept||(v.accept=z);let y;function _(){y.abort(),document.hidden||$()}c||document.addEventListener("visibilitychange",_);let x=ve,O=0;function Q(){document.removeEventListener("visibilitychange",_),window.clearTimeout(O),y.abort()}e==null||e.addEventListener("abort",()=>{Q(),g()});const ee=i!=null?i:window.fetch,te=s!=null?s:ye;function $(){return p(this,null,function*(){var N;y=new AbortController;try{const C=yield ee(r,w(u({},d),{headers:v,signal:y.signal}));yield te(C),yield ge(C.body,pe(ue(b=>{b?v[H]=b:delete v[H]},b=>{x=b},a))),o==null||o(),Q(),g()}catch(C){if(!y.signal.aborted)try{const b=(N=n==null?void 0:n(C))!=null?N:x;window.clearTimeout(O),O=window.setTimeout($,b)}catch(b){Q(),f(b)}}})}$()})}function ye(r){const e=r.headers.get("content-type");if(!(e!=null&&e.startsWith(z)))throw new Error(`Expected content-type to be ${z}, Actual: ${e}`)}const W=new S("[DialogSession] ");class we extends q{constructor(t,s="",a,o,n,c){super(t,s,a,o,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,o,n,c){return p(this,null,function*(){const i={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=w(u({},a),{stream:!0});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(d),openWhenHidden:!0,signal:o,onopen(l){return l.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(l){if(!l.data.includes('{"code": ')){let g={};try{g=JSON.parse(l.data)}catch(v){}(g==null?void 0:g.mtype)==="search"?i.searchReference.push(g):i.content=i.content+l.data;const f={content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:s,messageTime:U(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(n==null?void 0:n.onmessage)&&n.onmessage(f)}const h=JSON.parse(l.data);if(i.reference=h.data.reference,i.searchReference=h.data.searchReference,i.messageTime=h.data.messageTime,i.messageId=h.data.messageId,i.llmModel=h.data.llmModel,i.content=h.data.content,i.code=h.code,h.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 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,o,n,c){return p(this,null,function*(){const i={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},d=w(u({},a),{stream:!0});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(d),openWhenHidden:!0,signal:o,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 h={};try{h=JSON.parse(l.data)}catch(y){console.error("parse eventData to JSON failed. ",l.data)}if(h.code!==200)return i.index=-1,i.code=h.code,i.message=h.message,n!=null&&n.onmessage&&n.onmessage(i),c&&c({code:h.code,message:h.message});const g=h.data.type,f=h.data.payload;i.isReplying=!0;const v=()=>{if(!i.searchingStatus){i.searchingStatus="start";return}if(i.searchingStatus==="start"){i.searchingStatus="end";return}};if(g==="beforeSearch"&&v(),g==="searchOver"&&v(),g==="search"&&i.searchReference.push(f),g==="thinking"){i.thinkingStatus="start";const _=f.choices[0];i.reasoningContent=i.reasoningContent+_.delta.reasoningContent}if(g==="thinkingOver"){i.thinkingStatus="end";const y=f.thinkingSecs;i.thinkingSecs=y}if(g==="text"){const _=f.choices[0];i.content=i.content+_.delta.content}if(g==="reference"&&(i.reference=f),g==="result"){const y=f.messageId,_=f.llmModel,x=f.messageTime;i.messageId=y,i.llmModel=_,i.messageTime=x,i.sessionId=s}g==="over"?i.index=-1:(i.code=h.code,i.message=h.message),n!=null&&n.onmessage&&n.onmessage(i)},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const l=w(u({},i),{isReplying:!1});n!=null&&n.onclose&&n.onclose(l)}})})}sendQuestion(t,s){return p(this,null,function*(){var d;const{content:a,fileIds:o,oldMessageId:n}=t,{stream:c,referenceFirst:i}=s;if(this.active||(yield this.activate()),this._id){let l={content:a,fileIds:o,referenceFirst:i,oldMessageId:n,promptVariables:this.promptVariables.reduce((h,g)=>w(u({},h),{[g.key]:g.value}),{}),knowledges:(d=this.knowledges)==null?void 0:d.map(h=>h.id)};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,l,this.ctrl.signal,{onopen:()=>{W.log("open",this.ctrl)},onmessage:h=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===I.ChatMessageRole.Robot?(g=u(u({},g),h),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(h),this.event.emit("message:content",h))},onclose:h=>p(this,null,function*(){this._stopAnswer||(W.log(h,"onclose"),this.event.emit("answer:finish",h))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}}const Ie=new S("[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,G(t),this._applicationId=V(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(()=>{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(o=>(typeof o.arrange[0].recommendQuestionOpen!="boolean"&&(o.arrange[0].recommendQuestionOpen=!0),w(u({},o),{arrange:[w(u({},o.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&o.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(o=>o.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,o){return p(this,null,function*(){const n=this;return new Promise((c,i)=>{const d=l=>p(this,null,function*(){if(l===I.ApplicationTypes.Agent)c(new fe(e,t,s,a,o,n));else if(l===I.ApplicationTypes.Dialog)c(new we(e,t,s,a,o,n));else throw Error(`不支持的应用类型:${l}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return p(this,null,function*(){return new Promise((t,s)=>{const a=()=>this.cvforceApi.listSessions(this._applicationId,e).then(o=>{const n=[];return o.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(o=>o.id===e):this._activeSession;if(!a){console.warn("setTop session failed.");return}return yield a.setTop(t),this.getSessions({order:s})})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return p(this,null,function*(){this.checkReady();let s=-1;if(typeof e=="string"?s=this._sessions.findIndex(a=>a.id===e):s=this._sessions.findIndex(a=>a.id===e.id),s>-1){const a=this._sessions[s];t&&(yield a.delete()),this._sessions.splice(s,1)}else console.warn("session delete failed, session is not exist.")})}clean(){this._sessions.forEach(e=>e.destroy()),this.sessions=[]}}class Ae{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=Ae;exports.BotClient=_e;exports.Session=q;exports.configure=G;
|
|
4
|
+
`+h:h;break;case"event":s.event=h;break;case"id":r(s.id=h);break;case"retry":const g=parseInt(h,10);isNaN(g)||e(s.retry=g);break}}}}function me(r,e){const t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function j(){return{data:"",event:"",id:"",retry:void 0}}const z="text/event-stream",ve=1e3,H="last-event-id";function Y(r,l){var h=l,{signal:e,headers:t,onopen:s,onmessage:a,onclose:o,onerror:n,openWhenHidden:c,fetch:i}=h,d=F(h,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,f)=>{const v=u({},t);v.accept||(v.accept=z);let y;function _(){y.abort(),document.hidden||$()}c||document.addEventListener("visibilitychange",_);let x=ve,O=0;function Q(){document.removeEventListener("visibilitychange",_),window.clearTimeout(O),y.abort()}e==null||e.addEventListener("abort",()=>{Q(),g()});const ee=i!=null?i:window.fetch,te=s!=null?s:ye;function $(){return p(this,null,function*(){var N;y=new AbortController;try{const C=yield ee(r,w(u({},d),{headers:v,signal:y.signal}));yield te(C),yield ge(C.body,pe(ue(b=>{b?v[H]=b:delete v[H]},b=>{x=b},a))),o==null||o(),Q(),g()}catch(C){if(!y.signal.aborted)try{const b=(N=n==null?void 0:n(C))!=null?N:x;window.clearTimeout(O),O=window.setTimeout($,b)}catch(b){Q(),f(b)}}})}$()})}function ye(r){const e=r.headers.get("content-type");if(!(e!=null&&e.startsWith(z)))throw new Error(`Expected content-type to be ${z}, Actual: ${e}`)}const W=new S("[DialogSession] ");class we extends q{constructor(t,s="",a,o,n,c){super(t,s,a,o,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,o,n,c){return p(this,null,function*(){const i={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=w(u({},a),{stream:!0});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(d),openWhenHidden:!0,signal:o,onopen(l){return l.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(l){if(!l.data.includes('{"code": ')){let g={};try{g=JSON.parse(l.data)}catch(v){}(g==null?void 0:g.mtype)==="search"?i.searchReference.push(g):i.content=i.content+l.data;const f={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(f)}const h=JSON.parse(l.data);if(i.reference=h.data.reference,i.searchReference=h.data.searchReference,i.messageTime=h.data.messageTime,i.messageId=h.data.messageId,i.llmModel=h.data.llmModel,i.content=h.data.content,i.code=h.code,h.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 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,o,n,c){return p(this,null,function*(){const i={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},d=w(u({},a),{stream:!0});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(d),openWhenHidden:!0,signal:o,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 h={};try{h=JSON.parse(l.data)}catch(y){console.error("parse eventData to JSON failed. ",l.data)}if(h.code!==200)return i.index=-1,i.code=h.code,i.message=h.message,n!=null&&n.onmessage&&n.onmessage(i),c&&c({code:h.code,message:h.message});const g=h.data.type,f=h.data.payload;i.isReplying=!0;const v=()=>{if(!i.searchingStatus){i.searchingStatus="start";return}if(i.searchingStatus==="start"){i.searchingStatus="end";return}};if(g==="beforeSearch"&&v(),g==="searchOver"&&v(),g==="search"&&i.searchReference.push(f),g==="thinking"){i.thinkingStatus="start";const _=f.choices[0];i.reasoningContent=i.reasoningContent+_.delta.reasoningContent}if(g==="thinkingOver"){i.thinkingStatus="end";const y=f.thinkingSecs;i.thinkingSecs=y}if(g==="text"){const _=f.choices[0];i.content=i.content+_.delta.content}if(g==="reference"&&(i.reference=f),g==="result"){const y=f.messageId,_=f.llmModel,x=f.messageTime;i.messageId=y,i.llmModel=_,i.messageTime=x,i.sessionId=s}g==="over"?i.index=-1:(i.code=h.code,i.message=h.message),n!=null&&n.onmessage&&n.onmessage(i)},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const l=w(u({},i),{isReplying:!1});n!=null&&n.onclose&&n.onclose(l)}})})}sendQuestion(t,s){return p(this,null,function*(){var d;const{content:a,fileIds:o,oldMessageId:n}=t,{stream:c,referenceFirst:i}=s;if(this.active||(yield this.activate()),this._id){let l={content:a,fileIds:o,referenceFirst:i,oldMessageId:n,promptVariables:this.promptVariables.reduce((h,g)=>w(u({},h),{[g.key]:g.value}),{}),knowledges:(d=this.knowledges)==null?void 0:d.map(h=>h.id)};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,l,this.ctrl.signal,{onopen:()=>{W.log("open",this.ctrl)},onmessage:h=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===I.ChatMessageRole.Robot?(g=u(u({},g),h),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(h),this.event.emit("message:content",h))},onclose:h=>p(this,null,function*(){this._stopAnswer||(W.log(h,"onclose"),this.event.emit("answer:finish",h))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}}const Ie=new S("[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,G(t),this._applicationId=V(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(()=>{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(o=>(typeof o.arrange[0].recommendQuestionOpen!="boolean"&&(o.arrange[0].recommendQuestionOpen=!0),w(u({},o),{arrange:[w(u({},o.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&o.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(o=>o.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,o){return p(this,null,function*(){const n=this;return new Promise((c,i)=>{const d=l=>p(this,null,function*(){if(l===I.ApplicationTypes.Agent)c(new fe(e,t,s,a,o,n));else if(l===I.ApplicationTypes.Dialog)c(new we(e,t,s,a,o,n));else throw Error(`不支持的应用类型:${l}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return p(this,null,function*(){return new Promise((t,s)=>{const a=()=>this.cvforceApi.listSessions(this._applicationId,e).then(o=>{const n=[];return o.forEach(c=>p(this,null,function*(){const i=this._sessions.find(d=>c.id===d.id);if(i)i.data=c,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(o=>o.id===e):this._activeSession;if(!a){console.warn("setTop session failed.");return}return yield a.setTop(t),this.getSessions({order:s})})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return p(this,null,function*(){this.checkReady();let s=-1;if(typeof e=="string"?s=this._sessions.findIndex(a=>a.id===e):s=this._sessions.findIndex(a=>a.id===e.id),s>-1){const a=this._sessions[s];t&&(yield a.delete()),this._sessions.splice(s,1)}else console.warn("session delete failed, session is not exist.")})}clean(){this._sessions.forEach(e=>e.destroy()),this.sessions=[]}}class Ae{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=Ae;exports.BotClient=_e;exports.Session=q;exports.configure=G;
|
package/dist/src/Session.d.ts
CHANGED
|
@@ -85,7 +85,6 @@ export default abstract class Session {
|
|
|
85
85
|
get id(): string;
|
|
86
86
|
get applicationId(): string;
|
|
87
87
|
get application(): IApplication | null;
|
|
88
|
-
set application(v: IApplication | null);
|
|
89
88
|
loadApplicationInfo(): Promise<IApplication>;
|
|
90
89
|
get ready(): boolean;
|
|
91
90
|
get frozen(): boolean;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glodon-aiot/agent-cli-sdk",
|
|
3
|
-
"version": "3.2.
|
|
3
|
+
"version": "3.2.10-beta.1",
|
|
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.2.
|
|
82
|
+
"@glodon-aiot/apis": "^3.2.10-beta.1",
|
|
83
83
|
"axios": "0.24.0",
|
|
84
84
|
"buffer": "^6.0.3",
|
|
85
85
|
"dayjs": "^1.11.13",
|