@glodon-aiot/bot-client-sdk 3.5.0-alpha.3 → 3.6.0-alpha.5
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/DialogSession.mjs +104 -102
- package/dist/es/Session.mjs +112 -110
- package/dist/es/package.json.mjs +2 -2
- package/dist/lib/index.js +3 -3
- package/dist/src/Session.d.ts +4 -1
- package/package.json +2 -2
|
@@ -2,56 +2,56 @@ var T = Object.defineProperty, A = Object.defineProperties;
|
|
|
2
2
|
var I = Object.getOwnPropertyDescriptors;
|
|
3
3
|
var M = Object.getOwnPropertySymbols;
|
|
4
4
|
var P = Object.prototype.hasOwnProperty, k = Object.prototype.propertyIsEnumerable;
|
|
5
|
-
var
|
|
5
|
+
var R = (m, n, a) => n in m ? T(m, n, { enumerable: !0, configurable: !0, writable: !0, value: a }) : m[n] = a, u = (m, n) => {
|
|
6
6
|
for (var a in n || (n = {}))
|
|
7
|
-
P.call(n, a) &&
|
|
7
|
+
P.call(n, a) && R(m, a, n[a]);
|
|
8
8
|
if (M)
|
|
9
9
|
for (var a of M(n))
|
|
10
|
-
k.call(n, a) &&
|
|
11
|
-
return
|
|
12
|
-
},
|
|
13
|
-
var w = (
|
|
14
|
-
var
|
|
15
|
-
var
|
|
10
|
+
k.call(n, a) && R(m, a, n[a]);
|
|
11
|
+
return m;
|
|
12
|
+
}, y = (m, n) => A(m, I(n));
|
|
13
|
+
var w = (m, n, a) => (R(m, typeof n != "symbol" ? n + "" : n, a), a);
|
|
14
|
+
var f = (m, n, a) => new Promise((l, d) => {
|
|
15
|
+
var h = (r) => {
|
|
16
16
|
try {
|
|
17
|
-
|
|
18
|
-
} catch (
|
|
19
|
-
|
|
17
|
+
i(a.next(r));
|
|
18
|
+
} catch (o) {
|
|
19
|
+
d(o);
|
|
20
20
|
}
|
|
21
21
|
}, e = (r) => {
|
|
22
22
|
try {
|
|
23
|
-
|
|
24
|
-
} catch (
|
|
25
|
-
|
|
23
|
+
i(a.throw(r));
|
|
24
|
+
} catch (o) {
|
|
25
|
+
d(o);
|
|
26
26
|
}
|
|
27
|
-
},
|
|
28
|
-
|
|
27
|
+
}, i = (r) => r.done ? l(r.value) : Promise.resolve(r.value).then(h, e);
|
|
28
|
+
i((a = a.apply(m, n)).next());
|
|
29
29
|
});
|
|
30
|
-
import { IHistoryRole as b, PromptVariableType as
|
|
30
|
+
import { IHistoryRole as b, PromptVariableType as C, ChatMessageRole as D } from "@glodon-aiot/apis";
|
|
31
31
|
import O from "./Logger.mjs";
|
|
32
32
|
import V from "./Session.mjs";
|
|
33
33
|
import $ from "dayjs";
|
|
34
|
-
import { configuration as
|
|
35
|
-
import { fetchEventSource as
|
|
36
|
-
const
|
|
34
|
+
import { configuration as S } from "./Config.mjs";
|
|
35
|
+
import { fetchEventSource as p } from "./api/fetchEventSource/fetch.mjs";
|
|
36
|
+
const v = new O("[DialogSession] ");
|
|
37
37
|
class B extends V {
|
|
38
|
-
constructor(a,
|
|
39
|
-
super(a,
|
|
38
|
+
constructor(a, l = "", d, h, e, i) {
|
|
39
|
+
super(a, l, d, h, e, i);
|
|
40
40
|
w(this, "ctrl", new AbortController());
|
|
41
41
|
}
|
|
42
42
|
prepareConnection() {
|
|
43
|
-
return new Promise((a) =>
|
|
43
|
+
return new Promise((a) => f(this, null, function* () {
|
|
44
44
|
this._ready = !0, this.event.emit("ready"), this.frozen = !1, a(!0);
|
|
45
45
|
}));
|
|
46
46
|
}
|
|
47
|
-
postChatV2EventSource(a,
|
|
48
|
-
return
|
|
47
|
+
postChatV2EventSource(a, l, d, h, e, i) {
|
|
48
|
+
return f(this, null, function* () {
|
|
49
49
|
const r = {
|
|
50
50
|
code: 0,
|
|
51
51
|
// messageId: uuidv4(),
|
|
52
52
|
content: "",
|
|
53
53
|
role: b.Robot,
|
|
54
|
-
sessionId:
|
|
54
|
+
sessionId: l,
|
|
55
55
|
reference: [],
|
|
56
56
|
searchReference: [],
|
|
57
57
|
messageTime: "",
|
|
@@ -60,60 +60,60 @@ class B extends V {
|
|
|
60
60
|
isAgree: 0
|
|
61
61
|
},
|
|
62
62
|
isReplying: !1
|
|
63
|
-
},
|
|
64
|
-
stream:
|
|
63
|
+
}, o = y(u({}, d), {
|
|
64
|
+
stream: S.stream
|
|
65
65
|
});
|
|
66
|
-
|
|
66
|
+
p(`${S.apiRoot}/chat/v2/chat?applicationId=${a}&sessionId=${l}`, {
|
|
67
67
|
method: "POST",
|
|
68
68
|
headers: {
|
|
69
69
|
Authorization: `Bearer ${this.token}`,
|
|
70
70
|
"Content-Type": "application/json"
|
|
71
71
|
},
|
|
72
|
-
body: JSON.stringify(
|
|
72
|
+
body: JSON.stringify(o),
|
|
73
73
|
openWhenHidden: !0,
|
|
74
|
-
signal:
|
|
75
|
-
onopen(
|
|
76
|
-
return
|
|
74
|
+
signal: h,
|
|
75
|
+
onopen(g) {
|
|
76
|
+
return g.ok && e != null && e.onopen && e.onopen(), Promise.resolve();
|
|
77
77
|
},
|
|
78
|
-
onmessage(
|
|
79
|
-
if (!
|
|
80
|
-
let
|
|
78
|
+
onmessage(g) {
|
|
79
|
+
if (!g.data.includes('{"code": ')) {
|
|
80
|
+
let s = {};
|
|
81
81
|
try {
|
|
82
|
-
|
|
82
|
+
s = JSON.parse(g.data);
|
|
83
83
|
} catch (_) {
|
|
84
84
|
}
|
|
85
|
-
(
|
|
86
|
-
const
|
|
85
|
+
(s == null ? void 0 : s.mtype) === "search" ? r.searchReference.push(s) : r.content = r.content + g.data;
|
|
86
|
+
const c = {
|
|
87
87
|
content: r.content,
|
|
88
88
|
role: 1,
|
|
89
89
|
reference: r.reference,
|
|
90
90
|
searchReference: r.searchReference,
|
|
91
91
|
messageId: r.messageId,
|
|
92
|
-
sessionId:
|
|
92
|
+
sessionId: l,
|
|
93
93
|
messageTime: $(/* @__PURE__ */ new Date()).format("YYYY-MM-DD HH:mm:ss"),
|
|
94
94
|
comment: {
|
|
95
95
|
isAgree: 0
|
|
96
96
|
},
|
|
97
97
|
isReplying: !0
|
|
98
98
|
};
|
|
99
|
-
return (e == null ? void 0 : e.onmessage) && e.onmessage(
|
|
99
|
+
return (e == null ? void 0 : e.onmessage) && e.onmessage(c);
|
|
100
100
|
}
|
|
101
|
-
const
|
|
102
|
-
if (r.reference =
|
|
103
|
-
const
|
|
101
|
+
const t = JSON.parse(g.data);
|
|
102
|
+
if (r.reference = t.data.reference, r.searchReference = t.data.searchReference, r.messageTime = t.data.messageTime, r.messageId = t.data.messageId, r.llmModel = t.data.llmModel, r.content = t.data.content, r.code = t.code, t.code === 200) {
|
|
103
|
+
const s = {
|
|
104
104
|
code: r.code,
|
|
105
105
|
content: r.content,
|
|
106
106
|
role: 1,
|
|
107
107
|
reference: r.reference,
|
|
108
108
|
searchReference: r.searchReference,
|
|
109
109
|
messageId: r.messageId,
|
|
110
|
-
sessionId:
|
|
110
|
+
sessionId: l,
|
|
111
111
|
messageTime: r.messageTime,
|
|
112
112
|
isReplying: !0
|
|
113
113
|
};
|
|
114
|
-
e != null && e.onmessage && e.onmessage(
|
|
114
|
+
e != null && e.onmessage && e.onmessage(s);
|
|
115
115
|
} else
|
|
116
|
-
return e != null && e.onclose && e.onclose(r),
|
|
116
|
+
return e != null && e.onclose && e.onclose(r), i && i({
|
|
117
117
|
code: r.code,
|
|
118
118
|
message: r.message
|
|
119
119
|
});
|
|
@@ -122,14 +122,14 @@ class B extends V {
|
|
|
122
122
|
e != null && e.onerror && e.onerror();
|
|
123
123
|
},
|
|
124
124
|
onclose() {
|
|
125
|
-
const
|
|
125
|
+
const g = {
|
|
126
126
|
code: r.code,
|
|
127
127
|
content: r.content,
|
|
128
128
|
role: 1,
|
|
129
129
|
reference: r.reference,
|
|
130
130
|
searchReference: r.searchReference,
|
|
131
131
|
messageId: r.messageId,
|
|
132
|
-
sessionId:
|
|
132
|
+
sessionId: l,
|
|
133
133
|
messageTime: r.messageTime,
|
|
134
134
|
comment: {
|
|
135
135
|
isAgree: 0
|
|
@@ -137,19 +137,19 @@ class B extends V {
|
|
|
137
137
|
isReplying: !1,
|
|
138
138
|
index: -1
|
|
139
139
|
};
|
|
140
|
-
e != null && e.onclose && e.onclose(
|
|
140
|
+
e != null && e.onclose && e.onclose(g);
|
|
141
141
|
}
|
|
142
142
|
});
|
|
143
143
|
});
|
|
144
144
|
}
|
|
145
|
-
postChatV3EventSource(a,
|
|
146
|
-
return
|
|
147
|
-
const r = this,
|
|
145
|
+
postChatV3EventSource(a, l, d, h, e, i) {
|
|
146
|
+
return f(this, null, function* () {
|
|
147
|
+
const r = this, o = {
|
|
148
148
|
code: 0,
|
|
149
149
|
// messageId: uuidv4(),
|
|
150
150
|
content: "",
|
|
151
151
|
role: b.Robot,
|
|
152
|
-
sessionId:
|
|
152
|
+
sessionId: l,
|
|
153
153
|
reference: [],
|
|
154
154
|
searchReference: [],
|
|
155
155
|
messageTime: "",
|
|
@@ -162,88 +162,90 @@ class B extends V {
|
|
|
162
162
|
thinkingSecs: "",
|
|
163
163
|
thinkingStatus: "",
|
|
164
164
|
searchingStatus: ""
|
|
165
|
-
},
|
|
166
|
-
stream:
|
|
165
|
+
}, g = y(u({}, d), {
|
|
166
|
+
stream: S.stream
|
|
167
167
|
});
|
|
168
|
-
|
|
168
|
+
p(`${S.apiRoot}/chat/v3/chat?applicationId=${a}&sessionId=${l}`, {
|
|
169
169
|
method: "POST",
|
|
170
170
|
headers: {
|
|
171
171
|
Authorization: `Bearer ${this.token}`,
|
|
172
172
|
"Content-Type": "application/json"
|
|
173
173
|
},
|
|
174
|
-
body: JSON.stringify(
|
|
174
|
+
body: JSON.stringify(g),
|
|
175
175
|
openWhenHidden: !0,
|
|
176
|
-
signal:
|
|
177
|
-
onopen(
|
|
178
|
-
return
|
|
176
|
+
signal: h,
|
|
177
|
+
onopen(t) {
|
|
178
|
+
return t.ok && e != null && e.onopen && e.onopen(), Promise.resolve();
|
|
179
179
|
},
|
|
180
|
-
onmessage(
|
|
181
|
-
if (!
|
|
180
|
+
onmessage(t) {
|
|
181
|
+
if (!t.data && !t.event && !t.id && !t.retry)
|
|
182
182
|
return;
|
|
183
|
-
let
|
|
183
|
+
let s = {};
|
|
184
184
|
try {
|
|
185
|
-
|
|
186
|
-
} catch (
|
|
187
|
-
console.error("parse eventData to JSON failed. ",
|
|
185
|
+
s = JSON.parse(t.data);
|
|
186
|
+
} catch (c) {
|
|
187
|
+
console.error("parse eventData to JSON failed. ", t.data);
|
|
188
188
|
}
|
|
189
|
-
if (
|
|
190
|
-
return
|
|
191
|
-
code:
|
|
192
|
-
message:
|
|
189
|
+
if (s.code !== 200)
|
|
190
|
+
return o.index = -1, o.code = s.code, o.message = s.message, e != null && e.onmessage && e.onmessage(o), i && i({
|
|
191
|
+
code: s.code,
|
|
192
|
+
message: s.message
|
|
193
193
|
});
|
|
194
|
-
r.handleStreamAnswer(
|
|
194
|
+
r.handleStreamAnswer(s, o), e != null && e.onmessage && e.onmessage(o);
|
|
195
195
|
},
|
|
196
196
|
onerror() {
|
|
197
197
|
e != null && e.onerror && e.onerror();
|
|
198
198
|
},
|
|
199
199
|
onclose() {
|
|
200
|
-
const
|
|
200
|
+
const t = y(u({}, o), {
|
|
201
201
|
isReplying: !1
|
|
202
202
|
});
|
|
203
|
-
e != null && e.onclose && e.onclose(
|
|
203
|
+
e != null && e.onclose && e.onclose(t);
|
|
204
204
|
}
|
|
205
205
|
});
|
|
206
206
|
});
|
|
207
207
|
}
|
|
208
|
-
sendQuestion(a,
|
|
209
|
-
return
|
|
210
|
-
var
|
|
208
|
+
sendQuestion(a, l) {
|
|
209
|
+
return f(this, null, function* () {
|
|
210
|
+
var g;
|
|
211
211
|
const {
|
|
212
|
-
content:
|
|
213
|
-
fileIds:
|
|
214
|
-
oldMessageId: e
|
|
212
|
+
content: d,
|
|
213
|
+
fileIds: h,
|
|
214
|
+
oldMessageId: e,
|
|
215
|
+
imageContent: i
|
|
215
216
|
} = a, {
|
|
216
|
-
stream:
|
|
217
|
-
referenceFirst:
|
|
218
|
-
} =
|
|
217
|
+
stream: r,
|
|
218
|
+
referenceFirst: o
|
|
219
|
+
} = l;
|
|
219
220
|
if (this.active || (yield this.activate()), this._id) {
|
|
220
|
-
let
|
|
221
|
-
content:
|
|
222
|
-
fileIds:
|
|
223
|
-
referenceFirst:
|
|
221
|
+
let t = {
|
|
222
|
+
content: d,
|
|
223
|
+
fileIds: h,
|
|
224
|
+
referenceFirst: o,
|
|
224
225
|
oldMessageId: e,
|
|
225
|
-
promptVariables: this.promptVariables.filter((s) => s.type ===
|
|
226
|
-
[
|
|
226
|
+
promptVariables: this.promptVariables.filter((s) => s.type === C.User).reduce((s, c) => y(u({}, s), {
|
|
227
|
+
[c.key]: c.value
|
|
227
228
|
}), {}),
|
|
228
|
-
systemPromptVariables: this.promptVariables.filter((s) => s.type ===
|
|
229
|
-
[
|
|
229
|
+
systemPromptVariables: this.promptVariables.filter((s) => s.type === C.System).reduce((s, c) => y(u({}, s), {
|
|
230
|
+
[c.key]: c.value
|
|
230
231
|
}), {}),
|
|
231
|
-
knowledges: (
|
|
232
|
+
knowledges: (g = this.knowledges) == null ? void 0 : g.map((s) => s.id),
|
|
232
233
|
//开启内容摘要
|
|
233
|
-
enableTitleSummary: !0
|
|
234
|
+
enableTitleSummary: !0,
|
|
235
|
+
imageContent: i
|
|
234
236
|
};
|
|
235
|
-
this.ctrl = new AbortController(), this.postChatV3EventSource(this._applicationId, this._id,
|
|
237
|
+
this.ctrl = new AbortController(), this.postChatV3EventSource(this._applicationId, this._id, t, this.ctrl.signal, {
|
|
236
238
|
onopen: () => {
|
|
237
|
-
|
|
239
|
+
v.log("open", this.ctrl);
|
|
238
240
|
},
|
|
239
241
|
onmessage: (s) => {
|
|
240
242
|
if (this._stopAnswer)
|
|
241
243
|
return;
|
|
242
|
-
let
|
|
243
|
-
|
|
244
|
+
let c = this.messages[this.messages.length - 1];
|
|
245
|
+
c && c.role === D.Robot ? (c = u(u({}, c), s), this.messages[this.messages.length - 1] = c, this.event.emit("message:content", c), this.event.emit("message:updated", c)) : (this.pushMessage(s), this.event.emit("message:content", s));
|
|
244
246
|
},
|
|
245
|
-
onclose: (s) =>
|
|
246
|
-
this._stopAnswer || (
|
|
247
|
+
onclose: (s) => f(this, null, function* () {
|
|
248
|
+
this._stopAnswer || (v.log(s, "onclose"), this.event.emit("answer:finish", s));
|
|
247
249
|
}),
|
|
248
250
|
onerror: () => {
|
|
249
251
|
this._stopAnswer || (this.event.emit("message:error", ""), this.frozen = !1);
|
|
@@ -256,17 +258,17 @@ class B extends V {
|
|
|
256
258
|
this.ctrl.abort();
|
|
257
259
|
}
|
|
258
260
|
registerMcpFromClientConfig() {
|
|
259
|
-
return
|
|
261
|
+
return f(this, null, function* () {
|
|
260
262
|
throw new Error("MCP registration is not supported by DialogSession");
|
|
261
263
|
});
|
|
262
264
|
}
|
|
263
265
|
addMcpServers(a) {
|
|
264
|
-
return
|
|
266
|
+
return f(this, null, function* () {
|
|
265
267
|
throw new Error("MCP registration is not supported by DialogSession");
|
|
266
268
|
});
|
|
267
269
|
}
|
|
268
270
|
listMcpServers() {
|
|
269
|
-
return
|
|
271
|
+
return f(this, null, function* () {
|
|
270
272
|
throw new Error("MCP registration is not supported by DialogSession");
|
|
271
273
|
});
|
|
272
274
|
}
|
package/dist/es/Session.mjs
CHANGED
|
@@ -1,43 +1,43 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var
|
|
4
|
-
var
|
|
5
|
-
var k = (c, e, t) => e in c ?
|
|
1
|
+
var Q = Object.defineProperty, T = Object.defineProperties;
|
|
2
|
+
var M = Object.getOwnPropertyDescriptors;
|
|
3
|
+
var E = Object.getOwnPropertySymbols;
|
|
4
|
+
var C = Object.prototype.hasOwnProperty, R = Object.prototype.propertyIsEnumerable;
|
|
5
|
+
var k = (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
|
-
|
|
8
|
-
if (
|
|
9
|
-
for (var t of
|
|
7
|
+
C.call(e, t) && k(c, t, e[t]);
|
|
8
|
+
if (E)
|
|
9
|
+
for (var t of E(e))
|
|
10
10
|
R.call(e, t) && k(c, t, e[t]);
|
|
11
11
|
return c;
|
|
12
|
-
},
|
|
12
|
+
}, I = (c, e) => T(c, M(e));
|
|
13
13
|
var p = (c, e, t) => (k(c, typeof e != "symbol" ? e + "" : e, t), t);
|
|
14
|
-
var h = (c, e, t) => new Promise((i,
|
|
14
|
+
var h = (c, e, t) => new Promise((i, o) => {
|
|
15
15
|
var a = (s) => {
|
|
16
16
|
try {
|
|
17
17
|
r(t.next(s));
|
|
18
18
|
} catch (l) {
|
|
19
|
-
|
|
19
|
+
o(l);
|
|
20
20
|
}
|
|
21
21
|
}, d = (s) => {
|
|
22
22
|
try {
|
|
23
23
|
r(t.throw(s));
|
|
24
24
|
} catch (l) {
|
|
25
|
-
|
|
25
|
+
o(l);
|
|
26
26
|
}
|
|
27
27
|
}, r = (s) => s.done ? i(s.value) : Promise.resolve(s.value).then(a, d);
|
|
28
28
|
r((t = t.apply(c, e)).next());
|
|
29
29
|
});
|
|
30
|
-
import { v4 as
|
|
31
|
-
import { parseJWT as
|
|
32
|
-
import { ApplicationTypes as
|
|
33
|
-
import
|
|
30
|
+
import { v4 as x } from "uuid";
|
|
31
|
+
import { parseJWT as O, removeNewlines as z, removeLeadingAndTrailingBackslashes as P } from "./utils.mjs";
|
|
32
|
+
import { ApplicationTypes as V, PromptStatus as q, PromptVariableType as L, ChatMessageRole as S } from "@glodon-aiot/apis";
|
|
33
|
+
import F from "./Logger.mjs";
|
|
34
34
|
import { configuration as A } from "./Config.mjs";
|
|
35
|
-
import
|
|
36
|
-
import { getCVForceService as
|
|
37
|
-
import
|
|
38
|
-
const u = new
|
|
39
|
-
var
|
|
40
|
-
class
|
|
35
|
+
import N from "./EventBus.mjs";
|
|
36
|
+
import { getCVForceService as B } from "./api/index.mjs";
|
|
37
|
+
import U from "dayjs";
|
|
38
|
+
const u = new F("[Session] ");
|
|
39
|
+
var H = /* @__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))(H || {});
|
|
40
|
+
class Z {
|
|
41
41
|
/**
|
|
42
42
|
* Session 类的构造函数,用于初始化会话实例。
|
|
43
43
|
* @param token - 用户的身份验证令牌,用于解析应用 ID。
|
|
@@ -47,14 +47,14 @@ class X {
|
|
|
47
47
|
* @param _application - 应用信息,可选参数。
|
|
48
48
|
* @param client - Bot 客户端实例,可选参数。
|
|
49
49
|
*/
|
|
50
|
-
constructor(e, t = "", i,
|
|
50
|
+
constructor(e, t = "", i, o, a, d) {
|
|
51
51
|
p(this, "_id");
|
|
52
52
|
p(this, "_frozen", !1);
|
|
53
53
|
//是否可发送新问题
|
|
54
54
|
p(this, "inactivating", !1);
|
|
55
55
|
p(this, "_ready", !1);
|
|
56
56
|
// ready = false;
|
|
57
|
-
p(this, "event", new
|
|
57
|
+
p(this, "event", new N());
|
|
58
58
|
//从token解析出来的用户信息
|
|
59
59
|
p(this, "_applicationId");
|
|
60
60
|
p(this, "_application", null);
|
|
@@ -72,13 +72,13 @@ class X {
|
|
|
72
72
|
p(this, "_dataLoading", !1);
|
|
73
73
|
p(this, "_dataLoaded", !1);
|
|
74
74
|
p(this, "_mcpServers", null);
|
|
75
|
-
this.token = e, this.lazyload =
|
|
75
|
+
this.token = e, this.lazyload = o, this.client = d || null, this._applicationId = O(e).rid || A.applicationId, this.cvforceApi = this.getService(), a && (this._application = a), this.event.emit("init", {
|
|
76
76
|
applicationId: this._applicationId,
|
|
77
77
|
sessionId: t
|
|
78
78
|
}), this.loadApplicationInfo().then(() => {
|
|
79
79
|
var r;
|
|
80
80
|
if (t)
|
|
81
|
-
this._id = t, this.event.emit("data:loading"), i ? (this.data = i,
|
|
81
|
+
this._id = t, this.event.emit("data:loading"), i ? (this.data = i, o || (this._dataLoading = !0, this.cvforceApi.getSession(this.applicationId, t).then((s) => h(this, null, function* () {
|
|
82
82
|
this.data = s, this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, t);
|
|
83
83
|
})).then(() => h(this, null, function* () {
|
|
84
84
|
this.messages = [], yield this.fetchMessages(), this.event.emit("data:loaded", this.data), this.event.emit("data:updated", this.data);
|
|
@@ -100,24 +100,24 @@ class X {
|
|
|
100
100
|
applicationId: this._applicationId
|
|
101
101
|
}).then((l) => h(this, null, function* () {
|
|
102
102
|
var m;
|
|
103
|
-
this._id = l.id, this.data =
|
|
103
|
+
this._id = l.id, this.data = I(f({}, l), {
|
|
104
104
|
knowledges: i == null ? void 0 : i.knowledges
|
|
105
105
|
}), this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, this._id), yield (() => h(this, null, function* () {
|
|
106
106
|
if (i != null && i.knowledges)
|
|
107
107
|
return this.setKnowledges((i == null ? void 0 : i.knowledges) || void 0);
|
|
108
108
|
}))(), yield (() => {
|
|
109
109
|
if (i != null && i.promptVariables) {
|
|
110
|
-
const
|
|
111
|
-
var
|
|
112
|
-
const
|
|
113
|
-
return
|
|
114
|
-
value:
|
|
110
|
+
const w = this._promptVariables.map((v) => {
|
|
111
|
+
var _, n;
|
|
112
|
+
const y = ((n = (_ = i.promptVariables) == null ? void 0 : _.find((g) => g.key === v.key && g.type === v.type)) == null ? void 0 : n.value) || "";
|
|
113
|
+
return I(f({}, v), {
|
|
114
|
+
value: y
|
|
115
115
|
});
|
|
116
|
-
}).sort((
|
|
117
|
-
return this.setPromptVariables(
|
|
116
|
+
}).sort((v, y) => v.key.localeCompare(y.key));
|
|
117
|
+
return this.setPromptVariables(w || []);
|
|
118
118
|
} else
|
|
119
119
|
return;
|
|
120
|
-
})(), this.event.emit("data:created", this.data), this.event.emit("data:loaded", this.data), this.event.emit("data:updated", this.data), ((m = this.application) == null ? void 0 : m.type) !==
|
|
120
|
+
})(), this.event.emit("data:created", this.data), this.event.emit("data:loaded", this.data), this.event.emit("data:updated", this.data), ((m = this.application) == null ? void 0 : m.type) !== V.Agent && (this._ready = !0, this.event.emit("ready"));
|
|
121
121
|
}));
|
|
122
122
|
}
|
|
123
123
|
});
|
|
@@ -181,7 +181,7 @@ class X {
|
|
|
181
181
|
throw Error("session id is not defined");
|
|
182
182
|
if (!this.data)
|
|
183
183
|
throw Error("session data is not loaded");
|
|
184
|
-
const e = this.promptVariables.filter((t) => t.status ===
|
|
184
|
+
const e = this.promptVariables.filter((t) => t.status === q.Quoted).filter((t) => !t.value);
|
|
185
185
|
if (e.length)
|
|
186
186
|
throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map((t) => t.key).join(", ")}`);
|
|
187
187
|
}
|
|
@@ -190,12 +190,12 @@ class X {
|
|
|
190
190
|
}
|
|
191
191
|
setPromptVariables(e) {
|
|
192
192
|
return h(this, null, function* () {
|
|
193
|
-
const t = e == null ? void 0 : e.map((a) => a.type ? a :
|
|
193
|
+
const t = e == null ? void 0 : e.map((a) => a.type ? a : I(f({}, a), {
|
|
194
194
|
type: "instruction"
|
|
195
195
|
})), i = this._promptVariables.map((a) => {
|
|
196
196
|
var r;
|
|
197
197
|
const d = ((r = t == null ? void 0 : t.find((s) => s.key === a.key && s.type === a.type)) == null ? void 0 : r.value) || a.value;
|
|
198
|
-
return
|
|
198
|
+
return I(f({}, a), {
|
|
199
199
|
value: d
|
|
200
200
|
});
|
|
201
201
|
}).sort((a, d) => a.key.localeCompare(d.key));
|
|
@@ -227,12 +227,12 @@ class X {
|
|
|
227
227
|
*/
|
|
228
228
|
setNetOpen(e) {
|
|
229
229
|
return h(this, null, function* () {
|
|
230
|
-
var t, i,
|
|
231
|
-
if (u.log("setNetOpen:", e), u.log("application arrange setting value: ", (t = this._application) == null ? void 0 : t.arrange[0].enableNetOpen), ((i = this._application) == null ? void 0 : i.type) ===
|
|
230
|
+
var t, i, o;
|
|
231
|
+
if (u.log("setNetOpen:", e), u.log("application arrange setting value: ", (t = this._application) == null ? void 0 : t.arrange[0].enableNetOpen), ((i = this._application) == null ? void 0 : i.type) === V.Agent) {
|
|
232
232
|
console.warn("Agent Application Sessions are disabled to setNetOpen.");
|
|
233
233
|
return;
|
|
234
234
|
}
|
|
235
|
-
if (((
|
|
235
|
+
if (((o = this._application) == null ? void 0 : o.arrange[0].enableNetOpen) === !1) {
|
|
236
236
|
console.warn("This Application is disabled to change netOpen.");
|
|
237
237
|
return;
|
|
238
238
|
}
|
|
@@ -247,7 +247,7 @@ class X {
|
|
|
247
247
|
});
|
|
248
248
|
}
|
|
249
249
|
getService() {
|
|
250
|
-
return
|
|
250
|
+
return B(A.apiRoot, this.token, (e, t) => {
|
|
251
251
|
const i = new Error("data request error", {
|
|
252
252
|
cause: {
|
|
253
253
|
status: e,
|
|
@@ -276,18 +276,18 @@ class X {
|
|
|
276
276
|
*/
|
|
277
277
|
fetchMessages() {
|
|
278
278
|
return h(this, arguments, function* (e = {}) {
|
|
279
|
-
var i,
|
|
279
|
+
var i, o;
|
|
280
280
|
const t = {
|
|
281
281
|
pageSize: this._loadingMessagesSize
|
|
282
282
|
};
|
|
283
283
|
if (this._id) {
|
|
284
284
|
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;
|
|
285
285
|
const a = yield this.cvforceApi.getChatHistorySessionId(this._applicationId, this._id, e), d = a.map((s, l) => {
|
|
286
|
-
var
|
|
287
|
-
let m = [],
|
|
288
|
-
return typeof ((
|
|
286
|
+
var v, y;
|
|
287
|
+
let m = [], w;
|
|
288
|
+
return typeof ((v = s.agentHistoryList) == null ? void 0 : v.agentList) == "string" && (m = JSON.parse(s.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 && (w = (y = this.data) == null ? void 0 : y.lastRelatedQuestion), I(f({}, s), {
|
|
289
289
|
actions: m,
|
|
290
|
-
relatedQuesion:
|
|
290
|
+
relatedQuesion: w
|
|
291
291
|
});
|
|
292
292
|
});
|
|
293
293
|
if (!e.endTime && !e.startTime) {
|
|
@@ -304,7 +304,7 @@ class X {
|
|
|
304
304
|
this.messages.splice(s, l - s + 1, ...d);
|
|
305
305
|
}
|
|
306
306
|
const r = this.messages[this.messages.length - 1];
|
|
307
|
-
return r && !r.relatedQuesion && (r.relatedQuesion = (
|
|
307
|
+
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;
|
|
308
308
|
} else {
|
|
309
309
|
const a = new Error(
|
|
310
310
|
"session id is not defined"
|
|
@@ -398,48 +398,48 @@ class X {
|
|
|
398
398
|
return h(this, arguments, function* (e, t = {
|
|
399
399
|
stream: A.stream
|
|
400
400
|
}) {
|
|
401
|
-
var
|
|
401
|
+
var _;
|
|
402
402
|
try {
|
|
403
403
|
this.validateConfigs();
|
|
404
|
-
} catch (
|
|
405
|
-
console.error(
|
|
404
|
+
} catch (n) {
|
|
405
|
+
console.error(n);
|
|
406
406
|
}
|
|
407
407
|
const {
|
|
408
|
-
stream:
|
|
408
|
+
stream: o = A.stream,
|
|
409
409
|
referenceFirst: a = !1
|
|
410
|
-
} = t, d = e.uuid ||
|
|
410
|
+
} = t, d = e.uuid || x(), r = ((_ = e.text) == null ? void 0 : _.trim()) || "", s = e.files || [], l = e.fileIds, m = e.imageContent;
|
|
411
411
|
if (!r && !s.length && !(l != null && l.length)) {
|
|
412
|
-
const
|
|
412
|
+
const n = new Error(
|
|
413
413
|
"failed at sending empty content"
|
|
414
414
|
/* SendingEmptyContent */
|
|
415
415
|
// {
|
|
416
416
|
// cause: SESSION_ERROR_CAUSE[SessionErrors.SendingEmptyContent],
|
|
417
417
|
// }
|
|
418
418
|
);
|
|
419
|
-
return u.error(
|
|
419
|
+
return u.error(n), this.event.emit("error", n), !1;
|
|
420
420
|
}
|
|
421
421
|
if (!this._id) {
|
|
422
|
-
const
|
|
422
|
+
const n = new Error(
|
|
423
423
|
"session id is not defined"
|
|
424
424
|
/* IdUndefined */
|
|
425
425
|
// {
|
|
426
426
|
// cause: SESSION_ERROR_CAUSE[SessionErrors.IdUndefined],
|
|
427
427
|
// }
|
|
428
428
|
);
|
|
429
|
-
return u.error(
|
|
429
|
+
return u.error(n), this.event.emit("error", n), !1;
|
|
430
430
|
}
|
|
431
431
|
if (this.frozen) {
|
|
432
|
-
const
|
|
432
|
+
const n = new Error(
|
|
433
433
|
"session is frozen"
|
|
434
434
|
/* Frozen */
|
|
435
435
|
// {
|
|
436
436
|
// cause: { code: -1, message: 'session is frozen.' },
|
|
437
437
|
// }
|
|
438
438
|
);
|
|
439
|
-
return u.error(
|
|
439
|
+
return u.error(n), this.event.emit("error", n), !1;
|
|
440
440
|
}
|
|
441
441
|
this.frozen = !0, this._stopAnswer = !1;
|
|
442
|
-
const
|
|
442
|
+
const w = {
|
|
443
443
|
sessionId: this.id,
|
|
444
444
|
role: 2,
|
|
445
445
|
content: r,
|
|
@@ -447,45 +447,47 @@ class X {
|
|
|
447
447
|
reference: [],
|
|
448
448
|
searchReference: [],
|
|
449
449
|
messageTime: "",
|
|
450
|
-
files: s
|
|
451
|
-
|
|
450
|
+
files: s,
|
|
451
|
+
imageContent: m
|
|
452
|
+
}, v = {
|
|
452
453
|
content: r,
|
|
453
|
-
stream:
|
|
454
|
+
stream: o,
|
|
454
455
|
requestId: d,
|
|
455
456
|
fileIds: l,
|
|
456
|
-
referenceFirst: a
|
|
457
|
+
referenceFirst: a,
|
|
458
|
+
imageContent: m
|
|
457
459
|
};
|
|
458
|
-
this.pushMessage(
|
|
459
|
-
const
|
|
460
|
-
if (
|
|
460
|
+
this.pushMessage(w), this.event.emit("question:content", r);
|
|
461
|
+
const y = (n) => h(this, null, function* () {
|
|
462
|
+
if (n.role !== S.Robot)
|
|
461
463
|
return;
|
|
462
|
-
switch (this.removeEventListener("answer:finish",
|
|
463
|
-
finialMessage:
|
|
464
|
+
switch (this.removeEventListener("answer:finish", y), this._id && n.content && n.index && n.index < 0 && (this.data = yield this.cvforceApi.patchSessionsId(this.applicationId, this._id, {
|
|
465
|
+
finialMessage: n.content
|
|
464
466
|
}), this.event.emit("data:updated", this.data), this.event.emit("data:updated:finialMessage", {
|
|
465
|
-
finialMessage:
|
|
466
|
-
})), yield this.fillMessageReference(
|
|
467
|
+
finialMessage: n.content
|
|
468
|
+
})), yield this.fillMessageReference(n), n.code) {
|
|
467
469
|
case 11915:
|
|
468
|
-
|
|
470
|
+
n.content = "请您换个问题问我吧~", n.index = -1, n.isSensitive = !0, n.isLoading = !1, n.sessionId = this._id || "", this.event.emit("message:error", n);
|
|
469
471
|
break;
|
|
470
472
|
case 200:
|
|
471
|
-
|
|
473
|
+
n.index = -1, n.isLoading = !1;
|
|
472
474
|
break;
|
|
473
475
|
default:
|
|
474
|
-
|
|
476
|
+
n.content = n.message || "未知错误", n.isLoading = !1, n.index = -1, this.event.emit("message:error", n);
|
|
475
477
|
}
|
|
476
|
-
this.getRelatedQuesion(
|
|
477
|
-
let
|
|
478
|
-
if (
|
|
479
|
-
const
|
|
480
|
-
this.messages[this.messages.length - 1] =
|
|
478
|
+
this.getRelatedQuesion(n), n.isLoading = !1;
|
|
479
|
+
let g = this.messages[this.messages.length - 1];
|
|
480
|
+
if (g && g.role === S.Robot) {
|
|
481
|
+
const b = f(f({}, g), n);
|
|
482
|
+
this.messages[this.messages.length - 1] = b, this.event.emit("message:updated", b);
|
|
481
483
|
} else
|
|
482
|
-
this.pushMessage(
|
|
484
|
+
this.pushMessage(n);
|
|
483
485
|
this.frozen = !1;
|
|
484
486
|
});
|
|
485
|
-
return this.addEventListener("answer:finish",
|
|
486
|
-
stream:
|
|
487
|
+
return this.addEventListener("answer:finish", y), this.sendQuestion(v, I(f({}, t), {
|
|
488
|
+
stream: o,
|
|
487
489
|
referenceFirst: a
|
|
488
|
-
})),
|
|
490
|
+
})), w;
|
|
489
491
|
});
|
|
490
492
|
}
|
|
491
493
|
getRelatedQuesion(e) {
|
|
@@ -498,7 +500,7 @@ class X {
|
|
|
498
500
|
content: e.content
|
|
499
501
|
}).catch((r) => null);
|
|
500
502
|
if (!t) {
|
|
501
|
-
const r = [], s =
|
|
503
|
+
const r = [], s = I(f({}, e), {
|
|
502
504
|
relatedQuesion: r,
|
|
503
505
|
index: -3,
|
|
504
506
|
isLoading: !1
|
|
@@ -507,22 +509,22 @@ class X {
|
|
|
507
509
|
relatedQuesion: r
|
|
508
510
|
}), this.event.emit("message:updated", s), s;
|
|
509
511
|
}
|
|
510
|
-
const i = (d = t.content) == null ? void 0 : d.split("*").map(
|
|
512
|
+
const i = (d = t.content) == null ? void 0 : d.split("*").map(z).map(P).filter((r) => !!r);
|
|
511
513
|
e.relatedQuesion = i, e.index = -3, e.isLoading = !1;
|
|
512
|
-
const
|
|
514
|
+
const o = I(f({}, e), {
|
|
513
515
|
relatedQuesion: i,
|
|
514
516
|
index: -3,
|
|
515
517
|
isLoading: !1
|
|
516
518
|
});
|
|
517
|
-
return this.event.emit("message:relatedQuesion:loaded",
|
|
519
|
+
return this.event.emit("message:relatedQuesion:loaded", o), this.event.emit("message:updated", o), this._id && this.cvforceApi.patchSessionsId(this._applicationId, this._id, {
|
|
518
520
|
lastRelatedQuestion: i
|
|
519
|
-
}),
|
|
521
|
+
}), o;
|
|
520
522
|
});
|
|
521
523
|
}
|
|
522
524
|
fillMessageReference(e) {
|
|
523
525
|
return h(this, null, function* () {
|
|
524
526
|
const t = yield Promise.all(e.reference.map((i) => this.cvforceApi.getKnowledgeIdFileId(i.knowledgeId, i.docId)));
|
|
525
|
-
return e.reference = e.reference.map((i,
|
|
527
|
+
return e.reference = e.reference.map((i, o) => f(f({}, i), t[o])), this.event.emit("message:updated", e), e;
|
|
526
528
|
});
|
|
527
529
|
}
|
|
528
530
|
answerAgain() {
|
|
@@ -536,14 +538,14 @@ class X {
|
|
|
536
538
|
const {
|
|
537
539
|
stream: i = A.stream
|
|
538
540
|
} = e;
|
|
539
|
-
let
|
|
540
|
-
t.role !== S.User && (
|
|
541
|
+
let o;
|
|
542
|
+
t.role !== S.User && (o = e.oldMessageId || t.messageId, this.messages.splice(this.messages.length - 1, 1), this.event.emit("message:remove", t), this.event.emit("history:remove", t));
|
|
541
543
|
const a = this.messages[this.messages.length - 1], d = {
|
|
542
544
|
content: a.content,
|
|
543
545
|
fileIds: a.fileIds,
|
|
544
546
|
requestId: a.messageId,
|
|
545
547
|
stream: i,
|
|
546
|
-
oldMessageId:
|
|
548
|
+
oldMessageId: o
|
|
547
549
|
}, r = (s) => h(this, null, function* () {
|
|
548
550
|
if (s.role === S.Robot && s.index === -1) {
|
|
549
551
|
switch (this._id && s.content && s.index && s.index < 0 && (this.data = yield this.cvforceApi.patchSessionsId(this.applicationId, this._id, {
|
|
@@ -563,7 +565,7 @@ class X {
|
|
|
563
565
|
this.getRelatedQuesion(s), this.removeEventListener("message:content", r), this.frozen = !1;
|
|
564
566
|
}
|
|
565
567
|
});
|
|
566
|
-
this.addEventListener("message:content", r), this.sendQuestion(d,
|
|
568
|
+
this.addEventListener("message:content", r), this.sendQuestion(d, I(f({}, e), {
|
|
567
569
|
stream: i
|
|
568
570
|
}));
|
|
569
571
|
});
|
|
@@ -590,13 +592,13 @@ class X {
|
|
|
590
592
|
this.stopAnswer(), this.frozen = !1, this._stopAnswer = !0;
|
|
591
593
|
let e = this.messages[this.messages.length - 1];
|
|
592
594
|
const t = {
|
|
593
|
-
messageId:
|
|
595
|
+
messageId: x(),
|
|
594
596
|
// 生成唯一的消息 ID
|
|
595
597
|
isLoading: !1,
|
|
596
598
|
// 标记消息已停止加载
|
|
597
599
|
index: -2,
|
|
598
600
|
// 消息索引,用于标识特殊状态
|
|
599
|
-
messageTime:
|
|
601
|
+
messageTime: U(/* @__PURE__ */ new Date()).format("YYYY-MM-DD HH:ss:mm"),
|
|
600
602
|
// 消息时间
|
|
601
603
|
content: "",
|
|
602
604
|
// 消息内容
|
|
@@ -613,9 +615,9 @@ class X {
|
|
|
613
615
|
if (e.index === -2)
|
|
614
616
|
return;
|
|
615
617
|
if (e.actions) {
|
|
616
|
-
const
|
|
617
|
-
if (
|
|
618
|
-
const a =
|
|
618
|
+
const o = e.actions[((i = e.actions) == null ? void 0 : i.length) - 1];
|
|
619
|
+
if (o) {
|
|
620
|
+
const a = o[o.length - 1];
|
|
619
621
|
if (a && (a.type === "BEFORE_CALL" || a.type === "FUNCTION_CALL")) {
|
|
620
622
|
const {
|
|
621
623
|
pluginName: d,
|
|
@@ -623,7 +625,7 @@ class X {
|
|
|
623
625
|
funcCode: s,
|
|
624
626
|
funcName: l
|
|
625
627
|
} = a.data;
|
|
626
|
-
|
|
628
|
+
o.push({
|
|
627
629
|
data: {
|
|
628
630
|
pluginName: d,
|
|
629
631
|
pluginCode: r,
|
|
@@ -634,7 +636,7 @@ class X {
|
|
|
634
636
|
type: "ABORT"
|
|
635
637
|
}), this.event.emit("message:action", {
|
|
636
638
|
messageId: e.messageId,
|
|
637
|
-
action:
|
|
639
|
+
action: o
|
|
638
640
|
});
|
|
639
641
|
}
|
|
640
642
|
}
|
|
@@ -652,7 +654,7 @@ class X {
|
|
|
652
654
|
handleStreamAnswer(e, t) {
|
|
653
655
|
if (!e.data)
|
|
654
656
|
return;
|
|
655
|
-
const i = e.data.type,
|
|
657
|
+
const i = e.data.type, o = e.data.payload;
|
|
656
658
|
t.isReplying = !0;
|
|
657
659
|
const a = () => {
|
|
658
660
|
if (!t.searchingStatus) {
|
|
@@ -664,22 +666,22 @@ class X {
|
|
|
664
666
|
return;
|
|
665
667
|
}
|
|
666
668
|
};
|
|
667
|
-
if (i === "error" && (t.index = -1), i === "beforeSearch" && a(), i === "searchOver" && a(), i === "search" && t.searchReference.push(
|
|
669
|
+
if (i === "error" && (t.index = -1), i === "beforeSearch" && a(), i === "searchOver" && a(), i === "search" && t.searchReference.push(o), i === "thinking") {
|
|
668
670
|
t.thinkingStatus = "start";
|
|
669
|
-
const r =
|
|
671
|
+
const r = o.choices[0];
|
|
670
672
|
t.reasoningContent = t.reasoningContent + r.delta.reasoningContent;
|
|
671
673
|
}
|
|
672
674
|
if (i === "thinkingOver") {
|
|
673
675
|
t.thinkingStatus = "end";
|
|
674
|
-
const d =
|
|
676
|
+
const d = o.thinkingSecs;
|
|
675
677
|
t.thinkingSecs = d;
|
|
676
678
|
}
|
|
677
679
|
if (i === "text") {
|
|
678
|
-
const r =
|
|
680
|
+
const r = o.choices[0];
|
|
679
681
|
t.content = t.content + r.delta.content;
|
|
680
682
|
}
|
|
681
|
-
if (i === "reference" && (t.reference =
|
|
682
|
-
const d =
|
|
683
|
+
if (i === "reference" && (t.reference = o), i === "updateSession" && o && this.data && (this.data = f(f({}, this.data), o), this.event.emit("data:updated", this.data)), i === "result") {
|
|
684
|
+
const d = o.messageId, r = o.llmModel, s = o.messageTime;
|
|
683
685
|
t.messageId = d, t.llmModel = r, t.messageTime = s;
|
|
684
686
|
}
|
|
685
687
|
i === "over" ? t.index = -1 : (t.code = e.code, t.message = e.message);
|
|
@@ -694,7 +696,7 @@ class X {
|
|
|
694
696
|
if (!this._applicationId || !this._id)
|
|
695
697
|
throw Error("session is not avalible. id is undefined");
|
|
696
698
|
return this.cvforceApi.postComments(this._applicationId, this._id, e).then((t) => {
|
|
697
|
-
const i = this.messages.find((
|
|
699
|
+
const i = this.messages.find((o) => o.messageId === e.messageId);
|
|
698
700
|
return i && (i.comment = e, this.event.emit("message:comment", i)), t;
|
|
699
701
|
});
|
|
700
702
|
});
|
|
@@ -722,6 +724,6 @@ class X {
|
|
|
722
724
|
}
|
|
723
725
|
}
|
|
724
726
|
export {
|
|
725
|
-
|
|
726
|
-
|
|
727
|
+
H as SessionErrors,
|
|
728
|
+
Z as default
|
|
727
729
|
};
|
package/dist/es/package.json.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e = "@glodon-aiot/bot-client-sdk", t = "3.
|
|
1
|
+
const e = "@glodon-aiot/bot-client-sdk", t = "3.6.0-alpha.5", 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.5.0-alpha.3", i = "glodoncv", s
|
|
|
59
59
|
access: "public",
|
|
60
60
|
registry: "https://registry.npmjs.org/"
|
|
61
61
|
}, b = {
|
|
62
|
-
"@glodon-aiot/apis": "^3.
|
|
62
|
+
"@glodon-aiot/apis": "^3.6.0-alpha.5",
|
|
63
63
|
axios: "0.24.0",
|
|
64
64
|
buffer: "^6.0.3",
|
|
65
65
|
dayjs: "^1.11.13",
|
package/dist/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var T=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var $=(c,e,t)=>e in c?se(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t,g=(c,e)=>{for(var t in e||(e={}))B.call(e,t)&&$(c,t,e[t]);if(T)for(var t of T(e))F.call(e,t)&&$(c,t,e[t]);return c},y=(c,e)=>ie(c,ne(e));var J=(c,e)=>{var t={};for(var s in c)B.call(c,s)&&e.indexOf(s)<0&&(t[s]=c[s]);if(c!=null&&T)for(var s of T(c))e.indexOf(s)<0&&F.call(c,s)&&(t[s]=c[s]);return t};var m=(c,e,t)=>($(c,typeof e!="symbol"?e+"":e,t),t);var 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 ae=require("js-base64"),re=require("axios"),v=require("@glodon-aiot/apis"),oe=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 ce=new S("[Config] ");var G=(c=>(c.dev="https://aiot-dev.glodon.com/api/cvforcepd",c.test="https://aiot-dev.glodon.com/api/cvforce",c.prod="https://copilot.glodon.com/api/cvforce",c.local="http://localhost:3000/api/cvforcepd",c))(G||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function Q(c){S.debug=(c==null?void 0:c.debug)||!1,exports.configuration=y(g(g({},exports.configuration),c),{apiRoot:(c==null?void 0:c.apiRoot)||exports.configuration.apiRoot||(c!=null&&c.env?G[c.env||"prod"]:exports.configuration.apiRoot)}),S.debug&&ce.log("updated",exports.configuration)}const E=c=>JSON.parse(ae.decode(c.split(".")[1])),de=c=>{const e=E(c).exp;return new Date().valueOf()/1e3>=e},he=c=>c==null?void 0:c.replace(/[\r\n]+/gm,""),le=c=>c.replace(/\\|\\/g,"");function X(c,e,t){const s=d=>{var l;return e&&(de(e)&&t(403,"aiotToken is timeout"),d.headers=(l=d.headers)!=null?l:{},d.headers=y(g({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function r(d,l=!0){const h=`${c}${d}`,u=re.create({baseURL:h});return l&&u.interceptors.request.use(s),u}const a=(d,l)=>{d===401&&t(d,"aiotToken is invalid")},i=(d,l)=>{d!==10001&&d!==10215&&t(d,l)},o=r("/data/v1");return new v.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 Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&R.disable()}getEventListenerMap(){return g({},this.eventListenerMap)}on(e,t,s=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),s?this.eventListenerMap[e].push({fn:t,once:!0}):this.eventListenerMap[e].push(t),R.log(`add event ${e} listener ${s?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const s=this.eventListenerMap[e].findIndex(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 _=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 q{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 Z);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);m(this,"_mcpServers",null);this.token=e,this.lazyload=r,this.client=i||null,this._applicationId=E(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 l;this._id=d.id,this.data=y(g({},d),{knowledges:s==null?void 0:s.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),yield(()=>f(this,null,function*(){if(s!=null&&s.knowledges)return this.setKnowledges((s==null?void 0:s.knowledges)||void 0)}))(),yield(()=>{if(s!=null&&s.promptVariables){const h=this._promptVariables.map(u=>{var p,I;const w=((I=(p=s.promptVariables)==null?void 0:p.find(b=>b.key===u.key&&b.type===u.type))==null?void 0:I.value)||"";return y(g({},u),{value:w})}).sort((u,w)=>u.key.localeCompare(w.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),((l=this.application)==null?void 0:l.type)!==v.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");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===v.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===v.PromptVariableType.User&&e.key==="query")&&!(e.type===v.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return f(this,null,function*(){const t=e==null?void 0:e.map(a=>a.type?a:y(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 y(g({},a),{value:i})}).sort((a,i)=>a.key.localeCompare(i.key));if(!(yield Promise.all(s.filter(a=>!(a.type===v.PromptVariableType.User&&a.key==="query")&&!(a.type===v.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(_.log("setNetOpen:",e),_.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===v.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,_.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return X(exports.configuration.apiRoot,this.token,(e,t)=>{const s=new Error("data request error",{cause:{status:e,message:t}});_.error(s),this.event.emit("error",s)})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}fetchMessages(){return 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"),_.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),_.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,w;let l=[],h;return typeof((u=n.agentHistoryList)==null?void 0:u.agentList)=="string"&&(l=JSON.parse(n.agentHistoryList.agentList).reduce((I,b)=>(I[b.data.step-1]||(I[b.data.step-1]=[]),I[b.data.step-1].push(b),I),[])),d===a.length-1&&(h=(w=this.data)==null?void 0:w.lastRelatedQuestion),y(g({},n),{actions:l,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(l=>l.ts===e.endTime),d=this.messages.findLastIndex(l=>l.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),_.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 _.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}),_.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),_.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),_.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 _.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 w;try{this.validateConfigs()}catch(p){console.error(p)}const{stream:r=exports.configuration.stream,referenceFirst:a=!1}=t,i=e.uuid||Y.v4(),o=((w=e.text)==null?void 0:w.trim())||"",n=e.files||[],d=e.fileIds;if(!o&&!n.length&&!(d!=null&&d.length)){const p=new Error("failed at sending empty content");return _.error(p),this.event.emit("error",p),!1}if(!this._id){const p=new Error("session id is not defined");return _.error(p),this.event.emit("error",p),!1}if(this.frozen){const p=new Error("session is frozen");return _.error(p),this.event.emit("error",p),!1}this.frozen=!0,this._stopAnswer=!1;const l={sessionId:this.id,role:2,content:o,messageId:i,reference:[],searchReference:[],messageTime:"",files:n},h={content:o,stream:r,requestId:i,fileIds:d,referenceFirst:a};this.pushMessage(l),this.event.emit("question:content",o);const u=p=>f(this,null,function*(){if(p.role!==v.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",u),this._id&&p.content&&p.index&&p.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:p.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:p.content})),yield this.fillMessageReference(p),p.code){case 11915:p.content="请您换个问题问我吧~",p.index=-1,p.isSensitive=!0,p.isLoading=!1,p.sessionId=this._id||"",this.event.emit("message:error",p);break;case 200:p.index=-1,p.isLoading=!1;break;default:p.content=p.message||"未知错误",p.isLoading=!1,p.index=-1,this.event.emit("message:error",p)}this.getRelatedQuesion(p),p.isLoading=!1;let I=this.messages[this.messages.length-1];if(I&&I.role===v.ChatMessageRole.Robot){const b=g(g({},I),p);this.messages[this.messages.length-1]=b,this.event.emit("message:updated",b)}else this.pushMessage(p);this.frozen=!1});return this.addEventListener("answer:finish",u),this.sendQuestion(h,y(g({},t),{stream:r,referenceFirst:a})),l})}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=y(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(he).map(le).filter(o=>!!o);e.relatedQuesion=s,e.index=-3,e.isLoading=!1;const r=y(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*(){const t=yield Promise.all(e.reference.map(s=>this.cvforceApi.getKnowledgeIdFileId(s.knowledgeId,s.docId)));return e.reference=e.reference.map((s,r)=>g(g({},s),t[r])),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!==v.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===v.ChatMessageRole.Robot&&n.index===-1){switch(this._id&&n.content&&n.index&&n.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:n.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:n.content})),yield this.fillMessageReference(n),n.code){case 11915:n.content="请您换个问题问我吧~",n.index=-1,n.isSensitive=!0,n.isLoading=!1,n.sessionId=this._id||"",this.event.emit("message:error",n);break;case 200:n.index=-1,n.isLoading=!1;break;default:n.content=n.message||"未知错误",n.isLoading=!1,n.index=-1,this.event.emit("message:error",n)}this.getRelatedQuesion(n),this.removeEventListener("message:content",o),this.frozen=!1}});this.addEventListener("message:content",o),this.sendQuestion(i,y(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:v.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 A=new S("[AgentSession] ");class pe extends q{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 oe.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});r.on("connect",()=>{A.log("socket:connect"),this.event.emit("socket:connect"),r.emit("init")}),r.on("disconnect",()=>{A.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),r.on("ready",a=>{if(a.code===200){A.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);A.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:l,parameters:h,requestBody:u}}=a,w=this.messages[this.messages.length-1];if(!w.messageId)w.actions||(w.actions=[]),w.actions[a.data.step-1]||(w.actions[a.data.step-1]=[]),w.actions[a.data.step-1].push(a),this.event.emit("message:action",{messageId:w.messageId,action:a}),this.event.emit("message:updated",w);else{const p={messageId:"",content:"",role:v.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[a]],comment:{isAgree:0},isReplying:!0};this.pushMessage(p),this.event.emit("message:action",{messageId:p.messageId,action:a})}if(this.inactivating){const p=new Error(L.Inactive);A.warn("error",p),this.event.emit("error",p)}else if(o==="FUNCTION_CALL"&&n){if(A.log(`calling function ${l} of plugin ${d} with argument:
|
|
2
|
-
${JSON.stringify(h)}`),!exports.configuration.plugins[d]){i({code:404,message:"对不起,没有找到插件。"});return}const
|
|
1
|
+
"use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var E=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var Q=(c,e,t)=>e in c?se(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t,g=(c,e)=>{for(var t in e||(e={}))B.call(e,t)&&Q(c,t,e[t]);if(E)for(var t of E(e))F.call(e,t)&&Q(c,t,e[t]);return c},w=(c,e)=>ie(c,ne(e));var J=(c,e)=>{var t={};for(var s in c)B.call(c,s)&&e.indexOf(s)<0&&(t[s]=c[s]);if(c!=null&&E)for(var s of E(c))e.indexOf(s)<0&&F.call(c,s)&&(t[s]=c[s]);return t};var m=(c,e,t)=>(Q(c,typeof e!="symbol"?e+"":e,t),t);var p=(c,e,t)=>new Promise((s,r)=>{var n=a=>{try{o(t.next(a))}catch(d){r(d)}},i=a=>{try{o(t.throw(a))}catch(d){r(d)}},o=a=>a.done?s(a.value):Promise.resolve(a.value).then(n,i);o((t=t.apply(c,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),re=require("axios"),y=require("@glodon-aiot/apis"),oe=require("socket.io-client"),Y=require("uuid"),q=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 ce=new S("[Config] ");var G=(c=>(c.dev="https://aiot-dev.glodon.com/api/cvforcepd",c.test="https://aiot-dev.glodon.com/api/cvforce",c.prod="https://copilot.glodon.com/api/cvforce",c.local="http://localhost:3000/api/cvforcepd",c))(G||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function 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?G[c.env||"prod"]:exports.configuration.apiRoot)}),S.debug&&ce.log("updated",exports.configuration)}const P=c=>JSON.parse(ae.decode(c.split(".")[1])),de=c=>{const e=P(c).exp;return new Date().valueOf()/1e3>=e},he=c=>c==null?void 0:c.replace(/[\r\n]+/gm,""),le=c=>c.replace(/\\|\\/g,"");function X(c,e,t){const s=d=>{var l;return e&&(de(e)&&t(403,"aiotToken is timeout"),d.headers=(l=d.headers)!=null?l:{},d.headers=w(g({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function r(d,l=!0){const h=`${c}${d}`,f=re.create({baseURL:h});return l&&f.interceptors.request.use(s),f}const n=(d,l)=>{d===401&&t(d,"aiotToken is invalid")},i=(d,l)=>{d!==10001&&d!==10215&&t(d,l)},o=r("/data/v1");return new y.CVForceApi(o,{onHttpStatusError:n,onAppStatusError:i})}var x=(c=>(c[c.Normal=0]="Normal",c[c.Debug=1]="Debug",c))(x||{});const R=new S("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&R.disable()}getEventListenerMap(){return g({},this.eventListenerMap)}on(e,t,s=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),s?this.eventListenerMap[e].push({fn:t,once:!0}):this.eventListenerMap[e].push(t),R.log(`add event ${e} listener ${s?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const s=this.eventListenerMap[e].findIndex(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 n=this.eventListenerMap[e][r];typeof n=="function"?n(t):s.push(n)}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 _=new S("[Session] ");var C=(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))(C||{});class N{constructor(e,t="",s,r,n,i){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new Z);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);m(this,"_mcpServers",null);this.token=e,this.lazyload=r,this.client=i||null,this._applicationId=P(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),n&&(this._application=n),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(a=>p(this,null,function*(){this.data=a,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data)})))):(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(a=>p(this,null,function*(){this.data=a,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoading=!1,this._dataLoaded=!0})));else{const a=(s==null?void 0:s.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:a}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:a,netOpen:s==null?void 0:s.netOpen,knowledgeIdList:(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 l;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),yield(()=>p(this,null,function*(){if(s!=null&&s.knowledges)return this.setKnowledges((s==null?void 0:s.knowledges)||void 0)}))(),yield(()=>{if(s!=null&&s.promptVariables){const h=this._promptVariables.map(f=>{var I,u;const v=((u=(I=s.promptVariables)==null?void 0:I.find(b=>b.key===f.key&&b.type===f.type))==null?void 0:u.value)||"";return w(g({},f),{value:v})}).sort((f,v)=>f.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),((l=this.application)==null?void 0:l.type)!==y.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}fetchData(){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.getSession(this.applicationId,this.data.id).then(e=>p(this,null,function*(){return this.data=e,this.event.emit("data:updated",this.data),e}))})}get id(){var e;return this._id||((e=this.data)==null?void 0:e.id)||""}get applicationId(){return this._applicationId}get application(){return this._application}set application(e){this._application=e}loadApplicationInfo(){if(this._application)return Promise.resolve(this._application);if(this._applicationId&&!this._application)return this.event.emit("application:data:loading"),this.cvforceApi.getApplicationId(this._applicationId).then(e=>(this._application=e,this.event.emit("application:data:loaded",e),e));throw Error("application id is not defined")}get ready(){return this._ready}get frozen(){return this._frozen}set frozen(e){e===!1&&this.inactivating&&this.socket&&(this.socket.disconnect(),this.socket=null,this.event.emit("inactivated")),this._frozen=e,this.event.emit("frozen",e)}get knowledges(){if(!this.data)throw Error("session data is not loaded");return this.data.knowledges||void 0}setKnowledges(e){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(t=>t.status===y.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>!(e.type===y.PromptVariableType.User&&e.key==="query")&&!(e.type===y.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return p(this,null,function*(){const t=e==null?void 0:e.map(n=>n.type?n:w(g({},n),{type:"instruction"})),s=this._promptVariables.map(n=>{var o;const i=((o=t==null?void 0:t.find(a=>a.key===n.key&&a.type===n.type))==null?void 0:o.value)||n.value;return w(g({},n),{value:i})}).sort((n,i)=>n.key.localeCompare(i.key));if(!(yield Promise.all(s.filter(n=>!(n.type===y.PromptVariableType.User&&n.key==="query")&&!(n.type===y.PromptVariableType.System&&n.key==="datetime")).map(n=>{if(!this.data)throw Error("session data is not loaded");if(!(!n.id||!n.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,n.id,{value:n.value})})).then(()=>!0).catch(n=>!1)))return!1;if(!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return p(this,null,function*(){var t,s,r;if(_.log("setNetOpen:",e),_.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===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,_.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return X(exports.configuration.apiRoot,this.token,(e,t)=>{const s=new Error("data request error",{cause:{status:e,message:t}});_.error(s),this.event.emit("error",s)})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}fetchMessages(){return p(this,arguments,function*(e={}){var s,r;const t={pageSize:this._loadingMessagesSize};if(this._id){e=g(g({},t),e),this.event.emit("history:loading"),_.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),_.log("history:moreloading",e)),this._loadingMessages=!0;const n=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),i=n.map((a,d)=>{var f,v;let l=[],h;return typeof((f=a.agentHistoryList)==null?void 0:f.agentList)=="string"&&(l=JSON.parse(a.agentHistoryList.agentList).reduce((u,b)=>(u[b.data.step-1]||(u[b.data.step-1]=[]),u[b.data.step-1].push(b),u),[])),d===n.length-1&&(h=(v=this.data)==null?void 0:v.lastRelatedQuestion),w(g({},a),{actions:l,relatedQuesion:h})});if(!e.endTime&&!e.startTime){const a=this.messages[this.messages.length-1];a&&!a.relatedQuesion&&(a.relatedQuesion=(s=this.data)==null?void 0:s.lastRelatedQuestion),this.messages=[...i,...this.messages]}else if(e.endTime&&!e.startTime){const a=this.messages.findIndex(d=>d.ts===e.endTime);this.messages.splice(0,a+1),this.messages=[...i,...this.messages]}else if(!e.endTime&&e.startTime){const a=this.messages.findLastIndex(d=>d.ts===e.endTime);this.messages.splice(a,this.messages.length-a-1),this.messages=[...this.messages,...i]}else{const a=this.messages.findIndex(l=>l.ts===e.endTime),d=this.messages.findLastIndex(l=>l.ts===e.endTime);this.messages.splice(a,d-a+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),_.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,i}else{const n=new Error("session id is not defined");return _.error(n),this.event.emit("error",n),!1}})}rename(e){return p(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),_.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return p(this,null,function*(){this.messages.push(e),_.log("history:add",e),this.event.emit("history:add",e),this.event.emit("message:new",e),this.event.emit("message:updated",e)})}reloadSessionInfo(){if(!this._id)throw Error("session is not created yet");return this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,this._id).then(e=>p(this,null,function*(){if(this.data=e,!this._id)throw Error("session is not created yet");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),_.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>p(this,null,function*(){return this.messages=[],yield this.fetchMessages(),this._dataLoading=!1,this._dataLoaded=!0,this.event.emit("data:loaded",this.data),this}))}reload(){return p(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return p(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return _.error(e),this.event.emit("error",e),!1}return this.event.emit("data:deleting"),yield this.cvforceApi.delSessionsId(this.applicationId,this.id),this.event.emit("data:deleted"),this.destroy()})}activate(){return p(this,null,function*(){if(this.activing)return new Promise(t=>{this.addEventListener("activated",()=>{t(!0)},!0)});if(!this._id)throw Error("session is not avalible. id is undefined");this.activing=!0;const e=this._id;return this._dataLoading=!0,this._dataLoaded=!1,this.data=yield this.cvforceApi.getSession(this.applicationId,e).then(t=>p(this,null,function*(){return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,e),t})),this.messages.length||(this.messages=[],yield this.fetchMessages()),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoaded=!0,this._dataLoading=!1,this.inactivating=!1,this.frozen=!0,yield this.prepareConnection(),this.event.emit("activated",this.socket),this.active=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?this._frozen?(e||(this.inactivating=!0),this.activing=!1,!0):(this.socket.close(),this.socket=null,this.event.emit("inactivated"),this.active=!1,this.activing=!1,!0):(this.activing=!1,!0)}get dataLoaded(){return this._dataLoaded}get messagesLoading(){return this._loadingMessages}send(s){return p(this,arguments,function*(e,t={stream:exports.configuration.stream}){var I;try{this.validateConfigs()}catch(u){console.error(u)}const{stream:r=exports.configuration.stream,referenceFirst:n=!1}=t,i=e.uuid||Y.v4(),o=((I=e.text)==null?void 0:I.trim())||"",a=e.files||[],d=e.fileIds,l=e.imageContent;if(!o&&!a.length&&!(d!=null&&d.length)){const u=new Error("failed at sending empty content");return _.error(u),this.event.emit("error",u),!1}if(!this._id){const u=new Error("session id is not defined");return _.error(u),this.event.emit("error",u),!1}if(this.frozen){const u=new Error("session is frozen");return _.error(u),this.event.emit("error",u),!1}this.frozen=!0,this._stopAnswer=!1;const h={sessionId:this.id,role:2,content:o,messageId:i,reference:[],searchReference:[],messageTime:"",files:a,imageContent:l},f={content:o,stream:r,requestId:i,fileIds:d,referenceFirst:n,imageContent:l};this.pushMessage(h),this.event.emit("question:content",o);const v=u=>p(this,null,function*(){if(u.role!==y.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",v),this._id&&u.content&&u.index&&u.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:u.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:u.content})),yield this.fillMessageReference(u),u.code){case 11915:u.content="请您换个问题问我吧~",u.index=-1,u.isSensitive=!0,u.isLoading=!1,u.sessionId=this._id||"",this.event.emit("message:error",u);break;case 200:u.index=-1,u.isLoading=!1;break;default:u.content=u.message||"未知错误",u.isLoading=!1,u.index=-1,this.event.emit("message:error",u)}this.getRelatedQuesion(u),u.isLoading=!1;let b=this.messages[this.messages.length-1];if(b&&b.role===y.ChatMessageRole.Robot){const L=g(g({},b),u);this.messages[this.messages.length-1]=L,this.event.emit("message:updated",L)}else this.pushMessage(u);this.frozen=!1});return this.addEventListener("answer:finish",v),this.sendQuestion(f,w(g({},t),{stream:r,referenceFirst:n})),h})}getRelatedQuesion(e){return p(this,null,function*(){var n,i;if(!e.content||e.isSensitive||e.code!==200||!((n=this.application)!=null&&n.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=[],a=w(g({},e),{relatedQuesion:o,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:o}),this.event.emit("message:updated",a),a}const s=(i=t.content)==null?void 0:i.split("*").map(he).map(le).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*(){const t=yield Promise.all(e.reference.map(s=>this.cvforceApi.getKnowledgeIdFileId(s.knowledgeId,s.docId)));return e.reference=e.reference.map((s,r)=>g(g({},s),t[r])),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 n=this.messages[this.messages.length-1],i={content:n.content,fileIds:n.fileIds,requestId:n.messageId,stream:s,oldMessageId:r},o=a=>p(this,null,function*(){if(a.role===y.ChatMessageRole.Robot&&a.index===-1){switch(this._id&&a.content&&a.index&&a.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:a.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:a.content})),yield this.fillMessageReference(a),a.code){case 11915:a.content="请您换个问题问我吧~",a.index=-1,a.isSensitive=!0,a.isLoading=!1,a.sessionId=this._id||"",this.event.emit("message:error",a);break;case 200:a.index=-1,a.isLoading=!1;break;default:a.content=a.message||"未知错误",a.isLoading=!1,a.index=-1,this.event.emit("message:error",a)}this.getRelatedQuesion(a),this.removeEventListener("message:content",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:q(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 n=r[r.length-1];if(n&&(n.type==="BEFORE_CALL"||n.type==="FUNCTION_CALL")){const{pluginName:i,pluginCode:o,funcCode:a,funcName:d}=n.data;r.push({data:{pluginName:i,pluginCode:o,funcCode:a,funcName:d,step:n.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 n=()=>{if(!t.searchingStatus){t.searchingStatus="start";return}if(t.searchingStatus==="start"){t.searchingStatus="end";return}};if(s==="error"&&(t.index=-1),s==="beforeSearch"&&n(),s==="searchOver"&&n(),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,a=r.messageTime;t.messageId=i,t.llmModel=o,t.messageTime=a}s==="over"?t.index=-1:(t.code=e.code,t.message=e.message)}postMessageComment(e){return p(this,null,function*(){if(!this._applicationId||!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.postComments(this._applicationId,this._id,e).then(t=>{const s=this.messages.find(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 A=new S("[AgentSession] ");class pe extends N{constructor(e,t="",s,r,n,i){super(e,t,s,r,n,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 oe.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});r.on("connect",()=>{A.log("socket:connect"),this.event.emit("socket:connect"),r.emit("init")}),r.on("disconnect",()=>{A.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),r.on("ready",n=>{if(n.code===200){A.log("ready");const i=exports.configuration.debug?x.Debug:x.Normal;i===x.Debug&&n.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(C.SocketConnectionFailed);A.error("error",i),this.event.emit("error",i),e(!1)}}),r.on("action",(n,i)=>p(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:o,data:{runnerIsClient:a,pluginCode:d,funcCode:l,parameters:h,requestBody:f}}=n,v=this.messages[this.messages.length-1];if(!v.messageId)v.actions||(v.actions=[]),v.actions[n.data.step-1]||(v.actions[n.data.step-1]=[]),v.actions[n.data.step-1].push(n),this.event.emit("message:action",{messageId:v.messageId,action:n}),this.event.emit("message:updated",v);else{const I={messageId:"",content:"",role:y.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[n]],comment:{isAgree:0},isReplying:!0};this.pushMessage(I),this.event.emit("message:action",{messageId:I.messageId,action:n})}if(this.inactivating){const I=new Error(C.Inactive);A.warn("error",I),this.event.emit("error",I)}else if(o==="FUNCTION_CALL"&&a){if(A.log(`calling function ${l} of plugin ${d} with argument:
|
|
2
|
+
${JSON.stringify(h)}`),!exports.configuration.plugins[d]){i({code:404,message:"对不起,没有找到插件。"});return}const I=exports.configuration.plugins[d][l];typeof I!="function"&&i({code:404,message:"对不起,没有找到插件方法。"});let u=h==null?void 0:h.query;try{u=JSON.parse(h==null?void 0:h.query)}catch(b){}I(u,(...b)=>{this._stopAnswer||i(...b)})}})),r.on("answer",n=>{if(!this._stopAnswer)if(n.data.code!==200&&(n.data.index=-1,this.event.emit("error",n.data)),n.data.stream||n.data.stream===void 0){let i=this.messages[this.messages.length-1];if(i&&i.role===y.ChatMessageRole.Robot)this.handleStreamAnswer(n.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:q(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};this.handleStreamAnswer(n.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(n.data.updateSession&&this.data&&(this.data=g(g({},this.data),n.data.updateSession),this.event.emit("data:updated",this.data)),n.data.index===-1){let i=this.messages[this.messages.length-1];if(i&&!i.messageId)i=g(g({},i),n.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},n.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),n.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},n.data)),this.event.emit("message:content",n.data))}}),r.on("reference",n=>p(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const h=new Error(C.IdUndefined);A.error(h),this.event.emit("error",h),this.frozen=!1;return}const{type:i,data:o,requestId:a}=n,d=this.messages.findIndex(h=>h.messageId===a&&h.role===y.ChatMessageRole.User);if(d<0)return;const l=d+1;if(l>=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[l]=w(g({},this.messages[l]),{reference:o.knowledgeReference}),yield this.fillMessageReference(this.messages[l]),this.event.emit("message:reference",o.knowledgeReference),this.event.emit("message:updated",this.messages[l])):i==="WEB_SEARCH"&&(this.messages[l]=w(g({},this.messages[l]),{searchReference:o.knowledgeReference}),this.event.emit("message:searchreference",o.searchReference),this.event.emit("message:updated",this.messages[l]))})),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 p(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(n=>{r.data[n].code!==200&&console.error(n,"MCP Server 注册失败。",r.data[n])}),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 p(this,null,function*(){return this.ready?this.socket?new Promise((e,t)=>{this.socket&&this.socket.emit("list_mcp_servers",s=>{s.code===200?e(s.data):t(s)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(e,t){return p(this,null,function*(){var r,n,i;let s=w(g({},e),{promptVariables:this.promptVariables.filter(o=>o.type===y.PromptVariableType.User).reduce((o,a)=>w(g({},o),{[a.key]:a.value}),{}),systemPromptVariables:this.promptVariables.filter(o=>o.type===y.PromptVariableType.System).reduce((o,a)=>w(g({},o),{[a.key]:a.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(C.SocketConnectionFailed);return A.warn("error",o),this.event.emit("error",o),!1}(n=this.socket)==null||n.emit("question",s);return}(i=this.socket)==null||i.emit("question",s)})}stopAnswer(){var e;(e=this.socket)==null||e.emit("stop_answer")}}function fe(c,e){return p(this,null,function*(){const t=c.getReader();let s;for(;!(s=yield t.read()).done;)e(s.value)})}function ue(c){let e,t,s,r=!1,n;return function(o){e===void 0?(e=o,t=0,s=-1,n=!1):e=me(e,o);const a=e.length;let d=0;for(;t<a;){r&&(e[t]===10&&(d=++t),r=!1);let l=-1;for(;t<a&&l===-1;++t)switch(e[t]){case 58:s===-1&&(s=t-d);break;case 13:r=!1,t+4<a&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(n=!0);case 10:l=t;break}if(l===-1)break;c(e.subarray(d,l),s,n),d=t,s=-1,n=!1}d===a?e=void 0:d!==0&&(e=e.subarray(d),t-=d)}}function ge(c,e,t){let s=H();const r=new TextDecoder;return function(i,o,a){if(i.length===0)t==null||t(s),s=H();else if(o>0){const d=r.decode(i.subarray(0,o)),l=o+(i[o+1]===32?2:1);let h=r.decode(i.subarray(l));switch(a&&(h+=`
|
|
3
3
|
`),d){case"data":s.data=s.data?s.data+`
|
|
4
|
-
`+h:h;break;case"event":s.event=h;break;case"id":c(s.id=h);break;case"retry":const u=parseInt(h,10);isNaN(u)||e(s.retry=u);break}}}}function me(c,e){const t=new Uint8Array(c.length+e.length);return t.set(c),t.set(e,c.length),t}function H(){return{data:"",event:"",id:"",retry:void 0}}const z="text/event-stream",ve=1e3,U="last-event-id";function W(c,l){var h=l,{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,w)=>{const p=g({},t);p.accept||(p.accept=z);let I;function b(){I.abort(),document.hidden||O()}o||document.addEventListener("visibilitychange",b);let N=ve,P=0;function V(){document.removeEventListener("visibilitychange",b),window.clearTimeout(P),I.abort()}e==null||e.addEventListener("abort",()=>{V(),u()});const ee=n!=null?n:window.fetch,te=s!=null?s:ye;function O(){return f(this,null,function*(){var D;I=new AbortController;try{const C=yield ee(c,y(g({},d),{headers:p,signal:I.signal}));yield te(C),yield fe(C.body,ue(ge(k=>{k?p[U]=k:delete p[U]},k=>{N=k},r))),a==null||a(),V(),u()}catch(C){if(!I.signal.aborted)try{const k=(D=i==null?void 0:i(C))!=null?D:N;window.clearTimeout(P),P=window.setTimeout(O,k)}catch(k){V(),w(k)}}})}O()})}function ye(c){const e=c.headers.get("content-type");if(!(e!=null&&e.startsWith(z)))throw new Error(`Expected content-type to be ${z}, Actual: ${e}`)}const K=new S("[DialogSession] ");class we extends q{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:v.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=y(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(l){return l.ok&&i!=null&&i.onopen&&i.onopen(),Promise.resolve()},onmessage(l){if(!l.data.includes('{"code": ')){let u={};try{u=JSON.parse(l.data)}catch(p){}(u==null?void 0:u.mtype)==="search"?n.searchReference.push(u):n.content=n.content+l.data;const w={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(w)}const h=JSON.parse(l.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 l={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(l)}})})}postChatV3EventSource(t,s,r,a,i,o){return f(this,null,function*(){const n=this,d={code:0,content:"",role:v.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},l=y(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(l),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(w){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=y(g({},d),{isReplying:!1});i!=null&&i.onclose&&i.onclose(h)}})})}sendQuestion(t,s){return f(this,null,function*(){var d;const{content:r,fileIds:a,oldMessageId:i}=t,{stream:o,referenceFirst:n}=s;if(this.active||(yield this.activate()),this._id){let l={content:r,fileIds:a,referenceFirst:n,oldMessageId:i,promptVariables:this.promptVariables.filter(h=>h.type===v.PromptVariableType.User).reduce((h,u)=>y(g({},h),{[u.key]:u.value}),{}),systemPromptVariables:this.promptVariables.filter(h=>h.type===v.PromptVariableType.System).reduce((h,u)=>y(g({},h),{[u.key]:u.value}),{}),knowledges:(d=this.knowledges)==null?void 0:d.map(h=>h.id),enableTitleSummary:!0};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,l,this.ctrl.signal,{onopen:()=>{K.log("open",this.ctrl)},onmessage:h=>{if(this._stopAnswer)return;let u=this.messages[this.messages.length-1];u&&u.role===v.ChatMessageRole.Robot?(u=g(g({},u),h),this.messages[this.messages.length-1]=u,this.event.emit("message:content",u),this.event.emit("message:updated",u)):(this.pushMessage(h),this.event.emit("message:content",h))},onclose:h=>f(this,null,function*(){this._stopAnswer||(K.log(h,"onclose"),this.event.emit("answer:finish",h))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return 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")})}}const Ie="@glodon-aiot/bot-client-sdk",be="3.5.0-alpha.3",_e="glodoncv",Se="aiot bot client js sdk",ke="module",Ae=!1,Re=["aiot","bot","bot client","sdk"],Me=["dist"],xe="./dist/es/index.mjs",Le="./dist/lib/index.js",Ce="./dist/src/index.d.ts",Te={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},Ee="MIT",Pe={watch:"yarn build --watch",example:"node ./example/server.js",dev:"npm-run-all -p watch example",start:"vite",build:"tsc && vite build --mode prod && yarn build:cdn","build:npm":"tsc && vite build --mode prod","build:cdn":"tsc && vite build --mode prod --config ./vite.config.cdn.ts",preview:"vite preview",check:"yarn prettier --check .",write:"yarn prettier --write .",lint:"eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js"},Ve={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@types/express":"^4","@types/identity-obj-proxy":"^3","@typescript-eslint/eslint-plugin":"^5.35.1","@typescript-eslint/parser":"^5.35.1","babel-loader":"^8.3.0",eslint:"^8.0.1","eslint-config-prettier":"^8.5.0","eslint-config-standard-with-typescript":"^22.0.0","eslint-plugin-import":"^2.25.2","eslint-plugin-n":"^15.0.0","eslint-plugin-promise":"^6.0.0","eslint-plugin-react":"^7.31.0","eslint-plugin-storybook":"^0.6.10",express:"4","http-proxy-middleware":"^3.0.0","identity-obj-proxy":"^3.0.0","npm-run-all":"^4.1.5",prettier:"2.7.1","rollup-plugin-visualizer":"^6.0.1","socket.io":"^4.7.5","ts-node":"^10.9.2",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0","vite-tsconfig-paths":"^5.1.4"},Oe={access:"public",registry:"https://registry.npmjs.org/"},$e={"@glodon-aiot/apis":"^3.5.0-alpha.3",axios:"0.24.0",buffer:"^6.0.3",dayjs:"^1.11.13","js-base64":"^3.7.7","socket.io-client":"^4.7.5",uuid:"^11.1.0"},Qe={name:Ie,version:be,author:_e,description:Se,type:ke,sideEffects:Ae,keywords:Re,files:Me,module:xe,main:Le,typings:Ce,exports:Te,license:Ee,scripts:Pe,devDependencies:Ve,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:Oe,dependencies:$e},ze=new S("[BotClient] ");class je{constructor(e,t,s=!0,r={analytics:{enabled:!1}}){m(this,"event",new Z);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=s,this.sdkConfigs=r,Q(t),this._applicationId=E(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(a=>{Q(y(g({},t),{stream:t.stream===void 0?(a==null?void 0:a.type)===v.ApplicationTypes.Dialog||(a==null?void 0:a.type)===v.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:Qe.version}).then(o=>(typeof o.arrange[0].recommendQuestionOpen!="boolean"&&(o.arrange[0].recommendQuestionOpen=!0),y(g({},o),{arrange:[y(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:v.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:v.PromptVariableType.System})]).then(([o,n])=>[...o,...n]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:X(exports.configuration.apiRoot,this.token,(e,t)=>ze.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=E(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=l=>f(this,null,function*(){if(l===v.ApplicationTypes.Agent)o(new pe(e,t,s,r,a,i));else if(l===v.ApplicationTypes.Dialog)o(new we(e,t,s,r,a,i));else throw Error(`不支持的应用类型:${l}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return f(this,null,function*(){return new Promise((t,s)=>{const r=()=>this.cvforceApi.listSessions(this._applicationId,e).then(a=>{const i=[];return a.forEach(o=>f(this,null,function*(){const n=this._sessions.find(d=>o.id===d.id);if(n)n.data=o,this._application?n.application=this._application: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)}})),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?(yield s.activate(),this._activeSession=s):s.addEventListener("data:loaded",()=>{this._activeSession!==s&&(s==null||s.activate(),this._activeSession=s)},!0),s})}reload(){return this.loadApplication().then(()=>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 qe{constructor(e,t={},s){m(this,"code");m(this,"description","");m(this,"loaded",!1);m(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}exports.AgentPlugin=qe;exports.BotClient=je;exports.Session=q;exports.configure=Q;
|
|
4
|
+
`+h:h;break;case"event":s.event=h;break;case"id":c(s.id=h);break;case"retry":const f=parseInt(h,10);isNaN(f)||e(s.retry=f);break}}}}function me(c,e){const t=new Uint8Array(c.length+e.length);return t.set(c),t.set(e,c.length),t}function H(){return{data:"",event:"",id:"",retry:void 0}}const j="text/event-stream",ve=1e3,U="last-event-id";function W(c,l){var h=l,{signal:e,headers:t,onopen:s,onmessage:r,onclose:n,onerror:i,openWhenHidden:o,fetch:a}=h,d=J(h,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,v)=>{const I=g({},t);I.accept||(I.accept=j);let u;function b(){u.abort(),document.hidden||$()}o||document.addEventListener("visibilitychange",b);let L=ve,V=0;function O(){document.removeEventListener("visibilitychange",b),window.clearTimeout(V),u.abort()}e==null||e.addEventListener("abort",()=>{O(),f()});const ee=a!=null?a:window.fetch,te=s!=null?s:ye;function $(){return p(this,null,function*(){var D;u=new AbortController;try{const T=yield ee(c,w(g({},d),{headers:I,signal:u.signal}));yield te(T),yield fe(T.body,ue(ge(k=>{k?I[U]=k:delete I[U]},k=>{L=k},r))),n==null||n(),O(),f()}catch(T){if(!u.signal.aborted)try{const k=(D=i==null?void 0:i(T))!=null?D:L;window.clearTimeout(V),V=window.setTimeout($,k)}catch(k){O(),v(k)}}})}$()})}function ye(c){const e=c.headers.get("content-type");if(!(e!=null&&e.startsWith(j)))throw new Error(`Expected content-type to be ${j}, Actual: ${e}`)}const K=new S("[DialogSession] ");class we extends N{constructor(t,s="",r,n,i,o){super(t,s,r,n,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,n,i,o){return p(this,null,function*(){const a={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:n,onopen(l){return l.ok&&i!=null&&i.onopen&&i.onopen(),Promise.resolve()},onmessage(l){if(!l.data.includes('{"code": ')){let f={};try{f=JSON.parse(l.data)}catch(I){}(f==null?void 0:f.mtype)==="search"?a.searchReference.push(f):a.content=a.content+l.data;const v={content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:s,messageTime:q(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(l.data);if(a.reference=h.data.reference,a.searchReference=h.data.searchReference,a.messageTime=h.data.messageTime,a.messageId=h.data.messageId,a.llmModel=h.data.llmModel,a.content=h.data.content,a.code=h.code,h.code===200){const f={code:a.code,content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:s,messageTime:a.messageTime,isReplying:!0};i!=null&&i.onmessage&&i.onmessage(f)}else return i!=null&&i.onclose&&i.onclose(a),o&&o({code:a.code,message:a.message})},onerror(){i!=null&&i.onerror&&i.onerror()},onclose(){const l={code:a.code,content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:s,messageTime:a.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};i!=null&&i.onclose&&i.onclose(l)}})})}postChatV3EventSource(t,s,r,n,i,o){return p(this,null,function*(){const a=this,d={code:0,content:"",role:y.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},l=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(l),openWhenHidden:!0,signal:n,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 f={};try{f=JSON.parse(h.data)}catch(v){console.error("parse eventData to JSON failed. ",h.data)}if(f.code!==200)return d.index=-1,d.code=f.code,d.message=f.message,i!=null&&i.onmessage&&i.onmessage(d),o&&o({code:f.code,message:f.message});a.handleStreamAnswer(f,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*(){var l;const{content:r,fileIds:n,oldMessageId:i,imageContent:o}=t,{stream:a,referenceFirst:d}=s;if(this.active||(yield this.activate()),this._id){let h={content:r,fileIds:n,referenceFirst:d,oldMessageId:i,promptVariables:this.promptVariables.filter(f=>f.type===y.PromptVariableType.User).reduce((f,v)=>w(g({},f),{[v.key]:v.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===y.PromptVariableType.System).reduce((f,v)=>w(g({},f),{[v.key]:v.value}),{}),knowledges:(l=this.knowledges)==null?void 0:l.map(f=>f.id),enableTitleSummary:!0,imageContent:o};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,h,this.ctrl.signal,{onopen:()=>{K.log("open",this.ctrl)},onmessage:f=>{if(this._stopAnswer)return;let v=this.messages[this.messages.length-1];v&&v.role===y.ChatMessageRole.Robot?(v=g(g({},v),f),this.messages[this.messages.length-1]=v,this.event.emit("message:content",v),this.event.emit("message:updated",v)):(this.pushMessage(f),this.event.emit("message:content",f))},onclose:f=>p(this,null,function*(){this._stopAnswer||(K.log(f,"onclose"),this.event.emit("answer:finish",f))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}}const Ie="@glodon-aiot/bot-client-sdk",be="3.6.0-alpha.5",_e="glodoncv",Se="aiot bot client js sdk",ke="module",Ae=!1,Re=["aiot","bot","bot client","sdk"],Me=["dist"],xe="./dist/es/index.mjs",Le="./dist/lib/index.js",Ce="./dist/src/index.d.ts",Te={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},Ee="MIT",Pe={watch:"yarn build --watch",example:"node ./example/server.js",dev:"npm-run-all -p watch example",start:"vite",build:"tsc && vite build --mode prod && yarn build:cdn","build:npm":"tsc && vite build --mode prod","build:cdn":"tsc && vite build --mode prod --config ./vite.config.cdn.ts",preview:"vite preview",check:"yarn prettier --check .",write:"yarn prettier --write .",lint:"eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js"},Ve={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@types/express":"^4","@types/identity-obj-proxy":"^3","@typescript-eslint/eslint-plugin":"^5.35.1","@typescript-eslint/parser":"^5.35.1","babel-loader":"^8.3.0",eslint:"^8.0.1","eslint-config-prettier":"^8.5.0","eslint-config-standard-with-typescript":"^22.0.0","eslint-plugin-import":"^2.25.2","eslint-plugin-n":"^15.0.0","eslint-plugin-promise":"^6.0.0","eslint-plugin-react":"^7.31.0","eslint-plugin-storybook":"^0.6.10",express:"4","http-proxy-middleware":"^3.0.0","identity-obj-proxy":"^3.0.0","npm-run-all":"^4.1.5",prettier:"2.7.1","rollup-plugin-visualizer":"^6.0.1","socket.io":"^4.7.5","ts-node":"^10.9.2",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0","vite-tsconfig-paths":"^5.1.4"},Oe={access:"public",registry:"https://registry.npmjs.org/"},$e={"@glodon-aiot/apis":"^3.6.0-alpha.5",axios:"0.24.0",buffer:"^6.0.3",dayjs:"^1.11.13","js-base64":"^3.7.7","socket.io-client":"^4.7.5",uuid:"^11.1.0"},Qe={name:Ie,version:be,author:_e,description:Se,type:ke,sideEffects:Ae,keywords:Re,files:Me,module:xe,main:Le,typings:Ce,exports:Te,license:Ee,scripts:Pe,devDependencies:Ve,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:Oe,dependencies:$e},ze=new S("[BotClient] ");class je{constructor(e,t,s=!0,r={analytics:{enabled:!1}}){m(this,"event",new Z);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=s,this.sdkConfigs=r,z(t),this._applicationId=P(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(n=>{z(w(g({},t),{stream:t.stream===void 0?(n==null?void 0:n.type)===y.ApplicationTypes.Dialog||(n==null?void 0:n.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,n,i;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(s=this.sdkConfigs.ui)==null?void 0:s.version,sdkVersion:Qe.version}).then(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=(n=(r=this._application)==null?void 0:r.arrange)==null?void 0:n[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,a])=>[...o,...a]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:X(exports.configuration.apiRoot,this.token,(e,t)=>ze.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=P(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,n){return p(this,null,function*(){const i=this;return new Promise((o,a)=>{const d=l=>p(this,null,function*(){if(l===y.ApplicationTypes.Agent)o(new pe(e,t,s,r,n,i));else if(l===y.ApplicationTypes.Dialog)o(new we(e,t,s,r,n,i));else throw Error(`不支持的应用类型:${l}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return p(this,null,function*(){return new Promise((t,s)=>{const r=()=>this.cvforceApi.listSessions(this._applicationId,e).then(n=>{const i=[];return n.forEach(o=>p(this,null,function*(){const a=this._sessions.find(d=>o.id===d.id);if(a)a.data=o,this._application?a.application=this._application:a.loadApplicationInfo(),i.push(a);else{const d=yield this.createSession(this.token,o.id,o,this.lazyload,this._application||void 0);i.push(d)}})),this.sessions=i,i});if(this.ready){if(!this._application)throw Error("_application is null");t(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?(yield s.activate(),this._activeSession=s):s.addEventListener("data:loaded",()=>{this._activeSession!==s&&(s==null||s.activate(),this._activeSession=s)},!0),s})}reload(){return this.loadApplication().then(()=>p(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return p(this,null,function*(){yield this.reload();let t=this._sessions.find(s=>s.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,s="top_time desc, sort_status desc, updated_at desc"){return p(this,null,function*(){let r=e?this._sessions.find(n=>n.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 qe{constructor(e,t={},s){m(this,"code");m(this,"description","");m(this,"loaded",!1);m(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}exports.AgentPlugin=qe;exports.BotClient=je;exports.Session=N;exports.configure=z;
|
package/dist/src/Session.d.ts
CHANGED
|
@@ -15,6 +15,7 @@ export interface QuestionBody {
|
|
|
15
15
|
fileIds?: string[];
|
|
16
16
|
oldMessageId?: string;
|
|
17
17
|
referenceFirst?: boolean;
|
|
18
|
+
imageContent?: string[];
|
|
18
19
|
}
|
|
19
20
|
export interface QuestionConfig {
|
|
20
21
|
stream?: boolean;
|
|
@@ -88,7 +89,7 @@ export default abstract class Session {
|
|
|
88
89
|
get applicationId(): string;
|
|
89
90
|
get application(): IApplication | null;
|
|
90
91
|
set application(v: IApplication | null);
|
|
91
|
-
loadApplicationInfo(): Promise<IApplication>;
|
|
92
|
+
loadApplicationInfo(): Promise<IApplication> | Promise<import('@glodon-aiot/apis/dist/src/cvforce').IApplication>;
|
|
92
93
|
get ready(): boolean;
|
|
93
94
|
get frozen(): boolean;
|
|
94
95
|
protected set frozen(v: boolean);
|
|
@@ -174,6 +175,7 @@ export default abstract class Session {
|
|
|
174
175
|
files?: any[];
|
|
175
176
|
uuid?: string;
|
|
176
177
|
fileIds?: string[];
|
|
178
|
+
imageContent?: string[];
|
|
177
179
|
}, configs?: QuestionConfig): Promise<false | {
|
|
178
180
|
sessionId: string;
|
|
179
181
|
role: number;
|
|
@@ -183,6 +185,7 @@ export default abstract class Session {
|
|
|
183
185
|
searchReference: never[];
|
|
184
186
|
messageTime: string;
|
|
185
187
|
files: any[];
|
|
188
|
+
imageContent: string[] | undefined;
|
|
186
189
|
}>;
|
|
187
190
|
protected getRelatedQuesion(message: IChatMessage): Promise<IChatMessage>;
|
|
188
191
|
protected fillMessageReference(message: IChatMessage): Promise<IChatMessage>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glodon-aiot/bot-client-sdk",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.6.0-alpha.5",
|
|
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.
|
|
82
|
+
"@glodon-aiot/apis": "^3.6.0-alpha.5",
|
|
83
83
|
"axios": "0.24.0",
|
|
84
84
|
"buffer": "^6.0.3",
|
|
85
85
|
"dayjs": "^1.11.13",
|