@glodon-aiot/bot-client-sdk 3.3.5-alpha.29 → 3.3.5-beta.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/es/AgentSession.mjs +29 -29
- package/dist/es/Session.mjs +69 -69
- package/dist/es/package.json.mjs +11 -11
- package/dist/lib/index.js +3 -3
- package/dist/src/Session.d.ts +2 -0
- package/package.json +2 -2
package/dist/es/AgentSession.mjs
CHANGED
|
@@ -9,7 +9,7 @@ var S = (m, i, r) => i in m ? A(m, i, { enumerable: !0, configurable: !0, writab
|
|
|
9
9
|
for (var r of b(i))
|
|
10
10
|
E.call(i, r) && S(m, r, i[r]);
|
|
11
11
|
return m;
|
|
12
|
-
},
|
|
12
|
+
}, w = (m, i) => C(m, P(i));
|
|
13
13
|
var v = (m, i, r) => new Promise((o, n) => {
|
|
14
14
|
var s = (a) => {
|
|
15
15
|
try {
|
|
@@ -26,7 +26,7 @@ var v = (m, i, r) => new Promise((o, n) => {
|
|
|
26
26
|
}, t = (a) => a.done ? o(a.value) : Promise.resolve(a.value).then(s, e);
|
|
27
27
|
t((r = r.apply(m, i)).next());
|
|
28
28
|
});
|
|
29
|
-
import { ChatMessageRole as
|
|
29
|
+
import { ChatMessageRole as y, PromptVariableType as _ } from "@glodon-aiot/apis";
|
|
30
30
|
import L from "./Logger.mjs";
|
|
31
31
|
import { configuration as u } from "./Config.mjs";
|
|
32
32
|
import { io as q } from "socket.io-client";
|
|
@@ -84,17 +84,17 @@ class H extends N {
|
|
|
84
84
|
parameters: c,
|
|
85
85
|
requestBody: U
|
|
86
86
|
}
|
|
87
|
-
} = s,
|
|
88
|
-
if (!
|
|
89
|
-
|
|
90
|
-
messageId:
|
|
87
|
+
} = s, l = this.messages[this.messages.length - 1];
|
|
88
|
+
if (!l.messageId)
|
|
89
|
+
l.actions || (l.actions = []), l.actions[s.data.step - 1] || (l.actions[s.data.step - 1] = []), l.actions[s.data.step - 1].push(s), this.event.emit("message:action", {
|
|
90
|
+
messageId: l.messageId,
|
|
91
91
|
action: s
|
|
92
|
-
}), this.event.emit("message:updated",
|
|
92
|
+
}), this.event.emit("message:updated", l);
|
|
93
93
|
else {
|
|
94
|
-
const
|
|
94
|
+
const f = {
|
|
95
95
|
messageId: "",
|
|
96
96
|
content: "",
|
|
97
|
-
role:
|
|
97
|
+
role: y.Robot,
|
|
98
98
|
sessionId: this.id,
|
|
99
99
|
reference: [],
|
|
100
100
|
searchReference: [],
|
|
@@ -106,13 +106,13 @@ class H extends N {
|
|
|
106
106
|
},
|
|
107
107
|
isReplying: !0
|
|
108
108
|
};
|
|
109
|
-
this.pushMessage(
|
|
110
|
-
messageId:
|
|
109
|
+
this.pushMessage(f), this.event.emit("message:action", {
|
|
110
|
+
messageId: f.messageId,
|
|
111
111
|
action: s
|
|
112
112
|
});
|
|
113
113
|
}
|
|
114
114
|
if (this.inactivating) {
|
|
115
|
-
const
|
|
115
|
+
const f = new Error(
|
|
116
116
|
I.Inactive
|
|
117
117
|
// {
|
|
118
118
|
// cause: {
|
|
@@ -122,7 +122,7 @@ class H extends N {
|
|
|
122
122
|
// },
|
|
123
123
|
// }
|
|
124
124
|
);
|
|
125
|
-
p.warn("error",
|
|
125
|
+
p.warn("error", f), this.event.emit("error", f);
|
|
126
126
|
} else if (t === "FUNCTION_CALL" && a) {
|
|
127
127
|
if (p.log(`calling function ${g} of plugin ${h} with argument:
|
|
128
128
|
${JSON.stringify(c)}`), !u.plugins[h]) {
|
|
@@ -132,8 +132,8 @@ class H extends N {
|
|
|
132
132
|
});
|
|
133
133
|
return;
|
|
134
134
|
}
|
|
135
|
-
const
|
|
136
|
-
typeof
|
|
135
|
+
const f = u.plugins[h][g];
|
|
136
|
+
typeof f != "function" && e({
|
|
137
137
|
code: 404,
|
|
138
138
|
message: "对不起,没有找到插件方法。"
|
|
139
139
|
});
|
|
@@ -142,7 +142,7 @@ class H extends N {
|
|
|
142
142
|
M = JSON.parse(c == null ? void 0 : c.query);
|
|
143
143
|
} catch (R) {
|
|
144
144
|
}
|
|
145
|
-
|
|
145
|
+
f(M, (...R) => {
|
|
146
146
|
this._stopAnswer || e(...R);
|
|
147
147
|
});
|
|
148
148
|
}
|
|
@@ -150,12 +150,12 @@ class H extends N {
|
|
|
150
150
|
if (!this._stopAnswer)
|
|
151
151
|
if (s.data.code !== 200 && (s.data.index = -1, this.event.emit("error", s.data)), s.data.stream || s.data.stream === void 0) {
|
|
152
152
|
let e = this.messages[this.messages.length - 1];
|
|
153
|
-
if (e && e.role ===
|
|
154
|
-
this.handleStreamAnswer(s.data, e), this.messages[this.messages.length - 1] = e, this.event.emit("message:content", e), this.event.emit("message:updated", e), e.index === -1 && this.event.emit("answer:finish", e);
|
|
153
|
+
if (e && e.role === y.Robot)
|
|
154
|
+
this.handleStreamAnswer(s.data, e), this.messages[this.messages.length - 1] = e, this.event.emit("message:content", e), this.event.emit("message:updated", e), e.index === -1 && (e.isReplying = !1, this.event.emit("answer:finish", e));
|
|
155
155
|
else {
|
|
156
156
|
const t = {
|
|
157
157
|
content: "",
|
|
158
|
-
role:
|
|
158
|
+
role: y.Robot,
|
|
159
159
|
reference: [],
|
|
160
160
|
searchReference: [],
|
|
161
161
|
messageId: "",
|
|
@@ -166,7 +166,7 @@ class H extends N {
|
|
|
166
166
|
},
|
|
167
167
|
isReplying: !0
|
|
168
168
|
};
|
|
169
|
-
this.handleStreamAnswer(s.data, t), this.pushMessage(t), this.event.emit("message:content", t), t.index === -1 && this.event.emit("answer:finish", t);
|
|
169
|
+
this.handleStreamAnswer(s.data, t), this.pushMessage(t), this.event.emit("message:content", t), t.index === -1 && (t.isReplying = !1, this.event.emit("answer:finish", t));
|
|
170
170
|
}
|
|
171
171
|
} else if (s.data.index === -1) {
|
|
172
172
|
let e = this.messages[this.messages.length - 1];
|
|
@@ -176,7 +176,7 @@ class H extends N {
|
|
|
176
176
|
const t = d({
|
|
177
177
|
messageId: "",
|
|
178
178
|
content: "",
|
|
179
|
-
role:
|
|
179
|
+
role: y.Robot,
|
|
180
180
|
sessionId: this.id,
|
|
181
181
|
reference: [],
|
|
182
182
|
searchReference: [],
|
|
@@ -195,7 +195,7 @@ class H extends N {
|
|
|
195
195
|
e && !e.messageId ? (e = d(d({}, e), s.data), this.messages[this.messages.length - 1] = e, this.event.emit("message:content", e), this.event.emit("message:updated", e)) : (this.pushMessage(d({
|
|
196
196
|
messageId: "",
|
|
197
197
|
content: "",
|
|
198
|
-
role:
|
|
198
|
+
role: y.Robot,
|
|
199
199
|
sessionId: this.id,
|
|
200
200
|
reference: [],
|
|
201
201
|
searchReference: [],
|
|
@@ -225,7 +225,7 @@ class H extends N {
|
|
|
225
225
|
type: e,
|
|
226
226
|
data: t,
|
|
227
227
|
requestId: a
|
|
228
|
-
} = s, h = this.messages.findIndex((c) => c.messageId === a && c.role ===
|
|
228
|
+
} = s, h = this.messages.findIndex((c) => c.messageId === a && c.role === y.User);
|
|
229
229
|
if (h < 0)
|
|
230
230
|
return;
|
|
231
231
|
const g = h + 1;
|
|
@@ -233,7 +233,7 @@ class H extends N {
|
|
|
233
233
|
const c = {
|
|
234
234
|
messageId: "",
|
|
235
235
|
content: "",
|
|
236
|
-
role:
|
|
236
|
+
role: y.Robot,
|
|
237
237
|
sessionId: this.id,
|
|
238
238
|
reference: [],
|
|
239
239
|
searchReference: [],
|
|
@@ -247,9 +247,9 @@ class H extends N {
|
|
|
247
247
|
};
|
|
248
248
|
this.pushMessage(c);
|
|
249
249
|
}
|
|
250
|
-
e === "KG" ? (this.messages[g] =
|
|
250
|
+
e === "KG" ? (this.messages[g] = w(d({}, this.messages[g]), {
|
|
251
251
|
reference: t.knowledgeReference
|
|
252
|
-
}), yield this.fillMessageReference(this.messages[g]), this.event.emit("message:reference", t.knowledgeReference), this.event.emit("message:updated", this.messages[g])) : e === "WEB_SEARCH" && (this.messages[g] =
|
|
252
|
+
}), yield this.fillMessageReference(this.messages[g]), this.event.emit("message:reference", t.knowledgeReference), this.event.emit("message:updated", this.messages[g])) : e === "WEB_SEARCH" && (this.messages[g] = w(d({}, this.messages[g]), {
|
|
253
253
|
searchReference: t.knowledgeReference
|
|
254
254
|
}), this.event.emit("message:searchreference", t.searchReference), this.event.emit("message:updated", this.messages[g]));
|
|
255
255
|
})), this.socket = n, n.open();
|
|
@@ -291,11 +291,11 @@ class H extends N {
|
|
|
291
291
|
sendQuestion(i, r) {
|
|
292
292
|
return v(this, null, function* () {
|
|
293
293
|
var n, s, e;
|
|
294
|
-
let o =
|
|
295
|
-
promptVariables: this.promptVariables.filter((t) => t.type === _.User).reduce((t, a) =>
|
|
294
|
+
let o = w(d({}, i), {
|
|
295
|
+
promptVariables: this.promptVariables.filter((t) => t.type === _.User).reduce((t, a) => w(d({}, t), {
|
|
296
296
|
[a.key]: a.value
|
|
297
297
|
}), {}),
|
|
298
|
-
systemPromptVariables: this.promptVariables.filter((t) => t.type === _.System).reduce((t, a) =>
|
|
298
|
+
systemPromptVariables: this.promptVariables.filter((t) => t.type === _.System).reduce((t, a) => w(d({}, t), {
|
|
299
299
|
[a.key]: a.value
|
|
300
300
|
}), {}),
|
|
301
301
|
knowledges: (n = this.knowledges) == null ? void 0 : n.map((t) => t.id)
|
package/dist/es/Session.mjs
CHANGED
|
@@ -9,20 +9,20 @@ var k = (c, e, t) => e in c ? V(c, e, { enumerable: !0, configurable: !0, writab
|
|
|
9
9
|
for (var t of b(e))
|
|
10
10
|
R.call(e, t) && k(c, t, e[t]);
|
|
11
11
|
return c;
|
|
12
|
-
},
|
|
13
|
-
var
|
|
12
|
+
}, w = (c, e) => Q(c, T(e));
|
|
13
|
+
var p = (c, e, t) => (k(c, typeof e != "symbol" ? e + "" : e, t), t);
|
|
14
14
|
var h = (c, e, t) => new Promise((i, a) => {
|
|
15
15
|
var r = (s) => {
|
|
16
16
|
try {
|
|
17
17
|
o(t.next(s));
|
|
18
|
-
} catch (
|
|
19
|
-
a(
|
|
18
|
+
} catch (l) {
|
|
19
|
+
a(l);
|
|
20
20
|
}
|
|
21
21
|
}, d = (s) => {
|
|
22
22
|
try {
|
|
23
23
|
o(t.throw(s));
|
|
24
|
-
} catch (
|
|
25
|
-
a(
|
|
24
|
+
} catch (l) {
|
|
25
|
+
a(l);
|
|
26
26
|
}
|
|
27
27
|
}, o = (s) => s.done ? i(s.value) : Promise.resolve(s.value).then(r, d);
|
|
28
28
|
o((t = t.apply(c, e)).next());
|
|
@@ -48,30 +48,30 @@ class X {
|
|
|
48
48
|
* @param client - Bot 客户端实例,可选参数。
|
|
49
49
|
*/
|
|
50
50
|
constructor(e, t = "", i, a, r, d) {
|
|
51
|
-
|
|
52
|
-
|
|
51
|
+
p(this, "_id");
|
|
52
|
+
p(this, "_frozen", !1);
|
|
53
53
|
//是否可发送新问题
|
|
54
|
-
|
|
55
|
-
|
|
54
|
+
p(this, "inactivating", !1);
|
|
55
|
+
p(this, "_ready", !1);
|
|
56
56
|
// ready = false;
|
|
57
|
-
|
|
57
|
+
p(this, "event", new F());
|
|
58
58
|
//从token解析出来的用户信息
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
59
|
+
p(this, "_applicationId");
|
|
60
|
+
p(this, "_application", null);
|
|
61
|
+
p(this, "data", null);
|
|
62
|
+
p(this, "client", null);
|
|
63
|
+
p(this, "messages", []);
|
|
64
|
+
p(this, "_loadingMessages", !1);
|
|
65
|
+
p(this, "_loadingMessagesSize", 10);
|
|
66
|
+
p(this, "cvforceApi");
|
|
67
|
+
p(this, "socket", null);
|
|
68
|
+
p(this, "_promptVariables", []);
|
|
69
|
+
p(this, "active", !1);
|
|
70
|
+
p(this, "activing", !1);
|
|
71
|
+
p(this, "_stopAnswer", !1);
|
|
72
|
+
p(this, "_dataLoading", !1);
|
|
73
|
+
p(this, "_dataLoaded", !1);
|
|
74
|
+
p(this, "_mcpServers", null);
|
|
75
75
|
this.token = e, this.lazyload = a, this.client = d || null, this._applicationId = C(e).rid || A.applicationId, this.cvforceApi = this.getService(), r && (this._application = r), this.event.emit("init", {
|
|
76
76
|
applicationId: this._applicationId,
|
|
77
77
|
sessionId: t
|
|
@@ -96,25 +96,25 @@ class X {
|
|
|
96
96
|
name: s,
|
|
97
97
|
// @ts-ignore
|
|
98
98
|
netOpen: i == null ? void 0 : i.netOpen,
|
|
99
|
-
knowledgeIdList: (o = i == null ? void 0 : i.knowledges) == null ? void 0 : o.map((
|
|
99
|
+
knowledgeIdList: (o = i == null ? void 0 : i.knowledges) == null ? void 0 : o.map((l) => l.id),
|
|
100
100
|
applicationId: this._applicationId
|
|
101
|
-
}).then((
|
|
101
|
+
}).then((l) => h(this, null, function* () {
|
|
102
102
|
var m;
|
|
103
|
-
this._id =
|
|
103
|
+
this._id = l.id, this.data = w(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 _ = this._promptVariables.map((g) => {
|
|
111
|
+
var n, v;
|
|
112
|
+
const y = ((v = (n = i.promptVariables) == null ? void 0 : n.find((I) => I.key === g.key && I.type === g.type)) == null ? void 0 : v.value) || "";
|
|
113
|
+
return w(f({}, g), {
|
|
114
|
+
value: y
|
|
115
115
|
});
|
|
116
|
-
}).sort((g,
|
|
117
|
-
return this.setPromptVariables(
|
|
116
|
+
}).sort((g, y) => g.key.localeCompare(y.key));
|
|
117
|
+
return this.setPromptVariables(_ || []);
|
|
118
118
|
} else
|
|
119
119
|
return;
|
|
120
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) !== x.Agent && (this._ready = !0, this.event.emit("ready"));
|
|
@@ -193,7 +193,7 @@ class X {
|
|
|
193
193
|
const t = this._promptVariables.map((a) => {
|
|
194
194
|
var d;
|
|
195
195
|
const r = ((d = e == null ? void 0 : e.find((o) => o.key === a.key && o.type === a.type)) == null ? void 0 : d.value) || a.value;
|
|
196
|
-
return
|
|
196
|
+
return w(f({}, a), {
|
|
197
197
|
value: r
|
|
198
198
|
});
|
|
199
199
|
}).sort((a, r) => a.key.localeCompare(r.key));
|
|
@@ -280,26 +280,26 @@ class X {
|
|
|
280
280
|
};
|
|
281
281
|
if (this._id) {
|
|
282
282
|
e = f(f({}, t), e), this.event.emit("history:loading"), u.log("history:loading"), (e.endTime || e.startTime) && (this.event.emit("history:moreloading", e), u.log("history:moreloading", e)), this._loadingMessages = !0;
|
|
283
|
-
const r = yield this.cvforceApi.getChatHistorySessionId(this._applicationId, this._id, e), d = r.map((s,
|
|
284
|
-
var g,
|
|
285
|
-
let m = [],
|
|
286
|
-
return typeof ((g = s.agentHistoryList) == null ? void 0 : g.agentList) == "string" && (m = JSON.parse(s.agentHistoryList.agentList).reduce((v,
|
|
283
|
+
const r = yield this.cvforceApi.getChatHistorySessionId(this._applicationId, this._id, e), d = r.map((s, l) => {
|
|
284
|
+
var g, y;
|
|
285
|
+
let m = [], _;
|
|
286
|
+
return typeof ((g = s.agentHistoryList) == null ? void 0 : g.agentList) == "string" && (m = JSON.parse(s.agentHistoryList.agentList).reduce((v, I) => (v[I.data.step - 1] || (v[I.data.step - 1] = []), v[I.data.step - 1].push(I), v), [])), l === r.length - 1 && (_ = (y = this.data) == null ? void 0 : y.lastRelatedQuestion), w(f({}, s), {
|
|
287
287
|
actions: m,
|
|
288
|
-
relatedQuesion:
|
|
288
|
+
relatedQuesion: _
|
|
289
289
|
});
|
|
290
290
|
});
|
|
291
291
|
if (!e.endTime && !e.startTime) {
|
|
292
292
|
const s = this.messages[this.messages.length - 1];
|
|
293
293
|
s && !s.relatedQuesion && (s.relatedQuesion = (i = this.data) == null ? void 0 : i.lastRelatedQuestion), this.messages = [...d, ...this.messages];
|
|
294
294
|
} else if (e.endTime && !e.startTime) {
|
|
295
|
-
const s = this.messages.findIndex((
|
|
295
|
+
const s = this.messages.findIndex((l) => l.ts === e.endTime);
|
|
296
296
|
this.messages.splice(0, s + 1), this.messages = [...d, ...this.messages];
|
|
297
297
|
} else if (!e.endTime && e.startTime) {
|
|
298
|
-
const s = this.messages.findLastIndex((
|
|
298
|
+
const s = this.messages.findLastIndex((l) => l.ts === e.endTime);
|
|
299
299
|
this.messages.splice(s, this.messages.length - s - 1), this.messages = [...this.messages, ...d];
|
|
300
300
|
} else {
|
|
301
|
-
const s = this.messages.findIndex((m) => m.ts === e.endTime),
|
|
302
|
-
this.messages.splice(s,
|
|
301
|
+
const s = this.messages.findIndex((m) => m.ts === e.endTime), l = this.messages.findLastIndex((m) => m.ts === e.endTime);
|
|
302
|
+
this.messages.splice(s, l - s + 1, ...d);
|
|
303
303
|
}
|
|
304
304
|
const o = this.messages[this.messages.length - 1];
|
|
305
305
|
return o && !o.relatedQuesion && (o.relatedQuesion = (a = this.data) == null ? void 0 : a.lastRelatedQuestion), this.event.emit("history:moreloaded", d), u.log("history:loaded", this.messages), this.event.emit("history:loaded", this.messages), this._loadingMessages = !1, d;
|
|
@@ -396,7 +396,7 @@ class X {
|
|
|
396
396
|
return h(this, arguments, function* (e, t = {
|
|
397
397
|
stream: A.stream
|
|
398
398
|
}) {
|
|
399
|
-
var
|
|
399
|
+
var y;
|
|
400
400
|
try {
|
|
401
401
|
this.validateConfigs();
|
|
402
402
|
} catch (n) {
|
|
@@ -405,9 +405,8 @@ class X {
|
|
|
405
405
|
const {
|
|
406
406
|
stream: a = A.stream,
|
|
407
407
|
referenceFirst: r = !1
|
|
408
|
-
} = t, d = e.uuid || E(), o = ((
|
|
409
|
-
if (!o &&
|
|
410
|
-
!(s != null && s.length)) {
|
|
408
|
+
} = t, d = e.uuid || E(), o = ((y = e.text) == null ? void 0 : y.trim()) || "", s = e.files || [], l = e.fileIds;
|
|
409
|
+
if (!o && !s.length && !(l != null && l.length)) {
|
|
411
410
|
const n = new Error(
|
|
412
411
|
"failed at sending empty content"
|
|
413
412
|
/* SendingEmptyContent */
|
|
@@ -438,26 +437,27 @@ class X {
|
|
|
438
437
|
return u.error(n), this.event.emit("error", n), !1;
|
|
439
438
|
}
|
|
440
439
|
this.frozen = !0, this._stopAnswer = !1;
|
|
441
|
-
const
|
|
440
|
+
const m = {
|
|
442
441
|
sessionId: this.id,
|
|
443
442
|
role: 2,
|
|
444
443
|
content: o,
|
|
445
444
|
messageId: d,
|
|
446
445
|
reference: [],
|
|
447
446
|
searchReference: [],
|
|
448
|
-
messageTime: ""
|
|
449
|
-
|
|
447
|
+
messageTime: "",
|
|
448
|
+
files: s
|
|
449
|
+
}, _ = {
|
|
450
450
|
content: o,
|
|
451
451
|
stream: a,
|
|
452
452
|
requestId: d,
|
|
453
|
-
fileIds:
|
|
453
|
+
fileIds: l,
|
|
454
454
|
referenceFirst: r
|
|
455
455
|
};
|
|
456
|
-
this.pushMessage(
|
|
457
|
-
const
|
|
456
|
+
this.pushMessage(m), this.event.emit("question:content", o);
|
|
457
|
+
const g = (n) => h(this, null, function* () {
|
|
458
458
|
if (n.role !== S.Robot)
|
|
459
459
|
return;
|
|
460
|
-
switch (this.removeEventListener("answer:finish",
|
|
460
|
+
switch (this.removeEventListener("answer:finish", g), this._id && n.content && n.index && n.index < 0 && (this.data = yield this.cvforceApi.patchSessionsId(this.applicationId, this._id, {
|
|
461
461
|
finialMessage: n.content
|
|
462
462
|
}), this.event.emit("data:updated", this.data), this.event.emit("data:updated:finialMessage", {
|
|
463
463
|
finialMessage: n.content
|
|
@@ -472,18 +472,18 @@ class X {
|
|
|
472
472
|
n.content = n.message || "未知错误", n.isLoading = !1, n.index = -1, this.event.emit("message:error", n);
|
|
473
473
|
}
|
|
474
474
|
this.getRelatedQuesion(n), n.isLoading = !1;
|
|
475
|
-
let
|
|
476
|
-
if (
|
|
477
|
-
const
|
|
478
|
-
this.messages[this.messages.length - 1] =
|
|
475
|
+
let v = this.messages[this.messages.length - 1];
|
|
476
|
+
if (v && v.role === S.Robot) {
|
|
477
|
+
const I = f(f({}, v), n);
|
|
478
|
+
this.messages[this.messages.length - 1] = I, this.event.emit("message:updated", I);
|
|
479
479
|
} else
|
|
480
480
|
this.pushMessage(n);
|
|
481
481
|
this.frozen = !1;
|
|
482
482
|
});
|
|
483
|
-
return this.addEventListener("answer:finish",
|
|
483
|
+
return this.addEventListener("answer:finish", g), this.sendQuestion(_, w(f({}, t), {
|
|
484
484
|
stream: a,
|
|
485
485
|
referenceFirst: r
|
|
486
|
-
})),
|
|
486
|
+
})), m;
|
|
487
487
|
});
|
|
488
488
|
}
|
|
489
489
|
getRelatedQuesion(e) {
|
|
@@ -496,7 +496,7 @@ class X {
|
|
|
496
496
|
content: e.content
|
|
497
497
|
}).catch((o) => null);
|
|
498
498
|
if (!t) {
|
|
499
|
-
const o = [], s =
|
|
499
|
+
const o = [], s = w(f({}, e), {
|
|
500
500
|
relatedQuesion: o,
|
|
501
501
|
index: -3,
|
|
502
502
|
isLoading: !1
|
|
@@ -507,7 +507,7 @@ class X {
|
|
|
507
507
|
}
|
|
508
508
|
const i = (d = t.content) == null ? void 0 : d.split("*").map(O).map(z).filter((o) => !!o);
|
|
509
509
|
e.relatedQuesion = i, e.index = -3, e.isLoading = !1;
|
|
510
|
-
const a =
|
|
510
|
+
const a = w(f({}, e), {
|
|
511
511
|
relatedQuesion: i,
|
|
512
512
|
index: -3,
|
|
513
513
|
isLoading: !1
|
|
@@ -561,7 +561,7 @@ class X {
|
|
|
561
561
|
this.getRelatedQuesion(s), this.removeEventListener("message:content", o), this.frozen = !1;
|
|
562
562
|
}
|
|
563
563
|
});
|
|
564
|
-
this.addEventListener("message:content", o), this.sendQuestion(d,
|
|
564
|
+
this.addEventListener("message:content", o), this.sendQuestion(d, w(f({}, e), {
|
|
565
565
|
stream: i
|
|
566
566
|
}));
|
|
567
567
|
});
|
|
@@ -619,14 +619,14 @@ class X {
|
|
|
619
619
|
pluginName: d,
|
|
620
620
|
pluginCode: o,
|
|
621
621
|
funcCode: s,
|
|
622
|
-
funcName:
|
|
622
|
+
funcName: l
|
|
623
623
|
} = r.data;
|
|
624
624
|
a.push({
|
|
625
625
|
data: {
|
|
626
626
|
pluginName: d,
|
|
627
627
|
pluginCode: o,
|
|
628
628
|
funcCode: s,
|
|
629
|
-
funcName:
|
|
629
|
+
funcName: l,
|
|
630
630
|
step: r.data.step + 1
|
|
631
631
|
},
|
|
632
632
|
type: "ABORT"
|
package/dist/es/package.json.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e = "@glodon-aiot/bot-client-sdk", t = "3.3.5-
|
|
1
|
+
const e = "@glodon-aiot/bot-client-sdk", t = "3.3.5-beta.30", i = "glodoncv", s = "aiot bot client js sdk", n = "module", y = !1, o = [
|
|
2
2
|
"aiot",
|
|
3
3
|
"bot",
|
|
4
4
|
"bot client",
|
|
@@ -23,7 +23,7 @@ const e = "@glodon-aiot/bot-client-sdk", t = "3.3.5-alpha.29", i = "glodoncv", s
|
|
|
23
23
|
check: "yarn prettier --check .",
|
|
24
24
|
write: "yarn prettier --write .",
|
|
25
25
|
lint: "eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js"
|
|
26
|
-
},
|
|
26
|
+
}, b = {
|
|
27
27
|
"@babel/core": "^7.20.12",
|
|
28
28
|
"@commitlint/cli": "^17.0.3",
|
|
29
29
|
"@commitlint/config-conventional": "^17.0.3",
|
|
@@ -55,11 +55,11 @@ const e = "@glodon-aiot/bot-client-sdk", t = "3.3.5-alpha.29", i = "glodoncv", s
|
|
|
55
55
|
"vite-plugin-dts": "^4.3.0",
|
|
56
56
|
"vite-plugin-externalize-deps": "^0.9.0",
|
|
57
57
|
"vite-tsconfig-paths": "^5.1.4"
|
|
58
|
-
},
|
|
58
|
+
}, g = {
|
|
59
59
|
access: "public",
|
|
60
60
|
registry: "https://registry.npmjs.org/"
|
|
61
|
-
},
|
|
62
|
-
"@glodon-aiot/apis": "^3.3.5-
|
|
61
|
+
}, m = {
|
|
62
|
+
"@glodon-aiot/apis": "^3.3.5-beta.30",
|
|
63
63
|
axios: "0.24.0",
|
|
64
64
|
buffer: "^6.0.3",
|
|
65
65
|
dayjs: "^1.11.13",
|
|
@@ -81,19 +81,19 @@ const e = "@glodon-aiot/bot-client-sdk", t = "3.3.5-alpha.29", i = "glodoncv", s
|
|
|
81
81
|
exports: d,
|
|
82
82
|
license: a,
|
|
83
83
|
scripts: u,
|
|
84
|
-
devDependencies:
|
|
84
|
+
devDependencies: b,
|
|
85
85
|
"lint-staged": {
|
|
86
86
|
"*.{js,css,md,jsx,less,ts,tsx,json}": "prettier --write"
|
|
87
87
|
},
|
|
88
|
-
publishConfig:
|
|
89
|
-
dependencies:
|
|
88
|
+
publishConfig: g,
|
|
89
|
+
dependencies: m
|
|
90
90
|
};
|
|
91
91
|
export {
|
|
92
92
|
i as author,
|
|
93
93
|
x as default,
|
|
94
|
-
|
|
94
|
+
m as dependencies,
|
|
95
95
|
s as description,
|
|
96
|
-
|
|
96
|
+
b as devDependencies,
|
|
97
97
|
d as exports,
|
|
98
98
|
l as files,
|
|
99
99
|
o as keywords,
|
|
@@ -101,7 +101,7 @@ export {
|
|
|
101
101
|
c as main,
|
|
102
102
|
p as module,
|
|
103
103
|
e as name,
|
|
104
|
-
|
|
104
|
+
g as publishConfig,
|
|
105
105
|
u as scripts,
|
|
106
106
|
y as sideEffects,
|
|
107
107
|
n as type,
|
package/dist/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var E=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var $=(c,e,t)=>e in c?se(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t,g=(c,e)=>{for(var t in e||(e={}))B.call(e,t)&&$(c,t,e[t]);if(E)for(var t of E(e))F.call(e,t)&&$(c,t,e[t]);return c},y=(c,e)=>ie(c,ne(e));var J=(c,e)=>{var t={};for(var s in c)B.call(c,s)&&e.indexOf(s)<0&&(t[s]=c[s]);if(c!=null&&E)for(var s of E(c))e.indexOf(s)<0&&F.call(c,s)&&(t[s]=c[s]);return t};var m=(c,e,t)=>($(c,typeof e!="symbol"?e+"":e,t),t);var f=(c,e,t)=>new Promise((s,n)=>{var r=a=>{try{o(t.next(a))}catch(d){n(d)}},i=a=>{try{o(t.throw(a))}catch(d){n(d)}},o=a=>a.done?s(a.value):Promise.resolve(a.value).then(r,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 k=M;const ce=new k("[Config] ");var G=(c=>(c.dev="https://aiot-dev.glodon.com/api/cvforcepd",c.test="https://aiot-dev.glodon.com/api/cvforce",c.prod="https://copilot.glodon.com/api/cvforce",c.local="http://localhost:3000/api/cvforcepd",c))(G||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function Q(c){k.debug=(c==null?void 0:c.debug)||!1,exports.configuration=y(g(g({},exports.configuration),c),{apiRoot:(c==null?void 0:c.apiRoot)||exports.configuration.apiRoot||(c!=null&&c.env?G[c.env||"prod"]:exports.configuration.apiRoot)}),k.debug&&ce.log("updated",exports.configuration)}const T=c=>JSON.parse(ae.decode(c.split(".")[1])),de=c=>{const e=T(c).exp;return new Date().valueOf()/1e3>=e},he=c=>c==null?void 0:c.replace(/[\r\n]+/gm,""),le=c=>c.replace(/\\|\\/g,"");function X(c,e,t){const s=d=>{var p;return e&&(de(e)&&t(403,"aiotToken is timeout"),d.headers=(p=d.headers)!=null?p:{},d.headers=y(g({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function n(d,p=!0){const h=`${c}${d}`,u=re.create({baseURL:h});return p&&u.interceptors.request.use(s),u}const r=(d,p)=>{d===401&&t(d,"aiotToken is invalid")},i=(d,p)=>{d!==10001&&d!==10215&&t(d,p)},o=n("/data/v1");return new v.CVForceApi(o,{onHttpStatusError:r,onAppStatusError:i})}var x=(c=>(c[c.Normal=0]="Normal",c[c.Debug=1]="Debug",c))(x||{});const R=new k("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&R.disable()}getEventListenerMap(){return g({},this.eventListenerMap)}on(e,t,s=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),s?this.eventListenerMap[e].push({fn:t,once:!0}):this.eventListenerMap[e].push(t),R.log(`add event ${e} listener ${s?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const s=this.eventListenerMap[e].findIndex(n=>{if(typeof n=="function"&&t===n)return!0;if(n=n,n.fn===t)return!0});s<0?R.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),R.log(`remove event ${e} listener`))}else R.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){R.log(`event ${e} listeners is empty`);return}const s=[];for(let n=0;n<this.eventListenerMap[e].length;n++){const r=this.eventListenerMap[e][n];typeof r=="function"?r(t):s.push(r)}s.forEach(n=>{n&&(n.fn(t),this.off(e,n.fn))}),R.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const b=new k("[Session] ");var L=(c=>(c.DataRequestFailed="data request error",c.SocketConnectionFailed="socket error",c.IdUndefined="session id is not defined",c.SendingEmptyContent="failed at sending empty content",c.Frozen="session is frozen",c.UserModeError="failed at setting socket user mode",c.Inactive="session is inactive",c))(L||{});class q{constructor(e,t="",s,n,r,i){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new Z);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);m(this,"_mcpServers",null);this.token=e,this.lazyload=n,this.client=i||null,this._applicationId=T(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),r&&(this._application=r),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,n||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(a=>f(this,null,function*(){this.data=a,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(a=>f(this,null,function*(){this.data=a,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 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=>f(this,null,function*(){var p;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 w,I;const l=((I=(w=s.promptVariables)==null?void 0:w.find(_=>_.key===u.key&&_.type===u.type))==null?void 0:I.value)||"";return y(g({},u),{value:l})}).sort((u,l)=>u.key.localeCompare(l.key));return this.setPromptVariables(h||[])}else return})(),this.event.emit("data:created",this.data),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),((p=this.application)==null?void 0:p.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=this._promptVariables.map(n=>{var i;const r=((i=e==null?void 0:e.find(o=>o.key===n.key&&o.type===n.type))==null?void 0:i.value)||n.value;return y(g({},n),{value:r})}).sort((n,r)=>n.key.localeCompare(r.key));if(!(yield Promise.all(t.filter(n=>!(n.type===v.PromptVariableType.User&&n.key==="query")&&!(n.type===v.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 f(this,null,function*(){var t,s,n;if(b.log("setNetOpen:",e),b.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===v.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((n=this._application)==null?void 0:n.arrange[0].enableNetOpen)===!1){console.warn("This Application is disabled to change netOpen.");return}if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{netOpen:e?1:2}),this.data.netOpen=e,b.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}});b.error(s),this.event.emit("error",s)})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}fetchMessages(){return f(this,arguments,function*(e={}){var s,n;const t={pageSize:this._loadingMessagesSize};if(this._id){e=g(g({},t),e),this.event.emit("history:loading"),b.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),b.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),i=r.map((a,d)=>{var u,l;let p=[],h;return typeof((u=a.agentHistoryList)==null?void 0:u.agentList)=="string"&&(p=JSON.parse(a.agentHistoryList.agentList).reduce((I,_)=>(I[_.data.step-1]||(I[_.data.step-1]=[]),I[_.data.step-1].push(_),I),[])),d===r.length-1&&(h=(l=this.data)==null?void 0:l.lastRelatedQuestion),y(g({},a),{actions:p,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(p=>p.ts===e.endTime),d=this.messages.findLastIndex(p=>p.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=(n=this.data)==null?void 0:n.lastRelatedQuestion),this.event.emit("history:moreloaded",i),b.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,i}else{const r=new Error("session id is not defined");return b.error(r),this.event.emit("error",r),!1}})}rename(e){return f(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),b.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return f(this,null,function*(){this.messages.push(e),b.log("history:add",e),this.event.emit("history:add",e),this.event.emit("message:new",e),this.event.emit("message:updated",e)})}reloadSessionInfo(){if(!this._id)throw Error("session is not created yet");return this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,this._id).then(e=>f(this,null,function*(){if(this.data=e,!this._id)throw Error("session is not created yet");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),b.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>f(this,null,function*(){return this.messages=[],yield this.fetchMessages(),this._dataLoading=!1,this._dataLoaded=!0,this.event.emit("data:loaded",this.data),this}))}reload(){return f(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return f(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return b.error(e),this.event.emit("error",e),!1}return this.event.emit("data:deleting"),yield this.cvforceApi.delSessionsId(this.applicationId,this.id),this.event.emit("data:deleted"),this.destroy()})}activate(){return f(this,null,function*(){if(this.activing)return new Promise(t=>{this.addEventListener("activated",()=>{t(!0)},!0)});if(!this._id)throw Error("session is not avalible. id is undefined");this.activing=!0;const e=this._id;return this._dataLoading=!0,this._dataLoaded=!1,this.data=yield this.cvforceApi.getSession(this.applicationId,e).then(t=>f(this,null,function*(){return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,e),t})),this.messages.length||(this.messages=[],yield this.fetchMessages()),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoaded=!0,this._dataLoading=!1,this.inactivating=!1,this.frozen=!0,yield this.prepareConnection(),this.event.emit("activated",this.socket),this.active=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?this._frozen?(e||(this.inactivating=!0),this.activing=!1,!0):(this.socket.close(),this.socket=null,this.event.emit("inactivated"),this.active=!1,this.activing=!1,!0):(this.activing=!1,!0)}get dataLoaded(){return this._dataLoaded}get messagesLoading(){return this._loadingMessages}send(s){return f(this,arguments,function*(e,t={stream:exports.configuration.stream}){var u;try{this.validateConfigs()}catch(l){console.error(l)}const{stream:n=exports.configuration.stream,referenceFirst:r=!1}=t,i=e.uuid||Y.v4(),o=((u=e.text)==null?void 0:u.trim())||"",a=e.fileIds;if(!o&&!(a!=null&&a.length)){const l=new Error("failed at sending empty content");return b.error(l),this.event.emit("error",l),!1}if(!this._id){const l=new Error("session id is not defined");return b.error(l),this.event.emit("error",l),!1}if(this.frozen){const l=new Error("session is frozen");return b.error(l),this.event.emit("error",l),!1}this.frozen=!0,this._stopAnswer=!1;const d={sessionId:this.id,role:2,content:o,messageId:i,reference:[],searchReference:[],messageTime:""},p={content:o,stream:n,requestId:i,fileIds:a,referenceFirst:r};this.pushMessage(d),this.event.emit("question:content",o);const h=l=>f(this,null,function*(){if(l.role!==v.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",h),this._id&&l.content&&l.index&&l.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:l.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:l.content})),yield this.fillMessageReference(l),l.code){case 11915:l.content="请您换个问题问我吧~",l.index=-1,l.isSensitive=!0,l.isLoading=!1,l.sessionId=this._id||"",this.event.emit("message:error",l);break;case 200:l.index=-1,l.isLoading=!1;break;default:l.content=l.message||"未知错误",l.isLoading=!1,l.index=-1,this.event.emit("message:error",l)}this.getRelatedQuesion(l),l.isLoading=!1;let w=this.messages[this.messages.length-1];if(w&&w.role===v.ChatMessageRole.Robot){const I=g(g({},w),l);this.messages[this.messages.length-1]=I,this.event.emit("message:updated",I)}else this.pushMessage(l);this.frozen=!1});return this.addEventListener("answer:finish",h),this.sendQuestion(p,y(g({},t),{stream:n,referenceFirst:r})),d})}getRelatedQuesion(e){return f(this,null,function*(){var r,i;if(!e.content||e.isSensitive||e.code!==200||!((r=this.application)!=null&&r.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const t=yield this.cvforceApi.postGeneques({content:e.content}).catch(o=>null);if(!t){const o=[],a=y(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 n=y(g({},e),{relatedQuesion:s,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",n),this.event.emit("message:updated",n),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:s}),n})}fillMessageReference(e){return 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,n)=>g(g({},s),t[n])),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 n;t.role!==v.ChatMessageRole.User&&(n=e.oldMessageId||t.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",t),this.event.emit("history:remove",t));const r=this.messages[this.messages.length-1],i={content:r.content,fileIds:r.fileIds,requestId:r.messageId,stream:s,oldMessageId:n},o=a=>f(this,null,function*(){if(a.role===v.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,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 n=e.actions[((s=e.actions)==null?void 0:s.length)-1];if(n){const r=n[n.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:i,pluginCode:o,funcCode:a,funcName:d}=r.data;n.push({data:{pluginName:i,pluginCode:o,funcCode:a,funcName:d,step:r.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:n})}}}e=g(g({},e),t),this.event.emit("message:content",e),this.event.emit("message:updated",e)}else this.pushMessage(t),this.event.emit("message:content",t);return this}handleStreamAnswer(e,t){if(!e.data)return;const s=e.data.type,n=e.data.payload;t.isReplying=!0;const r=()=>{if(!t.searchingStatus){t.searchingStatus="start";return}if(t.searchingStatus==="start"){t.searchingStatus="end";return}};if(s==="error"&&(t.index=-1),s==="beforeSearch"&&r(),s==="searchOver"&&r(),s==="search"&&t.searchReference.push(n),s==="thinking"){t.thinkingStatus="start";const o=n.choices[0];t.reasoningContent=t.reasoningContent+o.delta.reasoningContent}if(s==="thinkingOver"){t.thinkingStatus="end";const i=n.thinkingSecs;t.thinkingSecs=i}if(s==="text"){const o=n.choices[0];t.content=t.content+o.delta.content}if(s==="reference"&&(t.reference=n),s==="result"){const i=n.messageId,o=n.llmModel,a=n.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 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(n=>n.messageId===e.messageId);return s&&(s.comment=e,this.event.emit("message:comment",s)),t})})}clear(){if(!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.patchApplicationIdSessionsIdContext(this._applicationId,this._id).then(()=>(this.event.emit("context:clear"),!0))}destroy(){var e;return this._ready=!1,this.event.removeAllListeners(),(e=this.socket)==null||e.disconnect(),this.socket=null,this.event.emit("destroy",{applicationId:this._applicationId,sessionId:this._id}),this._id||""}}const A=new k("[AgentSession] ");class pe extends q{constructor(e,t="",s,n,r,i){super(e,t,s,n,r,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),n=yield oe.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});n.on("connect",()=>{A.log("socket:connect"),this.event.emit("socket:connect"),n.emit("init")}),n.on("disconnect",()=>{A.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),n.on("ready",r=>{if(r.code===200){A.log("ready");const i=exports.configuration.debug?x.Debug:x.Normal;i===x.Debug&&r.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const i=new Error(L.SocketConnectionFailed);A.error("error",i),this.event.emit("error",i),e(!1)}}),n.on("action",(r,i)=>f(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:o,data:{runnerIsClient:a,pluginCode:d,funcCode:p,parameters:h,requestBody:u}}=r,l=this.messages[this.messages.length-1];if(!l.messageId)l.actions||(l.actions=[]),l.actions[r.data.step-1]||(l.actions[r.data.step-1]=[]),l.actions[r.data.step-1].push(r),this.event.emit("message:action",{messageId:l.messageId,action:r}),this.event.emit("message:updated",l);else{const w={messageId:"",content:"",role:v.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[r]],comment:{isAgree:0},isReplying:!0};this.pushMessage(w),this.event.emit("message:action",{messageId:w.messageId,action:r})}if(this.inactivating){const w=new Error(L.Inactive);A.warn("error",w),this.event.emit("error",w)}else if(o==="FUNCTION_CALL"&&a){if(A.log(`calling function ${p} 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 $=(c,e,t)=>e in c?se(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t,g=(c,e)=>{for(var t in e||(e={}))B.call(e,t)&&$(c,t,e[t]);if(E)for(var t of E(e))F.call(e,t)&&$(c,t,e[t]);return c},y=(c,e)=>ie(c,ne(e));var J=(c,e)=>{var t={};for(var s in c)B.call(c,s)&&e.indexOf(s)<0&&(t[s]=c[s]);if(c!=null&&E)for(var s of E(c))e.indexOf(s)<0&&F.call(c,s)&&(t[s]=c[s]);return t};var m=(c,e,t)=>($(c,typeof e!="symbol"?e+"":e,t),t);var f=(c,e,t)=>new Promise((s,n)=>{var r=a=>{try{o(t.next(a))}catch(d){n(d)}},i=a=>{try{o(t.throw(a))}catch(d){n(d)}},o=a=>a.done?s(a.value):Promise.resolve(a.value).then(r,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 k=M;const ce=new k("[Config] ");var G=(c=>(c.dev="https://aiot-dev.glodon.com/api/cvforcepd",c.test="https://aiot-dev.glodon.com/api/cvforce",c.prod="https://copilot.glodon.com/api/cvforce",c.local="http://localhost:3000/api/cvforcepd",c))(G||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function Q(c){k.debug=(c==null?void 0:c.debug)||!1,exports.configuration=y(g(g({},exports.configuration),c),{apiRoot:(c==null?void 0:c.apiRoot)||exports.configuration.apiRoot||(c!=null&&c.env?G[c.env||"prod"]:exports.configuration.apiRoot)}),k.debug&&ce.log("updated",exports.configuration)}const T=c=>JSON.parse(ae.decode(c.split(".")[1])),de=c=>{const e=T(c).exp;return new Date().valueOf()/1e3>=e},he=c=>c==null?void 0:c.replace(/[\r\n]+/gm,""),le=c=>c.replace(/\\|\\/g,"");function X(c,e,t){const s=d=>{var 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 n(d,l=!0){const h=`${c}${d}`,u=re.create({baseURL:h});return l&&u.interceptors.request.use(s),u}const r=(d,l)=>{d===401&&t(d,"aiotToken is invalid")},i=(d,l)=>{d!==10001&&d!==10215&&t(d,l)},o=n("/data/v1");return new v.CVForceApi(o,{onHttpStatusError:r,onAppStatusError:i})}var x=(c=>(c[c.Normal=0]="Normal",c[c.Debug=1]="Debug",c))(x||{});const R=new k("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&R.disable()}getEventListenerMap(){return g({},this.eventListenerMap)}on(e,t,s=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),s?this.eventListenerMap[e].push({fn:t,once:!0}):this.eventListenerMap[e].push(t),R.log(`add event ${e} listener ${s?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const s=this.eventListenerMap[e].findIndex(n=>{if(typeof n=="function"&&t===n)return!0;if(n=n,n.fn===t)return!0});s<0?R.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),R.log(`remove event ${e} listener`))}else R.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){R.log(`event ${e} listeners is empty`);return}const s=[];for(let n=0;n<this.eventListenerMap[e].length;n++){const r=this.eventListenerMap[e][n];typeof r=="function"?r(t):s.push(r)}s.forEach(n=>{n&&(n.fn(t),this.off(e,n.fn))}),R.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const _=new k("[Session] ");var L=(c=>(c.DataRequestFailed="data request error",c.SocketConnectionFailed="socket error",c.IdUndefined="session id is not defined",c.SendingEmptyContent="failed at sending empty content",c.Frozen="session is frozen",c.UserModeError="failed at setting socket user mode",c.Inactive="session is inactive",c))(L||{});class q{constructor(e,t="",s,n,r,i){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new Z);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);m(this,"_mcpServers",null);this.token=e,this.lazyload=n,this.client=i||null,this._applicationId=T(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),r&&(this._application=r),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,n||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(a=>f(this,null,function*(){this.data=a,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(a=>f(this,null,function*(){this.data=a,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 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=>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=this._promptVariables.map(n=>{var i;const r=((i=e==null?void 0:e.find(o=>o.key===n.key&&o.type===n.type))==null?void 0:i.value)||n.value;return y(g({},n),{value:r})}).sort((n,r)=>n.key.localeCompare(r.key));if(!(yield Promise.all(t.filter(n=>!(n.type===v.PromptVariableType.User&&n.key==="query")&&!(n.type===v.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 f(this,null,function*(){var t,s,n;if(_.log("setNetOpen:",e),_.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===v.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((n=this._application)==null?void 0:n.arrange[0].enableNetOpen)===!1){console.warn("This Application is disabled to change netOpen.");return}if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{netOpen:e?1:2}),this.data.netOpen=e,_.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return X(exports.configuration.apiRoot,this.token,(e,t)=>{const s=new Error("data request error",{cause:{status:e,message:t}});_.error(s),this.event.emit("error",s)})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}fetchMessages(){return f(this,arguments,function*(e={}){var s,n;const t={pageSize:this._loadingMessagesSize};if(this._id){e=g(g({},t),e),this.event.emit("history:loading"),_.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),_.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),i=r.map((a,d)=>{var u,w;let l=[],h;return typeof((u=a.agentHistoryList)==null?void 0:u.agentList)=="string"&&(l=JSON.parse(a.agentHistoryList.agentList).reduce((I,b)=>(I[b.data.step-1]||(I[b.data.step-1]=[]),I[b.data.step-1].push(b),I),[])),d===r.length-1&&(h=(w=this.data)==null?void 0:w.lastRelatedQuestion),y(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=(n=this.data)==null?void 0:n.lastRelatedQuestion),this.event.emit("history:moreloaded",i),_.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,i}else{const r=new Error("session id is not defined");return _.error(r),this.event.emit("error",r),!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:n=exports.configuration.stream,referenceFirst:r=!1}=t,i=e.uuid||Y.v4(),o=((w=e.text)==null?void 0:w.trim())||"",a=e.files||[],d=e.fileIds;if(!o&&!a.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:a},h={content:o,stream:n,requestId:i,fileIds:d,referenceFirst:r};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:n,referenceFirst:r})),l})}getRelatedQuesion(e){return f(this,null,function*(){var r,i;if(!e.content||e.isSensitive||e.code!==200||!((r=this.application)!=null&&r.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const t=yield this.cvforceApi.postGeneques({content:e.content}).catch(o=>null);if(!t){const o=[],a=y(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 n=y(g({},e),{relatedQuesion:s,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",n),this.event.emit("message:updated",n),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:s}),n})}fillMessageReference(e){return 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,n)=>g(g({},s),t[n])),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 n;t.role!==v.ChatMessageRole.User&&(n=e.oldMessageId||t.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",t),this.event.emit("history:remove",t));const r=this.messages[this.messages.length-1],i={content:r.content,fileIds:r.fileIds,requestId:r.messageId,stream:s,oldMessageId:n},o=a=>f(this,null,function*(){if(a.role===v.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,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 n=e.actions[((s=e.actions)==null?void 0:s.length)-1];if(n){const r=n[n.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:i,pluginCode:o,funcCode:a,funcName:d}=r.data;n.push({data:{pluginName:i,pluginCode:o,funcCode:a,funcName:d,step:r.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:n})}}}e=g(g({},e),t),this.event.emit("message:content",e),this.event.emit("message:updated",e)}else this.pushMessage(t),this.event.emit("message:content",t);return this}handleStreamAnswer(e,t){if(!e.data)return;const s=e.data.type,n=e.data.payload;t.isReplying=!0;const r=()=>{if(!t.searchingStatus){t.searchingStatus="start";return}if(t.searchingStatus==="start"){t.searchingStatus="end";return}};if(s==="error"&&(t.index=-1),s==="beforeSearch"&&r(),s==="searchOver"&&r(),s==="search"&&t.searchReference.push(n),s==="thinking"){t.thinkingStatus="start";const o=n.choices[0];t.reasoningContent=t.reasoningContent+o.delta.reasoningContent}if(s==="thinkingOver"){t.thinkingStatus="end";const i=n.thinkingSecs;t.thinkingSecs=i}if(s==="text"){const o=n.choices[0];t.content=t.content+o.delta.content}if(s==="reference"&&(t.reference=n),s==="result"){const i=n.messageId,o=n.llmModel,a=n.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 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(n=>n.messageId===e.messageId);return s&&(s.comment=e,this.event.emit("message:comment",s)),t})})}clear(){if(!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.patchApplicationIdSessionsIdContext(this._applicationId,this._id).then(()=>(this.event.emit("context:clear"),!0))}destroy(){var e;return this._ready=!1,this.event.removeAllListeners(),(e=this.socket)==null||e.disconnect(),this.socket=null,this.event.emit("destroy",{applicationId:this._applicationId,sessionId:this._id}),this._id||""}}const A=new k("[AgentSession] ");class pe extends q{constructor(e,t="",s,n,r,i){super(e,t,s,n,r,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),n=yield oe.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});n.on("connect",()=>{A.log("socket:connect"),this.event.emit("socket:connect"),n.emit("init")}),n.on("disconnect",()=>{A.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),n.on("ready",r=>{if(r.code===200){A.log("ready");const i=exports.configuration.debug?x.Debug:x.Normal;i===x.Debug&&r.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const i=new Error(L.SocketConnectionFailed);A.error("error",i),this.event.emit("error",i),e(!1)}}),n.on("action",(r,i)=>f(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:o,data:{runnerIsClient:a,pluginCode:d,funcCode:l,parameters:h,requestBody:u}}=r,w=this.messages[this.messages.length-1];if(!w.messageId)w.actions||(w.actions=[]),w.actions[r.data.step-1]||(w.actions[r.data.step-1]=[]),w.actions[r.data.step-1].push(r),this.event.emit("message:action",{messageId:w.messageId,action:r}),this.event.emit("message:updated",w);else{const p={messageId:"",content:"",role:v.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[r]],comment:{isAgree:0},isReplying:!0};this.pushMessage(p),this.event.emit("message:action",{messageId:p.messageId,action:r})}if(this.inactivating){const p=new Error(L.Inactive);A.warn("error",p),this.event.emit("error",p)}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 p=exports.configuration.plugins[d][l];typeof p!="function"&&i({code:404,message:"对不起,没有找到插件方法。"});let I=h==null?void 0:h.query;try{I=JSON.parse(h==null?void 0:h.query)}catch(b){}p(I,(...b)=>{this._stopAnswer||i(...b)})}})),n.on("answer",r=>{if(!this._stopAnswer)if(r.data.code!==200&&(r.data.index=-1,this.event.emit("error",r.data)),r.data.stream||r.data.stream===void 0){let i=this.messages[this.messages.length-1];if(i&&i.role===v.ChatMessageRole.Robot)this.handleStreamAnswer(r.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:v.ChatMessageRole.Robot,reference:[],searchReference:[],messageId:"",sessionId:this.id,messageTime:j(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};this.handleStreamAnswer(r.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(r.data.index===-1){let i=this.messages[this.messages.length-1];if(i&&!i.messageId)i=g(g({},i),r.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:v.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},r.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),r.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:v.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},r.data)),this.event.emit("message:content",r.data))}}),n.on("reference",r=>f(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const h=new Error(L.IdUndefined);A.error(h),this.event.emit("error",h),this.frozen=!1;return}const{type:i,data:o,requestId:a}=r,d=this.messages.findIndex(h=>h.messageId===a&&h.role===v.ChatMessageRole.User);if(d<0)return;const l=d+1;if(l>=this.messages.length){const h={messageId:"",content:"",role:v.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0};this.pushMessage(h)}i==="KG"?(this.messages[l]=y(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]=y(g({},this.messages[l]),{searchReference:o.knowledgeReference}),this.event.emit("message:searchreference",o.searchReference),this.event.emit("message:updated",this.messages[l]))})),this.socket=n,n.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((e,t)=>{if(!this.socket){t("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,s=>{s.code===200?(Object.keys(s.data).forEach(n=>{s.data[n].code!==200&&console.error(n,"MCP Server 注册失败。",s.data[n])}),e(!0)):(console.error("MCP Server 注册失败。",s),t(s))})}):Promise.resolve(!0)}addMcpServers(e){return f(this,null,function*(){return this.ready?this.socket?new Promise((t,s)=>{this.socket&&this.socket.emit("add_mcp_servers",e,n=>{n.code===200?(Object.keys(n.data).forEach(r=>{n.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",n.data[r])}),t(!0)):(console.error("MCP Server 注册失败。",n),s(n))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return f(this,null,function*(){return this.ready?this.socket?new Promise((e,t)=>{this.socket&&this.socket.emit("list_mcp_servers",s=>{s.code===200?e(s.data):t(s)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(e,t){return f(this,null,function*(){var n,r,i;let s=y(g({},e),{promptVariables:this.promptVariables.filter(o=>o.type===v.PromptVariableType.User).reduce((o,a)=>y(g({},o),{[a.key]:a.value}),{}),systemPromptVariables:this.promptVariables.filter(o=>o.type===v.PromptVariableType.System).reduce((o,a)=>y(g({},o),{[a.key]:a.value}),{}),knowledges:(n=this.knowledges)==null?void 0:n.map(o=>o.id)});if(!this.active){if(yield this.activate(),!this.socket){const o=new Error(L.SocketConnectionFailed);return A.warn("error",o),this.event.emit("error",o),!1}(r=this.socket)==null||r.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 f(this,null,function*(){const t=c.getReader();let s;for(;!(s=yield t.read()).done;)e(s.value)})}function ue(c){let e,t,s,n=!1,r;return function(o){e===void 0?(e=o,t=0,s=-1,r=!1):e=me(e,o);const a=e.length;let d=0;for(;t<a;){n&&(e[t]===10&&(d=++t),n=!1);let l=-1;for(;t<a&&l===-1;++t)switch(e[t]){case 58:s===-1&&(s=t-d);break;case 13:n=!1,t+4<a&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(r=!0);case 10:l=t;break}if(l===-1)break;c(e.subarray(d,l),s,r),d=t,s=-1,r=!1}d===a?e=void 0:d!==0&&(e=e.subarray(d),t-=d)}}function ge(c,e,t){let s=H();const n=new TextDecoder;return function(i,o,a){if(i.length===0)t==null||t(s),s=H();else if(o>0){const d=n.decode(i.subarray(0,o)),l=o+(i[o+1]===32?2:1);let h=n.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,p){var h=p,{signal:e,headers:t,onopen:s,onmessage:n,onclose:r,onerror:i,openWhenHidden:o,fetch:a}=h,d=J(h,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((u,l)=>{const w=g({},t);w.accept||(w.accept=z);let I;function _(){I.abort(),document.hidden||O()}o||document.addEventListener("visibilitychange",_);let N=ve,P=0;function V(){document.removeEventListener("visibilitychange",_),window.clearTimeout(P),I.abort()}e==null||e.addEventListener("abort",()=>{V(),u()});const ee=a!=null?a:window.fetch,te=s!=null?s:ye;function O(){return f(this,null,function*(){var D;I=new AbortController;try{const C=yield ee(c,y(g({},d),{headers:w,signal:I.signal}));yield te(C),yield fe(C.body,ue(ge(S=>{S?w[U]=S:delete w[U]},S=>{N=S},n))),r==null||r(),V(),u()}catch(C){if(!I.signal.aborted)try{const S=(D=i==null?void 0:i(C))!=null?D:N;window.clearTimeout(P),P=window.setTimeout(O,S)}catch(S){V(),l(S)}}})}O()})}function ye(c){const e=c.headers.get("content-type");if(!(e!=null&&e.startsWith(z)))throw new Error(`Expected content-type to be ${z}, Actual: ${e}`)}const K=new k("[DialogSession] ");class we extends q{constructor(t,s="",n,r,i,o){super(t,s,n,r,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,n,r,i,o){return f(this,null,function*(){const a={code:0,content:"",role:v.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=y(g({},n),{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:r,onopen(p){return p.ok&&i!=null&&i.onopen&&i.onopen(),Promise.resolve()},onmessage(p){if(!p.data.includes('{"code": ')){let u={};try{u=JSON.parse(p.data)}catch(w){}(u==null?void 0:u.mtype)==="search"?a.searchReference.push(u):a.content=a.content+p.data;const l={content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:s,messageTime:j(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(i==null?void 0:i.onmessage)&&i.onmessage(l)}const h=JSON.parse(p.data);if(a.reference=h.data.reference,a.searchReference=h.data.searchReference,a.messageTime=h.data.messageTime,a.messageId=h.data.messageId,a.llmModel=h.data.llmModel,a.content=h.data.content,a.code=h.code,h.code===200){const u={code:a.code,content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:s,messageTime:a.messageTime,isReplying:!0};i!=null&&i.onmessage&&i.onmessage(u)}else return i!=null&&i.onclose&&i.onclose(a),o&&o({code:a.code,message:a.message})},onerror(){i!=null&&i.onerror&&i.onerror()},onclose(){const p={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(p)}})})}postChatV3EventSource(t,s,n,r,i,o){return f(this,null,function*(){const a=this,d={code:0,content:"",role:v.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},p=y(g({},n),{stream:exports.configuration.stream});W(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(p),openWhenHidden:!0,signal:r,onopen(h){return h.ok&&i!=null&&i.onopen&&i.onopen(),Promise.resolve()},onmessage(h){if(!h.data&&!h.event&&!h.id&&!h.retry)return;let u={};try{u=JSON.parse(h.data)}catch(l){console.error("parse eventData to JSON failed. ",h.data)}if(u.code!==200)return d.index=-1,d.code=u.code,d.message=u.message,i!=null&&i.onmessage&&i.onmessage(d),o&&o({code:u.code,message:u.message});a.handleStreamAnswer(u,d),i!=null&&i.onmessage&&i.onmessage(d)},onerror(){i!=null&&i.onerror&&i.onerror()},onclose(){const h=y(g({},d),{isReplying:!1});i!=null&&i.onclose&&i.onclose(h)}})})}sendQuestion(t,s){return f(this,null,function*(){var d;const{content:n,fileIds:r,oldMessageId:i}=t,{stream:o,referenceFirst:a}=s;if(this.active||(yield this.activate()),this._id){let p={content:n,fileIds:r,referenceFirst:a,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)};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,p,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.3.5-alpha.29",_e="glodoncv",ke="aiot bot client js sdk",Se="module",Ae=!1,Re=["aiot","bot","bot client","sdk"],Me=["dist"],xe="./dist/es/index.mjs",Le="./dist/lib/index.js",Ce="./dist/src/index.d.ts",Ee={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},Te="MIT",Pe={watch:"yarn build --watch",example:"node ./example/server.js",dev:"npm-run-all -p watch example",start:"vite",build:"tsc && vite build --mode prod && yarn build:cdn","build:npm":"tsc && vite build --mode prod","build:cdn":"tsc && vite build --mode prod --config ./vite.config.cdn.ts",preview:"vite preview",check:"yarn prettier --check .",write:"yarn prettier --write .",lint:"eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js"},Ve={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@types/express":"^4","@types/identity-obj-proxy":"^3","@typescript-eslint/eslint-plugin":"^5.35.1","@typescript-eslint/parser":"^5.35.1","babel-loader":"^8.3.0",eslint:"^8.0.1","eslint-config-prettier":"^8.5.0","eslint-config-standard-with-typescript":"^22.0.0","eslint-plugin-import":"^2.25.2","eslint-plugin-n":"^15.0.0","eslint-plugin-promise":"^6.0.0","eslint-plugin-react":"^7.31.0","eslint-plugin-storybook":"^0.6.10",express:"4","http-proxy-middleware":"^3.0.0","identity-obj-proxy":"^3.0.0","npm-run-all":"^4.1.5",prettier:"2.7.1","rollup-plugin-visualizer":"^6.0.1","socket.io":"^4.7.5","ts-node":"^10.9.2",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0","vite-tsconfig-paths":"^5.1.4"},Oe={access:"public",registry:"https://registry.npmjs.org/"},$e={"@glodon-aiot/apis":"^3.3.5-alpha.29",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:ke,type:Se,sideEffects:Ae,keywords:Re,files:Me,module:xe,main:Le,typings:Ce,exports:Ee,license:Te,scripts:Pe,devDependencies:Ve,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:Oe,dependencies:$e},ze=new k("[BotClient] ");class je{constructor(e,t,s=!0,n={analytics:{enabled:!1}}){m(this,"event",new Z);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=s,this.sdkConfigs=n,Q(t),this._applicationId=T(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(r=>{Q(y(g({},t),{stream:t.stream===void 0?(r==null?void 0:r.type)===v.ApplicationTypes.Dialog:t.stream})),this.event.emit("ready")})}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return f(this,null,function*(){var t,s,n,r,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=(r=(n=this._application)==null?void 0:n.arrange)==null?void 0:r[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,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=T(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,s,n,r){return f(this,null,function*(){const i=this;return new Promise((o,a)=>{const d=p=>f(this,null,function*(){if(p===v.ApplicationTypes.Agent)o(new pe(e,t,s,n,r,i));else if(p===v.ApplicationTypes.Dialog)o(new we(e,t,s,n,r,i));else throw Error(`不支持的应用类型:${p}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return f(this,null,function*(){return new Promise((t,s)=>{const n=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>{const i=[];return r.forEach(o=>f(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(n())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(n())},!0)})})}loadSession(e="",t){return f(this,null,function*(){this.checkReady();let s=this.sessions.find(n=>n.id===e);if(s||(s=yield this.createSession(this.token,e,t),this._sessions.push(s)),this._activeSession){if(this._activeSession===s)return s;this._activeSession.inactivate()}return s.id?(yield s.activate(),this._activeSession=s):s.addEventListener("data:loaded",()=>{this._activeSession!==s&&(s==null||s.activate(),this._activeSession=s)},!0),s})}reload(){return this.loadApplication().then(()=>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 n=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!n){console.warn("setTop session failed.");return}return yield n.setTop(t),this.getSessions({order:s})})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return f(this,null,function*(){this.checkReady();let s=-1;if(typeof e=="string"?s=this._sessions.findIndex(n=>n.id===e):s=this._sessions.findIndex(n=>n.id===e.id),s>-1){const n=this._sessions[s];t&&(yield n.delete()),this._sessions.splice(s,1)}else console.warn("session delete failed, session is not exist.")})}clean(){this._sessions.forEach(e=>e.destroy()),this.sessions=[]}}class qe{constructor(e,t={},s){m(this,"code");m(this,"description","");m(this,"loaded",!1);m(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}exports.AgentPlugin=qe;exports.BotClient=je;exports.Session=q;exports.configure=Q;
|
|
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:n,onclose:r,onerror:i,openWhenHidden:o,fetch:a}=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=a!=null?a: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(S=>{S?p[U]=S:delete p[U]},S=>{N=S},n))),r==null||r(),V(),u()}catch(C){if(!I.signal.aborted)try{const S=(D=i==null?void 0:i(C))!=null?D:N;window.clearTimeout(P),P=window.setTimeout(O,S)}catch(S){V(),w(S)}}})}O()})}function ye(c){const e=c.headers.get("content-type");if(!(e!=null&&e.startsWith(z)))throw new Error(`Expected content-type to be ${z}, Actual: ${e}`)}const K=new k("[DialogSession] ");class we extends q{constructor(t,s="",n,r,i,o){super(t,s,n,r,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,n,r,i,o){return f(this,null,function*(){const a={code:0,content:"",role:v.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=y(g({},n),{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:r,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"?a.searchReference.push(u):a.content=a.content+l.data;const w={content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:s,messageTime:j(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(i==null?void 0:i.onmessage)&&i.onmessage(w)}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 u={code:a.code,content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:s,messageTime:a.messageTime,isReplying:!0};i!=null&&i.onmessage&&i.onmessage(u)}else return i!=null&&i.onclose&&i.onclose(a),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,n,r,i,o){return f(this,null,function*(){const a=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({},n),{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:r,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});a.handleStreamAnswer(u,d),i!=null&&i.onmessage&&i.onmessage(d)},onerror(){i!=null&&i.onerror&&i.onerror()},onclose(){const h=y(g({},d),{isReplying:!1});i!=null&&i.onclose&&i.onclose(h)}})})}sendQuestion(t,s){return f(this,null,function*(){var d;const{content:n,fileIds:r,oldMessageId:i}=t,{stream:o,referenceFirst:a}=s;if(this.active||(yield this.activate()),this._id){let l={content:n,fileIds:r,referenceFirst:a,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)};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.3.5-beta.30",_e="glodoncv",ke="aiot bot client js sdk",Se="module",Ae=!1,Re=["aiot","bot","bot client","sdk"],Me=["dist"],xe="./dist/es/index.mjs",Le="./dist/lib/index.js",Ce="./dist/src/index.d.ts",Ee={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},Te="MIT",Pe={watch:"yarn build --watch",example:"node ./example/server.js",dev:"npm-run-all -p watch example",start:"vite",build:"tsc && vite build --mode prod && yarn build:cdn","build:npm":"tsc && vite build --mode prod","build:cdn":"tsc && vite build --mode prod --config ./vite.config.cdn.ts",preview:"vite preview",check:"yarn prettier --check .",write:"yarn prettier --write .",lint:"eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js"},Ve={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@types/express":"^4","@types/identity-obj-proxy":"^3","@typescript-eslint/eslint-plugin":"^5.35.1","@typescript-eslint/parser":"^5.35.1","babel-loader":"^8.3.0",eslint:"^8.0.1","eslint-config-prettier":"^8.5.0","eslint-config-standard-with-typescript":"^22.0.0","eslint-plugin-import":"^2.25.2","eslint-plugin-n":"^15.0.0","eslint-plugin-promise":"^6.0.0","eslint-plugin-react":"^7.31.0","eslint-plugin-storybook":"^0.6.10",express:"4","http-proxy-middleware":"^3.0.0","identity-obj-proxy":"^3.0.0","npm-run-all":"^4.1.5",prettier:"2.7.1","rollup-plugin-visualizer":"^6.0.1","socket.io":"^4.7.5","ts-node":"^10.9.2",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0","vite-tsconfig-paths":"^5.1.4"},Oe={access:"public",registry:"https://registry.npmjs.org/"},$e={"@glodon-aiot/apis":"^3.3.5-beta.30",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:ke,type:Se,sideEffects:Ae,keywords:Re,files:Me,module:xe,main:Le,typings:Ce,exports:Ee,license:Te,scripts:Pe,devDependencies:Ve,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:Oe,dependencies:$e},ze=new k("[BotClient] ");class je{constructor(e,t,s=!0,n={analytics:{enabled:!1}}){m(this,"event",new Z);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=s,this.sdkConfigs=n,Q(t),this._applicationId=T(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(r=>{Q(y(g({},t),{stream:t.stream===void 0?(r==null?void 0:r.type)===v.ApplicationTypes.Dialog:t.stream})),this.event.emit("ready")})}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return f(this,null,function*(){var t,s,n,r,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=(r=(n=this._application)==null?void 0:n.arrange)==null?void 0:r[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,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=T(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,s,n,r){return f(this,null,function*(){const i=this;return new Promise((o,a)=>{const d=l=>f(this,null,function*(){if(l===v.ApplicationTypes.Agent)o(new pe(e,t,s,n,r,i));else if(l===v.ApplicationTypes.Dialog)o(new we(e,t,s,n,r,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 n=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>{const i=[];return r.forEach(o=>f(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(n())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(n())},!0)})})}loadSession(e="",t){return f(this,null,function*(){this.checkReady();let s=this.sessions.find(n=>n.id===e);if(s||(s=yield this.createSession(this.token,e,t),this._sessions.push(s)),this._activeSession){if(this._activeSession===s)return s;this._activeSession.inactivate()}return s.id?(yield s.activate(),this._activeSession=s):s.addEventListener("data:loaded",()=>{this._activeSession!==s&&(s==null||s.activate(),this._activeSession=s)},!0),s})}reload(){return this.loadApplication().then(()=>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 n=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!n){console.warn("setTop session failed.");return}return yield n.setTop(t),this.getSessions({order:s})})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return f(this,null,function*(){this.checkReady();let s=-1;if(typeof e=="string"?s=this._sessions.findIndex(n=>n.id===e):s=this._sessions.findIndex(n=>n.id===e.id),s>-1){const n=this._sessions[s];t&&(yield n.delete()),this._sessions.splice(s,1)}else console.warn("session delete failed, session is not exist.")})}clean(){this._sessions.forEach(e=>e.destroy()),this.sessions=[]}}class qe{constructor(e,t={},s){m(this,"code");m(this,"description","");m(this,"loaded",!1);m(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}exports.AgentPlugin=qe;exports.BotClient=je;exports.Session=q;exports.configure=Q;
|
package/dist/src/Session.d.ts
CHANGED
|
@@ -171,6 +171,7 @@ export default abstract class Session {
|
|
|
171
171
|
get messagesLoading(): boolean;
|
|
172
172
|
send(params: {
|
|
173
173
|
text?: string;
|
|
174
|
+
files?: any[];
|
|
174
175
|
uuid?: string;
|
|
175
176
|
fileIds?: string[];
|
|
176
177
|
}, configs?: QuestionConfig): Promise<false | {
|
|
@@ -181,6 +182,7 @@ export default abstract class Session {
|
|
|
181
182
|
reference: never[];
|
|
182
183
|
searchReference: never[];
|
|
183
184
|
messageTime: string;
|
|
185
|
+
files: any[];
|
|
184
186
|
}>;
|
|
185
187
|
protected getRelatedQuesion(message: IChatMessage): Promise<IChatMessage>;
|
|
186
188
|
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.5-
|
|
3
|
+
"version": "3.3.5-beta.30",
|
|
4
4
|
"author": "glodoncv",
|
|
5
5
|
"description": "aiot bot client js sdk",
|
|
6
6
|
"type": "module",
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
"registry": "https://registry.npmjs.org/"
|
|
80
80
|
},
|
|
81
81
|
"dependencies": {
|
|
82
|
-
"@glodon-aiot/apis": "^3.3.5-
|
|
82
|
+
"@glodon-aiot/apis": "^3.3.5-beta.30",
|
|
83
83
|
"axios": "0.24.0",
|
|
84
84
|
"buffer": "^6.0.3",
|
|
85
85
|
"dayjs": "^1.11.13",
|