@glodon-aiot/agent-cli-sdk 3.1.0-beta.16 → 3.2.2-beta.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.
- package/dist/agent-cli-sdk.js +33145 -0
- package/dist/agent-cli-sdk.umd.cjs +140 -0
- package/dist/src/AgentSession.d.ts +2 -2
- package/dist/src/BotClient.d.ts +2 -2
- package/dist/src/Config.d.ts +2 -0
- package/dist/src/DialogSession.d.ts +2 -2
- package/dist/src/Session.d.ts +11 -9
- package/dist/src/__ tests __/AgentClient.spec.d.ts +1 -0
- package/dist/src/__ tests __/AgentSession.spec.d.ts +1 -0
- package/dist/src/__ tests __/DialogClient.spec.d.ts +1 -0
- package/dist/src/api/fetchEventSource/fetch.d.ts +1 -1
- package/dist/src/api/fetchEventSource/index.d.ts +1 -1
- package/package.json +20 -16
- package/dist/es/AgentPlugin.mjs +0 -20
- package/dist/es/AgentSession.mjs +0 -246
- package/dist/es/BotClient.mjs +0 -236
- package/dist/es/Config.mjs +0 -34
- package/dist/es/DialogSession.mjs +0 -274
- package/dist/es/EventBus.mjs +0 -64
- package/dist/es/Logger.mjs +0 -31
- package/dist/es/PayloadTypes.mjs +0 -4
- package/dist/es/Session.mjs +0 -690
- package/dist/es/api/fetchEventSource/fetch.mjs +0 -112
- package/dist/es/api/fetchEventSource/parse.mjs +0 -97
- package/dist/es/api/index.mjs +0 -41
- package/dist/es/index.mjs +0 -11
- package/dist/es/utils.mjs +0 -11
- package/dist/lib/index.js +0 -4
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
var W = Object.defineProperty, j = Object.defineProperties;
|
|
2
|
-
var k = Object.getOwnPropertyDescriptors;
|
|
3
|
-
var v = Object.getOwnPropertySymbols;
|
|
4
|
-
var A = Object.prototype.hasOwnProperty, R = Object.prototype.propertyIsEnumerable;
|
|
5
|
-
var I = (t, e, a) => e in t ? W(t, e, { enumerable: !0, configurable: !0, writable: !0, value: a }) : t[e] = a, E = (t, e) => {
|
|
6
|
-
for (var a in e || (e = {}))
|
|
7
|
-
A.call(e, a) && I(t, a, e[a]);
|
|
8
|
-
if (v)
|
|
9
|
-
for (var a of v(e))
|
|
10
|
-
R.call(e, a) && I(t, a, e[a]);
|
|
11
|
-
return t;
|
|
12
|
-
}, $ = (t, e) => j(t, k(e));
|
|
13
|
-
var q = (t, e) => {
|
|
14
|
-
var a = {};
|
|
15
|
-
for (var n in t)
|
|
16
|
-
A.call(t, n) && e.indexOf(n) < 0 && (a[n] = t[n]);
|
|
17
|
-
if (t != null && v)
|
|
18
|
-
for (var n of v(t))
|
|
19
|
-
e.indexOf(n) < 0 && R.call(t, n) && (a[n] = t[n]);
|
|
20
|
-
return a;
|
|
21
|
-
};
|
|
22
|
-
var B = (t, e, a) => new Promise((n, w) => {
|
|
23
|
-
var o = (r) => {
|
|
24
|
-
try {
|
|
25
|
-
c(a.next(r));
|
|
26
|
-
} catch (d) {
|
|
27
|
-
w(d);
|
|
28
|
-
}
|
|
29
|
-
}, i = (r) => {
|
|
30
|
-
try {
|
|
31
|
-
c(a.throw(r));
|
|
32
|
-
} catch (d) {
|
|
33
|
-
w(d);
|
|
34
|
-
}
|
|
35
|
-
}, c = (r) => r.done ? n(r.value) : Promise.resolve(r.value).then(o, i);
|
|
36
|
-
c((a = a.apply(t, e)).next());
|
|
37
|
-
});
|
|
38
|
-
import { getBytes as z, getLines as G, getMessages as H } from "./parse.mjs";
|
|
39
|
-
const g = "text/event-stream", J = 1e3, D = "last-event-id";
|
|
40
|
-
function X(t, N) {
|
|
41
|
-
var u = N, {
|
|
42
|
-
signal: e,
|
|
43
|
-
headers: a,
|
|
44
|
-
onopen: n,
|
|
45
|
-
onmessage: w,
|
|
46
|
-
onclose: o,
|
|
47
|
-
onerror: i,
|
|
48
|
-
openWhenHidden: c,
|
|
49
|
-
fetch: r
|
|
50
|
-
} = u, d = q(u, [
|
|
51
|
-
"signal",
|
|
52
|
-
"headers",
|
|
53
|
-
"onopen",
|
|
54
|
-
"onmessage",
|
|
55
|
-
"onclose",
|
|
56
|
-
"onerror",
|
|
57
|
-
"openWhenHidden",
|
|
58
|
-
"fetch"
|
|
59
|
-
]);
|
|
60
|
-
return new Promise((L, M) => {
|
|
61
|
-
const f = E({}, a);
|
|
62
|
-
f.accept || (f.accept = g);
|
|
63
|
-
let l;
|
|
64
|
-
function C() {
|
|
65
|
-
l.abort(), document.hidden || b();
|
|
66
|
-
}
|
|
67
|
-
c || document.addEventListener("visibilitychange", C);
|
|
68
|
-
let T = J, y = 0;
|
|
69
|
-
function h() {
|
|
70
|
-
document.removeEventListener("visibilitychange", C), window.clearTimeout(y), l.abort();
|
|
71
|
-
}
|
|
72
|
-
e == null || e.addEventListener("abort", () => {
|
|
73
|
-
h(), L();
|
|
74
|
-
});
|
|
75
|
-
const P = r != null ? r : window.fetch, V = n != null ? n : K;
|
|
76
|
-
function b() {
|
|
77
|
-
return B(this, null, function* () {
|
|
78
|
-
var x;
|
|
79
|
-
l = new AbortController();
|
|
80
|
-
try {
|
|
81
|
-
const m = yield P(t, $(E({}, d), {
|
|
82
|
-
headers: f,
|
|
83
|
-
signal: l.signal
|
|
84
|
-
}));
|
|
85
|
-
yield V(m), yield z(m.body, G(H((s) => {
|
|
86
|
-
s ? f[D] = s : delete f[D];
|
|
87
|
-
}, (s) => {
|
|
88
|
-
T = s;
|
|
89
|
-
}, w))), o == null || o(), h(), L();
|
|
90
|
-
} catch (m) {
|
|
91
|
-
if (!l.signal.aborted)
|
|
92
|
-
try {
|
|
93
|
-
const s = (x = i == null ? void 0 : i(m)) != null ? x : T;
|
|
94
|
-
window.clearTimeout(y), y = window.setTimeout(b, s);
|
|
95
|
-
} catch (s) {
|
|
96
|
-
h(), M(s);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
b();
|
|
102
|
-
});
|
|
103
|
-
}
|
|
104
|
-
function K(t) {
|
|
105
|
-
const e = t.headers.get("content-type");
|
|
106
|
-
if (!(e != null && e.startsWith(g)))
|
|
107
|
-
throw new Error(`Expected content-type to be ${g}, Actual: ${e}`);
|
|
108
|
-
}
|
|
109
|
-
export {
|
|
110
|
-
g as EventStreamContentType,
|
|
111
|
-
X as fetchEventSource
|
|
112
|
-
};
|
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
var b = (s, t, e) => new Promise((a, c) => {
|
|
2
|
-
var f = (r) => {
|
|
3
|
-
try {
|
|
4
|
-
i(e.next(r));
|
|
5
|
-
} catch (n) {
|
|
6
|
-
c(n);
|
|
7
|
-
}
|
|
8
|
-
}, l = (r) => {
|
|
9
|
-
try {
|
|
10
|
-
i(e.throw(r));
|
|
11
|
-
} catch (n) {
|
|
12
|
-
c(n);
|
|
13
|
-
}
|
|
14
|
-
}, i = (r) => r.done ? a(r.value) : Promise.resolve(r.value).then(f, l);
|
|
15
|
-
i((e = e.apply(s, t)).next());
|
|
16
|
-
});
|
|
17
|
-
function w(s, t) {
|
|
18
|
-
return b(this, null, function* () {
|
|
19
|
-
const e = s.getReader();
|
|
20
|
-
let a;
|
|
21
|
-
for (; !(a = yield e.read()).done; )
|
|
22
|
-
t(a.value);
|
|
23
|
-
});
|
|
24
|
-
}
|
|
25
|
-
function g(s) {
|
|
26
|
-
let t, e, a, c = !1, f;
|
|
27
|
-
return function(i) {
|
|
28
|
-
t === void 0 ? (t = i, e = 0, a = -1, f = !1) : t = h(t, i);
|
|
29
|
-
const r = t.length;
|
|
30
|
-
let n = 0;
|
|
31
|
-
for (; e < r; ) {
|
|
32
|
-
c && (t[e] === 10 && (n = ++e), c = !1);
|
|
33
|
-
let o = -1;
|
|
34
|
-
for (; e < r && o === -1; ++e)
|
|
35
|
-
switch (t[e]) {
|
|
36
|
-
case 58:
|
|
37
|
-
a === -1 && (a = e - n);
|
|
38
|
-
break;
|
|
39
|
-
case 13:
|
|
40
|
-
c = !1, e + 4 < r && t[e + 1] === 10 && t[e + 2] !== 13 && t[e - 1] !== 10 && t[e - 2] !== 13 && (f = !0);
|
|
41
|
-
case 10:
|
|
42
|
-
o = e;
|
|
43
|
-
break;
|
|
44
|
-
}
|
|
45
|
-
if (o === -1)
|
|
46
|
-
break;
|
|
47
|
-
s(t.subarray(n, o), a, f), n = e, a = -1, f = !1;
|
|
48
|
-
}
|
|
49
|
-
n === r ? t = void 0 : n !== 0 && (t = t.subarray(n), e -= n);
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
function k(s, t, e) {
|
|
53
|
-
let a = y();
|
|
54
|
-
const c = new TextDecoder();
|
|
55
|
-
return function(l, i, r) {
|
|
56
|
-
if (l.length === 0)
|
|
57
|
-
e == null || e(a), a = y();
|
|
58
|
-
else if (i > 0) {
|
|
59
|
-
const n = c.decode(l.subarray(0, i)), o = i + (l[i + 1] === 32 ? 2 : 1);
|
|
60
|
-
let d = c.decode(l.subarray(o));
|
|
61
|
-
switch (r && (d += `
|
|
62
|
-
`), n) {
|
|
63
|
-
case "data":
|
|
64
|
-
a.data = a.data ? a.data + `
|
|
65
|
-
` + d : d;
|
|
66
|
-
break;
|
|
67
|
-
case "event":
|
|
68
|
-
a.event = d;
|
|
69
|
-
break;
|
|
70
|
-
case "id":
|
|
71
|
-
s(a.id = d);
|
|
72
|
-
break;
|
|
73
|
-
case "retry":
|
|
74
|
-
const u = parseInt(d, 10);
|
|
75
|
-
isNaN(u) || t(a.retry = u);
|
|
76
|
-
break;
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
function h(s, t) {
|
|
82
|
-
const e = new Uint8Array(s.length + t.length);
|
|
83
|
-
return e.set(s), e.set(t, s.length), e;
|
|
84
|
-
}
|
|
85
|
-
function y() {
|
|
86
|
-
return {
|
|
87
|
-
data: "",
|
|
88
|
-
event: "",
|
|
89
|
-
id: "",
|
|
90
|
-
retry: void 0
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
export {
|
|
94
|
-
w as getBytes,
|
|
95
|
-
g as getLines,
|
|
96
|
-
k as getMessages
|
|
97
|
-
};
|
package/dist/es/api/index.mjs
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
var d = Object.defineProperty, h = Object.defineProperties;
|
|
2
|
-
var x = Object.getOwnPropertyDescriptors;
|
|
3
|
-
var c = Object.getOwnPropertySymbols;
|
|
4
|
-
var E = Object.prototype.hasOwnProperty, I = Object.prototype.propertyIsEnumerable;
|
|
5
|
-
var a = (t, e, o) => e in t ? d(t, e, { enumerable: !0, configurable: !0, writable: !0, value: o }) : t[e] = o, f = (t, e) => {
|
|
6
|
-
for (var o in e || (e = {}))
|
|
7
|
-
E.call(e, o) && a(t, o, e[o]);
|
|
8
|
-
if (c)
|
|
9
|
-
for (var o of c(e))
|
|
10
|
-
I.call(e, o) && a(t, o, e[o]);
|
|
11
|
-
return t;
|
|
12
|
-
}, p = (t, e) => h(t, x(e));
|
|
13
|
-
import S from "axios";
|
|
14
|
-
import { isExpired as $ } from "../utils.mjs";
|
|
15
|
-
import { CVForceApi as C } from "@glodon-aiot/apis";
|
|
16
|
-
function z(t, e, o) {
|
|
17
|
-
const m = (r) => {
|
|
18
|
-
var i;
|
|
19
|
-
return e && ($(e) && o(403, "aiotToken is timeout"), r.headers = (i = r.headers) != null ? i : {}, r.headers = p(f({}, r.headers), {
|
|
20
|
-
Authorization: e ? `Bearer ${e}` : ""
|
|
21
|
-
})), r;
|
|
22
|
-
};
|
|
23
|
-
function u(r, i = !0) {
|
|
24
|
-
const n = `${t}${r}`, s = S.create({
|
|
25
|
-
baseURL: n
|
|
26
|
-
});
|
|
27
|
-
return i && s.interceptors.request.use(m), s;
|
|
28
|
-
}
|
|
29
|
-
const g = (r, i) => {
|
|
30
|
-
r === 401 && o(r, "aiotToken is invalid");
|
|
31
|
-
}, v = (r, i) => {
|
|
32
|
-
r !== 10001 && r !== 10215 && o(r, i);
|
|
33
|
-
}, A = u("/data/v1");
|
|
34
|
-
return new C(A, {
|
|
35
|
-
onHttpStatusError: g,
|
|
36
|
-
onAppStatusError: v
|
|
37
|
-
});
|
|
38
|
-
}
|
|
39
|
-
export {
|
|
40
|
-
z as getCVForceService
|
|
41
|
-
};
|
package/dist/es/index.mjs
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { configuration as t, configure as r } from "./Config.mjs";
|
|
2
|
-
import { default as a } from "./BotClient.mjs";
|
|
3
|
-
import { default as i } from "./Session.mjs";
|
|
4
|
-
import { default as l } from "./AgentPlugin.mjs";
|
|
5
|
-
export {
|
|
6
|
-
l as AgentPlugin,
|
|
7
|
-
a as BotClient,
|
|
8
|
-
i as Session,
|
|
9
|
-
t as configuration,
|
|
10
|
-
r as configure
|
|
11
|
-
};
|
package/dist/es/utils.mjs
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { decode as n } from "js-base64";
|
|
2
|
-
const c = (e) => JSON.parse(n(e.split(".")[1])), i = (e) => {
|
|
3
|
-
const r = c(e).exp;
|
|
4
|
-
return (/* @__PURE__ */ new Date()).valueOf() / 1e3 >= r;
|
|
5
|
-
}, a = (e) => e == null ? void 0 : e.replace(/[\r\n]+/gm, ""), p = (e) => e.replace(/\\|\\/g, "");
|
|
6
|
-
export {
|
|
7
|
-
i as isExpired,
|
|
8
|
-
c as parseJWT,
|
|
9
|
-
p as removeLeadingAndTrailingBackslashes,
|
|
10
|
-
a as removeNewlines
|
|
11
|
-
};
|
package/dist/lib/index.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
"use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var C=Object.getOwnPropertySymbols;var D=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var z=(r,e,t)=>e in r?se(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,u=(r,e)=>{for(var t in e||(e={}))D.call(e,t)&&z(r,t,e[t]);if(C)for(var t of C(e))B.call(e,t)&&z(r,t,e[t]);return r},I=(r,e)=>ie(r,ne(e));var F=(r,e)=>{var t={};for(var s in r)D.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&C)for(var s of C(r))e.indexOf(s)<0&&B.call(r,s)&&(t[s]=r[s]);return t};var m=(r,e,t)=>(z(r,typeof e!="symbol"?e+"":e,t),t);var p=(r,e,t)=>new Promise((s,a)=>{var o=i=>{try{l(t.next(i))}catch(c){a(c)}},n=i=>{try{l(t.throw(i))}catch(c){a(c)}},l=i=>i.done?s(i.value):Promise.resolve(i.value).then(o,n);l((t=t.apply(r,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),oe=require("axios"),w=require("@glodon-aiot/apis"),re=require("socket.io-client"),J=require("uuid"),K=require("dayjs"),R=class R{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!R.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!R.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!R.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!R.debug||console.warn(this.prefix,...e)}};m(R,"debug",!1);let b=R;const ce=new b("[Config] ");var U=(r=>(r.dev="https://aiot-dev.glodon.com/api/cvforcepd",r.test="https://aiot-dev.glodon.com/api/cvforce",r.prod="https://copilot.glodon.com/api/cvforce",r.local="http://localhost:3000/api/cvforcepd",r))(U||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{}};function G(r){b.debug=(r==null?void 0:r.debug)||!1,exports.configuration=I(u(u({},exports.configuration),r),{apiRoot:(r==null?void 0:r.apiRoot)||exports.configuration.apiRoot||(r!=null&&r.env?U[r.env||"prod"]:exports.configuration.apiRoot)}),b.debug&&ce.log("updated",exports.configuration)}const T=r=>JSON.parse(ae.decode(r.split(".")[1])),de=r=>{const e=T(r).exp;return new Date().valueOf()/1e3>=e},he=r=>r==null?void 0:r.replace(/[\r\n]+/gm,""),le=r=>r.replace(/\\|\\/g,"");function X(r,e,t){const s=c=>{var f;return e&&(de(e)&&t(403,"aiotToken is timeout"),c.headers=(f=c.headers)!=null?f:{},c.headers=I(u({},c.headers),{Authorization:e?`Bearer ${e}`:""})),c};function a(c,f=!0){const d=`${r}${c}`,g=oe.create({baseURL:d});return f&&g.interceptors.request.use(s),g}const o=(c,f)=>{c===401&&t(c,"aiotToken is invalid")},n=(c,f)=>{c!==10001&&c!==10215&&t(c,f)},l=a("/data/v1");return new w.CVForceApi(l,{onHttpStatusError:o,onAppStatusError:n})}var L=(r=>(r[r.Normal=0]="Normal",r[r.Debug=1]="Debug",r))(L||{});const k=new b("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&k.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),k.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?k.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),k.log(`remove event ${e} listener`))}else k.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){k.log(`event ${e} listeners is empty`);return}const s=[];for(let a=0;a<this.eventListenerMap[e].length;a++){const o=this.eventListenerMap[e][a];typeof o=="function"?o(t):s.push(o)}s.forEach(a=>{a&&(a.fn(t),this.off(e,a.fn))}),k.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const A=new b("[Session] ");var E=(r=>(r.DataRequestFailed="data request error",r.SocketConnectionFailed="socket error",r.IdUndefined="session id is not defined",r.SendingEmptyContent="failed at sending empty content",r.Frozen="session is frozen",r.UserModeError="failed at setting socket user mode",r.Inactive="session is inactive",r))(E||{});class Q{constructor(e,t="",s,a,o,n){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new Z);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);this.token=e,this.lazyload=a,this.client=n||null,this._applicationId=T(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),o&&(this._application=o),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var l;if(t)this._id=t,this.event.emit("data:loading"),s?(this.data=s,a||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(i=>p(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data)})))):(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(i=>p(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoading=!1,this._dataLoaded=!0})));else{const i=(s==null?void 0:s.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:i}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:i,netOpen:s==null?void 0:s.netOpen,knowledgeList:(l=s==null?void 0:s.knowledges)==null?void 0:l.map(c=>c.id),applicationId:this._applicationId}).then(c=>p(this,null,function*(){this._id=c.id,this.data=c,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),yield(()=>{if(s!=null&&s.knowledges)return this.setKnowledges((s==null?void 0:s.knowledges)||void 0)})(),yield(()=>{if(s!=null&&s.promptVariables){const f=this._promptVariables.map(d=>{var h,v;const g=((v=(h=s.promptVariables)==null?void 0:h.find(y=>y.key===d.key))==null?void 0:v.value)||"";return I(u({},d),{value:g})}).sort((d,g)=>d.key.localeCompare(g.key));return this.setPromptVariables(f||[])}else return})(),this.event.emit("data:created",this.data),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._ready=!0,this.event.emit("ready")}))}})}fetchData(){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.getSession(this.applicationId,this.data.id).then(e=>p(this,null,function*(){return this.data=e,this.event.emit("data:updated",this.data),e}))})}get id(){var e;return this._id||((e=this.data)==null?void 0:e.id)||""}get applicationId(){return this._applicationId}get application(){return this._application}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*(){var t;if(((t=this._application)==null?void 0:t.type)===w.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setKnowledges.");return}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.key!=="query")}setPromptVariables(e){return p(this,null,function*(){var s;if(((s=this._application)==null?void 0:s.type)===w.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setPromptVariables.");return}const t=this._promptVariables.map(a=>{var n;const o=((n=e==null?void 0:e.find(l=>l.key===a.key))==null?void 0:n.value)||a.value;return I(u({},a),{value:o})}).sort((a,o)=>a.key.localeCompare(o.key));if(yield Promise.all(t.filter(a=>a.key!=="query").map(a=>{if(!this.data)throw Error("session data is not loaded");if(!(!a.id||!a.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,a.id,{value:a.value}).catch(console.error)})),!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return p(this,null,function*(){var t,s,a;if(A.log("setNetOpen:",e),A.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===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,A.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return X(exports.configuration.apiRoot,this.token,(e,t)=>{const s=new Error("data request error");A.error(s),this.event.emit("error",s)})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}fetchMessages(){return p(this,arguments,function*(e={}){var s,a;const t={pageSize:this._loadingMessagesSize};if(this._id){e=u(u({},t),e),this.event.emit("history:loading"),A.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),A.log("history:moreloading",e)),this._loadingMessages=!0;const o=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),n=o.map((i,c)=>{var g,h;let f=[],d;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),[])),c===o.length-1&&(d=(h=this.data)==null?void 0:h.lastRelatedQuestion),I(u({},i),{actions:f,relatedQuesion:d})});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(c=>c.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(c=>c.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),c=this.messages.findLastIndex(f=>f.ts===e.endTime);this.messages.splice(i,c-i+1,...n)}const l=this.messages[this.messages.length-1];return l&&!l.relatedQuesion&&(l.relatedQuesion=(a=this.data)==null?void 0:a.lastRelatedQuestion),this.event.emit("history:moreloaded",n),A.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,n}else{const o=new Error("session id is not defined");return A.error(o),this.event.emit("error",o),!1}})}rename(e){return p(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),A.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return p(this,null,function*(){this.messages.push(e),A.log("history:add",e),this.event.emit("history:add",e),this.event.emit("message:new",e),this.event.emit("message:updated",e)})}reloadSessionInfo(){if(!this._id)throw Error("session is not created yet");return this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,this._id).then(e=>p(this,null,function*(){if(this.data=e,!this._id)throw Error("session is not created yet");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),A.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>p(this,null,function*(){return this.messages=[],yield this.fetchMessages(),this._dataLoading=!1,this._dataLoaded=!0,this.event.emit("data:loaded",this.data),this}))}reload(){return p(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return p(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return A.error(e),this.event.emit("error",e),!1}return this.event.emit("data:deleting"),yield this.cvforceApi.delSessionsId(this.applicationId,this.id),this.event.emit("data:deleted"),this.destroy()})}activate(){return p(this,null,function*(){if(this.activing)return new Promise(t=>{this.addEventListener("activated",()=>{t(!0)},!0)});if(!this._id)throw Error("session is not avalible. id is undefined");this.activing=!0;const e=this._id;return this._dataLoading=!0,this._dataLoaded=!1,this.data=yield this.cvforceApi.getSession(this.applicationId,e).then(t=>p(this,null,function*(){return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,e),t})),this.messages.length||(this.messages=[],yield this.fetchMessages()),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoaded=!0,this._dataLoading=!1,this.inactivating=!1,this.frozen=!0,yield this.prepareConnection(),this.event.emit("activated",this.socket),this.active=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?this._frozen?(e||(this.inactivating=!0),this.activing=!1,!0):(this.socket.close(),this.socket=null,this.event.emit("inactivated"),this.active=!1,this.activing=!1,!0):(this.activing=!1,!0)}get dataLoaded(){return this._dataLoaded}get messagesLoading(){return this._loadingMessages}send(s){return p(this,arguments,function*(e,t={stream:!1}){var g;try{this.validateConfigs()}catch(h){console.error(h)}const{stream:a=!1,referenceFirst:o=!1}=t,n=e.uuid||J.v4(),l=((g=e.text)==null?void 0:g.trim())||"",i=e.fileIds;if(!l&&!(i!=null&&i.length)){const h=new Error("failed at sending empty content");return A.error(h),this.event.emit("error",h),!1}if(!this._id){const h=new Error("session id is not defined");return A.error(h),this.event.emit("error",h),!1}if(this.frozen){const h=new Error("session is frozen");return A.error(h),this.event.emit("error",h),!1}this.frozen=!0,this._stopAnswer=!1;const c={sessionId:this.id,role:2,content:l,messageId:n,reference:[],searchReference:[],messageTime:""},f={content:l,stream:a,requestId:n,fileIds:i,referenceFirst:o};this.pushMessage(c),this.event.emit("question:content",l);const d=h=>p(this,null,function*(){if(h.role!==w.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",d),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 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)}const v=yield this.getRelatedQuesion(h);h=u(u({},h),v),h.isLoading=!1;let y=this.messages[this.messages.length-1];if(y&&y.role===w.ChatMessageRole.Robot){const _=u(u({},y),h);this.messages[this.messages.length-1]=_,this.event.emit("message:updated",_)}else this.pushMessage(h);this.frozen=!1});return this.addEventListener("answer:finish",d),this.sendQuestion(f,I(u({},t),{stream:a,referenceFirst:o})),c})}getRelatedQuesion(e){return p(this,null,function*(){var o;if(!e.content||e.isSensitive||e.code!==200)return e;this.event.emit("message:relatedQuesion:loading",e);const t=yield this.cvforceApi.postGeneques({content:e.content}).catch(n=>null);if(!t){const n=[],l=I(u({},e),{relatedQuesion:n,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:n}),l}const s=(o=t.content)==null?void 0:o.split("*").map(he).map(le).filter(n=>!!n);e.relatedQuesion=s,e.index=-3,e.isLoading=!1;const a=I(u({},e),{relatedQuesion:s,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",a),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:s}),a})}fillMessageReference(e){return p(this,null,function*(){var t;return(t=e.reference)==null||t.forEach((s,a)=>p(this,null,function*(){const o=yield this.cvforceApi.getKnowledgeIdFileId(s.knowledgeId,s.docId);e.reference[a]=u(u({},s),o)})),e})}answerAgain(){return p(this,arguments,function*(e={stream:!1}){const t=this.messages[this.messages.length-1];if(!t)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1;const{stream:s=!1}=e;let a;t.role!==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 o=this.messages[this.messages.length-1],n={content:o.content,fileIds:o.fileIds,requestId:o.messageId,stream:s,oldMessageId:a},l=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 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)}const c=yield this.getRelatedQuesion(i);this.event.emit("message:updated",c),this.removeEventListener("message:content",l),this.frozen=!1}});this.addEventListener("message:content",l),this.sendQuestion(n,I(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 o=a[a.length-1];if(o&&(o.type==="BEFORE_CALL"||o.type==="FUNCTION_CALL")){const{pluginName:n,pluginCode:l,funcCode:i,funcName:c}=o.data;a.push({data:{pluginName:n,pluginCode:l,funcCode:i,funcName:c,step:o.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:a})}}}e=u(u({},e),t),this.event.emit("message:content",e),this.event.emit("message:updated",e)}else this.pushMessage(t),this.event.emit("message:content",t);return this}postMessageComment(e){return p(this,null,function*(){if(!this._applicationId||!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.postComments(this._applicationId,this._id,e).then(t=>{const s=this.messages.find(a=>a.messageId===e.messageId);return s&&(s.comment=e,this.event.emit("message:comment",s)),t})})}clear(){if(!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.patchApplicationIdSessionsIdContext(this._applicationId,this._id).then(()=>(this.event.emit("context:clear"),!0))}destroy(){var e;return this._ready=!1,this.event.removeAllListeners(),(e=this.socket)==null||e.disconnect(),this.socket=null,this.event.emit("destroy",{applicationId:this._applicationId,sessionId:this._id}),this._id||""}}const S=new b("[AgentSession] ");class fe extends Q{constructor(e,t="",s,a,o,n){super(e,t,s,a,o,n)}prepareConnection(){return new Promise(e=>p(this,null,function*(){this.socket&&e(!0);const t={version:"1.0",stream:"false",appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?L.Debug:L.Normal},s=new URL(exports.configuration.apiRoot),a=yield re.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});a.on("connect",()=>{S.log("socket:connect"),this.event.emit("socket:connect"),a.emit("init")}),a.on("disconnect",()=>{S.log("socket:disconnect"),this.event.emit("socket:disconnect")}),a.on("ready",o=>{if(o.code===200){S.log("ready");const n=exports.configuration.debug?L.Debug:L.Normal;n===L.Debug&&o.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,e(!0)}else{this._ready&&(this._ready=!1);const n=new Error(E.SocketConnectionFailed);S.error("error",n),this.event.emit("error",n),e(!1)}}),a.on("action",(o,n)=>p(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:l,data:{runnerIsClient:i,pluginCode:c,funcCode:f,parameters:d,requestBody:g}}=o,h=this.messages[this.messages.length-1];if(!h.messageId)h.actions||(h.actions=[]),h.actions[o.data.step-1]||(h.actions[o.data.step-1]=[]),h.actions[o.data.step-1].push(o),this.event.emit("message:action",{messageId:h.messageId,action:o}),this.event.emit("message:updated",h);else{const v={messageId:"",content:"",role:w.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[o]],comment:{isAgree:0}};this.pushMessage(v),this.event.emit("message:action",{messageId:v.messageId,action:o})}if(this.inactivating){const v=new Error(E.Inactive);S.warn("error",v),this.event.emit("error",v)}else if(l==="FUNCTION_CALL"&&i){if(S.log(`calling function ${f} of plugin ${c} with argument:
|
|
2
|
-
${JSON.stringify(d)}`),!exports.configuration.plugins[c]){n({code:404,message:"对不起,没有找到插件。"});return}const v=exports.configuration.plugins[c][f];typeof v!="function"&&n({code:404,message:"对不起,没有找到插件方法。"});let y=d==null?void 0:d.query;try{y=JSON.parse(d==null?void 0:d.query)}catch(_){}v(y,(..._)=>{this._stopAnswer||n(..._)})}})),a.on("answer",o=>{if(!this._stopAnswer)if(o.data.code!==200&&(o.data.index=-1,this.event.emit("error",o.data)),o.data.index===-1){let n=this.messages[this.messages.length-1];if(n&&!n.messageId)n=u(u({},n),o.data),this.event.emit("message:content",n),this.event.emit("message:updated",n),this.event.emit("answer:finish",n);else{const l=u({messageId:"",content:"",role:w.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0}},o.data);this.event.emit("message:content",l),this.pushMessage(l),this.event.emit("answer:finish",l)}}else{let n=this.messages[this.messages.length-1];n&&!n.messageId?(n=u(u({},n),o.data),this.messages[this.messages.length-1]=n,this.event.emit("message:content",n),this.event.emit("message:updated",n)):(this.pushMessage(o.data),this.event.emit("message:content",o.data))}}),a.on("reference",o=>p(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const d=new Error(E.IdUndefined);S.error(d),this.event.emit("error",d),this.frozen=!1;return}const{type:n,data:l,requestId:i}=o,c=this.messages.findIndex(d=>d.messageId===i&&d.role===w.ChatMessageRole.User);if(c<0)return;const f=c+1;if(f>=this.messages.length){const d={messageId:"",content:"",role:w.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0}};this.pushMessage(d)}n==="KG"?(this.messages[f]=I(u({},this.messages[f]),{reference:l.knowledgeReference}),yield this.fillMessageReference(this.messages[f]),this.event.emit("message:reference",l.knowledgeReference),this.event.emit("message:updated",this.messages[f])):n==="WEB_SEARCH"&&(this.messages[f]=I(u({},this.messages[f]),{searchReference:l.knowledgeReference}),this.event.emit("message:searchreference",l.searchReference),this.event.emit("message:updated",this.messages[f]))})),this.socket=a,a.open()}))}sendQuestion(e,t){return p(this,null,function*(){var s,a;if(!this.active){if(yield this.activate(),!this.socket){const o=new Error(E.SocketConnectionFailed);return S.warn("error",o),this.event.emit("error",o),!1}(s=this.socket)==null||s.emit("question",e);return}(a=this.socket)==null||a.emit("question",e)})}stopAnswer(){var e;(e=this.socket)==null||e.emit("stop_answer")}}function pe(r,e){return p(this,null,function*(){const t=r.getReader();let s;for(;!(s=yield t.read()).done;)e(s.value)})}function ge(r){let e,t,s,a=!1,o;return function(l){e===void 0?(e=l,t=0,s=-1,o=!1):e=me(e,l);const i=e.length;let c=0;for(;t<i;){a&&(e[t]===10&&(c=++t),a=!1);let f=-1;for(;t<i&&f===-1;++t)switch(e[t]){case 58:s===-1&&(s=t-c);break;case 13:a=!1,t+4<i&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(o=!0);case 10:f=t;break}if(f===-1)break;r(e.subarray(c,f),s,o),c=t,s=-1,o=!1}c===i?e=void 0:c!==0&&(e=e.subarray(c),t-=c)}}function ue(r,e,t){let s=j();const a=new TextDecoder;return function(n,l,i){if(n.length===0)t==null||t(s),s=j();else if(l>0){const c=a.decode(n.subarray(0,l)),f=l+(n[l+1]===32?2:1);let d=a.decode(n.subarray(f));switch(i&&(d+=`
|
|
3
|
-
`),c){case"data":s.data=s.data?s.data+`
|
|
4
|
-
`+d:d;break;case"event":s.event=d;break;case"id":r(s.id=d);break;case"retry":const g=parseInt(d,10);isNaN(g)||e(s.retry=g);break}}}}function me(r,e){const t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function j(){return{data:"",event:"",id:"",retry:void 0}}const O="text/event-stream",ve=1e3,H="last-event-id";function Y(r,f){var d=f,{signal:e,headers:t,onopen:s,onmessage:a,onclose:o,onerror:n,openWhenHidden:l,fetch:i}=d,c=F(d,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((g,h)=>{const v=u({},t);v.accept||(v.accept=O);let y;function _(){y.abort(),document.hidden||P()}l||document.addEventListener("visibilitychange",_);let N=ve,V=0;function $(){document.removeEventListener("visibilitychange",_),window.clearTimeout(V),y.abort()}e==null||e.addEventListener("abort",()=>{$(),g()});const ee=i!=null?i:window.fetch,te=s!=null?s:ye;function P(){return p(this,null,function*(){var q;y=new AbortController;try{const x=yield ee(r,I(u({},c),{headers:v,signal:y.signal}));yield te(x),yield pe(x.body,ge(ue(M=>{M?v[H]=M:delete v[H]},M=>{N=M},a))),o==null||o(),$(),g()}catch(x){if(!y.signal.aborted)try{const M=(q=n==null?void 0:n(x))!=null?q:N;window.clearTimeout(V),V=window.setTimeout(P,M)}catch(M){$(),h(M)}}})}P()})}function ye(r){const e=r.headers.get("content-type");if(!(e!=null&&e.startsWith(O)))throw new Error(`Expected content-type to be ${O}, Actual: ${e}`)}const W=new b("[DialogSession] ");class we extends Q{constructor(t,s="",a,o,n,l){super(t,s,a,o,n,l);m(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>p(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,s,a,o,n,l){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},c=I(u({},a),{stream:!0});Y(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(c),openWhenHidden:!0,signal:o,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: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 d=JSON.parse(f.data);if(i.reference=d.data.reference,i.searchReference=d.data.searchReference,i.messageTime=d.data.messageTime,i.messageId=d.data.messageId,i.llmModel=d.data.llmModel,i.content=d.data.content,i.code=d.code,d.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),l&&l({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,o,n,l){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:""},c=I(u({},a),{stream:!0});Y(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(c),openWhenHidden:!0,signal:o,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 d={};try{d=JSON.parse(f.data)}catch(v){console.error("parse eventData to JSON failed. ",f.data)}if(d.code!==200)return i.index=-1,i.code=d.code,i.message=d.message,n!=null&&n.onmessage&&n.onmessage(i),l&&l({code:d.code,message:d.message});const g=d.data.type,h=d.data.payload;if(i.isReplying=!0,g==="search"&&i.searchReference.push(h),g==="thinking"){i.thinkingStatus="start";const y=h.choices[0];i.reasoningContent=i.reasoningContent+y.delta.reasoningContent}if(g==="thinkingOver"){i.thinkingStatus="end";const v=h.thinkingSecs;i.thinkingSecs=v}if(g==="text"){const y=h.choices[0];i.content=i.content+y.delta.content}if(g==="reference"&&(i.reference=h),g==="result"){const v=h.messageId,y=h.llmModel,_=h.messageTime;i.messageId=v,i.llmModel=y,i.messageTime=_,i.sessionId=s}g==="over"?i.index=-1:(i.code=d.code,i.message=d.message),n!=null&&n.onmessage&&n.onmessage(i)},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const f=I(u({},i),{isReplying:!1});n!=null&&n.onclose&&n.onclose(f)}})})}sendQuestion(t,s){return p(this,null,function*(){var c;const{content:a,fileIds:o,oldMessageId:n}=t,{stream:l,referenceFirst:i}=s;if(this.active||(yield this.activate()),this._id){let f={content:a,fileIds:o,referenceFirst:i,oldMessageId:n,promptVariables:this.promptVariables.reduce((d,g)=>I(u({},d),{[g.key]:g.value}),{}),knowledges:(c=this.knowledges)==null?void 0:c.map(d=>d.id)};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,f,this.ctrl.signal,{onopen:()=>{W.log("open",this.ctrl)},onmessage:d=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===w.ChatMessageRole.Robot?(g=u(u({},g),d),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(d),this.event.emit("message:content",d))},onclose:d=>p(this,null,function*(){this._stopAnswer||(W.log(d,"onclose"),this.event.emit("answer:finish",d))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}}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,G(t),this._applicationId=T(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(()=>{this.event.emit("ready")})}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return p(this,null,function*(){var t,s;this._application=yield this.cvforceApi.getApplicationId(this._applicationId);const e=(s=(t=this._application.arrange)==null?void 0:t[0])==null?void 0:s.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(a=>a.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=T(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,s,a,o){return p(this,null,function*(){const n=this;return new Promise((l,i)=>{const c=f=>p(this,null,function*(){if(f===w.ApplicationTypes.Agent)l(new fe(e,t,s,a,o,n));else if(f===w.ApplicationTypes.Dialog)l(new we(e,t,s,a,o,n));else throw Error(`不支持的应用类型:${f}`)});if(this.ready){if(!this._application)throw Error("client is not ready");c(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");c(this._application.type)},!0)})})}getSessions(e){return p(this,null,function*(){return new Promise((t,s)=>{const a=()=>this.cvforceApi.listSessions(this._applicationId,e).then(o=>{const n=[];return o.forEach(l=>p(this,null,function*(){const i=this._sessions.find(c=>l.id===c.id);if(i)i.data=l,n.push(i);else{const c=yield this.createSession(this.token,l.id,l,this.lazyload,this._application||void 0);n.push(c)}})),this.sessions=n,n});if(this.ready){if(!this._application)throw Error("_application is null");t(a())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(a())},!0)})})}loadSession(e="",t){return p(this,null,function*(){this.checkReady();let s=this.sessions.find(a=>a.id===e);if(s||(s=yield this.createSession(this.token,e,t),this._sessions.push(s)),this._activeSession){if(this._activeSession===s)return s;this._activeSession.inactivate()}return s.id?(yield s.activate(),this._activeSession=s):s.addEventListener("data:loaded",()=>{this._activeSession!==s&&(s==null||s.activate(),this._activeSession=s)},!0),s})}reload(){return this.loadApplication().then(()=>p(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return p(this,null,function*(){yield this.reload();let t=this._sessions.find(s=>s.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,s="top_time desc, sort_status desc, updated_at desc"){return p(this,null,function*(){let a=e?this._sessions.find(o=>o.id===e):this._activeSession;if(!a){console.warn("setTop session failed.");return}return yield a.setTop(t),this.getSessions({order:s})})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return p(this,null,function*(){this.checkReady();let s=-1;if(typeof e=="string"?s=this._sessions.findIndex(a=>a.id===e):s=this._sessions.findIndex(a=>a.id===e.id),s>-1){const a=this._sessions[s];t&&(yield a.delete()),this._sessions.splice(s,1)}else console.warn("session delete failed, session is not exist.")})}clean(){this._sessions.forEach(e=>e.destroy()),this.sessions=[]}}class Ae{constructor(e,t={},s){m(this,"code");m(this,"description","");m(this,"loaded",!1);m(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}exports.AgentPlugin=Ae;exports.BotClient=_e;exports.Session=Q;exports.configure=G;
|