@glodon-aiot/bot-client-sdk 3.3.0-beta.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +157 -0
- package/dist/agent-cli-sdk.js +33141 -0
- package/dist/agent-cli-sdk.umd.cjs +140 -0
- package/dist/es/AgentPlugin.mjs +20 -0
- package/dist/es/AgentSession.mjs +285 -0
- package/dist/es/BotClient.mjs +250 -0
- package/dist/es/Config.mjs +36 -0
- package/dist/es/DialogSession.mjs +301 -0
- package/dist/es/EventBus.mjs +64 -0
- package/dist/es/Logger.mjs +31 -0
- package/dist/es/PayloadTypes.mjs +4 -0
- package/dist/es/Session.mjs +683 -0
- package/dist/es/api/fetchEventSource/fetch.mjs +112 -0
- package/dist/es/api/fetchEventSource/parse.mjs +97 -0
- package/dist/es/api/index.mjs +41 -0
- package/dist/es/index.mjs +11 -0
- package/dist/es/utils.mjs +11 -0
- package/dist/lib/index.js +4 -0
- package/dist/src/AgentPlugin.d.ts +17 -0
- package/dist/src/AgentSession.d.ts +13 -0
- package/dist/src/BotClient.d.ts +48 -0
- package/dist/src/Config.d.ts +46 -0
- package/dist/src/DialogSession.d.ts +26 -0
- package/dist/src/EventBus.d.ts +23 -0
- package/dist/src/Logger.d.ts +12 -0
- package/dist/src/PayloadTypes.d.ts +84 -0
- package/dist/src/Session.d.ts +222 -0
- 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 +44 -0
- package/dist/src/api/fetchEventSource/index.d.ts +1 -0
- package/dist/src/api/fetchEventSource/parse.d.ts +36 -0
- package/dist/src/api/index.d.ts +2 -0
- package/dist/src/index.d.ts +5 -0
- package/dist/src/utils.d.ts +4 -0
- package/package.json +90 -0
|
@@ -0,0 +1,112 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,97 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,41 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var T=Object.getOwnPropertySymbols;var D=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var $=(o,e,s)=>e in o?se(o,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):o[e]=s,u=(o,e)=>{for(var s in e||(e={}))D.call(e,s)&&$(o,s,e[s]);if(T)for(var s of T(e))B.call(e,s)&&$(o,s,e[s]);return o},w=(o,e)=>ie(o,ne(e));var F=(o,e)=>{var s={};for(var t in o)D.call(o,t)&&e.indexOf(t)<0&&(s[t]=o[t]);if(o!=null&&T)for(var t of T(o))e.indexOf(t)<0&&B.call(o,t)&&(s[t]=o[t]);return s};var m=(o,e,s)=>($(o,typeof e!="symbol"?e+"":e,s),s);var g=(o,e,s)=>new Promise((t,a)=>{var r=i=>{try{c(s.next(i))}catch(d){a(d)}},n=i=>{try{c(s.throw(i))}catch(d){a(d)}},c=i=>i.done?t(i.value):Promise.resolve(i.value).then(r,n);c((s=s.apply(o,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),re=require("axios"),I=require("@glodon-aiot/apis"),oe=require("socket.io-client"),j=require("uuid"),U=require("dayjs"),R=class R{constructor(e,s=!1){this.prefix=e,this.open=s}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!R.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!R.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!R.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!R.debug||console.warn(this.prefix,...e)}};m(R,"debug",!1);let M=R;const ce=new M("[Config] ");var K=(o=>(o.dev="https://aiot-dev.glodon.com/api/cvforcepd",o.test="https://aiot-dev.glodon.com/api/cvforce",o.prod="https://copilot.glodon.com/api/cvforce",o.local="http://localhost:3000/api/cvforcepd",o))(K||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0};function G(o){M.debug=(o==null?void 0:o.debug)||!1,exports.configuration=w(u(u({},exports.configuration),o),{apiRoot:(o==null?void 0:o.apiRoot)||exports.configuration.apiRoot||(o!=null&&o.env?K[o.env||"prod"]:exports.configuration.apiRoot)}),M.debug&&ce.log("updated",exports.configuration)}const P=o=>JSON.parse(ae.decode(o.split(".")[1])),de=o=>{const e=P(o).exp;return new Date().valueOf()/1e3>=e},he=o=>o==null?void 0:o.replace(/[\r\n]+/gm,""),le=o=>o.replace(/\\|\\/g,"");function X(o,e,s){const t=d=>{var l;return e&&(de(e)&&s(403,"aiotToken is timeout"),d.headers=(l=d.headers)!=null?l:{},d.headers=w(u({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function a(d,l=!0){const h=`${o}${d}`,p=re.create({baseURL:h});return l&&p.interceptors.request.use(t),p}const r=(d,l)=>{d===401&&s(d,"aiotToken is invalid")},n=(d,l)=>{d!==10001&&d!==10215&&s(d,l)},c=a("/data/v1");return new I.CVForceApi(c,{onHttpStatusError:r,onAppStatusError:n})}var L=(o=>(o[o.Normal=0]="Normal",o[o.Debug=1]="Debug",o))(L||{});const A=new M("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&A.disable()}getEventListenerMap(){return u({},this.eventListenerMap)}on(e,s,t=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),t?this.eventListenerMap[e].push({fn:s,once:!0}):this.eventListenerMap[e].push(s),A.log(`add event ${e} listener ${t?", call once":""}`)}once(e,s){this.on(e,s,!0)}off(e,s){if(this.eventListenerMap[e]){const t=this.eventListenerMap[e].findIndex(a=>{if(typeof a=="function"&&s===a)return!0;if(a=a,a.fn===s)return!0});t<0?A.log(`event ${e} listener ${s.name} is not found`):(this.eventListenerMap[e].splice(t,1),A.log(`remove event ${e} listener`))}else A.log(`event ${e} listeners is empty`)}emit(e,s){if(!this.eventListenerMap[e]){A.log(`event ${e} listeners is empty`);return}const t=[];for(let a=0;a<this.eventListenerMap[e].length;a++){const r=this.eventListenerMap[e][a];typeof r=="function"?r(s):t.push(r)}t.forEach(a=>{a&&(a.fn(s),this.off(e,a.fn))}),A.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const S=new M("[Session] ");var C=(o=>(o.DataRequestFailed="data request error",o.SocketConnectionFailed="socket error",o.IdUndefined="session id is not defined",o.SendingEmptyContent="failed at sending empty content",o.Frozen="session is frozen",o.UserModeError="failed at setting socket user mode",o.Inactive="session is inactive",o))(C||{});class q{constructor(e,s="",t,a,r,n){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new Z);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);m(this,"_mcpServers",null);this.token=e,this.lazyload=a,this.client=n||null,this._applicationId=P(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),r&&(this._application=r),this.event.emit("init",{applicationId:this._applicationId,sessionId:s}),this.loadApplicationInfo().then(()=>{var c;if(s)this._id=s,this.event.emit("data:loading"),t?(this.data=t,a||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,s).then(i=>g(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,s)})).then(()=>g(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data)})))):(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,s).then(i=>g(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,s)})).then(()=>g(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoading=!1,this._dataLoaded=!0})));else{const i=(t==null?void 0:t.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:i}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:i,netOpen:t==null?void 0:t.netOpen,knowledgeIdList:(c=t==null?void 0:t.knowledges)==null?void 0:c.map(d=>d.id),applicationId:this._applicationId}).then(d=>g(this,null,function*(){this._id=d.id,this.data=w(u({},d),{knowledges:t==null?void 0:t.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),yield(()=>g(this,null,function*(){if(t!=null&&t.knowledges)return this.setKnowledges((t==null?void 0:t.knowledges)||void 0)}))(),yield(()=>{if(t!=null&&t.promptVariables){const l=this._promptVariables.map(h=>{var f,v;const p=((v=(f=t.promptVariables)==null?void 0:f.find(y=>y.key===h.key))==null?void 0:v.value)||"";return w(u({},h),{value:p})}).sort((h,p)=>h.key.localeCompare(p.key));return this.setPromptVariables(l||[])}else return})(),this.event.emit("data:created",this.data),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._ready=!0,this.event.emit("ready")}))}})}fetchData(){return g(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.getSession(this.applicationId,this.data.id).then(e=>g(this,null,function*(){return this.data=e,this.event.emit("data:updated",this.data),e}))})}get id(){var e;return this._id||((e=this.data)==null?void 0:e.id)||""}get applicationId(){return this._applicationId}get application(){return this._application}set application(e){this._application=e}loadApplicationInfo(){if(this._application)return Promise.resolve(this._application);if(this._applicationId&&!this._application)return this.event.emit("application:data:loading"),this.cvforceApi.getApplicationId(this._applicationId).then(e=>(this._application=e,this.event.emit("application:data:loaded",e),e));throw Error("application id is not defined")}get ready(){return this._ready}get frozen(){return this._frozen}set frozen(e){e===!1&&this.inactivating&&this.socket&&(this.socket.disconnect(),this.socket=null,this.event.emit("inactivated")),this._frozen=e,this.event.emit("frozen",e)}get knowledges(){if(!this.data)throw Error("session data is not loaded");return this.data.knowledges||void 0}setKnowledges(e){return g(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(s=>s.status===I.PromptStatus.Quoted).filter(s=>!s.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(s=>s.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>e.key!=="query")}setPromptVariables(e){return g(this,null,function*(){const s=this._promptVariables.map(t=>{var r;const a=((r=e==null?void 0:e.find(n=>n.key===t.key))==null?void 0:r.value)||t.value;return w(u({},t),{value:a})}).sort((t,a)=>t.key.localeCompare(a.key));if(yield Promise.all(s.filter(t=>t.key!=="query").map(t=>{if(!this.data)throw Error("session data is not loaded");if(!(!t.id||!t.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,t.id,{value:t.value}).catch(console.error)})),!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return g(this,null,function*(){var s,t,a;if(S.log("setNetOpen:",e),S.log("application arrange setting value: ",(s=this._application)==null?void 0:s.arrange[0].enableNetOpen),((t=this._application)==null?void 0:t.type)===I.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((a=this._application)==null?void 0:a.arrange[0].enableNetOpen)===!1){console.warn("This Application is disabled to change netOpen.");return}if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{netOpen:e?1:2}),this.data.netOpen=e,S.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return X(exports.configuration.apiRoot,this.token,(e,s)=>{const t=new Error("data request error");S.error(t),this.event.emit("error",t)})}addEventListener(e,s,t=!1){if(typeof s!="function")throw Error("event listener is not a function");if(t){this.event.once(e,s);return}this.event.on(e,s)}removeEventListener(e,s){this.event.off(e,s)}fetchMessages(){return g(this,arguments,function*(e={}){var t,a;const s={pageSize:this._loadingMessagesSize};if(this._id){e=u(u({},s),e),this.event.emit("history:loading"),S.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),S.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),n=r.map((i,d)=>{var p,f;let l=[],h;return typeof((p=i.agentHistoryList)==null?void 0:p.agentList)=="string"&&(l=JSON.parse(i.agentHistoryList.agentList).reduce((y,_)=>(y[_.data.step-1]||(y[_.data.step-1]=[]),y[_.data.step-1].push(_),y),[])),d===r.length-1&&(h=(f=this.data)==null?void 0:f.lastRelatedQuestion),w(u({},i),{actions:l,relatedQuesion:h})});if(!e.endTime&&!e.startTime){const i=this.messages[this.messages.length-1];i&&!i.relatedQuesion&&(i.relatedQuesion=(t=this.data)==null?void 0:t.lastRelatedQuestion),this.messages=[...n,...this.messages]}else if(e.endTime&&!e.startTime){const i=this.messages.findIndex(d=>d.ts===e.endTime);this.messages.splice(0,i+1),this.messages=[...n,...this.messages]}else if(!e.endTime&&e.startTime){const i=this.messages.findLastIndex(d=>d.ts===e.endTime);this.messages.splice(i,this.messages.length-i-1),this.messages=[...this.messages,...n]}else{const i=this.messages.findIndex(l=>l.ts===e.endTime),d=this.messages.findLastIndex(l=>l.ts===e.endTime);this.messages.splice(i,d-i+1,...n)}const c=this.messages[this.messages.length-1];return c&&!c.relatedQuesion&&(c.relatedQuesion=(a=this.data)==null?void 0:a.lastRelatedQuestion),this.event.emit("history:moreloaded",n),S.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,n}else{const r=new Error("session id is not defined");return S.error(r),this.event.emit("error",r),!1}})}rename(e){return g(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),S.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return g(this,null,function*(){this.messages.push(e),S.log("history:add",e),this.event.emit("history:add",e),this.event.emit("message:new",e),this.event.emit("message:updated",e)})}reloadSessionInfo(){if(!this._id)throw Error("session is not created yet");return this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,this._id).then(e=>g(this,null,function*(){if(this.data=e,!this._id)throw Error("session is not created yet");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),S.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>g(this,null,function*(){return this.messages=[],yield this.fetchMessages(),this._dataLoading=!1,this._dataLoaded=!0,this.event.emit("data:loaded",this.data),this}))}reload(){return g(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return g(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return S.error(e),this.event.emit("error",e),!1}return this.event.emit("data:deleting"),yield this.cvforceApi.delSessionsId(this.applicationId,this.id),this.event.emit("data:deleted"),this.destroy()})}activate(){return g(this,null,function*(){if(this.activing)return new Promise(s=>{this.addEventListener("activated",()=>{s(!0)},!0)});if(!this._id)throw Error("session is not avalible. id is undefined");this.activing=!0;const e=this._id;return this._dataLoading=!0,this._dataLoaded=!1,this.data=yield this.cvforceApi.getSession(this.applicationId,e).then(s=>g(this,null,function*(){return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,e),s})),this.messages.length||(this.messages=[],yield this.fetchMessages()),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoaded=!0,this._dataLoading=!1,this.inactivating=!1,this.frozen=!0,yield this.prepareConnection(),this.event.emit("activated",this.socket),this.active=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?this._frozen?(e||(this.inactivating=!0),this.activing=!1,!0):(this.socket.close(),this.socket=null,this.event.emit("inactivated"),this.active=!1,this.activing=!1,!0):(this.activing=!1,!0)}get dataLoaded(){return this._dataLoaded}get messagesLoading(){return this._loadingMessages}send(t){return g(this,arguments,function*(e,s={stream:!1}){var p;try{this.validateConfigs()}catch(f){console.error(f)}const{stream:a=!1,referenceFirst:r=!1}=s,n=e.uuid||j.v4(),c=((p=e.text)==null?void 0:p.trim())||"",i=e.fileIds;if(!c&&!(i!=null&&i.length)){const f=new Error("failed at sending empty content");return S.error(f),this.event.emit("error",f),!1}if(!this._id){const f=new Error("session id is not defined");return S.error(f),this.event.emit("error",f),!1}if(this.frozen){const f=new Error("session is frozen");return S.error(f),this.event.emit("error",f),!1}this.frozen=!0,this._stopAnswer=!1;const d={sessionId:this.id,role:2,content:c,messageId:n,reference:[],searchReference:[],messageTime:""},l={content:c,stream:a,requestId:n,fileIds:i,referenceFirst:r};this.pushMessage(d),this.event.emit("question:content",c);const h=f=>g(this,null,function*(){if(f.role!==I.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",h),this._id&&f.content&&f.index&&f.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:f.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:f.content})),yield this.fillMessageReference(f),f.code){case 11915:f.content="请您换个问题问我吧~",f.index=-1,f.isSensitive=!0,f.isLoading=!1,f.sessionId=this._id||"",this.event.emit("message:error",f);break;case 200:f.index=-1,f.isLoading=!1;break;default:f.content=f.message||"未知错误",f.isLoading=!1,f.index=-1,this.event.emit("message:error",f)}this.getRelatedQuesion(f),f.isLoading=!1;let v=this.messages[this.messages.length-1];if(v&&v.role===I.ChatMessageRole.Robot){const y=u(u({},v),f);this.messages[this.messages.length-1]=y,this.event.emit("message:updated",y)}else this.pushMessage(f);this.frozen=!1});return this.addEventListener("answer:finish",h),this.sendQuestion(l,w(u({},s),{stream:a,referenceFirst:r})),d})}getRelatedQuesion(e){return g(this,null,function*(){var r,n;if(!e.content||e.isSensitive||e.code!==200||!((r=this.application)!=null&&r.arrange[0].recommendQuestionOpen))return e;this.event.emit("message:relatedQuesion:loading",e);const s=yield this.cvforceApi.postGeneques({content:e.content}).catch(c=>null);if(!s){const c=[],i=w(u({},e),{relatedQuesion:c,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:c}),this.event.emit("message:updated",i),i}const t=(n=s.content)==null?void 0:n.split("*").map(he).map(le).filter(c=>!!c);e.relatedQuesion=t,e.index=-3,e.isLoading=!1;const a=w(u({},e),{relatedQuesion:t,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",a),this.event.emit("message:updated",a),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:t}),a})}fillMessageReference(e){return g(this,null,function*(){const s=yield Promise.all(e.reference.map(t=>this.cvforceApi.getKnowledgeIdFileId(t.knowledgeId,t.docId)));return e.reference=e.reference.map((t,a)=>u(u({},t),s[a])),this.event.emit("message:updated",e),e})}answerAgain(){return g(this,arguments,function*(e={stream:!1}){const s=this.messages[this.messages.length-1];if(!s)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1;const{stream:t=!1}=e;let a;s.role!==I.ChatMessageRole.User&&(a=e.oldMessageId||s.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",s),this.event.emit("history:remove",s));const r=this.messages[this.messages.length-1],n={content:r.content,fileIds:r.fileIds,requestId:r.messageId,stream:t,oldMessageId:a},c=i=>g(this,null,function*(){if(i.role===I.ChatMessageRole.Robot&&i.index===-1){switch(this._id&&i.content&&i.index&&i.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:i.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:i.content})),yield this.fillMessageReference(i),i.code){case 11915:i.content="请您换个问题问我吧~",i.index=-1,i.isSensitive=!0,i.isLoading=!1,i.sessionId=this._id||"",this.event.emit("message:error",i);break;case 200:i.index=-1,i.isLoading=!1;break;default:i.content=i.message||"未知错误",i.isLoading=!1,i.index=-1,this.event.emit("message:error",i)}this.getRelatedQuesion(i),this.removeEventListener("message:content",c),this.frozen=!1}});this.addEventListener("message:content",c),this.sendQuestion(n,w(u({},e),{stream:t}))})}setTop(e){return g(this,null,function*(){if(!this._id)throw Error("session is not avalible. id is undefined");this.data=yield this.cvforceApi.patchSessionsId(this._applicationId,this._id,{top:e}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:top",{top:e})})}suspend(){var t;this.stopAnswer(),this.frozen=!1,this._stopAnswer=!0;let e=this.messages[this.messages.length-1];const s={messageId:j.v4(),isLoading:!1,index:-2,messageTime:U(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:I.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const a=e.actions[((t=e.actions)==null?void 0:t.length)-1];if(a){const r=a[a.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:n,pluginCode:c,funcCode:i,funcName:d}=r.data;a.push({data:{pluginName:n,pluginCode:c,funcCode:i,funcName:d,step:r.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:a})}}}e=u(u({},e),s),this.event.emit("message:content",e),this.event.emit("message:updated",e)}else this.pushMessage(s),this.event.emit("message:content",s);return this}postMessageComment(e){return g(this,null,function*(){if(!this._applicationId||!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.postComments(this._applicationId,this._id,e).then(s=>{const t=this.messages.find(a=>a.messageId===e.messageId);return t&&(t.comment=e,this.event.emit("message:comment",t)),s})})}clear(){if(!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.patchApplicationIdSessionsIdContext(this._applicationId,this._id).then(()=>(this.event.emit("context:clear"),!0))}destroy(){var e;return this._ready=!1,this.event.removeAllListeners(),(e=this.socket)==null||e.disconnect(),this.socket=null,this.event.emit("destroy",{applicationId:this._applicationId,sessionId:this._id}),this._id||""}}const k=new M("[AgentSession] ");class fe extends q{constructor(e,s="",t,a,r,n){super(e,s,t,a,r,n)}prepareConnection(){return new Promise(e=>g(this,null,function*(){this.socket&&e(!0);const s={version:"1.0",stream:"false",appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?L.Debug:L.Normal},t=new URL(exports.configuration.apiRoot),a=yield oe.io(t.origin,{path:t.pathname.replace("api","socketio")+"/copilot",query:s,transports:["websocket"]});a.on("connect",()=>{k.log("socket:connect"),this.event.emit("socket:connect"),a.emit("init")}),a.on("disconnect",()=>{k.log("socket:disconnect"),this.event.emit("socket:disconnect")}),a.on("ready",r=>{if(r.code===200){k.log("ready");const n=exports.configuration.debug?L.Debug:L.Normal;n===L.Debug&&r.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const n=new Error(C.SocketConnectionFailed);k.error("error",n),this.event.emit("error",n),e(!1)}}),a.on("action",(r,n)=>g(this,null,function*(){if(this._stopAnswer||!this.id)return;const{type:c,data:{runnerIsClient:i,pluginCode:d,funcCode:l,parameters:h,requestBody:p}}=r,f=this.messages[this.messages.length-1];if(!f.messageId)f.actions||(f.actions=[]),f.actions[r.data.step-1]||(f.actions[r.data.step-1]=[]),f.actions[r.data.step-1].push(r),this.event.emit("message:action",{messageId:f.messageId,action:r}),this.event.emit("message:updated",f);else{const v={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[r]],comment:{isAgree:0}};this.pushMessage(v),this.event.emit("message:action",{messageId:v.messageId,action:r})}if(this.inactivating){const v=new Error(C.Inactive);k.warn("error",v),this.event.emit("error",v)}else if(c==="FUNCTION_CALL"&&i){if(k.log(`calling function ${l} of plugin ${d} with argument:
|
|
2
|
+
${JSON.stringify(h)}`),!exports.configuration.plugins[d]){n({code:404,message:"对不起,没有找到插件。"});return}const v=exports.configuration.plugins[d][l];typeof v!="function"&&n({code:404,message:"对不起,没有找到插件方法。"});let y=h==null?void 0:h.query;try{y=JSON.parse(h==null?void 0:h.query)}catch(_){}v(y,(..._)=>{this._stopAnswer||n(..._)})}})),a.on("answer",r=>{if(!this._stopAnswer)if(r.data.code!==200&&(r.data.index=-1,this.event.emit("error",r.data)),r.data.index===-1){let n=this.messages[this.messages.length-1];if(n&&!n.messageId)n=u(u({},n),r.data),this.event.emit("message:content",n),this.event.emit("message:updated",n),this.event.emit("answer:finish",n);else{const c=u({messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0}},r.data);this.event.emit("message:content",c),this.pushMessage(c),this.event.emit("answer:finish",c)}}else{let n=this.messages[this.messages.length-1];n&&!n.messageId?(n=u(u({},n),r.data),this.messages[this.messages.length-1]=n,this.event.emit("message:content",n),this.event.emit("message:updated",n)):(this.pushMessage(r.data),this.event.emit("message:content",r.data))}}),a.on("reference",r=>g(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const h=new Error(C.IdUndefined);k.error(h),this.event.emit("error",h),this.frozen=!1;return}const{type:n,data:c,requestId:i}=r,d=this.messages.findIndex(h=>h.messageId===i&&h.role===I.ChatMessageRole.User);if(d<0)return;const l=d+1;if(l>=this.messages.length){const h={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0}};this.pushMessage(h)}n==="KG"?(this.messages[l]=w(u({},this.messages[l]),{reference:c.knowledgeReference}),yield this.fillMessageReference(this.messages[l]),this.event.emit("message:reference",c.knowledgeReference),this.event.emit("message:updated",this.messages[l])):n==="WEB_SEARCH"&&(this.messages[l]=w(u({},this.messages[l]),{searchReference:c.knowledgeReference}),this.event.emit("message:searchreference",c.searchReference),this.event.emit("message:updated",this.messages[l]))})),this.socket=a,a.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((e,s)=>{if(!this.socket){s("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,t=>{t.code===200?(Object.keys(t.data).forEach(a=>{t.data[a].code!==200&&console.error(a,"MCP Server 注册失败。",t.data[a])}),e(!0)):(console.error("MCP Server 注册失败。",t),s(t))})}):Promise.resolve(!0)}addMcpServers(e){return g(this,null,function*(){return this.ready?this.socket?new Promise((s,t)=>{this.socket&&this.socket.emit("add_mcp_servers",e,a=>{a.code===200?(Object.keys(a.data).forEach(r=>{a.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",a.data[r])}),s(!0)):(console.error("MCP Server 注册失败。",a),t(a))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return g(this,null,function*(){return this.ready?this.socket?new Promise((e,s)=>{this.socket&&this.socket.emit("list_mcp_servers",t=>{t.code===200?e(t.data):s(t)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(e,s){return g(this,null,function*(){var a,r,n;let t=w(u({},e),{promptVariables:this.promptVariables.reduce((c,i)=>w(u({},c),{[i.key]:i.value}),{}),knowledges:(a=this.knowledges)==null?void 0:a.map(c=>c.id)});if(!this.active){if(yield this.activate(),!this.socket){const c=new Error(C.SocketConnectionFailed);return k.warn("error",c),this.event.emit("error",c),!1}(r=this.socket)==null||r.emit("question",t);return}(n=this.socket)==null||n.emit("question",t)})}stopAnswer(){var e;(e=this.socket)==null||e.emit("stop_answer")}}function ge(o,e){return g(this,null,function*(){const s=o.getReader();let t;for(;!(t=yield s.read()).done;)e(t.value)})}function pe(o){let e,s,t,a=!1,r;return function(c){e===void 0?(e=c,s=0,t=-1,r=!1):e=me(e,c);const i=e.length;let d=0;for(;s<i;){a&&(e[s]===10&&(d=++s),a=!1);let l=-1;for(;s<i&&l===-1;++s)switch(e[s]){case 58:t===-1&&(t=s-d);break;case 13:a=!1,s+4<i&&e[s+1]===10&&e[s+2]!==13&&e[s-1]!==10&&e[s-2]!==13&&(r=!0);case 10:l=s;break}if(l===-1)break;o(e.subarray(d,l),t,r),d=s,t=-1,r=!1}d===i?e=void 0:d!==0&&(e=e.subarray(d),s-=d)}}function ue(o,e,s){let t=J();const a=new TextDecoder;return function(n,c,i){if(n.length===0)s==null||s(t),t=J();else if(c>0){const d=a.decode(n.subarray(0,c)),l=c+(n[c+1]===32?2:1);let h=a.decode(n.subarray(l));switch(i&&(h+=`
|
|
3
|
+
`),d){case"data":t.data=t.data?t.data+`
|
|
4
|
+
`+h:h;break;case"event":t.event=h;break;case"id":o(t.id=h);break;case"retry":const p=parseInt(h,10);isNaN(p)||e(t.retry=p);break}}}}function me(o,e){const s=new Uint8Array(o.length+e.length);return s.set(o),s.set(e,o.length),s}function J(){return{data:"",event:"",id:"",retry:void 0}}const z="text/event-stream",ve=1e3,H="last-event-id";function Y(o,l){var h=l,{signal:e,headers:s,onopen:t,onmessage:a,onclose:r,onerror:n,openWhenHidden:c,fetch:i}=h,d=F(h,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((p,f)=>{const v=u({},s);v.accept||(v.accept=z);let y;function _(){y.abort(),document.hidden||Q()}c||document.addEventListener("visibilitychange",_);let E=ve,V=0;function O(){document.removeEventListener("visibilitychange",_),window.clearTimeout(V),y.abort()}e==null||e.addEventListener("abort",()=>{O(),p()});const ee=i!=null?i:window.fetch,te=t!=null?t:ye;function Q(){return g(this,null,function*(){var N;y=new AbortController;try{const x=yield ee(o,w(u({},d),{headers:v,signal:y.signal}));yield te(x),yield ge(x.body,pe(ue(b=>{b?v[H]=b:delete v[H]},b=>{E=b},a))),r==null||r(),O(),p()}catch(x){if(!y.signal.aborted)try{const b=(N=n==null?void 0:n(x))!=null?N:E;window.clearTimeout(V),V=window.setTimeout(Q,b)}catch(b){O(),f(b)}}})}Q()})}function ye(o){const e=o.headers.get("content-type");if(!(e!=null&&e.startsWith(z)))throw new Error(`Expected content-type to be ${z}, Actual: ${e}`)}const W=new M("[DialogSession] ");class we extends q{constructor(s,t="",a,r,n,c){super(s,t,a,r,n,c);m(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(s=>g(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,s(!0)}))}postChatV2EventSource(s,t,a,r,n,c){return g(this,null,function*(){const i={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:t,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=w(u({},a),{stream:!0});Y(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${s}&sessionId=${t}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:r,onopen(l){return l.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(l){if(!l.data.includes('{"code": ')){let p={};try{p=JSON.parse(l.data)}catch(v){}(p==null?void 0:p.mtype)==="search"?i.searchReference.push(p):i.content=i.content+l.data;const f={content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:t,messageTime:U(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(n==null?void 0:n.onmessage)&&n.onmessage(f)}const h=JSON.parse(l.data);if(i.reference=h.data.reference,i.searchReference=h.data.searchReference,i.messageTime=h.data.messageTime,i.messageId=h.data.messageId,i.llmModel=h.data.llmModel,i.content=h.data.content,i.code=h.code,h.code===200){const p={code:i.code,content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:t,messageTime:i.messageTime,isReplying:!0};n!=null&&n.onmessage&&n.onmessage(p)}else return n!=null&&n.onclose&&n.onclose(i),c&&c({code:i.code,message:i.message})},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const l={code:i.code,content:i.content,role:1,reference:i.reference,searchReference:i.searchReference,messageId:i.messageId,sessionId:t,messageTime:i.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};n!=null&&n.onclose&&n.onclose(l)}})})}postChatV3EventSource(s,t,a,r,n,c){return g(this,null,function*(){const i={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:t,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},d=w(u({},a),{stream:!0});Y(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${s}&sessionId=${t}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:r,onopen(l){return l.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(l){if(!l.data&&!l.event&&!l.id&&!l.retry)return;let h={};try{h=JSON.parse(l.data)}catch(y){console.error("parse eventData to JSON failed. ",l.data)}if(h.code!==200)return i.index=-1,i.code=h.code,i.message=h.message,n!=null&&n.onmessage&&n.onmessage(i),c&&c({code:h.code,message:h.message});const p=h.data.type,f=h.data.payload;i.isReplying=!0;const v=()=>{if(!i.searchingStatus){i.searchingStatus="start";return}if(i.searchingStatus==="start"){i.searchingStatus="end";return}};if(p==="beforeSearch"&&v(),p==="searchOver"&&v(),p==="search"&&i.searchReference.push(f),p==="thinking"){i.thinkingStatus="start";const _=f.choices[0];i.reasoningContent=i.reasoningContent+_.delta.reasoningContent}if(p==="thinkingOver"){i.thinkingStatus="end";const y=f.thinkingSecs;i.thinkingSecs=y}if(p==="text"){const _=f.choices[0];i.content=i.content+_.delta.content}if(p==="reference"&&(i.reference=f),p==="result"){const y=f.messageId,_=f.llmModel,E=f.messageTime;i.messageId=y,i.llmModel=_,i.messageTime=E,i.sessionId=t}p==="over"?i.index=-1:(i.code=h.code,i.message=h.message),n!=null&&n.onmessage&&n.onmessage(i)},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const l=w(u({},i),{isReplying:!1});n!=null&&n.onclose&&n.onclose(l)}})})}sendQuestion(s,t){return g(this,null,function*(){var d;const{content:a,fileIds:r,oldMessageId:n}=s,{stream:c,referenceFirst:i}=t;if(this.active||(yield this.activate()),this._id){let l={content:a,fileIds:r,referenceFirst:i,oldMessageId:n,promptVariables:this.promptVariables.reduce((h,p)=>w(u({},h),{[p.key]:p.value}),{}),knowledges:(d=this.knowledges)==null?void 0:d.map(h=>h.id)};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,l,this.ctrl.signal,{onopen:()=>{W.log("open",this.ctrl)},onmessage:h=>{if(this._stopAnswer)return;let p=this.messages[this.messages.length-1];p&&p.role===I.ChatMessageRole.Robot?(p=u(u({},p),h),this.messages[this.messages.length-1]=p,this.event.emit("message:content",p),this.event.emit("message:updated",p)):(this.pushMessage(h),this.event.emit("message:content",h))},onclose:h=>g(this,null,function*(){this._stopAnswer||(W.log(h,"onclose"),this.event.emit("answer:finish",h))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return g(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(s){return g(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return g(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}}const Ie=new M("[BotClient] ");class _e{constructor(e,s,t=!0){m(this,"event",new Z);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=t,G(s),this._applicationId=P(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(()=>{this.event.emit("ready")})}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return g(this,null,function*(){var s,t,a;this._application=yield this.cvforceApi.getApplicationId(this._applicationId).then(r=>(typeof r.arrange[0].recommendQuestionOpen!="boolean"&&(r.arrange[0].recommendQuestionOpen=!0),w(u({},r),{arrange:[w(u({},r.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&r.arrange[0].recommendQuestionOpen})]})));const e=(a=(t=(s=this._application)==null?void 0:s.arrange)==null?void 0:t[0])==null?void 0:a.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(r=>r.maxModelLength)),this._promptVariables=yield this.cvforceApi.getPrompts(this._applicationId),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:X(exports.configuration.apiRoot,this.token,(e,s)=>Ie.error(s))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const s=P(e).rid;this._applicationId!==s&&(this._applicationId=s,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(s=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=s})}createSession(e,s,t,a,r){return g(this,null,function*(){const n=this;return new Promise((c,i)=>{const d=l=>g(this,null,function*(){if(l===I.ApplicationTypes.Agent)c(new fe(e,s,t,a,r,n));else if(l===I.ApplicationTypes.Dialog)c(new we(e,s,t,a,r,n));else throw Error(`不支持的应用类型:${l}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return g(this,null,function*(){return new Promise((s,t)=>{const a=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>{const n=[];return r.forEach(c=>g(this,null,function*(){const i=this._sessions.find(d=>c.id===d.id);if(i)i.data=c,this._application?i.application=this._application:i.loadApplicationInfo(),n.push(i);else{const d=yield this.createSession(this.token,c.id,c,this.lazyload,this._application||void 0);n.push(d)}})),this.sessions=n,n});if(this.ready){if(!this._application)throw Error("_application is null");s(a())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");s(a())},!0)})})}loadSession(e="",s){return g(this,null,function*(){this.checkReady();let t=this.sessions.find(a=>a.id===e);if(t||(t=yield this.createSession(this.token,e,s),this._sessions.push(t)),this._activeSession){if(this._activeSession===t)return t;this._activeSession.inactivate()}return t.id?(yield t.activate(),this._activeSession=t):t.addEventListener("data:loaded",()=>{this._activeSession!==t&&(t==null||t.activate(),this._activeSession=t)},!0),t})}reload(){return this.loadApplication().then(()=>g(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return g(this,null,function*(){yield this.reload();let s=this._sessions.find(t=>t.id===e)||this._activeSession;if(!s){console.warn("reloadSession session failed.");return}return yield s.reload(),s})}setTop(e,s,t="top_time desc, sort_status desc, updated_at desc"){return g(this,null,function*(){let a=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!a){console.warn("setTop session failed.");return}return yield a.setTop(s),this.getSessions({order:t})})}addEventListener(e,s,t=!1){if(typeof s!="function")throw Error("event listener is not a function");if(t){this.event.once(e,s);return}this.event.on(e,s)}removeEventListener(e,s){this.event.off(e,s)}removeSession(e,s){return g(this,null,function*(){this.checkReady();let t=-1;if(typeof e=="string"?t=this._sessions.findIndex(a=>a.id===e):t=this._sessions.findIndex(a=>a.id===e.id),t>-1){const a=this._sessions[t];s&&(yield a.delete()),this._sessions.splice(t,1)}else console.warn("session delete failed, session is not exist.")})}clean(){this._sessions.forEach(e=>e.destroy()),this.sessions=[]}}class Se{constructor(e,s={},t){m(this,"code");m(this,"description","");m(this,"loaded",!1);m(this,"functions",{});this.code=e,s&&(this.functions=s)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}exports.AgentPlugin=Se;exports.BotClient=_e;exports.Session=q;exports.configure=G;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { AgentPluginRegistor } from '.';
|
|
2
|
+
/**
|
|
3
|
+
* Class AgentPlugin
|
|
4
|
+
* 提供获取插件数据、检测客户端插件等功能
|
|
5
|
+
*/
|
|
6
|
+
interface AgentPluginDetails {
|
|
7
|
+
}
|
|
8
|
+
export default class AgentPlugin {
|
|
9
|
+
code: string;
|
|
10
|
+
description: string;
|
|
11
|
+
loaded: boolean;
|
|
12
|
+
functions: AgentPluginRegistor;
|
|
13
|
+
constructor(code: any, functions?: AgentPluginRegistor, initalData?: AgentPluginDetails);
|
|
14
|
+
fetchData(): void;
|
|
15
|
+
checkFunctions(): void;
|
|
16
|
+
}
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { IApplication, ISession } from '@glodon-aiot/apis';
|
|
2
|
+
import { MCPConfig } from './Config';
|
|
3
|
+
import { default as Session, QuestionBody, QuestionConfig } from './Session';
|
|
4
|
+
import { default as BotClient } from './BotClient';
|
|
5
|
+
export default class AgentSession extends Session {
|
|
6
|
+
constructor(token: string, _id?: string, _data?: Partial<ISession>, lazyload?: boolean, application?: IApplication, client?: BotClient);
|
|
7
|
+
prepareConnection(): Promise<boolean>;
|
|
8
|
+
registerMcpFromClientConfig(): Promise<boolean>;
|
|
9
|
+
addMcpServers(mcpServers: MCPConfig): Promise<boolean>;
|
|
10
|
+
listMcpServers(): Promise<MCPConfig>;
|
|
11
|
+
sendQuestion(questionBody: QuestionBody, configs: QuestionConfig): Promise<false | undefined>;
|
|
12
|
+
stopAnswer(): void;
|
|
13
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { default as Session } from './Session';
|
|
2
|
+
import { BotClientConfig } from './Config';
|
|
3
|
+
import { IApplication, IPrompt, ISession, ISessionPrompt, SessionQueryParams } from '@glodon-aiot/apis';
|
|
4
|
+
import { default as EventBus } from './EventBus';
|
|
5
|
+
export type ClientEventName = 'ready' | 'application:loaded';
|
|
6
|
+
export default class BotClient {
|
|
7
|
+
private _token;
|
|
8
|
+
private lazyload;
|
|
9
|
+
protected event: EventBus;
|
|
10
|
+
private cvforceApi;
|
|
11
|
+
private _applicationId;
|
|
12
|
+
private _application;
|
|
13
|
+
private _sessions;
|
|
14
|
+
private _activeSession?;
|
|
15
|
+
private _ready?;
|
|
16
|
+
private _questionContextMaxLength?;
|
|
17
|
+
private _promptVariables?;
|
|
18
|
+
constructor(_token: string, //AIoT resource token
|
|
19
|
+
configs: BotClientConfig, lazyload?: boolean);
|
|
20
|
+
private checkReady;
|
|
21
|
+
get ready(): boolean | undefined;
|
|
22
|
+
private set ready(value);
|
|
23
|
+
get questionContextMaxLength(): number | undefined;
|
|
24
|
+
get promptVariables(): IPrompt[] | undefined;
|
|
25
|
+
get knowledges(): any;
|
|
26
|
+
get sessions(): Session[];
|
|
27
|
+
set sessions(v: Session[]);
|
|
28
|
+
private loadApplication;
|
|
29
|
+
private getService;
|
|
30
|
+
get token(): string;
|
|
31
|
+
set token(v: string);
|
|
32
|
+
get applicationId(): string;
|
|
33
|
+
get application(): IApplication | null;
|
|
34
|
+
get activeSession(): string;
|
|
35
|
+
set activeSession(sessionId: string);
|
|
36
|
+
private createSession;
|
|
37
|
+
getSessions(queryParams?: SessionQueryParams): Promise<Session[]>;
|
|
38
|
+
loadSession(sessionId?: string, sessionParams?: Partial<ISession & {
|
|
39
|
+
promptVariables?: ISessionPrompt[];
|
|
40
|
+
}>): Promise<Session>;
|
|
41
|
+
reload(): Promise<this>;
|
|
42
|
+
reloadSession(sessionId?: string): Promise<Session | undefined>;
|
|
43
|
+
setTop(sessionId: string, top: boolean, order?: string): Promise<Session[] | undefined>;
|
|
44
|
+
addEventListener(eventName: ClientEventName, callback: any, once?: boolean): void;
|
|
45
|
+
removeEventListener(eventName: ClientEventName, callback: any): void;
|
|
46
|
+
removeSession(session: string | Session, deleteFromRemote?: boolean): Promise<void>;
|
|
47
|
+
clean(): void;
|
|
48
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export interface McpServer {
|
|
2
|
+
type: 'sse';
|
|
3
|
+
url: string;
|
|
4
|
+
headers?: Record<string, string>;
|
|
5
|
+
}
|
|
6
|
+
export interface MCPConfig {
|
|
7
|
+
mcpServers: {
|
|
8
|
+
[key: string]: McpServer;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
export interface BotClientConfig {
|
|
12
|
+
debug?: boolean;
|
|
13
|
+
env?: Env;
|
|
14
|
+
applicationId?: string;
|
|
15
|
+
plugins?: AgentPluginMap;
|
|
16
|
+
apiRoot?: string;
|
|
17
|
+
loadRelatedQuesions?: boolean;
|
|
18
|
+
mcp?: MCPConfig;
|
|
19
|
+
}
|
|
20
|
+
export interface AgentPluginRegistor {
|
|
21
|
+
[key: string]: Function;
|
|
22
|
+
}
|
|
23
|
+
export interface AgentPluginMap {
|
|
24
|
+
[pluginCode: string]: AgentPluginRegistor;
|
|
25
|
+
}
|
|
26
|
+
export type Env = 'dev' | 'test' | 'prod' | 'local';
|
|
27
|
+
export declare enum ApiUrl {
|
|
28
|
+
dev = "https://aiot-dev.glodon.com/api/cvforcepd",
|
|
29
|
+
test = "https://aiot-dev.glodon.com/api/cvforce",
|
|
30
|
+
prod = "https://copilot.glodon.com/api/cvforce",
|
|
31
|
+
local = "http://localhost:3000/api/cvforcepd"
|
|
32
|
+
}
|
|
33
|
+
export declare let configuration: {
|
|
34
|
+
debug: boolean;
|
|
35
|
+
env: string;
|
|
36
|
+
apiRoot: string;
|
|
37
|
+
applicationId: string;
|
|
38
|
+
plugins: AgentPluginMap;
|
|
39
|
+
mcp: (MCPConfig | undefined);
|
|
40
|
+
loadRelatedQuesions: boolean;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* 配置SDK,可以在SDK被使用前被调用,该方法被调用后将改变是否debug模式、是否测试环境等基本配置
|
|
44
|
+
* @param param {debug?: boolean; env?: 'dev' | 'test' | 'prod';}
|
|
45
|
+
*/
|
|
46
|
+
export declare function configure(param?: BotClientConfig): void;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { IApplication, ISession } from '@glodon-aiot/apis';
|
|
2
|
+
import { default as Session, QuestionBody, QuestionConfig } from './Session';
|
|
3
|
+
import { MCPConfig } from './Config';
|
|
4
|
+
import { default as BotClient } from './BotClient';
|
|
5
|
+
export default class DialogSession extends Session {
|
|
6
|
+
private ctrl;
|
|
7
|
+
constructor(token: string, _id?: string, _data?: Partial<ISession>, lazyload?: boolean, application?: IApplication, client?: BotClient);
|
|
8
|
+
prepareConnection(): Promise<boolean>;
|
|
9
|
+
postChatV2EventSource(applicationId: string, sessionId: string, params: any, signal: AbortSignal, options: {
|
|
10
|
+
onopen?: any;
|
|
11
|
+
onmessage?: any;
|
|
12
|
+
onerror?: any;
|
|
13
|
+
onclose?: any;
|
|
14
|
+
}, onAppStatusError?: (error: any) => void): Promise<void>;
|
|
15
|
+
postChatV3EventSource(applicationId: string, sessionId: string, params: any, signal: AbortSignal, options: {
|
|
16
|
+
onopen?: any;
|
|
17
|
+
onmessage?: any;
|
|
18
|
+
onerror?: any;
|
|
19
|
+
onclose?: any;
|
|
20
|
+
}, onAppStatusError?: (error: any) => void): Promise<void>;
|
|
21
|
+
sendQuestion(questionBody: QuestionBody, configs: QuestionConfig): Promise<void>;
|
|
22
|
+
stopAnswer(): void;
|
|
23
|
+
registerMcpFromClientConfig(): Promise<boolean>;
|
|
24
|
+
addMcpServers(mcpServers: MCPConfig): Promise<boolean>;
|
|
25
|
+
listMcpServers(): Promise<MCPConfig>;
|
|
26
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
type Topic = string;
|
|
2
|
+
export interface ViewerEvent {
|
|
3
|
+
topic: Topic;
|
|
4
|
+
payload?: any;
|
|
5
|
+
}
|
|
6
|
+
export type EventListener = (e: any) => void;
|
|
7
|
+
interface SingleEventListener {
|
|
8
|
+
fn: EventListener;
|
|
9
|
+
once: true;
|
|
10
|
+
}
|
|
11
|
+
export default class EventBus {
|
|
12
|
+
private eventListenerMap;
|
|
13
|
+
constructor(disableLog?: boolean);
|
|
14
|
+
getEventListenerMap(): {
|
|
15
|
+
[key: string]: (SingleEventListener | EventListener)[];
|
|
16
|
+
};
|
|
17
|
+
on(topic: Topic, listener: EventListener, once?: boolean): void;
|
|
18
|
+
once(topic: Topic, listener: EventListener): void;
|
|
19
|
+
off(topic: Topic, listener: EventListener): void;
|
|
20
|
+
emit(topic: Topic, payload?: any): void;
|
|
21
|
+
removeAllListeners(): void;
|
|
22
|
+
}
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export default class Logger {
|
|
2
|
+
private prefix;
|
|
3
|
+
private open;
|
|
4
|
+
static debug: boolean;
|
|
5
|
+
constructor(prefix: string, open?: boolean);
|
|
6
|
+
disable(): void;
|
|
7
|
+
enable(): void;
|
|
8
|
+
log(...rest: any[]): void;
|
|
9
|
+
info(...rest: any[]): void;
|
|
10
|
+
error(...rest: any[]): void;
|
|
11
|
+
warn(...rest: any[]): void;
|
|
12
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
export declare enum UserMode {
|
|
2
|
+
Normal = 0,
|
|
3
|
+
Debug = 1
|
|
4
|
+
}
|
|
5
|
+
export interface ReadyEventPayload {
|
|
6
|
+
/**
|
|
7
|
+
* 错误码如下:
|
|
8
|
+
* 200: 成功
|
|
9
|
+
* 11903: 密钥失效
|
|
10
|
+
* 11904: 参数异常
|
|
11
|
+
* 11905: token解析异常
|
|
12
|
+
* 11907: 未知错误
|
|
13
|
+
* 11913: 获取应用编排数据失败
|
|
14
|
+
* 11914: 获取大模型服务失败, 请检查
|
|
15
|
+
* 11924: 用户无此应用权限
|
|
16
|
+
*/
|
|
17
|
+
code: number;
|
|
18
|
+
message: string;
|
|
19
|
+
userMode: UserMode;
|
|
20
|
+
}
|
|
21
|
+
export interface PluginFunctionBasic {
|
|
22
|
+
pluginName: string;
|
|
23
|
+
pluginCode: string;
|
|
24
|
+
funcCode: string;
|
|
25
|
+
funcName: string;
|
|
26
|
+
parameters?: {
|
|
27
|
+
header: any;
|
|
28
|
+
query: any;
|
|
29
|
+
};
|
|
30
|
+
requestBody?: any;
|
|
31
|
+
runnerIsClient?: boolean;
|
|
32
|
+
result?: {
|
|
33
|
+
code: number;
|
|
34
|
+
message: string;
|
|
35
|
+
data: any;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export interface PluginFunctionBeforeCall extends PluginFunctionBasic {
|
|
39
|
+
parameters: {
|
|
40
|
+
header: any;
|
|
41
|
+
query: any;
|
|
42
|
+
};
|
|
43
|
+
requestBody: any;
|
|
44
|
+
}
|
|
45
|
+
export interface PluginFunctionCall extends PluginFunctionBasic {
|
|
46
|
+
parameters: {
|
|
47
|
+
header: any;
|
|
48
|
+
query: any;
|
|
49
|
+
};
|
|
50
|
+
requestBody: any;
|
|
51
|
+
runnerIsClient: boolean;
|
|
52
|
+
}
|
|
53
|
+
export interface PluginFunctionResult extends PluginFunctionBasic {
|
|
54
|
+
result: {
|
|
55
|
+
code: number;
|
|
56
|
+
message: string;
|
|
57
|
+
data: any;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
export interface Thought {
|
|
61
|
+
step: number;
|
|
62
|
+
thought?: string;
|
|
63
|
+
observation?: string;
|
|
64
|
+
}
|
|
65
|
+
export interface BeforeCalldData extends Thought, PluginFunctionBeforeCall {
|
|
66
|
+
thought: string;
|
|
67
|
+
observation: undefined;
|
|
68
|
+
}
|
|
69
|
+
export interface FunctionCallData extends Thought, PluginFunctionCall {
|
|
70
|
+
thought: string;
|
|
71
|
+
observation: undefined;
|
|
72
|
+
}
|
|
73
|
+
export interface CallResultData extends Thought, PluginFunctionResult {
|
|
74
|
+
thought: undefined;
|
|
75
|
+
observation: undefined;
|
|
76
|
+
}
|
|
77
|
+
export interface AfterCallData extends Thought, PluginFunctionBasic {
|
|
78
|
+
thought: undefined;
|
|
79
|
+
observation: string;
|
|
80
|
+
}
|
|
81
|
+
export interface ActionPayload<T> {
|
|
82
|
+
type: 'BEFORE_CALL' | 'FUNCTION_CALL' | 'RESULT' | 'AFTER_CALL';
|
|
83
|
+
data: T;
|
|
84
|
+
}
|