@glodon-aiot/bot-client-sdk 3.26.0-alpha.24 → 3.26.0-alpha.26

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.
@@ -1,4 +1,4 @@
1
- const e = "@glodon-aiot/bot-client-sdk", s = "3.26.0-alpha.24", t = "glodoncv", i = "aiot bot client js sdk", n = "module", g = !1, o = [
1
+ const e = "@glodon-aiot/bot-client-sdk", s = "3.26.0-alpha.26", t = "glodoncv", i = "aiot bot client js sdk", n = "module", g = !1, o = [
2
2
  "aiot",
3
3
  "bot",
4
4
  "bot client",
@@ -68,7 +68,7 @@ const e = "@glodon-aiot/bot-client-sdk", s = "3.26.0-alpha.24", t = "glodoncv",
68
68
  access: "public",
69
69
  registry: "https://registry.npmjs.org/"
70
70
  }, y = {
71
- "@glodon-aiot/apis": "^3.26.0-alpha.24",
71
+ "@glodon-aiot/apis": "^3.26.0-alpha.26",
72
72
  axios: "0.24.0",
73
73
  buffer: "^6.0.3",
74
74
  dayjs: "^1.11.13",
package/dist/lib/index.js CHANGED
@@ -371,7 +371,7 @@ ${JSON.stringify(n.headers)}`}function Io(n){const e=n.trim();if(!e)return{};if(
371
371
  `):JSON.stringify(n)}function xo(n){return d(this,null,function*(){if(!(n.headers.get("content-type")||"").includes("text/event-stream")||!n.body)return n.text();const t=n.body.getReader(),i=new TextDecoder;let s="";try{for(;s.length<2e6;){const{done:r,value:o}=yield t.read();if(r)break;s+=i.decode(o,{stream:!0});const a=s.split(/\n\n/).filter(c=>/^\s*data:/m.test(c));if(a.length>0)return a[a.length-1]}return s}finally{yield t.cancel().catch(()=>{})}})}function it(n,e,t,i,s){return d(this,null,function*(){const r=S(w({},n.headers),{"content-type":"application/json",accept:"application/json, text/event-stream"});t!=null&&t.id&&(r["mcp-session-id"]=t.id),t!=null&&t.protocol&&(r["mcp-protocol-version"]=t.protocol);const o=yield s(n.url,{method:"POST",headers:r,body:JSON.stringify(e),signal:So(i)}),a=yield xo(o);if(!o.ok)throw new Error(`MCP HTTP ${o.status}: ${a.slice(0,300)}`);const c=Io(a),l=o.headers.get("mcp-session-id");return t&&l&&(t.id=l),c})}function st(n){const e=n.error;if(!e||typeof e!="object")return;const t=e.message;return typeof t=="string"&&t?t:"MCP 调用失败"}function Ao(n){const e=n instanceof Error?n.message:String(n);return/session/i.test(e)||e.includes("MCP HTTP 404")}function Ye(n,e,t){return d(this,null,function*(){const i=Vi(n),s=nt.get(i);if(s!=null&&s.id)return s;const r={protocol:"2024-11-05",nextId:1},o=yield it(n,{jsonrpc:"2.0",id:r.nextId,method:"initialize",params:{protocolVersion:r.protocol,capabilities:{},clientInfo:{name:"bot-client-sdk",version:"1.0.0"}}},r,e,t);r.nextId+=1;const a=st(o);if(a)throw new Error(a);const c=o.result;if(c&&typeof c=="object"){const l=c.protocolVersion;typeof l=="string"&&l&&(r.protocol=l)}return yield it(n,{jsonrpc:"2.0",method:"notifications/initialized"},r,e,t),nt.set(i,r),r})}function To(t){return d(this,arguments,function*(n,e=fetch){var a;const i=yield Ye(n,void 0,e),s=yield it(n,{jsonrpc:"2.0",id:i.nextId,method:"tools/list",params:{}},i,void 0,e);i.nextId+=1;const r=st(s);if(r)throw new Error(r);const o=s.result;return((a=o==null?void 0:o.tools)!=null?a:[]).filter(c=>c.name).map(c=>({name:c.name,description:c.description||"",inputSchema:c.inputSchema||{type:"object",properties:{}}}))})}function Ro(r,o,a,c){return d(this,arguments,function*(n,e,t,i,s=fetch){const l=Vi(n);let h=yield Ye(n,i,s);const u=()=>it(n,{jsonrpc:"2.0",id:h.nextId,method:"tools/call",params:{name:e,arguments:t&&typeof t=="object"?t:{}}},h,i,s);let f;try{f=yield u(),h.nextId+=1}catch(b){if(!Ao(b))throw b;nt.delete(l),h=yield Ye(n,i,s),f=yield u(),h.nextId+=1}let g=st(f);if(g&&/session/i.test(g)&&(nt.delete(l),h=yield Ye(n,i,s),f=yield u(),h.nextId+=1,g=st(f)),g)throw new Error(g);return ko(f.result)})}const we=new U("[LocalMcp] ",!0);function Lo(n){const e=n==null?void 0:n.mcps;return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"&&t.runtime==="local"&&t.id):[]}function Mo(n,e,t){return n==null||n.includes(e)?!0:!!t&&n.includes(t)}function Co(n){if(!n||typeof n!="object")return{};const e={};for(const[t,i]of Object.entries(n))typeof i=="string"&&(e[t]=i);return e}function Fo(n){var o,a;if(!n||typeof n!="object")return null;const e=n;if(typeof e.code=="number"&&e.code!==200)return null;const t=e.data&&typeof e.data=="object"?e.data:e,i=typeof t.code=="string"?t.code:"",s=i?(o=t.mcpServers)==null?void 0:o[i]:void 0,r=typeof(s==null?void 0:s.url)=="string"?s.url:void 0;return{code:i,deployType:typeof((a=t.deployConfig)==null?void 0:a.type)=="string"?t.deployConfig.type:void 0,url:r,headers:Co(s==null?void 0:s.headers)}}function No(s,r,o){return d(this,arguments,function*(n,e,t,i=fetch){const a=n.replace(/\/$/,""),c=e.startsWith("Bearer ")?e:`Bearer ${e}`,l=yield i(`${a}/mcpmgr/v1/mcpserver/${encodeURIComponent(t)}`,{headers:{Authorization:c}}),h=yield l.json().catch(()=>null);if(!l.ok)throw new Error(`MCP 详情 HTTP ${l.status}`);const u=Fo(h);if(!u)throw new Error("MCP 详情不可用");return u})}function Oo(n,e){return(t,i,s)=>{const r=Dr(n);if(!r){i({code:500,message:"缺少 MCP 地址"});return}Ro(r,n,t,s==null?void 0:s.signal,e).then(o=>i({code:0,message:"ok",data:o})).catch(o=>{i({code:500,message:o instanceof Error?o.message:String(o)})})}}function Po(n){return d(this,null,function*(){var a,c;const e=(a=n.fetchImpl)!=null?a:fetch,t=n.initMcp?Object.keys((c=n.initMcp.mcpServers)!=null?c:{}):null,i=Lo(n.arrange);if(!i.length){we.log("编排里没有 runtime=local 的 MCP,不发送 register_client_mcp_tools"),Pn([]),Pe();return}const s=yield Promise.all(i.map(l=>d(this,null,function*(){const h=l.id;try{const u=yield No(n.apiRoot,n.token,h,e);if(!Mo(t,h,u.code))return null;if(u.deployType!=="streamableHttp"||!u.url||!u.code)return we.log("skip local mcp",h),null;const f={code:u.code,url:u.url,headers:u.headers},g=yield To(f,e);return g.length?{code:u.code,url:u.url,binding:f,tools:g}:null}catch(u){return we.error("local mcp failed",h,u instanceof Error?u.message:String(u)),null}})));if(n.isCurrent&&!n.isCurrent())return;const r={},o=[];for(const l of s)if(l){r[l.code]={type:"streamableHttp",url:l.url,tools:l.tools};for(const h of l.tools)o.push({name:h.name,binding:l.binding,handler:Oo(h.name,e)})}if(Pn(o),Pe(),!Object.keys(r).length||!n.socket){we.log("没有可注册的本地 MCP 工具,不发送 register_client_mcp_tools");return}we.log("发送 register_client_mcp_tools",Object.entries(r).map(([l,h])=>`${l}: ${h.tools.map(u=>u.name).join(", ")}`).join("; ")),n.socket.emit("register_client_mcp_tools",{mcpServers:r},l=>{const h=l&&typeof l=="object"?l.code:void 0;typeof h=="number"&&h!==200&&we.error("register_client_mcp_tools",h)})})}const H=new U("[AgentSession] ");function zn(n){if(typeof n!="string")return n;const e=n.trim();if(e)try{return JSON.parse(e)}catch(t){return n}}function Wn(n){return n==null||n===""||typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function $o(n,e){const t=zn(n==null?void 0:n.query);if(!Wn(t))return t;const i=zn(e);return Wn(i)&&t!=null?t:i}class Do extends an{constructor(t,i="",s,r,o,a){super(t,i,s,r,o,a);y(this,"inflightCalls",new Set);y(this,"localMcpTicket",0)}prepareConnection(){return new Promise(t=>d(this,null,function*(){this.socket&&t(!0);const i={version:"1.0",stream:JSON.stringify(exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?be.Debug:be.Normal},s=new URL(exports.configuration.apiRoot),r=yield rs.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:i,transports:["websocket"]});r.on("connect",()=>{H.log("socket:connect"),this.event.emit("socket:connect"),r.emit("init")}),r.on("disconnect",()=>{H.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),r.on("ready",o=>{if(o.code===200){H.log("ready");const a=exports.configuration.debug?be.Debug:be.Normal;a===be.Debug&&o.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),this.registerLocalMcp(),t(!0)}else{this._ready&&(this._ready=!1);const a=new Error(Ne.SocketConnectionFailed);H.error("error",a),this.event.emit("error",a),t(!1)}}),r.on("action",(o,a)=>d(this,null,function*(){var v;if(this._stopAnswer||!this.id)return;const{type:c,data:{runnerIsClient:l,pluginCode:h,funcCode:u,parameters:f,requestBody:g}}=o,b=this.messages[this.messages.length-1];if(!b.messageId)b.actions||(b.actions=[]),b.actions[o.data.step-1]||(b.actions[o.data.step-1]=[]),b.actions[o.data.step-1].push(o),this.event.emit("message:action",{messageId:b.messageId,action:o}),this.event.emit("message:updated",b);else{const _={messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[o]],comment:{isAgree:0},isReplying:!0};this.pushMessage(_),this.event.emit("message:action",{messageId:_.messageId,action:o})}if(this.inactivating){const _=new Error(Ne.Inactive);H.warn("error",_),this.event.emit("error",_)}else if(c==="FUNCTION_CALL"&&l){H.log(`calling function ${u} of plugin ${h} with argument:
372
372
  ${JSON.stringify(f)}`);const _=(v=exports.configuration.plugins)==null?void 0:v[h];if(!_){a({code:404,message:"没有找到插件。"});return}const A=_[u];if(typeof A!="function"){a({code:404,message:"没有找到插件方法。"});return}const I=$o(f,g);this.invokeClientPlugin(A,I,a,{requestId:o.requestId,pluginCode:h,functionCode:u})}})),r.on("answer",o=>{if(!this._stopAnswer)if(o.data.code!==200&&(o.data.index=-1),o.data.stream||o.data.stream===void 0){let a=this.messages[this.messages.length-1];if(a&&a.role===x.ChatMessageRole.Robot)this.handleStreamAnswer(o.data,a),this.messages[this.messages.length-1]=a,this.event.emit("message:content",a),this.event.emit("message:updated",a),a.index===-1&&(a.isReplying=!1,this.event.emit("answer:finish",a));else{const c={content:"",role:x.ChatMessageRole.Robot,reference:[],searchReference:[],messageId:"",sessionId:this.id,messageTime:Dt(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""};this.handleStreamAnswer(o.data,c),this.pushMessage(c),this.event.emit("message:content",c),c.index===-1&&(c.isReplying=!1,this.event.emit("answer:finish",c))}}else if(o.data.updateSession&&this.data&&(this.data=w(w({},this.data),o.data.updateSession),this.event.emit("data:updated",this.data)),o.data.index===-1){let a=this.messages[this.messages.length-1];if(a&&!a.messageId)a=w(w({},a),o.data),this.event.emit("message:content",a),this.event.emit("message:updated",a),this.event.emit("answer:finish",a);else{const c=w({messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.data);this.event.emit("message:content",c),this.pushMessage(c),this.event.emit("answer:finish",c)}}else{let a=this.messages[this.messages.length-1];a&&!a.messageId?(a=w(w({},a),o.data),this.messages[this.messages.length-1]=a,this.event.emit("message:content",a),this.event.emit("message:updated",a)):(this.pushMessage(w({messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.data)),this.event.emit("message:content",o.data))}}),r.on("reference",o=>d(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const f=new Error(Ne.IdUndefined);H.error(f),this.event.emit("error",f),this.frozen=!1;return}const{type:a,data:c,requestId:l}=o,h=this.messages.findIndex(f=>f.messageId===l&&f.role===x.ChatMessageRole.User);if(h<0)return;const u=h+1;if(u>=this.messages.length){const f={messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0};this.pushMessage(f)}a==="KG"?(this.messages[u]=S(w({},this.messages[u]),{reference:c.knowledgeReference}),yield this.fillMessageReference(this.messages[u]),this.event.emit("message:reference",c.knowledgeReference),this.event.emit("message:updated",this.messages[u])):a==="WEB_SEARCH"&&(this.messages[u]=S(w({},this.messages[u]),{searchReference:c.knowledgeReference}),this.event.emit("message:searchreference",c.searchReference),this.event.emit("message:updated",this.messages[u]))})),this.socket=r,r.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((t,i)=>{if(!this.socket){i("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,s=>{s.code===200?(Object.keys(s.data).forEach(r=>{s.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",s.data[r])}),t(!0)):(console.error("MCP Server 注册失败。",s),i(s))})}):Promise.resolve(!0)}registerLocalMcp(){var s,r;const t=this.socket;if(!t)return;const i=++this.localMcpTicket;Po({arrange:(r=(s=this.application)==null?void 0:s.arrange)==null?void 0:r[0],initMcp:exports.configuration.mcp,apiRoot:exports.configuration.apiRoot,token:this.token,socket:t,isCurrent:()=>i===this.localMcpTicket}).catch(o=>{H.error("local mcp",o instanceof Error?o.message:String(o))})}addMcpServers(t){return d(this,null,function*(){return this.ready?this.socket?new Promise((i,s)=>{this.socket&&this.socket.emit("add_mcp_servers",t,r=>{r.code===200?(Object.keys(r.data).forEach(o=>{r.data[o].code!==200&&console.error(o,"MCP Server 注册失败。",r.data[o])}),i(!0)):(console.error("MCP Server 注册失败。",r),s(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 d(this,null,function*(){return this.ready?this.socket?new Promise((t,i)=>{this.socket&&this.socket.emit("list_mcp_servers",s=>{s.code===200?t(s.data):i(s)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(t,i){return d(this,null,function*(){var r,o,a;this.convertKnowledgesToChatFormat(this.knowledges);let s=S(w({},t),{promptVariables:this.promptVariables.filter(c=>c.type===x.PromptVariableType.User).reduce((c,l)=>S(w({},c),{[l.key]:l.value}),{}),systemPromptVariables:this.promptVariables.filter(c=>c.type===x.PromptVariableType.System).reduce((c,l)=>S(w({},c),{[l.key]:l.value}),{}),knowledges:(r=this.knowledges)==null?void 0:r.map(c=>c.id),enableTitleSummary:this.resolveEnableTitleSummary()});if(!this.active){if(yield this.activate(),!this.socket){const c=new Error(Ne.SocketConnectionFailed);return H.warn("error",c),this.event.emit("error",c),!1}(o=this.socket)==null||o.emit("question",s);return}(a=this.socket)==null||a.emit("question",s)})}invokeClientPlugin(t,i,s,r){const o=new AbortController;this.inflightCalls.add(o);let a=!1;const c=(...h)=>{a||(a=!0,this.inflightCalls.delete(o),!(this._stopAnswer||o.signal.aborted)&&s(...h))},l={requestId:r.requestId||ne.v4(),applicationId:this._applicationId,sessionId:this.id,pluginCode:r.pluginCode,functionCode:r.functionCode,signal:o.signal};try{const h=t(i,c,l);h&&typeof h.catch=="function"&&h.catch(u=>{H.error("client plugin failed",u),c({code:500,message:"客户端插件执行失败。"})})}catch(h){H.error("client plugin failed",h),c({code:500,message:"客户端插件执行失败。"})}}abortClientPluginCalls(){const t=Array.from(this.inflightCalls);this.inflightCalls.clear(),t.forEach(i=>i.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(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}function Bo(n,e){return d(this,null,function*(){const t=n.getReader();let i;for(;!(i=yield t.read()).done;)e(i.value)})}function jo(n){let e,t,i,s=!1,r;return function(a){e===void 0?(e=a,t=0,i=-1,r=!1):e=Ho(e,a);const c=e.length;let l=0;for(;t<c;){s&&(e[t]===10&&(l=++t),s=!1);let h=-1;for(;t<c&&h===-1;++t)switch(e[t]){case 58:i===-1&&(i=t-l);break;case 13:s=!1,t+4<c&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(r=!0);case 10:h=t;break}if(h===-1)break;n(e.subarray(l,h),i,r),l=t,i=-1,r=!1}l===c?e=void 0:l!==0&&(e=e.subarray(l),t-=l)}}function Uo(n,e,t){let i=Vn();const s=new TextDecoder;return function(o,a,c){if(o.length===0)t==null||t(i),i=Vn();else if(a>0){const l=s.decode(o.subarray(0,a)),h=a+(o[a+1]===32?2:1);let u=s.decode(o.subarray(h));switch(c&&(u+=`
373
373
  `),l){case"data":i.data=i.data?i.data+`
374
- `+u:u;break;case"event":i.event=u;break;case"id":n(i.id=u);break;case"retry":const f=parseInt(u,10);isNaN(f)||e(i.retry=f);break}}}}function Ho(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function Vn(){return{data:"",event:"",id:"",retry:void 0}}const $t="text/event-stream",qo=1e3,Gn="last-event-id";function Xn(n,h){var u=h,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:a,fetch:c}=u,l=un(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,g)=>{const b=w({},t);b.accept||(b.accept=$t);let v;function _(){v.abort(),document.hidden||P()}a||document.addEventListener("visibilitychange",_);let A=qo,I=0;function T(){document.removeEventListener("visibilitychange",_),window.clearTimeout(I),v.abort()}e==null||e.addEventListener("abort",()=>{T(),f()});const R=c!=null?c:window.fetch,Z=i!=null?i:zo;function P(){return d(this,null,function*(){var k;v=new AbortController;try{const C=yield R(n,S(w({},l),{headers:b,signal:v.signal}));yield Z(C),yield Bo(C.body,jo(Uo(N=>{N?b[Gn]=N:delete b[Gn]},N=>{A=N},s))),r==null||r(),T(),f()}catch(C){if(!v.signal.aborted)try{const N=(k=o==null?void 0:o(C))!=null?k:A;window.clearTimeout(I),I=window.setTimeout(P,N)}catch(N){T(),g(N)}}})}P()})}function zo(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith($t)))throw new Error(`Expected content-type to be ${$t}, Actual: ${e}`)}const Yn=new U("[DialogSession] ");class Wo extends an{constructor(t,i="",s,r,o,a){super(t,i,s,r,o,a);y(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>d(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c={code:0,content:"",role:x.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},l=S(w({},s),{stream:exports.configuration.stream});Xn(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(l),openWhenHidden:!0,signal:r,onopen(h){return h.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(h){if(!h.data.includes('{"code": ')){let f={};try{f=JSON.parse(h.data)}catch(b){}(f==null?void 0:f.mtype)==="search"?c.searchReference.push(f):c.content=c.content+h.data;const g={content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:Dt(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(o==null?void 0:o.onmessage)&&o.onmessage(g)}const u=JSON.parse(h.data);if(c.reference=u.data.reference,c.searchReference=u.data.searchReference,c.messageTime=u.data.messageTime,c.messageId=u.data.messageId,c.llmModel=u.data.llmModel,c.content=u.data.content,c.code=u.code,u.code===200){const f={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,isReplying:!0};o!=null&&o.onmessage&&o.onmessage(f)}else return o!=null&&o.onclose&&o.onclose(c),a&&a({code:c.code,message:c.message})},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const h={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};o!=null&&o.onclose&&o.onclose(h)}})})}postChatV3EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c=this,l={code:0,content:"",role:x.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},h=S(w({},s),{stream:exports.configuration.stream});Xn(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(h),openWhenHidden:!0,signal:r,onopen(u){return u.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(u){if(!u.data&&!u.event&&!u.id&&!u.retry)return;let f={};try{f=JSON.parse(u.data)}catch(g){console.error("parse eventData to JSON failed. ",u.data)}if(f.code!==200)return l.index=-1,l.code=f.code,l.message=f.message,o!=null&&o.onmessage&&o.onmessage(l),a&&a({code:f.code,message:f.message});c.handleStreamAnswer(f,l),o!=null&&o.onmessage&&o.onmessage(l)},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const u=S(w({},l),{isReplying:!1});o!=null&&o.onclose&&o.onclose(u)}})})}sendQuestion(t,i){return d(this,null,function*(){const{content:s,fileIds:r,oldMessageId:o,imageContent:a}=t,{stream:c,referenceFirst:l}=i;if(this.active||(yield this.activate()),this._id){const h=this.convertKnowledgesToChatFormat(this.knowledges);let u={content:s,fileIds:r,referenceFirst:l,oldMessageId:o,promptVariables:this.promptVariables.filter(f=>f.type===x.PromptVariableType.User).reduce((f,g)=>S(w({},f),{[g.key]:g.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===x.PromptVariableType.System).reduce((f,g)=>S(w({},f),{[g.key]:g.value}),{}),knowledges:h,enableTitleSummary:this.resolveEnableTitleSummary(),imageContent:a};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,u,this.ctrl.signal,{onopen:()=>{Yn.log("open",this.ctrl)},onmessage:f=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===x.ChatMessageRole.Robot?(g=w(w({},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=>d(this,null,function*(){this._stopAnswer||(Yn.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 d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}const Vo="@glodon-aiot/bot-client-sdk",Go="3.26.0-alpha.24",Xo="glodoncv",Yo="aiot bot client js sdk",Jo="module",Ko=!1,Qo=["aiot","bot","bot client","sdk"],Zo=["dist"],ea="./dist/es/index.mjs",ta="./dist/lib/index.js",na="./dist/src/index.d.ts",ia={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},sa="MIT",ra={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","build:just-bash":"node scripts/build-just-bash.mjs","upload:just-bash":"node scripts/build-just-bash.mjs && node scripts/upload-cdn-libs.cjs just-bash","build:pyodide":"node scripts/build-pyodide.mjs","upload:pyodide":"node scripts/build-pyodide.mjs && node scripts/upload-cdn-libs.cjs pyodide",test:"vitest run","test:watch":"vitest"},oa={"@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","just-bash":"3.6.0","npm-run-all":"^4.1.5",prettier:"2.7.1",pyodide:"314.0.7","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"},aa={access:"public",registry:"https://registry.npmjs.org/"},ca={"@glodon-aiot/apis":"^3.26.0-alpha.24",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"},la={name:Vo,version:Go,author:Xo,description:Yo,type:Jo,sideEffects:Ko,keywords:Qo,files:Zo,module:ea,main:ta,typings:na,exports:ia,license:sa,scripts:ra,devDependencies:oa,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:aa,dependencies:ca},Jn=new U("[BotClient] ");class da{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){y(this,"event",new nn);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=i,this.sdkConfigs=s,Nt(t,{refreshBuiltinPlugins:!1}),this._applicationId=tt(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{Nt(S(w({},t),{stream:t.stream===void 0?(r==null?void 0:r.type)===x.ApplicationTypes.Dialog||(r==null?void 0:r.type)===x.ApplicationTypes.Agent:t.stream})),this.event.emit("ready")})}setupLocalWorkspace(){var s,r;const e=(s=exports.configuration.builtinPlugins)==null?void 0:s.localFiles;if(!(e!=null&&e.enabled)){$n(void 0),Pe();return}const t=[],i=(r=e.backend)!=null?r:"file-system-access";if(i!=="file-system-access"&&i!=="host-bridge")t.push(new Error(`[LocalFiles] 不支持的 backend:${e.backend}`));else{const o=Vr(exports.configuration.apiRoot,this.token,(a,c)=>Jn.error(c));this._localWorkspace=new Wi({applicationId:this._applicationId,config:e,store:qi(),picker:i==="host-bridge"?null:void 0,transfer:rn(()=>this.cvforceApi,()=>o)}),$n(this._localWorkspace),this._localWorkspace.platformSkills=new Jr({applicationId:()=>this._applicationId,getToken:()=>this.token,getSkills:()=>{var a,c,l,h;return(h=(l=(c=(a=this._application)==null?void 0:a.arrange)==null?void 0:c[0])==null?void 0:l.skills)!=null?h:[]},apiRoot:()=>exports.configuration.apiRoot,getSandbox:()=>{var c;const a=(c=this._localWorkspace)==null?void 0:c.adapter;return a instanceof $e?a.sandbox:void 0}}),i==="host-bridge"?this._disconnectHost=Qr(this._localWorkspace):this._localWorkspace.restore()}t.push(...Pe()),t.length&&Promise.resolve().then(()=>t.forEach(o=>this.event.emit("error",o)))}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 d(this,null,function*(){var t,i,s,r,o;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(i=this.sdkConfigs.ui)==null?void 0:i.version,sdkVersion:la.version}).then(a=>(typeof a.arrange[0].thinkingModeOpen!="boolean"&&(a.arrange[0].thinkingModeOpen=!0),typeof a.arrange[0].thinkingTextOpen!="boolean"&&(a.arrange[0].thinkingTextOpen=!0),S(w({},a),{arrange:[S(w({},a.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&a.arrange[0].recommendQuestionOpen})]})));const e=(o=(r=(s=this._application)==null?void 0:s.arrange)==null?void 0:r[0])==null?void 0:o.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(a=>a.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type:x.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:x.PromptVariableType.System})]).then(([a,c])=>[...a,...c]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:Pi(exports.configuration.apiRoot,this.token,(e,t)=>Jn.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=tt(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,i,s,r){return d(this,null,function*(){const o=this;return new Promise((a,c)=>{const l=h=>d(this,null,function*(){if(h===x.ApplicationTypes.Agent)a(new Do(e,t,i,s,r,o));else if(h===x.ApplicationTypes.Dialog)a(new Wo(e,t,i,s,r,o));else throw Error(`不支持的应用类型:${h}`)});if(this.ready){if(!this._application)throw Error("client is not ready");l(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");l(this._application.type)},!0)})})}getArtifacts(e){return d(this,null,function*(){var r,o;this.checkReady();const t=e||((r=this._activeSession)==null?void 0:r.id);if(!t)throw new Error("session id is not defined");const i=this._sessions.find(a=>a.id===t);if(i)return i.getArtifacts();const s=yield this.cvforceApi.getSessionArtifacts(this._applicationId,t);return(o=s==null?void 0:s.artifacts)!=null?o:[]})}getSessions(e){return d(this,null,function*(){return new Promise((t,i)=>{const s=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>d(this,null,function*(){const o=[];for(const a of r){const c=this._sessions.find(l=>l.id===a.id);if(c)c.data=a,this._application?c.application=this._application:yield c.loadApplicationInfo(),o.push(c);else{const l=yield this.createSession(this.token,a.id,a,this.lazyload,this._application||void 0);o.push(l)}}if(e!=null&&e.pageSize){const a=[...this._sessions,...o],c=new Map;for(const l of a)c.set(l.id,l);return this.sessions=Array.from(c.values()),this.sessions}else return this.sessions=o,o}));if(this.ready){if(!this._application)throw Error("_application is null");t(s())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(s())},!0)})})}loadSession(e="",t){return d(this,null,function*(){var s,r;this.checkReady(),(r=(s=this._localWorkspace)==null?void 0:s.platformSkills)==null||r.sync();let i=this.sessions.find(o=>o.id===e);if(i||(i=yield this.createSession(this.token,e,t),this._sessions.push(i)),this._activeSession){if(this._activeSession===i)return i;this._activeSession.inactivate()}return i.id?(this._activeSession=i,yield i.activate()):i.addEventListener("data:loaded",()=>{this._activeSession!==i&&(i==null||i.activate(),this._activeSession=i)},!0),i})}reload(){return this.loadApplication().then(()=>d(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return d(this,null,function*(){yield this.reload();let t=this._sessions.find(i=>i.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,i="top_time desc, sort_status desc, updated_at desc"){return d(this,null,function*(){let s=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!s){console.warn("setTop session failed.");return}return yield s.setTop(t),this.getSessions({order:i})})}addEventListener(e,t,i=!1){if(typeof t!="function")throw Error("event listener is not a function");if(i){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return d(this,null,function*(){this.checkReady();let i=-1;if(typeof e=="string"?i=this._sessions.findIndex(s=>s.id===e):i=this._sessions.findIndex(s=>s.id===e.id),i>-1){const s=this._sessions[i];t&&(yield s.delete()),this._sessions.splice(i,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 ha{constructor(e,t={},i){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(){}}const G="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",X={type:"string",enum:[Ie],description:`工作区 ID。省略时按 ${Ie} 处理,传其他值会被拒绝。`},Y=n=>({type:"string",description:`${n}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),St={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},Gi={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${G}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:X,path:Y('要列出的目录,省略或传 "." 表示工作区根目录。'),offset:{type:"integer",minimum:0,description:"分页起始位置,默认 0。"},limit:{type:"integer",minimum:1,maximum:1e3,description:"每页条数,默认 200。"}}}},read_file:{functionCode:"read_file",name:"读取本地文件",description:`${G}按行读取文本文件,单次最多返回 1 MiB,超出部分会被截断(truncated: true)。返回内容的 hash 可用于后续修改。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:X,path:Y("要读取的文件。"),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:`${G}返回文件或目录的类型、大小、修改时间,可选返回 hash。不返回文件内容。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:X,path:Y("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${G}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:X,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:Y("搜索起点目录,默认工作区根目录。"),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:`${G}在指定文件或目录(递归)中搜索普通文本(不支持正则),返回所在文件、行号与该行内容。必须指定 path,不能搜索整个文件夹。`,parameters:{type:"object",required:["grantId","path","query"],properties:{grantId:X,path:Y("搜索范围,可以是文件或目录。"),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:`${G}以查找替换的方式修改 UTF-8 文本文件。每条修改的 oldText 必须在文件中唯一出现(或设置 replaceAll)。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","expectedHash","edits"],properties:{grantId:X,path:Y("要修改的文件。"),expectedHash:St,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:`${G}新建文件,或整体覆盖已有文件(覆盖时必须提供 expectedHash)。修改已有文件优先使用 apply_patch。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","content"],properties:{grantId:X,path:Y("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:St,createDirectories:{type:"boolean",description:"父目录不存在时是否自动创建,默认否。"}}}},upload_file:{functionCode:"upload_file",name:"上传本地文件",description:`${G}把本地文件夹中的文件上传到平台文件服务,返回 fileId、name、size 和 url。url 是文件访问地址,可直接用于后续推理或对话。下载回本地文件夹时使用 download_file,source.type 为 platformFile。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:X,path:Y("要上传的文件。"),target:{type:"string",description:"上传目标,目前只支持 session(默认),其他值返回 501。"},mimeHint:{type:"string",description:"可选的 MIME 类型。"}}}},download_file:{functionCode:"download_file",name:"下载到本地文件夹",description:`${G}把会话文件、平台文件或 https 地址保存到本地文件夹。source.type 为 url 时必须同时填写 source.url(完整地址),为 sessionFile 或 platformFile 时必须同时填写 source.fileId。不要只传 type。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","destPath","source"],properties:{grantId:X,destPath:Y("保存位置(文件路径)。"),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:St}}}},ua=new TextEncoder;function ie(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const fa=(n,e)=>d(exports,null,function*(){const t=Q(n.path,{allowRoot:!0});if((yield e.adapter.stat(t)).kind!=="directory")throw new p(m.BadRequest,"目标是文件,不是目录。");const s=ie(n.offset,0,0,Number.MAX_SAFE_INTEGER),r=ie(n.limit,si,1,ri),o=yield e.adapter.listEntries(t,e.signal);o.sort((c,l)=>c.kind!==l.kind?c.kind==="directory"?-1:1:c.name<l.name?-1:c.name>l.name?1:0);const a=o.slice(s,s+r).map(c=>{const l=ji(t,c.name),h={name:c.name,path:l,kind:c.kind};return c.kind==="file"&&(h.size=c.size,h.lastModified=c.lastModified,e.sensitive.isSensitive(l)&&(h.sensitive=!0)),h});return{data:{path:t,entries:a,total:o.length,hasMore:s+a.length<o.length}}});function pa(n,e,t){return pe(this,null,function*(){var a;const i=new TextDecoder(e),s=n.stream().getReader();let r="",o=!1;try{for(;;){M(t);const{done:c,value:l}=yield new se(s.read());r+=c?i.decode():i.decode(l,{stream:!0});const h=r.split(`
374
+ `+u:u;break;case"event":i.event=u;break;case"id":n(i.id=u);break;case"retry":const f=parseInt(u,10);isNaN(f)||e(i.retry=f);break}}}}function Ho(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function Vn(){return{data:"",event:"",id:"",retry:void 0}}const $t="text/event-stream",qo=1e3,Gn="last-event-id";function Xn(n,h){var u=h,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:a,fetch:c}=u,l=un(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,g)=>{const b=w({},t);b.accept||(b.accept=$t);let v;function _(){v.abort(),document.hidden||P()}a||document.addEventListener("visibilitychange",_);let A=qo,I=0;function T(){document.removeEventListener("visibilitychange",_),window.clearTimeout(I),v.abort()}e==null||e.addEventListener("abort",()=>{T(),f()});const R=c!=null?c:window.fetch,Z=i!=null?i:zo;function P(){return d(this,null,function*(){var k;v=new AbortController;try{const C=yield R(n,S(w({},l),{headers:b,signal:v.signal}));yield Z(C),yield Bo(C.body,jo(Uo(N=>{N?b[Gn]=N:delete b[Gn]},N=>{A=N},s))),r==null||r(),T(),f()}catch(C){if(!v.signal.aborted)try{const N=(k=o==null?void 0:o(C))!=null?k:A;window.clearTimeout(I),I=window.setTimeout(P,N)}catch(N){T(),g(N)}}})}P()})}function zo(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith($t)))throw new Error(`Expected content-type to be ${$t}, Actual: ${e}`)}const Yn=new U("[DialogSession] ");class Wo extends an{constructor(t,i="",s,r,o,a){super(t,i,s,r,o,a);y(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>d(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c={code:0,content:"",role:x.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},l=S(w({},s),{stream:exports.configuration.stream});Xn(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(l),openWhenHidden:!0,signal:r,onopen(h){return h.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(h){if(!h.data.includes('{"code": ')){let f={};try{f=JSON.parse(h.data)}catch(b){}(f==null?void 0:f.mtype)==="search"?c.searchReference.push(f):c.content=c.content+h.data;const g={content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:Dt(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(o==null?void 0:o.onmessage)&&o.onmessage(g)}const u=JSON.parse(h.data);if(c.reference=u.data.reference,c.searchReference=u.data.searchReference,c.messageTime=u.data.messageTime,c.messageId=u.data.messageId,c.llmModel=u.data.llmModel,c.content=u.data.content,c.code=u.code,u.code===200){const f={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,isReplying:!0};o!=null&&o.onmessage&&o.onmessage(f)}else return o!=null&&o.onclose&&o.onclose(c),a&&a({code:c.code,message:c.message})},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const h={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};o!=null&&o.onclose&&o.onclose(h)}})})}postChatV3EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c=this,l={code:0,content:"",role:x.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},h=S(w({},s),{stream:exports.configuration.stream});Xn(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(h),openWhenHidden:!0,signal:r,onopen(u){return u.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(u){if(!u.data&&!u.event&&!u.id&&!u.retry)return;let f={};try{f=JSON.parse(u.data)}catch(g){console.error("parse eventData to JSON failed. ",u.data)}if(f.code!==200)return l.index=-1,l.code=f.code,l.message=f.message,o!=null&&o.onmessage&&o.onmessage(l),a&&a({code:f.code,message:f.message});c.handleStreamAnswer(f,l),o!=null&&o.onmessage&&o.onmessage(l)},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const u=S(w({},l),{isReplying:!1});o!=null&&o.onclose&&o.onclose(u)}})})}sendQuestion(t,i){return d(this,null,function*(){const{content:s,fileIds:r,oldMessageId:o,imageContent:a}=t,{stream:c,referenceFirst:l}=i;if(this.active||(yield this.activate()),this._id){const h=this.convertKnowledgesToChatFormat(this.knowledges);let u={content:s,fileIds:r,referenceFirst:l,oldMessageId:o,promptVariables:this.promptVariables.filter(f=>f.type===x.PromptVariableType.User).reduce((f,g)=>S(w({},f),{[g.key]:g.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===x.PromptVariableType.System).reduce((f,g)=>S(w({},f),{[g.key]:g.value}),{}),knowledges:h,enableTitleSummary:this.resolveEnableTitleSummary(),imageContent:a};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,u,this.ctrl.signal,{onopen:()=>{Yn.log("open",this.ctrl)},onmessage:f=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===x.ChatMessageRole.Robot?(g=w(w({},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=>d(this,null,function*(){this._stopAnswer||(Yn.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 d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}const Vo="@glodon-aiot/bot-client-sdk",Go="3.26.0-alpha.26",Xo="glodoncv",Yo="aiot bot client js sdk",Jo="module",Ko=!1,Qo=["aiot","bot","bot client","sdk"],Zo=["dist"],ea="./dist/es/index.mjs",ta="./dist/lib/index.js",na="./dist/src/index.d.ts",ia={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},sa="MIT",ra={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","build:just-bash":"node scripts/build-just-bash.mjs","upload:just-bash":"node scripts/build-just-bash.mjs && node scripts/upload-cdn-libs.cjs just-bash","build:pyodide":"node scripts/build-pyodide.mjs","upload:pyodide":"node scripts/build-pyodide.mjs && node scripts/upload-cdn-libs.cjs pyodide",test:"vitest run","test:watch":"vitest"},oa={"@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","just-bash":"3.6.0","npm-run-all":"^4.1.5",prettier:"2.7.1",pyodide:"314.0.7","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"},aa={access:"public",registry:"https://registry.npmjs.org/"},ca={"@glodon-aiot/apis":"^3.26.0-alpha.26",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"},la={name:Vo,version:Go,author:Xo,description:Yo,type:Jo,sideEffects:Ko,keywords:Qo,files:Zo,module:ea,main:ta,typings:na,exports:ia,license:sa,scripts:ra,devDependencies:oa,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:aa,dependencies:ca},Jn=new U("[BotClient] ");class da{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){y(this,"event",new nn);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=i,this.sdkConfigs=s,Nt(t,{refreshBuiltinPlugins:!1}),this._applicationId=tt(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{Nt(S(w({},t),{stream:t.stream===void 0?(r==null?void 0:r.type)===x.ApplicationTypes.Dialog||(r==null?void 0:r.type)===x.ApplicationTypes.Agent:t.stream})),this.event.emit("ready")})}setupLocalWorkspace(){var s,r;const e=(s=exports.configuration.builtinPlugins)==null?void 0:s.localFiles;if(!(e!=null&&e.enabled)){$n(void 0),Pe();return}const t=[],i=(r=e.backend)!=null?r:"file-system-access";if(i!=="file-system-access"&&i!=="host-bridge")t.push(new Error(`[LocalFiles] 不支持的 backend:${e.backend}`));else{const o=Vr(exports.configuration.apiRoot,this.token,(a,c)=>Jn.error(c));this._localWorkspace=new Wi({applicationId:this._applicationId,config:e,store:qi(),picker:i==="host-bridge"?null:void 0,transfer:rn(()=>this.cvforceApi,()=>o)}),$n(this._localWorkspace),this._localWorkspace.platformSkills=new Jr({applicationId:()=>this._applicationId,getToken:()=>this.token,getSkills:()=>{var a,c,l,h;return(h=(l=(c=(a=this._application)==null?void 0:a.arrange)==null?void 0:c[0])==null?void 0:l.skills)!=null?h:[]},apiRoot:()=>exports.configuration.apiRoot,getSandbox:()=>{var c;const a=(c=this._localWorkspace)==null?void 0:c.adapter;return a instanceof $e?a.sandbox:void 0}}),i==="host-bridge"?this._disconnectHost=Qr(this._localWorkspace):this._localWorkspace.restore()}t.push(...Pe()),t.length&&Promise.resolve().then(()=>t.forEach(o=>this.event.emit("error",o)))}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 d(this,null,function*(){var t,i,s,r,o;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(i=this.sdkConfigs.ui)==null?void 0:i.version,sdkVersion:la.version}).then(a=>(typeof a.arrange[0].thinkingModeOpen!="boolean"&&(a.arrange[0].thinkingModeOpen=!0),typeof a.arrange[0].thinkingTextOpen!="boolean"&&(a.arrange[0].thinkingTextOpen=!0),S(w({},a),{arrange:[S(w({},a.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&a.arrange[0].recommendQuestionOpen})]})));const e=(o=(r=(s=this._application)==null?void 0:s.arrange)==null?void 0:r[0])==null?void 0:o.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(a=>a.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type:x.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:x.PromptVariableType.System})]).then(([a,c])=>[...a,...c]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:Pi(exports.configuration.apiRoot,this.token,(e,t)=>Jn.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=tt(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,i,s,r){return d(this,null,function*(){const o=this;return new Promise((a,c)=>{const l=h=>d(this,null,function*(){if(h===x.ApplicationTypes.Agent)a(new Do(e,t,i,s,r,o));else if(h===x.ApplicationTypes.Dialog)a(new Wo(e,t,i,s,r,o));else throw Error(`不支持的应用类型:${h}`)});if(this.ready){if(!this._application)throw Error("client is not ready");l(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");l(this._application.type)},!0)})})}getArtifacts(e){return d(this,null,function*(){var r,o;this.checkReady();const t=e||((r=this._activeSession)==null?void 0:r.id);if(!t)throw new Error("session id is not defined");const i=this._sessions.find(a=>a.id===t);if(i)return i.getArtifacts();const s=yield this.cvforceApi.getSessionArtifacts(this._applicationId,t);return(o=s==null?void 0:s.artifacts)!=null?o:[]})}getSessions(e){return d(this,null,function*(){return new Promise((t,i)=>{const s=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>d(this,null,function*(){const o=[];for(const a of r){const c=this._sessions.find(l=>l.id===a.id);if(c)c.data=a,this._application?c.application=this._application:yield c.loadApplicationInfo(),o.push(c);else{const l=yield this.createSession(this.token,a.id,a,this.lazyload,this._application||void 0);o.push(l)}}if(e!=null&&e.pageSize){const a=[...this._sessions,...o],c=new Map;for(const l of a)c.set(l.id,l);return this.sessions=Array.from(c.values()),this.sessions}else return this.sessions=o,o}));if(this.ready){if(!this._application)throw Error("_application is null");t(s())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(s())},!0)})})}loadSession(e="",t){return d(this,null,function*(){var s,r;this.checkReady(),(r=(s=this._localWorkspace)==null?void 0:s.platformSkills)==null||r.sync();let i=this.sessions.find(o=>o.id===e);if(i||(i=yield this.createSession(this.token,e,t),this._sessions.push(i)),this._activeSession){if(this._activeSession===i)return i;this._activeSession.inactivate()}return i.id?(this._activeSession=i,yield i.activate()):i.addEventListener("data:loaded",()=>{this._activeSession!==i&&(i==null||i.activate(),this._activeSession=i)},!0),i})}reload(){return this.loadApplication().then(()=>d(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return d(this,null,function*(){yield this.reload();let t=this._sessions.find(i=>i.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,i="top_time desc, sort_status desc, updated_at desc"){return d(this,null,function*(){let s=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!s){console.warn("setTop session failed.");return}return yield s.setTop(t),this.getSessions({order:i})})}addEventListener(e,t,i=!1){if(typeof t!="function")throw Error("event listener is not a function");if(i){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return d(this,null,function*(){this.checkReady();let i=-1;if(typeof e=="string"?i=this._sessions.findIndex(s=>s.id===e):i=this._sessions.findIndex(s=>s.id===e.id),i>-1){const s=this._sessions[i];t&&(yield s.delete()),this._sessions.splice(i,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 ha{constructor(e,t={},i){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(){}}const G="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",X={type:"string",enum:[Ie],description:`工作区 ID。省略时按 ${Ie} 处理,传其他值会被拒绝。`},Y=n=>({type:"string",description:`${n}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),St={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},Gi={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${G}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:X,path:Y('要列出的目录,省略或传 "." 表示工作区根目录。'),offset:{type:"integer",minimum:0,description:"分页起始位置,默认 0。"},limit:{type:"integer",minimum:1,maximum:1e3,description:"每页条数,默认 200。"}}}},read_file:{functionCode:"read_file",name:"读取本地文件",description:`${G}按行读取文本文件,单次最多返回 1 MiB,超出部分会被截断(truncated: true)。返回内容的 hash 可用于后续修改。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:X,path:Y("要读取的文件。"),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:`${G}返回文件或目录的类型、大小、修改时间,可选返回 hash。不返回文件内容。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:X,path:Y("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${G}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:X,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:Y("搜索起点目录,默认工作区根目录。"),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:`${G}在指定文件或目录(递归)中搜索普通文本(不支持正则),返回所在文件、行号与该行内容。必须指定 path,不能搜索整个文件夹。`,parameters:{type:"object",required:["grantId","path","query"],properties:{grantId:X,path:Y("搜索范围,可以是文件或目录。"),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:`${G}以查找替换的方式修改 UTF-8 文本文件。每条修改的 oldText 必须在文件中唯一出现(或设置 replaceAll)。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","expectedHash","edits"],properties:{grantId:X,path:Y("要修改的文件。"),expectedHash:St,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:`${G}新建文件,或整体覆盖已有文件(覆盖时必须提供 expectedHash)。修改已有文件优先使用 apply_patch。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","content"],properties:{grantId:X,path:Y("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:St,createDirectories:{type:"boolean",description:"父目录不存在时是否自动创建,默认否。"}}}},upload_file:{functionCode:"upload_file",name:"上传本地文件",description:`${G}把本地文件夹中的文件上传到平台文件服务,返回 fileId、name、size 和 url。url 是文件访问地址,可直接用于后续推理或对话。下载回本地文件夹时使用 download_file,source.type 为 platformFile。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:X,path:Y("要上传的文件。"),target:{type:"string",description:"上传目标,目前只支持 session(默认),其他值返回 501。"},mimeHint:{type:"string",description:"可选的 MIME 类型。"}}}},download_file:{functionCode:"download_file",name:"下载到本地文件夹",description:`${G}把会话文件、平台文件或 https 地址保存到本地文件夹。source.type 为 url 时必须同时填写 source.url(完整地址),为 sessionFile 或 platformFile 时必须同时填写 source.fileId。不要只传 type。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","destPath","source"],properties:{grantId:X,destPath:Y("保存位置(文件路径)。"),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:St}}}},ua=new TextEncoder;function ie(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const fa=(n,e)=>d(exports,null,function*(){const t=Q(n.path,{allowRoot:!0});if((yield e.adapter.stat(t)).kind!=="directory")throw new p(m.BadRequest,"目标是文件,不是目录。");const s=ie(n.offset,0,0,Number.MAX_SAFE_INTEGER),r=ie(n.limit,si,1,ri),o=yield e.adapter.listEntries(t,e.signal);o.sort((c,l)=>c.kind!==l.kind?c.kind==="directory"?-1:1:c.name<l.name?-1:c.name>l.name?1:0);const a=o.slice(s,s+r).map(c=>{const l=ji(t,c.name),h={name:c.name,path:l,kind:c.kind};return c.kind==="file"&&(h.size=c.size,h.lastModified=c.lastModified,e.sensitive.isSensitive(l)&&(h.sensitive=!0)),h});return{data:{path:t,entries:a,total:o.length,hasMore:s+a.length<o.length}}});function pa(n,e,t){return pe(this,null,function*(){var a;const i=new TextDecoder(e),s=n.stream().getReader();let r="",o=!1;try{for(;;){M(t);const{done:c,value:l}=yield new se(s.read());r+=c?i.decode():i.decode(l,{stream:!0});const h=r.split(`
375
375
  `);r=(a=h.pop())!=null?a:"";for(const u of h)o=!0,yield u;if(c)break}}finally{s.releaseLock()}(r||!o)&&(yield r)})}const ma=(n,e)=>d(exports,null,function*(){var T,R;const t=Q(n.path);Te(e,t,"read");const i=yield Yt(e.adapter,t),s=yield e.adapter.readFile(t),r=(T=i.size)!=null?T:s.size;if(yield Cs(s))throw new p(m.BadRequest,"这是二进制文件,不能按文本读取。可以使用 stat_file 查看信息,或使用 upload_file 上传到会话。");const o=yield V(s.slice(0,3)),a=Ii(o)?"utf-8":(R=n.encoding)!=null?R:"utf-8",c=ie(n.startLine,1,1,Number.MAX_SAFE_INTEGER),l=n.endLine===void 0?Number.MAX_SAFE_INTEGER:Math.max(Math.trunc(n.endLine),c),h=ie(n.maxBytes,e.limits.maxReadBytes,1,e.limits.maxReadBytes),u=r<=e.limits.maxTransferBytes,f=[];let g=0,b=0,v=c-1,_=!1,A=!1;try{for(var Z=W(pa(s,a,e.signal)),P,k,C;P=!(k=yield Z.next()).done;P=!1){const N=k.value;b++;const $=N.endsWith("\r")?N.slice(0,-1):N;if($!==N&&(A=!0),b<c||b>l||_){if(!u&&(_||b>l))break;continue}const ue=Jt($)+(f.length?1:0);if(g+ue>h){if(_=!0,f.length||(f.push(ga($,h)),v=b),!u)break;continue}f.push($),g+=ue,v=b}}catch(k){C=[k]}finally{try{P&&(k=Z.return)&&(yield k.call(Z))}finally{if(C)throw C[0]}}const I={path:t,content:f.join(`
376
376
  `),startLine:c,endLine:Math.max(v,c-1),size:r,encoding:a,lineEnding:A?"crlf":"lf"};return u&&(I.totalLines=b),r<=e.limits.maxWriteBytes&&(I.hash=yield xe(yield V(s))),{data:I,truncated:_||void 0}});function ga(n,e){const t=ua.encode(n);return t.byteLength<=e?n:new TextDecoder().decode(t.slice(0,e)).replace(/\uFFFD$/,"")}const ya=(n,e)=>d(exports,null,function*(){var r;const t=Q(n.path),i=yield e.adapter.stat(t),s={path:t,kind:i.kind,sensitive:i.kind==="file"&&e.sensitive.isSensitive(t)};return i.kind==="file"&&(s.size=i.size,s.lastModified=i.lastModified,n.includeHash&&((r=i.size)!=null?r:0)<=e.limits.maxTransferBytes&&(s.hash=yield xe(yield V(yield e.adapter.readFile(t))))),{data:s}});function wa(n){return ui.some(e=>Ze(e,n))}function Xi(n,e,t){return pe(this,null,function*(){const i=[{path:e,depth:0}];let s=0;for(;i.length;){const r=i.shift();M(n.signal),++s%20===0&&(yield new se(ki()));const o=yield new se(n.adapter.listEntries(r.path,n.signal));o.sort((a,c)=>a.name<c.name?-1:a.name>c.name?1:0);for(const a of o){const c=ji(r.path,a.name);if(a.kind==="directory"){r.depth+1<t&&!hi.includes(a.name)&&i.push({path:c,depth:r.depth+1});continue}wa(a.name)||n.sensitive.match(c,"search")||(yield{path:c,relativePath:e?c.slice(e.length+1):c,name:a.name,size:a.size,lastModified:a.lastModified})}}})}function Yi(n,e){return n.includes("/")?Ze(n,e.relativePath):Ze(n,e.name)}const va=(n,e)=>d(exports,null,function*(){const t=Q(n.path,{allowRoot:!0});if(!n.pattern.trim())throw new p(m.BadRequest,"参数 pattern 不能为空。");const i=n.pattern.replace(/\\/g,"/").replace(/^\.\//,"");if((yield e.adapter.stat(t)).kind!=="directory")throw new p(m.BadRequest,"参数 path 必须是目录。");const r=ie(n.maxDepth,oi,1,jt),o=ie(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),a=[];let c=!1;try{for(var l=W(Xi(e,t,r)),h,u,f;h=!(u=yield l.next()).done;h=!1){const g=u.value;if(Yi(i,g)){if(a.length>=o){c=!0;break}a.push({path:g.path,size:g.size,lastModified:g.lastModified})}}}catch(u){f=[u]}finally{try{h&&(u=l.return)&&(yield u.call(l))}finally{if(f)throw f[0]}}return{data:{matches:a},truncated:c||void 0}});function It(n,e){if(n.length<=Ge)return n;const t=Math.max(0,Math.min(e-100,n.length-Ge));return n.slice(t,t+Ge)}const ba=(n,e)=>d(exports,null,function*(){var f;const t=Q(n.path,{allowRoot:!0});if(!t&&!e.allowWorkspaceWideTextSearch)throw new p(m.BadRequest,"不支持在整个工作区内搜索文本,请把 path 缩小到具体的子目录或文件。");if(n.isRegex)throw new p(m.NotImplemented,"暂不支持正则搜索,请使用普通文本搜索。");if(!n.query)throw new p(m.BadRequest,"参数 query 不能为空。");const i=n.caseSensitive===!0,s=i?n.query:n.query.toLowerCase(),r=ie(n.contextLines,0,0,li),o=ie(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),a=yield e.adapter.stat(t);let c;a.kind==="file"?(Te(e,t,"search"),c=function(){return pe(this,null,function*(){yield{path:t,relativePath:t,name:a.name,size:a.size}})}()):c=Xi(e,t,jt);const l=[];let h=0,u=!1;e:try{for(var g=W(c),b,v,_;b=!(v=yield g.next()).done;b=!1){const A=v.value;if(n.glob&&!Yi(n.glob,A)||((f=A.size)!=null?f:0)>ci)continue;if(h>=ai){u=!0;break}h++,h%20===0&&(yield ki()),M(e.signal);const I=yield V(yield e.adapter.readFile(A.path));if(he(I))continue;const T=new TextDecoder("utf-8").decode(I).split(/\r?\n/);for(let R=0;R<T.length;R++){const P=(i?T[R]:T[R].toLowerCase()).indexOf(s);if(P<0)continue;if(l.length>=o){u=!0;break e}const k={path:A.path,line:R+1,column:P+1,text:It(T[R],P)};r&&(k.before=T.slice(Math.max(0,R-r),R).map(C=>It(C,0)),k.after=T.slice(R+1,R+1+r).map(C=>It(C,0))),l.push(k)}}}catch(v){_=[v]}finally{try{b&&(v=g.return)&&(yield v.call(g))}finally{if(_)throw _[0]}}return{data:{matches:l,filesScanned:h},truncated:u||void 0}});function Kn(){return new p(m.Forbidden,"下载地址不在允许范围内:只允许 https 协议且域名在白名单中的地址。",{reason:"url_not_allowed"})}const _a=(n,e)=>d(exports,null,function*(){var u,f;const t=Q(n.path);if(((u=n.target)!=null?u:"session")!=="session")throw new p(m.NotImplemented,"目前只支持上传到当前会话(target: session)。");Te(e,t,"read");const s=yield Yt(e.adapter,t),r=(f=s.size)!=null?f:0;if(r>e.limits.maxTransferBytes)throw de(e.limits.maxTransferBytes);const o=Gt(t);yield e.requestApproval(t,{type:"upload",name:o,size:r,target:"session"}),e.progress({stage:"reading",loaded:0,total:r,path:t});const a=yield e.adapter.readFile(t);M(e.signal);const c=new File([a],o,{type:n.mimeHint||a.type||"application/octet-stream",lastModified:s.lastModified}),{fileId:l,url:h}=yield e.transfer.upload(c,e.context,({loaded:g,total:b})=>e.progress({stage:"uploading",loaded:g,total:b,path:t}));return M(e.signal),e.progress({stage:"done",loaded:r,total:r,path:t}),{data:{fileId:l,name:o,size:r,url:h}}});function Ea(n){const e=n;if(!e||typeof e!="object")throw new p(m.BadRequest,"缺少参数 source。");if(e.type==="sessionFile"||e.type==="platformFile"){if(typeof e.fileId!="string"||!e.fileId)throw new p(m.BadRequest,"source.fileId 必须是非空字符串。");return{type:e.type,fileId:e.fileId}}if(e.type==="url"){if(typeof e.url!="string"||!e.url)throw new p(m.BadRequest,"source.url 必须是非空字符串。");return{type:"url",url:e.url}}throw new p(m.BadRequest,"source.type 必须是 sessionFile、platformFile 或 url 之一。")}function Sa(n){return n.type==="sessionFile"?"会话文件":n.type==="platformFile"?"平台文件":new URL(n.url).hostname}function Ia(n,e,t,i,s){return pe(this,null,function*(){const r=n.getReader();let o=0;try{for(;;){M(e.signal);const{done:a,value:c}=yield new se(r.read());if(a)break;if(o+=c.byteLength,o>e.limits.maxTransferBytes)throw de(e.limits.maxTransferBytes,"下载内容");s.push(c),e.progress({stage:"downloading",loaded:o,total:i,path:t}),yield c}}finally{r.cancel().catch(()=>{})}})}const ka=(n,e)=>d(exports,null,function*(){var v,_,A;const t=Q(n.destPath,{field:"destPath"}),i=Ea(n.source);if(i.type==="url"&&!Pt(i.url,e.downloadUrlAllowlist))throw Kn();Te(e,t,"write");const s=yield Xe(e.adapter,t);if((s==null?void 0:s.kind)==="directory")throw new p(m.BadRequest,"目标是目录,不能写入文件。");if(s&&!n.overwrite)throw new p(m.Conflict,"目标文件已存在。如需覆盖,请设置 overwrite: true。");const r=()=>d(exports,null,function*(){if(!s||!n.expectedHash)return;const I=yield xe(yield V(yield e.adapter.readFile(t)));if(I!==n.expectedHash)throw new p(m.Conflict,"expectedHash 与目标文件当前内容不一致。",{currentHash:I})});yield r();const o=i.type==="url"?{url:i.url}:yield e.transfer.resolveDownload(i,e.context);if(o.size!==void 0&&o.size>e.limits.maxTransferBytes)throw de(e.limits.maxTransferBytes);const a={type:"download",source:{type:i.type,label:Sa(i)},name:(v=o.name)!=null?v:Gt(t),size:o.size,overwrite:!!s};yield e.requestApproval(t,a),yield r();let c;try{c=yield e.fetch(o.url,{headers:o.headers,credentials:"omit",redirect:"follow",signal:e.signal})}catch(I){throw M(e.signal),new p(m.Internal,"下载失败,无法连接到文件地址。")}if(i.type==="url"&&c.url&&!Pt(c.url,e.downloadUrlAllowlist))throw(_=c.body)==null||_.cancel().catch(()=>{}),Kn();if(!c.ok||!c.body)throw(A=c.body)==null||A.cancel().catch(()=>{}),new p(c.status===404?m.NotFound:m.Internal,`下载失败(HTTP ${c.status})。`);const l=Number(c.headers.get("content-length")),h=Number.isFinite(l)&&l>0?l:void 0;if(h!==void 0&&h>e.limits.maxTransferBytes)throw c.body.cancel().catch(()=>{}),de(e.limits.maxTransferBytes);const u=[];yield e.adapter.writeFile(t,Ia(c.body,e,t,h,u),{signal:e.signal});const f=u.reduce((I,T)=>I+T.byteLength,0),g=new Uint8Array(f);let b=0;return u.forEach(I=>{g.set(I,b),b+=I.byteLength}),e.progress({stage:"done",loaded:f,total:f,path:t}),{data:{path:t,size:f,hash:yield xe(g)}}}),kt=new Uint8Array([239,187,191]);function rt(n,e){return new p(m.Conflict,e,{currentHash:n})}function cn(n,e){return d(this,null,function*(){var s;if(((s=(yield Yt(n.adapter,e)).size)!=null?s:0)>n.limits.maxWriteBytes)throw de(n.limits.maxWriteBytes,"目标文件");const i=yield V(yield n.adapter.readFile(e));return{bytes:i,hash:yield xe(i)}})}function Ji(n,e,t){return d(this,null,function*(){const{hash:i}=yield cn(n,e);if(i!==t)throw rt(i,"文件在确认期间已被修改,本次写入已取消。请重新读取后再修改。")})}function xa(n,e){const t=new TextEncoder().encode(n);if(!e)return t;const i=new Uint8Array(kt.byteLength+t.byteLength);return i.set(kt,0),i.set(t,kt.byteLength),i}function Aa(n,e){let t=0,i=n.indexOf(e);for(;i>=0;)t++,i=n.indexOf(e,i+e.length);return t}function Qn(n,e){return!e||n.includes(`\r
377
377
  `)?n:n.replace(/\n/g,`\r
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glodon-aiot/bot-client-sdk",
3
- "version": "3.26.0-alpha.24",
3
+ "version": "3.26.0-alpha.26",
4
4
  "author": "glodoncv",
5
5
  "description": "aiot bot client js sdk",
6
6
  "type": "module",
@@ -88,7 +88,7 @@
88
88
  "registry": "https://registry.npmjs.org/"
89
89
  },
90
90
  "dependencies": {
91
- "@glodon-aiot/apis": "^3.26.0-alpha.24",
91
+ "@glodon-aiot/apis": "^3.26.0-alpha.26",
92
92
  "axios": "0.24.0",
93
93
  "buffer": "^6.0.3",
94
94
  "dayjs": "^1.11.13",