@glodon-aiot/bot-client-sdk 3.26.0-alpha.11 → 3.26.0-alpha.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -13
- package/dist/es/Config.mjs +53 -68
- package/dist/es/index.mjs +61 -68
- package/dist/es/localFiles/adapters/HostBridgeAdapter.mjs +18 -28
- package/dist/es/localFiles/constants.mjs +24 -29
- package/dist/es/localFiles/schemas.mjs +22 -53
- package/dist/es/package.json.mjs +2 -2
- package/dist/lib/index.js +34 -34
- package/dist/src/Config.d.ts +1 -5
- package/dist/src/index.d.ts +1 -1
- package/dist/src/localFiles/adapters/HostBridgeAdapter.d.ts +0 -1
- package/dist/src/localFiles/constants.d.ts +2 -13
- package/dist/src/localFiles/index.d.ts +1 -1
- package/dist/src/localFiles/schemas.d.ts +0 -2
- package/dist/src/localFiles/types.d.ts +1 -21
- package/package.json +2 -2
package/dist/lib/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
…输出已截断`;function Xt(n){if(n.length<=
|
|
3
|
-
…输出已截断`;return t&&(r+=`,完整输出见 ${t}`),i&&(r+=",日志已截断"),s+r}class Wi{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=Zt(f);if(g){c.push(Qt(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+Hi),d=o+a.length;this.send(qi(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>X&&(c=!0),r=r.slice(-X)):(o+=g,o.length>X&&(a=!0),o=o.slice(-X));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:en(r,c,u,f),stderr:en(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=Zt(e);if(t){const s=Qt(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 tn(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 Vn{constructor(e,t="",i=new Wi){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 tn(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=>tn(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})}runPython(e,t,i,s){return h(this,null,function*(){return this.sandbox.exec({op:"run_python",path:e,args:t,timeoutMs:i},s)})}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=V(St(t)),u,f,g;u=!(f=yield l.next()).done;u=!1){const _=f.value;N(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 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 ot(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)=>ot(s,i,`${t}[${r}]`))}break;case"object":return Gn(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 Gn(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 Yn(n,e){return Gn(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,Vi=2e4,Xn=".",O="/workspace",Gi=[".py",".sh",".js"],Yi=["input","output","uploads","tmp"],xt="不要使用 input、output、uploads、tmp,也不要新建这些目录。请把文件直接放在工作区已有位置或根目录。",Xi=/(?:^|[\s'"=;|&<>`:])\/?(?:input|output|uploads|tmp)(?=\/|[\s'"=;|&<>`:]|$)/;function ze(n){return Xi.test(n)}function At(n){const e=n.split("/")[0];return Yi.includes(e)}function dt(n){throw new m(p.Forbidden,n,{reason:"path_outside_workspace"})}function Kn(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&&At(t[0]))throw new m(p.BadRequest,xt);return t.join("/")}function Se(n){return Kn(n)}function Ki(n){return Kn(n)}function Tt(n){return n?`/${n}`:"/"}function Ji(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!=="..")&&!At(e[0])}function kt(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 Jn="https://cv-cdn.obs.cn-north-4.myhuaweicloud.com/glodon/libs/",Qi="3.6.0",Zi=`${Jn}just-bash/${Qi}/just-bash.mjs`,es="314.0.7",ts=`${Jn}pyodide/${es}/`,Qn=["numpy","pandas","matplotlib","pillow","lxml"],Je=new Map;function ns(n){return import(n)}function is(n){let e=Je.get(n);return e||(e=ns(n).catch(t=>{throw Je.delete(n),t}),Je.set(n,e)),e}const nn=new Map;function ss(n){return/[\\^$.|+()[\]{}]/.test(n)?`\\${n}`:n}function rs(n,e=!1){const t=`${e?"s":"i"}:${n}`,i=nn.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+=ss(c)}const r=new RegExp(`^${s}$`,e?"":"i");return nn.set(t,r),r}function Ve(n,e,t=!1){return rs(n,t).test(e)}function Lt(n){const e=n.lastIndexOf("/");return e<0?n:n.slice(e+1)}const Zn=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"}]),os="该文件被列为敏感文件,不允许访问";class ei{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=[...Zn,...t]}match(e,t){if(!e)return null;const i=Lt(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||os},已拒绝访问。`}}function Ie(n,e,t){const i=n.sensitive.match(e,t);if(i)throw new m(p.Forbidden,ei.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(Xe(t).code===p.NotFound)return null;throw t}})}function Rt(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 z(n){return h(this,null,function*(){return new Uint8Array(yield n.arrayBuffer())})}function ae(n){const e=Math.min(n.byteLength,bt);for(let t=0;t<e;t++)if(n[t]===0)return!0;return!1}function as(n){return h(this,null,function*(){return ae(yield z(n.slice(0,bt)))})}function ti(n){return n[0]===239&&n[1]===187&&n[2]===191}function cs(n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch(e){throw new m(p.BadRequest,"文件不是 UTF-8 编码,暂不支持修改。")}}function Mt(n){return new TextEncoder().encode(n).byteLength}function ni(){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 ls=`# 在 Pyodide 里按 python3 命令行的语义运行代码。由 pyodideWorker.js 加载,最后一个表达式 run 交给 JS 调用。
|
|
1
|
+
"use strict";var xi=Object.defineProperty,Ai=Object.defineProperties;var Ti=Object.getOwnPropertyDescriptors;var Ne=Object.getOwnPropertySymbols;var Wt=Object.prototype.hasOwnProperty,zt=Object.prototype.propertyIsEnumerable;var Te=(n,e)=>{if(e=Symbol[n])return e;throw Error("Symbol."+n+" is not defined")};var Ke=(n,e,t)=>e in n?xi(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,v=(n,e)=>{for(var t in e||(e={}))Wt.call(e,t)&&Ke(n,t,e[t]);if(Ne)for(var t of Ne(e))zt.call(e,t)&&Ke(n,t,e[t]);return n},E=(n,e)=>Ai(n,Ti(e));var Vt=(n,e)=>{var t={};for(var i in n)Wt.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&Ne)for(var i of Ne(n))e.indexOf(i)<0&&zt.call(n,i)&&(t[i]=n[i]);return t};var w=(n,e,t)=>(Ke(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(d){s(d)}},o=a=>{try{c(t.throw(a))}catch(d){s(d)}},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},le=(n,e,t)=>{var i=(o,c,a,d)=>{try{var l=t[o](c),u=(c=l.value)instanceof te,f=l.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,d):a({value:g,done:f})).catch(g=>i("throw",g,a,d))}catch(g){d(g)}},s=o=>r[o]=c=>new Promise((a,d)=>i(o,c,a,d)),r={};return t=t.apply(n,e),r[Symbol.asyncIterator]=()=>r,s("next"),s("throw"),s("return"),r},Gt=n=>{var e=n[Te("asyncIterator")],t=!1,i,s={};return e==null?(e=n[Te("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[Te("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[Te("asyncIterator")])?e.call(n):(n=n[Te("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(d=>o({value:d,done:a}),c)))),t("next"),t("return"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _e=require("uuid"),ki=require("js-base64"),Li=require("axios"),A=require("@glodon-aiot/apis"),Ri=require("socket.io-client"),yt=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)}};w(re,"debug",!1);let U=re;const wt=["list_directory","read_file","stat_file","search_files","search_text","apply_patch","write_file","upload_file","download_file"],ke="builtin_tools",kn={dev:ke,test:ke,prod:ke,local:ke},Ln=kn,be="current-workspace",Rn=1024,Me=1024*1024,Mn=50,je=Object.freeze({maxReadBytes:1*Me,maxWriteBytes:5*Me,maxSearchResults:200,maxConcurrentRequests:4,maxTransferBytes:Mn*Me,toolTimeoutMs:3e4,searchTimeoutMs:6e4,transferTimeoutMs:10*6e4,approvalTimeoutMs:5*6e4}),Cn=200,Fn=1e3,On=8,vt=16,Nn=2e3,Dn=1*Me,Ue=500,Pn=3,_t=8*Rn,$n=Object.freeze(["glodon.com"]),Bn=Object.freeze([".git","node_modules",".svn",".idea",".vscode"]),jn=Object.freeze(["~$*",".~lock*","*.tmp"]),Mi=["apply_patch","write_file","upload_file","download_file"],Un=["search_files","search_text"],Hn=["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);w(this,"code");w(this,"data");this.name="ToolError",this.code=t,this.data=s}}const Ci="尚未授权工作文件夹,请先在助手中选择或恢复访问工作文件夹。";function bt(){return new m(403,Ci,{reason:"workspace_not_granted"})}function j(){return new m(499,"操作已取消。")}function O(n){if(n!=null&&n.aborted)throw j()}function Ye(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 bt();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,Fi=`
|
|
2
|
+
…输出已截断`;function Xt(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)+Fi}function Yt(n){return{exec(t){return h(this,null,function*(){const i=yield n.exec(t);return E(v({},i),{stdout:Xt(i.stdout),stderr:Xt(i.stderr)})})}}}function qn(n,e){return e===n||e.startsWith(`${n}/`)}function S(n,e=n){return new DOMException(e,n)}function Et(n){return le(this,null,function*(){typeof n=="string"?yield new TextEncoder().encode(n):n instanceof Uint8Array?yield n:yield*Gt(n)})}const St="glodon-workspace",qe="__glodonHostBridge",ye=2;function Oi(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===St)return t}function Kt(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 Ni(n){const e=globalThis;n?e[qe]=n:delete e[qe]}function Di(){var e;const n=Kt(globalThis[qe]);return n||Kt((e=globalThis.chrome)==null?void 0:e.webview)}const Pi=1024*1024;function $i(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 Jt(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 Qt(n){if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n)}function Zt(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 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 调用。
|
|
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
|
+
`,os=`// 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
|
-
`,lt=`浏览器环境不能安装依赖。可以直接 import ${
|
|
334
|
-
`,
|
|
333
|
+
`,lt=`浏览器环境不能安装依赖。可以直接 import ${Kn.join("、")},需要其他包请改用宿主环境。
|
|
334
|
+
`,as=10*1024*1024,cs=64*1024*1024;function ds(n){return!n||n==="."||n==="/"?F:n===F||n.startsWith(`${F}/`)?n:`${F}/${n.replace(/^\/+/,"")}`}function De(n){if(n===F)return"";if(n.startsWith(`${F}/`))return n.slice(F.length+1)}const ls=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 hs(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 us(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
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,lt):{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 Qe(n){var e;return n&&typeof n=="object"?String((e=n.name)!=null?e:""):""}function Ze(n){return n instanceof Error?n.message:String(n)}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,l;let a;try{a=yield t.listEntries(c,e)}catch(u){if(Qe(u)==="NotFoundError"||Qe(u)==="TypeMismatchError")return;throw u}s.dirs.push(c?`${
|
|
341
|
-
`,
|
|
342
|
-
`,exitCode:1}}})),u=new e.Bash({fs:a,cwd:t,env:{HOME:"/tmp",LANG:"C.UTF-8"},customCommands:[d("node",
|
|
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((T=e.signal)!=null&&T.aborted)throw S("AbortError");return{exitCode:d.exitCode,stdout:tt(d.stdout),stderr:tt(d.stderr),cwd:
|
|
345
|
-
${n.length>
|
|
337
|
+
`);if(!(ls.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:hs(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 Qe(n){var e;return n&&typeof n=="object"?String((e=n.name)!=null?e:""):""}function Ze(n){return n instanceof Error?n.message:String(n)}function nn(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 fs(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 ps{constructor(e){w(this,"state");w(this,"queue",Promise.resolve());w(this,"nextId",0);this.options=e}get indexURL(){return this.options.indexURL||Ki}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:fs)(os)}catch(o){throw this.loadError(`(${Ze(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 d=this.loadError(`(${c.message})`);t.reject(d),this.dispose(s,d)}else c.type==="result"&&((a=s.pending.get(c.id))==null||a.resolve(c),s.pending.delete(c.id))},e.onerror=o=>{var d;const c=Ze((d=o==null?void 0:o.message)!=null?d:o),a=this.loadError(`(${c})`);t.reject(a),this.dispose(s,new Error(`Python 运行环境意外退出:${c}`))},e.postMessage({type:"init",indexURL:this.indexURL,packages:Kn,runner:rs}),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=ds(e.cwd),i=us(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,nn(e.signal)]);const r=yield this.collect(e.signal),o=this.nextId+=1,c=new Promise((_,y)=>s.pending.set(o,{resolve:_,reject:y}));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,nn(e.signal,()=>this.dispose(s,S("AbortError")))]),d=[];if(r.skipped.length>0){const _=r.skipped.slice(0,5).map(b=>`/${b}`),y=r.skipped.length>_.length?` 等 ${r.skipped.length} 个`:"";d.push(`提示:${_.join("、")}${y}文件超过同步上限(单个 10 MB、合计 64 MB),Python 里看不到。`)}return{exitCode:(yield this.writeBack(a,r,d))&&a.exitCode===0?1:a.exitCode,stdout:a.stdout,stderr:a.stderr+d.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 d,l;let a;try{a=yield t.listEntries(c,e)}catch(u){if(Qe(u)==="NotFoundError"||Qe(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=(l=(d=u.size)!=null?d:(yield t.stat(f)).size)!=null?l:0;if(g>as||r+g>cs){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=(d,l)=>{o=!0,i.push(`写回 ${d} 失败:${Ze(l)}`)};for(const d of e.createdDirs.sort()){const l=De(d);!l||!s.createDirectory||(yield s.createDirectory(l).catch(u=>c(d,u)))}for(const{path:d,data:l}of e.written){const u=De(d);u&&(r.match(u,"write")?i.push(`没有写回 ${d}:敏感文件不能由命令修改。`):!t.synced.has(u)&&(yield this.exists(u))?i.push(`没有写回 ${d}:工作区里已有这个文件,但它没有同步进 Python,为避免覆盖已跳过。`):yield s.writeFile(u,l,{createDirectories:!0}).catch(f=>c(d,f)))}if(e.removed.length>0&&!s.remove)return i.push(`当前工作区不支持删除,${e.removed.join("、")} 仍然保留。`),o;for(const d of e.removed){const l=De(d);l&&(yield s.remove(l).catch(u=>{Qe(u)!=="NotFoundError"&&c(d,u)}))}const a=e.removedDirs.sort((d,l)=>l.split("/").length-d.split("/").length);for(const d of a){const l=De(d);l&&(yield s.remove(l).catch(()=>{}))}return o})}}const ms={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 R(n,e,t){var s;const i=new Error(`${n}: ${(s=ms[n])!=null?s:n}, ${e} '${t}'`);return i.code=n,i}function Pe(n){var e;return n&&typeof n=="object"?String((e=n.name)!=null?e:""):""}function et(n){const e=typeof n=="string"?n:n==null?void 0:n.encoding;return(e!=null?e:"utf8").toLowerCase()}function sn(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return e}function gs(n,e){switch(e){case"binary":case"latin1":case"ascii":return sn(n);case"base64":return btoa(sn(n));case"hex":return Array.from(n,t=>t.toString(16).padStart(2,"0")).join("");default:return new TextDecoder().decode(n)}}function rn(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 ys{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 R("EACCES",i,this.shown(e));return s}mapError(e,t,i){if(e&&typeof e=="object"&&typeof e.code=="string")return e;switch(Pe(e)){case"NotFoundError":return R("ENOENT",t,this.shown(i));case"TypeMismatchError":return R(t==="open"||t==="write"?"EISDIR":"ENOTDIR",t,this.shown(i));case"InvalidModificationError":return R(t==="rm"?"ENOTEMPTY":"EEXIST",t,this.shown(i));case"NotAllowedError":case"SecurityError":case"NoModificationAllowedError":return R("EACCES",t,this.shown(i));default:return R("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)&&Pe(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(Pe(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 R("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 gs(yield this.readFileBuffer(e),et(t))})}writeFile(e,t,i){return h(this,null,function*(){if(this.isRoot(e))throw R("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,rn(t,et(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=rn(t,et(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 R("EPERM","mkdir",this.shown(e));if(yield this.exists(e)){if(t!=null&&t.recursive)return;throw R("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 R("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 R("ENOTDIR","scandir",this.shown(e));let i;try{i=yield this.adapter.listEntries(this.relative(e))}catch(s){if(this.isRoot(e)&&Pe(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 R("EPERM","rm",this.shown(e));const i=this.guard(e,"write","rm");if(!(yield this.exists(e))){if(t!=null&&t.force)return;throw R("ENOENT","rm",this.shown(e))}if(!this.adapter.remove)throw R("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 R("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 R("EPERM","rename",this.shown(e));const i=this.guard(e,"write","rename"),s=this.guard(t,"write","rename");if(!this.adapter.move)throw R("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 R("EPERM","symlink",this.shown(t))})}link(e,t){return h(this,null,function*(){throw R("EPERM","link",this.shown(t))})}readlink(e){return h(this,null,function*(){throw yield this.entry(e,"readlink"),R("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 ws=`当前环境没有 Node,请改用 python3 或 shell 命令。
|
|
341
|
+
`,vs=new Set(["writeFile","appendFile","mkdir","rm","cp","mv","chmod","symlink","link","utimes","createExclusive"]),_s="dev|bin|usr|proc|etc|System|Library|private|var|opt|sbin|tmp|Applications|Volumes|cores|net|home",bs=new RegExp(`(^|[\\s'"=(;|&<>\`:])/(?!${_s}(?=$|[/\\s'"\`;|&)<>:]))(?!/)`,"g");function Es(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 d;const a=String((d=c[0])!=null?d:"");if(e&&vs.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 Ss(n){return n instanceof Uint8Array?n:Uint8Array.from(String(n!=null?n:""),e=>e.charCodeAt(0)&255)}function Is(n){return n instanceof DOMException&&n.name==="AbortError"}function xs(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 on(n){return!n||n==="."?F:n===F||n.startsWith(`${F}/`)?n:`${F}/${n.replace(/^\/+/,"")}`}function As(n){return n.replace(bs,(e,t)=>`${t}${F}/`)}function tt(n){return n.replace(/\/workspace(?![\p{L}\p{N}_.\-])/gu,(e,t,i)=>i[t+e.length]==="/"?"":"/")}class Ts{constructor(e){w(this,"python");this.options=e,this.python=new ps({adapter:e.adapter,sensitive:e.sensitive,indexURL:e.pyodideIndexURL,createWorker:e.createWorker})}load(){return h(this,null,function*(){const e=this.options.moduleURL||Xi;try{return yield Qi(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=Es(new e.InMemoryFs),a=new e.MountableFs({base:c.fs});a.mount(F,new ys(r,"",o));const d=(f,g,_)=>e.defineCommand(f,()=>h(this,null,function*(){return{stdout:"",stderr:g,exitCode:_}})),l=f=>e.defineCommand(f,(g,_)=>h(this,null,function*(){var y;try{return yield this.python.run({args:g,cwd:_.cwd,stdin:Ss(_.stdin),signal:i})}catch(b){return b instanceof m||Is(b)?((y=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:[d("node",ws,127),d("pip",lt,1),d("pip3",lt,1),l("python3"),l("python")],defenseInDepth:!1});return c.lock(),u}exec(e){return h(this,null,function*(){var l,u,f,g,_,y,b,T,I;if(xt(e.cwd)||ze((l=e.command)!=null?l:"")||ze((f=(u=e.argv)==null?void 0:u[1])!=null?f:""))return{exitCode:1,stdout:"",stderr:`${It}
|
|
343
|
+
`};const t=yield this.load();if((g=e.signal)!=null&&g.aborted)throw S("AbortError");const i=on(e.cwd),s={},r=this.create(t,i,e.signal,s),[o,c,...a]=(_=e.argv)!=null?_:[];let d;try{d=e.argv?yield r.exec(o,{cwd:i,signal:e.signal,args:[on(c),...a]}):yield r.exec(As((y=e.command)!=null?y:""),{cwd:i,signal:e.signal,rawScript:!0})}catch(k){if(s.fatal)throw s.fatal;if((b=e.signal)!=null&&b.aborted)throw S("AbortError");const L=k instanceof Error?k.message:String(k);return{exitCode:1,stdout:"",stderr:`bash: ${tt(L)}
|
|
344
|
+
`}}if(s.fatal)throw s.fatal;if((T=e.signal)!=null&&T.aborted)throw S("AbortError");return{exitCode:d.exitCode,stdout:tt(d.stdout),stderr:tt(d.stderr),cwd:xs((I=d.env)==null?void 0:I.PWD)}})}}const ne=n=>({type:"string",minLength:1,description:n}),fe="必填。工作区内绝对路径,以 / 开头,例如 /说明.md。不要使用 /input、/output、/uploads、/tmp,也不要新建这些目录。",Mt={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:Ui,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。",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:"单个脚本参数。"}}}}}},an=Object.keys(Mt);if(an.length!==at.length||at.some(n=>!an.includes(n)))throw new Error("BUILTIN_TOOL_SCHEMAS 与 BUILTIN_FUNCTION_CODES 不一致");const cn=500;function we(n){return`预览:
|
|
345
|
+
${n.length>cn?n.slice(0,cn):n}`}function ks(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 dn(n,e){var d,l;const t=n.match(/<([A-Za-z_][\w:.-]*)\b/),i=(d=t==null?void 0:t[1])!=null?d:"未知",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,((l=s.get(u))!=null?l: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 ln(n,e,t){var a;const i=n.split(/\r?\n/).filter(d=>d.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 Ls(n){const e=Ce(n);return e===".json"||e===".xml"||e===".svg"||e===".csv"||e===".tsv"}function Rs(n,e){const t=Ce(n);return t===".json"?ks(e):t===".svg"?dn(e,"SVG"):t===".xml"?dn(e,"XML"):t===".tsv"?ln(e," ","TSV"):t===".csv"?ln(e,",","CSV"):we(e)}function Ce(n){var i;const e=(i=n.split("/").pop())!=null?i:"",t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}const Ms=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".tif",".tiff"]);function ti(n){return Ms.has(Ce(n))}function ni(n,e){return Ce(n)===".pdf"?!0:!e||e.byteLength<4?!1:e[0]===37&&e[1]===80&&e[2]===68&&e[3]===70}function Ct(n){return!!n&&typeof n=="object"&&n.name==="NotFoundError"}function Fe(n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch(e){throw new m(p.BadRequest,"文件不是 UTF-8 文本。")}}function Ft(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 xe(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
|
|
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 d=0;d<t.length;d+=1){const l
|
|
360
|
-
`)}}function
|
|
355
|
+
`)}function Cs(n,e,t){if(e!==void 0&&t!==void 0&&t<e)throw new m(p.BadRequest,"end_line 不能小于 start_line。");const i=Ft(n),s=Math.max((e!=null?e:1)-1,0),r=t!=null?t:i.length;return i.slice(s,r).join(`
|
|
356
|
+
`)}function hn(n){if(Rt(n)<=ct)return{text:n,truncated:!1};const e=new TextEncoder().encode(n);let t=ct;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 xe(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 un(n,e,t){const i=typeof t=="number"?`${t} 字节,`:"";return`${n},${i}路径 ${At(e)}。不返回正文。`}function Ot(n){const e=Ce(n);if(!Hi.includes(e))throw new m(p.BadRequest,"只能执行 .py、.sh 或 .js 文件。");return e===".py"?"python3":e===".js"?"node":"sh"}function ii(n){if(!n.runner)throw new m(p.NotImplemented,"当前环境不能执行命令或脚本,需要端侧宿主。");return n.runner}function Nt(n,e,t,i){return h(this,null,function*(){yield n.writeFile(e,t,{createDirectories:!0,signal:i})})}function Fs(n,e){return h(this,null,function*(){const t=Se(n.path);if(O(e.signal),ti(t)){const a=yield e.adapter.stat(t);if(a.kind!=="file")throw new m(p.BadRequest,"目标是目录,不是文件。");return{data:{content:un("图片",t,a.size),truncated:!1}}}const{entry:i,bytes:s}=yield xe(e.adapter,t);if(ni(t,s))return{data:{content:un("PDF",t,i.size),truncated:!1}};if(ae(s))throw new m(p.BadRequest,"文件不是文本,无法读取正文。");const r=Fe(s);if(n.start_line!==void 0||n.end_line!==void 0){const a=Cs(r,n.start_line,n.end_line),d=hn(a);return{data:{content:d.text,truncated:d.truncated}}}if(s.byteLength>ct&&Ls(t))return{data:{content:Rs(t,r),truncated:!0}};const c=hn(r);return{data:{content:c.text,truncated:c.truncated}}})}function Os(n,e){return h(this,null,function*(){const t=Se(n.path);if(Rt(n.content)>We)throw new m(p.TooLarge,`content 按 UTF-8 计超过 ${We} 字节。请缩短后写入,或改用 append_file、edit_file。`);return O(e.signal),yield Nt(e.adapter,t,n.content,e.signal),{data:{}}})}function Ns(n,e){return h(this,null,function*(){const t=Se(n.path);O(e.signal);let i="";try{const{bytes:s}=yield xe(e.adapter,t);if(ae(s))throw new m(p.BadRequest,"文件不是文本,无法追加。");i=Fe(s)}catch(s){if(!Ct(s))throw s}return yield Nt(e.adapter,t,i+n.content,e.signal),{data:{}}})}function Ds(n,e){return h(this,null,function*(){const t=Se(n.path);O(e.signal);const{bytes:i}=yield xe(e.adapter,t);if(ae(i))throw new m(p.BadRequest,"文件不是文本,无法修改。");const s=Fe(i),r=s.indexOf(n.old_text);if(r<0){const c=Ps(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 Nt(e.adapter,t,o,e.signal),{data:{}}})}function Ps(n,e){var a;const t=Ft(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 d=0;d<t.length;d+=1){const l=$s(t[d],s);l>o&&(o=l,r=d)}const c=Math.min(Math.max(i.length,1),8);return{line:r+1,excerpt:t.slice(r,r+c).join(`
|
|
360
|
+
`)}}function $s(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 Bs(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":ht(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:ht(i)}return new RegExp(e)}function ht(n){return/[\\^$.*+?()[\]{}|]/.test(n)?`\\${n}`:n}function js(n){try{return Bs(n)}catch(e){throw new m(p.BadRequest,"pattern 不是合法的 grep 基本正则。")}}function Dt(n,e,t,i,s){return h(this,null,function*(){if(i>16)return;O(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 Dt(n,a,t,i+1,s)}})}function Us(n,e){return h(this,null,function*(){const t=Se(n.path),i=js(n.pattern),s=[];yield Dt(e.adapter,t,e.signal,0,(o,c)=>h(this,null,function*(){if(c!=="file"||s.length>=200)return;const{bytes:a}=yield xe(e.adapter,o);if(ae(a)||ti(o)||ni(o,a))return;let d;try{d=Fe(a)}catch(u){return}const l=Ft(d);for(let u=0;u<l.length&&s.length<200;u+=1){if(!i.test(l[u]))continue;const f=l[u].length>500?`${l[u].slice(0,500)}…`:l[u];s.push(`${At(o)}:${u+1}:${f}`)}}));const r=s.join(`
|
|
361
361
|
`);return{data:{matches:s.length>=200?`${r}
|
|
362
|
-
(匹配过多,已截断)`:r}}})}function
|
|
362
|
+
(匹配过多,已截断)`:r}}})}function Hs(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+=ht(s)}return new RegExp(`${t}$`).test(e)}function qs(n,e){return h(this,null,function*(){const t=Se(n.path),i=[];yield Dt(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;Hs(n.name,o)&&i.push(At(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 hi(n,e,t){return new A.CVForceApi(ui(n,"/data/v1",e,t),fi(t))}function wr(n,e,t){return new A.AIShopApi(ui(n,"/aishop",e,t),fi(t))}function ui(n,e,t,i){const s=o=>{var c;return t&&(pr(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=Mi.create({baseURL:a});return c&&d.interceptors.request.use(s),d}return r(e)}function fi(n){return{onHttpStatusError:(i,s)=>{i===401&&n(i,"aiotToken is invalid")},onAppStatusError:(i,s)=>{i!==10001&&i!==10215&&n(i,s)}}}function vr(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 _r(n){ie==null||ie(),ie=void 0;const e=ji();if(!e)return()=>{};const t=new Vn(e),i=r=>{const o=Bi(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(vr(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:It,type:"hello"});const s=()=>{e.removeEventListener("message",i),ie===s&&(ie=void 0)};return ie=s,s}const se=new H("[EventBus] ");class $t{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 br="路径必须是工作区内的相对路径,不能包含 ..、绝对路径或盘符。";function $e(){return new m(p.Forbidden,br,{reason:"path_outside_workspace"})}function Er(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 Sr(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}function pi(n,e){return n?`${n}/${e}`:e}function pe(n,e){return!!n&&typeof n=="object"&&n.name===e}class mi{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=V(i.values()),o,c,a;o=!(c=yield r.next()).done;o=!1){const d=c.value;if(N(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=V(St(t)),g,_,y;g=!(_=yield f.next()).done;g=!1){const b=_.value;N(i.signal),yield u.write(b)}}catch(_){y=[_]}finally{try{g&&(_=f.return)&&(yield _.call(f))}finally{if(y)throw y[0]}}N(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 gn(c,r),d=yield this.resolveDirectory(s);if(zn(e,t))throw S("InvalidModificationError");let l;try{l=yield gn(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 gi(a,d,o),yield c.removeEntry(r,{recursive:!0})})}}function gn(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 gi(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=V(n.values()),r,o,c;r=!(o=yield s.next()).done;r=!1){const a=o.value;yield gi(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 Ir(){if(typeof window=="undefined")return;const n=window.showDirectoryPicker;return typeof n=="function"?n.bind(window):void 0}const xr=/^[a-z0-9-]+(\.[a-z0-9-]+)+$/;function Ar(n){if(typeof n!="string")return null;const e=n.trim().toLowerCase().replace(/^\*?\./,"").replace(/\.$/,"");return!xr.test(e)||yi(e)?null:e}function yi(n){return n.startsWith("[")||n.includes(":")?!0:/^[0-9.]+$/.test(n)||/^0x[0-9a-f.]+$/i.test(n)}function Bt(n=[]){const e=new Set(Un);for(const t of n){const i=Ar(t);i&&e.add(i)}return Array.from(e)}function Tr(n,e){return mt(n,Bt(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||yi(i)||i==="localhost"||i.endsWith(".localhost")?!1:e.some(s=>i===s||i.endsWith(`.${s}`))}function kr(n={}){const e=v({},Ue);return Object.keys(Ue).forEach(t=>{const i=n[t];typeof i=="number"&&Number.isFinite(i)&&i>0&&(e[t]=Math.min(i,Ue[t]))}),e}function me(){return new m(p.Internal,"平台文件服务请求失败,请稍后重试。")}function Ut(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 Lr(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 Lr(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 Rr="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 Mr(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}function wi(n=Rr){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 Mr(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 yn(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 Cr(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=yn(o.relativePathComponents),a=yn(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 Or(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 Nr(n){return!!n&&typeof n=="object"&&n.name==="AbortError"}class vi{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 $t(!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:Ir(),this.limits=kr(t.limits),this.sensitive=new ei(t.sensitiveRulesAppend),this.downloadUrlAllowlist=Bt(t.downloadUrlAllowlistAppend),this.allowWorkspaceWideTextSearch=!!t.allowWorkspaceWideTextSearch,this.approvalHandler=t.onApprovalRequired;const i=(d=e.transfer)!=null?d:Ut(()=>{});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 mi(e),this.setStatus("granted",e.name),this.unwatchDirectory(),this.stopWatching=Cr(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(Nr(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=Or(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 wn=100,D=new H("[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 Ht{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 $t);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){D.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)>wn)throw Error(`knowledges and fileIds total count cannot exceed ${wn}`);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(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)===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,D.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return hi(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,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),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(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 D.error(y),this.event.emit("error",y),!1}if(!this._id){const y=new Error("session id is not defined");return D.error(y),this.event.emit("error",y),!1}if(this.frozen){const y=new Error("session is frozen");return D.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=yr(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(mr).map(gr).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 q=new H("[AgentSession] ");function vn(n){if(typeof n!="string")return n;const e=n.trim();if(e)try{return JSON.parse(e)}catch(t){return n}}function _n(n){return n==null||n===""||typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function Fr(n,e){const t=vn(n==null?void 0:n.query);if(!_n(t))return t;const i=vn(e);return _n(i)&&t!=null?t:i}class Pr extends Ht{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 Ci.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:i,transports:["websocket"]});r.on("connect",()=>{q.log("socket:connect"),this.event.emit("socket:connect"),r.emit("init")}),r.on("disconnect",()=>{q.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),r.on("ready",o=>{if(o.code===200){q.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);q.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);q.warn("error",b),this.event.emit("error",b)}else if(a==="FUNCTION_CALL"&&d){q.log(`calling function ${u} of plugin ${l} with argument:
|
|
367
|
-
${JSON.stringify(f)}`);const b=(y=exports.configuration.plugins)==null?void 0:y[l];if(!b){c({code:404,message:"没有找到插件。"});return}const T=b[u];if(typeof T!="function"){c({code:404,message:"没有找到插件方法。"});return}const I=
|
|
364
|
+
(结果过多,已截断)`:s}}})}function si(n,e,t){return h(this,null,function*(){const i=ii(t);yield xe(t.adapter,n);const s=yield i.exec({argv:[Ot(n),n,...e],cwd:Gn,timeoutMs:t.timeoutMs,signal:t.signal});return{data:{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr}}})}function Ws(n,e){return h(this,null,function*(){const t=zi(n.path);return Ot(t),si(t,[],e)})}function zs(n,e){return h(this,null,function*(){if(ze(n.command)||ze(e.shellCwd.cwd))return{data:{exitCode:1,stdout:"",stderr:`${It}
|
|
365
|
+
`}};const i=yield ii(e).exec({command:n.command,cwd:e.shellCwd.cwd,timeoutMs:e.timeoutMs,signal:e.signal});return i.cwd&&Vi(i.cwd)&&(e.shellCwd.cwd=i.cwd),{data:{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}})}function ri(n,e){return h(this,null,function*(){try{const{bytes:t}=yield xe(e.adapter,n);if(ae(t))throw new m(p.BadRequest,"技能资源不是文本。");return Fe(t)}catch(t){throw Ct(t)?new m(p.NotFound,"技能或资源不存在。"):t}})}function Vs(n,e){return h(this,null,function*(){return{data:{content:yield ri(Tt(n.skill_name,"SKILL.md"),e)}}})}function Gs(n,e){return h(this,null,function*(){return{data:{content:yield ri(Tt(n.skill_name,n.resource_name),e)}}})}function Xs(n,e){return h(this,null,function*(){var i;const t=Tt(n.skill_name,n.script_name);Ot(t);try{return yield si(t,(i=n.args)!=null?i:[],e)}catch(s){throw Ct(s)?new m(p.NotFound,"技能脚本不存在。"):s}})}const Ys={shell:zs,read_file:Fs,write_file:Os,append_file:Ns,run_file:Ws,edit_file:Ds,grep:Us,find:qs,load_skill:Vs,read_skill_resource:Gs,run_skill_script:Xs},Le=new U("[BuiltinTools] "),fn=new Set(["shell","run_file","run_skill_script"]);function Ks(n,e,t){var i,s;if(n.commandRunner)return Yt(n.commandRunner);if(e instanceof Wn){if(e.protocolMismatch){const r=`${(i=e.sandboxVersion)!=null?i:""}@${(s=e.sandboxProtocol)!=null?s:""}`;t.rejectedSandbox!==r&&(t.rejectedSandbox=r,Le.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=Yt(new Ts({adapter:e,sensitive:n.sensitive,moduleURL:n.browserRuntime.bashModuleURL,pyodideIndexURL:n.browserRuntime.pyodideIndexURL}))),t.runner}function Js(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch(e){throw new m(p.BadRequest,"参数不是合法的 JSON 对象。")}}function Qs(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 Zs(n){return new Promise((e,t)=>{n.aborted&&t(j()),n.addEventListener("abort",()=>t(j()),{once:!0})})}function oi(n,e=160){return n.length>e?`${n.slice(0,e)}…`:n}function er(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=oi(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 tr(n){return v({code:n.code,message:n.message},n.data?{data:n.data}:{})}function nr({pluginCode:n,workspace:e}){const t=new Map,i={},s={};return at.forEach(r=>{s[r]=(o,c,a)=>{let d=!1;ir(e,t,i,r,o,u=>{if(!d){d=!0;try{c(u)}catch(f){console.error("[BuiltinTools] callback failed",f)}}},E(v({},a),{pluginCode:n}))}}),{[n]:s}}function ir(n,e,t,i,s,r,o){return h(this,null,function*(){var T,I,k,L,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},d=new AbortController;let l=!1;const u=setTimeout(()=>{l=!0,d.abort()},n.limits.toolTimeoutMs),f=()=>d.abort();(T=c.signal)==null||T.addEventListener("abort",f,{once:!0}),(I=c.signal)!=null&&I.aborted&&d.abort();let g=null,_=null,y;const b=Date.now();try{const N=Js(s),x=Vn(N,Mt[i].parameters);if(typeof x.path=="string"&&(a.path=x.path),Le.log("start",v(v({},a),er(x))),yield n.ready,d.signal.aborted)throw j();const M=n.adapter;if(!M)throw bt();if(g=n.acquireSlot(),!g)throw new m(p.TooManyRequests,"同时进行的文件操作过多,请稍后重试。");if(fn.has(i)&&(_=n.acquireCommand(),!_))throw new m(p.TooManyRequests,"已有一个命令在运行,请等它结束后再试。");y=n.track(d),n.emit("tool:start",v({},a));const C=c.sessionId||"default";let D=e.get(C);D||(D={cwd:Gn},e.set(C,D));const ce=Ks(n,M,t),de=D.cwd,Ae={adapter:M,runner:ce,signal:d.signal,timeoutMs:n.limits.toolTimeoutMs,shellCwd:D},Q=yield Promise.race([Ys[i](x,Ae),Zs(d.signal)]),Oe={code:p.Ok,message:"ok",data:Q.data};Q.truncated&&(Oe.truncated=!0);const Ii=Date.now()-b,qt=Q.data.exitCode;Le.log("finish",v(v(v(E(v({},a),{elapsedMs:Ii,code:p.Ok}),Q.truncated?{truncated:!0}:{}),typeof qt=="number"?{exitCode:qt}:{}),i==="shell"?{cwd:D.cwd,cwdChanged:D.cwd!==de}:{})),n.emit("tool:finish",E(v({},a),{code:p.Ok})),fn.has(i)&&n.notifyFilesChanged(),r(Oe)}catch(N){let x=(k=Qs(N))!=null?k:Ye(N);l?x=new m(p.Timeout,"操作超时,已中止。"):d.signal.aborted&&x.code!==p.Cancelled&&(x=j());const M=Date.now()-b;x.code===p.Cancelled?(Le.log("cancelled",E(v({},a),{elapsedMs:M,timedOut:l})),n.emit("tool:cancelled",v({},a))):(Le.error("error",E(v({},a),{elapsedMs:M,code:x.code,message:oi(x.message,300)})),n.emit("tool:error",E(v({},a),{code:x.code,message:x.message,reason:(L=x.data)==null?void 0:L.reason}))),r(tr(x))}finally{clearTimeout(u),(J=c.signal)==null||J.removeEventListener("abort",f),g==null||g(),_==null||_(),y==null||y()}})}const sr=new U("[Config] ");var ai=(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))(ai||{});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 ut=new Set;function pn(n){ve!==n&&(ve=n,X=void 0,ut.clear())}function rr(){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 ci(n,e){return(n==null?void 0:n.pluginCode)||Ln[e]}function or(){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?ci(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:nr({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 ft(){return or().filter(n=>!ut.has(n)).map(n=>(ut.add(n),console.error(n),new Error(n)))}function pt(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?ai[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&&ft(),U.debug&&sr.log("updated",exports.configuration)}const Ge=n=>JSON.parse(ki.decode(n.split(".")[1])),ar=n=>{const e=Ge(n).exp;return new Date().valueOf()/1e3>=e},cr=n=>n==null?void 0:n.replace(/[\r\n]+/gm,""),dr=n=>n.replace(/\\|\\/g,""),lr=(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 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=(y=exports.configuration.plugins)==null?void 0:y[l];if(!b){c({code:404,message:"没有找到插件。"});return}const T=b[u];if(typeof T!="function"){c({code:404,message:"没有找到插件方法。"});return}const I=kr(f,g);this.invokeClientPlugin(T,I,c,{requestId:o.requestId,pluginCode:l,functionCode:u})}})),r.on("answer",o=>{if(!this._stopAnswer)if(o.data.code!==200&&(o.data.index=-1),o.data.stream||o.data.stream===void 0){let c=this.messages[this.messages.length-1];if(c&&c.role===A.ChatMessageRole.Robot)this.handleStreamAnswer(o.data,c),this.messages[this.messages.length-1]=c,this.event.emit("message:content",c),this.event.emit("message:updated",c),c.index===-1&&(c.isReplying=!1,this.event.emit("answer:finish",c));else{const a={content:"",role:A.ChatMessageRole.Robot,reference:[],searchReference:[],messageId:"",sessionId:this.id,messageTime:yt(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""};this.handleStreamAnswer(o.data,a),this.pushMessage(a),this.event.emit("message:content",a),a.index===-1&&(a.isReplying=!1,this.event.emit("answer:finish",a))}}else if(o.data.updateSession&&this.data&&(this.data=v(v({},this.data),o.data.updateSession),this.event.emit("data:updated",this.data)),o.data.index===-1){let c=this.messages[this.messages.length-1];if(c&&!c.messageId)c=v(v({},c),o.data),this.event.emit("message:content",c),this.event.emit("message:updated",c),this.event.emit("answer:finish",c);else{const a=v({messageId:"",content:"",role:A.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.data);this.event.emit("message:content",a),this.pushMessage(a),this.event.emit("answer:finish",a)}}else{let c=this.messages[this.messages.length-1];c&&!c.messageId?(c=v(v({},c),o.data),this.messages[this.messages.length-1]=c,this.event.emit("message:content",c),this.event.emit("message:updated",c)):(this.pushMessage(v({messageId:"",content:"",role:A.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.data)),this.event.emit("message:content",o.data))}}),r.on("reference",o=>h(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const f=new Error(Re.IdUndefined);H.error(f),this.event.emit("error",f),this.frozen=!1;return}const{type:c,data:a,requestId:d}=o,l=this.messages.findIndex(f=>f.messageId===d&&f.role===A.ChatMessageRole.User);if(l<0)return;const u=l+1;if(u>=this.messages.length){const f={messageId:"",content:"",role:A.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0};this.pushMessage(f)}c==="KG"?(this.messages[u]=E(v({},this.messages[u]),{reference:a.knowledgeReference}),yield this.fillMessageReference(this.messages[u]),this.event.emit("message:reference",a.knowledgeReference),this.event.emit("message:updated",this.messages[u])):c==="WEB_SEARCH"&&(this.messages[u]=E(v({},this.messages[u]),{searchReference:a.knowledgeReference}),this.event.emit("message:searchreference",a.searchReference),this.event.emit("message:updated",this.messages[u]))})),this.socket=r,r.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((t,i)=>{if(!this.socket){i("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,s=>{s.code===200?(Object.keys(s.data).forEach(r=>{s.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",s.data[r])}),t(!0)):(console.error("MCP Server 注册失败。",s),i(s))})}):Promise.resolve(!0)}addMcpServers(t){return h(this,null,function*(){return this.ready?this.socket?new Promise((i,s)=>{this.socket&&this.socket.emit("add_mcp_servers",t,r=>{r.code===200?(Object.keys(r.data).forEach(o=>{r.data[o].code!==200&&console.error(o,"MCP Server 注册失败。",r.data[o])}),i(!0)):(console.error("MCP Server 注册失败。",r),s(r))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return h(this,null,function*(){return this.ready?this.socket?new Promise((t,i)=>{this.socket&&this.socket.emit("list_mcp_servers",s=>{s.code===200?t(s.data):i(s)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(t,i){return h(this,null,function*(){var r,o,c;this.convertKnowledgesToChatFormat(this.knowledges);let s=E(v({},t),{promptVariables:this.promptVariables.filter(a=>a.type===A.PromptVariableType.User).reduce((a,d)=>E(v({},a),{[d.key]:d.value}),{}),systemPromptVariables:this.promptVariables.filter(a=>a.type===A.PromptVariableType.System).reduce((a,d)=>E(v({},a),{[d.key]:d.value}),{}),knowledges:(r=this.knowledges)==null?void 0:r.map(a=>a.id),enableTitleSummary:this.resolveEnableTitleSummary()});if(!this.active){if(yield this.activate(),!this.socket){const a=new Error(Re.SocketConnectionFailed);return H.warn("error",a),this.event.emit("error",a),!1}(o=this.socket)==null||o.emit("question",s);return}(c=this.socket)==null||c.emit("question",s)})}invokeClientPlugin(t,i,s,r){const o=new AbortController;this.inflightCalls.add(o);let c=!1;const a=(...l)=>{c||(c=!0,this.inflightCalls.delete(o),!(this._stopAnswer||o.signal.aborted)&&s(...l))},d={requestId:r.requestId||_e.v4(),applicationId:this._applicationId,sessionId:this.id,pluginCode:r.pluginCode,functionCode:r.functionCode,signal:o.signal};try{const l=t(i,a,d);l&&typeof l.catch=="function"&&l.catch(u=>{H.error("client plugin failed",u),a({code:500,message:"客户端插件执行失败。"})})}catch(l){H.error("client plugin failed",l),a({code:500,message:"客户端插件执行失败。"})}}abortClientPluginCalls(){const t=Array.from(this.inflightCalls);this.inflightCalls.clear(),t.forEach(i=>i.abort())}stopAnswer(){var t;this.abortClientPluginCalls(),(t=this.socket)==null||t.emit("stop_answer")}inactivate(t=!1){return this.abortClientPluginCalls(),super.inactivate(t)}destroy(){return this.abortClientPluginCalls(),super.destroy()}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}function Rr(n,e){return h(this,null,function*(){const t=n.getReader();let i;for(;!(i=yield t.read()).done;)e(i.value)})}function Mr(n){let e,t,i,s=!1,r;return function(c){e===void 0?(e=c,t=0,i=-1,r=!1):e=Fr(e,c);const a=e.length;let d=0;for(;t<a;){s&&(e[t]===10&&(d=++t),s=!1);let l=-1;for(;t<a&&l===-1;++t)switch(e[t]){case 58:i===-1&&(i=t-d);break;case 13:s=!1,t+4<a&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(r=!0);case 10:l=t;break}if(l===-1)break;n(e.subarray(d,l),i,r),d=t,i=-1,r=!1}d===a?e=void 0:d!==0&&(e=e.subarray(d),t-=d)}}function Cr(n,e,t){let i=_n();const s=new TextDecoder;return function(o,c,a){if(o.length===0)t==null||t(i),i=_n();else if(c>0){const d=s.decode(o.subarray(0,c)),l=c+(o[c+1]===32?2:1);let u=s.decode(o.subarray(l));switch(a&&(u+=`
|
|
368
368
|
`),d){case"data":i.data=i.data?i.data+`
|
|
369
|
-
`+u:u;break;case"event":i.event=u;break;case"id":n(i.id=u);break;case"retry":const f=parseInt(u,10);isNaN(f)||e(i.retry=f);break}}}}function Ur(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function bn(){return{data:"",event:"",id:"",retry:void 0}}const gt="text/event-stream",jr=1e3,En="last-event-id";function Sn(n,l){var u=l,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:c,fetch:a}=u,d=Gt(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||F()}c||document.addEventListener("visibilitychange",b);let T=jr,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:Hr;function F(){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 Dr(M.body,$r(Br(C=>{C?_[En]=C:delete _[En]},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(F,C)}catch(C){k(),g(C)}}})}F()})}function Hr(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 In=new H("[DialogSession] ");class qr extends Ht{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});Sn(`${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});Sn(`${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:()=>{In.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||(In.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 Wr="@glodon-aiot/bot-client-sdk",zr="3.26.0-alpha.11",Vr="glodoncv",Gr="aiot bot client js sdk",Yr="module",Xr=!1,Kr=["aiot","bot","bot client","sdk"],Jr=["dist"],Qr="./dist/es/index.mjs",Zr="./dist/lib/index.js",eo="./dist/src/index.d.ts",to={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},no="MIT",io={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"},so={"@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"},ro={access:"public",registry:"https://registry.npmjs.org/"},oo={"@glodon-aiot/apis":"^3.26.0-alpha.11",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"},ao={name:Wr,version:zr,author:Vr,description:Gr,type:Yr,sideEffects:Xr,keywords:Kr,files:Jr,module:Qr,main:Zr,typings:eo,exports:to,license:no,scripts:io,devDependencies:so,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:ro,dependencies:oo},xn=new H("[BotClient] ");class co{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){w(this,"event",new $t);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)){mn(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=wr(exports.configuration.apiRoot,this.token,(c,a)=>xn.error(a));this._localWorkspace=new vi({applicationId:this._applicationId,config:e,store:wi(),picker:i==="host-bridge"?null:void 0,transfer:Ut(()=>this.cvforceApi,()=>o)}),mn(this._localWorkspace),i==="host-bridge"?this._disconnectHost=_r(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:ao.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:hi(exports.configuration.apiRoot,this.token,(e,t)=>xn.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 Pr(e,t,i,s,r,o));else if(l===A.ApplicationTypes.Dialog)c(new qr(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 lo{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 G="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",W={type:"string",enum:[be],description:`工作区 ID。省略时按 ${be} 处理,传其他值会被拒绝。`},Y=n=>({type:"string",description:`${n}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),it={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},_i={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${G}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:W,path:Y('要列出的目录,省略或传 "." 表示工作区根目录。'),offset:{type:"integer",minimum:0,description:"分页起始位置,默认 0。"},limit:{type:"integer",minimum:1,maximum:1e3,description:"每页条数,默认 200。"}}}},read_file:{functionCode:"read_file",name:"读取本地文件",description:`${G}按行读取文本文件,单次最多返回 1 MiB,超出部分会被截断(truncated: true)。返回内容的 hash 可用于后续修改。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:W,path:Y("要读取的文件。"),startLine:{type:"integer",minimum:1,description:"起始行(从 1 开始,含)。"},endLine:{type:"integer",minimum:1,description:"结束行(含)。"},maxBytes:{type:"integer",minimum:1,description:"返回内容的最大字节数,不超过 1 MiB。"},encoding:{type:"string",enum:["utf-8","gbk","gb18030"],description:"文本编码,默认 utf-8。"}}}},stat_file:{functionCode:"stat_file",name:"查看本地文件信息",description:`${G}返回文件或目录的类型、大小、修改时间,可选返回 hash。不返回文件内容。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:W,path:Y("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${G}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:W,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:Y("搜索起点目录,默认工作区根目录。"),maxDepth:{type:"integer",minimum:1,maximum:16,description:"最大目录深度,默认 8。"},maxResults:{type:"integer",minimum:1,maximum:200,description:"最多返回条数,默认 200。"}}}},search_text:{functionCode:"search_text",name:"搜索本地文本",description:`${G}在指定文件或目录(递归)中搜索普通文本(不支持正则),返回所在文件、行号与该行内容。必须指定 path,不能搜索整个文件夹。`,parameters:{type:"object",required:["grantId","path","query"],properties:{grantId:W,path:Y("搜索范围,可以是文件或目录。"),query:{type:"string",minLength:1,description:"要查找的文本。"},caseSensitive:{type:"boolean",description:"是否区分大小写,默认否。"},isRegex:{type:"boolean",description:"暂不支持正则,传 true 会返回 501。"},glob:{type:"string",description:"只搜索匹配该 glob 的文件,如 *.md。"},maxResults:{type:"integer",minimum:1,maximum:200,description:"最多返回条数,默认 200。"},contextLines:{type:"integer",minimum:0,maximum:3,description:"附带的上下文行数,默认 0。"}}}},apply_patch:{functionCode:"apply_patch",name:"修改本地文件",description:`${G}以查找替换的方式修改 UTF-8 文本文件。每条修改的 oldText 必须在文件中唯一出现(或设置 replaceAll)。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","expectedHash","edits"],properties:{grantId:W,path:Y("要修改的文件。"),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:`${G}新建文件,或整体覆盖已有文件(覆盖时必须提供 expectedHash)。修改已有文件优先使用 apply_patch。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","content"],properties:{grantId:W,path:Y("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:it,createDirectories:{type:"boolean",description:"父目录不存在时是否自动创建,默认否。"}}}},upload_file:{functionCode:"upload_file",name:"上传本地文件",description:`${G}把本地文件夹中的文件上传到平台文件服务,返回 fileId、name、size 和 url。url 是文件访问地址,可直接用于后续推理或对话。下载回本地文件夹时使用 download_file,source.type 为 platformFile。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:W,path:Y("要上传的文件。"),target:{type:"string",description:"上传目标,目前只支持 session(默认),其他值返回 501。"},mimeHint:{type:"string",description:"可选的 MIME 类型。"}}}},download_file:{functionCode:"download_file",name:"下载到本地文件夹",description:`${G}把会话文件、平台文件或 https 地址保存到本地文件夹。source.type 为 url 时必须同时填写 source.url(完整地址),为 sessionFile 或 platformFile 时必须同时填写 source.fileId。不要只传 type。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","destPath","source"],properties:{grantId:W,destPath:Y("保存位置(文件路径)。"),source:{type:"object",required:["type"],description:"下载来源。type 为 url 时必填 url;type 为 sessionFile 或 platformFile 时必填 fileId。",properties:{type:{type:"string",enum:["sessionFile","platformFile","url"],description:"sessionFile:当前会话文件;platformFile:平台文件(upload_file 返回的 fileId);url:https 地址。"},fileId:{type:"string",description:"type 为 sessionFile 或 platformFile 时必填,不能只传 type。"},url:{type:"string",description:"type 为 url 时必填,填写完整 https 地址。不能只传 type。默认只允许 glodon.com 及其子域。"}}},overwrite:{type:"boolean",description:"目标已存在时是否覆盖,默认否。"},expectedHash:it}}}},ho="在已绑定的本地工程目录中运行已有 .py,路径相对该目录。不要用于云端工作区,不要传 shell 或代码,只能传 path 和 args。",uo={functionCode:Rn,name:"运行本地 Python 脚本",description:`${ho}每次运行需用户单独确认,文件读写授权不能代替。确认后脚本可直接读写该目录并使用标准库,改动立即落盘。不能联网,不能在运行中安装包,也不能访问该目录以外的文件。第三方包写在工程根目录 sandbox-requirements.txt。结果打印到标准输出。code 为 0 只表示已结束,成功看 data.exitCode,超时看 data.timedOut。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:W,path:{type:"string",description:"要运行的脚本。必须是已存在、以 .py 结尾的相对路径,以 / 分隔,不能包含 .. 、盘符或绝对路径。"},args:{type:"array",maxItems:16,description:"传给脚本的参数,最多 16 个。每个参数单独一项,不能含空格、引号或 shell 语法,只能包含字母、数字、下划线以及 . / : @ = + - , 。",items:{type:"string",description:"一个脚本参数。"}},timeoutMs:{type:"integer",minimum:1e3,maximum:12e4,description:"超时毫秒数。默认 20000,最大 120000。到时脚本会被终止。"}}}},fo=new TextEncoder;function ee(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const po=(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,Nn,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=pi(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 mo(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(;;){N(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=l.pop())!=null?c:"";for(const u of l)o=!0,yield u;if(a)break}}finally{s.releaseLock()}(r||!o)&&(yield r)})}const
|
|
371
|
-
`),startLine:a,endLine:Math.max(y,a-1),size:r,encoding:c,lineEnding:T?"crlf":"lf"};return u&&(I.totalLines=_),r<=e.limits.maxWriteBytes&&(I.hash=yield Ee(yield
|
|
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=l.pop())!=null?c:"";for(const u of l)o=!0,yield u;if(a)break}}finally{s.releaseLock()}(r||!o)&&(yield r)})}const oo=(n,e)=>h(exports,null,function*(){var k,L;const t=K(n.path);Ie(e,t,"read");const i=yield Lt(e.adapter,t),s=yield e.adapter.readFile(t),r=(k=i.size)!=null?k:s.size;if(yield ns(s))throw new m(p.BadRequest,"这是二进制文件,不能按文本读取。可以使用 stat_file 查看信息,或使用 upload_file 上传到会话。");const o=yield q(s.slice(0,3)),c=Zn(o)?"utf-8":(L=n.encoding)!=null?L:"utf-8",a=ee(n.startLine,1,1,Number.MAX_SAFE_INTEGER),d=n.endLine===void 0?Number.MAX_SAFE_INTEGER:Math.max(Math.trunc(n.endLine),a),l=ee(n.maxBytes,e.limits.maxReadBytes,1,e.limits.maxReadBytes),u=r<=e.limits.maxTransferBytes,f=[];let g=0,_=0,y=a-1,b=!1,T=!1;try{for(var J=W(ro(s,c,e.signal)),N,x,M;N=!(x=yield J.next()).done;N=!1){const C=x.value;_++;const D=C.endsWith("\r")?C.slice(0,-1):C;if(D!==C&&(T=!0),_<a||_>d||b){if(!u&&(b||_>d))break;continue}const ce=Rt(D)+(f.length?1:0);if(g+ce>l){if(b=!0,f.length||(f.push(ao(D,l)),y=_),!u)break;continue}f.push(D),g+=ce,y=_}}catch(x){M=[x]}finally{try{N&&(x=J.return)&&(yield x.call(J))}finally{if(M)throw M[0]}}const I={path:t,content:f.join(`
|
|
371
|
+
`),startLine:a,endLine:Math.max(y,a-1),size:r,encoding:c,lineEnding:T?"crlf":"lf"};return u&&(I.totalLines=_),r<=e.limits.maxWriteBytes&&(I.hash=yield Ee(yield q(s))),{data:I,truncated:b||void 0}});function ao(n,e){const t=io.encode(n);return t.byteLength<=e?n:new TextDecoder().decode(t.slice(0,e)).replace(/\uFFFD$/,"")}const co=(n,e)=>h(exports,null,function*(){var r;const t=K(n.path),i=yield e.adapter.stat(t),s={path:t,kind:i.kind,sensitive:i.kind==="file"&&e.sensitive.isSensitive(t)};return i.kind==="file"&&(s.size=i.size,s.lastModified=i.lastModified,n.includeHash&&((r=i.size)!=null?r:0)<=e.limits.maxTransferBytes&&(s.hash=yield Ee(yield q(yield e.adapter.readFile(t))))),{data:s}});function lo(n){return jn.some(e=>Ve(e,n))}function vi(n,e,t){return le(this,null,function*(){const i=[{path:e,depth:0}];let s=0;for(;i.length;){const r=i.shift();O(n.signal),++s%20===0&&(yield new te(ei()));const o=yield new te(n.adapter.listEntries(r.path,n.signal));o.sort((c,a)=>c.name<a.name?-1:c.name>a.name?1:0);for(const c of o){const a=ui(r.path,c.name);if(c.kind==="directory"){r.depth+1<t&&!Bn.includes(c.name)&&i.push({path:a,depth:r.depth+1});continue}lo(c.name)||n.sensitive.match(a,"search")||(yield{path:a,relativePath:e?a.slice(e.length+1):a,name:c.name,size:c.size,lastModified:c.lastModified})}}})}function _i(n,e){return n.includes("/")?Ve(n,e.relativePath):Ve(n,e.name)}const ho=(n,e)=>h(exports,null,function*(){const t=K(n.path,{allowRoot:!0});if(!n.pattern.trim())throw new m(p.BadRequest,"参数 pattern 不能为空。");const i=n.pattern.replace(/\\/g,"/").replace(/^\.\//,"");if((yield e.adapter.stat(t)).kind!=="directory")throw new m(p.BadRequest,"参数 path 必须是目录。");const r=ee(n.maxDepth,On,1,vt),o=ee(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),c=[];let a=!1;try{for(var d=W(vi(e,t,r)),l,u,f;l=!(u=yield d.next()).done;l=!1){const g=u.value;if(_i(i,g)){if(c.length>=o){a=!0;break}c.push({path:g.path,size:g.size,lastModified:g.lastModified})}}}catch(u){f=[u]}finally{try{l&&(u=d.return)&&(yield u.call(d))}finally{if(f)throw f[0]}}return{data:{matches:c},truncated:a||void 0}});function st(n,e){if(n.length<=Ue)return n;const t=Math.max(0,Math.min(e-100,n.length-Ue));return n.slice(t,t+Ue)}const uo=(n,e)=>h(exports,null,function*(){var f;const t=K(n.path,{allowRoot:!0});if(!t&&!e.allowWorkspaceWideTextSearch)throw new m(p.BadRequest,"不支持在整个工作区内搜索文本,请把 path 缩小到具体的子目录或文件。");if(n.isRegex)throw new m(p.NotImplemented,"暂不支持正则搜索,请使用普通文本搜索。");if(!n.query)throw new m(p.BadRequest,"参数 query 不能为空。");const i=n.caseSensitive===!0,s=i?n.query:n.query.toLowerCase(),r=ee(n.contextLines,0,0,Pn),o=ee(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),c=yield e.adapter.stat(t);let a;c.kind==="file"?(Ie(e,t,"search"),a=function(){return le(this,null,function*(){yield{path:t,relativePath:t,name:c.name,size:c.size}})}()):a=vi(e,t,vt);const d=[];let l=0,u=!1;e:try{for(var g=W(a),_,y,b;_=!(y=yield g.next()).done;_=!1){const T=y.value;if(n.glob&&!_i(n.glob,T)||((f=T.size)!=null?f:0)>Dn)continue;if(l>=Nn){u=!0;break}l++,l%20===0&&(yield ei()),O(e.signal);const I=yield q(yield e.adapter.readFile(T.path));if(ae(I))continue;const k=new TextDecoder("utf-8").decode(I).split(/\r?\n/);for(let L=0;L<k.length;L++){const N=(i?k[L]:k[L].toLowerCase()).indexOf(s);if(N<0)continue;if(d.length>=o){u=!0;break e}const x={path:T.path,line:L+1,column:N+1,text:st(k[L],N)};r&&(x.before=k.slice(Math.max(0,L-r),L).map(M=>st(M,0)),x.after=k.slice(L+1,L+1+r).map(M=>st(M,0))),d.push(x)}}}catch(y){b=[y]}finally{try{_&&(y=g.return)&&(yield y.call(g))}finally{if(b)throw b[0]}}return{data:{matches:d,filesScanned:l},truncated:u||void 0}});function xn(){return new m(p.Forbidden,"下载地址不在允许范围内:只允许 https 协议且域名在白名单中的地址。",{reason:"url_not_allowed"})}const fo=(n,e)=>h(exports,null,function*(){var u,f;const t=K(n.path);if(((u=n.target)!=null?u:"session")!=="session")throw new m(p.NotImplemented,"目前只支持上传到当前会话(target: session)。");Ie(e,t,"read");const s=yield Lt(e.adapter,t),r=(f=s.size)!=null?f:0;if(r>e.limits.maxTransferBytes)throw oe(e.limits.maxTransferBytes);const o=kt(t);yield e.requestApproval(t,{type:"upload",name:o,size:r,target:"session"}),e.progress({stage:"reading",loaded:0,total:r,path:t});const c=yield e.adapter.readFile(t);O(e.signal);const a=new File([c],o,{type:n.mimeHint||c.type||"application/octet-stream",lastModified:s.lastModified}),{fileId:d,url:l}=yield e.transfer.upload(a,e.context,({loaded:g,total:_})=>e.progress({stage:"uploading",loaded:g,total:_,path:t}));return O(e.signal),e.progress({stage:"done",loaded:r,total:r,path:t}),{data:{fileId:d,name:o,size:r,url:l}}});function po(n){const e=n;if(!e||typeof e!="object")throw new m(p.BadRequest,"缺少参数 source。");if(e.type==="sessionFile"||e.type==="platformFile"){if(typeof e.fileId!="string"||!e.fileId)throw new m(p.BadRequest,"source.fileId 必须是非空字符串。");return{type:e.type,fileId:e.fileId}}if(e.type==="url"){if(typeof e.url!="string"||!e.url)throw new m(p.BadRequest,"source.url 必须是非空字符串。");return{type:"url",url:e.url}}throw new m(p.BadRequest,"source.type 必须是 sessionFile、platformFile 或 url 之一。")}function mo(n){return n.type==="sessionFile"?"会话文件":n.type==="platformFile"?"平台文件":new URL(n.url).hostname}function go(n,e,t,i,s){return le(this,null,function*(){const r=n.getReader();let o=0;try{for(;;){O(e.signal);const{done:c,value:a}=yield new te(r.read());if(c)break;if(o+=a.byteLength,o>e.limits.maxTransferBytes)throw oe(e.limits.maxTransferBytes,"下载内容");s.push(a),e.progress({stage:"downloading",loaded:o,total:i,path:t}),yield a}}finally{r.cancel().catch(()=>{})}})}const yo=(n,e)=>h(exports,null,function*(){var y,b,T;const t=K(n.destPath,{field:"destPath"}),i=po(n.source);if(i.type==="url"&&!mt(i.url,e.downloadUrlAllowlist))throw xn();Ie(e,t,"write");const s=yield He(e.adapter,t);if((s==null?void 0:s.kind)==="directory")throw new m(p.BadRequest,"目标是目录,不能写入文件。");if(s&&!n.overwrite)throw new m(p.Conflict,"目标文件已存在。如需覆盖,请设置 overwrite: true。");const r=()=>h(exports,null,function*(){if(!s||!n.expectedHash)return;const I=yield Ee(yield q(yield e.adapter.readFile(t)));if(I!==n.expectedHash)throw new m(p.Conflict,"expectedHash 与目标文件当前内容不一致。",{currentHash:I})});yield r();const o=i.type==="url"?{url:i.url}:yield e.transfer.resolveDownload(i,e.context);if(o.size!==void 0&&o.size>e.limits.maxTransferBytes)throw oe(e.limits.maxTransferBytes);const c={type:"download",source:{type:i.type,label:mo(i)},name:(y=o.name)!=null?y:kt(t),size:o.size,overwrite:!!s};yield e.requestApproval(t,c),yield r();let a;try{a=yield e.fetch(o.url,{headers:o.headers,credentials:"omit",redirect:"follow",signal:e.signal})}catch(I){throw O(e.signal),new m(p.Internal,"下载失败,无法连接到文件地址。")}if(i.type==="url"&&a.url&&!mt(a.url,e.downloadUrlAllowlist))throw(b=a.body)==null||b.cancel().catch(()=>{}),xn();if(!a.ok||!a.body)throw(T=a.body)==null||T.cancel().catch(()=>{}),new m(a.status===404?p.NotFound:p.Internal,`下载失败(HTTP ${a.status})。`);const d=Number(a.headers.get("content-length")),l=Number.isFinite(d)&&d>0?d:void 0;if(l!==void 0&&l>e.limits.maxTransferBytes)throw a.body.cancel().catch(()=>{}),oe(e.limits.maxTransferBytes);const u=[];yield e.adapter.writeFile(t,go(a.body,e,t,l,u),{signal:e.signal});const f=u.reduce((I,k)=>I+k.byteLength,0),g=new Uint8Array(f);let _=0;return u.forEach(I=>{g.set(I,_),_+=I.byteLength}),e.progress({stage:"done",loaded:f,total:f,path:t}),{data:{path:t,size:f,hash:yield Ee(g)}}}),rt=new Uint8Array([239,187,191]);function Xe(n,e){return new m(p.Conflict,e,{currentHash:n})}function Ht(n,e){return h(this,null,function*(){var s;if(((s=(yield Lt(n.adapter,e)).size)!=null?s:0)>n.limits.maxWriteBytes)throw oe(n.limits.maxWriteBytes,"目标文件");const i=yield q(yield n.adapter.readFile(e));return{bytes:i,hash:yield Ee(i)}})}function bi(n,e,t){return h(this,null,function*(){const{hash:i}=yield Ht(n,e);if(i!==t)throw Xe(i,"文件在确认期间已被修改,本次写入已取消。请重新读取后再修改。")})}function wo(n,e){const t=new TextEncoder().encode(n);if(!e)return t;const i=new Uint8Array(rt.byteLength+t.byteLength);return i.set(rt,0),i.set(t,rt.byteLength),i}function vo(n,e){let t=0,i=n.indexOf(e);for(;i>=0;)t++,i=n.indexOf(e,i+e.length);return t}function An(n,e){return!e||n.includes(`\r
|
|
372
372
|
`)?n:n.replace(/\n/g,`\r
|
|
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=Tn(l.oldText,c),g=Tn(l.newText,c),_=ko(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=To(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 Si(e,t,s),{data:yield Ii(e,t,d)}}),Ro=(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 qt(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=Sr(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 Si(e,t,r);else if(yield He(e.adapter,t))throw new m(p.Conflict,"目标文件在确认期间被创建,本次写入已取消。请重新检查后再写入。");const c=yield Ii(e,t,o,n.createDirectories);return{data:E(v({},c),{created:!i})}}),Mo={list_directory:po,read_file:go,stat_file:wo,search_files:_o,search_text:bo,apply_patch:Lo,write_file:Ro,upload_file:Eo,download_file:Ao};class Co{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 Oo(n,e){return Wn.includes(e)?n.limits.transferTimeoutMs:qn.includes(e)?n.limits.searchTimeoutMs:n.limits.toolTimeoutMs}function No(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch(e){throw new m(p.BadRequest,"参数不是合法的 JSON 对象。")}}function Fo(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 xi(n){return new Promise((e,t)=>{n.aborted&&t(U()),n.addEventListener("abort",()=>t(U()),{once:!0})})}function Po(n){return v({code:n.code,message:n.message},n.data?{data:n.data}:{})}function Do(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 Co(Oo(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 F=No(t),x=Fo(F);x!=null&&Er(x);const M=Yn(F,_i[e].parameters),C=(b=M.path)!=null?b:M.destPath;if(typeof C=="string"&&(o.path=C),yield n.ready,c.signal.aborted)throw U();const P=n.adapter;if(!P)throw Et();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:P,workspaceName:(T=n.displayName)!=null?T:P.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)=>$o(n,{approvalPath:Q,preview:Ne,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([Mo[e](M,ce),xi(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(F){let x=Xe(F);a?x=new m(p.Timeout,"操作超时,已中止。"):c.signal.aborted&&x.code!==p.Cancelled&&(x=U()),((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(Po(x))}finally{d.clear(),(J=r.signal)==null||J.removeEventListener("abort",l),u==null||u(),f==null||f()}})}function $o(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 U();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)),xi(i.signal),new Promise(d=>{o=setTimeout(()=>d(!1),n.limits.approvalTimeoutMs)})]);if(e.signal.aborted)throw U();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 Bo({pluginCode:n,workspace:e}){const t={};return wt.forEach(i=>{t[i]=(s,r,o)=>{let c=!1;Do(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 kn(){return{kind:"directory",children:new Map}}class Uo{constructor(e={},t="memory-workspace"){w(this,"root",kn());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=kn(),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*(){N(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 _=V(St(t)),y,b,T;y=!(b=yield _.next()).done;y=!1){const I=b.value;N(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]}}N(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(zn(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=lo;exports.BINARY_SNIFF_BYTES=bt;exports.BUILTIN_TOOLS_PLUGIN_CODE=ke;exports.BUILTIN_TOOLS_PLUGIN_CODES=vt;exports.BUILTIN_TOOL_SCHEMAS=Ct;exports.BotClient=co;exports.DEFAULT_DOWNLOAD_URL_ALLOWLIST=Un;exports.DEFAULT_IGNORED_DIRECTORIES=jn;exports.DEFAULT_IGNORED_FILE_PATTERNS=Hn;exports.DEFAULT_LIMITS=Ue;exports.FileSystemAccessAdapter=mi;exports.HOST_BRIDGE_GLOBAL=qe;exports.HOST_CHANNEL=It;exports.KiB=Cn;exports.LIST_DIRECTORY_DEFAULT_LIMIT=Nn;exports.LIST_DIRECTORY_MAX_LIMIT=Fn;exports.LOCAL_FILES_FUNCTION_CODES=wt;exports.LOCAL_FILES_PLUGIN_CODES=Ln;exports.LOCAL_FILE_TOOL_SCHEMAS=_i;exports.LOCAL_PYTHON_FUNCTION_CODE=Rn;exports.LOCAL_PYTHON_PLUGIN_CODES=Mn;exports.LOCAL_PYTHON_TOOL_SCHEMA=uo;exports.LocalWorkspace=vi;exports.MemoryWorkspaceAdapter=Uo;exports.MiB=Me;exports.PYTHON_DEFAULT_TIMEOUT_MS=Oi;exports.PYTHON_MAX_ARGS=Fi;exports.PYTHON_MAX_TIMEOUT_MS=Ni;exports.SDK_SENSITIVE_BASELINE=Zn;exports.SEARCH_DEFAULT_DEPTH=Pn;exports.SEARCH_FUNCTION_CODES=qn;exports.SEARCH_MAX_DEPTH=_t;exports.Session=Ht;exports.TEXT_SEARCH_MAX_CONTEXT_LINES=Bn;exports.TEXT_SEARCH_MAX_FILES=Dn;exports.TEXT_SEARCH_MAX_FILE_BYTES=$n;exports.TEXT_SEARCH_MAX_LINE_CHARS=je;exports.TRANSFER_FILE_SIZE_LIMIT_MB=On;exports.TRANSFER_FUNCTION_CODES=Wn;exports.ToolCode=p;exports.ToolError=m;exports.WORKSPACE_GRANT_ID=be;exports.WRITE_FUNCTION_CODES=Pi;exports.configure=pt;exports.createDefaultSessionFileTransfer=Ut;exports.createIndexedDbStore=wi;exports.createLocalFilesPlugin=Bo;exports.createMemoryStore=jt;exports.getDownloadUrlAllowlist=Bt;exports.getRegisteredLocalFilesPluginCode=lr;exports.getRegisteredLocalPythonPluginCode=hr;exports.isDownloadUrlAllowed=Tr;exports.registerHostBridge=Ui;exports.resolveLocalFilesPluginCode=li;exports.toToolError=Xe;
|
|
373
|
+
`)}function Ei(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 Ee(t),size:t.byteLength}})}const _o=(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 Ht(e,t);if(s!==n.expectedHash)throw Xe(s,"expectedHash 与文件当前内容不一致,请重新读取文件后再修改。");const r=Zn(i),o=is(r?i.subarray(3):i),c=o.includes(`\r
|
|
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;
|