@glodon-aiot/agent-cli-sdk 3.25.1-alpha.1 → 3.25.1-alpha.3
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/es/utils.mjs +1 -1
- package/dist/lib/index.js +1 -1
- package/package.json +2 -2
package/dist/es/utils.mjs
CHANGED
|
@@ -6,7 +6,7 @@ const t = (n) => JSON.parse(o(n.split(".")[1])), w = (n) => {
|
|
|
6
6
|
if (n !== !0)
|
|
7
7
|
return null;
|
|
8
8
|
const s = (e == null ? void 0 : e.includeUserQuestion) === !0, u = (e == null ? void 0 : e.includeAiAnswer) === !0 || !s, r = [];
|
|
9
|
-
return s && r.push(
|
|
9
|
+
return s && r.push(`问题:${i}`), u && r.push(`回答:${c}`), r.join(`
|
|
10
10
|
`);
|
|
11
11
|
};
|
|
12
12
|
export {
|
package/dist/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var P=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,j=Object.prototype.propertyIsEnumerable;var Q=(o,e,t)=>e in o?se(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,g=(o,e)=>{for(var t in e||(e={}))B.call(e,t)&&Q(o,t,e[t]);if(P)for(var t of P(e))j.call(e,t)&&Q(o,t,e[t]);return o},w=(o,e)=>ie(o,ne(e));var F=(o,e)=>{var t={};for(var s in o)B.call(o,s)&&e.indexOf(s)<0&&(t[s]=o[s]);if(o!=null&&P)for(var s of P(o))e.indexOf(s)<0&&j.call(o,s)&&(t[s]=o[s]);return t};var m=(o,e,t)=>(Q(o,typeof e!="symbol"?e+"":e,t),t);var p=(o,e,t)=>new Promise((s,a)=>{var r=i=>{try{d(t.next(i))}catch(c){a(c)}},n=i=>{try{d(t.throw(i))}catch(c){a(c)}},d=i=>i.done?s(i.value):Promise.resolve(i.value).then(r,n);d((t=t.apply(o,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),re=require("axios"),y=require("@glodon-aiot/apis"),oe=require("socket.io-client"),J=require("uuid"),K=require("dayjs"),L=class L{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!L.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!L.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!L.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!L.debug||console.warn(this.prefix,...e)}};m(L,"debug",!1);let b=L;const ce=new b("[Config] ");var G=(o=>(o.dev="https://aiot-dev.glodon.com/api/cvforcepd",o.test="https://aiot-dev.glodon.com/api/cvforce",o.prod="https://copilot.glodon.com/api/cvforce",o.local="http://localhost:3000/api/cvforcepd",o))(G||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function z(o){var e,t;b.debug=(o==null?void 0:o.debug)||!1,exports.configuration=w(g(g({},exports.configuration),o),{apiRoot:(o==null?void 0:o.apiRoot)||exports.configuration.apiRoot||(o!=null&&o.env?G[o.env||"prod"]:exports.configuration.apiRoot),plugins:(t=(e=o==null?void 0:o.plugins)!=null?e:exports.configuration.plugins)!=null?t:{}}),b.debug&&ce.log("updated",exports.configuration)}const V=o=>JSON.parse(ae.decode(o.split(".")[1])),de=o=>{const e=V(o).exp;return new Date().valueOf()/1e3>=e},he=o=>o==null?void 0:o.replace(/[\r\n]+/gm,""),le=o=>o.replace(/\\|\\/g,""),fe=(o,e,t,s)=>{if(o!==!0)return null;const a=(e==null?void 0:e.includeUserQuestion)===!0,n=(e==null?void 0:e.includeAiAnswer)===!0||!a,d=[];return a&&d.push(
|
|
1
|
+
"use strict";var se=Object.defineProperty,ie=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var P=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,j=Object.prototype.propertyIsEnumerable;var Q=(o,e,t)=>e in o?se(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,g=(o,e)=>{for(var t in e||(e={}))B.call(e,t)&&Q(o,t,e[t]);if(P)for(var t of P(e))j.call(e,t)&&Q(o,t,e[t]);return o},w=(o,e)=>ie(o,ne(e));var F=(o,e)=>{var t={};for(var s in o)B.call(o,s)&&e.indexOf(s)<0&&(t[s]=o[s]);if(o!=null&&P)for(var s of P(o))e.indexOf(s)<0&&j.call(o,s)&&(t[s]=o[s]);return t};var m=(o,e,t)=>(Q(o,typeof e!="symbol"?e+"":e,t),t);var p=(o,e,t)=>new Promise((s,a)=>{var r=i=>{try{d(t.next(i))}catch(c){a(c)}},n=i=>{try{d(t.throw(i))}catch(c){a(c)}},d=i=>i.done?s(i.value):Promise.resolve(i.value).then(r,n);d((t=t.apply(o,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("js-base64"),re=require("axios"),y=require("@glodon-aiot/apis"),oe=require("socket.io-client"),J=require("uuid"),K=require("dayjs"),L=class L{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!L.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!L.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!L.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!L.debug||console.warn(this.prefix,...e)}};m(L,"debug",!1);let b=L;const ce=new b("[Config] ");var G=(o=>(o.dev="https://aiot-dev.glodon.com/api/cvforcepd",o.test="https://aiot-dev.glodon.com/api/cvforce",o.prod="https://copilot.glodon.com/api/cvforce",o.local="http://localhost:3000/api/cvforcepd",o))(G||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function z(o){var e,t;b.debug=(o==null?void 0:o.debug)||!1,exports.configuration=w(g(g({},exports.configuration),o),{apiRoot:(o==null?void 0:o.apiRoot)||exports.configuration.apiRoot||(o!=null&&o.env?G[o.env||"prod"]:exports.configuration.apiRoot),plugins:(t=(e=o==null?void 0:o.plugins)!=null?e:exports.configuration.plugins)!=null?t:{}}),b.debug&&ce.log("updated",exports.configuration)}const V=o=>JSON.parse(ae.decode(o.split(".")[1])),de=o=>{const e=V(o).exp;return new Date().valueOf()/1e3>=e},he=o=>o==null?void 0:o.replace(/[\r\n]+/gm,""),le=o=>o.replace(/\\|\\/g,""),fe=(o,e,t,s)=>{if(o!==!0)return null;const a=(e==null?void 0:e.includeUserQuestion)===!0,n=(e==null?void 0:e.includeAiAnswer)===!0||!a,d=[];return a&&d.push(`问题:${s}`),n&&d.push(`回答:${t}`),d.join(`
|
|
2
2
|
`)};function X(o,e,t){const s=c=>{var l;return e&&(de(e)&&t(403,"aiotToken is timeout"),c.headers=(l=c.headers)!=null?l:{},c.headers=w(g({},c.headers),{Authorization:e?`Bearer ${e}`:""})),c};function a(c,l=!0){const f=`${o}${c}`,u=re.create({baseURL:f});return l&&u.interceptors.request.use(s),u}const r=(c,l)=>{c===401&&t(c,"aiotToken is invalid")},n=(c,l)=>{console.log("onAppStatusError",c,l),c!==10001&&c!==10215&&t(c,l)},d=a("/data/v1");return new y.CVForceApi(d,{onHttpStatusError:r,onAppStatusError:n})}var E=(o=>(o[o.Normal=0]="Normal",o[o.Debug=1]="Debug",o))(E||{});const R=new b("[EventBus] ");class Z{constructor(e=!1){m(this,"eventListenerMap",{});e&&R.disable()}getEventListenerMap(){return g({},this.eventListenerMap)}on(e,t,s=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),s?this.eventListenerMap[e].push({fn:t,once:!0}):this.eventListenerMap[e].push(t),R.log(`add event ${e} listener ${s?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const s=this.eventListenerMap[e].findIndex(a=>{if(typeof a=="function"&&t===a)return!0;if(a=a,a.fn===t)return!0});s<0?R.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),R.log(`remove event ${e} listener`))}else R.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){R.log(`event ${e} listeners is empty`);return}const s=[];for(let a=0;a<this.eventListenerMap[e].length;a++){const r=this.eventListenerMap[e][a];typeof r=="function"?r(t):s.push(r)}s.forEach(a=>{a&&(a.fn(t),this.off(e,a.fn))}),R.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const S=new b("[Session] ");var x=(o=>(o.DataRequestFailed="data request error",o.SocketConnectionFailed="socket error",o.IdUndefined="session id is not defined",o.SendingEmptyContent="failed at sending empty content",o.Frozen="session is frozen",o.UserModeError="failed at setting socket user mode",o.Inactive="session is inactive",o))(x||{});class q{constructor(e,t="",s,a,r,n){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new Z);m(this,"_applicationId");m(this,"_application",null);m(this,"data",null);m(this,"client",null);m(this,"messages",[]);m(this,"_loadingMessages",!1);m(this,"_loadingMessagesSize",10);m(this,"cvforceApi");m(this,"socket",null);m(this,"_promptVariables",[]);m(this,"active",!1);m(this,"activing",!1);m(this,"_stopAnswer",!1);m(this,"_dataLoading",!1);m(this,"_dataLoaded",!1);m(this,"_mcpServers",null);this.token=e,this.lazyload=a,this.client=n||null,this._applicationId=V(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),r&&(this._application=r),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var d;if(t)this._id=t,this.event.emit("data:loading"),s?(this.data=s,a||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(i=>p(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data)})))):(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(i=>p(this,null,function*(){this.data=i,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>p(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoading=!1,this._dataLoaded=!0})));else{const i=(s==null?void 0:s.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:i}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:i,netOpen:s==null?void 0:s.netOpen,knowledgeIdList:(d=s==null?void 0:s.knowledges)==null?void 0:d.map(c=>c.id),applicationId:this._applicationId}).then(c=>p(this,null,function*(){var l;this._id=c.id,this.data=w(g({},c),{knowledges:s==null?void 0:s.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),yield(()=>p(this,null,function*(){if(s!=null&&s.knowledges)return this.setKnowledges((s==null?void 0:s.knowledges)||void 0)}))(),yield(()=>{if(s!=null&&s.promptVariables){const f=this._promptVariables.map(u=>{var I,v;const h=((v=(I=s.promptVariables)==null?void 0:I.find(_=>_.key===u.key&&_.type===u.type))==null?void 0:v.value)||"";return w(g({},u),{value:h})}).sort((u,h)=>u.key.localeCompare(h.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),((l=this.application)==null?void 0:l.type)!==y.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}fetchData(){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.getSession(this.applicationId,this.data.id).then(e=>p(this,null,function*(){return this.data=e,this.event.emit("data:updated",this.data),e}))})}get id(){var e;return this._id||((e=this.data)==null?void 0:e.id)||""}get applicationId(){return this._applicationId}get application(){return this._application}set application(e){this._application=e}loadApplicationInfo(){if(this._application)return Promise.resolve(this._application);if(this._applicationId&&!this._application)return this.event.emit("application:data:loading"),this.cvforceApi.getApplicationId(this._applicationId).then(e=>(this._application=e,this.event.emit("application:data:loaded",e),e));throw Error("application id is not defined")}get ready(){return this._ready}get frozen(){return this._frozen}set frozen(e){e===!1&&this.inactivating&&this.socket&&(this.socket.disconnect(),this.socket=null,this.event.emit("inactivated")),this._frozen=e,this.event.emit("frozen",e)}get knowledges(){if(!this.data)throw Error("session data is not loaded");return this.data.knowledges||void 0}setKnowledges(e){return p(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(t=>t.status===y.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>!(e.type===y.PromptVariableType.User&&e.key==="query")&&!(e.type===y.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return p(this,null,function*(){const t=this._promptVariables.map(s=>{var r;const a=((r=e==null?void 0:e.find(n=>n.key===s.key&&n.type===s.type))==null?void 0:r.value)||s.value;return w(g({},s),{value:a})}).sort((s,a)=>s.key.localeCompare(a.key));if(yield Promise.all(t.filter(s=>!(s.type===y.PromptVariableType.User&&s.key==="query")&&!(s.type===y.PromptVariableType.System&&s.key==="datetime")).map(s=>{if(!this.data)throw Error("session data is not loaded");if(!(!s.id||!s.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,s.id,{value:s.value})})),!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return p(this,null,function*(){var t,s,a;if(S.log("setNetOpen:",e),S.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===y.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((a=this._application)==null?void 0:a.arrange[0].enableNetOpen)===!1){console.warn("This Application is disabled to change netOpen.");return}if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{netOpen:e?1:2}),this.data.netOpen=e,S.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return X(exports.configuration.apiRoot,this.token,(e,t)=>{const s=new Error("data request error",{cause:{status:e,message:t}});S.error(s),this.event.emit("error",s)})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}fetchMessages(){return p(this,arguments,function*(e={}){var s,a;const t={pageSize:this._loadingMessagesSize};if(this._id){e=g(g({},t),e),this.event.emit("history:loading"),S.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),S.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),n=r.map((i,c)=>{var u,h;let l=[],f;return typeof((u=i.agentHistoryList)==null?void 0:u.agentList)=="string"&&(l=JSON.parse(i.agentHistoryList.agentList).reduce((v,_)=>(v[_.data.step-1]||(v[_.data.step-1]=[]),v[_.data.step-1].push(_),v),[])),c===r.length-1&&(f=(h=this.data)==null?void 0:h.lastRelatedQuestion),w(g({},i),{actions:l,relatedQuesion:f})});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(l=>l.ts===e.endTime),c=this.messages.findLastIndex(l=>l.ts===e.endTime);this.messages.splice(i,c-i+1,...n)}const d=this.messages[this.messages.length-1];return d&&!d.relatedQuesion&&(d.relatedQuesion=(a=this.data)==null?void 0:a.lastRelatedQuestion),this.event.emit("history:moreloaded",n),S.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,n}else{const r=new Error("session id is not defined");return S.error(r),this.event.emit("error",r),!1}})}rename(e){return p(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),S.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return p(this,null,function*(){this.messages.push(e),S.log("history:add",e),this.event.emit("history:add",e),this.event.emit("message:new",e),this.event.emit("message:updated",e)})}reloadSessionInfo(){if(!this._id)throw Error("session is not created yet");return this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,this._id).then(e=>p(this,null,function*(){if(this.data=e,!this._id)throw Error("session is not created yet");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),S.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>p(this,null,function*(){return this.messages=[],yield this.fetchMessages(),this._dataLoading=!1,this._dataLoaded=!0,this.event.emit("data:loaded",this.data),this}))}reload(){return p(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return p(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return S.error(e),this.event.emit("error",e),!1}return this.event.emit("data:deleting"),yield this.cvforceApi.delSessionsId(this.applicationId,this.id),this.event.emit("data:deleted"),this.destroy()})}activate(){return p(this,null,function*(){if(this.activing)return new Promise(t=>{this.addEventListener("activated",()=>{t(!0)},!0)});if(!this._id)throw Error("session is not avalible. id is undefined");this.activing=!0;const e=this._id;return this._dataLoading=!0,this._dataLoaded=!1,this.data=yield this.cvforceApi.getSession(this.applicationId,e).then(t=>p(this,null,function*(){return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,e),t})),this.messages.length||(this.messages=[],yield this.fetchMessages()),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoaded=!0,this._dataLoading=!1,this.inactivating=!1,this.frozen=!0,yield this.prepareConnection(),this.event.emit("activated",this.socket),this.active=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?this._frozen?(e||(this.inactivating=!0),this.activing=!1,!0):(this.socket.close(),this.socket=null,this.event.emit("inactivated"),this.active=!1,this.activing=!1,!0):(this.activing=!1,!0)}get dataLoaded(){return this._dataLoaded}get messagesLoading(){return this._loadingMessages}send(s){return p(this,arguments,function*(e,t={stream:exports.configuration.stream}){var u;try{this.validateConfigs()}catch(h){console.error(h)}const{stream:a=exports.configuration.stream,referenceFirst:r=!1}=t,n=e.uuid||J.v4(),d=((u=e.text)==null?void 0:u.trim())||"",i=e.fileIds;if(!d&&!(i!=null&&i.length)){const h=new Error("failed at sending empty content");return S.error(h),this.event.emit("error",h),!1}if(!this._id){const h=new Error("session id is not defined");return S.error(h),this.event.emit("error",h),!1}if(this.frozen){const h=new Error("session is frozen");return S.error(h),this.event.emit("error",h),!1}this.frozen=!0,this._stopAnswer=!1;const c={sessionId:this.id,role:2,content:d,messageId:n,reference:[],searchReference:[],messageTime:""},l={content:d,stream:a,requestId:n,fileIds:i,referenceFirst:r};this.pushMessage(c),this.event.emit("question:content",d);const f=h=>p(this,null,function*(){if(h.role!==y.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",f),this._id&&h.content&&h.index&&h.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:h.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:h.content})),yield this.fillMessageReference(h),h.code){case 11915:h.content="请您换个问题问我吧~",h.index=-1,h.isSensitive=!0,h.isLoading=!1,h.sessionId=this._id||"",this.event.emit("message:error",h);break;case 11916:h.content="尊敬的用户您好,让我们换个话题再聊聊吧。",h.index=-1,h.isSensitive=!0,h.isLoading=!1,h.sessionId=this._id||"",this.event.emit("message:error",h);break;case 200:h.index=-1,h.isLoading=!1;break;default:h.content=h.message||"未知错误",h.isLoading=!1,h.index=-1,this.event.emit("message:error",h)}this.getRelatedQuesion(h),h.isLoading=!1;let I=this.messages[this.messages.length-1];if(I&&I.role===y.ChatMessageRole.Robot){const v=g(g({},I),h);this.messages[this.messages.length-1]=v,this.event.emit("message:updated",v)}else this.pushMessage(h);this.frozen=!1});return this.addEventListener("answer:finish",f),this.sendQuestion(l,w(g({},t),{stream:a,referenceFirst:r})),c})}currentUserQuestion(){for(let e=this.messages.length-1;e>=0;e-=1){const t=this.messages[e];if(t.role===y.ChatMessageRole.User)return t.content||""}return""}getRelatedQuesion(e){return p(this,null,function*(){var d,i;if(!e.content||e.isSensitive||e.code!==200)return e;const t=(d=this.application)==null?void 0:d.arrange[0],s=fe(t==null?void 0:t.recommendQuestionOpen,t==null?void 0:t.relatedQuestionApp,e.content,this.currentUserQuestion());if(s===null)return e;this.event.emit("message:relatedQuesion:loading",e);const a=yield this.cvforceApi.postGeneques({content:s}).catch(c=>null);if(!a){const c=[],l=w(g({},e),{relatedQuesion:c,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:c}),this.event.emit("message:updated",l),l}const r=(i=a.content)==null?void 0:i.split("*").map(he).map(le).filter(c=>!!c);e.relatedQuesion=r,e.index=-3,e.isLoading=!1;const n=w(g({},e),{relatedQuesion:r,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",n),this.event.emit("message:updated",n),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:r}),n})}fillMessageReference(e){return p(this,null,function*(){const t=yield Promise.all(e.reference.map(s=>this.cvforceApi.getKnowledgeIdFileId(s.knowledgeId,s.docId)));return e.reference=e.reference.map((s,a)=>g(g({},s),t[a])),this.event.emit("message:updated",e),e})}answerAgain(){return p(this,arguments,function*(e={stream:exports.configuration.stream}){const t=this.messages[this.messages.length-1];if(!t)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1;const{stream:s=exports.configuration.stream}=e;let a;t.role!==y.ChatMessageRole.User&&(a=e.oldMessageId||t.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",t),this.event.emit("history:remove",t));const r=this.messages[this.messages.length-1],n={content:r.content,fileIds:r.fileIds,requestId:r.messageId,stream:s,oldMessageId:a},d=i=>p(this,null,function*(){if(i.role===y.ChatMessageRole.Robot&&i.index===-1){switch(this._id&&i.content&&i.index&&i.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:i.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:i.content})),yield this.fillMessageReference(i),i.code){case 11915:i.content="请您换个问题问我吧~",i.index=-1,i.isSensitive=!0,i.isLoading=!1,i.sessionId=this._id||"",this.event.emit("message:error",i);break;case 11916:i.content="尊敬的用户您好,让我们换个话题再聊聊吧。",i.index=-1,i.isSensitive=!0,i.isLoading=!1,i.sessionId=this._id||"",this.event.emit("message:error",i);break;case 200:i.index=-1,i.isLoading=!1;break;default:i.content=i.message||"未知错误",i.isLoading=!1,i.index=-1,this.event.emit("message:error",i)}this.getRelatedQuesion(i),this.removeEventListener("message:content",d),this.frozen=!1}});this.addEventListener("message:content",d),this.sendQuestion(n,w(g({},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:y.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const a=e.actions[((s=e.actions)==null?void 0:s.length)-1];if(a){const r=a[a.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:n,pluginCode:d,funcCode:i,funcName:c}=r.data;a.push({data:{pluginName:n,pluginCode:d,funcCode:i,funcName:c,step:r.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:a})}}}e=g(g({},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 M=new b("[AgentSession] ");class pe extends q{constructor(e,t="",s,a,r,n){super(e,t,s,a,r,n)}prepareConnection(){return new Promise(e=>p(this,null,function*(){this.socket&&e(!0);const t={version:"1.0",stream:JSON.stringify(exports.configuration.stream===void 0?!0:exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?E.Debug:E.Normal},s=new URL(exports.configuration.apiRoot),a=yield oe.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});a.on("connect",()=>{M.log("socket:connect"),this.event.emit("socket:connect"),a.emit("init")}),a.on("disconnect",()=>{M.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),a.on("ready",r=>{if(r.code===200){M.log("ready");const n=exports.configuration.debug?E.Debug:E.Normal;n===E.Debug&&r.userMode,this._ready=!0,this.event.emit("ready"),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const n=new Error(x.SocketConnectionFailed);M.error("error",n),this.event.emit("error",n),e(!1)}}),a.on("action",(r,n)=>p(this,null,function*(){var I;if(this._stopAnswer||!this.id)return;const{type:d,data:{runnerIsClient:i,pluginCode:c,funcCode:l,parameters:f,requestBody:u}}=r,h=this.messages[this.messages.length-1];if(!h.messageId)h.actions||(h.actions=[]),h.actions[r.data.step-1]||(h.actions[r.data.step-1]=[]),h.actions[r.data.step-1].push(r),this.event.emit("message:action",{messageId:h.messageId,action:r}),this.event.emit("message:updated",h);else{const v={messageId:"",content:"",role:y.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[r]],comment:{isAgree:0}};this.pushMessage(v),this.event.emit("message:action",{messageId:v.messageId,action:r})}if(this.inactivating){const v=new Error(x.Inactive);M.warn("error",v),this.event.emit("error",v)}else if(d==="FUNCTION_CALL"&&i){M.log(`calling function ${l} of plugin ${c} with argument:
|
|
3
3
|
${JSON.stringify(f)}`);const v=(I=exports.configuration.plugins)==null?void 0:I[c];if(!v){n({code:404,message:"没有找到插件。"});return}const _=v[l];if(typeof _!="function"){n({code:404,message:"没有找到插件方法。"});return}let A=f==null?void 0:f.query;try{A=JSON.parse(f==null?void 0:f.query)}catch(C){}_(A,(...C)=>{this._stopAnswer||n(...C)})}})),a.on("answer",r=>{if(!this._stopAnswer)if(r.data.code!==200&&(r.data.index=-1,this.event.emit("error",r.data)),r.data.index===-1){let n=this.messages[this.messages.length-1];if(n&&!n.messageId)n=g(g({},n),r.data),this.event.emit("message:content",n),this.event.emit("message:updated",n),this.event.emit("answer:finish",n);else{const d=g({messageId:"",content:"",role:y.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0}},r.data);this.event.emit("message:content",d),this.pushMessage(d),this.event.emit("answer:finish",d)}}else{let n=this.messages[this.messages.length-1];n&&!n.messageId?(n=g(g({},n),r.data),this.messages[this.messages.length-1]=n,this.event.emit("message:content",n),this.event.emit("message:updated",n)):(this.pushMessage(r.data),this.event.emit("message:content",r.data))}}),a.on("reference",r=>p(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const f=new Error(x.IdUndefined);M.error(f),this.event.emit("error",f),this.frozen=!1;return}const{type:n,data:d,requestId:i}=r,c=this.messages.findIndex(f=>f.messageId===i&&f.role===y.ChatMessageRole.User);if(c<0)return;const l=c+1;if(l>=this.messages.length){const f={messageId:"",content:"",role:y.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0}};this.pushMessage(f)}n==="KG"?(this.messages[l]=w(g({},this.messages[l]),{reference:d.knowledgeReference}),yield this.fillMessageReference(this.messages[l]),this.event.emit("message:reference",d.knowledgeReference),this.event.emit("message:updated",this.messages[l])):n==="WEB_SEARCH"&&(this.messages[l]=w(g({},this.messages[l]),{searchReference:d.knowledgeReference}),this.event.emit("message:searchreference",d.searchReference),this.event.emit("message:updated",this.messages[l]))})),this.socket=a,a.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((e,t)=>{if(!this.socket){t("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,s=>{s.code===200?(Object.keys(s.data).forEach(a=>{s.data[a].code!==200&&console.error(a,"MCP Server 注册失败。",s.data[a])}),e(!0)):(console.error("MCP Server 注册失败。",s),t(s))})}):Promise.resolve(!0)}addMcpServers(e){return p(this,null,function*(){return this.ready?this.socket?new Promise((t,s)=>{this.socket&&this.socket.emit("add_mcp_servers",e,a=>{a.code===200?(Object.keys(a.data).forEach(r=>{a.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",a.data[r])}),t(!0)):(console.error("MCP Server 注册失败。",a),s(a))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return p(this,null,function*(){return this.ready?this.socket?new Promise((e,t)=>{this.socket&&this.socket.emit("list_mcp_servers",s=>{s.code===200?e(s.data):t(s)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(e,t){return p(this,null,function*(){var a,r,n;let s=w(g({},e),{promptVariables:this.promptVariables.reduce((d,i)=>w(g({},d),{[i.key]:i.value}),{}),knowledges:(a=this.knowledges)==null?void 0:a.map(d=>d.id)});if(!this.active){if(yield this.activate(),!this.socket){const d=new Error(x.SocketConnectionFailed);return M.warn("error",d),this.event.emit("error",d),!1}(r=this.socket)==null||r.emit("question",s);return}(n=this.socket)==null||n.emit("question",s)})}stopAnswer(){var e;(e=this.socket)==null||e.emit("stop_answer")}}function ue(o,e){return p(this,null,function*(){const t=o.getReader();let s;for(;!(s=yield t.read()).done;)e(s.value)})}function ge(o){let e,t,s,a=!1,r;return function(d){e===void 0?(e=d,t=0,s=-1,r=!1):e=ve(e,d);const i=e.length;let c=0;for(;t<i;){a&&(e[t]===10&&(c=++t),a=!1);let l=-1;for(;t<i&&l===-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&&(r=!0);case 10:l=t;break}if(l===-1)break;o(e.subarray(c,l),s,r),c=t,s=-1,r=!1}c===i?e=void 0:c!==0&&(e=e.subarray(c),t-=c)}}function me(o,e,t){let s=U();const a=new TextDecoder;return function(n,d,i){if(n.length===0)t==null||t(s),s=U();else if(d>0){const c=a.decode(n.subarray(0,d)),l=d+(n[d+1]===32?2:1);let f=a.decode(n.subarray(l));switch(i&&(f+=`
|
|
4
4
|
`),c){case"data":s.data=s.data?s.data+`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glodon-aiot/agent-cli-sdk",
|
|
3
|
-
"version": "3.25.1-alpha.
|
|
3
|
+
"version": "3.25.1-alpha.3",
|
|
4
4
|
"author": "glodoncv",
|
|
5
5
|
"description": "aiot agent client js sdk",
|
|
6
6
|
"type": "module",
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
"registry": "https://registry.npmjs.org/"
|
|
80
80
|
},
|
|
81
81
|
"dependencies": {
|
|
82
|
-
"@glodon-aiot/apis": "^3.25.1-alpha.
|
|
82
|
+
"@glodon-aiot/apis": "^3.25.1-alpha.3",
|
|
83
83
|
"axios": "0.24.0",
|
|
84
84
|
"buffer": "^6.0.3",
|
|
85
85
|
"dayjs": "^1.11.13",
|