@glodon-aiot/bot-client-sdk 3.25.1-alpha.7 → 3.26.0-alpha.4
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 +543 -98
- package/dist/es/AgentSession.mjs +230 -165
- package/dist/es/BotClient.mjs +186 -136
- package/dist/es/Config.mjs +111 -26
- package/dist/es/Session.mjs +12 -0
- package/dist/es/api/index.mjs +42 -33
- package/dist/es/index.mjs +68 -9
- package/dist/es/localFiles/adapters/FileSystemAccessAdapter.mjs +174 -0
- package/dist/es/localFiles/adapters/HostBridgeAdapter.mjs +172 -0
- package/dist/es/localFiles/adapters/MemoryWorkspaceAdapter.mjs +162 -0
- package/dist/es/localFiles/adapters/WorkspaceFileAdapter.mjs +50 -0
- package/dist/es/localFiles/adapters/fsaTypes.mjs +9 -0
- package/dist/es/localFiles/constants.mjs +47 -0
- package/dist/es/localFiles/createLocalFilesPlugin.mjs +255 -0
- package/dist/es/localFiles/createLocalPythonPlugin.mjs +196 -0
- package/dist/es/localFiles/errors.mjs +57 -0
- package/dist/es/localFiles/host/connectHostBridge.mjs +50 -0
- package/dist/es/localFiles/host/protocol.mjs +26 -0
- package/dist/es/localFiles/limits.mjs +22 -0
- package/dist/es/localFiles/schemas.mjs +327 -0
- package/dist/es/localFiles/security/downloadUrlPolicy.mjs +39 -0
- package/dist/es/localFiles/security/glob.mjs +28 -0
- package/dist/es/localFiles/security/pathPolicy.mjs +59 -0
- package/dist/es/localFiles/security/sensitiveFiles.mjs +115 -0
- package/dist/es/localFiles/tools/readTools.mjs +333 -0
- package/dist/es/localFiles/tools/runtime.mjs +108 -0
- package/dist/es/localFiles/tools/transferTools.mjs +228 -0
- package/dist/es/localFiles/tools/writeTools.mjs +173 -0
- package/dist/es/localFiles/transfer/SessionFileTransfer.mjs +111 -0
- package/dist/es/localFiles/validate.mjs +66 -0
- package/dist/es/localFiles/workspace/LocalWorkspace.mjs +339 -0
- package/dist/es/localFiles/workspace/handleStore.mjs +79 -0
- package/dist/es/localFiles/workspace/watchDirectory.mjs +38 -0
- package/dist/es/package.json.mjs +7 -4
- package/dist/lib/index.js +9 -4
- package/dist/src/AgentSession.d.ts +9 -0
- package/dist/src/BotClient.d.ts +12 -2
- package/dist/src/Config.d.ts +22 -0
- package/dist/src/Session.d.ts +5 -1
- package/dist/src/api/index.d.ts +3 -1
- package/dist/src/index.d.ts +4 -2
- package/dist/src/localFiles/adapters/FileSystemAccessAdapter.d.ts +17 -0
- package/dist/src/localFiles/adapters/HostBridgeAdapter.d.ts +24 -0
- package/dist/src/localFiles/adapters/MemoryWorkspaceAdapter.d.ts +18 -0
- package/dist/src/localFiles/adapters/WorkspaceFileAdapter.d.ts +26 -0
- package/dist/src/localFiles/adapters/fsaTypes.d.ts +39 -0
- package/dist/src/localFiles/constants.d.ts +50 -0
- package/dist/src/localFiles/createLocalFilesPlugin.d.ts +11 -0
- package/dist/src/localFiles/createLocalPythonPlugin.d.ts +12 -0
- package/dist/src/localFiles/errors.d.ts +34 -0
- package/dist/src/localFiles/host/connectHostBridge.d.ts +6 -0
- package/dist/src/localFiles/host/protocol.d.ts +33 -0
- package/dist/src/localFiles/index.d.ts +21 -0
- package/dist/src/localFiles/limits.d.ts +3 -0
- package/dist/src/localFiles/schemas.d.ts +30 -0
- package/dist/src/localFiles/security/downloadUrlPolicy.d.ts +4 -0
- package/dist/src/localFiles/security/glob.d.ts +3 -0
- package/dist/src/localFiles/security/pathPolicy.d.ts +14 -0
- package/dist/src/localFiles/security/sensitiveFiles.d.ts +23 -0
- package/dist/src/localFiles/tools/readTools.d.ts +7 -0
- package/dist/src/localFiles/tools/runtime.d.ts +43 -0
- package/dist/src/localFiles/tools/transferTools.d.ts +4 -0
- package/dist/src/localFiles/tools/writeTools.d.ts +4 -0
- package/dist/src/localFiles/transfer/SessionFileTransfer.d.ts +40 -0
- package/dist/src/localFiles/types.d.ts +306 -0
- package/dist/src/localFiles/validate.d.ts +2 -0
- package/dist/src/localFiles/workspace/LocalWorkspace.d.ts +99 -0
- package/dist/src/localFiles/workspace/handleStore.d.ts +11 -0
- package/dist/src/localFiles/workspace/watchDirectory.d.ts +7 -0
- package/package.json +7 -4
package/dist/lib/index.js
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
|
-
"use strict";var ie=Object.defineProperty,ne=Object.defineProperties;var ae=Object.getOwnPropertyDescriptors;var V=Object.getOwnPropertySymbols;var q=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var z=(c,e,t)=>e in c?ie(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t,g=(c,e)=>{for(var t in e||(e={}))q.call(e,t)&&z(c,t,e[t]);if(V)for(var t of V(e))B.call(e,t)&&z(c,t,e[t]);return c},w=(c,e)=>ne(c,ae(e));var U=(c,e)=>{var t={};for(var s in c)q.call(c,s)&&e.indexOf(s)<0&&(t[s]=c[s]);if(c!=null&&V)for(var s of V(c))e.indexOf(s)<0&&B.call(c,s)&&(t[s]=c[s]);return t};var m=(c,e,t)=>(z(c,typeof e!="symbol"?e+"":e,t),t);var p=(c,e,t)=>new Promise((s,r)=>{var a=n=>{try{o(t.next(n))}catch(d){r(d)}},i=n=>{try{o(t.throw(n))}catch(d){r(d)}},o=n=>n.done?s(n.value):Promise.resolve(n.value).then(a,i);o((t=t.apply(c,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const re=require("js-base64"),oe=require("axios"),y=require("@glodon-aiot/apis"),ce=require("socket.io-client"),J=require("uuid"),Q=require("dayjs"),x=class x{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!x.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!x.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!x.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!x.debug||console.warn(this.prefix,...e)}};m(x,"debug",!1);let S=x;const de=new S("[Config] ");var X=(c=>(c.dev="https://aiot-dev.glodon.com/api/cvforcepd",c.test="https://aiot-dev.glodon.com/api/cvforce",c.prod="https://copilot.glodon.com/api/cvforce",c.local="http://localhost:3000/api/cvforcepd",c))(X||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},mcp:void 0,loadRelatedQuesions:!0,stream:!1};function N(c){var e,t;S.debug=(c==null?void 0:c.debug)||!1,exports.configuration=w(g(g({},exports.configuration),c),{apiRoot:(c==null?void 0:c.apiRoot)||exports.configuration.apiRoot||(c!=null&&c.env?X[c.env||"prod"]:exports.configuration.apiRoot),plugins:(t=(e=c==null?void 0:c.plugins)!=null?e:exports.configuration.plugins)!=null?t:{}}),S.debug&&de.log("updated",exports.configuration)}const P=c=>JSON.parse(re.decode(c.split(".")[1])),he=c=>{const e=P(c).exp;return new Date().valueOf()/1e3>=e},le=c=>c==null?void 0:c.replace(/[\r\n]+/gm,""),fe=c=>c.replace(/\\|\\/g,""),pe=(c,e,t,s)=>{if(c!==!0)return null;const r=(e==null?void 0:e.includeUserQuestion)===!0,i=(e==null?void 0:e.includeAiAnswer)===!0||!r,o=[];return r&&o.push(`问题:${s}`),i&&o.push(`回答:${t}`),o.join(`
|
|
2
|
-
`)};function Z(c,e,t){const s=d=>{var f;return e&&(he(e)&&t(403,"aiotToken is timeout"),d.headers=(f=d.headers)!=null?f:{},d.headers=w(g({},d.headers),{Authorization:e?`Bearer ${e}`:""})),d};function r(d,f=!0){const l=`${c}${d}`,u=oe.create({baseURL:l});return f&&u.interceptors.request.use(s),u}const a=(d,f)=>{d===401&&t(d,"aiotToken is invalid")},i=(d,f)=>{d!==10001&&d!==10215&&t(d,f)},o=r("/data/v1");return new y.CVForceApi(o,{onHttpStatusError:a,onAppStatusError:i})}var L=(c=>(c[c.Normal=0]="Normal",c[c.Debug=1]="Debug",c))(L||{});const M=new S("[EventBus] ");class ee{constructor(e=!1){m(this,"eventListenerMap",{});e&&M.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),M.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(r=>{if(typeof r=="function"&&t===r)return!0;if(r=r,r.fn===t)return!0});s<0?M.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),M.log(`remove event ${e} listener`))}else M.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){M.log(`event ${e} listeners is empty`);return}const s=[];for(let r=0;r<this.eventListenerMap[e].length;r++){const a=this.eventListenerMap[e][r];typeof a=="function"?a(t):s.push(a)}s.forEach(r=>{r&&(r.fn(t),this.off(e,r.fn))}),M.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const Y=100,b=new S("[Session] ");var T=(c=>(c.DataRequestFailed="data request error",c.SocketConnectionFailed="socket error",c.IdUndefined="session id is not defined",c.SendingEmptyContent="failed at sending empty content",c.Frozen="session is frozen",c.UserModeError="failed at setting socket user mode",c.Inactive="session is inactive",c))(T||{});class D{constructor(e,t="",s,r,a,i){m(this,"_id");m(this,"_frozen",!1);m(this,"inactivating",!1);m(this,"_ready",!1);m(this,"event",new ee);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=r,this.client=i||null,this._applicationId=P(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),a&&(this._application=a),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var o;if(t)this._id=t,this.event.emit("data:loading"),s?(this.data=s,r||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(n=>p(this,null,function*(){this.data=n,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(n=>p(this,null,function*(){this.data=n,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 n=(s==null?void 0:s.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:n}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:n,netOpen:s==null?void 0:s.netOpen,knowledgeIdList:(o=s==null?void 0:s.knowledges)==null?void 0:o.map(d=>d.id),applicationId:this._applicationId}).then(d=>p(this,null,function*(){var f;this._id=d.id,this.data=w(g({},d),{knowledges:s==null?void 0:s.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id);try{yield(()=>p(this,null,function*(){if(s!=null&&s.knowledges)return this.setKnowledges((s==null?void 0:s.knowledges)||void 0)}))()}catch(l){b.error(l)}yield(()=>{if(s!=null&&s.promptVariables){const l=this._promptVariables.map(u=>{var _,h;const v=((h=(_=s.promptVariables)==null?void 0:_.find(I=>I.key===u.key&&I.type===u.type))==null?void 0:h.value)||"";return w(g({},u),{value:v})}).sort((u,v)=>u.key.localeCompare(v.key));return this.setPromptVariables(l||[])}else return})(),this.event.emit("data:created",this.data),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),((f=this.application)==null?void 0:f.type)!==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");if((e||[]).some(r=>Array.isArray(r.fileIds)&&r.fileIds.length===0))throw Error("fileIds cannot be an empty array");if((e||[]).reduce((r,a)=>{var o,n;const i=(n=(o=a.fileIds)==null?void 0:o.length)!=null?n:0;return r+(i>0?i:1)},0)>Y)throw Error(`knowledges and fileIds total count cannot exceed ${Y}`);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=e==null?void 0:e.map(a=>a.type?a:w(g({},a),{type:"instruction"})),s=this._promptVariables.map(a=>{var o;const i=((o=t==null?void 0:t.find(n=>n.key===a.key&&n.type===a.type))==null?void 0:o.value)||a.value;return w(g({},a),{value:i})}).sort((a,i)=>a.key.localeCompare(i.key));if(!(yield Promise.all(s.filter(a=>!(a.type===y.PromptVariableType.User&&a.key==="query")&&!(a.type===y.PromptVariableType.System&&a.key==="datetime")).map(a=>{if(!this.data)throw Error("session data is not loaded");if(!(!a.id||!a.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,a.id,{value:a.value})})).then(()=>!0).catch(a=>!1)))return!1;if(!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,r;if(b.log("setNetOpen:",e),b.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(((r=this._application)==null?void 0:r.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,b.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return Z(exports.configuration.apiRoot,this.token,(e,t)=>{const s=new Error("data request error",{cause:{status:e,message:t}});b.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,r;const t={pageSize:this._loadingMessagesSize};if(this._id){e=g(g({},t),e),this.event.emit("history:loading"),b.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),b.log("history:moreloading",e)),this._loadingMessages=!0;const a=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),i=a.map((n,d)=>{var u,v;let f=[],l;return typeof((u=n.agentHistoryList)==null?void 0:u.agentList)=="string"&&(f=JSON.parse(n.agentHistoryList.agentList).reduce((h,I)=>(h[I.data.step-1]||(h[I.data.step-1]=[]),h[I.data.step-1].push(I),h),[])),d===a.length-1&&(l=(v=this.data)==null?void 0:v.lastRelatedQuestion),w(g({},n),{actions:f,relatedQuesion:l,fromHistory:!0})});if(!e.endTime&&!e.startTime){const n=this.messages[this.messages.length-1];n&&!n.relatedQuesion&&(n.relatedQuesion=(s=this.data)==null?void 0:s.lastRelatedQuestion),this.messages=[...i,...this.messages]}else if(e.endTime&&!e.startTime){const n=this.messages.findIndex(d=>d.ts===e.endTime);this.messages.splice(0,n+1),this.messages=[...i,...this.messages]}else if(!e.endTime&&e.startTime){const n=this.messages.findLastIndex(d=>d.ts===e.endTime);this.messages.splice(n,this.messages.length-n-1),this.messages=[...this.messages,...i]}else{const n=this.messages.findIndex(f=>f.ts===e.endTime),d=this.messages.findLastIndex(f=>f.ts===e.endTime);this.messages.splice(n,d-n+1,...i)}const o=this.messages[this.messages.length-1];return o&&!o.relatedQuesion&&(o.relatedQuesion=(r=this.data)==null?void 0:r.lastRelatedQuestion),this.event.emit("history:moreloaded",i),b.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,i}else{const a=new Error("session id is not defined");return b.error(a),this.event.emit("error",a),!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}),b.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),b.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),b.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 b.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 _;try{this.validateConfigs()}catch(h){console.error(h)}const{stream:r=exports.configuration.stream,referenceFirst:a=!1}=t,i=e.uuid||J.v4(),o=((_=e.text)==null?void 0:_.trim())||"",n=e.files||[],d=e.fileIds,f=e.imageContent;if(!o&&!n.length&&!(d!=null&&d.length)){const h=new Error("failed at sending empty content");return b.error(h),this.event.emit("error",h),!1}if(!this._id){const h=new Error("session id is not defined");return b.error(h),this.event.emit("error",h),!1}if(this.frozen){const h=new Error("session is frozen");return b.error(h),this.event.emit("error",h),!1}this.frozen=!0,this._stopAnswer=!1;const l={sessionId:this.id,role:2,content:o,messageId:i,reference:[],searchReference:[],messageTime:"",files:n,imageContent:f},u={content:o,stream:r,requestId:i,fileIds:d,referenceFirst:a,imageContent:f};this.pushMessage(l),this.event.emit("question:content",o);const v=h=>p(this,null,function*(){if(h.role!==y.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",v),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 A=g(g({},I),h);this.messages[this.messages.length-1]=A,this.event.emit("message:updated",A)}else this.pushMessage(h);this.frozen=!1});return this.addEventListener("answer:finish",v),this.sendQuestion(u,w(g({},t),{stream:r,referenceFirst:a})),l})}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 o,n;if(!e.content||e.isSensitive||e.code!==200)return e;const t=(o=this.application)==null?void 0:o.arrange[0],s=pe(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 r=yield this.cvforceApi.postGeneques({content:s}).catch(d=>null);if(!r){const d=[],f=w(g({},e),{relatedQuesion:d,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:d}),this.event.emit("message:updated",f),f}const a=(n=r.content)==null?void 0:n.split("*").map(le).map(fe).filter(d=>!!d);e.relatedQuesion=a,e.index=-3,e.isLoading=!1;const i=w(g({},e),{relatedQuesion:a,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",i),this.event.emit("message:updated",i),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:a}),i})}fillMessageReference(e){return p(this,null,function*(){try{const t=yield Promise.all(e.reference.map(s=>this.cvforceApi.getKnowledgeIdFileId(s.knowledgeId,s.docId)));e.reference=e.reference.map((s,r)=>g(g({},s),t[r]))}catch(t){console.error("Failed to fill message reference:",t)}return 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 r;t.role!==y.ChatMessageRole.User&&(r=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 a=this.messages[this.messages.length-1],i={content:a.content,fileIds:a.fileIds,requestId:a.messageId,stream:s,oldMessageId:r},o=n=>p(this,null,function*(){if(n.role===y.ChatMessageRole.Robot&&n.index===-1){switch(this._id&&n.content&&n.index&&n.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:n.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:n.content})),yield this.fillMessageReference(n),n.code){case 11915:n.content="请您换个问题问我吧~",n.index=-1,n.isSensitive=!0,n.isLoading=!1,n.sessionId=this._id||"",this.event.emit("message:error",n);break;case 11916:n.content="尊敬的用户您好,让我们换个话题再聊聊吧。",n.index=-1,n.isSensitive=!0,n.isLoading=!1,n.sessionId=this._id||"",this.event.emit("message:error",n);break;case 200:n.index=-1,n.isLoading=!1;break;default:n.content=n.message||"未知错误",n.isLoading=!1,n.index=-1,this.event.emit("message:error",n)}this.getRelatedQuesion(n),this.removeEventListener("message:content",o),this.frozen=!1}});this.addEventListener("message:content",o),this.sendQuestion(i,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:Q(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 r=e.actions[((s=e.actions)==null?void 0:s.length)-1];if(r){const a=r[r.length-1];if(a&&(a.type==="BEFORE_CALL"||a.type==="FUNCTION_CALL")){const{pluginName:i,pluginCode:o,funcCode:n,funcName:d}=a.data;r.push({data:{pluginName:i,pluginCode:o,funcCode:n,funcName:d,step:a.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:r})}}}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}handleStreamAnswer(e,t){var i;if(!e.data)return;const s=e.data.type,r=e.data.payload;t.isReplying=!0;const a=()=>{if(!t.searchingStatus){t.searchingStatus="start";return}if(t.searchingStatus==="start"){t.searchingStatus="end";return}};if(s==="error"&&(t.index=-1),s==="beforeSearch"&&a(),s==="searchOver"&&a(),s==="search"&&t.searchReference.push(r),s==="thinking"){t.thinkingStatus="start";const n=r.choices[0];t.reasoningContent=(t.reasoningContent||"")+((i=n.delta.reasoningContent)!=null?i:"")}if(s==="thinkingOver"){t.thinkingStatus="end";const o=r.thinkingSecs;t.thinkingSecs=o}if(s==="text"){const n=r.choices[0];t.content=(t.content||"")+n.delta.content}if(s==="reference"&&(t.reference=r),s==="updateSession"&&r&&this.data&&(this.data=g(g({},this.data),r),this.event.emit("data:updated",this.data)),s==="result"){const o=r.messageId,n=r.llmModel,d=r.messageTime;t.messageId=o,t.llmModel=n,t.messageTime=d}s==="over"?t.index=-1:(t.code=e.code,t.message=e.message)}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(r=>r.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 R=new S("[AgentSession] ");class ue extends D{constructor(e,t="",s,r,a,i){super(e,t,s,r,a,i)}prepareConnection(){return new Promise(e=>p(this,null,function*(){this.socket&&e(!0);const t={version:"1.0",stream:JSON.stringify(exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?L.Debug:L.Normal},s=new URL(exports.configuration.apiRoot),r=yield ce.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:t,transports:["websocket"]});r.on("connect",()=>{R.log("socket:connect"),this.event.emit("socket:connect"),r.emit("init")}),r.on("disconnect",()=>{R.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),r.on("ready",a=>{if(a.code===200){R.log("ready");const i=exports.configuration.debug?L.Debug:L.Normal;i===L.Debug&&a.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),e(!0)}else{this._ready&&(this._ready=!1);const i=new Error(T.SocketConnectionFailed);R.error("error",i),this.event.emit("error",i),e(!1)}}),r.on("action",(a,i)=>p(this,null,function*(){var _;if(this._stopAnswer||!this.id)return;const{type:o,data:{runnerIsClient:n,pluginCode:d,funcCode:f,parameters:l,requestBody:u}}=a,v=this.messages[this.messages.length-1];if(!v.messageId)v.actions||(v.actions=[]),v.actions[a.data.step-1]||(v.actions[a.data.step-1]=[]),v.actions[a.data.step-1].push(a),this.event.emit("message:action",{messageId:v.messageId,action:a}),this.event.emit("message:updated",v);else{const h={messageId:"",content:"",role:y.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[a]],comment:{isAgree:0},isReplying:!0};this.pushMessage(h),this.event.emit("message:action",{messageId:h.messageId,action:a})}if(this.inactivating){const h=new Error(T.Inactive);R.warn("error",h),this.event.emit("error",h)}else if(o==="FUNCTION_CALL"&&n){R.log(`calling function ${f} of plugin ${d} with argument:
|
|
3
|
-
|
|
1
|
+
"use strict";var fi=Object.defineProperty,pi=Object.defineProperties;var gi=Object.getOwnPropertyDescriptors;var ye=Object.getOwnPropertySymbols;var nt=Object.prototype.hasOwnProperty,rt=Object.prototype.propertyIsEnumerable;var he=(i,e)=>{if(e=Symbol[i])return e;throw Error("Symbol."+i+" is not defined")};var ke=(i,e,t)=>e in i?fi(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,v=(i,e)=>{for(var t in e||(e={}))nt.call(e,t)&&ke(i,t,e[t]);if(ye)for(var t of ye(e))rt.call(e,t)&&ke(i,t,e[t]);return i},I=(i,e)=>pi(i,gi(e));var at=(i,e)=>{var t={};for(var s in i)nt.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&ye)for(var s of ye(i))e.indexOf(s)<0&&rt.call(i,s)&&(t[s]=i[s]);return t};var y=(i,e,t)=>(ke(i,typeof e!="symbol"?e+"":e,t),t);var u=(i,e,t)=>new Promise((s,o)=>{var r=a=>{try{c(t.next(a))}catch(d){o(d)}},n=a=>{try{c(t.throw(a))}catch(d){o(d)}},c=a=>a.done?s(a.value):Promise.resolve(a.value).then(r,n);c((t=t.apply(i,e)).next())}),K=function(i,e){this[0]=i,this[1]=e},se=(i,e,t)=>{var s=(n,c,a,d)=>{try{var l=t[n](c),h=(c=l.value)instanceof K,f=l.done;Promise.resolve(h?c[0]:c).then(g=>h?s(n==="return"?n:"next",c[1]?{done:g.done,value:g.value}:g,a,d):a({value:g,done:f})).catch(g=>s("throw",g,a,d))}catch(g){d(g)}},o=n=>r[n]=c=>new Promise((a,d)=>s(n,c,a,d)),r={};return t=t.apply(i,e),r[Symbol.asyncIterator]=()=>r,o("next"),o("throw"),o("return"),r},ot=i=>{var e=i[he("asyncIterator")],t=!1,s,o={};return e==null?(e=i[he("iterator")](),s=r=>o[r]=n=>e[r](n)):(e=e.call(i),s=r=>o[r]=n=>{if(t){if(t=!1,r==="throw")throw n;return n}return t=!0,{done:!1,value:new K(new Promise(c=>{var a=e[r](n);if(!(a instanceof Object))throw TypeError("Object expected");c(a)}),1)}}),o[he("iterator")]=()=>o,s("next"),"throw"in e?s("throw"):o.throw=r=>{throw r},"return"in e&&s("return"),o},Y=(i,e,t)=>(e=i[he("asyncIterator")])?e.call(i):(i=i[he("iterator")](),e={},t=(s,o)=>(o=i[s])&&(e[s]=r=>new Promise((n,c,a)=>(r=o.call(i,r),a=r.done,Promise.resolve(r.value).then(d=>n({value:d,done:a}),c)))),t("next"),t("return"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("uuid"),mi=require("js-base64"),yi=require("axios"),A=require("@glodon-aiot/apis"),wi=require("socket.io-client"),Ue=require("dayjs"),ee=class ee{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!ee.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!ee.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!ee.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!ee.debug||console.warn(this.prefix,...e)}};y(ee,"debug",!1);let $=ee;const ze=["list_directory","read_file","stat_file","search_files","search_text","apply_patch","write_file","upload_file","download_file"],ue="buildin_tools",je={dev:ue,test:ue,prod:ue,local:ue},At=je,oe="run_python",St=je,Et=2e4,vi=12e4,Tt=16,Q="current-workspace",Lt=1024,pe=1024*1024,Ct=50,_e=Object.freeze({maxReadBytes:1*pe,maxWriteBytes:5*pe,maxSearchResults:200,maxConcurrentRequests:4,maxTransferBytes:Ct*pe,toolTimeoutMs:3e4,searchTimeoutMs:6e4,transferTimeoutMs:10*6e4,approvalTimeoutMs:5*6e4}),Rt=200,kt=1e3,Mt=8,We=16,xt=2e3,Ft=1*pe,be=500,Ot=3,Ve=8*Lt,Nt=Object.freeze(["glodon.com"]),Pt=Object.freeze([".git","node_modules",".svn",".idea",".vscode"]),Dt=Object.freeze(["~$*",".~lock*","*.tmp"]),_i=["apply_patch","write_file","upload_file","download_file"],Bt=["search_files","search_text"],qt=["upload_file","download_file"];var w=(i=>(i[i.Ok=0]="Ok",i[i.BadRequest=400]="BadRequest",i[i.Forbidden=403]="Forbidden",i[i.NotFound=404]="NotFound",i[i.Timeout=408]="Timeout",i[i.Conflict=409]="Conflict",i[i.TooLarge=413]="TooLarge",i[i.TooManyRequests=429]="TooManyRequests",i[i.Cancelled=499]="Cancelled",i[i.Internal=500]="Internal",i[i.NotImplemented=501]="NotImplemented",i))(w||{});class p extends Error{constructor(t,s,o){super(s);y(this,"code");y(this,"data");this.name="ToolError",this.code=t,this.data=o}}const bi="尚未授权工作文件夹,请先在助手中选择或恢复访问工作文件夹。";function Ye(){return new p(403,bi,{reason:"workspace_not_granted"})}function N(){return new p(499,"操作已取消。")}function M(i){if(i!=null&&i.aborted)throw N()}function Le(i){if(i instanceof p)return i;switch(i&&typeof i=="object"&&"name"in i?String(i.name):""){case"NotFoundError":return new p(404,"文件或目录不存在。");case"TypeMismatchError":return new p(400,"路径类型不匹配:目标是目录而不是文件,或路径中的某一段不是目录。");case"NotAllowedError":case"SecurityError":return Ye();case"AbortError":return N();case"NoModificationAllowedError":case"InvalidModificationError":case"InvalidStateError":return new p(403,"文件当前不可写,可能正被其他程序占用或为只读。");case"QuotaExceededError":return new p(413,"磁盘空间不足或超出写入配额。");default:return new p(500,"本地文件操作失败,请稍后重试。")}}const z="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",B={type:"string",enum:[Q],description:`工作区 ID。省略时按 ${Q} 处理,传其他值会被拒绝。`},j=i=>({type:"string",description:`${i}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),Me={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},Ge={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${z}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:B,path:j('要列出的目录,省略或传 "." 表示工作区根目录。'),offset:{type:"integer",minimum:0,description:"分页起始位置,默认 0。"},limit:{type:"integer",minimum:1,maximum:1e3,description:"每页条数,默认 200。"}}}},read_file:{functionCode:"read_file",name:"读取本地文件",description:`${z}按行读取文本文件,单次最多返回 1 MiB,超出部分会被截断(truncated: true)。返回内容的 hash 可用于后续修改。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:B,path:j("要读取的文件。"),startLine:{type:"integer",minimum:1,description:"起始行(从 1 开始,含)。"},endLine:{type:"integer",minimum:1,description:"结束行(含)。"},maxBytes:{type:"integer",minimum:1,description:"返回内容的最大字节数,不超过 1 MiB。"},encoding:{type:"string",enum:["utf-8","gbk","gb18030"],description:"文本编码,默认 utf-8。"}}}},stat_file:{functionCode:"stat_file",name:"查看本地文件信息",description:`${z}返回文件或目录的类型、大小、修改时间,可选返回 hash。不返回文件内容。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:B,path:j("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${z}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:B,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:j("搜索起点目录,默认工作区根目录。"),maxDepth:{type:"integer",minimum:1,maximum:16,description:"最大目录深度,默认 8。"},maxResults:{type:"integer",minimum:1,maximum:200,description:"最多返回条数,默认 200。"}}}},search_text:{functionCode:"search_text",name:"搜索本地文本",description:`${z}在指定文件或目录(递归)中搜索普通文本(不支持正则),返回所在文件、行号与该行内容。必须指定 path,不能搜索整个文件夹。`,parameters:{type:"object",required:["grantId","path","query"],properties:{grantId:B,path:j("搜索范围,可以是文件或目录。"),query:{type:"string",minLength:1,description:"要查找的文本。"},caseSensitive:{type:"boolean",description:"是否区分大小写,默认否。"},isRegex:{type:"boolean",description:"暂不支持正则,传 true 会返回 501。"},glob:{type:"string",description:"只搜索匹配该 glob 的文件,如 *.md。"},maxResults:{type:"integer",minimum:1,maximum:200,description:"最多返回条数,默认 200。"},contextLines:{type:"integer",minimum:0,maximum:3,description:"附带的上下文行数,默认 0。"}}}},apply_patch:{functionCode:"apply_patch",name:"修改本地文件",description:`${z}以查找替换的方式修改 UTF-8 文本文件。每条修改的 oldText 必须在文件中唯一出现(或设置 replaceAll)。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","expectedHash","edits"],properties:{grantId:B,path:j("要修改的文件。"),expectedHash:Me,edits:{type:"array",minItems:1,description:"按顺序应用的修改。",items:{type:"object",required:["oldText","newText"],properties:{oldText:{type:"string",minLength:1,description:"要替换的原文,需包含足够上下文以保证唯一。"},newText:{type:"string",description:"替换后的文本。"},replaceAll:{type:"boolean",description:"是否替换所有出现位置,默认否。"}}}}}}},write_file:{functionCode:"write_file",name:"写入本地文件",description:`${z}新建文件,或整体覆盖已有文件(覆盖时必须提供 expectedHash)。修改已有文件优先使用 apply_patch。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","content"],properties:{grantId:B,path:j("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:Me,createDirectories:{type:"boolean",description:"父目录不存在时是否自动创建,默认否。"}}}},upload_file:{functionCode:"upload_file",name:"上传本地文件",description:`${z}把本地文件夹中的文件上传到平台文件服务,返回 fileId、name、size 和 url。url 是文件访问地址,可直接用于后续推理或对话。下载回本地文件夹时使用 download_file,source.type 为 platformFile。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:B,path:j("要上传的文件。"),target:{type:"string",description:"上传目标,目前只支持 session(默认),其他值返回 501。"},mimeHint:{type:"string",description:"可选的 MIME 类型。"}}}},download_file:{functionCode:"download_file",name:"下载到本地文件夹",description:`${z}把会话文件、平台文件或 https 地址保存到本地文件夹。source.type 为 url 时必须同时填写 source.url(完整地址),为 sessionFile 或 platformFile 时必须同时填写 source.fileId。不要只传 type。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","destPath","source"],properties:{grantId:B,destPath:j("保存位置(文件路径)。"),source:{type:"object",required:["type"],description:"下载来源。type 为 url 时必填 url;type 为 sessionFile 或 platformFile 时必填 fileId。",properties:{type:{type:"string",enum:["sessionFile","platformFile","url"],description:"sessionFile:当前会话文件;platformFile:平台文件(upload_file 返回的 fileId);url:https 地址。"},fileId:{type:"string",description:"type 为 sessionFile 或 platformFile 时必填,不能只传 type。"},url:{type:"string",description:"type 为 url 时必填,填写完整 https 地址。不能只传 type。默认只允许 glodon.com 及其子域。"}}},overwrite:{type:"boolean",description:"目标已存在时是否覆盖,默认否。"},expectedHash:Me}}}},Ii="在已绑定的本地工程目录中运行已有 .py,路径相对该目录。不要用于云端工作区,不要传 shell 或代码,只能传 path 和 args。",Ht={functionCode:oe,name:"运行本地 Python 脚本",description:`${Ii}每次运行需用户单独确认,文件读写授权不能代替。确认后脚本可直接读写该目录并使用标准库,改动立即落盘。不能联网,不能在运行中安装包,也不能访问该目录以外的文件。第三方包写在工程根目录 sandbox-requirements.txt。结果打印到标准输出。code 为 0 只表示已结束,成功看 data.exitCode,超时看 data.timedOut。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:B,path:{type:"string",description:"要运行的脚本。必须是已存在、以 .py 结尾的相对路径,以 / 分隔,不能包含 .. 、盘符或绝对路径。"},args:{type:"array",maxItems:16,description:"传给脚本的参数,最多 16 个。每个参数单独一项,不能含空格、引号或 shell 语法,只能包含字母、数字、下划线以及 . / : @ = + - , 。",items:{type:"string",description:"一个脚本参数。"}},timeoutMs:{type:"integer",minimum:1e3,maximum:12e4,description:"超时毫秒数。默认 20000,最大 120000。到时脚本会被终止。"}}}},Ai=I(v({},Ge),{run_python:Ht}),Si="路径必须是工作区内的相对路径,不能包含 ..、绝对路径或盘符。";function we(){return new p(w.Forbidden,Si,{reason:"path_outside_workspace"})}function $t(i){if(i!==Q)throw new p(w.Forbidden,`未知的工作区 grantId,当前仅支持 ${Q}。`,{reason:"path_outside_workspace"})}function U(i,{allowRoot:e=!1,field:t="path"}={}){if(i==null){if(e)return"";throw new p(w.BadRequest,`缺少参数 ${t}。`)}if(typeof i!="string")throw new p(w.BadRequest,`参数 ${t} 必须是字符串。`);if(i.includes("\0")||/%(2e|2f|5c|00)/i.test(i))throw we();const s=i.normalize("NFC").replace(/\\/g,"/").trim();if(s.startsWith("/")||/^[a-zA-Z]:/.test(s))throw we();const o=[];for(const n of s.split("/"))if(!(n===""||n===".")){if(n==="..")throw we();o.push(n)}const r=o.join("/");if(!r&&!e)throw new p(w.BadRequest,`参数 ${t} 不能指向工作区根目录。`);return r}function G(i){return i?i.split("/"):[]}function Ei(i){const e=i.lastIndexOf("/");return e<0?"":i.slice(0,e)}function Ut(i,e){return i?`${i}/${e}`:e}const ct=new Map;function Ti(i){return/[\\^$.|+()[\]{}]/.test(i)?`\\${i}`:i}function Li(i,e=!1){const t=`${e?"s":"i"}:${i}`,s=ct.get(t);if(s)return s;let o="";for(let n=0;n<i.length;n++){const c=i[n];c==="*"?i[n+1]==="*"?(n++,i[n+1]==="/"?(n++,o+="(?:.*/)?"):o+=".*"):o+="[^/]*":c==="?"?o+="[^/]":o+=Ti(c)}const r=new RegExp(`^${o}$`,e?"":"i");return ct.set(t,r),r}function Ae(i,e,t=!1){return Li(i,t).test(e)}function Qe(i){const e=i.lastIndexOf("/");return e<0?i:i.slice(e+1)}const zt=Object.freeze([{id:"env-files",pattern:".env*",reason:"环境变量文件可能包含密钥",source:"sdk-baseline"},{id:"pem",pattern:"*.pem",reason:"证书或密钥文件",source:"sdk-baseline"},{id:"key",pattern:"*.key",reason:"密钥文件",source:"sdk-baseline"},{id:"p12",pattern:"*.p12",reason:"证书文件",source:"sdk-baseline"},{id:"pfx",pattern:"*.pfx",reason:"证书文件",source:"sdk-baseline"},{id:"id-rsa",pattern:"id_rsa*",reason:"SSH 私钥",source:"sdk-baseline"},{id:"id-ed25519",pattern:"id_ed25519*",reason:"SSH 私钥",source:"sdk-baseline"},{id:"id-ecdsa",pattern:"id_ecdsa*",reason:"SSH 私钥",source:"sdk-baseline"},{id:"credentials",pattern:".credentials",reason:"凭据文件",source:"sdk-baseline"},{id:"npmrc",pattern:".npmrc",reason:"可能包含 registry token",source:"sdk-baseline"},{id:"pypirc",pattern:".pypirc",reason:"可能包含仓库凭据",source:"sdk-baseline"},{id:"aws-credentials",pattern:"**/.aws/credentials",match:"path",reason:"云服务凭据",source:"sdk-baseline"},{id:"ssh-dir",pattern:"**/.ssh/**",match:"path",reason:"SSH 配置与密钥",source:"sdk-baseline"}]),Ci="该文件被列为敏感文件,不允许访问";class jt{constructor(e=[]){y(this,"rules");const t=e.filter(s=>s&&typeof s.pattern=="string"&&s.pattern).map(s=>I(v({},s),{id:String(s.id||s.pattern),source:s.source==="enterprise"?"enterprise":"product"}));this.rules=[...zt,...t]}match(e,t){if(!e)return null;const s=Qe(e);for(const o of this.rules){if(o.operations&&!o.operations.includes(t))continue;const r=o.match==="path"?e:s;if(Ae(o.pattern,r))return o}return null}isSensitive(e){return["read","write","search"].some(t=>this.match(e,t)!==null)}static reasonOf(e){return`${e.reason||Ci},已拒绝访问。`}}function de(i,e,t){const s=i.sensitive.match(e,t);if(s)throw new p(w.Forbidden,jt.reasonOf(s),{reason:"sensitive_file",ruleId:s.id})}function Ie(i,e){return u(this,null,function*(){try{return yield i.stat(e)}catch(t){if(Le(t).code===w.NotFound)return null;throw t}})}function Xe(i,e){return u(this,null,function*(){const t=yield i.stat(e);if(t.kind!=="file")throw new p(w.BadRequest,"目标是目录,不是文件。");return t})}function ce(i){return u(this,null,function*(){const e=yield crypto.subtle.digest("SHA-256",i);return`sha256:${Array.from(new Uint8Array(e)).map(s=>s.toString(16).padStart(2,"0")).join("")}`})}function te(i){return u(this,null,function*(){return new Uint8Array(yield i.arrayBuffer())})}function Wt(i){const e=Math.min(i.byteLength,Ve);for(let t=0;t<e;t++)if(i[t]===0)return!0;return!1}function Ri(i){return u(this,null,function*(){return Wt(yield te(i.slice(0,Ve)))})}function Vt(i){return i[0]===239&&i[1]===187&&i[2]===191}function ki(i){try{return new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch(e){throw new p(w.BadRequest,"文件不是 UTF-8 编码,暂不支持修改。")}}function Mi(i){return new TextEncoder().encode(i).byteLength}function Yt(){return new Promise(i=>setTimeout(i,0))}function xi(i){return i>=1024*1024?`${(i/1024/1024).toFixed(1)} MB`:i>=1024?`${(i/1024).toFixed(1)} KB`:`${i} B`}function ie(i,e="文件"){return new p(w.TooLarge,`${e}超过大小上限 ${xi(i)}。`)}const Fi=new TextEncoder;function X(i,e,t,s){return i===void 0?e:Math.min(Math.max(Math.trunc(i),t),s)}const Oi=(i,e)=>u(exports,null,function*(){const t=U(i.path,{allowRoot:!0});if((yield e.adapter.stat(t)).kind!=="directory")throw new p(w.BadRequest,"目标是文件,不是目录。");const o=X(i.offset,0,0,Number.MAX_SAFE_INTEGER),r=X(i.limit,Rt,1,kt),n=yield e.adapter.listEntries(t,e.signal);n.sort((a,d)=>a.kind!==d.kind?a.kind==="directory"?-1:1:a.name<d.name?-1:a.name>d.name?1:0);const c=n.slice(o,o+r).map(a=>{const d=Ut(t,a.name),l={name:a.name,path:d,kind:a.kind};return a.kind==="file"&&(l.size=a.size,l.lastModified=a.lastModified,e.sensitive.isSensitive(d)&&(l.sensitive=!0)),l});return{data:{path:t,entries:c,total:n.length,hasMore:o+c.length<n.length}}});function Ni(i,e,t){return se(this,null,function*(){var c;const s=new TextDecoder(e),o=i.stream().getReader();let r="",n=!1;try{for(;;){M(t);const{done:a,value:d}=yield new K(o.read());r+=a?s.decode():s.decode(d,{stream:!0});const l=r.split(`
|
|
2
|
+
`);r=(c=l.pop())!=null?c:"";for(const h of l)n=!0,yield h;if(a)break}}finally{o.releaseLock()}(r||!n)&&(yield r)})}const Pi=(i,e)=>u(exports,null,function*(){var E,C;const t=U(i.path);de(e,t,"read");const s=yield Xe(e.adapter,t),o=yield e.adapter.readFile(t),r=(E=s.size)!=null?E:o.size;if(yield Ri(o))throw new p(w.BadRequest,"这是二进制文件,不能按文本读取。可以使用 stat_file 查看信息,或使用 upload_file 上传到会话。");const n=yield te(o.slice(0,3)),c=Vt(n)?"utf-8":(C=i.encoding)!=null?C:"utf-8",a=X(i.startLine,1,1,Number.MAX_SAFE_INTEGER),d=i.endLine===void 0?Number.MAX_SAFE_INTEGER:Math.max(Math.trunc(i.endLine),a),l=X(i.maxBytes,e.limits.maxReadBytes,1,e.limits.maxReadBytes),h=r<=e.limits.maxTransferBytes,f=[];let g=0,_=0,m=a-1,b=!1,T=!1;try{for(var le=Y(Ni(o,c,e.signal)),x,L,F;x=!(L=yield le.next()).done;x=!1){const R=L.value;_++;const V=R.endsWith("\r")?R.slice(0,-1):R;if(V!==R&&(T=!0),_<a||_>d||b){if(!h&&(b||_>d))break;continue}const ge=Mi(V)+(f.length?1:0);if(g+ge>l){if(b=!0,f.length||(f.push(Di(V,l)),m=_),!h)break;continue}f.push(V),g+=ge,m=_}}catch(L){F=[L]}finally{try{x&&(L=le.return)&&(yield L.call(le))}finally{if(F)throw F[0]}}const S={path:t,content:f.join(`
|
|
3
|
+
`),startLine:a,endLine:Math.max(m,a-1),size:r,encoding:c,lineEnding:T?"crlf":"lf"};return h&&(S.totalLines=_),r<=e.limits.maxWriteBytes&&(S.hash=yield ce(yield te(o))),{data:S,truncated:b||void 0}});function Di(i,e){const t=Fi.encode(i);return t.byteLength<=e?i:new TextDecoder().decode(t.slice(0,e)).replace(/\uFFFD$/,"")}const Bi=(i,e)=>u(exports,null,function*(){var r;const t=U(i.path),s=yield e.adapter.stat(t),o={path:t,kind:s.kind,sensitive:s.kind==="file"&&e.sensitive.isSensitive(t)};return s.kind==="file"&&(o.size=s.size,o.lastModified=s.lastModified,i.includeHash&&((r=s.size)!=null?r:0)<=e.limits.maxTransferBytes&&(o.hash=yield ce(yield te(yield e.adapter.readFile(t))))),{data:o}});function qi(i){return Dt.some(e=>Ae(e,i))}function Gt(i,e,t){return se(this,null,function*(){const s=[{path:e,depth:0}];let o=0;for(;s.length;){const r=s.shift();M(i.signal),++o%20===0&&(yield new K(Yt()));const n=yield new K(i.adapter.listEntries(r.path,i.signal));n.sort((c,a)=>c.name<a.name?-1:c.name>a.name?1:0);for(const c of n){const a=Ut(r.path,c.name);if(c.kind==="directory"){r.depth+1<t&&!Pt.includes(c.name)&&s.push({path:a,depth:r.depth+1});continue}qi(c.name)||i.sensitive.match(a,"search")||(yield{path:a,relativePath:e?a.slice(e.length+1):a,name:c.name,size:c.size,lastModified:c.lastModified})}}})}function Qt(i,e){return i.includes("/")?Ae(i,e.relativePath):Ae(i,e.name)}const Hi=(i,e)=>u(exports,null,function*(){const t=U(i.path,{allowRoot:!0});if(!i.pattern.trim())throw new p(w.BadRequest,"参数 pattern 不能为空。");const s=i.pattern.replace(/\\/g,"/").replace(/^\.\//,"");if((yield e.adapter.stat(t)).kind!=="directory")throw new p(w.BadRequest,"参数 path 必须是目录。");const r=X(i.maxDepth,Mt,1,We),n=X(i.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),c=[];let a=!1;try{for(var d=Y(Gt(e,t,r)),l,h,f;l=!(h=yield d.next()).done;l=!1){const g=h.value;if(Qt(s,g)){if(c.length>=n){a=!0;break}c.push({path:g.path,size:g.size,lastModified:g.lastModified})}}}catch(h){f=[h]}finally{try{l&&(h=d.return)&&(yield h.call(d))}finally{if(f)throw f[0]}}return{data:{matches:c},truncated:a||void 0}});function xe(i,e){if(i.length<=be)return i;const t=Math.max(0,Math.min(e-100,i.length-be));return i.slice(t,t+be)}const $i=(i,e)=>u(exports,null,function*(){var f;const t=U(i.path,{allowRoot:!0});if(!t&&!e.allowWorkspaceWideTextSearch)throw new p(w.BadRequest,"不支持在整个工作区内搜索文本,请把 path 缩小到具体的子目录或文件。");if(i.isRegex)throw new p(w.NotImplemented,"暂不支持正则搜索,请使用普通文本搜索。");if(!i.query)throw new p(w.BadRequest,"参数 query 不能为空。");const s=i.caseSensitive===!0,o=s?i.query:i.query.toLowerCase(),r=X(i.contextLines,0,0,Ot),n=X(i.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),c=yield e.adapter.stat(t);let a;c.kind==="file"?(de(e,t,"search"),a=function(){return se(this,null,function*(){yield{path:t,relativePath:t,name:c.name,size:c.size}})}()):a=Gt(e,t,We);const d=[];let l=0,h=!1;e:try{for(var g=Y(a),_,m,b;_=!(m=yield g.next()).done;_=!1){const T=m.value;if(i.glob&&!Qt(i.glob,T)||((f=T.size)!=null?f:0)>Ft)continue;if(l>=xt){h=!0;break}l++,l%20===0&&(yield Yt()),M(e.signal);const S=yield te(yield e.adapter.readFile(T.path));if(Wt(S))continue;const E=new TextDecoder("utf-8").decode(S).split(/\r?\n/);for(let C=0;C<E.length;C++){const x=(s?E[C]:E[C].toLowerCase()).indexOf(o);if(x<0)continue;if(d.length>=n){h=!0;break e}const L={path:T.path,line:C+1,column:x+1,text:xe(E[C],x)};r&&(L.before=E.slice(Math.max(0,C-r),C).map(F=>xe(F,0)),L.after=E.slice(C+1,C+1+r).map(F=>xe(F,0))),d.push(L)}}}catch(m){b=[m]}finally{try{_&&(m=g.return)&&(yield m.call(g))}finally{if(b)throw b[0]}}return{data:{matches:d,filesScanned:l},truncated:h||void 0}}),Ui=/^[a-z0-9-]+(\.[a-z0-9-]+)+$/;function zi(i){if(typeof i!="string")return null;const e=i.trim().toLowerCase().replace(/^\*?\./,"").replace(/\.$/,"");return!Ui.test(e)||Xt(e)?null:e}function Xt(i){return i.startsWith("[")||i.includes(":")?!0:/^[0-9.]+$/.test(i)||/^0x[0-9a-f.]+$/i.test(i)}function Ke(i=[]){const e=new Set(Nt);for(const t of i){const s=zi(t);s&&e.add(s)}return Array.from(e)}function ji(i,e){return Pe(i,Ke(e))}function Pe(i,e){let t;try{t=new URL(i)}catch(o){return!1}if(t.protocol!=="https:"||t.username||t.password)return!1;const s=t.hostname.toLowerCase().replace(/\.$/,"");return!s||Xt(s)||s==="localhost"||s.endsWith(".localhost")?!1:e.some(o=>s===o||s.endsWith(`.${o}`))}function dt(){return new p(w.Forbidden,"下载地址不在允许范围内:只允许 https 协议且域名在白名单中的地址。",{reason:"url_not_allowed"})}const Wi=(i,e)=>u(exports,null,function*(){var h,f;const t=U(i.path);if(((h=i.target)!=null?h:"session")!=="session")throw new p(w.NotImplemented,"目前只支持上传到当前会话(target: session)。");de(e,t,"read");const o=yield Xe(e.adapter,t),r=(f=o.size)!=null?f:0;if(r>e.limits.maxTransferBytes)throw ie(e.limits.maxTransferBytes);const n=Qe(t);yield e.requestApproval(t,{type:"upload",name:n,size:r,target:"session"}),e.progress({stage:"reading",loaded:0,total:r,path:t});const c=yield e.adapter.readFile(t);M(e.signal);const a=new File([c],n,{type:i.mimeHint||c.type||"application/octet-stream",lastModified:o.lastModified}),{fileId:d,url:l}=yield e.transfer.upload(a,e.context,({loaded:g,total:_})=>e.progress({stage:"uploading",loaded:g,total:_,path:t}));return M(e.signal),e.progress({stage:"done",loaded:r,total:r,path:t}),{data:{fileId:d,name:n,size:r,url:l}}});function Vi(i){const e=i;if(!e||typeof e!="object")throw new p(w.BadRequest,"缺少参数 source。");if(e.type==="sessionFile"||e.type==="platformFile"){if(typeof e.fileId!="string"||!e.fileId)throw new p(w.BadRequest,"source.fileId 必须是非空字符串。");return{type:e.type,fileId:e.fileId}}if(e.type==="url"){if(typeof e.url!="string"||!e.url)throw new p(w.BadRequest,"source.url 必须是非空字符串。");return{type:"url",url:e.url}}throw new p(w.BadRequest,"source.type 必须是 sessionFile、platformFile 或 url 之一。")}function Yi(i){return i.type==="sessionFile"?"会话文件":i.type==="platformFile"?"平台文件":new URL(i.url).hostname}function Gi(i,e,t,s,o){return se(this,null,function*(){const r=i.getReader();let n=0;try{for(;;){M(e.signal);const{done:c,value:a}=yield new K(r.read());if(c)break;if(n+=a.byteLength,n>e.limits.maxTransferBytes)throw ie(e.limits.maxTransferBytes,"下载内容");o.push(a),e.progress({stage:"downloading",loaded:n,total:s,path:t}),yield a}}finally{r.cancel().catch(()=>{})}})}const Qi=(i,e)=>u(exports,null,function*(){var m,b,T;const t=U(i.destPath,{field:"destPath"}),s=Vi(i.source);if(s.type==="url"&&!Pe(s.url,e.downloadUrlAllowlist))throw dt();de(e,t,"write");const o=yield Ie(e.adapter,t);if((o==null?void 0:o.kind)==="directory")throw new p(w.BadRequest,"目标是目录,不能写入文件。");if(o&&!i.overwrite)throw new p(w.Conflict,"目标文件已存在。如需覆盖,请设置 overwrite: true。");const r=()=>u(exports,null,function*(){if(!o||!i.expectedHash)return;const S=yield ce(yield te(yield e.adapter.readFile(t)));if(S!==i.expectedHash)throw new p(w.Conflict,"expectedHash 与目标文件当前内容不一致。",{currentHash:S})});yield r();const n=s.type==="url"?{url:s.url}:yield e.transfer.resolveDownload(s,e.context);if(n.size!==void 0&&n.size>e.limits.maxTransferBytes)throw ie(e.limits.maxTransferBytes);const c={type:"download",source:{type:s.type,label:Yi(s)},name:(m=n.name)!=null?m:Qe(t),size:n.size,overwrite:!!o};yield e.requestApproval(t,c),yield r();let a;try{a=yield e.fetch(n.url,{headers:n.headers,credentials:"omit",redirect:"follow",signal:e.signal})}catch(S){throw M(e.signal),new p(w.Internal,"下载失败,无法连接到文件地址。")}if(s.type==="url"&&a.url&&!Pe(a.url,e.downloadUrlAllowlist))throw(b=a.body)==null||b.cancel().catch(()=>{}),dt();if(!a.ok||!a.body)throw(T=a.body)==null||T.cancel().catch(()=>{}),new p(a.status===404?w.NotFound:w.Internal,`下载失败(HTTP ${a.status})。`);const d=Number(a.headers.get("content-length")),l=Number.isFinite(d)&&d>0?d:void 0;if(l!==void 0&&l>e.limits.maxTransferBytes)throw a.body.cancel().catch(()=>{}),ie(e.limits.maxTransferBytes);const h=[];yield e.adapter.writeFile(t,Gi(a.body,e,t,l,h),{signal:e.signal});const f=h.reduce((S,E)=>S+E.byteLength,0),g=new Uint8Array(f);let _=0;return h.forEach(S=>{g.set(S,_),_+=S.byteLength}),e.progress({stage:"done",loaded:f,total:f,path:t}),{data:{path:t,size:f,hash:yield ce(g)}}}),Fe=new Uint8Array([239,187,191]);function Se(i,e){return new p(w.Conflict,e,{currentHash:i})}function Je(i,e){return u(this,null,function*(){var o;if(((o=(yield Xe(i.adapter,e)).size)!=null?o:0)>i.limits.maxWriteBytes)throw ie(i.limits.maxWriteBytes,"目标文件");const s=yield te(yield i.adapter.readFile(e));return{bytes:s,hash:yield ce(s)}})}function Kt(i,e,t){return u(this,null,function*(){const{hash:s}=yield Je(i,e);if(s!==t)throw Se(s,"文件在确认期间已被修改,本次写入已取消。请重新读取后再修改。")})}function Xi(i,e){const t=new TextEncoder().encode(i);if(!e)return t;const s=new Uint8Array(Fe.byteLength+t.byteLength);return s.set(Fe,0),s.set(t,Fe.byteLength),s}function Ki(i,e){let t=0,s=i.indexOf(e);for(;s>=0;)t++,s=i.indexOf(e,s+e.length);return t}function lt(i,e){return!e||i.includes(`\r
|
|
4
|
+
`)?i:i.replace(/\n/g,`\r
|
|
5
|
+
`)}function Jt(i,e,t,s=!1){return u(this,null,function*(){return i.progress({stage:"writing",loaded:0,total:t.byteLength,path:e}),yield i.adapter.writeFile(e,t,{createDirectories:s,signal:i.signal}),{path:e,hash:yield ce(t),size:t.byteLength}})}const Ji=(i,e)=>u(exports,null,function*(){const t=U(i.path);if(de(e,t,"write"),!i.edits.length)throw new p(w.BadRequest,"参数 edits 不能为空。");const{bytes:s,hash:o}=yield Je(e,t);if(o!==i.expectedHash)throw Se(o,"expectedHash 与文件当前内容不一致,请重新读取文件后再修改。");const r=Vt(s),n=ki(r?s.subarray(3):s),c=n.includes(`\r
|
|
6
|
+
`);let a=n;i.edits.forEach((l,h)=>{if(typeof(l==null?void 0:l.oldText)!="string"||!l.oldText||typeof l.newText!="string")throw new p(w.BadRequest,`第 ${h+1} 条修改无效:oldText 必须是非空字符串,newText 必须是字符串。`);const f=lt(l.oldText,c),g=lt(l.newText,c),_=Ki(a,f);if(_===0)throw new p(w.Conflict,`第 ${h+1} 条修改的 oldText 在文件中不存在,请重新读取文件确认当前内容。`);if(_>1&&!l.replaceAll)throw new p(w.BadRequest,`第 ${h+1} 条修改的 oldText 在文件中出现了 ${_} 次,请补充上下文使其唯一,或设置 replaceAll。`);a=l.replaceAll?a.split(f).join(g):a.replace(f,()=>g)});const d=Xi(a,r);if(d.byteLength>e.limits.maxWriteBytes)throw ie(e.limits.maxWriteBytes,"修改后的内容");return yield e.requestApproval(t,{type:"text",before:n,after:a,created:!1}),yield Kt(e,t,o),{data:yield Jt(e,t,d)}}),Zi=(i,e)=>u(exports,null,function*(){const t=U(i.path);de(e,t,"write");const s=yield Ie(e.adapter,t);if((s==null?void 0:s.kind)==="directory")throw new p(w.BadRequest,"目标是目录,不能写入文件。");let o,r;if(s){const a=yield Je(e,t);if(r=a.hash,!i.expectedHash)throw Se(r,"目标文件已存在,覆盖前需要提供 expectedHash(可通过 read_file 或 stat_file 获取)。");if(i.expectedHash!==r)throw Se(r,"expectedHash 与文件当前内容不一致,请重新读取文件后再写入。");o=new TextDecoder("utf-8").decode(a.bytes)}else if(!i.createDirectories){const a=Ei(t),d=a?yield Ie(e.adapter,a):{kind:"directory"};if(!d)throw new p(w.NotFound,"父目录不存在,可设置 createDirectories 自动创建。");if(d.kind!=="directory")throw new p(w.BadRequest,"父路径不是目录。")}const n=new TextEncoder().encode(i.content);if(n.byteLength>e.limits.maxWriteBytes)throw ie(e.limits.maxWriteBytes,"写入内容");if(yield e.requestApproval(t,{type:"text",before:o,after:i.content,created:!s}),r)yield Kt(e,t,r);else if(yield Ie(e.adapter,t))throw new p(w.Conflict,"目标文件在确认期间被创建,本次写入已取消。请重新检查后再写入。");const c=yield Jt(e,t,n,i.createDirectories);return{data:I(v({},c),{created:!s})}});function O(i,e){throw new p(w.BadRequest,i?`参数 ${i} ${e}`:`参数${e}`)}function es(i,e){return typeof i!="string"?i:(e.type==="integer"||e.type==="number")&&/^-?\d+(\.\d+)?$/.test(i.trim())?Number(i):e.type==="boolean"&&(i==="true"||i==="false")?i==="true":i}function De(i,e,t){switch(i=es(i,e),e.type){case"string":typeof i!="string"&&O(t,"必须是字符串。"),e.minLength!==void 0&&i.length<e.minLength&&O(t,"不能为空。");break;case"integer":(typeof i!="number"||!Number.isInteger(i))&&O(t,"必须是整数。");break;case"number":(typeof i!="number"||!Number.isFinite(i))&&O(t,"必须是数字。");break;case"boolean":typeof i!="boolean"&&O(t,"必须是布尔值。");break;case"array":if(Array.isArray(i)||O(t,"必须是数组。"),e.minItems!==void 0&&i.length<e.minItems&&O(t,"不能为空。"),e.items){const s=e.items;return i.map((o,r)=>De(o,s,`${t}[${r}]`))}break;case"object":return Zt(i,e,t)}return e.enum&&!e.enum.includes(i)&&O(t,`必须是 ${e.enum.join("、")} 之一。`),typeof i=="number"&&(e.minimum!==void 0&&i<e.minimum&&O(t,`不能小于 ${e.minimum}。`),e.maximum!==void 0&&i>e.maximum&&O(t,`不能大于 ${e.maximum}。`)),i}function Zt(i,e,t){var r,n;(!i||typeof i!="object"||Array.isArray(i))&&O(t,"必须是对象。");const s=i,o={};for(const c of(r=e.required)!=null?r:[])(s[c]===void 0||s[c]===null)&&O(t?`${t}.${c}`:c,"是必填项。");for(const[c,a]of Object.entries((n=e.properties)!=null?n:{})){if(s[c]===void 0||s[c]===null)continue;const d=t?`${t}.${c}`:c;o[c]=a.oneOf?(De(s[c],I(v({},a),{oneOf:void 0}),d),s[c]):De(s[c],a,d)}return o}function ei(i,e){return Zt(i,e,"")}const ts={list_directory:Oi,read_file:Pi,stat_file:Bi,search_files:Hi,search_text:$i,apply_patch:Ji,write_file:Zi,upload_file:Wi,download_file:Qi};class is{constructor(e,t){y(this,"remaining");y(this,"startedAt",0);y(this,"handle");this.onTimeout=t,this.remaining=e}resume(){this.handle!==void 0||this.remaining<=0||(this.startedAt=Date.now(),this.handle=setTimeout(()=>{this.handle=void 0,this.remaining=0,this.onTimeout()},this.remaining))}pause(){this.handle!==void 0&&(clearTimeout(this.handle),this.handle=void 0,this.remaining-=Date.now()-this.startedAt)}clear(){this.pause(),this.remaining=0}}function ss(i,e){return qt.includes(e)?i.limits.transferTimeoutMs:Bt.includes(e)?i.limits.searchTimeoutMs:i.limits.toolTimeoutMs}function ns(i){if(typeof i!="string")return i;try{return JSON.parse(i)}catch(e){throw new p(w.BadRequest,"参数不是合法的 JSON 对象。")}}function rs(i){if(!i||typeof i!="object"||Array.isArray(i))return;const e=i;return(e.grantId===void 0||e.grantId===null||e.grantId==="")&&(e.grantId=Q),e.grantId}function ti(i){return new Promise((e,t)=>{i.aborted&&t(N()),i.addEventListener("abort",()=>t(N()),{once:!0})})}function as(i){return v({code:i.code,message:i.message},i.data?{data:i.data}:{})}function os(i,e,t,s,o){return u(this,null,function*(){var _,m,b,T,S,E,C,le;const r={requestId:o.requestId||ae.v4(),applicationId:o.applicationId||i.applicationId,sessionId:o.sessionId||"",pluginCode:o.pluginCode,functionCode:e,signal:o.signal},n={requestId:r.requestId,sessionId:r.sessionId,functionCode:e},c=new AbortController;let a=!1;const d=new is(ss(i,e),()=>{a=!0,c.abort()}),l=()=>c.abort();(_=r.signal)==null||_.addEventListener("abort",l,{once:!0}),(m=r.signal)!=null&&m.aborted&&c.abort();let h=null,f,g=!1;try{const x=ns(t),L=rs(x);L!=null&&$t(L);const F=ei(x,Ge[e].parameters),R=(b=F.path)!=null?b:F.destPath;if(typeof R=="string"&&(n.path=R),yield i.ready,c.signal.aborted)throw N();const V=i.adapter;if(!V)throw Ye();if(h=i.acquireSlot(),!h)throw new p(w.TooManyRequests,"同时进行的文件操作过多,请稍后重试。");f=i.track(c),g=!0,i.emit("tool:start",v({},n)),d.resume();const ge={adapter:V,workspaceName:(T=i.displayName)!=null?T:V.displayName,limits:i.limits,sensitive:i.sensitive,downloadUrlAllowlist:i.downloadUrlAllowlist,allowWorkspaceWideTextSearch:i.allowWorkspaceWideTextSearch,transfer:i.transfer,fetch:i.fetch,context:I(v({},r),{signal:c.signal}),signal:c.signal,requestApproval:(Re,ui)=>cs(i,{approvalPath:Re,preview:ui,context:r,functionCode:e,signal:c.signal,timer:d,base:n}),progress:Re=>i.emit("tool:progress",v(v({},n),Re))},me=yield Promise.race([ts[e](F,ge),ti(c.signal)]),Ce={code:w.Ok,message:"ok",data:me.data};me.truncated&&(Ce.truncated=!0),(S=me.warnings)!=null&&S.length&&(Ce.warnings=me.warnings),i.emit("tool:finish",I(v({},n),{code:w.Ok})),s(Ce)}catch(x){let L=Le(x);a?L=new p(w.Timeout,"操作超时,已中止。"):c.signal.aborted&&L.code!==w.Cancelled&&(L=N()),((E=L.data)==null?void 0:E.reason)==="workspace_not_granted"&&g&&i.handlePermissionLost(),L.code===w.Cancelled?i.emit("tool:cancelled",v({},n)):i.emit("tool:error",I(v({},n),{code:L.code,message:L.message,reason:(C=L.data)==null?void 0:C.reason})),s(as(L))}finally{d.clear(),(le=r.signal)==null||le.removeEventListener("abort",l),h==null||h(),f==null||f()}})}function cs(i,e){return u(this,null,function*(){var c;const t=i.getApprovalHandler();if(!t)throw new p(w.Forbidden,"当前环境未提供操作确认能力,无法执行写入或传输操作。",{reason:"approval_unavailable"});if(e.signal.aborted)throw N();const s=new AbortController,o=()=>s.abort();e.signal.addEventListener("abort",o,{once:!0});const r={id:ae.v4(),requestId:e.context.requestId,sessionId:e.context.sessionId,functionCode:e.functionCode,path:e.approvalPath,workspaceName:(c=i.displayName)!=null?c:"",preview:e.preview,signal:s.signal};e.timer.pause(),i.emit("tool:approval-required",I(v({},e.base),{path:e.approvalPath,approvalId:r.id}));let n;try{const a=yield Promise.race([Promise.resolve().then(()=>t(r)),ti(s.signal),new Promise(d=>{n=setTimeout(()=>d(!1),i.limits.approvalTimeoutMs)})]);if(e.signal.aborted)throw N();if(a!==!0)throw new p(w.Forbidden,"用户拒绝了本次操作。",{reason:"user_rejected"})}catch(a){throw a instanceof p?a:new p(w.Forbidden,"操作确认失败,已取消本次操作。",{reason:"user_rejected"})}finally{clearTimeout(n),e.signal.removeEventListener("abort",o),s.abort(),e.timer.resume()}})}function ii({pluginCode:i,workspace:e}){const t={};return ze.forEach(s=>{t[s]=(o,r,n)=>{let c=!1;os(e,s,o,d=>{if(!c){c=!0;try{r(d)}catch(l){console.error("[LocalFiles] callback failed",l)}}},I(v({},n),{pluginCode:i}))}}),{[i]:t}}function P(i,e=i){return new DOMException(e,i)}function Ze(i){return se(this,null,function*(){typeof i=="string"?yield new TextEncoder().encode(i):i instanceof Uint8Array?yield i:yield*ot(i)})}const Ee="glodon-workspace";function ds(i){let e=i;if(typeof e=="string")try{e=JSON.parse(e)}catch(s){return}if(!e||typeof e!="object")return;const t=e;if(t.channel===Ee)return t}function ls(){var e;const i=(e=globalThis.chrome)==null?void 0:e.webview;if(!(!i||typeof i.postMessage!="function"||typeof i.addEventListener!="function"))return i}const hs=3e4;function us(i){let e="";for(let s=0;s<i.length;s+=32768)e+=String.fromCharCode(...i.subarray(s,s+32768));return btoa(e)}function fs(i){const e=atob(i),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}function ht(i,e){const t=i&&typeof i=="object"?i:{},s=t.kind==="directory"?"directory":"file",o={name:typeof t.name=="string"&&t.name?t.name:e,kind:s};return s==="file"&&typeof t.size=="number"&&(o.size=t.size),typeof t.lastModified=="number"&&(o.lastModified=t.lastModified),o}class si{constructor(e,t=""){y(this,"displayName");y(this,"seq",0);y(this,"pending",new Map);this.view=e,this.displayName=t}settle(e){const t=this.pending.get(e.id);if(t){if(clearTimeout(t.timer),this.pending.delete(e.id),e.ok===!1){t.reject(P(e.name||"NotAllowedError",e.message||e.name||"NotAllowedError"));return}t.resolve(e)}}call(e,t,s,o=hs){M(s);const r=`host-${++this.seq}`;return new Promise((n,c)=>{const a=setTimeout(()=>{this.pending.delete(r),c(P("AbortError"))},o),d=()=>{clearTimeout(a),this.pending.delete(r),c(P("AbortError"))};s==null||s.addEventListener("abort",d,{once:!0}),this.pending.set(r,{resolve:l=>{s==null||s.removeEventListener("abort",d),n(l)},reject:c,timer:a}),this.view.postMessage(v({channel:Ee,id:r,op:e},t))})}stat(e){return u(this,null,function*(){const t=yield this.call("stat",{path:e});return ht(t.entry,e.split("/").pop()||this.displayName)})}listEntries(e,t){return u(this,null,function*(){const s=yield this.call("list",{path:e},t);return(Array.isArray(s.entries)?s.entries:[]).map(r=>ht(r,""))})}readFile(e){return u(this,null,function*(){var o;const t=yield this.call("read",{path:e}),s=fs((o=t.contentBase64)!=null?o:"");return new Blob([s])})}runPython(e,t,s,o){return u(this,null,function*(){var n,c;const r=yield this.call("run_python",{path:e,args:t,timeoutMs:s},o,s+15e3);return{exitCode:typeof r.exitCode=="number"?r.exitCode:1,timedOut:r.timedOut===!0,stdout:(n=r.stdout)!=null?n:"",stderr:(c=r.stderr)!=null?c:""}})}writeFile(o,r){return u(this,arguments,function*(e,t,s={}){const n=[];try{for(var l=Y(Ze(t)),h,f,g;h=!(f=yield l.next()).done;h=!1){const _=f.value;M(s.signal),n.push(_)}}catch(f){g=[f]}finally{try{h&&(f=l.return)&&(yield f.call(l))}finally{if(g)throw g[0]}}const c=n.reduce((_,m)=>_+m.byteLength,0),a=new Uint8Array(c);let d=0;n.forEach(_=>{a.set(_,d),d+=_.byteLength}),yield this.call("write",{path:e,contentBase64:us(a),createDirectories:s.createDirectories===!0},s.signal)})}}const ps=/^[\p{L}\p{N}_./:@=+\-,]+$/u,gs={type:"object",required:["grantId","path"],properties:{grantId:{type:"string",enum:[Q]},path:{type:"string",minLength:1},args:{type:"array",items:{type:"string",minLength:1}},timeoutMs:{type:"integer",minimum:1e3,maximum:12e4}}};function ms(i){const e=i instanceof DOMException?i.name:"",t=i instanceof Error?i.message:"";switch(e){case"NotFoundError":return new p(w.NotFound,"脚本不存在。");case"TypeMismatchError":return new p(w.BadRequest,"只能运行 .py 文件。");case"SecurityError":return new p(w.BadRequest,"脚本路径不合法。");case"AbortError":return t.includes("已有")?new p(w.TooManyRequests,"已有一个脚本在沙箱里运行。"):new p(w.Timeout,"脚本运行超时,已中止。");default:return new p(w.NotImplemented,"当前环境不能运行本地脚本。")}}function ys(i,e,t,s,o){return u(this,null,function*(){if(!e)throw new p(w.Forbidden,"当前环境未提供脚本运行确认,无法执行。",{reason:"approval_unavailable"});if(o.aborted)throw N();const r=new AbortController,n=()=>r.abort();o.addEventListener("abort",n,{once:!0});let c;try{const a=yield Promise.race([Promise.resolve().then(()=>{var d;return e({requestId:s.requestId,sessionId:s.sessionId,path:t.path,args:t.args,workspaceName:(d=i.displayName)!=null?d:"",signal:r.signal})}),new Promise(d=>{c=setTimeout(()=>d(!1),i.limits.approvalTimeoutMs)})]);if(o.aborted)throw N();if(a!==!0)throw new p(w.Forbidden,"用户拒绝了本次脚本运行。",{reason:"user_rejected"})}catch(a){throw a instanceof p?a:new p(w.Forbidden,"脚本运行确认失败,已取消本次运行。",{reason:"user_rejected"})}finally{clearTimeout(c),o.removeEventListener("abort",n),r.abort()}})}function ws(i,e,t,s,o){return u(this,null,function*(){var c,a,d,l;const r=new AbortController,n=()=>r.abort();(c=s.signal)==null||c.addEventListener("abort",n);try{const h=typeof e=="string"?JSON.parse(e):e;if(h&&typeof h=="object"&&!Array.isArray(h)){const E=h;(E.grantId===void 0||E.grantId===null||E.grantId==="")&&(E.grantId=Q)}const f=ei(h,gs);$t(f.grantId);const g=U(f.path);if(!g.toLowerCase().endsWith(".py"))throw new p(w.BadRequest,"只能运行工程内已有的 .py 文件。");const _=(a=f.args)!=null?a:[];if(_.length>Tt||_.some(E=>!ps.test(E)))throw new p(w.BadRequest,"脚本参数不合法。每个参数单独填写,不能包含空格或 shell 语法。");const m=i.sensitive.match(g,"read");if(m)throw new p(w.Forbidden,"该脚本被列为敏感文件,不能运行。",{reason:"sensitive_file",ruleId:m.id});if(yield i.ready,r.signal.aborted)throw N();const b=i.adapter;if(!b)throw Ye();if(!(b instanceof si))throw new p(w.NotImplemented,"当前环境不能运行本地脚本。");yield ys(i,o,{path:g,args:_},s,r.signal);const T=yield b.runPython(g,_,(d=f.timeoutMs)!=null?d:Et,r.signal);i.notifyFilesChanged();const S={code:w.Ok,message:"ok",data:T};t(S)}catch(h){const f=r.signal.aborted?N():h instanceof SyntaxError?new p(w.BadRequest,"参数不是合法的 JSON 对象。"):h instanceof p?h:ms(h),g=Le(f);t({code:g.code,message:g.message,data:g.data})}finally{(l=s.signal)==null||l.removeEventListener("abort",n)}})}function vs({pluginCode:i,workspace:e,onApprovalRequired:t}){const s=(o,r,n)=>{var d,l,h;let c=!1;ws(e,o,f=>{if(!c){c=!0;try{r(f)}catch(g){console.error("[LocalPython] callback failed",g)}}},{requestId:(d=n==null?void 0:n.requestId)!=null?d:ae.v4(),applicationId:(l=n==null?void 0:n.applicationId)!=null?l:e.applicationId,sessionId:(h=n==null?void 0:n.sessionId)!=null?h:"",pluginCode:i,functionCode:oe,signal:n==null?void 0:n.signal},t)};return{[i]:{[oe]:s}}}const _s=new $("[Config] ");var ni=(i=>(i.dev="https://aiot-dev.glodon.com/api/cvforcepd",i.test="https://aiot-dev.glodon.com/api/cvforce",i.prod="https://copilot.glodon.com/api/cvforce",i.local="http://localhost:3000/api/cvforcepd",i))(ni||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},businessPlugins:{},builtinPlugins:void 0,mcp:void 0,loadRelatedQuesions:!0,stream:!1};let q,W,H;const Be=new Set;function ut(i){q!==i&&(q=i,W=void 0,H=void 0,Be.clear())}function bs(){if(!W)return;const{pluginCode:i,table:e}=W,t=exports.configuration.plugins[i],s=e[i];if(!(!t||t.list_directory!==s.list_directory))return i}function Is(){if(!H)return;const{pluginCode:i,table:e}=H,t=exports.configuration.plugins[i],s=e[i];if(!(!t||t[oe]!==s[oe]))return i}function ri(i,e){return(i==null?void 0:i.pluginCode)||At[e]}function As(i,e,t){return(i==null?void 0:i.pluginCode)||t||St[e]}function Ss(){var c,a,d;const i=(c=exports.configuration.businessPlugins)!=null?c:{},e=(a=exports.configuration.builtinPlugins)==null?void 0:a.localFiles,t=(d=exports.configuration.builtinPlugins)==null?void 0:d.localPython,s=[],o=v({},i);let r,n=!1;if(e!=null&&e.enabled&&q&&(r=ri(e,exports.configuration.env),r?i[r]?s.push(`[LocalFiles] 业务插件中已存在 pluginCode「${r}」,已保留业务插件,内置文件工具未注册。`):(((W==null?void 0:W.workspace)!==q||W.pluginCode!==r)&&(W={workspace:q,pluginCode:r,table:ii({pluginCode:r,workspace:q})}),o[r]=W.table[r],n=!0):s.push(`[LocalFiles] 当前环境(env: ${exports.configuration.env})没有默认的内置工具插件编码,请配置 builtinPlugins.localFiles.pluginCode。内置文件工具未注册。`)),t!=null&&t.enabled){const l=As(t,exports.configuration.env,r);if(!q)s.push("[LocalPython] 运行脚本依赖已启用的本地工作区。内置脚本工具未注册。");else if(!l)s.push(`[LocalPython] 当前环境(env: ${exports.configuration.env})没有默认的内置工具插件编码,请配置 builtinPlugins.localPython.pluginCode,或与文件工具使用同一个 pluginCode。内置脚本工具未注册。`);else if(i[l])s.push(`[LocalPython] pluginCode「${l}」已被业务插件占用,已保留业务插件,内置脚本工具未注册。`);else if(o[l]&&!(n&&l===r))s.push(`[LocalPython] pluginCode「${l}」已被占用,已保留原插件,内置脚本工具未注册。`);else{((H==null?void 0:H.workspace)!==q||H.pluginCode!==l||H.approve!==t.onApprovalRequired)&&(H={workspace:q,pluginCode:l,approve:t.onApprovalRequired,table:vs({pluginCode:l,workspace:q,onApprovalRequired:t.onApprovalRequired})});const h=H.table[l];o[l]=n&&l===r?v(v({},o[l]),h):h}}return exports.configuration.plugins=o,s}function qe(){return Ss().filter(i=>!Be.has(i)).map(i=>(Be.add(i),console.error(i),new Error(i)))}function He(i){var e,t,s;$.debug=(i==null?void 0:i.debug)||!1,exports.configuration=I(v(v({},exports.configuration),i),{apiRoot:(i==null?void 0:i.apiRoot)||exports.configuration.apiRoot||(i!=null&&i.env?ni[i.env||"prod"]:exports.configuration.apiRoot),businessPlugins:(t=(e=i==null?void 0:i.plugins)!=null?e:exports.configuration.businessPlugins)!=null?t:{},builtinPlugins:(s=i==null?void 0:i.builtinPlugins)!=null?s:exports.configuration.builtinPlugins}),qe(),$.debug&&_s.log("updated",exports.configuration)}const Te=i=>JSON.parse(mi.decode(i.split(".")[1])),Es=i=>{const e=Te(i).exp;return new Date().valueOf()/1e3>=e},Ts=i=>i==null?void 0:i.replace(/[\r\n]+/gm,""),Ls=i=>i.replace(/\\|\\/g,""),Cs=(i,e,t,s)=>{if(i!==!0)return null;const o=(e==null?void 0:e.includeUserQuestion)===!0,n=(e==null?void 0:e.includeAiAnswer)===!0||!o,c=[];return o&&c.push(`问题:${s}`),n&&c.push(`回答:${t}`),c.join(`
|
|
7
|
+
`)};function ai(i,e,t){return new A.CVForceApi(oi(i,"/data/v1",e,t),ci(t))}function Rs(i,e,t){return new A.AIShopApi(oi(i,"/aishop",e,t),ci(t))}function oi(i,e,t,s){const o=n=>{var c;return t&&(Es(t)&&s(403,"aiotToken is timeout"),n.headers=(c=n.headers)!=null?c:{},n.headers=I(v({},n.headers),{Authorization:t?`Bearer ${t}`:""})),n};function r(n,c=!0){const a=`${i}${n}`,d=yi.create({baseURL:a});return c&&d.interceptors.request.use(o),d}return r(e)}function ci(i){return{onHttpStatusError:(s,o)=>{s===401&&i(s,"aiotToken is invalid")},onAppStatusError:(s,o)=>{s!==10001&&s!==10215&&i(s,o)}}}let J;function ks(i){J==null||J(),J=void 0;const e=ls();if(!e)return()=>{};const t=new si(e),s=r=>{const n=ds(r.data);if(n){if(n.type==="workspace"){const c=n.granted===!0,a=typeof n.displayName=="string"?n.displayName:"";c?(t.displayName=a||"工程目录",(i.status!=="granted"||i.displayName!==t.displayName)&&i.attachAdapter(t,t.displayName)):i.status==="granted"&&i.clear();return}if(n.type==="fs-changed"){const c=Array.isArray(n.paths)?n.paths.filter(a=>typeof a=="string"):[];i.notifyFilesChanged(c);return}typeof n.id=="string"&&t.settle({channel:Ee,id:n.id,ok:n.ok!==!1,name:typeof n.name=="string"?n.name:void 0,entries:n.entries,entry:n.entry,contentBase64:typeof n.contentBase64=="string"?n.contentBase64:void 0,exitCode:typeof n.exitCode=="number"?n.exitCode:void 0,timedOut:n.timedOut===!0,stdout:typeof n.stdout=="string"?n.stdout:void 0,stderr:typeof n.stderr=="string"?n.stderr:void 0,message:typeof n.message=="string"?n.message:void 0})}};e.addEventListener("message",s),e.postMessage({channel:Ee,type:"hello"});const o=()=>{e.removeEventListener("message",s),J===o&&(J=void 0)};return J=o,o}const Z=new $("[EventBus] ");class et{constructor(e=!1){y(this,"eventListenerMap",{});e&&Z.disable()}getEventListenerMap(){return v({},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),Z.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(o=>{if(typeof o=="function"&&t===o)return!0;if(o=o,o.fn===t)return!0});s<0?Z.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(s,1),Z.log(`remove event ${e} listener`))}else Z.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){Z.log(`event ${e} listeners is empty`);return}const s=[];for(let o=0;o<this.eventListenerMap[e].length;o++){const r=this.eventListenerMap[e][o];typeof r=="function"?r(t):s.push(r)}s.forEach(o=>{o&&(o.fn(t),this.off(e,o.fn))}),Z.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}function Oe(i,e){return!!i&&typeof i=="object"&&i.name===e}class di{constructor(e){this.root=e}get displayName(){return this.root.name}resolveDirectory(e,t=!1){return u(this,null,function*(){let s=this.root;for(const o of e)s=yield s.getDirectoryHandle(o,{create:t});return s})}resolveFile(e){return u(this,null,function*(){const t=G(e),s=t.pop();if(!s)throw P("TypeMismatchError");return(yield this.resolveDirectory(t)).getFileHandle(s)})}stat(e){return u(this,null,function*(){const t=G(e),s=t.pop();if(!s)return{name:this.root.name,kind:"directory"};const o=yield this.resolveDirectory(t);try{const r=yield(yield o.getFileHandle(s)).getFile();return{name:s,kind:"file",size:r.size,lastModified:r.lastModified}}catch(r){if(!Oe(r,"TypeMismatchError"))throw r;return yield o.getDirectoryHandle(s),{name:s,kind:"directory"}}})}listEntries(e,t){return u(this,null,function*(){const s=yield this.resolveDirectory(G(e)),o=[];try{for(var r=Y(s.values()),n,c,a;n=!(c=yield r.next()).done;n=!1){const d=c.value;if(M(t),d.kind==="directory")o.push({name:d.name,kind:"directory"});else try{const l=yield d.getFile();o.push({name:d.name,kind:"file",size:l.size,lastModified:l.lastModified})}catch(l){if(Oe(l,"NotAllowedError"))throw l;o.push({name:d.name,kind:"file"})}}}catch(c){a=[c]}finally{try{n&&(c=r.return)&&(yield c.call(r))}finally{if(a)throw a[0]}}return o})}readFile(e){return u(this,null,function*(){return(yield this.resolveFile(e)).getFile()})}writeFile(o,r){return u(this,arguments,function*(e,t,s={}){const n=G(e),c=n.pop();if(!c)throw P("TypeMismatchError");const a=yield this.resolveDirectory(n,s.createDirectories);let d=!0;try{yield a.getFileHandle(c)}catch(b){if(!Oe(b,"NotFoundError"))throw b;d=!1}const l=yield a.getFileHandle(c,{create:!0});let h;try{h=yield l.createWritable();try{for(var f=Y(Ze(t)),g,_,m;g=!(_=yield f.next()).done;g=!1){const b=_.value;M(s.signal),yield h.write(b)}}catch(_){m=[_]}finally{try{g&&(_=f.return)&&(yield _.call(f))}finally{if(m)throw m[0]}}M(s.signal),yield h.close()}catch(b){throw yield h==null?void 0:h.abort().catch(()=>{}),d||(yield a.removeEntry(c).catch(()=>{})),b}})}}function Ms(){if(typeof window=="undefined")return;const i=window.showDirectoryPicker;return typeof i=="function"?i.bind(window):void 0}function xs(i={}){const e=v({},_e);return Object.keys(_e).forEach(t=>{const s=i[t];typeof s=="number"&&Number.isFinite(s)&&s>0&&(e[t]=Math.min(s,_e[t]))}),e}function ne(){return new p(w.Internal,"平台文件服务请求失败,请稍后重试。")}function tt(i,e=()=>{}){const t=()=>{const r=i();if(!r)throw ne();return r},s=()=>{const r=e();if(!r)throw ne();return r};return{upload(r,n,c){return u(this,null,function*(){if(!n.sessionId)throw new p(w.BadRequest,"当前没有可用的会话,无法上传文件。");try{c==null||c({loaded:0,total:r.size});const a=yield s().postFile(r,(d,l)=>c==null?void 0:c({loaded:d,total:l}));if(!(a!=null&&a.id)||!a.url)throw ne();return c==null||c({loaded:r.size,total:r.size}),{fileId:a.id,url:a.url}}catch(a){throw a instanceof p?a:ne()}})},resolveDownload(r,n){return u(this,null,function*(){if(r.type==="platformFile")return Fs(s(),r.fileId);if(!n.sessionId)throw new p(w.BadRequest,"当前没有可用的会话,无法下载会话文件。");let c;try{c=yield t().getApplicationIdSessionFile(n.applicationId,n.sessionId,r.fileId)}catch(a){throw ne()}if(!(c!=null&&c.url))throw new p(w.NotFound,"会话文件不存在或暂不可下载。");return{url:c.url,name:c.name,size:c.size}})}}}function Fs(i,e){return u(this,null,function*(){let t;try{t=yield i.getFile(e)}catch(o){throw ne()}if(!(t!=null&&t.url))throw new p(w.NotFound,"平台文件不存在或暂不可下载。");let s;try{s=new URL(t.url)}catch(o){throw new p(w.Internal,"平台返回的下载地址无效。")}if(s.protocol!=="https:")throw new p(w.Internal,"平台返回的下载地址无效。");return{url:t.url,size:t.bytes}})}const Os="glodon-aiot-local-workspace",Ne="kv";function it(){const i=new Map;return{get(t){return u(this,null,function*(){return i.get(t)})},set(t,s){return u(this,null,function*(){i.set(t,s)})},delete(t){return u(this,null,function*(){i.delete(t)})}}}function Ns(i){return new Promise((e,t)=>{i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}function li(i=Os){if(typeof indexedDB=="undefined")return it();let e;const t=()=>(e||(e=new Promise((r,n)=>{const c=indexedDB.open(i,1);c.onupgradeneeded=()=>{c.result.createObjectStore(Ne)},c.onsuccess=()=>r(c.result),c.onerror=()=>{e=void 0,n(c.error)}})),e),s=(r,n)=>u(this,null,function*(){const c=yield t();return Ns(n(c.transaction(Ne,r).objectStore(Ne)))});return{get(r){return u(this,null,function*(){return yield s("readonly",n=>n.get(r))})},set(r,n){return u(this,null,function*(){yield s("readwrite",c=>c.put(n,r))})},delete(r){return u(this,null,function*(){yield s("readwrite",n=>n.delete(r))})}}}function ft(i){if(i!=null&&i.length&&!i.some(e=>!e||e==="."||e===".."||e.includes("/")||e.includes("\\")))return i.length===1?"":i.slice(0,-1).join("/")}function Ps(i,e){const t=globalThis.FileSystemObserver;if(typeof t!="function")return()=>{};let s;try{s=new t(o=>{const r=new Set;for(const n of o){if(n.type==="errored"){e();return}const c=ft(n.relativePathComponents),a=ft(n.relativePathMovedFrom);if(c===void 0&&a===void 0){e();return}c!==void 0&&r.add(c),a!==void 0&&r.add(a)}r.size&&e([...r])})}catch(o){return()=>{}}return s.observe(i,{recursive:!0}).catch(()=>s.disconnect()),()=>s.disconnect()}const ve={mode:"readwrite"};function Ds(i){const e=i.replace(/\\/g,"/").trim().replace(/^\.\/+/,"").replace(/\/+$/,"");if(!e||e===".")return"";if(e.startsWith("/")||e.includes(":")||e.includes("\0"))return;const t=e.split("/");if(!t.some(s=>!s||s==="."||s===".."))return t.join("/")}function Bs(i){return!!i&&typeof i=="object"&&i.name==="AbortError"}class hi{constructor(e){y(this,"applicationId");y(this,"limits");y(this,"sensitive");y(this,"downloadUrlAllowlist");y(this,"allowWorkspaceWideTextSearch");y(this,"transfer");y(this,"fetch");y(this,"store");y(this,"picker");y(this,"event",new et(!0));y(this,"_status");y(this,"_displayName");y(this,"_adapter",null);y(this,"pendingHandle",null);y(this,"approvalHandler");y(this,"activeCalls",0);y(this,"inflight",new Set);y(this,"_ready",Promise.resolve());y(this,"stopWatching",()=>{});y(this,"pendingChangePaths",new Set);y(this,"changeTimer");y(this,"refreshAllVisible",!1);var r,n,c,a,d,l,h,f,g;const t=(r=e.config)!=null?r:{};this.applicationId=e.applicationId,this.store=(n=e.store)!=null?n:it(),this.picker=e.picker===null?void 0:(c=e.picker)!=null?c:Ms(),this.limits=xs(t.limits),this.sensitive=new jt(t.sensitiveRulesAppend),this.downloadUrlAllowlist=Ke(t.downloadUrlAllowlistAppend),this.allowWorkspaceWideTextSearch=!!t.allowWorkspaceWideTextSearch,this.approvalHandler=t.onApprovalRequired;const s=(a=e.transfer)!=null?a:tt(()=>{});this.transfer={upload:(l=(d=t.transfer)==null?void 0:d.upload)!=null?l:s.upload,resolveDownload:(f=(h=t.transfer)==null?void 0:h.resolveDownload)!=null?f:s.resolveDownload};const o=(g=e.fetch)!=null?g:typeof fetch=="function"?fetch:void 0;this.fetch=o?o.bind(globalThis):()=>Promise.reject(new Error("fetch is not available")),this._status=this.picker?"none":"unsupported"}get status(){return this._status}get displayName(){return this._displayName}get isSupported(){return!!this.picker}get ready(){return this._ready}get adapter(){return this._status==="granted"?this._adapter:null}get handleKey(){return`workspace:${this.applicationId}`}get disclosureKey(){return`disclosure:${this.applicationId}`}setStatus(e,t=this._displayName){e===this._status&&t===this._displayName||(this._status=e,this._displayName=t,this.emit("workspace:changed",{status:e,displayName:t}))}attachHandle(e){this.cancelFilesChanged(),this.pendingHandle=e,this._adapter=new di(e),this.setStatus("granted",e.name),this.unwatchDirectory(),this.stopWatching=Ps(e,t=>this.notifyFilesChanged(t))}pick(){if(!this.picker)return Promise.resolve(!1);let e;try{e=this.picker({mode:"readwrite"})}catch(t){return Promise.reject(t)}return e.then(t=>u(this,null,function*(){var o,r;this.cancelAll();const s=(r=yield(o=t.queryPermission)==null?void 0:o.call(t,ve))!=null?r:"granted";return yield this.store.set(this.handleKey,{handle:t,displayName:t.name,savedAt:Date.now()}).catch(()=>{}),s==="denied"?(this.pendingHandle=t,this._adapter=null,this.setStatus("denied",t.name),!1):(this.attachHandle(t),!0)}),t=>{if(Bs(t))return!1;throw t})}restore(){return this._ready=this.doRestore(),this._ready}doRestore(){return u(this,null,function*(){var s,o,r;if(!this.picker){this._adapter||this.setStatus("unsupported");return}let e;try{e=yield this.store.get(this.handleKey)}catch(n){e=void 0}if(!(e!=null&&e.handle)){this.pendingHandle=null,this._adapter=null,this.setStatus("none",void 0);return}let t;try{t=(r=yield(o=(s=e.handle).queryPermission)==null?void 0:o.call(s,ve))!=null?r:"prompt"}catch(n){t="prompt"}t==="granted"?this.attachHandle(e.handle):(this.pendingHandle=e.handle,this._adapter=null,this.setStatus(t==="denied"?"denied":"prompt",e.displayName))})}requestPermission(){const e=this.pendingHandle;if(!(e!=null&&e.requestPermission))return Promise.resolve(!1);let t;try{t=e.requestPermission(ve)}catch(s){return Promise.reject(s)}return t.then(s=>s==="granted"?(this.attachHandle(e),!0):(this._adapter=null,this.setStatus(s==="denied"?"denied":"prompt",e.name),!1))}clear(){return u(this,null,function*(){this.cancelAll(),this.cancelFilesChanged(),this.unwatchDirectory(),this.pendingHandle=null,this._adapter=null,this.setStatus(this.picker?"none":"unsupported",void 0),yield this.store.delete(this.handleKey).catch(()=>{})})}attachAdapter(e,t=e.displayName){this.cancelAll(),this.cancelFilesChanged(),this.unwatchDirectory(),this.pendingHandle=null,this._adapter=e,this.setStatus("granted",t)}notifyFilesChanged(e){if(this._status==="granted"){if(!e||e.length===0)this.refreshAllVisible=!0;else for(const t of e){const s=Ds(t);s===void 0?this.refreshAllVisible=!0:this.pendingChangePaths.add(s)}clearTimeout(this.changeTimer),this.changeTimer=setTimeout(()=>this.flushFilesChanged(),150)}}handlePermissionLost(){return u(this,null,function*(){const e=this.pendingHandle;if(!(e!=null&&e.queryPermission))return;const t=yield e.queryPermission(ve).catch(()=>"prompt");t!=="granted"&&(this.cancelAll(),this.cancelFilesChanged(),this.unwatchDirectory(),this._adapter=null,this.setStatus(t==="denied"?"denied":"prompt",e.name))})}isDisclosureAcknowledged(){return u(this,null,function*(){try{return!!(yield this.store.get(this.disclosureKey))}catch(e){return!1}})}acknowledgeDisclosure(){return u(this,null,function*(){yield this.store.set(this.disclosureKey,!0).catch(()=>{})})}setApprovalHandler(e){this.approvalHandler=e}get hasApprovalHandler(){return!!this.approvalHandler}getApprovalHandler(){return this.approvalHandler}acquireSlot(){if(this.activeCalls>=this.limits.maxConcurrentRequests)return null;this.activeCalls++;let e=!1;return()=>{e||(e=!0,this.activeCalls--)}}track(e){return this.inflight.add(e),()=>this.inflight.delete(e)}cancelAll(){const e=Array.from(this.inflight);this.inflight.clear(),e.forEach(t=>t.abort())}handshake(){const e=Object.fromEntries(ze.map(t=>[t,!0]));return{protocolVersion:"1.0",capabilities:I(v({},e),{cancellation:!0,atomicWrite:!0}),limits:v({},this.limits)}}on(e,t){return this.event.on(e,t),()=>this.off(e,t)}off(e,t){this.event.off(e,t)}unwatchDirectory(){const e=this.stopWatching;this.stopWatching=()=>{},e()}cancelFilesChanged(){clearTimeout(this.changeTimer),this.changeTimer=void 0,this.pendingChangePaths.clear(),this.refreshAllVisible=!1}flushFilesChanged(){this.changeTimer=void 0;const e=this.refreshAllVisible,t=[...this.pendingChangePaths].sort((s,o)=>s<o?-1:s>o?1:0);this.pendingChangePaths.clear(),this.refreshAllVisible=!1,this._status==="granted"&&this.emit("files:changed",{paths:e?[]:t})}emit(e,t){try{this.event.emit(e,t)}catch(s){console.error(`[LocalWorkspace] ${e} listener failed`,s)}}}var re=(i=>(i[i.Normal=0]="Normal",i[i.Debug=1]="Debug",i))(re||{});const pt=100,k=new $("[Session] ");var fe=(i=>(i.DataRequestFailed="data request error",i.SocketConnectionFailed="socket error",i.IdUndefined="session id is not defined",i.SendingEmptyContent="failed at sending empty content",i.Frozen="session is frozen",i.UserModeError="failed at setting socket user mode",i.Inactive="session is inactive",i))(fe||{});class st{constructor(e,t="",s,o,r,n){y(this,"_id");y(this,"_frozen",!1);y(this,"inactivating",!1);y(this,"_ready",!1);y(this,"event",new et);y(this,"_applicationId");y(this,"_application",null);y(this,"data",null);y(this,"client",null);y(this,"messages",[]);y(this,"_loadingMessages",!1);y(this,"_loadingMessagesSize",10);y(this,"cvforceApi");y(this,"socket",null);y(this,"_promptVariables",[]);y(this,"active",!1);y(this,"activing",!1);y(this,"_stopAnswer",!1);y(this,"_dataLoading",!1);y(this,"_dataLoaded",!1);y(this,"_mcpServers",null);this.token=e,this.lazyload=o,this.client=n||null,this._applicationId=Te(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),r&&(this._application=r),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var c;if(t)this._id=t,this.event.emit("data:loading"),s?(this.data=s,o||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(a=>u(this,null,function*(){this.data=a,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>u(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(a=>u(this,null,function*(){this.data=a,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>u(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 a=(s==null?void 0:s.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:a}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:a,netOpen:s==null?void 0:s.netOpen,knowledgeIdList:(c=s==null?void 0:s.knowledges)==null?void 0:c.map(d=>d.id),applicationId:this._applicationId}).then(d=>u(this,null,function*(){var l;this._id=d.id,this.data=I(v({},d),{knowledges:s==null?void 0:s.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id);try{yield(()=>u(this,null,function*(){if(s!=null&&s.knowledges)return this.setKnowledges((s==null?void 0:s.knowledges)||void 0)}))()}catch(h){k.error(h)}yield(()=>{if(s!=null&&s.promptVariables){const h=this._promptVariables.map(f=>{var _,m;const g=((m=(_=s.promptVariables)==null?void 0:_.find(b=>b.key===f.key&&b.type===f.type))==null?void 0:m.value)||"";return I(v({},f),{value:g})}).sort((f,g)=>f.key.localeCompare(g.key));return this.setPromptVariables(h||[])}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)!==A.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}fetchData(){return u(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=>u(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 u(this,null,function*(){if(!this.data)throw Error("session data is not loaded");if((e||[]).some(o=>Array.isArray(o.fileIds)&&o.fileIds.length===0))throw Error("fileIds cannot be an empty array");if((e||[]).reduce((o,r)=>{var c,a;const n=(a=(c=r.fileIds)==null?void 0:c.length)!=null?a:0;return o+(n>0?n:1)},0)>pt)throw Error(`knowledges and fileIds total count cannot exceed ${pt}`);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===A.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===A.PromptVariableType.User&&e.key==="query")&&!(e.type===A.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return u(this,null,function*(){const t=e==null?void 0:e.map(r=>r.type?r:I(v({},r),{type:"instruction"})),s=this._promptVariables.map(r=>{var c;const n=((c=t==null?void 0:t.find(a=>a.key===r.key&&a.type===r.type))==null?void 0:c.value)||r.value;return I(v({},r),{value:n})}).sort((r,n)=>r.key.localeCompare(n.key));if(!(yield Promise.all(s.filter(r=>!(r.type===A.PromptVariableType.User&&r.key==="query")&&!(r.type===A.PromptVariableType.System&&r.key==="datetime")).map(r=>{if(!this.data)throw Error("session data is not loaded");if(!(!r.id||!r.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,r.id,{value:r.value})})).then(()=>!0).catch(r=>!1)))return!1;if(!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 u(this,null,function*(){var t,s,o;if(k.log("setNetOpen:",e),k.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((s=this._application)==null?void 0:s.type)===A.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((o=this._application)==null?void 0:o.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,k.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return ai(exports.configuration.apiRoot,this.token,(e,t)=>{const s=new Error("data request error",{cause:{status:e,message:t}});k.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 u(this,arguments,function*(e={}){var s,o;const t={pageSize:this._loadingMessagesSize};if(this._id){e=v(v({},t),e),this.event.emit("history:loading"),k.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),k.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),n=r.map((a,d)=>{var f,g;let l=[],h;return typeof((f=a.agentHistoryList)==null?void 0:f.agentList)=="string"&&(l=JSON.parse(a.agentHistoryList.agentList).reduce((m,b)=>(m[b.data.step-1]||(m[b.data.step-1]=[]),m[b.data.step-1].push(b),m),[])),d===r.length-1&&(h=(g=this.data)==null?void 0:g.lastRelatedQuestion),I(v({},a),{actions:l,relatedQuesion:h,fromHistory:!0})});if(!e.endTime&&!e.startTime){const a=this.messages[this.messages.length-1];a&&!a.relatedQuesion&&(a.relatedQuesion=(s=this.data)==null?void 0:s.lastRelatedQuestion),this.messages=[...n,...this.messages]}else if(e.endTime&&!e.startTime){const a=this.messages.findIndex(d=>d.ts===e.endTime);this.messages.splice(0,a+1),this.messages=[...n,...this.messages]}else if(!e.endTime&&e.startTime){const a=this.messages.findLastIndex(d=>d.ts===e.endTime);this.messages.splice(a,this.messages.length-a-1),this.messages=[...this.messages,...n]}else{const a=this.messages.findIndex(l=>l.ts===e.endTime),d=this.messages.findLastIndex(l=>l.ts===e.endTime);this.messages.splice(a,d-a+1,...n)}const c=this.messages[this.messages.length-1];return c&&!c.relatedQuesion&&(c.relatedQuesion=(o=this.data)==null?void 0:o.lastRelatedQuestion),this.event.emit("history:moreloaded",n),k.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 k.error(r),this.event.emit("error",r),!1}})}rename(e){return u(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}),k.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return u(this,null,function*(){this.messages.push(e),k.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=>u(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),k.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>u(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 u(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return u(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return k.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 u(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=>u(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 u(this,arguments,function*(e,t={stream:exports.configuration.stream}){var _;try{this.validateConfigs()}catch(m){console.error(m)}const{stream:o=exports.configuration.stream,referenceFirst:r=!1}=t,n=e.uuid||ae.v4(),c=((_=e.text)==null?void 0:_.trim())||"",a=e.files||[],d=e.fileIds,l=e.imageContent;if(!c&&!a.length&&!(d!=null&&d.length)){const m=new Error("failed at sending empty content");return k.error(m),this.event.emit("error",m),!1}if(!this._id){const m=new Error("session id is not defined");return k.error(m),this.event.emit("error",m),!1}if(this.frozen){const m=new Error("session is frozen");return k.error(m),this.event.emit("error",m),!1}this.frozen=!0,this._stopAnswer=!1;const h={sessionId:this.id,role:2,content:c,messageId:n,reference:[],searchReference:[],messageTime:"",files:a,imageContent:l},f={content:c,stream:o,requestId:n,fileIds:d,referenceFirst:r,imageContent:l};this.pushMessage(h),this.event.emit("question:content",c);const g=m=>u(this,null,function*(){if(m.role!==A.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",g),this._id&&m.content&&m.index&&m.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:m.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:m.content})),yield this.fillMessageReference(m),m.code){case 11915:m.content="请您换个问题问我吧~",m.index=-1,m.isSensitive=!0,m.isLoading=!1,m.sessionId=this._id||"",this.event.emit("message:error",m);break;case 11916:m.content="尊敬的用户您好,让我们换个话题再聊聊吧。",m.index=-1,m.isSensitive=!0,m.isLoading=!1,m.sessionId=this._id||"",this.event.emit("message:error",m);break;case 200:m.index=-1,m.isLoading=!1;break;default:m.content=m.message||"未知错误",m.isLoading=!1,m.index=-1,this.event.emit("message:error",m)}this.getRelatedQuesion(m),m.isLoading=!1;let b=this.messages[this.messages.length-1];if(b&&b.role===A.ChatMessageRole.Robot){const T=v(v({},b),m);this.messages[this.messages.length-1]=T,this.event.emit("message:updated",T)}else this.pushMessage(m);this.frozen=!1});return this.addEventListener("answer:finish",g),this.sendQuestion(f,I(v({},t),{stream:o,referenceFirst:r})),h})}currentUserQuestion(){for(let e=this.messages.length-1;e>=0;e-=1){const t=this.messages[e];if(t.role===A.ChatMessageRole.User)return t.content||""}return""}getRelatedQuesion(e){return u(this,null,function*(){var c,a;if(!e.content||e.isSensitive||e.code!==200)return e;const t=(c=this.application)==null?void 0:c.arrange[0],s=Cs(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 o=yield this.cvforceApi.postGeneques({content:s}).catch(d=>null);if(!o){const d=[],l=I(v({},e),{relatedQuesion:d,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:d}),this.event.emit("message:updated",l),l}const r=(a=o.content)==null?void 0:a.split("*").map(Ts).map(Ls).filter(d=>!!d);e.relatedQuesion=r,e.index=-3,e.isLoading=!1;const n=I(v({},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 u(this,null,function*(){try{const t=yield Promise.all(e.reference.map(s=>this.cvforceApi.getKnowledgeIdFileId(s.knowledgeId,s.docId)));e.reference=e.reference.map((s,o)=>v(v({},s),t[o]))}catch(t){console.error("Failed to fill message reference:",t)}return this.event.emit("message:updated",e),e})}answerAgain(){return u(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 o;t.role!==A.ChatMessageRole.User&&(o=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:o},c=a=>u(this,null,function*(){if(a.role===A.ChatMessageRole.Robot&&a.index===-1){switch(this._id&&a.content&&a.index&&a.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:a.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:a.content})),yield this.fillMessageReference(a),a.code){case 11915:a.content="请您换个问题问我吧~",a.index=-1,a.isSensitive=!0,a.isLoading=!1,a.sessionId=this._id||"",this.event.emit("message:error",a);break;case 11916:a.content="尊敬的用户您好,让我们换个话题再聊聊吧。",a.index=-1,a.isSensitive=!0,a.isLoading=!1,a.sessionId=this._id||"",this.event.emit("message:error",a);break;case 200:a.index=-1,a.isLoading=!1;break;default:a.content=a.message||"未知错误",a.isLoading=!1,a.index=-1,this.event.emit("message:error",a)}this.getRelatedQuesion(a),this.removeEventListener("message:content",c),this.frozen=!1}});this.addEventListener("message:content",c),this.sendQuestion(n,I(v({},e),{stream:s}))})}setTop(e){return u(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:ae.v4(),isLoading:!1,index:-2,messageTime:Ue(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:A.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const o=e.actions[((s=e.actions)==null?void 0:s.length)-1];if(o){const r=o[o.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:n,pluginCode:c,funcCode:a,funcName:d}=r.data;o.push({data:{pluginName:n,pluginCode:c,funcCode:a,funcName:d,step:r.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:o})}}}e=v(v({},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}handleStreamAnswer(e,t){var n;if(!e.data)return;const s=e.data.type,o=e.data.payload;t.isReplying=!0;const r=()=>{if(!t.searchingStatus){t.searchingStatus="start";return}if(t.searchingStatus==="start"){t.searchingStatus="end";return}};if(s==="error"&&(t.index=-1),s==="beforeSearch"&&r(),s==="searchOver"&&r(),s==="search"&&t.searchReference.push(o),s==="thinking"){t.thinkingStatus="start";const a=o.choices[0];t.reasoningContent=(t.reasoningContent||"")+((n=a.delta.reasoningContent)!=null?n:"")}if(s==="thinkingOver"){t.thinkingStatus="end";const c=o.thinkingSecs;t.thinkingSecs=c}if(s==="text"){const a=o.choices[0];t.content=(t.content||"")+a.delta.content}if(s==="reference"&&(t.reference=o),s==="updateSession"&&o&&this.data&&(this.data=v(v({},this.data),o),this.event.emit("data:updated",this.data)),s==="result"){const c=o.messageId,a=o.llmModel,d=o.messageTime;t.messageId=c,t.llmModel=a,t.messageTime=d}s==="over"?t.index=-1:(t.code=e.code,t.message=e.message)}getArtifacts(){return u(this,null,function*(){var t;if(!this._applicationId||!this._id)throw Error("session is not avalible. id is undefined");const e=yield this.cvforceApi.getSessionArtifacts(this._applicationId,this._id);return(t=e==null?void 0:e.artifacts)!=null?t:[]})}postMessageComment(e){return u(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(o=>o.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 D=new $("[AgentSession] ");function gt(i){if(typeof i!="string")return i;const e=i.trim();if(e)try{return JSON.parse(e)}catch(t){return i}}function mt(i){return i==null||i===""||typeof i=="object"&&!Array.isArray(i)&&Object.keys(i).length===0}function qs(i,e){const t=gt(i==null?void 0:i.query);if(!mt(t))return t;const s=gt(e);return mt(s)&&t!=null?t:s}class Hs extends st{constructor(t,s="",o,r,n,c){super(t,s,o,r,n,c);y(this,"inflightCalls",new Set)}prepareConnection(){return new Promise(t=>u(this,null,function*(){this.socket&&t(!0);const s={version:"1.0",stream:JSON.stringify(exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?re.Debug:re.Normal},o=new URL(exports.configuration.apiRoot),r=yield wi.io(o.origin,{path:o.pathname.replace("api","socketio")+"/copilot",query:s,transports:["websocket"]});r.on("connect",()=>{D.log("socket:connect"),this.event.emit("socket:connect"),r.emit("init")}),r.on("disconnect",()=>{D.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),r.on("ready",n=>{if(n.code===200){D.log("ready");const c=exports.configuration.debug?re.Debug:re.Normal;c===re.Debug&&n.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),t(!0)}else{this._ready&&(this._ready=!1);const c=new Error(fe.SocketConnectionFailed);D.error("error",c),this.event.emit("error",c),t(!1)}}),r.on("action",(n,c)=>u(this,null,function*(){var m;if(this._stopAnswer||!this.id)return;const{type:a,data:{runnerIsClient:d,pluginCode:l,funcCode:h,parameters:f,requestBody:g}}=n,_=this.messages[this.messages.length-1];if(!_.messageId)_.actions||(_.actions=[]),_.actions[n.data.step-1]||(_.actions[n.data.step-1]=[]),_.actions[n.data.step-1].push(n),this.event.emit("message:action",{messageId:_.messageId,action:n}),this.event.emit("message:updated",_);else{const b={messageId:"",content:"",role:A.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[n]],comment:{isAgree:0},isReplying:!0};this.pushMessage(b),this.event.emit("message:action",{messageId:b.messageId,action:n})}if(this.inactivating){const b=new Error(fe.Inactive);D.warn("error",b),this.event.emit("error",b)}else if(a==="FUNCTION_CALL"&&d){D.log(`calling function ${h} of plugin ${l} with argument:
|
|
8
|
+
${JSON.stringify(f)}`);const b=(m=exports.configuration.plugins)==null?void 0:m[l];if(!b){c({code:404,message:"没有找到插件。"});return}const T=b[h];if(typeof T!="function"){c({code:404,message:"没有找到插件方法。"});return}const S=qs(f,g);this.invokeClientPlugin(T,S,c,{requestId:n.requestId,pluginCode:l,functionCode:h})}})),r.on("answer",n=>{if(!this._stopAnswer)if(n.data.code!==200&&(n.data.index=-1),n.data.stream||n.data.stream===void 0){let c=this.messages[this.messages.length-1];if(c&&c.role===A.ChatMessageRole.Robot)this.handleStreamAnswer(n.data,c),this.messages[this.messages.length-1]=c,this.event.emit("message:content",c),this.event.emit("message:updated",c),c.index===-1&&(c.isReplying=!1,this.event.emit("answer:finish",c));else{const a={content:"",role:A.ChatMessageRole.Robot,reference:[],searchReference:[],messageId:"",sessionId:this.id,messageTime:Ue(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""};this.handleStreamAnswer(n.data,a),this.pushMessage(a),this.event.emit("message:content",a),a.index===-1&&(a.isReplying=!1,this.event.emit("answer:finish",a))}}else if(n.data.updateSession&&this.data&&(this.data=v(v({},this.data),n.data.updateSession),this.event.emit("data:updated",this.data)),n.data.index===-1){let c=this.messages[this.messages.length-1];if(c&&!c.messageId)c=v(v({},c),n.data),this.event.emit("message:content",c),this.event.emit("message:updated",c),this.event.emit("answer:finish",c);else{const a=v({messageId:"",content:"",role:A.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},n.data);this.event.emit("message:content",a),this.pushMessage(a),this.event.emit("answer:finish",a)}}else{let c=this.messages[this.messages.length-1];c&&!c.messageId?(c=v(v({},c),n.data),this.messages[this.messages.length-1]=c,this.event.emit("message:content",c),this.event.emit("message:updated",c)):(this.pushMessage(v({messageId:"",content:"",role:A.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},n.data)),this.event.emit("message:content",n.data))}}),r.on("reference",n=>u(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const f=new Error(fe.IdUndefined);D.error(f),this.event.emit("error",f),this.frozen=!1;return}const{type:c,data:a,requestId:d}=n,l=this.messages.findIndex(f=>f.messageId===d&&f.role===A.ChatMessageRole.User);if(l<0)return;const h=l+1;if(h>=this.messages.length){const f={messageId:"",content:"",role:A.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0};this.pushMessage(f)}c==="KG"?(this.messages[h]=I(v({},this.messages[h]),{reference:a.knowledgeReference}),yield this.fillMessageReference(this.messages[h]),this.event.emit("message:reference",a.knowledgeReference),this.event.emit("message:updated",this.messages[h])):c==="WEB_SEARCH"&&(this.messages[h]=I(v({},this.messages[h]),{searchReference:a.knowledgeReference}),this.event.emit("message:searchreference",a.searchReference),this.event.emit("message:updated",this.messages[h]))})),this.socket=r,r.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((t,s)=>{if(!this.socket){s("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,o=>{o.code===200?(Object.keys(o.data).forEach(r=>{o.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",o.data[r])}),t(!0)):(console.error("MCP Server 注册失败。",o),s(o))})}):Promise.resolve(!0)}addMcpServers(t){return u(this,null,function*(){return this.ready?this.socket?new Promise((s,o)=>{this.socket&&this.socket.emit("add_mcp_servers",t,r=>{r.code===200?(Object.keys(r.data).forEach(n=>{r.data[n].code!==200&&console.error(n,"MCP Server 注册失败。",r.data[n])}),s(!0)):(console.error("MCP Server 注册失败。",r),o(r))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return u(this,null,function*(){return this.ready?this.socket?new Promise((t,s)=>{this.socket&&this.socket.emit("list_mcp_servers",o=>{o.code===200?t(o.data):s(o)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(t,s){return u(this,null,function*(){var r,n,c;this.convertKnowledgesToChatFormat(this.knowledges);let o=I(v({},t),{promptVariables:this.promptVariables.filter(a=>a.type===A.PromptVariableType.User).reduce((a,d)=>I(v({},a),{[d.key]:d.value}),{}),systemPromptVariables:this.promptVariables.filter(a=>a.type===A.PromptVariableType.System).reduce((a,d)=>I(v({},a),{[d.key]:d.value}),{}),knowledges:(r=this.knowledges)==null?void 0:r.map(a=>a.id),enableTitleSummary:!0});if(!this.active){if(yield this.activate(),!this.socket){const a=new Error(fe.SocketConnectionFailed);return D.warn("error",a),this.event.emit("error",a),!1}(n=this.socket)==null||n.emit("question",o);return}(c=this.socket)==null||c.emit("question",o)})}invokeClientPlugin(t,s,o,r){const n=new AbortController;this.inflightCalls.add(n);let c=!1;const a=(...l)=>{c||(c=!0,this.inflightCalls.delete(n),!(this._stopAnswer||n.signal.aborted)&&o(...l))},d={requestId:r.requestId||ae.v4(),applicationId:this._applicationId,sessionId:this.id,pluginCode:r.pluginCode,functionCode:r.functionCode,signal:n.signal};try{const l=t(s,a,d);l&&typeof l.catch=="function"&&l.catch(h=>{D.error("client plugin failed",h),a({code:500,message:"客户端插件执行失败。"})})}catch(l){D.error("client plugin failed",l),a({code:500,message:"客户端插件执行失败。"})}}abortClientPluginCalls(){const t=Array.from(this.inflightCalls);this.inflightCalls.clear(),t.forEach(s=>s.abort())}stopAnswer(){var t;this.abortClientPluginCalls(),(t=this.socket)==null||t.emit("stop_answer")}inactivate(t=!1){return this.abortClientPluginCalls(),super.inactivate(t)}destroy(){return this.abortClientPluginCalls(),super.destroy()}convertKnowledgesToChatFormat(t){return t?t.map(s=>s!=null&&s.fileIds?{id:s.id,fileIds:s.fileIds}:s.id):[]}}function $s(i,e){return u(this,null,function*(){const t=i.getReader();let s;for(;!(s=yield t.read()).done;)e(s.value)})}function Us(i){let e,t,s,o=!1,r;return function(c){e===void 0?(e=c,t=0,s=-1,r=!1):e=js(e,c);const a=e.length;let d=0;for(;t<a;){o&&(e[t]===10&&(d=++t),o=!1);let l=-1;for(;t<a&&l===-1;++t)switch(e[t]){case 58:s===-1&&(s=t-d);break;case 13:o=!1,t+4<a&&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;i(e.subarray(d,l),s,r),d=t,s=-1,r=!1}d===a?e=void 0:d!==0&&(e=e.subarray(d),t-=d)}}function zs(i,e,t){let s=yt();const o=new TextDecoder;return function(n,c,a){if(n.length===0)t==null||t(s),s=yt();else if(c>0){const d=o.decode(n.subarray(0,c)),l=c+(n[c+1]===32?2:1);let h=o.decode(n.subarray(l));switch(a&&(h+=`
|
|
4
9
|
`),d){case"data":s.data=s.data?s.data+`
|
|
5
|
-
`+l:l;break;case"event":s.event=l;break;case"id":c(s.id=l);break;case"retry":const u=parseInt(l,10);isNaN(u)||e(s.retry=u);break}}}}function ye(c,e){const t=new Uint8Array(c.length+e.length);return t.set(c),t.set(e,c.length),t}function H(){return{data:"",event:"",id:"",retry:void 0}}const j="text/event-stream",we=1e3,K="last-event-id";function W(c,f){var l=f,{signal:e,headers:t,onopen:s,onmessage:r,onclose:a,onerror:i,openWhenHidden:o,fetch:n}=l,d=U(l,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((u,v)=>{const _=g({},t);_.accept||(_.accept=j);let h;function I(){h.abort(),document.hidden||$()}o||document.addEventListener("visibilitychange",I);let A=we,C=0;function O(){document.removeEventListener("visibilitychange",I),window.clearTimeout(C),h.abort()}e==null||e.addEventListener("abort",()=>{O(),u()});const te=n!=null?n:window.fetch,se=s!=null?s:Ie;function $(){return p(this,null,function*(){var F;h=new AbortController;try{const E=yield te(c,w(g({},d),{headers:_,signal:h.signal}));yield se(E),yield ge(E.body,me(ve(k=>{k?_[K]=k:delete _[K]},k=>{A=k},r))),a==null||a(),O(),u()}catch(E){if(!h.signal.aborted)try{const k=(F=i==null?void 0:i(E))!=null?F:A;window.clearTimeout(C),C=window.setTimeout($,k)}catch(k){O(),v(k)}}})}$()})}function Ie(c){const e=c.headers.get("content-type");if(!(e!=null&&e.startsWith(j)))throw new Error(`Expected content-type to be ${j}, Actual: ${e}`)}const G=new S("[DialogSession] ");class _e extends D{constructor(t,s="",r,a,i,o){super(t,s,r,a,i,o);m(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>p(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,s,r,a,i,o){return p(this,null,function*(){const n={code:0,content:"",role:y.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=w(g({},r),{stream:exports.configuration.stream});W(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:a,onopen(f){return f.ok&&i!=null&&i.onopen&&i.onopen(),Promise.resolve()},onmessage(f){if(!f.data.includes('{"code": ')){let u={};try{u=JSON.parse(f.data)}catch(_){}(u==null?void 0:u.mtype)==="search"?n.searchReference.push(u):n.content=n.content+f.data;const v={content:n.content,role:1,reference:n.reference,searchReference:n.searchReference,messageId:n.messageId,sessionId:s,messageTime:Q(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(i==null?void 0:i.onmessage)&&i.onmessage(v)}const l=JSON.parse(f.data);if(n.reference=l.data.reference,n.searchReference=l.data.searchReference,n.messageTime=l.data.messageTime,n.messageId=l.data.messageId,n.llmModel=l.data.llmModel,n.content=l.data.content,n.code=l.code,l.code===200){const u={code:n.code,content:n.content,role:1,reference:n.reference,searchReference:n.searchReference,messageId:n.messageId,sessionId:s,messageTime:n.messageTime,isReplying:!0};i!=null&&i.onmessage&&i.onmessage(u)}else return i!=null&&i.onclose&&i.onclose(n),o&&o({code:n.code,message:n.message})},onerror(){i!=null&&i.onerror&&i.onerror()},onclose(){const f={code:n.code,content:n.content,role:1,reference:n.reference,searchReference:n.searchReference,messageId:n.messageId,sessionId:s,messageTime:n.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};i!=null&&i.onclose&&i.onclose(f)}})})}postChatV3EventSource(t,s,r,a,i,o){return p(this,null,function*(){const n=this,d={code:0,content:"",role:y.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},f=w(g({},r),{stream:exports.configuration.stream});W(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(f),openWhenHidden:!0,signal:a,onopen(l){return l.ok&&i!=null&&i.onopen&&i.onopen(),Promise.resolve()},onmessage(l){if(!l.data&&!l.event&&!l.id&&!l.retry)return;let u={};try{u=JSON.parse(l.data)}catch(v){console.error("parse eventData to JSON failed. ",l.data)}if(u.code!==200)return d.index=-1,d.code=u.code,d.message=u.message,i!=null&&i.onmessage&&i.onmessage(d),o&&o({code:u.code,message:u.message});n.handleStreamAnswer(u,d),i!=null&&i.onmessage&&i.onmessage(d)},onerror(){i!=null&&i.onerror&&i.onerror()},onclose(){const l=w(g({},d),{isReplying:!1});i!=null&&i.onclose&&i.onclose(l)}})})}sendQuestion(t,s){return p(this,null,function*(){const{content:r,fileIds:a,oldMessageId:i,imageContent:o}=t,{stream:n,referenceFirst:d}=s;if(this.active||(yield this.activate()),this._id){const f=this.convertKnowledgesToChatFormat(this.knowledges);let l={content:r,fileIds:a,referenceFirst:d,oldMessageId:i,promptVariables:this.promptVariables.filter(u=>u.type===y.PromptVariableType.User).reduce((u,v)=>w(g({},u),{[v.key]:v.value}),{}),systemPromptVariables:this.promptVariables.filter(u=>u.type===y.PromptVariableType.System).reduce((u,v)=>w(g({},u),{[v.key]:v.value}),{}),knowledges:f,enableTitleSummary:!0,imageContent:o};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,l,this.ctrl.signal,{onopen:()=>{G.log("open",this.ctrl)},onmessage:u=>{if(this._stopAnswer)return;let v=this.messages[this.messages.length-1];v&&v.role===y.ChatMessageRole.Robot?(v=g(g({},v),u),this.messages[this.messages.length-1]=v,this.event.emit("message:content",v),this.event.emit("message:updated",v)):(this.pushMessage(u),this.event.emit("message:content",u))},onclose:u=>p(this,null,function*(){this._stopAnswer||(G.log(u,"onclose"),this.event.emit("answer:finish",u))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return p(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}convertKnowledgesToChatFormat(t){return t?t.map(s=>s!=null&&s.fileIds?{id:s.id,fileIds:s.fileIds}:s.id):[]}}const be="@glodon-aiot/bot-client-sdk",Se="3.25.1-alpha.7",Ae="glodoncv",ke="aiot bot client js sdk",Re="module",Me=!1,xe=["aiot","bot","bot client","sdk"],Ce=["dist"],Le="./dist/es/index.mjs",Te="./dist/lib/index.js",Ee="./dist/src/index.d.ts",Ve={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},Pe="MIT",Oe={watch:"yarn build --watch",example:"node ./example/server.js",dev:"npm-run-all -p watch example",start:"vite",build:"tsc && vite build --mode prod && yarn build:cdn","build:npm":"tsc && vite build --mode prod","build:cdn":"tsc && vite build --mode prod --config ./vite.config.cdn.ts",preview:"vite preview",check:"yarn prettier --check .",write:"yarn prettier --write .",lint:"eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js"},$e={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@types/express":"^4","@types/identity-obj-proxy":"^3","@typescript-eslint/eslint-plugin":"^5.35.1","@typescript-eslint/parser":"^5.35.1","babel-loader":"^8.3.0",eslint:"^8.0.1","eslint-config-prettier":"^8.5.0","eslint-config-standard-with-typescript":"^22.0.0","eslint-plugin-import":"^2.25.2","eslint-plugin-n":"^15.0.0","eslint-plugin-promise":"^6.0.0","eslint-plugin-react":"^7.31.0","eslint-plugin-storybook":"^0.6.10",express:"4","http-proxy-middleware":"^3.0.0","identity-obj-proxy":"^3.0.0","npm-run-all":"^4.1.5",prettier:"2.7.1","rollup-plugin-visualizer":"^6.0.1","socket.io":"^4.7.5","ts-node":"^10.9.2",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0","vite-tsconfig-paths":"^5.1.4"},ze={access:"public",registry:"https://registry.npmjs.org/"},Ne={"@glodon-aiot/apis":"^3.25.1-alpha.7",axios:"0.24.0",buffer:"^6.0.3",dayjs:"^1.11.13","js-base64":"^3.7.7","socket.io-client":"^4.7.5",uuid:"^11.1.0"},je={name:be,version:Se,author:Ae,description:ke,type:Re,sideEffects:Me,keywords:xe,files:Ce,module:Le,main:Te,typings:Ee,exports:Ve,license:Pe,scripts:Oe,devDependencies:$e,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:ze,dependencies:Ne},Qe=new S("[BotClient] ");class De{constructor(e,t,s=!0,r={analytics:{enabled:!1}}){m(this,"event",new ee);m(this,"cvforceApi");m(this,"_applicationId");m(this,"_application",null);m(this,"_sessions",[]);m(this,"_activeSession");m(this,"_ready",!1);m(this,"_questionContextMaxLength",4e3);m(this,"_promptVariables",[]);if(this._token=e,this.lazyload=s,this.sdkConfigs=r,N(t),this._applicationId=P(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.loadApplication().then(a=>{N(w(g({},t),{stream:t.stream===void 0?(a==null?void 0:a.type)===y.ApplicationTypes.Dialog||(a==null?void 0:a.type)===y.ApplicationTypes.Agent:t.stream})),this.event.emit("ready")})}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return p(this,null,function*(){var t,s,r,a,i;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(s=this.sdkConfigs.ui)==null?void 0:s.version,sdkVersion:je.version}).then(o=>(typeof o.arrange[0].thinkingModeOpen!="boolean"&&(o.arrange[0].thinkingModeOpen=!0),typeof o.arrange[0].thinkingTextOpen!="boolean"&&(o.arrange[0].thinkingTextOpen=!0),w(g({},o),{arrange:[w(g({},o.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&o.arrange[0].recommendQuestionOpen})]})));const e=(i=(a=(r=this._application)==null?void 0:r.arrange)==null?void 0:a[0])==null?void 0:i.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(o=>o.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type:y.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:y.PromptVariableType.System})]).then(([o,n])=>[...o,...n]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:Z(exports.configuration.apiRoot,this.token,(e,t)=>Qe.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=P(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,s,r,a){return p(this,null,function*(){const i=this;return new Promise((o,n)=>{const d=f=>p(this,null,function*(){if(f===y.ApplicationTypes.Agent)o(new ue(e,t,s,r,a,i));else if(f===y.ApplicationTypes.Dialog)o(new _e(e,t,s,r,a,i));else throw Error(`不支持的应用类型:${f}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getSessions(e){return p(this,null,function*(){return new Promise((t,s)=>{const r=()=>this.cvforceApi.listSessions(this._applicationId,e).then(a=>p(this,null,function*(){const i=[];for(const o of a){const n=this._sessions.find(d=>d.id===o.id);if(n)n.data=o,this._application?n.application=this._application:yield n.loadApplicationInfo(),i.push(n);else{const d=yield this.createSession(this.token,o.id,o,this.lazyload,this._application||void 0);i.push(d)}}if(e!=null&&e.pageSize){const o=[...this._sessions,...i],n=new Map;for(const d of o)n.set(d.id,d);return this.sessions=Array.from(n.values()),this.sessions}else return this.sessions=i,i}));if(this.ready){if(!this._application)throw Error("_application is null");t(r())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(r())},!0)})})}loadSession(e="",t){return p(this,null,function*(){this.checkReady();let s=this.sessions.find(r=>r.id===e);if(s||(s=yield this.createSession(this.token,e,t),this._sessions.push(s)),this._activeSession){if(this._activeSession===s)return s;this._activeSession.inactivate()}return s.id?(this._activeSession=s,yield s.activate()):s.addEventListener("data:loaded",()=>{this._activeSession!==s&&(s==null||s.activate(),this._activeSession=s)},!0),s})}reload(){return this.loadApplication().then(()=>p(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return p(this,null,function*(){yield this.reload();let t=this._sessions.find(s=>s.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,s="top_time desc, sort_status desc, updated_at desc"){return p(this,null,function*(){let r=e?this._sessions.find(a=>a.id===e):this._activeSession;if(!r){console.warn("setTop session failed.");return}return yield r.setTop(t),this.getSessions({order:s})})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return p(this,null,function*(){this.checkReady();let s=-1;if(typeof e=="string"?s=this._sessions.findIndex(r=>r.id===e):s=this._sessions.findIndex(r=>r.id===e.id),s>-1){const r=this._sessions[s];t&&(yield r.delete()),this._sessions.splice(s,1)}else console.warn("session delete failed, session is not exist.")})}clean(){this._sessions.forEach(e=>e.destroy()),this.sessions=[]}}class Fe{constructor(e,t={},s){m(this,"code");m(this,"description","");m(this,"loaded",!1);m(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}exports.AgentPlugin=Fe;exports.BotClient=De;exports.Session=D;exports.configure=N;
|
|
10
|
+
`+h:h;break;case"event":s.event=h;break;case"id":i(s.id=h);break;case"retry":const f=parseInt(h,10);isNaN(f)||e(s.retry=f);break}}}}function js(i,e){const t=new Uint8Array(i.length+e.length);return t.set(i),t.set(e,i.length),t}function yt(){return{data:"",event:"",id:"",retry:void 0}}const $e="text/event-stream",Ws=1e3,wt="last-event-id";function vt(i,l){var h=l,{signal:e,headers:t,onopen:s,onmessage:o,onclose:r,onerror:n,openWhenHidden:c,fetch:a}=h,d=at(h,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,g)=>{const _=v({},t);_.accept||(_.accept=$e);let m;function b(){m.abort(),document.hidden||x()}c||document.addEventListener("visibilitychange",b);let T=Ws,S=0;function E(){document.removeEventListener("visibilitychange",b),window.clearTimeout(S),m.abort()}e==null||e.addEventListener("abort",()=>{E(),f()});const C=a!=null?a:window.fetch,le=s!=null?s:Vs;function x(){return u(this,null,function*(){var L;m=new AbortController;try{const F=yield C(i,I(v({},d),{headers:_,signal:m.signal}));yield le(F),yield $s(F.body,Us(zs(R=>{R?_[wt]=R:delete _[wt]},R=>{T=R},o))),r==null||r(),E(),f()}catch(F){if(!m.signal.aborted)try{const R=(L=n==null?void 0:n(F))!=null?L:T;window.clearTimeout(S),S=window.setTimeout(x,R)}catch(R){E(),g(R)}}})}x()})}function Vs(i){const e=i.headers.get("content-type");if(!(e!=null&&e.startsWith($e)))throw new Error(`Expected content-type to be ${$e}, Actual: ${e}`)}const _t=new $("[DialogSession] ");class Ys extends st{constructor(t,s="",o,r,n,c){super(t,s,o,r,n,c);y(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>u(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,s,o,r,n,c){return u(this,null,function*(){const a={code:0,content:"",role:A.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=I(v({},o),{stream:exports.configuration.stream});vt(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:r,onopen(l){return l.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(l){if(!l.data.includes('{"code": ')){let f={};try{f=JSON.parse(l.data)}catch(_){}(f==null?void 0:f.mtype)==="search"?a.searchReference.push(f):a.content=a.content+l.data;const g={content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:s,messageTime:Ue(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(n==null?void 0:n.onmessage)&&n.onmessage(g)}const h=JSON.parse(l.data);if(a.reference=h.data.reference,a.searchReference=h.data.searchReference,a.messageTime=h.data.messageTime,a.messageId=h.data.messageId,a.llmModel=h.data.llmModel,a.content=h.data.content,a.code=h.code,h.code===200){const f={code:a.code,content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:s,messageTime:a.messageTime,isReplying:!0};n!=null&&n.onmessage&&n.onmessage(f)}else return n!=null&&n.onclose&&n.onclose(a),c&&c({code:a.code,message:a.message})},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const l={code:a.code,content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:s,messageTime:a.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};n!=null&&n.onclose&&n.onclose(l)}})})}postChatV3EventSource(t,s,o,r,n,c){return u(this,null,function*(){const a=this,d={code:0,content:"",role:A.IHistoryRole.Robot,sessionId:s,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},l=I(v({},o),{stream:exports.configuration.stream});vt(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${s}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(l),openWhenHidden:!0,signal:r,onopen(h){return h.ok&&n!=null&&n.onopen&&n.onopen(),Promise.resolve()},onmessage(h){if(!h.data&&!h.event&&!h.id&&!h.retry)return;let f={};try{f=JSON.parse(h.data)}catch(g){console.error("parse eventData to JSON failed. ",h.data)}if(f.code!==200)return d.index=-1,d.code=f.code,d.message=f.message,n!=null&&n.onmessage&&n.onmessage(d),c&&c({code:f.code,message:f.message});a.handleStreamAnswer(f,d),n!=null&&n.onmessage&&n.onmessage(d)},onerror(){n!=null&&n.onerror&&n.onerror()},onclose(){const h=I(v({},d),{isReplying:!1});n!=null&&n.onclose&&n.onclose(h)}})})}sendQuestion(t,s){return u(this,null,function*(){const{content:o,fileIds:r,oldMessageId:n,imageContent:c}=t,{stream:a,referenceFirst:d}=s;if(this.active||(yield this.activate()),this._id){const l=this.convertKnowledgesToChatFormat(this.knowledges);let h={content:o,fileIds:r,referenceFirst:d,oldMessageId:n,promptVariables:this.promptVariables.filter(f=>f.type===A.PromptVariableType.User).reduce((f,g)=>I(v({},f),{[g.key]:g.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===A.PromptVariableType.System).reduce((f,g)=>I(v({},f),{[g.key]:g.value}),{}),knowledges:l,enableTitleSummary:!0,imageContent:c};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,h,this.ctrl.signal,{onopen:()=>{_t.log("open",this.ctrl)},onmessage:f=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===A.ChatMessageRole.Robot?(g=v(v({},g),f),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(f),this.event.emit("message:content",f))},onclose:f=>u(this,null,function*(){this._stopAnswer||(_t.log(f,"onclose"),this.event.emit("answer:finish",f))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return u(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return u(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return u(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}convertKnowledgesToChatFormat(t){return t?t.map(s=>s!=null&&s.fileIds?{id:s.id,fileIds:s.fileIds}:s.id):[]}}const Gs="@glodon-aiot/bot-client-sdk",Qs="3.26.0-alpha.4",Xs="glodoncv",Ks="aiot bot client js sdk",Js="module",Zs=!1,en=["aiot","bot","bot client","sdk"],tn=["dist"],sn="./dist/es/index.mjs",nn="./dist/lib/index.js",rn="./dist/src/index.d.ts",an={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},on="MIT",cn={watch:"yarn build --watch",example:"node ./example/server.js",dev:"npm-run-all -p watch example",start:"vite",build:"tsc && vite build --mode prod && yarn build:cdn","build:npm":"tsc && vite build --mode prod","build:cdn":"tsc && vite build --mode prod --config ./vite.config.cdn.ts",preview:"vite preview",check:"yarn prettier --check .",write:"yarn prettier --write .",lint:"eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js",test:"vitest run","test:watch":"vitest"},dn={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@types/express":"^4","@types/identity-obj-proxy":"^3","@typescript-eslint/eslint-plugin":"^5.35.1","@typescript-eslint/parser":"^5.35.1","babel-loader":"^8.3.0",eslint:"^8.0.1","eslint-config-prettier":"^8.5.0","eslint-config-standard-with-typescript":"^22.0.0","eslint-plugin-import":"^2.25.2","eslint-plugin-n":"^15.0.0","eslint-plugin-promise":"^6.0.0","eslint-plugin-react":"^7.31.0","eslint-plugin-storybook":"^0.6.10",express:"4","http-proxy-middleware":"^3.0.0","identity-obj-proxy":"^3.0.0","npm-run-all":"^4.1.5",prettier:"2.7.1","rollup-plugin-visualizer":"^6.0.1","socket.io":"^4.7.5","ts-node":"^10.9.2",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0","vite-tsconfig-paths":"^5.1.4",vitest:"^0.34.6"},ln={access:"public",registry:"https://registry.npmjs.org/"},hn={"@glodon-aiot/apis":"^3.26.0-alpha.4",axios:"0.24.0",buffer:"^6.0.3",dayjs:"^1.11.13","js-base64":"^3.7.7","socket.io-client":"^4.7.5",uuid:"^11.1.0"},un={name:Gs,version:Qs,author:Xs,description:Ks,type:Js,sideEffects:Zs,keywords:en,files:tn,module:sn,main:nn,typings:rn,exports:an,license:on,scripts:cn,devDependencies:dn,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:ln,dependencies:hn},bt=new $("[BotClient] ");class fn{constructor(e,t,s=!0,o={analytics:{enabled:!1}}){y(this,"event",new et);y(this,"cvforceApi");y(this,"_applicationId");y(this,"_application",null);y(this,"_sessions",[]);y(this,"_activeSession");y(this,"_ready",!1);y(this,"_questionContextMaxLength",4e3);y(this,"_promptVariables",[]);y(this,"_localWorkspace");y(this,"_disconnectHost");if(this._token=e,this.lazyload=s,this.sdkConfigs=o,He(t),this._applicationId=Te(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{He(I(v({},t),{stream:t.stream===void 0?(r==null?void 0:r.type)===A.ApplicationTypes.Dialog||(r==null?void 0:r.type)===A.ApplicationTypes.Agent:t.stream})),this.event.emit("ready")})}setupLocalWorkspace(){var o,r;const e=(o=exports.configuration.builtinPlugins)==null?void 0:o.localFiles;if(!(e!=null&&e.enabled)){ut(void 0),qe();return}const t=[],s=(r=e.backend)!=null?r:"file-system-access";if(s!=="file-system-access"&&s!=="host-bridge")t.push(new Error(`[LocalFiles] 不支持的 backend:${e.backend}`));else{const n=Rs(exports.configuration.apiRoot,this.token,(c,a)=>bt.error(a));this._localWorkspace=new hi({applicationId:this._applicationId,config:e,store:li(),picker:s==="host-bridge"?null:void 0,transfer:tt(()=>this.cvforceApi,()=>n)}),ut(this._localWorkspace),s==="host-bridge"?this._disconnectHost=ks(this._localWorkspace):this._localWorkspace.restore()}t.push(...qe()),t.length&&Promise.resolve().then(()=>t.forEach(n=>this.event.emit("error",n)))}get localWorkspace(){return this._localWorkspace}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 u(this,null,function*(){var t,s,o,r,n;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(s=this.sdkConfigs.ui)==null?void 0:s.version,sdkVersion:un.version}).then(c=>(typeof c.arrange[0].thinkingModeOpen!="boolean"&&(c.arrange[0].thinkingModeOpen=!0),typeof c.arrange[0].thinkingTextOpen!="boolean"&&(c.arrange[0].thinkingTextOpen=!0),I(v({},c),{arrange:[I(v({},c.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&c.arrange[0].recommendQuestionOpen})]})));const e=(n=(r=(o=this._application)==null?void 0:o.arrange)==null?void 0:r[0])==null?void 0:n.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(c=>c.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type:A.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:A.PromptVariableType.System})]).then(([c,a])=>[...c,...a]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:ai(exports.configuration.apiRoot,this.token,(e,t)=>bt.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=Te(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,s,o,r){return u(this,null,function*(){const n=this;return new Promise((c,a)=>{const d=l=>u(this,null,function*(){if(l===A.ApplicationTypes.Agent)c(new Hs(e,t,s,o,r,n));else if(l===A.ApplicationTypes.Dialog)c(new Ys(e,t,s,o,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)})})}getArtifacts(e){return u(this,null,function*(){var r,n;this.checkReady();const t=e||((r=this._activeSession)==null?void 0:r.id);if(!t)throw new Error("session id is not defined");const s=this._sessions.find(c=>c.id===t);if(s)return s.getArtifacts();const o=yield this.cvforceApi.getSessionArtifacts(this._applicationId,t);return(n=o==null?void 0:o.artifacts)!=null?n:[]})}getSessions(e){return u(this,null,function*(){return new Promise((t,s)=>{const o=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>u(this,null,function*(){const n=[];for(const c of r){const a=this._sessions.find(d=>d.id===c.id);if(a)a.data=c,this._application?a.application=this._application:yield a.loadApplicationInfo(),n.push(a);else{const d=yield this.createSession(this.token,c.id,c,this.lazyload,this._application||void 0);n.push(d)}}if(e!=null&&e.pageSize){const c=[...this._sessions,...n],a=new Map;for(const d of c)a.set(d.id,d);return this.sessions=Array.from(a.values()),this.sessions}else return this.sessions=n,n}));if(this.ready){if(!this._application)throw Error("_application is null");t(o())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(o())},!0)})})}loadSession(e="",t){return u(this,null,function*(){this.checkReady();let s=this.sessions.find(o=>o.id===e);if(s||(s=yield this.createSession(this.token,e,t),this._sessions.push(s)),this._activeSession){if(this._activeSession===s)return s;this._activeSession.inactivate()}return s.id?(this._activeSession=s,yield s.activate()):s.addEventListener("data:loaded",()=>{this._activeSession!==s&&(s==null||s.activate(),this._activeSession=s)},!0),s})}reload(){return this.loadApplication().then(()=>u(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return u(this,null,function*(){yield this.reload();let t=this._sessions.find(s=>s.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,s="top_time desc, sort_status desc, updated_at desc"){return u(this,null,function*(){let o=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!o){console.warn("setTop session failed.");return}return yield o.setTop(t),this.getSessions({order:s})})}addEventListener(e,t,s=!1){if(typeof t!="function")throw Error("event listener is not a function");if(s){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return u(this,null,function*(){this.checkReady();let s=-1;if(typeof e=="string"?s=this._sessions.findIndex(o=>o.id===e):s=this._sessions.findIndex(o=>o.id===e.id),s>-1){const o=this._sessions[s];t&&(yield o.delete()),this._sessions.splice(s,1)}else console.warn("session delete failed, session is not exist.")})}clean(){var e;(e=this._disconnectHost)==null||e.call(this),this._disconnectHost=void 0,this._sessions.forEach(t=>t.destroy()),this.sessions=[]}}class pn{constructor(e,t={},s){y(this,"code");y(this,"description","");y(this,"loaded",!1);y(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}function It(){return{kind:"directory",children:new Map}}class gn{constructor(e={},t="memory-workspace"){y(this,"root",It());this.displayName=t,Object.entries(e).forEach(([s,o])=>this.seed(s,o))}seed(e,t="",s=Date.now()){const o=e.split("/").filter(Boolean);if(e.endsWith("/")){this.resolveDirectory(o,!0);return}const r=o.pop();if(!r)return;const n=this.resolveDirectory(o,!0),c=typeof t=="string"?new TextEncoder().encode(t):t;n.children.set(r,{kind:"file",data:c,lastModified:s})}resolveDirectory(e,t=!1){let s=this.root;for(const o of e){let r=s.children.get(o);if(!r){if(!t)throw P("NotFoundError");r=It(),s.children.set(o,r)}if(r.kind!=="directory")throw P("TypeMismatchError");s=r}return s}resolveNode(e){const t=G(e),s=t.pop();if(s===void 0)return this.root;const o=this.resolveDirectory(t).children.get(s);if(!o)throw P("NotFoundError");return o}stat(e){return u(this,null,function*(){var o;const t=this.resolveNode(e),s=(o=G(e).pop())!=null?o:this.displayName;return t.kind==="directory"?{name:s,kind:"directory"}:{name:s,kind:"file",size:t.data.byteLength,lastModified:t.lastModified}})}listEntries(e,t){return u(this,null,function*(){M(t);const s=this.resolveDirectory(G(e));return Array.from(s.children.entries()).map(([o,r])=>r.kind==="directory"?{name:o,kind:"directory"}:{name:o,kind:"file",size:r.data.byteLength,lastModified:r.lastModified})})}readFile(e){return u(this,null,function*(){const t=this.resolveNode(e);if(t.kind!=="file")throw P("TypeMismatchError");return new Blob([t.data])})}writeFile(o,r){return u(this,arguments,function*(e,t,s={}){const n=G(e),c=n.pop();if(!c)throw P("TypeMismatchError");const a=this.resolveDirectory(n,s.createDirectories),d=a.children.get(c);if((d==null?void 0:d.kind)==="directory")throw P("TypeMismatchError");const l=[];let h=0;try{for(var _=Y(Ze(t)),m,b,T;m=!(b=yield _.next()).done;m=!1){const S=b.value;M(s.signal),l.push(S),h+=S.byteLength}}catch(b){T=[b]}finally{try{m&&(b=_.return)&&(yield b.call(_))}finally{if(T)throw T[0]}}M(s.signal);const f=new Uint8Array(h);let g=0;l.forEach(S=>{f.set(S,g),g+=S.byteLength}),a.children.set(c,{kind:"file",data:f,lastModified:Date.now()})})}}exports.AgentPlugin=pn;exports.BINARY_SNIFF_BYTES=Ve;exports.BUILTIN_TOOLS_PLUGIN_CODE=ue;exports.BUILTIN_TOOLS_PLUGIN_CODES=je;exports.BUILTIN_TOOL_SCHEMAS=Ai;exports.BotClient=fn;exports.DEFAULT_DOWNLOAD_URL_ALLOWLIST=Nt;exports.DEFAULT_IGNORED_DIRECTORIES=Pt;exports.DEFAULT_IGNORED_FILE_PATTERNS=Dt;exports.DEFAULT_LIMITS=_e;exports.FileSystemAccessAdapter=di;exports.KiB=Lt;exports.LIST_DIRECTORY_DEFAULT_LIMIT=Rt;exports.LIST_DIRECTORY_MAX_LIMIT=kt;exports.LOCAL_FILES_FUNCTION_CODES=ze;exports.LOCAL_FILES_PLUGIN_CODES=At;exports.LOCAL_FILE_TOOL_SCHEMAS=Ge;exports.LOCAL_PYTHON_FUNCTION_CODE=oe;exports.LOCAL_PYTHON_PLUGIN_CODES=St;exports.LOCAL_PYTHON_TOOL_SCHEMA=Ht;exports.LocalWorkspace=hi;exports.MemoryWorkspaceAdapter=gn;exports.MiB=pe;exports.PYTHON_DEFAULT_TIMEOUT_MS=Et;exports.PYTHON_MAX_ARGS=Tt;exports.PYTHON_MAX_TIMEOUT_MS=vi;exports.SDK_SENSITIVE_BASELINE=zt;exports.SEARCH_DEFAULT_DEPTH=Mt;exports.SEARCH_FUNCTION_CODES=Bt;exports.SEARCH_MAX_DEPTH=We;exports.Session=st;exports.TEXT_SEARCH_MAX_CONTEXT_LINES=Ot;exports.TEXT_SEARCH_MAX_FILES=xt;exports.TEXT_SEARCH_MAX_FILE_BYTES=Ft;exports.TEXT_SEARCH_MAX_LINE_CHARS=be;exports.TRANSFER_FILE_SIZE_LIMIT_MB=Ct;exports.TRANSFER_FUNCTION_CODES=qt;exports.ToolCode=w;exports.ToolError=p;exports.WORKSPACE_GRANT_ID=Q;exports.WRITE_FUNCTION_CODES=_i;exports.configure=He;exports.createDefaultSessionFileTransfer=tt;exports.createIndexedDbStore=li;exports.createLocalFilesPlugin=ii;exports.createMemoryStore=it;exports.getDownloadUrlAllowlist=Ke;exports.getRegisteredLocalFilesPluginCode=bs;exports.getRegisteredLocalPythonPluginCode=Is;exports.isDownloadUrlAllowed=ji;exports.resolveLocalFilesPluginCode=ri;exports.toToolError=Le;
|
|
@@ -3,12 +3,21 @@ import { MCPConfig } from './Config';
|
|
|
3
3
|
import { default as Session, QuestionBody, QuestionConfig } from './Session';
|
|
4
4
|
import { default as BotClient } from './BotClient';
|
|
5
5
|
export default class AgentSession extends Session {
|
|
6
|
+
private readonly inflightCalls;
|
|
6
7
|
constructor(token: string, _id?: string, _data?: Partial<ISession>, lazyload?: boolean, application?: IApplication, client?: BotClient);
|
|
7
8
|
prepareConnection(): Promise<boolean>;
|
|
8
9
|
registerMcpFromClientConfig(): Promise<boolean>;
|
|
9
10
|
addMcpServers(mcpServers: MCPConfig): Promise<boolean>;
|
|
10
11
|
listMcpServers(): Promise<MCPConfig>;
|
|
11
12
|
sendQuestion(questionBody: QuestionBody, configs: QuestionConfig): Promise<false | undefined>;
|
|
13
|
+
/**
|
|
14
|
+
* 调用客户端插件:传入第三个参数 context(旧插件可忽略),结果最多回传一次,
|
|
15
|
+
* 停止回答或调用被取消后不再回传。
|
|
16
|
+
*/
|
|
17
|
+
private invokeClientPlugin;
|
|
18
|
+
private abortClientPluginCalls;
|
|
12
19
|
stopAnswer(): void;
|
|
20
|
+
inactivate(immediately?: boolean): boolean;
|
|
21
|
+
destroy(): string;
|
|
13
22
|
private convertKnowledgesToChatFormat;
|
|
14
23
|
}
|
package/dist/src/BotClient.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { default as Session } from './Session';
|
|
2
2
|
import { BotClientConfig } from './Config';
|
|
3
|
-
import {
|
|
3
|
+
import { LocalWorkspace } from './localFiles/workspace/LocalWorkspace';
|
|
4
|
+
import { IApplication, IPrompt, ISession, ISessionArtifact, ISessionPrompt, SessionQueryParams } from '@glodon-aiot/apis';
|
|
4
5
|
import { default as EventBus } from './EventBus';
|
|
5
|
-
export type ClientEventName = 'ready' | 'application:loaded';
|
|
6
|
+
export type ClientEventName = 'ready' | 'application:loaded' | 'error';
|
|
6
7
|
export interface SDKConfig {
|
|
7
8
|
analytics: {
|
|
8
9
|
enabled: boolean;
|
|
@@ -25,8 +26,13 @@ export default class BotClient {
|
|
|
25
26
|
private _ready?;
|
|
26
27
|
private _questionContextMaxLength?;
|
|
27
28
|
private _promptVariables?;
|
|
29
|
+
private _localWorkspace?;
|
|
30
|
+
private _disconnectHost?;
|
|
28
31
|
constructor(_token: string, //AIoT resource token
|
|
29
32
|
configs: BotClientConfig, lazyload?: boolean, sdkConfigs?: SDKConfig);
|
|
33
|
+
private setupLocalWorkspace;
|
|
34
|
+
/** 启用 builtinPlugins.localFiles 后可用;UI 与纯 SDK 集成共用此实例。 */
|
|
35
|
+
get localWorkspace(): LocalWorkspace | undefined;
|
|
30
36
|
private checkReady;
|
|
31
37
|
get ready(): boolean | undefined;
|
|
32
38
|
private set ready(value);
|
|
@@ -44,6 +50,10 @@ export default class BotClient {
|
|
|
44
50
|
get activeSession(): string;
|
|
45
51
|
set activeSession(sessionId: string);
|
|
46
52
|
private createSession;
|
|
53
|
+
/**
|
|
54
|
+
* 获取会话产出物。不传 sessionId 时取当前活跃会话。没有产出物时返回空数组。
|
|
55
|
+
*/
|
|
56
|
+
getArtifacts(sessionId?: string): Promise<ISessionArtifact[]>;
|
|
47
57
|
getSessions(queryParams?: SessionQueryParams): Promise<Session[]>;
|
|
48
58
|
loadSession(sessionId?: string, sessionParams?: Partial<ISession & {
|
|
49
59
|
promptVariables?: ISessionPrompt[];
|
package/dist/src/Config.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { BuiltinPluginsConfig, LocalFilesConfig, LocalPythonConfig } from './localFiles/types';
|
|
2
|
+
import { LocalWorkspace } from './localFiles/workspace/LocalWorkspace';
|
|
1
3
|
export interface McpServer {
|
|
2
4
|
type: 'sse';
|
|
3
5
|
url: string;
|
|
@@ -17,6 +19,8 @@ export interface BotClientConfig {
|
|
|
17
19
|
loadRelatedQuesions?: boolean;
|
|
18
20
|
mcp?: MCPConfig;
|
|
19
21
|
stream?: boolean;
|
|
22
|
+
/** SDK 内置插件:本地文件工具和 run_python,注册到同一个 pluginCode。 */
|
|
23
|
+
builtinPlugins?: BuiltinPluginsConfig;
|
|
20
24
|
}
|
|
21
25
|
export interface AgentPluginRegistor {
|
|
22
26
|
[key: string]: Function;
|
|
@@ -36,11 +40,29 @@ export declare let configuration: {
|
|
|
36
40
|
env: string;
|
|
37
41
|
apiRoot: string;
|
|
38
42
|
applicationId: string;
|
|
43
|
+
/** 最终生效的插件表 = 业务插件 + 内置插件,由 configure() 计算,不要直接修改。 */
|
|
39
44
|
plugins: AgentPluginMap;
|
|
45
|
+
/** 集成方传入的原始 plugins。 */
|
|
46
|
+
businessPlugins: AgentPluginMap;
|
|
47
|
+
builtinPlugins: BuiltinPluginsConfig | undefined;
|
|
40
48
|
mcp: (MCPConfig | undefined);
|
|
41
49
|
loadRelatedQuesions: boolean;
|
|
42
50
|
stream: boolean;
|
|
43
51
|
};
|
|
52
|
+
export declare function setActiveLocalWorkspace(workspace?: LocalWorkspace): void;
|
|
53
|
+
export declare function getActiveLocalWorkspace(): LocalWorkspace | undefined;
|
|
54
|
+
/** 当前已注册到 configuration.plugins 的内置文件工具编码;未注册时返回 undefined。 */
|
|
55
|
+
export declare function getRegisteredLocalFilesPluginCode(): string | undefined;
|
|
56
|
+
/** 当前已注册到 configuration.plugins 的 run_python 所在插件编码;未注册时返回 undefined。 */
|
|
57
|
+
export declare function getRegisteredLocalPythonPluginCode(): string | undefined;
|
|
58
|
+
/** 显式配置优先,其次按 env 取默认值;都没有时返回 undefined。 */
|
|
59
|
+
export declare function resolveLocalFilesPluginCode(config: LocalFilesConfig | undefined, env: string): string;
|
|
60
|
+
/** 显式配置优先,其次跟随文件工具编码,最后按 env 取默认值。 */
|
|
61
|
+
export declare function resolveLocalPythonPluginCode(config: LocalPythonConfig | undefined, env: string, filesPluginCode?: string): string;
|
|
62
|
+
/**
|
|
63
|
+
* 重新计算 configuration.plugins,返回本次新出现的问题(相同问题只报告一次)。
|
|
64
|
+
*/
|
|
65
|
+
export declare function refreshBuiltinPlugins(): Error[];
|
|
44
66
|
/**
|
|
45
67
|
* 配置SDK,可以在SDK被使用前被调用,该方法被调用后将改变是否debug模式、是否测试环境等基本配置
|
|
46
68
|
* @param param {debug?: boolean; env?: 'dev' | 'test' | 'prod';}
|
package/dist/src/Session.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ChatMessageRole, IApplication, IChatMessage, ICommentParam, ISession, ISessionPrompt, CVForceApi, ChatHistoryParams, IKnowledge } from '@glodon-aiot/apis';
|
|
1
|
+
import { ChatMessageRole, IApplication, IChatMessage, ICommentParam, ISession, ISessionArtifact, ISessionPrompt, CVForceApi, ChatHistoryParams, IKnowledge } from '@glodon-aiot/apis';
|
|
2
2
|
import { MCPConfig } from './Config';
|
|
3
3
|
import { Socket } from 'socket.io-client';
|
|
4
4
|
import { default as EventBus } from './EventBus';
|
|
@@ -212,6 +212,10 @@ export default abstract class Session {
|
|
|
212
212
|
* @param params - 评论参数,包含评论相关的信息,如消息 ID 等
|
|
213
213
|
* @returns 返回调用 API 提交评论后的响应结果
|
|
214
214
|
*/
|
|
215
|
+
/**
|
|
216
|
+
* 获取当前会话的产出物。没有产出物时返回空数组。
|
|
217
|
+
*/
|
|
218
|
+
getArtifacts(): Promise<ISessionArtifact[]>;
|
|
215
219
|
postMessageComment(params: ICommentParam): Promise<string>;
|
|
216
220
|
/**
|
|
217
221
|
* 清除当前会话的上下文信息
|