UNPKG

@glodon-aiot/agent-cli-sdk

Version:

aiot agent client js sdk

286 lines (285 loc) 10.5 kB
var R = Object.defineProperty, S = Object.defineProperties; var b = Object.getOwnPropertyDescriptors; var _ = Object.getOwnPropertySymbols; var A = Object.prototype.hasOwnProperty, E = Object.prototype.propertyIsEnumerable; var P = (d, t, n) => t in d ? R(d, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : d[t] = n, h = (d, t) => { for (var n in t || (t = {})) A.call(t, n) && P(d, n, t[n]); if (_) for (var n of _(t)) E.call(t, n) && P(d, n, t[n]); return d; }, k = (d, t) => S(d, b(t)); var v = (d, t, n) => new Promise((r, i) => { var s = (c) => { try { o(n.next(c)); } catch (g) { i(g); } }, e = (c) => { try { o(n.throw(c)); } catch (g) { i(g); } }, o = (c) => c.done ? r(c.value) : Promise.resolve(c.value).then(s, e); o((n = n.apply(d, t)).next()); }); import { ChatMessageRole as I } from "@glodon-aiot/apis"; import q from "./Logger.mjs"; import { configuration as f } from "./Config.mjs"; import { io as x } from "socket.io-client"; import { UserMode as w } from "./PayloadTypes.mjs"; import L, { SessionErrors as y } from "./Session.mjs"; const p = new q("[AgentSession] "); class D extends L { constructor(t, n = "", r, i, s, e) { super(t, n, r, i, s, e); } prepareConnection() { return new Promise((t) => v(this, null, function* () { this.socket && t(!0); const n = { version: "1.0", stream: JSON.stringify(f.stream === void 0 ? !0 : f.stream), appId: this._applicationId, sessionId: this.id, Authorization: `${this.token}`, userMode: f.debug ? w.Debug : w.Normal }, r = new URL(f.apiRoot), i = yield x(r.origin, { path: r.pathname.replace("api", "socketio") + "/copilot", query: n, transports: ["websocket"] }); i.on("connect", () => { p.log("socket:connect"), this.event.emit("socket:connect"), i.emit("init"); }), i.on("disconnect", () => { p.log("socket:disconnect"), this.event.emit("socket:disconnect"), this._ready = !1; }), i.on("ready", (s) => { if (s.code === 200) { p.log("ready"); const e = f.debug ? w.Debug : w.Normal; e === w.Debug && s.userMode, this._ready = !0, this.event.emit("ready"), this.frozen = !1, this.registerMcpFromClientConfig(), t(!0); } else { this._ready && (this._ready = !1); const e = new Error( y.SocketConnectionFailed // , { // cause: data, // } ); p.error("error", e), this.event.emit("error", e), t(!1); } }), i.on("action", (s, e) => v(this, null, function* () { if (this._stopAnswer || !this.id) return; const { type: o, data: { runnerIsClient: c, pluginCode: g, funcCode: m, parameters: a, requestBody: N } } = s, l = this.messages[this.messages.length - 1]; if (!l.messageId) l.actions || (l.actions = []), l.actions[s.data.step - 1] || (l.actions[s.data.step - 1] = []), l.actions[s.data.step - 1].push(s), this.event.emit("message:action", { messageId: l.messageId, action: s }), this.event.emit("message:updated", l); else { const u = { messageId: "", content: "", role: I.Robot, sessionId: this.id, reference: [], searchReference: [], isLoading: !0, messageTime: "", actions: [[s]], comment: { isAgree: 0 } }; this.pushMessage(u), this.event.emit("message:action", { messageId: u.messageId, action: s }); } if (this.inactivating) { const u = new Error( y.Inactive // { // cause: { // code: -1, // message: // 'session is inactive, skipping plugin client function call', // }, // } ); p.warn("error", u), this.event.emit("error", u); } else if (o === "FUNCTION_CALL" && c) { if (p.log(`calling function ${m} of plugin ${g} with argument: ${JSON.stringify(a)}`), !f.plugins[g]) { e({ code: 404, message: "对不起,没有找到插件。" }); return; } const u = f.plugins[g][m]; typeof u != "function" && e({ code: 404, message: "对不起,没有找到插件方法。" }); let M = a == null ? void 0 : a.query; try { M = JSON.parse(a == null ? void 0 : a.query); } catch (C) { } u(M, (...C) => { this._stopAnswer || e(...C); }); } })), i.on("answer", (s) => { if (!this._stopAnswer) if (s.data.code !== 200 && (s.data.index = -1, this.event.emit("error", s.data)), s.data.index === -1) { let e = this.messages[this.messages.length - 1]; if (e && !e.messageId) e = h(h({}, e), s.data), this.event.emit("message:content", e), this.event.emit("message:updated", e), this.event.emit("answer:finish", e); else { const o = h({ messageId: "", content: "", role: I.Robot, sessionId: this.id, reference: [], searchReference: [], isLoading: !1, messageTime: "", actions: [], comment: { isAgree: 0 } }, s.data); this.event.emit("message:content", o), this.pushMessage(o), this.event.emit("answer:finish", o); } } else { let e = this.messages[this.messages.length - 1]; e && !e.messageId ? (e = h(h({}, e), s.data), this.messages[this.messages.length - 1] = e, this.event.emit("message:content", e), this.event.emit("message:updated", e)) : (this.pushMessage(s.data), this.event.emit("message:content", s.data)); } }), i.on("reference", (s) => v(this, null, function* () { if (this._stopAnswer) return; if (!this.id) { const a = new Error( y.IdUndefined // { // cause: SESSION_ERROR_CAUSE[SessionErrors.IdUndefined], // } ); p.error(a), this.event.emit("error", a), this.frozen = !1; return; } const { type: e, data: o, requestId: c } = s, g = this.messages.findIndex((a) => a.messageId === c && a.role === I.User); if (g < 0) return; const m = g + 1; if (m >= this.messages.length) { const a = { messageId: "", content: "", role: I.Robot, sessionId: this.id, reference: [], searchReference: [], isLoading: !0, messageTime: "", actions: [], comment: { isAgree: 0 } }; this.pushMessage(a); } e === "KG" ? (this.messages[m] = k(h({}, this.messages[m]), { reference: o.knowledgeReference }), yield this.fillMessageReference(this.messages[m]), this.event.emit("message:reference", o.knowledgeReference), this.event.emit("message:updated", this.messages[m])) : e === "WEB_SEARCH" && (this.messages[m] = k(h({}, this.messages[m]), { searchReference: o.knowledgeReference }), this.event.emit("message:searchreference", o.searchReference), this.event.emit("message:updated", this.messages[m])); })), this.socket = i, i.open(); })); } registerMcpFromClientConfig() { return f.mcp ? new Promise((t, n) => { if (!this.socket) { n("socket is undefined"); return; } this.socket.emit("add_mcp_servers", f.mcp, (r) => { r.code === 200 ? (Object.keys(r.data).forEach((i) => { r.data[i].code !== 200 && console.error(i, "MCP Server 注册失败。", r.data[i]); }), t(!0)) : (console.error("MCP Server 注册失败。", r), n(r)); }); }) : Promise.resolve(!0); } addMcpServers(t) { return v(this, null, function* () { return this.ready ? this.socket ? new Promise((n, r) => { this.socket && this.socket.emit("add_mcp_servers", t, (i) => { i.code === 200 ? (Object.keys(i.data).forEach((s) => { i.data[s].code !== 200 && console.error(s, "MCP Server 注册失败。", i.data[s]); }), n(!0)) : (console.error("MCP Server 注册失败。", i), r(i)); }); }) : (console.error(" socket is undefined."), Promise.reject("socket is undefined")) : (console.error("session is not avalible."), Promise.reject("session is not avalible")); }); } listMcpServers() { return v(this, null, function* () { return this.ready ? this.socket ? new Promise((t, n) => { this.socket && this.socket.emit("list_mcp_servers", (r) => { r.code === 200 ? t(r.data) : n(r); }); }) : (console.error(" socket is undefined."), Promise.reject("socket is undefined")) : (console.error("session is not avalible."), Promise.reject("session is not avalible")); }); } sendQuestion(t, n) { return v(this, null, function* () { var i, s, e; let r = k(h({}, t), { promptVariables: this.promptVariables.reduce((o, c) => k(h({}, o), { [c.key]: c.value }), {}), knowledges: (i = this.knowledges) == null ? void 0 : i.map((o) => o.id) }); if (!this.active) { if (yield this.activate(), !this.socket) { const o = new Error( y.SocketConnectionFailed // { // cause: { code: -1, message: 'socket is null' }, // } ); return p.warn("error", o), this.event.emit("error", o), !1; } (s = this.socket) == null || s.emit("question", r); return; } (e = this.socket) == null || e.emit("question", r); }); } stopAnswer() { var t; (t = this.socket) == null || t.emit("stop_answer"); } } export { D as default };