@glodon-aiot/bot-client-sdk 3.26.0-alpha.31 → 3.26.0-alpha.32
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 +3 -8
- package/dist/es/package.json.mjs +2 -2
- package/dist/lib/index.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -8,11 +8,9 @@ AIoT 应用客户端 SDK,支持 Agent 与对话型应用。会话、消息、
|
|
|
8
8
|
| --- | --- |
|
|
9
9
|
| 只接对话 UI | [快速开始](#快速开始) → [对话界面](#对话界面) → [产出物](#产出物) |
|
|
10
10
|
| 浏览器里读本地文件夹 / 跑命令 | 上栏 + [Agent 插件](#agent-插件) → [本地工作文件夹](#本地工作文件夹) → [命令和脚本](#命令和脚本) |
|
|
11
|
-
| 端侧宿主(桌面内嵌页 + 沙箱) | [宿主通道](#宿主通道)
|
|
11
|
+
| 端侧宿主(桌面内嵌页 + 沙箱) | [宿主通道](#宿主通道);沙箱协议与策略见 npm 包 `@glodon-aiot/workspace-sandbox` |
|
|
12
12
|
| 查工具参数 / 错误码 / 限额 | [内置工具参考](#内置工具参考) · [安全与限额](#安全与限额) · [错误码](#错误码) |
|
|
13
13
|
|
|
14
|
-
集成方总览:[`bot-client-ui/docs/agent-integration-handbook.md`](../bot-client-ui/docs/agent-integration-handbook.md)。Windows 宿主步骤:[`local-workspace-windows-host.md`](../bot-client-ui/docs/local-workspace-windows-host.md)。
|
|
15
|
-
|
|
16
14
|
| 能力 | 适用应用 | 运行环境 | 见 |
|
|
17
15
|
| --- | --- | --- | --- |
|
|
18
16
|
| 会话与流式对话 | Agent、对话型 | 浏览器、端侧宿主 | [对话界面](#对话界面) |
|
|
@@ -490,8 +488,6 @@ function openApprovalDialog(request: ApprovalRequest): Promise<boolean> {
|
|
|
490
488
|
|
|
491
489
|
宿主已授权但沙箱未就绪时**不**降级。`starting` = 启动中;失败看 `sandbox.message`。协议非 1 另发 `error`。收到 `bye` / `exited` / `failed` 后在途调用以 `AbortError` 失败且不重放;等新的 `ready` 再用新地址与令牌。
|
|
492
490
|
|
|
493
|
-
参照宿主:`examples/qt-workspace-host`。
|
|
494
|
-
|
|
495
491
|
### 浏览器运行时
|
|
496
492
|
|
|
497
493
|
| 能力 | 行为 |
|
|
@@ -512,7 +508,7 @@ CSP:放行 OBS 的 `script-src` / `connect-src`;Pyodide 需 `worker-src blob
|
|
|
512
508
|
|
|
513
509
|
### 宿主沙箱(摘要)
|
|
514
510
|
|
|
515
|
-
完整协议、策略 JSON、平台隔离差异见
|
|
511
|
+
完整协议、策略 JSON、平台隔离差异见 npm 包 `@glodon-aiot/workspace-sandbox`。此处只列页面侧要点:
|
|
516
512
|
|
|
517
513
|
- 启动:`workspace-sandbox --listen --root <工程> --origin <页面来源>`;联网 / pip / 并发由 `--policy` 定,页面不能改
|
|
518
514
|
- 宿主职责:启停、读 ready、可选 status / policy、shutdown(3 秒后杀进程组)、把退出告诉页面;**不中转**文件与命令
|
|
@@ -522,7 +518,6 @@ CSP:放行 OBS 的 `script-src` / `connect-src`;Pyodide 需 `worker-src blob
|
|
|
522
518
|
- 默认断网;`allowlist` 拒绝项写在 `stderr`;允许时 `pip install` 直装工程 venv,不必先改 `open`
|
|
523
519
|
- 平台技能:进会话按编排核对版本;页面用 `client.token` 下载 ZIP,经已认证 WS 调 `installSkill`(沙箱收不到令牌)。缓存在用户目录,不在工程内
|
|
524
520
|
- 分发:`Resources/node/`(Node 24)+ `Resources/workspace-sandbox/`;可选 `python/`
|
|
525
|
-
- Windows 细节:[`local-workspace-windows-host.md`](../bot-client-ui/docs/local-workspace-windows-host.md)
|
|
526
521
|
|
|
527
522
|
## 宿主通道
|
|
528
523
|
|
|
@@ -572,7 +567,7 @@ CSP:放行 OBS 的 `script-src` / `connect-src`;Pyodide 需 `worker-src blob
|
|
|
572
567
|
|
|
573
568
|
脚本跑完、用户在资源管理器改文件都应推送。Qt 示例默不监视 `.git` / `node_modules` / `__pycache__` 内部。
|
|
574
569
|
|
|
575
|
-
数据面:页面连沙箱后发协议 1
|
|
570
|
+
数据面:页面连沙箱后发协议 1 帧(细节见 `@glodon-aiot/workspace-sandbox`)。取消只发 `{ "op": "cancel", "id" }`,不关套接字。`bye` / `exited` / `failed` 后在途失败且不重放。
|
|
576
571
|
|
|
577
572
|
## 安全与限额
|
|
578
573
|
|
package/dist/es/package.json.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e = "@glodon-aiot/bot-client-sdk", s = "3.26.0-alpha.
|
|
1
|
+
const e = "@glodon-aiot/bot-client-sdk", s = "3.26.0-alpha.32", 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.31", t = "glodoncv",
|
|
|
68
68
|
access: "public",
|
|
69
69
|
registry: "https://registry.npmjs.org/"
|
|
70
70
|
}, y = {
|
|
71
|
-
"@glodon-aiot/apis": "^3.26.0-alpha.
|
|
71
|
+
"@glodon-aiot/apis": "^3.26.0-alpha.32",
|
|
72
72
|
axios: "0.24.0",
|
|
73
73
|
buffer: "^6.0.3",
|
|
74
74
|
dayjs: "^1.11.13",
|
package/dist/lib/index.js
CHANGED
|
@@ -374,7 +374,7 @@ ${JSON.stringify(n.headers)}`}function Oo(n){const e=n.trim();if(!e)return{};if(
|
|
|
374
374
|
`):JSON.stringify(n)}function $o(n){return d(this,null,function*(){if(!(n.headers.get("content-type")||"").includes("text/event-stream")||!n.body)return n.text();const t=n.body.getReader(),i=new TextDecoder;let s="";try{for(;s.length<2e6;){const{done:r,value:o}=yield t.read();if(r)break;s+=i.decode(o,{stream:!0});const a=s.split(/\n\n/).filter(c=>/^\s*data:/m.test(c));if(a.length>0)return a[a.length-1]}return s}finally{yield t.cancel().catch(()=>{})}})}function rt(n,e,t,i,s){return d(this,null,function*(){const r=E(w({},n.headers),{"content-type":"application/json",accept:"application/json, text/event-stream"});t!=null&&t.id&&(r["mcp-session-id"]=t.id),t!=null&&t.protocol&&(r["mcp-protocol-version"]=t.protocol);const o=yield s(n.url,{method:"POST",headers:r,body:JSON.stringify(e),signal:Fo(i)}),a=yield $o(o);if(!o.ok)throw new Error(`MCP HTTP ${o.status}: ${a.slice(0,300)}`);const c=Oo(a),l=o.headers.get("mcp-session-id");return t&&l&&(t.id=l),c})}function ot(n){const e=n.error;if(!e||typeof e!="object")return;const t=e.message;return typeof t=="string"&&t?t:"MCP 调用失败"}function Po(n){const e=n instanceof Error?n.message:String(n);return/session/i.test(e)||e.includes("MCP HTTP 404")}function Je(n,e,t){return d(this,null,function*(){const i=Ji(n),s=st.get(i);if(s!=null&&s.id)return s;const r={protocol:"2024-11-05",nextId:1},o=yield rt(n,{jsonrpc:"2.0",id:r.nextId,method:"initialize",params:{protocolVersion:r.protocol,capabilities:{},clientInfo:{name:"bot-client-sdk",version:"1.0.0"}}},r,e,t);r.nextId+=1;const a=ot(o);if(a)throw new Error(a);const c=o.result;if(c&&typeof c=="object"){const l=c.protocolVersion;typeof l=="string"&&l&&(r.protocol=l)}return yield rt(n,{jsonrpc:"2.0",method:"notifications/initialized"},r,e,t),st.set(i,r),r})}function Do(t){return d(this,arguments,function*(n,e=fetch){var a;const i=yield Je(n,void 0,e),s=yield rt(n,{jsonrpc:"2.0",id:i.nextId,method:"tools/list",params:{}},i,void 0,e);i.nextId+=1;const r=ot(s);if(r)throw new Error(r);const o=s.result;return((a=o==null?void 0:o.tools)!=null?a:[]).filter(c=>c.name).map(c=>({name:c.name,description:c.description||"",inputSchema:c.inputSchema||{type:"object",properties:{}}}))})}function Bo(r,o,a,c){return d(this,arguments,function*(n,e,t,i,s=fetch){const l=Ji(n);let h=yield Je(n,i,s);const u=()=>rt(n,{jsonrpc:"2.0",id:h.nextId,method:"tools/call",params:{name:e,arguments:t&&typeof t=="object"?t:{}}},h,i,s);let f;try{f=yield u(),h.nextId+=1}catch(b){if(!Po(b))throw b;st.delete(l),h=yield Je(n,i,s),f=yield u(),h.nextId+=1}let g=ot(f);if(g&&/session/i.test(g)&&(st.delete(l),h=yield Je(n,i,s),f=yield u(),h.nextId+=1,g=ot(f)),g)throw new Error(g);return No(f.result)})}const we=new U("[LocalMcp] ",!0);function jo(n){const e=n==null?void 0:n.mcps;return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"&&t.runtime==="local"&&t.id):[]}function Uo(n,e,t){return n==null||n.includes(e)?!0:!!t&&n.includes(t)}function qo(n){if(!n||typeof n!="object")return{};const e={};for(const[t,i]of Object.entries(n))typeof i=="string"&&(e[t]=i);return e}function Ho(n){var o,a;if(!n||typeof n!="object")return null;const e=n;if(typeof e.code=="number"&&e.code!==200)return null;const t=e.data&&typeof e.data=="object"?e.data:e,i=typeof t.code=="string"?t.code:"",s=i?(o=t.mcpServers)==null?void 0:o[i]:void 0,r=typeof(s==null?void 0:s.url)=="string"?s.url:void 0;return{code:i,deployType:typeof((a=t.deployConfig)==null?void 0:a.type)=="string"?t.deployConfig.type:void 0,url:r,headers:qo(s==null?void 0:s.headers)}}function zo(s,r,o){return d(this,arguments,function*(n,e,t,i=fetch){const a=n.replace(/\/$/,""),c=e.startsWith("Bearer ")?e:`Bearer ${e}`,l=yield i(`${a}/mcpmgr/v1/mcpserver/${encodeURIComponent(t)}`,{headers:{Authorization:c}}),h=yield l.json().catch(()=>null);if(!l.ok)throw new Error(`MCP 详情 HTTP ${l.status}`);const u=Ho(h);if(!u)throw new Error("MCP 详情不可用");return u})}function Wo(n,e){return(t,i,s)=>{const r=Xr(n);if(!r){i({code:500,message:"缺少 MCP 地址"});return}Bo(r,n,t,s==null?void 0:s.signal,e).then(o=>i({code:0,message:"ok",data:o})).catch(o=>{i({code:500,message:o instanceof Error?o.message:String(o)})})}}function Vo(n){return d(this,null,function*(){var a,c;const e=(a=n.fetchImpl)!=null?a:fetch,t=n.initMcp?Object.keys((c=n.initMcp.mcpServers)!=null?c:{}):null,i=jo(n.arrange);if(!i.length){we.log("编排里没有 runtime=local 的 MCP,不发送 register_client_mcp_tools"),Hn([]),De();return}const s=yield Promise.all(i.map(l=>d(this,null,function*(){const h=l.id;try{const u=yield zo(n.apiRoot,n.token,h,e);if(!Uo(t,h,u.code))return null;if(u.deployType!=="streamableHttp"||!u.url||!u.code)return we.log("skip local mcp",h),null;const f={code:u.code,url:u.url,headers:u.headers},g=yield Do(f,e);return g.length?{code:u.code,url:u.url,binding:f,tools:g}:null}catch(u){return we.error("local mcp failed",h,u instanceof Error?u.message:String(u)),null}})));if(n.isCurrent&&!n.isCurrent())return;const r={},o=[];for(const l of s)if(l){r[l.code]={type:"streamableHttp",url:l.url,tools:l.tools};for(const h of l.tools)o.push({name:h.name,binding:l.binding,handler:Wo(h.name,e)})}if(Hn(o),De(),!Object.keys(r).length||!n.socket){we.log("没有可注册的本地 MCP 工具,不发送 register_client_mcp_tools");return}we.log("发送 register_client_mcp_tools",Object.entries(r).map(([l,h])=>`${l}: ${h.tools.map(u=>u.name).join(", ")}`).join("; ")),n.socket.emit("register_client_mcp_tools",{mcpServers:r},l=>{const h=l&&typeof l=="object"?l.code:void 0;typeof h=="number"&&h!==200&&we.error("register_client_mcp_tools",h)})})}const H=new U("[AgentSession] ");function Jn(n){if(typeof n!="string")return n;const e=n.trim();if(e)try{return JSON.parse(e)}catch(t){return n}}function Qn(n){return n==null||n===""||typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function Go(n,e){const t=Jn(n==null?void 0:n.query);if(!Qn(t))return t;const i=Jn(e);return Qn(i)&&t!=null?t:i}class Xo extends pn{constructor(t,i="",s,r,o,a){super(t,i,s,r,o,a);y(this,"inflightCalls",new Set);y(this,"localMcpTicket",0)}prepareConnection(){return new Promise(t=>d(this,null,function*(){this.socket&&t(!0);const i={version:"1.0",stream:JSON.stringify(exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?be.Debug:be.Normal},s=new URL(exports.configuration.apiRoot),r=yield ds.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:i,transports:["websocket"]});r.on("connect",()=>{H.log("socket:connect"),this.event.emit("socket:connect"),r.emit("init")}),r.on("disconnect",()=>{H.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),r.on("ready",o=>{if(o.code===200){H.log("ready");const a=exports.configuration.debug?be.Debug:be.Normal;a===be.Debug&&o.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),this.registerLocalMcp(),t(!0)}else{this._ready&&(this._ready=!1);const a=new Error($e.SocketConnectionFailed);H.error("error",a),this.event.emit("error",a),t(!1)}}),r.on("action",(o,a)=>d(this,null,function*(){var v;if(this._stopAnswer||!this.id)return;const{type:c,data:{runnerIsClient:l,pluginCode:h,funcCode:u,parameters:f,requestBody:g}}=o,b=this.messages[this.messages.length-1];if(!b.messageId)b.actions||(b.actions=[]),b.actions[o.data.step-1]||(b.actions[o.data.step-1]=[]),b.actions[o.data.step-1].push(o),this.event.emit("message:action",{messageId:b.messageId,action:o}),this.event.emit("message:updated",b);else{const _={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[o]],comment:{isAgree:0},isReplying:!0};this.pushMessage(_),this.event.emit("message:action",{messageId:_.messageId,action:o})}if(this.inactivating){const _=new Error($e.Inactive);H.warn("error",_),this.event.emit("error",_)}else if(c==="FUNCTION_CALL"&&l){H.log(`calling function ${u} of plugin ${h} with argument:
|
|
375
375
|
${JSON.stringify(f)}`);const _=(v=exports.configuration.plugins)==null?void 0:v[h];if(!_){a({code:404,message:"没有找到插件。"});return}const x=_[u];if(typeof x!="function"){a({code:404,message:"没有找到插件方法。"});return}const S=Go(f,g);this.invokeClientPlugin(x,S,a,{requestId:o.requestId,pluginCode:h,functionCode:u})}})),r.on("answer",o=>{if(!this._stopAnswer)if(o.data.code!==200&&(o.data.index=-1),o.data.stream||o.data.stream===void 0){let a=this.messages[this.messages.length-1];if(a&&a.role===I.ChatMessageRole.Robot)this.handleStreamAnswer(o.data,a),this.messages[this.messages.length-1]=a,this.event.emit("message:content",a),this.event.emit("message:updated",a),a.index===-1&&(a.isReplying=!1,this.event.emit("answer:finish",a));else{const c={content:"",role:I.ChatMessageRole.Robot,reference:[],searchReference:[],messageId:"",sessionId:this.id,messageTime:qt(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""};this.handleStreamAnswer(o.data,c),this.pushMessage(c),this.event.emit("message:content",c),c.index===-1&&(c.isReplying=!1,this.event.emit("answer:finish",c))}}else if(o.data.updateSession&&this.data&&(this.data=w(w({},this.data),o.data.updateSession),this.event.emit("data:updated",this.data)),o.data.index===-1){let a=this.messages[this.messages.length-1];if(a&&!a.messageId)a=w(w({},a),o.data),this.event.emit("message:content",a),this.event.emit("message:updated",a),this.event.emit("answer:finish",a);else{const c=w({messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.data);this.event.emit("message:content",c),this.pushMessage(c),this.event.emit("answer:finish",c)}}else{let a=this.messages[this.messages.length-1];a&&!a.messageId?(a=w(w({},a),o.data),this.messages[this.messages.length-1]=a,this.event.emit("message:content",a),this.event.emit("message:updated",a)):(this.pushMessage(w({messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.data)),this.event.emit("message:content",o.data))}}),r.on("reference",o=>d(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const f=new Error($e.IdUndefined);H.error(f),this.event.emit("error",f),this.frozen=!1;return}const{type:a,data:c,requestId:l}=o,h=this.messages.findIndex(f=>f.messageId===l&&f.role===I.ChatMessageRole.User);if(h<0)return;const u=h+1;if(u>=this.messages.length){const f={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0};this.pushMessage(f)}a==="KG"?(this.messages[u]=E(w({},this.messages[u]),{reference:c.knowledgeReference}),yield this.fillMessageReference(this.messages[u]),this.event.emit("message:reference",c.knowledgeReference),this.event.emit("message:updated",this.messages[u])):a==="WEB_SEARCH"&&(this.messages[u]=E(w({},this.messages[u]),{searchReference:c.knowledgeReference}),this.event.emit("message:searchreference",c.searchReference),this.event.emit("message:updated",this.messages[u]))})),this.socket=r,r.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((t,i)=>{if(!this.socket){i("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,s=>{s.code===200?(Object.keys(s.data).forEach(r=>{s.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",s.data[r])}),t(!0)):(console.error("MCP Server 注册失败。",s),i(s))})}):Promise.resolve(!0)}registerLocalMcp(){var s,r;const t=this.socket;if(!t)return;const i=++this.localMcpTicket;Vo({arrange:(r=(s=this.application)==null?void 0:s.arrange)==null?void 0:r[0],initMcp:exports.configuration.mcp,apiRoot:exports.configuration.apiRoot,token:this.token,socket:t,isCurrent:()=>i===this.localMcpTicket}).catch(o=>{H.error("local mcp",o instanceof Error?o.message:String(o))})}addMcpServers(t){return d(this,null,function*(){return this.ready?this.socket?new Promise((i,s)=>{this.socket&&this.socket.emit("add_mcp_servers",t,r=>{r.code===200?(Object.keys(r.data).forEach(o=>{r.data[o].code!==200&&console.error(o,"MCP Server 注册失败。",r.data[o])}),i(!0)):(console.error("MCP Server 注册失败。",r),s(r))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return d(this,null,function*(){return this.ready?this.socket?new Promise((t,i)=>{this.socket&&this.socket.emit("list_mcp_servers",s=>{s.code===200?t(s.data):i(s)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(t,i){return d(this,null,function*(){var r,o,a;this.convertKnowledgesToChatFormat(this.knowledges);let s=E(w({},t),{promptVariables:this.promptVariables.filter(c=>c.type===I.PromptVariableType.User).reduce((c,l)=>E(w({},c),{[l.key]:l.value}),{}),systemPromptVariables:this.promptVariables.filter(c=>c.type===I.PromptVariableType.System).reduce((c,l)=>E(w({},c),{[l.key]:l.value}),{}),knowledges:(r=this.knowledges)==null?void 0:r.map(c=>c.id),enableTitleSummary:this.resolveEnableTitleSummary()});if(!this.active){if(yield this.activate(),!this.socket){const c=new Error($e.SocketConnectionFailed);return H.warn("error",c),this.event.emit("error",c),!1}(o=this.socket)==null||o.emit("question",s);return}(a=this.socket)==null||a.emit("question",s)})}invokeClientPlugin(t,i,s,r){const o=new AbortController;this.inflightCalls.add(o);let a=!1;const c=(...h)=>{a||(a=!0,this.inflightCalls.delete(o),!(this._stopAnswer||o.signal.aborted)&&s(...h))},l={requestId:r.requestId||ne.v4(),applicationId:this._applicationId,sessionId:this.id,pluginCode:r.pluginCode,functionCode:r.functionCode,signal:o.signal};try{const h=t(i,c,l);h&&typeof h.catch=="function"&&h.catch(u=>{H.error("client plugin failed",u),c({code:500,message:"客户端插件执行失败。"})})}catch(h){H.error("client plugin failed",h),c({code:500,message:"客户端插件执行失败。"})}}abortClientPluginCalls(){const t=Array.from(this.inflightCalls);this.inflightCalls.clear(),t.forEach(i=>i.abort())}stopAnswer(){var t;this.abortClientPluginCalls(),(t=this.socket)==null||t.emit("stop_answer")}inactivate(t=!1){return this.abortClientPluginCalls(),super.inactivate(t)}destroy(){return this.abortClientPluginCalls(),super.destroy()}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}function Yo(n,e){return d(this,null,function*(){const t=n.getReader();let i;for(;!(i=yield t.read()).done;)e(i.value)})}function Ko(n){let e,t,i,s=!1,r;return function(a){e===void 0?(e=a,t=0,i=-1,r=!1):e=Qo(e,a);const c=e.length;let l=0;for(;t<c;){s&&(e[t]===10&&(l=++t),s=!1);let h=-1;for(;t<c&&h===-1;++t)switch(e[t]){case 58:i===-1&&(i=t-l);break;case 13:s=!1,t+4<c&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(r=!0);case 10:h=t;break}if(h===-1)break;n(e.subarray(l,h),i,r),l=t,i=-1,r=!1}l===c?e=void 0:l!==0&&(e=e.subarray(l),t-=l)}}function Jo(n,e,t){let i=Zn();const s=new TextDecoder;return function(o,a,c){if(o.length===0)t==null||t(i),i=Zn();else if(a>0){const l=s.decode(o.subarray(0,a)),h=a+(o[a+1]===32?2:1);let u=s.decode(o.subarray(h));switch(c&&(u+=`
|
|
376
376
|
`),l){case"data":i.data=i.data?i.data+`
|
|
377
|
-
`+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 Qo(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function Zn(){return{data:"",event:"",id:"",retry:void 0}}const Ut="text/event-stream",Zo=1e3,ei="last-event-id";function ti(n,h){var u=h,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:a,fetch:c}=u,l=bn(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,g)=>{const b=w({},t);b.accept||(b.accept=Ut);let v;function _(){v.abort(),document.hidden||P()}a||document.addEventListener("visibilitychange",_);let x=Zo,S=0;function T(){document.removeEventListener("visibilitychange",_),window.clearTimeout(S),v.abort()}e==null||e.addEventListener("abort",()=>{T(),f()});const M=c!=null?c:window.fetch,ee=i!=null?i:ea;function P(){return d(this,null,function*(){var L;v=new AbortController;try{const A=yield M(n,E(w({},l),{headers:b,signal:v.signal}));yield ee(A),yield Yo(A.body,Ko(Jo(R=>{R?b[ei]=R:delete b[ei]},R=>{x=R},s))),r==null||r(),T(),f()}catch(A){if(!v.signal.aborted)try{const R=(L=o==null?void 0:o(A))!=null?L:x;window.clearTimeout(S),S=window.setTimeout(P,R)}catch(R){T(),g(R)}}})}P()})}function ea(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith(Ut)))throw new Error(`Expected content-type to be ${Ut}, Actual: ${e}`)}const ni=new U("[DialogSession] ");class ta extends pn{constructor(t,i="",s,r,o,a){super(t,i,s,r,o,a);y(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>d(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},l=E(w({},s),{stream:exports.configuration.stream});ti(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(l),openWhenHidden:!0,signal:r,onopen(h){return h.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(h){if(!h.data.includes('{"code": ')){let f={};try{f=JSON.parse(h.data)}catch(b){}(f==null?void 0:f.mtype)==="search"?c.searchReference.push(f):c.content=c.content+h.data;const g={content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:qt(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(o==null?void 0:o.onmessage)&&o.onmessage(g)}const u=JSON.parse(h.data);if(c.reference=u.data.reference,c.searchReference=u.data.searchReference,c.messageTime=u.data.messageTime,c.messageId=u.data.messageId,c.llmModel=u.data.llmModel,c.content=u.data.content,c.code=u.code,u.code===200){const f={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,isReplying:!0};o!=null&&o.onmessage&&o.onmessage(f)}else return o!=null&&o.onclose&&o.onclose(c),a&&a({code:c.code,message:c.message})},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const h={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};o!=null&&o.onclose&&o.onclose(h)}})})}postChatV3EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c=this,l={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},h=E(w({},s),{stream:exports.configuration.stream});ti(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(h),openWhenHidden:!0,signal:r,onopen(u){return u.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(u){if(!u.data&&!u.event&&!u.id&&!u.retry)return;let f={};try{f=JSON.parse(u.data)}catch(g){console.error("parse eventData to JSON failed. ",u.data)}if(f.code!==200)return l.index=-1,l.code=f.code,l.message=f.message,o!=null&&o.onmessage&&o.onmessage(l),a&&a({code:f.code,message:f.message});c.handleStreamAnswer(f,l),o!=null&&o.onmessage&&o.onmessage(l)},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const u=E(w({},l),{isReplying:!1});o!=null&&o.onclose&&o.onclose(u)}})})}sendQuestion(t,i){return d(this,null,function*(){const{content:s,fileIds:r,oldMessageId:o,imageContent:a}=t,{stream:c,referenceFirst:l}=i;if(this.active||(yield this.activate()),this._id){const h=this.convertKnowledgesToChatFormat(this.knowledges);let u={content:s,fileIds:r,referenceFirst:l,oldMessageId:o,promptVariables:this.promptVariables.filter(f=>f.type===I.PromptVariableType.User).reduce((f,g)=>E(w({},f),{[g.key]:g.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===I.PromptVariableType.System).reduce((f,g)=>E(w({},f),{[g.key]:g.value}),{}),knowledges:h,enableTitleSummary:this.resolveEnableTitleSummary(),imageContent:a};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,u,this.ctrl.signal,{onopen:()=>{ni.log("open",this.ctrl)},onmessage:f=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===I.ChatMessageRole.Robot?(g=w(w({},g),f),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(f),this.event.emit("message:content",f))},onclose:f=>d(this,null,function*(){this._stopAnswer||(ni.log(f,"onclose"),this.event.emit("answer:finish",f))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}const na="@glodon-aiot/bot-client-sdk",ia="3.26.0-alpha.31",sa="glodoncv",ra="aiot bot client js sdk",oa="module",aa=!1,ca=["aiot","bot","bot client","sdk"],la=["dist"],da="./dist/es/index.mjs",ha="./dist/lib/index.js",ua="./dist/src/index.d.ts",fa={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},pa="MIT",ma={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"},ga={"@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"},ya={access:"public",registry:"https://registry.npmjs.org/"},wa={"@glodon-aiot/apis":"^3.26.0-alpha.31",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"},va={name:na,version:ia,author:sa,description:ra,type:oa,sideEffects:aa,keywords:ca,files:la,module:da,main:ha,typings:ua,exports:fa,license:pa,scripts:ma,devDependencies:ga,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:ya,dependencies:wa},ii=new U("[BotClient] ");class ba{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){y(this,"event",new dn);y(this,"cvforceApi");y(this,"_applicationId");y(this,"_application",null);y(this,"_sessions",[]);y(this,"_activeSession");y(this,"_ready",!1);y(this,"_questionContextMaxLength",4e3);y(this,"_promptVariables",[]);y(this,"_localWorkspace");y(this,"_disconnectHost");if(this._token=e,this.lazyload=i,this.sdkConfigs=s,Dt(t,{refreshBuiltinPlugins:!1}),this._applicationId=it(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{Dt(E(w({},t),{stream:t.stream===void 0?(r==null?void 0:r.type)===I.ApplicationTypes.Dialog||(r==null?void 0:r.type)===I.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)){zn(void 0),De();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=no(exports.configuration.apiRoot,this.token,(a,c)=>ii.error(c));this._localWorkspace=new Ki({applicationId:this._applicationId,config:e,store:Xi(),picker:i==="host-bridge"?null:void 0,transfer:un(()=>this.cvforceApi,()=>o)}),zn(this._localWorkspace),this._localWorkspace.platformSkills=new oo({applicationId:()=>this._applicationId,getToken:()=>this.token,getSkills:()=>{var a,c,l,h;return(h=(l=(c=(a=this._application)==null?void 0:a.arrange)==null?void 0:c[0])==null?void 0:l.skills)!=null?h:[]},apiRoot:()=>exports.configuration.apiRoot,getSandbox:()=>{var c;const a=(c=this._localWorkspace)==null?void 0:c.adapter;return a instanceof Be?a.sandbox:void 0}}),i==="host-bridge"?this._disconnectHost=co(this._localWorkspace):this._localWorkspace.restore()}t.push(...De()),t.length&&Promise.resolve().then(()=>t.forEach(o=>this.event.emit("error",o)))}get localWorkspace(){return this._localWorkspace}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return d(this,null,function*(){var t,i,s,r,o;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(i=this.sdkConfigs.ui)==null?void 0:i.version,sdkVersion:va.version}).then(a=>(typeof a.arrange[0].thinkingModeOpen!="boolean"&&(a.arrange[0].thinkingModeOpen=!0),typeof a.arrange[0].thinkingTextOpen!="boolean"&&(a.arrange[0].thinkingTextOpen=!0),E(w({},a),{arrange:[E(w({},a.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&a.arrange[0].recommendQuestionOpen})]})));const e=(o=(r=(s=this._application)==null?void 0:s.arrange)==null?void 0:r[0])==null?void 0:o.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(a=>a.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type:I.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:I.PromptVariableType.System})]).then(([a,c])=>[...a,...c]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:Ui(exports.configuration.apiRoot,this.token,(e,t)=>ii.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=it(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,i,s,r){return d(this,null,function*(){const o=this;return new Promise((a,c)=>{const l=h=>d(this,null,function*(){if(h===I.ApplicationTypes.Agent)a(new Xo(e,t,i,s,r,o));else if(h===I.ApplicationTypes.Dialog)a(new ta(e,t,i,s,r,o));else throw Error(`不支持的应用类型:${h}`)});if(this.ready){if(!this._application)throw Error("client is not ready");l(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");l(this._application.type)},!0)})})}getArtifacts(e){return d(this,null,function*(){var r,o;this.checkReady();const t=e||((r=this._activeSession)==null?void 0:r.id);if(!t)throw new Error("session id is not defined");const i=this._sessions.find(a=>a.id===t);if(i)return i.getArtifacts();const s=yield this.cvforceApi.getSessionArtifacts(this._applicationId,t);return(o=s==null?void 0:s.artifacts)!=null?o:[]})}getSessions(e){return d(this,null,function*(){return new Promise((t,i)=>{const s=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>d(this,null,function*(){const o=[];for(const a of r){const c=this._sessions.find(l=>l.id===a.id);if(c)c.data=a,this._application?c.application=this._application:yield c.loadApplicationInfo(),o.push(c);else{const l=yield this.createSession(this.token,a.id,a,this.lazyload,this._application||void 0);o.push(l)}}if(e!=null&&e.pageSize){const a=[...this._sessions,...o],c=new Map;for(const l of a)c.set(l.id,l);return this.sessions=Array.from(c.values()),this.sessions}else return this.sessions=o,o}));if(this.ready){if(!this._application)throw Error("_application is null");t(s())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(s())},!0)})})}loadSession(e="",t){return d(this,null,function*(){var s,r;this.checkReady(),(r=(s=this._localWorkspace)==null?void 0:s.platformSkills)==null||r.sync();let i=this.sessions.find(o=>o.id===e);if(i||(i=yield this.createSession(this.token,e,t),this._sessions.push(i)),this._activeSession){if(this._activeSession===i)return i;this._activeSession.inactivate()}return i.id?(this._activeSession=i,yield i.activate()):i.addEventListener("data:loaded",()=>{this._activeSession!==i&&(i==null||i.activate(),this._activeSession=i)},!0),i})}reload(){return this.loadApplication().then(()=>d(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return d(this,null,function*(){yield this.reload();let t=this._sessions.find(i=>i.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,i="top_time desc, sort_status desc, updated_at desc"){return d(this,null,function*(){let s=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!s){console.warn("setTop session failed.");return}return yield s.setTop(t),this.getSessions({order:i})})}addEventListener(e,t,i=!1){if(typeof t!="function")throw Error("event listener is not a function");if(i){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return d(this,null,function*(){this.checkReady();let i=-1;if(typeof e=="string"?i=this._sessions.findIndex(s=>s.id===e):i=this._sessions.findIndex(s=>s.id===e.id),i>-1){const s=this._sessions[i];t&&(yield s.delete()),this._sessions.splice(i,1)}else console.warn("session delete failed, session is not exist.")})}clean(){var e;(e=this._disconnectHost)==null||e.call(this),this._disconnectHost=void 0,this._sessions.forEach(t=>t.destroy()),this.sessions=[]}}class _a{constructor(e,t={},i){y(this,"code");y(this,"description","");y(this,"loaded",!1);y(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}const X="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",Y={type:"string",enum:[Se],description:`工作区 ID。省略时按 ${Se} 处理,传其他值会被拒绝。`},K=n=>({type:"string",description:`${n}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),At={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},Qi={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${X}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:Y,path:K('要列出的目录,省略或传 "." 表示工作区根目录。'),offset:{type:"integer",minimum:0,description:"分页起始位置,默认 0。"},limit:{type:"integer",minimum:1,maximum:1e3,description:"每页条数,默认 200。"}}}},read_file:{functionCode:"read_file",name:"读取本地文件",description:`${X}按行读取文本文件,单次最多返回 1 MiB,超出部分会被截断(truncated: true)。返回内容的 hash 可用于后续修改。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:Y,path:K("要读取的文件。"),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:`${X}返回文件或目录的类型、大小、修改时间,可选返回 hash。不返回文件内容。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:Y,path:K("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${X}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:Y,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:K("搜索起点目录,默认工作区根目录。"),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:`${X}在指定文件或目录(递归)中搜索普通文本(不支持正则),返回所在文件、行号与该行内容。必须指定 path,不能搜索整个文件夹。`,parameters:{type:"object",required:["grantId","path","query"],properties:{grantId:Y,path:K("搜索范围,可以是文件或目录。"),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:`${X}以查找替换的方式修改 UTF-8 文本文件。每条修改的 oldText 必须在文件中唯一出现(或设置 replaceAll)。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","expectedHash","edits"],properties:{grantId:Y,path:K("要修改的文件。"),expectedHash:At,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:`${X}新建文件,或整体覆盖已有文件(覆盖时必须提供 expectedHash)。修改已有文件优先使用 apply_patch。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","content"],properties:{grantId:Y,path:K("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:At,createDirectories:{type:"boolean",description:"父目录不存在时是否自动创建,默认否。"}}}},upload_file:{functionCode:"upload_file",name:"上传本地文件",description:`${X}把本地文件夹中的文件上传到平台文件服务,返回 fileId、name、size 和 url。url 是文件访问地址,可直接用于后续推理或对话。下载回本地文件夹时使用 download_file,source.type 为 platformFile。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:Y,path:K("要上传的文件。"),target:{type:"string",description:"上传目标,目前只支持 session(默认),其他值返回 501。"},mimeHint:{type:"string",description:"可选的 MIME 类型。"}}}},download_file:{functionCode:"download_file",name:"下载到本地文件夹",description:`${X}把会话文件、平台文件或 https 地址保存到本地文件夹。source.type 为 url 时必须同时填写 source.url(完整地址),为 sessionFile 或 platformFile 时必须同时填写 source.fileId。不要只传 type。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","destPath","source"],properties:{grantId:Y,destPath:K("保存位置(文件路径)。"),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:At}}}},ka=new TextEncoder;function ie(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const Ea=(n,e)=>d(exports,null,function*(){const t=Z(n.path,{allowRoot:!0});if((yield e.adapter.stat(t)).kind!=="directory")throw new p(m.BadRequest,"目标是文件,不是目录。");const s=ie(n.offset,0,0,Number.MAX_SAFE_INTEGER),r=ie(n.limit,hi,1,ui),o=yield e.adapter.listEntries(t,e.signal);o.sort((c,l)=>c.kind!==l.kind?c.kind==="directory"?-1:1:c.name<l.name?-1:c.name>l.name?1:0);const a=o.slice(s,s+r).map(c=>{const l=Wi(t,c.name),h={name:c.name,path:l,kind:c.kind};return c.kind==="file"&&(h.size=c.size,h.lastModified=c.lastModified,e.sensitive.isSensitive(l)&&(h.sensitive=!0)),h});return{data:{path:t,entries:a,total:o.length,hasMore:s+a.length<o.length}}});function Sa(n,e,t){return pe(this,null,function*(){var a;const i=new TextDecoder(e),s=n.stream().getReader();let r="",o=!1;try{for(;;){F(t);const{done:c,value:l}=yield new se(s.read());r+=c?i.decode():i.decode(l,{stream:!0});const h=r.split(`
|
|
377
|
+
`+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 Qo(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function Zn(){return{data:"",event:"",id:"",retry:void 0}}const Ut="text/event-stream",Zo=1e3,ei="last-event-id";function ti(n,h){var u=h,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:a,fetch:c}=u,l=bn(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,g)=>{const b=w({},t);b.accept||(b.accept=Ut);let v;function _(){v.abort(),document.hidden||P()}a||document.addEventListener("visibilitychange",_);let x=Zo,S=0;function T(){document.removeEventListener("visibilitychange",_),window.clearTimeout(S),v.abort()}e==null||e.addEventListener("abort",()=>{T(),f()});const M=c!=null?c:window.fetch,ee=i!=null?i:ea;function P(){return d(this,null,function*(){var L;v=new AbortController;try{const A=yield M(n,E(w({},l),{headers:b,signal:v.signal}));yield ee(A),yield Yo(A.body,Ko(Jo(R=>{R?b[ei]=R:delete b[ei]},R=>{x=R},s))),r==null||r(),T(),f()}catch(A){if(!v.signal.aborted)try{const R=(L=o==null?void 0:o(A))!=null?L:x;window.clearTimeout(S),S=window.setTimeout(P,R)}catch(R){T(),g(R)}}})}P()})}function ea(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith(Ut)))throw new Error(`Expected content-type to be ${Ut}, Actual: ${e}`)}const ni=new U("[DialogSession] ");class ta extends pn{constructor(t,i="",s,r,o,a){super(t,i,s,r,o,a);y(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>d(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},l=E(w({},s),{stream:exports.configuration.stream});ti(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(l),openWhenHidden:!0,signal:r,onopen(h){return h.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(h){if(!h.data.includes('{"code": ')){let f={};try{f=JSON.parse(h.data)}catch(b){}(f==null?void 0:f.mtype)==="search"?c.searchReference.push(f):c.content=c.content+h.data;const g={content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:qt(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(o==null?void 0:o.onmessage)&&o.onmessage(g)}const u=JSON.parse(h.data);if(c.reference=u.data.reference,c.searchReference=u.data.searchReference,c.messageTime=u.data.messageTime,c.messageId=u.data.messageId,c.llmModel=u.data.llmModel,c.content=u.data.content,c.code=u.code,u.code===200){const f={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,isReplying:!0};o!=null&&o.onmessage&&o.onmessage(f)}else return o!=null&&o.onclose&&o.onclose(c),a&&a({code:c.code,message:c.message})},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const h={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};o!=null&&o.onclose&&o.onclose(h)}})})}postChatV3EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c=this,l={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},h=E(w({},s),{stream:exports.configuration.stream});ti(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(h),openWhenHidden:!0,signal:r,onopen(u){return u.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(u){if(!u.data&&!u.event&&!u.id&&!u.retry)return;let f={};try{f=JSON.parse(u.data)}catch(g){console.error("parse eventData to JSON failed. ",u.data)}if(f.code!==200)return l.index=-1,l.code=f.code,l.message=f.message,o!=null&&o.onmessage&&o.onmessage(l),a&&a({code:f.code,message:f.message});c.handleStreamAnswer(f,l),o!=null&&o.onmessage&&o.onmessage(l)},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const u=E(w({},l),{isReplying:!1});o!=null&&o.onclose&&o.onclose(u)}})})}sendQuestion(t,i){return d(this,null,function*(){const{content:s,fileIds:r,oldMessageId:o,imageContent:a}=t,{stream:c,referenceFirst:l}=i;if(this.active||(yield this.activate()),this._id){const h=this.convertKnowledgesToChatFormat(this.knowledges);let u={content:s,fileIds:r,referenceFirst:l,oldMessageId:o,promptVariables:this.promptVariables.filter(f=>f.type===I.PromptVariableType.User).reduce((f,g)=>E(w({},f),{[g.key]:g.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===I.PromptVariableType.System).reduce((f,g)=>E(w({},f),{[g.key]:g.value}),{}),knowledges:h,enableTitleSummary:this.resolveEnableTitleSummary(),imageContent:a};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,u,this.ctrl.signal,{onopen:()=>{ni.log("open",this.ctrl)},onmessage:f=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===I.ChatMessageRole.Robot?(g=w(w({},g),f),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(f),this.event.emit("message:content",f))},onclose:f=>d(this,null,function*(){this._stopAnswer||(ni.log(f,"onclose"),this.event.emit("answer:finish",f))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}const na="@glodon-aiot/bot-client-sdk",ia="3.26.0-alpha.32",sa="glodoncv",ra="aiot bot client js sdk",oa="module",aa=!1,ca=["aiot","bot","bot client","sdk"],la=["dist"],da="./dist/es/index.mjs",ha="./dist/lib/index.js",ua="./dist/src/index.d.ts",fa={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},pa="MIT",ma={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"},ga={"@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"},ya={access:"public",registry:"https://registry.npmjs.org/"},wa={"@glodon-aiot/apis":"^3.26.0-alpha.32",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"},va={name:na,version:ia,author:sa,description:ra,type:oa,sideEffects:aa,keywords:ca,files:la,module:da,main:ha,typings:ua,exports:fa,license:pa,scripts:ma,devDependencies:ga,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:ya,dependencies:wa},ii=new U("[BotClient] ");class ba{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){y(this,"event",new dn);y(this,"cvforceApi");y(this,"_applicationId");y(this,"_application",null);y(this,"_sessions",[]);y(this,"_activeSession");y(this,"_ready",!1);y(this,"_questionContextMaxLength",4e3);y(this,"_promptVariables",[]);y(this,"_localWorkspace");y(this,"_disconnectHost");if(this._token=e,this.lazyload=i,this.sdkConfigs=s,Dt(t,{refreshBuiltinPlugins:!1}),this._applicationId=it(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{Dt(E(w({},t),{stream:t.stream===void 0?(r==null?void 0:r.type)===I.ApplicationTypes.Dialog||(r==null?void 0:r.type)===I.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)){zn(void 0),De();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=no(exports.configuration.apiRoot,this.token,(a,c)=>ii.error(c));this._localWorkspace=new Ki({applicationId:this._applicationId,config:e,store:Xi(),picker:i==="host-bridge"?null:void 0,transfer:un(()=>this.cvforceApi,()=>o)}),zn(this._localWorkspace),this._localWorkspace.platformSkills=new oo({applicationId:()=>this._applicationId,getToken:()=>this.token,getSkills:()=>{var a,c,l,h;return(h=(l=(c=(a=this._application)==null?void 0:a.arrange)==null?void 0:c[0])==null?void 0:l.skills)!=null?h:[]},apiRoot:()=>exports.configuration.apiRoot,getSandbox:()=>{var c;const a=(c=this._localWorkspace)==null?void 0:c.adapter;return a instanceof Be?a.sandbox:void 0}}),i==="host-bridge"?this._disconnectHost=co(this._localWorkspace):this._localWorkspace.restore()}t.push(...De()),t.length&&Promise.resolve().then(()=>t.forEach(o=>this.event.emit("error",o)))}get localWorkspace(){return this._localWorkspace}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return d(this,null,function*(){var t,i,s,r,o;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(i=this.sdkConfigs.ui)==null?void 0:i.version,sdkVersion:va.version}).then(a=>(typeof a.arrange[0].thinkingModeOpen!="boolean"&&(a.arrange[0].thinkingModeOpen=!0),typeof a.arrange[0].thinkingTextOpen!="boolean"&&(a.arrange[0].thinkingTextOpen=!0),E(w({},a),{arrange:[E(w({},a.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&a.arrange[0].recommendQuestionOpen})]})));const e=(o=(r=(s=this._application)==null?void 0:s.arrange)==null?void 0:r[0])==null?void 0:o.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(a=>a.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type:I.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:I.PromptVariableType.System})]).then(([a,c])=>[...a,...c]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:Ui(exports.configuration.apiRoot,this.token,(e,t)=>ii.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=it(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,i,s,r){return d(this,null,function*(){const o=this;return new Promise((a,c)=>{const l=h=>d(this,null,function*(){if(h===I.ApplicationTypes.Agent)a(new Xo(e,t,i,s,r,o));else if(h===I.ApplicationTypes.Dialog)a(new ta(e,t,i,s,r,o));else throw Error(`不支持的应用类型:${h}`)});if(this.ready){if(!this._application)throw Error("client is not ready");l(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");l(this._application.type)},!0)})})}getArtifacts(e){return d(this,null,function*(){var r,o;this.checkReady();const t=e||((r=this._activeSession)==null?void 0:r.id);if(!t)throw new Error("session id is not defined");const i=this._sessions.find(a=>a.id===t);if(i)return i.getArtifacts();const s=yield this.cvforceApi.getSessionArtifacts(this._applicationId,t);return(o=s==null?void 0:s.artifacts)!=null?o:[]})}getSessions(e){return d(this,null,function*(){return new Promise((t,i)=>{const s=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>d(this,null,function*(){const o=[];for(const a of r){const c=this._sessions.find(l=>l.id===a.id);if(c)c.data=a,this._application?c.application=this._application:yield c.loadApplicationInfo(),o.push(c);else{const l=yield this.createSession(this.token,a.id,a,this.lazyload,this._application||void 0);o.push(l)}}if(e!=null&&e.pageSize){const a=[...this._sessions,...o],c=new Map;for(const l of a)c.set(l.id,l);return this.sessions=Array.from(c.values()),this.sessions}else return this.sessions=o,o}));if(this.ready){if(!this._application)throw Error("_application is null");t(s())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(s())},!0)})})}loadSession(e="",t){return d(this,null,function*(){var s,r;this.checkReady(),(r=(s=this._localWorkspace)==null?void 0:s.platformSkills)==null||r.sync();let i=this.sessions.find(o=>o.id===e);if(i||(i=yield this.createSession(this.token,e,t),this._sessions.push(i)),this._activeSession){if(this._activeSession===i)return i;this._activeSession.inactivate()}return i.id?(this._activeSession=i,yield i.activate()):i.addEventListener("data:loaded",()=>{this._activeSession!==i&&(i==null||i.activate(),this._activeSession=i)},!0),i})}reload(){return this.loadApplication().then(()=>d(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return d(this,null,function*(){yield this.reload();let t=this._sessions.find(i=>i.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,i="top_time desc, sort_status desc, updated_at desc"){return d(this,null,function*(){let s=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!s){console.warn("setTop session failed.");return}return yield s.setTop(t),this.getSessions({order:i})})}addEventListener(e,t,i=!1){if(typeof t!="function")throw Error("event listener is not a function");if(i){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return d(this,null,function*(){this.checkReady();let i=-1;if(typeof e=="string"?i=this._sessions.findIndex(s=>s.id===e):i=this._sessions.findIndex(s=>s.id===e.id),i>-1){const s=this._sessions[i];t&&(yield s.delete()),this._sessions.splice(i,1)}else console.warn("session delete failed, session is not exist.")})}clean(){var e;(e=this._disconnectHost)==null||e.call(this),this._disconnectHost=void 0,this._sessions.forEach(t=>t.destroy()),this.sessions=[]}}class _a{constructor(e,t={},i){y(this,"code");y(this,"description","");y(this,"loaded",!1);y(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}const X="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",Y={type:"string",enum:[Se],description:`工作区 ID。省略时按 ${Se} 处理,传其他值会被拒绝。`},K=n=>({type:"string",description:`${n}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),At={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},Qi={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${X}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:Y,path:K('要列出的目录,省略或传 "." 表示工作区根目录。'),offset:{type:"integer",minimum:0,description:"分页起始位置,默认 0。"},limit:{type:"integer",minimum:1,maximum:1e3,description:"每页条数,默认 200。"}}}},read_file:{functionCode:"read_file",name:"读取本地文件",description:`${X}按行读取文本文件,单次最多返回 1 MiB,超出部分会被截断(truncated: true)。返回内容的 hash 可用于后续修改。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:Y,path:K("要读取的文件。"),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:`${X}返回文件或目录的类型、大小、修改时间,可选返回 hash。不返回文件内容。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:Y,path:K("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${X}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:Y,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:K("搜索起点目录,默认工作区根目录。"),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:`${X}在指定文件或目录(递归)中搜索普通文本(不支持正则),返回所在文件、行号与该行内容。必须指定 path,不能搜索整个文件夹。`,parameters:{type:"object",required:["grantId","path","query"],properties:{grantId:Y,path:K("搜索范围,可以是文件或目录。"),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:`${X}以查找替换的方式修改 UTF-8 文本文件。每条修改的 oldText 必须在文件中唯一出现(或设置 replaceAll)。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","expectedHash","edits"],properties:{grantId:Y,path:K("要修改的文件。"),expectedHash:At,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:`${X}新建文件,或整体覆盖已有文件(覆盖时必须提供 expectedHash)。修改已有文件优先使用 apply_patch。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","content"],properties:{grantId:Y,path:K("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:At,createDirectories:{type:"boolean",description:"父目录不存在时是否自动创建,默认否。"}}}},upload_file:{functionCode:"upload_file",name:"上传本地文件",description:`${X}把本地文件夹中的文件上传到平台文件服务,返回 fileId、name、size 和 url。url 是文件访问地址,可直接用于后续推理或对话。下载回本地文件夹时使用 download_file,source.type 为 platformFile。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:Y,path:K("要上传的文件。"),target:{type:"string",description:"上传目标,目前只支持 session(默认),其他值返回 501。"},mimeHint:{type:"string",description:"可选的 MIME 类型。"}}}},download_file:{functionCode:"download_file",name:"下载到本地文件夹",description:`${X}把会话文件、平台文件或 https 地址保存到本地文件夹。source.type 为 url 时必须同时填写 source.url(完整地址),为 sessionFile 或 platformFile 时必须同时填写 source.fileId。不要只传 type。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","destPath","source"],properties:{grantId:Y,destPath:K("保存位置(文件路径)。"),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:At}}}},ka=new TextEncoder;function ie(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const Ea=(n,e)=>d(exports,null,function*(){const t=Z(n.path,{allowRoot:!0});if((yield e.adapter.stat(t)).kind!=="directory")throw new p(m.BadRequest,"目标是文件,不是目录。");const s=ie(n.offset,0,0,Number.MAX_SAFE_INTEGER),r=ie(n.limit,hi,1,ui),o=yield e.adapter.listEntries(t,e.signal);o.sort((c,l)=>c.kind!==l.kind?c.kind==="directory"?-1:1:c.name<l.name?-1:c.name>l.name?1:0);const a=o.slice(s,s+r).map(c=>{const l=Wi(t,c.name),h={name:c.name,path:l,kind:c.kind};return c.kind==="file"&&(h.size=c.size,h.lastModified=c.lastModified,e.sensitive.isSensitive(l)&&(h.sensitive=!0)),h});return{data:{path:t,entries:a,total:o.length,hasMore:s+a.length<o.length}}});function Sa(n,e,t){return pe(this,null,function*(){var a;const i=new TextDecoder(e),s=n.stream().getReader();let r="",o=!1;try{for(;;){F(t);const{done:c,value:l}=yield new se(s.read());r+=c?i.decode():i.decode(l,{stream:!0});const h=r.split(`
|
|
378
378
|
`);r=(a=h.pop())!=null?a:"";for(const u of h)o=!0,yield u;if(c)break}}finally{s.releaseLock()}(r||!o)&&(yield r)})}const Ia=(n,e)=>d(exports,null,function*(){var T,M;const t=Z(n.path);Te(e,t,"read");const i=yield Zt(e.adapter,t),s=yield e.adapter.readFile(t),r=(T=i.size)!=null?T:s.size;if(yield Ds(s))throw new p(m.BadRequest,"这是二进制文件,不能按文本读取。可以使用 stat_file 查看信息,或使用 upload_file 上传到会话。");const o=yield G(s.slice(0,3)),a=Ri(o)?"utf-8":(M=n.encoding)!=null?M:"utf-8",c=ie(n.startLine,1,1,Number.MAX_SAFE_INTEGER),l=n.endLine===void 0?Number.MAX_SAFE_INTEGER:Math.max(Math.trunc(n.endLine),c),h=ie(n.maxBytes,e.limits.maxReadBytes,1,e.limits.maxReadBytes),u=r<=e.limits.maxTransferBytes,f=[];let g=0,b=0,v=c-1,_=!1,x=!1;try{for(var ee=V(Sa(s,a,e.signal)),P,L,A;P=!(L=yield ee.next()).done;P=!1){const R=L.value;b++;const q=R.endsWith("\r")?R.slice(0,-1):R;if(q!==R&&(x=!0),b<c||b>l||_){if(!u&&(_||b>l))break;continue}const j=en(q)+(f.length?1:0);if(g+j>h){if(_=!0,f.length||(f.push(xa(q,h)),v=b),!u)break;continue}f.push(q),g+=j,v=b}}catch(L){A=[L]}finally{try{P&&(L=ee.return)&&(yield L.call(ee))}finally{if(A)throw A[0]}}const S={path:t,content:f.join(`
|
|
379
379
|
`),startLine:c,endLine:Math.max(v,c-1),size:r,encoding:a,lineEnding:x?"crlf":"lf"};return u&&(S.totalLines=b),r<=e.limits.maxWriteBytes&&(S.hash=yield xe(yield G(s))),{data:S,truncated:_||void 0}});function xa(n,e){const t=ka.encode(n);return t.byteLength<=e?n:new TextDecoder().decode(t.slice(0,e)).replace(/\uFFFD$/,"")}const Aa=(n,e)=>d(exports,null,function*(){var r;const t=Z(n.path),i=yield e.adapter.stat(t),s={path:t,kind:i.kind,sensitive:i.kind==="file"&&e.sensitive.isSensitive(t)};return i.kind==="file"&&(s.size=i.size,s.lastModified=i.lastModified,n.includeHash&&((r=i.size)!=null?r:0)<=e.limits.maxTransferBytes&&(s.hash=yield xe(yield G(yield e.adapter.readFile(t))))),{data:s}});function Ta(n){return vi.some(e=>tt(e,n))}function Zi(n,e,t){return pe(this,null,function*(){const i=[{path:e,depth:0}];let s=0;for(;i.length;){const r=i.shift();F(n.signal),++s%20===0&&(yield new se(Mi()));const o=yield new se(n.adapter.listEntries(r.path,n.signal));o.sort((a,c)=>a.name<c.name?-1:a.name>c.name?1:0);for(const a of o){const c=Wi(r.path,a.name);if(a.kind==="directory"){r.depth+1<t&&!wi.includes(a.name)&&i.push({path:c,depth:r.depth+1});continue}Ta(a.name)||n.sensitive.match(c,"search")||(yield{path:c,relativePath:e?c.slice(e.length+1):c,name:a.name,size:a.size,lastModified:a.lastModified})}}})}function es(n,e){return n.includes("/")?tt(n,e.relativePath):tt(n,e.name)}const La=(n,e)=>d(exports,null,function*(){const t=Z(n.path,{allowRoot:!0});if(!n.pattern.trim())throw new p(m.BadRequest,"参数 pattern 不能为空。");const i=n.pattern.replace(/\\/g,"/").replace(/^\.\//,"");if((yield e.adapter.stat(t)).kind!=="directory")throw new p(m.BadRequest,"参数 path 必须是目录。");const r=ie(n.maxDepth,fi,1,zt),o=ie(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),a=[];let c=!1;try{for(var l=V(Zi(e,t,r)),h,u,f;h=!(u=yield l.next()).done;h=!1){const g=u.value;if(es(i,g)){if(a.length>=o){c=!0;break}a.push({path:g.path,size:g.size,lastModified:g.lastModified})}}}catch(u){f=[u]}finally{try{h&&(u=l.return)&&(yield u.call(l))}finally{if(f)throw f[0]}}return{data:{matches:a},truncated:c||void 0}});function Tt(n,e){if(n.length<=Xe)return n;const t=Math.max(0,Math.min(e-100,n.length-Xe));return n.slice(t,t+Xe)}const Ra=(n,e)=>d(exports,null,function*(){var f;const t=Z(n.path,{allowRoot:!0});if(!t&&!e.allowWorkspaceWideTextSearch)throw new p(m.BadRequest,"不支持在整个工作区内搜索文本,请把 path 缩小到具体的子目录或文件。");if(n.isRegex)throw new p(m.NotImplemented,"暂不支持正则搜索,请使用普通文本搜索。");if(!n.query)throw new p(m.BadRequest,"参数 query 不能为空。");const i=n.caseSensitive===!0,s=i?n.query:n.query.toLowerCase(),r=ie(n.contextLines,0,0,gi),o=ie(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),a=yield e.adapter.stat(t);let c;a.kind==="file"?(Te(e,t,"search"),c=function(){return pe(this,null,function*(){yield{path:t,relativePath:t,name:a.name,size:a.size}})}()):c=Zi(e,t,zt);const l=[];let h=0,u=!1;e:try{for(var g=V(c),b,v,_;b=!(v=yield g.next()).done;b=!1){const x=v.value;if(n.glob&&!es(n.glob,x)||((f=x.size)!=null?f:0)>mi)continue;if(h>=pi){u=!0;break}h++,h%20===0&&(yield Mi()),F(e.signal);const S=yield G(yield e.adapter.readFile(x.path));if(he(S))continue;const T=new TextDecoder("utf-8").decode(S).split(/\r?\n/);for(let M=0;M<T.length;M++){const P=(i?T[M]:T[M].toLowerCase()).indexOf(s);if(P<0)continue;if(l.length>=o){u=!0;break e}const L={path:x.path,line:M+1,column:P+1,text:Tt(T[M],P)};r&&(L.before=T.slice(Math.max(0,M-r),M).map(A=>Tt(A,0)),L.after=T.slice(M+1,M+1+r).map(A=>Tt(A,0))),l.push(L)}}}catch(v){_=[v]}finally{try{b&&(v=g.return)&&(yield v.call(g))}finally{if(_)throw _[0]}}return{data:{matches:l,filesScanned:h},truncated:u||void 0}});function si(){return new p(m.Forbidden,"下载地址不在允许范围内:只允许 https 协议且域名在白名单中的地址。",{reason:"url_not_allowed"})}const Ma=(n,e)=>d(exports,null,function*(){var u,f;const t=Z(n.path);if(((u=n.target)!=null?u:"session")!=="session")throw new p(m.NotImplemented,"目前只支持上传到当前会话(target: session)。");Te(e,t,"read");const s=yield Zt(e.adapter,t),r=(f=s.size)!=null?f:0;if(r>e.limits.maxTransferBytes)throw de(e.limits.maxTransferBytes);const o=Jt(t);yield e.requestApproval(t,{type:"upload",name:o,size:r,target:"session"}),e.progress({stage:"reading",loaded:0,total:r,path:t});const a=yield e.adapter.readFile(t);F(e.signal);const c=new File([a],o,{type:n.mimeHint||a.type||"application/octet-stream",lastModified:s.lastModified}),{fileId:l,url:h}=yield e.transfer.upload(c,e.context,({loaded:g,total:b})=>e.progress({stage:"uploading",loaded:g,total:b,path:t}));return F(e.signal),e.progress({stage:"done",loaded:r,total:r,path:t}),{data:{fileId:l,name:o,size:r,url:h}}});function Ca(n){const e=n;if(!e||typeof e!="object")throw new p(m.BadRequest,"缺少参数 source。");if(e.type==="sessionFile"||e.type==="platformFile"){if(typeof e.fileId!="string"||!e.fileId)throw new p(m.BadRequest,"source.fileId 必须是非空字符串。");return{type:e.type,fileId:e.fileId}}if(e.type==="url"){if(typeof e.url!="string"||!e.url)throw new p(m.BadRequest,"source.url 必须是非空字符串。");return{type:"url",url:e.url}}throw new p(m.BadRequest,"source.type 必须是 sessionFile、platformFile 或 url 之一。")}function Fa(n){return n.type==="sessionFile"?"会话文件":n.type==="platformFile"?"平台文件":new URL(n.url).hostname}function Oa(n,e,t,i,s){return pe(this,null,function*(){const r=n.getReader();let o=0;try{for(;;){F(e.signal);const{done:a,value:c}=yield new se(r.read());if(a)break;if(o+=c.byteLength,o>e.limits.maxTransferBytes)throw de(e.limits.maxTransferBytes,"下载内容");s.push(c),e.progress({stage:"downloading",loaded:o,total:i,path:t}),yield c}}finally{r.cancel().catch(()=>{})}})}const Na=(n,e)=>d(exports,null,function*(){var v,_,x;const t=Z(n.destPath,{field:"destPath"}),i=Ca(n.source);if(i.type==="url"&&!jt(i.url,e.downloadUrlAllowlist))throw si();Te(e,t,"write");const s=yield Ke(e.adapter,t);if((s==null?void 0:s.kind)==="directory")throw new p(m.BadRequest,"目标是目录,不能写入文件。");if(s&&!n.overwrite)throw new p(m.Conflict,"目标文件已存在。如需覆盖,请设置 overwrite: true。");const r=()=>d(exports,null,function*(){if(!s||!n.expectedHash)return;const S=yield xe(yield G(yield e.adapter.readFile(t)));if(S!==n.expectedHash)throw new p(m.Conflict,"expectedHash 与目标文件当前内容不一致。",{currentHash:S})});yield r();const o=i.type==="url"?{url:i.url}:yield e.transfer.resolveDownload(i,e.context);if(o.size!==void 0&&o.size>e.limits.maxTransferBytes)throw de(e.limits.maxTransferBytes);const a={type:"download",source:{type:i.type,label:Fa(i)},name:(v=o.name)!=null?v:Jt(t),size:o.size,overwrite:!!s};yield e.requestApproval(t,a),yield r();let c;try{c=yield e.fetch(o.url,{headers:o.headers,credentials:"omit",redirect:"follow",signal:e.signal})}catch(S){throw F(e.signal),new p(m.Internal,"下载失败,无法连接到文件地址。")}if(i.type==="url"&&c.url&&!jt(c.url,e.downloadUrlAllowlist))throw(_=c.body)==null||_.cancel().catch(()=>{}),si();if(!c.ok||!c.body)throw(x=c.body)==null||x.cancel().catch(()=>{}),new p(c.status===404?m.NotFound:m.Internal,`下载失败(HTTP ${c.status})。`);const l=Number(c.headers.get("content-length")),h=Number.isFinite(l)&&l>0?l:void 0;if(h!==void 0&&h>e.limits.maxTransferBytes)throw c.body.cancel().catch(()=>{}),de(e.limits.maxTransferBytes);const u=[];yield e.adapter.writeFile(t,Oa(c.body,e,t,h,u),{signal:e.signal});const f=u.reduce((S,T)=>S+T.byteLength,0),g=new Uint8Array(f);let b=0;return u.forEach(S=>{g.set(S,b),b+=S.byteLength}),e.progress({stage:"done",loaded:f,total:f,path:t}),{data:{path:t,size:f,hash:yield xe(g)}}}),Lt=new Uint8Array([239,187,191]);function at(n,e){return new p(m.Conflict,e,{currentHash:n})}function mn(n,e){return d(this,null,function*(){var s;if(((s=(yield Zt(n.adapter,e)).size)!=null?s:0)>n.limits.maxWriteBytes)throw de(n.limits.maxWriteBytes,"目标文件");const i=yield G(yield n.adapter.readFile(e));return{bytes:i,hash:yield xe(i)}})}function ts(n,e,t){return d(this,null,function*(){const{hash:i}=yield mn(n,e);if(i!==t)throw at(i,"文件在确认期间已被修改,本次写入已取消。请重新读取后再修改。")})}function $a(n,e){const t=new TextEncoder().encode(n);if(!e)return t;const i=new Uint8Array(Lt.byteLength+t.byteLength);return i.set(Lt,0),i.set(t,Lt.byteLength),i}function Pa(n,e){let t=0,i=n.indexOf(e);for(;i>=0;)t++,i=n.indexOf(e,i+e.length);return t}function ri(n,e){return!e||n.includes(`\r
|
|
380
380
|
`)?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.
|
|
3
|
+
"version": "3.26.0-alpha.32",
|
|
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.
|
|
91
|
+
"@glodon-aiot/apis": "^3.26.0-alpha.32",
|
|
92
92
|
"axios": "0.24.0",
|
|
93
93
|
"buffer": "^6.0.3",
|
|
94
94
|
"dayjs": "^1.11.13",
|