@glodon-aiot/agent-cli-sdk 3.25.0-alpha.9 → 3.25.0

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,39 +1,39 @@
1
- var R = Object.defineProperty, S = Object.defineProperties;
2
- var b = Object.getOwnPropertyDescriptors;
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) => {
1
+ var b = Object.defineProperty, A = Object.defineProperties;
2
+ var E = Object.getOwnPropertyDescriptors;
3
+ var R = Object.getOwnPropertySymbols;
4
+ var q = Object.prototype.hasOwnProperty, x = Object.prototype.propertyIsEnumerable;
5
+ var S = (d, t, n) => t in d ? b(d, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : d[t] = n, g = (d, t) => {
6
6
  for (var n in t || (t = {}))
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]);
7
+ q.call(t, n) && S(d, n, t[n]);
8
+ if (R)
9
+ for (var n of R(t))
10
+ x.call(t, n) && S(d, n, t[n]);
11
11
  return d;
12
- }, k = (d, t) => S(d, b(t));
12
+ }, k = (d, t) => A(d, E(t));
13
13
  var v = (d, t, n) => new Promise((r, i) => {
14
14
  var s = (c) => {
15
15
  try {
16
16
  o(n.next(c));
17
- } catch (g) {
18
- i(g);
17
+ } catch (h) {
18
+ i(h);
19
19
  }
20
20
  }, e = (c) => {
21
21
  try {
22
22
  o(n.throw(c));
23
- } catch (g) {
24
- i(g);
23
+ } catch (h) {
24
+ i(h);
25
25
  }
26
26
  }, o = (c) => c.done ? r(c.value) : Promise.resolve(c.value).then(s, e);
27
27
  o((n = n.apply(d, t)).next());
28
28
  });
29
29
  import { ChatMessageRole as I } from "@glodon-aiot/apis";
30
- import q from "./Logger.mjs";
31
- import { configuration as f } from "./Config.mjs";
32
- import { io as x } from "socket.io-client";
30
+ import L from "./Logger.mjs";
31
+ import { configuration as u } from "./Config.mjs";
32
+ import { io as N } from "socket.io-client";
33
33
  import { UserMode as w } from "./PayloadTypes.mjs";
