@glodon-aiot/bot-client-sdk 3.20.2-alpha.1 → 3.20.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/es/AgentSession.mjs +31 -22
- package/dist/es/BotClient.mjs +100 -100
- package/dist/es/Session.mjs +35 -36
- package/dist/es/package.json.mjs +2 -2
- package/dist/lib/index.js +3 -3
- package/package.json +2 -2
package/dist/es/AgentSession.mjs
CHANGED
|
@@ -14,14 +14,14 @@ var v = (m, t, i) => new Promise((o, r) => {
|
|
|
14
14
|
var s = (a) => {
|
|
15
15
|
try {
|
|
16
16
|
n(i.next(a));
|
|
17
|
-
} catch (
|
|
18
|
-
r(
|
|
17
|
+
} catch (h) {
|
|
18
|
+
r(h);
|
|
19
19
|
}
|
|
20
20
|
}, e = (a) => {
|
|
21
21
|
try {
|
|
22
22
|
n(i.throw(a));
|
|
23
|
-
} catch (
|
|
24
|
-
r(
|
|
23
|
+
} catch (h) {
|
|
24
|
+
r(h);
|
|
25
25
|
}
|
|
26
26
|
}, n = (a) => a.done ? o(a.value) : Promise.resolve(a.value).then(s, e);
|
|
27
27
|
n((i = i.apply(m, t)).next());
|
|
@@ -79,8 +79,8 @@ class H extends q {
|
|
|
79
79
|
type: n,
|
|
80
80
|
data: {
|
|
81
81
|
runnerIsClient: a,
|
|
82
|
-
pluginCode:
|
|
83
|
-
funcCode:
|
|
82
|
+
pluginCode: h,
|
|
83
|
+
funcCode: g,
|
|
84
84
|
parameters: c,
|
|
85
85
|
requestBody: N
|
|
86
86
|
}
|
|
@@ -124,26 +124,26 @@ class H extends q {
|
|
|
124
124
|
);
|
|
125
125
|
p.warn("error", f), this.event.emit("error", f);
|
|
126
126
|
} else if (n === "FUNCTION_CALL" && a) {
|
|
127
|
-
if (p.log(`calling function ${
|
|
128
|
-
${JSON.stringify(c)}`), !u.plugins[
|
|
127
|
+
if (p.log(`calling function ${g} of plugin ${h} with argument:
|
|
128
|
+
${JSON.stringify(c)}`), !u.plugins[h]) {
|
|
129
129
|
e({
|
|
130
130
|
code: 404,
|
|
131
131
|
message: "对不起,没有找到插件。"
|
|
132
132
|
});
|
|
133
133
|
return;
|
|
134
134
|
}
|
|
135
|
-
const f = u.plugins[
|
|
135
|
+
const f = u.plugins[h][g];
|
|
136
136
|
typeof f != "function" && e({
|
|
137
137
|
code: 404,
|
|
138
138
|
message: "对不起,没有找到插件方法。"
|
|
139
139
|
});
|
|
140
|
-
let
|
|
140
|
+
let k = c == null ? void 0 : c.query;
|
|
141
141
|
try {
|
|
142
|
-
|
|
143
|
-
} catch (
|
|
142
|
+
k = JSON.parse(c == null ? void 0 : c.query);
|
|
143
|
+
} catch (R) {
|
|
144
144
|
}
|
|
145
|
-
f(
|
|
146
|
-
this._stopAnswer || e(...
|
|
145
|
+
f(k, (...R) => {
|
|
146
|
+
this._stopAnswer || e(...R);
|
|
147
147
|
});
|
|
148
148
|
}
|
|
149
149
|
})), r.on("answer", (s) => {
|
|
@@ -164,7 +164,16 @@ class H extends q {
|
|
|
164
164
|
comment: {
|
|
165
165
|
isAgree: 0
|
|
166
166
|
},
|
|
167
|
-
isReplying: !0
|
|
167
|
+
isReplying: !0,
|
|
168
|
+
// bugfix:这几个字段之前没有初始化,`handleStreamAnswer` 收到第一个 "thinking"
|
|
169
|
+
// 分片时会执行 `targetMessage.reasoningContent = targetMessage.reasoningContent +
|
|
170
|
+
// choice.delta.reasoningContent`——`undefined + string` 在 JS 里会被转成字面字符串
|
|
171
|
+
// "undefined" 拼在正文最前面(如 "undefined好的,用户..."),导致推理过程正文开头
|
|
172
|
+
// 永久带着这段无意义文本。跟 DialogSession.ts 的 tempMessage 初始化对齐,补上默认值。
|
|
173
|
+
reasoningContent: "",
|
|
174
|
+
thinkingSecs: "",
|
|
175
|
+
thinkingStatus: "",
|
|
176
|
+
searchingStatus: ""
|
|
168
177
|
};
|
|
169
178
|
this.handleStreamAnswer(s.data, n), this.pushMessage(n), this.event.emit("message:content", n), n.index === -1 && (n.isReplying = !1, this.event.emit("answer:finish", n));
|
|
170
179
|
}
|
|
@@ -225,11 +234,11 @@ class H extends q {
|
|
|
225
234
|
type: e,
|
|
226
235
|
data: n,
|
|
227
236
|
requestId: a
|
|
228
|
-
} = s,
|
|
229
|
-
if (
|
|
237
|
+
} = s, h = this.messages.findIndex((c) => c.messageId === a && c.role === y.User);
|
|
238
|
+
if (h < 0)
|
|
230
239
|
return;
|
|
231
|
-
const
|
|
232
|
-
if (
|
|
240
|
+
const g = h + 1;
|
|
241
|
+
if (g >= this.messages.length) {
|
|
233
242
|
const c = {
|
|
234
243
|
messageId: "",
|
|
235
244
|
content: "",
|
|
@@ -247,11 +256,11 @@ class H extends q {
|
|
|
247
256
|
};
|
|
248
257
|
this.pushMessage(c);
|
|
249
258
|
}
|
|
250
|
-
e === "KG" ? (this.messages[
|
|
259
|
+
e === "KG" ? (this.messages[g] = w(d({}, this.messages[g]), {
|
|
251
260
|
reference: n.knowledgeReference
|
|
252
|
-
}), yield this.fillMessageReference(this.messages[
|
|
261
|
+
}), yield this.fillMessageReference(this.messages[g]), this.event.emit("message:reference", n.knowledgeReference), this.event.emit("message:updated", this.messages[g])) : e === "WEB_SEARCH" && (this.messages[g] = w(d({}, this.messages[g]), {
|
|
253
262
|
searchReference: n.knowledgeReference
|
|
254
|
-
}), this.event.emit("message:searchreference", n.searchReference), this.event.emit("message:updated", this.messages[
|
|
263
|
+
}), this.event.emit("message:searchreference", n.searchReference), this.event.emit("message:updated", this.messages[g]));
|
|
255
264
|
})), this.socket = r, r.open();
|
|
256
265
|
}));
|
|
257
266
|
}
|
package/dist/es/BotClient.mjs
CHANGED
|
@@ -1,49 +1,49 @@
|
|
|
1
1
|
var k = Object.defineProperty, A = Object.defineProperties;
|
|
2
2
|
var x = Object.getOwnPropertyDescriptors;
|
|
3
|
-
var
|
|
3
|
+
var m = Object.getOwnPropertySymbols;
|
|
4
4
|
var I = Object.prototype.hasOwnProperty, R = Object.prototype.propertyIsEnumerable;
|
|
5
|
-
var g = (r,
|
|
6
|
-
for (var
|
|
7
|
-
I.call(
|
|
8
|
-
if (
|
|
9
|
-
for (var
|
|
10
|
-
R.call(
|
|
5
|
+
var g = (r, i, e) => i in r ? k(r, i, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[i] = e, p = (r, i) => {
|
|
6
|
+
for (var e in i || (i = {}))
|
|
7
|
+
I.call(i, e) && g(r, e, i[e]);
|
|
8
|
+
if (m)
|
|
9
|
+
for (var e of m(i))
|
|
10
|
+
R.call(i, e) && g(r, e, i[e]);
|
|
11
11
|
return r;
|
|
12
|
-
}, f = (r,
|
|
13
|
-
var d = (r,
|
|
14
|
-
var l = (r,
|
|
12
|
+
}, f = (r, i) => A(r, x(i));
|
|
13
|
+
var d = (r, i, e) => (g(r, typeof i != "symbol" ? i + "" : i, e), e);
|
|
14
|
+
var l = (r, i, e) => new Promise((t, s) => {
|
|
15
15
|
var a = (o) => {
|
|
16
16
|
try {
|
|
17
|
-
|
|
18
|
-
} catch (
|
|
19
|
-
|
|
17
|
+
n(e.next(o));
|
|
18
|
+
} catch (h) {
|
|
19
|
+
s(h);
|
|
20
20
|
}
|
|
21
|
-
},
|
|
21
|
+
}, c = (o) => {
|
|
22
22
|
try {
|
|
23
|
-
|
|
24
|
-
} catch (
|
|
25
|
-
|
|
23
|
+
n(e.throw(o));
|
|
24
|
+
} catch (h) {
|
|
25
|
+
s(h);
|
|
26
26
|
}
|
|
27
|
-
},
|
|
28
|
-
|
|
27
|
+
}, n = (o) => o.done ? t(o.value) : Promise.resolve(o.value).then(a, c);
|
|
28
|
+
n((e = e.apply(r, i)).next());
|
|
29
29
|
});
|
|
30
|
-
import { parseJWT as
|
|
30
|
+
import { parseJWT as y } from "./utils.mjs";
|
|
31
31
|
import E from "./Logger.mjs";
|
|
32
|
-
import { getCVForceService as
|
|
33
|
-
import { configure as S, configuration as
|
|
32
|
+
import { getCVForceService as C } from "./api/index.mjs";
|
|
33
|
+
import { configure as S, configuration as v } from "./Config.mjs";
|
|
34
34
|
import { ApplicationTypes as _, PromptVariableType as w } from "@glodon-aiot/apis";
|
|
35
|
-
import
|
|
36
|
-
import
|
|
37
|
-
import
|
|
35
|
+
import L from "./AgentSession.mjs";
|
|
36
|
+
import M from "./DialogSession.mjs";
|
|
37
|
+
import V from "./EventBus.mjs";
|
|
38
38
|
import T from "./package.json.mjs";
|
|
39
39
|
const b = new E("[BotClient] ");
|
|
40
40
|
class W {
|
|
41
|
-
constructor(
|
|
41
|
+
constructor(i, e, t = !0, s = {
|
|
42
42
|
analytics: {
|
|
43
43
|
enabled: !1
|
|
44
44
|
}
|
|
45
45
|
}) {
|
|
46
|
-
d(this, "event", new
|
|
46
|
+
d(this, "event", new V());
|
|
47
47
|
d(this, "cvforceApi");
|
|
48
48
|
//从token解析出来的用户信息
|
|
49
49
|
d(this, "_applicationId");
|
|
@@ -56,11 +56,11 @@ class W {
|
|
|
56
56
|
//问题长度
|
|
57
57
|
d(this, "_questionContextMaxLength", 4e3);
|
|
58
58
|
d(this, "_promptVariables", []);
|
|
59
|
-
if (this._token =
|
|
59
|
+
if (this._token = i, this.lazyload = t, this.sdkConfigs = s, S(e), this._applicationId = y(i).rid || v.applicationId, !this._applicationId)
|
|
60
60
|
throw "token is not vaild";
|
|
61
61
|
this.cvforceApi = this.getService(), this.loadApplication().then((a) => {
|
|
62
|
-
S(f(p({},
|
|
63
|
-
stream:
|
|
62
|
+
S(f(p({}, e), {
|
|
63
|
+
stream: e.stream === void 0 ? (a == null ? void 0 : a.type) === _.Dialog || (a == null ? void 0 : a.type) === _.Agent : e.stream
|
|
64
64
|
})), this.event.emit("ready");
|
|
65
65
|
});
|
|
66
66
|
}
|
|
@@ -71,8 +71,8 @@ class W {
|
|
|
71
71
|
get ready() {
|
|
72
72
|
return this._ready;
|
|
73
73
|
}
|
|
74
|
-
set ready(
|
|
75
|
-
this._ready =
|
|
74
|
+
set ready(i) {
|
|
75
|
+
this._ready = i;
|
|
76
76
|
}
|
|
77
77
|
get questionContextMaxLength() {
|
|
78
78
|
return this.checkReady(), this._questionContextMaxLength;
|
|
@@ -81,49 +81,49 @@ class W {
|
|
|
81
81
|
return this.checkReady(), this._promptVariables;
|
|
82
82
|
}
|
|
83
83
|
get knowledges() {
|
|
84
|
-
var
|
|
85
|
-
return this.checkReady(), (
|
|
84
|
+
var i;
|
|
85
|
+
return this.checkReady(), (i = this._application) == null ? void 0 : i.arrange[0].knowledges;
|
|
86
86
|
}
|
|
87
87
|
get sessions() {
|
|
88
88
|
return this.checkReady(), this._sessions;
|
|
89
89
|
}
|
|
90
|
-
set sessions(
|
|
91
|
-
this.checkReady(), this._sessions =
|
|
90
|
+
set sessions(i) {
|
|
91
|
+
this.checkReady(), this._sessions = i, this.event.emit("sessions:updated", i);
|
|
92
92
|
}
|
|
93
93
|
loadApplication() {
|
|
94
94
|
return l(this, null, function* () {
|
|
95
|
-
var
|
|
95
|
+
var e, t, s, a, c;
|
|
96
96
|
this._application = yield this.cvforceApi.getApplicationId(
|
|
97
97
|
this._applicationId,
|
|
98
98
|
// 这里记录应用的名称和版本,以便后期数据分析
|
|
99
99
|
{
|
|
100
|
-
ui: (
|
|
100
|
+
ui: (e = this.sdkConfigs.ui) == null ? void 0 : e.name,
|
|
101
101
|
uiVersion: (t = this.sdkConfigs.ui) == null ? void 0 : t.version,
|
|
102
102
|
sdkVersion: T.version
|
|
103
103
|
}
|
|
104
|
-
).then((
|
|
105
|
-
arrange: [f(p({},
|
|
106
|
-
recommendQuestionOpen:
|
|
104
|
+
).then((n) => (typeof n.arrange[0].recommendQuestionOpen != "boolean" && (n.arrange[0].recommendQuestionOpen = !0), f(p({}, n), {
|
|
105
|
+
arrange: [f(p({}, n.arrange[0]), {
|
|
106
|
+
recommendQuestionOpen: v.loadRelatedQuesions && n.arrange[0].recommendQuestionOpen
|
|
107
107
|
})]
|
|
108
108
|
})));
|
|
109
|
-
const
|
|
110
|
-
return
|
|
109
|
+
const i = (c = (a = (s = this._application) == null ? void 0 : s.arrange) == null ? void 0 : a[0]) == null ? void 0 : c.llmModel;
|
|
110
|
+
return i && (this._questionContextMaxLength = yield this.cvforceApi.getBaseModel(i).then((n) => n.maxModelLength)), this._promptVariables = yield Promise.all([this.cvforceApi.getPrompts(this._applicationId, {
|
|
111
111
|
type: w.User
|
|
112
112
|
}), this.cvforceApi.getPrompts(this._applicationId, {
|
|
113
113
|
type: w.System
|
|
114
|
-
})]).then(([
|
|
114
|
+
})]).then(([n, o]) => [...n, ...o]), this._ready = !0, this.event.emit("application:loaded"), this._application;
|
|
115
115
|
});
|
|
116
116
|
}
|
|
117
117
|
getService() {
|
|
118
|
-
return this.cvforceApi ? this.cvforceApi :
|
|
118
|
+
return this.cvforceApi ? this.cvforceApi : C(v.apiRoot, this.token, (i, e) => b.error(e));
|
|
119
119
|
}
|
|
120
120
|
get token() {
|
|
121
121
|
return this._token;
|
|
122
122
|
}
|
|
123
|
-
set token(
|
|
124
|
-
this.checkReady(), this._token =
|
|
125
|
-
const
|
|
126
|
-
this._applicationId !==
|
|
123
|
+
set token(i) {
|
|
124
|
+
this.checkReady(), this._token = i, this.ready = !1;
|
|
125
|
+
const e = y(i).rid;
|
|
126
|
+
this._applicationId !== e && (this._applicationId = e, this._application = null, this.loadApplication().then(() => {
|
|
127
127
|
this.event.emit("ready");
|
|
128
128
|
}), this.clean());
|
|
129
129
|
}
|
|
@@ -134,79 +134,79 @@ class W {
|
|
|
134
134
|
return this.checkReady(), this._application;
|
|
135
135
|
}
|
|
136
136
|
get activeSession() {
|
|
137
|
-
var
|
|
138
|
-
return this.checkReady(), ((
|
|
137
|
+
var i;
|
|
138
|
+
return this.checkReady(), ((i = this._activeSession) == null ? void 0 : i.id) || "";
|
|
139
139
|
}
|
|
140
|
-
set activeSession(
|
|
141
|
-
this.checkReady(), this.loadSession(
|
|
142
|
-
this._activeSession && this._activeSession.id !==
|
|
140
|
+
set activeSession(i) {
|
|
141
|
+
this.checkReady(), this.loadSession(i).then((e) => {
|
|
142
|
+
this._activeSession && this._activeSession.id !== i && this._activeSession.inactivate(), this._activeSession = e;
|
|
143
143
|
});
|
|
144
144
|
}
|
|
145
|
-
createSession(
|
|
145
|
+
createSession(i, e, t, s, a) {
|
|
146
146
|
return l(this, null, function* () {
|
|
147
|
-
const
|
|
148
|
-
return new Promise((
|
|
149
|
-
const
|
|
147
|
+
const c = this;
|
|
148
|
+
return new Promise((n, o) => {
|
|
149
|
+
const h = (u) => l(this, null, function* () {
|
|
150
150
|
if (u === _.Agent)
|
|
151
|
-
|
|
151
|
+
n(new L(i, e, t, s, a, c));
|
|
152
152
|
else if (u === _.Dialog)
|
|
153
|
-
|
|
153
|
+
n(new M(i, e, t, s, a, c));
|
|
154
154
|
else
|
|
155
155
|
throw Error(`不支持的应用类型:${u}`);
|
|
156
156
|
});
|
|
157
157
|
if (this.ready) {
|
|
158
158
|
if (!this._application)
|
|
159
159
|
throw Error("client is not ready");
|
|
160
|
-
|
|
160
|
+
h(this._application.type);
|
|
161
161
|
} else
|
|
162
162
|
this.event.on("ready", () => {
|
|
163
163
|
if (!this._application)
|
|
164
164
|
throw Error("_application is null");
|
|
165
|
-
|
|
165
|
+
h(this._application.type);
|
|
166
166
|
}, !0);
|
|
167
167
|
});
|
|
168
168
|
});
|
|
169
169
|
}
|
|
170
|
-
getSessions(
|
|
170
|
+
getSessions(i) {
|
|
171
171
|
return l(this, null, function* () {
|
|
172
|
-
return new Promise((
|
|
173
|
-
const
|
|
174
|
-
const
|
|
175
|
-
for (const
|
|
176
|
-
const o = this._sessions.find((
|
|
172
|
+
return new Promise((e, t) => {
|
|
173
|
+
const s = () => this.cvforceApi.listSessions(this._applicationId, i).then((a) => l(this, null, function* () {
|
|
174
|
+
const c = [];
|
|
175
|
+
for (const n of a) {
|
|
176
|
+
const o = this._sessions.find((h) => h.id === n.id);
|
|
177
177
|
if (o)
|
|
178
|
-
o.data =
|
|
178
|
+
o.data = n, this._application ? o.application = this._application : yield o.loadApplicationInfo(), c.push(o);
|
|
179
179
|
else {
|
|
180
|
-
const
|
|
181
|
-
|
|
180
|
+
const h = yield this.createSession(this.token, n.id, n, this.lazyload, this._application || void 0);
|
|
181
|
+
c.push(h);
|
|
182
182
|
}
|
|
183
183
|
}
|
|
184
|
-
if (
|
|
185
|
-
const
|
|
186
|
-
for (const
|
|
187
|
-
o.set(
|
|
184
|
+
if (i != null && i.pageSize) {
|
|
185
|
+
const n = [...this._sessions, ...c], o = /* @__PURE__ */ new Map();
|
|
186
|
+
for (const h of n)
|
|
187
|
+
o.set(h.id, h);
|
|
188
188
|
return this.sessions = Array.from(o.values()), this.sessions;
|
|
189
189
|
} else
|
|
190
|
-
return this.sessions =
|
|
190
|
+
return this.sessions = c, c;
|
|
191
191
|
}));
|
|
192
192
|
if (this.ready) {
|
|
193
193
|
if (!this._application)
|
|
194
194
|
throw Error("_application is null");
|
|
195
|
-
|
|
195
|
+
e(s());
|
|
196
196
|
} else
|
|
197
197
|
this.event.on("ready", () => {
|
|
198
198
|
if (!this._application)
|
|
199
199
|
throw Error("_application is null");
|
|
200
|
-
|
|
200
|
+
e(s());
|
|
201
201
|
}, !0);
|
|
202
202
|
});
|
|
203
203
|
});
|
|
204
204
|
}
|
|
205
|
-
loadSession(
|
|
205
|
+
loadSession(i = "", e) {
|
|
206
206
|
return l(this, null, function* () {
|
|
207
207
|
this.checkReady();
|
|
208
|
-
let t = this.sessions.find((
|
|
209
|
-
if (t || (t = yield this.createSession(this.token,
|
|
208
|
+
let t = this.sessions.find((s) => s.id === i);
|
|
209
|
+
if (t || (t = yield this.createSession(this.token, i, e), this._sessions.push(t)), this._activeSession) {
|
|
210
210
|
if (this._activeSession === t)
|
|
211
211
|
return t;
|
|
212
212
|
this._activeSession.inactivate();
|
|
@@ -221,54 +221,54 @@ class W {
|
|
|
221
221
|
return yield this.getSessions(), this.event.emit("ready"), this;
|
|
222
222
|
}));
|
|
223
223
|
}
|
|
224
|
-
reloadSession(
|
|
224
|
+
reloadSession(i) {
|
|
225
225
|
return l(this, null, function* () {
|
|
226
226
|
yield this.reload();
|
|
227
|
-
let
|
|
228
|
-
if (!
|
|
227
|
+
let e = this._sessions.find((t) => t.id === i) || this._activeSession;
|
|
228
|
+
if (!e) {
|
|
229
229
|
console.warn("reloadSession session failed.");
|
|
230
230
|
return;
|
|
231
231
|
}
|
|
232
|
-
return yield
|
|
232
|
+
return yield e.reload(), e;
|
|
233
233
|
});
|
|
234
234
|
}
|
|
235
|
-
setTop(
|
|
235
|
+
setTop(i, e, t = "top_time desc, sort_status desc, updated_at desc") {
|
|
236
236
|
return l(this, null, function* () {
|
|
237
|
-
let
|
|
238
|
-
if (!
|
|
237
|
+
let s = i ? this._sessions.find((a) => a.id === i) : this._activeSession;
|
|
238
|
+
if (!s) {
|
|
239
239
|
console.warn("setTop session failed.");
|
|
240
240
|
return;
|
|
241
241
|
}
|
|
242
|
-
return yield
|
|
242
|
+
return yield s.setTop(e), this.getSessions({
|
|
243
243
|
order: t
|
|
244
244
|
});
|
|
245
245
|
});
|
|
246
246
|
}
|
|
247
|
-
addEventListener(
|
|
248
|
-
if (typeof
|
|
247
|
+
addEventListener(i, e, t = !1) {
|
|
248
|
+
if (typeof e != "function")
|
|
249
249
|
throw Error("event listener is not a function");
|
|
250
250
|
if (t) {
|
|
251
|
-
this.event.once(
|
|
251
|
+
this.event.once(i, e);
|
|
252
252
|
return;
|
|
253
253
|
}
|
|
254
|
-
this.event.on(
|
|
254
|
+
this.event.on(i, e);
|
|
255
255
|
}
|
|
256
|
-
removeEventListener(
|
|
257
|
-
this.event.off(
|
|
256
|
+
removeEventListener(i, e) {
|
|
257
|
+
this.event.off(i, e);
|
|
258
258
|
}
|
|
259
|
-
removeSession(
|
|
259
|
+
removeSession(i, e) {
|
|
260
260
|
return l(this, null, function* () {
|
|
261
261
|
this.checkReady();
|
|
262
262
|
let t = -1;
|
|
263
|
-
if (typeof
|
|
264
|
-
const
|
|
265
|
-
|
|
263
|
+
if (typeof i == "string" ? t = this._sessions.findIndex((s) => s.id === i) : t = this._sessions.findIndex((s) => s.id === i.id), t > -1) {
|
|
264
|
+
const s = this._sessions[t];
|
|
265
|
+
e && (yield s.delete()), this._sessions.splice(t, 1);
|
|
266
266
|
} else
|
|
267
267
|
console.warn("session delete failed, session is not exist.");
|
|
268
268
|
});
|
|
269
269
|
}
|
|
270
270
|
clean() {
|
|
271
|
-
this._sessions.forEach((
|
|
271
|
+
this._sessions.forEach((i) => i.destroy()), this.sessions = [];
|
|
272
272
|
}
|
|
273
273
|
}
|
|
274
274
|
export {
|
package/dist/es/Session.mjs
CHANGED
|
@@ -2,30 +2,30 @@ var Q = Object.defineProperty, T = Object.defineProperties;
|
|
|
2
2
|
var M = Object.getOwnPropertyDescriptors;
|
|
3
3
|
var E = Object.getOwnPropertySymbols;
|
|
4
4
|
var O = Object.prototype.hasOwnProperty, R = Object.prototype.propertyIsEnumerable;
|
|
5
|
-
var b = (
|
|
5
|
+
var b = (c, e, t) => e in c ? Q(c, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : c[e] = t, f = (c, e) => {
|
|
6
6
|
for (var t in e || (e = {}))
|
|
7
|
-
O.call(e, t) && b(
|
|
7
|
+
O.call(e, t) && b(c, t, e[t]);
|
|
8
8
|
if (E)
|
|
9
9
|
for (var t of E(e))
|
|
10
|
-
R.call(e, t) && b(
|
|
11
|
-
return
|
|
12
|
-
}, I = (
|
|
13
|
-
var p = (
|
|
14
|
-
var h = (
|
|
10
|
+
R.call(e, t) && b(c, t, e[t]);
|
|
11
|
+
return c;
|
|
12
|
+
}, I = (c, e) => T(c, M(e));
|
|
13
|
+
var p = (c, e, t) => (b(c, typeof e != "symbol" ? e + "" : e, t), t);
|
|
14
|
+
var h = (c, e, t) => new Promise((s, o) => {
|
|
15
15
|
var a = (i) => {
|
|
16
16
|
try {
|
|
17
17
|
r(t.next(i));
|
|
18
|
-
} catch (
|
|
19
|
-
o(
|
|
18
|
+
} catch (l) {
|
|
19
|
+
o(l);
|
|
20
20
|
}
|
|
21
21
|
}, d = (i) => {
|
|
22
22
|
try {
|
|
23
23
|
r(t.throw(i));
|
|
24
|
-
} catch (
|
|
25
|
-
o(
|
|
24
|
+
} catch (l) {
|
|
25
|
+
o(l);
|
|
26
26
|
}
|
|
27
27
|
}, r = (i) => i.done ? s(i.value) : Promise.resolve(i.value).then(a, d);
|
|
28
|
-
r((t = t.apply(
|
|
28
|
+
r((t = t.apply(c, e)).next());
|
|
29
29
|
});
|
|
30
30
|
import { v4 as x } from "uuid";
|
|
31
31
|
import { parseJWT as z, removeNewlines as P, removeLeadingAndTrailingBackslashes as F } from "./utils.mjs";
|
|
@@ -36,7 +36,7 @@ import U from "./EventBus.mjs";
|
|
|
36
36
|
import { getCVForceService as B } from "./api/index.mjs";
|
|
37
37
|
import H from "dayjs";
|
|
38
38
|
const C = 100, u = new q("[Session] ");
|
|
39
|
-
var K = /* @__PURE__ */ ((
|
|
39
|
+
var K = /* @__PURE__ */ ((c) => (c.DataRequestFailed = "data request error", c.SocketConnectionFailed = "socket error", c.IdUndefined = "session id is not defined", c.SendingEmptyContent = "failed at sending empty content", c.Frozen = "session is frozen", c.UserModeError = "failed at setting socket user mode", c.Inactive = "session is inactive", c))(K || {});
|
|
40
40
|
class ee {
|
|
41
41
|
/**
|
|
42
42
|
* Session 类的构造函数,用于初始化会话实例。
|
|
@@ -96,11 +96,11 @@ class ee {
|
|
|
96
96
|
name: i,
|
|
97
97
|
// @ts-ignore
|
|
98
98
|
netOpen: s == null ? void 0 : s.netOpen,
|
|
99
|
-
knowledgeIdList: (r = s == null ? void 0 : s.knowledges) == null ? void 0 : r.map((
|
|
99
|
+
knowledgeIdList: (r = s == null ? void 0 : s.knowledges) == null ? void 0 : r.map((l) => l.id),
|
|
100
100
|
applicationId: this._applicationId
|
|
101
|
-
}).then((
|
|
101
|
+
}).then((l) => h(this, null, function* () {
|
|
102
102
|
var m;
|
|
103
|
-
this._id =
|
|
103
|
+
this._id = l.id, this.data = I(f({}, l), {
|
|
104
104
|
knowledges: s == null ? void 0 : s.knowledges
|
|
105
105
|
}), this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, this._id);
|
|
106
106
|
try {
|
|
@@ -296,10 +296,10 @@ class ee {
|
|
|
296
296
|
};
|
|
297
297
|
if (this._id) {
|
|
298
298
|
e = f(f({}, t), e), this.event.emit("history:loading"), u.log("history:loading"), (e.endTime || e.startTime) && (this.event.emit("history:moreloading", e), u.log("history:moreloading", e)), this._loadingMessages = !0;
|
|
299
|
-
const a = yield this.cvforceApi.getChatHistorySessionId(this._applicationId, this._id, e), d = a.map((i,
|
|
299
|
+
const a = yield this.cvforceApi.getChatHistorySessionId(this._applicationId, this._id, e), d = a.map((i, l) => {
|
|
300
300
|
var v, w;
|
|
301
301
|
let m = [], y;
|
|
302
|
-
return typeof ((v = i.agentHistoryList) == null ? void 0 : v.agentList) == "string" && (m = JSON.parse(i.agentHistoryList.agentList).reduce((n, g) => (n[g.data.step - 1] || (n[g.data.step - 1] = []), n[g.data.step - 1].push(g), n), [])),
|
|
302
|
+
return typeof ((v = i.agentHistoryList) == null ? void 0 : v.agentList) == "string" && (m = JSON.parse(i.agentHistoryList.agentList).reduce((n, g) => (n[g.data.step - 1] || (n[g.data.step - 1] = []), n[g.data.step - 1].push(g), n), [])), l === a.length - 1 && (y = (w = this.data) == null ? void 0 : w.lastRelatedQuestion), I(f({}, i), {
|
|
303
303
|
actions: m,
|
|
304
304
|
relatedQuesion: y
|
|
305
305
|
});
|
|
@@ -308,14 +308,14 @@ class ee {
|
|
|
308
308
|
const i = this.messages[this.messages.length - 1];
|
|
309
309
|
i && !i.relatedQuesion && (i.relatedQuesion = (s = this.data) == null ? void 0 : s.lastRelatedQuestion), this.messages = [...d, ...this.messages];
|
|
310
310
|
} else if (e.endTime && !e.startTime) {
|
|
311
|
-
const i = this.messages.findIndex((
|
|
311
|
+
const i = this.messages.findIndex((l) => l.ts === e.endTime);
|
|
312
312
|
this.messages.splice(0, i + 1), this.messages = [...d, ...this.messages];
|
|
313
313
|
} else if (!e.endTime && e.startTime) {
|
|
314
|
-
const i = this.messages.findLastIndex((
|
|
314
|
+
const i = this.messages.findLastIndex((l) => l.ts === e.endTime);
|
|
315
315
|
this.messages.splice(i, this.messages.length - i - 1), this.messages = [...this.messages, ...d];
|
|
316
316
|
} else {
|
|
317
|
-
const i = this.messages.findIndex((m) => m.ts === e.endTime),
|
|
318
|
-
this.messages.splice(i,
|
|
317
|
+
const i = this.messages.findIndex((m) => m.ts === e.endTime), l = this.messages.findLastIndex((m) => m.ts === e.endTime);
|
|
318
|
+
this.messages.splice(i, l - i + 1, ...d);
|
|
319
319
|
}
|
|
320
320
|
const r = this.messages[this.messages.length - 1];
|
|
321
321
|
return r && !r.relatedQuesion && (r.relatedQuesion = (o = this.data) == null ? void 0 : o.lastRelatedQuestion), this.event.emit("history:moreloaded", d), u.log("history:loaded", this.messages), this.event.emit("history:loaded", this.messages), this._loadingMessages = !1, d;
|
|
@@ -421,8 +421,8 @@ class ee {
|
|
|
421
421
|
const {
|
|
422
422
|
stream: o = A.stream,
|
|
423
423
|
referenceFirst: a = !1
|
|
424
|
-
} = t, d = e.uuid || x(), r = ((_ = e.text) == null ? void 0 : _.trim()) || "", i = e.files || [],
|
|
425
|
-
if (!r && !i.length && !(
|
|
424
|
+
} = t, d = e.uuid || x(), r = ((_ = e.text) == null ? void 0 : _.trim()) || "", i = e.files || [], l = e.fileIds, m = e.imageContent;
|
|
425
|
+
if (!r && !i.length && !(l != null && l.length)) {
|
|
426
426
|
const n = new Error(
|
|
427
427
|
"failed at sending empty content"
|
|
428
428
|
/* SendingEmptyContent */
|
|
@@ -467,7 +467,7 @@ class ee {
|
|
|
467
467
|
content: r,
|
|
468
468
|
stream: o,
|
|
469
469
|
requestId: d,
|
|
470
|
-
fileIds:
|
|
470
|
+
fileIds: l,
|
|
471
471
|
referenceFirst: a,
|
|
472
472
|
imageContent: m
|
|
473
473
|
};
|
|
@@ -648,14 +648,14 @@ class ee {
|
|
|
648
648
|
pluginName: d,
|
|
649
649
|
pluginCode: r,
|
|
650
650
|
funcCode: i,
|
|
651
|
-
funcName:
|
|
651
|
+
funcName: l
|
|
652
652
|
} = a.data;
|
|
653
653
|
o.push({
|
|
654
654
|
data: {
|
|
655
655
|
pluginName: d,
|
|
656
656
|
pluginCode: r,
|
|
657
657
|
funcCode: i,
|
|
658
|
-
funcName:
|
|
658
|
+
funcName: l,
|
|
659
659
|
step: a.data.step + 1
|
|
660
660
|
},
|
|
661
661
|
type: "ABORT"
|
|
@@ -677,7 +677,6 @@ class ee {
|
|
|
677
677
|
* @param targetMessage - 要更新的目标聊天消息对象。
|
|
678
678
|
*/
|
|
679
679
|
handleStreamAnswer(e, t) {
|
|
680
|
-
var d;
|
|
681
680
|
if (!e.data)
|
|
682
681
|
return;
|
|
683
682
|
const s = e.data.type, o = e.data.payload;
|
|
@@ -694,21 +693,21 @@ class ee {
|
|
|
694
693
|
};
|
|
695
694
|
if (s === "error" && (t.index = -1), s === "beforeSearch" && a(), s === "searchOver" && a(), s === "search" && t.searchReference.push(o), s === "thinking") {
|
|
696
695
|
t.thinkingStatus = "start";
|
|
697
|
-
const
|
|
698
|
-
t.reasoningContent = t.reasoningContent
|
|
696
|
+
const r = o.choices[0];
|
|
697
|
+
t.reasoningContent = (t.reasoningContent || "") + r.delta.reasoningContent;
|
|
699
698
|
}
|
|
700
699
|
if (s === "thinkingOver") {
|
|
701
700
|
t.thinkingStatus = "end";
|
|
702
|
-
const
|
|
703
|
-
t.thinkingSecs =
|
|
701
|
+
const d = o.thinkingSecs;
|
|
702
|
+
t.thinkingSecs = d;
|
|
704
703
|
}
|
|
705
704
|
if (s === "text") {
|
|
706
|
-
const
|
|
707
|
-
t.content = t.content +
|
|
705
|
+
const r = o.choices[0];
|
|
706
|
+
t.content = (t.content || "") + r.delta.content;
|
|
708
707
|
}
|
|
709
708
|
if (s === "reference" && (t.reference = o), s === "updateSession" && o && this.data && (this.data = f(f({}, this.data), o), this.event.emit("data:updated", this.data)), s === "result") {
|
|
710
|
-
const
|
|
711
|
-
t.messageId =
|
|
709
|
+
const d = o.messageId, r = o.llmModel, i = o.messageTime;
|
|
710
|
+
t.messageId = d, t.llmModel = r, t.messageTime = i;
|
|
712
711
|
}
|
|
713
712
|
s === "over" ? t.index = -1 : (t.code = e.code, t.message = e.message);
|
|
714
713
|
}
|
package/dist/es/package.json.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e = "@glodon-aiot/bot-client-sdk", t = "3.20.2
|
|
1
|
+
const e = "@glodon-aiot/bot-client-sdk", t = "3.20.2", i = "glodoncv", s = "aiot bot client js sdk", n = "module", y = !1, o = [
|
|
2
2
|
"aiot",
|
|
3
3
|
"bot",
|
|
4
4
|
"bot client",
|
|
@@ -59,7 +59,7 @@ const e = "@glodon-aiot/bot-client-sdk", t = "3.20.2-alpha.1", i = "glodoncv", s
|
|
|
59
59
|
access: "public",
|
|
60
60
|
registry: "https://registry.npmjs.org/"
|
|
61
61
|
}, b = {
|
|
62
|
-
"@glodon-aiot/apis": "^3.20.2
|
|
62
|
+
"@glodon-aiot/apis": "^3.20.2",
|
|
63
63
|
axios: "0.24.0",
|
|
64
64
|
buffer: "^6.0.3",
|
|
65
65
|
dayjs: "^1.11.13",
|
package/dist/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var ie=Object.defineProperty,ne=Object.defineProperties;var ae=Object.getOwnPropertyDescriptors;var E=Object.getOwnPropertySymbols;var q=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var Q=(c,e,t)=>e in c?ie(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t,g=(c,e)=>{for(var t in e||(e={}))q.call(e,t)&&Q(c,t,e[t]);if(E)for(var t of E(e))B.call(e,t)&&Q(c,t,e[t]);return c},w=(c,e)=>ne(c,ae(e));var J=(c,e)=>{var t={};for(var s in c)q.call(c,s)&&e.indexOf(s)<0&&(t[s]=c[s]);if(c!=null&&E)for(var s of E(c))e.indexOf(s)<0&&B.call(c,s)&&(t[s]=c[s]);return t};var m=(c,e,t)=>(Q(c,typeof e!="symbol"?e+"":e,t),t);var p=(c,e,t)=>new Promise((s,r)=>{var a=n=>{try{o(t.next(n))}catch(d){r(d)}},i=n=>{try{o(t.throw(n))}catch(d){r(d)}},o=n=>n.done?s(n.value):Promise.resolve(n.value).then(a,i);o((t=t.apply(c,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const re=require("js-base64"),oe=require("axios"),y=require("@glodon-aiot/apis"),ce=require("socket.io-client"),Y=require("uuid"),j=require("dayjs"),M=class M{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!M.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!M.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!M.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!M.debug||console.warn(this.prefix,...e)}};m(M,"debug",!1);let S=M;const de=new S("[Config] ");var X=(c=>(c.dev="https://aiot-dev.glodon.com/api/cvforcepd",c.test="https://aiot-dev.glodon.com/api/cvforce",c.prod="https://copilot.glodon.com/api/cvforce",c.local="http://localhost:3000/api/cvforcepd",c))(X||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function z(c){S.debug=(c==null?void 0:c.debug)||!1,exports.configuration=w(g(g({},exports.configuration),c),{apiRoot:(c==null?void 0:c.apiRoot)||exports.configuration.apiRoot||(c!=null&&c.env?X[c.env||"prod"]:exports.configuration.apiRoot)}),S.debug&&de.log("updated",exports.configuration)}const V=c=>JSON.parse(re.decode(c.split(".")[1])),he=c=>{const e=V(c).exp;return new Date().valueOf()/1e3>=e},le=c=>c==null?void 0:c.replace(/[\r\n]+/gm,""),fe=c=>c.replace(/\\|\\/g,"");function Z(c,e,t){const s=d=>{var f;return e&&(he(e)&&t(403,"aiotToken is timeout"),d.headers=(f=d.headers)!=null?f:{},d.headers=w(g({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function r(d,f=!0){const h=`${c}${d}`,u=oe.create({baseURL:h});return f&&u.interceptors.request.use(s),u}const a=(d,f)=>{d===401&&t(d,"aiotToken is invalid")},i=(d,f)=>{d!==10001&&d!==10215&&t(d,f)},o=r("/data/v1");return new y.CVForceApi(o,{onHttpStatusError:a,onAppStatusError:i})}var x=(c=>(c[c.Normal=0]="Normal",c[c.Debug=1]="Debug",c))(x||{});const R=new S("[EventBus] ");class ee{constructor(e=!1){m(this,"eventListenerMap",{});e&&R.disable()}getEventListenerMap(){return g({},this.eventListenerMap)}on(e,t,s=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),s?this.eventListenerMap[e].push({fn:t,once:!0}):this.eventListenerMap[e].push(t),R.log(`add event ${e} listener ${s?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const s=this.eventListenerMap[e].findIndex(r=>{if(typeof r=="function"&&t===r)return!0;if(r=r,r.fn===t)return!0});s<0?R.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),R.log(`remove event ${e} listener`))}else R.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){R.log(`event ${e} listeners is empty`);return}const s=[];for(let r=0;r<this.eventListenerMap[e].length;r++){const a=this.eventListenerMap[e][r];typeof a=="function"?a(t):s.push(a)}s.forEach(r=>{r&&(r.fn(t),this.off(e,r.fn))}),R.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const U=100,b=new S("[Session] ");var L=(c=>(c.DataRequestFailed="data request error",c.SocketConnectionFailed="socket error",c.IdUndefined="session id is not defined",c.SendingEmptyContent="failed at sending empty content",c.Frozen="session is frozen",c.UserModeError="failed at setting socket user mode",c.Inactive="session is inactive",c))(L||{});class D{constructor(e,t="",s,r,a,i){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new ee);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);m(this,"_mcpServers",null);this.token=e,this.lazyload=r,this.client=i||null,this._applicationId=V(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),a&&(this._application=a),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var o;if(t)this._id=t,this.event.emit("data:loading"),s?(this.data=s,r||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(n=>p(this,null,function*(){this.data=n,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data)})))):(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(n=>p(this,null,function*(){this.data=n,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoading=!1,this._dataLoaded=!0})));else{const n=(s==null?void 0:s.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:n}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:n,netOpen:s==null?void 0:s.netOpen,knowledgeIdList:(o=s==null?void 0:s.knowledges)==null?void 0:o.map(d=>d.id),applicationId:this._applicationId}).then(d=>p(this,null,function*(){var f;this._id=d.id,this.data=w(g({},d),{knowledges:s==null?void 0:s.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id);try{yield(()=>p(this,null,function*(){if(s!=null&&s.knowledges)return this.setKnowledges((s==null?void 0:s.knowledges)||void 0)}))()}catch(h){b.error(h)}yield(()=>{if(s!=null&&s.promptVariables){const h=this._promptVariables.map(u=>{var I,l;const v=((l=(I=s.promptVariables)==null?void 0:I.find(_=>_.key===u.key&&_.type===u.type))==null?void 0:l.value)||"";return w(g({},u),{value:v})}).sort((u,v)=>u.key.localeCompare(v.key));return this.setPromptVariables(h||[])}else return})(),this.event.emit("data:created",this.data),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),((f=this.application)==null?void 0:f.type)!==y.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}fetchData(){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.getSession(this.applicationId,this.data.id).then(e=>p(this,null,function*(){return this.data=e,this.event.emit("data:updated",this.data),e}))})}get id(){var e;return this._id||((e=this.data)==null?void 0:e.id)||""}get applicationId(){return this._applicationId}get application(){return this._application}set application(e){this._application=e}loadApplicationInfo(){if(this._application)return Promise.resolve(this._application);if(this._applicationId&&!this._application)return this.event.emit("application:data:loading"),this.cvforceApi.getApplicationId(this._applicationId).then(e=>(this._application=e,this.event.emit("application:data:loaded",e),e));throw Error("application id is not defined")}get ready(){return this._ready}get frozen(){return this._frozen}set frozen(e){e===!1&&this.inactivating&&this.socket&&(this.socket.disconnect(),this.socket=null,this.event.emit("inactivated")),this._frozen=e,this.event.emit("frozen",e)}get knowledges(){if(!this.data)throw Error("session data is not loaded");return this.data.knowledges||void 0}setKnowledges(e){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");if((e||[]).some(r=>Array.isArray(r.fileIds)&&r.fileIds.length===0))throw Error("fileIds cannot be an empty array");if((e||[]).reduce((r,a)=>{var o,n;const i=(n=(o=a.fileIds)==null?void 0:o.length)!=null?n:0;return r+(i>0?i:1)},0)>U)throw Error(`knowledges and fileIds total count cannot exceed ${U}`);return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(t=>t.status===y.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>!(e.type===y.PromptVariableType.User&&e.key==="query")&&!(e.type===y.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return p(this,null,function*(){const t=e==null?void 0:e.map(a=>a.type?a:w(g({},a),{type:"instruction"})),s=this._promptVariables.map(a=>{var o;const i=((o=t==null?void 0:t.find(n=>n.key===a.key&&n.type===a.type))==null?void 0:o.value)||a.value;return w(g({},a),{value:i})}).sort((a,i)=>a.key.localeCompare(i.key));if(!(yield Promise.all(s.filter(a=>!(a.type===y.PromptVariableType.User&&a.key==="query")&&!(a.type===y.PromptVariableType.System&&a.key==="datetime")).map(a=>{if(!this.data)throw Error("session data is not loaded");if(!(!a.id||!a.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,a.id,{value:a.value})})).then(()=>!0).catch(a=>!1)))return!1;if(!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return p(this,null,function*(){var t,s,r;if(b.log("setNetOpen:",e),b.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===y.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((r=this._application)==null?void 0:r.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,b.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return Z(exports.configuration.apiRoot,this.token,(e,t)=>{const s=new Error("data request error",{cause:{status:e,message:t}});b.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,r;const t={pageSize:this._loadingMessagesSize};if(this._id){e=g(g({},t),e),this.event.emit("history:loading"),b.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),b.log("history:moreloading",e)),this._loadingMessages=!0;const a=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),i=a.map((n,d)=>{var u,v;let f=[],h;return typeof((u=n.agentHistoryList)==null?void 0:u.agentList)=="string"&&(f=JSON.parse(n.agentHistoryList.agentList).reduce((l,_)=>(l[_.data.step-1]||(l[_.data.step-1]=[]),l[_.data.step-1].push(_),l),[])),d===a.length-1&&(h=(v=this.data)==null?void 0:v.lastRelatedQuestion),w(g({},n),{actions:f,relatedQuesion:h})});if(!e.endTime&&!e.startTime){const n=this.messages[this.messages.length-1];n&&!n.relatedQuesion&&(n.relatedQuesion=(s=this.data)==null?void 0:s.lastRelatedQuestion),this.messages=[...i,...this.messages]}else if(e.endTime&&!e.startTime){const n=this.messages.findIndex(d=>d.ts===e.endTime);this.messages.splice(0,n+1),this.messages=[...i,...this.messages]}else if(!e.endTime&&e.startTime){const n=this.messages.findLastIndex(d=>d.ts===e.endTime);this.messages.splice(n,this.messages.length-n-1),this.messages=[...this.messages,...i]}else{const n=this.messages.findIndex(f=>f.ts===e.endTime),d=this.messages.findLastIndex(f=>f.ts===e.endTime);this.messages.splice(n,d-n+1,...i)}const o=this.messages[this.messages.length-1];return o&&!o.relatedQuesion&&(o.relatedQuesion=(r=this.data)==null?void 0:r.lastRelatedQuestion),this.event.emit("history:moreloaded",i),b.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,i}else{const a=new Error("session id is not defined");return b.error(a),this.event.emit("error",a),!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}),b.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),b.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),b.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 b.error(e),this.event.emit("error",e),!1}return this.event.emit("data:deleting"),yield this.cvforceApi.delSessionsId(this.applicationId,this.id),this.event.emit("data:deleted"),this.destroy()})}activate(){return p(this,null,function*(){if(this.activing)return new Promise(t=>{this.addEventListener("activated",()=>{t(!0)},!0)});if(!this._id)throw Error("session is not avalible. id is undefined");this.activing=!0;const e=this._id;return this._dataLoading=!0,this._dataLoaded=!1,this.data=yield this.cvforceApi.getSession(this.applicationId,e).then(t=>p(this,null,function*(){return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,e),t})),this.messages.length||(this.messages=[],yield this.fetchMessages()),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoaded=!0,this._dataLoading=!1,this.inactivating=!1,this.frozen=!0,yield this.prepareConnection(),this.event.emit("activated",this.socket),this.active=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?this._frozen?(e||(this.inactivating=!0),this.activing=!1,!0):(this.socket.close(),this.socket=null,this.event.emit("inactivated"),this.active=!1,this.activing=!1,!0):(this.activing=!1,!0)}get dataLoaded(){return this._dataLoaded}get messagesLoading(){return this._loadingMessages}send(s){return p(this,arguments,function*(e,t={stream:exports.configuration.stream}){var I;try{this.validateConfigs()}catch(l){console.error(l)}const{stream:r=exports.configuration.stream,referenceFirst:a=!1}=t,i=e.uuid||Y.v4(),o=((I=e.text)==null?void 0:I.trim())||"",n=e.files||[],d=e.fileIds,f=e.imageContent;if(!o&&!n.length&&!(d!=null&&d.length)){const l=new Error("failed at sending empty content");return b.error(l),this.event.emit("error",l),!1}if(!this._id){const l=new Error("session id is not defined");return b.error(l),this.event.emit("error",l),!1}if(this.frozen){const l=new Error("session is frozen");return b.error(l),this.event.emit("error",l),!1}this.frozen=!0,this._stopAnswer=!1;const h={sessionId:this.id,role:2,content:o,messageId:i,reference:[],searchReference:[],messageTime:"",files:n,imageContent:f},u={content:o,stream:r,requestId:i,fileIds:d,referenceFirst:a,imageContent:f};this.pushMessage(h),this.event.emit("question:content",o);const v=l=>p(this,null,function*(){if(l.role!==y.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",v),this._id&&l.content&&l.index&&l.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:l.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:l.content})),yield this.fillMessageReference(l),l.code){case 11915:l.content="请您换个问题问我吧~",l.index=-1,l.isSensitive=!0,l.isLoading=!1,l.sessionId=this._id||"",this.event.emit("message:error",l);break;case 11916:l.content="尊敬的用户您好,让我们换个话题再聊聊吧。",l.index=-1,l.isSensitive=!0,l.isLoading=!1,l.sessionId=this._id||"",this.event.emit("message:error",l);break;case 200:l.index=-1,l.isLoading=!1;break;default:l.content=l.message||"未知错误",l.isLoading=!1,l.index=-1,this.event.emit("message:error",l)}this.getRelatedQuesion(l),l.isLoading=!1;let _=this.messages[this.messages.length-1];if(_&&_.role===y.ChatMessageRole.Robot){const C=g(g({},_),l);this.messages[this.messages.length-1]=C,this.event.emit("message:updated",C)}else this.pushMessage(l);this.frozen=!1});return this.addEventListener("answer:finish",v),this.sendQuestion(u,w(g({},t),{stream:r,referenceFirst:a})),h})}getRelatedQuesion(e){return p(this,null,function*(){var a,i;if(!e.content||e.isSensitive||e.code!==200||!((a=this.application)!=null&&a.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const t=yield this.cvforceApi.postGeneques({content:e.content}).catch(o=>null);if(!t){const o=[],n=w(g({},e),{relatedQuesion:o,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:o}),this.event.emit("message:updated",n),n}const s=(i=t.content)==null?void 0:i.split("*").map(le).map(fe).filter(o=>!!o);e.relatedQuesion=s,e.index=-3,e.isLoading=!1;const r=w(g({},e),{relatedQuesion:s,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",r),this.event.emit("message:updated",r),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:s}),r})}fillMessageReference(e){return p(this,null,function*(){try{const t=yield Promise.all(e.reference.map(s=>this.cvforceApi.getKnowledgeIdFileId(s.knowledgeId,s.docId)));e.reference=e.reference.map((s,r)=>g(g({},s),t[r]))}catch(t){console.error("Failed to fill message reference:",t)}return this.event.emit("message:updated",e),e})}answerAgain(){return p(this,arguments,function*(e={stream:exports.configuration.stream}){const t=this.messages[this.messages.length-1];if(!t)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1;const{stream:s=exports.configuration.stream}=e;let r;t.role!==y.ChatMessageRole.User&&(r=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 a=this.messages[this.messages.length-1],i={content:a.content,fileIds:a.fileIds,requestId:a.messageId,stream:s,oldMessageId:r},o=n=>p(this,null,function*(){if(n.role===y.ChatMessageRole.Robot&&n.index===-1){switch(this._id&&n.content&&n.index&&n.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:n.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:n.content})),yield this.fillMessageReference(n),n.code){case 11915:n.content="请您换个问题问我吧~",n.index=-1,n.isSensitive=!0,n.isLoading=!1,n.sessionId=this._id||"",this.event.emit("message:error",n);break;case 11916:n.content="尊敬的用户您好,让我们换个话题再聊聊吧。",n.index=-1,n.isSensitive=!0,n.isLoading=!1,n.sessionId=this._id||"",this.event.emit("message:error",n);break;case 200:n.index=-1,n.isLoading=!1;break;default:n.content=n.message||"未知错误",n.isLoading=!1,n.index=-1,this.event.emit("message:error",n)}this.getRelatedQuesion(n),this.removeEventListener("message:content",o),this.frozen=!1}});this.addEventListener("message:content",o),this.sendQuestion(i,w(g({},e),{stream:s}))})}setTop(e){return p(this,null,function*(){if(!this._id)throw Error("session is not avalible. id is undefined");this.data=yield this.cvforceApi.patchSessionsId(this._applicationId,this._id,{top:e}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:top",{top:e})})}suspend(){var s;this.stopAnswer(),this.frozen=!1,this._stopAnswer=!0;let e=this.messages[this.messages.length-1];const t={messageId:Y.v4(),isLoading:!1,index:-2,messageTime:j(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:y.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const r=e.actions[((s=e.actions)==null?void 0:s.length)-1];if(r){const a=r[r.length-1];if(a&&(a.type==="BEFORE_CALL"||a.type==="FUNCTION_CALL")){const{pluginName:i,pluginCode:o,funcCode:n,funcName:d}=a.data;r.push({data:{pluginName:i,pluginCode:o,funcCode:n,funcName:d,step:a.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:r})}}}e=g(g({},e),t),this.event.emit("message:content",e),this.event.emit("message:updated",e)}else this.pushMessage(t),this.event.emit("message:content",t);return this}handleStreamAnswer(e,t){var i;if(!e.data)return;const s=e.data.type,r=e.data.payload;t.isReplying=!0;const a=()=>{if(!t.searchingStatus){t.searchingStatus="start";return}if(t.searchingStatus==="start"){t.searchingStatus="end";return}};if(s==="error"&&(t.index=-1),s==="beforeSearch"&&a(),s==="searchOver"&&a(),s==="search"&&t.searchReference.push(r),s==="thinking"){t.thinkingStatus="start";const n=r.choices[0];t.reasoningContent=t.reasoningContent+((i=n.delta.reasoningContent)!=null?i:"")}if(s==="thinkingOver"){t.thinkingStatus="end";const o=r.thinkingSecs;t.thinkingSecs=o}if(s==="text"){const n=r.choices[0];t.content=t.content+n.delta.content}if(s==="reference"&&(t.reference=r),s==="updateSession"&&r&&this.data&&(this.data=g(g({},this.data),r),this.event.emit("data:updated",this.data)),s==="result"){const o=r.messageId,n=r.llmModel,d=r.messageTime;t.messageId=o,t.llmModel=n,t.messageTime=d}s==="over"?t.index=-1:(t.code=e.code,t.message=e.message)}postMessageComment(e){return p(this,null,function*(){if(!this._applicationId||!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.postComments(this._applicationId,this._id,e).then(t=>{const s=this.messages.find(r=>r.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 pe extends D{constructor(e,t="",s,r,a,i){super(e,t,s,r,a,i)}prepareConnection(){return new Promise(e=>p(this,null,function*(){this.socket&&e(!0);const t={version:"1.0",stream:JSON.stringify(exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?x.Debug:x.Normal},s=new URL(exports.configuration.apiRoot),r=yield ce.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});r.on("connect",()=>{k.log("socket:connect"),this.event.emit("socket:connect"),r.emit("init")}),r.on("disconnect",()=>{k.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),r.on("ready",a=>{if(a.code===200){k.log("ready");const i=exports.configuration.debug?x.Debug:x.Normal;i===x.Debug&&a.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const i=new Error(L.SocketConnectionFailed);k.error("error",i),this.event.emit("error",i),e(!1)}}),r.on("action",(a,i)=>p(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:o,data:{runnerIsClient:n,pluginCode:d,funcCode:f,parameters:h,requestBody:u}}=a,v=this.messages[this.messages.length-1];if(!v.messageId)v.actions||(v.actions=[]),v.actions[a.data.step-1]||(v.actions[a.data.step-1]=[]),v.actions[a.data.step-1].push(a),this.event.emit("message:action",{messageId:v.messageId,action:a}),this.event.emit("message:updated",v);else{const I={messageId:"",content:"",role:y.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[a]],comment:{isAgree:0},isReplying:!0};this.pushMessage(I),this.event.emit("message:action",{messageId:I.messageId,action:a})}if(this.inactivating){const I=new Error(L.Inactive);k.warn("error",I),this.event.emit("error",I)}else if(o==="FUNCTION_CALL"&&n){if(k.log(`calling function ${f} of plugin ${d} with argument:
|
|
2
|
-
${JSON.stringify(h)}`),!exports.configuration.plugins[d]){i({code:404,message:"对不起,没有找到插件。"});return}const I=exports.configuration.plugins[d][
|
|
1
|
+
"use strict";var ie=Object.defineProperty,ne=Object.defineProperties;var ae=Object.getOwnPropertyDescriptors;var E=Object.getOwnPropertySymbols;var q=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var Q=(c,e,t)=>e in c?ie(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t,g=(c,e)=>{for(var t in e||(e={}))q.call(e,t)&&Q(c,t,e[t]);if(E)for(var t of E(e))B.call(e,t)&&Q(c,t,e[t]);return c},w=(c,e)=>ne(c,ae(e));var J=(c,e)=>{var t={};for(var s in c)q.call(c,s)&&e.indexOf(s)<0&&(t[s]=c[s]);if(c!=null&&E)for(var s of E(c))e.indexOf(s)<0&&B.call(c,s)&&(t[s]=c[s]);return t};var m=(c,e,t)=>(Q(c,typeof e!="symbol"?e+"":e,t),t);var f=(c,e,t)=>new Promise((s,r)=>{var a=n=>{try{o(t.next(n))}catch(d){r(d)}},i=n=>{try{o(t.throw(n))}catch(d){r(d)}},o=n=>n.done?s(n.value):Promise.resolve(n.value).then(a,i);o((t=t.apply(c,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const re=require("js-base64"),oe=require("axios"),y=require("@glodon-aiot/apis"),ce=require("socket.io-client"),Y=require("uuid"),j=require("dayjs"),M=class M{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!M.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!M.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!M.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!M.debug||console.warn(this.prefix,...e)}};m(M,"debug",!1);let S=M;const de=new S("[Config] ");var X=(c=>(c.dev="https://aiot-dev.glodon.com/api/cvforcepd",c.test="https://aiot-dev.glodon.com/api/cvforce",c.prod="https://copilot.glodon.com/api/cvforce",c.local="http://localhost:3000/api/cvforcepd",c))(X||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function z(c){S.debug=(c==null?void 0:c.debug)||!1,exports.configuration=w(g(g({},exports.configuration),c),{apiRoot:(c==null?void 0:c.apiRoot)||exports.configuration.apiRoot||(c!=null&&c.env?X[c.env||"prod"]:exports.configuration.apiRoot)}),S.debug&&de.log("updated",exports.configuration)}const V=c=>JSON.parse(re.decode(c.split(".")[1])),he=c=>{const e=V(c).exp;return new Date().valueOf()/1e3>=e},le=c=>c==null?void 0:c.replace(/[\r\n]+/gm,""),pe=c=>c.replace(/\\|\\/g,"");function Z(c,e,t){const s=d=>{var p;return e&&(he(e)&&t(403,"aiotToken is timeout"),d.headers=(p=d.headers)!=null?p:{},d.headers=w(g({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function r(d,p=!0){const h=`${c}${d}`,u=oe.create({baseURL:h});return p&&u.interceptors.request.use(s),u}const a=(d,p)=>{d===401&&t(d,"aiotToken is invalid")},i=(d,p)=>{d!==10001&&d!==10215&&t(d,p)},o=r("/data/v1");return new y.CVForceApi(o,{onHttpStatusError:a,onAppStatusError:i})}var x=(c=>(c[c.Normal=0]="Normal",c[c.Debug=1]="Debug",c))(x||{});const R=new S("[EventBus] ");class ee{constructor(e=!1){m(this,"eventListenerMap",{});e&&R.disable()}getEventListenerMap(){return g({},this.eventListenerMap)}on(e,t,s=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),s?this.eventListenerMap[e].push({fn:t,once:!0}):this.eventListenerMap[e].push(t),R.log(`add event ${e} listener ${s?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const s=this.eventListenerMap[e].findIndex(r=>{if(typeof r=="function"&&t===r)return!0;if(r=r,r.fn===t)return!0});s<0?R.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),R.log(`remove event ${e} listener`))}else R.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){R.log(`event ${e} listeners is empty`);return}const s=[];for(let r=0;r<this.eventListenerMap[e].length;r++){const a=this.eventListenerMap[e][r];typeof a=="function"?a(t):s.push(a)}s.forEach(r=>{r&&(r.fn(t),this.off(e,r.fn))}),R.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const U=100,b=new S("[Session] ");var L=(c=>(c.DataRequestFailed="data request error",c.SocketConnectionFailed="socket error",c.IdUndefined="session id is not defined",c.SendingEmptyContent="failed at sending empty content",c.Frozen="session is frozen",c.UserModeError="failed at setting socket user mode",c.Inactive="session is inactive",c))(L||{});class D{constructor(e,t="",s,r,a,i){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new ee);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);m(this,"_mcpServers",null);this.token=e,this.lazyload=r,this.client=i||null,this._applicationId=V(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),a&&(this._application=a),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var o;if(t)this._id=t,this.event.emit("data:loading"),s?(this.data=s,r||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(n=>f(this,null,function*(){this.data=n,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>f(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data)})))):(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(n=>f(this,null,function*(){this.data=n,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>f(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoading=!1,this._dataLoaded=!0})));else{const n=(s==null?void 0:s.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:n}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:n,netOpen:s==null?void 0:s.netOpen,knowledgeIdList:(o=s==null?void 0:s.knowledges)==null?void 0:o.map(d=>d.id),applicationId:this._applicationId}).then(d=>f(this,null,function*(){var p;this._id=d.id,this.data=w(g({},d),{knowledges:s==null?void 0:s.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id);try{yield(()=>f(this,null,function*(){if(s!=null&&s.knowledges)return this.setKnowledges((s==null?void 0:s.knowledges)||void 0)}))()}catch(h){b.error(h)}yield(()=>{if(s!=null&&s.promptVariables){const h=this._promptVariables.map(u=>{var I,l;const v=((l=(I=s.promptVariables)==null?void 0:I.find(_=>_.key===u.key&&_.type===u.type))==null?void 0:l.value)||"";return w(g({},u),{value:v})}).sort((u,v)=>u.key.localeCompare(v.key));return this.setPromptVariables(h||[])}else return})(),this.event.emit("data:created",this.data),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),((p=this.application)==null?void 0:p.type)!==y.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}fetchData(){return f(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=>f(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 f(this,null,function*(){if(!this.data)throw Error("session data is not loaded");if((e||[]).some(r=>Array.isArray(r.fileIds)&&r.fileIds.length===0))throw Error("fileIds cannot be an empty array");if((e||[]).reduce((r,a)=>{var o,n;const i=(n=(o=a.fileIds)==null?void 0:o.length)!=null?n:0;return r+(i>0?i:1)},0)>U)throw Error(`knowledges and fileIds total count cannot exceed ${U}`);return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(t=>t.status===y.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>!(e.type===y.PromptVariableType.User&&e.key==="query")&&!(e.type===y.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return f(this,null,function*(){const t=e==null?void 0:e.map(a=>a.type?a:w(g({},a),{type:"instruction"})),s=this._promptVariables.map(a=>{var o;const i=((o=t==null?void 0:t.find(n=>n.key===a.key&&n.type===a.type))==null?void 0:o.value)||a.value;return w(g({},a),{value:i})}).sort((a,i)=>a.key.localeCompare(i.key));if(!(yield Promise.all(s.filter(a=>!(a.type===y.PromptVariableType.User&&a.key==="query")&&!(a.type===y.PromptVariableType.System&&a.key==="datetime")).map(a=>{if(!this.data)throw Error("session data is not loaded");if(!(!a.id||!a.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,a.id,{value:a.value})})).then(()=>!0).catch(a=>!1)))return!1;if(!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return f(this,null,function*(){var t,s,r;if(b.log("setNetOpen:",e),b.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===y.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((r=this._application)==null?void 0:r.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,b.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return Z(exports.configuration.apiRoot,this.token,(e,t)=>{const s=new Error("data request error",{cause:{status:e,message:t}});b.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 f(this,arguments,function*(e={}){var s,r;const t={pageSize:this._loadingMessagesSize};if(this._id){e=g(g({},t),e),this.event.emit("history:loading"),b.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),b.log("history:moreloading",e)),this._loadingMessages=!0;const a=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),i=a.map((n,d)=>{var u,v;let p=[],h;return typeof((u=n.agentHistoryList)==null?void 0:u.agentList)=="string"&&(p=JSON.parse(n.agentHistoryList.agentList).reduce((l,_)=>(l[_.data.step-1]||(l[_.data.step-1]=[]),l[_.data.step-1].push(_),l),[])),d===a.length-1&&(h=(v=this.data)==null?void 0:v.lastRelatedQuestion),w(g({},n),{actions:p,relatedQuesion:h})});if(!e.endTime&&!e.startTime){const n=this.messages[this.messages.length-1];n&&!n.relatedQuesion&&(n.relatedQuesion=(s=this.data)==null?void 0:s.lastRelatedQuestion),this.messages=[...i,...this.messages]}else if(e.endTime&&!e.startTime){const n=this.messages.findIndex(d=>d.ts===e.endTime);this.messages.splice(0,n+1),this.messages=[...i,...this.messages]}else if(!e.endTime&&e.startTime){const n=this.messages.findLastIndex(d=>d.ts===e.endTime);this.messages.splice(n,this.messages.length-n-1),this.messages=[...this.messages,...i]}else{const n=this.messages.findIndex(p=>p.ts===e.endTime),d=this.messages.findLastIndex(p=>p.ts===e.endTime);this.messages.splice(n,d-n+1,...i)}const o=this.messages[this.messages.length-1];return o&&!o.relatedQuesion&&(o.relatedQuesion=(r=this.data)==null?void 0:r.lastRelatedQuestion),this.event.emit("history:moreloaded",i),b.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,i}else{const a=new Error("session id is not defined");return b.error(a),this.event.emit("error",a),!1}})}rename(e){return f(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}),b.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return f(this,null,function*(){this.messages.push(e),b.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=>f(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),b.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>f(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 f(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return f(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return b.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 f(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=>f(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 f(this,arguments,function*(e,t={stream:exports.configuration.stream}){var I;try{this.validateConfigs()}catch(l){console.error(l)}const{stream:r=exports.configuration.stream,referenceFirst:a=!1}=t,i=e.uuid||Y.v4(),o=((I=e.text)==null?void 0:I.trim())||"",n=e.files||[],d=e.fileIds,p=e.imageContent;if(!o&&!n.length&&!(d!=null&&d.length)){const l=new Error("failed at sending empty content");return b.error(l),this.event.emit("error",l),!1}if(!this._id){const l=new Error("session id is not defined");return b.error(l),this.event.emit("error",l),!1}if(this.frozen){const l=new Error("session is frozen");return b.error(l),this.event.emit("error",l),!1}this.frozen=!0,this._stopAnswer=!1;const h={sessionId:this.id,role:2,content:o,messageId:i,reference:[],searchReference:[],messageTime:"",files:n,imageContent:p},u={content:o,stream:r,requestId:i,fileIds:d,referenceFirst:a,imageContent:p};this.pushMessage(h),this.event.emit("question:content",o);const v=l=>f(this,null,function*(){if(l.role!==y.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",v),this._id&&l.content&&l.index&&l.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:l.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:l.content})),yield this.fillMessageReference(l),l.code){case 11915:l.content="请您换个问题问我吧~",l.index=-1,l.isSensitive=!0,l.isLoading=!1,l.sessionId=this._id||"",this.event.emit("message:error",l);break;case 11916:l.content="尊敬的用户您好,让我们换个话题再聊聊吧。",l.index=-1,l.isSensitive=!0,l.isLoading=!1,l.sessionId=this._id||"",this.event.emit("message:error",l);break;case 200:l.index=-1,l.isLoading=!1;break;default:l.content=l.message||"未知错误",l.isLoading=!1,l.index=-1,this.event.emit("message:error",l)}this.getRelatedQuesion(l),l.isLoading=!1;let _=this.messages[this.messages.length-1];if(_&&_.role===y.ChatMessageRole.Robot){const C=g(g({},_),l);this.messages[this.messages.length-1]=C,this.event.emit("message:updated",C)}else this.pushMessage(l);this.frozen=!1});return this.addEventListener("answer:finish",v),this.sendQuestion(u,w(g({},t),{stream:r,referenceFirst:a})),h})}getRelatedQuesion(e){return f(this,null,function*(){var a,i;if(!e.content||e.isSensitive||e.code!==200||!((a=this.application)!=null&&a.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const t=yield this.cvforceApi.postGeneques({content:e.content}).catch(o=>null);if(!t){const o=[],n=w(g({},e),{relatedQuesion:o,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:o}),this.event.emit("message:updated",n),n}const s=(i=t.content)==null?void 0:i.split("*").map(le).map(pe).filter(o=>!!o);e.relatedQuesion=s,e.index=-3,e.isLoading=!1;const r=w(g({},e),{relatedQuesion:s,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",r),this.event.emit("message:updated",r),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:s}),r})}fillMessageReference(e){return f(this,null,function*(){try{const t=yield Promise.all(e.reference.map(s=>this.cvforceApi.getKnowledgeIdFileId(s.knowledgeId,s.docId)));e.reference=e.reference.map((s,r)=>g(g({},s),t[r]))}catch(t){console.error("Failed to fill message reference:",t)}return this.event.emit("message:updated",e),e})}answerAgain(){return f(this,arguments,function*(e={stream:exports.configuration.stream}){const t=this.messages[this.messages.length-1];if(!t)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1;const{stream:s=exports.configuration.stream}=e;let r;t.role!==y.ChatMessageRole.User&&(r=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 a=this.messages[this.messages.length-1],i={content:a.content,fileIds:a.fileIds,requestId:a.messageId,stream:s,oldMessageId:r},o=n=>f(this,null,function*(){if(n.role===y.ChatMessageRole.Robot&&n.index===-1){switch(this._id&&n.content&&n.index&&n.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:n.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:n.content})),yield this.fillMessageReference(n),n.code){case 11915:n.content="请您换个问题问我吧~",n.index=-1,n.isSensitive=!0,n.isLoading=!1,n.sessionId=this._id||"",this.event.emit("message:error",n);break;case 11916:n.content="尊敬的用户您好,让我们换个话题再聊聊吧。",n.index=-1,n.isSensitive=!0,n.isLoading=!1,n.sessionId=this._id||"",this.event.emit("message:error",n);break;case 200:n.index=-1,n.isLoading=!1;break;default:n.content=n.message||"未知错误",n.isLoading=!1,n.index=-1,this.event.emit("message:error",n)}this.getRelatedQuesion(n),this.removeEventListener("message:content",o),this.frozen=!1}});this.addEventListener("message:content",o),this.sendQuestion(i,w(g({},e),{stream:s}))})}setTop(e){return f(this,null,function*(){if(!this._id)throw Error("session is not avalible. id is undefined");this.data=yield this.cvforceApi.patchSessionsId(this._applicationId,this._id,{top:e}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:top",{top:e})})}suspend(){var s;this.stopAnswer(),this.frozen=!1,this._stopAnswer=!0;let e=this.messages[this.messages.length-1];const t={messageId:Y.v4(),isLoading:!1,index:-2,messageTime:j(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:y.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const r=e.actions[((s=e.actions)==null?void 0:s.length)-1];if(r){const a=r[r.length-1];if(a&&(a.type==="BEFORE_CALL"||a.type==="FUNCTION_CALL")){const{pluginName:i,pluginCode:o,funcCode:n,funcName:d}=a.data;r.push({data:{pluginName:i,pluginCode:o,funcCode:n,funcName:d,step:a.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:r})}}}e=g(g({},e),t),this.event.emit("message:content",e),this.event.emit("message:updated",e)}else this.pushMessage(t),this.event.emit("message:content",t);return this}handleStreamAnswer(e,t){if(!e.data)return;const s=e.data.type,r=e.data.payload;t.isReplying=!0;const a=()=>{if(!t.searchingStatus){t.searchingStatus="start";return}if(t.searchingStatus==="start"){t.searchingStatus="end";return}};if(s==="error"&&(t.index=-1),s==="beforeSearch"&&a(),s==="searchOver"&&a(),s==="search"&&t.searchReference.push(r),s==="thinking"){t.thinkingStatus="start";const o=r.choices[0];t.reasoningContent=(t.reasoningContent||"")+o.delta.reasoningContent}if(s==="thinkingOver"){t.thinkingStatus="end";const i=r.thinkingSecs;t.thinkingSecs=i}if(s==="text"){const o=r.choices[0];t.content=(t.content||"")+o.delta.content}if(s==="reference"&&(t.reference=r),s==="updateSession"&&r&&this.data&&(this.data=g(g({},this.data),r),this.event.emit("data:updated",this.data)),s==="result"){const i=r.messageId,o=r.llmModel,n=r.messageTime;t.messageId=i,t.llmModel=o,t.messageTime=n}s==="over"?t.index=-1:(t.code=e.code,t.message=e.message)}postMessageComment(e){return f(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(r=>r.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 D{constructor(e,t="",s,r,a,i){super(e,t,s,r,a,i)}prepareConnection(){return new Promise(e=>f(this,null,function*(){this.socket&&e(!0);const t={version:"1.0",stream:JSON.stringify(exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?x.Debug:x.Normal},s=new URL(exports.configuration.apiRoot),r=yield ce.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});r.on("connect",()=>{k.log("socket:connect"),this.event.emit("socket:connect"),r.emit("init")}),r.on("disconnect",()=>{k.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),r.on("ready",a=>{if(a.code===200){k.log("ready");const i=exports.configuration.debug?x.Debug:x.Normal;i===x.Debug&&a.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const i=new Error(L.SocketConnectionFailed);k.error("error",i),this.event.emit("error",i),e(!1)}}),r.on("action",(a,i)=>f(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:o,data:{runnerIsClient:n,pluginCode:d,funcCode:p,parameters:h,requestBody:u}}=a,v=this.messages[this.messages.length-1];if(!v.messageId)v.actions||(v.actions=[]),v.actions[a.data.step-1]||(v.actions[a.data.step-1]=[]),v.actions[a.data.step-1].push(a),this.event.emit("message:action",{messageId:v.messageId,action:a}),this.event.emit("message:updated",v);else{const I={messageId:"",content:"",role:y.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[a]],comment:{isAgree:0},isReplying:!0};this.pushMessage(I),this.event.emit("message:action",{messageId:I.messageId,action:a})}if(this.inactivating){const I=new Error(L.Inactive);k.warn("error",I),this.event.emit("error",I)}else if(o==="FUNCTION_CALL"&&n){if(k.log(`calling function ${p} of plugin ${d} with argument:
|
|
2
|
+
${JSON.stringify(h)}`),!exports.configuration.plugins[d]){i({code:404,message:"对不起,没有找到插件。"});return}const I=exports.configuration.plugins[d][p];typeof I!="function"&&i({code:404,message:"对不起,没有找到插件方法。"});let l=h==null?void 0:h.query;try{l=JSON.parse(h==null?void 0:h.query)}catch(_){}I(l,(..._)=>{this._stopAnswer||i(..._)})}})),r.on("answer",a=>{if(!this._stopAnswer)if(a.data.code!==200&&(a.data.index=-1),a.data.stream||a.data.stream===void 0){let i=this.messages[this.messages.length-1];if(i&&i.role===y.ChatMessageRole.Robot)this.handleStreamAnswer(a.data,i),this.messages[this.messages.length-1]=i,this.event.emit("message:content",i),this.event.emit("message:updated",i),i.index===-1&&(i.isReplying=!1,this.event.emit("answer:finish",i));else{const o={content:"",role:y.ChatMessageRole.Robot,reference:[],searchReference:[],messageId:"",sessionId:this.id,messageTime:j(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""};this.handleStreamAnswer(a.data,o),this.pushMessage(o),this.event.emit("message:content",o),o.index===-1&&(o.isReplying=!1,this.event.emit("answer:finish",o))}}else if(a.data.updateSession&&this.data&&(this.data=g(g({},this.data),a.data.updateSession),this.event.emit("data:updated",this.data)),a.data.index===-1){let i=this.messages[this.messages.length-1];if(i&&!i.messageId)i=g(g({},i),a.data),this.event.emit("message:content",i),this.event.emit("message:updated",i),this.event.emit("answer:finish",i);else{const o=g({messageId:"",content:"",role:y.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},a.data);this.event.emit("message:content",o),this.pushMessage(o),this.event.emit("answer:finish",o)}}else{let i=this.messages[this.messages.length-1];i&&!i.messageId?(i=g(g({},i),a.data),this.messages[this.messages.length-1]=i,this.event.emit("message:content",i),this.event.emit("message:updated",i)):(this.pushMessage(g({messageId:"",content:"",role:y.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},a.data)),this.event.emit("message:content",a.data))}}),r.on("reference",a=>f(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const h=new Error(L.IdUndefined);k.error(h),this.event.emit("error",h),this.frozen=!1;return}const{type:i,data:o,requestId:n}=a,d=this.messages.findIndex(h=>h.messageId===n&&h.role===y.ChatMessageRole.User);if(d<0)return;const p=d+1;if(p>=this.messages.length){const h={messageId:"",content:"",role:y.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0};this.pushMessage(h)}i==="KG"?(this.messages[p]=w(g({},this.messages[p]),{reference:o.knowledgeReference}),yield this.fillMessageReference(this.messages[p]),this.event.emit("message:reference",o.knowledgeReference),this.event.emit("message:updated",this.messages[p])):i==="WEB_SEARCH"&&(this.messages[p]=w(g({},this.messages[p]),{searchReference:o.knowledgeReference}),this.event.emit("message:searchreference",o.searchReference),this.event.emit("message:updated",this.messages[p]))})),this.socket=r,r.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((e,t)=>{if(!this.socket){t("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,s=>{s.code===200?(Object.keys(s.data).forEach(r=>{s.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",s.data[r])}),e(!0)):(console.error("MCP Server 注册失败。",s),t(s))})}):Promise.resolve(!0)}addMcpServers(e){return f(this,null,function*(){return this.ready?this.socket?new Promise((t,s)=>{this.socket&&this.socket.emit("add_mcp_servers",e,r=>{r.code===200?(Object.keys(r.data).forEach(a=>{r.data[a].code!==200&&console.error(a,"MCP Server 注册失败。",r.data[a])}),t(!0)):(console.error("MCP Server 注册失败。",r),s(r))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return f(this,null,function*(){return this.ready?this.socket?new Promise((e,t)=>{this.socket&&this.socket.emit("list_mcp_servers",s=>{s.code===200?e(s.data):t(s)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(e,t){return f(this,null,function*(){var r,a,i;this.convertKnowledgesToChatFormat(this.knowledges);let s=w(g({},e),{promptVariables:this.promptVariables.filter(o=>o.type===y.PromptVariableType.User).reduce((o,n)=>w(g({},o),{[n.key]:n.value}),{}),systemPromptVariables:this.promptVariables.filter(o=>o.type===y.PromptVariableType.System).reduce((o,n)=>w(g({},o),{[n.key]:n.value}),{}),knowledges:(r=this.knowledges)==null?void 0:r.map(o=>o.id),enableTitleSummary:!0});if(!this.active){if(yield this.activate(),!this.socket){const o=new Error(L.SocketConnectionFailed);return k.warn("error",o),this.event.emit("error",o),!1}(a=this.socket)==null||a.emit("question",s);return}(i=this.socket)==null||i.emit("question",s)})}stopAnswer(){var e;(e=this.socket)==null||e.emit("stop_answer")}convertKnowledgesToChatFormat(e){return e?e.map(t=>t!=null&&t.fileIds?{id:t.id,fileIds:t.fileIds}:t.id):[]}}function ue(c,e){return f(this,null,function*(){const t=c.getReader();let s;for(;!(s=yield t.read()).done;)e(s.value)})}function ge(c){let e,t,s,r=!1,a;return function(o){e===void 0?(e=o,t=0,s=-1,a=!1):e=ve(e,o);const n=e.length;let d=0;for(;t<n;){r&&(e[t]===10&&(d=++t),r=!1);let p=-1;for(;t<n&&p===-1;++t)switch(e[t]){case 58:s===-1&&(s=t-d);break;case 13:r=!1,t+4<n&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(a=!0);case 10:p=t;break}if(p===-1)break;c(e.subarray(d,p),s,a),d=t,s=-1,a=!1}d===n?e=void 0:d!==0&&(e=e.subarray(d),t-=d)}}function me(c,e,t){let s=H();const r=new TextDecoder;return function(i,o,n){if(i.length===0)t==null||t(s),s=H();else if(o>0){const d=r.decode(i.subarray(0,o)),p=o+(i[o+1]===32?2:1);let h=r.decode(i.subarray(p));switch(n&&(h+=`
|
|
3
3
|
`),d){case"data":s.data=s.data?s.data+`
|
|
4
|
-
`+h:h;break;case"event":s.event=h;break;case"id":c(s.id=h);break;case"retry":const u=parseInt(h,10);isNaN(u)||e(s.retry=u);break}}}}function ve(c,e){const t=new Uint8Array(c.length+e.length);return t.set(c),t.set(e,c.length),t}function H(){return{data:"",event:"",id:"",retry:void 0}}const N="text/event-stream",ye=1e3,K="last-event-id";function W(c,f){var h=f,{signal:e,headers:t,onopen:s,onmessage:r,onclose:a,onerror:i,openWhenHidden:o,fetch:n}=h,d=J(h,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((u,v)=>{const I=g({},t);I.accept||(I.accept=N);let l;function _(){l.abort(),document.hidden||$()}o||document.addEventListener("visibilitychange",_);let C=ye,P=0;function O(){document.removeEventListener("visibilitychange",_),window.clearTimeout(P),l.abort()}e==null||e.addEventListener("abort",()=>{O(),u()});const te=n!=null?n:window.fetch,se=s!=null?s:we;function $(){return p(this,null,function*(){var F;l=new AbortController;try{const T=yield te(c,w(g({},d),{headers:I,signal:l.signal}));yield se(T),yield ue(T.body,ge(me(A=>{A?I[K]=A:delete I[K]},A=>{C=A},r))),a==null||a(),O(),u()}catch(T){if(!l.signal.aborted)try{const A=(F=i==null?void 0:i(T))!=null?F:C;window.clearTimeout(P),P=window.setTimeout($,A)}catch(A){O(),v(A)}}})}$()})}function we(c){const e=c.headers.get("content-type");if(!(e!=null&&e.startsWith(N)))throw new Error(`Expected content-type to be ${N}, Actual: ${e}`)}const G=new S("[DialogSession] ");class Ie extends D{constructor(t,s="",r,a,i,o){super(t,s,r,a,i,o);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,r,a,i,o){return p(this,null,function*(){const n={code:0,content:"",role:y.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=w(g({},r),{stream:exports.configuration.stream});W(`${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:a,onopen(f){return f.ok&&i!=null&&i.onopen&&i.onopen(),Promise.resolve()},onmessage(f){if(!f.data.includes('{"code": ')){let u={};try{u=JSON.parse(f.data)}catch(I){}(u==null?void 0:u.mtype)==="search"?n.searchReference.push(u):n.content=n.content+f.data;const v={content:n.content,role:1,reference:n.reference,searchReference:n.searchReference,messageId:n.messageId,sessionId:s,messageTime:j(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(i==null?void 0:i.onmessage)&&i.onmessage(v)}const h=JSON.parse(f.data);if(n.reference=h.data.reference,n.searchReference=h.data.searchReference,n.messageTime=h.data.messageTime,n.messageId=h.data.messageId,n.llmModel=h.data.llmModel,n.content=h.data.content,n.code=h.code,h.code===200){const u={code:n.code,content:n.content,role:1,reference:n.reference,searchReference:n.searchReference,messageId:n.messageId,sessionId:s,messageTime:n.messageTime,isReplying:!0};i!=null&&i.onmessage&&i.onmessage(u)}else return i!=null&&i.onclose&&i.onclose(n),o&&o({code:n.code,message:n.message})},onerror(){i!=null&&i.onerror&&i.onerror()},onclose(){const f={code:n.code,content:n.content,role:1,reference:n.reference,searchReference:n.searchReference,messageId:n.messageId,sessionId:s,messageTime:n.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};i!=null&&i.onclose&&i.onclose(f)}})})}postChatV3EventSource(t,s,r,a,i,o){return p(this,null,function*(){const n=this,d={code:0,content:"",role:y.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},f=w(g({},r),{stream:exports.configuration.stream});W(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(f),openWhenHidden:!0,signal:a,onopen(h){return h.ok&&i!=null&&i.onopen&&i.onopen(),Promise.resolve()},onmessage(h){if(!h.data&&!h.event&&!h.id&&!h.retry)return;let u={};try{u=JSON.parse(h.data)}catch(v){console.error("parse eventData to JSON failed. ",h.data)}if(u.code!==200)return d.index=-1,d.code=u.code,d.message=u.message,i!=null&&i.onmessage&&i.onmessage(d),o&&o({code:u.code,message:u.message});n.handleStreamAnswer(u,d),i!=null&&i.onmessage&&i.onmessage(d)},onerror(){i!=null&&i.onerror&&i.onerror()},onclose(){const h=w(g({},d),{isReplying:!1});i!=null&&i.onclose&&i.onclose(h)}})})}sendQuestion(t,s){return p(this,null,function*(){const{content:r,fileIds:a,oldMessageId:i,imageContent:o}=t,{stream:n,referenceFirst:d}=s;if(this.active||(yield this.activate()),this._id){const f=this.convertKnowledgesToChatFormat(this.knowledges);let h={content:r,fileIds:a,referenceFirst:d,oldMessageId:i,promptVariables:this.promptVariables.filter(u=>u.type===y.PromptVariableType.User).reduce((u,v)=>w(g({},u),{[v.key]:v.value}),{}),systemPromptVariables:this.promptVariables.filter(u=>u.type===y.PromptVariableType.System).reduce((u,v)=>w(g({},u),{[v.key]:v.value}),{}),knowledges:f,enableTitleSummary:!0,imageContent:o};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,h,this.ctrl.signal,{onopen:()=>{G.log("open",this.ctrl)},onmessage:u=>{if(this._stopAnswer)return;let v=this.messages[this.messages.length-1];v&&v.role===y.ChatMessageRole.Robot?(v=g(g({},v),u),this.messages[this.messages.length-1]=v,this.event.emit("message:content",v),this.event.emit("message:updated",v)):(this.pushMessage(u),this.event.emit("message:content",u))},onclose:u=>p(this,null,function*(){this._stopAnswer||(G.log(u,"onclose"),this.event.emit("answer:finish",u))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}convertKnowledgesToChatFormat(t){return t?t.map(s=>s!=null&&s.fileIds?{id:s.id,fileIds:s.fileIds}:s.id):[]}}const _e="@glodon-aiot/bot-client-sdk",be="3.20.2-alpha.1",Se="glodoncv",Ae="aiot bot client js sdk",ke="module",Re=!1,Me=["aiot","bot","bot client","sdk"],xe=["dist"],Ce="./dist/es/index.mjs",Le="./dist/lib/index.js",Te="./dist/src/index.d.ts",Ee={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},Ve="MIT",Pe={watch:"yarn build --watch",example:"node ./example/server.js",dev:"npm-run-all -p watch example",start:"vite",build:"tsc && vite build --mode prod && yarn build:cdn","build:npm":"tsc && vite build --mode prod","build:cdn":"tsc && vite build --mode prod --config ./vite.config.cdn.ts",preview:"vite preview",check:"yarn prettier --check .",write:"yarn prettier --write .",lint:"eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js"},Oe={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@types/express":"^4","@types/identity-obj-proxy":"^3","@typescript-eslint/eslint-plugin":"^5.35.1","@typescript-eslint/parser":"^5.35.1","babel-loader":"^8.3.0",eslint:"^8.0.1","eslint-config-prettier":"^8.5.0","eslint-config-standard-with-typescript":"^22.0.0","eslint-plugin-import":"^2.25.2","eslint-plugin-n":"^15.0.0","eslint-plugin-promise":"^6.0.0","eslint-plugin-react":"^7.31.0","eslint-plugin-storybook":"^0.6.10",express:"4","http-proxy-middleware":"^3.0.0","identity-obj-proxy":"^3.0.0","npm-run-all":"^4.1.5",prettier:"2.7.1","rollup-plugin-visualizer":"^6.0.1","socket.io":"^4.7.5","ts-node":"^10.9.2",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0","vite-tsconfig-paths":"^5.1.4"},$e={access:"public",registry:"https://registry.npmjs.org/"},Qe={"@glodon-aiot/apis":"^3.20.2-alpha.1",axios:"0.24.0",buffer:"^6.0.3",dayjs:"^1.11.13","js-base64":"^3.7.7","socket.io-client":"^4.7.5",uuid:"^11.1.0"},ze={name:_e,version:be,author:Se,description:Ae,type:ke,sideEffects:Re,keywords:Me,files:xe,module:Ce,main:Le,typings:Te,exports:Ee,license:Ve,scripts:Pe,devDependencies:Oe,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:$e,dependencies:Qe},Ne=new S("[BotClient] ");class je{constructor(e,t,s=!0,r={analytics:{enabled:!1}}){m(this,"event",new ee);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=s,this.sdkConfigs=r,z(t),this._applicationId=V(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(a=>{z(w(g({},t),{stream:t.stream===void 0?(a==null?void 0:a.type)===y.ApplicationTypes.Dialog||(a==null?void 0:a.type)===y.ApplicationTypes.Agent:t.stream})),this.event.emit("ready")})}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return p(this,null,function*(){var t,s,r,a,i;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(s=this.sdkConfigs.ui)==null?void 0:s.version,sdkVersion:ze.version}).then(o=>(typeof o.arrange[0].recommendQuestionOpen!="boolean"&&(o.arrange[0].recommendQuestionOpen=!0),typeof o.arrange[0].thinkingModeOpen!="boolean"&&(o.arrange[0].thinkingModeOpen=!0),typeof o.arrange[0].thinkingTextOpen!="boolean"&&(o.arrange[0].thinkingTextOpen=!0),w(g({},o),{arrange:[w(g({},o.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&o.arrange[0].recommendQuestionOpen})]})));const e=(i=(a=(r=this._application)==null?void 0:r.arrange)==null?void 0:a[0])==null?void 0:i.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(o=>o.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type:y.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:y.PromptVariableType.System})]).then(([o,n])=>[...o,...n]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:Z(exports.configuration.apiRoot,this.token,(e,t)=>Ne.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,r,a){return p(this,null,function*(){const i=this;return new Promise((o,n)=>{const d=f=>p(this,null,function*(){if(f===y.ApplicationTypes.Agent)o(new pe(e,t,s,r,a,i));else if(f===y.ApplicationTypes.Dialog)o(new Ie(e,t,s,r,a,i));else throw Error(`不支持的应用类型:${f}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return p(this,null,function*(){return new Promise((t,s)=>{const r=()=>this.cvforceApi.listSessions(this._applicationId,e).then(a=>p(this,null,function*(){const i=[];for(const o of a){const n=this._sessions.find(d=>d.id===o.id);if(n)n.data=o,this._application?n.application=this._application:yield n.loadApplicationInfo(),i.push(n);else{const d=yield this.createSession(this.token,o.id,o,this.lazyload,this._application||void 0);i.push(d)}}if(e!=null&&e.pageSize){const o=[...this._sessions,...i],n=new Map;for(const d of o)n.set(d.id,d);return this.sessions=Array.from(n.values()),this.sessions}else return this.sessions=i,i}));if(this.ready){if(!this._application)throw Error("_application is null");t(r())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(r())},!0)})})}loadSession(e="",t){return p(this,null,function*(){this.checkReady();let s=this.sessions.find(r=>r.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?(this._activeSession=s,yield s.activate()):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 r=e?this._sessions.find(a=>a.id===e):this._activeSession;if(!r){console.warn("setTop session failed.");return}return yield r.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(r=>r.id===e):s=this._sessions.findIndex(r=>r.id===e.id),s>-1){const r=this._sessions[s];t&&(yield r.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 De{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=De;exports.BotClient=je;exports.Session=D;exports.configure=z;
|
|
4
|
+
`+h:h;break;case"event":s.event=h;break;case"id":c(s.id=h);break;case"retry":const u=parseInt(h,10);isNaN(u)||e(s.retry=u);break}}}}function ve(c,e){const t=new Uint8Array(c.length+e.length);return t.set(c),t.set(e,c.length),t}function H(){return{data:"",event:"",id:"",retry:void 0}}const N="text/event-stream",ye=1e3,K="last-event-id";function W(c,p){var h=p,{signal:e,headers:t,onopen:s,onmessage:r,onclose:a,onerror:i,openWhenHidden:o,fetch:n}=h,d=J(h,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((u,v)=>{const I=g({},t);I.accept||(I.accept=N);let l;function _(){l.abort(),document.hidden||$()}o||document.addEventListener("visibilitychange",_);let C=ye,P=0;function O(){document.removeEventListener("visibilitychange",_),window.clearTimeout(P),l.abort()}e==null||e.addEventListener("abort",()=>{O(),u()});const te=n!=null?n:window.fetch,se=s!=null?s:we;function $(){return f(this,null,function*(){var F;l=new AbortController;try{const T=yield te(c,w(g({},d),{headers:I,signal:l.signal}));yield se(T),yield ue(T.body,ge(me(A=>{A?I[K]=A:delete I[K]},A=>{C=A},r))),a==null||a(),O(),u()}catch(T){if(!l.signal.aborted)try{const A=(F=i==null?void 0:i(T))!=null?F:C;window.clearTimeout(P),P=window.setTimeout($,A)}catch(A){O(),v(A)}}})}$()})}function we(c){const e=c.headers.get("content-type");if(!(e!=null&&e.startsWith(N)))throw new Error(`Expected content-type to be ${N}, Actual: ${e}`)}const G=new S("[DialogSession] ");class Ie extends D{constructor(t,s="",r,a,i,o){super(t,s,r,a,i,o);m(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>f(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,s,r,a,i,o){return f(this,null,function*(){const n={code:0,content:"",role:y.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=w(g({},r),{stream:exports.configuration.stream});W(`${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:a,onopen(p){return p.ok&&i!=null&&i.onopen&&i.onopen(),Promise.resolve()},onmessage(p){if(!p.data.includes('{"code": ')){let u={};try{u=JSON.parse(p.data)}catch(I){}(u==null?void 0:u.mtype)==="search"?n.searchReference.push(u):n.content=n.content+p.data;const v={content:n.content,role:1,reference:n.reference,searchReference:n.searchReference,messageId:n.messageId,sessionId:s,messageTime:j(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(i==null?void 0:i.onmessage)&&i.onmessage(v)}const h=JSON.parse(p.data);if(n.reference=h.data.reference,n.searchReference=h.data.searchReference,n.messageTime=h.data.messageTime,n.messageId=h.data.messageId,n.llmModel=h.data.llmModel,n.content=h.data.content,n.code=h.code,h.code===200){const u={code:n.code,content:n.content,role:1,reference:n.reference,searchReference:n.searchReference,messageId:n.messageId,sessionId:s,messageTime:n.messageTime,isReplying:!0};i!=null&&i.onmessage&&i.onmessage(u)}else return i!=null&&i.onclose&&i.onclose(n),o&&o({code:n.code,message:n.message})},onerror(){i!=null&&i.onerror&&i.onerror()},onclose(){const p={code:n.code,content:n.content,role:1,reference:n.reference,searchReference:n.searchReference,messageId:n.messageId,sessionId:s,messageTime:n.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};i!=null&&i.onclose&&i.onclose(p)}})})}postChatV3EventSource(t,s,r,a,i,o){return f(this,null,function*(){const n=this,d={code:0,content:"",role:y.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},p=w(g({},r),{stream:exports.configuration.stream});W(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(p),openWhenHidden:!0,signal:a,onopen(h){return h.ok&&i!=null&&i.onopen&&i.onopen(),Promise.resolve()},onmessage(h){if(!h.data&&!h.event&&!h.id&&!h.retry)return;let u={};try{u=JSON.parse(h.data)}catch(v){console.error("parse eventData to JSON failed. ",h.data)}if(u.code!==200)return d.index=-1,d.code=u.code,d.message=u.message,i!=null&&i.onmessage&&i.onmessage(d),o&&o({code:u.code,message:u.message});n.handleStreamAnswer(u,d),i!=null&&i.onmessage&&i.onmessage(d)},onerror(){i!=null&&i.onerror&&i.onerror()},onclose(){const h=w(g({},d),{isReplying:!1});i!=null&&i.onclose&&i.onclose(h)}})})}sendQuestion(t,s){return f(this,null,function*(){const{content:r,fileIds:a,oldMessageId:i,imageContent:o}=t,{stream:n,referenceFirst:d}=s;if(this.active||(yield this.activate()),this._id){const p=this.convertKnowledgesToChatFormat(this.knowledges);let h={content:r,fileIds:a,referenceFirst:d,oldMessageId:i,promptVariables:this.promptVariables.filter(u=>u.type===y.PromptVariableType.User).reduce((u,v)=>w(g({},u),{[v.key]:v.value}),{}),systemPromptVariables:this.promptVariables.filter(u=>u.type===y.PromptVariableType.System).reduce((u,v)=>w(g({},u),{[v.key]:v.value}),{}),knowledges:p,enableTitleSummary:!0,imageContent:o};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,h,this.ctrl.signal,{onopen:()=>{G.log("open",this.ctrl)},onmessage:u=>{if(this._stopAnswer)return;let v=this.messages[this.messages.length-1];v&&v.role===y.ChatMessageRole.Robot?(v=g(g({},v),u),this.messages[this.messages.length-1]=v,this.event.emit("message:content",v),this.event.emit("message:updated",v)):(this.pushMessage(u),this.event.emit("message:content",u))},onclose:u=>f(this,null,function*(){this._stopAnswer||(G.log(u,"onclose"),this.event.emit("answer:finish",u))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return f(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return f(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return f(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}convertKnowledgesToChatFormat(t){return t?t.map(s=>s!=null&&s.fileIds?{id:s.id,fileIds:s.fileIds}:s.id):[]}}const _e="@glodon-aiot/bot-client-sdk",be="3.20.2",Se="glodoncv",Ae="aiot bot client js sdk",ke="module",Re=!1,Me=["aiot","bot","bot client","sdk"],xe=["dist"],Ce="./dist/es/index.mjs",Le="./dist/lib/index.js",Te="./dist/src/index.d.ts",Ee={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},Ve="MIT",Pe={watch:"yarn build --watch",example:"node ./example/server.js",dev:"npm-run-all -p watch example",start:"vite",build:"tsc && vite build --mode prod && yarn build:cdn","build:npm":"tsc && vite build --mode prod","build:cdn":"tsc && vite build --mode prod --config ./vite.config.cdn.ts",preview:"vite preview",check:"yarn prettier --check .",write:"yarn prettier --write .",lint:"eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js"},Oe={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@types/express":"^4","@types/identity-obj-proxy":"^3","@typescript-eslint/eslint-plugin":"^5.35.1","@typescript-eslint/parser":"^5.35.1","babel-loader":"^8.3.0",eslint:"^8.0.1","eslint-config-prettier":"^8.5.0","eslint-config-standard-with-typescript":"^22.0.0","eslint-plugin-import":"^2.25.2","eslint-plugin-n":"^15.0.0","eslint-plugin-promise":"^6.0.0","eslint-plugin-react":"^7.31.0","eslint-plugin-storybook":"^0.6.10",express:"4","http-proxy-middleware":"^3.0.0","identity-obj-proxy":"^3.0.0","npm-run-all":"^4.1.5",prettier:"2.7.1","rollup-plugin-visualizer":"^6.0.1","socket.io":"^4.7.5","ts-node":"^10.9.2",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0","vite-tsconfig-paths":"^5.1.4"},$e={access:"public",registry:"https://registry.npmjs.org/"},Qe={"@glodon-aiot/apis":"^3.20.2",axios:"0.24.0",buffer:"^6.0.3",dayjs:"^1.11.13","js-base64":"^3.7.7","socket.io-client":"^4.7.5",uuid:"^11.1.0"},ze={name:_e,version:be,author:Se,description:Ae,type:ke,sideEffects:Re,keywords:Me,files:xe,module:Ce,main:Le,typings:Te,exports:Ee,license:Ve,scripts:Pe,devDependencies:Oe,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:$e,dependencies:Qe},Ne=new S("[BotClient] ");class je{constructor(e,t,s=!0,r={analytics:{enabled:!1}}){m(this,"event",new ee);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=s,this.sdkConfigs=r,z(t),this._applicationId=V(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(a=>{z(w(g({},t),{stream:t.stream===void 0?(a==null?void 0:a.type)===y.ApplicationTypes.Dialog||(a==null?void 0:a.type)===y.ApplicationTypes.Agent:t.stream})),this.event.emit("ready")})}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return f(this,null,function*(){var t,s,r,a,i;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(s=this.sdkConfigs.ui)==null?void 0:s.version,sdkVersion:ze.version}).then(o=>(typeof o.arrange[0].recommendQuestionOpen!="boolean"&&(o.arrange[0].recommendQuestionOpen=!0),w(g({},o),{arrange:[w(g({},o.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&o.arrange[0].recommendQuestionOpen})]})));const e=(i=(a=(r=this._application)==null?void 0:r.arrange)==null?void 0:a[0])==null?void 0:i.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(o=>o.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type:y.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:y.PromptVariableType.System})]).then(([o,n])=>[...o,...n]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:Z(exports.configuration.apiRoot,this.token,(e,t)=>Ne.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,r,a){return f(this,null,function*(){const i=this;return new Promise((o,n)=>{const d=p=>f(this,null,function*(){if(p===y.ApplicationTypes.Agent)o(new fe(e,t,s,r,a,i));else if(p===y.ApplicationTypes.Dialog)o(new Ie(e,t,s,r,a,i));else throw Error(`不支持的应用类型:${p}`)});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 f(this,null,function*(){return new Promise((t,s)=>{const r=()=>this.cvforceApi.listSessions(this._applicationId,e).then(a=>f(this,null,function*(){const i=[];for(const o of a){const n=this._sessions.find(d=>d.id===o.id);if(n)n.data=o,this._application?n.application=this._application:yield n.loadApplicationInfo(),i.push(n);else{const d=yield this.createSession(this.token,o.id,o,this.lazyload,this._application||void 0);i.push(d)}}if(e!=null&&e.pageSize){const o=[...this._sessions,...i],n=new Map;for(const d of o)n.set(d.id,d);return this.sessions=Array.from(n.values()),this.sessions}else return this.sessions=i,i}));if(this.ready){if(!this._application)throw Error("_application is null");t(r())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(r())},!0)})})}loadSession(e="",t){return f(this,null,function*(){this.checkReady();let s=this.sessions.find(r=>r.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?(this._activeSession=s,yield s.activate()):s.addEventListener("data:loaded",()=>{this._activeSession!==s&&(s==null||s.activate(),this._activeSession=s)},!0),s})}reload(){return this.loadApplication().then(()=>f(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return f(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 f(this,null,function*(){let r=e?this._sessions.find(a=>a.id===e):this._activeSession;if(!r){console.warn("setTop session failed.");return}return yield r.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 f(this,null,function*(){this.checkReady();let s=-1;if(typeof e=="string"?s=this._sessions.findIndex(r=>r.id===e):s=this._sessions.findIndex(r=>r.id===e.id),s>-1){const r=this._sessions[s];t&&(yield r.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 De{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=De;exports.BotClient=je;exports.Session=D;exports.configure=z;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glodon-aiot/bot-client-sdk",
|
|
3
|
-
"version": "3.20.2
|
|
3
|
+
"version": "3.20.2",
|
|
4
4
|
"author": "glodoncv",
|
|
5
5
|
"description": "aiot bot client js sdk",
|
|
6
6
|
"type": "module",
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
"registry": "https://registry.npmjs.org/"
|
|
80
80
|
},
|
|
81
81
|
"dependencies": {
|
|
82
|
-
"@glodon-aiot/apis": "^3.20.2
|
|
82
|
+
"@glodon-aiot/apis": "^3.20.2",
|
|
83
83
|
"axios": "0.24.0",
|
|
84
84
|
"buffer": "^6.0.3",
|
|
85
85
|
"dayjs": "^1.11.13",
|