@glodon-aiot/bot-client-sdk 3.26.0-alpha.14 → 3.26.0-alpha.15

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.14", 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.15", 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.14", t = "glodoncv",
68
68
  access: "public",
69
69
  registry: "https://registry.npmjs.org/"
70
70
  }, y = {
71
- "@glodon-aiot/apis": "^3.26.0-alpha.14",
71
+ "@glodon-aiot/apis": "^3.26.0-alpha.15",
72
72
  axios: "0.24.0",
73
73
  buffer: "^6.0.3",
74
74
  dayjs: "^1.11.13",
package/dist/lib/index.js CHANGED
@@ -366,7 +366,7 @@ ${c.excerpt}`,{line:c.line,excerpt:c.excerpt})}const o=s.slice(0,r)+n.new_text+s
366
366
  `)};function mi(n,e,t){return new x.CVForceApi(gi(n,"/data/v1",e,t),yi(t))}function vr(n,e,t){return new x.AIShopApi(gi(n,"/aishop",e,t),yi(t))}function gi(n,e,t,i){const s=o=>{var c;return t&&(pi(t)&&i(403,"aiotToken is timeout"),o.headers=(c=o.headers)!=null?c:{},o.headers=E(v({},o.headers),{Authorization:t?`Bearer ${t}`:""})),o};function r(o,c=!0){const a=`${n}${o}`,l=$i.create({baseURL:a});return c&&l.interceptors.request.use(s),l}return r(e)}function yi(n){return{onHttpStatusError:(i,s)=>{i===401&&n(i,"aiotToken is invalid")},onAppStatusError:(i,s)=>{i!==10001&&i!==10215&&n(i,s)}}}const _r=20*1024*1024,wi=/^[A-Za-z0-9._-]+$/;function ot(n){const e=n==null?void 0:n.skills;return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"):[]}function br(n){if(!n)return!1;try{return!pi(n)}catch(e){return!1}}function vn(n){if(!(typeof n.skillId!="string"||!wi.test(n.skillId))&&!(typeof n.name!="string"||!n.name||/[\\/\0]/.test(n.name)||n.name==="."||n.name==="..")&&!(typeof n.version!="number"||!Number.isInteger(n.version)||n.version<1))return{skillId:n.skillId,name:n.name,version:n.version}}function Sr(n){return Array.isArray(n)?n.flatMap(e=>{if(!e||typeof e!="object")return[];const t=e;return typeof t.skillId!="string"||typeof t.name!="string"||typeof t.version!="number"?[]:[{skillId:t.skillId,name:t.name,version:t.version}]}):[]}class Er{constructor(e){y(this,"inflight",new Map);y(this,"busy",new Set);this.options=e}sync(){return this.reconcile().catch(()=>{})}read(e,t,i){return h(this,null,function*(){const s=yield this.prepare(e,i);return this.requireSandbox().skillRead(this.options.applicationId(),s.skillId,s.version,t,i)})}target(e,t){return h(this,null,function*(){const i=yield this.prepare(e,t);return{applicationId:this.options.applicationId(),skillId:i.skillId,version:i.version,name:i.name}})}track(e,t){const i=`${e}/${t}`;this.busy.add(i);let s=!1;return()=>{s||(s=!0,this.busy.delete(i),this.prune().catch(()=>{}))}}requireSandbox(){const e=this.options.getSandbox();if(!e)throw new m(p.NotImplemented,"当前环境不能加载平台技能,需要端侧宿主。");return e}prepare(e,t){return h(this,null,function*(){const i=this.bound(e);if(!i)throw new m(p.NotFound,"技能或资源不存在。");return yield this.ensure(i,t),i})}bound(e){if(!wi.test(this.options.applicationId()))return;const t=ot({skills:this.options.getSkills()}).find(i=>i.name===e);return t?vn(t):void 0}reconcile(){return h(this,null,function*(){if(!this.options.getSandbox())return;const t=ot({skills:this.options.getSkills()}).flatMap(i=>{const s=vn(i);return s?[s]:[]});yield Promise.all(t.map(i=>this.ensure(i).catch(()=>{}))),yield this.prune()})}ensure(e,t){return h(this,null,function*(){const i=`${this.options.applicationId()}/${e.skillId}/${e.version}`,s=this.inflight.get(i);if(s)return s;const r=this.installIfNeeded(e,t).finally(()=>{this.inflight.get(i)===r&&this.inflight.delete(i)});return this.inflight.set(i,r),r})}installIfNeeded(e,t){return h(this,null,function*(){var a;const i=this.requireSandbox();if(i.ready&&(yield this.alreadyInstalled(i,e,t)))return;const s=this.options.getToken();if(!br(s))throw new m(p.Forbidden,"技能下载令牌不可用。");const r=this.options.apiRoot().replace(/\/$/,""),o=yield((a=this.options.fetch)!=null?a:fetch)(`${r}/skill/v1/skills/${encodeURIComponent(e.skillId)}/versions/${e.version}/download`,{headers:{Authorization:`Bearer ${s}`},signal:t});if(!o.ok)throw new m(p.BadRequest,`技能下载失败(${o.status})。`);const c=new Uint8Array(yield o.arrayBuffer());if(c.byteLength>_r)throw new m(p.BadRequest,"技能压缩包超过 20 MB。");yield this.waitReady(i,t),!(yield this.alreadyInstalled(i,e,t))&&(yield i.installSkill({applicationId:this.options.applicationId(),skillId:e.skillId,version:e.version,name:e.name},c,t))})}alreadyInstalled(e,t,i){return h(this,null,function*(){return Sr(yield e.skillStatus(this.options.applicationId(),i)).some(r=>r.skillId===t.skillId&&r.version===t.version&&r.name===t.name)})}prune(){return h(this,null,function*(){const e=this.options.getSandbox();if(!(e!=null&&e.ready))return;const t=ot({skills:this.options.getSkills()}).flatMap(s=>typeof s.skillId!="string"||typeof s.version!="number"||s.version<1?[]:[{skillId:s.skillId,version:s.version}]),i=[...this.busy].map(s=>{const[r,o]=s.split("/");return{skillId:r,version:Number(o)}});yield e.skillPrune(this.options.applicationId(),t,i)})}waitReady(e,t){return h(this,null,function*(){e.ready||(yield new Promise((i,s)=>{const r=setInterval(()=>{if(t!=null&&t.aborted){clearInterval(r),s(new m(p.Cancelled,"已取消。"));return}e.ready&&(clearInterval(r),i())},50)}))})}}function Ir(n){if(!n||typeof n!="object")return;const e=n;return{state:e.state,url:typeof e.url=="string"?e.url:void 0,token:typeof e.token=="string"?e.token:void 0,protocol:typeof e.protocol=="number"?e.protocol:void 0,exitCode:typeof e.exitCode=="number"?e.exitCode:void 0,detail:typeof e.detail=="string"?e.detail:void 0,message:typeof e.message=="string"?e.message:void 0,reason:typeof e.reason=="string"?e.reason:void 0}}let ie;function kr(n){ie==null||ie(),ie=void 0;const e=qi();if(!e)return()=>{};const t=new Je(e),i=r=>{const o=Ui(r.data);if(o){if(o.type==="workspace"){const c=o.granted===!0,a=typeof o.displayName=="string"?o.displayName:"";t.setCapabilities(o.capabilities,{version:o.sandboxVersion}),t.applySandbox(Ir(o.sandbox)),c?(t.displayName=a||"工程目录",(n.status!=="granted"||n.displayName!==t.displayName)&&n.attachAdapter(t,t.displayName)):n.status==="granted"&&n.clear();return}if(o.type==="fs-changed"){const c=Array.isArray(o.paths)?o.paths.filter(a=>typeof a=="string"):[];n.notifyFilesChanged(c);return}}};e.addEventListener("message",i),e.postMessage({channel:Rt,type:"hello"});const s=()=>{e.removeEventListener("message",i),ie===s&&(ie=void 0)};return ie=s,s}const se=new U("[EventBus] ");class Ut{constructor(e=!1){y(this,"eventListenerMap",{});e&&se.disable()}getEventListenerMap(){return v({},this.eventListenerMap)}on(e,t,i=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),i?this.eventListenerMap[e].push({fn:t,once:!0}):this.eventListenerMap[e].push(t),se.log(`add event ${e} listener ${i?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const i=this.eventListenerMap[e].findIndex(s=>{if(typeof s=="function"&&t===s)return!0;if(s=s,s.fn===t)return!0});i<0?se.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(i,1),se.log(`remove event ${e} listener`))}else se.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){se.log(`event ${e} listeners is empty`);return}const i=[];for(let s=0;s<this.eventListenerMap[e].length;s++){const r=this.eventListenerMap[e][s];typeof r=="function"?r(t):i.push(r)}i.forEach(s=>{s&&(s.fn(t),this.off(e,s.fn))}),se.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const xr="路径必须是工作区内的相对路径,不能包含 ..、绝对路径或盘符。";function Pe(){return new m(p.Forbidden,xr,{reason:"path_outside_workspace"})}function Ar(n){if(n!==be)throw new m(p.Forbidden,`未知的工作区 grantId,当前仅支持 ${be}。`,{reason:"path_outside_workspace"})}function K(n,{allowRoot:e=!1,field:t="path"}={}){if(n==null){if(e)return"";throw new m(p.BadRequest,`缺少参数 ${t}。`)}if(typeof n!="string")throw new m(p.BadRequest,`参数 ${t} 必须是字符串。`);if(n.includes("\0")||/%(2e|2f|5c|00)/i.test(n))throw Pe();const i=n.normalize("NFC").replace(/\\/g,"/").trim();if(i.startsWith("/")||/^[a-zA-Z]:/.test(i))throw Pe();const s=[];for(const o of i.split("/"))if(!(o===""||o===".")){if(o==="..")throw Pe();s.push(o)}const r=s.join("/");if(!r&&!e)throw new m(p.BadRequest,`参数 ${t} 不能指向工作区根目录。`);return r}function P(n){return n?n.split("/"):[]}function Tr(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}function vi(n,e){return n?`${n}/${e}`:e}function pe(n,e){return!!n&&typeof n=="object"&&n.name===e}class _i{constructor(e){this.root=e}get displayName(){return this.root.name}resolveDirectory(e,t=!1){return h(this,null,function*(){let i=this.root;for(const s of e)i=yield i.getDirectoryHandle(s,{create:t});return i})}resolveFile(e){return h(this,null,function*(){const t=P(e),i=t.pop();if(!i)throw S("TypeMismatchError");return(yield this.resolveDirectory(t)).getFileHandle(i)})}stat(e){return h(this,null,function*(){const t=P(e),i=t.pop();if(!i)return{name:this.root.name,kind:"directory"};const s=yield this.resolveDirectory(t);try{const r=yield(yield s.getFileHandle(i)).getFile();return{name:i,kind:"file",size:r.size,lastModified:r.lastModified}}catch(r){if(!pe(r,"TypeMismatchError"))throw r;return yield s.getDirectoryHandle(i),{name:i,kind:"directory"}}})}listEntries(e,t){return h(this,null,function*(){const i=yield this.resolveDirectory(P(e)),s=[];try{for(var r=W(i.values()),o,c,a;o=!(c=yield r.next()).done;o=!1){const l=c.value;if(N(t),l.kind==="directory")s.push({name:l.name,kind:"directory"});else try{const d=yield l.getFile();s.push({name:l.name,kind:"file",size:d.size,lastModified:d.lastModified})}catch(d){if(pe(d,"NotAllowedError"))throw d;s.push({name:l.name,kind:"file"})}}}catch(c){a=[c]}finally{try{o&&(c=r.return)&&(yield c.call(r))}finally{if(a)throw a[0]}}return s})}readFile(e){return h(this,null,function*(){return(yield this.resolveFile(e)).getFile()})}writeFile(s,r){return h(this,arguments,function*(e,t,i={}){const o=P(e),c=o.pop();if(!c)throw S("TypeMismatchError");const a=yield this.resolveDirectory(o,i.createDirectories);let l=!0;try{yield a.getFileHandle(c)}catch(b){if(!pe(b,"NotFoundError"))throw b;l=!1}const d=yield a.getFileHandle(c,{create:!0});let u;try{u=yield d.createWritable();try{for(var f=W(Tt(t)),g,_,w;g=!(_=yield f.next()).done;g=!1){const b=_.value;N(i.signal),yield u.write(b)}}catch(_){w=[_]}finally{try{g&&(_=f.return)&&(yield _.call(f))}finally{if(w)throw w[0]}}N(i.signal),yield u.close()}catch(b){throw yield u==null?void 0:u.abort().catch(()=>{}),l||(yield a.removeEntry(c).catch(()=>{})),b}})}createDirectory(e){return h(this,null,function*(){yield this.resolveDirectory(P(e),!0)})}remove(i){return h(this,arguments,function*(e,t={}){const s=P(e),r=s.pop();if(!r)throw S("InvalidModificationError");yield(yield this.resolveDirectory(s)).removeEntry(r,{recursive:t.recursive===!0})})}move(e,t){return h(this,null,function*(){const i=P(e),s=P(t),r=i.pop(),o=s.pop();if(!r||!o)throw S("InvalidModificationError");const c=yield this.resolveDirectory(i),a=yield _n(c,r),l=yield this.resolveDirectory(s);if(Xn(e,t))throw S("InvalidModificationError");let d;try{d=yield _n(l,o)}catch(u){if(!pe(u,"NotFoundError"))throw u}if(d&&(d.kind==="directory"||a.kind==="directory"))throw S("InvalidModificationError");if(!d&&typeof a.move=="function")try{yield a.move(l,o);return}catch(u){if(!pe(u,"NotSupportedError")&&!(u instanceof TypeError))throw u}yield bi(a,l,o),yield c.removeEntry(r,{recursive:!0})})}}function _n(n,e){return h(this,null,function*(){try{return yield n.getFileHandle(e)}catch(t){if(!pe(t,"TypeMismatchError"))throw t;return n.getDirectoryHandle(e)}})}function bi(n,e,t){return h(this,null,function*(){if(n.kind==="file"){const a=yield n.getFile(),l=yield(yield e.getFileHandle(t,{create:!0})).createWritable();try{yield l.write(a),yield l.close()}catch(d){throw yield l.abort().catch(()=>{}),d}return}const i=yield e.getDirectoryHandle(t,{create:!0});try{for(var s=W(n.values()),r,o,c;r=!(o=yield s.next()).done;r=!1){const a=o.value;yield bi(a,i,a.name)}}catch(o){c=[o]}finally{try{r&&(o=s.return)&&(yield o.call(s))}finally{if(c)throw c[0]}}})}function Rr(){if(typeof window=="undefined")return;const n=window.showDirectoryPicker;return typeof n=="function"?n.bind(window):void 0}const Lr=/^[a-z0-9-]+(\.[a-z0-9-]+)+$/;function Mr(n){if(typeof n!="string")return null;const e=n.trim().toLowerCase().replace(/^\*?\./,"").replace(/\.$/,"");return!Lr.test(e)||Si(e)?null:e}function Si(n){return n.startsWith("[")||n.includes(":")?!0:/^[0-9.]+$/.test(n)||/^0x[0-9a-f.]+$/i.test(n)}function Ht(n=[]){const e=new Set(qn);for(const t of n){const i=Mr(t);i&&e.add(i)}return Array.from(e)}function Cr(n,e){return bt(n,Ht(e))}function bt(n,e){let t;try{t=new URL(n)}catch(s){return!1}if(t.protocol!=="https:"||t.username||t.password)return!1;const i=t.hostname.toLowerCase().replace(/\.$/,"");return!i||Si(i)||i==="localhost"||i.endsWith(".localhost")?!1:e.some(s=>i===s||i.endsWith(`.${s}`))}function Fr(n={}){const e=v({},je);return Object.keys(je).forEach(t=>{const i=n[t];typeof i=="number"&&Number.isFinite(i)&&i>0&&(e[t]=Math.min(i,je[t]))}),e}function me(){return new m(p.Internal,"平台文件服务请求失败,请稍后重试。")}function qt(n,e=()=>{}){const t=()=>{const r=n();if(!r)throw me();return r},i=()=>{const r=e();if(!r)throw me();return r};return{upload(r,o,c){return h(this,null,function*(){if(!o.sessionId)throw new m(p.BadRequest,"当前没有可用的会话,无法上传文件。");try{c==null||c({loaded:0,total:r.size});const a=yield i().postFile(r,(l,d)=>c==null?void 0:c({loaded:l,total:d}));if(!(a!=null&&a.id)||!a.url)throw me();return c==null||c({loaded:r.size,total:r.size}),{fileId:a.id,url:a.url}}catch(a){throw a instanceof m?a:me()}})},resolveDownload(r,o){return h(this,null,function*(){if(r.type==="platformFile")return Nr(i(),r.fileId);if(!o.sessionId)throw new m(p.BadRequest,"当前没有可用的会话,无法下载会话文件。");let c;try{c=yield t().getApplicationIdSessionFile(o.applicationId,o.sessionId,r.fileId)}catch(a){throw me()}if(!(c!=null&&c.url))throw new m(p.NotFound,"会话文件不存在或暂不可下载。");return{url:c.url,name:c.name,size:c.size}})}}}function Nr(n,e){return h(this,null,function*(){let t;try{t=yield n.getFile(e)}catch(s){throw me()}if(!(t!=null&&t.url))throw new m(p.NotFound,"平台文件不存在或暂不可下载。");let i;try{i=new URL(t.url)}catch(s){throw new m(p.Internal,"平台返回的下载地址无效。")}if(i.protocol!=="https:")throw new m(p.Internal,"平台返回的下载地址无效。");return{url:t.url,size:t.bytes}})}const Or="glodon-aiot-local-workspace",at="kv";function Wt(){const n=new Map;return{get(t){return h(this,null,function*(){return n.get(t)})},set(t,i){return h(this,null,function*(){n.set(t,i)})},delete(t){return h(this,null,function*(){n.delete(t)})}}}function $r(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}function Ei(n=Or){if(typeof indexedDB=="undefined")return Wt();let e;const t=()=>(e||(e=new Promise((r,o)=>{const c=indexedDB.open(n,1);c.onupgradeneeded=()=>{c.result.createObjectStore(at)},c.onsuccess=()=>r(c.result),c.onerror=()=>{e=void 0,o(c.error)}})),e),i=(r,o)=>h(this,null,function*(){const c=yield t();return $r(o(c.transaction(at,r).objectStore(at)))});return{get(r){return h(this,null,function*(){return yield i("readonly",o=>o.get(r))})},set(r,o){return h(this,null,function*(){yield i("readwrite",c=>c.put(o,r))})},delete(r){return h(this,null,function*(){yield i("readwrite",o=>o.delete(r))})}}}function bn(n){if(n!=null&&n.length&&!n.some(e=>!e||e==="."||e===".."||e.includes("/")||e.includes("\\")))return n.length===1?"":n.slice(0,-1).join("/")}function Dr(n,e){const t=globalThis.FileSystemObserver;if(typeof t!="function")return()=>{};let i;try{i=new t(s=>{const r=new Set;for(const o of s){if(o.type==="errored"){e();return}const c=bn(o.relativePathComponents),a=bn(o.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(s){return()=>{}}return i.observe(n,{recursive:!0}).catch(()=>i.disconnect()),()=>i.disconnect()}const Be={mode:"readwrite"};function Pr(n){const e=n.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(i=>!i||i==="."||i===".."))return t.join("/")}function Br(n){return!!n&&typeof n=="object"&&n.name==="AbortError"}class Ii{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,"commandRunner");y(this,"platformSkills");y(this,"browserRuntime");y(this,"store");y(this,"picker");y(this,"event",new Ut(!0));y(this,"_status");y(this,"_displayName");y(this,"_adapter",null);y(this,"pendingHandle",null);y(this,"approvalHandler");y(this,"activeCalls",0);y(this,"commandRunning",!1);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 o,c,a,l,d,u,f,g,_,w;const t=(o=e.config)!=null?o:{};this.applicationId=e.applicationId,this.store=(c=e.store)!=null?c:Wt(),this.picker=e.picker===null?void 0:(a=e.picker)!=null?a:Rr(),this.limits=Fr(t.limits),this.sensitive=new ni(t.sensitiveRulesAppend),this.downloadUrlAllowlist=Ht(t.downloadUrlAllowlistAppend),this.allowWorkspaceWideTextSearch=!!t.allowWorkspaceWideTextSearch,this.approvalHandler=t.onApprovalRequired;const i=(l=e.transfer)!=null?l:qt(()=>{});this.transfer={upload:(u=(d=t.transfer)==null?void 0:d.upload)!=null?u:i.upload,resolveDownload:(g=(f=t.transfer)==null?void 0:f.resolveDownload)!=null?g:i.resolveDownload};const s=(_=e.fetch)!=null?_:typeof fetch=="function"?fetch:void 0;this.fetch=s?s.bind(globalThis):()=>Promise.reject(new Error("fetch is not available")),this.commandRunner=e.commandRunner;const r=(w=t.commandRuntime)==null?void 0:w.browser;this.browserRuntime={enabled:(r==null?void 0:r.enabled)!==!1,bashModuleURL:r==null?void 0:r.bashModuleURL,pyodideIndexURL:r==null?void 0:r.pyodideIndexURL},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 _i(e),this.setStatus("granted",e.name),this.unwatchDirectory(),this.stopWatching=Dr(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=>h(this,null,function*(){var s,r;this.cancelAll();const i=(r=yield(s=t.queryPermission)==null?void 0:s.call(t,Be))!=null?r:"granted";return yield this.store.set(this.handleKey,{handle:t,displayName:t.name,savedAt:Date.now()}).catch(()=>{}),i==="denied"?(this.pendingHandle=t,this._adapter=null,this.setStatus("denied",t.name),!1):(this.attachHandle(t),!0)}),t=>{if(Br(t))return!1;throw t})}restore(){return this._ready=this.doRestore(),this._ready}doRestore(){return h(this,null,function*(){var i,s,r;if(!this.picker){this._adapter||this.setStatus("unsupported");return}let e;try{e=yield this.store.get(this.handleKey)}catch(o){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(s=(i=e.handle).queryPermission)==null?void 0:s.call(i,Be))!=null?r:"prompt"}catch(o){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(Be)}catch(i){return Promise.reject(i)}return t.then(i=>i==="granted"?(this.attachHandle(e),!0):(this._adapter=null,this.setStatus(i==="denied"?"denied":"prompt",e.name),!1))}clear(){return h(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 i=Pr(t);i===void 0?this.refreshAllVisible=!0:this.pendingChangePaths.add(i)}clearTimeout(this.changeTimer),this.changeTimer=setTimeout(()=>this.flushFilesChanged(),150)}}handlePermissionLost(){return h(this,null,function*(){const e=this.pendingHandle;if(!(e!=null&&e.queryPermission))return;const t=yield e.queryPermission(Be).catch(()=>"prompt");t!=="granted"&&(this.cancelAll(),this.cancelFilesChanged(),this.unwatchDirectory(),this._adapter=null,this.setStatus(t==="denied"?"denied":"prompt",e.name))})}isDisclosureAcknowledged(){return h(this,null,function*(){try{return!!(yield this.store.get(this.disclosureKey))}catch(e){return!1}})}acknowledgeDisclosure(){return h(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--)}}acquireCommand(){if(this.commandRunning)return null;this.commandRunning=!0;let e=!1;return()=>{e||(e=!0,this.commandRunning=!1)}}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(It.map(t=>[t,!0]));return{protocolVersion:"1.0",capabilities:E(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((i,s)=>i<s?-1:i>s?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(i){console.error(`[LocalWorkspace] ${e} listener failed`,i)}}}var ge=(n=>(n[n.Normal=0]="Normal",n[n.Debug=1]="Debug",n))(ge||{});const Sn=100,D=new U("[Session] ");var Re=(n=>(n.DataRequestFailed="data request error",n.SocketConnectionFailed="socket error",n.IdUndefined="session id is not defined",n.SendingEmptyContent="failed at sending empty content",n.Frozen="session is frozen",n.UserModeError="failed at setting socket user mode",n.Inactive="session is inactive",n))(Re||{});class zt{constructor(e,t="",i,s,r,o){y(this,"_id");y(this,"_frozen",!1);y(this,"inactivating",!1);y(this,"_ready",!1);y(this,"event",new Ut);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=s,this.client=o||null,this._applicationId=Xe(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"),i?(this.data=i,s||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(a=>h(this,null,function*(){this.data=a,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>h(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=>h(this,null,function*(){this.data=a,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>h(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=(i==null?void 0:i.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:a}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:a,netOpen:i==null?void 0:i.netOpen,knowledgeIdList:(c=i==null?void 0:i.knowledges)==null?void 0:c.map(l=>l.id),applicationId:this._applicationId}).then(l=>h(this,null,function*(){var d;this._id=l.id,this.data=E(v({},l),{knowledges:i==null?void 0:i.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id);try{yield(()=>h(this,null,function*(){if(i!=null&&i.knowledges)return this.setKnowledges((i==null?void 0:i.knowledges)||void 0)}))()}catch(u){D.error(u)}yield(()=>{if(i!=null&&i.promptVariables){const u=this._promptVariables.map(f=>{var _,w;const g=((w=(_=i.promptVariables)==null?void 0:_.find(b=>b.key===f.key&&b.type===f.type))==null?void 0:w.value)||"";return E(v({},f),{value:g})}).sort((f,g)=>f.key.localeCompare(g.key));return this.setPromptVariables(u||[])}else return})(),this.event.emit("data:created",this.data),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),((d=this.application)==null?void 0:d.type)!==x.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}fetchData(){return h(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=>h(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 h(this,null,function*(){if(!this.data)throw Error("session data is not loaded");if((e||[]).some(s=>Array.isArray(s.fileIds)&&s.fileIds.length===0))throw Error("fileIds cannot be an empty array");if((e||[]).reduce((s,r)=>{var c,a;const o=(a=(c=r.fileIds)==null?void 0:c.length)!=null?a:0;return s+(o>0?o:1)},0)>Sn)throw Error(`knowledges and fileIds total count cannot exceed ${Sn}`);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===x.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===x.PromptVariableType.User&&e.key==="query")&&!(e.type===x.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return h(this,null,function*(){const t=e==null?void 0:e.map(r=>r.type?r:E(v({},r),{type:"instruction"})),i=this._promptVariables.map(r=>{var c;const o=((c=t==null?void 0:t.find(a=>a.key===r.key&&a.type===r.type))==null?void 0:c.value)||r.value;return E(v({},r),{value:o})}).sort((r,o)=>r.key.localeCompare(o.key));if(!(yield Promise.all(i.filter(r=>!(r.type===x.PromptVariableType.User&&r.key==="query")&&!(r.type===x.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 h(this,null,function*(){var t,i,s;if(D.log("setNetOpen:",e),D.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((i=this._application)==null?void 0:i.type)===x.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((s=this._application)==null?void 0:s.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,D.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return mi(exports.configuration.apiRoot,this.token,(e,t)=>{const i=new Error("data request error",{cause:{status:e,message:t}});D.error(i),this.event.emit("error",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)}fetchMessages(){return h(this,arguments,function*(e={}){var i,s;const t={pageSize:this._loadingMessagesSize};if(this._id){e=v(v({},t),e),this.event.emit("history:loading"),D.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),D.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),o=r.map((a,l)=>{var f,g;let d=[],u;return typeof((f=a.agentHistoryList)==null?void 0:f.agentList)=="string"&&(d=JSON.parse(a.agentHistoryList.agentList).reduce((w,b)=>(w[b.data.step-1]||(w[b.data.step-1]=[]),w[b.data.step-1].push(b),w),[])),l===r.length-1&&(u=(g=this.data)==null?void 0:g.lastRelatedQuestion),E(v({},a),{actions:d,relatedQuesion:u,fromHistory:!0})});if(!e.endTime&&!e.startTime){const a=this.messages[this.messages.length-1];a&&!a.relatedQuesion&&(a.relatedQuesion=(i=this.data)==null?void 0:i.lastRelatedQuestion),this.messages=[...o,...this.messages]}else if(e.endTime&&!e.startTime){const a=this.messages.findIndex(l=>l.ts===e.endTime);this.messages.splice(0,a+1),this.messages=[...o,...this.messages]}else if(!e.endTime&&e.startTime){const a=this.messages.findLastIndex(l=>l.ts===e.endTime);this.messages.splice(a,this.messages.length-a-1),this.messages=[...this.messages,...o]}else{const a=this.messages.findIndex(d=>d.ts===e.endTime),l=this.messages.findLastIndex(d=>d.ts===e.endTime);this.messages.splice(a,l-a+1,...o)}const c=this.messages[this.messages.length-1];return c&&!c.relatedQuesion&&(c.relatedQuesion=(s=this.data)==null?void 0:s.lastRelatedQuestion),this.event.emit("history:moreloaded",o),D.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,o}else{const r=new Error("session id is not defined");return D.error(r),this.event.emit("error",r),!1}})}rename(e){return h(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}),D.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return h(this,null,function*(){this.messages.push(e),D.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=>h(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),D.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>h(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 h(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return h(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return D.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 h(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=>h(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)}resolveEnableTitleSummary(){var t,i,s;const e=(s=(i=(t=this.application)==null?void 0:t.arrange)==null?void 0:i[0])==null?void 0:s.autoGenerateSessionTitle;return typeof e=="boolean"?e:!0}get dataLoaded(){return this._dataLoaded}get messagesLoading(){return this._loadingMessages}send(i){return h(this,arguments,function*(e,t={stream:exports.configuration.stream}){var _;try{this.validateConfigs()}catch(w){console.error(w)}const{stream:s=exports.configuration.stream,referenceFirst:r=!1}=t,o=e.uuid||_e.v4(),c=((_=e.text)==null?void 0:_.trim())||"",a=e.files||[],l=e.fileIds,d=e.imageContent;if(!c&&!a.length&&!(l!=null&&l.length)){const w=new Error("failed at sending empty content");return D.error(w),this.event.emit("error",w),!1}if(!this._id){const w=new Error("session id is not defined");return D.error(w),this.event.emit("error",w),!1}if(this.frozen){const w=new Error("session is frozen");return D.error(w),this.event.emit("error",w),!1}this.frozen=!0,this._stopAnswer=!1;const u={sessionId:this.id,role:2,content:c,messageId:o,reference:[],searchReference:[],messageTime:"",files:a,imageContent:d},f={content:c,stream:s,requestId:o,fileIds:l,referenceFirst:r,imageContent:d};this.pushMessage(u),this.event.emit("question:content",c);const g=w=>h(this,null,function*(){if(w.role!==x.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",g),this._id&&w.content&&w.index&&w.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:w.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:w.content})),yield this.fillMessageReference(w),w.code){case 11915:w.content="请您换个问题问我吧~",w.index=-1,w.isSensitive=!0,w.isLoading=!1,w.sessionId=this._id||"",this.event.emit("message:error",w);break;case 11916:w.content="尊敬的用户您好,让我们换个话题再聊聊吧。",w.index=-1,w.isSensitive=!0,w.isLoading=!1,w.sessionId=this._id||"",this.event.emit("message:error",w);break;case 200:w.index=-1,w.isLoading=!1;break;default:w.content=w.message||"未知错误",w.isLoading=!1,w.index=-1,this.event.emit("message:error",w)}this.getRelatedQuesion(w),w.isLoading=!1;let b=this.messages[this.messages.length-1];if(b&&b.role===x.ChatMessageRole.Robot){const A=v(v({},b),w);this.messages[this.messages.length-1]=A,this.event.emit("message:updated",A)}else this.pushMessage(w);this.frozen=!1});return this.addEventListener("answer:finish",g),this.sendQuestion(f,E(v({},t),{stream:s,referenceFirst:r})),u})}currentUserQuestion(){for(let e=this.messages.length-1;e>=0;e-=1){const t=this.messages[e];if(t.role===x.ChatMessageRole.User)return t.content||""}return""}getRelatedQuesion(e){return h(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],i=wr(t==null?void 0:t.recommendQuestionOpen,t==null?void 0:t.relatedQuestionApp,e.content,this.currentUserQuestion());if(i===null)return e;this.event.emit("message:relatedQuesion:loading",e);const s=yield this.cvforceApi.postGeneques({content:i}).catch(l=>null);if(!s){const l=[],d=E(v({},e),{relatedQuesion:l,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:l}),this.event.emit("message:updated",d),d}const r=(a=s.content)==null?void 0:a.split("*").map(gr).map(yr).filter(l=>!!l);e.relatedQuesion=r,e.index=-3,e.isLoading=!1;const o=E(v({},e),{relatedQuesion:r,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",o),this.event.emit("message:updated",o),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:r}),o})}fillMessageReference(e){return h(this,null,function*(){try{const t=yield Promise.all(e.reference.map(i=>this.cvforceApi.getKnowledgeIdFileId(i.knowledgeId,i.docId)));e.reference=e.reference.map((i,s)=>v(v({},i),t[s]))}catch(t){console.error("Failed to fill message reference:",t)}return this.event.emit("message:updated",e),e})}answerAgain(){return h(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:i=exports.configuration.stream}=e;let s;t.role!==x.ChatMessageRole.User&&(s=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],o={content:r.content,fileIds:r.fileIds,requestId:r.messageId,stream:i,oldMessageId:s},c=a=>h(this,null,function*(){if(a.role===x.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(o,E(v({},e),{stream:i}))})}setTop(e){return h(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 i;this.stopAnswer(),this.frozen=!1,this._stopAnswer=!0;let e=this.messages[this.messages.length-1];const t={messageId:_e.v4(),isLoading:!1,index:-2,messageTime:Et(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:x.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const s=e.actions[((i=e.actions)==null?void 0:i.length)-1];if(s){const r=s[s.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:o,pluginCode:c,funcCode:a,funcName:l}=r.data;s.push({data:{pluginName:o,pluginCode:c,funcCode:a,funcName:l,step:r.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:s})}}}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 o;if(!e.data)return;const i=e.data.type,s=e.data.payload;t.isReplying=!0;const r=()=>{if(!t.searchingStatus){t.searchingStatus="start";return}if(t.searchingStatus==="start"){t.searchingStatus="end";return}};if(i==="error"&&(t.index=-1),i==="beforeSearch"&&r(),i==="searchOver"&&r(),i==="search"&&t.searchReference.push(s),i==="thinking"){t.thinkingStatus="start";const a=s.choices[0];t.reasoningContent=(t.reasoningContent||"")+((o=a.delta.reasoningContent)!=null?o:"")}if(i==="thinkingOver"){t.thinkingStatus="end";const c=s.thinkingSecs;t.thinkingSecs=c}if(i==="text"){const a=s.choices[0];t.content=(t.content||"")+a.delta.content}if(i==="reference"&&(t.reference=s),i==="updateSession"&&s&&this.data&&(this.data=v(v({},this.data),s),this.event.emit("data:updated",this.data)),i==="result"){const c=s.messageId,a=s.llmModel,l=s.messageTime;t.messageId=c,t.llmModel=a,t.messageTime=l}i==="over"?t.index=-1:(t.code=e.code,t.message=e.message)}getArtifacts(){return h(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 h(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 i=this.messages.find(s=>s.messageId===e.messageId);return i&&(i.comment=e,this.event.emit("message:comment",i)),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 H=new U("[AgentSession] ");function En(n){if(typeof n!="string")return n;const e=n.trim();if(e)try{return JSON.parse(e)}catch(t){return n}}function In(n){return n==null||n===""||typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function jr(n,e){const t=En(n==null?void 0:n.query);if(!In(t))return t;const i=En(e);return In(i)&&t!=null?t:i}class Ur extends zt{constructor(t,i="",s,r,o,c){super(t,i,s,r,o,c);y(this,"inflightCalls",new Set)}prepareConnection(){return new Promise(t=>h(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?ge.Debug:ge.Normal},s=new URL(exports.configuration.apiRoot),r=yield Di.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 c=exports.configuration.debug?ge.Debug:ge.Normal;c===ge.Debug&&o.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(Re.SocketConnectionFailed);H.error("error",c),this.event.emit("error",c),t(!1)}}),r.on("action",(o,c)=>h(this,null,function*(){var w;if(this._stopAnswer||!this.id)return;const{type:a,data:{runnerIsClient:l,pluginCode:d,funcCode:u,parameters:f,requestBody:g}}=o,_=this.messages[this.messages.length-1];if(!_.messageId)_.actions||(_.actions=[]),_.actions[o.data.step-1]||(_.actions[o.data.step-1]=[]),_.actions[o.data.step-1].push(o),this.event.emit("message:action",{messageId:_.messageId,action:o}),this.event.emit("message:updated",_);else{const b={messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[o]],comment:{isAgree:0},isReplying:!0};this.pushMessage(b),this.event.emit("message:action",{messageId:b.messageId,action:o})}if(this.inactivating){const b=new Error(Re.Inactive);H.warn("error",b),this.event.emit("error",b)}else if(a==="FUNCTION_CALL"&&l){H.log(`calling function ${u} of plugin ${d} with argument:
367
367
  ${JSON.stringify(f)}`);const b=(w=exports.configuration.plugins)==null?void 0:w[d];if(!b){c({code:404,message:"没有找到插件。"});return}const A=b[u];if(typeof A!="function"){c({code:404,message:"没有找到插件方法。"});return}const I=jr(f,g);this.invokeClientPlugin(A,I,c,{requestId:o.requestId,pluginCode:d,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 c=this.messages[this.messages.length-1];if(c&&c.role===x.ChatMessageRole.Robot)this.handleStreamAnswer(o.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:x.ChatMessageRole.Robot,reference:[],searchReference:[],messageId:"",sessionId:this.id,messageTime:Et(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""};this.handleStreamAnswer(o.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(o.data.updateSession&&this.data&&(this.data=v(v({},this.data),o.data.updateSession),this.event.emit("data:updated",this.data)),o.data.index===-1){let c=this.messages[this.messages.length-1];if(c&&!c.messageId)c=v(v({},c),o.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:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.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),o.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: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=>h(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const f=new Error(Re.IdUndefined);H.error(f),this.event.emit("error",f),this.frozen=!1;return}const{type:c,data:a,requestId:l}=o,d=this.messages.findIndex(f=>f.messageId===l&&f.role===x.ChatMessageRole.User);if(d<0)return;const u=d+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)}c==="KG"?(this.messages[u]=E(v({},this.messages[u]),{reference:a.knowledgeReference}),yield this.fillMessageReference(this.messages[u]),this.event.emit("message:reference",a.knowledgeReference),this.event.emit("message:updated",this.messages[u])):c==="WEB_SEARCH"&&(this.messages[u]=E(v({},this.messages[u]),{searchReference:a.knowledgeReference}),this.event.emit("message:searchreference",a.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)}addMcpServers(t){return h(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 h(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 h(this,null,function*(){var r,o,c;this.convertKnowledgesToChatFormat(this.knowledges);let s=E(v({},t),{promptVariables:this.promptVariables.filter(a=>a.type===x.PromptVariableType.User).reduce((a,l)=>E(v({},a),{[l.key]:l.value}),{}),systemPromptVariables:this.promptVariables.filter(a=>a.type===x.PromptVariableType.System).reduce((a,l)=>E(v({},a),{[l.key]:l.value}),{}),knowledges:(r=this.knowledges)==null?void 0:r.map(a=>a.id),enableTitleSummary:this.resolveEnableTitleSummary()});if(!this.active){if(yield this.activate(),!this.socket){const a=new Error(Re.SocketConnectionFailed);return H.warn("error",a),this.event.emit("error",a),!1}(o=this.socket)==null||o.emit("question",s);return}(c=this.socket)==null||c.emit("question",s)})}invokeClientPlugin(t,i,s,r){const o=new AbortController;this.inflightCalls.add(o);let c=!1;const a=(...d)=>{c||(c=!0,this.inflightCalls.delete(o),!(this._stopAnswer||o.signal.aborted)&&s(...d))},l={requestId:r.requestId||_e.v4(),applicationId:this._applicationId,sessionId:this.id,pluginCode:r.pluginCode,functionCode:r.functionCode,signal:o.signal};try{const d=t(i,a,l);d&&typeof d.catch=="function"&&d.catch(u=>{H.error("client plugin failed",u),a({code:500,message:"客户端插件执行失败。"})})}catch(d){H.error("client plugin failed",d),a({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 Hr(n,e){return h(this,null,function*(){const t=n.getReader();let i;for(;!(i=yield t.read()).done;)e(i.value)})}function qr(n){let e,t,i,s=!1,r;return function(c){e===void 0?(e=c,t=0,i=-1,r=!1):e=zr(e,c);const a=e.length;let l=0;for(;t<a;){s&&(e[t]===10&&(l=++t),s=!1);let d=-1;for(;t<a&&d===-1;++t)switch(e[t]){case 58:i===-1&&(i=t-l);break;case 13:s=!1,t+4<a&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(r=!0);case 10:d=t;break}if(d===-1)break;n(e.subarray(l,d),i,r),l=t,i=-1,r=!1}l===a?e=void 0:l!==0&&(e=e.subarray(l),t-=l)}}function Wr(n,e,t){let i=kn();const s=new TextDecoder;return function(o,c,a){if(o.length===0)t==null||t(i),i=kn();else if(c>0){const l=s.decode(o.subarray(0,c)),d=c+(o[c+1]===32?2:1);let u=s.decode(o.subarray(d));switch(a&&(u+=`
368
368
  `),l){case"data":i.data=i.data?i.data+`
369
- `+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 zr(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function kn(){return{data:"",event:"",id:"",retry:void 0}}const St="text/event-stream",Vr=1e3,xn="last-event-id";function An(n,d){var u=d,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:c,fetch:a}=u,l=Kt(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,g)=>{const _=v({},t);_.accept||(_.accept=St);let w;function b(){w.abort(),document.hidden||O()}c||document.addEventListener("visibilitychange",b);let A=Vr,I=0;function T(){document.removeEventListener("visibilitychange",b),window.clearTimeout(I),w.abort()}e==null||e.addEventListener("abort",()=>{T(),f()});const R=a!=null?a:window.fetch,J=i!=null?i:Gr;function O(){return h(this,null,function*(){var k;w=new AbortController;try{const M=yield R(n,E(v({},l),{headers:_,signal:w.signal}));yield J(M),yield Hr(M.body,qr(Wr(C=>{C?_[xn]=C:delete _[xn]},C=>{A=C},s))),r==null||r(),T(),f()}catch(M){if(!w.signal.aborted)try{const C=(k=o==null?void 0:o(M))!=null?k:A;window.clearTimeout(I),I=window.setTimeout(O,C)}catch(C){T(),g(C)}}})}O()})}function Gr(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith(St)))throw new Error(`Expected content-type to be ${St}, Actual: ${e}`)}const Tn=new U("[DialogSession] ");class Xr extends zt{constructor(t,i="",s,r,o,c){super(t,i,s,r,o,c);y(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>h(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,i,s,r,o,c){return h(this,null,function*(){const a={code:0,content:"",role:x.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},l=E(v({},s),{stream:exports.configuration.stream});An(`${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(d){return d.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(d){if(!d.data.includes('{"code": ')){let f={};try{f=JSON.parse(d.data)}catch(_){}(f==null?void 0:f.mtype)==="search"?a.searchReference.push(f):a.content=a.content+d.data;const g={content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:i,messageTime:Et(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(d.data);if(a.reference=u.data.reference,a.searchReference=u.data.searchReference,a.messageTime=u.data.messageTime,a.messageId=u.data.messageId,a.llmModel=u.data.llmModel,a.content=u.data.content,a.code=u.code,u.code===200){const f={code:a.code,content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:i,messageTime:a.messageTime,isReplying:!0};o!=null&&o.onmessage&&o.onmessage(f)}else return o!=null&&o.onclose&&o.onclose(a),c&&c({code:a.code,message:a.message})},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const d={code:a.code,content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:i,messageTime:a.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};o!=null&&o.onclose&&o.onclose(d)}})})}postChatV3EventSource(t,i,s,r,o,c){return h(this,null,function*(){const a=this,l={code:0,content:"",role:x.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},d=E(v({},s),{stream:exports.configuration.stream});An(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),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),c&&c({code:f.code,message:f.message});a.handleStreamAnswer(f,l),o!=null&&o.onmessage&&o.onmessage(l)},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const u=E(v({},l),{isReplying:!1});o!=null&&o.onclose&&o.onclose(u)}})})}sendQuestion(t,i){return h(this,null,function*(){const{content:s,fileIds:r,oldMessageId:o,imageContent:c}=t,{stream:a,referenceFirst:l}=i;if(this.active||(yield this.activate()),this._id){const d=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)=>E(v({},f),{[g.key]:g.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===x.PromptVariableType.System).reduce((f,g)=>E(v({},f),{[g.key]:g.value}),{}),knowledges:d,enableTitleSummary:this.resolveEnableTitleSummary(),imageContent:c};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,u,this.ctrl.signal,{onopen:()=>{Tn.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=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=>h(this,null,function*(){this._stopAnswer||(Tn.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 h(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return h(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return h(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 Yr="@glodon-aiot/bot-client-sdk",Kr="3.26.0-alpha.14",Jr="glodoncv",Qr="aiot bot client js sdk",Zr="module",eo=!1,to=["aiot","bot","bot client","sdk"],no=["dist"],io="./dist/es/index.mjs",so="./dist/lib/index.js",ro="./dist/src/index.d.ts",oo={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},ao="MIT",co={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"},lo={"@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"},ho={access:"public",registry:"https://registry.npmjs.org/"},uo={"@glodon-aiot/apis":"^3.26.0-alpha.14",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"},fo={name:Yr,version:Kr,author:Jr,description:Qr,type:Zr,sideEffects:eo,keywords:to,files:no,module:io,main:so,typings:ro,exports:oo,license:ao,scripts:co,devDependencies:lo,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:ho,dependencies:uo},Rn=new U("[BotClient] ");class po{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){y(this,"event",new Ut);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,_t(t,{refreshBuiltinPlugins:!1}),this._applicationId=Xe(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{_t(E(v({},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)){wn(void 0),vt();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,(c,a)=>Rn.error(a));this._localWorkspace=new Ii({applicationId:this._applicationId,config:e,store:Ei(),picker:i==="host-bridge"?null:void 0,transfer:qt(()=>this.cvforceApi,()=>o)}),wn(this._localWorkspace),this._localWorkspace.platformSkills=new Er({applicationId:()=>this._applicationId,getToken:()=>this.token,getSkills:()=>{var c,a,l,d;return(d=(l=(a=(c=this._application)==null?void 0:c.arrange)==null?void 0:a[0])==null?void 0:l.skills)!=null?d:[]},apiRoot:()=>exports.configuration.apiRoot,getSandbox:()=>{var a;const c=(a=this._localWorkspace)==null?void 0:a.adapter;return c instanceof Je?c.sandbox:void 0}}),i==="host-bridge"?this._disconnectHost=kr(this._localWorkspace):this._localWorkspace.restore()}t.push(...vt()),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 h(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:fo.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),E(v({},c),{arrange:[E(v({},c.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&c.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(c=>c.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(([c,a])=>[...c,...a]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:mi(exports.configuration.apiRoot,this.token,(e,t)=>Rn.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=Xe(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 h(this,null,function*(){const o=this;return new Promise((c,a)=>{const l=d=>h(this,null,function*(){if(d===x.ApplicationTypes.Agent)c(new Ur(e,t,i,s,r,o));else if(d===x.ApplicationTypes.Dialog)c(new Xr(e,t,i,s,r,o));else throw Error(`不支持的应用类型:${d}`)});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 h(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(c=>c.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 h(this,null,function*(){return new Promise((t,i)=>{const s=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>h(this,null,function*(){const o=[];for(const c of r){const a=this._sessions.find(l=>l.id===c.id);if(a)a.data=c,this._application?a.application=this._application:yield a.loadApplicationInfo(),o.push(a);else{const l=yield this.createSession(this.token,c.id,c,this.lazyload,this._application||void 0);o.push(l)}}if(e!=null&&e.pageSize){const c=[...this._sessions,...o],a=new Map;for(const l of c)a.set(l.id,l);return this.sessions=Array.from(a.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 h(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(()=>h(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return h(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 h(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 h(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 mo{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 z="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",V={type:"string",enum:[be],description:`工作区 ID。省略时按 ${be} 处理,传其他值会被拒绝。`},G=n=>({type:"string",description:`${n}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),ct={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},ki={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${z}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:V,path:G('要列出的目录,省略或传 "." 表示工作区根目录。'),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:V,path:G("要读取的文件。"),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:V,path:G("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${z}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:V,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:G("搜索起点目录,默认工作区根目录。"),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:V,path:G("搜索范围,可以是文件或目录。"),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:V,path:G("要修改的文件。"),expectedHash:ct,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:V,path:G("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:ct,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:V,path:G("要上传的文件。"),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:V,destPath:G("保存位置(文件路径)。"),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:ct}}}},go=new TextEncoder;function ee(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const yo=(n,e)=>h(exports,null,function*(){const t=K(n.path,{allowRoot:!0});if((yield e.adapter.stat(t)).kind!=="directory")throw new m(p.BadRequest,"目标是文件,不是目录。");const s=ee(n.offset,0,0,Number.MAX_SAFE_INTEGER),r=ee(n.limit,Dn,1,Pn),o=yield e.adapter.listEntries(t,e.signal);o.sort((a,l)=>a.kind!==l.kind?a.kind==="directory"?-1:1:a.name<l.name?-1:a.name>l.name?1:0);const c=o.slice(s,s+r).map(a=>{const l=vi(t,a.name),d={name:a.name,path:l,kind:a.kind};return a.kind==="file"&&(d.size=a.size,d.lastModified=a.lastModified,e.sensitive.isSensitive(l)&&(d.sensitive=!0)),d});return{data:{path:t,entries:c,total:o.length,hasMore:s+c.length<o.length}}});function wo(n,e,t){return de(this,null,function*(){var c;const i=new TextDecoder(e),s=n.stream().getReader();let r="",o=!1;try{for(;;){N(t);const{done:a,value:l}=yield new te(s.read());r+=a?i.decode():i.decode(l,{stream:!0});const d=r.split(`
369
+ `+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 zr(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function kn(){return{data:"",event:"",id:"",retry:void 0}}const St="text/event-stream",Vr=1e3,xn="last-event-id";function An(n,d){var u=d,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:c,fetch:a}=u,l=Kt(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,g)=>{const _=v({},t);_.accept||(_.accept=St);let w;function b(){w.abort(),document.hidden||O()}c||document.addEventListener("visibilitychange",b);let A=Vr,I=0;function T(){document.removeEventListener("visibilitychange",b),window.clearTimeout(I),w.abort()}e==null||e.addEventListener("abort",()=>{T(),f()});const R=a!=null?a:window.fetch,J=i!=null?i:Gr;function O(){return h(this,null,function*(){var k;w=new AbortController;try{const M=yield R(n,E(v({},l),{headers:_,signal:w.signal}));yield J(M),yield Hr(M.body,qr(Wr(C=>{C?_[xn]=C:delete _[xn]},C=>{A=C},s))),r==null||r(),T(),f()}catch(M){if(!w.signal.aborted)try{const C=(k=o==null?void 0:o(M))!=null?k:A;window.clearTimeout(I),I=window.setTimeout(O,C)}catch(C){T(),g(C)}}})}O()})}function Gr(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith(St)))throw new Error(`Expected content-type to be ${St}, Actual: ${e}`)}const Tn=new U("[DialogSession] ");class Xr extends zt{constructor(t,i="",s,r,o,c){super(t,i,s,r,o,c);y(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>h(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,i,s,r,o,c){return h(this,null,function*(){const a={code:0,content:"",role:x.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},l=E(v({},s),{stream:exports.configuration.stream});An(`${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(d){return d.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(d){if(!d.data.includes('{"code": ')){let f={};try{f=JSON.parse(d.data)}catch(_){}(f==null?void 0:f.mtype)==="search"?a.searchReference.push(f):a.content=a.content+d.data;const g={content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:i,messageTime:Et(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(d.data);if(a.reference=u.data.reference,a.searchReference=u.data.searchReference,a.messageTime=u.data.messageTime,a.messageId=u.data.messageId,a.llmModel=u.data.llmModel,a.content=u.data.content,a.code=u.code,u.code===200){const f={code:a.code,content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:i,messageTime:a.messageTime,isReplying:!0};o!=null&&o.onmessage&&o.onmessage(f)}else return o!=null&&o.onclose&&o.onclose(a),c&&c({code:a.code,message:a.message})},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const d={code:a.code,content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:i,messageTime:a.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};o!=null&&o.onclose&&o.onclose(d)}})})}postChatV3EventSource(t,i,s,r,o,c){return h(this,null,function*(){const a=this,l={code:0,content:"",role:x.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},d=E(v({},s),{stream:exports.configuration.stream});An(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),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),c&&c({code:f.code,message:f.message});a.handleStreamAnswer(f,l),o!=null&&o.onmessage&&o.onmessage(l)},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const u=E(v({},l),{isReplying:!1});o!=null&&o.onclose&&o.onclose(u)}})})}sendQuestion(t,i){return h(this,null,function*(){const{content:s,fileIds:r,oldMessageId:o,imageContent:c}=t,{stream:a,referenceFirst:l}=i;if(this.active||(yield this.activate()),this._id){const d=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)=>E(v({},f),{[g.key]:g.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===x.PromptVariableType.System).reduce((f,g)=>E(v({},f),{[g.key]:g.value}),{}),knowledges:d,enableTitleSummary:this.resolveEnableTitleSummary(),imageContent:c};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,u,this.ctrl.signal,{onopen:()=>{Tn.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=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=>h(this,null,function*(){this._stopAnswer||(Tn.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 h(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return h(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return h(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 Yr="@glodon-aiot/bot-client-sdk",Kr="3.26.0-alpha.15",Jr="glodoncv",Qr="aiot bot client js sdk",Zr="module",eo=!1,to=["aiot","bot","bot client","sdk"],no=["dist"],io="./dist/es/index.mjs",so="./dist/lib/index.js",ro="./dist/src/index.d.ts",oo={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},ao="MIT",co={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"},lo={"@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"},ho={access:"public",registry:"https://registry.npmjs.org/"},uo={"@glodon-aiot/apis":"^3.26.0-alpha.15",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"},fo={name:Yr,version:Kr,author:Jr,description:Qr,type:Zr,sideEffects:eo,keywords:to,files:no,module:io,main:so,typings:ro,exports:oo,license:ao,scripts:co,devDependencies:lo,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:ho,dependencies:uo},Rn=new U("[BotClient] ");class po{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){y(this,"event",new Ut);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,_t(t,{refreshBuiltinPlugins:!1}),this._applicationId=Xe(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{_t(E(v({},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)){wn(void 0),vt();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,(c,a)=>Rn.error(a));this._localWorkspace=new Ii({applicationId:this._applicationId,config:e,store:Ei(),picker:i==="host-bridge"?null:void 0,transfer:qt(()=>this.cvforceApi,()=>o)}),wn(this._localWorkspace),this._localWorkspace.platformSkills=new Er({applicationId:()=>this._applicationId,getToken:()=>this.token,getSkills:()=>{var c,a,l,d;return(d=(l=(a=(c=this._application)==null?void 0:c.arrange)==null?void 0:a[0])==null?void 0:l.skills)!=null?d:[]},apiRoot:()=>exports.configuration.apiRoot,getSandbox:()=>{var a;const c=(a=this._localWorkspace)==null?void 0:a.adapter;return c instanceof Je?c.sandbox:void 0}}),i==="host-bridge"?this._disconnectHost=kr(this._localWorkspace):this._localWorkspace.restore()}t.push(...vt()),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 h(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:fo.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),E(v({},c),{arrange:[E(v({},c.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&c.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(c=>c.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(([c,a])=>[...c,...a]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:mi(exports.configuration.apiRoot,this.token,(e,t)=>Rn.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=Xe(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 h(this,null,function*(){const o=this;return new Promise((c,a)=>{const l=d=>h(this,null,function*(){if(d===x.ApplicationTypes.Agent)c(new Ur(e,t,i,s,r,o));else if(d===x.ApplicationTypes.Dialog)c(new Xr(e,t,i,s,r,o));else throw Error(`不支持的应用类型:${d}`)});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 h(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(c=>c.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 h(this,null,function*(){return new Promise((t,i)=>{const s=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>h(this,null,function*(){const o=[];for(const c of r){const a=this._sessions.find(l=>l.id===c.id);if(a)a.data=c,this._application?a.application=this._application:yield a.loadApplicationInfo(),o.push(a);else{const l=yield this.createSession(this.token,c.id,c,this.lazyload,this._application||void 0);o.push(l)}}if(e!=null&&e.pageSize){const c=[...this._sessions,...o],a=new Map;for(const l of c)a.set(l.id,l);return this.sessions=Array.from(a.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 h(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(()=>h(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return h(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 h(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 h(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 mo{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 z="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",V={type:"string",enum:[be],description:`工作区 ID。省略时按 ${be} 处理,传其他值会被拒绝。`},G=n=>({type:"string",description:`${n}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),ct={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},ki={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${z}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:V,path:G('要列出的目录,省略或传 "." 表示工作区根目录。'),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:V,path:G("要读取的文件。"),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:V,path:G("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${z}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:V,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:G("搜索起点目录,默认工作区根目录。"),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:V,path:G("搜索范围,可以是文件或目录。"),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:V,path:G("要修改的文件。"),expectedHash:ct,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:V,path:G("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:ct,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:V,path:G("要上传的文件。"),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:V,destPath:G("保存位置(文件路径)。"),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:ct}}}},go=new TextEncoder;function ee(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const yo=(n,e)=>h(exports,null,function*(){const t=K(n.path,{allowRoot:!0});if((yield e.adapter.stat(t)).kind!=="directory")throw new m(p.BadRequest,"目标是文件,不是目录。");const s=ee(n.offset,0,0,Number.MAX_SAFE_INTEGER),r=ee(n.limit,Dn,1,Pn),o=yield e.adapter.listEntries(t,e.signal);o.sort((a,l)=>a.kind!==l.kind?a.kind==="directory"?-1:1:a.name<l.name?-1:a.name>l.name?1:0);const c=o.slice(s,s+r).map(a=>{const l=vi(t,a.name),d={name:a.name,path:l,kind:a.kind};return a.kind==="file"&&(d.size=a.size,d.lastModified=a.lastModified,e.sensitive.isSensitive(l)&&(d.sensitive=!0)),d});return{data:{path:t,entries:c,total:o.length,hasMore:s+c.length<o.length}}});function wo(n,e,t){return de(this,null,function*(){var c;const i=new TextDecoder(e),s=n.stream().getReader();let r="",o=!1;try{for(;;){N(t);const{done:a,value:l}=yield new te(s.read());r+=a?i.decode():i.decode(l,{stream:!0});const d=r.split(`
370
370
  `);r=(c=d.pop())!=null?c:"";for(const u of d)o=!0,yield u;if(a)break}}finally{s.releaseLock()}(r||!o)&&(yield r)})}const vo=(n,e)=>h(exports,null,function*(){var T,R;const t=K(n.path);Ie(e,t,"read");const i=yield Ot(e.adapter,t),s=yield e.adapter.readFile(t),r=(T=i.size)!=null?T:s.size;if(yield cs(s))throw new m(p.BadRequest,"这是二进制文件,不能按文本读取。可以使用 stat_file 查看信息,或使用 upload_file 上传到会话。");const o=yield q(s.slice(0,3)),c=ii(o)?"utf-8":(R=n.encoding)!=null?R:"utf-8",a=ee(n.startLine,1,1,Number.MAX_SAFE_INTEGER),l=n.endLine===void 0?Number.MAX_SAFE_INTEGER:Math.max(Math.trunc(n.endLine),a),d=ee(n.maxBytes,e.limits.maxReadBytes,1,e.limits.maxReadBytes),u=r<=e.limits.maxTransferBytes,f=[];let g=0,_=0,w=a-1,b=!1,A=!1;try{for(var J=W(wo(s,c,e.signal)),O,k,M;O=!(k=yield J.next()).done;O=!1){const C=k.value;_++;const $=C.endsWith("\r")?C.slice(0,-1):C;if($!==C&&(A=!0),_<a||_>l||b){if(!u&&(b||_>l))break;continue}const ce=$t($)+(f.length?1:0);if(g+ce>d){if(b=!0,f.length||(f.push(_o($,d)),w=_),!u)break;continue}f.push($),g+=ce,w=_}}catch(k){M=[k]}finally{try{O&&(k=J.return)&&(yield k.call(J))}finally{if(M)throw M[0]}}const I={path:t,content:f.join(`
371
371
  `),startLine:a,endLine:Math.max(w,a-1),size:r,encoding:c,lineEnding:A?"crlf":"lf"};return u&&(I.totalLines=_),r<=e.limits.maxWriteBytes&&(I.hash=yield Se(yield q(s))),{data:I,truncated:b||void 0}});function _o(n,e){const t=go.encode(n);return t.byteLength<=e?n:new TextDecoder().decode(t.slice(0,e)).replace(/\uFFFD$/,"")}const bo=(n,e)=>h(exports,null,function*(){var r;const t=K(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 Se(yield q(yield e.adapter.readFile(t))))),{data:s}});function So(n){return zn.some(e=>Ve(e,n))}function xi(n,e,t){return de(this,null,function*(){const i=[{path:e,depth:0}];let s=0;for(;i.length;){const r=i.shift();N(n.signal),++s%20===0&&(yield new te(si()));const o=yield new te(n.adapter.listEntries(r.path,n.signal));o.sort((c,a)=>c.name<a.name?-1:c.name>a.name?1:0);for(const c of o){const a=vi(r.path,c.name);if(c.kind==="directory"){r.depth+1<t&&!Wn.includes(c.name)&&i.push({path:a,depth:r.depth+1});continue}So(c.name)||n.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 Ai(n,e){return n.includes("/")?Ve(n,e.relativePath):Ve(n,e.name)}const Eo=(n,e)=>h(exports,null,function*(){const t=K(n.path,{allowRoot:!0});if(!n.pattern.trim())throw new m(p.BadRequest,"参数 pattern 不能为空。");const i=n.pattern.replace(/\\/g,"/").replace(/^\.\//,"");if((yield e.adapter.stat(t)).kind!=="directory")throw new m(p.BadRequest,"参数 path 必须是目录。");const r=ee(n.maxDepth,Bn,1,kt),o=ee(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),c=[];let a=!1;try{for(var l=W(xi(e,t,r)),d,u,f;d=!(u=yield l.next()).done;d=!1){const g=u.value;if(Ai(i,g)){if(c.length>=o){a=!0;break}c.push({path:g.path,size:g.size,lastModified:g.lastModified})}}}catch(u){f=[u]}finally{try{d&&(u=l.return)&&(yield u.call(l))}finally{if(f)throw f[0]}}return{data:{matches:c},truncated:a||void 0}});function lt(n,e){if(n.length<=Ue)return n;const t=Math.max(0,Math.min(e-100,n.length-Ue));return n.slice(t,t+Ue)}const Io=(n,e)=>h(exports,null,function*(){var f;const t=K(n.path,{allowRoot:!0});if(!t&&!e.allowWorkspaceWideTextSearch)throw new m(p.BadRequest,"不支持在整个工作区内搜索文本,请把 path 缩小到具体的子目录或文件。");if(n.isRegex)throw new m(p.NotImplemented,"暂不支持正则搜索,请使用普通文本搜索。");if(!n.query)throw new m(p.BadRequest,"参数 query 不能为空。");const i=n.caseSensitive===!0,s=i?n.query:n.query.toLowerCase(),r=ee(n.contextLines,0,0,Hn),o=ee(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),c=yield e.adapter.stat(t);let a;c.kind==="file"?(Ie(e,t,"search"),a=function(){return de(this,null,function*(){yield{path:t,relativePath:t,name:c.name,size:c.size}})}()):a=xi(e,t,kt);const l=[];let d=0,u=!1;e:try{for(var g=W(a),_,w,b;_=!(w=yield g.next()).done;_=!1){const A=w.value;if(n.glob&&!Ai(n.glob,A)||((f=A.size)!=null?f:0)>Un)continue;if(d>=jn){u=!0;break}d++,d%20===0&&(yield si()),N(e.signal);const I=yield q(yield e.adapter.readFile(A.path));if(ae(I))continue;const T=new TextDecoder("utf-8").decode(I).split(/\r?\n/);for(let R=0;R<T.length;R++){const O=(i?T[R]:T[R].toLowerCase()).indexOf(s);if(O<0)continue;if(l.length>=o){u=!0;break e}const k={path:A.path,line:R+1,column:O+1,text:lt(T[R],O)};r&&(k.before=T.slice(Math.max(0,R-r),R).map(M=>lt(M,0)),k.after=T.slice(R+1,R+1+r).map(M=>lt(M,0))),l.push(k)}}}catch(w){b=[w]}finally{try{_&&(w=g.return)&&(yield w.call(g))}finally{if(b)throw b[0]}}return{data:{matches:l,filesScanned:d},truncated:u||void 0}});function Ln(){return new m(p.Forbidden,"下载地址不在允许范围内:只允许 https 协议且域名在白名单中的地址。",{reason:"url_not_allowed"})}const ko=(n,e)=>h(exports,null,function*(){var u,f;const t=K(n.path);if(((u=n.target)!=null?u:"session")!=="session")throw new m(p.NotImplemented,"目前只支持上传到当前会话(target: session)。");Ie(e,t,"read");const s=yield Ot(e.adapter,t),r=(f=s.size)!=null?f:0;if(r>e.limits.maxTransferBytes)throw oe(e.limits.maxTransferBytes);const o=Nt(t);yield e.requestApproval(t,{type:"upload",name:o,size:r,target:"session"}),e.progress({stage:"reading",loaded:0,total:r,path:t});const c=yield e.adapter.readFile(t);N(e.signal);const a=new File([c],o,{type:n.mimeHint||c.type||"application/octet-stream",lastModified:s.lastModified}),{fileId:l,url:d}=yield e.transfer.upload(a,e.context,({loaded:g,total:_})=>e.progress({stage:"uploading",loaded:g,total:_,path:t}));return N(e.signal),e.progress({stage:"done",loaded:r,total:r,path:t}),{data:{fileId:l,name:o,size:r,url:d}}});function xo(n){const e=n;if(!e||typeof e!="object")throw new m(p.BadRequest,"缺少参数 source。");if(e.type==="sessionFile"||e.type==="platformFile"){if(typeof e.fileId!="string"||!e.fileId)throw new m(p.BadRequest,"source.fileId 必须是非空字符串。");return{type:e.type,fileId:e.fileId}}if(e.type==="url"){if(typeof e.url!="string"||!e.url)throw new m(p.BadRequest,"source.url 必须是非空字符串。");return{type:"url",url:e.url}}throw new m(p.BadRequest,"source.type 必须是 sessionFile、platformFile 或 url 之一。")}function Ao(n){return n.type==="sessionFile"?"会话文件":n.type==="platformFile"?"平台文件":new URL(n.url).hostname}function To(n,e,t,i,s){return de(this,null,function*(){const r=n.getReader();let o=0;try{for(;;){N(e.signal);const{done:c,value:a}=yield new te(r.read());if(c)break;if(o+=a.byteLength,o>e.limits.maxTransferBytes)throw oe(e.limits.maxTransferBytes,"下载内容");s.push(a),e.progress({stage:"downloading",loaded:o,total:i,path:t}),yield a}}finally{r.cancel().catch(()=>{})}})}const Ro=(n,e)=>h(exports,null,function*(){var w,b,A;const t=K(n.destPath,{field:"destPath"}),i=xo(n.source);if(i.type==="url"&&!bt(i.url,e.downloadUrlAllowlist))throw Ln();Ie(e,t,"write");const s=yield He(e.adapter,t);if((s==null?void 0:s.kind)==="directory")throw new m(p.BadRequest,"目标是目录,不能写入文件。");if(s&&!n.overwrite)throw new m(p.Conflict,"目标文件已存在。如需覆盖,请设置 overwrite: true。");const r=()=>h(exports,null,function*(){if(!s||!n.expectedHash)return;const I=yield Se(yield q(yield e.adapter.readFile(t)));if(I!==n.expectedHash)throw new m(p.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 oe(e.limits.maxTransferBytes);const c={type:"download",source:{type:i.type,label:Ao(i)},name:(w=o.name)!=null?w:Nt(t),size:o.size,overwrite:!!s};yield e.requestApproval(t,c),yield r();let a;try{a=yield e.fetch(o.url,{headers:o.headers,credentials:"omit",redirect:"follow",signal:e.signal})}catch(I){throw N(e.signal),new m(p.Internal,"下载失败,无法连接到文件地址。")}if(i.type==="url"&&a.url&&!bt(a.url,e.downloadUrlAllowlist))throw(b=a.body)==null||b.cancel().catch(()=>{}),Ln();if(!a.ok||!a.body)throw(A=a.body)==null||A.cancel().catch(()=>{}),new m(a.status===404?p.NotFound:p.Internal,`下载失败(HTTP ${a.status})。`);const l=Number(a.headers.get("content-length")),d=Number.isFinite(l)&&l>0?l:void 0;if(d!==void 0&&d>e.limits.maxTransferBytes)throw a.body.cancel().catch(()=>{}),oe(e.limits.maxTransferBytes);const u=[];yield e.adapter.writeFile(t,To(a.body,e,t,d,u),{signal:e.signal});const f=u.reduce((I,T)=>I+T.byteLength,0),g=new Uint8Array(f);let _=0;return u.forEach(I=>{g.set(I,_),_+=I.byteLength}),e.progress({stage:"done",loaded:f,total:f,path:t}),{data:{path:t,size:f,hash:yield Se(g)}}}),dt=new Uint8Array([239,187,191]);function Ye(n,e){return new m(p.Conflict,e,{currentHash:n})}function Vt(n,e){return h(this,null,function*(){var s;if(((s=(yield Ot(n.adapter,e)).size)!=null?s:0)>n.limits.maxWriteBytes)throw oe(n.limits.maxWriteBytes,"目标文件");const i=yield q(yield n.adapter.readFile(e));return{bytes:i,hash:yield Se(i)}})}function Ti(n,e,t){return h(this,null,function*(){const{hash:i}=yield Vt(n,e);if(i!==t)throw Ye(i,"文件在确认期间已被修改,本次写入已取消。请重新读取后再修改。")})}function Lo(n,e){const t=new TextEncoder().encode(n);if(!e)return t;const i=new Uint8Array(dt.byteLength+t.byteLength);return i.set(dt,0),i.set(t,dt.byteLength),i}function Mo(n,e){let t=0,i=n.indexOf(e);for(;i>=0;)t++,i=n.indexOf(e,i+e.length);return t}function Mn(n,e){return!e||n.includes(`\r
372
372
  `)?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.14",
3
+ "version": "3.26.0-alpha.15",
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.14",
91
+ "@glodon-aiot/apis": "^3.26.0-alpha.15",
92
92
  "axios": "0.24.0",
93
93
  "buffer": "^6.0.3",
94
94
  "dayjs": "^1.11.13",