@glodon-aiot/agent-cli-sdk 3.3.2-beta.9 → 3.3.5-alpha.16

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.
@@ -1,43 +1,43 @@
1
- var E = Object.defineProperty, V = Object.defineProperties;
2
- var x = Object.getOwnPropertyDescriptors;
3
- var M = Object.getOwnPropertySymbols;
4
- var Q = Object.prototype.hasOwnProperty, R = Object.prototype.propertyIsEnumerable;
5
- var b = (h, e, t) => e in h ? E(h, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : h[e] = t, f = (h, e) => {
6
- for (var t in e || (e = {}))
7
- Q.call(e, t) && b(h, t, e[t]);
8
- if (M)
9
- for (var t of M(e))
10
- R.call(e, t) && b(h, t, e[t]);
1
+ var V = Object.defineProperty, x = Object.defineProperties;
2
+ var Q = Object.getOwnPropertyDescriptors;
3
+ var k = Object.getOwnPropertySymbols;
4
+ var T = Object.prototype.hasOwnProperty, R = Object.prototype.propertyIsEnumerable;
5
+ var M = (h, e, i) => e in h ? V(h, e, { enumerable: !0, configurable: !0, writable: !0, value: i }) : h[e] = i, f = (h, e) => {
6
+ for (var i in e || (e = {}))
7
+ T.call(e, i) && M(h, i, e[i]);
8
+ if (k)
9
+ for (var i of k(e))
10
+ R.call(e, i) && M(h, i, e[i]);
11
11
  return h;
12
- }, I = (h, e) => V(h, x(e));
13
- var c = (h, e, t) => (b(h, typeof e != "symbol" ? e + "" : e, t), t);
14
- var r = (h, e, t) => new Promise((i, n) => {
12
+ }, I = (h, e) => x(h, Q(e));
13
+ var c = (h, e, i) => (M(h, typeof e != "symbol" ? e + "" : e, i), i);
14
+ var r = (h, e, i) => new Promise((t, n) => {
15
15
  var o = (s) => {
16
16
  try {
17
- d(t.next(s));
17
+ d(i.next(s));
18
18
  } catch (p) {
19
19
  n(p);
20
20
  }
21
21
  }, l = (s) => {
22
22
  try {
23
- d(t.throw(s));
23
+ d(i.throw(s));
24
24
  } catch (p) {
25
25
  n(p);
26
26
  }
27
- }, d = (s) => s.done ? i(s.value) : Promise.resolve(s.value).then(o, l);
28
- d((t = t.apply(h, e)).next());
27
+ }, d = (s) => s.done ? t(s.value) : Promise.resolve(s.value).then(o, l);
28
+ d((i = i.apply(h, e)).next());
29
29
  });
30
- import { v4 as k } from "uuid";
31
- import { parseJWT as T, removeNewlines as z, removeLeadingAndTrailingBackslashes as O } from "./utils.mjs";
32
- import { ApplicationTypes as S, PromptStatus as C, ChatMessageRole as L } from "@glodon-aiot/apis";
33
- import P from "./Logger.mjs";
30
+ import { v4 as S } from "uuid";
31
+ import { parseJWT as z, removeNewlines as O, removeLeadingAndTrailingBackslashes as C } from "./utils.mjs";
32
+ import { ApplicationTypes as E, PromptStatus as P, PromptVariableType as b, ChatMessageRole as L } from "@glodon-aiot/apis";
33
+ import q from "./Logger.mjs";
34
34
  import { configuration as A } from "./Config.mjs";
35
- import q from "./EventBus.mjs";
36
- import { getCVForceService as F } from "./api/index.mjs";
37
- import N from "dayjs";
38
- const u = new P("[Session] ");
39
- var B = /* @__PURE__ */ ((h) => (h.DataRequestFailed = "data request error", h.SocketConnectionFailed = "socket error", h.IdUndefined = "session id is not defined", h.SendingEmptyContent = "failed at sending empty content", h.Frozen = "session is frozen", h.UserModeError = "failed at setting socket user mode", h.Inactive = "session is inactive", h))(B || {});
40
- class $ {
35
+ import F from "./EventBus.mjs";
36
+ import { getCVForceService as N } from "./api/index.mjs";
37
+ import B from "dayjs";
38
+ const u = new q("[Session] ");
39
+ var U = /* @__PURE__ */ ((h) => (h.DataRequestFailed = "data request error", h.SocketConnectionFailed = "socket error", h.IdUndefined = "session id is not defined", h.SendingEmptyContent = "failed at sending empty content", h.Frozen = "session is frozen", h.UserModeError = "failed at setting socket user mode", h.Inactive = "session is inactive", h))(U || {});
40
+ class X {
41
41
  /**
42
42
  * Session 类的构造函数,用于初始化会话实例。
43
43
  * @param token - 用户的身份验证令牌,用于解析应用 ID。
@@ -47,14 +47,14 @@ class $ {
47
47
  * @param _application - 应用信息,可选参数。
48
48
  * @param client - Bot 客户端实例,可选参数。
49
49
  */
50
- constructor(e, t = "", i, n, o, l) {
50
+ constructor(e, i = "", t, n, o, l) {
51
51
  c(this, "_id");
52
52
  c(this, "_frozen", !1);
53
53
  //是否可发送新问题
54
54
  c(this, "inactivating", !1);
55
55
  c(this, "_ready", !1);
56
56
  // ready = false;
57
- c(this, "event", new q());
57
+ c(this, "event", new F());
58
58
  //从token解析出来的用户信息
59
59
  c(this, "_applicationId");
60
60
  c(this, "_application", null);
@@ -72,52 +72,52 @@ class $ {
72
72
  c(this, "_dataLoading", !1);
73
73
  c(this, "_dataLoaded", !1);
74
74
  c(this, "_mcpServers", null);
75
- this.token = e, this.lazyload = n, this.client = l || null, this._applicationId = T(e).rid || A.applicationId, this.cvforceApi = this.getService(), o && (this._application = o), this.event.emit("init", {
75
+ this.token = e, this.lazyload = n, this.client = l || null, this._applicationId = z(e).rid || A.applicationId, this.cvforceApi = this.getService(), o && (this._application = o), this.event.emit("init", {
76
76
  applicationId: this._applicationId,
77
- sessionId: t
77
+ sessionId: i
78
78
  }), this.loadApplicationInfo().then(() => {
79
79
  var d;
80
- if (t)
81
- this._id = t, this.event.emit("data:loading"), i ? (this.data = i, n || (this._dataLoading = !0, this.cvforceApi.getSession(this.applicationId, t).then((s) => r(this, null, function* () {
82
- this.data = s, this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, t);
80
+ if (i)
81
+ this._id = i, this.event.emit("data:loading"), t ? (this.data = t, n || (this._dataLoading = !0, this.cvforceApi.getSession(this.applicationId, i).then((s) => r(this, null, function* () {
82
+ this.data = s, this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, i);
83
83
  })).then(() => r(this, null, function* () {
84
84
  this.messages = [], yield this.fetchMessages(), this.event.emit("data:loaded", this.data), this.event.emit("data:updated", this.data);
85
- })))) : (this._dataLoading = !0, this.cvforceApi.getSession(this.applicationId, t).then((s) => r(this, null, function* () {
86
- this.data = s, this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, t);
85
+ })))) : (this._dataLoading = !0, this.cvforceApi.getSession(this.applicationId, i).then((s) => r(this, null, function* () {
86
+ this.data = s, this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, i);
87
87
  })).then(() => r(this, null, function* () {
88
88
  this.messages = [], yield this.fetchMessages(), this.event.emit("data:loaded", this.data), this.event.emit("data:updated", this.data), this._dataLoading = !1, this._dataLoaded = !0;
89
89
  })));
90
90
  else {
91
- const s = (i == null ? void 0 : i.name) || "新建会话";
91
+ const s = (t == null ? void 0 : t.name) || "新建会话";
92
92
  this.event.emit("data:creating", {
93
93
  applicationId: this._applicationId,
94
94
  name: s
95
95
  }), this.event.emit("data:loading"), this.cvforceApi.postSession(this.applicationId, {
96
96
  name: s,
97
97
  // @ts-ignore
98
- netOpen: i == null ? void 0 : i.netOpen,
99
- knowledgeIdList: (d = i == null ? void 0 : i.knowledges) == null ? void 0 : d.map((p) => p.id),
98
+ netOpen: t == null ? void 0 : t.netOpen,
99
+ knowledgeIdList: (d = t == null ? void 0 : t.knowledges) == null ? void 0 : d.map((p) => p.id),
100
100
  applicationId: this._applicationId
101
101
  }).then((p) => r(this, null, function* () {
102
102
  var g;
103
103
  this._id = p.id, this.data = I(f({}, p), {
104
- knowledges: i == null ? void 0 : i.knowledges
104
+ knowledges: t == null ? void 0 : t.knowledges
105
105
  }), this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, this._id), yield (() => r(this, null, function* () {
106
- if (i != null && i.knowledges)
107
- return this.setKnowledges((i == null ? void 0 : i.knowledges) || void 0);
106
+ if (t != null && t.knowledges)
107
+ return this.setKnowledges((t == null ? void 0 : t.knowledges) || void 0);
108
108
  }))(), yield (() => {
109
- if (i != null && i.promptVariables) {
110
- const w = this._promptVariables.map((m) => {
111
- var y, v;
112
- const a = ((v = (y = i.promptVariables) == null ? void 0 : y.find((_) => _.key === m.key)) == null ? void 0 : v.value) || "";
109
+ if (t != null && t.promptVariables) {
110
+ const y = this._promptVariables.map((m) => {
111
+ var w, v;
112
+ const a = ((v = (w = t.promptVariables) == null ? void 0 : w.find((_) => _.key === m.key)) == null ? void 0 : v.value) || "";
113
113
  return I(f({}, m), {
114
114
  value: a
115
115
  });
116
116
  }).sort((m, a) => m.key.localeCompare(a.key));
117
- return this.setPromptVariables(w || []);
117
+ return this.setPromptVariables(y || []);
118
118
  } else
119
119
  return;
120
- })(), this.event.emit("data:created", this.data), this.event.emit("data:loaded", this.data), this.event.emit("data:updated", this.data), ((g = this.application) == null ? void 0 : g.type) !== S.Agent && (this._ready = !0, this.event.emit("ready"));
120
+ })(), this.event.emit("data:created", this.data), this.event.emit("data:loaded", this.data), this.event.emit("data:updated", this.data), ((g = this.application) == null ? void 0 : g.type) !== E.Agent && (this._ready = !0, this.event.emit("ready"));
121
121
  }));
122
122
  }
123
123
  });
@@ -181,28 +181,28 @@ class $ {
181
181
  throw Error("session id is not defined");
182
182
  if (!this.data)
183
183
  throw Error("session data is not loaded");
184
- const e = this.promptVariables.filter((t) => t.status === C.Quoted).filter((t) => !t.value);
184
+ const e = this.promptVariables.filter((i) => i.status === P.Quoted).filter((i) => !i.value);
185
185
  if (e.length)
186
- throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map((t) => t.key).join(", ")}`);
186
+ throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map((i) => i.key).join(", ")}`);
187
187
  }
188
188
  get promptVariables() {
189
- return this._promptVariables.filter((e) => e.key !== "query");
189
+ return this._promptVariables.filter((e) => !(e.type === b.User && e.key === "query") && !(e.type === b.System && e.key === "datetime"));
190
190
  }
191
191
  setPromptVariables(e) {
192
192
  return r(this, null, function* () {
193
- const t = this._promptVariables.map((i) => {
193
+ const i = this._promptVariables.map((t) => {
194
194
  var o;
195
- const n = ((o = e == null ? void 0 : e.find((l) => l.key === i.key)) == null ? void 0 : o.value) || i.value;
196
- return I(f({}, i), {
195
+ const n = ((o = e == null ? void 0 : e.find((l) => l.key === t.key)) == null ? void 0 : o.value) || t.value;
196
+ return I(f({}, t), {
197
197
  value: n
198
198
  });
199
- }).sort((i, n) => i.key.localeCompare(n.key));
200
- if (yield Promise.all(t.filter((i) => i.key !== "query").map((i) => {
199
+ }).sort((t, n) => t.key.localeCompare(n.key));
200
+ if (yield Promise.all(i.filter((t) => !(t.type === b.User && t.key === "query") && !(t.type === b.System && t.key === "datetime")).map((t) => {
201
201
  if (!this.data)
202
202
  throw Error("session data is not loaded");
203
- if (!(!i.id || !i.key))
204
- return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId, this.data.id, i.id, {
205
- value: i.value
203
+ if (!(!t.id || !t.key))
204
+ return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId, this.data.id, t.id, {
205
+ value: t.value
206
206
  }).catch(console.error);
207
207
  })), !this.data)
208
208
  throw Error("session data is not loaded");
@@ -223,8 +223,8 @@ class $ {
223
223
  */
224
224
  setNetOpen(e) {
225
225
  return r(this, null, function* () {
226
- var t, i, n;
227
- if (u.log("setNetOpen:", e), u.log("application arrange setting value: ", (t = this._application) == null ? void 0 : t.arrange[0].enableNetOpen), ((i = this._application) == null ? void 0 : i.type) === S.Agent) {
226
+ var i, t, n;
227
+ if (u.log("setNetOpen:", e), u.log("application arrange setting value: ", (i = this._application) == null ? void 0 : i.arrange[0].enableNetOpen), ((t = this._application) == null ? void 0 : t.type) === E.Agent) {
228
228
  console.warn("Agent Application Sessions are disabled to setNetOpen.");
229
229
  return;
230
230
  }
@@ -243,28 +243,28 @@ class $ {
243
243
  });
244
244
  }
245
245
  getService() {
246
- return F(A.apiRoot, this.token, (e, t) => {
247
- const i = new Error(
246
+ return N(A.apiRoot, this.token, (e, i) => {
247
+ const t = new Error(
248
248
  "data request error"
249
249
  /* DataRequestFailed */
250
250
  // {
251
251
  // cause: { status, message },
252
252
  // }
253
253
  );
254
- u.error(i), this.event.emit("error", i);
254
+ u.error(t), this.event.emit("error", t);
255
255
  });
256
256
  }
257
- addEventListener(e, t, i = !1) {
258
- if (typeof t != "function")
257
+ addEventListener(e, i, t = !1) {
258
+ if (typeof i != "function")
259
259
  throw Error("event listener is not a function");
260
- if (i) {
261
- this.event.once(e, t);
260
+ if (t) {
261
+ this.event.once(e, i);
262
262
  return;
263
263
  }
264
- this.event.on(e, t);
264
+ this.event.on(e, i);
265
265
  }
266
- removeEventListener(e, t) {
267
- this.event.off(e, t);
266
+ removeEventListener(e, i) {
267
+ this.event.off(e, i);
268
268
  }
269
269
  /**
270
270
  * 获取对话记录
@@ -273,23 +273,23 @@ class $ {
273
273
  */
274
274
  fetchMessages() {
275
275
  return r(this, arguments, function* (e = {}) {
276
- var i, n;
277
- const t = {
276
+ var t, n;
277
+ const i = {
278
278
  pageSize: this._loadingMessagesSize
279
279
  };
280
280
  if (this._id) {
281
- e = f(f({}, t), e), this.event.emit("history:loading"), u.log("history:loading"), (e.endTime || e.startTime) && (this.event.emit("history:moreloading", e), u.log("history:moreloading", e)), this._loadingMessages = !0;
281
+ e = f(f({}, i), 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;
282
282
  const o = yield this.cvforceApi.getChatHistorySessionId(this._applicationId, this._id, e), l = o.map((s, p) => {
283
283
  var m, a;
284
- let g = [], w;
285
- return typeof ((m = s.agentHistoryList) == null ? void 0 : m.agentList) == "string" && (g = JSON.parse(s.agentHistoryList.agentList).reduce((v, _) => (v[_.data.step - 1] || (v[_.data.step - 1] = []), v[_.data.step - 1].push(_), v), [])), p === o.length - 1 && (w = (a = this.data) == null ? void 0 : a.lastRelatedQuestion), I(f({}, s), {
284
+ let g = [], y;
285
+ return typeof ((m = s.agentHistoryList) == null ? void 0 : m.agentList) == "string" && (g = JSON.parse(s.agentHistoryList.agentList).reduce((v, _) => (v[_.data.step - 1] || (v[_.data.step - 1] = []), v[_.data.step - 1].push(_), v), [])), p === o.length - 1 && (y = (a = this.data) == null ? void 0 : a.lastRelatedQuestion), I(f({}, s), {
286
286
  actions: g,
287
- relatedQuesion: w
287
+ relatedQuesion: y
288
288
  });
289
289
  });
290
290
  if (!e.endTime && !e.startTime) {
291
291
  const s = this.messages[this.messages.length - 1];
292
- s && !s.relatedQuesion && (s.relatedQuesion = (i = this.data) == null ? void 0 : i.lastRelatedQuestion), this.messages = [...l, ...this.messages];
292
+ s && !s.relatedQuesion && (s.relatedQuesion = (t = this.data) == null ? void 0 : t.lastRelatedQuestion), this.messages = [...l, ...this.messages];
293
293
  } else if (e.endTime && !e.startTime) {
294
294
  const s = this.messages.findIndex((p) => p.ts === e.endTime);
295
295
  this.messages.splice(0, s + 1), this.messages = [...l, ...this.messages];
@@ -366,17 +366,17 @@ class $ {
366
366
  activate() {
367
367
  return r(this, null, function* () {
368
368
  if (this.activing)
369
- return new Promise((t) => {
369
+ return new Promise((i) => {
370
370
  this.addEventListener("activated", () => {
371
- t(!0);
371
+ i(!0);
372
372
  }, !0);
373
373
  });
374
374
  if (!this._id)
375
375
  throw Error("session is not avalible. id is undefined");
376
376
  this.activing = !0;
377
377
  const e = this._id;
378
- return this._dataLoading = !0, this._dataLoaded = !1, this.data = yield this.cvforceApi.getSession(this.applicationId, e).then((t) => r(this, null, function* () {
379
- return this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, e), t;
378
+ return this._dataLoading = !0, this._dataLoaded = !1, this.data = yield this.cvforceApi.getSession(this.applicationId, e).then((i) => r(this, null, function* () {
379
+ return this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, e), i;
380
380
  })), 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;
381
381
  });
382
382
  }
@@ -391,8 +391,8 @@ class $ {
391
391
  get messagesLoading() {
392
392
  return this._loadingMessages;
393
393
  }
394
- send(i) {
395
- return r(this, arguments, function* (e, t = {
394
+ send(t) {
395
+ return r(this, arguments, function* (e, i = {
396
396
  stream: A.stream
397
397
  }) {
398
398
  var m;
@@ -404,7 +404,7 @@ class $ {
404
404
  const {
405
405
  stream: n = A.stream,
406
406
  referenceFirst: o = !1
407
- } = t, l = e.uuid || k(), d = ((m = e.text) == null ? void 0 : m.trim()) || "", s = e.fileIds;
407
+ } = i, l = e.uuid || S(), d = ((m = e.text) == null ? void 0 : m.trim()) || "", s = e.fileIds;
408
408
  if (!d && /*!files.length &&*/
409
409
  !(s != null && s.length)) {
410
410
  const a = new Error(
@@ -453,10 +453,10 @@ class $ {
453
453
  referenceFirst: o
454
454
  };
455
455
  this.pushMessage(p), this.event.emit("question:content", d);
456
- const w = (a) => r(this, null, function* () {
456
+ const y = (a) => r(this, null, function* () {
457
457
  if (a.role !== L.Robot)
458
458
  return;
459
- switch (this.removeEventListener("answer:finish", w), this._id && a.content && a.index && a.index < 0 && (this.data = yield this.cvforceApi.patchSessionsId(this.applicationId, this._id, {
459
+ switch (this.removeEventListener("answer:finish", y), this._id && a.content && a.index && a.index < 0 && (this.data = yield this.cvforceApi.patchSessionsId(this.applicationId, this._id, {
460
460
  finialMessage: a.content
461
461
  }), this.event.emit("data:updated", this.data), this.event.emit("data:updated:finialMessage", {
462
462
  finialMessage: a.content
@@ -471,15 +471,15 @@ class $ {
471
471
  a.content = a.message || "未知错误", a.isLoading = !1, a.index = -1, this.event.emit("message:error", a);
472
472
  }
473
473
  this.getRelatedQuesion(a), a.isLoading = !1;
474
- let y = this.messages[this.messages.length - 1];
475
- if (y && y.role === L.Robot) {
476
- const v = f(f({}, y), a);
474
+ let w = this.messages[this.messages.length - 1];
475
+ if (w && w.role === L.Robot) {
476
+ const v = f(f({}, w), a);
477
477
  this.messages[this.messages.length - 1] = v, this.event.emit("message:updated", v);
478
478
  } else
479
479
  this.pushMessage(a);
480
480
  this.frozen = !1;
481
481
  });
482
- return this.addEventListener("answer:finish", w), this.sendQuestion(g, I(f({}, t), {
482
+ return this.addEventListener("answer:finish", y), this.sendQuestion(g, I(f({}, i), {
483
483
  stream: n,
484
484
  referenceFirst: o
485
485
  })), p;
@@ -491,10 +491,10 @@ class $ {
491
491
  if (!e.content || e.isSensitive || e.code !== 200 || !((o = this.application) != null && o.arrange[0].recommendQuestionOpen))
492
492
  return e;
493
493
  this.event.emit("message:relatedQuesion:loading", e);
494
- const t = yield this.cvforceApi.postGeneques({
494
+ const i = yield this.cvforceApi.postGeneques({
495
495
  content: e.content
496
496
  }).catch((d) => null);
497
- if (!t) {
497
+ if (!i) {
498
498
  const d = [], s = I(f({}, e), {
499
499
  relatedQuesion: d,
500
500
  index: -3,
@@ -504,42 +504,42 @@ class $ {
504
504
  relatedQuesion: d
505
505
  }), this.event.emit("message:updated", s), s;
506
506
  }
507
- const i = (l = t.content) == null ? void 0 : l.split("*").map(z).map(O).filter((d) => !!d);
508
- e.relatedQuesion = i, e.index = -3, e.isLoading = !1;
507
+ const t = (l = i.content) == null ? void 0 : l.split("*").map(O).map(C).filter((d) => !!d);
508
+ e.relatedQuesion = t, e.index = -3, e.isLoading = !1;
509
509
  const n = I(f({}, e), {
510
- relatedQuesion: i,
510
+ relatedQuesion: t,
511
511
  index: -3,
512
512
  isLoading: !1
513
513
  });
514
514
  return this.event.emit("message:relatedQuesion:loaded", n), this.event.emit("message:updated", n), this._id && this.cvforceApi.patchSessionsId(this._applicationId, this._id, {
515
- lastRelatedQuestion: i
515
+ lastRelatedQuestion: t
516
516
  }), n;
517
517
  });
518
518
  }
519
519
  fillMessageReference(e) {
520
520
  return r(this, null, function* () {
521
- const t = yield Promise.all(e.reference.map((i) => this.cvforceApi.getKnowledgeIdFileId(i.knowledgeId, i.docId)));
522
- return e.reference = e.reference.map((i, n) => f(f({}, i), t[n])), this.event.emit("message:updated", e), e;
521
+ const i = yield Promise.all(e.reference.map((t) => this.cvforceApi.getKnowledgeIdFileId(t.knowledgeId, t.docId)));
522
+ return e.reference = e.reference.map((t, n) => f(f({}, t), i[n])), this.event.emit("message:updated", e), e;
523
523
  });
524
524
  }
525
525
  answerAgain() {
526
526
  return r(this, arguments, function* (e = {
527
527
  stream: A.stream
528
528
  }) {
529
- const t = this.messages[this.messages.length - 1];
530
- if (!t)
529
+ const i = this.messages[this.messages.length - 1];
530
+ if (!i)
531
531
  throw Error("message list is empty");
532
532
  this.frozen = !0, this._stopAnswer = !1;
533
533
  const {
534
- stream: i = A.stream
534
+ stream: t = A.stream
535
535
  } = e;
536
536
  let n;
537
- t.role !== L.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));
537
+ i.role !== L.User && (n = e.oldMessageId || i.messageId, this.messages.splice(this.messages.length - 1, 1), this.event.emit("message:remove", i), this.event.emit("history:remove", i));
538
538
  const o = this.messages[this.messages.length - 1], l = {
539
539
  content: o.content,
540
540
  fileIds: o.fileIds,
541
541
  requestId: o.messageId,
542
- stream: i,
542
+ stream: t,
543
543
  oldMessageId: n
544
544
  }, d = (s) => r(this, null, function* () {
545
545
  if (s.role === L.Robot && s.index === -1) {
@@ -561,7 +561,7 @@ class $ {
561
561
  }
562
562
  });
563
563
  this.addEventListener("message:content", d), this.sendQuestion(l, I(f({}, e), {
564
- stream: i
564
+ stream: t
565
565
  }));
566
566
  });
567
567
  }
@@ -583,17 +583,17 @@ class $ {
583
583
  * @returns 返回当前会话实例
584
584
  */
585
585
  suspend() {
586
- var i;
586
+ var t;
587
587
  this.stopAnswer(), this.frozen = !1, this._stopAnswer = !0;
588
588
  let e = this.messages[this.messages.length - 1];
589
- const t = {
590
- messageId: k(),
589
+ const i = {
590
+ messageId: S(),
591
591
  // 生成唯一的消息 ID
592
592
  isLoading: !1,
593
593
  // 标记消息已停止加载
594
594
  index: -2,
595
595
  // 消息索引,用于标识特殊状态
596
- messageTime: N(/* @__PURE__ */ new Date()).format("YYYY-MM-DD HH:ss:mm"),
596
+ messageTime: B(/* @__PURE__ */ new Date()).format("YYYY-MM-DD HH:ss:mm"),
597
597
  // 消息时间
598
598
  content: "",
599
599
  // 消息内容
@@ -610,7 +610,7 @@ class $ {
610
610
  if (e.index === -2)
611
611
  return;
612
612
  if (e.actions) {
613
- const n = e.actions[((i = e.actions) == null ? void 0 : i.length) - 1];
613
+ const n = e.actions[((t = e.actions) == null ? void 0 : t.length) - 1];
614
614
  if (n) {
615
615
  const o = n[n.length - 1];
616
616
  if (o && (o.type === "BEFORE_CALL" || o.type === "FUNCTION_CALL")) {
@@ -636,9 +636,9 @@ class $ {
636
636
  }
637
637
  }
638
638
  }
639
- e = f(f({}, e), t), this.event.emit("message:content", e), this.event.emit("message:updated", e);
639
+ e = f(f({}, e), i), this.event.emit("message:content", e), this.event.emit("message:updated", e);
640
640
  } else
641
- this.pushMessage(t), this.event.emit("message:content", t);
641
+ this.pushMessage(i), this.event.emit("message:content", i);
642
642
  return this;
643
643
  }
644
644
  /**
@@ -650,9 +650,9 @@ class $ {
650
650
  return r(this, null, function* () {
651
651
  if (!this._applicationId || !this._id)
652
652
  throw Error("session is not avalible. id is undefined");
653
- return this.cvforceApi.postComments(this._applicationId, this._id, e).then((t) => {
654
- const i = this.messages.find((n) => n.messageId === e.messageId);
655
- return i && (i.comment = e, this.event.emit("message:comment", i)), t;
653
+ return this.cvforceApi.postComments(this._applicationId, this._id, e).then((i) => {
654
+ const t = this.messages.find((n) => n.messageId === e.messageId);
655
+ return t && (t.comment = e, this.event.emit("message:comment", t)), i;
656
656
  });
657
657
  });
658
658
  }
@@ -679,6 +679,6 @@ class $ {
679
679
  }
680
680
  }
681
681
  export {
682
- B as SessionErrors,
683
- $ as default
682
+ U as SessionErrors,
683
+ X as default
684
684
  };
package/dist/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var T=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var $=(o,e,t)=>e in o?se(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,u=(o,e)=>{for(var t in e||(e={}))B.call(e,t)&&$(o,t,e[t]);if(T)for(var t of T(e))F.call(e,t)&&$(o,t,e[t]);return o},w=(o,e)=>ie(o,ne(e));var j=(o,e)=>{var t={};for(var s in o)B.call(o,s)&&e.indexOf(s)<0&&(t[s]=o[s]);if(o!=null&&T)for(var s of T(o))e.indexOf(s)<0&&F.call(o,s)&&(t[s]=o[s]);return t};var m=(o,e,t)=>($(o,typeof e!="symbol"?e+"":e,t),t);var g=(o,e,t)=>new Promise((s,a)=>{var r=i=>{try{c(t.next(i))}catch(d){a(d)}},n=i=>{try{c(t.throw(i))}catch(d){a(d)}},c=i=>i.done?s(i.value):Promise.resolve(i.value).then(r,n);c((t=t.apply(o,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),re=require("axios"),I=require("@glodon-aiot/apis"),oe=require("socket.io-client"),J=require("uuid"),K=require("dayjs"),R=class R{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!R.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!R.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!R.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!R.debug||console.warn(this.prefix,...e)}};m(R,"debug",!1);let M=R;const ce=new M("[Config] ");var G=(o=>(o.dev="https://aiot-dev.glodon.com/api/cvforcepd",o.test="https://aiot-dev.glodon.com/api/cvforce",o.prod="https://copilot.glodon.com/api/cvforce",o.local="http://localhost:3000/api/cvforcepd",o))(G||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function z(o){M.debug=(o==null?void 0:o.debug)||!1,exports.configuration=w(u(u({},exports.configuration),o),{apiRoot:(o==null?void 0:o.apiRoot)||exports.configuration.apiRoot||(o!=null&&o.env?G[o.env||"prod"]:exports.configuration.apiRoot)}),M.debug&&ce.log("updated",exports.configuration)}const P=o=>JSON.parse(ae.decode(o.split(".")[1])),de=o=>{const e=P(o).exp;return new Date().valueOf()/1e3>=e},he=o=>o==null?void 0:o.replace(/[\r\n]+/gm,""),le=o=>o.replace(/\\|\\/g,"");function X(o,e,t){const s=d=>{var l;return e&&(de(e)&&t(403,"aiotToken is timeout"),d.headers=(l=d.headers)!=null?l:{},d.headers=w(u({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function a(d,l=!0){const h=`${o}${d}`,p=re.create({baseURL:h});return l&&p.interceptors.request.use(s),p}const r=(d,l)=>{d===401&&t(d,"aiotToken is invalid")},n=(d,l)=>{d!==10001&&d!==10215&&t(d,l)},c=a("/data/v1");return new I.CVForceApi(c,{onHttpStatusError:r,onAppStatusError:n})}var L=(o=>(o[o.Normal=0]="Normal",o[o.Debug=1]="Debug",o))(L||{});const A=new M("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&A.disable()}getEventListenerMap(){return u({},this.eventListenerMap)}on(e,t,s=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),s?this.eventListenerMap[e].push({fn:t,once:!0}):this.eventListenerMap[e].push(t),A.log(`add event ${e} listener ${s?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const s=this.eventListenerMap[e].findIndex(a=>{if(typeof a=="function"&&t===a)return!0;if(a=a,a.fn===t)return!0});s<0?A.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),A.log(`remove event ${e} listener`))}else A.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){A.log(`event ${e} listeners is empty`);return}const s=[];for(let a=0;a<this.eventListenerMap[e].length;a++){const r=this.eventListenerMap[e][a];typeof r=="function"?r(t):s.push(r)}s.forEach(a=>{a&&(a.fn(t),this.off(e,a.fn))}),A.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const S=new M("[Session] ");var C=(o=>(o.DataRequestFailed="data request error",o.SocketConnectionFailed="socket error",o.IdUndefined="session id is not defined",o.SendingEmptyContent="failed at sending empty content",o.Frozen="session is frozen",o.UserModeError="failed at setting socket user mode",o.Inactive="session is inactive",o))(C||{});class q{constructor(e,t="",s,a,r,n){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new Z);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);m(this,"_mcpServers",null);this.token=e,this.lazyload=a,this.client=n||null,this._applicationId=P(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),r&&(this._application=r),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var c;if(t)this._id=t,this.event.emit("data:loading"),s?(this.data=s,a||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(i=>g(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>g(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data)})))):(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(i=>g(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>g(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoading=!1,this._dataLoaded=!0})));else{const i=(s==null?void 0:s.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:i}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:i,netOpen:s==null?void 0:s.netOpen,knowledgeIdList:(c=s==null?void 0:s.knowledges)==null?void 0:c.map(d=>d.id),applicationId:this._applicationId}).then(d=>g(this,null,function*(){var l;this._id=d.id,this.data=w(u({},d),{knowledges:s==null?void 0:s.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),yield(()=>g(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(p=>{var v,y;const f=((y=(v=s.promptVariables)==null?void 0:v.find(_=>_.key===p.key))==null?void 0:y.value)||"";return w(u({},p),{value:f})}).sort((p,f)=>p.key.localeCompare(f.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)!==I.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}fetchData(){return g(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=>g(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 g(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(t=>t.status===I.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>e.key!=="query")}setPromptVariables(e){return g(this,null,function*(){const t=this._promptVariables.map(s=>{var r;const a=((r=e==null?void 0:e.find(n=>n.key===s.key))==null?void 0:r.value)||s.value;return w(u({},s),{value:a})}).sort((s,a)=>s.key.localeCompare(a.key));if(yield Promise.all(t.filter(s=>s.key!=="query").map(s=>{if(!this.data)throw Error("session data is not loaded");if(!(!s.id||!s.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,s.id,{value:s.value}).catch(console.error)})),!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return g(this,null,function*(){var t,s,a;if(S.log("setNetOpen:",e),S.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===I.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((a=this._application)==null?void 0:a.arrange[0].enableNetOpen)===!1){console.warn("This Application is disabled to change netOpen.");return}if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{netOpen:e?1:2}),this.data.netOpen=e,S.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return X(exports.configuration.apiRoot,this.token,(e,t)=>{const s=new Error("data request error");S.error(s),this.event.emit("error",s)})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}fetchMessages(){return g(this,arguments,function*(e={}){var s,a;const t={pageSize:this._loadingMessagesSize};if(this._id){e=u(u({},t),e),this.event.emit("history:loading"),S.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),S.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),n=r.map((i,d)=>{var p,f;let l=[],h;return typeof((p=i.agentHistoryList)==null?void 0:p.agentList)=="string"&&(l=JSON.parse(i.agentHistoryList.agentList).reduce((y,_)=>(y[_.data.step-1]||(y[_.data.step-1]=[]),y[_.data.step-1].push(_),y),[])),d===r.length-1&&(h=(f=this.data)==null?void 0:f.lastRelatedQuestion),w(u({},i),{actions:l,relatedQuesion:h})});if(!e.endTime&&!e.startTime){const i=this.messages[this.messages.length-1];i&&!i.relatedQuesion&&(i.relatedQuesion=(s=this.data)==null?void 0:s.lastRelatedQuestion),this.messages=[...n,...this.messages]}else if(e.endTime&&!e.startTime){const i=this.messages.findIndex(d=>d.ts===e.endTime);this.messages.splice(0,i+1),this.messages=[...n,...this.messages]}else if(!e.endTime&&e.startTime){const i=this.messages.findLastIndex(d=>d.ts===e.endTime);this.messages.splice(i,this.messages.length-i-1),this.messages=[...this.messages,...n]}else{const i=this.messages.findIndex(l=>l.ts===e.endTime),d=this.messages.findLastIndex(l=>l.ts===e.endTime);this.messages.splice(i,d-i+1,...n)}const c=this.messages[this.messages.length-1];return c&&!c.relatedQuesion&&(c.relatedQuesion=(a=this.data)==null?void 0:a.lastRelatedQuestion),this.event.emit("history:moreloaded",n),S.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,n}else{const r=new Error("session id is not defined");return S.error(r),this.event.emit("error",r),!1}})}rename(e){return g(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),S.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return g(this,null,function*(){this.messages.push(e),S.log("history:add",e),this.event.emit("history:add",e),this.event.emit("message:new",e),this.event.emit("message:updated",e)})}reloadSessionInfo(){if(!this._id)throw Error("session is not created yet");return this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,this._id).then(e=>g(this,null,function*(){if(this.data=e,!this._id)throw Error("session is not created yet");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),S.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>g(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 g(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return g(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return S.error(e),this.event.emit("error",e),!1}return this.event.emit("data:deleting"),yield this.cvforceApi.delSessionsId(this.applicationId,this.id),this.event.emit("data:deleted"),this.destroy()})}activate(){return g(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=>g(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 g(this,arguments,function*(e,t={stream:exports.configuration.stream}){var p;try{this.validateConfigs()}catch(f){console.error(f)}const{stream:a=exports.configuration.stream,referenceFirst:r=!1}=t,n=e.uuid||J.v4(),c=((p=e.text)==null?void 0:p.trim())||"",i=e.fileIds;if(!c&&!(i!=null&&i.length)){const f=new Error("failed at sending empty content");return S.error(f),this.event.emit("error",f),!1}if(!this._id){const f=new Error("session id is not defined");return S.error(f),this.event.emit("error",f),!1}if(this.frozen){const f=new Error("session is frozen");return S.error(f),this.event.emit("error",f),!1}this.frozen=!0,this._stopAnswer=!1;const d={sessionId:this.id,role:2,content:c,messageId:n,reference:[],searchReference:[],messageTime:""},l={content:c,stream:a,requestId:n,fileIds:i,referenceFirst:r};this.pushMessage(d),this.event.emit("question:content",c);const h=f=>g(this,null,function*(){if(f.role!==I.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",h),this._id&&f.content&&f.index&&f.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:f.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:f.content})),yield this.fillMessageReference(f),f.code){case 11915:f.content="请您换个问题问我吧~",f.index=-1,f.isSensitive=!0,f.isLoading=!1,f.sessionId=this._id||"",this.event.emit("message:error",f);break;case 200:f.index=-1,f.isLoading=!1;break;default:f.content=f.message||"未知错误",f.isLoading=!1,f.index=-1,this.event.emit("message:error",f)}this.getRelatedQuesion(f),f.isLoading=!1;let v=this.messages[this.messages.length-1];if(v&&v.role===I.ChatMessageRole.Robot){const y=u(u({},v),f);this.messages[this.messages.length-1]=y,this.event.emit("message:updated",y)}else this.pushMessage(f);this.frozen=!1});return this.addEventListener("answer:finish",h),this.sendQuestion(l,w(u({},t),{stream:a,referenceFirst:r})),d})}getRelatedQuesion(e){return g(this,null,function*(){var r,n;if(!e.content||e.isSensitive||e.code!==200||!((r=this.application)!=null&&r.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const t=yield this.cvforceApi.postGeneques({content:e.content}).catch(c=>null);if(!t){const c=[],i=w(u({},e),{relatedQuesion:c,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:c}),this.event.emit("message:updated",i),i}const s=(n=t.content)==null?void 0:n.split("*").map(he).map(le).filter(c=>!!c);e.relatedQuesion=s,e.index=-3,e.isLoading=!1;const a=w(u({},e),{relatedQuesion:s,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",a),this.event.emit("message:updated",a),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:s}),a})}fillMessageReference(e){return g(this,null,function*(){const t=yield Promise.all(e.reference.map(s=>this.cvforceApi.getKnowledgeIdFileId(s.knowledgeId,s.docId)));return e.reference=e.reference.map((s,a)=>u(u({},s),t[a])),this.event.emit("message:updated",e),e})}answerAgain(){return g(this,arguments,function*(e={stream:exports.configuration.stream}){const t=this.messages[this.messages.length-1];if(!t)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1;const{stream:s=exports.configuration.stream}=e;let a;t.role!==I.ChatMessageRole.User&&(a=e.oldMessageId||t.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",t),this.event.emit("history:remove",t));const r=this.messages[this.messages.length-1],n={content:r.content,fileIds:r.fileIds,requestId:r.messageId,stream:s,oldMessageId:a},c=i=>g(this,null,function*(){if(i.role===I.ChatMessageRole.Robot&&i.index===-1){switch(this._id&&i.content&&i.index&&i.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:i.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:i.content})),yield this.fillMessageReference(i),i.code){case 11915:i.content="请您换个问题问我吧~",i.index=-1,i.isSensitive=!0,i.isLoading=!1,i.sessionId=this._id||"",this.event.emit("message:error",i);break;case 200:i.index=-1,i.isLoading=!1;break;default:i.content=i.message||"未知错误",i.isLoading=!1,i.index=-1,this.event.emit("message:error",i)}this.getRelatedQuesion(i),this.removeEventListener("message:content",c),this.frozen=!1}});this.addEventListener("message:content",c),this.sendQuestion(n,w(u({},e),{stream:s}))})}setTop(e){return g(this,null,function*(){if(!this._id)throw Error("session is not avalible. id is undefined");this.data=yield this.cvforceApi.patchSessionsId(this._applicationId,this._id,{top:e}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:top",{top:e})})}suspend(){var s;this.stopAnswer(),this.frozen=!1,this._stopAnswer=!0;let e=this.messages[this.messages.length-1];const t={messageId:J.v4(),isLoading:!1,index:-2,messageTime:K(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:I.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const a=e.actions[((s=e.actions)==null?void 0:s.length)-1];if(a){const r=a[a.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:n,pluginCode:c,funcCode:i,funcName:d}=r.data;a.push({data:{pluginName:n,pluginCode:c,funcCode:i,funcName:d,step:r.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:a})}}}e=u(u({},e),t),this.event.emit("message:content",e),this.event.emit("message:updated",e)}else this.pushMessage(t),this.event.emit("message:content",t);return this}postMessageComment(e){return g(this,null,function*(){if(!this._applicationId||!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.postComments(this._applicationId,this._id,e).then(t=>{const s=this.messages.find(a=>a.messageId===e.messageId);return s&&(s.comment=e,this.event.emit("message:comment",s)),t})})}clear(){if(!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.patchApplicationIdSessionsIdContext(this._applicationId,this._id).then(()=>(this.event.emit("context:clear"),!0))}destroy(){var e;return this._ready=!1,this.event.removeAllListeners(),(e=this.socket)==null||e.disconnect(),this.socket=null,this.event.emit("destroy",{applicationId:this._applicationId,sessionId:this._id}),this._id||""}}const k=new M("[AgentSession] ");class fe extends q{constructor(e,t="",s,a,r,n){super(e,t,s,a,r,n)}prepareConnection(){return new Promise(e=>g(this,null,function*(){this.socket&&e(!0);const t={version:"1.0",stream:JSON.stringify(exports.configuration.stream===void 0?!0:exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?L.Debug:L.Normal},s=new URL(exports.configuration.apiRoot),a=yield oe.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});a.on("connect",()=>{k.log("socket:connect"),this.event.emit("socket:connect"),a.emit("init")}),a.on("disconnect",()=>{k.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),a.on("ready",r=>{if(r.code===200){k.log("ready");const n=exports.configuration.debug?L.Debug:L.Normal;n===L.Debug&&r.userMode,this._ready=!0,this.event.emit("ready"),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const n=new Error(C.SocketConnectionFailed);k.error("error",n),this.event.emit("error",n),e(!1)}}),a.on("action",(r,n)=>g(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:c,data:{runnerIsClient:i,pluginCode:d,funcCode:l,parameters:h,requestBody:p}}=r,f=this.messages[this.messages.length-1];if(!f.messageId)f.actions||(f.actions=[]),f.actions[r.data.step-1]||(f.actions[r.data.step-1]=[]),f.actions[r.data.step-1].push(r),this.event.emit("message:action",{messageId:f.messageId,action:r}),this.event.emit("message:updated",f);else{const v={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[r]],comment:{isAgree:0}};this.pushMessage(v),this.event.emit("message:action",{messageId:v.messageId,action:r})}if(this.inactivating){const v=new Error(C.Inactive);k.warn("error",v),this.event.emit("error",v)}else if(c==="FUNCTION_CALL"&&i){if(k.log(`calling function ${l} of plugin ${d} with argument:
2
- ${JSON.stringify(h)}`),!exports.configuration.plugins[d]){n({code:404,message:"对不起,没有找到插件。"});return}const v=exports.configuration.plugins[d][l];typeof v!="function"&&n({code:404,message:"对不起,没有找到插件方法。"});let y=h==null?void 0:h.query;try{y=JSON.parse(h==null?void 0:h.query)}catch(_){}v(y,(..._)=>{this._stopAnswer||n(..._)})}})),a.on("answer",r=>{if(!this._stopAnswer)if(r.data.code!==200&&(r.data.index=-1,this.event.emit("error",r.data)),r.data.index===-1){let n=this.messages[this.messages.length-1];if(n&&!n.messageId)n=u(u({},n),r.data),this.event.emit("message:content",n),this.event.emit("message:updated",n),this.event.emit("answer:finish",n);else{const c=u({messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0}},r.data);this.event.emit("message:content",c),this.pushMessage(c),this.event.emit("answer:finish",c)}}else{let n=this.messages[this.messages.length-1];n&&!n.messageId?(n=u(u({},n),r.data),this.messages[this.messages.length-1]=n,this.event.emit("message:content",n),this.event.emit("message:updated",n)):(this.pushMessage(r.data),this.event.emit("message:content",r.data))}}),a.on("reference",r=>g(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const h=new Error(C.IdUndefined);k.error(h),this.event.emit("error",h),this.frozen=!1;return}const{type:n,data:c,requestId:i}=r,d=this.messages.findIndex(h=>h.messageId===i&&h.role===I.ChatMessageRole.User);if(d<0)return;const l=d+1;if(l>=this.messages.length){const h={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0}};this.pushMessage(h)}n==="KG"?(this.messages[l]=w(u({},this.messages[l]),{reference:c.knowledgeReference}),yield this.fillMessageReference(this.messages[l]),this.event.emit("message:reference",c.knowledgeReference),this.event.emit("message:updated",this.messages[l])):n==="WEB_SEARCH"&&(this.messages[l]=w(u({},this.messages[l]),{searchReference:c.knowledgeReference}),this.event.emit("message:searchreference",c.searchReference),this.event.emit("message:updated",this.messages[l]))})),this.socket=a,a.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((e,t)=>{if(!this.socket){t("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,s=>{s.code===200?(Object.keys(s.data).forEach(a=>{s.data[a].code!==200&&console.error(a,"MCP Server 注册失败。",s.data[a])}),e(!0)):(console.error("MCP Server 注册失败。",s),t(s))})}):Promise.resolve(!0)}addMcpServers(e){return g(this,null,function*(){return this.ready?this.socket?new Promise((t,s)=>{this.socket&&this.socket.emit("add_mcp_servers",e,a=>{a.code===200?(Object.keys(a.data).forEach(r=>{a.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",a.data[r])}),t(!0)):(console.error("MCP Server 注册失败。",a),s(a))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return g(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 g(this,null,function*(){var a,r,n;let s=w(u({},e),{promptVariables:this.promptVariables.reduce((c,i)=>w(u({},c),{[i.key]:i.value}),{}),knowledges:(a=this.knowledges)==null?void 0:a.map(c=>c.id)});if(!this.active){if(yield this.activate(),!this.socket){const c=new Error(C.SocketConnectionFailed);return k.warn("error",c),this.event.emit("error",c),!1}(r=this.socket)==null||r.emit("question",s);return}(n=this.socket)==null||n.emit("question",s)})}stopAnswer(){var e;(e=this.socket)==null||e.emit("stop_answer")}}function ge(o,e){return g(this,null,function*(){const t=o.getReader();let s;for(;!(s=yield t.read()).done;)e(s.value)})}function pe(o){let e,t,s,a=!1,r;return function(c){e===void 0?(e=c,t=0,s=-1,r=!1):e=me(e,c);const i=e.length;let d=0;for(;t<i;){a&&(e[t]===10&&(d=++t),a=!1);let l=-1;for(;t<i&&l===-1;++t)switch(e[t]){case 58:s===-1&&(s=t-d);break;case 13:a=!1,t+4<i&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(r=!0);case 10:l=t;break}if(l===-1)break;o(e.subarray(d,l),s,r),d=t,s=-1,r=!1}d===i?e=void 0:d!==0&&(e=e.subarray(d),t-=d)}}function ue(o,e,t){let s=H();const a=new TextDecoder;return function(n,c,i){if(n.length===0)t==null||t(s),s=H();else if(c>0){const d=a.decode(n.subarray(0,c)),l=c+(n[c+1]===32?2:1);let h=a.decode(n.subarray(l));switch(i&&(h+=`
3
- `),d){case"data":s.data=s.data?s.data+`
4
- `+h:h;break;case"event":s.event=h;break;case"id":o(s.id=h);break;case"retry":const p=parseInt(h,10);isNaN(p)||e(s.retry=p);break}}}}function me(o,e){const t=new Uint8Array(o.length+e.length);return t.set(o),t.set(e,o.length),t}function H(){return{data:"",event:"",id:"",retry:void 0}}const N="text/event-stream",ve=1e3,Y="last-event-id";function W(o,l){var h=l,{signal:e,headers:t,onopen:s,onmessage:a,onclose:r,onerror:n,openWhenHidden:c,fetch:i}=h,d=j(h,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((p,f)=>{const v=u({},t);v.accept||(v.accept=N);let y;function _(){y.abort(),document.hidden||Q()}c||document.addEventListener("visibilitychange",_);let E=ve,V=0;function O(){document.removeEventListener("visibilitychange",_),window.clearTimeout(V),y.abort()}e==null||e.addEventListener("abort",()=>{O(),p()});const ee=i!=null?i:window.fetch,te=s!=null?s:ye;function Q(){return g(this,null,function*(){var D;y=new AbortController;try{const x=yield ee(o,w(u({},d),{headers:v,signal:y.signal}));yield te(x),yield ge(x.body,pe(ue(b=>{b?v[Y]=b:delete v[Y]},b=>{E=b},a))),r==null||r(),O(),p()}catch(x){if(!y.signal.aborted)try{const b=(D=n==null?void 0:n(x))!=null?D:E;window.clearTimeout(V),V=window.setTimeout(Q,b)}catch(b){O(),f(b)}}})}Q()})}function ye(o){const e=o.headers.get("content-type");if(!(e!=null&&e.startsWith(N)))throw new Error(`Expected content-type to be ${N}, Actual: ${e}`)}const U=new M("[DialogSession] ");class we extends q{constructor(t,s="",a,r,n,c){super(t,s,a,r,n,c);m(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>g(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,s,a,r,n,c){return g(this,null,function*(){const i={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=w(u({},a),{stream: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&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(l){if(!l.data.includes('{"code": ')){let p={};try{p=JSON.parse(l.data)}catch(v){}(p==null?void 0:p.mtype)==="search"?i.searchReference.push(p):i.content=i.content+l.data;const f={content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:s,messageTime:K(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(n==null?void 0:n.onmessage)&&n.onmessage(f)}const h=JSON.parse(l.data);if(i.reference=h.data.reference,i.searchReference=h.data.searchReference,i.messageTime=h.data.messageTime,i.messageId=h.data.messageId,i.llmModel=h.data.llmModel,i.content=h.data.content,i.code=h.code,h.code===200){const p={code:i.code,content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:s,messageTime:i.messageTime,isReplying:!0};n!=null&&n.onmessage&&n.onmessage(p)}else return n!=null&&n.onclose&&n.onclose(i),c&&c({code:i.code,message:i.message})},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const l={code:i.code,content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:s,messageTime:i.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};n!=null&&n.onclose&&n.onclose(l)}})})}postChatV3EventSource(t,s,a,r,n,c){return g(this,null,function*(){const i={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},d=w(u({},a),{stream: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(d),openWhenHidden:!0,signal:r,onopen(l){return l.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(l){if(!l.data&&!l.event&&!l.id&&!l.retry)return;let h={};try{h=JSON.parse(l.data)}catch(y){console.error("parse eventData to JSON failed. ",l.data)}if(h.code!==200)return i.index=-1,i.code=h.code,i.message=h.message,n!=null&&n.onmessage&&n.onmessage(i),c&&c({code:h.code,message:h.message});const p=h.data.type,f=h.data.payload;i.isReplying=!0;const v=()=>{if(!i.searchingStatus){i.searchingStatus="start";return}if(i.searchingStatus==="start"){i.searchingStatus="end";return}};if(p==="beforeSearch"&&v(),p==="searchOver"&&v(),p==="search"&&i.searchReference.push(f),p==="thinking"){i.thinkingStatus="start";const _=f.choices[0];i.reasoningContent=i.reasoningContent+_.delta.reasoningContent}if(p==="thinkingOver"){i.thinkingStatus="end";const y=f.thinkingSecs;i.thinkingSecs=y}if(p==="text"){const _=f.choices[0];i.content=i.content+_.delta.content}if(p==="reference"&&(i.reference=f),p==="result"){const y=f.messageId,_=f.llmModel,E=f.messageTime;i.messageId=y,i.llmModel=_,i.messageTime=E,i.sessionId=s}p==="over"?i.index=-1:(i.code=h.code,i.message=h.message),n!=null&&n.onmessage&&n.onmessage(i)},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const l=w(u({},i),{isReplying:!1});n!=null&&n.onclose&&n.onclose(l)}})})}sendQuestion(t,s){return g(this,null,function*(){var d;const{content:a,fileIds:r,oldMessageId:n}=t,{stream:c,referenceFirst:i}=s;if(this.active||(yield this.activate()),this._id){let l={content:a,fileIds:r,referenceFirst:i,oldMessageId:n,promptVariables:this.promptVariables.reduce((h,p)=>w(u({},h),{[p.key]:p.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:()=>{U.log("open",this.ctrl)},onmessage:h=>{if(this._stopAnswer)return;let p=this.messages[this.messages.length-1];p&&p.role===I.ChatMessageRole.Robot?(p=u(u({},p),h),this.messages[this.messages.length-1]=p,this.event.emit("message:content",p),this.event.emit("message:updated",p)):(this.pushMessage(h),this.event.emit("message:content",h))},onclose:h=>g(this,null,function*(){this._stopAnswer||(U.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 g(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return g(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return g(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}}const Ie=new M("[BotClient] ");class _e{constructor(e,t,s=!0){m(this,"event",new Z);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=s,z(t),this._applicationId=P(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(a=>{z(w(u({},t),{stream:t.stream===void 0?(a==null?void 0:a.type)===I.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 g(this,null,function*(){var t,s,a;this._application=yield this.cvforceApi.getApplicationId(this._applicationId).then(r=>(typeof r.arrange[0].recommendQuestionOpen!="boolean"&&(r.arrange[0].recommendQuestionOpen=!0),w(u({},r),{arrange:[w(u({},r.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&r.arrange[0].recommendQuestionOpen})]})));const e=(a=(s=(t=this._application)==null?void 0:t.arrange)==null?void 0:s[0])==null?void 0:a.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(r=>r.maxModelLength)),this._promptVariables=yield this.cvforceApi.getPrompts(this._applicationId),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:X(exports.configuration.apiRoot,this.token,(e,t)=>Ie.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=P(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,s,a,r){return g(this,null,function*(){const n=this;return new Promise((c,i)=>{const d=l=>g(this,null,function*(){if(l===I.ApplicationTypes.Agent)c(new fe(e,t,s,a,r,n));else if(l===I.ApplicationTypes.Dialog)c(new we(e,t,s,a,r,n));else throw Error(`不支持的应用类型:${l}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return g(this,null,function*(){return new Promise((t,s)=>{const a=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>{const n=[];return r.forEach(c=>g(this,null,function*(){const i=this._sessions.find(d=>c.id===d.id);if(i)i.data=c,this._application?i.application=this._application:i.loadApplicationInfo(),n.push(i);else{const d=yield this.createSession(this.token,c.id,c,this.lazyload,this._application||void 0);n.push(d)}})),this.sessions=n,n});if(this.ready){if(!this._application)throw Error("_application is null");t(a())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(a())},!0)})})}loadSession(e="",t){return g(this,null,function*(){this.checkReady();let s=this.sessions.find(a=>a.id===e);if(s||(s=yield this.createSession(this.token,e,t),this._sessions.push(s)),this._activeSession){if(this._activeSession===s)return s;this._activeSession.inactivate()}return s.id?(yield s.activate(),this._activeSession=s):s.addEventListener("data:loaded",()=>{this._activeSession!==s&&(s==null||s.activate(),this._activeSession=s)},!0),s})}reload(){return this.loadApplication().then(()=>g(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return g(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 g(this,null,function*(){let a=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!a){console.warn("setTop session failed.");return}return yield a.setTop(t),this.getSessions({order:s})})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return g(this,null,function*(){this.checkReady();let s=-1;if(typeof e=="string"?s=this._sessions.findIndex(a=>a.id===e):s=this._sessions.findIndex(a=>a.id===e.id),s>-1){const a=this._sessions[s];t&&(yield a.delete()),this._sessions.splice(s,1)}else console.warn("session delete failed, session is not exist.")})}clean(){this._sessions.forEach(e=>e.destroy()),this.sessions=[]}}class Se{constructor(e,t={},s){m(this,"code");m(this,"description","");m(this,"loaded",!1);m(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}exports.AgentPlugin=Se;exports.BotClient=_e;exports.Session=q;exports.configure=z;
1
+ "use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var T=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var $=(o,e,s)=>e in o?se(o,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):o[e]=s,u=(o,e)=>{for(var s in e||(e={}))B.call(e,s)&&$(o,s,e[s]);if(T)for(var s of T(e))F.call(e,s)&&$(o,s,e[s]);return o},w=(o,e)=>ie(o,ne(e));var j=(o,e)=>{var s={};for(var t in o)B.call(o,t)&&e.indexOf(t)<0&&(s[t]=o[t]);if(o!=null&&T)for(var t of T(o))e.indexOf(t)<0&&F.call(o,t)&&(s[t]=o[t]);return s};var m=(o,e,s)=>($(o,typeof e!="symbol"?e+"":e,s),s);var p=(o,e,s)=>new Promise((t,a)=>{var r=i=>{try{c(s.next(i))}catch(d){a(d)}},n=i=>{try{c(s.throw(i))}catch(d){a(d)}},c=i=>i.done?t(i.value):Promise.resolve(i.value).then(r,n);c((s=s.apply(o,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),re=require("axios"),I=require("@glodon-aiot/apis"),oe=require("socket.io-client"),J=require("uuid"),K=require("dayjs"),R=class R{constructor(e,s=!1){this.prefix=e,this.open=s}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!R.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!R.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!R.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!R.debug||console.warn(this.prefix,...e)}};m(R,"debug",!1);let b=R;const ce=new b("[Config] ");var G=(o=>(o.dev="https://aiot-dev.glodon.com/api/cvforcepd",o.test="https://aiot-dev.glodon.com/api/cvforce",o.prod="https://copilot.glodon.com/api/cvforce",o.local="http://localhost:3000/api/cvforcepd",o))(G||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function z(o){b.debug=(o==null?void 0:o.debug)||!1,exports.configuration=w(u(u({},exports.configuration),o),{apiRoot:(o==null?void 0:o.apiRoot)||exports.configuration.apiRoot||(o!=null&&o.env?G[o.env||"prod"]:exports.configuration.apiRoot)}),b.debug&&ce.log("updated",exports.configuration)}const P=o=>JSON.parse(ae.decode(o.split(".")[1])),de=o=>{const e=P(o).exp;return new Date().valueOf()/1e3>=e},he=o=>o==null?void 0:o.replace(/[\r\n]+/gm,""),le=o=>o.replace(/\\|\\/g,"");function X(o,e,s){const t=d=>{var l;return e&&(de(e)&&s(403,"aiotToken is timeout"),d.headers=(l=d.headers)!=null?l:{},d.headers=w(u({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function a(d,l=!0){const h=`${o}${d}`,g=re.create({baseURL:h});return l&&g.interceptors.request.use(t),g}const r=(d,l)=>{d===401&&s(d,"aiotToken is invalid")},n=(d,l)=>{d!==10001&&d!==10215&&s(d,l)},c=a("/data/v1");return new I.CVForceApi(c,{onHttpStatusError:r,onAppStatusError:n})}var L=(o=>(o[o.Normal=0]="Normal",o[o.Debug=1]="Debug",o))(L||{});const A=new b("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&A.disable()}getEventListenerMap(){return u({},this.eventListenerMap)}on(e,s,t=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),t?this.eventListenerMap[e].push({fn:s,once:!0}):this.eventListenerMap[e].push(s),A.log(`add event ${e} listener ${t?", call once":""}`)}once(e,s){this.on(e,s,!0)}off(e,s){if(this.eventListenerMap[e]){const t=this.eventListenerMap[e].findIndex(a=>{if(typeof a=="function"&&s===a)return!0;if(a=a,a.fn===s)return!0});t<0?A.log(`event ${e} listener ${s.name} is not found`):(this.eventListenerMap[e].splice(t,1),A.log(`remove event ${e} listener`))}else A.log(`event ${e} listeners is empty`)}emit(e,s){if(!this.eventListenerMap[e]){A.log(`event ${e} listeners is empty`);return}const t=[];for(let a=0;a<this.eventListenerMap[e].length;a++){const r=this.eventListenerMap[e][a];typeof r=="function"?r(s):t.push(r)}t.forEach(a=>{a&&(a.fn(s),this.off(e,a.fn))}),A.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const S=new b("[Session] ");var C=(o=>(o.DataRequestFailed="data request error",o.SocketConnectionFailed="socket error",o.IdUndefined="session id is not defined",o.SendingEmptyContent="failed at sending empty content",o.Frozen="session is frozen",o.UserModeError="failed at setting socket user mode",o.Inactive="session is inactive",o))(C||{});class q{constructor(e,s="",t,a,r,n){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new Z);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);m(this,"_mcpServers",null);this.token=e,this.lazyload=a,this.client=n||null,this._applicationId=P(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),r&&(this._application=r),this.event.emit("init",{applicationId:this._applicationId,sessionId:s}),this.loadApplicationInfo().then(()=>{var c;if(s)this._id=s,this.event.emit("data:loading"),t?(this.data=t,a||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,s).then(i=>p(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,s)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data)})))):(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,s).then(i=>p(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,s)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoading=!1,this._dataLoaded=!0})));else{const i=(t==null?void 0:t.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:i}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:i,netOpen:t==null?void 0:t.netOpen,knowledgeIdList:(c=t==null?void 0:t.knowledges)==null?void 0:c.map(d=>d.id),applicationId:this._applicationId}).then(d=>p(this,null,function*(){var l;this._id=d.id,this.data=w(u({},d),{knowledges:t==null?void 0:t.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),yield(()=>p(this,null,function*(){if(t!=null&&t.knowledges)return this.setKnowledges((t==null?void 0:t.knowledges)||void 0)}))(),yield(()=>{if(t!=null&&t.promptVariables){const h=this._promptVariables.map(g=>{var v,y;const f=((y=(v=t.promptVariables)==null?void 0:v.find(_=>_.key===g.key))==null?void 0:y.value)||"";return w(u({},g),{value:f})}).sort((g,f)=>g.key.localeCompare(f.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)!==I.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}fetchData(){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.getSession(this.applicationId,this.data.id).then(e=>p(this,null,function*(){return this.data=e,this.event.emit("data:updated",this.data),e}))})}get id(){var e;return this._id||((e=this.data)==null?void 0:e.id)||""}get applicationId(){return this._applicationId}get application(){return this._application}set application(e){this._application=e}loadApplicationInfo(){if(this._application)return Promise.resolve(this._application);if(this._applicationId&&!this._application)return this.event.emit("application:data:loading"),this.cvforceApi.getApplicationId(this._applicationId).then(e=>(this._application=e,this.event.emit("application:data:loaded",e),e));throw Error("application id is not defined")}get ready(){return this._ready}get frozen(){return this._frozen}set frozen(e){e===!1&&this.inactivating&&this.socket&&(this.socket.disconnect(),this.socket=null,this.event.emit("inactivated")),this._frozen=e,this.event.emit("frozen",e)}get knowledges(){if(!this.data)throw Error("session data is not loaded");return this.data.knowledges||void 0}setKnowledges(e){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(s=>s.status===I.PromptStatus.Quoted).filter(s=>!s.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(s=>s.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>!(e.type===I.PromptVariableType.User&&e.key==="query")&&!(e.type===I.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return p(this,null,function*(){const s=this._promptVariables.map(t=>{var r;const a=((r=e==null?void 0:e.find(n=>n.key===t.key))==null?void 0:r.value)||t.value;return w(u({},t),{value:a})}).sort((t,a)=>t.key.localeCompare(a.key));if(yield Promise.all(s.filter(t=>!(t.type===I.PromptVariableType.User&&t.key==="query")&&!(t.type===I.PromptVariableType.System&&t.key==="datetime")).map(t=>{if(!this.data)throw Error("session data is not loaded");if(!(!t.id||!t.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,t.id,{value:t.value}).catch(console.error)})),!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return p(this,null,function*(){var s,t,a;if(S.log("setNetOpen:",e),S.log("application arrange setting value: ",(s=this._application)==null?void 0:s.arrange[0].enableNetOpen),((t=this._application)==null?void 0:t.type)===I.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((a=this._application)==null?void 0:a.arrange[0].enableNetOpen)===!1){console.warn("This Application is disabled to change netOpen.");return}if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{netOpen:e?1:2}),this.data.netOpen=e,S.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return X(exports.configuration.apiRoot,this.token,(e,s)=>{const t=new Error("data request error");S.error(t),this.event.emit("error",t)})}addEventListener(e,s,t=!1){if(typeof s!="function")throw Error("event listener is not a function");if(t){this.event.once(e,s);return}this.event.on(e,s)}removeEventListener(e,s){this.event.off(e,s)}fetchMessages(){return p(this,arguments,function*(e={}){var t,a;const s={pageSize:this._loadingMessagesSize};if(this._id){e=u(u({},s),e),this.event.emit("history:loading"),S.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),S.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),n=r.map((i,d)=>{var g,f;let l=[],h;return typeof((g=i.agentHistoryList)==null?void 0:g.agentList)=="string"&&(l=JSON.parse(i.agentHistoryList.agentList).reduce((y,_)=>(y[_.data.step-1]||(y[_.data.step-1]=[]),y[_.data.step-1].push(_),y),[])),d===r.length-1&&(h=(f=this.data)==null?void 0:f.lastRelatedQuestion),w(u({},i),{actions:l,relatedQuesion:h})});if(!e.endTime&&!e.startTime){const i=this.messages[this.messages.length-1];i&&!i.relatedQuesion&&(i.relatedQuesion=(t=this.data)==null?void 0:t.lastRelatedQuestion),this.messages=[...n,...this.messages]}else if(e.endTime&&!e.startTime){const i=this.messages.findIndex(d=>d.ts===e.endTime);this.messages.splice(0,i+1),this.messages=[...n,...this.messages]}else if(!e.endTime&&e.startTime){const i=this.messages.findLastIndex(d=>d.ts===e.endTime);this.messages.splice(i,this.messages.length-i-1),this.messages=[...this.messages,...n]}else{const i=this.messages.findIndex(l=>l.ts===e.endTime),d=this.messages.findLastIndex(l=>l.ts===e.endTime);this.messages.splice(i,d-i+1,...n)}const c=this.messages[this.messages.length-1];return c&&!c.relatedQuesion&&(c.relatedQuesion=(a=this.data)==null?void 0:a.lastRelatedQuestion),this.event.emit("history:moreloaded",n),S.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,n}else{const r=new Error("session id is not defined");return S.error(r),this.event.emit("error",r),!1}})}rename(e){return p(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),S.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return p(this,null,function*(){this.messages.push(e),S.log("history:add",e),this.event.emit("history:add",e),this.event.emit("message:new",e),this.event.emit("message:updated",e)})}reloadSessionInfo(){if(!this._id)throw Error("session is not created yet");return this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,this._id).then(e=>p(this,null,function*(){if(this.data=e,!this._id)throw Error("session is not created yet");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),S.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>p(this,null,function*(){return this.messages=[],yield this.fetchMessages(),this._dataLoading=!1,this._dataLoaded=!0,this.event.emit("data:loaded",this.data),this}))}reload(){return p(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return p(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return S.error(e),this.event.emit("error",e),!1}return this.event.emit("data:deleting"),yield this.cvforceApi.delSessionsId(this.applicationId,this.id),this.event.emit("data:deleted"),this.destroy()})}activate(){return p(this,null,function*(){if(this.activing)return new Promise(s=>{this.addEventListener("activated",()=>{s(!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(s=>p(this,null,function*(){return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,e),s})),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(t){return p(this,arguments,function*(e,s={stream:exports.configuration.stream}){var g;try{this.validateConfigs()}catch(f){console.error(f)}const{stream:a=exports.configuration.stream,referenceFirst:r=!1}=s,n=e.uuid||J.v4(),c=((g=e.text)==null?void 0:g.trim())||"",i=e.fileIds;if(!c&&!(i!=null&&i.length)){const f=new Error("failed at sending empty content");return S.error(f),this.event.emit("error",f),!1}if(!this._id){const f=new Error("session id is not defined");return S.error(f),this.event.emit("error",f),!1}if(this.frozen){const f=new Error("session is frozen");return S.error(f),this.event.emit("error",f),!1}this.frozen=!0,this._stopAnswer=!1;const d={sessionId:this.id,role:2,content:c,messageId:n,reference:[],searchReference:[],messageTime:""},l={content:c,stream:a,requestId:n,fileIds:i,referenceFirst:r};this.pushMessage(d),this.event.emit("question:content",c);const h=f=>p(this,null,function*(){if(f.role!==I.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",h),this._id&&f.content&&f.index&&f.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:f.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:f.content})),yield this.fillMessageReference(f),f.code){case 11915:f.content="请您换个问题问我吧~",f.index=-1,f.isSensitive=!0,f.isLoading=!1,f.sessionId=this._id||"",this.event.emit("message:error",f);break;case 200:f.index=-1,f.isLoading=!1;break;default:f.content=f.message||"未知错误",f.isLoading=!1,f.index=-1,this.event.emit("message:error",f)}this.getRelatedQuesion(f),f.isLoading=!1;let v=this.messages[this.messages.length-1];if(v&&v.role===I.ChatMessageRole.Robot){const y=u(u({},v),f);this.messages[this.messages.length-1]=y,this.event.emit("message:updated",y)}else this.pushMessage(f);this.frozen=!1});return this.addEventListener("answer:finish",h),this.sendQuestion(l,w(u({},s),{stream:a,referenceFirst:r})),d})}getRelatedQuesion(e){return p(this,null,function*(){var r,n;if(!e.content||e.isSensitive||e.code!==200||!((r=this.application)!=null&&r.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const s=yield this.cvforceApi.postGeneques({content:e.content}).catch(c=>null);if(!s){const c=[],i=w(u({},e),{relatedQuesion:c,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:c}),this.event.emit("message:updated",i),i}const t=(n=s.content)==null?void 0:n.split("*").map(he).map(le).filter(c=>!!c);e.relatedQuesion=t,e.index=-3,e.isLoading=!1;const a=w(u({},e),{relatedQuesion:t,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",a),this.event.emit("message:updated",a),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:t}),a})}fillMessageReference(e){return p(this,null,function*(){const s=yield Promise.all(e.reference.map(t=>this.cvforceApi.getKnowledgeIdFileId(t.knowledgeId,t.docId)));return e.reference=e.reference.map((t,a)=>u(u({},t),s[a])),this.event.emit("message:updated",e),e})}answerAgain(){return p(this,arguments,function*(e={stream:exports.configuration.stream}){const s=this.messages[this.messages.length-1];if(!s)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1;const{stream:t=exports.configuration.stream}=e;let a;s.role!==I.ChatMessageRole.User&&(a=e.oldMessageId||s.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",s),this.event.emit("history:remove",s));const r=this.messages[this.messages.length-1],n={content:r.content,fileIds:r.fileIds,requestId:r.messageId,stream:t,oldMessageId:a},c=i=>p(this,null,function*(){if(i.role===I.ChatMessageRole.Robot&&i.index===-1){switch(this._id&&i.content&&i.index&&i.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:i.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:i.content})),yield this.fillMessageReference(i),i.code){case 11915:i.content="请您换个问题问我吧~",i.index=-1,i.isSensitive=!0,i.isLoading=!1,i.sessionId=this._id||"",this.event.emit("message:error",i);break;case 200:i.index=-1,i.isLoading=!1;break;default:i.content=i.message||"未知错误",i.isLoading=!1,i.index=-1,this.event.emit("message:error",i)}this.getRelatedQuesion(i),this.removeEventListener("message:content",c),this.frozen=!1}});this.addEventListener("message:content",c),this.sendQuestion(n,w(u({},e),{stream:t}))})}setTop(e){return p(this,null,function*(){if(!this._id)throw Error("session is not avalible. id is undefined");this.data=yield this.cvforceApi.patchSessionsId(this._applicationId,this._id,{top:e}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:top",{top:e})})}suspend(){var t;this.stopAnswer(),this.frozen=!1,this._stopAnswer=!0;let e=this.messages[this.messages.length-1];const s={messageId:J.v4(),isLoading:!1,index:-2,messageTime:K(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:I.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const a=e.actions[((t=e.actions)==null?void 0:t.length)-1];if(a){const r=a[a.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:n,pluginCode:c,funcCode:i,funcName:d}=r.data;a.push({data:{pluginName:n,pluginCode:c,funcCode:i,funcName:d,step:r.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:a})}}}e=u(u({},e),s),this.event.emit("message:content",e),this.event.emit("message:updated",e)}else this.pushMessage(s),this.event.emit("message:content",s);return this}postMessageComment(e){return p(this,null,function*(){if(!this._applicationId||!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.postComments(this._applicationId,this._id,e).then(s=>{const t=this.messages.find(a=>a.messageId===e.messageId);return t&&(t.comment=e,this.event.emit("message:comment",t)),s})})}clear(){if(!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.patchApplicationIdSessionsIdContext(this._applicationId,this._id).then(()=>(this.event.emit("context:clear"),!0))}destroy(){var e;return this._ready=!1,this.event.removeAllListeners(),(e=this.socket)==null||e.disconnect(),this.socket=null,this.event.emit("destroy",{applicationId:this._applicationId,sessionId:this._id}),this._id||""}}const M=new b("[AgentSession] ");class fe extends q{constructor(e,s="",t,a,r,n){super(e,s,t,a,r,n)}prepareConnection(){return new Promise(e=>p(this,null,function*(){this.socket&&e(!0);const s={version:"1.0",stream:JSON.stringify(exports.configuration.stream===void 0?!0:exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?L.Debug:L.Normal},t=new URL(exports.configuration.apiRoot),a=yield oe.io(t.origin,{path:t.pathname.replace("api","socketio")+"/copilot",query:s,transports:["websocket"]});a.on("connect",()=>{M.log("socket:connect"),this.event.emit("socket:connect"),a.emit("init")}),a.on("disconnect",()=>{M.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),a.on("ready",r=>{if(r.code===200){M.log("ready");const n=exports.configuration.debug?L.Debug:L.Normal;n===L.Debug&&r.userMode,this._ready=!0,this.event.emit("ready"),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const n=new Error(C.SocketConnectionFailed);M.error("error",n),this.event.emit("error",n),e(!1)}}),a.on("action",(r,n)=>p(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:c,data:{runnerIsClient:i,pluginCode:d,funcCode:l,parameters:h,requestBody:g}}=r,f=this.messages[this.messages.length-1];if(!f.messageId)f.actions||(f.actions=[]),f.actions[r.data.step-1]||(f.actions[r.data.step-1]=[]),f.actions[r.data.step-1].push(r),this.event.emit("message:action",{messageId:f.messageId,action:r}),this.event.emit("message:updated",f);else{const v={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[r]],comment:{isAgree:0}};this.pushMessage(v),this.event.emit("message:action",{messageId:v.messageId,action:r})}if(this.inactivating){const v=new Error(C.Inactive);M.warn("error",v),this.event.emit("error",v)}else if(c==="FUNCTION_CALL"&&i){if(M.log(`calling function ${l} of plugin ${d} with argument:
2
+ ${JSON.stringify(h)}`),!exports.configuration.plugins[d]){n({code:404,message:"对不起,没有找到插件。"});return}const v=exports.configuration.plugins[d][l];typeof v!="function"&&n({code:404,message:"对不起,没有找到插件方法。"});let y=h==null?void 0:h.query;try{y=JSON.parse(h==null?void 0:h.query)}catch(_){}v(y,(..._)=>{this._stopAnswer||n(..._)})}})),a.on("answer",r=>{if(!this._stopAnswer)if(r.data.code!==200&&(r.data.index=-1,this.event.emit("error",r.data)),r.data.index===-1){let n=this.messages[this.messages.length-1];if(n&&!n.messageId)n=u(u({},n),r.data),this.event.emit("message:content",n),this.event.emit("message:updated",n),this.event.emit("answer:finish",n);else{const c=u({messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0}},r.data);this.event.emit("message:content",c),this.pushMessage(c),this.event.emit("answer:finish",c)}}else{let n=this.messages[this.messages.length-1];n&&!n.messageId?(n=u(u({},n),r.data),this.messages[this.messages.length-1]=n,this.event.emit("message:content",n),this.event.emit("message:updated",n)):(this.pushMessage(r.data),this.event.emit("message:content",r.data))}}),a.on("reference",r=>p(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const h=new Error(C.IdUndefined);M.error(h),this.event.emit("error",h),this.frozen=!1;return}const{type:n,data:c,requestId:i}=r,d=this.messages.findIndex(h=>h.messageId===i&&h.role===I.ChatMessageRole.User);if(d<0)return;const l=d+1;if(l>=this.messages.length){const h={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0}};this.pushMessage(h)}n==="KG"?(this.messages[l]=w(u({},this.messages[l]),{reference:c.knowledgeReference}),yield this.fillMessageReference(this.messages[l]),this.event.emit("message:reference",c.knowledgeReference),this.event.emit("message:updated",this.messages[l])):n==="WEB_SEARCH"&&(this.messages[l]=w(u({},this.messages[l]),{searchReference:c.knowledgeReference}),this.event.emit("message:searchreference",c.searchReference),this.event.emit("message:updated",this.messages[l]))})),this.socket=a,a.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((e,s)=>{if(!this.socket){s("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,t=>{t.code===200?(Object.keys(t.data).forEach(a=>{t.data[a].code!==200&&console.error(a,"MCP Server 注册失败。",t.data[a])}),e(!0)):(console.error("MCP Server 注册失败。",t),s(t))})}):Promise.resolve(!0)}addMcpServers(e){return p(this,null,function*(){return this.ready?this.socket?new Promise((s,t)=>{this.socket&&this.socket.emit("add_mcp_servers",e,a=>{a.code===200?(Object.keys(a.data).forEach(r=>{a.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",a.data[r])}),s(!0)):(console.error("MCP Server 注册失败。",a),t(a))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return p(this,null,function*(){return this.ready?this.socket?new Promise((e,s)=>{this.socket&&this.socket.emit("list_mcp_servers",t=>{t.code===200?e(t.data):s(t)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(e,s){return p(this,null,function*(){var a,r,n;let t=w(u({},e),{promptVariables:this.promptVariables.reduce((c,i)=>w(u({},c),{[i.key]:i.value}),{}),knowledges:(a=this.knowledges)==null?void 0:a.map(c=>c.id)});if(!this.active){if(yield this.activate(),!this.socket){const c=new Error(C.SocketConnectionFailed);return M.warn("error",c),this.event.emit("error",c),!1}(r=this.socket)==null||r.emit("question",t);return}(n=this.socket)==null||n.emit("question",t)})}stopAnswer(){var e;(e=this.socket)==null||e.emit("stop_answer")}}function pe(o,e){return p(this,null,function*(){const s=o.getReader();let t;for(;!(t=yield s.read()).done;)e(t.value)})}function ge(o){let e,s,t,a=!1,r;return function(c){e===void 0?(e=c,s=0,t=-1,r=!1):e=me(e,c);const i=e.length;let d=0;for(;s<i;){a&&(e[s]===10&&(d=++s),a=!1);let l=-1;for(;s<i&&l===-1;++s)switch(e[s]){case 58:t===-1&&(t=s-d);break;case 13:a=!1,s+4<i&&e[s+1]===10&&e[s+2]!==13&&e[s-1]!==10&&e[s-2]!==13&&(r=!0);case 10:l=s;break}if(l===-1)break;o(e.subarray(d,l),t,r),d=s,t=-1,r=!1}d===i?e=void 0:d!==0&&(e=e.subarray(d),s-=d)}}function ue(o,e,s){let t=H();const a=new TextDecoder;return function(n,c,i){if(n.length===0)s==null||s(t),t=H();else if(c>0){const d=a.decode(n.subarray(0,c)),l=c+(n[c+1]===32?2:1);let h=a.decode(n.subarray(l));switch(i&&(h+=`
3
+ `),d){case"data":t.data=t.data?t.data+`
4
+ `+h:h;break;case"event":t.event=h;break;case"id":o(t.id=h);break;case"retry":const g=parseInt(h,10);isNaN(g)||e(t.retry=g);break}}}}function me(o,e){const s=new Uint8Array(o.length+e.length);return s.set(o),s.set(e,o.length),s}function H(){return{data:"",event:"",id:"",retry:void 0}}const N="text/event-stream",ve=1e3,Y="last-event-id";function U(o,l){var h=l,{signal:e,headers:s,onopen:t,onmessage:a,onclose:r,onerror:n,openWhenHidden:c,fetch:i}=h,d=j(h,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,f)=>{const v=u({},s);v.accept||(v.accept=N);let y;function _(){y.abort(),document.hidden||Q()}c||document.addEventListener("visibilitychange",_);let E=ve,V=0;function O(){document.removeEventListener("visibilitychange",_),window.clearTimeout(V),y.abort()}e==null||e.addEventListener("abort",()=>{O(),g()});const ee=i!=null?i:window.fetch,te=t!=null?t:ye;function Q(){return p(this,null,function*(){var D;y=new AbortController;try{const x=yield ee(o,w(u({},d),{headers:v,signal:y.signal}));yield te(x),yield pe(x.body,ge(ue(k=>{k?v[Y]=k:delete v[Y]},k=>{E=k},a))),r==null||r(),O(),g()}catch(x){if(!y.signal.aborted)try{const k=(D=n==null?void 0:n(x))!=null?D:E;window.clearTimeout(V),V=window.setTimeout(Q,k)}catch(k){O(),f(k)}}})}Q()})}function ye(o){const e=o.headers.get("content-type");if(!(e!=null&&e.startsWith(N)))throw new Error(`Expected content-type to be ${N}, Actual: ${e}`)}const W=new b("[DialogSession] ");class we extends q{constructor(s,t="",a,r,n,c){super(s,t,a,r,n,c);m(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(s=>p(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,s(!0)}))}postChatV2EventSource(s,t,a,r,n,c){return p(this,null,function*(){const i={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:t,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=w(u({},a),{stream:exports.configuration.stream});U(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${s}&sessionId=${t}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:r,onopen(l){return l.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(l){if(!l.data.includes('{"code": ')){let g={};try{g=JSON.parse(l.data)}catch(v){}(g==null?void 0:g.mtype)==="search"?i.searchReference.push(g):i.content=i.content+l.data;const f={content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:t,messageTime:K(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(n==null?void 0:n.onmessage)&&n.onmessage(f)}const h=JSON.parse(l.data);if(i.reference=h.data.reference,i.searchReference=h.data.searchReference,i.messageTime=h.data.messageTime,i.messageId=h.data.messageId,i.llmModel=h.data.llmModel,i.content=h.data.content,i.code=h.code,h.code===200){const g={code:i.code,content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:t,messageTime:i.messageTime,isReplying:!0};n!=null&&n.onmessage&&n.onmessage(g)}else return n!=null&&n.onclose&&n.onclose(i),c&&c({code:i.code,message:i.message})},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const l={code:i.code,content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:t,messageTime:i.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};n!=null&&n.onclose&&n.onclose(l)}})})}postChatV3EventSource(s,t,a,r,n,c){return p(this,null,function*(){const i={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:t,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},d=w(u({},a),{stream:exports.configuration.stream});U(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${s}&sessionId=${t}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:r,onopen(l){return l.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(l){if(!l.data&&!l.event&&!l.id&&!l.retry)return;let h={};try{h=JSON.parse(l.data)}catch(y){console.error("parse eventData to JSON failed. ",l.data)}if(h.code!==200)return i.index=-1,i.code=h.code,i.message=h.message,n!=null&&n.onmessage&&n.onmessage(i),c&&c({code:h.code,message:h.message});const g=h.data.type,f=h.data.payload;i.isReplying=!0;const v=()=>{if(!i.searchingStatus){i.searchingStatus="start";return}if(i.searchingStatus==="start"){i.searchingStatus="end";return}};if(g==="beforeSearch"&&v(),g==="searchOver"&&v(),g==="search"&&i.searchReference.push(f),g==="thinking"){i.thinkingStatus="start";const _=f.choices[0];i.reasoningContent=i.reasoningContent+_.delta.reasoningContent}if(g==="thinkingOver"){i.thinkingStatus="end";const y=f.thinkingSecs;i.thinkingSecs=y}if(g==="text"){const _=f.choices[0];i.content=i.content+_.delta.content}if(g==="reference"&&(i.reference=f),g==="result"){const y=f.messageId,_=f.llmModel,E=f.messageTime;i.messageId=y,i.llmModel=_,i.messageTime=E,i.sessionId=t}g==="over"?i.index=-1:(i.code=h.code,i.message=h.message),n!=null&&n.onmessage&&n.onmessage(i)},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const l=w(u({},i),{isReplying:!1});n!=null&&n.onclose&&n.onclose(l)}})})}sendQuestion(s,t){return p(this,null,function*(){var d;const{content:a,fileIds:r,oldMessageId:n}=s,{stream:c,referenceFirst:i}=t;if(this.active||(yield this.activate()),this._id){let l={content:a,fileIds:r,referenceFirst:i,oldMessageId:n,promptVariables:this.promptVariables.reduce((h,g)=>w(u({},h),{[g.key]:g.value}),{}),knowledges:(d=this.knowledges)==null?void 0:d.map(h=>h.id)};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,l,this.ctrl.signal,{onopen:()=>{W.log("open",this.ctrl)},onmessage:h=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===I.ChatMessageRole.Robot?(g=u(u({},g),h),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(h),this.event.emit("message:content",h))},onclose:h=>p(this,null,function*(){this._stopAnswer||(W.log(h,"onclose"),this.event.emit("answer:finish",h))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(s){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}}const Ie=new b("[BotClient] ");class _e{constructor(e,s,t=!0){m(this,"event",new Z);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=t,z(s),this._applicationId=P(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(a=>{z(w(u({},s),{stream:s.stream===void 0?(a==null?void 0:a.type)===I.ApplicationTypes.Dialog:s.stream})),this.event.emit("ready")})}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return p(this,null,function*(){var s,t,a;this._application=yield this.cvforceApi.getApplicationId(this._applicationId).then(r=>(typeof r.arrange[0].recommendQuestionOpen!="boolean"&&(r.arrange[0].recommendQuestionOpen=!0),w(u({},r),{arrange:[w(u({},r.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&r.arrange[0].recommendQuestionOpen})]})));const e=(a=(t=(s=this._application)==null?void 0:s.arrange)==null?void 0:t[0])==null?void 0:a.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(r=>r.maxModelLength)),this._promptVariables=yield this.cvforceApi.getPrompts(this._applicationId),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:X(exports.configuration.apiRoot,this.token,(e,s)=>Ie.error(s))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const s=P(e).rid;this._applicationId!==s&&(this._applicationId=s,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(s=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=s})}createSession(e,s,t,a,r){return p(this,null,function*(){const n=this;return new Promise((c,i)=>{const d=l=>p(this,null,function*(){if(l===I.ApplicationTypes.Agent)c(new fe(e,s,t,a,r,n));else if(l===I.ApplicationTypes.Dialog)c(new we(e,s,t,a,r,n));else throw Error(`不支持的应用类型:${l}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return p(this,null,function*(){return new Promise((s,t)=>{const a=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>{const n=[];return r.forEach(c=>p(this,null,function*(){const i=this._sessions.find(d=>c.id===d.id);if(i)i.data=c,this._application?i.application=this._application:i.loadApplicationInfo(),n.push(i);else{const d=yield this.createSession(this.token,c.id,c,this.lazyload,this._application||void 0);n.push(d)}})),this.sessions=n,n});if(this.ready){if(!this._application)throw Error("_application is null");s(a())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");s(a())},!0)})})}loadSession(e="",s){return p(this,null,function*(){this.checkReady();let t=this.sessions.find(a=>a.id===e);if(t||(t=yield this.createSession(this.token,e,s),this._sessions.push(t)),this._activeSession){if(this._activeSession===t)return t;this._activeSession.inactivate()}return t.id?(yield t.activate(),this._activeSession=t):t.addEventListener("data:loaded",()=>{this._activeSession!==t&&(t==null||t.activate(),this._activeSession=t)},!0),t})}reload(){return this.loadApplication().then(()=>p(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return p(this,null,function*(){yield this.reload();let s=this._sessions.find(t=>t.id===e)||this._activeSession;if(!s){console.warn("reloadSession session failed.");return}return yield s.reload(),s})}setTop(e,s,t="top_time desc, sort_status desc, updated_at desc"){return p(this,null,function*(){let a=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!a){console.warn("setTop session failed.");return}return yield a.setTop(s),this.getSessions({order:t})})}addEventListener(e,s,t=!1){if(typeof s!="function")throw Error("event listener is not a function");if(t){this.event.once(e,s);return}this.event.on(e,s)}removeEventListener(e,s){this.event.off(e,s)}removeSession(e,s){return p(this,null,function*(){this.checkReady();let t=-1;if(typeof e=="string"?t=this._sessions.findIndex(a=>a.id===e):t=this._sessions.findIndex(a=>a.id===e.id),t>-1){const a=this._sessions[t];s&&(yield a.delete()),this._sessions.splice(t,1)}else console.warn("session delete failed, session is not exist.")})}clean(){this._sessions.forEach(e=>e.destroy()),this.sessions=[]}}class Se{constructor(e,s={},t){m(this,"code");m(this,"description","");m(this,"loaded",!1);m(this,"functions",{});this.code=e,s&&(this.functions=s)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}exports.AgentPlugin=Se;exports.BotClient=_e;exports.Session=q;exports.configure=z;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glodon-aiot/agent-cli-sdk",
3
- "version": "3.3.2-beta.9",
3
+ "version": "3.3.5-alpha.16",
4
4
  "author": "glodoncv",
5
5
  "description": "aiot agent client js sdk",
6
6
  "type": "module",
@@ -79,7 +79,7 @@
79
79
  "registry": "https://registry.npmjs.org/"
80
80
  },
81
81
  "dependencies": {
82
- "@glodon-aiot/apis": "^3.3.2-beta.9",
82
+ "@glodon-aiot/apis": "^3.3.5-alpha.16",
83
83
  "axios": "0.24.0",
84
84
  "buffer": "^6.0.3",
85
85
  "dayjs": "^1.11.13",