@glodon-aiot/bot-client-sdk 3.26.0-alpha.12 → 3.26.0-alpha.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -202,7 +202,7 @@ const schema = pluginCode === getRegisteredLocalFilesPluginCode()
202
202
 
203
203
  - 工具参数使用工作区内以 `/` 开头的绝对路径,或相对工作区根的相对路径,例如 `/说明.md`、`notes/a.md`。
204
204
  - **不要**使用或新建 `input`、`output`、`uploads`、`tmp` 作为约定根目录。
205
- - 技能在 `skills/<名称>/` 下,只通过技能工具访问。
205
+ - 平台技能不在工程里。`load_skill`、`read_skill_resource`、`run_skill_script` 读取端侧缓存;`read_file`、`shell` 等拒绝第一段为 `skills` 的路径。
206
206
  - `/dev`、`/usr`、`/bin` 仍是系统路径。写进脚本文件里的路径请用相对路径。
207
207
 
208
208
  网页里由用户选择文件夹时依赖 File System Access API,只在 Chromium 内核(Chrome、Edge、WebView2)的安全上下文(https 或 localhost)中可用。端侧宿主自己掌握工程目录时,页面不再弹选择框,见[宿主通道](#宿主通道)。
@@ -262,11 +262,11 @@ const workspace = client.localWorkspace;
262
262
 
263
263
  **`run_file`** 执行已存在的脚本。浏览器:`.py`(Pyodide)、`.sh`(just-bash);`.js` / `node` 明确不支持。宿主沙箱:另支持 `.js`(沙箱自带 Node)。
264
264
 
265
- **`load_skill`** 读取 `skills/<名称>/SKILL.md`。
265
+ **`load_skill`** 读取编排里该技能已发布版本的 `SKILL.md`。技能包在工程外的平台缓存中,不在工作区 `skills/` 下。
266
266
 
267
- **`read_skill_resource`** 读取该技能目录内的相对路径。
267
+ **`read_skill_resource`** 读取该版本目录内的相对路径,只返回 UTF-8 文本。
268
268
 
269
- **`run_skill_script`** 执行技能脚本,`args` 是位置参数数组。工作目录为工作区根(与当前命令执行器一致)。
269
+ **`run_skill_script`** 在宿主沙箱里执行技能脚本,`args` 是位置参数数组。工作目录是工程根。用户文件按相对工程根传入。技能自己的资源按脚本文件所在目录查找。没有宿主沙箱时返回 501,不改走浏览器运行时。
270
270
 
271
271
  ### 浏览器里授权
272
272
 
@@ -455,7 +455,7 @@ function openApprovalDialog(request: ApprovalRequest): Promise<boolean> {
455
455
 
456
456
  ## 命令和脚本
457
457
 
458
- `shell`、`run_file`、`run_skill_script` 共用同一套执行器选择(`runnerFor`),成功时 `data` 为 `{ exitCode, stdout, stderr, cwd? }`。`exitCode !== 0` 仍是工具成功(`code === 0`)。跨命令只保留 cwd,不保留环境变量。
458
+ `shell`、`run_file` 共用同一套执行器选择(`runnerFor`)。`run_skill_script` 只用注入的执行器或已就绪的宿主沙箱,没有沙箱时不改走浏览器运行时。成功时 `data` 为 `{ exitCode, stdout, stderr, cwd? }`。`exitCode !== 0` 仍是工具成功(`code === 0`)。跨命令只保留 cwd,不保留环境变量。
459
459
 
460
460
  ### 执行器选择顺序
461
461
 
@@ -500,7 +500,8 @@ function openApprovalDialog(request: ApprovalRequest): Promise<boolean> {
500
500
  - 运行中崩溃时推送 `sandbox.state: "exited"`。同一次打开最多自动重启一次
501
501
  - 文件被其他程序占用时原文件保持不变,错误是「文件正在被占用,没有写入。」
502
502
  - 随安装包分发:`Resources/node/`(Node 24)+ `Resources/workspace-sandbox/`(`yarn bundle --platform …` 产物),可选 `python/`
503
- - 输出做路径反向替换,页面看不到工程绝对路径
503
+ - 输出做路径反向替换,页面看不到工程绝对路径,也看不到技能缓存的绝对路径
504
+ - 平台技能:进入会话时按编排 `arrange[0].skills` 核对已发布版本(`version >= 1`)。页面用当时的 `client.token` 作 `Authorization: Bearer` 下载 ZIP,再经已认证的本地 WebSocket 交给沙箱 `installSkill`。沙箱收不到这个令牌。缓存按系统放在用户目录(Windows `%LOCALAPPDATA%\glodon-workspace-sandbox`,macOS `~/Library/Caches/glodon-workspace-sandbox`,Linux `$XDG_CACHE_HOME` 或 `~/.cache` 下的同名目录),不在工程内。删除会话不删缓存;编排不再引用且没有脚本在跑的版本,下次进入会话时删除。非 debug 的对话气泡不显示这三个技能工具
504
505
  - 细节与 Windows 步骤见 [`local-workspace-windows-host.md`](../bot-client-ui/docs/local-workspace-windows-host.md)
505
506
 
506
507
  ## 宿主通道
@@ -1,4 +1,4 @@
1
- const e = "@glodon-aiot/bot-client-sdk", s = "3.26.0-alpha.12", 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.13", 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.12", t = "glodoncv",
68
68
  access: "public",
69
69
  registry: "https://registry.npmjs.org/"
70
70
  }, y = {
71
- "@glodon-aiot/apis": "^3.26.0-alpha.12",
71
+ "@glodon-aiot/apis": "^3.26.0-alpha.13",
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 di(n,e,t){return new A.CVForceApi(li(n,"/data/v1",e,t),hi(t))}function hr(n,e,t){return new A.AIShopApi(li(n,"/aishop",e,t),hi(t))}function li(n,e,t,i){const s=o=>{var c;return t&&(ar(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}`,d=Li.create({baseURL:a});return c&&d.interceptors.request.use(s),d}return r(e)}function hi(n){return{onHttpStatusError:(i,s)=>{i===401&&n(i,"aiotToken is invalid")},onAppStatusError:(i,s)=>{i!==10001&&i!==10215&&n(i,s)}}}function ur(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 fr(n){ie==null||ie(),ie=void 0;const e=Di();if(!e)return()=>{};const t=new Wn(e),i=r=>{const o=Oi(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(ur(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:St,type:"hello"});const s=()=>{e.removeEventListener("message",i),ie===s&&(ie=void 0)};return ie=s,s}const se=new U("[EventBus] ");class Pt{constructor(e=!1){w(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 pr="路径必须是工作区内的相对路径,不能包含 ..、绝对路径或盘符。";function $e(){return new m(p.Forbidden,pr,{reason:"path_outside_workspace"})}function mr(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 $e();const i=n.normalize("NFC").replace(/\\/g,"/").trim();if(i.startsWith("/")||/^[a-zA-Z]:/.test(i))throw $e();const s=[];for(const o of i.split("/"))if(!(o===""||o===".")){if(o==="..")throw $e();s.push(o)}const r=s.join("/");if(!r&&!e)throw new m(p.BadRequest,`参数 ${t} 不能指向工作区根目录。`);return r}function $(n){return n?n.split("/"):[]}function gr(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}function ui(n,e){return n?`${n}/${e}`:e}function pe(n,e){return!!n&&typeof n=="object"&&n.name===e}class fi{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=$(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=$(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($(e)),s=[];try{for(var r=W(i.values()),o,c,a;o=!(c=yield r.next()).done;o=!1){const d=c.value;if(O(t),d.kind==="directory")s.push({name:d.name,kind:"directory"});else try{const l=yield d.getFile();s.push({name:d.name,kind:"file",size:l.size,lastModified:l.lastModified})}catch(l){if(pe(l,"NotAllowedError"))throw l;s.push({name:d.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=$(e),c=o.pop();if(!c)throw S("TypeMismatchError");const a=yield this.resolveDirectory(o,i.createDirectories);let d=!0;try{yield a.getFileHandle(c)}catch(b){if(!pe(b,"NotFoundError"))throw b;d=!1}const l=yield a.getFileHandle(c,{create:!0});let u;try{u=yield l.createWritable();try{for(var f=W(Et(t)),g,_,y;g=!(_=yield f.next()).done;g=!1){const b=_.value;O(i.signal),yield u.write(b)}}catch(_){y=[_]}finally{try{g&&(_=f.return)&&(yield _.call(f))}finally{if(y)throw y[0]}}O(i.signal),yield u.close()}catch(b){throw yield u==null?void 0:u.abort().catch(()=>{}),d||(yield a.removeEntry(c).catch(()=>{})),b}})}createDirectory(e){return h(this,null,function*(){yield this.resolveDirectory($(e),!0)})}remove(i){return h(this,arguments,function*(e,t={}){const s=$(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=$(e),s=$(t),r=i.pop(),o=s.pop();if(!r||!o)throw S("InvalidModificationError");const c=yield this.resolveDirectory(i),a=yield mn(c,r),d=yield this.resolveDirectory(s);if(qn(e,t))throw S("InvalidModificationError");let l;try{l=yield mn(d,o)}catch(u){if(!pe(u,"NotFoundError"))throw u}if(l&&(l.kind==="directory"||a.kind==="directory"))throw S("InvalidModificationError");if(!l&&typeof a.move=="function")try{yield a.move(d,o);return}catch(u){if(!pe(u,"NotSupportedError")&&!(u instanceof TypeError))throw u}yield pi(a,d,o),yield c.removeEntry(r,{recursive:!0})})}}function mn(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 pi(n,e,t){return h(this,null,function*(){if(n.kind==="file"){const a=yield n.getFile(),d=yield(yield e.getFileHandle(t,{create:!0})).createWritable();try{yield d.write(a),yield d.close()}catch(l){throw yield d.abort().catch(()=>{}),l}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 pi(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 yr(){if(typeof window=="undefined")return;const n=window.showDirectoryPicker;return typeof n=="function"?n.bind(window):void 0}const wr=/^[a-z0-9-]+(\.[a-z0-9-]+)+$/;function vr(n){if(typeof n!="string")return null;const e=n.trim().toLowerCase().replace(/^\*?\./,"").replace(/\.$/,"");return!wr.test(e)||mi(e)?null:e}function mi(n){return n.startsWith("[")||n.includes(":")?!0:/^[0-9.]+$/.test(n)||/^0x[0-9a-f.]+$/i.test(n)}function $t(n=[]){const e=new Set($n);for(const t of n){const i=vr(t);i&&e.add(i)}return Array.from(e)}function _r(n,e){return mt(n,$t(e))}function mt(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||mi(i)||i==="localhost"||i.endsWith(".localhost")?!1:e.some(s=>i===s||i.endsWith(`.${s}`))}function br(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 Bt(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,(d,l)=>c==null?void 0:c({loaded:d,total:l}));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 Er(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 Er(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 Sr="glodon-aiot-local-workspace",nt="kv";function jt(){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 Ir(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}function gi(n=Sr){if(typeof indexedDB=="undefined")return jt();let e;const t=()=>(e||(e=new Promise((r,o)=>{const c=indexedDB.open(n,1);c.onupgradeneeded=()=>{c.result.createObjectStore(nt)},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 Ir(o(c.transaction(nt,r).objectStore(nt)))});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 gn(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 xr(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=gn(o.relativePathComponents),a=gn(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 Ar(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 Tr(n){return!!n&&typeof n=="object"&&n.name==="AbortError"}class yi{constructor(e){w(this,"applicationId");w(this,"limits");w(this,"sensitive");w(this,"downloadUrlAllowlist");w(this,"allowWorkspaceWideTextSearch");w(this,"transfer");w(this,"fetch");w(this,"commandRunner");w(this,"browserRuntime");w(this,"store");w(this,"picker");w(this,"event",new Pt(!0));w(this,"_status");w(this,"_displayName");w(this,"_adapter",null);w(this,"pendingHandle",null);w(this,"approvalHandler");w(this,"activeCalls",0);w(this,"commandRunning",!1);w(this,"inflight",new Set);w(this,"_ready",Promise.resolve());w(this,"stopWatching",()=>{});w(this,"pendingChangePaths",new Set);w(this,"changeTimer");w(this,"refreshAllVisible",!1);var o,c,a,d,l,u,f,g,_,y;const t=(o=e.config)!=null?o:{};this.applicationId=e.applicationId,this.store=(c=e.store)!=null?c:jt(),this.picker=e.picker===null?void 0:(a=e.picker)!=null?a:yr(),this.limits=br(t.limits),this.sensitive=new Qn(t.sensitiveRulesAppend),this.downloadUrlAllowlist=$t(t.downloadUrlAllowlistAppend),this.allowWorkspaceWideTextSearch=!!t.allowWorkspaceWideTextSearch,this.approvalHandler=t.onApprovalRequired;const i=(d=e.transfer)!=null?d:Bt(()=>{});this.transfer={upload:(u=(l=t.transfer)==null?void 0:l.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=(y=t.commandRuntime)==null?void 0:y.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 fi(e),this.setStatus("granted",e.name),this.unwatchDirectory(),this.stopWatching=xr(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(Tr(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=Ar(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(wt.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 yn=100,P=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 Ut{constructor(e,t="",i,s,r,o){w(this,"_id");w(this,"_frozen",!1);w(this,"inactivating",!1);w(this,"_ready",!1);w(this,"event",new Pt);w(this,"_applicationId");w(this,"_application",null);w(this,"data",null);w(this,"client",null);w(this,"messages",[]);w(this,"_loadingMessages",!1);w(this,"_loadingMessagesSize",10);w(this,"cvforceApi");w(this,"socket",null);w(this,"_promptVariables",[]);w(this,"active",!1);w(this,"activing",!1);w(this,"_stopAnswer",!1);w(this,"_dataLoading",!1);w(this,"_dataLoaded",!1);w(this,"_mcpServers",null);this.token=e,this.lazyload=s,this.client=o||null,this._applicationId=Ge(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(d=>d.id),applicationId:this._applicationId}).then(d=>h(this,null,function*(){var l;this._id=d.id,this.data=E(v({},d),{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){P.error(u)}yield(()=>{if(i!=null&&i.promptVariables){const u=this._promptVariables.map(f=>{var _,y;const g=((y=(_=i.promptVariables)==null?void 0:_.find(b=>b.key===f.key&&b.type===f.type))==null?void 0:y.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),((l=this.application)==null?void 0:l.type)!==A.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)>yn)throw Error(`knowledges and fileIds total count cannot exceed ${yn}`);return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(t=>t.status===A.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>!(e.type===A.PromptVariableType.User&&e.key==="query")&&!(e.type===A.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return 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===A.PromptVariableType.User&&r.key==="query")&&!(r.type===A.PromptVariableType.System&&r.key==="datetime")).map(r=>{if(!this.data)throw Error("session data is not loaded");if(!(!r.id||!r.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,r.id,{value:r.value})})).then(()=>!0).catch(r=>!1)))return!1;if(!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return h(this,null,function*(){var t,i,s;if(P.log("setNetOpen:",e),P.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((i=this._application)==null?void 0:i.type)===A.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,P.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return di(exports.configuration.apiRoot,this.token,(e,t)=>{const i=new Error("data request error",{cause:{status:e,message:t}});P.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"),P.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),P.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),o=r.map((a,d)=>{var f,g;let l=[],u;return typeof((f=a.agentHistoryList)==null?void 0:f.agentList)=="string"&&(l=JSON.parse(a.agentHistoryList.agentList).reduce((y,b)=>(y[b.data.step-1]||(y[b.data.step-1]=[]),y[b.data.step-1].push(b),y),[])),d===r.length-1&&(u=(g=this.data)==null?void 0:g.lastRelatedQuestion),E(v({},a),{actions:l,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(d=>d.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(d=>d.ts===e.endTime);this.messages.splice(a,this.messages.length-a-1),this.messages=[...this.messages,...o]}else{const a=this.messages.findIndex(l=>l.ts===e.endTime),d=this.messages.findLastIndex(l=>l.ts===e.endTime);this.messages.splice(a,d-a+1,...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),P.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 P.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}),P.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),P.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),P.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 P.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(y){console.error(y)}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||[],d=e.fileIds,l=e.imageContent;if(!c&&!a.length&&!(d!=null&&d.length)){const y=new Error("failed at sending empty content");return P.error(y),this.event.emit("error",y),!1}if(!this._id){const y=new Error("session id is not defined");return P.error(y),this.event.emit("error",y),!1}if(this.frozen){const y=new Error("session is frozen");return P.error(y),this.event.emit("error",y),!1}this.frozen=!0,this._stopAnswer=!1;const u={sessionId:this.id,role:2,content:c,messageId:o,reference:[],searchReference:[],messageTime:"",files:a,imageContent:l},f={content:c,stream:s,requestId:o,fileIds:d,referenceFirst:r,imageContent:l};this.pushMessage(u),this.event.emit("question:content",c);const g=y=>h(this,null,function*(){if(y.role!==A.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",g),this._id&&y.content&&y.index&&y.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:y.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:y.content})),yield this.fillMessageReference(y),y.code){case 11915:y.content="请您换个问题问我吧~",y.index=-1,y.isSensitive=!0,y.isLoading=!1,y.sessionId=this._id||"",this.event.emit("message:error",y);break;case 11916:y.content="尊敬的用户您好,让我们换个话题再聊聊吧。",y.index=-1,y.isSensitive=!0,y.isLoading=!1,y.sessionId=this._id||"",this.event.emit("message:error",y);break;case 200:y.index=-1,y.isLoading=!1;break;default:y.content=y.message||"未知错误",y.isLoading=!1,y.index=-1,this.event.emit("message:error",y)}this.getRelatedQuesion(y),y.isLoading=!1;let b=this.messages[this.messages.length-1];if(b&&b.role===A.ChatMessageRole.Robot){const T=v(v({},b),y);this.messages[this.messages.length-1]=T,this.event.emit("message:updated",T)}else this.pushMessage(y);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===A.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=lr(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(d=>null);if(!s){const d=[],l=E(v({},e),{relatedQuesion:d,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:d}),this.event.emit("message:updated",l),l}const r=(a=s.content)==null?void 0:a.split("*").map(cr).map(dr).filter(d=>!!d);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!==A.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===A.ChatMessageRole.Robot&&a.index===-1){switch(this._id&&a.content&&a.index&&a.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:a.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:a.content})),yield this.fillMessageReference(a),a.code){case 11915:a.content="请您换个问题问我吧~",a.index=-1,a.isSensitive=!0,a.isLoading=!1,a.sessionId=this._id||"",this.event.emit("message:error",a);break;case 11916:a.content="尊敬的用户您好,让我们换个话题再聊聊吧。",a.index=-1,a.isSensitive=!0,a.isLoading=!1,a.sessionId=this._id||"",this.event.emit("message:error",a);break;case 200:a.index=-1,a.isLoading=!1;break;default:a.content=a.message||"未知错误",a.isLoading=!1,a.index=-1,this.event.emit("message:error",a)}this.getRelatedQuesion(a),this.removeEventListener("message:content",c),this.frozen=!1}});this.addEventListener("message:content",c),this.sendQuestion(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:yt(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:A.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const 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:d}=r.data;s.push({data:{pluginName:o,pluginCode:c,funcCode:a,funcName:d,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,d=s.messageTime;t.messageId=c,t.llmModel=a,t.messageTime=d}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 wn(n){if(typeof n!="string")return n;const e=n.trim();if(e)try{return JSON.parse(e)}catch(t){return n}}function vn(n){return n==null||n===""||typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function kr(n,e){const t=wn(n==null?void 0:n.query);if(!vn(t))return t;const i=wn(e);return vn(i)&&t!=null?t:i}class Lr extends Ut{constructor(t,i="",s,r,o,c){super(t,i,s,r,o,c);w(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 Ri.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 y;if(this._stopAnswer||!this.id)return;const{type:a,data:{runnerIsClient:d,pluginCode:l,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:A.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"&&d){H.log(`calling function ${u} of plugin ${l} with argument:
367
367
  ${JSON.stringify(f)}`);const b=(y=exports.configuration.plugins)==null?void 0:y[l];if(!b){c({code:404,message:"没有找到插件。"});return}const T=b[u];if(typeof T!="function"){c({code:404,message:"没有找到插件方法。"});return}const I=kr(f,g);this.invokeClientPlugin(T,I,c,{requestId:o.requestId,pluginCode:l,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===A.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:A.ChatMessageRole.Robot,reference:[],searchReference:[],messageId:"",sessionId:this.id,messageTime:yt(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:A.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:A.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:d}=o,l=this.messages.findIndex(f=>f.messageId===d&&f.role===A.ChatMessageRole.User);if(l<0)return;const u=l+1;if(u>=this.messages.length){const f={messageId:"",content:"",role:A.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0};this.pushMessage(f)}c==="KG"?(this.messages[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===A.PromptVariableType.User).reduce((a,d)=>E(v({},a),{[d.key]:d.value}),{}),systemPromptVariables:this.promptVariables.filter(a=>a.type===A.PromptVariableType.System).reduce((a,d)=>E(v({},a),{[d.key]:d.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=(...l)=>{c||(c=!0,this.inflightCalls.delete(o),!(this._stopAnswer||o.signal.aborted)&&s(...l))},d={requestId:r.requestId||_e.v4(),applicationId:this._applicationId,sessionId:this.id,pluginCode:r.pluginCode,functionCode:r.functionCode,signal:o.signal};try{const l=t(i,a,d);l&&typeof l.catch=="function"&&l.catch(u=>{H.error("client plugin failed",u),a({code:500,message:"客户端插件执行失败。"})})}catch(l){H.error("client plugin failed",l),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 Rr(n,e){return h(this,null,function*(){const t=n.getReader();let i;for(;!(i=yield t.read()).done;)e(i.value)})}function Mr(n){let e,t,i,s=!1,r;return function(c){e===void 0?(e=c,t=0,i=-1,r=!1):e=Fr(e,c);const a=e.length;let d=0;for(;t<a;){s&&(e[t]===10&&(d=++t),s=!1);let l=-1;for(;t<a&&l===-1;++t)switch(e[t]){case 58:i===-1&&(i=t-d);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:l=t;break}if(l===-1)break;n(e.subarray(d,l),i,r),d=t,i=-1,r=!1}d===a?e=void 0:d!==0&&(e=e.subarray(d),t-=d)}}function Cr(n,e,t){let i=_n();const s=new TextDecoder;return function(o,c,a){if(o.length===0)t==null||t(i),i=_n();else if(c>0){const d=s.decode(o.subarray(0,c)),l=c+(o[c+1]===32?2:1);let u=s.decode(o.subarray(l));switch(a&&(u+=`
368
368
  `),d){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 Fr(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function _n(){return{data:"",event:"",id:"",retry:void 0}}const gt="text/event-stream",Or=1e3,bn="last-event-id";function En(n,l){var u=l,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:c,fetch:a}=u,d=Vt(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,g)=>{const _=v({},t);_.accept||(_.accept=gt);let y;function b(){y.abort(),document.hidden||N()}c||document.addEventListener("visibilitychange",b);let T=Or,I=0;function k(){document.removeEventListener("visibilitychange",b),window.clearTimeout(I),y.abort()}e==null||e.addEventListener("abort",()=>{k(),f()});const L=a!=null?a:window.fetch,J=i!=null?i:Nr;function N(){return h(this,null,function*(){var x;y=new AbortController;try{const M=yield L(n,E(v({},d),{headers:_,signal:y.signal}));yield J(M),yield Rr(M.body,Mr(Cr(C=>{C?_[bn]=C:delete _[bn]},C=>{T=C},s))),r==null||r(),k(),f()}catch(M){if(!y.signal.aborted)try{const C=(x=o==null?void 0:o(M))!=null?x:T;window.clearTimeout(I),I=window.setTimeout(N,C)}catch(C){k(),g(C)}}})}N()})}function Nr(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith(gt)))throw new Error(`Expected content-type to be ${gt}, Actual: ${e}`)}const Sn=new U("[DialogSession] ");class Dr extends Ut{constructor(t,i="",s,r,o,c){super(t,i,s,r,o,c);w(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:A.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=E(v({},s),{stream:exports.configuration.stream});En(`${exports.configuration.apiRoot}/chat/v2/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(l){return l.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(l){if(!l.data.includes('{"code": ')){let f={};try{f=JSON.parse(l.data)}catch(_){}(f==null?void 0:f.mtype)==="search"?a.searchReference.push(f):a.content=a.content+l.data;const g={content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:i,messageTime:yt(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(l.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 l={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(l)}})})}postChatV3EventSource(t,i,s,r,o,c){return h(this,null,function*(){const a=this,d={code:0,content:"",role:A.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},l=E(v({},s),{stream:exports.configuration.stream});En(`${exports.configuration.apiRoot}/chat/v3/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(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 d.index=-1,d.code=f.code,d.message=f.message,o!=null&&o.onmessage&&o.onmessage(d),c&&c({code:f.code,message:f.message});a.handleStreamAnswer(f,d),o!=null&&o.onmessage&&o.onmessage(d)},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const u=E(v({},d),{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:d}=i;if(this.active||(yield this.activate()),this._id){const l=this.convertKnowledgesToChatFormat(this.knowledges);let u={content:s,fileIds:r,referenceFirst:d,oldMessageId:o,promptVariables:this.promptVariables.filter(f=>f.type===A.PromptVariableType.User).reduce((f,g)=>E(v({},f),{[g.key]:g.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===A.PromptVariableType.System).reduce((f,g)=>E(v({},f),{[g.key]:g.value}),{}),knowledges:l,enableTitleSummary:this.resolveEnableTitleSummary(),imageContent:c};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,u,this.ctrl.signal,{onopen:()=>{Sn.log("open",this.ctrl)},onmessage:f=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===A.ChatMessageRole.Robot?(g=v(v({},g),f),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(f),this.event.emit("message:content",f))},onclose:f=>h(this,null,function*(){this._stopAnswer||(Sn.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 Pr="@glodon-aiot/bot-client-sdk",$r="3.26.0-alpha.12",Br="glodoncv",jr="aiot bot client js sdk",Ur="module",Hr=!1,qr=["aiot","bot","bot client","sdk"],Wr=["dist"],zr="./dist/es/index.mjs",Vr="./dist/lib/index.js",Gr="./dist/src/index.d.ts",Xr={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},Yr="MIT",Kr={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"},Jr={"@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"},Qr={access:"public",registry:"https://registry.npmjs.org/"},Zr={"@glodon-aiot/apis":"^3.26.0-alpha.12",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"},eo={name:Pr,version:$r,author:Br,description:jr,type:Ur,sideEffects:Hr,keywords:qr,files:Wr,module:zr,main:Vr,typings:Gr,exports:Xr,license:Yr,scripts:Kr,devDependencies:Jr,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:Qr,dependencies:Zr},In=new U("[BotClient] ");class to{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){w(this,"event",new Pt);w(this,"cvforceApi");w(this,"_applicationId");w(this,"_application",null);w(this,"_sessions",[]);w(this,"_activeSession");w(this,"_ready",!1);w(this,"_questionContextMaxLength",4e3);w(this,"_promptVariables",[]);w(this,"_localWorkspace");w(this,"_disconnectHost");if(this._token=e,this.lazyload=i,this.sdkConfigs=s,pt(t,{refreshBuiltinPlugins:!1}),this._applicationId=Ge(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{pt(E(v({},t),{stream:t.stream===void 0?(r==null?void 0:r.type)===A.ApplicationTypes.Dialog||(r==null?void 0:r.type)===A.ApplicationTypes.Agent:t.stream})),this.event.emit("ready")})}setupLocalWorkspace(){var s,r;const e=(s=exports.configuration.builtinPlugins)==null?void 0:s.localFiles;if(!(e!=null&&e.enabled)){pn(void 0),ft();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=hr(exports.configuration.apiRoot,this.token,(c,a)=>In.error(a));this._localWorkspace=new yi({applicationId:this._applicationId,config:e,store:gi(),picker:i==="host-bridge"?null:void 0,transfer:Bt(()=>this.cvforceApi,()=>o)}),pn(this._localWorkspace),i==="host-bridge"?this._disconnectHost=fr(this._localWorkspace):this._localWorkspace.restore()}t.push(...ft()),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:eo.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:A.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:A.PromptVariableType.System})]).then(([c,a])=>[...c,...a]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:di(exports.configuration.apiRoot,this.token,(e,t)=>In.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=Ge(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 d=l=>h(this,null,function*(){if(l===A.ApplicationTypes.Agent)c(new Lr(e,t,i,s,r,o));else if(l===A.ApplicationTypes.Dialog)c(new Dr(e,t,i,s,r,o));else throw Error(`不支持的应用类型:${l}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getArtifacts(e){return 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(d=>d.id===c.id);if(a)a.data=c,this._application?a.application=this._application:yield a.loadApplicationInfo(),o.push(a);else{const d=yield this.createSession(this.token,c.id,c,this.lazyload,this._application||void 0);o.push(d)}}if(e!=null&&e.pageSize){const c=[...this._sessions,...o],a=new Map;for(const d of c)a.set(d.id,d);return this.sessions=Array.from(a.values()),this.sessions}else return this.sessions=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*(){this.checkReady();let i=this.sessions.find(s=>s.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 no{constructor(e,t={},i){w(this,"code");w(this,"description","");w(this,"loaded",!1);w(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}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),it={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},wi={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:it,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:it,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:it}}}},io=new TextEncoder;function ee(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const so=(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,Cn,1,Fn),o=yield e.adapter.listEntries(t,e.signal);o.sort((a,d)=>a.kind!==d.kind?a.kind==="directory"?-1:1:a.name<d.name?-1:a.name>d.name?1:0);const c=o.slice(s,s+r).map(a=>{const d=ui(t,a.name),l={name:a.name,path:d,kind:a.kind};return a.kind==="file"&&(l.size=a.size,l.lastModified=a.lastModified,e.sensitive.isSensitive(d)&&(l.sensitive=!0)),l});return{data:{path:t,entries:c,total:o.length,hasMore:s+c.length<o.length}}});function ro(n,e,t){return le(this,null,function*(){var c;const i=new TextDecoder(e),s=n.stream().getReader();let r="",o=!1;try{for(;;){O(t);const{done:a,value:d}=yield new te(s.read());r+=a?i.decode():i.decode(d,{stream:!0});const l=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 Fr(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function _n(){return{data:"",event:"",id:"",retry:void 0}}const gt="text/event-stream",Or=1e3,bn="last-event-id";function En(n,l){var u=l,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:c,fetch:a}=u,d=Vt(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,g)=>{const _=v({},t);_.accept||(_.accept=gt);let y;function b(){y.abort(),document.hidden||N()}c||document.addEventListener("visibilitychange",b);let T=Or,I=0;function k(){document.removeEventListener("visibilitychange",b),window.clearTimeout(I),y.abort()}e==null||e.addEventListener("abort",()=>{k(),f()});const L=a!=null?a:window.fetch,J=i!=null?i:Nr;function N(){return h(this,null,function*(){var x;y=new AbortController;try{const M=yield L(n,E(v({},d),{headers:_,signal:y.signal}));yield J(M),yield Rr(M.body,Mr(Cr(C=>{C?_[bn]=C:delete _[bn]},C=>{T=C},s))),r==null||r(),k(),f()}catch(M){if(!y.signal.aborted)try{const C=(x=o==null?void 0:o(M))!=null?x:T;window.clearTimeout(I),I=window.setTimeout(N,C)}catch(C){k(),g(C)}}})}N()})}function Nr(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith(gt)))throw new Error(`Expected content-type to be ${gt}, Actual: ${e}`)}const Sn=new U("[DialogSession] ");class Dr extends Ut{constructor(t,i="",s,r,o,c){super(t,i,s,r,o,c);w(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:A.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},d=E(v({},s),{stream:exports.configuration.stream});En(`${exports.configuration.apiRoot}/chat/v2/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(l){return l.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(l){if(!l.data.includes('{"code": ')){let f={};try{f=JSON.parse(l.data)}catch(_){}(f==null?void 0:f.mtype)==="search"?a.searchReference.push(f):a.content=a.content+l.data;const g={content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:i,messageTime:yt(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(l.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 l={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(l)}})})}postChatV3EventSource(t,i,s,r,o,c){return h(this,null,function*(){const a=this,d={code:0,content:"",role:A.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},l=E(v({},s),{stream:exports.configuration.stream});En(`${exports.configuration.apiRoot}/chat/v3/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(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 d.index=-1,d.code=f.code,d.message=f.message,o!=null&&o.onmessage&&o.onmessage(d),c&&c({code:f.code,message:f.message});a.handleStreamAnswer(f,d),o!=null&&o.onmessage&&o.onmessage(d)},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const u=E(v({},d),{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:d}=i;if(this.active||(yield this.activate()),this._id){const l=this.convertKnowledgesToChatFormat(this.knowledges);let u={content:s,fileIds:r,referenceFirst:d,oldMessageId:o,promptVariables:this.promptVariables.filter(f=>f.type===A.PromptVariableType.User).reduce((f,g)=>E(v({},f),{[g.key]:g.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===A.PromptVariableType.System).reduce((f,g)=>E(v({},f),{[g.key]:g.value}),{}),knowledges:l,enableTitleSummary:this.resolveEnableTitleSummary(),imageContent:c};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,u,this.ctrl.signal,{onopen:()=>{Sn.log("open",this.ctrl)},onmessage:f=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===A.ChatMessageRole.Robot?(g=v(v({},g),f),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(f),this.event.emit("message:content",f))},onclose:f=>h(this,null,function*(){this._stopAnswer||(Sn.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 Pr="@glodon-aiot/bot-client-sdk",$r="3.26.0-alpha.13",Br="glodoncv",jr="aiot bot client js sdk",Ur="module",Hr=!1,qr=["aiot","bot","bot client","sdk"],Wr=["dist"],zr="./dist/es/index.mjs",Vr="./dist/lib/index.js",Gr="./dist/src/index.d.ts",Xr={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},Yr="MIT",Kr={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"},Jr={"@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"},Qr={access:"public",registry:"https://registry.npmjs.org/"},Zr={"@glodon-aiot/apis":"^3.26.0-alpha.13",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"},eo={name:Pr,version:$r,author:Br,description:jr,type:Ur,sideEffects:Hr,keywords:qr,files:Wr,module:zr,main:Vr,typings:Gr,exports:Xr,license:Yr,scripts:Kr,devDependencies:Jr,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:Qr,dependencies:Zr},In=new U("[BotClient] ");class to{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){w(this,"event",new Pt);w(this,"cvforceApi");w(this,"_applicationId");w(this,"_application",null);w(this,"_sessions",[]);w(this,"_activeSession");w(this,"_ready",!1);w(this,"_questionContextMaxLength",4e3);w(this,"_promptVariables",[]);w(this,"_localWorkspace");w(this,"_disconnectHost");if(this._token=e,this.lazyload=i,this.sdkConfigs=s,pt(t,{refreshBuiltinPlugins:!1}),this._applicationId=Ge(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{pt(E(v({},t),{stream:t.stream===void 0?(r==null?void 0:r.type)===A.ApplicationTypes.Dialog||(r==null?void 0:r.type)===A.ApplicationTypes.Agent:t.stream})),this.event.emit("ready")})}setupLocalWorkspace(){var s,r;const e=(s=exports.configuration.builtinPlugins)==null?void 0:s.localFiles;if(!(e!=null&&e.enabled)){pn(void 0),ft();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=hr(exports.configuration.apiRoot,this.token,(c,a)=>In.error(a));this._localWorkspace=new yi({applicationId:this._applicationId,config:e,store:gi(),picker:i==="host-bridge"?null:void 0,transfer:Bt(()=>this.cvforceApi,()=>o)}),pn(this._localWorkspace),i==="host-bridge"?this._disconnectHost=fr(this._localWorkspace):this._localWorkspace.restore()}t.push(...ft()),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:eo.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:A.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:A.PromptVariableType.System})]).then(([c,a])=>[...c,...a]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:di(exports.configuration.apiRoot,this.token,(e,t)=>In.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=Ge(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 d=l=>h(this,null,function*(){if(l===A.ApplicationTypes.Agent)c(new Lr(e,t,i,s,r,o));else if(l===A.ApplicationTypes.Dialog)c(new Dr(e,t,i,s,r,o));else throw Error(`不支持的应用类型:${l}`)});if(this.ready){if(!this._application)throw Error("client is not ready");d(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");d(this._application.type)},!0)})})}getArtifacts(e){return 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(d=>d.id===c.id);if(a)a.data=c,this._application?a.application=this._application:yield a.loadApplicationInfo(),o.push(a);else{const d=yield this.createSession(this.token,c.id,c,this.lazyload,this._application||void 0);o.push(d)}}if(e!=null&&e.pageSize){const c=[...this._sessions,...o],a=new Map;for(const d of c)a.set(d.id,d);return this.sessions=Array.from(a.values()),this.sessions}else return this.sessions=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*(){this.checkReady();let i=this.sessions.find(s=>s.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 no{constructor(e,t={},i){w(this,"code");w(this,"description","");w(this,"loaded",!1);w(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}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),it={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},wi={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:it,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:it,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:it}}}},io=new TextEncoder;function ee(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const so=(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,Cn,1,Fn),o=yield e.adapter.listEntries(t,e.signal);o.sort((a,d)=>a.kind!==d.kind?a.kind==="directory"?-1:1:a.name<d.name?-1:a.name>d.name?1:0);const c=o.slice(s,s+r).map(a=>{const d=ui(t,a.name),l={name:a.name,path:d,kind:a.kind};return a.kind==="file"&&(l.size=a.size,l.lastModified=a.lastModified,e.sensitive.isSensitive(d)&&(l.sensitive=!0)),l});return{data:{path:t,entries:c,total:o.length,hasMore:s+c.length<o.length}}});function ro(n,e,t){return le(this,null,function*(){var c;const i=new TextDecoder(e),s=n.stream().getReader();let r="",o=!1;try{for(;;){O(t);const{done:a,value:d}=yield new te(s.read());r+=a?i.decode():i.decode(d,{stream:!0});const l=r.split(`
370
370
  `);r=(c=l.pop())!=null?c:"";for(const u of l)o=!0,yield u;if(a)break}}finally{s.releaseLock()}(r||!o)&&(yield r)})}const oo=(n,e)=>h(exports,null,function*(){var k,L;const t=K(n.path);Ie(e,t,"read");const i=yield Lt(e.adapter,t),s=yield e.adapter.readFile(t),r=(k=i.size)!=null?k:s.size;if(yield ns(s))throw new m(p.BadRequest,"这是二进制文件,不能按文本读取。可以使用 stat_file 查看信息,或使用 upload_file 上传到会话。");const o=yield q(s.slice(0,3)),c=Zn(o)?"utf-8":(L=n.encoding)!=null?L:"utf-8",a=ee(n.startLine,1,1,Number.MAX_SAFE_INTEGER),d=n.endLine===void 0?Number.MAX_SAFE_INTEGER:Math.max(Math.trunc(n.endLine),a),l=ee(n.maxBytes,e.limits.maxReadBytes,1,e.limits.maxReadBytes),u=r<=e.limits.maxTransferBytes,f=[];let g=0,_=0,y=a-1,b=!1,T=!1;try{for(var J=W(ro(s,c,e.signal)),N,x,M;N=!(x=yield J.next()).done;N=!1){const C=x.value;_++;const D=C.endsWith("\r")?C.slice(0,-1):C;if(D!==C&&(T=!0),_<a||_>d||b){if(!u&&(b||_>d))break;continue}const ce=Rt(D)+(f.length?1:0);if(g+ce>l){if(b=!0,f.length||(f.push(ao(D,l)),y=_),!u)break;continue}f.push(D),g+=ce,y=_}}catch(x){M=[x]}finally{try{N&&(x=J.return)&&(yield x.call(J))}finally{if(M)throw M[0]}}const I={path:t,content:f.join(`
371
371
  `),startLine:a,endLine:Math.max(y,a-1),size:r,encoding:c,lineEnding:T?"crlf":"lf"};return u&&(I.totalLines=_),r<=e.limits.maxWriteBytes&&(I.hash=yield Ee(yield q(s))),{data:I,truncated:b||void 0}});function ao(n,e){const t=io.encode(n);return t.byteLength<=e?n:new TextDecoder().decode(t.slice(0,e)).replace(/\uFFFD$/,"")}const co=(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 Ee(yield q(yield e.adapter.readFile(t))))),{data:s}});function lo(n){return jn.some(e=>Ve(e,n))}function vi(n,e,t){return le(this,null,function*(){const i=[{path:e,depth:0}];let s=0;for(;i.length;){const r=i.shift();O(n.signal),++s%20===0&&(yield new te(ei()));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=ui(r.path,c.name);if(c.kind==="directory"){r.depth+1<t&&!Bn.includes(c.name)&&i.push({path:a,depth:r.depth+1});continue}lo(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 _i(n,e){return n.includes("/")?Ve(n,e.relativePath):Ve(n,e.name)}const ho=(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,On,1,vt),o=ee(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),c=[];let a=!1;try{for(var d=W(vi(e,t,r)),l,u,f;l=!(u=yield d.next()).done;l=!1){const g=u.value;if(_i(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{l&&(u=d.return)&&(yield u.call(d))}finally{if(f)throw f[0]}}return{data:{matches:c},truncated:a||void 0}});function st(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 uo=(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,Pn),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 le(this,null,function*(){yield{path:t,relativePath:t,name:c.name,size:c.size}})}()):a=vi(e,t,vt);const d=[];let l=0,u=!1;e:try{for(var g=W(a),_,y,b;_=!(y=yield g.next()).done;_=!1){const T=y.value;if(n.glob&&!_i(n.glob,T)||((f=T.size)!=null?f:0)>Dn)continue;if(l>=Nn){u=!0;break}l++,l%20===0&&(yield ei()),O(e.signal);const I=yield q(yield e.adapter.readFile(T.path));if(ae(I))continue;const k=new TextDecoder("utf-8").decode(I).split(/\r?\n/);for(let L=0;L<k.length;L++){const N=(i?k[L]:k[L].toLowerCase()).indexOf(s);if(N<0)continue;if(d.length>=o){u=!0;break e}const x={path:T.path,line:L+1,column:N+1,text:st(k[L],N)};r&&(x.before=k.slice(Math.max(0,L-r),L).map(M=>st(M,0)),x.after=k.slice(L+1,L+1+r).map(M=>st(M,0))),d.push(x)}}}catch(y){b=[y]}finally{try{_&&(y=g.return)&&(yield y.call(g))}finally{if(b)throw b[0]}}return{data:{matches:d,filesScanned:l},truncated:u||void 0}});function xn(){return new m(p.Forbidden,"下载地址不在允许范围内:只允许 https 协议且域名在白名单中的地址。",{reason:"url_not_allowed"})}const fo=(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 Lt(e.adapter,t),r=(f=s.size)!=null?f:0;if(r>e.limits.maxTransferBytes)throw oe(e.limits.maxTransferBytes);const o=kt(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);O(e.signal);const a=new File([c],o,{type:n.mimeHint||c.type||"application/octet-stream",lastModified:s.lastModified}),{fileId:d,url:l}=yield e.transfer.upload(a,e.context,({loaded:g,total:_})=>e.progress({stage:"uploading",loaded:g,total:_,path:t}));return O(e.signal),e.progress({stage:"done",loaded:r,total:r,path:t}),{data:{fileId:d,name:o,size:r,url:l}}});function po(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 mo(n){return n.type==="sessionFile"?"会话文件":n.type==="platformFile"?"平台文件":new URL(n.url).hostname}function go(n,e,t,i,s){return le(this,null,function*(){const r=n.getReader();let o=0;try{for(;;){O(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 yo=(n,e)=>h(exports,null,function*(){var y,b,T;const t=K(n.destPath,{field:"destPath"}),i=po(n.source);if(i.type==="url"&&!mt(i.url,e.downloadUrlAllowlist))throw xn();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 Ee(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:mo(i)},name:(y=o.name)!=null?y:kt(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 O(e.signal),new m(p.Internal,"下载失败,无法连接到文件地址。")}if(i.type==="url"&&a.url&&!mt(a.url,e.downloadUrlAllowlist))throw(b=a.body)==null||b.cancel().catch(()=>{}),xn();if(!a.ok||!a.body)throw(T=a.body)==null||T.cancel().catch(()=>{}),new m(a.status===404?p.NotFound:p.Internal,`下载失败(HTTP ${a.status})。`);const d=Number(a.headers.get("content-length")),l=Number.isFinite(d)&&d>0?d:void 0;if(l!==void 0&&l>e.limits.maxTransferBytes)throw a.body.cancel().catch(()=>{}),oe(e.limits.maxTransferBytes);const u=[];yield e.adapter.writeFile(t,go(a.body,e,t,l,u),{signal:e.signal});const f=u.reduce((I,k)=>I+k.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 Ee(g)}}}),rt=new Uint8Array([239,187,191]);function Xe(n,e){return new m(p.Conflict,e,{currentHash:n})}function Ht(n,e){return h(this,null,function*(){var s;if(((s=(yield Lt(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 Ee(i)}})}function bi(n,e,t){return h(this,null,function*(){const{hash:i}=yield Ht(n,e);if(i!==t)throw Xe(i,"文件在确认期间已被修改,本次写入已取消。请重新读取后再修改。")})}function wo(n,e){const t=new TextEncoder().encode(n);if(!e)return t;const i=new Uint8Array(rt.byteLength+t.byteLength);return i.set(rt,0),i.set(t,rt.byteLength),i}function vo(n,e){let t=0,i=n.indexOf(e);for(;i>=0;)t++,i=n.indexOf(e,i+e.length);return t}function An(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.12",
3
+ "version": "3.26.0-alpha.13",
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.12",
91
+ "@glodon-aiot/apis": "^3.26.0-alpha.13",
92
92
  "axios": "0.24.0",
93
93
  "buffer": "^6.0.3",
94
94
  "dayjs": "^1.11.13",