34
- import L, { SessionErrors as y } from "./Session.mjs";
35
- const p = new q("[AgentSession] ");
36
- class D extends L {
34
+ import O, { SessionErrors as y } from "./Session.mjs";
35
+ const p = new L("[AgentSession] ");
36
+ class B extends O {
37
37
  constructor(t, n = "", r, i, s, e) {
38
38
  super(t, n, r, i, s, e);
39
39
  }
@@ -42,12 +42,12 @@ class D extends L {
42
42
  this.socket && t(!0);
43
43
  const n = {
44
44
  version: "1.0",
45
- stream: JSON.stringify(f.stream === void 0 ? !0 : f.stream),
45
+ stream: JSON.stringify(u.stream === void 0 ? !0 : u.stream),
46
46
  appId: this._applicationId,
47
47
  sessionId: this.id,
48
48
  Authorization: `${this.token}`,
49
- userMode: f.debug ? w.Debug : w.Normal
50
- }, r = new URL(f.apiRoot), i = yield x(r.origin, {
49
+ userMode: u.debug ? w.Debug : w.Normal
50
+ }, r = new URL(u.apiRoot), i = yield N(r.origin, {
51
51
  path: r.pathname.replace("api", "socketio") + "/copilot",
52
52
  query: n,
53
53
  transports: ["websocket"]
@@ -59,7 +59,7 @@ class D extends L {
59
59
  }), i.on("ready", (s) => {
60
60
  if (s.code === 200) {
61
61
  p.log("ready");
62
- const e = f.debug ? w.Debug : w.Normal;
62
+ const e = u.debug ? w.Debug : w.Normal;
63
63
  e === w.Debug && s.userMode, this._ready = !0, this.event.emit("ready"), this.frozen = !1, this.registerMcpFromClientConfig(), t(!0);
64
64
  } else {
65
65
  this._ready && (this._ready = !1);
@@ -72,25 +72,26 @@ class D extends L {
72
72
  p.error("error", e), this.event.emit("error", e), t(!1);
73
73
  }
74
74
  }), i.on("action", (s, e) => v(this, null, function* () {
75
+ var M;
75
76
  if (this._stopAnswer || !this.id)
76
77
  return;
77
78
  const {
78
79
  type: o,
79
80
  data: {
80
81
  runnerIsClient: c,
81
- pluginCode: g,
82
+ pluginCode: h,
82
83
  funcCode: m,
83
84
  parameters: a,
84
- requestBody: N
85
+ requestBody: U
85
86
  }
86
- } = s, l = this.messages[this.messages.length - 1];
87
- if (!l.messageId)
88
- l.actions || (l.actions = []), l.actions[s.data.step - 1] || (l.actions[s.data.step - 1] = []), l.actions[s.data.step - 1].push(s), this.event.emit("message:action", {
89
- messageId: l.messageId,
87
+ } = s, f = this.messages[this.messages.length - 1];
88
+ if (!f.messageId)
89
+ f.actions || (f.actions = []), f.actions[s.data.step - 1] || (f.actions[s.data.step - 1] = []), f.actions[s.data.step - 1].push(s), this.event.emit("message:action", {
90
+ messageId: f.messageId,
90
91
  action: s
91
- }), this.event.emit("message:updated", l);
92
+ }), this.event.emit("message:updated", f);
92
93
  else {
93
- const u = {
94
+ const l = {
94
95
  messageId: "",
95
96
  content: "",
96
97
  role: I.Robot,
@@ -104,13 +105,13 @@ class D extends L {
104
105
  isAgree: 0
105
106
  }
106
107
  };
107
- this.pushMessage(u), this.event.emit("message:action", {
108
- messageId: u.messageId,
108
+ this.pushMessage(l), this.event.emit("message:action", {
109
+ messageId: l.messageId,
109
110
  action: s
110
111
  });
111
112
  }
112
113
  if (this.inactivating) {
113
- const u = new Error(
114
+ const l = new Error(
114
115
  y.Inactive
115
116
  // {
116
117
  // cause: {
@@ -120,28 +121,33 @@ class D extends L {
120
121
  // },
121
122
  // }
122
123
  );
123
- p.warn("error", u), this.event.emit("error", u);
124
+ p.warn("error", l), this.event.emit("error", l);
124
125
  } else if (o === "FUNCTION_CALL" && c) {
125
- if (p.log(`calling function ${m} of plugin ${g} with argument:
126
- ${JSON.stringify(a)}`), !f.plugins[g]) {
126
+ p.log(`calling function ${m} of plugin ${h} with argument:
127
+ ${JSON.stringify(a)}`);
128
+ const l = (M = u.plugins) == null ? void 0 : M[h];
129
+ if (!l) {
127
130
  e({
128
131
  code: 404,
129
- message: "对不起,没有找到插件。"
132
+ message: "没有找到插件。"
130
133
  });
131
134
  return;
132
135
  }
133
- const u = f.plugins[g][m];
134
- typeof u != "function" && e({
135
- code: 404,
136
- message: "对不起,没有找到插件方法。"
137
- });
138
- let M = a == null ? void 0 : a.query;
136
+ const C = l[m];
137
+ if (typeof C != "function") {
138
+ e({
139
+ code: 404,
140
+ message: "没有找到插件方法。"
141
+ });
142
+ return;
143
+ }
144
+ let _ = a == null ? void 0 : a.query;
139
145
  try {
140
- M = JSON.parse(a == null ? void 0 : a.query);
141
- } catch (C) {
146
+ _ = JSON.parse(a == null ? void 0 : a.query);
147
+ } catch (P) {
142
148
  }
143
- u(M, (...C) => {
144
- this._stopAnswer || e(...C);
149
+ C(_, (...P) => {
150
+ this._stopAnswer || e(...P);
145
151
  });
146
152
  }
147
153
  })), i.on("answer", (s) => {
@@ -149,9 +155,9 @@ class D extends L {
149
155
  if (s.data.code !== 200 && (s.data.index = -1, this.event.emit("error", s.data)), s.data.index === -1) {
150
156
  let e = this.messages[this.messages.length - 1];
151
157
  if (e && !e.messageId)
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);
158
+ e = g(g({}, e), s.data), this.event.emit("message:content", e), this.event.emit("message:updated", e), this.event.emit("answer:finish", e);
153
159
  else {
154
- const o = h({
160
+ const o = g({
155
161
  messageId: "",
156
162
  content: "",
157
163
  role: I.Robot,
@@ -169,7 +175,7 @@ class D extends L {
169
175
  }
170
176
  } else {
171
177
  let e = this.messages[this.messages.length - 1];
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));
178
+ e && !e.messageId ? (e = g(g({}, 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
179
  }
174
180
  }), i.on("reference", (s) => v(this, null, function* () {
175
181
  if (this._stopAnswer)
@@ -188,10 +194,10 @@ class D extends L {
188
194
  type: e,
189
195
  data: o,
190
196
  requestId: c
191
- } = s, g = this.messages.findIndex((a) => a.messageId === c && a.role === I.User);
192
- if (g < 0)
197
+ } = s, h = this.messages.findIndex((a) => a.messageId === c && a.role === I.User);
198
+ if (h < 0)
193
199
  return;
194
- const m = g + 1;
200
+ const m = h + 1;
195
201
  if (m >= this.messages.length) {
196
202
  const a = {
197
203
  messageId: "",
@@ -209,21 +215,21 @@ class D extends L {
209
215
  };
210
216
  this.pushMessage(a);
211
217
  }
212
- e === "KG" ? (this.messages[m] = k(h({}, this.messages[m]), {
218
+ e === "KG" ? (this.messages[m] = k(g({}, this.messages[m]), {
213
219
  reference: o.knowledgeReference
214
- }), yield this.fillMessageReference(this.messages[m]), this.event.emit("message:reference", o.knowledgeReference), this.event.emit("message:updated", this.messages[m])) : e === "WEB_SEARCH" && (this.messages[m] = k(h({}, this.messages[m]), {
220
+ }), yield this.fillMessageReference(this.messages[m]), this.event.emit("message:reference", o.knowledgeReference), this.event.emit("message:updated", this.messages[m])) : e === "WEB_SEARCH" && (this.messages[m] = k(g({}, this.messages[m]), {
215
221
  searchReference: o.knowledgeReference
216
222
  }), this.event.emit("message:searchreference", o.searchReference), this.event.emit("message:updated", this.messages[m]));
217
223
  })), this.socket = i, i.open();
218
224
  }));
219
225
  }
220
226
  registerMcpFromClientConfig() {
221
- return f.mcp ? new Promise((t, n) => {
227
+ return u.mcp ? new Promise((t, n) => {
222
228
  if (!this.socket) {
223
229
  n("socket is undefined");
224
230
  return;
225
231
  }
226
- this.socket.emit("add_mcp_servers", f.mcp, (r) => {
232
+ this.socket.emit("add_mcp_servers", u.mcp, (r) => {
227
233
  r.code === 200 ? (Object.keys(r.data).forEach((i) => {
228
234
  r.data[i].code !== 200 && console.error(i, "MCP Server 注册失败。", r.data[i]);
229
235
  }), t(!0)) : (console.error("MCP Server 注册失败。", r), n(r));
@@ -253,8 +259,8 @@ class D extends L {
253
259
  sendQuestion(t, n) {
254
260
  return v(this, null, function* () {
255
261
  var i, s, e;
256
- let r = k(h({}, t), {
257
- promptVariables: this.promptVariables.reduce((o, c) => k(h({}, o), {
262
+ let r = k(g({}, t), {
263
+ promptVariables: this.promptVariables.reduce((o, c) => k(g({}, o), {
258
264
  [c.key]: c.value
259
265
  }), {}),
260
266
  knowledges: (i = this.knowledges) == null ? void 0 : i.map((o) => o.id)
@@ -281,5 +287,5 @@ class D extends L {
281
287
  }
282
288
  }
283
289
  export {
284
- D as default
290
+ B as default
285
291
  };
@@ -1,19 +1,19 @@
1
- var s = Object.defineProperty, v = Object.defineProperties;
2
- var u = Object.getOwnPropertyDescriptors;
1
+ var u = Object.defineProperty, f = Object.defineProperties;
2
+ var v = 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 ? u(o, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : o[t] = e, c = (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) => v(o, u(t));
12
+ }, l = (o, t) => f(o, v(t));
13
13
  import d from "./Logger.mjs";
14
14
  const R = new d("[Config] ");
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 || {});
16
- let c = {
15
+ var s = /* @__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))(s || {});
16
+ let i = {
17
17
  debug: !1,
18
18
  env: "prod",
19
19
  //AIoT 环境, 与apiRoot配对使用
@@ -25,13 +25,16 @@ let c = {
25
25
  loadRelatedQuesions: !0,
26
26
  stream: !1
27
27
  };
28
- function w(o) {
29
- d.debug = (o == null ? void 0 : o.debug) || !1, c = l(i(i({}, c), o), {
30
- apiRoot: (o == null ? void 0 : o.apiRoot) || c.apiRoot || (o != null && o.env ? f[o.env || "prod"] : c.apiRoot)
31
- }), d.debug && R.log("updated", c);
28
+ function x(o) {
29
+ var t, e;
30
+ d.debug = (o == null ? void 0 : o.debug) || !1, i = l(c(c({}, i), o), {
31
+ apiRoot: (o == null ? void 0 : o.apiRoot) || i.apiRoot || (o != null && o.env ? s[o.env || "prod"] : i.apiRoot),
32
+ // 应用未注册插件时 param.plugins 为 undefined,避免覆盖默认空表
33
+ plugins: (e = (t = o == null ? void 0 : o.plugins) != null ? t : i.plugins) != null ? e : {}
34
+ }), d.debug && R.log("updated", i);
32
35
  }
33
36
  export {
34
- f as ApiUrl,
35
- c as configuration,
36
- w as configure
37
+ s as ApiUrl,
38
+ i as configuration,
39
+ x as configure
37
40
  };
package/dist/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var T=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var $=(o,e,s)=>e in o?se(o,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):o[e]=s,u=(o,e)=>{for(var s in e||(e={}))B.call(e,s)&&$(o,s,e[s]);if(T)for(var s of T(e))F.call(e,s)&&$(o,s,e[s]);return o},w=(o,e)=>ie(o,ne(e));var j=(o,e)=>{var s={};for(var t in o)B.call(o,t)&&e.indexOf(t)<0&&(s[t]=o[t]);if(o!=null&&T)for(var t of T(o))e.indexOf(t)<0&&F.call(o,t)&&(s[t]=o[t]);return s};var m=(o,e,s)=>($(o,typeof e!="symbol"?e+"":e,s),s);var p=(o,e,s)=>new Promise((t,a)=>{var r=i=>{try{c(s.next(i))}catch(d){a(d)}},n=i=>{try{c(s.throw(i))}catch(d){a(d)}},c=i=>i.done?t(i.value):Promise.resolve(i.value).then(r,n);c((s=s.apply(o,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),re=require("axios"),I=require("@glodon-aiot/apis"),oe=require("socket.io-client"),J=require("uuid"),K=require("dayjs"),R=class R{constructor(e,s=!1){this.prefix=e,this.open=s}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!R.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!R.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!R.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!R.debug||console.warn(this.prefix,...e)}};m(R,"debug",!1);let b=R;const ce=new b("[Config] ");var G=(o=>(o.dev="https://aiot-dev.glodon.com/api/cvforcepd",o.test="https://aiot-dev.glodon.com/api/cvforce",o.prod="https://copilot.glodon.com/api/cvforce",o.local="http://localhost:3000/api/cvforcepd",o))(G||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function z(o){b.debug=(o==null?void 0:o.debug)||!1,exports.configuration=w(u(u({},exports.configuration),o),{apiRoot:(o==null?void 0:o.apiRoot)||exports.configuration.apiRoot||(o!=null&&o.env?G[o.env||"prod"]:exports.configuration.apiRoot)}),b.debug&&ce.log("updated",exports.configuration)}const P=o=>JSON.parse(ae.decode(o.split(".")[1])),de=o=>{const e=P(o).exp;return new Date().valueOf()/1e3>=e},he=o=>o==null?void 0:o.replace(/[\r\n]+/gm,""),le=o=>o.replace(/\\|\\/g,"");function X(o,e,s){const t=d=>{var f;return e&&(de(e)&&s(403,"aiotToken is timeout"),d.headers=(f=d.headers)!=null?f:{},d.headers=w(u({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function a(d,f=!0){const l=`${o}${d}`,g=re.create({baseURL:l});return f&&g.interceptors.request.use(t),g}const r=(d,f)=>{d===401&&s(d,"aiotToken is invalid")},n=(d,f)=>{console.log("onAppStatusError",d,f),d!==10001&&d!==10215&&s(d,f)},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 M=new b("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&M.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),M.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?M.log(`event ${e} listener ${s.name} is not found`):(this.eventListenerMap[e].splice(t,1),M.log(`remove event ${e} listener`))}else M.log(`event ${e} listeners is empty`)}emit(e,s){if(!this.eventListenerMap[e]){M.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))}),M.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const S=new b("[Session] ");var C=(o=>(o.DataRequestFailed="data request error",o.SocketConnectionFailed="socket error",o.IdUndefined="session id is not defined",o.SendingEmptyContent="failed at sending empty content",o.Frozen="session is frozen",o.UserModeError="failed at setting socket user mode",o.Inactive="session is inactive",o))(C||{});class q{constructor(e,s="",t,a,r,n){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new Z);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);m(this,"_mcpServers",null);this.token=e,this.lazyload=a,this.client=n||null,this._applicationId=P(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),r&&(this._application=r),this.event.emit("init",{applicationId:this._applicationId,sessionId:s}),this.loadApplicationInfo().then(()=>{var c;if(s)this._id=s,this.event.emit("data:loading"),t?(this.data=t,a||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,s).then(i=>p(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,s)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data)})))):(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,s).then(i=>p(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,s)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoading=!1,this._dataLoaded=!0})));else{const i=(t==null?void 0:t.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:i}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:i,netOpen:t==null?void 0:t.netOpen,knowledgeIdList:(c=t==null?void 0:t.knowledges)==null?void 0:c.map(d=>d.id),applicationId:this._applicationId}).then(d=>p(this,null,function*(){var f;this._id=d.id,this.data=w(u({},d),{knowledges:t==null?void 0:t.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),yield(()=>p(this,null,function*(){if(t!=null&&t.knowledges)return this.setKnowledges((t==null?void 0:t.knowledges)||void 0)}))(),yield(()=>{if(t!=null&&t.promptVariables){const l=this._promptVariables.map(g=>{var v,y;const h=((y=(v=t.promptVariables)==null?void 0:v.find(_=>_.key===g.key&&_.type===g.type))==null?void 0:y.value)||"";return w(u({},g),{value:h})}).sort((g,h)=>g.key.localeCompare(h.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),((f=this.application)==null?void 0:f.type)!==I.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}fetchData(){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.getSession(this.applicationId,this.data.id).then(e=>p(this,null,function*(){return this.data=e,this.event.emit("data:updated",this.data),e}))})}get id(){var e;return this._id||((e=this.data)==null?void 0:e.id)||""}get applicationId(){return this._applicationId}get application(){return this._application}set application(e){this._application=e}loadApplicationInfo(){if(this._application)return Promise.resolve(this._application);if(this._applicationId&&!this._application)return this.event.emit("application:data:loading"),this.cvforceApi.getApplicationId(this._applicationId).then(e=>(this._application=e,this.event.emit("application:data:loaded",e),e));throw Error("application id is not defined")}get ready(){return this._ready}get frozen(){return this._frozen}set frozen(e){e===!1&&this.inactivating&&this.socket&&(this.socket.disconnect(),this.socket=null,this.event.emit("inactivated")),this._frozen=e,this.event.emit("frozen",e)}get knowledges(){if(!this.data)throw Error("session data is not loaded");return this.data.knowledges||void 0}setKnowledges(e){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(s=>s.status===I.PromptStatus.Quoted).filter(s=>!s.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(s=>s.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>!(e.type===I.PromptVariableType.User&&e.key==="query")&&!(e.type===I.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return p(this,null,function*(){const s=this._promptVariables.map(t=>{var r;const a=((r=e==null?void 0:e.find(n=>n.key===t.key&&n.type===t.type))==null?void 0:r.value)||t.value;return w(u({},t),{value:a})}).sort((t,a)=>t.key.localeCompare(a.key));if(yield Promise.all(s.filter(t=>!(t.type===I.PromptVariableType.User&&t.key==="query")&&!(t.type===I.PromptVariableType.System&&t.key==="datetime")).map(t=>{if(!this.data)throw Error("session data is not loaded");if(!(!t.id||!t.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,t.id,{value:t.value})})),!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return p(this,null,function*(){var s,t,a;if(S.log("setNetOpen:",e),S.log("application arrange setting value: ",(s=this._application)==null?void 0:s.arrange[0].enableNetOpen),((t=this._application)==null?void 0:t.type)===I.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((a=this._application)==null?void 0:a.arrange[0].enableNetOpen)===!1){console.warn("This Application is disabled to change netOpen.");return}if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{netOpen:e?1:2}),this.data.netOpen=e,S.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return X(exports.configuration.apiRoot,this.token,(e,s)=>{const t=new Error("data request error",{cause:{status:e,message:s}});S.error(t),this.event.emit("error",t)})}addEventListener(e,s,t=!1){if(typeof s!="function")throw Error("event listener is not a function");if(t){this.event.once(e,s);return}this.event.on(e,s)}removeEventListener(e,s){this.event.off(e,s)}fetchMessages(){return p(this,arguments,function*(e={}){var t,a;const s={pageSize:this._loadingMessagesSize};if(this._id){e=u(u({},s),e),this.event.emit("history:loading"),S.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),S.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),n=r.map((i,d)=>{var g,h;let f=[],l;return typeof((g=i.agentHistoryList)==null?void 0:g.agentList)=="string"&&(f=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&&(l=(h=this.data)==null?void 0:h.lastRelatedQuestion),w(u({},i),{actions:f,relatedQuesion:l})});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(f=>f.ts===e.endTime),d=this.messages.findLastIndex(f=>f.ts===e.endTime);this.messages.splice(i,d-i+1,...n)}const c=this.messages[this.messages.length-1];return c&&!c.relatedQuesion&&(c.relatedQuesion=(a=this.data)==null?void 0:a.lastRelatedQuestion),this.event.emit("history:moreloaded",n),S.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,n}else{const r=new Error("session id is not defined");return S.error(r),this.event.emit("error",r),!1}})}rename(e){return p(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),S.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return p(this,null,function*(){this.messages.push(e),S.log("history:add",e),this.event.emit("history:add",e),this.event.emit("message:new",e),this.event.emit("message:updated",e)})}reloadSessionInfo(){if(!this._id)throw Error("session is not created yet");return this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,this._id).then(e=>p(this,null,function*(){if(this.data=e,!this._id)throw Error("session is not created yet");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),S.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>p(this,null,function*(){return this.messages=[],yield this.fetchMessages(),this._dataLoading=!1,this._dataLoaded=!0,this.event.emit("data:loaded",this.data),this}))}reload(){return p(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return p(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return S.error(e),this.event.emit("error",e),!1}return this.event.emit("data:deleting"),yield this.cvforceApi.delSessionsId(this.applicationId,this.id),this.event.emit("data:deleted"),this.destroy()})}activate(){return p(this,null,function*(){if(this.activing)return new Promise(s=>{this.addEventListener("activated",()=>{s(!0)},!0)});if(!this._id)throw Error("session is not avalible. id is undefined");this.activing=!0;const e=this._id;return this._dataLoading=!0,this._dataLoaded=!1,this.data=yield this.cvforceApi.getSession(this.applicationId,e).then(s=>p(this,null,function*(){return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,e),s})),this.messages.length||(this.messages=[],yield this.fetchMessages()),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoaded=!0,this._dataLoading=!1,this.inactivating=!1,this.frozen=!0,yield this.prepareConnection(),this.event.emit("activated",this.socket),this.active=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?this._frozen?(e||(this.inactivating=!0),this.activing=!1,!0):(this.socket.close(),this.socket=null,this.event.emit("inactivated"),this.active=!1,this.activing=!1,!0):(this.activing=!1,!0)}get dataLoaded(){return this._dataLoaded}get messagesLoading(){return this._loadingMessages}send(t){return p(this,arguments,function*(e,s={stream:exports.configuration.stream}){var g;try{this.validateConfigs()}catch(h){console.error(h)}const{stream:a=exports.configuration.stream,referenceFirst:r=!1}=s,n=e.uuid||J.v4(),c=((g=e.text)==null?void 0:g.trim())||"",i=e.fileIds;if(!c&&!(i!=null&&i.length)){const h=new Error("failed at sending empty content");return S.error(h),this.event.emit("error",h),!1}if(!this._id){const h=new Error("session id is not defined");return S.error(h),this.event.emit("error",h),!1}if(this.frozen){const h=new Error("session is frozen");return S.error(h),this.event.emit("error",h),!1}this.frozen=!0,this._stopAnswer=!1;const d={sessionId:this.id,role:2,content:c,messageId:n,reference:[],searchReference:[],messageTime:""},f={content:c,stream:a,requestId:n,fileIds:i,referenceFirst:r};this.pushMessage(d),this.event.emit("question:content",c);const l=h=>p(this,null,function*(){if(h.role!==I.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",l),this._id&&h.content&&h.index&&h.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:h.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:h.content})),yield this.fillMessageReference(h),h.code){case 11915:h.content="请您换个问题问我吧~",h.index=-1,h.isSensitive=!0,h.isLoading=!1,h.sessionId=this._id||"",this.event.emit("message:error",h);break;case 11916:h.content="尊敬的用户您好,让我们换个话题再聊聊吧。",h.index=-1,h.isSensitive=!0,h.isLoading=!1,h.sessionId=this._id||"",this.event.emit("message:error",h);break;case 200:h.index=-1,h.isLoading=!1;break;default:h.content=h.message||"未知错误",h.isLoading=!1,h.index=-1,this.event.emit("message:error",h)}this.getRelatedQuesion(h),h.isLoading=!1;let v=this.messages[this.messages.length-1];if(v&&v.role===I.ChatMessageRole.Robot){const y=u(u({},v),h);this.messages[this.messages.length-1]=y,this.event.emit("message:updated",y)}else this.pushMessage(h);this.frozen=!1});return this.addEventListener("answer:finish",l),this.sendQuestion(f,w(u({},s),{stream:a,referenceFirst:r})),d})}getRelatedQuesion(e){return p(this,null,function*(){var r,n;if(!e.content||e.isSensitive||e.code!==200||!((r=this.application)!=null&&r.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const s=yield this.cvforceApi.postGeneques({content:e.content}).catch(c=>null);if(!s){const c=[],i=w(u({},e),{relatedQuesion:c,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:c}),this.event.emit("message:updated",i),i}const t=(n=s.content)==null?void 0:n.split("*").map(he).map(le).filter(c=>!!c);e.relatedQuesion=t,e.index=-3,e.isLoading=!1;const a=w(u({},e),{relatedQuesion:t,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",a),this.event.emit("message:updated",a),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:t}),a})}fillMessageReference(e){return p(this,null,function*(){const s=yield Promise.all(e.reference.map(t=>this.cvforceApi.getKnowledgeIdFileId(t.knowledgeId,t.docId)));return e.reference=e.reference.map((t,a)=>u(u({},t),s[a])),this.event.emit("message:updated",e),e})}answerAgain(){return p(this,arguments,function*(e={stream:exports.configuration.stream}){const s=this.messages[this.messages.length-1];if(!s)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1;const{stream:t=exports.configuration.stream}=e;let a;s.role!==I.ChatMessageRole.User&&(a=e.oldMessageId||s.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",s),this.event.emit("history:remove",s));const r=this.messages[this.messages.length-1],n={content:r.content,fileIds:r.fileIds,requestId:r.messageId,stream:t,oldMessageId:a},c=i=>p(this,null,function*(){if(i.role===I.ChatMessageRole.Robot&&i.index===-1){switch(this._id&&i.content&&i.index&&i.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:i.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:i.content})),yield this.fillMessageReference(i),i.code){case 11915:i.content="请您换个问题问我吧~",i.index=-1,i.isSensitive=!0,i.isLoading=!1,i.sessionId=this._id||"",this.event.emit("message:error",i);break;case 11916:i.content="尊敬的用户您好,让我们换个话题再聊聊吧。",i.index=-1,i.isSensitive=!0,i.isLoading=!1,i.sessionId=this._id||"",this.event.emit("message:error",i);break;case 200:i.index=-1,i.isLoading=!1;break;default:i.content=i.message||"未知错误",i.isLoading=!1,i.index=-1,this.event.emit("message:error",i)}this.getRelatedQuesion(i),this.removeEventListener("message:content",c),this.frozen=!1}});this.addEventListener("message:content",c),this.sendQuestion(n,w(u({},e),{stream:t}))})}setTop(e){return p(this,null,function*(){if(!this._id)throw Error("session is not avalible. id is undefined");this.data=yield this.cvforceApi.patchSessionsId(this._applicationId,this._id,{top:e}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:top",{top:e})})}suspend(){var t;this.stopAnswer(),this.frozen=!1,this._stopAnswer=!0;let e=this.messages[this.messages.length-1];const s={messageId:J.v4(),isLoading:!1,index:-2,messageTime:K(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:I.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const a=e.actions[((t=e.actions)==null?void 0:t.length)-1];if(a){const r=a[a.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:n,pluginCode:c,funcCode:i,funcName:d}=r.data;a.push({data:{pluginName:n,pluginCode:c,funcCode:i,funcName:d,step:r.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:a})}}}e=u(u({},e),s),this.event.emit("message:content",e),this.event.emit("message:updated",e)}else this.pushMessage(s),this.event.emit("message:content",s);return this}postMessageComment(e){return p(this,null,function*(){if(!this._applicationId||!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.postComments(this._applicationId,this._id,e).then(s=>{const t=this.messages.find(a=>a.messageId===e.messageId);return t&&(t.comment=e,this.event.emit("message:comment",t)),s})})}clear(){if(!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.patchApplicationIdSessionsIdContext(this._applicationId,this._id).then(()=>(this.event.emit("context:clear"),!0))}destroy(){var e;return this._ready=!1,this.event.removeAllListeners(),(e=this.socket)==null||e.disconnect(),this.socket=null,this.event.emit("destroy",{applicationId:this._applicationId,sessionId:this._id}),this._id||""}}const A=new b("[AgentSession] ");class fe extends q{constructor(e,s="",t,a,r,n){super(e,s,t,a,r,n)}prepareConnection(){return new Promise(e=>p(this,null,function*(){this.socket&&e(!0);const s={version:"1.0",stream:JSON.stringify(exports.configuration.stream===void 0?!0:exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?L.Debug:L.Normal},t=new URL(exports.configuration.apiRoot),a=yield oe.io(t.origin,{path:t.pathname.replace("api","socketio")+"/copilot",query:s,transports:["websocket"]});a.on("connect",()=>{A.log("socket:connect"),this.event.emit("socket:connect"),a.emit("init")}),a.on("disconnect",()=>{A.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),a.on("ready",r=>{if(r.code===200){A.log("ready");const n=exports.configuration.debug?L.Debug:L.Normal;n===L.Debug&&r.userMode,this._ready=!0,this.event.emit("ready"),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const n=new Error(C.SocketConnectionFailed);A.error("error",n),this.event.emit("error",n),e(!1)}}),a.on("action",(r,n)=>p(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:c,data:{runnerIsClient:i,pluginCode:d,funcCode:f,parameters:l,requestBody:g}}=r,h=this.messages[this.messages.length-1];if(!h.messageId)h.actions||(h.actions=[]),h.actions[r.data.step-1]||(h.actions[r.data.step-1]=[]),h.actions[r.data.step-1].push(r),this.event.emit("message:action",{messageId:h.messageId,action:r}),this.event.emit("message:updated",h);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);A.warn("error",v),this.event.emit("error",v)}else if(c==="FUNCTION_CALL"&&i){if(A.log(`calling function ${f} of plugin ${d} with argument:
2
- ${JSON.stringify(l)}`),!exports.configuration.plugins[d]){n({code:404,message:"对不起,没有找到插件。"});return}const v=exports.configuration.plugins[d][f];typeof v!="function"&&n({code:404,message:"对不起,没有找到插件方法。"});let y=l==null?void 0:l.query;try{y=JSON.parse(l==null?void 0:l.query)}catch(_){}v(y,(..._)=>{this._stopAnswer||n(..._)})}})),a.on("answer",r=>{if(!this._stopAnswer)if(r.data.code!==200&&(r.data.index=-1,this.event.emit("error",r.data)),r.data.index===-1){let n=this.messages[this.messages.length-1];if(n&&!n.messageId)n=u(u({},n),r.data),this.event.emit("message:content",n),this.event.emit("message:updated",n),this.event.emit("answer:finish",n);else{const c=u({messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0}},r.data);this.event.emit("message:content",c),this.pushMessage(c),this.event.emit("answer:finish",c)}}else{let n=this.messages[this.messages.length-1];n&&!n.messageId?(n=u(u({},n),r.data),this.messages[this.messages.length-1]=n,this.event.emit("message:content",n),this.event.emit("message:updated",n)):(this.pushMessage(r.data),this.event.emit("message:content",r.data))}}),a.on("reference",r=>p(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const l=new Error(C.IdUndefined);A.error(l),this.event.emit("error",l),this.frozen=!1;return}const{type:n,data:c,requestId:i}=r,d=this.messages.findIndex(l=>l.messageId===i&&l.role===I.ChatMessageRole.User);if(d<0)return;const f=d+1;if(f>=this.messages.length){const l={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0}};this.pushMessage(l)}n==="KG"?(this.messages[f]=w(u({},this.messages[f]),{reference:c.knowledgeReference}),yield this.fillMessageReference(this.messages[f]),this.event.emit("message:reference",c.knowledgeReference),this.event.emit("message:updated",this.messages[f])):n==="WEB_SEARCH"&&(this.messages[f]=w(u({},this.messages[f]),{searchReference:c.knowledgeReference}),this.event.emit("message:searchreference",c.searchReference),this.event.emit("message:updated",this.messages[f]))})),this.socket=a,a.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((e,s)=>{if(!this.socket){s("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,t=>{t.code===200?(Object.keys(t.data).forEach(a=>{t.data[a].code!==200&&console.error(a,"MCP Server 注册失败。",t.data[a])}),e(!0)):(console.error("MCP Server 注册失败。",t),s(t))})}):Promise.resolve(!0)}addMcpServers(e){return p(this,null,function*(){return this.ready?this.socket?new Promise((s,t)=>{this.socket&&this.socket.emit("add_mcp_servers",e,a=>{a.code===200?(Object.keys(a.data).forEach(r=>{a.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",a.data[r])}),s(!0)):(console.error("MCP Server 注册失败。",a),t(a))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return p(this,null,function*(){return this.ready?this.socket?new Promise((e,s)=>{this.socket&&this.socket.emit("list_mcp_servers",t=>{t.code===200?e(t.data):s(t)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(e,s){return p(this,null,function*(){var a,r,n;let t=w(u({},e),{promptVariables:this.promptVariables.reduce((c,i)=>w(u({},c),{[i.key]:i.value}),{}),knowledges:(a=this.knowledges)==null?void 0:a.map(c=>c.id)});if(!this.active){if(yield this.activate(),!this.socket){const c=new Error(C.SocketConnectionFailed);return A.warn("error",c),this.event.emit("error",c),!1}(r=this.socket)==null||r.emit("question",t);return}(n=this.socket)==null||n.emit("question",t)})}stopAnswer(){var e;(e=this.socket)==null||e.emit("stop_answer")}}function pe(o,e){return p(this,null,function*(){const s=o.getReader();let t;for(;!(t=yield s.read()).done;)e(t.value)})}function ge(o){let e,s,t,a=!1,r;return function(c){e===void 0?(e=c,s=0,t=-1,r=!1):e=me(e,c);const i=e.length;let d=0;for(;s<i;){a&&(e[s]===10&&(d=++s),a=!1);let f=-1;for(;s<i&&f===-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:f=s;break}if(f===-1)break;o(e.subarray(d,f),t,r),d=s,t=-1,r=!1}d===i?e=void 0:d!==0&&(e=e.subarray(d),s-=d)}}function ue(o,e,s){let t=H();const a=new TextDecoder;return function(n,c,i){if(n.length===0)s==null||s(t),t=H();else if(c>0){const d=a.decode(n.subarray(0,c)),f=c+(n[c+1]===32?2:1);let l=a.decode(n.subarray(f));switch(i&&(l+=`
3
- `),d){case"data":t.data=t.data?t.data+`
4
- `+l:l;break;case"event":t.event=l;break;case"id":o(t.id=l);break;case"retry":const g=parseInt(l,10);isNaN(g)||e(t.retry=g);break}}}}function me(o,e){const s=new Uint8Array(o.length+e.length);return s.set(o),s.set(e,o.length),s}function H(){return{data:"",event:"",id:"",retry:void 0}}const N="text/event-stream",ve=1e3,Y="last-event-id";function U(o,f){var l=f,{signal:e,headers:s,onopen:t,onmessage:a,onclose:r,onerror:n,openWhenHidden:c,fetch:i}=l,d=j(l,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,h)=>{const v=u({},s);v.accept||(v.accept=N);let y;function _(){y.abort(),document.hidden||Q()}c||document.addEventListener("visibilitychange",_);let E=ve,V=0;function O(){document.removeEventListener("visibilitychange",_),window.clearTimeout(V),y.abort()}e==null||e.addEventListener("abort",()=>{O(),g()});const ee=i!=null?i:window.fetch,te=t!=null?t:ye;function Q(){return p(this,null,function*(){var D;y=new AbortController;try{const x=yield ee(o,w(u({},d),{headers:v,signal:y.signal}));yield te(x),yield pe(x.body,ge(ue(k=>{k?v[Y]=k:delete v[Y]},k=>{E=k},a))),r==null||r(),O(),g()}catch(x){if(!y.signal.aborted)try{const k=(D=n==null?void 0:n(x))!=null?D:E;window.clearTimeout(V),V=window.setTimeout(Q,k)}catch(k){O(),h(k)}}})}Q()})}function ye(o){const e=o.headers.get("content-type");if(!(e!=null&&e.startsWith(N)))throw new Error(`Expected content-type to be ${N}, Actual: ${e}`)}const W=new b("[DialogSession] ");class we extends q{constructor(s,t="",a,r,n,c){super(s,t,a,r,n,c);m(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(s=>p(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,s(!0)}))}postChatV2EventSource(s,t,a,r,n,c){return p(this,null,function*(){const i={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:t,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=w(u({},a),{stream:exports.configuration.stream});U(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${s}&sessionId=${t}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:r,onopen(f){return f.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(f){if(!f.data.includes('{"code": ')){let g={};try{g=JSON.parse(f.data)}catch(v){}(g==null?void 0:g.mtype)==="search"?i.searchReference.push(g):i.content=i.content+f.data;const h={content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:t,messageTime:K(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(n==null?void 0:n.onmessage)&&n.onmessage(h)}const l=JSON.parse(f.data);if(i.reference=l.data.reference,i.searchReference=l.data.searchReference,i.messageTime=l.data.messageTime,i.messageId=l.data.messageId,i.llmModel=l.data.llmModel,i.content=l.data.content,i.code=l.code,l.code===200){const g={code:i.code,content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:t,messageTime:i.messageTime,isReplying:!0};n!=null&&n.onmessage&&n.onmessage(g)}else return n!=null&&n.onclose&&n.onclose(i),c&&c({code:i.code,message:i.message})},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const f={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(f)}})})}postChatV3EventSource(s,t,a,r,n,c){return p(this,null,function*(){const i={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:t,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},d=w(u({},a),{stream:exports.configuration.stream});U(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${s}&sessionId=${t}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:r,onopen(f){return f.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(f){if(!f.data&&!f.event&&!f.id&&!f.retry)return;let l={};try{l=JSON.parse(f.data)}catch(y){console.error("parse eventData to JSON failed. ",f.data)}if(l.code!==200)return i.index=-1,i.code=l.code,i.message=l.message,n!=null&&n.onmessage&&n.onmessage(i),c&&c({code:l.code,message:l.message});const g=l.data.type,h=l.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(h),g==="thinking"){i.thinkingStatus="start";const _=h.choices[0];i.reasoningContent=i.reasoningContent+_.delta.reasoningContent}if(g==="thinkingOver"){i.thinkingStatus="end";const y=h.thinkingSecs;i.thinkingSecs=y}if(g==="text"){const _=h.choices[0];i.content=i.content+_.delta.content}if(g==="reference"&&(i.reference=h),g==="result"){const y=h.messageId,_=h.llmModel,E=h.messageTime;i.messageId=y,i.llmModel=_,i.messageTime=E,i.sessionId=t}g==="over"?i.index=-1:(i.code=l.code,i.message=l.message),n!=null&&n.onmessage&&n.onmessage(i)},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const f=w(u({},i),{isReplying:!1});n!=null&&n.onclose&&n.onclose(f)}})})}sendQuestion(s,t){return p(this,null,function*(){var d;const{content:a,fileIds:r,oldMessageId:n}=s,{stream:c,referenceFirst:i}=t;if(this.active||(yield this.activate()),this._id){let f={content:a,fileIds:r,referenceFirst:i,oldMessageId:n,promptVariables:this.promptVariables.reduce((l,g)=>w(u({},l),{[g.key]:g.value}),{}),knowledges:(d=this.knowledges)==null?void 0:d.map(l=>l.id)};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,f,this.ctrl.signal,{onopen:()=>{W.log("open",this.ctrl)},onmessage:l=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===I.ChatMessageRole.Robot?(g=u(u({},g),l),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(l),this.event.emit("message:content",l))},onclose:l=>p(this,null,function*(){this._stopAnswer||(W.log(l,"onclose"),this.event.emit("answer:finish",l))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(s){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}}const Ie=new b("[BotClient] ");class _e{constructor(e,s,t=!0){m(this,"event",new Z);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=t,z(s),this._applicationId=P(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(a=>{z(w(u({},s),{stream:s.stream===void 0?(a==null?void 0:a.type)===I.ApplicationTypes.Dialog:s.stream})),this.event.emit("ready")})}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return p(this,null,function*(){var s,t,a;this._application=yield this.cvforceApi.getApplicationId(this._applicationId).then(r=>(typeof r.arrange[0].recommendQuestionOpen!="boolean"&&(r.arrange[0].recommendQuestionOpen=!0),w(u({},r),{arrange:[w(u({},r.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&r.arrange[0].recommendQuestionOpen})]})));const e=(a=(t=(s=this._application)==null?void 0:s.arrange)==null?void 0:t[0])==null?void 0:a.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(r=>r.maxModelLength)),this._promptVariables=yield this.cvforceApi.getPrompts(this._applicationId),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:X(exports.configuration.apiRoot,this.token,(e,s)=>Ie.error(s))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const s=P(e).rid;this._applicationId!==s&&(this._applicationId=s,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(s=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=s})}createSession(e,s,t,a,r){return p(this,null,function*(){const n=this;return new Promise((c,i)=>{const d=f=>p(this,null,function*(){if(f===I.ApplicationTypes.Agent)c(new fe(e,s,t,a,r,n));else if(f===I.ApplicationTypes.Dialog)c(new we(e,s,t,a,r,n));else throw Error(`不支持的应用类型:${f}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return p(this,null,function*(){return new Promise((s,t)=>{const a=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>{const n=[];return r.forEach(c=>p(this,null,function*(){const i=this._sessions.find(d=>c.id===d.id);if(i)i.data=c,this._application?i.application=this._application:i.loadApplicationInfo(),n.push(i);else{const d=yield this.createSession(this.token,c.id,c,this.lazyload,this._application||void 0);n.push(d)}})),this.sessions=n,n});if(this.ready){if(!this._application)throw Error("_application is null");s(a())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");s(a())},!0)})})}loadSession(e="",s){return p(this,null,function*(){this.checkReady();let t=this.sessions.find(a=>a.id===e);if(t||(t=yield this.createSession(this.token,e,s),this._sessions.push(t)),this._activeSession){if(this._activeSession===t)return t;this._activeSession.inactivate()}return t.id?(yield t.activate(),this._activeSession=t):t.addEventListener("data:loaded",()=>{this._activeSession!==t&&(t==null||t.activate(),this._activeSession=t)},!0),t})}reload(){return this.loadApplication().then(()=>p(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return p(this,null,function*(){yield this.reload();let s=this._sessions.find(t=>t.id===e)||this._activeSession;if(!s){console.warn("reloadSession session failed.");return}return yield s.reload(),s})}setTop(e,s,t="top_time desc, sort_status desc, updated_at desc"){return p(this,null,function*(){let a=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!a){console.warn("setTop session failed.");return}return yield a.setTop(s),this.getSessions({order:t})})}addEventListener(e,s,t=!1){if(typeof s!="function")throw Error("event listener is not a function");if(t){this.event.once(e,s);return}this.event.on(e,s)}removeEventListener(e,s){this.event.off(e,s)}removeSession(e,s){return p(this,null,function*(){this.checkReady();let t=-1;if(typeof e=="string"?t=this._sessions.findIndex(a=>a.id===e):t=this._sessions.findIndex(a=>a.id===e.id),t>-1){const a=this._sessions[t];s&&(yield a.delete()),this._sessions.splice(t,1)}else console.warn("session delete failed, session is not exist.")})}clean(){this._sessions.forEach(e=>e.destroy()),this.sessions=[]}}class Se{constructor(e,s={},t){m(this,"code");m(this,"description","");m(this,"loaded",!1);m(this,"functions",{});this.code=e,s&&(this.functions=s)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}exports.AgentPlugin=Se;exports.BotClient=_e;exports.Session=q;exports.configure=z;
1
+ "use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var P=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var $=(o,e,t)=>e in o?se(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,u=(o,e)=>{for(var t in e||(e={}))B.call(e,t)&&$(o,t,e[t]);if(P)for(var t of P(e))F.call(e,t)&&$(o,t,e[t]);return o},y=(o,e)=>ie(o,ne(e));var j=(o,e)=>{var t={};for(var s in o)B.call(o,s)&&e.indexOf(s)<0&&(t[s]=o[s]);if(o!=null&&P)for(var s of P(o))e.indexOf(s)<0&&F.call(o,s)&&(t[s]=o[s]);return t};var m=(o,e,t)=>($(o,typeof e!="symbol"?e+"":e,t),t);var p=(o,e,t)=>new Promise((s,a)=>{var r=i=>{try{c(t.next(i))}catch(d){a(d)}},n=i=>{try{c(t.throw(i))}catch(d){a(d)}},c=i=>i.done?s(i.value):Promise.resolve(i.value).then(r,n);c((t=t.apply(o,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),re=require("axios"),w=require("@glodon-aiot/apis"),oe=require("socket.io-client"),J=require("uuid"),K=require("dayjs"),L=class L{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!L.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!L.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!L.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!L.debug||console.warn(this.prefix,...e)}};m(L,"debug",!1);let b=L;const ce=new b("[Config] ");var G=(o=>(o.dev="https://aiot-dev.glodon.com/api/cvforcepd",o.test="https://aiot-dev.glodon.com/api/cvforce",o.prod="https://copilot.glodon.com/api/cvforce",o.local="http://localhost:3000/api/cvforcepd",o))(G||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function z(o){var e,t;b.debug=(o==null?void 0:o.debug)||!1,exports.configuration=y(u(u({},exports.configuration),o),{apiRoot:(o==null?void 0:o.apiRoot)||exports.configuration.apiRoot||(o!=null&&o.env?G[o.env||"prod"]:exports.configuration.apiRoot),plugins:(t=(e=o==null?void 0:o.plugins)!=null?e:exports.configuration.plugins)!=null?t:{}}),b.debug&&ce.log("updated",exports.configuration)}const V=o=>JSON.parse(ae.decode(o.split(".")[1])),de=o=>{const e=V(o).exp;return new Date().valueOf()/1e3>=e},he=o=>o==null?void 0:o.replace(/[\r\n]+/gm,""),le=o=>o.replace(/\\|\\/g,"");function X(o,e,t){const s=d=>{var f;return e&&(de(e)&&t(403,"aiotToken is timeout"),d.headers=(f=d.headers)!=null?f:{},d.headers=y(u({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function a(d,f=!0){const l=`${o}${d}`,g=re.create({baseURL:l});return f&&g.interceptors.request.use(s),g}const r=(d,f)=>{d===401&&t(d,"aiotToken is invalid")},n=(d,f)=>{console.log("onAppStatusError",d,f),d!==10001&&d!==10215&&t(d,f)},c=a("/data/v1");return new w.CVForceApi(c,{onHttpStatusError:r,onAppStatusError:n})}var E=(o=>(o[o.Normal=0]="Normal",o[o.Debug=1]="Debug",o))(E||{});const R=new b("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&R.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),R.log(`add event ${e} listener ${s?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const s=this.eventListenerMap[e].findIndex(a=>{if(typeof a=="function"&&t===a)return!0;if(a=a,a.fn===t)return!0});s<0?R.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),R.log(`remove event ${e} listener`))}else R.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){R.log(`event ${e} listeners is empty`);return}const s=[];for(let a=0;a<this.eventListenerMap[e].length;a++){const r=this.eventListenerMap[e][a];typeof r=="function"?r(t):s.push(r)}s.forEach(a=>{a&&(a.fn(t),this.off(e,a.fn))}),R.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const S=new b("[Session] ");var x=(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))(x||{});class q{constructor(e,t="",s,a,r,n){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new Z);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);m(this,"_mcpServers",null);this.token=e,this.lazyload=a,this.client=n||null,this._applicationId=V(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),r&&(this._application=r),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var c;if(t)this._id=t,this.event.emit("data:loading"),s?(this.data=s,a||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(i=>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,knowledgeIdList:(c=s==null?void 0:s.knowledges)==null?void 0:c.map(d=>d.id),applicationId:this._applicationId}).then(d=>p(this,null,function*(){var f;this._id=d.id,this.data=y(u({},d),{knowledges:s==null?void 0:s.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),yield(()=>p(this,null,function*(){if(s!=null&&s.knowledges)return this.setKnowledges((s==null?void 0:s.knowledges)||void 0)}))(),yield(()=>{if(s!=null&&s.promptVariables){const l=this._promptVariables.map(g=>{var I,v;const h=((v=(I=s.promptVariables)==null?void 0:I.find(_=>_.key===g.key&&_.type===g.type))==null?void 0:v.value)||"";return y(u({},g),{value:h})}).sort((g,h)=>g.key.localeCompare(h.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),((f=this.application)==null?void 0:f.type)!==w.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}fetchData(){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.getSession(this.applicationId,this.data.id).then(e=>p(this,null,function*(){return this.data=e,this.event.emit("data:updated",this.data),e}))})}get id(){var e;return this._id||((e=this.data)==null?void 0:e.id)||""}get applicationId(){return this._applicationId}get application(){return this._application}set application(e){this._application=e}loadApplicationInfo(){if(this._application)return Promise.resolve(this._application);if(this._applicationId&&!this._application)return this.event.emit("application:data:loading"),this.cvforceApi.getApplicationId(this._applicationId).then(e=>(this._application=e,this.event.emit("application:data:loaded",e),e));throw Error("application id is not defined")}get ready(){return this._ready}get frozen(){return this._frozen}set frozen(e){e===!1&&this.inactivating&&this.socket&&(this.socket.disconnect(),this.socket=null,this.event.emit("inactivated")),this._frozen=e,this.event.emit("frozen",e)}get knowledges(){if(!this.data)throw Error("session data is not loaded");return this.data.knowledges||void 0}setKnowledges(e){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(t=>t.status===w.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>!(e.type===w.PromptVariableType.User&&e.key==="query")&&!(e.type===w.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return p(this,null,function*(){const t=this._promptVariables.map(s=>{var r;const a=((r=e==null?void 0:e.find(n=>n.key===s.key&&n.type===s.type))==null?void 0:r.value)||s.value;return y(u({},s),{value:a})}).sort((s,a)=>s.key.localeCompare(a.key));if(yield Promise.all(t.filter(s=>!(s.type===w.PromptVariableType.User&&s.key==="query")&&!(s.type===w.PromptVariableType.System&&s.key==="datetime")).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})})),!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(S.log("setNetOpen:",e),S.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===w.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((a=this._application)==null?void 0:a.arrange[0].enableNetOpen)===!1){console.warn("This Application is disabled to change netOpen.");return}if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{netOpen:e?1:2}),this.data.netOpen=e,S.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return X(exports.configuration.apiRoot,this.token,(e,t)=>{const s=new Error("data request error",{cause:{status:e,message:t}});S.error(s),this.event.emit("error",s)})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}fetchMessages(){return 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"),S.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),S.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),n=r.map((i,d)=>{var g,h;let f=[],l;return typeof((g=i.agentHistoryList)==null?void 0:g.agentList)=="string"&&(f=JSON.parse(i.agentHistoryList.agentList).reduce((v,_)=>(v[_.data.step-1]||(v[_.data.step-1]=[]),v[_.data.step-1].push(_),v),[])),d===r.length-1&&(l=(h=this.data)==null?void 0:h.lastRelatedQuestion),y(u({},i),{actions:f,relatedQuesion:l})});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(f=>f.ts===e.endTime),d=this.messages.findLastIndex(f=>f.ts===e.endTime);this.messages.splice(i,d-i+1,...n)}const c=this.messages[this.messages.length-1];return c&&!c.relatedQuesion&&(c.relatedQuesion=(a=this.data)==null?void 0:a.lastRelatedQuestion),this.event.emit("history:moreloaded",n),S.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,n}else{const r=new Error("session id is not defined");return S.error(r),this.event.emit("error",r),!1}})}rename(e){return p(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),S.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return p(this,null,function*(){this.messages.push(e),S.log("history:add",e),this.event.emit("history:add",e),this.event.emit("message:new",e),this.event.emit("message:updated",e)})}reloadSessionInfo(){if(!this._id)throw Error("session is not created yet");return this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,this._id).then(e=>p(this,null,function*(){if(this.data=e,!this._id)throw Error("session is not created yet");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),S.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>p(this,null,function*(){return this.messages=[],yield this.fetchMessages(),this._dataLoading=!1,this._dataLoaded=!0,this.event.emit("data:loaded",this.data),this}))}reload(){return p(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return p(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return S.error(e),this.event.emit("error",e),!1}return this.event.emit("data:deleting"),yield this.cvforceApi.delSessionsId(this.applicationId,this.id),this.event.emit("data:deleted"),this.destroy()})}activate(){return p(this,null,function*(){if(this.activing)return new Promise(t=>{this.addEventListener("activated",()=>{t(!0)},!0)});if(!this._id)throw Error("session is not avalible. id is undefined");this.activing=!0;const e=this._id;return this._dataLoading=!0,this._dataLoaded=!1,this.data=yield this.cvforceApi.getSession(this.applicationId,e).then(t=>p(this,null,function*(){return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,e),t})),this.messages.length||(this.messages=[],yield this.fetchMessages()),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoaded=!0,this._dataLoading=!1,this.inactivating=!1,this.frozen=!0,yield this.prepareConnection(),this.event.emit("activated",this.socket),this.active=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?this._frozen?(e||(this.inactivating=!0),this.activing=!1,!0):(this.socket.close(),this.socket=null,this.event.emit("inactivated"),this.active=!1,this.activing=!1,!0):(this.activing=!1,!0)}get dataLoaded(){return this._dataLoaded}get messagesLoading(){return this._loadingMessages}send(s){return p(this,arguments,function*(e,t={stream:exports.configuration.stream}){var g;try{this.validateConfigs()}catch(h){console.error(h)}const{stream:a=exports.configuration.stream,referenceFirst:r=!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 h=new Error("failed at sending empty content");return S.error(h),this.event.emit("error",h),!1}if(!this._id){const h=new Error("session id is not defined");return S.error(h),this.event.emit("error",h),!1}if(this.frozen){const h=new Error("session is frozen");return S.error(h),this.event.emit("error",h),!1}this.frozen=!0,this._stopAnswer=!1;const d={sessionId:this.id,role:2,content:c,messageId:n,reference:[],searchReference:[],messageTime:""},f={content:c,stream:a,requestId:n,fileIds:i,referenceFirst:r};this.pushMessage(d),this.event.emit("question:content",c);const l=h=>p(this,null,function*(){if(h.role!==w.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",l),this._id&&h.content&&h.index&&h.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:h.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:h.content})),yield this.fillMessageReference(h),h.code){case 11915:h.content="请您换个问题问我吧~",h.index=-1,h.isSensitive=!0,h.isLoading=!1,h.sessionId=this._id||"",this.event.emit("message:error",h);break;case 11916:h.content="尊敬的用户您好,让我们换个话题再聊聊吧。",h.index=-1,h.isSensitive=!0,h.isLoading=!1,h.sessionId=this._id||"",this.event.emit("message:error",h);break;case 200:h.index=-1,h.isLoading=!1;break;default:h.content=h.message||"未知错误",h.isLoading=!1,h.index=-1,this.event.emit("message:error",h)}this.getRelatedQuesion(h),h.isLoading=!1;let I=this.messages[this.messages.length-1];if(I&&I.role===w.ChatMessageRole.Robot){const v=u(u({},I),h);this.messages[this.messages.length-1]=v,this.event.emit("message:updated",v)}else this.pushMessage(h);this.frozen=!1});return this.addEventListener("answer:finish",l),this.sendQuestion(f,y(u({},t),{stream:a,referenceFirst:r})),d})}getRelatedQuesion(e){return p(this,null,function*(){var r,n;if(!e.content||e.isSensitive||e.code!==200||!((r=this.application)!=null&&r.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const t=yield this.cvforceApi.postGeneques({content:e.content}).catch(c=>null);if(!t){const c=[],i=y(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=y(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:exports.configuration.stream}){const t=this.messages[this.messages.length-1];if(!t)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1;const{stream:s=exports.configuration.stream}=e;let a;t.role!==w.ChatMessageRole.User&&(a=e.oldMessageId||t.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",t),this.event.emit("history:remove",t));const r=this.messages[this.messages.length-1],n={content:r.content,fileIds:r.fileIds,requestId:r.messageId,stream:s,oldMessageId:a},c=i=>p(this,null,function*(){if(i.role===w.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 11916: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,y(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:K(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:w.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const a=e.actions[((s=e.actions)==null?void 0:s.length)-1];if(a){const r=a[a.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:n,pluginCode:c,funcCode:i,funcName:d}=r.data;a.push({data:{pluginName:n,pluginCode:c,funcCode:i,funcName:d,step:r.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:a})}}}e=u(u({},e),t),this.event.emit("message:content",e),this.event.emit("message:updated",e)}else this.pushMessage(t),this.event.emit("message:content",t);return this}postMessageComment(e){return 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 A=new b("[AgentSession] ");class fe extends q{constructor(e,t="",s,a,r,n){super(e,t,s,a,r,n)}prepareConnection(){return new Promise(e=>p(this,null,function*(){this.socket&&e(!0);const t={version:"1.0",stream:JSON.stringify(exports.configuration.stream===void 0?!0:exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?E.Debug:E.Normal},s=new URL(exports.configuration.apiRoot),a=yield oe.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});a.on("connect",()=>{A.log("socket:connect"),this.event.emit("socket:connect"),a.emit("init")}),a.on("disconnect",()=>{A.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),a.on("ready",r=>{if(r.code===200){A.log("ready");const n=exports.configuration.debug?E.Debug:E.Normal;n===E.Debug&&r.userMode,this._ready=!0,this.event.emit("ready"),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const n=new Error(x.SocketConnectionFailed);A.error("error",n),this.event.emit("error",n),e(!1)}}),a.on("action",(r,n)=>p(this,null,function*(){var I;if(this._stopAnswer||!this.id)return;const{type:c,data:{runnerIsClient:i,pluginCode:d,funcCode:f,parameters:l,requestBody:g}}=r,h=this.messages[this.messages.length-1];if(!h.messageId)h.actions||(h.actions=[]),h.actions[r.data.step-1]||(h.actions[r.data.step-1]=[]),h.actions[r.data.step-1].push(r),this.event.emit("message:action",{messageId:h.messageId,action:r}),this.event.emit("message:updated",h);else{const v={messageId:"",content:"",role:w.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(x.Inactive);A.warn("error",v),this.event.emit("error",v)}else if(c==="FUNCTION_CALL"&&i){A.log(`calling function ${f} of plugin ${d} with argument:
2
+ ${JSON.stringify(l)}`);const v=(I=exports.configuration.plugins)==null?void 0:I[d];if(!v){n({code:404,message:"没有找到插件。"});return}const _=v[f];if(typeof _!="function"){n({code:404,message:"没有找到插件方法。"});return}let M=l==null?void 0:l.query;try{M=JSON.parse(l==null?void 0:l.query)}catch(C){}_(M,(...C)=>{this._stopAnswer||n(...C)})}})),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:w.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0}},r.data);this.event.emit("message:content",c),this.pushMessage(c),this.event.emit("answer:finish",c)}}else{let n=this.messages[this.messages.length-1];n&&!n.messageId?(n=u(u({},n),r.data),this.messages[this.messages.length-1]=n,this.event.emit("message:content",n),this.event.emit("message:updated",n)):(this.pushMessage(r.data),this.event.emit("message:content",r.data))}}),a.on("reference",r=>p(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const l=new Error(x.IdUndefined);A.error(l),this.event.emit("error",l),this.frozen=!1;return}const{type:n,data:c,requestId:i}=r,d=this.messages.findIndex(l=>l.messageId===i&&l.role===w.ChatMessageRole.User);if(d<0)return;const f=d+1;if(f>=this.messages.length){const l={messageId:"",content:"",role:w.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0}};this.pushMessage(l)}n==="KG"?(this.messages[f]=y(u({},this.messages[f]),{reference:c.knowledgeReference}),yield this.fillMessageReference(this.messages[f]),this.event.emit("message:reference",c.knowledgeReference),this.event.emit("message:updated",this.messages[f])):n==="WEB_SEARCH"&&(this.messages[f]=y(u({},this.messages[f]),{searchReference:c.knowledgeReference}),this.event.emit("message:searchreference",c.searchReference),this.event.emit("message:updated",this.messages[f]))})),this.socket=a,a.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((e,t)=>{if(!this.socket){t("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,s=>{s.code===200?(Object.keys(s.data).forEach(a=>{s.data[a].code!==200&&console.error(a,"MCP Server 注册失败。",s.data[a])}),e(!0)):(console.error("MCP Server 注册失败。",s),t(s))})}):Promise.resolve(!0)}addMcpServers(e){return p(this,null,function*(){return this.ready?this.socket?new Promise((t,s)=>{this.socket&&this.socket.emit("add_mcp_servers",e,a=>{a.code===200?(Object.keys(a.data).forEach(r=>{a.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",a.data[r])}),t(!0)):(console.error("MCP Server 注册失败。",a),s(a))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return p(this,null,function*(){return this.ready?this.socket?new Promise((e,t)=>{this.socket&&this.socket.emit("list_mcp_servers",s=>{s.code===200?e(s.data):t(s)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(e,t){return p(this,null,function*(){var a,r,n;let s=y(u({},e),{promptVariables:this.promptVariables.reduce((c,i)=>y(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(x.SocketConnectionFailed);return A.warn("error",c),this.event.emit("error",c),!1}(r=this.socket)==null||r.emit("question",s);return}(n=this.socket)==null||n.emit("question",s)})}stopAnswer(){var e;(e=this.socket)==null||e.emit("stop_answer")}}function pe(o,e){return p(this,null,function*(){const t=o.getReader();let s;for(;!(s=yield t.read()).done;)e(s.value)})}function ge(o){let e,t,s,a=!1,r;return function(c){e===void 0?(e=c,t=0,s=-1,r=!1):e=me(e,c);const i=e.length;let d=0;for(;t<i;){a&&(e[t]===10&&(d=++t),a=!1);let f=-1;for(;t<i&&f===-1;++t)switch(e[t]){case 58:s===-1&&(s=t-d);break;case 13:a=!1,t+4<i&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(r=!0);case 10:f=t;break}if(f===-1)break;o(e.subarray(d,f),s,r),d=t,s=-1,r=!1}d===i?e=void 0:d!==0&&(e=e.subarray(d),t-=d)}}function ue(o,e,t){let s=H();const a=new TextDecoder;return function(n,c,i){if(n.length===0)t==null||t(s),s=H();else if(c>0){const d=a.decode(n.subarray(0,c)),f=c+(n[c+1]===32?2:1);let l=a.decode(n.subarray(f));switch(i&&(l+=`
3
+ `),d){case"data":s.data=s.data?s.data+`
4
+ `+l:l;break;case"event":s.event=l;break;case"id":o(s.id=l);break;case"retry":const g=parseInt(l,10);isNaN(g)||e(s.retry=g);break}}}}function me(o,e){const t=new Uint8Array(o.length+e.length);return t.set(o),t.set(e,o.length),t}function H(){return{data:"",event:"",id:"",retry:void 0}}const N="text/event-stream",ve=1e3,Y="last-event-id";function U(o,f){var l=f,{signal:e,headers:t,onopen:s,onmessage:a,onclose:r,onerror:n,openWhenHidden:c,fetch:i}=l,d=j(l,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,h)=>{const I=u({},t);I.accept||(I.accept=N);let v;function _(){v.abort(),document.hidden||Q()}c||document.addEventListener("visibilitychange",_);let M=ve,C=0;function O(){document.removeEventListener("visibilitychange",_),window.clearTimeout(C),v.abort()}e==null||e.addEventListener("abort",()=>{O(),g()});const ee=i!=null?i:window.fetch,te=s!=null?s:ye;function Q(){return p(this,null,function*(){var D;v=new AbortController;try{const T=yield ee(o,y(u({},d),{headers:I,signal:v.signal}));yield te(T),yield pe(T.body,ge(ue(k=>{k?I[Y]=k:delete I[Y]},k=>{M=k},a))),r==null||r(),O(),g()}catch(T){if(!v.signal.aborted)try{const k=(D=n==null?void 0:n(T))!=null?D:M;window.clearTimeout(C),C=window.setTimeout(Q,k)}catch(k){O(),h(k)}}})}Q()})}function ye(o){const e=o.headers.get("content-type");if(!(e!=null&&e.startsWith(N)))throw new Error(`Expected content-type to be ${N}, Actual: ${e}`)}const W=new b("[DialogSession] ");class we extends q{constructor(t,s="",a,r,n,c){super(t,s,a,r,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,r,n,c){return p(this,null,function*(){const i={code:0,content:"",role:w.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=y(u({},a),{stream:exports.configuration.stream});U(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:r,onopen(f){return f.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(f){if(!f.data.includes('{"code": ')){let g={};try{g=JSON.parse(f.data)}catch(I){}(g==null?void 0:g.mtype)==="search"?i.searchReference.push(g):i.content=i.content+f.data;const h={content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:s,messageTime:K(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(n==null?void 0:n.onmessage)&&n.onmessage(h)}const l=JSON.parse(f.data);if(i.reference=l.data.reference,i.searchReference=l.data.searchReference,i.messageTime=l.data.messageTime,i.messageId=l.data.messageId,i.llmModel=l.data.llmModel,i.content=l.data.content,i.code=l.code,l.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 f={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(f)}})})}postChatV3EventSource(t,s,a,r,n,c){return p(this,null,function*(){const i={code:0,content:"",role:w.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},d=y(u({},a),{stream:exports.configuration.stream});U(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:r,onopen(f){return f.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(f){if(!f.data&&!f.event&&!f.id&&!f.retry)return;let l={};try{l=JSON.parse(f.data)}catch(v){console.error("parse eventData to JSON failed. ",f.data)}if(l.code!==200)return i.index=-1,i.code=l.code,i.message=l.message,n!=null&&n.onmessage&&n.onmessage(i),c&&c({code:l.code,message:l.message});const g=l.data.type,h=l.data.payload;i.isReplying=!0;const I=()=>{if(!i.searchingStatus){i.searchingStatus="start";return}if(i.searchingStatus==="start"){i.searchingStatus="end";return}};if(g==="beforeSearch"&&I(),g==="searchOver"&&I(),g==="search"&&i.searchReference.push(h),g==="thinking"){i.thinkingStatus="start";const _=h.choices[0];i.reasoningContent=i.reasoningContent+_.delta.reasoningContent}if(g==="thinkingOver"){i.thinkingStatus="end";const v=h.thinkingSecs;i.thinkingSecs=v}if(g==="text"){const _=h.choices[0];i.content=i.content+_.delta.content}if(g==="reference"&&(i.reference=h),g==="result"){const v=h.messageId,_=h.llmModel,M=h.messageTime;i.messageId=v,i.llmModel=_,i.messageTime=M,i.sessionId=s}g==="over"?i.index=-1:(i.code=l.code,i.message=l.message),n!=null&&n.onmessage&&n.onmessage(i)},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const f=y(u({},i),{isReplying:!1});n!=null&&n.onclose&&n.onclose(f)}})})}sendQuestion(t,s){return p(this,null,function*(){var d;const{content:a,fileIds:r,oldMessageId:n}=t,{stream:c,referenceFirst:i}=s;if(this.active||(yield this.activate()),this._id){let f={content:a,fileIds:r,referenceFirst:i,oldMessageId:n,promptVariables:this.promptVariables.reduce((l,g)=>y(u({},l),{[g.key]:g.value}),{}),knowledges:(d=this.knowledges)==null?void 0:d.map(l=>l.id)};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,f,this.ctrl.signal,{onopen:()=>{W.log("open",this.ctrl)},onmessage:l=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===w.ChatMessageRole.Robot?(g=u(u({},g),l),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(l),this.event.emit("message:content",l))},onclose:l=>p(this,null,function*(){this._stopAnswer||(W.log(l,"onclose"),this.event.emit("answer:finish",l))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}}const Ie=new b("[BotClient] ");class _e{constructor(e,t,s=!0){m(this,"event",new Z);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=s,z(t),this._applicationId=V(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(a=>{z(y(u({},t),{stream:t.stream===void 0?(a==null?void 0:a.type)===w.ApplicationTypes.Dialog:t.stream})),this.event.emit("ready")})}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return p(this,null,function*(){var t,s,a;this._application=yield this.cvforceApi.getApplicationId(this._applicationId).then(r=>(typeof r.arrange[0].recommendQuestionOpen!="boolean"&&(r.arrange[0].recommendQuestionOpen=!0),y(u({},r),{arrange:[y(u({},r.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&r.arrange[0].recommendQuestionOpen})]})));const e=(a=(s=(t=this._application)==null?void 0:t.arrange)==null?void 0:s[0])==null?void 0:a.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(r=>r.maxModelLength)),this._promptVariables=yield this.cvforceApi.getPrompts(this._applicationId),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:X(exports.configuration.apiRoot,this.token,(e,t)=>Ie.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=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,r){return p(this,null,function*(){const n=this;return new Promise((c,i)=>{const d=f=>p(this,null,function*(){if(f===w.ApplicationTypes.Agent)c(new fe(e,t,s,a,r,n));else if(f===w.ApplicationTypes.Dialog)c(new we(e,t,s,a,r,n));else throw Error(`不支持的应用类型:${f}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return p(this,null,function*(){return new Promise((t,s)=>{const a=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>{const n=[];return r.forEach(c=>p(this,null,function*(){const i=this._sessions.find(d=>c.id===d.id);if(i)i.data=c,this._application?i.application=this._application:i.loadApplicationInfo(),n.push(i);else{const d=yield this.createSession(this.token,c.id,c,this.lazyload,this._application||void 0);n.push(d)}})),this.sessions=n,n});if(this.ready){if(!this._application)throw Error("_application is null");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(r=>r.id===e):this._activeSession;if(!a){console.warn("setTop session failed.");return}return yield a.setTop(t),this.getSessions({order:s})})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return 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 Se{constructor(e,t={},s){m(this,"code");m(this,"description","");m(this,"loaded",!1);m(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}exports.AgentPlugin=Se;exports.BotClient=_e;exports.Session=q;exports.configure=z;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glodon-aiot/agent-cli-sdk",
3
- "version": "3.25.0-alpha.9",
3
+ "version": "3.25.0",
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.25.0-alpha.9",
82
+ "@glodon-aiot/apis": "^3.25.0",
83
83
  "axios": "0.24.0",
84
84
  "buffer": "^6.0.3",
85
85
  "dayjs": "^1.11.13",