@glodon-aiot/bot-client-sdk 3.26.0-alpha.13 → 3.26.0-alpha.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/dist/es/BotClient.mjs +153 -137
- package/dist/es/builtinTools/createBuiltinToolsPlugin.mjs +99 -82
- package/dist/es/builtinTools/paths.mjs +28 -22
- package/dist/es/builtinTools/platformSkills.mjs +210 -0
- package/dist/es/builtinTools/schemas.mjs +2 -2
- package/dist/es/builtinTools/tools.mjs +256 -233
- package/dist/es/localFiles/adapters/HostBridgeAdapter.mjs +19 -18
- package/dist/es/localFiles/host/protocol.mjs +1 -1
- package/dist/es/localFiles/host/sandboxClient.mjs +171 -100
- package/dist/es/localFiles/workspace/LocalWorkspace.mjs +46 -44
- package/dist/es/package.json.mjs +2 -2
- package/dist/lib/index.js +36 -36
- package/dist/src/builtinTools/command.d.ts +7 -0
- package/dist/src/builtinTools/paths.d.ts +1 -0
- package/dist/src/builtinTools/platformSkills.d.ts +67 -0
- package/dist/src/builtinTools/tools.d.ts +4 -0
- package/dist/src/localFiles/adapters/HostBridgeAdapter.d.ts +1 -1
- package/dist/src/localFiles/host/protocol.d.ts +1 -1
- package/dist/src/localFiles/host/sandboxClient.d.ts +15 -0
- package/dist/src/localFiles/workspace/LocalWorkspace.d.ts +3 -0
- package/package.json +2 -2
package/dist/lib/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
…输出已截断`;function
|
|
3
|
-
…输出已截断`;return t&&(r+=`,完整输出见 ${t}`),i&&(r+=",日志已截断"),s+r}class Bi{constructor(e=t=>new WebSocket(t)){w(this,"notice");w(this,"socket");w(this,"generation",0);w(this,"authed",!1);w(this,"seq",0);w(this,"calls",new Map);w(this,"outgoing",[]);this.openSocket=e}get ready(){const e=this.notice;return(e==null?void 0:e.state)==="ready"&&e.protocol===ye&&!!(e.url&&e.token)}unavailableMessage(){var e,t,i,s;return((e=this.notice)==null?void 0:e.state)==="starting"?"沙箱正在启动。":(t=this.notice)!=null&&t.message?this.notice.message:((i=this.notice)==null?void 0:i.state)==="exited"||((s=this.notice)==null?void 0:s.state)==="failed"?he:"沙箱没有就绪。"}apply(e){const t=this.notice;if(this.notice=e,!this.ready||!(e!=null&&e.url)||!e.token){this.failAll(S("NotAllowedError",this.unavailableMessage())),this.stop();return}(t==null?void 0:t.url)===e.url&&t.token===e.token&&this.socket&&this.socket.readyState<=1||(this.failAll(S("AbortError",he)),this.stop(),this.connect(e.url,e.token))}stat(e){return h(this,null,function*(){return this.invoke({op:"stat",path:e})})}list(e,t){return h(this,null,function*(){return this.invoke({op:"list",path:e},t)})}read(r){return h(this,arguments,function*(e,t=0,i=50*1024*1024,s){const o=this.begin({op:"read",path:e,offset:t,maxBytes:i},s),c=[];let a;for(;!a;){const f=yield this.next(o),g=Qt(f);if(g){c.push(Jt(g).payload);continue}a=f}if(this.calls.delete(o),a.ok===!1)throw S(String(a.name||"NotAllowedError"),String(a.message||"读取失败。"));const d=c.reduce((f,g)=>f+g.length,0),l=new Uint8Array(d);let u=0;return c.forEach(f=>{l.set(f,u),u+=f.length}),l})}write(e,t,i,s){return h(this,null,function*(){const r=this.begin({op:"write",path:e,size:t.length,createDirectories:i},s);let o=0;for(;o<t.length;){const a=t.subarray(o,o+Pi),d=o+a.length;this.send($i(r,o,d===t.length,a)),o=d;const u=yield this.next(r);if(u.ok===!1)throw this.calls.delete(r),S(String(u.name||"NotAllowedError"),String(u.message||"写入失败。"));if(u.op!=="ack"&&u.ok===!0){this.calls.delete(r);return}}const c=yield this.next(r);if(this.calls.delete(r),c.ok===!1)throw S(String(c.name||"NotAllowedError"),String(c.message||"写入失败。"))})}mkdir(e){return h(this,null,function*(){yield this.invoke({op:"mkdir",path:e})})}remove(e,t){return h(this,null,function*(){yield this.invoke({op:"remove",path:e,recursive:t})})}move(e,t){return h(this,null,function*(){yield this.invoke({op:"move",from:e,to:t})})}exec(e,t,i){return h(this,null,function*(){var d;const s=this.begin(v({},e),t,()=>{this.send({protocol:ye,id:s,op:"cancel"})});let r="",o="",c=!1,a=!1;for(;this.calls.has(s);){const l=yield this.next(s);if(l.op==="stdout"||l.op==="stderr"){const g=String((d=l.text)!=null?d:"");i==null||i(l.op,g),l.op==="stdout"?(r+=g,r.length>Y&&(c=!0),r=r.slice(-Y)):(o+=g,o.length>Y&&(a=!0),o=o.slice(-Y));continue}if(this.calls.delete(s),l.ok===!1)throw S(String(l.name||"NotAllowedError"),String(l.message||"命令失败。"));const u=typeof l.logPath=="string"?l.logPath:void 0,f=l.logTruncated===!0;return{exitCode:typeof l.exitCode=="number"?l.exitCode:1,timedOut:l.timedOut===!0,stdout:Zt(r,c,u,f),stderr:Zt(o,a,u,f),cwd:typeof l.cwd=="string"?l.cwd:void 0}}throw S("AbortError",he)})}invoke(e,t){const i=this.begin(e,t);return this.next(i).then(s=>{this.calls.delete(i);const r=s;if(r.ok===!1)throw S(String(r.name||"NotAllowedError"),String(r.message||"请求失败。"));return r})}begin(e,t,i){if(!this.ready)throw S("NotAllowedError",this.unavailableMessage());if(t!=null&&t.aborted)throw S("AbortError");const s=`sbx-${++this.seq}`;let r=()=>{};const o={messages:[],waiters:[],reject:a=>r(a)};this.calls.set(s,o);const c=()=>{i==null||i(),o.reject(S("AbortError"))};return t==null||t.addEventListener("abort",c,{once:!0}),r=a=>{t==null||t.removeEventListener("abort",c),this.calls.delete(s);const d=o.waiters.shift();d&&d(Promise.reject(a))},this.send(v({protocol:ye,id:s},e)),s}next(e){const t=this.calls.get(e);if(!t)return Promise.reject(S("AbortError",he));const i=t.messages.shift();return i!==void 0?Promise.resolve(i):new Promise((s,r)=>{t.waiters.push(s),t.reject=o=>{this.calls.delete(e),r(o)}})}send(e){var i;const t=()=>{var r;const s=e instanceof Uint8Array?e:JSON.stringify(e);(r=this.socket)==null||r.send(s)};this.authed&&((i=this.socket)==null?void 0:i.readyState)===1?t():this.outgoing.push(t)}connect(e,t){const i=++this.generation,s=this.openSocket(e);this.socket=s,this.authed=!1,s.binaryType="arraybuffer",s.onopen=()=>{i===this.generation&&s.send(JSON.stringify({protocol:ye,op:"auth",token:t}))},s.onmessage=r=>{i===this.generation&&this.onFrame(r.data)},s.onclose=()=>{i===this.generation&&(this.authed=!1,this.failAll(S("AbortError",he)))},s.onerror=()=>{}}onFrame(e){const t=Qt(e);if(t){const s=Jt(t);this.push(s.id,t);return}let i;try{i=JSON.parse(String(e))}catch(s){return}if(i.op==="auth"){if(i.ok===!0){this.authed=!0;const s=this.outgoing;this.outgoing=[],s.forEach(r=>r())}return}if(i.op==="bye"){this.failAll(S("AbortError",he)),this.stop();return}typeof i.id=="string"&&this.push(i.id,i)}push(e,t){const i=this.calls.get(e);if(!i)return;const s=i.waiters.shift();s?s(t):i.messages.push(t)}failAll(e){for(const t of this.calls.values())t.reject(e);this.calls.clear()}stop(){this.generation+=1,this.authed=!1,this.outgoing=[];const e=this.socket;this.socket=void 0;try{e==null||e.close()}catch(t){}}}function en(n,e){const t=n&&typeof n=="object"?n:{},i=t.kind==="directory"?"directory":"file",s={name:typeof t.name=="string"&&t.name?t.name:e,kind:i};return i==="file"&&typeof t.size=="number"&&(s.size=t.size),typeof t.lastModified=="number"&&(s.lastModified=t.lastModified),s}class Wn{constructor(e,t="",i=new Bi){w(this,"displayName");w(this,"capabilities",new Set);w(this,"sandboxVersion");w(this,"sandboxProtocol");w(this,"sandbox");this.displayName=t,this.sandbox=i}setCapabilities(e,t={}){const i=Array.isArray(e)?e.filter(s=>typeof s=="string"):[];this.capabilities=new Set(i),this.sandboxVersion=typeof t.version=="string"?t.version:void 0}applySandbox(e){this.sandboxProtocol=e==null?void 0:e.protocol,this.sandbox.apply(e)}get canExec(){return this.sandbox.ready}get protocolMismatch(){return this.sandboxProtocol!==void 0&&this.sandboxProtocol!==ye}unavailableMessage(){return this.sandbox.unavailableMessage()}stat(e){return h(this,null,function*(){const t=yield this.sandbox.stat(e);return en(t.entry,e.split("/").pop()||this.displayName)})}listEntries(e,t){return h(this,null,function*(){const i=yield this.sandbox.list(e,t);return(Array.isArray(i.entries)?i.entries:[]).map(r=>en(r,""))})}readFile(e,t){return h(this,null,function*(){var s;const i=yield this.sandbox.read(e,(s=t==null?void 0:t.offset)!=null?s:0,t==null?void 0:t.maxBytes);return new Blob([i])})}createDirectory(e){return h(this,null,function*(){yield this.sandbox.mkdir(e)})}remove(i){return h(this,arguments,function*(e,t={}){yield this.sandbox.remove(e,t.recursive===!0)})}move(e,t){return h(this,null,function*(){yield this.sandbox.move(e,t)})}exec(e){return h(this,null,function*(){const t=yield this.sandbox.exec({op:"exec",cwd:e.cwd,command:e.command,argv:e.argv,timeoutMs:e.timeoutMs},e.signal,e.onOutput);if(t.timedOut)throw S("AbortError","命令运行超时。");return t})}writeFile(s,r){return h(this,arguments,function*(e,t,i={}){if(typeof t=="string"){yield this.sandbox.write(e,new TextEncoder().encode(t),i.createDirectories===!0,i.signal);return}if(t instanceof Uint8Array){yield this.sandbox.write(e,t,i.createDirectories===!0,i.signal);return}const o=[];try{for(var l=W(Et(t)),u,f,g;u=!(f=yield l.next()).done;u=!1){const _=f.value;O(i.signal),o.push(_)}}catch(f){g=[f]}finally{try{u&&(f=l.return)&&(yield f.call(l))}finally{if(g)throw g[0]}}const c=o.reduce((_,y)=>_+y.byteLength,0),a=new Uint8Array(c);let d=0;o.forEach(_=>{a.set(_,d),d+=_.byteLength}),yield this.sandbox.write(e,a,i.createDirectories===!0,i.signal)})}}function B(n,e){throw new m(p.BadRequest,n?`参数 ${n} ${e}`:`参数${e}`)}function ji(n,e){return typeof n!="string"?n:(e.type==="integer"||e.type==="number")&&/^-?\d+(\.\d+)?$/.test(n.trim())?Number(n):e.type==="boolean"&&(n==="true"||n==="false")?n==="true":n}function ot(n,e,t){switch(n=ji(n,e),e.type){case"string":typeof n!="string"&&B(t,"必须是字符串。"),e.minLength!==void 0&&n.length<e.minLength&&B(t,"不能为空。"),e.maxLength!==void 0&&n.length>e.maxLength&&B(t,`不能超过 ${e.maxLength} 字。`);break;case"integer":(typeof n!="number"||!Number.isInteger(n))&&B(t,"必须是整数。");break;case"number":(typeof n!="number"||!Number.isFinite(n))&&B(t,"必须是数字。");break;case"boolean":typeof n!="boolean"&&B(t,"必须是布尔值。");break;case"array":if(Array.isArray(n)||B(t,"必须是数组。"),e.minItems!==void 0&&n.length<e.minItems&&B(t,"不能为空。"),e.items){const i=e.items;return n.map((s,r)=>ot(s,i,`${t}[${r}]`))}break;case"object":return zn(n,e,t)}return e.enum&&!e.enum.includes(n)&&B(t,`必须是 ${e.enum.join("、")} 之一。`),typeof n=="number"&&(e.minimum!==void 0&&n<e.minimum&&B(t,`不能小于 ${e.minimum}。`),e.maximum!==void 0&&n>e.maximum&&B(t,`不能大于 ${e.maximum}。`)),n}function zn(n,e,t){var r,o;(!n||typeof n!="object"||Array.isArray(n))&&B(t,"必须是对象。");const i=n,s={};for(const c of(r=e.required)!=null?r:[])(i[c]===void 0||i[c]===null)&&B(t?`${t}.${c}`:c,"是必填项。");for(const[c,a]of Object.entries((o=e.properties)!=null?o:{})){if(i[c]===void 0||i[c]===null)continue;const d=t?`${t}.${c}`:c;s[c]=a.oneOf?(ot(i[c],E(v({},a),{oneOf:void 0}),d),i[c]):ot(i[c],a,d)}return s}function Vn(n,e){return zn(n,e,"")}const at=["shell","read_file","write_file","append_file","run_file","edit_file","grep","find","load_skill","read_skill_resource","run_skill_script"],ct=81920,We=81920,Ui=2e4,Gn=".",F="/workspace",Hi=[".py",".sh",".js"],qi=["input","output","uploads","tmp"],It="不要使用 input、output、uploads、tmp,也不要新建这些目录。请把文件直接放在工作区已有位置或根目录。",Wi=/(?:^|[\s'"=;|&<>`:])\/?(?:input|output|uploads|tmp)(?=\/|[\s'"=;|&<>`:]|$)/;function ze(n){return Wi.test(n)}function xt(n){const e=n.split("/")[0];return qi.includes(e)}function dt(n){throw new m(p.Forbidden,n,{reason:"path_outside_workspace"})}function Xn(n){if(typeof n!="string"||n.length===0)throw new m(p.BadRequest,"path 必须是工作区内绝对路径。");(n.includes("\0")||n.includes("\\"))&&dt("路径不能包含反斜杠。");const e=n.normalize("NFC").trim();if(!e.startsWith("/"))throw new m(p.BadRequest,"path 必须是工作区内绝对路径,例如 /说明.md。");const t=e.split("/").filter(i=>i.length>0);if(t.some(i=>i==="."||i==="..")&&dt("路径不能包含 . 或 .. 。"),t.length>0&&xt(t[0]))throw new m(p.BadRequest,It);return t.join("/")}function Se(n){return Xn(n)}function zi(n){return Xn(n)}function At(n){return n?`/${n}`:"/"}function Vi(n){if(n===".")return!0;if(!n||n.startsWith("/")||n.includes("\\")||n.includes("\0"))return!1;const e=n.split("/").filter(t=>t.length>0);return e.length>0&&e.every(t=>t!=="."&&t!=="..")&&!xt(e[0])}function Tt(n,e){if(!n||/[\\/\0]/.test(n)||n==="."||n==="..")throw new m(p.BadRequest,"skill_name 必须是单个技能目录名。");if(!e||e.startsWith("/")||e.includes("\\")||e.includes("\0"))throw new m(p.BadRequest,"资源路径必须是技能目录内的相对路径。");const t=e.split("/").filter(i=>i.length>0);return(t.length===0||t.some(i=>i==="."||i===".."))&&dt("资源路径不能跳出技能目录。"),`skills/${n}/${t.join("/")}`}const Yn="https://cv-cdn.obs.cn-north-4.myhuaweicloud.com/glodon/libs/",Gi="3.6.0",Xi=`${Yn}just-bash/${Gi}/just-bash.mjs`,Yi="314.0.7",Ki=`${Yn}pyodide/${Yi}/`,Kn=["numpy","pandas","matplotlib","pillow","lxml"],Je=new Map;function Ji(n){return import(n)}function Qi(n){let e=Je.get(n);return e||(e=Ji(n).catch(t=>{throw Je.delete(n),t}),Je.set(n,e)),e}const tn=new Map;function Zi(n){return/[\\^$.|+()[\]{}]/.test(n)?`\\${n}`:n}function es(n,e=!1){const t=`${e?"s":"i"}:${n}`,i=tn.get(t);if(i)return i;let s="";for(let o=0;o<n.length;o++){const c=n[o];c==="*"?n[o+1]==="*"?(o++,n[o+1]==="/"?(o++,s+="(?:.*/)?"):s+=".*"):s+="[^/]*":c==="?"?s+="[^/]":s+=Zi(c)}const r=new RegExp(`^${s}$`,e?"":"i");return tn.set(t,r),r}function Ve(n,e,t=!1){return es(n,t).test(e)}function kt(n){const e=n.lastIndexOf("/");return e<0?n:n.slice(e+1)}const Jn=Object.freeze([{id:"env-files",pattern:".env*",reason:"环境变量文件可能包含密钥",source:"sdk-baseline"},{id:"pem",pattern:"*.pem",reason:"证书或密钥文件",source:"sdk-baseline"},{id:"key",pattern:"*.key",reason:"密钥文件",source:"sdk-baseline"},{id:"p12",pattern:"*.p12",reason:"证书文件",source:"sdk-baseline"},{id:"pfx",pattern:"*.pfx",reason:"证书文件",source:"sdk-baseline"},{id:"id-rsa",pattern:"id_rsa*",reason:"SSH 私钥",source:"sdk-baseline"},{id:"id-ed25519",pattern:"id_ed25519*",reason:"SSH 私钥",source:"sdk-baseline"},{id:"id-ecdsa",pattern:"id_ecdsa*",reason:"SSH 私钥",source:"sdk-baseline"},{id:"credentials",pattern:".credentials",reason:"凭据文件",source:"sdk-baseline"},{id:"npmrc",pattern:".npmrc",reason:"可能包含 registry token",source:"sdk-baseline"},{id:"pypirc",pattern:".pypirc",reason:"可能包含仓库凭据",source:"sdk-baseline"},{id:"aws-credentials",pattern:"**/.aws/credentials",match:"path",reason:"云服务凭据",source:"sdk-baseline"},{id:"ssh-dir",pattern:"**/.ssh/**",match:"path",reason:"SSH 配置与密钥",source:"sdk-baseline"}]),ts="该文件被列为敏感文件,不允许访问";class Qn{constructor(e=[]){w(this,"rules");const t=e.filter(i=>i&&typeof i.pattern=="string"&&i.pattern).map(i=>E(v({},i),{id:String(i.id||i.pattern),source:i.source==="enterprise"?"enterprise":"product"}));this.rules=[...Jn,...t]}match(e,t){if(!e)return null;const i=kt(e);for(const s of this.rules){if(s.operations&&!s.operations.includes(t))continue;const r=s.match==="path"?e:i;if(Ve(s.pattern,r))return s}return null}isSensitive(e){return["read","write","search"].some(t=>this.match(e,t)!==null)}static reasonOf(e){return`${e.reason||ts},已拒绝访问。`}}function Ie(n,e,t){const i=n.sensitive.match(e,t);if(i)throw new m(p.Forbidden,Qn.reasonOf(i),{reason:"sensitive_file",ruleId:i.id})}function He(n,e){return h(this,null,function*(){try{return yield n.stat(e)}catch(t){if(Ye(t).code===p.NotFound)return null;throw t}})}function Lt(n,e){return h(this,null,function*(){const t=yield n.stat(e);if(t.kind!=="file")throw new m(p.BadRequest,"目标是目录,不是文件。");return t})}function Ee(n){return h(this,null,function*(){const e=yield crypto.subtle.digest("SHA-256",n);return`sha256:${Array.from(new Uint8Array(e)).map(i=>i.toString(16).padStart(2,"0")).join("")}`})}function q(n){return h(this,null,function*(){return new Uint8Array(yield n.arrayBuffer())})}function ae(n){const e=Math.min(n.byteLength,_t);for(let t=0;t<e;t++)if(n[t]===0)return!0;return!1}function ns(n){return h(this,null,function*(){return ae(yield q(n.slice(0,_t)))})}function Zn(n){return n[0]===239&&n[1]===187&&n[2]===191}function is(n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch(e){throw new m(p.BadRequest,"文件不是 UTF-8 编码,暂不支持修改。")}}function Rt(n){return new TextEncoder().encode(n).byteLength}function ei(){return new Promise(n=>setTimeout(n,0))}function ss(n){return n>=1024*1024?`${(n/1024/1024).toFixed(1)} MB`:n>=1024?`${(n/1024).toFixed(1)} KB`:`${n} B`}function oe(n,e="文件"){return new m(p.TooLarge,`${e}超过大小上限 ${ss(n)}。`)}const rs=`# 在 Pyodide 里按 python3 命令行的语义运行代码。由 pyodideWorker.js 加载,最后一个表达式 run 交给 JS 调用。
|
|
1
|
+
"use strict";var Ci=Object.defineProperty,Fi=Object.defineProperties;var Ni=Object.getOwnPropertyDescriptors;var Oe=Object.getOwnPropertySymbols;var Xt=Object.prototype.hasOwnProperty,Yt=Object.prototype.propertyIsEnumerable;var xe=(n,e)=>{if(e=Symbol[n])return e;throw Error("Symbol."+n+" is not defined")};var Qe=(n,e,t)=>e in n?Ci(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,v=(n,e)=>{for(var t in e||(e={}))Xt.call(e,t)&&Qe(n,t,e[t]);if(Oe)for(var t of Oe(e))Yt.call(e,t)&&Qe(n,t,e[t]);return n},E=(n,e)=>Fi(n,Ni(e));var Kt=(n,e)=>{var t={};for(var i in n)Xt.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&Oe)for(var i of Oe(n))e.indexOf(i)<0&&Yt.call(n,i)&&(t[i]=n[i]);return t};var y=(n,e,t)=>(Qe(n,typeof e!="symbol"?e+"":e,t),t);var h=(n,e,t)=>new Promise((i,s)=>{var r=a=>{try{c(t.next(a))}catch(l){s(l)}},o=a=>{try{c(t.throw(a))}catch(l){s(l)}},c=a=>a.done?i(a.value):Promise.resolve(a.value).then(r,o);c((t=t.apply(n,e)).next())}),te=function(n,e){this[0]=n,this[1]=e},de=(n,e,t)=>{var i=(o,c,a,l)=>{try{var d=t[o](c),u=(c=d.value)instanceof te,f=d.done;Promise.resolve(u?c[0]:c).then(g=>u?i(o==="return"?o:"next",c[1]?{done:g.done,value:g.value}:g,a,l):a({value:g,done:f})).catch(g=>i("throw",g,a,l))}catch(g){l(g)}},s=o=>r[o]=c=>new Promise((a,l)=>i(o,c,a,l)),r={};return t=t.apply(n,e),r[Symbol.asyncIterator]=()=>r,s("next"),s("throw"),s("return"),r},Jt=n=>{var e=n[xe("asyncIterator")],t=!1,i,s={};return e==null?(e=n[xe("iterator")](),i=r=>s[r]=o=>e[r](o)):(e=e.call(n),i=r=>s[r]=o=>{if(t){if(t=!1,r==="throw")throw o;return o}return t=!0,{done:!1,value:new te(new Promise(c=>{var a=e[r](o);if(!(a instanceof Object))throw TypeError("Object expected");c(a)}),1)}}),s[xe("iterator")]=()=>s,i("next"),"throw"in e?i("throw"):s.throw=r=>{throw r},"return"in e&&i("return"),s},W=(n,e,t)=>(e=n[xe("asyncIterator")])?e.call(n):(n=n[xe("iterator")](),e={},t=(i,s)=>(s=n[i])&&(e[i]=r=>new Promise((o,c,a)=>(r=s.call(n,r),a=r.done,Promise.resolve(r.value).then(l=>o({value:l,done:a}),c)))),t("next"),t("return"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _e=require("uuid"),Oi=require("js-base64"),$i=require("axios"),x=require("@glodon-aiot/apis"),Di=require("socket.io-client"),Et=require("dayjs"),re=class re{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!re.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!re.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!re.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!re.debug||console.warn(this.prefix,...e)}};y(re,"debug",!1);let U=re;const It=["list_directory","read_file","stat_file","search_files","search_text","apply_patch","write_file","upload_file","download_file"],Ae="builtin_tools",Fn={dev:Ae,test:Ae,prod:Ae,local:Ae},Nn=Fn,be="current-workspace",On=1024,Le=1024*1024,$n=50,je=Object.freeze({maxReadBytes:1*Le,maxWriteBytes:5*Le,maxSearchResults:200,maxConcurrentRequests:4,maxTransferBytes:$n*Le,toolTimeoutMs:3e4,searchTimeoutMs:6e4,transferTimeoutMs:10*6e4,approvalTimeoutMs:5*6e4}),Dn=200,Pn=1e3,Bn=8,kt=16,jn=2e3,Un=1*Le,Ue=500,Hn=3,xt=8*On,qn=Object.freeze(["glodon.com"]),Wn=Object.freeze([".git","node_modules",".svn",".idea",".vscode"]),zn=Object.freeze(["~$*",".~lock*","*.tmp"]),Pi=["apply_patch","write_file","upload_file","download_file"],Vn=["search_files","search_text"],Gn=["upload_file","download_file"];var p=(n=>(n[n.Ok=0]="Ok",n[n.BadRequest=400]="BadRequest",n[n.Forbidden=403]="Forbidden",n[n.NotFound=404]="NotFound",n[n.Timeout=408]="Timeout",n[n.Conflict=409]="Conflict",n[n.TooLarge=413]="TooLarge",n[n.TooManyRequests=429]="TooManyRequests",n[n.Cancelled=499]="Cancelled",n[n.Internal=500]="Internal",n[n.NotImplemented=501]="NotImplemented",n))(p||{});class m extends Error{constructor(t,i,s){super(i);y(this,"code");y(this,"data");this.name="ToolError",this.code=t,this.data=s}}const Bi="尚未授权工作文件夹,请先在助手中选择或恢复访问工作文件夹。";function At(){return new m(403,Bi,{reason:"workspace_not_granted"})}function j(){return new m(499,"操作已取消。")}function N(n){if(n!=null&&n.aborted)throw j()}function Ke(n){if(n instanceof m)return n;switch(n&&typeof n=="object"&&"name"in n?String(n.name):""){case"NotFoundError":return new m(404,"文件或目录不存在。");case"TypeMismatchError":return new m(400,"路径类型不匹配:目标是目录而不是文件,或路径中的某一段不是目录。");case"NotAllowedError":case"SecurityError":return At();case"AbortError":return j();case"NoModificationAllowedError":case"InvalidModificationError":case"InvalidStateError":return new m(403,"文件当前不可写,可能正被其他程序占用或为只读。");case"QuotaExceededError":return new m(413,"磁盘空间不足或超出写入配额。");default:return new m(500,"本地文件操作失败,请稍后重试。")}}const Y=16e3,ji=`
|
|
2
|
+
…输出已截断`;function Qt(n){if(n.length<=Y)return n;let e=Y;const t=n.charCodeAt(e-1);return t>=55296&&t<=56319&&(e-=1),n.slice(0,e)+ji}function ht(n){return{exec(t){return h(this,null,function*(){const i=yield n.exec(t);return E(v({},i),{stdout:Qt(i.stdout),stderr:Qt(i.stderr)})})}}}function Xn(n,e){return e===n||e.startsWith(`${n}/`)}function S(n,e=n){return new DOMException(e,n)}function Tt(n){return de(this,null,function*(){typeof n=="string"?yield new TextEncoder().encode(n):n instanceof Uint8Array?yield n:yield*Jt(n)})}const Rt="glodon-workspace",qe="__glodonHostBridge",ye=1;function Ui(n){let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch(i){return}if(!e||typeof e!="object")return;const t=e;if(t.channel===Rt)return t}function Zt(n){if(!n||typeof n!="object")return;const e=n;if(!(typeof e.postMessage!="function"||typeof e.addEventListener!="function"||typeof e.removeEventListener!="function"))return e}function Hi(n){const e=globalThis;n?e[qe]=n:delete e[qe]}function qi(){var e;const n=Zt(globalThis[qe]);return n||Zt((e=globalThis.chrome)==null?void 0:e.webview)}const en=1024*1024;function tn(n,e,t,i){const s=new TextEncoder().encode(n),r=new Uint8Array(4+s.length+8),o=new DataView(r.buffer);o.setUint8(0,1),o.setUint8(1,t?1:0),o.setUint16(2,s.length),r.set(s,4),o.setBigUint64(4+s.length,BigInt(e));const c=new Uint8Array(r.length+i.length);return c.set(r,0),c.set(i,r.length),c}function Ze(n){const e=new DataView(n.buffer,n.byteOffset,n.byteLength),i=4+e.getUint16(2),s=new TextDecoder().decode(n.subarray(4,i)),r=Number(e.getBigUint64(i)),o=(e.getUint8(1)&1)===1;return{id:s,offset:r,eof:o,payload:n.subarray(i+8)}}const he="沙箱已退出。";function et(n){if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n)}function nn(n,e,t,i){const s=n.length>Y?n.slice(n.length-Y):n;if(!e&&!t&&!i&&n.length<=Y)return s;let r=`
|
|
3
|
+
…输出已截断`;return t&&(r+=`,完整输出见 ${t}`),i&&(r+=",日志已截断"),s+r}class Wi{constructor(e=t=>new WebSocket(t)){y(this,"notice");y(this,"socket");y(this,"generation",0);y(this,"authed",!1);y(this,"seq",0);y(this,"calls",new Map);y(this,"outgoing",[]);this.openSocket=e}get ready(){const e=this.notice;return(e==null?void 0:e.state)==="ready"&&e.protocol===ye&&!!(e.url&&e.token)}unavailableMessage(){var e,t,i,s;return((e=this.notice)==null?void 0:e.state)==="starting"?"沙箱正在启动。":(t=this.notice)!=null&&t.message?this.notice.message:((i=this.notice)==null?void 0:i.state)==="exited"||((s=this.notice)==null?void 0:s.state)==="failed"?he:"沙箱没有就绪。"}apply(e){const t=this.notice;if(this.notice=e,!this.ready||!(e!=null&&e.url)||!e.token){this.failAll(S("NotAllowedError",this.unavailableMessage())),this.stop();return}(t==null?void 0:t.url)===e.url&&t.token===e.token&&this.socket&&this.socket.readyState<=1||(this.failAll(S("AbortError",he)),this.stop(),this.connect(e.url,e.token))}stat(e){return h(this,null,function*(){return this.invoke({op:"stat",path:e})})}list(e,t){return h(this,null,function*(){return this.invoke({op:"list",path:e},t)})}read(r){return h(this,arguments,function*(e,t=0,i=50*1024*1024,s){const o=this.begin({op:"read",path:e,offset:t,maxBytes:i},s),c=[];let a;for(;!a;){const f=yield this.next(o),g=et(f);if(g){c.push(Ze(g).payload);continue}a=f}if(this.calls.delete(o),a.ok===!1)throw S(String(a.name||"NotAllowedError"),String(a.message||"读取失败。"));const l=c.reduce((f,g)=>f+g.length,0),d=new Uint8Array(l);let u=0;return c.forEach(f=>{d.set(f,u),u+=f.length}),d})}write(e,t,i,s){return h(this,null,function*(){const r=this.begin({op:"write",path:e,size:t.length,createDirectories:i},s);let o=0;for(;o<t.length;){const a=t.subarray(o,o+en),l=o+a.length;this.send(tn(r,o,l===t.length,a)),o=l;const u=yield this.next(r);if(u.ok===!1)throw this.calls.delete(r),S(String(u.name||"NotAllowedError"),String(u.message||"写入失败。"));if(u.op!=="ack"&&u.ok===!0){this.calls.delete(r);return}}const c=yield this.next(r);if(this.calls.delete(r),c.ok===!1)throw S(String(c.name||"NotAllowedError"),String(c.message||"写入失败。"))})}skillStatus(e,t){return h(this,null,function*(){const i=yield this.invoke({op:"skillStatus",applicationId:e},t);return Array.isArray(i.skills)?i.skills:[]})}skillRead(e,t,i,s,r){return h(this,null,function*(){const o=this.begin({op:"skillRead",applicationId:e,skillId:t,version:i,path:s},r),c=[];let a;for(;!a;){const f=yield this.next(o),g=et(f);if(g){c.push(Ze(g).payload);continue}a=f}if(this.calls.delete(o),a.ok===!1)throw S(String(a.name||"NotAllowedError"),String(a.message||"读取失败。"));const l=c.reduce((f,g)=>f+g.length,0),d=new Uint8Array(l);let u=0;return c.forEach(f=>{d.set(f,u),u+=f.length}),d})}installSkill(e,t,i){return h(this,null,function*(){const s=this.begin(E(v({op:"installSkill"},e),{size:t.length}),i);let r=0;for(;r<t.length;){const c=t.subarray(r,r+en),a=r+c.length;this.send(tn(s,r,a===t.length,c)),r=a;const l=yield this.next(s);if(l.ok===!1)throw this.calls.delete(s),S(String(l.name||"NotAllowedError"),String(l.message||"安装失败。"));if(l.op!=="ack"&&l.ok===!0){this.calls.delete(s);return}}const o=yield this.next(s);if(this.calls.delete(s),o.ok===!1)throw S(String(o.name||"NotAllowedError"),String(o.message||"安装失败。"))})}skillPrune(e,t,i,s){return h(this,null,function*(){yield this.invoke({op:"skillPrune",applicationId:e,keep:t,busy:i},s)})}mkdir(e){return h(this,null,function*(){yield this.invoke({op:"mkdir",path:e})})}remove(e,t){return h(this,null,function*(){yield this.invoke({op:"remove",path:e,recursive:t})})}move(e,t){return h(this,null,function*(){yield this.invoke({op:"move",from:e,to:t})})}exec(e,t,i){return h(this,null,function*(){var l;const s=this.begin(v({},e),t,()=>{this.send({protocol:ye,id:s,op:"cancel"})});let r="",o="",c=!1,a=!1;for(;this.calls.has(s);){const d=yield this.next(s);if(d.op==="stdout"||d.op==="stderr"){const g=String((l=d.text)!=null?l:"");i==null||i(d.op,g),d.op==="stdout"?(r+=g,r.length>Y&&(c=!0),r=r.slice(-Y)):(o+=g,o.length>Y&&(a=!0),o=o.slice(-Y));continue}if(this.calls.delete(s),d.ok===!1)throw S(String(d.name||"NotAllowedError"),String(d.message||"命令失败。"));const u=typeof d.logPath=="string"?d.logPath:void 0,f=d.logTruncated===!0;return{exitCode:typeof d.exitCode=="number"?d.exitCode:1,timedOut:d.timedOut===!0,stdout:nn(r,c,u,f),stderr:nn(o,a,u,f),cwd:typeof d.cwd=="string"?d.cwd:void 0}}throw S("AbortError",he)})}invoke(e,t){const i=this.begin(e,t);return this.next(i).then(s=>{this.calls.delete(i);const r=s;if(r.ok===!1)throw S(String(r.name||"NotAllowedError"),String(r.message||"请求失败。"));return r})}begin(e,t,i){if(!this.ready)throw S("NotAllowedError",this.unavailableMessage());if(t!=null&&t.aborted)throw S("AbortError");const s=`sbx-${++this.seq}`;let r=()=>{};const o={messages:[],waiters:[],reject:a=>r(a)};this.calls.set(s,o);const c=()=>{i==null||i(),o.reject(S("AbortError"))};return t==null||t.addEventListener("abort",c,{once:!0}),r=a=>{t==null||t.removeEventListener("abort",c),this.calls.delete(s);const l=o.waiters.shift();l&&l(Promise.reject(a))},this.send(v({protocol:ye,id:s},e)),s}next(e){const t=this.calls.get(e);if(!t)return Promise.reject(S("AbortError",he));const i=t.messages.shift();return i!==void 0?Promise.resolve(i):new Promise((s,r)=>{t.waiters.push(s),t.reject=o=>{this.calls.delete(e),r(o)}})}send(e){var i;const t=()=>{var r;const s=e instanceof Uint8Array?e:JSON.stringify(e);(r=this.socket)==null||r.send(s)};this.authed&&((i=this.socket)==null?void 0:i.readyState)===1?t():this.outgoing.push(t)}connect(e,t){const i=++this.generation,s=this.openSocket(e);this.socket=s,this.authed=!1,s.binaryType="arraybuffer",s.onopen=()=>{i===this.generation&&s.send(JSON.stringify({protocol:ye,op:"auth",token:t}))},s.onmessage=r=>{i===this.generation&&this.onFrame(r.data)},s.onclose=()=>{i===this.generation&&(this.authed=!1,this.failAll(S("AbortError",he)))},s.onerror=()=>{}}onFrame(e){const t=et(e);if(t){const s=Ze(t);this.push(s.id,t);return}let i;try{i=JSON.parse(String(e))}catch(s){return}if(i.op==="auth"){if(i.ok===!0){this.authed=!0;const s=this.outgoing;this.outgoing=[],s.forEach(r=>r())}return}if(i.op==="bye"){this.failAll(S("AbortError",he)),this.stop();return}typeof i.id=="string"&&this.push(i.id,i)}push(e,t){const i=this.calls.get(e);if(!i)return;const s=i.waiters.shift();s?s(t):i.messages.push(t)}failAll(e){for(const t of this.calls.values())t.reject(e);this.calls.clear()}stop(){this.generation+=1,this.authed=!1,this.outgoing=[];const e=this.socket;this.socket=void 0;try{e==null||e.close()}catch(t){}}}function sn(n,e){const t=n&&typeof n=="object"?n:{},i=t.kind==="directory"?"directory":"file",s={name:typeof t.name=="string"&&t.name?t.name:e,kind:i};return i==="file"&&typeof t.size=="number"&&(s.size=t.size),typeof t.lastModified=="number"&&(s.lastModified=t.lastModified),s}class Je{constructor(e,t="",i=new Wi){y(this,"displayName");y(this,"capabilities",new Set);y(this,"sandboxVersion");y(this,"sandboxProtocol");y(this,"sandbox");this.displayName=t,this.sandbox=i}setCapabilities(e,t={}){const i=Array.isArray(e)?e.filter(s=>typeof s=="string"):[];this.capabilities=new Set(i),this.sandboxVersion=typeof t.version=="string"?t.version:void 0}applySandbox(e){this.sandboxProtocol=e==null?void 0:e.protocol,this.sandbox.apply(e)}get canExec(){return this.sandbox.ready}get protocolMismatch(){return this.sandboxProtocol!==void 0&&this.sandboxProtocol!==ye}unavailableMessage(){return this.sandbox.unavailableMessage()}stat(e){return h(this,null,function*(){const t=yield this.sandbox.stat(e);return sn(t.entry,e.split("/").pop()||this.displayName)})}listEntries(e,t){return h(this,null,function*(){const i=yield this.sandbox.list(e,t);return(Array.isArray(i.entries)?i.entries:[]).map(r=>sn(r,""))})}readFile(e,t){return h(this,null,function*(){var s;const i=yield this.sandbox.read(e,(s=t==null?void 0:t.offset)!=null?s:0,t==null?void 0:t.maxBytes);return new Blob([i])})}createDirectory(e){return h(this,null,function*(){yield this.sandbox.mkdir(e)})}remove(i){return h(this,arguments,function*(e,t={}){yield this.sandbox.remove(e,t.recursive===!0)})}move(e,t){return h(this,null,function*(){yield this.sandbox.move(e,t)})}exec(e){return h(this,null,function*(){const t=yield this.sandbox.exec({op:"exec",cwd:e.cwd,command:e.command,argv:e.argv,timeoutMs:e.timeoutMs,skill:e.skill},e.signal,e.onOutput);if(t.timedOut)throw S("AbortError","命令运行超时。");return t})}writeFile(s,r){return h(this,arguments,function*(e,t,i={}){if(typeof t=="string"){yield this.sandbox.write(e,new TextEncoder().encode(t),i.createDirectories===!0,i.signal);return}if(t instanceof Uint8Array){yield this.sandbox.write(e,t,i.createDirectories===!0,i.signal);return}const o=[];try{for(var d=W(Tt(t)),u,f,g;u=!(f=yield d.next()).done;u=!1){const _=f.value;N(i.signal),o.push(_)}}catch(f){g=[f]}finally{try{u&&(f=d.return)&&(yield f.call(d))}finally{if(g)throw g[0]}}const c=o.reduce((_,w)=>_+w.byteLength,0),a=new Uint8Array(c);let l=0;o.forEach(_=>{a.set(_,l),l+=_.byteLength}),yield this.sandbox.write(e,a,i.createDirectories===!0,i.signal)})}}function B(n,e){throw new m(p.BadRequest,n?`参数 ${n} ${e}`:`参数${e}`)}function zi(n,e){return typeof n!="string"?n:(e.type==="integer"||e.type==="number")&&/^-?\d+(\.\d+)?$/.test(n.trim())?Number(n):e.type==="boolean"&&(n==="true"||n==="false")?n==="true":n}function ut(n,e,t){switch(n=zi(n,e),e.type){case"string":typeof n!="string"&&B(t,"必须是字符串。"),e.minLength!==void 0&&n.length<e.minLength&&B(t,"不能为空。"),e.maxLength!==void 0&&n.length>e.maxLength&&B(t,`不能超过 ${e.maxLength} 字。`);break;case"integer":(typeof n!="number"||!Number.isInteger(n))&&B(t,"必须是整数。");break;case"number":(typeof n!="number"||!Number.isFinite(n))&&B(t,"必须是数字。");break;case"boolean":typeof n!="boolean"&&B(t,"必须是布尔值。");break;case"array":if(Array.isArray(n)||B(t,"必须是数组。"),e.minItems!==void 0&&n.length<e.minItems&&B(t,"不能为空。"),e.items){const i=e.items;return n.map((s,r)=>ut(s,i,`${t}[${r}]`))}break;case"object":return Yn(n,e,t)}return e.enum&&!e.enum.includes(n)&&B(t,`必须是 ${e.enum.join("、")} 之一。`),typeof n=="number"&&(e.minimum!==void 0&&n<e.minimum&&B(t,`不能小于 ${e.minimum}。`),e.maximum!==void 0&&n>e.maximum&&B(t,`不能大于 ${e.maximum}。`)),n}function Yn(n,e,t){var r,o;(!n||typeof n!="object"||Array.isArray(n))&&B(t,"必须是对象。");const i=n,s={};for(const c of(r=e.required)!=null?r:[])(i[c]===void 0||i[c]===null)&&B(t?`${t}.${c}`:c,"是必填项。");for(const[c,a]of Object.entries((o=e.properties)!=null?o:{})){if(i[c]===void 0||i[c]===null)continue;const l=t?`${t}.${c}`:c;s[c]=a.oneOf?(ut(i[c],E(v({},a),{oneOf:void 0}),l),i[c]):ut(i[c],a,l)}return s}function Kn(n,e){return Yn(n,e,"")}const ft=["shell","read_file","write_file","append_file","run_file","edit_file","grep","find","load_skill","read_skill_resource","run_skill_script"],pt=81920,We=81920,Vi=2e4,Lt=".",F="/workspace",Gi=[".py",".sh",".js"],Xi=["input","output","uploads","tmp"],Mt="不要使用 input、output、uploads、tmp,也不要新建这些目录。请把文件直接放在工作区已有位置或根目录。",Yi=/(?:^|[\s'"=;|&<>`:])\/?(?:input|output|uploads|tmp)(?=\/|[\s'"=;|&<>`:]|$)/,Ki=/(?:^|[\s'"=;|&<>`:])\/?skills(?=\/|[\s'"=;|&<>`:]|$)/;function rn(n){return Ki.test(n)}function ze(n){return Yi.test(n)}function Ct(n){const e=n.split("/")[0];return Xi.includes(e)}function mt(n){throw new m(p.Forbidden,n,{reason:"path_outside_workspace"})}function Jn(n){if(typeof n!="string"||n.length===0)throw new m(p.BadRequest,"path 必须是工作区内绝对路径。");(n.includes("\0")||n.includes("\\"))&&mt("路径不能包含反斜杠。");const e=n.normalize("NFC").trim();if(!e.startsWith("/"))throw new m(p.BadRequest,"path 必须是工作区内绝对路径,例如 /说明.md。");const t=e.split("/").filter(i=>i.length>0);if(t.some(i=>i==="."||i==="..")&&mt("路径不能包含 . 或 .. 。"),t.length>0&&Ct(t[0]))throw new m(p.BadRequest,Mt);if(t[0]==="skills")throw new m(p.Forbidden,"技能文件只能通过技能工具访问。");return t.join("/")}function Ee(n){return Jn(n)}function Ji(n){return Jn(n)}function Ft(n){return n?`/${n}`:"/"}function Qi(n){if(n===".")return!0;if(!n||n.startsWith("/")||n.includes("\\")||n.includes("\0"))return!1;const e=n.split("/").filter(t=>t.length>0);return e.length>0&&e.every(t=>t!=="."&&t!=="..")&&!Ct(e[0])}function Qn(n,e){if(!n||/[\\/\0]/.test(n)||n==="."||n==="..")throw new m(p.BadRequest,"skill_name 必须是单个技能目录名。");if(!e||e.startsWith("/")||e.includes("\\")||e.includes("\0"))throw new m(p.BadRequest,"资源路径必须是技能目录内的相对路径。");const t=e.split("/").filter(i=>i.length>0);return(t.length===0||t.some(i=>i==="."||i===".."))&&mt("资源路径不能跳出技能目录。"),`skills/${n}/${t.join("/")}`}const Zn="https://cv-cdn.obs.cn-north-4.myhuaweicloud.com/glodon/libs/",Zi="3.6.0",es=`${Zn}just-bash/${Zi}/just-bash.mjs`,ts="314.0.7",ns=`${Zn}pyodide/${ts}/`,ei=["numpy","pandas","matplotlib","pillow","lxml"],tt=new Map;function is(n){return import(n)}function ss(n){let e=tt.get(n);return e||(e=is(n).catch(t=>{throw tt.delete(n),t}),tt.set(n,e)),e}const on=new Map;function rs(n){return/[\\^$.|+()[\]{}]/.test(n)?`\\${n}`:n}function os(n,e=!1){const t=`${e?"s":"i"}:${n}`,i=on.get(t);if(i)return i;let s="";for(let o=0;o<n.length;o++){const c=n[o];c==="*"?n[o+1]==="*"?(o++,n[o+1]==="/"?(o++,s+="(?:.*/)?"):s+=".*"):s+="[^/]*":c==="?"?s+="[^/]":s+=rs(c)}const r=new RegExp(`^${s}$`,e?"":"i");return on.set(t,r),r}function Ve(n,e,t=!1){return os(n,t).test(e)}function Nt(n){const e=n.lastIndexOf("/");return e<0?n:n.slice(e+1)}const ti=Object.freeze([{id:"env-files",pattern:".env*",reason:"环境变量文件可能包含密钥",source:"sdk-baseline"},{id:"pem",pattern:"*.pem",reason:"证书或密钥文件",source:"sdk-baseline"},{id:"key",pattern:"*.key",reason:"密钥文件",source:"sdk-baseline"},{id:"p12",pattern:"*.p12",reason:"证书文件",source:"sdk-baseline"},{id:"pfx",pattern:"*.pfx",reason:"证书文件",source:"sdk-baseline"},{id:"id-rsa",pattern:"id_rsa*",reason:"SSH 私钥",source:"sdk-baseline"},{id:"id-ed25519",pattern:"id_ed25519*",reason:"SSH 私钥",source:"sdk-baseline"},{id:"id-ecdsa",pattern:"id_ecdsa*",reason:"SSH 私钥",source:"sdk-baseline"},{id:"credentials",pattern:".credentials",reason:"凭据文件",source:"sdk-baseline"},{id:"npmrc",pattern:".npmrc",reason:"可能包含 registry token",source:"sdk-baseline"},{id:"pypirc",pattern:".pypirc",reason:"可能包含仓库凭据",source:"sdk-baseline"},{id:"aws-credentials",pattern:"**/.aws/credentials",match:"path",reason:"云服务凭据",source:"sdk-baseline"},{id:"ssh-dir",pattern:"**/.ssh/**",match:"path",reason:"SSH 配置与密钥",source:"sdk-baseline"}]),as="该文件被列为敏感文件,不允许访问";class ni{constructor(e=[]){y(this,"rules");const t=e.filter(i=>i&&typeof i.pattern=="string"&&i.pattern).map(i=>E(v({},i),{id:String(i.id||i.pattern),source:i.source==="enterprise"?"enterprise":"product"}));this.rules=[...ti,...t]}match(e,t){if(!e)return null;const i=Nt(e);for(const s of this.rules){if(s.operations&&!s.operations.includes(t))continue;const r=s.match==="path"?e:i;if(Ve(s.pattern,r))return s}return null}isSensitive(e){return["read","write","search"].some(t=>this.match(e,t)!==null)}static reasonOf(e){return`${e.reason||as},已拒绝访问。`}}function Ie(n,e,t){const i=n.sensitive.match(e,t);if(i)throw new m(p.Forbidden,ni.reasonOf(i),{reason:"sensitive_file",ruleId:i.id})}function He(n,e){return h(this,null,function*(){try{return yield n.stat(e)}catch(t){if(Ke(t).code===p.NotFound)return null;throw t}})}function Ot(n,e){return h(this,null,function*(){const t=yield n.stat(e);if(t.kind!=="file")throw new m(p.BadRequest,"目标是目录,不是文件。");return t})}function Se(n){return h(this,null,function*(){const e=yield crypto.subtle.digest("SHA-256",n);return`sha256:${Array.from(new Uint8Array(e)).map(i=>i.toString(16).padStart(2,"0")).join("")}`})}function q(n){return h(this,null,function*(){return new Uint8Array(yield n.arrayBuffer())})}function ae(n){const e=Math.min(n.byteLength,xt);for(let t=0;t<e;t++)if(n[t]===0)return!0;return!1}function cs(n){return h(this,null,function*(){return ae(yield q(n.slice(0,xt)))})}function ii(n){return n[0]===239&&n[1]===187&&n[2]===191}function ls(n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch(e){throw new m(p.BadRequest,"文件不是 UTF-8 编码,暂不支持修改。")}}function $t(n){return new TextEncoder().encode(n).byteLength}function si(){return new Promise(n=>setTimeout(n,0))}function ds(n){return n>=1024*1024?`${(n/1024/1024).toFixed(1)} MB`:n>=1024?`${(n/1024).toFixed(1)} KB`:`${n} B`}function oe(n,e="文件"){return new m(p.TooLarge,`${e}超过大小上限 ${ds(n)}。`)}const hs=`# 在 Pyodide 里按 python3 命令行的语义运行代码。由 pyodideWorker.js 加载,最后一个表达式 run 交给 JS 调用。
|
|
4
4
|
# 解释器在多次命令之间复用,所以每次运行前恢复 sys.path、环境变量和工作目录,并丢掉工作区里的模块缓存。
|
|
5
5
|
import io
|
|
6
6
|
import os
|
|
@@ -92,7 +92,7 @@ def run(mode, target, argv, cwd, stdin):
|
|
|
92
92
|
|
|
93
93
|
|
|
94
94
|
run
|
|
95
|
-
`,
|
|
95
|
+
`,us=`// Pyodide 专用 Worker。PythonRunner 用这份源码创建 Blob Module Worker,不经过集成方的打包器,
|
|
96
96
|
// 所以这里只能写浏览器直接能跑的 JS,不能有 import/export 语句和顶层 await。
|
|
97
97
|
//
|
|
98
98
|
// init { indexURL, packages, runner } → ready | failed { message }
|
|
@@ -330,45 +330,45 @@ self.onmessage = (event) => {
|
|
|
330
330
|
);
|
|
331
331
|
}
|
|
332
332
|
};
|
|
333
|
-
`,
|
|
334
|
-
`,
|
|
335
|
-
`):{mode:"c",target:c,argv:["-c",...o],stdin:t}}if(r==="-m"){const c=o.shift();return c?c==="pip"||c==="ensurepip"?ue(1,
|
|
333
|
+
`,gt=`浏览器环境不能安装依赖。可以直接 import ${ei.join("、")},需要其他包请改用宿主环境。
|
|
334
|
+
`,fs=10*1024*1024,ps=64*1024*1024;function ms(n){return!n||n==="."||n==="/"?F:n===F||n.startsWith(`${F}/`)?n:`${F}/${n.replace(/^\/+/,"")}`}function $e(n){if(n===F)return"";if(n.startsWith(`${F}/`))return n.slice(F.length+1)}const gs=new Set(["-u","-B","-E","-s","-S","-I","-O","-OO","-q","-b","-bb"]);function ue(n,e,t=""){return{exitCode:n,stdout:t,stderr:e}}function ys(n,e){const t=[];for(const i of(e.startsWith("/")?e:`${n}/${e}`).split("/"))!i||i==="."||(i===".."?t.pop():t.push(i));return`/${t.join("/")}`}function ws(n,e,t){const i=new Uint8Array(0);for(let s=0;s<n.length;s+=1){const r=n[s],o=n.slice(s+1);if(r==="-c"||r.startsWith("-c")&&!r.startsWith("--")){const c=r==="-c"?o.shift():r.slice(2);return c===void 0?ue(2,`python3: -c 后面缺少代码
|
|
335
|
+
`):{mode:"c",target:c,argv:["-c",...o],stdin:t}}if(r==="-m"){const c=o.shift();return c?c==="pip"||c==="ensurepip"?ue(1,gt):{mode:"m",target:c,argv:[c,...o],stdin:t}:ue(2,`python3: -m 后面缺少模块名
|
|
336
336
|
`)}if(r==="-V"||r==="--version")return{mode:"c",target:"import sys; print('Python ' + sys.version.split()[0])",argv:["-c"],stdin:t};if(r==="-h"||r==="--help")return ue(0,"",`usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
|
|
337
|
-
`);if(!(
|
|
338
|
-
`):{mode:"file",target:
|
|
339
|
-
`)}function
|
|
340
|
-
`).join("")}})}collect(e){return h(this,null,function*(){const{adapter:t,sensitive:i}=this.options,s={files:[],dirs:[],synced:new Set,skipped:[]};let r=0;const o=c=>h(this,null,function*(){var d
|
|
341
|
-
`,
|
|
342
|
-
`,exitCode:1}}})),u=new e.Bash({fs:a,cwd:t,env:{HOME:"/tmp",LANG:"C.UTF-8"},customCommands:[
|
|
343
|
-
`};const t=yield this.load();if((g=e.signal)!=null&&g.aborted)throw S("AbortError");const i=
|
|
344
|
-
`}}if(s.fatal)throw s.fatal;if((
|
|
345
|
-
${n.length>
|
|
337
|
+
`);if(!(gs.has(r)||/^-[WX]./.test(r))){if(r==="-W"||r==="-X"){s+=1;continue}return r==="-"?{mode:"c",target:new TextDecoder().decode(t),argv:["-",...o],stdin:i}:r.startsWith("-")?ue(2,`python3: 浏览器环境不支持参数 ${r}
|
|
338
|
+
`):{mode:"file",target:ys(e,r),argv:[r,...o],stdin:t}}}return t.length>0?{mode:"c",target:new TextDecoder().decode(t),argv:[""],stdin:i}:ue(2,`浏览器环境不支持交互式 Python,请用 python3 -c "…" 或脚本文件。
|
|
339
|
+
`)}function nt(n){var e;return n&&typeof n=="object"?String((e=n.name)!=null?e:""):""}function it(n){return n instanceof Error?n.message:String(n)}function an(n,e){return new Promise((t,i)=>{if(!n)return;const s=()=>{e==null||e(),i(S("AbortError"))};n.aborted?s():n.addEventListener("abort",s,{once:!0})})}function vs(n){const e=URL.createObjectURL(new Blob([n],{type:"text/javascript"})),t=new Worker(e,{type:"module"}),i=()=>URL.revokeObjectURL(e);return t.addEventListener("message",i,{once:!0}),t.addEventListener("error",i,{once:!0}),t}class _s{constructor(e){y(this,"state");y(this,"queue",Promise.resolve());y(this,"nextId",0);this.options=e}get indexURL(){return this.options.indexURL||ns}loadError(e){return new m(p.NotImplemented,`Python 运行环境加载失败,请确认页面能访问 ${this.indexURL}(CSP 需在 script-src、connect-src 放行该地址,worker-src 放行 blob:)。${e}`)}dispose(e,t){this.state===e&&(this.state=void 0),e.worker.terminate(),e.pending.forEach(({reject:i})=>i(t)),e.pending.clear()}spawn(){var r;let e;try{e=((r=this.options.createWorker)!=null?r:vs)(us)}catch(o){throw this.loadError(`(${it(o)})`)}let t;const i=new Promise((o,c)=>t={resolve:o,reject:c}),s={worker:e,ready:i,pending:new Map};return i.catch(()=>{}),e.onmessage=({data:o})=>{var a;const c=o;if(c.type==="ready")t.resolve();else if(c.type==="failed"){const l=this.loadError(`(${c.message})`);t.reject(l),this.dispose(s,l)}else c.type==="result"&&((a=s.pending.get(c.id))==null||a.resolve(c),s.pending.delete(c.id))},e.onerror=o=>{var l;const c=it((l=o==null?void 0:o.message)!=null?l:o),a=this.loadError(`(${c})`);t.reject(a),this.dispose(s,new Error(`Python 运行环境意外退出:${c}`))},e.postMessage({type:"init",indexURL:this.indexURL,packages:ei,runner:hs}),s}run(e){const t=this.queue.then(()=>this.runNow(e));return this.queue=t.catch(()=>{}),t}runNow(e){return h(this,null,function*(){var u,f,g;const t=ms(e.cwd),i=ws(e.args,t,(u=e.stdin)!=null?u:new Uint8Array(0));if(!("mode"in i))return i;if((f=e.signal)!=null&&f.aborted)throw S("AbortError");const s=(g=this.state)!=null?g:this.state=this.spawn();yield Promise.race([s.ready,an(e.signal)]);const r=yield this.collect(e.signal),o=this.nextId+=1,c=new Promise((_,w)=>s.pending.set(o,{resolve:_,reject:w}));s.worker.postMessage(v({type:"run",id:o,files:r.files,dirs:r.dirs,cwd:t},i),r.files.map(_=>_.data.buffer));const a=yield Promise.race([c,an(e.signal,()=>this.dispose(s,S("AbortError")))]),l=[];if(r.skipped.length>0){const _=r.skipped.slice(0,5).map(b=>`/${b}`),w=r.skipped.length>_.length?` 等 ${r.skipped.length} 个`:"";l.push(`提示:${_.join("、")}${w}文件超过同步上限(单个 10 MB、合计 64 MB),Python 里看不到。`)}return{exitCode:(yield this.writeBack(a,r,l))&&a.exitCode===0?1:a.exitCode,stdout:a.stdout,stderr:a.stderr+l.map(_=>`${_}
|
|
340
|
+
`).join("")}})}collect(e){return h(this,null,function*(){const{adapter:t,sensitive:i}=this.options,s={files:[],dirs:[],synced:new Set,skipped:[]};let r=0;const o=c=>h(this,null,function*(){var l,d;let a;try{a=yield t.listEntries(c,e)}catch(u){if(nt(u)==="NotFoundError"||nt(u)==="TypeMismatchError")return;throw u}s.dirs.push(c?`${F}/${c}`:F);for(const u of a.sort((f,g)=>f.name.localeCompare(g.name))){const f=c?`${c}/${u.name}`:u.name;if(u.kind==="directory"){yield o(f);continue}if(i.match(f,"read"))continue;const g=(d=(l=u.size)!=null?l:(yield t.stat(f)).size)!=null?d:0;if(g>fs||r+g>ps){s.skipped.push(f);continue}const _=yield q(yield t.readFile(f));r+=_.byteLength,s.files.push({path:`${F}/${f}`,data:_}),s.synced.add(f)}});return yield o(""),s})}exists(e){return h(this,null,function*(){try{return yield this.options.adapter.stat(e),!0}catch(t){return!1}})}writeBack(e,t,i){return h(this,null,function*(){const{adapter:s,sensitive:r}=this.options;let o=!1;const c=(l,d)=>{o=!0,i.push(`写回 ${l} 失败:${it(d)}`)};for(const l of e.createdDirs.sort()){const d=$e(l);!d||!s.createDirectory||(yield s.createDirectory(d).catch(u=>c(l,u)))}for(const{path:l,data:d}of e.written){const u=$e(l);u&&(r.match(u,"write")?i.push(`没有写回 ${l}:敏感文件不能由命令修改。`):!t.synced.has(u)&&(yield this.exists(u))?i.push(`没有写回 ${l}:工作区里已有这个文件,但它没有同步进 Python,为避免覆盖已跳过。`):yield s.writeFile(u,d,{createDirectories:!0}).catch(f=>c(l,f)))}if(e.removed.length>0&&!s.remove)return i.push(`当前工作区不支持删除,${e.removed.join("、")} 仍然保留。`),o;for(const l of e.removed){const d=$e(l);d&&(yield s.remove(d).catch(u=>{nt(u)!=="NotFoundError"&&c(l,u)}))}const a=e.removedDirs.sort((l,d)=>d.split("/").length-l.split("/").length);for(const l of a){const d=$e(l);d&&(yield s.remove(d).catch(()=>{}))}return o})}}const bs={ENOENT:"no such file or directory",EEXIST:"file already exists",EISDIR:"illegal operation on a directory",ENOTDIR:"not a directory",ENOTEMPTY:"directory not empty",EACCES:"permission denied",EPERM:"operation not permitted",EINVAL:"invalid argument",EIO:"i/o error"};function L(n,e,t){var s;const i=new Error(`${n}: ${(s=bs[n])!=null?s:n}, ${e} '${t}'`);return i.code=n,i}function De(n){var e;return n&&typeof n=="object"?String((e=n.name)!=null?e:""):""}function st(n){const e=typeof n=="string"?n:n==null?void 0:n.encoding;return(e!=null?e:"utf8").toLowerCase()}function cn(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return e}function Ss(n,e){switch(e){case"binary":case"latin1":case"ascii":return cn(n);case"base64":return btoa(cn(n));case"hex":return Array.from(n,t=>t.toString(16).padStart(2,"0")).join("");default:return new TextDecoder().decode(n)}}function ln(n,e){var t;if(typeof n!="string")return n;switch(e){case"binary":case"latin1":case"ascii":return Uint8Array.from(n,i=>i.charCodeAt(0)&255);case"base64":return Uint8Array.from(atob(n),i=>i.charCodeAt(0));case"hex":return Uint8Array.from((t=n.match(/../g))!=null?t:[],i=>parseInt(i,16));default:return new TextEncoder().encode(n)}}function Z(n){const e=[];for(const t of n.split("/"))!t||t==="."||(t===".."?e.pop():e.push(t));return`/${e.join("/")}`}class Es{constructor(e,t,i){this.adapter=e,this.root=t,this.sensitive=i}relative(e){const t=Z(e).slice(1);return this.root?t?`${this.root}/${t}`:this.root:t}shown(e){const t=this.relative(e);return t?`/${t}`:"/"}isRoot(e){return Z(e)==="/"}guard(e,t,i){const s=this.relative(e);if(this.sensitive.match(s,t))throw L("EACCES",i,this.shown(e));return s}mapError(e,t,i){if(e&&typeof e=="object"&&typeof e.code=="string")return e;switch(De(e)){case"NotFoundError":return L("ENOENT",t,this.shown(i));case"TypeMismatchError":return L(t==="open"||t==="write"?"EISDIR":"ENOTDIR",t,this.shown(i));case"InvalidModificationError":return L(t==="rm"?"ENOTEMPTY":"EEXIST",t,this.shown(i));case"NotAllowedError":case"SecurityError":case"NoModificationAllowedError":return L("EACCES",t,this.shown(i));default:return L("EIO",t,this.shown(i))}}entry(e,t){return h(this,null,function*(){try{return yield this.adapter.stat(this.relative(e))}catch(i){if(this.isRoot(e)&&De(i)==="NotFoundError")return{name:this.root,kind:"directory"};throw this.mapError(i,t,e)}})}ensureRoot(){return h(this,null,function*(){if(this.root)try{yield this.adapter.stat(this.root)}catch(e){if(De(e)!=="NotFoundError")throw e;this.adapter.createDirectory&&(yield this.adapter.createDirectory(this.root))}})}readFileBuffer(e){return h(this,null,function*(){const t=this.guard(e,"read","open");if((yield this.entry(e,"open")).kind!=="file")throw L("EISDIR","read",this.shown(e));try{return yield q(yield this.adapter.readFile(t))}catch(s){throw this.mapError(s,"open",e)}})}readFile(e,t){return h(this,null,function*(){return Ss(yield this.readFileBuffer(e),st(t))})}writeFile(e,t,i){return h(this,null,function*(){if(this.isRoot(e))throw L("EISDIR","open",this.shown(e));const s=this.guard(e,"write","open"),r=Z(e).lastIndexOf("/")===0;try{r&&(yield this.ensureRoot()),yield this.adapter.writeFile(s,ln(t,st(i)),{createDirectories:!0})}catch(o){throw this.mapError(o,"open",e)}})}appendFile(e,t,i){return h(this,null,function*(){let s=new Uint8Array;(yield this.exists(e))&&(s=yield this.readFileBuffer(e));const r=ln(t,st(i)),o=new Uint8Array(s.byteLength+r.byteLength);o.set(s),o.set(r,s.byteLength),yield this.writeFile(e,o)})}exists(e){return h(this,null,function*(){try{return yield this.entry(e,"access"),!0}catch(t){return!1}})}stat(e){return h(this,null,function*(){var s,r;const t=yield this.entry(e,"stat"),i=t.kind==="directory";return{isFile:!i,isDirectory:i,isSymbolicLink:!1,mode:i?493:420,size:(s=t.size)!=null?s:0,mtime:new Date((r=t.lastModified)!=null?r:0)}})}lstat(e){return this.stat(e)}mkdir(e,t){return h(this,null,function*(){if(!this.adapter.createDirectory)throw L("EPERM","mkdir",this.shown(e));if(yield this.exists(e)){if(t!=null&&t.recursive)return;throw L("EEXIST","mkdir",this.shown(e))}if(!(t!=null&&t.recursive)){const i=Z(e),s=i.slice(0,i.lastIndexOf("/"))||"/";if(!(yield this.exists(s)))throw L("ENOENT","mkdir",this.shown(e))}try{yield this.adapter.createDirectory(this.relative(e))}catch(i){throw this.mapError(i,"mkdir",e)}})}readdirWithFileTypes(e){return h(this,null,function*(){if((yield this.entry(e,"scandir")).kind!=="directory")throw L("ENOTDIR","scandir",this.shown(e));let i;try{i=yield this.adapter.listEntries(this.relative(e))}catch(s){if(this.isRoot(e)&&De(s)==="NotFoundError")return[];throw this.mapError(s,"scandir",e)}return i.map(s=>({name:s.name,isFile:s.kind==="file",isDirectory:s.kind==="directory",isSymbolicLink:!1})).sort((s,r)=>s.name<r.name?-1:s.name>r.name?1:0)})}readdir(e){return h(this,null,function*(){return(yield this.readdirWithFileTypes(e)).map(t=>t.name)})}rm(e,t){return h(this,null,function*(){if(this.isRoot(e))throw L("EPERM","rm",this.shown(e));const i=this.guard(e,"write","rm");if(!(yield this.exists(e))){if(t!=null&&t.force)return;throw L("ENOENT","rm",this.shown(e))}if(!this.adapter.remove)throw L("EPERM","rm",this.shown(e));try{yield this.adapter.remove(i,{recursive:(t==null?void 0:t.recursive)===!0})}catch(s){throw this.mapError(s,"rm",e)}})}cp(e,t,i){return h(this,null,function*(){if((yield this.entry(e,"cp")).kind==="file"){yield this.writeFile(t,yield this.readFileBuffer(e));return}if(!(i!=null&&i.recursive))throw L("EISDIR","cp",this.shown(e));yield this.mkdir(t,{recursive:!0});for(const r of yield this.readdir(e))yield this.cp(`${Z(e)}/${r}`,`${Z(t)}/${r}`,i)})}mv(e,t){return h(this,null,function*(){if(this.isRoot(e)||this.isRoot(t))throw L("EPERM","rename",this.shown(e));const i=this.guard(e,"write","rename"),s=this.guard(t,"write","rename");if(!this.adapter.move)throw L("EPERM","rename",this.shown(e));try{yield this.adapter.move(i,s)}catch(r){throw this.mapError(r,"rename",e)}})}resolvePath(e,t){return Z(t.startsWith("/")?t:`${e}/${t}`)}getAllPaths(){return[]}chmod(e){return h(this,null,function*(){yield this.entry(e,"chmod")})}symlink(e,t){return h(this,null,function*(){throw L("EPERM","symlink",this.shown(t))})}link(e,t){return h(this,null,function*(){throw L("EPERM","link",this.shown(t))})}readlink(e){return h(this,null,function*(){throw yield this.entry(e,"readlink"),L("EINVAL","readlink",this.shown(e))})}realpath(e){return h(this,null,function*(){return yield this.entry(e,"realpath"),Z(e)})}utimes(e){return h(this,null,function*(){yield this.entry(e,"utime")})}}const Is=`当前环境没有 Node,请改用 python3 或 shell 命令。
|
|
341
|
+
`,ks=new Set(["writeFile","appendFile","mkdir","rm","cp","mv","chmod","symlink","link","utimes","createExclusive"]),xs="dev|bin|usr|proc|etc|System|Library|private|var|opt|sbin|tmp|Applications|Volumes|cores|net|home",As=new RegExp(`(^|[\\s'"=(;|&<>\`:])/(?!${xs}(?=$|[/\\s'"\`;|&)<>:]))(?!/)`,"g");function Ts(n){let e=!1;return{fs:new Proxy(n,{get(i,s,r){const o=Reflect.get(i,s,r);return typeof o!="function"?o:(...c)=>{var l;const a=String((l=c[0])!=null?l:"");if(e&&ks.has(String(s))&&!a.startsWith("/dev/"))throw Object.assign(new Error(`EROFS: 只能写入工作区下的路径, open '${a}'`),{code:"EROFS"});return o.apply(i,c)}}}),lock:()=>e=!0}}function Rs(n){return n instanceof Uint8Array?n:Uint8Array.from(String(n!=null?n:""),e=>e.charCodeAt(0)&255)}function Ls(n){return n instanceof DOMException&&n.name==="AbortError"}function Ms(n){if(!n)return;if(n===F)return".";if(!n.startsWith(`${F}/`))return;const e=n.slice(F.length+1).replace(/\/+$/,"");if(!e)return".";const t=e.split("/");if(!t.some(i=>!i||i==="."||i===".."))return t.join("/")}function dn(n){return!n||n==="."?F:n===F||n.startsWith(`${F}/`)?n:`${F}/${n.replace(/^\/+/,"")}`}function Cs(n){return n.replace(As,(e,t)=>`${t}${F}/`)}function rt(n){return n.replace(/\/workspace(?![\p{L}\p{N}_.\-])/gu,(e,t,i)=>i[t+e.length]==="/"?"":"/")}class Fs{constructor(e){y(this,"python");this.options=e,this.python=new _s({adapter:e.adapter,sensitive:e.sensitive,indexURL:e.pyodideIndexURL,createWorker:e.createWorker})}load(){return h(this,null,function*(){const e=this.options.moduleURL||es;try{return yield ss(e)}catch(t){throw new m(p.NotImplemented,`命令运行时加载失败,请确认页面能访问 ${e}(CSP 需在 script-src 放行该地址)。`)}})}create(e,t,i,s){const{adapter:r,sensitive:o}=this.options,c=Ts(new e.InMemoryFs),a=new e.MountableFs({base:c.fs});a.mount(F,new Es(r,"",o));const l=(f,g,_)=>e.defineCommand(f,()=>h(this,null,function*(){return{stdout:"",stderr:g,exitCode:_}})),d=f=>e.defineCommand(f,(g,_)=>h(this,null,function*(){var w;try{return yield this.python.run({args:g,cwd:_.cwd,stdin:Rs(_.stdin),signal:i})}catch(b){return b instanceof m||Ls(b)?((w=s.fatal)!=null||(s.fatal=b),{stdout:"",stderr:"",exitCode:1}):{stdout:"",stderr:`${f}: ${b instanceof Error?b.message:String(b)}
|
|
342
|
+
`,exitCode:1}}})),u=new e.Bash({fs:a,cwd:t,env:{HOME:"/tmp",LANG:"C.UTF-8"},customCommands:[l("node",Is,127),l("pip",gt,1),l("pip3",gt,1),d("python3"),d("python")],defenseInDepth:!1});return c.lock(),u}exec(e){return h(this,null,function*(){var d,u,f,g,_,w,b,A,I;if(Ct(e.cwd)||ze((d=e.command)!=null?d:"")||ze((f=(u=e.argv)==null?void 0:u[1])!=null?f:""))return{exitCode:1,stdout:"",stderr:`${Mt}
|
|
343
|
+
`};const t=yield this.load();if((g=e.signal)!=null&&g.aborted)throw S("AbortError");const i=dn(e.cwd),s={},r=this.create(t,i,e.signal,s),[o,c,...a]=(_=e.argv)!=null?_:[];let l;try{l=e.argv?yield r.exec(o,{cwd:i,signal:e.signal,args:[dn(c),...a]}):yield r.exec(Cs((w=e.command)!=null?w:""),{cwd:i,signal:e.signal,rawScript:!0})}catch(T){if(s.fatal)throw s.fatal;if((b=e.signal)!=null&&b.aborted)throw S("AbortError");const R=T instanceof Error?T.message:String(T);return{exitCode:1,stdout:"",stderr:`bash: ${rt(R)}
|
|
344
|
+
`}}if(s.fatal)throw s.fatal;if((A=e.signal)!=null&&A.aborted)throw S("AbortError");return{exitCode:l.exitCode,stdout:rt(l.stdout),stderr:rt(l.stderr),cwd:Ms((I=l.env)==null?void 0:I.PWD)}})}}const ne=n=>({type:"string",minLength:1,description:n}),fe="必填。工作区内绝对路径,以 / 开头,例如 /说明.md。不要使用 /input、/output、/uploads、/tmp,也不要新建这些目录。",Dt={shell:{functionCode:"shell",name:"执行命令",description:"在当前会话工作区中执行一条 shell 命令并返回标准输出。每次调用都是新的 shell,只保留上次停留的目录;环境变量不会保留,需要时在同一条命令里设置。当前目录是工作区根目录。用相对路径,或以 / 开头表示工作区内已有的路径,例如 notes/a.md、/说明.md。不要使用或新建 input、output、uploads、tmp。/dev、/usr、/bin 仍是系统路径。写进脚本文件里的路径要用相对路径(见 run_file)。超过 20000 字的脚本请用 write_file 写到工作区文件后再调用 run_file;读取文件正文或结构摘要请用 read_file 的 start_line 和 end_line,不要用 cat、sed 或 head 把大文件正文打到标准输出。",parameters:{type:"object",required:["command"],properties:{command:{type:"string",minLength:1,maxLength:Vi,description:"必填。一条不超过 20000 字的 shell 命令。当前目录已是工作区根目录。可以包含短的 python 或 heredoc。读取文件正文请改用 read_file。"}}}},read_file:{functionCode:"read_file",name:"读取文件",description:"按绝对路径读取工作区内的文本文件并返回内容;读不到时返回失败原因。未超过上限的文本按原文返回;超过单次读取上限的结构化文本(JSON/XML/SVG/CSV/TSV)会先附带通用结构概览和短预览,需要特定片段时再用 start_line 和 end_line。PDF 和图片只返回文件摘要,不返回正文。",parameters:{type:"object",required:["path"],properties:{path:ne(fe),start_line:{type:"integer",minimum:1,description:"可选。起始行号,从 1 开始,含本行。省略则从第 1 行读。"},end_line:{type:"integer",minimum:1,description:"可选。结束行号,从 1 开始,含本行。省略则读到文件末尾。"}}}},write_file:{functionCode:"write_file",name:"写入文件",description:`把文本写入工作区内文件,path 为工作区内绝对路径,文件已存在时覆盖。单次覆盖写入按 UTF-8 字节计,默认不超过 ${We} 字节。超限时先写一段,再用 edit_file 修改,或用 append_file 追加下一段。SVG 和整页 HTML 由工作区里的脚本生成,不要直接放进 content。`,parameters:{type:"object",required:["path","content"],properties:{path:ne(fe),content:{type:"string",description:`必填。覆盖写入的文本,UTF-8 不超过 ${We} 字节。不要放入 SVG 或整页 HTML。`}}}},append_file:{functionCode:"append_file",name:"追加文件",description:"把一段文本追加到工作区内文件末尾,path 为工作区内绝对路径,文件不存在时创建。覆盖写入超过字节上限时,用本工具把下一段接到同一文件。追加不设字节上限,但不要在一次调用里放入整份 HTML 或 SVG。",parameters:{type:"object",required:["path","content"],properties:{path:ne(fe),content:{type:"string",description:"必填。要追加到文件末尾的文本。不受覆盖写入的字节上限约束。"}}}},run_file:{functionCode:"run_file",name:"执行文件",description:"执行工作区里已经存在的 .py、.sh 或 .js 脚本文件。生成 SVG、HTML、JSON 等产物时优先使用:先用 write_file 写脚本,脚本自行读取工作区文件并写出产物,再调用本工具。脚本运行时当前目录是工作区根目录,脚本里访问工作区文件要写相对路径,例如 data.json、notes/a.py。不要使用或新建 input、output、uploads、tmp。需要查看文件正文时用 read_file,不要把整份文件打印到标准输出。",parameters:{type:"object",required:["path"],properties:{path:ne("必填。要执行的 .py、.sh 或 .js 文件,工作区内绝对路径,例如 /scripts/gen.py。")}}},edit_file:{functionCode:"edit_file",name:"修改文件",description:"把工作区内文本文件中第一处与 old_text 完全相同的内容替换为 new_text。找不到 old_text 时返回最接近片段的行号,可直接复制原文重试,不必再读全文。old_text 与 new_text 不设长度上限。",parameters:{type:"object",required:["path","old_text","new_text"],properties:{path:ne(fe),old_text:{type:"string",minLength:1,description:"必填。文件中要被替换的原文,必须完全一致。"},new_text:{type:"string",description:"必填。替换后的文本。可以是一整段生成逻辑,不必拆成追加。"}}}},grep:{functionCode:"grep",name:"搜索文件",description:"在工作区目录中递归搜索文本,返回带行号的匹配行。path 为工作区内绝对路径,pattern 按 grep 基本正则匹配。用于定位内容,不要用来取回大文件全文。",parameters:{type:"object",required:["path","pattern"],properties:{path:ne(fe),pattern:{type:"string",minLength:1,description:"必填。grep 基本正则表达式。"}}}},find:{functionCode:"find",name:"查找文件",description:"按文件名通配在工作区目录中查找文件。path 为起始绝对路径,name 传给 find 的 -name,例如 *.html。",parameters:{type:"object",required:["path","name"],properties:{path:ne(fe),name:{type:"string",minLength:1,description:"必填。find -name 通配,例如 *.svg 或 *.html。"}}}},load_skill:{functionCode:"load_skill",name:"加载技能",description:"按技能名称加载平台技能的完整说明(SKILL.md)。技能不在工程目录里。",parameters:{type:"object",required:["skill_name"],properties:{skill_name:{type:"string",minLength:1,description:"必填。要加载的技能名称。"}}}},read_skill_resource:{functionCode:"read_skill_resource",name:"读取技能资源",description:"读取与指定技能关联的资源文件,例如参考资料、模板或附加说明。",parameters:{type:"object",required:["skill_name","resource_name"],properties:{skill_name:{type:"string",minLength:1,description:"必填。技能名称。"},resource_name:{type:"string",minLength:1,description:"必填。要读取的技能资源相对路径名称。"}}}},run_skill_script:{functionCode:"run_skill_script",name:"运行技能脚本",description:"执行平台技能包内的脚本并返回输出。当前目录是工作区根目录,参数里的用户文件按相对工作区根目录传,例如 docs/a.docx。技能自己的资源按脚本文件所在目录查找,不在工程的 skills 目录里。",parameters:{type:"object",required:["skill_name","script_name"],properties:{skill_name:{type:"string",minLength:1,description:"必填。技能名称。"},script_name:{type:"string",minLength:1,description:"必填。要运行的技能脚本相对路径(保持技能说明中列出的目录前缀,如 scripts/run.py)。"},args:{type:"array",description:'传递给脚本的命令行位置参数数组,例如 ["input.docx", "--output", "result.idx"]。',items:{type:"string",description:"单个脚本参数。"}}}}}},hn=Object.keys(Dt);if(hn.length!==ft.length||ft.some(n=>!hn.includes(n)))throw new Error("BUILTIN_TOOL_SCHEMAS 与 BUILTIN_FUNCTION_CODES 不一致");const un=500;function we(n){return`预览:
|
|
345
|
+
${n.length>un?n.slice(0,un):n}`}function Ns(n){let e;try{e=JSON.parse(n)}catch(t){return`JSON 无法完整解析。
|
|
346
346
|
${we(n)}`}if(Array.isArray(e)){const t=e[0],i=t&&typeof t=="object"&&!Array.isArray(t)?`元素字段:${Object.keys(t).slice(0,20).join(", ")||"(无)"}。`:`元素类型:${t===null?"null":typeof t}。`;return`JSON 数组,长度 ${e.length}。${i}
|
|
347
347
|
${we(n)}`}if(e&&typeof e=="object"){const t=e,i=Object.keys(t),s=i.filter(o=>Array.isArray(t[o])).slice(0,10).map(o=>`${o} (${t[o].length})`),r=s.length?`数组字段:${s.join("、")}。`:"";return`JSON 对象。字段:${i.slice(0,40).join(", ")||"(无)"}。${r}
|
|
348
348
|
${we(n)}`}return`JSON ${e===null?"null":typeof e}。
|
|
349
|
-
${we(n)}`}function
|
|
350
|
-
${we(n)}`}function
|
|
349
|
+
${we(n)}`}function fn(n,e){var l,d;const t=n.match(/<([A-Za-z_][\w:.-]*)\b/),i=(l=t==null?void 0:t[1])!=null?l:"未知",s=new Map,r=new RegExp("<([A-Za-z_][\\w:.-]*)\\b","g");let o,c=!1;for(;o=r.exec(n);){const u=o[1];if(!c&&u===i){c=!0;continue}if(s.set(u,((d=s.get(u))!=null?d:0)+1),s.size>30)break}const a=Array.from(s.entries()).slice(0,20).map(([u,f])=>`${u} (${f})`).join("、");return`${e} 根元素 ${i}。直接或嵌套子元素:${a||"(无)"}。
|
|
350
|
+
${we(n)}`}function pn(n,e,t){var a;const i=n.split(/\r?\n/).filter(l=>l.length>0),s=(a=i[0])!=null?a:"",r=s?s.split(e).length:0,o=Math.max(i.length-1,0),c=i.slice(0,4).join(`
|
|
351
351
|
`);return`${t},${r} 列,数据行 ${o}。表头:${s}
|
|
352
352
|
预览:
|
|
353
|
-
${c}`}function
|
|
353
|
+
${c}`}function Os(n){const e=Me(n);return e===".json"||e===".xml"||e===".svg"||e===".csv"||e===".tsv"}function $s(n,e){const t=Me(n);return t===".json"?Ns(e):t===".svg"?fn(e,"SVG"):t===".xml"?fn(e,"XML"):t===".tsv"?pn(e," ","TSV"):t===".csv"?pn(e,",","CSV"):we(e)}function Me(n){var i;const e=(i=n.split("/").pop())!=null?i:"",t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}const Ds=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".tif",".tiff"]);function ri(n){return Ds.has(Me(n))}function oi(n,e){return Me(n)===".pdf"?!0:!e||e.byteLength<4?!1:e[0]===37&&e[1]===80&&e[2]===68&&e[3]===70}function ai(n){return!!n&&typeof n=="object"&&n.name==="NotFoundError"}function Ce(n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch(e){throw new m(p.BadRequest,"文件不是 UTF-8 文本。")}}function Pt(n){return n===""?[]:(n.endsWith(`
|
|
354
354
|
`)?n.slice(0,-1):n).split(`
|
|
355
|
-
`)}function
|
|
356
|
-
`)}function
|
|
357
|
-
`);return{text:s>0?i.slice(0,s):i,truncated:!0}}function
|
|
358
|
-
${c.excerpt}`,{line:c.line,excerpt:c.excerpt})}const o=s.slice(0,r)+n.new_text+s.slice(r+n.old_text.length);return yield
|
|
359
|
-
`),s=((a=i[0])!=null?a:"").slice(0,200);let r=0,o=-1;for(let
|
|
360
|
-
`)}}function
|
|
355
|
+
`)}function Ps(n,e,t){if(e!==void 0&&t!==void 0&&t<e)throw new m(p.BadRequest,"end_line 不能小于 start_line。");const i=Pt(n),s=Math.max((e!=null?e:1)-1,0),r=t!=null?t:i.length;return i.slice(s,r).join(`
|
|
356
|
+
`)}function mn(n){if($t(n)<=pt)return{text:n,truncated:!1};const e=new TextEncoder().encode(n);let t=pt;for(;t>0&&(e[t]&192)===128;)t-=1;const i=new TextDecoder().decode(e.slice(0,t)),s=i.lastIndexOf(`
|
|
357
|
+
`);return{text:s>0?i.slice(0,s):i,truncated:!0}}function Fe(n,e){return h(this,null,function*(){const t=yield n.stat(e);if(t.kind!=="file")throw new m(p.BadRequest,"目标是目录,不是文件。");const i=yield q(yield n.readFile(e));return{entry:t,bytes:i}})}function gn(n,e,t){const i=typeof t=="number"?`${t} 字节,`:"";return`${n},${i}路径 ${Ft(e)}。不返回正文。`}function Ge(n){const e=Me(n);if(!Gi.includes(e))throw new m(p.BadRequest,"只能执行 .py、.sh 或 .js 文件。");return e===".py"?"python3":e===".js"?"node":"sh"}function ci(n){if(!n.runner)throw new m(p.NotImplemented,"当前环境不能执行命令或脚本,需要端侧宿主。");return n.runner}function Bt(n,e,t,i){return h(this,null,function*(){yield n.writeFile(e,t,{createDirectories:!0,signal:i})})}function Bs(n,e){return h(this,null,function*(){const t=Ee(n.path);if(N(e.signal),ri(t)){const a=yield e.adapter.stat(t);if(a.kind!=="file")throw new m(p.BadRequest,"目标是目录,不是文件。");return{data:{content:gn("图片",t,a.size),truncated:!1}}}const{entry:i,bytes:s}=yield Fe(e.adapter,t);if(oi(t,s))return{data:{content:gn("PDF",t,i.size),truncated:!1}};if(ae(s))throw new m(p.BadRequest,"文件不是文本,无法读取正文。");const r=Ce(s);if(n.start_line!==void 0||n.end_line!==void 0){const a=Ps(r,n.start_line,n.end_line),l=mn(a);return{data:{content:l.text,truncated:l.truncated}}}if(s.byteLength>pt&&Os(t))return{data:{content:$s(t,r),truncated:!0}};const c=mn(r);return{data:{content:c.text,truncated:c.truncated}}})}function js(n,e){return h(this,null,function*(){const t=Ee(n.path);if($t(n.content)>We)throw new m(p.TooLarge,`content 按 UTF-8 计超过 ${We} 字节。请缩短后写入,或改用 append_file、edit_file。`);return N(e.signal),yield Bt(e.adapter,t,n.content,e.signal),{data:{}}})}function Us(n,e){return h(this,null,function*(){const t=Ee(n.path);N(e.signal);let i="";try{const{bytes:s}=yield Fe(e.adapter,t);if(ae(s))throw new m(p.BadRequest,"文件不是文本,无法追加。");i=Ce(s)}catch(s){if(!ai(s))throw s}return yield Bt(e.adapter,t,i+n.content,e.signal),{data:{}}})}function Hs(n,e){return h(this,null,function*(){const t=Ee(n.path);N(e.signal);const{bytes:i}=yield Fe(e.adapter,t);if(ae(i))throw new m(p.BadRequest,"文件不是文本,无法修改。");const s=Ce(i),r=s.indexOf(n.old_text);if(r<0){const c=qs(s,n.old_text);throw new m(p.BadRequest,`找不到与 old_text 完全相同的内容。最接近的原文从第 ${c.line} 行开始,可复制后重试:
|
|
358
|
+
${c.excerpt}`,{line:c.line,excerpt:c.excerpt})}const o=s.slice(0,r)+n.new_text+s.slice(r+n.old_text.length);return yield Bt(e.adapter,t,o,e.signal),{data:{}}})}function qs(n,e){var a;const t=Pt(n);if(t.length===0)return{line:1,excerpt:""};const i=e.split(`
|
|
359
|
+
`),s=((a=i[0])!=null?a:"").slice(0,200);let r=0,o=-1;for(let l=0;l<t.length;l+=1){const d=Ws(t[l],s);d>o&&(o=d,r=l)}const c=Math.min(Math.max(i.length,1),8);return{line:r+1,excerpt:t.slice(r,r+c).join(`
|
|
360
|
+
`)}}function Ws(n,e){if(!e)return 0;const t=n.toLowerCase(),i=e.toLowerCase();let s=0,r=0;for(const o of t)r<i.length&&o===i[r]&&(s+=1,r+=1);return s}function zs(n){let e="";for(let t=0;t<n.length;t+=1){const i=n[t];if(i==="\\"){const s=n[t+1];if(s===void 0){e+="\\\\";continue}t+=1,e+="+?|{}()".includes(s)?`\\${s}`:s==="n"?"\\n":s==="t"?"\\t":yt(s);continue}if("+?|{}()".includes(i)){e+=`\\${i}`;continue}if(i==="["){const s=n.indexOf("]",t+1);if(s<0){e+="\\[";continue}e+=n.slice(t,s+1),t=s;continue}e+=".^$*".includes(i)?i:yt(i)}return new RegExp(e)}function yt(n){return/[\\^$.*+?()[\]{}|]/.test(n)?`\\${n}`:n}function Vs(n){try{return zs(n)}catch(e){throw new m(p.BadRequest,"pattern 不是合法的 grep 基本正则。")}}function jt(n,e,t,i,s){return h(this,null,function*(){if(i>16)return;N(t);const r=yield n.stat(e);if(yield s(e,r.kind),r.kind!=="directory")return;const o=yield n.listEntries(e,t);o.sort((c,a)=>c.name<a.name?-1:c.name>a.name?1:0);for(const c of o){const a=e?`${e}/${c.name}`:c.name;yield jt(n,a,t,i+1,s)}})}function Gs(n,e){return h(this,null,function*(){const t=Ee(n.path),i=Vs(n.pattern),s=[];yield jt(e.adapter,t,e.signal,0,(o,c)=>h(this,null,function*(){if(c!=="file"||s.length>=200)return;const{bytes:a}=yield Fe(e.adapter,o);if(ae(a)||ri(o)||oi(o,a))return;let l;try{l=Ce(a)}catch(u){return}const d=Pt(l);for(let u=0;u<d.length&&s.length<200;u+=1){if(!i.test(d[u]))continue;const f=d[u].length>500?`${d[u].slice(0,500)}…`:d[u];s.push(`${Ft(o)}:${u+1}:${f}`)}}));const r=s.join(`
|
|
361
361
|
`);return{data:{matches:s.length>=200?`${r}
|
|
362
|
-
(匹配过多,已截断)`:r}}})}function
|
|
362
|
+
(匹配过多,已截断)`:r}}})}function Xs(n,e){let t="^";for(let i=0;i<n.length;i+=1){const s=n[i];if(s==="*")t+=".*";else if(s==="?")t+=".";else if(s==="["){const r=n.indexOf("]",i+1);r<0?t+="\\[":(t+=n.slice(i,r+1),i=r)}else t+=yt(s)}return new RegExp(`${t}$`).test(e)}function Ys(n,e){return h(this,null,function*(){const t=Ee(n.path),i=[];yield jt(e.adapter,t,e.signal,0,r=>h(this,null,function*(){var c;if(i.length>=500)return;const o=(c=r.split("/").pop())!=null?c:r;Xs(n.name,o)&&i.push(Ft(r))})),i.sort();const s=i.join(`
|
|
363
363
|
`);return{data:{files:i.length>=500?`${s}
|
|
364
|
-
(结果过多,已截断)`:s}}})}function
|
|
365
|
-
`}};const i=yield
|
|
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
|
-
${JSON.stringify(f)}`);const b=(
|
|
368
|
-
`),
|
|
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
|
-
`);r=(c=
|
|
371
|
-
`),startLine:a,endLine:Math.max(
|
|
364
|
+
(结果过多,已截断)`:s}}})}function Ks(n,e,t){return h(this,null,function*(){const i=ci(t);yield Fe(t.adapter,n);const s=yield i.exec({argv:[Ge(n),n,...e],cwd:Lt,timeoutMs:t.timeoutMs,signal:t.signal});return{data:{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr}}})}function Js(n,e){return h(this,null,function*(){const t=Ji(n.path);return Ge(t),Ks(t,[],e)})}function Qs(n,e){return h(this,null,function*(){if(rn(n.command)||rn(e.shellCwd.cwd))throw new m(p.Forbidden,"技能文件只能通过技能工具访问。");if(ze(n.command)||ze(e.shellCwd.cwd))return{data:{exitCode:1,stdout:"",stderr:`${Mt}
|
|
365
|
+
`}};const i=yield ci(e).exec({command:n.command,cwd:e.shellCwd.cwd,timeoutMs:e.timeoutMs,signal:e.signal});return i.cwd&&Qi(i.cwd)&&(e.shellCwd.cwd=i.cwd),{data:{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}})}function li(n){if(!n.skills)throw new m(p.NotImplemented,"当前环境不能加载平台技能,需要端侧宿主。");return n.skills}function di(n,e,t){return h(this,null,function*(){Qn(n,e);const i=yield li(t).read(n,e,t.signal);if(ae(i))throw new m(p.BadRequest,"技能资源不是文本。");return Ce(i)})}function Zs(n){if(!n.skillRunner)throw new m(p.NotImplemented,"当前环境不能加载平台技能,需要端侧宿主。");return n.skillRunner}function er(n,e){return h(this,null,function*(){return{data:{content:yield di(n.skill_name,"SKILL.md",e)}}})}function tr(n,e){return h(this,null,function*(){return{data:{content:yield di(n.skill_name,n.resource_name,e)}}})}function nr(n,e){return h(this,null,function*(){var o;const t=li(e);Qn(n.skill_name,n.script_name),Ge(n.script_name);const i=Zs(e),s=yield t.target(n.skill_name,e.signal),r=t.track(s.skillId,s.version);try{const c=yield i.exec({argv:[Ge(n.script_name),n.script_name,...(o=n.args)!=null?o:[]],cwd:Lt,timeoutMs:e.timeoutMs,signal:e.signal,skill:s});return{data:{exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr}}}catch(c){throw ai(c)?new m(p.NotFound,"技能脚本不存在。"):c}finally{r()}})}const ir={shell:Qs,read_file:Bs,write_file:js,append_file:Us,run_file:Js,edit_file:Hs,grep:Gs,find:Ys,load_skill:er,read_skill_resource:tr,run_skill_script:nr},Te=new U("[BuiltinTools] "),yn=new Set(["shell","run_file","run_skill_script"]);function sr(n,e,t){var i,s;if(n.commandRunner)return ht(n.commandRunner);if(e instanceof Je){if(e.protocolMismatch){const r=`${(i=e.sandboxVersion)!=null?i:""}@${(s=e.sandboxProtocol)!=null?s:""}`;t.rejectedSandbox!==r&&(t.rejectedSandbox=r,Te.error("sandbox-protocol",{sandboxVersion:e.sandboxVersion,sandboxProtocol:e.sandboxProtocol,supported:ye}))}if(!e.canExec){const r=e.unavailableMessage();return{exec:()=>Promise.reject(S("NotAllowedError",r))}}return{exec:r=>e.exec(r)}}if(n.browserRuntime.enabled)return(t.adapter!==e||!t.runner)&&(t.adapter=e,t.runner=ht(new Fs({adapter:e,sensitive:n.sensitive,moduleURL:n.browserRuntime.bashModuleURL,pyodideIndexURL:n.browserRuntime.pyodideIndexURL}))),t.runner}function rr(n,e){if(n.commandRunner)return ht(n.commandRunner);if(e instanceof Je){if(!e.canExec){const t=e.unavailableMessage();return{exec:()=>Promise.reject(S("NotAllowedError",t))}}return{exec:t=>e.exec(t)}}}function or(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch(e){throw new m(p.BadRequest,"参数不是合法的 JSON 对象。")}}function ar(n){const e=n instanceof DOMException?n.name:"",t=n instanceof Error?n.message:"";if(e==="NotFoundError")return new m(p.NotFound,"脚本或目录不存在。");if(e==="SecurityError")return new m(p.Forbidden,"命令路径不在工作区内。");if(e==="AbortError")return t.includes("超时")?new m(p.Timeout,"命令运行超时,已中止。"):t.includes("已有")?new m(p.TooManyRequests,"已有一个命令在运行。"):j();if(e==="NotAllowedError")return t.startsWith("沙箱")?new m(p.NotImplemented,t):new m(p.NotImplemented,"当前环境不能执行命令或脚本,需要端侧宿主。")}function cr(n){return new Promise((e,t)=>{n.aborted&&t(j()),n.addEventListener("abort",()=>t(j()),{once:!0})})}function hi(n,e=160){return n.length>e?`${n.slice(0,e)}…`:n}function lr(n){const e={};for(const t of["path","skill_name","resource_name","script_name","pattern","name"])typeof n[t]=="string"&&(e[t]=n[t]);return typeof n.command=="string"&&(e.command=hi(n.command)),typeof n.start_line=="number"&&(e.start_line=n.start_line),typeof n.end_line=="number"&&(e.end_line=n.end_line),typeof n.content=="string"&&(e.contentLength=n.content.length),typeof n.old_text=="string"&&(e.oldTextLength=n.old_text.length),typeof n.new_text=="string"&&(e.newTextLength=n.new_text.length),Array.isArray(n.args)&&(e.argCount=n.args.length),e}function dr(n){return v({code:n.code,message:n.message},n.data?{data:n.data}:{})}function hr({pluginCode:n,workspace:e}){const t=new Map,i={},s={};return ft.forEach(r=>{s[r]=(o,c,a)=>{let l=!1;ur(e,t,i,r,o,u=>{if(!l){l=!0;try{c(u)}catch(f){console.error("[BuiltinTools] callback failed",f)}}},E(v({},a),{pluginCode:n}))}}),{[n]:s}}function ur(n,e,t,i,s,r,o){return h(this,null,function*(){var A,I,T,R,J;const c={requestId:o.requestId||_e.v4(),applicationId:o.applicationId||n.applicationId,sessionId:o.sessionId||"",pluginCode:o.pluginCode,functionCode:i,signal:o.signal},a={requestId:c.requestId,sessionId:c.sessionId,functionCode:i},l=new AbortController;let d=!1;const u=setTimeout(()=>{d=!0,l.abort()},n.limits.toolTimeoutMs),f=()=>l.abort();(A=c.signal)==null||A.addEventListener("abort",f,{once:!0}),(I=c.signal)!=null&&I.aborted&&l.abort();let g=null,_=null,w;const b=Date.now();try{const O=or(s),k=Kn(O,Dt[i].parameters);if(typeof k.path=="string"&&(a.path=k.path),Te.log("start",v(v({},a),lr(k))),yield n.ready,l.signal.aborted)throw j();const M=n.adapter;if(!M)throw At();if(g=n.acquireSlot(),!g)throw new m(p.TooManyRequests,"同时进行的文件操作过多,请稍后重试。");if(yn.has(i)&&(_=n.acquireCommand(),!_))throw new m(p.TooManyRequests,"已有一个命令在运行,请等它结束后再试。");w=n.track(l),n.emit("tool:start",v({},a));const C=c.sessionId||"default";let $=e.get(C);$||($={cwd:Lt},e.set(C,$));const ce=sr(n,M,t),le=$.cwd,ke={adapter:M,runner:ce,signal:l.signal,timeoutMs:n.limits.toolTimeoutMs,shellCwd:$,skills:n.platformSkills,skillRunner:rr(n,M)},Q=yield Promise.race([ir[i](k,ke),cr(l.signal)]),Ne={code:p.Ok,message:"ok",data:Q.data};Q.truncated&&(Ne.truncated=!0);const Mi=Date.now()-b,Gt=Q.data.exitCode;Te.log("finish",v(v(v(E(v({},a),{elapsedMs:Mi,code:p.Ok}),Q.truncated?{truncated:!0}:{}),typeof Gt=="number"?{exitCode:Gt}:{}),i==="shell"?{cwd:$.cwd,cwdChanged:$.cwd!==le}:{})),n.emit("tool:finish",E(v({},a),{code:p.Ok})),yn.has(i)&&n.notifyFilesChanged(),r(Ne)}catch(O){let k=(T=ar(O))!=null?T:Ke(O);d?k=new m(p.Timeout,"操作超时,已中止。"):l.signal.aborted&&k.code!==p.Cancelled&&(k=j());const M=Date.now()-b;k.code===p.Cancelled?(Te.log("cancelled",E(v({},a),{elapsedMs:M,timedOut:d})),n.emit("tool:cancelled",v({},a))):(Te.error("error",E(v({},a),{elapsedMs:M,code:k.code,message:hi(k.message,300)})),n.emit("tool:error",E(v({},a),{code:k.code,message:k.message,reason:(R=k.data)==null?void 0:R.reason}))),r(dr(k))}finally{clearTimeout(u),(J=c.signal)==null||J.removeEventListener("abort",f),g==null||g(),_==null||_(),w==null||w()}})}const fr=new U("[Config] ");var ui=(n=>(n.dev="https://aiot-dev.glodon.com/api/cvforcepd",n.test="https://aiot-dev.glodon.com/api/cvforce",n.prod="https://copilot.glodon.com/api/cvforce",n.local="http://localhost:3000/api/cvforcepd",n))(ui||{});exports.configuration={debug:!1,env:"prod",apiRoot:"https://copilot.glodon.com/api/cvforce",applicationId:"",plugins:{},businessPlugins:{},builtinPlugins:void 0,mcp:void 0,loadRelatedQuesions:!0,stream:!1};let ve,X;const wt=new Set;function wn(n){ve!==n&&(ve=n,X=void 0,wt.clear())}function pr(){if(!X)return;const{pluginCode:n,table:e}=X,t=exports.configuration.plugins[n],i=e[n];if(!(!t||t.shell!==i.shell))return n}function fi(n,e){return(n==null?void 0:n.pluginCode)||Nn[e]}function mr(){var o,c;const n=(o=exports.configuration.businessPlugins)!=null?o:{},e=(c=exports.configuration.builtinPlugins)==null?void 0:c.localFiles,t=[],i=v({},n);if(!!!(e!=null&&e.enabled))return exports.configuration.plugins=i,t;if(!ve)return t.push("[BuiltinTools] 内置工具依赖已启用的本地工作区。工具未注册。"),exports.configuration.plugins=i,t;const r=e!=null&&e.enabled?fi(e,exports.configuration.env):void 0;return r?n[r]?t.push(`[BuiltinTools] 业务插件中已存在 pluginCode「${r}」,已保留业务插件,内置工具未注册。`):(((X==null?void 0:X.workspace)!==ve||X.pluginCode!==r)&&(X={workspace:ve,pluginCode:r,table:hr({pluginCode:r,workspace:ve})}),i[r]=X.table[r]):t.push(`[BuiltinTools] 当前环境(env: ${exports.configuration.env})没有默认的内置工具插件编码,请配置 builtinPlugins.localFiles.pluginCode。内置工具未注册。`),exports.configuration.plugins=i,t}function vt(){return mr().filter(n=>!wt.has(n)).map(n=>(wt.add(n),console.error(n),new Error(n)))}function _t(n,e={}){var t,i,s;U.debug=(n==null?void 0:n.debug)||!1,exports.configuration=E(v(v({},exports.configuration),n),{apiRoot:(n==null?void 0:n.apiRoot)||exports.configuration.apiRoot||(n!=null&&n.env?ui[n.env||"prod"]:exports.configuration.apiRoot),businessPlugins:(i=(t=n==null?void 0:n.plugins)!=null?t:exports.configuration.businessPlugins)!=null?i:{},builtinPlugins:(s=n==null?void 0:n.builtinPlugins)!=null?s:exports.configuration.builtinPlugins}),e.refreshBuiltinPlugins!==!1&&vt(),U.debug&&fr.log("updated",exports.configuration)}const Xe=n=>JSON.parse(Oi.decode(n.split(".")[1])),pi=n=>{const e=Xe(n).exp;return new Date().valueOf()/1e3>=e},gr=n=>n==null?void 0:n.replace(/[\r\n]+/gm,""),yr=n=>n.replace(/\\|\\/g,""),wr=(n,e,t,i)=>{if(n!==!0)return null;const s=(e==null?void 0:e.includeUserQuestion)===!0,o=(e==null?void 0:e.includeAiAnswer)===!0||!s,c=[];return s&&c.push(`问题:${i}`),o&&c.push(`回答:${t}`),c.join(`
|
|
366
|
+
`)};function mi(n,e,t){return new x.CVForceApi(gi(n,"/data/v1",e,t),yi(t))}function vr(n,e,t){return new x.AIShopApi(gi(n,"/aishop",e,t),yi(t))}function gi(n,e,t,i){const s=o=>{var c;return t&&(pi(t)&&i(403,"aiotToken is timeout"),o.headers=(c=o.headers)!=null?c:{},o.headers=E(v({},o.headers),{Authorization:t?`Bearer ${t}`:""})),o};function r(o,c=!0){const a=`${n}${o}`,l=$i.create({baseURL:a});return c&&l.interceptors.request.use(s),l}return r(e)}function yi(n){return{onHttpStatusError:(i,s)=>{i===401&&n(i,"aiotToken is invalid")},onAppStatusError:(i,s)=>{i!==10001&&i!==10215&&n(i,s)}}}const _r=20*1024*1024,wi=/^[A-Za-z0-9._-]+$/;function ot(n){const e=n==null?void 0:n.skills;return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"):[]}function br(n){if(!n)return!1;try{return!pi(n)}catch(e){return!1}}function vn(n){if(!(typeof n.skillId!="string"||!wi.test(n.skillId))&&!(typeof n.name!="string"||!n.name||/[\\/\0]/.test(n.name)||n.name==="."||n.name==="..")&&!(typeof n.version!="number"||!Number.isInteger(n.version)||n.version<1))return{skillId:n.skillId,name:n.name,version:n.version}}function Sr(n){return Array.isArray(n)?n.flatMap(e=>{if(!e||typeof e!="object")return[];const t=e;return typeof t.skillId!="string"||typeof t.name!="string"||typeof t.version!="number"?[]:[{skillId:t.skillId,name:t.name,version:t.version}]}):[]}class Er{constructor(e){y(this,"inflight",new Map);y(this,"busy",new Set);this.options=e}sync(){return this.reconcile().catch(()=>{})}read(e,t,i){return h(this,null,function*(){const s=yield this.prepare(e,i);return this.requireSandbox().skillRead(this.options.applicationId(),s.skillId,s.version,t,i)})}target(e,t){return h(this,null,function*(){const i=yield this.prepare(e,t);return{applicationId:this.options.applicationId(),skillId:i.skillId,version:i.version,name:i.name}})}track(e,t){const i=`${e}/${t}`;this.busy.add(i);let s=!1;return()=>{s||(s=!0,this.busy.delete(i),this.prune().catch(()=>{}))}}requireSandbox(){const e=this.options.getSandbox();if(!e)throw new m(p.NotImplemented,"当前环境不能加载平台技能,需要端侧宿主。");return e}prepare(e,t){return h(this,null,function*(){const i=this.bound(e);if(!i)throw new m(p.NotFound,"技能或资源不存在。");return yield this.ensure(i,t),i})}bound(e){if(!wi.test(this.options.applicationId()))return;const t=ot({skills:this.options.getSkills()}).find(i=>i.name===e);return t?vn(t):void 0}reconcile(){return h(this,null,function*(){if(!this.options.getSandbox())return;const t=ot({skills:this.options.getSkills()}).flatMap(i=>{const s=vn(i);return s?[s]:[]});yield Promise.all(t.map(i=>this.ensure(i).catch(()=>{}))),yield this.prune()})}ensure(e,t){return h(this,null,function*(){const i=`${this.options.applicationId()}/${e.skillId}/${e.version}`,s=this.inflight.get(i);if(s)return s;const r=this.installIfNeeded(e,t).finally(()=>{this.inflight.get(i)===r&&this.inflight.delete(i)});return this.inflight.set(i,r),r})}installIfNeeded(e,t){return h(this,null,function*(){var a;const i=this.requireSandbox();if(i.ready&&(yield this.alreadyInstalled(i,e,t)))return;const s=this.options.getToken();if(!br(s))throw new m(p.Forbidden,"技能下载令牌不可用。");const r=this.options.apiRoot().replace(/\/$/,""),o=yield((a=this.options.fetch)!=null?a:fetch)(`${r}/skill/v1/skills/${encodeURIComponent(e.skillId)}/versions/${e.version}/download`,{headers:{Authorization:`Bearer ${s}`},signal:t});if(!o.ok)throw new m(p.BadRequest,`技能下载失败(${o.status})。`);const c=new Uint8Array(yield o.arrayBuffer());if(c.byteLength>_r)throw new m(p.BadRequest,"技能压缩包超过 20 MB。");yield this.waitReady(i,t),!(yield this.alreadyInstalled(i,e,t))&&(yield i.installSkill({applicationId:this.options.applicationId(),skillId:e.skillId,version:e.version,name:e.name},c,t))})}alreadyInstalled(e,t,i){return h(this,null,function*(){return Sr(yield e.skillStatus(this.options.applicationId(),i)).some(r=>r.skillId===t.skillId&&r.version===t.version&&r.name===t.name)})}prune(){return h(this,null,function*(){const e=this.options.getSandbox();if(!(e!=null&&e.ready))return;const t=ot({skills:this.options.getSkills()}).flatMap(s=>typeof s.skillId!="string"||typeof s.version!="number"||s.version<1?[]:[{skillId:s.skillId,version:s.version}]),i=[...this.busy].map(s=>{const[r,o]=s.split("/");return{skillId:r,version:Number(o)}});yield e.skillPrune(this.options.applicationId(),t,i)})}waitReady(e,t){return h(this,null,function*(){e.ready||(yield new Promise((i,s)=>{const r=setInterval(()=>{if(t!=null&&t.aborted){clearInterval(r),s(new m(p.Cancelled,"已取消。"));return}e.ready&&(clearInterval(r),i())},50)}))})}}function Ir(n){if(!n||typeof n!="object")return;const e=n;return{state:e.state,url:typeof e.url=="string"?e.url:void 0,token:typeof e.token=="string"?e.token:void 0,protocol:typeof e.protocol=="number"?e.protocol:void 0,exitCode:typeof e.exitCode=="number"?e.exitCode:void 0,detail:typeof e.detail=="string"?e.detail:void 0,message:typeof e.message=="string"?e.message:void 0,reason:typeof e.reason=="string"?e.reason:void 0}}let ie;function kr(n){ie==null||ie(),ie=void 0;const e=qi();if(!e)return()=>{};const t=new Je(e),i=r=>{const o=Ui(r.data);if(o){if(o.type==="workspace"){const c=o.granted===!0,a=typeof o.displayName=="string"?o.displayName:"";t.setCapabilities(o.capabilities,{version:o.sandboxVersion}),t.applySandbox(Ir(o.sandbox)),c?(t.displayName=a||"工程目录",(n.status!=="granted"||n.displayName!==t.displayName)&&n.attachAdapter(t,t.displayName)):n.status==="granted"&&n.clear();return}if(o.type==="fs-changed"){const c=Array.isArray(o.paths)?o.paths.filter(a=>typeof a=="string"):[];n.notifyFilesChanged(c);return}}};e.addEventListener("message",i),e.postMessage({channel:Rt,type:"hello"});const s=()=>{e.removeEventListener("message",i),ie===s&&(ie=void 0)};return ie=s,s}const se=new U("[EventBus] ");class Ut{constructor(e=!1){y(this,"eventListenerMap",{});e&&se.disable()}getEventListenerMap(){return v({},this.eventListenerMap)}on(e,t,i=!1){this.eventListenerMap[e]||(this.eventListenerMap[e]=[]),i?this.eventListenerMap[e].push({fn:t,once:!0}):this.eventListenerMap[e].push(t),se.log(`add event ${e} listener ${i?", call once":""}`)}once(e,t){this.on(e,t,!0)}off(e,t){if(this.eventListenerMap[e]){const i=this.eventListenerMap[e].findIndex(s=>{if(typeof s=="function"&&t===s)return!0;if(s=s,s.fn===t)return!0});i<0?se.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(i,1),se.log(`remove event ${e} listener`))}else se.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){se.log(`event ${e} listeners is empty`);return}const i=[];for(let s=0;s<this.eventListenerMap[e].length;s++){const r=this.eventListenerMap[e][s];typeof r=="function"?r(t):i.push(r)}i.forEach(s=>{s&&(s.fn(t),this.off(e,s.fn))}),se.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const xr="路径必须是工作区内的相对路径,不能包含 ..、绝对路径或盘符。";function Pe(){return new m(p.Forbidden,xr,{reason:"path_outside_workspace"})}function Ar(n){if(n!==be)throw new m(p.Forbidden,`未知的工作区 grantId,当前仅支持 ${be}。`,{reason:"path_outside_workspace"})}function K(n,{allowRoot:e=!1,field:t="path"}={}){if(n==null){if(e)return"";throw new m(p.BadRequest,`缺少参数 ${t}。`)}if(typeof n!="string")throw new m(p.BadRequest,`参数 ${t} 必须是字符串。`);if(n.includes("\0")||/%(2e|2f|5c|00)/i.test(n))throw Pe();const i=n.normalize("NFC").replace(/\\/g,"/").trim();if(i.startsWith("/")||/^[a-zA-Z]:/.test(i))throw Pe();const s=[];for(const o of i.split("/"))if(!(o===""||o===".")){if(o==="..")throw Pe();s.push(o)}const r=s.join("/");if(!r&&!e)throw new m(p.BadRequest,`参数 ${t} 不能指向工作区根目录。`);return r}function P(n){return n?n.split("/"):[]}function Tr(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}function vi(n,e){return n?`${n}/${e}`:e}function pe(n,e){return!!n&&typeof n=="object"&&n.name===e}class _i{constructor(e){this.root=e}get displayName(){return this.root.name}resolveDirectory(e,t=!1){return h(this,null,function*(){let i=this.root;for(const s of e)i=yield i.getDirectoryHandle(s,{create:t});return i})}resolveFile(e){return h(this,null,function*(){const t=P(e),i=t.pop();if(!i)throw S("TypeMismatchError");return(yield this.resolveDirectory(t)).getFileHandle(i)})}stat(e){return h(this,null,function*(){const t=P(e),i=t.pop();if(!i)return{name:this.root.name,kind:"directory"};const s=yield this.resolveDirectory(t);try{const r=yield(yield s.getFileHandle(i)).getFile();return{name:i,kind:"file",size:r.size,lastModified:r.lastModified}}catch(r){if(!pe(r,"TypeMismatchError"))throw r;return yield s.getDirectoryHandle(i),{name:i,kind:"directory"}}})}listEntries(e,t){return h(this,null,function*(){const i=yield this.resolveDirectory(P(e)),s=[];try{for(var r=W(i.values()),o,c,a;o=!(c=yield r.next()).done;o=!1){const l=c.value;if(N(t),l.kind==="directory")s.push({name:l.name,kind:"directory"});else try{const d=yield l.getFile();s.push({name:l.name,kind:"file",size:d.size,lastModified:d.lastModified})}catch(d){if(pe(d,"NotAllowedError"))throw d;s.push({name:l.name,kind:"file"})}}}catch(c){a=[c]}finally{try{o&&(c=r.return)&&(yield c.call(r))}finally{if(a)throw a[0]}}return s})}readFile(e){return h(this,null,function*(){return(yield this.resolveFile(e)).getFile()})}writeFile(s,r){return h(this,arguments,function*(e,t,i={}){const o=P(e),c=o.pop();if(!c)throw S("TypeMismatchError");const a=yield this.resolveDirectory(o,i.createDirectories);let l=!0;try{yield a.getFileHandle(c)}catch(b){if(!pe(b,"NotFoundError"))throw b;l=!1}const d=yield a.getFileHandle(c,{create:!0});let u;try{u=yield d.createWritable();try{for(var f=W(Tt(t)),g,_,w;g=!(_=yield f.next()).done;g=!1){const b=_.value;N(i.signal),yield u.write(b)}}catch(_){w=[_]}finally{try{g&&(_=f.return)&&(yield _.call(f))}finally{if(w)throw w[0]}}N(i.signal),yield u.close()}catch(b){throw yield u==null?void 0:u.abort().catch(()=>{}),l||(yield a.removeEntry(c).catch(()=>{})),b}})}createDirectory(e){return h(this,null,function*(){yield this.resolveDirectory(P(e),!0)})}remove(i){return h(this,arguments,function*(e,t={}){const s=P(e),r=s.pop();if(!r)throw S("InvalidModificationError");yield(yield this.resolveDirectory(s)).removeEntry(r,{recursive:t.recursive===!0})})}move(e,t){return h(this,null,function*(){const i=P(e),s=P(t),r=i.pop(),o=s.pop();if(!r||!o)throw S("InvalidModificationError");const c=yield this.resolveDirectory(i),a=yield _n(c,r),l=yield this.resolveDirectory(s);if(Xn(e,t))throw S("InvalidModificationError");let d;try{d=yield _n(l,o)}catch(u){if(!pe(u,"NotFoundError"))throw u}if(d&&(d.kind==="directory"||a.kind==="directory"))throw S("InvalidModificationError");if(!d&&typeof a.move=="function")try{yield a.move(l,o);return}catch(u){if(!pe(u,"NotSupportedError")&&!(u instanceof TypeError))throw u}yield bi(a,l,o),yield c.removeEntry(r,{recursive:!0})})}}function _n(n,e){return h(this,null,function*(){try{return yield n.getFileHandle(e)}catch(t){if(!pe(t,"TypeMismatchError"))throw t;return n.getDirectoryHandle(e)}})}function bi(n,e,t){return h(this,null,function*(){if(n.kind==="file"){const a=yield n.getFile(),l=yield(yield e.getFileHandle(t,{create:!0})).createWritable();try{yield l.write(a),yield l.close()}catch(d){throw yield l.abort().catch(()=>{}),d}return}const i=yield e.getDirectoryHandle(t,{create:!0});try{for(var s=W(n.values()),r,o,c;r=!(o=yield s.next()).done;r=!1){const a=o.value;yield bi(a,i,a.name)}}catch(o){c=[o]}finally{try{r&&(o=s.return)&&(yield o.call(s))}finally{if(c)throw c[0]}}})}function Rr(){if(typeof window=="undefined")return;const n=window.showDirectoryPicker;return typeof n=="function"?n.bind(window):void 0}const Lr=/^[a-z0-9-]+(\.[a-z0-9-]+)+$/;function Mr(n){if(typeof n!="string")return null;const e=n.trim().toLowerCase().replace(/^\*?\./,"").replace(/\.$/,"");return!Lr.test(e)||Si(e)?null:e}function Si(n){return n.startsWith("[")||n.includes(":")?!0:/^[0-9.]+$/.test(n)||/^0x[0-9a-f.]+$/i.test(n)}function Ht(n=[]){const e=new Set(qn);for(const t of n){const i=Mr(t);i&&e.add(i)}return Array.from(e)}function Cr(n,e){return bt(n,Ht(e))}function bt(n,e){let t;try{t=new URL(n)}catch(s){return!1}if(t.protocol!=="https:"||t.username||t.password)return!1;const i=t.hostname.toLowerCase().replace(/\.$/,"");return!i||Si(i)||i==="localhost"||i.endsWith(".localhost")?!1:e.some(s=>i===s||i.endsWith(`.${s}`))}function Fr(n={}){const e=v({},je);return Object.keys(je).forEach(t=>{const i=n[t];typeof i=="number"&&Number.isFinite(i)&&i>0&&(e[t]=Math.min(i,je[t]))}),e}function me(){return new m(p.Internal,"平台文件服务请求失败,请稍后重试。")}function qt(n,e=()=>{}){const t=()=>{const r=n();if(!r)throw me();return r},i=()=>{const r=e();if(!r)throw me();return r};return{upload(r,o,c){return h(this,null,function*(){if(!o.sessionId)throw new m(p.BadRequest,"当前没有可用的会话,无法上传文件。");try{c==null||c({loaded:0,total:r.size});const a=yield i().postFile(r,(l,d)=>c==null?void 0:c({loaded:l,total:d}));if(!(a!=null&&a.id)||!a.url)throw me();return c==null||c({loaded:r.size,total:r.size}),{fileId:a.id,url:a.url}}catch(a){throw a instanceof m?a:me()}})},resolveDownload(r,o){return h(this,null,function*(){if(r.type==="platformFile")return Nr(i(),r.fileId);if(!o.sessionId)throw new m(p.BadRequest,"当前没有可用的会话,无法下载会话文件。");let c;try{c=yield t().getApplicationIdSessionFile(o.applicationId,o.sessionId,r.fileId)}catch(a){throw me()}if(!(c!=null&&c.url))throw new m(p.NotFound,"会话文件不存在或暂不可下载。");return{url:c.url,name:c.name,size:c.size}})}}}function Nr(n,e){return h(this,null,function*(){let t;try{t=yield n.getFile(e)}catch(s){throw me()}if(!(t!=null&&t.url))throw new m(p.NotFound,"平台文件不存在或暂不可下载。");let i;try{i=new URL(t.url)}catch(s){throw new m(p.Internal,"平台返回的下载地址无效。")}if(i.protocol!=="https:")throw new m(p.Internal,"平台返回的下载地址无效。");return{url:t.url,size:t.bytes}})}const Or="glodon-aiot-local-workspace",at="kv";function Wt(){const n=new Map;return{get(t){return h(this,null,function*(){return n.get(t)})},set(t,i){return h(this,null,function*(){n.set(t,i)})},delete(t){return h(this,null,function*(){n.delete(t)})}}}function $r(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}function Ei(n=Or){if(typeof indexedDB=="undefined")return Wt();let e;const t=()=>(e||(e=new Promise((r,o)=>{const c=indexedDB.open(n,1);c.onupgradeneeded=()=>{c.result.createObjectStore(at)},c.onsuccess=()=>r(c.result),c.onerror=()=>{e=void 0,o(c.error)}})),e),i=(r,o)=>h(this,null,function*(){const c=yield t();return $r(o(c.transaction(at,r).objectStore(at)))});return{get(r){return h(this,null,function*(){return yield i("readonly",o=>o.get(r))})},set(r,o){return h(this,null,function*(){yield i("readwrite",c=>c.put(o,r))})},delete(r){return h(this,null,function*(){yield i("readwrite",o=>o.delete(r))})}}}function bn(n){if(n!=null&&n.length&&!n.some(e=>!e||e==="."||e===".."||e.includes("/")||e.includes("\\")))return n.length===1?"":n.slice(0,-1).join("/")}function Dr(n,e){const t=globalThis.FileSystemObserver;if(typeof t!="function")return()=>{};let i;try{i=new t(s=>{const r=new Set;for(const o of s){if(o.type==="errored"){e();return}const c=bn(o.relativePathComponents),a=bn(o.relativePathMovedFrom);if(c===void 0&&a===void 0){e();return}c!==void 0&&r.add(c),a!==void 0&&r.add(a)}r.size&&e([...r])})}catch(s){return()=>{}}return i.observe(n,{recursive:!0}).catch(()=>i.disconnect()),()=>i.disconnect()}const Be={mode:"readwrite"};function Pr(n){const e=n.replace(/\\/g,"/").trim().replace(/^\.\/+/,"").replace(/\/+$/,"");if(!e||e===".")return"";if(e.startsWith("/")||e.includes(":")||e.includes("\0"))return;const t=e.split("/");if(!t.some(i=>!i||i==="."||i===".."))return t.join("/")}function Br(n){return!!n&&typeof n=="object"&&n.name==="AbortError"}class Ii{constructor(e){y(this,"applicationId");y(this,"limits");y(this,"sensitive");y(this,"downloadUrlAllowlist");y(this,"allowWorkspaceWideTextSearch");y(this,"transfer");y(this,"fetch");y(this,"commandRunner");y(this,"platformSkills");y(this,"browserRuntime");y(this,"store");y(this,"picker");y(this,"event",new Ut(!0));y(this,"_status");y(this,"_displayName");y(this,"_adapter",null);y(this,"pendingHandle",null);y(this,"approvalHandler");y(this,"activeCalls",0);y(this,"commandRunning",!1);y(this,"inflight",new Set);y(this,"_ready",Promise.resolve());y(this,"stopWatching",()=>{});y(this,"pendingChangePaths",new Set);y(this,"changeTimer");y(this,"refreshAllVisible",!1);var o,c,a,l,d,u,f,g,_,w;const t=(o=e.config)!=null?o:{};this.applicationId=e.applicationId,this.store=(c=e.store)!=null?c:Wt(),this.picker=e.picker===null?void 0:(a=e.picker)!=null?a:Rr(),this.limits=Fr(t.limits),this.sensitive=new ni(t.sensitiveRulesAppend),this.downloadUrlAllowlist=Ht(t.downloadUrlAllowlistAppend),this.allowWorkspaceWideTextSearch=!!t.allowWorkspaceWideTextSearch,this.approvalHandler=t.onApprovalRequired;const i=(l=e.transfer)!=null?l:qt(()=>{});this.transfer={upload:(u=(d=t.transfer)==null?void 0:d.upload)!=null?u:i.upload,resolveDownload:(g=(f=t.transfer)==null?void 0:f.resolveDownload)!=null?g:i.resolveDownload};const s=(_=e.fetch)!=null?_:typeof fetch=="function"?fetch:void 0;this.fetch=s?s.bind(globalThis):()=>Promise.reject(new Error("fetch is not available")),this.commandRunner=e.commandRunner;const r=(w=t.commandRuntime)==null?void 0:w.browser;this.browserRuntime={enabled:(r==null?void 0:r.enabled)!==!1,bashModuleURL:r==null?void 0:r.bashModuleURL,pyodideIndexURL:r==null?void 0:r.pyodideIndexURL},this._status=this.picker?"none":"unsupported"}get status(){return this._status}get displayName(){return this._displayName}get isSupported(){return!!this.picker}get ready(){return this._ready}get adapter(){return this._status==="granted"?this._adapter:null}get handleKey(){return`workspace:${this.applicationId}`}get disclosureKey(){return`disclosure:${this.applicationId}`}setStatus(e,t=this._displayName){e===this._status&&t===this._displayName||(this._status=e,this._displayName=t,this.emit("workspace:changed",{status:e,displayName:t}))}attachHandle(e){this.cancelFilesChanged(),this.pendingHandle=e,this._adapter=new _i(e),this.setStatus("granted",e.name),this.unwatchDirectory(),this.stopWatching=Dr(e,t=>this.notifyFilesChanged(t))}pick(){if(!this.picker)return Promise.resolve(!1);let e;try{e=this.picker({mode:"readwrite"})}catch(t){return Promise.reject(t)}return e.then(t=>h(this,null,function*(){var s,r;this.cancelAll();const i=(r=yield(s=t.queryPermission)==null?void 0:s.call(t,Be))!=null?r:"granted";return yield this.store.set(this.handleKey,{handle:t,displayName:t.name,savedAt:Date.now()}).catch(()=>{}),i==="denied"?(this.pendingHandle=t,this._adapter=null,this.setStatus("denied",t.name),!1):(this.attachHandle(t),!0)}),t=>{if(Br(t))return!1;throw t})}restore(){return this._ready=this.doRestore(),this._ready}doRestore(){return h(this,null,function*(){var i,s,r;if(!this.picker){this._adapter||this.setStatus("unsupported");return}let e;try{e=yield this.store.get(this.handleKey)}catch(o){e=void 0}if(!(e!=null&&e.handle)){this.pendingHandle=null,this._adapter=null,this.setStatus("none",void 0);return}let t;try{t=(r=yield(s=(i=e.handle).queryPermission)==null?void 0:s.call(i,Be))!=null?r:"prompt"}catch(o){t="prompt"}t==="granted"?this.attachHandle(e.handle):(this.pendingHandle=e.handle,this._adapter=null,this.setStatus(t==="denied"?"denied":"prompt",e.displayName))})}requestPermission(){const e=this.pendingHandle;if(!(e!=null&&e.requestPermission))return Promise.resolve(!1);let t;try{t=e.requestPermission(Be)}catch(i){return Promise.reject(i)}return t.then(i=>i==="granted"?(this.attachHandle(e),!0):(this._adapter=null,this.setStatus(i==="denied"?"denied":"prompt",e.name),!1))}clear(){return h(this,null,function*(){this.cancelAll(),this.cancelFilesChanged(),this.unwatchDirectory(),this.pendingHandle=null,this._adapter=null,this.setStatus(this.picker?"none":"unsupported",void 0),yield this.store.delete(this.handleKey).catch(()=>{})})}attachAdapter(e,t=e.displayName){this.cancelAll(),this.cancelFilesChanged(),this.unwatchDirectory(),this.pendingHandle=null,this._adapter=e,this.setStatus("granted",t)}notifyFilesChanged(e){if(this._status==="granted"){if(!e||e.length===0)this.refreshAllVisible=!0;else for(const t of e){const i=Pr(t);i===void 0?this.refreshAllVisible=!0:this.pendingChangePaths.add(i)}clearTimeout(this.changeTimer),this.changeTimer=setTimeout(()=>this.flushFilesChanged(),150)}}handlePermissionLost(){return h(this,null,function*(){const e=this.pendingHandle;if(!(e!=null&&e.queryPermission))return;const t=yield e.queryPermission(Be).catch(()=>"prompt");t!=="granted"&&(this.cancelAll(),this.cancelFilesChanged(),this.unwatchDirectory(),this._adapter=null,this.setStatus(t==="denied"?"denied":"prompt",e.name))})}isDisclosureAcknowledged(){return h(this,null,function*(){try{return!!(yield this.store.get(this.disclosureKey))}catch(e){return!1}})}acknowledgeDisclosure(){return h(this,null,function*(){yield this.store.set(this.disclosureKey,!0).catch(()=>{})})}setApprovalHandler(e){this.approvalHandler=e}get hasApprovalHandler(){return!!this.approvalHandler}getApprovalHandler(){return this.approvalHandler}acquireSlot(){if(this.activeCalls>=this.limits.maxConcurrentRequests)return null;this.activeCalls++;let e=!1;return()=>{e||(e=!0,this.activeCalls--)}}acquireCommand(){if(this.commandRunning)return null;this.commandRunning=!0;let e=!1;return()=>{e||(e=!0,this.commandRunning=!1)}}track(e){return this.inflight.add(e),()=>this.inflight.delete(e)}cancelAll(){const e=Array.from(this.inflight);this.inflight.clear(),e.forEach(t=>t.abort())}handshake(){const e=Object.fromEntries(It.map(t=>[t,!0]));return{protocolVersion:"1.0",capabilities:E(v({},e),{cancellation:!0,atomicWrite:!0}),limits:v({},this.limits)}}on(e,t){return this.event.on(e,t),()=>this.off(e,t)}off(e,t){this.event.off(e,t)}unwatchDirectory(){const e=this.stopWatching;this.stopWatching=()=>{},e()}cancelFilesChanged(){clearTimeout(this.changeTimer),this.changeTimer=void 0,this.pendingChangePaths.clear(),this.refreshAllVisible=!1}flushFilesChanged(){this.changeTimer=void 0;const e=this.refreshAllVisible,t=[...this.pendingChangePaths].sort((i,s)=>i<s?-1:i>s?1:0);this.pendingChangePaths.clear(),this.refreshAllVisible=!1,this._status==="granted"&&this.emit("files:changed",{paths:e?[]:t})}emit(e,t){try{this.event.emit(e,t)}catch(i){console.error(`[LocalWorkspace] ${e} listener failed`,i)}}}var ge=(n=>(n[n.Normal=0]="Normal",n[n.Debug=1]="Debug",n))(ge||{});const Sn=100,D=new U("[Session] ");var Re=(n=>(n.DataRequestFailed="data request error",n.SocketConnectionFailed="socket error",n.IdUndefined="session id is not defined",n.SendingEmptyContent="failed at sending empty content",n.Frozen="session is frozen",n.UserModeError="failed at setting socket user mode",n.Inactive="session is inactive",n))(Re||{});class zt{constructor(e,t="",i,s,r,o){y(this,"_id");y(this,"_frozen",!1);y(this,"inactivating",!1);y(this,"_ready",!1);y(this,"event",new Ut);y(this,"_applicationId");y(this,"_application",null);y(this,"data",null);y(this,"client",null);y(this,"messages",[]);y(this,"_loadingMessages",!1);y(this,"_loadingMessagesSize",10);y(this,"cvforceApi");y(this,"socket",null);y(this,"_promptVariables",[]);y(this,"active",!1);y(this,"activing",!1);y(this,"_stopAnswer",!1);y(this,"_dataLoading",!1);y(this,"_dataLoaded",!1);y(this,"_mcpServers",null);this.token=e,this.lazyload=s,this.client=o||null,this._applicationId=Xe(e).rid||exports.configuration.applicationId,this.cvforceApi=this.getService(),r&&(this._application=r),this.event.emit("init",{applicationId:this._applicationId,sessionId:t}),this.loadApplicationInfo().then(()=>{var c;if(t)this._id=t,this.event.emit("data:loading"),i?(this.data=i,s||(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(a=>h(this,null,function*(){this.data=a,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>h(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data)})))):(this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,t).then(a=>h(this,null,function*(){this.data=a,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>h(this,null,function*(){this.messages=[],yield this.fetchMessages(),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoading=!1,this._dataLoaded=!0})));else{const a=(i==null?void 0:i.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:a}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:a,netOpen:i==null?void 0:i.netOpen,knowledgeIdList:(c=i==null?void 0:i.knowledges)==null?void 0:c.map(l=>l.id),applicationId:this._applicationId}).then(l=>h(this,null,function*(){var d;this._id=l.id,this.data=E(v({},l),{knowledges:i==null?void 0:i.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id);try{yield(()=>h(this,null,function*(){if(i!=null&&i.knowledges)return this.setKnowledges((i==null?void 0:i.knowledges)||void 0)}))()}catch(u){D.error(u)}yield(()=>{if(i!=null&&i.promptVariables){const u=this._promptVariables.map(f=>{var _,w;const g=((w=(_=i.promptVariables)==null?void 0:_.find(b=>b.key===f.key&&b.type===f.type))==null?void 0:w.value)||"";return E(v({},f),{value:g})}).sort((f,g)=>f.key.localeCompare(g.key));return this.setPromptVariables(u||[])}else return})(),this.event.emit("data:created",this.data),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),((d=this.application)==null?void 0:d.type)!==x.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}fetchData(){return h(this,null,function*(){if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.getSession(this.applicationId,this.data.id).then(e=>h(this,null,function*(){return this.data=e,this.event.emit("data:updated",this.data),e}))})}get id(){var e;return this._id||((e=this.data)==null?void 0:e.id)||""}get applicationId(){return this._applicationId}get application(){return this._application}set application(e){this._application=e}loadApplicationInfo(){if(this._application)return Promise.resolve(this._application);if(this._applicationId&&!this._application)return this.event.emit("application:data:loading"),this.cvforceApi.getApplicationId(this._applicationId).then(e=>(this._application=e,this.event.emit("application:data:loaded",e),e));throw Error("application id is not defined")}get ready(){return this._ready}get frozen(){return this._frozen}set frozen(e){e===!1&&this.inactivating&&this.socket&&(this.socket.disconnect(),this.socket=null,this.event.emit("inactivated")),this._frozen=e,this.event.emit("frozen",e)}get knowledges(){if(!this.data)throw Error("session data is not loaded");return this.data.knowledges||void 0}setKnowledges(e){return h(this,null,function*(){if(!this.data)throw Error("session data is not loaded");if((e||[]).some(s=>Array.isArray(s.fileIds)&&s.fileIds.length===0))throw Error("fileIds cannot be an empty array");if((e||[]).reduce((s,r)=>{var c,a;const o=(a=(c=r.fileIds)==null?void 0:c.length)!=null?a:0;return s+(o>0?o:1)},0)>Sn)throw Error(`knowledges and fileIds total count cannot exceed ${Sn}`);return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(t=>t.status===x.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>!(e.type===x.PromptVariableType.User&&e.key==="query")&&!(e.type===x.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return h(this,null,function*(){const t=e==null?void 0:e.map(r=>r.type?r:E(v({},r),{type:"instruction"})),i=this._promptVariables.map(r=>{var c;const o=((c=t==null?void 0:t.find(a=>a.key===r.key&&a.type===r.type))==null?void 0:c.value)||r.value;return E(v({},r),{value:o})}).sort((r,o)=>r.key.localeCompare(o.key));if(!(yield Promise.all(i.filter(r=>!(r.type===x.PromptVariableType.User&&r.key==="query")&&!(r.type===x.PromptVariableType.System&&r.key==="datetime")).map(r=>{if(!this.data)throw Error("session data is not loaded");if(!(!r.id||!r.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,r.id,{value:r.value})})).then(()=>!0).catch(r=>!1)))return!1;if(!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return h(this,null,function*(){var t,i,s;if(D.log("setNetOpen:",e),D.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((i=this._application)==null?void 0:i.type)===x.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((s=this._application)==null?void 0:s.arrange[0].enableNetOpen)===!1){console.warn("This Application is disabled to change netOpen.");return}if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{netOpen:e?1:2}),this.data.netOpen=e,D.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return mi(exports.configuration.apiRoot,this.token,(e,t)=>{const i=new Error("data request error",{cause:{status:e,message:t}});D.error(i),this.event.emit("error",i)})}addEventListener(e,t,i=!1){if(typeof t!="function")throw Error("event listener is not a function");if(i){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}fetchMessages(){return h(this,arguments,function*(e={}){var i,s;const t={pageSize:this._loadingMessagesSize};if(this._id){e=v(v({},t),e),this.event.emit("history:loading"),D.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),D.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),o=r.map((a,l)=>{var f,g;let d=[],u;return typeof((f=a.agentHistoryList)==null?void 0:f.agentList)=="string"&&(d=JSON.parse(a.agentHistoryList.agentList).reduce((w,b)=>(w[b.data.step-1]||(w[b.data.step-1]=[]),w[b.data.step-1].push(b),w),[])),l===r.length-1&&(u=(g=this.data)==null?void 0:g.lastRelatedQuestion),E(v({},a),{actions:d,relatedQuesion:u,fromHistory:!0})});if(!e.endTime&&!e.startTime){const a=this.messages[this.messages.length-1];a&&!a.relatedQuesion&&(a.relatedQuesion=(i=this.data)==null?void 0:i.lastRelatedQuestion),this.messages=[...o,...this.messages]}else if(e.endTime&&!e.startTime){const a=this.messages.findIndex(l=>l.ts===e.endTime);this.messages.splice(0,a+1),this.messages=[...o,...this.messages]}else if(!e.endTime&&e.startTime){const a=this.messages.findLastIndex(l=>l.ts===e.endTime);this.messages.splice(a,this.messages.length-a-1),this.messages=[...this.messages,...o]}else{const a=this.messages.findIndex(d=>d.ts===e.endTime),l=this.messages.findLastIndex(d=>d.ts===e.endTime);this.messages.splice(a,l-a+1,...o)}const c=this.messages[this.messages.length-1];return c&&!c.relatedQuesion&&(c.relatedQuesion=(s=this.data)==null?void 0:s.lastRelatedQuestion),this.event.emit("history:moreloaded",o),D.log("history:loaded",this.messages),this.event.emit("history:loaded",this.messages),this._loadingMessages=!1,o}else{const r=new Error("session id is not defined");return D.error(r),this.event.emit("error",r),!1}})}rename(e){return h(this,null,function*(){if(!this._id)throw Error("session is not created yet");if(e.trim()==="")throw Error("name is empty");return this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{name:e}),D.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return h(this,null,function*(){this.messages.push(e),D.log("history:add",e),this.event.emit("history:add",e),this.event.emit("message:new",e),this.event.emit("message:updated",e)})}reloadSessionInfo(){if(!this._id)throw Error("session is not created yet");return this._dataLoading=!0,this.cvforceApi.getSession(this.applicationId,this._id).then(e=>h(this,null,function*(){if(this.data=e,!this._id)throw Error("session is not created yet");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id),D.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>h(this,null,function*(){return this.messages=[],yield this.fetchMessages(),this._dataLoading=!1,this._dataLoaded=!0,this.event.emit("data:loaded",this.data),this}))}reload(){return h(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return h(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return D.error(e),this.event.emit("error",e),!1}return this.event.emit("data:deleting"),yield this.cvforceApi.delSessionsId(this.applicationId,this.id),this.event.emit("data:deleted"),this.destroy()})}activate(){return h(this,null,function*(){if(this.activing)return new Promise(t=>{this.addEventListener("activated",()=>{t(!0)},!0)});if(!this._id)throw Error("session is not avalible. id is undefined");this.activing=!0;const e=this._id;return this._dataLoading=!0,this._dataLoaded=!1,this.data=yield this.cvforceApi.getSession(this.applicationId,e).then(t=>h(this,null,function*(){return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,e),t})),this.messages.length||(this.messages=[],yield this.fetchMessages()),this.event.emit("data:loaded",this.data),this.event.emit("data:updated",this.data),this._dataLoaded=!0,this._dataLoading=!1,this.inactivating=!1,this.frozen=!0,yield this.prepareConnection(),this.event.emit("activated",this.socket),this.active=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?this._frozen?(e||(this.inactivating=!0),this.activing=!1,!0):(this.socket.close(),this.socket=null,this.event.emit("inactivated"),this.active=!1,this.activing=!1,!0):(this.activing=!1,!0)}resolveEnableTitleSummary(){var t,i,s;const e=(s=(i=(t=this.application)==null?void 0:t.arrange)==null?void 0:i[0])==null?void 0:s.autoGenerateSessionTitle;return typeof e=="boolean"?e:!0}get dataLoaded(){return this._dataLoaded}get messagesLoading(){return this._loadingMessages}send(i){return h(this,arguments,function*(e,t={stream:exports.configuration.stream}){var _;try{this.validateConfigs()}catch(w){console.error(w)}const{stream:s=exports.configuration.stream,referenceFirst:r=!1}=t,o=e.uuid||_e.v4(),c=((_=e.text)==null?void 0:_.trim())||"",a=e.files||[],l=e.fileIds,d=e.imageContent;if(!c&&!a.length&&!(l!=null&&l.length)){const w=new Error("failed at sending empty content");return D.error(w),this.event.emit("error",w),!1}if(!this._id){const w=new Error("session id is not defined");return D.error(w),this.event.emit("error",w),!1}if(this.frozen){const w=new Error("session is frozen");return D.error(w),this.event.emit("error",w),!1}this.frozen=!0,this._stopAnswer=!1;const u={sessionId:this.id,role:2,content:c,messageId:o,reference:[],searchReference:[],messageTime:"",files:a,imageContent:d},f={content:c,stream:s,requestId:o,fileIds:l,referenceFirst:r,imageContent:d};this.pushMessage(u),this.event.emit("question:content",c);const g=w=>h(this,null,function*(){if(w.role!==x.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",g),this._id&&w.content&&w.index&&w.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:w.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:w.content})),yield this.fillMessageReference(w),w.code){case 11915:w.content="请您换个问题问我吧~",w.index=-1,w.isSensitive=!0,w.isLoading=!1,w.sessionId=this._id||"",this.event.emit("message:error",w);break;case 11916:w.content="尊敬的用户您好,让我们换个话题再聊聊吧。",w.index=-1,w.isSensitive=!0,w.isLoading=!1,w.sessionId=this._id||"",this.event.emit("message:error",w);break;case 200:w.index=-1,w.isLoading=!1;break;default:w.content=w.message||"未知错误",w.isLoading=!1,w.index=-1,this.event.emit("message:error",w)}this.getRelatedQuesion(w),w.isLoading=!1;let b=this.messages[this.messages.length-1];if(b&&b.role===x.ChatMessageRole.Robot){const A=v(v({},b),w);this.messages[this.messages.length-1]=A,this.event.emit("message:updated",A)}else this.pushMessage(w);this.frozen=!1});return this.addEventListener("answer:finish",g),this.sendQuestion(f,E(v({},t),{stream:s,referenceFirst:r})),u})}currentUserQuestion(){for(let e=this.messages.length-1;e>=0;e-=1){const t=this.messages[e];if(t.role===x.ChatMessageRole.User)return t.content||""}return""}getRelatedQuesion(e){return h(this,null,function*(){var c,a;if(!e.content||e.isSensitive||e.code!==200)return e;const t=(c=this.application)==null?void 0:c.arrange[0],i=wr(t==null?void 0:t.recommendQuestionOpen,t==null?void 0:t.relatedQuestionApp,e.content,this.currentUserQuestion());if(i===null)return e;this.event.emit("message:relatedQuesion:loading",e);const s=yield this.cvforceApi.postGeneques({content:i}).catch(l=>null);if(!s){const l=[],d=E(v({},e),{relatedQuesion:l,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:l}),this.event.emit("message:updated",d),d}const r=(a=s.content)==null?void 0:a.split("*").map(gr).map(yr).filter(l=>!!l);e.relatedQuesion=r,e.index=-3,e.isLoading=!1;const o=E(v({},e),{relatedQuesion:r,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",o),this.event.emit("message:updated",o),this._id&&this.cvforceApi.patchSessionsId(this._applicationId,this._id,{lastRelatedQuestion:r}),o})}fillMessageReference(e){return h(this,null,function*(){try{const t=yield Promise.all(e.reference.map(i=>this.cvforceApi.getKnowledgeIdFileId(i.knowledgeId,i.docId)));e.reference=e.reference.map((i,s)=>v(v({},i),t[s]))}catch(t){console.error("Failed to fill message reference:",t)}return this.event.emit("message:updated",e),e})}answerAgain(){return h(this,arguments,function*(e={stream:exports.configuration.stream}){const t=this.messages[this.messages.length-1];if(!t)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1;const{stream:i=exports.configuration.stream}=e;let s;t.role!==x.ChatMessageRole.User&&(s=e.oldMessageId||t.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",t),this.event.emit("history:remove",t));const r=this.messages[this.messages.length-1],o={content:r.content,fileIds:r.fileIds,requestId:r.messageId,stream:i,oldMessageId:s},c=a=>h(this,null,function*(){if(a.role===x.ChatMessageRole.Robot&&a.index===-1){switch(this._id&&a.content&&a.index&&a.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:a.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:a.content})),yield this.fillMessageReference(a),a.code){case 11915:a.content="请您换个问题问我吧~",a.index=-1,a.isSensitive=!0,a.isLoading=!1,a.sessionId=this._id||"",this.event.emit("message:error",a);break;case 11916:a.content="尊敬的用户您好,让我们换个话题再聊聊吧。",a.index=-1,a.isSensitive=!0,a.isLoading=!1,a.sessionId=this._id||"",this.event.emit("message:error",a);break;case 200:a.index=-1,a.isLoading=!1;break;default:a.content=a.message||"未知错误",a.isLoading=!1,a.index=-1,this.event.emit("message:error",a)}this.getRelatedQuesion(a),this.removeEventListener("message:content",c),this.frozen=!1}});this.addEventListener("message:content",c),this.sendQuestion(o,E(v({},e),{stream:i}))})}setTop(e){return h(this,null,function*(){if(!this._id)throw Error("session is not avalible. id is undefined");this.data=yield this.cvforceApi.patchSessionsId(this._applicationId,this._id,{top:e}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:top",{top:e})})}suspend(){var i;this.stopAnswer(),this.frozen=!1,this._stopAnswer=!0;let e=this.messages[this.messages.length-1];const t={messageId:_e.v4(),isLoading:!1,index:-2,messageTime:Et(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:x.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const s=e.actions[((i=e.actions)==null?void 0:i.length)-1];if(s){const r=s[s.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:o,pluginCode:c,funcCode:a,funcName:l}=r.data;s.push({data:{pluginName:o,pluginCode:c,funcCode:a,funcName:l,step:r.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:s})}}}e=v(v({},e),t),this.event.emit("message:content",e),this.event.emit("message:updated",e)}else this.pushMessage(t),this.event.emit("message:content",t);return this}handleStreamAnswer(e,t){var o;if(!e.data)return;const i=e.data.type,s=e.data.payload;t.isReplying=!0;const r=()=>{if(!t.searchingStatus){t.searchingStatus="start";return}if(t.searchingStatus==="start"){t.searchingStatus="end";return}};if(i==="error"&&(t.index=-1),i==="beforeSearch"&&r(),i==="searchOver"&&r(),i==="search"&&t.searchReference.push(s),i==="thinking"){t.thinkingStatus="start";const a=s.choices[0];t.reasoningContent=(t.reasoningContent||"")+((o=a.delta.reasoningContent)!=null?o:"")}if(i==="thinkingOver"){t.thinkingStatus="end";const c=s.thinkingSecs;t.thinkingSecs=c}if(i==="text"){const a=s.choices[0];t.content=(t.content||"")+a.delta.content}if(i==="reference"&&(t.reference=s),i==="updateSession"&&s&&this.data&&(this.data=v(v({},this.data),s),this.event.emit("data:updated",this.data)),i==="result"){const c=s.messageId,a=s.llmModel,l=s.messageTime;t.messageId=c,t.llmModel=a,t.messageTime=l}i==="over"?t.index=-1:(t.code=e.code,t.message=e.message)}getArtifacts(){return h(this,null,function*(){var t;if(!this._applicationId||!this._id)throw Error("session is not avalible. id is undefined");const e=yield this.cvforceApi.getSessionArtifacts(this._applicationId,this._id);return(t=e==null?void 0:e.artifacts)!=null?t:[]})}postMessageComment(e){return h(this,null,function*(){if(!this._applicationId||!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.postComments(this._applicationId,this._id,e).then(t=>{const i=this.messages.find(s=>s.messageId===e.messageId);return i&&(i.comment=e,this.event.emit("message:comment",i)),t})})}clear(){if(!this._id)throw Error("session is not avalible. id is undefined");return this.cvforceApi.patchApplicationIdSessionsIdContext(this._applicationId,this._id).then(()=>(this.event.emit("context:clear"),!0))}destroy(){var e;return this._ready=!1,this.event.removeAllListeners(),(e=this.socket)==null||e.disconnect(),this.socket=null,this.event.emit("destroy",{applicationId:this._applicationId,sessionId:this._id}),this._id||""}}const H=new U("[AgentSession] ");function En(n){if(typeof n!="string")return n;const e=n.trim();if(e)try{return JSON.parse(e)}catch(t){return n}}function In(n){return n==null||n===""||typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function jr(n,e){const t=En(n==null?void 0:n.query);if(!In(t))return t;const i=En(e);return In(i)&&t!=null?t:i}class Ur extends zt{constructor(t,i="",s,r,o,c){super(t,i,s,r,o,c);y(this,"inflightCalls",new Set)}prepareConnection(){return new Promise(t=>h(this,null,function*(){this.socket&&t(!0);const i={version:"1.0",stream:JSON.stringify(exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?ge.Debug:ge.Normal},s=new URL(exports.configuration.apiRoot),r=yield Di.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:i,transports:["websocket"]});r.on("connect",()=>{H.log("socket:connect"),this.event.emit("socket:connect"),r.emit("init")}),r.on("disconnect",()=>{H.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),r.on("ready",o=>{if(o.code===200){H.log("ready");const c=exports.configuration.debug?ge.Debug:ge.Normal;c===ge.Debug&&o.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),t(!0)}else{this._ready&&(this._ready=!1);const c=new Error(Re.SocketConnectionFailed);H.error("error",c),this.event.emit("error",c),t(!1)}}),r.on("action",(o,c)=>h(this,null,function*(){var w;if(this._stopAnswer||!this.id)return;const{type:a,data:{runnerIsClient:l,pluginCode:d,funcCode:u,parameters:f,requestBody:g}}=o,_=this.messages[this.messages.length-1];if(!_.messageId)_.actions||(_.actions=[]),_.actions[o.data.step-1]||(_.actions[o.data.step-1]=[]),_.actions[o.data.step-1].push(o),this.event.emit("message:action",{messageId:_.messageId,action:o}),this.event.emit("message:updated",_);else{const b={messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[o]],comment:{isAgree:0},isReplying:!0};this.pushMessage(b),this.event.emit("message:action",{messageId:b.messageId,action:o})}if(this.inactivating){const b=new Error(Re.Inactive);H.warn("error",b),this.event.emit("error",b)}else if(a==="FUNCTION_CALL"&&l){H.log(`calling function ${u} of plugin ${d} with argument:
|
|
367
|
+
${JSON.stringify(f)}`);const b=(w=exports.configuration.plugins)==null?void 0:w[d];if(!b){c({code:404,message:"没有找到插件。"});return}const A=b[u];if(typeof A!="function"){c({code:404,message:"没有找到插件方法。"});return}const I=jr(f,g);this.invokeClientPlugin(A,I,c,{requestId:o.requestId,pluginCode:d,functionCode:u})}})),r.on("answer",o=>{if(!this._stopAnswer)if(o.data.code!==200&&(o.data.index=-1),o.data.stream||o.data.stream===void 0){let c=this.messages[this.messages.length-1];if(c&&c.role===x.ChatMessageRole.Robot)this.handleStreamAnswer(o.data,c),this.messages[this.messages.length-1]=c,this.event.emit("message:content",c),this.event.emit("message:updated",c),c.index===-1&&(c.isReplying=!1,this.event.emit("answer:finish",c));else{const a={content:"",role:x.ChatMessageRole.Robot,reference:[],searchReference:[],messageId:"",sessionId:this.id,messageTime:Et(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""};this.handleStreamAnswer(o.data,a),this.pushMessage(a),this.event.emit("message:content",a),a.index===-1&&(a.isReplying=!1,this.event.emit("answer:finish",a))}}else if(o.data.updateSession&&this.data&&(this.data=v(v({},this.data),o.data.updateSession),this.event.emit("data:updated",this.data)),o.data.index===-1){let c=this.messages[this.messages.length-1];if(c&&!c.messageId)c=v(v({},c),o.data),this.event.emit("message:content",c),this.event.emit("message:updated",c),this.event.emit("answer:finish",c);else{const a=v({messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.data);this.event.emit("message:content",a),this.pushMessage(a),this.event.emit("answer:finish",a)}}else{let c=this.messages[this.messages.length-1];c&&!c.messageId?(c=v(v({},c),o.data),this.messages[this.messages.length-1]=c,this.event.emit("message:content",c),this.event.emit("message:updated",c)):(this.pushMessage(v({messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.data)),this.event.emit("message:content",o.data))}}),r.on("reference",o=>h(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const f=new Error(Re.IdUndefined);H.error(f),this.event.emit("error",f),this.frozen=!1;return}const{type:c,data:a,requestId:l}=o,d=this.messages.findIndex(f=>f.messageId===l&&f.role===x.ChatMessageRole.User);if(d<0)return;const u=d+1;if(u>=this.messages.length){const f={messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0};this.pushMessage(f)}c==="KG"?(this.messages[u]=E(v({},this.messages[u]),{reference:a.knowledgeReference}),yield this.fillMessageReference(this.messages[u]),this.event.emit("message:reference",a.knowledgeReference),this.event.emit("message:updated",this.messages[u])):c==="WEB_SEARCH"&&(this.messages[u]=E(v({},this.messages[u]),{searchReference:a.knowledgeReference}),this.event.emit("message:searchreference",a.searchReference),this.event.emit("message:updated",this.messages[u]))})),this.socket=r,r.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((t,i)=>{if(!this.socket){i("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,s=>{s.code===200?(Object.keys(s.data).forEach(r=>{s.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",s.data[r])}),t(!0)):(console.error("MCP Server 注册失败。",s),i(s))})}):Promise.resolve(!0)}addMcpServers(t){return h(this,null,function*(){return this.ready?this.socket?new Promise((i,s)=>{this.socket&&this.socket.emit("add_mcp_servers",t,r=>{r.code===200?(Object.keys(r.data).forEach(o=>{r.data[o].code!==200&&console.error(o,"MCP Server 注册失败。",r.data[o])}),i(!0)):(console.error("MCP Server 注册失败。",r),s(r))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return h(this,null,function*(){return this.ready?this.socket?new Promise((t,i)=>{this.socket&&this.socket.emit("list_mcp_servers",s=>{s.code===200?t(s.data):i(s)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(t,i){return h(this,null,function*(){var r,o,c;this.convertKnowledgesToChatFormat(this.knowledges);let s=E(v({},t),{promptVariables:this.promptVariables.filter(a=>a.type===x.PromptVariableType.User).reduce((a,l)=>E(v({},a),{[l.key]:l.value}),{}),systemPromptVariables:this.promptVariables.filter(a=>a.type===x.PromptVariableType.System).reduce((a,l)=>E(v({},a),{[l.key]:l.value}),{}),knowledges:(r=this.knowledges)==null?void 0:r.map(a=>a.id),enableTitleSummary:this.resolveEnableTitleSummary()});if(!this.active){if(yield this.activate(),!this.socket){const a=new Error(Re.SocketConnectionFailed);return H.warn("error",a),this.event.emit("error",a),!1}(o=this.socket)==null||o.emit("question",s);return}(c=this.socket)==null||c.emit("question",s)})}invokeClientPlugin(t,i,s,r){const o=new AbortController;this.inflightCalls.add(o);let c=!1;const a=(...d)=>{c||(c=!0,this.inflightCalls.delete(o),!(this._stopAnswer||o.signal.aborted)&&s(...d))},l={requestId:r.requestId||_e.v4(),applicationId:this._applicationId,sessionId:this.id,pluginCode:r.pluginCode,functionCode:r.functionCode,signal:o.signal};try{const d=t(i,a,l);d&&typeof d.catch=="function"&&d.catch(u=>{H.error("client plugin failed",u),a({code:500,message:"客户端插件执行失败。"})})}catch(d){H.error("client plugin failed",d),a({code:500,message:"客户端插件执行失败。"})}}abortClientPluginCalls(){const t=Array.from(this.inflightCalls);this.inflightCalls.clear(),t.forEach(i=>i.abort())}stopAnswer(){var t;this.abortClientPluginCalls(),(t=this.socket)==null||t.emit("stop_answer")}inactivate(t=!1){return this.abortClientPluginCalls(),super.inactivate(t)}destroy(){return this.abortClientPluginCalls(),super.destroy()}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}function Hr(n,e){return h(this,null,function*(){const t=n.getReader();let i;for(;!(i=yield t.read()).done;)e(i.value)})}function qr(n){let e,t,i,s=!1,r;return function(c){e===void 0?(e=c,t=0,i=-1,r=!1):e=zr(e,c);const a=e.length;let l=0;for(;t<a;){s&&(e[t]===10&&(l=++t),s=!1);let d=-1;for(;t<a&&d===-1;++t)switch(e[t]){case 58:i===-1&&(i=t-l);break;case 13:s=!1,t+4<a&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(r=!0);case 10:d=t;break}if(d===-1)break;n(e.subarray(l,d),i,r),l=t,i=-1,r=!1}l===a?e=void 0:l!==0&&(e=e.subarray(l),t-=l)}}function Wr(n,e,t){let i=kn();const s=new TextDecoder;return function(o,c,a){if(o.length===0)t==null||t(i),i=kn();else if(c>0){const l=s.decode(o.subarray(0,c)),d=c+(o[c+1]===32?2:1);let u=s.decode(o.subarray(d));switch(a&&(u+=`
|
|
368
|
+
`),l){case"data":i.data=i.data?i.data+`
|
|
369
|
+
`+u:u;break;case"event":i.event=u;break;case"id":n(i.id=u);break;case"retry":const f=parseInt(u,10);isNaN(f)||e(i.retry=f);break}}}}function zr(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function kn(){return{data:"",event:"",id:"",retry:void 0}}const St="text/event-stream",Vr=1e3,xn="last-event-id";function An(n,d){var u=d,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:c,fetch:a}=u,l=Kt(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,g)=>{const _=v({},t);_.accept||(_.accept=St);let w;function b(){w.abort(),document.hidden||O()}c||document.addEventListener("visibilitychange",b);let A=Vr,I=0;function T(){document.removeEventListener("visibilitychange",b),window.clearTimeout(I),w.abort()}e==null||e.addEventListener("abort",()=>{T(),f()});const R=a!=null?a:window.fetch,J=i!=null?i:Gr;function O(){return h(this,null,function*(){var k;w=new AbortController;try{const M=yield R(n,E(v({},l),{headers:_,signal:w.signal}));yield J(M),yield Hr(M.body,qr(Wr(C=>{C?_[xn]=C:delete _[xn]},C=>{A=C},s))),r==null||r(),T(),f()}catch(M){if(!w.signal.aborted)try{const C=(k=o==null?void 0:o(M))!=null?k:A;window.clearTimeout(I),I=window.setTimeout(O,C)}catch(C){T(),g(C)}}})}O()})}function Gr(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith(St)))throw new Error(`Expected content-type to be ${St}, Actual: ${e}`)}const Tn=new U("[DialogSession] ");class Xr extends zt{constructor(t,i="",s,r,o,c){super(t,i,s,r,o,c);y(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>h(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,i,s,r,o,c){return h(this,null,function*(){const a={code:0,content:"",role:x.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},l=E(v({},s),{stream:exports.configuration.stream});An(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(l),openWhenHidden:!0,signal:r,onopen(d){return d.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(d){if(!d.data.includes('{"code": ')){let f={};try{f=JSON.parse(d.data)}catch(_){}(f==null?void 0:f.mtype)==="search"?a.searchReference.push(f):a.content=a.content+d.data;const g={content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:i,messageTime:Et(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(o==null?void 0:o.onmessage)&&o.onmessage(g)}const u=JSON.parse(d.data);if(a.reference=u.data.reference,a.searchReference=u.data.searchReference,a.messageTime=u.data.messageTime,a.messageId=u.data.messageId,a.llmModel=u.data.llmModel,a.content=u.data.content,a.code=u.code,u.code===200){const f={code:a.code,content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:i,messageTime:a.messageTime,isReplying:!0};o!=null&&o.onmessage&&o.onmessage(f)}else return o!=null&&o.onclose&&o.onclose(a),c&&c({code:a.code,message:a.message})},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const d={code:a.code,content:a.content,role:1,reference:a.reference,searchReference:a.searchReference,messageId:a.messageId,sessionId:i,messageTime:a.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};o!=null&&o.onclose&&o.onclose(d)}})})}postChatV3EventSource(t,i,s,r,o,c){return h(this,null,function*(){const a=this,l={code:0,content:"",role:x.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},d=E(v({},s),{stream:exports.configuration.stream});An(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(d),openWhenHidden:!0,signal:r,onopen(u){return u.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(u){if(!u.data&&!u.event&&!u.id&&!u.retry)return;let f={};try{f=JSON.parse(u.data)}catch(g){console.error("parse eventData to JSON failed. ",u.data)}if(f.code!==200)return l.index=-1,l.code=f.code,l.message=f.message,o!=null&&o.onmessage&&o.onmessage(l),c&&c({code:f.code,message:f.message});a.handleStreamAnswer(f,l),o!=null&&o.onmessage&&o.onmessage(l)},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const u=E(v({},l),{isReplying:!1});o!=null&&o.onclose&&o.onclose(u)}})})}sendQuestion(t,i){return h(this,null,function*(){const{content:s,fileIds:r,oldMessageId:o,imageContent:c}=t,{stream:a,referenceFirst:l}=i;if(this.active||(yield this.activate()),this._id){const d=this.convertKnowledgesToChatFormat(this.knowledges);let u={content:s,fileIds:r,referenceFirst:l,oldMessageId:o,promptVariables:this.promptVariables.filter(f=>f.type===x.PromptVariableType.User).reduce((f,g)=>E(v({},f),{[g.key]:g.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===x.PromptVariableType.System).reduce((f,g)=>E(v({},f),{[g.key]:g.value}),{}),knowledges:d,enableTitleSummary:this.resolveEnableTitleSummary(),imageContent:c};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,u,this.ctrl.signal,{onopen:()=>{Tn.log("open",this.ctrl)},onmessage:f=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===x.ChatMessageRole.Robot?(g=v(v({},g),f),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(f),this.event.emit("message:content",f))},onclose:f=>h(this,null,function*(){this._stopAnswer||(Tn.log(f,"onclose"),this.event.emit("answer:finish",f))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return h(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return h(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return h(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}const Yr="@glodon-aiot/bot-client-sdk",Kr="3.26.0-alpha.15",Jr="glodoncv",Qr="aiot bot client js sdk",Zr="module",eo=!1,to=["aiot","bot","bot client","sdk"],no=["dist"],io="./dist/es/index.mjs",so="./dist/lib/index.js",ro="./dist/src/index.d.ts",oo={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},ao="MIT",co={watch:"yarn build --watch",example:"node ./example/server.js",dev:"npm-run-all -p watch example",start:"vite",build:"tsc && vite build --mode prod && yarn build:cdn","build:npm":"tsc && vite build --mode prod","build:cdn":"tsc && vite build --mode prod --config ./vite.config.cdn.ts",preview:"vite preview",check:"yarn prettier --check .",write:"yarn prettier --write .",lint:"eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js","build:just-bash":"node scripts/build-just-bash.mjs","upload:just-bash":"node scripts/build-just-bash.mjs && node scripts/upload-cdn-libs.cjs just-bash","build:pyodide":"node scripts/build-pyodide.mjs","upload:pyodide":"node scripts/build-pyodide.mjs && node scripts/upload-cdn-libs.cjs pyodide",test:"vitest run","test:watch":"vitest"},lo={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@types/express":"^4","@types/identity-obj-proxy":"^3","@typescript-eslint/eslint-plugin":"^5.35.1","@typescript-eslint/parser":"^5.35.1","babel-loader":"^8.3.0",eslint:"^8.0.1","eslint-config-prettier":"^8.5.0","eslint-config-standard-with-typescript":"^22.0.0","eslint-plugin-import":"^2.25.2","eslint-plugin-n":"^15.0.0","eslint-plugin-promise":"^6.0.0","eslint-plugin-react":"^7.31.0","eslint-plugin-storybook":"^0.6.10",express:"4","http-proxy-middleware":"^3.0.0","identity-obj-proxy":"^3.0.0","just-bash":"3.6.0","npm-run-all":"^4.1.5",prettier:"2.7.1",pyodide:"314.0.7","rollup-plugin-visualizer":"^6.0.1","socket.io":"^4.7.5","ts-node":"^10.9.2",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0","vite-tsconfig-paths":"^5.1.4",vitest:"^0.34.6"},ho={access:"public",registry:"https://registry.npmjs.org/"},uo={"@glodon-aiot/apis":"^3.26.0-alpha.15",axios:"0.24.0",buffer:"^6.0.3",dayjs:"^1.11.13","js-base64":"^3.7.7","socket.io-client":"^4.7.5",uuid:"^11.1.0"},fo={name:Yr,version:Kr,author:Jr,description:Qr,type:Zr,sideEffects:eo,keywords:to,files:no,module:io,main:so,typings:ro,exports:oo,license:ao,scripts:co,devDependencies:lo,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:ho,dependencies:uo},Rn=new U("[BotClient] ");class po{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){y(this,"event",new Ut);y(this,"cvforceApi");y(this,"_applicationId");y(this,"_application",null);y(this,"_sessions",[]);y(this,"_activeSession");y(this,"_ready",!1);y(this,"_questionContextMaxLength",4e3);y(this,"_promptVariables",[]);y(this,"_localWorkspace");y(this,"_disconnectHost");if(this._token=e,this.lazyload=i,this.sdkConfigs=s,_t(t,{refreshBuiltinPlugins:!1}),this._applicationId=Xe(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{_t(E(v({},t),{stream:t.stream===void 0?(r==null?void 0:r.type)===x.ApplicationTypes.Dialog||(r==null?void 0:r.type)===x.ApplicationTypes.Agent:t.stream})),this.event.emit("ready")})}setupLocalWorkspace(){var s,r;const e=(s=exports.configuration.builtinPlugins)==null?void 0:s.localFiles;if(!(e!=null&&e.enabled)){wn(void 0),vt();return}const t=[],i=(r=e.backend)!=null?r:"file-system-access";if(i!=="file-system-access"&&i!=="host-bridge")t.push(new Error(`[LocalFiles] 不支持的 backend:${e.backend}`));else{const o=vr(exports.configuration.apiRoot,this.token,(c,a)=>Rn.error(a));this._localWorkspace=new Ii({applicationId:this._applicationId,config:e,store:Ei(),picker:i==="host-bridge"?null:void 0,transfer:qt(()=>this.cvforceApi,()=>o)}),wn(this._localWorkspace),this._localWorkspace.platformSkills=new Er({applicationId:()=>this._applicationId,getToken:()=>this.token,getSkills:()=>{var c,a,l,d;return(d=(l=(a=(c=this._application)==null?void 0:c.arrange)==null?void 0:a[0])==null?void 0:l.skills)!=null?d:[]},apiRoot:()=>exports.configuration.apiRoot,getSandbox:()=>{var a;const c=(a=this._localWorkspace)==null?void 0:a.adapter;return c instanceof Je?c.sandbox:void 0}}),i==="host-bridge"?this._disconnectHost=kr(this._localWorkspace):this._localWorkspace.restore()}t.push(...vt()),t.length&&Promise.resolve().then(()=>t.forEach(o=>this.event.emit("error",o)))}get localWorkspace(){return this._localWorkspace}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return h(this,null,function*(){var t,i,s,r,o;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(i=this.sdkConfigs.ui)==null?void 0:i.version,sdkVersion:fo.version}).then(c=>(typeof c.arrange[0].thinkingModeOpen!="boolean"&&(c.arrange[0].thinkingModeOpen=!0),typeof c.arrange[0].thinkingTextOpen!="boolean"&&(c.arrange[0].thinkingTextOpen=!0),E(v({},c),{arrange:[E(v({},c.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&c.arrange[0].recommendQuestionOpen})]})));const e=(o=(r=(s=this._application)==null?void 0:s.arrange)==null?void 0:r[0])==null?void 0:o.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(c=>c.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type:x.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:x.PromptVariableType.System})]).then(([c,a])=>[...c,...a]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:mi(exports.configuration.apiRoot,this.token,(e,t)=>Rn.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=Xe(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,i,s,r){return h(this,null,function*(){const o=this;return new Promise((c,a)=>{const l=d=>h(this,null,function*(){if(d===x.ApplicationTypes.Agent)c(new Ur(e,t,i,s,r,o));else if(d===x.ApplicationTypes.Dialog)c(new Xr(e,t,i,s,r,o));else throw Error(`不支持的应用类型:${d}`)});if(this.ready){if(!this._application)throw Error("client is not ready");l(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");l(this._application.type)},!0)})})}getArtifacts(e){return h(this,null,function*(){var r,o;this.checkReady();const t=e||((r=this._activeSession)==null?void 0:r.id);if(!t)throw new Error("session id is not defined");const i=this._sessions.find(c=>c.id===t);if(i)return i.getArtifacts();const s=yield this.cvforceApi.getSessionArtifacts(this._applicationId,t);return(o=s==null?void 0:s.artifacts)!=null?o:[]})}getSessions(e){return h(this,null,function*(){return new Promise((t,i)=>{const s=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>h(this,null,function*(){const o=[];for(const c of r){const a=this._sessions.find(l=>l.id===c.id);if(a)a.data=c,this._application?a.application=this._application:yield a.loadApplicationInfo(),o.push(a);else{const l=yield this.createSession(this.token,c.id,c,this.lazyload,this._application||void 0);o.push(l)}}if(e!=null&&e.pageSize){const c=[...this._sessions,...o],a=new Map;for(const l of c)a.set(l.id,l);return this.sessions=Array.from(a.values()),this.sessions}else return this.sessions=o,o}));if(this.ready){if(!this._application)throw Error("_application is null");t(s())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(s())},!0)})})}loadSession(e="",t){return h(this,null,function*(){var s,r;this.checkReady(),(r=(s=this._localWorkspace)==null?void 0:s.platformSkills)==null||r.sync();let i=this.sessions.find(o=>o.id===e);if(i||(i=yield this.createSession(this.token,e,t),this._sessions.push(i)),this._activeSession){if(this._activeSession===i)return i;this._activeSession.inactivate()}return i.id?(this._activeSession=i,yield i.activate()):i.addEventListener("data:loaded",()=>{this._activeSession!==i&&(i==null||i.activate(),this._activeSession=i)},!0),i})}reload(){return this.loadApplication().then(()=>h(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return h(this,null,function*(){yield this.reload();let t=this._sessions.find(i=>i.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,i="top_time desc, sort_status desc, updated_at desc"){return h(this,null,function*(){let s=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!s){console.warn("setTop session failed.");return}return yield s.setTop(t),this.getSessions({order:i})})}addEventListener(e,t,i=!1){if(typeof t!="function")throw Error("event listener is not a function");if(i){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return h(this,null,function*(){this.checkReady();let i=-1;if(typeof e=="string"?i=this._sessions.findIndex(s=>s.id===e):i=this._sessions.findIndex(s=>s.id===e.id),i>-1){const s=this._sessions[i];t&&(yield s.delete()),this._sessions.splice(i,1)}else console.warn("session delete failed, session is not exist.")})}clean(){var e;(e=this._disconnectHost)==null||e.call(this),this._disconnectHost=void 0,this._sessions.forEach(t=>t.destroy()),this.sessions=[]}}class mo{constructor(e,t={},i){y(this,"code");y(this,"description","");y(this,"loaded",!1);y(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}const z="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",V={type:"string",enum:[be],description:`工作区 ID。省略时按 ${be} 处理,传其他值会被拒绝。`},G=n=>({type:"string",description:`${n}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),ct={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},ki={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${z}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:V,path:G('要列出的目录,省略或传 "." 表示工作区根目录。'),offset:{type:"integer",minimum:0,description:"分页起始位置,默认 0。"},limit:{type:"integer",minimum:1,maximum:1e3,description:"每页条数,默认 200。"}}}},read_file:{functionCode:"read_file",name:"读取本地文件",description:`${z}按行读取文本文件,单次最多返回 1 MiB,超出部分会被截断(truncated: true)。返回内容的 hash 可用于后续修改。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:V,path:G("要读取的文件。"),startLine:{type:"integer",minimum:1,description:"起始行(从 1 开始,含)。"},endLine:{type:"integer",minimum:1,description:"结束行(含)。"},maxBytes:{type:"integer",minimum:1,description:"返回内容的最大字节数,不超过 1 MiB。"},encoding:{type:"string",enum:["utf-8","gbk","gb18030"],description:"文本编码,默认 utf-8。"}}}},stat_file:{functionCode:"stat_file",name:"查看本地文件信息",description:`${z}返回文件或目录的类型、大小、修改时间,可选返回 hash。不返回文件内容。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:V,path:G("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${z}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:V,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:G("搜索起点目录,默认工作区根目录。"),maxDepth:{type:"integer",minimum:1,maximum:16,description:"最大目录深度,默认 8。"},maxResults:{type:"integer",minimum:1,maximum:200,description:"最多返回条数,默认 200。"}}}},search_text:{functionCode:"search_text",name:"搜索本地文本",description:`${z}在指定文件或目录(递归)中搜索普通文本(不支持正则),返回所在文件、行号与该行内容。必须指定 path,不能搜索整个文件夹。`,parameters:{type:"object",required:["grantId","path","query"],properties:{grantId:V,path:G("搜索范围,可以是文件或目录。"),query:{type:"string",minLength:1,description:"要查找的文本。"},caseSensitive:{type:"boolean",description:"是否区分大小写,默认否。"},isRegex:{type:"boolean",description:"暂不支持正则,传 true 会返回 501。"},glob:{type:"string",description:"只搜索匹配该 glob 的文件,如 *.md。"},maxResults:{type:"integer",minimum:1,maximum:200,description:"最多返回条数,默认 200。"},contextLines:{type:"integer",minimum:0,maximum:3,description:"附带的上下文行数,默认 0。"}}}},apply_patch:{functionCode:"apply_patch",name:"修改本地文件",description:`${z}以查找替换的方式修改 UTF-8 文本文件。每条修改的 oldText 必须在文件中唯一出现(或设置 replaceAll)。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","expectedHash","edits"],properties:{grantId:V,path:G("要修改的文件。"),expectedHash:ct,edits:{type:"array",minItems:1,description:"按顺序应用的修改。",items:{type:"object",required:["oldText","newText"],properties:{oldText:{type:"string",minLength:1,description:"要替换的原文,需包含足够上下文以保证唯一。"},newText:{type:"string",description:"替换后的文本。"},replaceAll:{type:"boolean",description:"是否替换所有出现位置,默认否。"}}}}}}},write_file:{functionCode:"write_file",name:"写入本地文件",description:`${z}新建文件,或整体覆盖已有文件(覆盖时必须提供 expectedHash)。修改已有文件优先使用 apply_patch。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","content"],properties:{grantId:V,path:G("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:ct,createDirectories:{type:"boolean",description:"父目录不存在时是否自动创建,默认否。"}}}},upload_file:{functionCode:"upload_file",name:"上传本地文件",description:`${z}把本地文件夹中的文件上传到平台文件服务,返回 fileId、name、size 和 url。url 是文件访问地址,可直接用于后续推理或对话。下载回本地文件夹时使用 download_file,source.type 为 platformFile。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:V,path:G("要上传的文件。"),target:{type:"string",description:"上传目标,目前只支持 session(默认),其他值返回 501。"},mimeHint:{type:"string",description:"可选的 MIME 类型。"}}}},download_file:{functionCode:"download_file",name:"下载到本地文件夹",description:`${z}把会话文件、平台文件或 https 地址保存到本地文件夹。source.type 为 url 时必须同时填写 source.url(完整地址),为 sessionFile 或 platformFile 时必须同时填写 source.fileId。不要只传 type。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","destPath","source"],properties:{grantId:V,destPath:G("保存位置(文件路径)。"),source:{type:"object",required:["type"],description:"下载来源。type 为 url 时必填 url;type 为 sessionFile 或 platformFile 时必填 fileId。",properties:{type:{type:"string",enum:["sessionFile","platformFile","url"],description:"sessionFile:当前会话文件;platformFile:平台文件(upload_file 返回的 fileId);url:https 地址。"},fileId:{type:"string",description:"type 为 sessionFile 或 platformFile 时必填,不能只传 type。"},url:{type:"string",description:"type 为 url 时必填,填写完整 https 地址。不能只传 type。默认只允许 glodon.com 及其子域。"}}},overwrite:{type:"boolean",description:"目标已存在时是否覆盖,默认否。"},expectedHash:ct}}}},go=new TextEncoder;function ee(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const yo=(n,e)=>h(exports,null,function*(){const t=K(n.path,{allowRoot:!0});if((yield e.adapter.stat(t)).kind!=="directory")throw new m(p.BadRequest,"目标是文件,不是目录。");const s=ee(n.offset,0,0,Number.MAX_SAFE_INTEGER),r=ee(n.limit,Dn,1,Pn),o=yield e.adapter.listEntries(t,e.signal);o.sort((a,l)=>a.kind!==l.kind?a.kind==="directory"?-1:1:a.name<l.name?-1:a.name>l.name?1:0);const c=o.slice(s,s+r).map(a=>{const l=vi(t,a.name),d={name:a.name,path:l,kind:a.kind};return a.kind==="file"&&(d.size=a.size,d.lastModified=a.lastModified,e.sensitive.isSensitive(l)&&(d.sensitive=!0)),d});return{data:{path:t,entries:c,total:o.length,hasMore:s+c.length<o.length}}});function wo(n,e,t){return de(this,null,function*(){var c;const i=new TextDecoder(e),s=n.stream().getReader();let r="",o=!1;try{for(;;){N(t);const{done:a,value:l}=yield new te(s.read());r+=a?i.decode():i.decode(l,{stream:!0});const d=r.split(`
|
|
370
|
+
`);r=(c=d.pop())!=null?c:"";for(const u of d)o=!0,yield u;if(a)break}}finally{s.releaseLock()}(r||!o)&&(yield r)})}const vo=(n,e)=>h(exports,null,function*(){var T,R;const t=K(n.path);Ie(e,t,"read");const i=yield Ot(e.adapter,t),s=yield e.adapter.readFile(t),r=(T=i.size)!=null?T:s.size;if(yield cs(s))throw new m(p.BadRequest,"这是二进制文件,不能按文本读取。可以使用 stat_file 查看信息,或使用 upload_file 上传到会话。");const o=yield q(s.slice(0,3)),c=ii(o)?"utf-8":(R=n.encoding)!=null?R:"utf-8",a=ee(n.startLine,1,1,Number.MAX_SAFE_INTEGER),l=n.endLine===void 0?Number.MAX_SAFE_INTEGER:Math.max(Math.trunc(n.endLine),a),d=ee(n.maxBytes,e.limits.maxReadBytes,1,e.limits.maxReadBytes),u=r<=e.limits.maxTransferBytes,f=[];let g=0,_=0,w=a-1,b=!1,A=!1;try{for(var J=W(wo(s,c,e.signal)),O,k,M;O=!(k=yield J.next()).done;O=!1){const C=k.value;_++;const $=C.endsWith("\r")?C.slice(0,-1):C;if($!==C&&(A=!0),_<a||_>l||b){if(!u&&(b||_>l))break;continue}const ce=$t($)+(f.length?1:0);if(g+ce>d){if(b=!0,f.length||(f.push(_o($,d)),w=_),!u)break;continue}f.push($),g+=ce,w=_}}catch(k){M=[k]}finally{try{O&&(k=J.return)&&(yield k.call(J))}finally{if(M)throw M[0]}}const I={path:t,content:f.join(`
|
|
371
|
+
`),startLine:a,endLine:Math.max(w,a-1),size:r,encoding:c,lineEnding:A?"crlf":"lf"};return u&&(I.totalLines=_),r<=e.limits.maxWriteBytes&&(I.hash=yield Se(yield q(s))),{data:I,truncated:b||void 0}});function _o(n,e){const t=go.encode(n);return t.byteLength<=e?n:new TextDecoder().decode(t.slice(0,e)).replace(/\uFFFD$/,"")}const bo=(n,e)=>h(exports,null,function*(){var r;const t=K(n.path),i=yield e.adapter.stat(t),s={path:t,kind:i.kind,sensitive:i.kind==="file"&&e.sensitive.isSensitive(t)};return i.kind==="file"&&(s.size=i.size,s.lastModified=i.lastModified,n.includeHash&&((r=i.size)!=null?r:0)<=e.limits.maxTransferBytes&&(s.hash=yield Se(yield q(yield e.adapter.readFile(t))))),{data:s}});function So(n){return zn.some(e=>Ve(e,n))}function xi(n,e,t){return de(this,null,function*(){const i=[{path:e,depth:0}];let s=0;for(;i.length;){const r=i.shift();N(n.signal),++s%20===0&&(yield new te(si()));const o=yield new te(n.adapter.listEntries(r.path,n.signal));o.sort((c,a)=>c.name<a.name?-1:c.name>a.name?1:0);for(const c of o){const a=vi(r.path,c.name);if(c.kind==="directory"){r.depth+1<t&&!Wn.includes(c.name)&&i.push({path:a,depth:r.depth+1});continue}So(c.name)||n.sensitive.match(a,"search")||(yield{path:a,relativePath:e?a.slice(e.length+1):a,name:c.name,size:c.size,lastModified:c.lastModified})}}})}function Ai(n,e){return n.includes("/")?Ve(n,e.relativePath):Ve(n,e.name)}const Eo=(n,e)=>h(exports,null,function*(){const t=K(n.path,{allowRoot:!0});if(!n.pattern.trim())throw new m(p.BadRequest,"参数 pattern 不能为空。");const i=n.pattern.replace(/\\/g,"/").replace(/^\.\//,"");if((yield e.adapter.stat(t)).kind!=="directory")throw new m(p.BadRequest,"参数 path 必须是目录。");const r=ee(n.maxDepth,Bn,1,kt),o=ee(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),c=[];let a=!1;try{for(var l=W(xi(e,t,r)),d,u,f;d=!(u=yield l.next()).done;d=!1){const g=u.value;if(Ai(i,g)){if(c.length>=o){a=!0;break}c.push({path:g.path,size:g.size,lastModified:g.lastModified})}}}catch(u){f=[u]}finally{try{d&&(u=l.return)&&(yield u.call(l))}finally{if(f)throw f[0]}}return{data:{matches:c},truncated:a||void 0}});function lt(n,e){if(n.length<=Ue)return n;const t=Math.max(0,Math.min(e-100,n.length-Ue));return n.slice(t,t+Ue)}const Io=(n,e)=>h(exports,null,function*(){var f;const t=K(n.path,{allowRoot:!0});if(!t&&!e.allowWorkspaceWideTextSearch)throw new m(p.BadRequest,"不支持在整个工作区内搜索文本,请把 path 缩小到具体的子目录或文件。");if(n.isRegex)throw new m(p.NotImplemented,"暂不支持正则搜索,请使用普通文本搜索。");if(!n.query)throw new m(p.BadRequest,"参数 query 不能为空。");const i=n.caseSensitive===!0,s=i?n.query:n.query.toLowerCase(),r=ee(n.contextLines,0,0,Hn),o=ee(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),c=yield e.adapter.stat(t);let a;c.kind==="file"?(Ie(e,t,"search"),a=function(){return de(this,null,function*(){yield{path:t,relativePath:t,name:c.name,size:c.size}})}()):a=xi(e,t,kt);const l=[];let d=0,u=!1;e:try{for(var g=W(a),_,w,b;_=!(w=yield g.next()).done;_=!1){const A=w.value;if(n.glob&&!Ai(n.glob,A)||((f=A.size)!=null?f:0)>Un)continue;if(d>=jn){u=!0;break}d++,d%20===0&&(yield si()),N(e.signal);const I=yield q(yield e.adapter.readFile(A.path));if(ae(I))continue;const T=new TextDecoder("utf-8").decode(I).split(/\r?\n/);for(let R=0;R<T.length;R++){const O=(i?T[R]:T[R].toLowerCase()).indexOf(s);if(O<0)continue;if(l.length>=o){u=!0;break e}const k={path:A.path,line:R+1,column:O+1,text:lt(T[R],O)};r&&(k.before=T.slice(Math.max(0,R-r),R).map(M=>lt(M,0)),k.after=T.slice(R+1,R+1+r).map(M=>lt(M,0))),l.push(k)}}}catch(w){b=[w]}finally{try{_&&(w=g.return)&&(yield w.call(g))}finally{if(b)throw b[0]}}return{data:{matches:l,filesScanned:d},truncated:u||void 0}});function Ln(){return new m(p.Forbidden,"下载地址不在允许范围内:只允许 https 协议且域名在白名单中的地址。",{reason:"url_not_allowed"})}const ko=(n,e)=>h(exports,null,function*(){var u,f;const t=K(n.path);if(((u=n.target)!=null?u:"session")!=="session")throw new m(p.NotImplemented,"目前只支持上传到当前会话(target: session)。");Ie(e,t,"read");const s=yield Ot(e.adapter,t),r=(f=s.size)!=null?f:0;if(r>e.limits.maxTransferBytes)throw oe(e.limits.maxTransferBytes);const o=Nt(t);yield e.requestApproval(t,{type:"upload",name:o,size:r,target:"session"}),e.progress({stage:"reading",loaded:0,total:r,path:t});const c=yield e.adapter.readFile(t);N(e.signal);const a=new File([c],o,{type:n.mimeHint||c.type||"application/octet-stream",lastModified:s.lastModified}),{fileId:l,url:d}=yield e.transfer.upload(a,e.context,({loaded:g,total:_})=>e.progress({stage:"uploading",loaded:g,total:_,path:t}));return N(e.signal),e.progress({stage:"done",loaded:r,total:r,path:t}),{data:{fileId:l,name:o,size:r,url:d}}});function xo(n){const e=n;if(!e||typeof e!="object")throw new m(p.BadRequest,"缺少参数 source。");if(e.type==="sessionFile"||e.type==="platformFile"){if(typeof e.fileId!="string"||!e.fileId)throw new m(p.BadRequest,"source.fileId 必须是非空字符串。");return{type:e.type,fileId:e.fileId}}if(e.type==="url"){if(typeof e.url!="string"||!e.url)throw new m(p.BadRequest,"source.url 必须是非空字符串。");return{type:"url",url:e.url}}throw new m(p.BadRequest,"source.type 必须是 sessionFile、platformFile 或 url 之一。")}function Ao(n){return n.type==="sessionFile"?"会话文件":n.type==="platformFile"?"平台文件":new URL(n.url).hostname}function To(n,e,t,i,s){return de(this,null,function*(){const r=n.getReader();let o=0;try{for(;;){N(e.signal);const{done:c,value:a}=yield new te(r.read());if(c)break;if(o+=a.byteLength,o>e.limits.maxTransferBytes)throw oe(e.limits.maxTransferBytes,"下载内容");s.push(a),e.progress({stage:"downloading",loaded:o,total:i,path:t}),yield a}}finally{r.cancel().catch(()=>{})}})}const Ro=(n,e)=>h(exports,null,function*(){var w,b,A;const t=K(n.destPath,{field:"destPath"}),i=xo(n.source);if(i.type==="url"&&!bt(i.url,e.downloadUrlAllowlist))throw Ln();Ie(e,t,"write");const s=yield He(e.adapter,t);if((s==null?void 0:s.kind)==="directory")throw new m(p.BadRequest,"目标是目录,不能写入文件。");if(s&&!n.overwrite)throw new m(p.Conflict,"目标文件已存在。如需覆盖,请设置 overwrite: true。");const r=()=>h(exports,null,function*(){if(!s||!n.expectedHash)return;const I=yield Se(yield q(yield e.adapter.readFile(t)));if(I!==n.expectedHash)throw new m(p.Conflict,"expectedHash 与目标文件当前内容不一致。",{currentHash:I})});yield r();const o=i.type==="url"?{url:i.url}:yield e.transfer.resolveDownload(i,e.context);if(o.size!==void 0&&o.size>e.limits.maxTransferBytes)throw oe(e.limits.maxTransferBytes);const c={type:"download",source:{type:i.type,label:Ao(i)},name:(w=o.name)!=null?w:Nt(t),size:o.size,overwrite:!!s};yield e.requestApproval(t,c),yield r();let a;try{a=yield e.fetch(o.url,{headers:o.headers,credentials:"omit",redirect:"follow",signal:e.signal})}catch(I){throw N(e.signal),new m(p.Internal,"下载失败,无法连接到文件地址。")}if(i.type==="url"&&a.url&&!bt(a.url,e.downloadUrlAllowlist))throw(b=a.body)==null||b.cancel().catch(()=>{}),Ln();if(!a.ok||!a.body)throw(A=a.body)==null||A.cancel().catch(()=>{}),new m(a.status===404?p.NotFound:p.Internal,`下载失败(HTTP ${a.status})。`);const l=Number(a.headers.get("content-length")),d=Number.isFinite(l)&&l>0?l:void 0;if(d!==void 0&&d>e.limits.maxTransferBytes)throw a.body.cancel().catch(()=>{}),oe(e.limits.maxTransferBytes);const u=[];yield e.adapter.writeFile(t,To(a.body,e,t,d,u),{signal:e.signal});const f=u.reduce((I,T)=>I+T.byteLength,0),g=new Uint8Array(f);let _=0;return u.forEach(I=>{g.set(I,_),_+=I.byteLength}),e.progress({stage:"done",loaded:f,total:f,path:t}),{data:{path:t,size:f,hash:yield Se(g)}}}),dt=new Uint8Array([239,187,191]);function Ye(n,e){return new m(p.Conflict,e,{currentHash:n})}function Vt(n,e){return h(this,null,function*(){var s;if(((s=(yield Ot(n.adapter,e)).size)!=null?s:0)>n.limits.maxWriteBytes)throw oe(n.limits.maxWriteBytes,"目标文件");const i=yield q(yield n.adapter.readFile(e));return{bytes:i,hash:yield Se(i)}})}function Ti(n,e,t){return h(this,null,function*(){const{hash:i}=yield Vt(n,e);if(i!==t)throw Ye(i,"文件在确认期间已被修改,本次写入已取消。请重新读取后再修改。")})}function Lo(n,e){const t=new TextEncoder().encode(n);if(!e)return t;const i=new Uint8Array(dt.byteLength+t.byteLength);return i.set(dt,0),i.set(t,dt.byteLength),i}function Mo(n,e){let t=0,i=n.indexOf(e);for(;i>=0;)t++,i=n.indexOf(e,i+e.length);return t}function Mn(n,e){return!e||n.includes(`\r
|
|
372
372
|
`)?n:n.replace(/\n/g,`\r
|
|
373
|
-
`)}function
|
|
374
|
-
`);let a=o;n.edits.forEach((l,u)=>{if(typeof(l==null?void 0:l.oldText)!="string"||!l.oldText||typeof l.newText!="string")throw new m(p.BadRequest,`第 ${u+1} 条修改无效:oldText 必须是非空字符串,newText 必须是字符串。`);const f=An(l.oldText,c),g=An(l.newText,c),_=vo(a,f);if(_===0)throw new m(p.Conflict,`第 ${u+1} 条修改的 oldText 在文件中不存在,请重新读取文件确认当前内容。`);if(_>1&&!l.replaceAll)throw new m(p.BadRequest,`第 ${u+1} 条修改的 oldText 在文件中出现了 ${_} 次,请补充上下文使其唯一,或设置 replaceAll。`);a=l.replaceAll?a.split(f).join(g):a.replace(f,()=>g)});const d=wo(a,r);if(d.byteLength>e.limits.maxWriteBytes)throw oe(e.limits.maxWriteBytes,"修改后的内容");return yield e.requestApproval(t,{type:"text",before:o,after:a,created:!1}),yield bi(e,t,s),{data:yield Ei(e,t,d)}}),bo=(n,e)=>h(exports,null,function*(){const t=K(n.path);Ie(e,t,"write");const i=yield He(e.adapter,t);if((i==null?void 0:i.kind)==="directory")throw new m(p.BadRequest,"目标是目录,不能写入文件。");let s,r;if(i){const a=yield Ht(e,t);if(r=a.hash,!n.expectedHash)throw Xe(r,"目标文件已存在,覆盖前需要提供 expectedHash(可通过 read_file 或 stat_file 获取)。");if(n.expectedHash!==r)throw Xe(r,"expectedHash 与文件当前内容不一致,请重新读取文件后再写入。");s=new TextDecoder("utf-8").decode(a.bytes)}else if(!n.createDirectories){const a=gr(t),d=a?yield He(e.adapter,a):{kind:"directory"};if(!d)throw new m(p.NotFound,"父目录不存在,可设置 createDirectories 自动创建。");if(d.kind!=="directory")throw new m(p.BadRequest,"父路径不是目录。")}const o=new TextEncoder().encode(n.content);if(o.byteLength>e.limits.maxWriteBytes)throw oe(e.limits.maxWriteBytes,"写入内容");if(yield e.requestApproval(t,{type:"text",before:s,after:n.content,created:!i}),r)yield bi(e,t,r);else if(yield He(e.adapter,t))throw new m(p.Conflict,"目标文件在确认期间被创建,本次写入已取消。请重新检查后再写入。");const c=yield Ei(e,t,o,n.createDirectories);return{data:E(v({},c),{created:!i})}}),Eo={list_directory:so,read_file:oo,stat_file:co,search_files:ho,search_text:uo,apply_patch:_o,write_file:bo,upload_file:fo,download_file:yo};class So{constructor(e,t){w(this,"remaining");w(this,"startedAt",0);w(this,"handle");this.onTimeout=t,this.remaining=e}resume(){this.handle!==void 0||this.remaining<=0||(this.startedAt=Date.now(),this.handle=setTimeout(()=>{this.handle=void 0,this.remaining=0,this.onTimeout()},this.remaining))}pause(){this.handle!==void 0&&(clearTimeout(this.handle),this.handle=void 0,this.remaining-=Date.now()-this.startedAt)}clear(){this.pause(),this.remaining=0}}function Io(n,e){return Hn.includes(e)?n.limits.transferTimeoutMs:Un.includes(e)?n.limits.searchTimeoutMs:n.limits.toolTimeoutMs}function xo(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch(e){throw new m(p.BadRequest,"参数不是合法的 JSON 对象。")}}function Ao(n){if(!n||typeof n!="object"||Array.isArray(n))return;const e=n;return(e.grantId===void 0||e.grantId===null||e.grantId==="")&&(e.grantId=be),e.grantId}function Si(n){return new Promise((e,t)=>{n.aborted&&t(j()),n.addEventListener("abort",()=>t(j()),{once:!0})})}function To(n){return v({code:n.code,message:n.message},n.data?{data:n.data}:{})}function ko(n,e,t,i,s){return h(this,null,function*(){var _,y,b,T,I,k,L,J;const r={requestId:s.requestId||_e.v4(),applicationId:s.applicationId||n.applicationId,sessionId:s.sessionId||"",pluginCode:s.pluginCode,functionCode:e,signal:s.signal},o={requestId:r.requestId,sessionId:r.sessionId,functionCode:e},c=new AbortController;let a=!1;const d=new So(Io(n,e),()=>{a=!0,c.abort()}),l=()=>c.abort();(_=r.signal)==null||_.addEventListener("abort",l,{once:!0}),(y=r.signal)!=null&&y.aborted&&c.abort();let u=null,f,g=!1;try{const N=xo(t),x=Ao(N);x!=null&&mr(x);const M=Vn(N,wi[e].parameters),C=(b=M.path)!=null?b:M.destPath;if(typeof C=="string"&&(o.path=C),yield n.ready,c.signal.aborted)throw j();const D=n.adapter;if(!D)throw bt();if(u=n.acquireSlot(),!u)throw new m(p.TooManyRequests,"同时进行的文件操作过多,请稍后重试。");f=n.track(c),g=!0,n.emit("tool:start",v({},o)),d.resume();const ce={adapter:D,workspaceName:(T=n.displayName)!=null?T:D.displayName,limits:n.limits,sensitive:n.sensitive,downloadUrlAllowlist:n.downloadUrlAllowlist,allowWorkspaceWideTextSearch:n.allowWorkspaceWideTextSearch,transfer:n.transfer,fetch:n.fetch,context:E(v({},r),{signal:c.signal}),signal:c.signal,requestApproval:(Q,Oe)=>Lo(n,{approvalPath:Q,preview:Oe,context:r,functionCode:e,signal:c.signal,timer:d,base:o}),progress:Q=>n.emit("tool:progress",v(v({},o),Q))},de=yield Promise.race([Eo[e](M,ce),Si(c.signal)]),Ae={code:p.Ok,message:"ok",data:de.data};de.truncated&&(Ae.truncated=!0),(I=de.warnings)!=null&&I.length&&(Ae.warnings=de.warnings),n.emit("tool:finish",E(v({},o),{code:p.Ok})),i(Ae)}catch(N){let x=Ye(N);a?x=new m(p.Timeout,"操作超时,已中止。"):c.signal.aborted&&x.code!==p.Cancelled&&(x=j()),((k=x.data)==null?void 0:k.reason)==="workspace_not_granted"&&g&&n.handlePermissionLost(),x.code===p.Cancelled?n.emit("tool:cancelled",v({},o)):n.emit("tool:error",E(v({},o),{code:x.code,message:x.message,reason:(L=x.data)==null?void 0:L.reason})),i(To(x))}finally{d.clear(),(J=r.signal)==null||J.removeEventListener("abort",l),u==null||u(),f==null||f()}})}function Lo(n,e){return h(this,null,function*(){var c;const t=n.getApprovalHandler();if(!t)throw new m(p.Forbidden,"当前环境未提供操作确认能力,无法执行写入或传输操作。",{reason:"approval_unavailable"});if(e.signal.aborted)throw j();const i=new AbortController,s=()=>i.abort();e.signal.addEventListener("abort",s,{once:!0});const r={id:_e.v4(),requestId:e.context.requestId,sessionId:e.context.sessionId,functionCode:e.functionCode,path:e.approvalPath,workspaceName:(c=n.displayName)!=null?c:"",preview:e.preview,signal:i.signal};e.timer.pause(),n.emit("tool:approval-required",E(v({},e.base),{path:e.approvalPath,approvalId:r.id}));let o;try{const a=yield Promise.race([Promise.resolve().then(()=>t(r)),Si(i.signal),new Promise(d=>{o=setTimeout(()=>d(!1),n.limits.approvalTimeoutMs)})]);if(e.signal.aborted)throw j();if(a!==!0)throw new m(p.Forbidden,"用户拒绝了本次操作。",{reason:"user_rejected"})}catch(a){throw a instanceof m?a:new m(p.Forbidden,"操作确认失败,已取消本次操作。",{reason:"user_rejected"})}finally{clearTimeout(o),e.signal.removeEventListener("abort",s),i.abort(),e.timer.resume()}})}function Ro({pluginCode:n,workspace:e}){const t={};return wt.forEach(i=>{t[i]=(s,r,o)=>{let c=!1;ko(e,i,s,d=>{if(!c){c=!0;try{r(d)}catch(l){console.error("[LocalFiles] callback failed",l)}}},E(v({},o),{pluginCode:n}))}}),{[n]:t}}function Tn(){return{kind:"directory",children:new Map}}class Mo{constructor(e={},t="memory-workspace"){w(this,"root",Tn());this.displayName=t,Object.entries(e).forEach(([i,s])=>this.seed(i,s))}seed(e,t="",i=Date.now()){const s=e.split("/").filter(Boolean);if(e.endsWith("/")){this.resolveDirectory(s,!0);return}const r=s.pop();if(!r)return;const o=this.resolveDirectory(s,!0),c=typeof t=="string"?new TextEncoder().encode(t):t;o.children.set(r,{kind:"file",data:c,lastModified:i})}resolveDirectory(e,t=!1){let i=this.root;for(const s of e){let r=i.children.get(s);if(!r){if(!t)throw S("NotFoundError");r=Tn(),i.children.set(s,r)}if(r.kind!=="directory")throw S("TypeMismatchError");i=r}return i}resolveNode(e){const t=$(e),i=t.pop();if(i===void 0)return this.root;const s=this.resolveDirectory(t).children.get(i);if(!s)throw S("NotFoundError");return s}stat(e){return h(this,null,function*(){var s;const t=this.resolveNode(e),i=(s=$(e).pop())!=null?s:this.displayName;return t.kind==="directory"?{name:i,kind:"directory"}:{name:i,kind:"file",size:t.data.byteLength,lastModified:t.lastModified}})}listEntries(e,t){return h(this,null,function*(){O(t);const i=this.resolveDirectory($(e));return Array.from(i.children.entries()).map(([s,r])=>r.kind==="directory"?{name:s,kind:"directory"}:{name:s,kind:"file",size:r.data.byteLength,lastModified:r.lastModified})})}readFile(e){return h(this,null,function*(){const t=this.resolveNode(e);if(t.kind!=="file")throw S("TypeMismatchError");return new Blob([t.data])})}writeFile(s,r){return h(this,arguments,function*(e,t,i={}){const o=$(e),c=o.pop();if(!c)throw S("TypeMismatchError");const a=this.resolveDirectory(o,i.createDirectories),d=a.children.get(c);if((d==null?void 0:d.kind)==="directory")throw S("TypeMismatchError");const l=[];let u=0;try{for(var _=W(Et(t)),y,b,T;y=!(b=yield _.next()).done;y=!1){const I=b.value;O(i.signal),l.push(I),u+=I.byteLength}}catch(b){T=[b]}finally{try{y&&(b=_.return)&&(yield b.call(_))}finally{if(T)throw T[0]}}O(i.signal);const f=new Uint8Array(u);let g=0;l.forEach(I=>{f.set(I,g),g+=I.byteLength}),a.children.set(c,{kind:"file",data:f,lastModified:Date.now()})})}createDirectory(e){return h(this,null,function*(){this.resolveDirectory($(e),!0)})}remove(i){return h(this,arguments,function*(e,t={}){const s=$(e),r=s.pop();if(r===void 0)throw S("InvalidModificationError");const o=this.resolveDirectory(s),c=o.children.get(r);if(!c)throw S("NotFoundError");if(c.kind==="directory"&&c.children.size>0&&!t.recursive)throw S("InvalidModificationError");o.children.delete(r)})}move(e,t){return h(this,null,function*(){const i=$(e),s=$(t),r=i.pop(),o=s.pop();if(r===void 0||o===void 0)throw S("InvalidModificationError");const c=this.resolveDirectory(i),a=c.children.get(r);if(!a)throw S("NotFoundError");const d=this.resolveDirectory(s);if(qn(e,t))throw S("InvalidModificationError");const l=d.children.get(o);if(l&&(l.kind==="directory"||a.kind==="directory"))throw S("InvalidModificationError");c.children.delete(r),d.children.set(o,a)})}}exports.AgentPlugin=no;exports.BINARY_SNIFF_BYTES=_t;exports.BUILTIN_TOOLS_PLUGIN_CODE=ke;exports.BUILTIN_TOOLS_PLUGIN_CODES=kn;exports.BUILTIN_TOOL_SCHEMAS=Mt;exports.BotClient=to;exports.DEFAULT_DOWNLOAD_URL_ALLOWLIST=$n;exports.DEFAULT_IGNORED_DIRECTORIES=Bn;exports.DEFAULT_IGNORED_FILE_PATTERNS=jn;exports.DEFAULT_LIMITS=je;exports.FileSystemAccessAdapter=fi;exports.HOST_BRIDGE_GLOBAL=qe;exports.HOST_CHANNEL=St;exports.KiB=Rn;exports.LIST_DIRECTORY_DEFAULT_LIMIT=Cn;exports.LIST_DIRECTORY_MAX_LIMIT=Fn;exports.LOCAL_FILES_FUNCTION_CODES=wt;exports.LOCAL_FILES_PLUGIN_CODES=Ln;exports.LOCAL_FILE_TOOL_SCHEMAS=wi;exports.LocalWorkspace=yi;exports.MemoryWorkspaceAdapter=Mo;exports.MiB=Me;exports.SDK_SENSITIVE_BASELINE=Jn;exports.SEARCH_DEFAULT_DEPTH=On;exports.SEARCH_FUNCTION_CODES=Un;exports.SEARCH_MAX_DEPTH=vt;exports.Session=Ut;exports.TEXT_SEARCH_MAX_CONTEXT_LINES=Pn;exports.TEXT_SEARCH_MAX_FILES=Nn;exports.TEXT_SEARCH_MAX_FILE_BYTES=Dn;exports.TEXT_SEARCH_MAX_LINE_CHARS=Ue;exports.TRANSFER_FILE_SIZE_LIMIT_MB=Mn;exports.TRANSFER_FUNCTION_CODES=Hn;exports.ToolCode=p;exports.ToolError=m;exports.WORKSPACE_GRANT_ID=be;exports.WRITE_FUNCTION_CODES=Mi;exports.configure=pt;exports.createDefaultSessionFileTransfer=Bt;exports.createIndexedDbStore=gi;exports.createLocalFilesPlugin=Ro;exports.createMemoryStore=jt;exports.getDownloadUrlAllowlist=$t;exports.getRegisteredLocalFilesPluginCode=rr;exports.isDownloadUrlAllowed=_r;exports.registerHostBridge=Ni;exports.resolveLocalFilesPluginCode=ci;exports.toToolError=Ye;
|
|
373
|
+
`)}function Ri(n,e,t,i=!1){return h(this,null,function*(){return n.progress({stage:"writing",loaded:0,total:t.byteLength,path:e}),yield n.adapter.writeFile(e,t,{createDirectories:i,signal:n.signal}),{path:e,hash:yield Se(t),size:t.byteLength}})}const Co=(n,e)=>h(exports,null,function*(){const t=K(n.path);if(Ie(e,t,"write"),!n.edits.length)throw new m(p.BadRequest,"参数 edits 不能为空。");const{bytes:i,hash:s}=yield Vt(e,t);if(s!==n.expectedHash)throw Ye(s,"expectedHash 与文件当前内容不一致,请重新读取文件后再修改。");const r=ii(i),o=ls(r?i.subarray(3):i),c=o.includes(`\r
|
|
374
|
+
`);let a=o;n.edits.forEach((d,u)=>{if(typeof(d==null?void 0:d.oldText)!="string"||!d.oldText||typeof d.newText!="string")throw new m(p.BadRequest,`第 ${u+1} 条修改无效:oldText 必须是非空字符串,newText 必须是字符串。`);const f=Mn(d.oldText,c),g=Mn(d.newText,c),_=Mo(a,f);if(_===0)throw new m(p.Conflict,`第 ${u+1} 条修改的 oldText 在文件中不存在,请重新读取文件确认当前内容。`);if(_>1&&!d.replaceAll)throw new m(p.BadRequest,`第 ${u+1} 条修改的 oldText 在文件中出现了 ${_} 次,请补充上下文使其唯一,或设置 replaceAll。`);a=d.replaceAll?a.split(f).join(g):a.replace(f,()=>g)});const l=Lo(a,r);if(l.byteLength>e.limits.maxWriteBytes)throw oe(e.limits.maxWriteBytes,"修改后的内容");return yield e.requestApproval(t,{type:"text",before:o,after:a,created:!1}),yield Ti(e,t,s),{data:yield Ri(e,t,l)}}),Fo=(n,e)=>h(exports,null,function*(){const t=K(n.path);Ie(e,t,"write");const i=yield He(e.adapter,t);if((i==null?void 0:i.kind)==="directory")throw new m(p.BadRequest,"目标是目录,不能写入文件。");let s,r;if(i){const a=yield Vt(e,t);if(r=a.hash,!n.expectedHash)throw Ye(r,"目标文件已存在,覆盖前需要提供 expectedHash(可通过 read_file 或 stat_file 获取)。");if(n.expectedHash!==r)throw Ye(r,"expectedHash 与文件当前内容不一致,请重新读取文件后再写入。");s=new TextDecoder("utf-8").decode(a.bytes)}else if(!n.createDirectories){const a=Tr(t),l=a?yield He(e.adapter,a):{kind:"directory"};if(!l)throw new m(p.NotFound,"父目录不存在,可设置 createDirectories 自动创建。");if(l.kind!=="directory")throw new m(p.BadRequest,"父路径不是目录。")}const o=new TextEncoder().encode(n.content);if(o.byteLength>e.limits.maxWriteBytes)throw oe(e.limits.maxWriteBytes,"写入内容");if(yield e.requestApproval(t,{type:"text",before:s,after:n.content,created:!i}),r)yield Ti(e,t,r);else if(yield He(e.adapter,t))throw new m(p.Conflict,"目标文件在确认期间被创建,本次写入已取消。请重新检查后再写入。");const c=yield Ri(e,t,o,n.createDirectories);return{data:E(v({},c),{created:!i})}}),No={list_directory:yo,read_file:vo,stat_file:bo,search_files:Eo,search_text:Io,apply_patch:Co,write_file:Fo,upload_file:ko,download_file:Ro};class Oo{constructor(e,t){y(this,"remaining");y(this,"startedAt",0);y(this,"handle");this.onTimeout=t,this.remaining=e}resume(){this.handle!==void 0||this.remaining<=0||(this.startedAt=Date.now(),this.handle=setTimeout(()=>{this.handle=void 0,this.remaining=0,this.onTimeout()},this.remaining))}pause(){this.handle!==void 0&&(clearTimeout(this.handle),this.handle=void 0,this.remaining-=Date.now()-this.startedAt)}clear(){this.pause(),this.remaining=0}}function $o(n,e){return Gn.includes(e)?n.limits.transferTimeoutMs:Vn.includes(e)?n.limits.searchTimeoutMs:n.limits.toolTimeoutMs}function Do(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch(e){throw new m(p.BadRequest,"参数不是合法的 JSON 对象。")}}function Po(n){if(!n||typeof n!="object"||Array.isArray(n))return;const e=n;return(e.grantId===void 0||e.grantId===null||e.grantId==="")&&(e.grantId=be),e.grantId}function Li(n){return new Promise((e,t)=>{n.aborted&&t(j()),n.addEventListener("abort",()=>t(j()),{once:!0})})}function Bo(n){return v({code:n.code,message:n.message},n.data?{data:n.data}:{})}function jo(n,e,t,i,s){return h(this,null,function*(){var _,w,b,A,I,T,R,J;const r={requestId:s.requestId||_e.v4(),applicationId:s.applicationId||n.applicationId,sessionId:s.sessionId||"",pluginCode:s.pluginCode,functionCode:e,signal:s.signal},o={requestId:r.requestId,sessionId:r.sessionId,functionCode:e},c=new AbortController;let a=!1;const l=new Oo($o(n,e),()=>{a=!0,c.abort()}),d=()=>c.abort();(_=r.signal)==null||_.addEventListener("abort",d,{once:!0}),(w=r.signal)!=null&&w.aborted&&c.abort();let u=null,f,g=!1;try{const O=Do(t),k=Po(O);k!=null&&Ar(k);const M=Kn(O,ki[e].parameters),C=(b=M.path)!=null?b:M.destPath;if(typeof C=="string"&&(o.path=C),yield n.ready,c.signal.aborted)throw j();const $=n.adapter;if(!$)throw At();if(u=n.acquireSlot(),!u)throw new m(p.TooManyRequests,"同时进行的文件操作过多,请稍后重试。");f=n.track(c),g=!0,n.emit("tool:start",v({},o)),l.resume();const ce={adapter:$,workspaceName:(A=n.displayName)!=null?A:$.displayName,limits:n.limits,sensitive:n.sensitive,downloadUrlAllowlist:n.downloadUrlAllowlist,allowWorkspaceWideTextSearch:n.allowWorkspaceWideTextSearch,transfer:n.transfer,fetch:n.fetch,context:E(v({},r),{signal:c.signal}),signal:c.signal,requestApproval:(Q,Ne)=>Uo(n,{approvalPath:Q,preview:Ne,context:r,functionCode:e,signal:c.signal,timer:l,base:o}),progress:Q=>n.emit("tool:progress",v(v({},o),Q))},le=yield Promise.race([No[e](M,ce),Li(c.signal)]),ke={code:p.Ok,message:"ok",data:le.data};le.truncated&&(ke.truncated=!0),(I=le.warnings)!=null&&I.length&&(ke.warnings=le.warnings),n.emit("tool:finish",E(v({},o),{code:p.Ok})),i(ke)}catch(O){let k=Ke(O);a?k=new m(p.Timeout,"操作超时,已中止。"):c.signal.aborted&&k.code!==p.Cancelled&&(k=j()),((T=k.data)==null?void 0:T.reason)==="workspace_not_granted"&&g&&n.handlePermissionLost(),k.code===p.Cancelled?n.emit("tool:cancelled",v({},o)):n.emit("tool:error",E(v({},o),{code:k.code,message:k.message,reason:(R=k.data)==null?void 0:R.reason})),i(Bo(k))}finally{l.clear(),(J=r.signal)==null||J.removeEventListener("abort",d),u==null||u(),f==null||f()}})}function Uo(n,e){return h(this,null,function*(){var c;const t=n.getApprovalHandler();if(!t)throw new m(p.Forbidden,"当前环境未提供操作确认能力,无法执行写入或传输操作。",{reason:"approval_unavailable"});if(e.signal.aborted)throw j();const i=new AbortController,s=()=>i.abort();e.signal.addEventListener("abort",s,{once:!0});const r={id:_e.v4(),requestId:e.context.requestId,sessionId:e.context.sessionId,functionCode:e.functionCode,path:e.approvalPath,workspaceName:(c=n.displayName)!=null?c:"",preview:e.preview,signal:i.signal};e.timer.pause(),n.emit("tool:approval-required",E(v({},e.base),{path:e.approvalPath,approvalId:r.id}));let o;try{const a=yield Promise.race([Promise.resolve().then(()=>t(r)),Li(i.signal),new Promise(l=>{o=setTimeout(()=>l(!1),n.limits.approvalTimeoutMs)})]);if(e.signal.aborted)throw j();if(a!==!0)throw new m(p.Forbidden,"用户拒绝了本次操作。",{reason:"user_rejected"})}catch(a){throw a instanceof m?a:new m(p.Forbidden,"操作确认失败,已取消本次操作。",{reason:"user_rejected"})}finally{clearTimeout(o),e.signal.removeEventListener("abort",s),i.abort(),e.timer.resume()}})}function Ho({pluginCode:n,workspace:e}){const t={};return It.forEach(i=>{t[i]=(s,r,o)=>{let c=!1;jo(e,i,s,l=>{if(!c){c=!0;try{r(l)}catch(d){console.error("[LocalFiles] callback failed",d)}}},E(v({},o),{pluginCode:n}))}}),{[n]:t}}function Cn(){return{kind:"directory",children:new Map}}class qo{constructor(e={},t="memory-workspace"){y(this,"root",Cn());this.displayName=t,Object.entries(e).forEach(([i,s])=>this.seed(i,s))}seed(e,t="",i=Date.now()){const s=e.split("/").filter(Boolean);if(e.endsWith("/")){this.resolveDirectory(s,!0);return}const r=s.pop();if(!r)return;const o=this.resolveDirectory(s,!0),c=typeof t=="string"?new TextEncoder().encode(t):t;o.children.set(r,{kind:"file",data:c,lastModified:i})}resolveDirectory(e,t=!1){let i=this.root;for(const s of e){let r=i.children.get(s);if(!r){if(!t)throw S("NotFoundError");r=Cn(),i.children.set(s,r)}if(r.kind!=="directory")throw S("TypeMismatchError");i=r}return i}resolveNode(e){const t=P(e),i=t.pop();if(i===void 0)return this.root;const s=this.resolveDirectory(t).children.get(i);if(!s)throw S("NotFoundError");return s}stat(e){return h(this,null,function*(){var s;const t=this.resolveNode(e),i=(s=P(e).pop())!=null?s:this.displayName;return t.kind==="directory"?{name:i,kind:"directory"}:{name:i,kind:"file",size:t.data.byteLength,lastModified:t.lastModified}})}listEntries(e,t){return h(this,null,function*(){N(t);const i=this.resolveDirectory(P(e));return Array.from(i.children.entries()).map(([s,r])=>r.kind==="directory"?{name:s,kind:"directory"}:{name:s,kind:"file",size:r.data.byteLength,lastModified:r.lastModified})})}readFile(e){return h(this,null,function*(){const t=this.resolveNode(e);if(t.kind!=="file")throw S("TypeMismatchError");return new Blob([t.data])})}writeFile(s,r){return h(this,arguments,function*(e,t,i={}){const o=P(e),c=o.pop();if(!c)throw S("TypeMismatchError");const a=this.resolveDirectory(o,i.createDirectories),l=a.children.get(c);if((l==null?void 0:l.kind)==="directory")throw S("TypeMismatchError");const d=[];let u=0;try{for(var _=W(Tt(t)),w,b,A;w=!(b=yield _.next()).done;w=!1){const I=b.value;N(i.signal),d.push(I),u+=I.byteLength}}catch(b){A=[b]}finally{try{w&&(b=_.return)&&(yield b.call(_))}finally{if(A)throw A[0]}}N(i.signal);const f=new Uint8Array(u);let g=0;d.forEach(I=>{f.set(I,g),g+=I.byteLength}),a.children.set(c,{kind:"file",data:f,lastModified:Date.now()})})}createDirectory(e){return h(this,null,function*(){this.resolveDirectory(P(e),!0)})}remove(i){return h(this,arguments,function*(e,t={}){const s=P(e),r=s.pop();if(r===void 0)throw S("InvalidModificationError");const o=this.resolveDirectory(s),c=o.children.get(r);if(!c)throw S("NotFoundError");if(c.kind==="directory"&&c.children.size>0&&!t.recursive)throw S("InvalidModificationError");o.children.delete(r)})}move(e,t){return h(this,null,function*(){const i=P(e),s=P(t),r=i.pop(),o=s.pop();if(r===void 0||o===void 0)throw S("InvalidModificationError");const c=this.resolveDirectory(i),a=c.children.get(r);if(!a)throw S("NotFoundError");const l=this.resolveDirectory(s);if(Xn(e,t))throw S("InvalidModificationError");const d=l.children.get(o);if(d&&(d.kind==="directory"||a.kind==="directory"))throw S("InvalidModificationError");c.children.delete(r),l.children.set(o,a)})}}exports.AgentPlugin=mo;exports.BINARY_SNIFF_BYTES=xt;exports.BUILTIN_TOOLS_PLUGIN_CODE=Ae;exports.BUILTIN_TOOLS_PLUGIN_CODES=Fn;exports.BUILTIN_TOOL_SCHEMAS=Dt;exports.BotClient=po;exports.DEFAULT_DOWNLOAD_URL_ALLOWLIST=qn;exports.DEFAULT_IGNORED_DIRECTORIES=Wn;exports.DEFAULT_IGNORED_FILE_PATTERNS=zn;exports.DEFAULT_LIMITS=je;exports.FileSystemAccessAdapter=_i;exports.HOST_BRIDGE_GLOBAL=qe;exports.HOST_CHANNEL=Rt;exports.KiB=On;exports.LIST_DIRECTORY_DEFAULT_LIMIT=Dn;exports.LIST_DIRECTORY_MAX_LIMIT=Pn;exports.LOCAL_FILES_FUNCTION_CODES=It;exports.LOCAL_FILES_PLUGIN_CODES=Nn;exports.LOCAL_FILE_TOOL_SCHEMAS=ki;exports.LocalWorkspace=Ii;exports.MemoryWorkspaceAdapter=qo;exports.MiB=Le;exports.SDK_SENSITIVE_BASELINE=ti;exports.SEARCH_DEFAULT_DEPTH=Bn;exports.SEARCH_FUNCTION_CODES=Vn;exports.SEARCH_MAX_DEPTH=kt;exports.Session=zt;exports.TEXT_SEARCH_MAX_CONTEXT_LINES=Hn;exports.TEXT_SEARCH_MAX_FILES=jn;exports.TEXT_SEARCH_MAX_FILE_BYTES=Un;exports.TEXT_SEARCH_MAX_LINE_CHARS=Ue;exports.TRANSFER_FILE_SIZE_LIMIT_MB=$n;exports.TRANSFER_FUNCTION_CODES=Gn;exports.ToolCode=p;exports.ToolError=m;exports.WORKSPACE_GRANT_ID=be;exports.WRITE_FUNCTION_CODES=Pi;exports.configure=_t;exports.createDefaultSessionFileTransfer=qt;exports.createIndexedDbStore=Ei;exports.createLocalFilesPlugin=Ho;exports.createMemoryStore=Wt;exports.getDownloadUrlAllowlist=Ht;exports.getRegisteredLocalFilesPluginCode=pr;exports.isDownloadUrlAllowed=Cr;exports.registerHostBridge=Hi;exports.resolveLocalFilesPluginCode=fi;exports.toToolError=Ke;
|