@glodon-aiot/agent-cli-sdk 3.2.10-beta.8 → 3.3.0-beta.13

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,44 +1,44 @@
1
- var C = Object.defineProperty, b = Object.defineProperties;
1
+ var R = Object.defineProperty, b = Object.defineProperties;
2
2
  var S = Object.getOwnPropertyDescriptors;
3
- var A = Object.getOwnPropertySymbols;
4
- var q = Object.prototype.hasOwnProperty, x = Object.prototype.propertyIsEnumerable;
5
- var _ = (c, t, n) => t in c ? C(c, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : c[t] = n, h = (c, t) => {
3
+ var _ = Object.getOwnPropertySymbols;
4
+ var A = Object.prototype.hasOwnProperty, E = Object.prototype.propertyIsEnumerable;
5
+ var P = (d, t, n) => t in d ? R(d, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : d[t] = n, h = (d, t) => {
6
6
  for (var n in t || (t = {}))
7
- q.call(t, n) && _(c, n, t[n]);
8
- if (A)
9
- for (var n of A(t))
10
- x.call(t, n) && _(c, n, t[n]);
11
- return c;
12
- }, p = (c, t) => b(c, S(t));
13
- var w = (c, t, n) => new Promise((d, o) => {
14
- var s = (a) => {
7
+ A.call(t, n) && P(d, n, t[n]);
8
+ if (_)
9
+ for (var n of _(t))
10
+ E.call(t, n) && P(d, n, t[n]);
11
+ return d;
12
+ }, k = (d, t) => b(d, S(t));
13
+ var p = (d, t, n) => new Promise((o, i) => {
14
+ var s = (c) => {
15
15
  try {
16
- i(n.next(a));
17
- } catch (m) {
18
- o(m);
16
+ r(n.next(c));
17
+ } catch (g) {
18
+ i(g);
19
19
  }
20
- }, e = (a) => {
20
+ }, e = (c) => {
21
21
  try {
22
- i(n.throw(a));
23
- } catch (m) {
24
- o(m);
22
+ r(n.throw(c));
23
+ } catch (g) {
24
+ i(g);
25
25
  }
26
- }, i = (a) => a.done ? d(a.value) : Promise.resolve(a.value).then(s, e);
27
- i((n = n.apply(c, t)).next());
26
+ }, r = (c) => c.done ? o(c.value) : Promise.resolve(c.value).then(s, e);
27
+ r((n = n.apply(d, t)).next());
28
28
  });
29
- import { ChatMessageRole as k } from "@glodon-aiot/apis";
30
- import E from "./Logger.mjs";
29
+ import { ChatMessageRole as I } from "@glodon-aiot/apis";
30
+ import q from "./Logger.mjs";
31
31
  import { configuration as v } from "./Config.mjs";
32
- import { io as L } from "socket.io-client";
33
- import { UserMode as I } from "./PayloadTypes.mjs";
34
- import N, { SessionErrors as y } from "./Session.mjs";
35
- const u = new E("[AgentSession] ");
36
- class B extends N {
37
- constructor(t, n = "", d, o, s, e) {
38
- super(t, n, d, o, s, e);
32
+ import { io as x } from "socket.io-client";
33
+ import { UserMode as w } from "./PayloadTypes.mjs";
34
+ import L, { SessionErrors as M } from "./Session.mjs";
35
+ const u = new q("[AgentSession] ");
36
+ class D extends L {
37
+ constructor(t, n = "", o, i, s, e) {
38
+ super(t, n, o, i, s, e);
39
39
  }
40
40
  prepareConnection() {
41
- return new Promise((t) => w(this, null, function* () {
41
+ return new Promise((t) => p(this, null, function* () {
42
42
  this.socket && t(!0);
43
43
  const n = {
44
44
  version: "1.0",
@@ -46,42 +46,42 @@ class B extends N {
46
46
  appId: this._applicationId,
47
47
  sessionId: this.id,
48
48
  Authorization: `${this.token}`,
49
- userMode: v.debug ? I.Debug : I.Normal
50
- }, d = new URL(v.apiRoot), o = yield L(d.origin, {
51
- path: d.pathname.replace("api", "socketio") + "/copilot",
49
+ userMode: v.debug ? w.Debug : w.Normal
50
+ }, o = new URL(v.apiRoot), i = yield x(o.origin, {
51
+ path: o.pathname.replace("api", "socketio") + "/copilot",
52
52
  query: n,
53
53
  transports: ["websocket"]
54
54
  });
55
- o.on("connect", () => {
56
- u.log("socket:connect"), this.event.emit("socket:connect"), o.emit("init");
57
- }), o.on("disconnect", () => {
55
+ i.on("connect", () => {
56
+ u.log("socket:connect"), this.event.emit("socket:connect"), i.emit("init");
57
+ }), i.on("disconnect", () => {
58
58
  u.log("socket:disconnect"), this.event.emit("socket:disconnect");
59
- }), o.on("ready", (s) => {
59
+ }), i.on("ready", (s) => {
60
60
  if (s.code === 200) {
61
61
  u.log("ready");
62
- const e = v.debug ? I.Debug : I.Normal;
63
- e === I.Debug && s.userMode, this._ready || (this._ready = !0, this.event.emit("ready")), this.frozen = !1, t(!0);
62
+ const e = v.debug ? w.Debug : w.Normal;
63
+ e === w.Debug && s.userMode, this._ready || (this._ready = !0, this.event.emit("ready")), this.frozen = !1, this.registerMcpFromClientConfig(), t(!0);
64
64
  } else {
65
65
  this._ready && (this._ready = !1);
66
66
  const e = new Error(
67
- y.SocketConnectionFailed
67
+ M.SocketConnectionFailed
68
68
  // , {
69
69
  // cause: data,
70
70
  // }
71
71
  );
72
72
  u.error("error", e), this.event.emit("error", e), t(!1);
73
73
  }
74
- }), o.on("action", (s, e) => w(this, null, function* () {
74
+ }), i.on("action", (s, e) => p(this, null, function* () {
75
75
  if (this._stopAnswer || !this.id)
76
76
  return;
77
77
  const {
78
- type: i,
78
+ type: r,
79
79
  data: {
80
- runnerIsClient: a,
81
- pluginCode: m,
82
- funcCode: g,
83
- parameters: r,
84
- requestBody: U
80
+ runnerIsClient: c,
81
+ pluginCode: g,
82
+ funcCode: m,
83
+ parameters: a,
84
+ requestBody: N
85
85
  }
86
86
  } = s, f = this.messages[this.messages.length - 1];
87
87
  if (!f.messageId)
@@ -93,7 +93,7 @@ class B extends N {
93
93
  const l = {
94
94
  messageId: "",
95
95
  content: "",
96
- role: k.Robot,
96
+ role: I.Robot,
97
97
  sessionId: this.id,
98
98
  reference: [],
99
99
  searchReference: [],
@@ -111,7 +111,7 @@ class B extends N {
111
111
  }
112
112
  if (this.inactivating) {
113
113
  const l = new Error(
114
- y.Inactive
114
+ M.Inactive
115
115
  // {
116
116
  // cause: {
117
117
  // code: -1,
@@ -121,40 +121,40 @@ class B extends N {
121
121
  // }
122
122
  );
123
123
  u.warn("error", l), this.event.emit("error", l);
124
- } else if (i === "FUNCTION_CALL" && a) {
125
- if (u.log(`calling function ${g} of plugin ${m} with argument:
126
- ${JSON.stringify(r)}`), !v.plugins[m]) {
124
+ } else if (r === "FUNCTION_CALL" && c) {
125
+ if (u.log(`calling function ${m} of plugin ${g} with argument:
126
+ ${JSON.stringify(a)}`), !v.plugins[g]) {
127
127
  e({
128
128
  code: 404,
129
129
  message: "对不起,没有找到插件。"
130
130
  });
131
131
  return;
132
132
  }
133
- const l = v.plugins[m][g];
133
+ const l = v.plugins[g][m];
134
134
  typeof l != "function" && e({
135
135
  code: 404,
136
136
  message: "对不起,没有找到插件方法。"
137
137
  });
138
- let M = r == null ? void 0 : r.query;
138
+ let y = a == null ? void 0 : a.query;
139
139
  try {
140
- M = JSON.parse(r == null ? void 0 : r.query);
141
- } catch (R) {
140
+ y = JSON.parse(a == null ? void 0 : a.query);
141
+ } catch (C) {
142
142
  }
143
- l(M, (...R) => {
144
- this._stopAnswer || e(...R);
143
+ l(y, (...C) => {
144
+ this._stopAnswer || e(...C);
145
145
  });
146
146
  }
147
- })), o.on("answer", (s) => {
147
+ })), i.on("answer", (s) => {
148
148
  if (!this._stopAnswer)
149
149
  if (s.data.code !== 200 && (s.data.index = -1, this.event.emit("error", s.data)), s.data.index === -1) {
150
150
  let e = this.messages[this.messages.length - 1];
151
151
  if (e && !e.messageId)
152
152
  e = h(h({}, e), s.data), this.event.emit("message:content", e), this.event.emit("message:updated", e), this.event.emit("answer:finish", e);
153
153
  else {
154
- const i = h({
154
+ const r = h({
155
155
  messageId: "",
156
156
  content: "",
157
- role: k.Robot,
157
+ role: I.Robot,
158
158
  sessionId: this.id,
159
159
  reference: [],
160
160
  searchReference: [],
@@ -165,38 +165,38 @@ class B extends N {
165
165
  isAgree: 0
166
166
  }
167
167
  }, s.data);
168
- this.event.emit("message:content", i), this.pushMessage(i), this.event.emit("answer:finish", i);
168
+ this.event.emit("message:content", r), this.pushMessage(r), this.event.emit("answer:finish", r);
169
169
  }
170
170
  } else {
171
171
  let e = this.messages[this.messages.length - 1];
172
172
  e && !e.messageId ? (e = h(h({}, e), s.data), this.messages[this.messages.length - 1] = e, this.event.emit("message:content", e), this.event.emit("message:updated", e)) : (this.pushMessage(s.data), this.event.emit("message:content", s.data));
173
173
  }
174
- }), o.on("reference", (s) => w(this, null, function* () {
174
+ }), i.on("reference", (s) => p(this, null, function* () {
175
175
  if (this._stopAnswer)
176
176
  return;
177
177
  if (!this.id) {
178
- const r = new Error(
179
- y.IdUndefined
178
+ const a = new Error(
179
+ M.IdUndefined
180
180
  // {
181
181
  // cause: SESSION_ERROR_CAUSE[SessionErrors.IdUndefined],
182
182
  // }
183
183
  );
184
- u.error(r), this.event.emit("error", r), this.frozen = !1;
184
+ u.error(a), this.event.emit("error", a), this.frozen = !1;
185
185
  return;
186
186
  }
187
187
  const {
188
188
  type: e,
189
- data: i,
190
- requestId: a
191
- } = s, m = this.messages.findIndex((r) => r.messageId === a && r.role === k.User);
192
- if (m < 0)
189
+ data: r,
190
+ requestId: c
191
+ } = s, g = this.messages.findIndex((a) => a.messageId === c && a.role === I.User);
192
+ if (g < 0)
193
193
  return;
194
- const g = m + 1;
195
- if (g >= this.messages.length) {
196
- const r = {
194
+ const m = g + 1;
195
+ if (m >= this.messages.length) {
196
+ const a = {
197
197
  messageId: "",
198
198
  content: "",
199
- role: k.Robot,
199
+ role: I.Robot,
200
200
  sessionId: this.id,
201
201
  reference: [],
202
202
  searchReference: [],
@@ -207,39 +207,72 @@ class B extends N {
207
207
  isAgree: 0
208
208
  }
209
209
  };
210
- this.pushMessage(r);
210
+ this.pushMessage(a);
211
211
  }
212
- e === "KG" ? (this.messages[g] = p(h({}, this.messages[g]), {
213
- reference: i.knowledgeReference
214
- }), yield this.fillMessageReference(this.messages[g]), this.event.emit("message:reference", i.knowledgeReference), this.event.emit("message:updated", this.messages[g])) : e === "WEB_SEARCH" && (this.messages[g] = p(h({}, this.messages[g]), {
215
- searchReference: i.knowledgeReference
216
- }), this.event.emit("message:searchreference", i.searchReference), this.event.emit("message:updated", this.messages[g]));
217
- })), this.socket = o, o.open();
212
+ e === "KG" ? (this.messages[m] = k(h({}, this.messages[m]), {
213
+ reference: r.knowledgeReference
214
+ }), yield this.fillMessageReference(this.messages[m]), this.event.emit("message:reference", r.knowledgeReference), this.event.emit("message:updated", this.messages[m])) : e === "WEB_SEARCH" && (this.messages[m] = k(h({}, this.messages[m]), {
215
+ searchReference: r.knowledgeReference
216
+ }), this.event.emit("message:searchreference", r.searchReference), this.event.emit("message:updated", this.messages[m]));
217
+ })), this.socket = i, i.open();
218
218
  }));
219
219
  }
220
+ registerMcpFromClientConfig() {
221
+ return v.mcp ? new Promise((t, n) => {
222
+ if (!this.socket) {
223
+ n("socket is undefined");
224
+ return;
225
+ }
226
+ this.socket.emit("add_mcp_servers", v.mcp, (o) => {
227
+ o.code === 200 ? (Object.keys(o.data).forEach((i) => {
228
+ o.data[i].code !== 200 && console.error(i, "MCP Server 注册失败。", o.data[i]);
229
+ }), t(!0)) : (console.error("MCP Server 注册失败。", o), n(o));
230
+ });
231
+ }) : Promise.resolve(!0);
232
+ }
233
+ addMcpServers(t) {
234
+ return p(this, null, function* () {
235
+ return this.ready ? this.socket ? new Promise((n, o) => {
236
+ this.socket && this.socket.emit("add_mcp_servers", t, (i) => {
237
+ i.code === 200 ? (Object.keys(i.data).forEach((s) => {
238
+ i.data[s].code !== 200 && console.error(s, "MCP Server 注册失败。", i.data[s]);
239
+ }), n(!0)) : (console.error("MCP Server 注册失败。", i), o(i));
240
+ });
241
+ }) : (console.error(" socket is undefined."), Promise.reject("socket is undefined")) : (console.error("session is not avalible."), Promise.reject("session is not avalible"));
242
+ });
243
+ }
244
+ listMcpServers() {
245
+ return p(this, null, function* () {
246
+ return this.ready ? this.socket ? new Promise((t, n) => {
247
+ this.socket && this.socket.emit("list_mcp_servers", (o) => {
248
+ o.code === 200 ? t(o.data) : n(o);
249
+ });
250
+ }) : (console.error(" socket is undefined."), Promise.reject("socket is undefined")) : (console.error("session is not avalible."), Promise.reject("session is not avalible"));
251
+ });
252
+ }
220
253
  sendQuestion(t, n) {
221
- return w(this, null, function* () {
222
- var o, s, e;
223
- let d = p(h({}, t), {
224
- promptVariables: this.promptVariables.reduce((i, a) => p(h({}, i), {
225
- [a.key]: a.value
254
+ return p(this, null, function* () {
255
+ var i, s, e;
256
+ let o = k(h({}, t), {
257
+ promptVariables: this.promptVariables.reduce((r, c) => k(h({}, r), {
258
+ [c.key]: c.value
226
259
  }), {}),
227
- knowledges: (o = this.knowledges) == null ? void 0 : o.map((i) => i.id)
260
+ knowledges: (i = this.knowledges) == null ? void 0 : i.map((r) => r.id)
228
261
  });
229
262
  if (!this.active) {
230
263
  if (yield this.activate(), !this.socket) {
231
- const i = new Error(
232
- y.SocketConnectionFailed
264
+ const r = new Error(
265
+ M.SocketConnectionFailed
233
266
  // {
234
267
  // cause: { code: -1, message: 'socket is null' },
235
268
  // }
236
269
  );
237
- return u.warn("error", i), this.event.emit("error", i), !1;
270
+ return u.warn("error", r), this.event.emit("error", r), !1;
238
271
  }
239
- (s = this.socket) == null || s.emit("question", d);
272
+ (s = this.socket) == null || s.emit("question", o);
240
273
  return;
241
274
  }
242
- (e = this.socket) == null || e.emit("question", d);
275
+ (e = this.socket) == null || e.emit("question", o);
243
276
  });
244
277
  }
245
278
  stopAnswer() {
@@ -248,5 +281,5 @@ class B extends N {
248
281
  }
249
282
  }
250
283
  export {
251
- B as default
284
+ D as default
252
285
  };
@@ -1,15 +1,15 @@
1
- var s = Object.defineProperty, u = Object.defineProperties;
2
- var v = Object.getOwnPropertyDescriptors;
1
+ var v = Object.defineProperty, s = Object.defineProperties;
2
+ var u = Object.getOwnPropertyDescriptors;
3
3
  var n = Object.getOwnPropertySymbols;
4
4
  var p = Object.prototype.hasOwnProperty, h = Object.prototype.propertyIsEnumerable;
5
- var g = (o, t, e) => t in o ? s(o, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : o[t] = e, i = (o, t) => {
5
+ var g = (o, t, e) => t in o ? v(o, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : o[t] = e, i = (o, t) => {
6
6
  for (var e in t || (t = {}))
7
7
  p.call(t, e) && g(o, e, t[e]);
8
8
  if (n)
9
9
  for (var e of n(t))
10
10
  h.call(t, e) && g(o, e, t[e]);
11
11
  return o;
12
- }, l = (o, t) => u(o, v(t));
12
+ }, l = (o, t) => s(o, u(t));
13
13
  import d from "./Logger.mjs";
14
14
  const R = new d("[Config] ");
15
15
  var f = /* @__PURE__ */ ((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))(f || {});
@@ -21,6 +21,7 @@ let c = {
21
21
  //https://${hostname}/${PRODUCD_CODE}
22
22
  applicationId: "",
23
23
  plugins: {},
24
+ mcp: void 0,
24
25
  loadRelatedQuesions: !0
25
26
  };
26
27
  function x(o) {
@@ -1,56 +1,56 @@
1
- var O = Object.defineProperty, $ = Object.defineProperties;
2
- var _ = Object.getOwnPropertyDescriptors;
3
- var T = Object.getOwnPropertySymbols;
4
- var x = Object.prototype.hasOwnProperty, D = Object.prototype.propertyIsEnumerable;
5
- var k = (i, c, a) => c in i ? O(i, c, { enumerable: !0, configurable: !0, writable: !0, value: a }) : i[c] = a, f = (i, c) => {
6
- for (var a in c || (c = {}))
7
- x.call(c, a) && k(i, a, c[a]);
8
- if (T)
9
- for (var a of T(c))
10
- D.call(c, a) && k(i, a, c[a]);
1
+ var A = Object.defineProperty, O = Object.defineProperties;
2
+ var D = Object.getOwnPropertyDescriptors;
3
+ var C = Object.getOwnPropertySymbols;
4
+ var P = Object.prototype.hasOwnProperty, $ = Object.prototype.propertyIsEnumerable;
5
+ var w = (i, c, t) => c in i ? A(i, c, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[c] = t, u = (i, c) => {
6
+ for (var t in c || (c = {}))
7
+ P.call(c, t) && w(i, t, c[t]);
8
+ if (C)
9
+ for (var t of C(c))
10
+ $.call(c, t) && w(i, t, c[t]);
11
11
  return i;
12
- }, R = (i, c) => $(i, _(c));
13
- var v = (i, c, a) => (k(i, typeof c != "symbol" ? c + "" : c, a), a);
14
- var y = (i, c, a) => new Promise((o, g) => {
12
+ }, R = (i, c) => O(i, D(c));
13
+ var v = (i, c, t) => (w(i, typeof c != "symbol" ? c + "" : c, t), t);
14
+ var f = (i, c, t) => new Promise((o, m) => {
15
15
  var d = (e) => {
16
16
  try {
17
- m(a.next(e));
17
+ g(t.next(e));
18
18
  } catch (l) {
19
- g(l);
19
+ m(l);
20
20
  }
21
21
  }, s = (e) => {
22
22
  try {
23
- m(a.throw(e));
23
+ g(t.throw(e));
24
24
  } catch (l) {
25
- g(l);
25
+ m(l);
26
26
  }
27
- }, m = (e) => e.done ? o(e.value) : Promise.resolve(e.value).then(d, s);
28
- m((a = a.apply(i, c)).next());
27
+ }, g = (e) => e.done ? o(e.value) : Promise.resolve(e.value).then(d, s);
28
+ g((t = t.apply(i, c)).next());
29
29
  });
30
- import { IHistoryRole as I, ChatMessageRole as J } from "@glodon-aiot/apis";
31
- import N from "./Logger.mjs";
32
- import P from "./Session.mjs";
33
- import V from "dayjs";
34
- import { configuration as w } from "./Config.mjs";
35
- import { fetchEventSource as C } from "./api/fetchEventSource/fetch.mjs";
36
- const b = new N("[DialogSession] ");
37
- class W extends P {
38
- constructor(a, o = "", g, d, s, m) {
39
- super(a, o, g, d, s, m);
30
+ import { IHistoryRole as k, ChatMessageRole as _ } from "@glodon-aiot/apis";
31
+ import x from "./Logger.mjs";
32
+ import J from "./Session.mjs";
33
+ import N from "dayjs";
34
+ import { configuration as T } from "./Config.mjs";
35
+ import { fetchEventSource as p } from "./api/fetchEventSource/fetch.mjs";
36
+ const I = new x("[DialogSession] ");
37
+ class H extends J {
38
+ constructor(t, o = "", m, d, s, g) {
39
+ super(t, o, m, d, s, g);
40
40
  v(this, "ctrl", new AbortController());
41
41
  }
42
42
  prepareConnection() {
43
- return new Promise((a) => y(this, null, function* () {
44
- this._ready = !0, this.event.emit("ready"), this.frozen = !1, a(!0);
43
+ return new Promise((t) => f(this, null, function* () {
44
+ this._ready = !0, this.event.emit("ready"), this.frozen = !1, t(!0);
45
45
  }));
46
46
  }
47
- postChatV2EventSource(a, o, g, d, s, m) {
48
- return y(this, null, function* () {
47
+ postChatV2EventSource(t, o, m, d, s, g) {
48
+ return f(this, null, function* () {
49
49
  const e = {
50
50
  code: 0,
51
51
  // messageId: uuidv4(),
52
52
  content: "",
53
- role: I.Robot,
53
+ role: k.Robot,
54
54
  sessionId: o,
55
55
  reference: [],
56
56
  searchReference: [],
@@ -60,10 +60,10 @@ class W extends P {
60
60
  isAgree: 0
61
61
  },
62
62
  isReplying: !1
63
- }, l = R(f({}, g), {
63
+ }, l = R(u({}, m), {
64
64
  stream: !0
65
65
  });
66
- C(`${w.apiRoot}/chat/v2/chat?applicationId=${a}&sessionId=${o}`, {
66
+ p(`${T.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${o}`, {
67
67
  method: "POST",
68
68
  headers: {
69
69
  Authorization: `Bearer ${this.token}`,
@@ -77,12 +77,12 @@ class W extends P {
77
77
  },
78
78
  onmessage(n) {
79
79
  if (!n.data.includes('{"code": ')) {
80
- let t = {};
80
+ let a = {};
81
81
  try {
82
- t = JSON.parse(n.data);
82
+ a = JSON.parse(n.data);
83
83
  } catch (M) {
84
84
  }
85
- (t == null ? void 0 : t.mtype) === "search" ? e.searchReference.push(t) : e.content = e.content + n.data;
85
+ (a == null ? void 0 : a.mtype) === "search" ? e.searchReference.push(a) : e.content = e.content + n.data;
86
86
  const h = {
87
87
  content: e.content,
88
88
  role: 1,
@@ -90,7 +90,7 @@ class W extends P {
90
90
  searchReference: e.searchReference,
91
91
  messageId: e.messageId,
92
92
  sessionId: o,
93
- messageTime: V(/* @__PURE__ */ new Date()).format("YYYY-MM-DD HH:mm:ss"),
93
+ messageTime: N(/* @__PURE__ */ new Date()).format("YYYY-MM-DD HH:mm:ss"),
94
94
  comment: {
95
95
  isAgree: 0
96
96
  },
@@ -100,7 +100,7 @@ class W extends P {
100
100
  }
101
101
  const r = JSON.parse(n.data);
102
102
  if (e.reference = r.data.reference, e.searchReference = r.data.searchReference, e.messageTime = r.data.messageTime, e.messageId = r.data.messageId, e.llmModel = r.data.llmModel, e.content = r.data.content, e.code = r.code, r.code === 200) {
103
- const t = {
103
+ const a = {
104
104
  code: e.code,
105
105
  content: e.content,
106
106
  role: 1,
@@ -111,9 +111,9 @@ class W extends P {
111
111
  messageTime: e.messageTime,
112
112
  isReplying: !0
113
113
  };
114
- s != null && s.onmessage && s.onmessage(t);
114
+ s != null && s.onmessage && s.onmessage(a);
115
115
  } else
116
- return s != null && s.onclose && s.onclose(e), m && m({
116
+ return s != null && s.onclose && s.onclose(e), g && g({
117
117
  code: e.code,
118
118
  message: e.message
119
119
  });
@@ -142,13 +142,13 @@ class W extends P {
142
142
  });
143
143
  });
144
144
  }
145
- postChatV3EventSource(a, o, g, d, s, m) {
146
- return y(this, null, function* () {
145
+ postChatV3EventSource(t, o, m, d, s, g) {
146
+ return f(this, null, function* () {
147
147
  const e = {
148
148
  code: 0,
149
149
  // messageId: uuidv4(),
150
150
  content: "",
151
- role: I.Robot,
151
+ role: k.Robot,
152
152
  sessionId: o,
153
153
  reference: [],
154
154
  searchReference: [],
@@ -162,10 +162,10 @@ class W extends P {
162
162
  thinkingSecs: "",
163
163
  thinkingStatus: "",
164
164
  searchingStatus: ""
165
- }, l = R(f({}, g), {
165
+ }, l = R(u({}, m), {
166
166
  stream: !0
167
167
  });
168
- C(`${w.apiRoot}/chat/v3/chat?applicationId=${a}&sessionId=${o}`, {
168
+ p(`${T.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${o}`, {
169
169
  method: "POST",
170
170
  headers: {
171
171
  Authorization: `Bearer ${this.token}`,
@@ -183,15 +183,15 @@ class W extends P {
183
183
  let r = {};
184
184
  try {
185
185
  r = JSON.parse(n.data);
186
- } catch (u) {
186
+ } catch (y) {
187
187
  console.error("parse eventData to JSON failed. ", n.data);
188
188
  }
189
189
  if (r.code !== 200)
190
- return e.index = -1, e.code = r.code, e.message = r.message, s != null && s.onmessage && s.onmessage(e), m && m({
190
+ return e.index = -1, e.code = r.code, e.message = r.message, s != null && s.onmessage && s.onmessage(e), g && g({
191
191
  code: r.code,
192
192
  message: r.message
193
193
  });
194
- const t = r.data.type, h = r.data.payload;
194
+ const a = r.data.type, h = r.data.payload;
195
195
  e.isReplying = !0;
196
196
  const M = () => {
197
197
  if (!e.searchingStatus) {
@@ -203,31 +203,31 @@ class W extends P {
203
203
  return;
204
204
  }
205
205
  };
206
- if (t === "beforeSearch" && M(), t === "searchOver" && M(), t === "search" && e.searchReference.push(h), t === "thinking") {
206
+ if (a === "beforeSearch" && M(), a === "searchOver" && M(), a === "search" && e.searchReference.push(h), a === "thinking") {
207
207
  e.thinkingStatus = "start";
208
208
  const S = h.choices[0];
209
209
  e.reasoningContent = e.reasoningContent + S.delta.reasoningContent;
210
210
  }
211
- if (t === "thinkingOver") {
211
+ if (a === "thinkingOver") {
212
212
  e.thinkingStatus = "end";
213
- const u = h.thinkingSecs;
214
- e.thinkingSecs = u;
213
+ const y = h.thinkingSecs;
214
+ e.thinkingSecs = y;
215
215
  }
216
- if (t === "text") {
216
+ if (a === "text") {
217
217
  const S = h.choices[0];
218
218
  e.content = e.content + S.delta.content;
219
219
  }
220
- if (t === "reference" && (e.reference = h), t === "result") {
221
- const u = h.messageId, S = h.llmModel, A = h.messageTime;
222
- e.messageId = u, e.llmModel = S, e.messageTime = A, e.sessionId = o;
220
+ if (a === "reference" && (e.reference = h), a === "result") {
221
+ const y = h.messageId, S = h.llmModel, b = h.messageTime;
222
+ e.messageId = y, e.llmModel = S, e.messageTime = b, e.sessionId = o;
223
223
  }
224
- t === "over" ? e.index = -1 : (e.code = r.code, e.message = r.message), s != null && s.onmessage && s.onmessage(e);
224
+ a === "over" ? e.index = -1 : (e.code = r.code, e.message = r.message), s != null && s.onmessage && s.onmessage(e);
225
225
  },
226
226
  onerror() {
227
227
  s != null && s.onerror && s.onerror();
228
228
  },
229
229
  onclose() {
230
- const n = R(f({}, e), {
230
+ const n = R(u({}, e), {
231
231
  isReplying: !1
232
232
  });
233
233
  s != null && s.onclose && s.onclose(n);
@@ -235,40 +235,40 @@ class W extends P {
235
235
  });
236
236
  });
237
237
  }
238
- sendQuestion(a, o) {
239
- return y(this, null, function* () {
238
+ sendQuestion(t, o) {
239
+ return f(this, null, function* () {
240
240
  var l;
241
241
  const {
242
- content: g,
242
+ content: m,
243
243
  fileIds: d,
244
244
  oldMessageId: s
245
- } = a, {
246
- stream: m,
245
+ } = t, {
246
+ stream: g,
247
247
  referenceFirst: e
248
248
  } = o;
249
249
  if (this.active || (yield this.activate()), this._id) {
250
250
  let n = {
251
- content: g,
251
+ content: m,
252
252
  fileIds: d,
253
253
  referenceFirst: e,
254
254
  oldMessageId: s,
255
- promptVariables: this.promptVariables.reduce((r, t) => R(f({}, r), {
256
- [t.key]: t.value
255
+ promptVariables: this.promptVariables.reduce((r, a) => R(u({}, r), {
256
+ [a.key]: a.value
257
257
  }), {}),
258
258
  knowledges: (l = this.knowledges) == null ? void 0 : l.map((r) => r.id)
259
259
  };
260
260
  this.ctrl = new AbortController(), this.postChatV3EventSource(this._applicationId, this._id, n, this.ctrl.signal, {
261
261
  onopen: () => {
262
- b.log("open", this.ctrl);
262
+ I.log("open", this.ctrl);
263
263
  },
264
264
  onmessage: (r) => {
265
265
  if (this._stopAnswer)
266
266
  return;
267
- let t = this.messages[this.messages.length - 1];
268
- t && t.role === J.Robot ? (t = f(f({}, t), r), this.messages[this.messages.length - 1] = t, this.event.emit("message:content", t), this.event.emit("message:updated", t)) : (this.pushMessage(r), this.event.emit("message:content", r));
267
+ let a = this.messages[this.messages.length - 1];
268
+ a && a.role === _.Robot ? (a = u(u({}, a), r), this.messages[this.messages.length - 1] = a, this.event.emit("message:content", a), this.event.emit("message:updated", a)) : (this.pushMessage(r), this.event.emit("message:content", r));
269
269
  },
270
- onclose: (r) => y(this, null, function* () {
271
- this._stopAnswer || (b.log(r, "onclose"), this.event.emit("answer:finish", r));
270
+ onclose: (r) => f(this, null, function* () {
271
+ this._stopAnswer || (I.log(r, "onclose"), this.event.emit("answer:finish", r));
272
272
  }),
273
273
  onerror: () => {
274
274
  this._stopAnswer || (this.event.emit("message:error", ""), this.frozen = !1);
@@ -280,7 +280,22 @@ class W extends P {
280
280
  stopAnswer() {
281
281
  this.ctrl.abort();
282
282
  }
283
+ registerMcpFromClientConfig() {
284
+ return f(this, null, function* () {
285
+ throw new Error("MCP registration is not supported by DialogSession");
286
+ });
287
+ }
288
+ addMcpServers(t) {
289
+ return f(this, null, function* () {
290
+ throw new Error("MCP registration is not supported by DialogSession");
291
+ });
292
+ }
293
+ listMcpServers() {
294
+ return f(this, null, function* () {
295
+ throw new Error("MCP registration is not supported by DialogSession");
296
+ });
297
+ }
283
298
  }
284
299
  export {
285
- W as default
300
+ H as default
286
301
  };
@@ -1,8 +1,8 @@
1
- var k = Object.defineProperty, E = Object.defineProperties;
1
+ var S = Object.defineProperty, E = Object.defineProperties;
2
2
  var V = Object.getOwnPropertyDescriptors;
3
3
  var b = Object.getOwnPropertySymbols;
4
4
  var x = Object.prototype.hasOwnProperty, Q = Object.prototype.propertyIsEnumerable;
5
- var L = (h, e, t) => e in h ? k(h, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : h[e] = t, f = (h, e) => {
5
+ var L = (h, e, t) => e in h ? S(h, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : h[e] = t, f = (h, e) => {
6
6
  for (var t in e || (e = {}))
7
7
  x.call(e, t) && L(h, t, e[t]);
8
8
  if (b)
@@ -10,19 +10,19 @@ var L = (h, e, t) => e in h ? k(h, e, { enumerable: !0, configurable: !0, writab
10
10
  Q.call(e, t) && L(h, t, e[t]);
11
11
  return h;
12
12
  }, w = (h, e) => E(h, V(e));
13
- var p = (h, e, t) => (L(h, typeof e != "symbol" ? e + "" : e, t), t);
13
+ var c = (h, e, t) => (L(h, typeof e != "symbol" ? e + "" : e, t), t);
14
14
  var r = (h, e, t) => new Promise((i, n) => {
15
15
  var o = (s) => {
16
16
  try {
17
17
  d(t.next(s));
18
- } catch (c) {
19
- n(c);
18
+ } catch (p) {
19
+ n(p);
20
20
  }
21
21
  }, l = (s) => {
22
22
  try {
23
23
  d(t.throw(s));
24
- } catch (c) {
25
- n(c);
24
+ } catch (p) {
25
+ n(p);
26
26
  }
27
27
  }, d = (s) => s.done ? i(s.value) : Promise.resolve(s.value).then(o, l);
28
28
  d((t = t.apply(h, e)).next());
@@ -31,7 +31,7 @@ import { v4 as M } from "uuid";
31
31
  import { parseJWT as R, removeNewlines as T, removeLeadingAndTrailingBackslashes as z } from "./utils.mjs";
32
32
  import { PromptStatus as O, ApplicationTypes as C, ChatMessageRole as _ } from "@glodon-aiot/apis";
33
33
  import P from "./Logger.mjs";
34
- import { configuration as S } from "./Config.mjs";
34
+ import { configuration as k } from "./Config.mjs";
35
35
  import q from "./EventBus.mjs";
36
36
  import { getCVForceService as F } from "./api/index.mjs";
37
37
  import N from "dayjs";
@@ -48,30 +48,31 @@ class $ {
48
48
  * @param client - Bot 客户端实例,可选参数。
49
49
  */
50
50
  constructor(e, t = "", i, n, o, l) {
51
- p(this, "_id");
52
- p(this, "_frozen", !1);
51
+ c(this, "_id");
52
+ c(this, "_frozen", !1);
53
53
  //是否可发送新问题
54
- p(this, "inactivating", !1);
55
- p(this, "_ready", !1);
54
+ c(this, "inactivating", !1);
55
+ c(this, "_ready", !1);
56
56
  // ready = false;
57
- p(this, "event", new q());
57
+ c(this, "event", new q());
58
58
  //从token解析出来的用户信息
59
- p(this, "_applicationId");
60
- p(this, "_application", null);
61
- p(this, "data", null);
62
- p(this, "client", null);
63
- p(this, "messages", []);
64
- p(this, "_loadingMessages", !1);
65
- p(this, "_loadingMessagesSize", 10);
66
- p(this, "cvforceApi");
67
- p(this, "socket", null);
68
- p(this, "_promptVariables", []);
69
- p(this, "active", !1);
70
- p(this, "activing", !1);
71
- p(this, "_stopAnswer", !1);
72
- p(this, "_dataLoading", !1);
73
- p(this, "_dataLoaded", !1);
74
- this.token = e, this.lazyload = n, this.client = l || null, this._applicationId = R(e).rid || S.applicationId, this.cvforceApi = this.getService(), o && (this._application = o), this.event.emit("init", {
59
+ c(this, "_applicationId");
60
+ c(this, "_application", null);
61
+ c(this, "data", null);
62
+ c(this, "client", null);
63
+ c(this, "messages", []);
64
+ c(this, "_loadingMessages", !1);
65
+ c(this, "_loadingMessagesSize", 10);
66
+ c(this, "cvforceApi");
67
+ c(this, "socket", null);
68
+ c(this, "_promptVariables", []);
69
+ c(this, "active", !1);
70
+ c(this, "activing", !1);
71
+ c(this, "_stopAnswer", !1);
72
+ c(this, "_dataLoading", !1);
73
+ c(this, "_dataLoaded", !1);
74
+ c(this, "_mcpServers", null);
75
+ this.token = e, this.lazyload = n, this.client = l || null, this._applicationId = R(e).rid || k.applicationId, this.cvforceApi = this.getService(), o && (this._application = o), this.event.emit("init", {
75
76
  applicationId: this._applicationId,
76
77
  sessionId: t
77
78
  }), this.loadApplicationInfo().then(() => {
@@ -95,13 +96,15 @@ class $ {
95
96
  name: s,
96
97
  // @ts-ignore
97
98
  netOpen: i == null ? void 0 : i.netOpen,
98
- knowledgeList: (d = i == null ? void 0 : i.knowledges) == null ? void 0 : d.map((c) => c.id),
99
+ knowledgeIdList: (d = i == null ? void 0 : i.knowledges) == null ? void 0 : d.map((p) => p.id),
99
100
  applicationId: this._applicationId
100
- }).then((c) => r(this, null, function* () {
101
- this._id = c.id, this.data = c, this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, this._id), yield (() => {
101
+ }).then((p) => r(this, null, function* () {
102
+ this._id = p.id, this.data = w(f({}, p), {
103
+ knowledges: i == null ? void 0 : i.knowledges
104
+ }), this._promptVariables = yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId, this._id), yield (() => r(this, null, function* () {
102
105
  if (i != null && i.knowledges)
103
106
  return this.setKnowledges((i == null ? void 0 : i.knowledges) || void 0);
104
- })(), yield (() => {
107
+ }))(), yield (() => {
105
108
  if (i != null && i.promptVariables) {
106
109
  const g = this._promptVariables.map((m) => {
107
110
  var a, y;
@@ -239,7 +242,7 @@ class $ {
239
242
  });
240
243
  }
241
244
  getService() {
242
- return F(S.apiRoot, this.token, (e, t) => {
245
+ return F(k.apiRoot, this.token, (e, t) => {
243
246
  const i = new Error(
244
247
  "data request error"
245
248
  /* DataRequestFailed */
@@ -275,10 +278,10 @@ class $ {
275
278
  };
276
279
  if (this._id) {
277
280
  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;
278
- const o = yield this.cvforceApi.getChatHistorySessionId(this._applicationId, this._id, e), l = o.map((s, c) => {
281
+ const o = yield this.cvforceApi.getChatHistorySessionId(this._applicationId, this._id, e), l = o.map((s, p) => {
279
282
  var v, a;
280
283
  let g = [], m;
281
- return typeof ((v = s.agentHistoryList) == null ? void 0 : v.agentList) == "string" && (g = JSON.parse(s.agentHistoryList.agentList).reduce((I, A) => (I[A.data.step - 1] || (I[A.data.step - 1] = []), I[A.data.step - 1].push(A), I), [])), c === o.length - 1 && (m = (a = this.data) == null ? void 0 : a.lastRelatedQuestion), w(f({}, s), {
284
+ return typeof ((v = s.agentHistoryList) == null ? void 0 : v.agentList) == "string" && (g = JSON.parse(s.agentHistoryList.agentList).reduce((I, A) => (I[A.data.step - 1] || (I[A.data.step - 1] = []), I[A.data.step - 1].push(A), I), [])), p === o.length - 1 && (m = (a = this.data) == null ? void 0 : a.lastRelatedQuestion), w(f({}, s), {
282
285
  actions: g,
283
286
  relatedQuesion: m
284
287
  });
@@ -287,14 +290,14 @@ class $ {
287
290
  const s = this.messages[this.messages.length - 1];
288
291
  s && !s.relatedQuesion && (s.relatedQuesion = (i = this.data) == null ? void 0 : i.lastRelatedQuestion), this.messages = [...l, ...this.messages];
289
292
  } else if (e.endTime && !e.startTime) {
290
- const s = this.messages.findIndex((c) => c.ts === e.endTime);
293
+ const s = this.messages.findIndex((p) => p.ts === e.endTime);
291
294
  this.messages.splice(0, s + 1), this.messages = [...l, ...this.messages];
292
295
  } else if (!e.endTime && e.startTime) {
293
- const s = this.messages.findLastIndex((c) => c.ts === e.endTime);
296
+ const s = this.messages.findLastIndex((p) => p.ts === e.endTime);
294
297
  this.messages.splice(s, this.messages.length - s - 1), this.messages = [...this.messages, ...l];
295
298
  } else {
296
- const s = this.messages.findIndex((g) => g.ts === e.endTime), c = this.messages.findLastIndex((g) => g.ts === e.endTime);
297
- this.messages.splice(s, c - s + 1, ...l);
299
+ const s = this.messages.findIndex((g) => g.ts === e.endTime), p = this.messages.findLastIndex((g) => g.ts === e.endTime);
300
+ this.messages.splice(s, p - s + 1, ...l);
298
301
  }
299
302
  const d = this.messages[this.messages.length - 1];
300
303
  return d && !d.relatedQuesion && (d.relatedQuesion = (n = this.data) == null ? void 0 : n.lastRelatedQuestion), this.event.emit("history:moreloaded", l), u.log("history:loaded", this.messages), this.event.emit("history:loaded", this.messages), this._loadingMessages = !1, l;
@@ -379,6 +382,8 @@ class $ {
379
382
  inactivate(e = !1) {
380
383
  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);
381
384
  }
385
+ //TODO: remove mcp server
386
+ // abstract removeMcpServers(mcpServers: MCPConfig): Promise<boolean>;
382
387
  get dataLoaded() {
383
388
  return this._dataLoaded;
384
389
  }
@@ -431,7 +436,7 @@ class $ {
431
436
  return u.error(a), this.event.emit("error", a), !1;
432
437
  }
433
438
  this.frozen = !0, this._stopAnswer = !1;
434
- const c = {
439
+ const p = {
435
440
  sessionId: this.id,
436
441
  role: 2,
437
442
  content: d,
@@ -446,7 +451,7 @@ class $ {
446
451
  fileIds: s,
447
452
  referenceFirst: o
448
453
  };
449
- this.pushMessage(c), this.event.emit("question:content", d);
454
+ this.pushMessage(p), this.event.emit("question:content", d);
450
455
  const m = (a) => r(this, null, function* () {
451
456
  if (a.role !== _.Robot)
452
457
  return;
@@ -454,7 +459,7 @@ class $ {
454
459
  finialMessage: a.content
455
460
  }), this.event.emit("data:updated", this.data), this.event.emit("data:updated:finialMessage", {
456
461
  finialMessage: a.content
457
- })), this.fillMessageReference(a), a.code) {
462
+ })), yield this.fillMessageReference(a), a.code) {
458
463
  case 11915:
459
464
  a.content = "请您换个问题问我吧~", a.index = -1, a.isSensitive = !0, a.isLoading = !1, a.sessionId = this._id || "", this.event.emit("message:error", a);
460
465
  break;
@@ -476,7 +481,7 @@ class $ {
476
481
  return this.addEventListener("answer:finish", m), this.sendQuestion(g, w(f({}, t), {
477
482
  stream: n,
478
483
  referenceFirst: o
479
- })), c;
484
+ })), p;
480
485
  });
481
486
  }
482
487
  getRelatedQuesion(e) {
@@ -541,7 +546,7 @@ class $ {
541
546
  finialMessage: s.content
542
547
  }), this.event.emit("data:updated", this.data), this.event.emit("data:updated:finialMessage", {
543
548
  finialMessage: s.content
544
- })), this.fillMessageReference(s), s.code) {
549
+ })), yield this.fillMessageReference(s), s.code) {
545
550
  case 11915:
546
551
  s.content = "请您换个问题问我吧~", s.index = -1, s.isSensitive = !0, s.isLoading = !1, s.sessionId = this._id || "", this.event.emit("message:error", s);
547
552
  break;
@@ -612,14 +617,14 @@ class $ {
612
617
  pluginName: l,
613
618
  pluginCode: d,
614
619
  funcCode: s,
615
- funcName: c
620
+ funcName: p
616
621
  } = o.data;
617
622
  n.push({
618
623
  data: {
619
624
  pluginName: l,
620
625
  pluginCode: d,
621
626
  funcCode: s,
622
- funcName: c,
627
+ funcName: p,
623
628
  step: o.data.step + 1
624
629
  },
625
630
  type: "ABORT"
package/dist/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var T=Object.getOwnPropertySymbols;var D=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var P=(r,e,t)=>e in r?se(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,u=(r,e)=>{for(var t in e||(e={}))D.call(e,t)&&P(r,t,e[t]);if(T)for(var t of T(e))B.call(e,t)&&P(r,t,e[t]);return r},w=(r,e)=>ie(r,ne(e));var F=(r,e)=>{var t={};for(var s in r)D.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&T)for(var s of T(r))e.indexOf(s)<0&&B.call(r,s)&&(t[s]=r[s]);return t};var m=(r,e,t)=>(P(r,typeof e!="symbol"?e+"":e,t),t);var p=(r,e,t)=>new Promise((s,a)=>{var o=i=>{try{c(t.next(i))}catch(d){a(d)}},n=i=>{try{c(t.throw(i))}catch(d){a(d)}},c=i=>i.done?s(i.value):Promise.resolve(i.value).then(o,n);c((t=t.apply(r,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),oe=require("axios"),I=require("@glodon-aiot/apis"),re=require("socket.io-client"),J=require("uuid"),U=require("dayjs"),R=class R{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!R.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!R.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!R.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!R.debug||console.warn(this.prefix,...e)}};m(R,"debug",!1);let S=R;const ce=new S("[Config] ");var K=(r=>(r.dev="https://aiot-dev.glodon.com/api/cvforcepd",r.test="https://aiot-dev.glodon.com/api/cvforce",r.prod="https://copilot.glodon.com/api/cvforce",r.local="http://localhost:3000/api/cvforcepd",r))(K||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},loadRelatedQuesions:!0};function G(r){S.debug=(r==null?void 0:r.debug)||!1,exports.configuration=w(u(u({},exports.configuration),r),{apiRoot:(r==null?void 0:r.apiRoot)||exports.configuration.apiRoot||(r!=null&&r.env?K[r.env||"prod"]:exports.configuration.apiRoot)}),S.debug&&ce.log("updated",exports.configuration)}const V=r=>JSON.parse(ae.decode(r.split(".")[1])),de=r=>{const e=V(r).exp;return new Date().valueOf()/1e3>=e},he=r=>r==null?void 0:r.replace(/[\r\n]+/gm,""),le=r=>r.replace(/\\|\\/g,"");function X(r,e,t){const s=d=>{var l;return e&&(de(e)&&t(403,"aiotToken is timeout"),d.headers=(l=d.headers)!=null?l:{},d.headers=w(u({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function a(d,l=!0){const h=`${r}${d}`,g=oe.create({baseURL:h});return l&&g.interceptors.request.use(s),g}const o=(d,l)=>{d===401&&t(d,"aiotToken is invalid")},n=(d,l)=>{d!==10001&&d!==10215&&t(d,l)},c=a("/data/v1");return new I.CVForceApi(c,{onHttpStatusError:o,onAppStatusError:n})}var L=(r=>(r[r.Normal=0]="Normal",r[r.Debug=1]="Debug",r))(L||{});const M=new S("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&M.disable()}getEventListenerMap(){return u({},this.eventListenerMap)}on(e,t,s=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),s?this.eventListenerMap[e].push({fn:t,once:!0}):this.eventListenerMap[e].push(t),M.log(`add event ${e} listener ${s?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const s=this.eventListenerMap[e].findIndex(a=>{if(typeof a=="function"&&t===a)return!0;if(a=a,a.fn===t)return!0});s<0?M.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),M.log(`remove event ${e} listener`))}else M.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){M.log(`event ${e} listeners is empty`);return}const s=[];for(let a=0;a<this.eventListenerMap[e].length;a++){const o=this.eventListenerMap[e][a];typeof o=="function"?o(t):s.push(o)}s.forEach(a=>{a&&(a.fn(t),this.off(e,a.fn))}),M.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const A=new S("[Session] ");var E=(r=>(r.DataRequestFailed="data request error",r.SocketConnectionFailed="socket error",r.IdUndefined="session id is not defined",r.SendingEmptyContent="failed at sending empty content",r.Frozen="session is frozen",r.UserModeError="failed at setting socket user mode",r.Inactive="session is inactive",r))(E||{});class q{constructor(e,t="",s,a,o,n){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new Z);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);this.token=e,this.lazyload=a,this.client=n||null,this._applicationId=V(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),o&&(this._application=o),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var c;if(t)this._id=t,this.event.emit("data:loading"),s?(this.data=s,a||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(i=>p(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data)})))):(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(i=>p(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoading=!1,this._dataLoaded=!0})));else{const i=(s==null?void 0:s.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:i}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:i,netOpen:s==null?void 0:s.netOpen,knowledgeList:(c=s==null?void 0:s.knowledges)==null?void 0:c.map(d=>d.id),applicationId:this._applicationId}).then(d=>p(this,null,function*(){this._id=d.id,this.data=d,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),yield(()=>{if(s!=null&&s.knowledges)return this.setKnowledges((s==null?void 0:s.knowledges)||void 0)})(),yield(()=>{if(s!=null&&s.promptVariables){const l=this._promptVariables.map(h=>{var f,v;const g=((v=(f=s.promptVariables)==null?void 0:f.find(y=>y.key===h.key))==null?void 0:v.value)||"";return w(u({},h),{value:g})}).sort((h,g)=>h.key.localeCompare(g.key));return this.setPromptVariables(l||[])}else return})(),this.event.emit("data:created",this.data),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._ready=!0,this.event.emit("ready")}))}})}fetchData(){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.getSession(this.applicationId,this.data.id).then(e=>p(this,null,function*(){return this.data=e,this.event.emit("data:updated",this.data),e}))})}get id(){var e;return this._id||((e=this.data)==null?void 0:e.id)||""}get applicationId(){return this._applicationId}get application(){return this._application}set application(e){this._application=e}loadApplicationInfo(){if(this._application)return Promise.resolve(this._application);if(this._applicationId&&!this._application)return this.event.emit("application:data:loading"),this.cvforceApi.getApplicationId(this._applicationId).then(e=>(this._application=e,this.event.emit("application:data:loaded",e),e));throw Error("application id is not defined")}get ready(){return this._ready}get frozen(){return this._frozen}set frozen(e){e===!1&&this.inactivating&&this.socket&&(this.socket.disconnect(),this.socket=null,this.event.emit("inactivated")),this._frozen=e,this.event.emit("frozen",e)}get knowledges(){if(!this.data)throw Error("session data is not loaded");return this.data.knowledges||void 0}setKnowledges(e){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(t=>t.status===I.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>e.key!=="query")}setPromptVariables(e){return p(this,null,function*(){const t=this._promptVariables.map(s=>{var o;const a=((o=e==null?void 0:e.find(n=>n.key===s.key))==null?void 0:o.value)||s.value;return w(u({},s),{value:a})}).sort((s,a)=>s.key.localeCompare(a.key));if(yield Promise.all(t.filter(s=>s.key!=="query").map(s=>{if(!this.data)throw Error("session data is not loaded");if(!(!s.id||!s.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,s.id,{value:s.value}).catch(console.error)})),!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return p(this,null,function*(){var t,s,a;if(A.log("setNetOpen:",e),A.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===I.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((a=this._application)==null?void 0:a.arrange[0].enableNetOpen)===!1){console.warn("This Application is disabled to change netOpen.");return}if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{netOpen:e?1:2}),this.data.netOpen=e,A.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return X(exports.configuration.apiRoot,this.token,(e,t)=>{const s=new Error("data request error");A.error(s),this.event.emit("error",s)})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}fetchMessages(){return p(this,arguments,function*(e={}){var s,a;const t={pageSize:this._loadingMessagesSize};if(this._id){e=u(u({},t),e),this.event.emit("history:loading"),A.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),A.log("history:moreloading",e)),this._loadingMessages=!0;const o=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),n=o.map((i,d)=>{var g,f;let l=[],h;return typeof((g=i.agentHistoryList)==null?void 0:g.agentList)=="string"&&(l=JSON.parse(i.agentHistoryList.agentList).reduce((y,_)=>(y[_.data.step-1]||(y[_.data.step-1]=[]),y[_.data.step-1].push(_),y),[])),d===o.length-1&&(h=(f=this.data)==null?void 0:f.lastRelatedQuestion),w(u({},i),{actions:l,relatedQuesion:h})});if(!e.endTime&&!e.startTime){const i=this.messages[this.messages.length-1];i&&!i.relatedQuesion&&(i.relatedQuesion=(s=this.data)==null?void 0:s.lastRelatedQuestion),this.messages=[...n,...this.messages]}else if(e.endTime&&!e.startTime){const i=this.messages.findIndex(d=>d.ts===e.endTime);this.messages.splice(0,i+1),this.messages=[...n,...this.messages]}else if(!e.endTime&&e.startTime){const i=this.messages.findLastIndex(d=>d.ts===e.endTime);this.messages.splice(i,this.messages.length-i-1),this.messages=[...this.messages,...n]}else{const i=this.messages.findIndex(l=>l.ts===e.endTime),d=this.messages.findLastIndex(l=>l.ts===e.endTime);this.messages.splice(i,d-i+1,...n)}const c=this.messages[this.messages.length-1];return c&&!c.relatedQuesion&&(c.relatedQuesion=(a=this.data)==null?void 0:a.lastRelatedQuestion),this.event.emit("history:moreloaded",n),A.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,n}else{const o=new Error("session id is not defined");return A.error(o),this.event.emit("error",o),!1}})}rename(e){return p(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),A.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return p(this,null,function*(){this.messages.push(e),A.log("history:add",e),this.event.emit("history:add",e),this.event.emit("message:new",e),this.event.emit("message:updated",e)})}reloadSessionInfo(){if(!this._id)throw Error("session is not created yet");return this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,this._id).then(e=>p(this,null,function*(){if(this.data=e,!this._id)throw Error("session is not created yet");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),A.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>p(this,null,function*(){return this.messages=[],yield this.fetchMessages(),this._dataLoading=!1,this._dataLoaded=!0,this.event.emit("data:loaded",this.data),this}))}reload(){return p(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return p(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return A.error(e),this.event.emit("error",e),!1}return this.event.emit("data:deleting"),yield this.cvforceApi.delSessionsId(this.applicationId,this.id),this.event.emit("data:deleted"),this.destroy()})}activate(){return p(this,null,function*(){if(this.activing)return new Promise(t=>{this.addEventListener("activated",()=>{t(!0)},!0)});if(!this._id)throw Error("session is not avalible. id is undefined");this.activing=!0;const e=this._id;return this._dataLoading=!0,this._dataLoaded=!1,this.data=yield this.cvforceApi.getSession(this.applicationId,e).then(t=>p(this,null,function*(){return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,e),t})),this.messages.length||(this.messages=[],yield this.fetchMessages()),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoaded=!0,this._dataLoading=!1,this.inactivating=!1,this.frozen=!0,yield this.prepareConnection(),this.event.emit("activated",this.socket),this.active=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?this._frozen?(e||(this.inactivating=!0),this.activing=!1,!0):(this.socket.close(),this.socket=null,this.event.emit("inactivated"),this.active=!1,this.activing=!1,!0):(this.activing=!1,!0)}get dataLoaded(){return this._dataLoaded}get messagesLoading(){return this._loadingMessages}send(s){return p(this,arguments,function*(e,t={stream:!1}){var g;try{this.validateConfigs()}catch(f){console.error(f)}const{stream:a=!1,referenceFirst:o=!1}=t,n=e.uuid||J.v4(),c=((g=e.text)==null?void 0:g.trim())||"",i=e.fileIds;if(!c&&!(i!=null&&i.length)){const f=new Error("failed at sending empty content");return A.error(f),this.event.emit("error",f),!1}if(!this._id){const f=new Error("session id is not defined");return A.error(f),this.event.emit("error",f),!1}if(this.frozen){const f=new Error("session is frozen");return A.error(f),this.event.emit("error",f),!1}this.frozen=!0,this._stopAnswer=!1;const d={sessionId:this.id,role:2,content:c,messageId:n,reference:[],searchReference:[],messageTime:""},l={content:c,stream:a,requestId:n,fileIds:i,referenceFirst:o};this.pushMessage(d),this.event.emit("question:content",c);const h=f=>p(this,null,function*(){if(f.role!==I.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",h),this._id&&f.content&&f.index&&f.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:f.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:f.content})),this.fillMessageReference(f),f.code){case 11915:f.content="请您换个问题问我吧~",f.index=-1,f.isSensitive=!0,f.isLoading=!1,f.sessionId=this._id||"",this.event.emit("message:error",f);break;case 200:f.index=-1,f.isLoading=!1;break;default:f.content=f.message||"未知错误",f.isLoading=!1,f.index=-1,this.event.emit("message:error",f)}this.getRelatedQuesion(f),f.isLoading=!1;let v=this.messages[this.messages.length-1];if(v&&v.role===I.ChatMessageRole.Robot){const y=u(u({},v),f);this.messages[this.messages.length-1]=y,this.event.emit("message:updated",y)}else this.pushMessage(f);this.frozen=!1});return this.addEventListener("answer:finish",h),this.sendQuestion(l,w(u({},t),{stream:a,referenceFirst:o})),d})}getRelatedQuesion(e){return p(this,null,function*(){var o,n;if(!e.content||e.isSensitive||e.code!==200||!((o=this.application)!=null&&o.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const t=yield this.cvforceApi.postGeneques({content:e.content}).catch(c=>null);if(!t){const c=[],i=w(u({},e),{relatedQuesion:c,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:c}),this.event.emit("message:updated",i),i}const s=(n=t.content)==null?void 0:n.split("*").map(he).map(le).filter(c=>!!c);e.relatedQuesion=s,e.index=-3,e.isLoading=!1;const a=w(u({},e),{relatedQuesion:s,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",a),this.event.emit("message:updated",a),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:s}),a})}fillMessageReference(e){return p(this,null,function*(){const t=yield Promise.all(e.reference.map(s=>this.cvforceApi.getKnowledgeIdFileId(s.knowledgeId,s.docId)));return e.reference=e.reference.map((s,a)=>u(u({},s),t[a])),this.event.emit("message:updated",e),e})}answerAgain(){return p(this,arguments,function*(e={stream:!1}){const t=this.messages[this.messages.length-1];if(!t)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1;const{stream:s=!1}=e;let a;t.role!==I.ChatMessageRole.User&&(a=e.oldMessageId||t.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",t),this.event.emit("history:remove",t));const o=this.messages[this.messages.length-1],n={content:o.content,fileIds:o.fileIds,requestId:o.messageId,stream:s,oldMessageId:a},c=i=>p(this,null,function*(){if(i.role===I.ChatMessageRole.Robot&&i.index===-1){switch(this._id&&i.content&&i.index&&i.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:i.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:i.content})),this.fillMessageReference(i),i.code){case 11915:i.content="请您换个问题问我吧~",i.index=-1,i.isSensitive=!0,i.isLoading=!1,i.sessionId=this._id||"",this.event.emit("message:error",i);break;case 200:i.index=-1,i.isLoading=!1;break;default:i.content=i.message||"未知错误",i.isLoading=!1,i.index=-1,this.event.emit("message:error",i)}this.getRelatedQuesion(i),this.removeEventListener("message:content",c),this.frozen=!1}});this.addEventListener("message:content",c),this.sendQuestion(n,w(u({},e),{stream:s}))})}setTop(e){return p(this,null,function*(){if(!this._id)throw Error("session is not avalible. id is undefined");this.data=yield this.cvforceApi.patchSessionsId(this._applicationId,this._id,{top:e}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:top",{top:e})})}suspend(){var s;this.stopAnswer(),this.frozen=!1,this._stopAnswer=!0;let e=this.messages[this.messages.length-1];const t={messageId:J.v4(),isLoading:!1,index:-2,messageTime:U(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:I.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const a=e.actions[((s=e.actions)==null?void 0:s.length)-1];if(a){const o=a[a.length-1];if(o&&(o.type==="BEFORE_CALL"||o.type==="FUNCTION_CALL")){const{pluginName:n,pluginCode:c,funcCode:i,funcName:d}=o.data;a.push({data:{pluginName:n,pluginCode:c,funcCode:i,funcName:d,step:o.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:a})}}}e=u(u({},e),t),this.event.emit("message:content",e),this.event.emit("message:updated",e)}else this.pushMessage(t),this.event.emit("message:content",t);return this}postMessageComment(e){return p(this,null,function*(){if(!this._applicationId||!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.postComments(this._applicationId,this._id,e).then(t=>{const s=this.messages.find(a=>a.messageId===e.messageId);return s&&(s.comment=e,this.event.emit("message:comment",s)),t})})}clear(){if(!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.patchApplicationIdSessionsIdContext(this._applicationId,this._id).then(()=>(this.event.emit("context:clear"),!0))}destroy(){var e;return this._ready=!1,this.event.removeAllListeners(),(e=this.socket)==null||e.disconnect(),this.socket=null,this.event.emit("destroy",{applicationId:this._applicationId,sessionId:this._id}),this._id||""}}const k=new S("[AgentSession] ");class fe extends q{constructor(e,t="",s,a,o,n){super(e,t,s,a,o,n)}prepareConnection(){return new Promise(e=>p(this,null,function*(){this.socket&&e(!0);const t={version:"1.0",stream:"false",appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?L.Debug:L.Normal},s=new URL(exports.configuration.apiRoot),a=yield re.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});a.on("connect",()=>{k.log("socket:connect"),this.event.emit("socket:connect"),a.emit("init")}),a.on("disconnect",()=>{k.log("socket:disconnect"),this.event.emit("socket:disconnect")}),a.on("ready",o=>{if(o.code===200){k.log("ready");const n=exports.configuration.debug?L.Debug:L.Normal;n===L.Debug&&o.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,e(!0)}else{this._ready&&(this._ready=!1);const n=new Error(E.SocketConnectionFailed);k.error("error",n),this.event.emit("error",n),e(!1)}}),a.on("action",(o,n)=>p(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:c,data:{runnerIsClient:i,pluginCode:d,funcCode:l,parameters:h,requestBody:g}}=o,f=this.messages[this.messages.length-1];if(!f.messageId)f.actions||(f.actions=[]),f.actions[o.data.step-1]||(f.actions[o.data.step-1]=[]),f.actions[o.data.step-1].push(o),this.event.emit("message:action",{messageId:f.messageId,action:o}),this.event.emit("message:updated",f);else{const v={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[o]],comment:{isAgree:0}};this.pushMessage(v),this.event.emit("message:action",{messageId:v.messageId,action:o})}if(this.inactivating){const v=new Error(E.Inactive);k.warn("error",v),this.event.emit("error",v)}else if(c==="FUNCTION_CALL"&&i){if(k.log(`calling function ${l} of plugin ${d} with argument:
2
- ${JSON.stringify(h)}`),!exports.configuration.plugins[d]){n({code:404,message:"对不起,没有找到插件。"});return}const v=exports.configuration.plugins[d][l];typeof v!="function"&&n({code:404,message:"对不起,没有找到插件方法。"});let y=h==null?void 0:h.query;try{y=JSON.parse(h==null?void 0:h.query)}catch(_){}v(y,(..._)=>{this._stopAnswer||n(..._)})}})),a.on("answer",o=>{if(!this._stopAnswer)if(o.data.code!==200&&(o.data.index=-1,this.event.emit("error",o.data)),o.data.index===-1){let n=this.messages[this.messages.length-1];if(n&&!n.messageId)n=u(u({},n),o.data),this.event.emit("message:content",n),this.event.emit("message:updated",n),this.event.emit("answer:finish",n);else{const c=u({messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0}},o.data);this.event.emit("message:content",c),this.pushMessage(c),this.event.emit("answer:finish",c)}}else{let n=this.messages[this.messages.length-1];n&&!n.messageId?(n=u(u({},n),o.data),this.messages[this.messages.length-1]=n,this.event.emit("message:content",n),this.event.emit("message:updated",n)):(this.pushMessage(o.data),this.event.emit("message:content",o.data))}}),a.on("reference",o=>p(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const h=new Error(E.IdUndefined);k.error(h),this.event.emit("error",h),this.frozen=!1;return}const{type:n,data:c,requestId:i}=o,d=this.messages.findIndex(h=>h.messageId===i&&h.role===I.ChatMessageRole.User);if(d<0)return;const l=d+1;if(l>=this.messages.length){const h={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0}};this.pushMessage(h)}n==="KG"?(this.messages[l]=w(u({},this.messages[l]),{reference:c.knowledgeReference}),yield this.fillMessageReference(this.messages[l]),this.event.emit("message:reference",c.knowledgeReference),this.event.emit("message:updated",this.messages[l])):n==="WEB_SEARCH"&&(this.messages[l]=w(u({},this.messages[l]),{searchReference:c.knowledgeReference}),this.event.emit("message:searchreference",c.searchReference),this.event.emit("message:updated",this.messages[l]))})),this.socket=a,a.open()}))}sendQuestion(e,t){return p(this,null,function*(){var a,o,n;let s=w(u({},e),{promptVariables:this.promptVariables.reduce((c,i)=>w(u({},c),{[i.key]:i.value}),{}),knowledges:(a=this.knowledges)==null?void 0:a.map(c=>c.id)});if(!this.active){if(yield this.activate(),!this.socket){const c=new Error(E.SocketConnectionFailed);return k.warn("error",c),this.event.emit("error",c),!1}(o=this.socket)==null||o.emit("question",s);return}(n=this.socket)==null||n.emit("question",s)})}stopAnswer(){var e;(e=this.socket)==null||e.emit("stop_answer")}}function ge(r,e){return p(this,null,function*(){const t=r.getReader();let s;for(;!(s=yield t.read()).done;)e(s.value)})}function pe(r){let e,t,s,a=!1,o;return function(c){e===void 0?(e=c,t=0,s=-1,o=!1):e=me(e,c);const i=e.length;let d=0;for(;t<i;){a&&(e[t]===10&&(d=++t),a=!1);let l=-1;for(;t<i&&l===-1;++t)switch(e[t]){case 58:s===-1&&(s=t-d);break;case 13:a=!1,t+4<i&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(o=!0);case 10:l=t;break}if(l===-1)break;r(e.subarray(d,l),s,o),d=t,s=-1,o=!1}d===i?e=void 0:d!==0&&(e=e.subarray(d),t-=d)}}function ue(r,e,t){let s=j();const a=new TextDecoder;return function(n,c,i){if(n.length===0)t==null||t(s),s=j();else if(c>0){const d=a.decode(n.subarray(0,c)),l=c+(n[c+1]===32?2:1);let h=a.decode(n.subarray(l));switch(i&&(h+=`
3
- `),d){case"data":s.data=s.data?s.data+`
4
- `+h:h;break;case"event":s.event=h;break;case"id":r(s.id=h);break;case"retry":const g=parseInt(h,10);isNaN(g)||e(s.retry=g);break}}}}function me(r,e){const t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function j(){return{data:"",event:"",id:"",retry:void 0}}const z="text/event-stream",ve=1e3,H="last-event-id";function Y(r,l){var h=l,{signal:e,headers:t,onopen:s,onmessage:a,onclose:o,onerror:n,openWhenHidden:c,fetch:i}=h,d=F(h,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,f)=>{const v=u({},t);v.accept||(v.accept=z);let y;function _(){y.abort(),document.hidden||$()}c||document.addEventListener("visibilitychange",_);let x=ve,O=0;function Q(){document.removeEventListener("visibilitychange",_),window.clearTimeout(O),y.abort()}e==null||e.addEventListener("abort",()=>{Q(),g()});const ee=i!=null?i:window.fetch,te=s!=null?s:ye;function $(){return p(this,null,function*(){var N;y=new AbortController;try{const C=yield ee(r,w(u({},d),{headers:v,signal:y.signal}));yield te(C),yield ge(C.body,pe(ue(b=>{b?v[H]=b:delete v[H]},b=>{x=b},a))),o==null||o(),Q(),g()}catch(C){if(!y.signal.aborted)try{const b=(N=n==null?void 0:n(C))!=null?N:x;window.clearTimeout(O),O=window.setTimeout($,b)}catch(b){Q(),f(b)}}})}$()})}function ye(r){const e=r.headers.get("content-type");if(!(e!=null&&e.startsWith(z)))throw new Error(`Expected content-type to be ${z}, Actual: ${e}`)}const W=new S("[DialogSession] ");class we extends q{constructor(t,s="",a,o,n,c){super(t,s,a,o,n,c);m(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>p(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,s,a,o,n,c){return p(this,null,function*(){const i={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=w(u({},a),{stream:!0});Y(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:o,onopen(l){return l.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(l){if(!l.data.includes('{"code": ')){let g={};try{g=JSON.parse(l.data)}catch(v){}(g==null?void 0:g.mtype)==="search"?i.searchReference.push(g):i.content=i.content+l.data;const f={content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:s,messageTime:U(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(n==null?void 0:n.onmessage)&&n.onmessage(f)}const h=JSON.parse(l.data);if(i.reference=h.data.reference,i.searchReference=h.data.searchReference,i.messageTime=h.data.messageTime,i.messageId=h.data.messageId,i.llmModel=h.data.llmModel,i.content=h.data.content,i.code=h.code,h.code===200){const g={code:i.code,content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:s,messageTime:i.messageTime,isReplying:!0};n!=null&&n.onmessage&&n.onmessage(g)}else return n!=null&&n.onclose&&n.onclose(i),c&&c({code:i.code,message:i.message})},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const l={code:i.code,content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:s,messageTime:i.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};n!=null&&n.onclose&&n.onclose(l)}})})}postChatV3EventSource(t,s,a,o,n,c){return p(this,null,function*(){const i={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},d=w(u({},a),{stream:!0});Y(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:o,onopen(l){return l.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(l){if(!l.data&&!l.event&&!l.id&&!l.retry)return;let h={};try{h=JSON.parse(l.data)}catch(y){console.error("parse eventData to JSON failed. ",l.data)}if(h.code!==200)return i.index=-1,i.code=h.code,i.message=h.message,n!=null&&n.onmessage&&n.onmessage(i),c&&c({code:h.code,message:h.message});const g=h.data.type,f=h.data.payload;i.isReplying=!0;const v=()=>{if(!i.searchingStatus){i.searchingStatus="start";return}if(i.searchingStatus==="start"){i.searchingStatus="end";return}};if(g==="beforeSearch"&&v(),g==="searchOver"&&v(),g==="search"&&i.searchReference.push(f),g==="thinking"){i.thinkingStatus="start";const _=f.choices[0];i.reasoningContent=i.reasoningContent+_.delta.reasoningContent}if(g==="thinkingOver"){i.thinkingStatus="end";const y=f.thinkingSecs;i.thinkingSecs=y}if(g==="text"){const _=f.choices[0];i.content=i.content+_.delta.content}if(g==="reference"&&(i.reference=f),g==="result"){const y=f.messageId,_=f.llmModel,x=f.messageTime;i.messageId=y,i.llmModel=_,i.messageTime=x,i.sessionId=s}g==="over"?i.index=-1:(i.code=h.code,i.message=h.message),n!=null&&n.onmessage&&n.onmessage(i)},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const l=w(u({},i),{isReplying:!1});n!=null&&n.onclose&&n.onclose(l)}})})}sendQuestion(t,s){return p(this,null,function*(){var d;const{content:a,fileIds:o,oldMessageId:n}=t,{stream:c,referenceFirst:i}=s;if(this.active||(yield this.activate()),this._id){let l={content:a,fileIds:o,referenceFirst:i,oldMessageId:n,promptVariables:this.promptVariables.reduce((h,g)=>w(u({},h),{[g.key]:g.value}),{}),knowledges:(d=this.knowledges)==null?void 0:d.map(h=>h.id)};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,l,this.ctrl.signal,{onopen:()=>{W.log("open",this.ctrl)},onmessage:h=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===I.ChatMessageRole.Robot?(g=u(u({},g),h),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(h),this.event.emit("message:content",h))},onclose:h=>p(this,null,function*(){this._stopAnswer||(W.log(h,"onclose"),this.event.emit("answer:finish",h))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}}const Ie=new S("[BotClient] ");class _e{constructor(e,t,s=!0){m(this,"event",new Z);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=s,G(t),this._applicationId=V(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(()=>{this.event.emit("ready")})}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return p(this,null,function*(){var t,s,a;this._application=yield this.cvforceApi.getApplicationId(this._applicationId).then(o=>(typeof o.arrange[0].recommendQuestionOpen!="boolean"&&(o.arrange[0].recommendQuestionOpen=!0),w(u({},o),{arrange:[w(u({},o.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&o.arrange[0].recommendQuestionOpen})]})));const e=(a=(s=(t=this._application)==null?void 0:t.arrange)==null?void 0:s[0])==null?void 0:a.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(o=>o.maxModelLength)),this._promptVariables=yield this.cvforceApi.getPrompts(this._applicationId),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:X(exports.configuration.apiRoot,this.token,(e,t)=>Ie.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=V(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,s,a,o){return p(this,null,function*(){const n=this;return new Promise((c,i)=>{const d=l=>p(this,null,function*(){if(l===I.ApplicationTypes.Agent)c(new fe(e,t,s,a,o,n));else if(l===I.ApplicationTypes.Dialog)c(new we(e,t,s,a,o,n));else throw Error(`不支持的应用类型:${l}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return p(this,null,function*(){return new Promise((t,s)=>{const a=()=>this.cvforceApi.listSessions(this._applicationId,e).then(o=>{const n=[];return o.forEach(c=>p(this,null,function*(){const i=this._sessions.find(d=>c.id===d.id);if(i)i.data=c,this._application?i.application=this._application:i.loadApplicationInfo(),n.push(i);else{const d=yield this.createSession(this.token,c.id,c,this.lazyload,this._application||void 0);n.push(d)}})),this.sessions=n,n});if(this.ready){if(!this._application)throw Error("_application is null");t(a())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(a())},!0)})})}loadSession(e="",t){return p(this,null,function*(){this.checkReady();let s=this.sessions.find(a=>a.id===e);if(s||(s=yield this.createSession(this.token,e,t),this._sessions.push(s)),this._activeSession){if(this._activeSession===s)return s;this._activeSession.inactivate()}return s.id?(yield s.activate(),this._activeSession=s):s.addEventListener("data:loaded",()=>{this._activeSession!==s&&(s==null||s.activate(),this._activeSession=s)},!0),s})}reload(){return this.loadApplication().then(()=>p(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return p(this,null,function*(){yield this.reload();let t=this._sessions.find(s=>s.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,s="top_time desc, sort_status desc, updated_at desc"){return p(this,null,function*(){let a=e?this._sessions.find(o=>o.id===e):this._activeSession;if(!a){console.warn("setTop session failed.");return}return yield a.setTop(t),this.getSessions({order:s})})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return p(this,null,function*(){this.checkReady();let s=-1;if(typeof e=="string"?s=this._sessions.findIndex(a=>a.id===e):s=this._sessions.findIndex(a=>a.id===e.id),s>-1){const a=this._sessions[s];t&&(yield a.delete()),this._sessions.splice(s,1)}else console.warn("session delete failed, session is not exist.")})}clean(){this._sessions.forEach(e=>e.destroy()),this.sessions=[]}}class Ae{constructor(e,t={},s){m(this,"code");m(this,"description","");m(this,"loaded",!1);m(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}exports.AgentPlugin=Ae;exports.BotClient=_e;exports.Session=q;exports.configure=G;
1
+ "use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var T=Object.getOwnPropertySymbols;var D=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var $=(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={}))D.call(e,s)&&$(o,s,e[s]);if(T)for(var s of T(e))B.call(e,s)&&$(o,s,e[s]);return o},w=(o,e)=>ie(o,ne(e));var F=(o,e)=>{var s={};for(var t in o)D.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&&B.call(o,t)&&(s[t]=o[t]);return s};var m=(o,e,s)=>($(o,typeof e!="symbol"?e+"":e,s),s);var g=(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"),U=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 M=R;const ce=new M("[Config] ");var K=(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))(K||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0};function G(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?K[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,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}`,p=re.create({baseURL:h});return l&&p.interceptors.request.use(t),p}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 M("[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 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,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=>g(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,s)})).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,s).then(i=>g(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,s)})).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=(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=>g(this,null,function*(){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(()=>g(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 l=this._promptVariables.map(h=>{var f,v;const p=((v=(f=t.promptVariables)==null?void 0:f.find(y=>y.key===h.key))==null?void 0:v.value)||"";return w(u({},h),{value:p})}).sort((h,p)=>h.key.localeCompare(p.key));return this.setPromptVariables(l||[])}else return})(),this.event.emit("data:created",this.data),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._ready=!0,this.event.emit("ready")}))}})}fetchData(){return 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(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.key!=="query")}setPromptVariables(e){return g(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.key!=="query").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 g(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 g(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 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=(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 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(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=>g(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 g(this,arguments,function*(e,s={stream:!1}){var p;try{this.validateConfigs()}catch(f){console.error(f)}const{stream:a=!1,referenceFirst:r=!1}=s,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({},s),{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 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 g(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 g(this,arguments,function*(e={stream:!1}){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=!1}=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=>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:t}))})}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 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:U(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:I.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const a=e.actions[((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 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(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 k=new M("[AgentSession] ");class fe extends q{constructor(e,s="",t,a,r,n){super(e,s,t,a,r,n)}prepareConnection(){return new Promise(e=>g(this,null,function*(){this.socket&&e(!0);const s={version:"1.0",stream:"false",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",()=>{k.log("socket:connect"),this.event.emit("socket:connect"),a.emit("init")}),a.on("disconnect",()=>{k.log("socket:disconnect"),this.event.emit("socket:disconnect")}),a.on("ready",r=>{if(r.code===200){k.log("ready");const n=exports.configuration.debug?L.Debug:L.Normal;n===L.Debug&&r.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const 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,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 g(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 g(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 g(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 k.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 ge(o,e){return g(this,null,function*(){const s=o.getReader();let t;for(;!(t=yield s.read()).done;)e(t.value)})}function pe(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=J();const a=new TextDecoder;return function(n,c,i){if(n.length===0)s==null||s(t),t=J();else if(c>0){const d=a.decode(n.subarray(0,c)),l=c+(n[c+1]===32?2:1);let h=a.decode(n.subarray(l));switch(i&&(h+=`
3
+ `),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 p=parseInt(h,10);isNaN(p)||e(t.retry=p);break}}}}function me(o,e){const s=new Uint8Array(o.length+e.length);return s.set(o),s.set(e,o.length),s}function J(){return{data:"",event:"",id:"",retry:void 0}}const z="text/event-stream",ve=1e3,H="last-event-id";function Y(o,l){var h=l,{signal:e,headers:s,onopen:t,onmessage:a,onclose:r,onerror:n,openWhenHidden:c,fetch:i}=h,d=F(h,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((p,f)=>{const v=u({},s);v.accept||(v.accept=z);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=t!=null?t:ye;function Q(){return g(this,null,function*(){var N;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[H]=b:delete v[H]},b=>{E=b},a))),r==null||r(),O(),p()}catch(x){if(!y.signal.aborted)try{const b=(N=n==null?void 0:n(x))!=null?N: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(z)))throw new Error(`Expected content-type to be ${z}, Actual: ${e}`)}const W=new M("[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=>g(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,s(!0)}))}postChatV2EventSource(s,t,a,r,n,c){return g(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:!0});Y(`${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 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:t,messageTime:U(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(n==null?void 0:n.onmessage)&&n.onmessage(f)}const h=JSON.parse(l.data);if(i.reference=h.data.reference,i.searchReference=h.data.searchReference,i.messageTime=h.data.messageTime,i.messageId=h.data.messageId,i.llmModel=h.data.llmModel,i.content=h.data.content,i.code=h.code,h.code===200){const p={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(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: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 g(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:!0});Y(`${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 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=t}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(s,t){return g(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,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:()=>{W.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||(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 g(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(s){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,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,G(s),this._applicationId=P(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(()=>{this.event.emit("ready")})}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return g(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 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,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 g(this,null,function*(){return new Promise((s,t)=>{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");s(a())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");s(a())},!0)})})}loadSession(e="",s){return g(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(()=>g(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return g(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 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(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 g(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=G;
@@ -1,9 +1,13 @@
1
1
  import { IApplication, ISession } from '@glodon-aiot/apis';
2
+ import { MCPConfig } from './Config';
2
3
  import { default as Session, QuestionBody, QuestionConfig } from './Session';
3
4
  import { default as BotClient } from './BotClient';
4
5
  export default class AgentSession extends Session {
5
6
  constructor(token: string, _id?: string, _data?: Partial<ISession>, lazyload?: boolean, application?: IApplication, client?: BotClient);
6
7
  prepareConnection(): Promise<boolean>;
8
+ registerMcpFromClientConfig(): Promise<boolean>;
9
+ addMcpServers(mcpServers: MCPConfig): Promise<boolean>;
10
+ listMcpServers(): Promise<MCPConfig>;
7
11
  sendQuestion(questionBody: QuestionBody, configs: QuestionConfig): Promise<false | undefined>;
8
12
  stopAnswer(): void;
9
13
  }
@@ -1,3 +1,19 @@
1
+ export interface McpSSEServer {
2
+ type: 'sse';
3
+ url: string;
4
+ headers?: Record<string, string>;
5
+ }
6
+ export interface McpPluginServer {
7
+ type: 'plugin';
8
+ headers?: Record<string, string>;
9
+ pluginId: string;
10
+ }
11
+ export type McpServer = McpSSEServer | McpPluginServer;
12
+ export interface MCPConfig {
13
+ mcpServers: {
14
+ [key: string]: McpServer;
15
+ };
16
+ }
1
17
  export interface BotClientConfig {
2
18
  debug?: boolean;
3
19
  env?: Env;
@@ -5,6 +21,7 @@ export interface BotClientConfig {
5
21
  plugins?: AgentPluginMap;
6
22
  apiRoot?: string;
7
23
  loadRelatedQuesions?: boolean;
24
+ mcp?: MCPConfig;
8
25
  }
9
26
  export interface AgentPluginRegistor {
10
27
  [key: string]: Function;
@@ -25,6 +42,7 @@ export declare let configuration: {
25
42
  apiRoot: string;
26
43
  applicationId: string;
27
44
  plugins: AgentPluginMap;
45
+ mcp: (MCPConfig | undefined);
28
46
  loadRelatedQuesions: boolean;
29
47
  };
30
48
  /**
@@ -1,5 +1,6 @@
1
1
  import { IApplication, ISession } from '@glodon-aiot/apis';
2
2
  import { default as Session, QuestionBody, QuestionConfig } from './Session';
3
+ import { MCPConfig } from './Config';
3
4
  import { default as BotClient } from './BotClient';
4
5
  export default class DialogSession extends Session {
5
6
  private ctrl;
@@ -19,4 +20,7 @@ export default class DialogSession extends Session {
19
20
  }, onAppStatusError?: (error: any) => void): Promise<void>;
20
21
  sendQuestion(questionBody: QuestionBody, configs: QuestionConfig): Promise<void>;
21
22
  stopAnswer(): void;
23
+ registerMcpFromClientConfig(): Promise<boolean>;
24
+ addMcpServers(mcpServers: MCPConfig): Promise<boolean>;
25
+ listMcpServers(): Promise<MCPConfig>;
22
26
  }
@@ -1,4 +1,5 @@
1
1
  import { ChatMessageRole, IApplication, IChatMessage, ICommentParam, ISession, ISessionPrompt, CVForceApi, ChatHistoryParams, IKnowledge } from '@glodon-aiot/apis';
2
+ import { MCPConfig } from './Config';
2
3
  import { Socket } from 'socket.io-client';
3
4
  import { default as EventBus } from './EventBus';
4
5
  import { ActionPayload, PluginFunctionBasic, Thought } from './PayloadTypes';
@@ -69,6 +70,7 @@ export default abstract class Session {
69
70
  protected _stopAnswer: boolean;
70
71
  private _dataLoading;
71
72
  private _dataLoaded;
73
+ protected _mcpServers: MCPConfig | null;
72
74
  /**
73
75
  * Session 类的构造函数,用于初始化会话实例。
74
76
  * @param token - 用户的身份验证令牌,用于解析应用 ID。
@@ -162,6 +164,9 @@ export default abstract class Session {
162
164
  abstract prepareConnection(): Promise<boolean>;
163
165
  abstract sendQuestion(params: QuestionBody, configs: QuestionConfig): any;
164
166
  abstract stopAnswer(): any;
167
+ abstract registerMcpFromClientConfig(): Promise<boolean>;
168
+ abstract addMcpServers(mcpServers: MCPConfig): Promise<boolean>;
169
+ abstract listMcpServers(): Promise<MCPConfig>;
165
170
  get dataLoaded(): boolean;
166
171
  get messagesLoading(): boolean;
167
172
  send(params: {
@@ -206,4 +211,12 @@ export default abstract class Session {
206
211
  */
207
212
  destroy(): string;
208
213
  }
214
+ export declare class DialogSession extends Session {
215
+ prepareConnection(): Promise<boolean>;
216
+ sendQuestion(params: QuestionBody, configs: QuestionConfig): Promise<void>;
217
+ stopAnswer(): void;
218
+ registerMcpFromClientConfig(): Promise<boolean>;
219
+ addMcpServers(mcpServers: MCPConfig): Promise<boolean>;
220
+ listMcpServers(): Promise<MCPConfig>;
221
+ }
209
222
  export {};
@@ -1,4 +1,4 @@
1
- export type { AgentPluginRegistor, AgentPluginMap } from './Config';
1
+ export type { AgentPluginRegistor, AgentPluginMap, MCPConfig, McpServer } from './Config';
2
2
  export { configure, configuration } from './Config';
3
3
  export { default as BotClient } from './BotClient';
4
4
  export { default as Session } from './Session';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glodon-aiot/agent-cli-sdk",
3
- "version": "3.2.10-beta.8",
3
+ "version": "3.3.0-beta.13",
4
4
  "author": "glodoncv",
5
5
  "description": "aiot agent client js sdk",
6
6
  "type": "module",
@@ -79,7 +79,7 @@
79
79
  "registry": "https://registry.npmjs.org/"
80
80
  },
81
81
  "dependencies": {
82
- "@glodon-aiot/apis": "^3.2.10-beta.8",
82
+ "@glodon-aiot/apis": "^3.3.0-beta.13",
83
83
  "axios": "0.24.0",
84
84
  "buffer": "^6.0.3",
85
85
  "dayjs": "^1.11.13",