@glodon-aiot/bot-client-sdk 3.26.0-alpha.33 → 3.26.0-alpha.34

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/dist/lib/index.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";var gs=Object.defineProperty,ys=Object.defineProperties;var ws=Object.getOwnPropertyDescriptors;var Ve=Object.getOwnPropertySymbols;var In=Object.prototype.hasOwnProperty,xn=Object.prototype.propertyIsEnumerable;var Oe=(n,e)=>{if(e=Symbol[n])return e;throw Error("Symbol."+n+" is not defined")};var gt=(n,e,t)=>e in n?gs(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,b=(n,e)=>{for(var t in e||(e={}))In.call(e,t)&&gt(n,t,e[t]);if(Ve)for(var t of Ve(e))xn.call(e,t)&&gt(n,t,e[t]);return n},E=(n,e)=>ys(n,ws(e));var An=(n,e)=>{var t={};for(var i in n)In.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&Ve)for(var i of Ve(n))e.indexOf(i)<0&&xn.call(n,i)&&(t[i]=n[i]);return t};var v=(n,e,t)=>(gt(n,typeof e!="symbol"?e+"":e,t),t);var d=(n,e,t)=>new Promise((i,s)=>{var r=c=>{try{a(t.next(c))}catch(l){s(l)}},o=c=>{try{a(t.throw(c))}catch(l){s(l)}},a=c=>c.done?i(c.value):Promise.resolve(c.value).then(r,o);a((t=t.apply(n,e)).next())}),se=function(n,e){this[0]=n,this[1]=e},ge=(n,e,t)=>{var i=(o,a,c,l)=>{try{var h=t[o](a),u=(a=h.value)instanceof se,f=h.done;Promise.resolve(u?a[0]:a).then(p=>u?i(o==="return"?o:"next",a[1]?{done:p.done,value:p.value}:p,c,l):c({value:p,done:f})).catch(p=>i("throw",p,c,l))}catch(p){l(p)}},s=o=>r[o]=a=>new Promise((c,l)=>i(o,a,c,l)),r={};return t=t.apply(n,e),r[Symbol.asyncIterator]=()=>r,s("next"),s("throw"),s("return"),r},Tn=n=>{var e=n[Oe("asyncIterator")],t=!1,i,s={};return e==null?(e=n[Oe("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 se(new Promise(a=>{var c=e[r](o);if(!(c instanceof Object))throw TypeError("Object expected");a(c)}),1)}}),s[Oe("iterator")]=()=>s,i("next"),"throw"in e?i("throw"):s.throw=r=>{throw r},"return"in e&&i("return"),s},G=(n,e,t)=>(e=n[Oe("asyncIterator")])?e.call(n):(n=n[Oe("iterator")](),e={},t=(i,s)=>(s=n[i])&&(e[i]=r=>new Promise((o,a,c)=>(r=s.call(n,r),c=r.done,Promise.resolve(r.value).then(l=>o({value:l,done:c}),a)))),t("next"),t("return"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ne=require("uuid"),vs=require("js-base64"),bs=require("axios"),x=require("@glodon-aiot/apis"),_s=require("socket.io-client"),Kt=require("dayjs"),de=class de{constructor(e,t=!1){this.prefix=e,this.open=t}disable(){this.open=!1}enable(){this.open=!0}log(...e){!this.open&&!de.debug||console.log(this.prefix,...e)}info(...e){!this.open&&!de.debug||console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}error(...e){!this.open&&!de.debug||console.error(this.prefix,...e)}warn(...e){!this.open&&!de.debug||console.warn(this.prefix,...e)}};v(de,"debug",!1);let q=de;const Jt=["list_directory","read_file","stat_file","search_files","search_text","apply_patch","write_file","upload_file","download_file"],Ne="builtin_tools",mi={dev:Ne,test:Ne,prod:Ne,local:Ne},gi=mi,xe="current-workspace",yi=1024,Be=1024*1024,wi=50,Je=Object.freeze({maxReadBytes:1*Be,maxWriteBytes:5*Be,maxSearchResults:200,maxConcurrentRequests:4,maxTransferBytes:wi*Be,toolTimeoutMs:3e4,commandTimeoutMs:10*6e4,searchTimeoutMs:6e4,transferTimeoutMs:10*6e4,approvalTimeoutMs:5*6e4}),vi=200,bi=1e3,_i=8,Qt=16,ki=2e3,Ei=1*Be,Qe=500,Si=3,Zt=8*yi,Ii=Object.freeze(["glodon.com"]),xi=Object.freeze([".git","node_modules",".svn",".idea",".vscode"]),Ai=Object.freeze(["~$*",".~lock*","*.tmp"]),ks=["apply_patch","write_file","upload_file","download_file"],Ti=["search_files","search_text"],Li=["upload_file","download_file"];var g=(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))(g||{});class m extends Error{constructor(t,i,s){super(i);v(this,"code");v(this,"data");this.name="ToolError",this.code=t,this.data=s}}const Es="尚未授权工作文件夹,请先在助手中选择或恢复访问工作文件夹。";function ut(){return new m(403,Es,{reason:"workspace_not_granted"})}function B(){return new m(499,"操作已取消。")}function F(n){if(n!=null&&n.aborted)throw B()}function Ln(n){const e=n&&typeof n=="object"&&"message"in n?String(n.message):"";return/[\u4e00-\u9fff]/.test(e)?e:void 0}function Ae(n){var t,i;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 ut();case"AbortError":return B();case"NoModificationAllowedError":case"InvalidModificationError":case"InvalidStateError":return new m(403,"文件当前不可写,可能正被其他程序占用或为只读。");case"QuotaExceededError":return new m(413,(t=Ln(n))!=null?t:"磁盘空间不足或超出写入配额。");case"TooManyRequestsError":return new m(429,(i=Ln(n))!=null?i:"排队的文件操作过多,请稍后重试。");case"PreviewLimitError":return new m(413,"同时预览的文件过多,请先关掉一些预览。");default:return new m(500,"本地文件操作失败,请稍后重试。")}}const Z=16e3,Ss=`
2
- …输出已截断`;function Mn(n){if(n.length<=Z)return n;let e=Z;const t=n.charCodeAt(e-1);return t>=55296&&t<=56319&&(e-=1),n.slice(0,e)+Ss}function Pt(n){return{exec(t){return d(this,null,function*(){const i=yield n.exec(t);return E(b({},i),{stdout:Mn(i.stdout),stderr:Mn(i.stderr)})})}}}function Mi(n,e){return e===n||e.startsWith(`${n}/`)}function k(n,e=n){return new DOMException(e,n)}function ft(n){return ge(this,null,function*(){typeof n=="string"?yield new TextEncoder().encode(n):n instanceof Uint8Array?yield n:yield*Tn(n)})}const en="glodon-workspace",it="__glodonHostBridge",Ee=1,Ri=500*1024*1024;function Ci(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===en)return t}function Rn(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 Is(n){const e=globalThis;n?e[it]=n:delete e[it]}function Fi(){var e;const n=Rn(globalThis[it]);return n||Rn((e=globalThis.chrome)==null?void 0:e.webview)}const xs=1024*1024;function As(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 a=new Uint8Array(r.length+i.length);return a.set(r,0),a.set(i,r.length),a}function yt(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 Cn={revision:0,network:{mode:"off",allow:[]},packages:{python:{enabled:!0}}};function Fn(n){var i,s,r,o,a,c,l;if(!n||typeof n!="object")return;const e=n,t=(i=e.network)==null?void 0:i.mode;if(!(t!=="off"&&t!=="allowlist"&&t!=="open"))return b({revision:typeof e.revision=="number"?e.revision:0,network:{mode:t,allow:Array.isArray((s=e.network)==null?void 0:s.allow)?e.network.allow.filter(h=>typeof h=="string"):[]},packages:{python:{enabled:((o=(r=e.packages)==null?void 0:r.python)==null?void 0:o.enabled)!==!1}}},Number.isInteger((a=e.exec)==null?void 0:a.maxConcurrent)&&((c=e.exec)==null?void 0:c.maxConcurrent)>=1?{exec:{maxConcurrent:(l=e.exec)==null?void 0:l.maxConcurrent}}:{})}function Ts(n){const e=n==null?void 0:n.denied;return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Ls(n,e){if(!e.length)return n;const t=`宿主网络策略拒绝了:${e.join("、")}。不要重试这些地址;需要时请用户在宿主设置里允许。`;return n?`${n}
3
- ${t}`:t}const ye="沙箱已退出。";function wt(n){if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n)}function On(n,e,t,i){const s=n.length>Z?n.slice(n.length-Z):n;if(!e&&!t&&!i&&n.length<=Z)return s;let r=`
4
- …输出已截断`;return t&&(r+=`,完整输出见 ${t}`),i&&(r+=",日志已截断"),s+r}class Ms{constructor(e=t=>new WebSocket(t)){v(this,"notice");v(this,"policy",Cn);v(this,"socket");v(this,"generation",0);v(this,"authed",!1);v(this,"seq",0);v(this,"calls",new Map);v(this,"outgoing",[]);this.openSocket=e}get ready(){const e=this.notice;return(e==null?void 0:e.state)==="ready"&&e.protocol===Ee&&!!(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"?ye:"沙箱没有就绪。"}apply(e){const t=this.notice;if(this.notice=e,!this.ready||!(e!=null&&e.url)||!e.token){this.failAll(k("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(k("AbortError",ye)),this.stop(),this.connect(e.url,e.token))}httpOrigin(){var t;const e=(t=this.notice)==null?void 0:t.url;return e!=null&&e.startsWith("ws://")?e.slice(5).replace(/\/$/,""):""}stat(e){return d(this,null,function*(){return this.invoke({op:"stat",path:e})})}url(e){return d(this,null,function*(){const i=(yield this.invoke({op:"url",path:e})).ticket;if(typeof i!="string"||!/^[a-f0-9]{32}$/.test(i))throw k("NotAllowedError","地址无效。");return i})}releaseUrl(e){return d(this,null,function*(){yield this.invoke({op:"releaseUrl",ticket:e})})}list(e,t){return d(this,null,function*(){return this.invoke({op:"list",path:e},t)})}read(r){return d(this,arguments,function*(e,t=0,i=Ri,s){const o=this.begin({op:"read",path:e,offset:t,maxBytes:i},s),a=[];let c;for(;!c;){const f=yield this.next(o),p=wt(f);if(p){a.push(yt(p).payload);continue}c=f}if(this.calls.delete(o),c.ok===!1)throw k(String(c.name||"NotAllowedError"),String(c.message||"读取失败。"));const l=a.reduce((f,p)=>f+p.length,0),h=new Uint8Array(l);let u=0;return a.forEach(f=>{h.set(f,u),u+=f.length}),h})}write(e,t,i,s){return d(this,null,function*(){const r=this.begin({op:"write",path:e,size:t.length,createDirectories:i},s);yield this.upload(r,t,"写入失败。")})}skillStatus(e,t){return d(this,null,function*(){const i=yield this.invoke({op:"skillStatus",applicationId:e},t);return Array.isArray(i.skills)?i.skills:[]})}skillRead(e,t,i,s,r){return d(this,null,function*(){const o=this.begin({op:"skillRead",applicationId:e,skillId:t,version:i,path:s},r),a=[];let c;for(;!c;){const f=yield this.next(o),p=wt(f);if(p){a.push(yt(p).payload);continue}c=f}if(this.calls.delete(o),c.ok===!1)throw k(String(c.name||"NotAllowedError"),String(c.message||"读取失败。"));const l=a.reduce((f,p)=>f+p.length,0),h=new Uint8Array(l);let u=0;return a.forEach(f=>{h.set(f,u),u+=f.length}),h})}skillList(e,t,i,s,r){return d(this,null,function*(){const o=yield this.invoke({op:"skillList",applicationId:e,skillId:t,version:i,path:s},r);return typeof o.files=="string"?o.files:""})}skillGrep(e,t,i,s,r,o){return d(this,null,function*(){const a=yield this.invoke({op:"skillGrep",applicationId:e,skillId:t,version:i,path:s,pattern:r},o);return typeof a.matches=="string"?a.matches:""})}installSkill(e,t,i){return d(this,null,function*(){const s=this.begin(E(b({op:"installSkill"},e),{size:t.length}),i);yield this.upload(s,t,"安装失败。")})}skillPrune(e,t,i,s){return d(this,null,function*(){yield this.invoke({op:"skillPrune",applicationId:e,keep:t,busy:i},s)})}mkdir(e){return d(this,null,function*(){yield this.invoke({op:"mkdir",path:e})})}remove(e,t){return d(this,null,function*(){yield this.invoke({op:"remove",path:e,recursive:t})})}move(e,t){return d(this,null,function*(){yield this.invoke({op:"move",from:e,to:t})})}exec(e,t,i){return d(this,null,function*(){var l;const s=this.begin(b({},e),t);let r="",o="",a=!1,c=!1;for(;this.calls.has(s);){const h=yield this.next(s);if(h.op==="stdout"||h.op==="stderr"){const y=String((l=h.text)!=null?l:"");i==null||i(h.op,y),h.op==="stdout"?(r+=y,r.length>Z&&(a=!0),r=r.slice(-Z)):(o+=y,o.length>Z&&(c=!0),o=o.slice(-Z));continue}if(this.calls.delete(s),h.ok===!1)throw k(String(h.name||"NotAllowedError"),String(h.message||"命令失败。"));const u=typeof h.logPath=="string"?h.logPath:void 0,f=h.logTruncated===!0,p=Ts(h.network);return b({exitCode:typeof h.exitCode=="number"?h.exitCode:1,timedOut:h.timedOut===!0,stdout:On(r,a,u,f),stderr:Ls(On(o,c,u,f),p),cwd:typeof h.cwd=="string"?h.cwd:void 0},p.length?{denied:p}:{})}throw k("AbortError",ye)})}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 k(String(r.name||"NotAllowedError"),String(r.message||"请求失败。"));return r})}upload(e,t,i){return d(this,null,function*(){let s=0;for(;;){const r=yield this.next(e);if(r.ok===!1)throw this.calls.delete(e),k(String(r.name||"NotAllowedError"),String(r.message||i));if(r.ok===!0){this.calls.delete(e);return}if(r.op!=="ack"||s>=t.length)continue;const o=t.subarray(s,s+xs),a=s+o.length;this.send(As(e,s,a===t.length,o)),s=a}})}begin(e,t){if(!this.ready)throw k("NotAllowedError",this.unavailableMessage());if(t!=null&&t.aborted)throw k("AbortError");const i=`sbx-${++this.seq}`;let s=()=>{};const r={messages:[],waiters:[],reject:a=>s(a)};this.calls.set(i,r);const o=()=>{this.send({protocol:Ee,id:i,op:"cancel"}),r.reject(k("AbortError"))};return t==null||t.addEventListener("abort",o,{once:!0}),s=a=>{t==null||t.removeEventListener("abort",o),this.calls.delete(i);const c=r.waiters.shift();c&&c(Promise.reject(a))},this.send(b({protocol:Ee,id:i},e)),i}next(e){const t=this.calls.get(e);if(!t)return Promise.reject(k("AbortError",ye));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:Ee,op:"auth",token:t}))},s.onmessage=r=>{i===this.generation&&this.onFrame(r.data)},s.onclose=()=>{i===this.generation&&(this.authed=!1,this.failAll(k("AbortError",ye)))},s.onerror=()=>{}}onFrame(e){var s,r;const t=wt(e);if(t){const o=yt(t);this.push(o.id,t);return}let i;try{i=JSON.parse(String(e))}catch(o){return}if(i.op==="policy"&&i.id===void 0){this.policy=(s=Fn(i.policy))!=null?s:this.policy;return}if(i.op==="auth"){if(i.ok===!0){this.policy=(r=Fn(i.policy))!=null?r:Cn,this.authed=!0;const o=this.outgoing;this.outgoing=[],o.forEach(a=>a())}return}if(i.op==="bye"){this.failAll(k("AbortError",ye)),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 Nn(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 qe{constructor(e,t="",i=new Ms){v(this,"displayName");v(this,"capabilities",new Set);v(this,"sandboxVersion");v(this,"sandboxProtocol");v(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!==Ee}unavailableMessage(){return this.sandbox.unavailableMessage()}stat(e){return d(this,null,function*(){const t=yield this.sandbox.stat(e);return Nn(t.entry,e.split("/").pop()||this.displayName)})}listEntries(e,t){return d(this,null,function*(){const i=yield this.sandbox.list(e,t);return(Array.isArray(i.entries)?i.entries:[]).map(r=>Nn(r,""))})}url(e){return d(this,null,function*(){const t=yield this.sandbox.url(e),i=this.sandbox.httpOrigin();if(!i)throw k("NotAllowedError",this.unavailableMessage());return{url:`http://${i}/file/${t}`,release:()=>{this.sandbox.releaseUrl(t).catch(()=>{})}}})}readFile(e,t){return d(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 d(this,null,function*(){yield this.sandbox.mkdir(e)})}remove(i){return d(this,arguments,function*(e,t={}){yield this.sandbox.remove(e,t.recursive===!0)})}move(e,t){return d(this,null,function*(){yield this.sandbox.move(e,t)})}exec(e){return d(this,null,function*(){const t=yield this.sandbox.exec({op:"exec",cwd:e.cwd,command:e.command,argv:e.argv,timeoutMs:e.timeoutMs,skill:e.skill},e.signal,e.onOutput);if(t.timedOut)throw k("AbortError","命令运行超时。");return t})}writeFile(s,r){return d(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 h=G(ft(t)),u,f,p;u=!(f=yield h.next()).done;u=!1){const y=f.value;F(i.signal),o.push(y)}}catch(f){p=[f]}finally{try{u&&(f=h.return)&&(yield f.call(h))}finally{if(p)throw p[0]}}const a=o.reduce((y,w)=>y+w.byteLength,0),c=new Uint8Array(a);let l=0;o.forEach(y=>{c.set(y,l),l+=y.byteLength}),yield this.sandbox.write(e,c,i.createDirectories===!0,i.signal)})}}function D(n,e){throw new m(g.BadRequest,n?`参数 ${n} ${e}`:`参数${e}`)}function Rs(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 Dt(n,e,t){switch(n=Rs(n,e),e.type){case"string":typeof n!="string"&&D(t,"必须是字符串。"),e.minLength!==void 0&&n.length<e.minLength&&D(t,"不能为空。"),e.maxLength!==void 0&&n.length>e.maxLength&&D(t,`不能超过 ${e.maxLength} 字。`);break;case"integer":(typeof n!="number"||!Number.isInteger(n))&&D(t,"必须是整数。");break;case"number":(typeof n!="number"||!Number.isFinite(n))&&D(t,"必须是数字。");break;case"boolean":typeof n!="boolean"&&D(t,"必须是布尔值。");break;case"array":if(Array.isArray(n)||D(t,"必须是数组。"),e.minItems!==void 0&&n.length<e.minItems&&D(t,"不能为空。"),e.items){const i=e.items;return n.map((s,r)=>Dt(s,i,`${t}[${r}]`))}break;case"object":return Oi(n,e,t)}return e.enum&&!e.enum.includes(n)&&D(t,`必须是 ${e.enum.join("、")} 之一。`),typeof n=="number"&&(e.minimum!==void 0&&n<e.minimum&&D(t,`不能小于 ${e.minimum}。`),e.maximum!==void 0&&n>e.maximum&&D(t,`不能大于 ${e.maximum}。`)),n}function Oi(n,e,t){var r,o;(!n||typeof n!="object"||Array.isArray(n))&&D(t,"必须是对象。");const i=n,s={};for(const a of(r=e.required)!=null?r:[])(i[a]===void 0||i[a]===null)&&D(t?`${t}.${a}`:a,"是必填项。");for(const[a,c]of Object.entries((o=e.properties)!=null?o:{})){if(i[a]===void 0||i[a]===null)continue;const l=t?`${t}.${a}`:a;s[a]=c.oneOf?(Dt(i[a],E(b({},c),{oneOf:void 0}),l),i[a]):Dt(i[a],c,l)}return s}function Ni(n,e){return Oi(n,e,"")}const Bt=["shell","read_file","write_file","append_file","run_file","edit_file","grep","find","load_skill","read_skill_resource","list_skill_files","grep_skill","run_skill_script"],jt=81920,st=81920,Cs=2e4,tn=".",N="/workspace",$n={".py":"python3",".sh":"sh",".bash":"sh",".js":"node",".mjs":"node",".cjs":"node"},Fs=["input","output","uploads","tmp"],nn="不要使用 input、output、uploads、tmp,也不要新建这些目录。请把文件直接放在工作区已有位置或根目录。",Os=/(?:^|[\s'"=;|&<>`:])\/?(?:input|output|uploads|tmp)(?=\/|[\s'"=;|&<>`:]|$)/,Ns=/(?:^|[\s'"=;|&<>`:])\/?skills(?=\/|[\s'"=;|&<>`:]|$)/;function Pn(n){return Ns.test(n)}function rt(n){return Os.test(n)}function sn(n){const e=n.split("/")[0];return Fs.includes(e)}function Ze(n){throw new m(g.Forbidden,n,{reason:"path_outside_workspace"})}function $i(n){if(typeof n!="string"||n.length===0)throw new m(g.BadRequest,"path 必须是工作区内路径。");(n.includes("\0")||n.includes("\\"))&&Ze("路径不能包含反斜杠。");const e=n.normalize("NFC").trim();if(!e)throw new m(g.BadRequest,"path 必须是工作区内路径。");/^[a-zA-Z]:/.test(e)&&Ze("路径不能包含盘符。");const t=e.split("/").filter(i=>i.length>0&&i!==".");if(t.some(i=>i==="..")&&Ze("路径不能包含 .. 。"),t.length>0&&sn(t[0]))throw new m(g.BadRequest,nn);if(t[0]==="skills")throw new m(g.Forbidden,"技能文件只能通过技能工具访问。");return t.join("/")}function Le(n){return $i(n)}function $s(n){return $i(n)}function rn(n){return n?`/${n}`:"/"}function Ps(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!=="..")&&!sn(e[0])}function pt(n,e){if(!n||/[\\/\0]/.test(n)||n==="."||n==="..")throw new m(g.BadRequest,"skill_name 必须是单个技能目录名。");if(!e||e.startsWith("/")||e.includes("\\")||e.includes("\0"))throw new m(g.BadRequest,"资源路径必须是技能目录内的相对路径。");const t=e.split("/").filter(i=>i.length>0);return(t.length===0||t.some(i=>i==="."||i===".."))&&Ze("资源路径不能跳出技能目录。"),`skills/${n}/${t.join("/")}`}const Pi="https://cv-cdn.obs.cn-north-4.myhuaweicloud.com/glodon/libs/",Ds="3.6.0",Bs=`${Pi}just-bash/${Ds}/just-bash.mjs`,js="314.0.7",Us=`${Pi}pyodide/${js}/`,Di=["numpy","pandas","matplotlib","pillow","lxml"],vt=new Map;function qs(n){return import(n)}function Hs(n){let e=vt.get(n);return e||(e=qs(n).catch(t=>{throw vt.delete(n),t}),vt.set(n,e)),e}const Dn=new Map;function zs(n){return/[\\^$.|+()[\]{}]/.test(n)?`\\${n}`:n}function Ws(n,e=!1){const t=`${e?"s":"i"}:${n}`,i=Dn.get(t);if(i)return i;let s="";for(let o=0;o<n.length;o++){const a=n[o];a==="*"?n[o+1]==="*"?(o++,n[o+1]==="/"?(o++,s+="(?:.*/)?"):s+=".*"):s+="[^/]*":a==="?"?s+="[^/]":s+=zs(a)}const r=new RegExp(`^${s}$`,e?"":"i");return Dn.set(t,r),r}function ot(n,e,t=!1){return Ws(n,t).test(e)}function on(n){const e=n.lastIndexOf("/");return e<0?n:n.slice(e+1)}const Bi=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"}]),Vs="该文件被列为敏感文件,不允许访问";class an{constructor(e=[]){v(this,"rules");const t=e.filter(i=>i&&typeof i.pattern=="string"&&i.pattern).map(i=>E(b({},i),{id:String(i.id||i.pattern),source:i.source==="enterprise"?"enterprise":"product"}));this.rules=[...Bi,...t]}match(e,t){if(!e)return null;const i=on(e);for(const s of this.rules){if(s.operations&&!s.operations.includes(t))continue;const r=s.match==="path"?e:i;if(ot(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||Vs},已拒绝访问。`}}function Me(n,e,t){const i=n.sensitive.match(e,t);if(i)throw new m(g.Forbidden,an.reasonOf(i),{reason:"sensitive_file",ruleId:i.id})}function et(n,e){return d(this,null,function*(){try{return yield n.stat(e)}catch(t){if(Ae(t).code===g.NotFound)return null;throw t}})}function cn(n,e){return d(this,null,function*(){const t=yield n.stat(e);if(t.kind!=="file")throw new m(g.BadRequest,"目标是目录,不是文件。");return t})}function Te(n){return d(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 X(n){return d(this,null,function*(){return new Uint8Array(yield n.arrayBuffer())})}function fe(n){const e=Math.min(n.byteLength,Zt);for(let t=0;t<e;t++)if(n[t]===0)return!0;return!1}function Gs(n){return d(this,null,function*(){return fe(yield X(n.slice(0,Zt)))})}function ji(n){return n[0]===239&&n[1]===187&&n[2]===191}function Xs(n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch(e){throw new m(g.BadRequest,"文件不是 UTF-8 编码,暂不支持修改。")}}function ln(n){return new TextEncoder().encode(n).byteLength}function Ui(){return new Promise(n=>setTimeout(n,0))}function Ys(n){return n>=1024*1024?`${(n/1024/1024).toFixed(1)} MB`:n>=1024?`${(n/1024).toFixed(1)} KB`:`${n} B`}function he(n,e="文件"){return new m(g.TooLarge,`${e}超过大小上限 ${Ys(n)}。`)}const Ks=`# 在 Pyodide 里按 python3 命令行的语义运行代码。由 pyodideWorker.js 加载,最后一个表达式 run 交给 JS 调用。
1
+ "use strict";var vs=Object.defineProperty,bs=Object.defineProperties;var _s=Object.getOwnPropertyDescriptors;var Ge=Object.getOwnPropertySymbols;var Tn=Object.prototype.hasOwnProperty,Ln=Object.prototype.propertyIsEnumerable;var $e=(n,e)=>{if(e=Symbol[n])return e;throw Error("Symbol."+n+" is not defined")};var vt=(n,e,t)=>e in n?vs(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,b=(n,e)=>{for(var t in e||(e={}))Tn.call(e,t)&&vt(n,t,e[t]);if(Ge)for(var t of Ge(e))Ln.call(e,t)&&vt(n,t,e[t]);return n},S=(n,e)=>bs(n,_s(e));var Rn=(n,e)=>{var t={};for(var i in n)Tn.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&Ge)for(var i of Ge(n))e.indexOf(i)<0&&Ln.call(n,i)&&(t[i]=n[i]);return t};var y=(n,e,t)=>(vt(n,typeof e!="symbol"?e+"":e,t),t);var d=(n,e,t)=>new Promise((i,s)=>{var r=c=>{try{a(t.next(c))}catch(l){s(l)}},o=c=>{try{a(t.throw(c))}catch(l){s(l)}},a=c=>c.done?i(c.value):Promise.resolve(c.value).then(r,o);a((t=t.apply(n,e)).next())}),re=function(n,e){this[0]=n,this[1]=e},ge=(n,e,t)=>{var i=(o,a,c,l)=>{try{var h=t[o](a),u=(a=h.value)instanceof re,f=h.done;Promise.resolve(u?a[0]:a).then(p=>u?i(o==="return"?o:"next",a[1]?{done:p.done,value:p.value}:p,c,l):c({value:p,done:f})).catch(p=>i("throw",p,c,l))}catch(p){l(p)}},s=o=>r[o]=a=>new Promise((c,l)=>i(o,a,c,l)),r={};return t=t.apply(n,e),r[Symbol.asyncIterator]=()=>r,s("next"),s("throw"),s("return"),r},Mn=n=>{var e=n[$e("asyncIterator")],t=!1,i,s={};return e==null?(e=n[$e("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 re(new Promise(a=>{var c=e[r](o);if(!(c instanceof Object))throw TypeError("Object expected");a(c)}),1)}}),s[$e("iterator")]=()=>s,i("next"),"throw"in e?i("throw"):s.throw=r=>{throw r},"return"in e&&i("return"),s},X=(n,e,t)=>(e=n[$e("asyncIterator")])?e.call(n):(n=n[$e("iterator")](),e={},t=(i,s)=>(s=n[i])&&(e[i]=r=>new Promise((o,a,c)=>(r=s.call(n,r),c=r.done,Promise.resolve(r.value).then(l=>o({value:l,done:c}),a)))),t("next"),t("return"),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ie=require("uuid"),ks=require("js-base64"),Ss=require("axios"),x=require("@glodon-aiot/apis"),Es=require("socket.io-client"),Zt=require("dayjs"),de=class de{constructor(e){this.prefix=e}log(...e){de.debug&&console.log(this.prefix,...e)}info(...e){de.debug&&console.info(`%c ${this.prefix} %o`,"color:#0f0;",...e)}warn(...e){de.debug&&console.warn(this.prefix,...e)}error(...e){de.debug&&console.error(this.prefix,...e)}report(...e){console.error(this.prefix,...e)}};y(de,"debug",!1);let B=de;const en=["list_directory","read_file","stat_file","search_files","search_text","apply_patch","write_file","upload_file","download_file"],De="builtin_tools",yi={dev:De,test:De,prod:De,local:De},wi=yi,Te="current-workspace",vi=1024,je=1024*1024,bi=50,Ze=Object.freeze({maxReadBytes:1*je,maxWriteBytes:5*je,maxSearchResults:200,maxConcurrentRequests:4,maxTransferBytes:bi*je,toolTimeoutMs:3e4,commandTimeoutMs:10*6e4,searchTimeoutMs:6e4,transferTimeoutMs:10*6e4,approvalTimeoutMs:5*6e4}),_i=200,ki=1e3,Si=8,tn=16,Ei=2e3,Ii=1*je,et=500,Ai=3,nn=8*vi,xi=Object.freeze(["glodon.com"]),Ti=Object.freeze([".git","node_modules",".svn",".idea",".vscode"]),Li=Object.freeze(["~$*",".~lock*","*.tmp"]),Is=["apply_patch","write_file","upload_file","download_file"],Ri=["search_files","search_text"],Mi=["upload_file","download_file"];var g=(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))(g||{});class m extends Error{constructor(t,i,s){super(i);y(this,"code");y(this,"data");this.name="ToolError",this.code=t,this.data=s}}const As="尚未授权工作文件夹,请先在助手中选择或恢复访问工作文件夹。";function mt(){return new m(403,As,{reason:"workspace_not_granted"})}function U(){return new m(499,"操作已取消。")}function N(n){if(n!=null&&n.aborted)throw U()}function Cn(n){const e=n&&typeof n=="object"&&"message"in n?String(n.message):"";return/[\u4e00-\u9fff]/.test(e)?e:void 0}function Le(n){var t,i;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 mt();case"AbortError":return U();case"NoModificationAllowedError":case"InvalidModificationError":case"InvalidStateError":return new m(403,"文件当前不可写,可能正被其他程序占用或为只读。");case"QuotaExceededError":return new m(413,(t=Cn(n))!=null?t:"磁盘空间不足或超出写入配额。");case"TooManyRequestsError":return new m(429,(i=Cn(n))!=null?i:"排队的文件操作过多,请稍后重试。");case"PreviewLimitError":return new m(413,"同时预览的文件过多,请先关掉一些预览。");default:return new m(500,"本地文件操作失败,请稍后重试。")}}const ee=16e3,xs=`
2
+ …输出已截断`;function Fn(n){if(n.length<=ee)return n;let e=ee;const t=n.charCodeAt(e-1);return t>=55296&&t<=56319&&(e-=1),n.slice(0,e)+xs}function jt(n){return{exec(t){return d(this,null,function*(){const i=yield n.exec(t);return S(b({},i),{stdout:Fn(i.stdout),stderr:Fn(i.stderr)})})}}}function Ci(n,e){return e===n||e.startsWith(`${n}/`)}function k(n,e=n){return new DOMException(e,n)}function gt(n){return ge(this,null,function*(){typeof n=="string"?yield new TextEncoder().encode(n):n instanceof Uint8Array?yield n:yield*Mn(n)})}const sn="glodon-workspace",ot="__glodonHostBridge",Ee=1,Fi=500*1024*1024;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===sn)return t}function On(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 Ts(n){const e=globalThis;n?e[ot]=n:delete e[ot]}function Ni(){var e;const n=On(globalThis[ot]);return n||On((e=globalThis.chrome)==null?void 0:e.webview)}const Ls=1024*1024;function Rs(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 a=new Uint8Array(r.length+i.length);return a.set(r,0),a.set(i,r.length),a}function bt(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 Nn={revision:0,network:{mode:"off",allow:[]},packages:{python:{enabled:!0}}};function $n(n){var i,s,r,o,a,c,l;if(!n||typeof n!="object")return;const e=n,t=(i=e.network)==null?void 0:i.mode;if(!(t!=="off"&&t!=="allowlist"&&t!=="open"))return b({revision:typeof e.revision=="number"?e.revision:0,network:{mode:t,allow:Array.isArray((s=e.network)==null?void 0:s.allow)?e.network.allow.filter(h=>typeof h=="string"):[]},packages:{python:{enabled:((o=(r=e.packages)==null?void 0:r.python)==null?void 0:o.enabled)!==!1}}},Number.isInteger((a=e.exec)==null?void 0:a.maxConcurrent)&&((c=e.exec)==null?void 0:c.maxConcurrent)>=1?{exec:{maxConcurrent:(l=e.exec)==null?void 0:l.maxConcurrent}}:{})}function Ms(n){const e=n==null?void 0:n.denied;return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Cs(n,e){if(!e.length)return n;const t=`宿主网络策略拒绝了:${e.join("、")}。不要重试这些地址;需要时请用户在宿主设置里允许。`;return n?`${n}
3
+ ${t}`:t}const ye="沙箱已退出。";function _t(n){if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n)}function Pn(n,e,t,i){const s=n.length>ee?n.slice(n.length-ee):n;if(!e&&!t&&!i&&n.length<=ee)return s;let r=`
4
+ …输出已截断`;return t&&(r+=`,完整输出见 ${t}`),i&&(r+=",日志已截断"),s+r}class Fs{constructor(e=t=>new WebSocket(t)){y(this,"notice");y(this,"policy",Nn);y(this,"socket");y(this,"generation",0);y(this,"authed",!1);y(this,"seq",0);y(this,"calls",new Map);y(this,"outgoing",[]);this.openSocket=e}get ready(){const e=this.notice;return(e==null?void 0:e.state)==="ready"&&e.protocol===Ee&&!!(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"?ye:"沙箱没有就绪。"}apply(e){const t=this.notice;if(this.notice=e,!this.ready||!(e!=null&&e.url)||!e.token){this.failAll(k("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(k("AbortError",ye)),this.stop(),this.connect(e.url,e.token))}httpOrigin(){var t;const e=(t=this.notice)==null?void 0:t.url;return e!=null&&e.startsWith("ws://")?e.slice(5).replace(/\/$/,""):""}stat(e){return d(this,null,function*(){return this.invoke({op:"stat",path:e})})}url(e){return d(this,null,function*(){const i=(yield this.invoke({op:"url",path:e})).ticket;if(typeof i!="string"||!/^[a-f0-9]{32}$/.test(i))throw k("NotAllowedError","地址无效。");return i})}releaseUrl(e){return d(this,null,function*(){yield this.invoke({op:"releaseUrl",ticket:e})})}list(e,t){return d(this,null,function*(){return this.invoke({op:"list",path:e},t)})}read(r){return d(this,arguments,function*(e,t=0,i=Fi,s){const o=this.begin({op:"read",path:e,offset:t,maxBytes:i},s),a=[];let c;for(;!c;){const f=yield this.next(o),p=_t(f);if(p){a.push(bt(p).payload);continue}c=f}if(this.calls.delete(o),c.ok===!1)throw k(String(c.name||"NotAllowedError"),String(c.message||"读取失败。"));const l=a.reduce((f,p)=>f+p.length,0),h=new Uint8Array(l);let u=0;return a.forEach(f=>{h.set(f,u),u+=f.length}),h})}write(e,t,i,s){return d(this,null,function*(){const r=this.begin({op:"write",path:e,size:t.length,createDirectories:i},s);yield this.upload(r,t,"写入失败。")})}skillStatus(e,t){return d(this,null,function*(){const i=yield this.invoke({op:"skillStatus",applicationId:e},t);return Array.isArray(i.skills)?i.skills:[]})}skillRead(e,t,i,s,r){return d(this,null,function*(){const o=this.begin({op:"skillRead",applicationId:e,skillId:t,version:i,path:s},r),a=[];let c;for(;!c;){const f=yield this.next(o),p=_t(f);if(p){a.push(bt(p).payload);continue}c=f}if(this.calls.delete(o),c.ok===!1)throw k(String(c.name||"NotAllowedError"),String(c.message||"读取失败。"));const l=a.reduce((f,p)=>f+p.length,0),h=new Uint8Array(l);let u=0;return a.forEach(f=>{h.set(f,u),u+=f.length}),h})}skillList(e,t,i,s,r){return d(this,null,function*(){const o=yield this.invoke({op:"skillList",applicationId:e,skillId:t,version:i,path:s},r);return typeof o.files=="string"?o.files:""})}skillGrep(e,t,i,s,r,o){return d(this,null,function*(){const a=yield this.invoke({op:"skillGrep",applicationId:e,skillId:t,version:i,path:s,pattern:r},o);return typeof a.matches=="string"?a.matches:""})}installSkill(e,t,i){return d(this,null,function*(){const s=this.begin(S(b({op:"installSkill"},e),{size:t.length}),i);yield this.upload(s,t,"安装失败。")})}skillPrune(e,t,i,s){return d(this,null,function*(){yield this.invoke({op:"skillPrune",applicationId:e,keep:t,busy:i},s)})}mkdir(e){return d(this,null,function*(){yield this.invoke({op:"mkdir",path:e})})}remove(e,t){return d(this,null,function*(){yield this.invoke({op:"remove",path:e,recursive:t})})}move(e,t){return d(this,null,function*(){yield this.invoke({op:"move",from:e,to:t})})}exec(e,t,i){return d(this,null,function*(){var l;const s=this.begin(b({},e),t);let r="",o="",a=!1,c=!1;for(;this.calls.has(s);){const h=yield this.next(s);if(h.op==="stdout"||h.op==="stderr"){const w=String((l=h.text)!=null?l:"");i==null||i(h.op,w),h.op==="stdout"?(r+=w,r.length>ee&&(a=!0),r=r.slice(-ee)):(o+=w,o.length>ee&&(c=!0),o=o.slice(-ee));continue}if(this.calls.delete(s),h.ok===!1)throw k(String(h.name||"NotAllowedError"),String(h.message||"命令失败。"));const u=typeof h.logPath=="string"?h.logPath:void 0,f=h.logTruncated===!0,p=Ms(h.network);return b({exitCode:typeof h.exitCode=="number"?h.exitCode:1,timedOut:h.timedOut===!0,stdout:Pn(r,a,u,f),stderr:Cs(Pn(o,c,u,f),p),cwd:typeof h.cwd=="string"?h.cwd:void 0},p.length?{denied:p}:{})}throw k("AbortError",ye)})}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 k(String(r.name||"NotAllowedError"),String(r.message||"请求失败。"));return r})}upload(e,t,i){return d(this,null,function*(){let s=0;for(;;){const r=yield this.next(e);if(r.ok===!1)throw this.calls.delete(e),k(String(r.name||"NotAllowedError"),String(r.message||i));if(r.ok===!0){this.calls.delete(e);return}if(r.op!=="ack"||s>=t.length)continue;const o=t.subarray(s,s+Ls),a=s+o.length;this.send(Rs(e,s,a===t.length,o)),s=a}})}begin(e,t){if(!this.ready)throw k("NotAllowedError",this.unavailableMessage());if(t!=null&&t.aborted)throw k("AbortError");const i=`sbx-${++this.seq}`;let s=()=>{};const r={messages:[],waiters:[],reject:a=>s(a)};this.calls.set(i,r);const o=()=>{this.send({protocol:Ee,id:i,op:"cancel"}),r.reject(k("AbortError"))};return t==null||t.addEventListener("abort",o,{once:!0}),s=a=>{t==null||t.removeEventListener("abort",o),this.calls.delete(i);const c=r.waiters.shift();c&&c(Promise.reject(a))},this.send(b({protocol:Ee,id:i},e)),i}next(e){const t=this.calls.get(e);if(!t)return Promise.reject(k("AbortError",ye));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:Ee,op:"auth",token:t}))},s.onmessage=r=>{i===this.generation&&this.onFrame(r.data)},s.onclose=()=>{i===this.generation&&(this.authed=!1,this.failAll(k("AbortError",ye)))},s.onerror=()=>{}}onFrame(e){var s,r;const t=_t(e);if(t){const o=bt(t);this.push(o.id,t);return}let i;try{i=JSON.parse(String(e))}catch(o){return}if(i.op==="policy"&&i.id===void 0){this.policy=(s=$n(i.policy))!=null?s:this.policy;return}if(i.op==="auth"){if(i.ok===!0){this.policy=(r=$n(i.policy))!=null?r:Nn,this.authed=!0;const o=this.outgoing;this.outgoing=[],o.forEach(a=>a())}return}if(i.op==="bye"){this.failAll(k("AbortError",ye)),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 Dn(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 He{constructor(e,t="",i=new Fs){y(this,"displayName");y(this,"capabilities",new Set);y(this,"sandboxVersion");y(this,"sandboxProtocol");y(this,"sandbox");this.displayName=t,this.sandbox=i}setCapabilities(e,t={}){const i=Array.isArray(e)?e.filter(s=>typeof s=="string"):[];this.capabilities=new Set(i),this.sandboxVersion=typeof t.version=="string"?t.version:void 0}applySandbox(e){this.sandboxProtocol=e==null?void 0:e.protocol,this.sandbox.apply(e)}get canExec(){return this.sandbox.ready}get protocolMismatch(){return this.sandboxProtocol!==void 0&&this.sandboxProtocol!==Ee}unavailableMessage(){return this.sandbox.unavailableMessage()}stat(e){return d(this,null,function*(){const t=yield this.sandbox.stat(e);return Dn(t.entry,e.split("/").pop()||this.displayName)})}listEntries(e,t){return d(this,null,function*(){const i=yield this.sandbox.list(e,t);return(Array.isArray(i.entries)?i.entries:[]).map(r=>Dn(r,""))})}url(e){return d(this,null,function*(){const t=yield this.sandbox.url(e),i=this.sandbox.httpOrigin();if(!i)throw k("NotAllowedError",this.unavailableMessage());return{url:`http://${i}/file/${t}`,release:()=>{this.sandbox.releaseUrl(t).catch(()=>{})}}})}readFile(e,t){return d(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 d(this,null,function*(){yield this.sandbox.mkdir(e)})}remove(i){return d(this,arguments,function*(e,t={}){yield this.sandbox.remove(e,t.recursive===!0)})}move(e,t){return d(this,null,function*(){yield this.sandbox.move(e,t)})}exec(e){return d(this,null,function*(){const t=yield this.sandbox.exec({op:"exec",cwd:e.cwd,command:e.command,argv:e.argv,timeoutMs:e.timeoutMs,skill:e.skill},e.signal,e.onOutput);if(t.timedOut)throw k("AbortError","命令运行超时。");return t})}writeFile(s,r){return d(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 h=X(gt(t)),u,f,p;u=!(f=yield h.next()).done;u=!1){const w=f.value;N(i.signal),o.push(w)}}catch(f){p=[f]}finally{try{u&&(f=h.return)&&(yield f.call(h))}finally{if(p)throw p[0]}}const a=o.reduce((w,_)=>w+_.byteLength,0),c=new Uint8Array(a);let l=0;o.forEach(w=>{c.set(w,l),l+=w.byteLength}),yield this.sandbox.write(e,c,i.createDirectories===!0,i.signal)})}}function j(n,e){throw new m(g.BadRequest,n?`参数 ${n} ${e}`:`参数${e}`)}function Os(n,e){return typeof n!="string"?n:(e.type==="integer"||e.type==="number")&&/^-?\d+(\.\d+)?$/.test(n.trim())?Number(n):e.type==="boolean"&&(n==="true"||n==="false")?n==="true":n}function Ut(n,e,t){switch(n=Os(n,e),e.type){case"string":typeof n!="string"&&j(t,"必须是字符串。"),e.minLength!==void 0&&n.length<e.minLength&&j(t,"不能为空。"),e.maxLength!==void 0&&n.length>e.maxLength&&j(t,`不能超过 ${e.maxLength} 字。`);break;case"integer":(typeof n!="number"||!Number.isInteger(n))&&j(t,"必须是整数。");break;case"number":(typeof n!="number"||!Number.isFinite(n))&&j(t,"必须是数字。");break;case"boolean":typeof n!="boolean"&&j(t,"必须是布尔值。");break;case"array":if(Array.isArray(n)||j(t,"必须是数组。"),e.minItems!==void 0&&n.length<e.minItems&&j(t,"不能为空。"),e.items){const i=e.items;return n.map((s,r)=>Ut(s,i,`${t}[${r}]`))}break;case"object":return $i(n,e,t)}return e.enum&&!e.enum.includes(n)&&j(t,`必须是 ${e.enum.join("、")} 之一。`),typeof n=="number"&&(e.minimum!==void 0&&n<e.minimum&&j(t,`不能小于 ${e.minimum}。`),e.maximum!==void 0&&n>e.maximum&&j(t,`不能大于 ${e.maximum}。`)),n}function $i(n,e,t){var r,o;(!n||typeof n!="object"||Array.isArray(n))&&j(t,"必须是对象。");const i=n,s={};for(const a of(r=e.required)!=null?r:[])(i[a]===void 0||i[a]===null)&&j(t?`${t}.${a}`:a,"是必填项。");for(const[a,c]of Object.entries((o=e.properties)!=null?o:{})){if(i[a]===void 0||i[a]===null)continue;const l=t?`${t}.${a}`:a;s[a]=c.oneOf?(Ut(i[a],S(b({},c),{oneOf:void 0}),l),i[a]):Ut(i[a],c,l)}return s}function Pi(n,e){return $i(n,e,"")}const qt=["shell","read_file","write_file","append_file","run_file","edit_file","grep","find","load_skill","read_skill_resource","list_skill_files","grep_skill","run_skill_script"],Ht=81920,at=81920,Ns=2e4,rn=".",P="/workspace",Bn={".py":"python3",".sh":"sh",".bash":"sh",".js":"node",".mjs":"node",".cjs":"node"},$s=["input","output","uploads","tmp"],on="不要使用 input、output、uploads、tmp,也不要新建这些目录。请把文件直接放在工作区已有位置或根目录。",Ps=/(?:^|[\s'"=;|&<>`:])\/?(?:input|output|uploads|tmp)(?=\/|[\s'"=;|&<>`:]|$)/,Ds=/(?:^|[\s'"=;|&<>`:])\/?skills(?=\/|[\s'"=;|&<>`:]|$)/;function jn(n){return Ds.test(n)}function ct(n){return Ps.test(n)}function an(n){const e=n.split("/")[0];return $s.includes(e)}function tt(n){throw new m(g.Forbidden,n,{reason:"path_outside_workspace"})}function Di(n){if(typeof n!="string"||n.length===0)throw new m(g.BadRequest,"path 必须是工作区内路径。");(n.includes("\0")||n.includes("\\"))&&tt("路径不能包含反斜杠。");const e=n.normalize("NFC").trim();if(!e)throw new m(g.BadRequest,"path 必须是工作区内路径。");/^[a-zA-Z]:/.test(e)&&tt("路径不能包含盘符。");const t=e.split("/").filter(i=>i.length>0&&i!==".");if(t.some(i=>i==="..")&&tt("路径不能包含 .. 。"),t.length>0&&an(t[0]))throw new m(g.BadRequest,on);if(t[0]==="skills")throw new m(g.Forbidden,"技能文件只能通过技能工具访问。");return t.join("/")}function Me(n){return Di(n)}function Bs(n){return Di(n)}function cn(n){return n?`/${n}`:"/"}function js(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!=="..")&&!an(e[0])}function yt(n,e){if(!n||/[\\/\0]/.test(n)||n==="."||n==="..")throw new m(g.BadRequest,"skill_name 必须是单个技能目录名。");if(!e||e.startsWith("/")||e.includes("\\")||e.includes("\0"))throw new m(g.BadRequest,"资源路径必须是技能目录内的相对路径。");const t=e.split("/").filter(i=>i.length>0);return(t.length===0||t.some(i=>i==="."||i===".."))&&tt("资源路径不能跳出技能目录。"),`skills/${n}/${t.join("/")}`}const Bi="https://cv-cdn.obs.cn-north-4.myhuaweicloud.com/glodon/libs/",Us="3.6.0",qs=`${Bi}just-bash/${Us}/just-bash.mjs`,Hs="314.0.7",zs=`${Bi}pyodide/${Hs}/`,ji=["numpy","pandas","matplotlib","pillow","lxml"],kt=new Map;function Ws(n){return import(n)}function Vs(n){let e=kt.get(n);return e||(e=Ws(n).catch(t=>{throw kt.delete(n),t}),kt.set(n,e)),e}const Un=new Map;function Gs(n){return/[\\^$.|+()[\]{}]/.test(n)?`\\${n}`:n}function Xs(n,e=!1){const t=`${e?"s":"i"}:${n}`,i=Un.get(t);if(i)return i;let s="";for(let o=0;o<n.length;o++){const a=n[o];a==="*"?n[o+1]==="*"?(o++,n[o+1]==="/"?(o++,s+="(?:.*/)?"):s+=".*"):s+="[^/]*":a==="?"?s+="[^/]":s+=Gs(a)}const r=new RegExp(`^${s}$`,e?"":"i");return Un.set(t,r),r}function lt(n,e,t=!1){return Xs(n,t).test(e)}function ln(n){const e=n.lastIndexOf("/");return e<0?n:n.slice(e+1)}const Ui=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"}]),Ys="该文件被列为敏感文件,不允许访问";class dn{constructor(e=[]){y(this,"rules");const t=e.filter(i=>i&&typeof i.pattern=="string"&&i.pattern).map(i=>S(b({},i),{id:String(i.id||i.pattern),source:i.source==="enterprise"?"enterprise":"product"}));this.rules=[...Ui,...t]}match(e,t){if(!e)return null;const i=ln(e);for(const s of this.rules){if(s.operations&&!s.operations.includes(t))continue;const r=s.match==="path"?e:i;if(lt(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||Ys},已拒绝访问。`}}function Ce(n,e,t){const i=n.sensitive.match(e,t);if(i)throw new m(g.Forbidden,dn.reasonOf(i),{reason:"sensitive_file",ruleId:i.id})}function nt(n,e){return d(this,null,function*(){try{return yield n.stat(e)}catch(t){if(Le(t).code===g.NotFound)return null;throw t}})}function hn(n,e){return d(this,null,function*(){const t=yield n.stat(e);if(t.kind!=="file")throw new m(g.BadRequest,"目标是目录,不是文件。");return t})}function Re(n){return d(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 Y(n){return d(this,null,function*(){return new Uint8Array(yield n.arrayBuffer())})}function fe(n){const e=Math.min(n.byteLength,nn);for(let t=0;t<e;t++)if(n[t]===0)return!0;return!1}function Ks(n){return d(this,null,function*(){return fe(yield Y(n.slice(0,nn)))})}function qi(n){return n[0]===239&&n[1]===187&&n[2]===191}function Js(n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch(e){throw new m(g.BadRequest,"文件不是 UTF-8 编码,暂不支持修改。")}}function un(n){return new TextEncoder().encode(n).byteLength}function Hi(){return new Promise(n=>setTimeout(n,0))}function Qs(n){return n>=1024*1024?`${(n/1024/1024).toFixed(1)} MB`:n>=1024?`${(n/1024).toFixed(1)} KB`:`${n} B`}function he(n,e="文件"){return new m(g.TooLarge,`${e}超过大小上限 ${Qs(n)}。`)}const Zs=`# 在 Pyodide 里按 python3 命令行的语义运行代码。由 pyodideWorker.js 加载,最后一个表达式 run 交给 JS 调用。
5
5
  # 解释器在多次命令之间复用,所以每次运行前恢复 sys.path、环境变量和工作目录,并丢掉工作区里的模块缓存。
6
6
  import io
7
7
  import os
@@ -93,7 +93,7 @@ def run(mode, target, argv, cwd, stdin):
93
93
 
94
94
 
95
95
  run
96
- `,Js=`// Pyodide 专用 Worker。PythonRunner 用这份源码创建 Blob Module Worker,不经过集成方的打包器,
96
+ `,er=`// Pyodide 专用 Worker。PythonRunner 用这份源码创建 Blob Module Worker,不经过集成方的打包器,
97
97
  // 所以这里只能写浏览器直接能跑的 JS,不能有 import/export 语句和顶层 await。
98
98
  //
99
99
  // init { indexURL, packages, runner } → ready | failed { message }
@@ -331,52 +331,52 @@ self.onmessage = (event) => {
331
331
  );
332
332
  }
333
333
  };
334
- `,Ut=`浏览器环境不能安装依赖。可以直接 import ${Di.join("、")},需要其他包请改用宿主环境。
335
- `,Qs=10*1024*1024,Zs=64*1024*1024;function er(n){return!n||n==="."||n==="/"?N:n===N||n.startsWith(`${N}/`)?n:`${N}/${n.replace(/^\/+/,"")}`}function Ge(n){if(n===N)return"";if(n.startsWith(`${N}/`))return n.slice(N.length+1)}const tr=new Set(["-u","-B","-E","-s","-S","-I","-O","-OO","-q","-b","-bb"]);function we(n,e,t=""){return{exitCode:n,stdout:t,stderr:e}}function nr(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 ir(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 a=r==="-c"?o.shift():r.slice(2);return a===void 0?we(2,`python3: -c 后面缺少代码
336
- `):{mode:"c",target:a,argv:["-c",...o],stdin:t}}if(r==="-m"){const a=o.shift();return a?a==="pip"||a==="ensurepip"?we(1,Ut):{mode:"m",target:a,argv:[a,...o],stdin:t}:we(2,`python3: -m 后面缺少模块名
334
+ `,zt=`浏览器环境不能安装依赖。可以直接 import ${ji.join("、")},需要其他包请改用宿主环境。
335
+ `,tr=10*1024*1024,nr=64*1024*1024;function ir(n){return!n||n==="."||n==="/"?P:n===P||n.startsWith(`${P}/`)?n:`${P}/${n.replace(/^\/+/,"")}`}function Xe(n){if(n===P)return"";if(n.startsWith(`${P}/`))return n.slice(P.length+1)}const sr=new Set(["-u","-B","-E","-s","-S","-I","-O","-OO","-q","-b","-bb"]);function we(n,e,t=""){return{exitCode:n,stdout:t,stderr:e}}function rr(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 or(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 a=r==="-c"?o.shift():r.slice(2);return a===void 0?we(2,`python3: -c 后面缺少代码
336
+ `):{mode:"c",target:a,argv:["-c",...o],stdin:t}}if(r==="-m"){const a=o.shift();return a?a==="pip"||a==="ensurepip"?we(1,zt):{mode:"m",target:a,argv:[a,...o],stdin:t}:we(2,`python3: -m 后面缺少模块名
337
337
  `)}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 we(0,"",`usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
338
- `);if(!(tr.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("-")?we(2,`python3: 浏览器环境不支持参数 ${r}
339
- `):{mode:"file",target:nr(e,r),argv:[r,...o],stdin:t}}}return t.length>0?{mode:"c",target:new TextDecoder().decode(t),argv:[""],stdin:i}:we(2,`浏览器环境不支持交互式 Python,请用 python3 -c "…" 或脚本文件。
340
- `)}function bt(n){var e;return n&&typeof n=="object"?String((e=n.name)!=null?e:""):""}function _t(n){return n instanceof Error?n.message:String(n)}function Bn(n,e){return new Promise((t,i)=>{if(!n)return;const s=()=>{e==null||e(),i(k("AbortError"))};n.aborted?s():n.addEventListener("abort",s,{once:!0})})}function sr(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 rr{constructor(e){v(this,"state");v(this,"queue",Promise.resolve());v(this,"nextId",0);this.options=e}get indexURL(){return this.options.indexURL||Us}loadError(e){return new m(g.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:sr)(Js)}catch(o){throw this.loadError(`(${_t(o)})`)}let t;const i=new Promise((o,a)=>t={resolve:o,reject:a}),s={worker:e,ready:i,pending:new Map};return i.catch(()=>{}),e.onmessage=({data:o})=>{var c;const a=o;if(a.type==="ready")t.resolve();else if(a.type==="failed"){const l=this.loadError(`(${a.message})`);t.reject(l),this.dispose(s,l)}else a.type==="result"&&((c=s.pending.get(a.id))==null||c.resolve(a),s.pending.delete(a.id))},e.onerror=o=>{var l;const a=_t((l=o==null?void 0:o.message)!=null?l:o),c=this.loadError(`(${a})`);t.reject(c),this.dispose(s,new Error(`Python 运行环境意外退出:${a}`))},e.postMessage({type:"init",indexURL:this.indexURL,packages:Di,runner:Ks}),s}run(e){const t=this.queue.then(()=>this.runNow(e));return this.queue=t.catch(()=>{}),t}runNow(e){return d(this,null,function*(){var u,f,p;const t=er(e.cwd),i=ir(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 k("AbortError");const s=(p=this.state)!=null?p:this.state=this.spawn();yield Promise.race([s.ready,Bn(e.signal)]);const r=yield this.collect(e.signal),o=this.nextId+=1,a=new Promise((y,w)=>s.pending.set(o,{resolve:y,reject:w}));s.worker.postMessage(b({type:"run",id:o,files:r.files,dirs:r.dirs,cwd:t},i),r.files.map(y=>y.data.buffer));const c=yield Promise.race([a,Bn(e.signal,()=>this.dispose(s,k("AbortError")))]),l=[];if(r.skipped.length>0){const y=r.skipped.slice(0,5).map(_=>`/${_}`),w=r.skipped.length>y.length?` 等 ${r.skipped.length} 个`:"";l.push(`提示:${y.join("、")}${w}文件超过同步上限(单个 10 MB、合计 64 MB),Python 里看不到。`)}return{exitCode:(yield this.writeBack(c,r,l))&&c.exitCode===0?1:c.exitCode,stdout:c.stdout,stderr:c.stderr+l.map(y=>`${y}
341
- `).join("")}})}collect(e){return d(this,null,function*(){const{adapter:t,sensitive:i}=this.options,s={files:[],dirs:[],synced:new Set,skipped:[]};let r=0;const o=a=>d(this,null,function*(){var l,h;let c;try{c=yield t.listEntries(a,e)}catch(u){if(bt(u)==="NotFoundError"||bt(u)==="TypeMismatchError")return;throw u}s.dirs.push(a?`${N}/${a}`:N);for(const u of c.sort((f,p)=>f.name.localeCompare(p.name))){const f=a?`${a}/${u.name}`:u.name;if(u.kind==="directory"){yield o(f);continue}if(i.match(f,"read"))continue;const p=(h=(l=u.size)!=null?l:(yield t.stat(f)).size)!=null?h:0;if(p>Qs||r+p>Zs){s.skipped.push(f);continue}const y=yield X(yield t.readFile(f));r+=y.byteLength,s.files.push({path:`${N}/${f}`,data:y}),s.synced.add(f)}});return yield o(""),s})}exists(e){return d(this,null,function*(){try{return yield this.options.adapter.stat(e),!0}catch(t){return!1}})}writeBack(e,t,i){return d(this,null,function*(){const{adapter:s,sensitive:r}=this.options;let o=!1;const a=(l,h)=>{o=!0,i.push(`写回 ${l} 失败:${_t(h)}`)};for(const l of e.createdDirs.sort()){const h=Ge(l);!h||!s.createDirectory||(yield s.createDirectory(h).catch(u=>a(l,u)))}for(const{path:l,data:h}of e.written){const u=Ge(l);u&&(r.match(u,"write")?i.push(`没有写回 ${l}:敏感文件不能由命令修改。`):!t.synced.has(u)&&(yield this.exists(u))?i.push(`没有写回 ${l}:工作区里已有这个文件,但它没有同步进 Python,为避免覆盖已跳过。`):yield s.writeFile(u,h,{createDirectories:!0}).catch(f=>a(l,f)))}if(e.removed.length>0&&!s.remove)return i.push(`当前工作区不支持删除,${e.removed.join("、")} 仍然保留。`),o;for(const l of e.removed){const h=Ge(l);h&&(yield s.remove(h).catch(u=>{bt(u)!=="NotFoundError"&&a(l,u)}))}const c=e.removedDirs.sort((l,h)=>h.split("/").length-l.split("/").length);for(const l of c){const h=Ge(l);h&&(yield s.remove(h).catch(()=>{}))}return o})}}const or={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 C(n,e,t){var s;const i=new Error(`${n}: ${(s=or[n])!=null?s:n}, ${e} '${t}'`);return i.code=n,i}function Xe(n){var e;return n&&typeof n=="object"?String((e=n.name)!=null?e:""):""}function kt(n){const e=typeof n=="string"?n:n==null?void 0:n.encoding;return(e!=null?e:"utf8").toLowerCase()}function jn(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return e}function ar(n,e){switch(e){case"binary":case"latin1":case"ascii":return jn(n);case"base64":return btoa(jn(n));case"hex":return Array.from(n,t=>t.toString(16).padStart(2,"0")).join("");default:return new TextDecoder().decode(n)}}function Un(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 te(n){const e=[];for(const t of n.split("/"))!t||t==="."||(t===".."?e.pop():e.push(t));return`/${e.join("/")}`}class cr{constructor(e,t,i){this.adapter=e,this.root=t,this.sensitive=i}relative(e){const t=te(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 te(e)==="/"}guard(e,t,i){const s=this.relative(e);if(this.sensitive.match(s,t))throw C("EACCES",i,this.shown(e));return s}mapError(e,t,i){if(e&&typeof e=="object"&&typeof e.code=="string")return e;switch(Xe(e)){case"NotFoundError":return C("ENOENT",t,this.shown(i));case"TypeMismatchError":return C(t==="open"||t==="write"?"EISDIR":"ENOTDIR",t,this.shown(i));case"InvalidModificationError":return C(t==="rm"?"ENOTEMPTY":"EEXIST",t,this.shown(i));case"NotAllowedError":case"SecurityError":case"NoModificationAllowedError":return C("EACCES",t,this.shown(i));default:return C("EIO",t,this.shown(i))}}entry(e,t){return d(this,null,function*(){try{return yield this.adapter.stat(this.relative(e))}catch(i){if(this.isRoot(e)&&Xe(i)==="NotFoundError")return{name:this.root,kind:"directory"};throw this.mapError(i,t,e)}})}ensureRoot(){return d(this,null,function*(){if(this.root)try{yield this.adapter.stat(this.root)}catch(e){if(Xe(e)!=="NotFoundError")throw e;this.adapter.createDirectory&&(yield this.adapter.createDirectory(this.root))}})}readFileBuffer(e){return d(this,null,function*(){const t=this.guard(e,"read","open");if((yield this.entry(e,"open")).kind!=="file")throw C("EISDIR","read",this.shown(e));try{return yield X(yield this.adapter.readFile(t))}catch(s){throw this.mapError(s,"open",e)}})}readFile(e,t){return d(this,null,function*(){return ar(yield this.readFileBuffer(e),kt(t))})}writeFile(e,t,i){return d(this,null,function*(){if(this.isRoot(e))throw C("EISDIR","open",this.shown(e));const s=this.guard(e,"write","open"),r=te(e).lastIndexOf("/")===0;try{r&&(yield this.ensureRoot()),yield this.adapter.writeFile(s,Un(t,kt(i)),{createDirectories:!0})}catch(o){throw this.mapError(o,"open",e)}})}appendFile(e,t,i){return d(this,null,function*(){let s=new Uint8Array;(yield this.exists(e))&&(s=yield this.readFileBuffer(e));const r=Un(t,kt(i)),o=new Uint8Array(s.byteLength+r.byteLength);o.set(s),o.set(r,s.byteLength),yield this.writeFile(e,o)})}exists(e){return d(this,null,function*(){try{return yield this.entry(e,"access"),!0}catch(t){return!1}})}stat(e){return d(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 d(this,null,function*(){if(!this.adapter.createDirectory)throw C("EPERM","mkdir",this.shown(e));if(yield this.exists(e)){if(t!=null&&t.recursive)return;throw C("EEXIST","mkdir",this.shown(e))}if(!(t!=null&&t.recursive)){const i=te(e),s=i.slice(0,i.lastIndexOf("/"))||"/";if(!(yield this.exists(s)))throw C("ENOENT","mkdir",this.shown(e))}try{yield this.adapter.createDirectory(this.relative(e))}catch(i){throw this.mapError(i,"mkdir",e)}})}readdirWithFileTypes(e){return d(this,null,function*(){if((yield this.entry(e,"scandir")).kind!=="directory")throw C("ENOTDIR","scandir",this.shown(e));let i;try{i=yield this.adapter.listEntries(this.relative(e))}catch(s){if(this.isRoot(e)&&Xe(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 d(this,null,function*(){return(yield this.readdirWithFileTypes(e)).map(t=>t.name)})}rm(e,t){return d(this,null,function*(){if(this.isRoot(e))throw C("EPERM","rm",this.shown(e));const i=this.guard(e,"write","rm");if(!(yield this.exists(e))){if(t!=null&&t.force)return;throw C("ENOENT","rm",this.shown(e))}if(!this.adapter.remove)throw C("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 d(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 C("EISDIR","cp",this.shown(e));yield this.mkdir(t,{recursive:!0});for(const r of yield this.readdir(e))yield this.cp(`${te(e)}/${r}`,`${te(t)}/${r}`,i)})}mv(e,t){return d(this,null,function*(){if(this.isRoot(e)||this.isRoot(t))throw C("EPERM","rename",this.shown(e));const i=this.guard(e,"write","rename"),s=this.guard(t,"write","rename");if(!this.adapter.move)throw C("EPERM","rename",this.shown(e));try{yield this.adapter.move(i,s)}catch(r){throw this.mapError(r,"rename",e)}})}resolvePath(e,t){return te(t.startsWith("/")?t:`${e}/${t}`)}getAllPaths(){return[]}chmod(e){return d(this,null,function*(){yield this.entry(e,"chmod")})}symlink(e,t){return d(this,null,function*(){throw C("EPERM","symlink",this.shown(t))})}link(e,t){return d(this,null,function*(){throw C("EPERM","link",this.shown(t))})}readlink(e){return d(this,null,function*(){throw yield this.entry(e,"readlink"),C("EINVAL","readlink",this.shown(e))})}realpath(e){return d(this,null,function*(){return yield this.entry(e,"realpath"),te(e)})}utimes(e){return d(this,null,function*(){yield this.entry(e,"utime")})}}const lr=`当前环境没有 Node,请改用 python3 或 shell 命令。
342
- `,dr=new Set(["writeFile","appendFile","mkdir","rm","cp","mv","chmod","symlink","link","utimes","createExclusive"]),hr="dev|bin|usr|proc|etc|System|Library|private|var|opt|sbin|tmp|Applications|Volumes|cores|net|home",ur=new RegExp(`(^|[\\s'"=(;|&<>\`:])/(?!${hr}(?=$|[/\\s'"\`;|&)<>:]))(?!/)`,"g");function fr(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:(...a)=>{var l;const c=String((l=a[0])!=null?l:"");if(e&&dr.has(String(s))&&!c.startsWith("/dev/"))throw Object.assign(new Error(`EROFS: 只能写入工作区下的路径, open '${c}'`),{code:"EROFS"});return o.apply(i,a)}}}),lock:()=>e=!0}}function pr(n){return n instanceof Uint8Array?n:Uint8Array.from(String(n!=null?n:""),e=>e.charCodeAt(0)&255)}function mr(n){return n instanceof DOMException&&n.name==="AbortError"}function gr(n){if(!n)return;if(n===N)return".";if(!n.startsWith(`${N}/`))return;const e=n.slice(N.length+1).replace(/\/+$/,"");if(!e)return".";const t=e.split("/");if(!t.some(i=>!i||i==="."||i===".."))return t.join("/")}function qn(n){return!n||n==="."?N:n===N||n.startsWith(`${N}/`)?n:`${N}/${n.replace(/^\/+/,"")}`}function yr(n){return n.replace(ur,(e,t)=>`${t}${N}/`)}function Et(n){return n.replace(/\/workspace(?![\p{L}\p{N}_.\-])/gu,(e,t,i)=>i[t+e.length]==="/"?"":"/")}class wr{constructor(e){v(this,"python");this.options=e,this.python=new rr({adapter:e.adapter,sensitive:e.sensitive,indexURL:e.pyodideIndexURL,createWorker:e.createWorker})}load(){return d(this,null,function*(){const e=this.options.moduleURL||Bs;try{return yield Hs(e)}catch(t){throw new m(g.NotImplemented,`命令运行时加载失败,请确认页面能访问 ${e}(CSP 需在 script-src 放行该地址)。`)}})}create(e,t,i,s){const{adapter:r,sensitive:o}=this.options,a=fr(new e.InMemoryFs),c=new e.MountableFs({base:a.fs});c.mount(N,new cr(r,"",o));const l=(f,p,y)=>e.defineCommand(f,()=>d(this,null,function*(){return{stdout:"",stderr:p,exitCode:y}})),h=f=>e.defineCommand(f,(p,y)=>d(this,null,function*(){var w;try{return yield this.python.run({args:p,cwd:y.cwd,stdin:pr(y.stdin),signal:i})}catch(_){return _ instanceof m||mr(_)?((w=s.fatal)!=null||(s.fatal=_),{stdout:"",stderr:"",exitCode:1}):{stdout:"",stderr:`${f}: ${_ instanceof Error?_.message:String(_)}
343
- `,exitCode:1}}})),u=new e.Bash({fs:c,cwd:t,env:{HOME:"/tmp",LANG:"C.UTF-8"},customCommands:[l("node",lr,127),l("pip",Ut,1),l("pip3",Ut,1),h("python3"),h("python")],defenseInDepth:!1});return a.lock(),u}exec(e){return d(this,null,function*(){var h,u,f,p,y,w,_,A,I;if(sn(e.cwd)||rt((h=e.command)!=null?h:"")||rt((f=(u=e.argv)==null?void 0:u[1])!=null?f:""))return{exitCode:1,stdout:"",stderr:`${nn}
344
- `};const t=yield this.load();if((p=e.signal)!=null&&p.aborted)throw k("AbortError");const i=qn(e.cwd),s={},r=this.create(t,i,e.signal,s),[o,a,...c]=(y=e.argv)!=null?y:[];let l;try{l=e.argv?yield r.exec(o,{cwd:i,signal:e.signal,args:[qn(a),...c]}):yield r.exec(yr((w=e.command)!=null?w:""),{cwd:i,signal:e.signal,rawScript:!0})}catch(S){if(s.fatal)throw s.fatal;if((_=e.signal)!=null&&_.aborted)throw k("AbortError");const L=S instanceof Error?S.message:String(S);return{exitCode:1,stdout:"",stderr:`bash: ${Et(L)}
345
- `}}if(s.fatal)throw s.fatal;if((A=e.signal)!=null&&A.aborted)throw k("AbortError");return{exitCode:l.exitCode,stdout:Et(l.stdout),stderr:Et(l.stderr),cwd:gr((I=l.env)==null?void 0:I.PWD)}})}}const re=n=>({type:"string",minLength:1,description:n}),St="脚本能否联网由运行环境决定;被宿主网络策略拒绝的地址会在结果里列出。",ve="必填。工作区内路径。以 / 开头,例如 /说明.md;也可以不写开头的斜杠,例如 notes/a.md。不要使用 input、output、uploads、tmp,也不要新建这些目录。",dn={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 把大文件正文打到标准输出。${St}`,parameters:{type:"object",required:["command"],properties:{command:{type:"string",minLength:1,maxLength:Cs,description:"必填。一条不超过 20000 字的 shell 命令。当前目录已是工作区根目录。可以包含短的 python 或 heredoc。读取文件正文请改用 read_file。"}}}},read_file:{functionCode:"read_file",name:"读取文件",description:"读取工作区内的文本文件并返回内容;读不到时返回失败原因。path 可以以 / 开头,也可以不写开头的斜杠。未超过上限的文本按原文返回;超过单次读取上限的结构化文本(JSON/XML/SVG/CSV/TSV)会先附带通用结构概览和短预览,需要特定片段时再用 start_line 和 end_line。PDF 和图片只返回文件摘要,不返回正文。",parameters:{type:"object",required:["path"],properties:{path:re(ve),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 可以是以 / 开头的工作区路径,也可以不带开头斜杠,例如 /说明.md、notes/a.md。文件已存在时覆盖。单次覆盖写入按 UTF-8 字节计,默认不超过 ${st} 字节。超限时先写一段,再用 edit_file 修改,或用 append_file 追加下一段。SVG 和整页 HTML 由工作区里的脚本生成,不要直接放进 content。`,parameters:{type:"object",required:["path","content"],properties:{path:re(ve),content:{type:"string",description:`必填。覆盖写入的文本,UTF-8 不超过 ${st} 字节。不要放入 SVG 或整页 HTML。`}}}},append_file:{functionCode:"append_file",name:"追加文件",description:"把一段文本追加到工作区内文件末尾。path 可以以 / 开头,也可以不写开头的斜杠。文件不存在时创建。覆盖写入超过字节上限时,用本工具把下一段接到同一文件。追加不设字节上限,但不要在一次调用里放入整份 HTML 或 SVG。",parameters:{type:"object",required:["path","content"],properties:{path:re(ve),content:{type:"string",description:"必填。要追加到文件末尾的文本。不受覆盖写入的字节上限约束。"}}}},run_file:{functionCode:"run_file",name:"执行文件",description:`执行工作区里已经存在的 .py、.sh、.bash、.js、.mjs 或 .cjs 脚本文件。生成 SVG、HTML、JSON 等产物时优先使用:先用 write_file 写脚本,脚本自行读取工作区文件并写出产物,再调用本工具。脚本运行时当前目录是工作区根目录,脚本里访问工作区文件要写相对路径,例如 data.json、notes/a.py。不要使用或新建 input、output、uploads、tmp。需要查看文件正文时用 read_file,不要把整份文件打印到标准输出。${St}`,parameters:{type:"object",required:["path"],properties:{path:re("必填。要执行的 .py、.sh、.bash、.js、.mjs 或 .cjs 文件。可以是 /scripts/gen.py,也可以是 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:re(ve),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:re(ve),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:re(ve),name:{type:"string",minLength:1,description:"必填。find -name 通配,例如 *.svg 或 *.html。"}}}},load_skill:{functionCode:"load_skill",name:"加载技能",description:"按技能名称加载平台技能的完整说明(SKILL.md),并附上技能包内全部文件的相对路径。技能不在工程目录里。之后用 read_skill_resource 按这些路径读取,或用 grep_skill 搜索。",parameters:{type:"object",required:["skill_name"],properties:{skill_name:{type:"string",minLength:1,description:"必填。要加载的技能名称。"}}}},read_skill_resource:{functionCode:"read_skill_resource",name:"读取技能资源",description:"读取技能包内的文本。resource_name 是相对技能根目录的路径。传目录则列出该目录下的文件;传 . 列出整个技能包;以 grep: 开头则按基本正则搜索,例如 grep:portrait。",parameters:{type:"object",required:["skill_name","resource_name"],properties:{skill_name:{type:"string",minLength:1,description:"必填。技能名称。"},resource_name:{type:"string",minLength:1,description:"必填。要读取的技能资源相对路径名称。"}}}},list_skill_files:{functionCode:"list_skill_files",name:"列出技能文件",description:"列出平台技能包内的文件和目录。不传 path 时列出整个技能包。技能不在工程目录里。",parameters:{type:"object",required:["skill_name"],properties:{skill_name:{type:"string",minLength:1,description:"必填。技能名称。"},path:{type:"string",description:"可选。技能包内的相对目录,例如 skills 或 tools/dwgkit。省略则从技能根目录列出。"}}}},grep_skill:{functionCode:"grep_skill",name:"搜索技能内容",description:"在平台技能包内按 grep 基本正则搜索文本,返回路径、行号和匹配行。",parameters:{type:"object",required:["skill_name","pattern"],properties:{skill_name:{type:"string",minLength:1,description:"必填。技能名称。"},pattern:{type:"string",minLength:1,description:"必填。grep 基本正则,例如 portrait 或 def .*。"},path:{type:"string",description:"可选。只搜索该相对目录或文件,例如 skills/cad-drawing-understanding。"}}}},run_skill_script:{functionCode:"run_skill_script",name:"运行技能脚本",description:`执行平台技能包内的脚本并返回输出。当前目录是工作区根目录,参数里的用户文件按相对工作区根目录传,例如 docs/a.docx。技能自己的资源按脚本文件所在目录查找,不在工程的 skills 目录里。${St}`,parameters:{type:"object",required:["skill_name","script_name"],properties:{skill_name:{type:"string",minLength:1,description:"必填。技能名称。"},script_name:{type:"string",minLength:1,description:"必填。要运行的技能脚本相对路径(保持技能说明中列出的目录前缀,如 scripts/run.py)。"},args:{type:"array",description:'传递给脚本的命令行位置参数数组,例如 ["input.docx", "--output", "result.idx"]。',items:{type:"string",description:"单个脚本参数。"}}}}}},Hn=Object.keys(dn);if(Hn.length!==Bt.length||Bt.some(n=>!Hn.includes(n)))throw new Error("BUILTIN_TOOL_SCHEMAS 与 BUILTIN_FUNCTION_CODES 不一致");const zn=500;function Se(n){return`预览:
346
- ${n.length>zn?n.slice(0,zn):n}`}function vr(n){let e;try{e=JSON.parse(n)}catch(t){return`JSON 无法完整解析。
347
- ${Se(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}
348
- ${Se(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}
349
- ${Se(n)}`}return`JSON ${e===null?"null":typeof e}。
350
- ${Se(n)}`}function Wn(n,e){var l,h;const t=n.match(/<([A-Za-z_][\w:.-]*)\b/),i=(l=t==null?void 0:t[1])!=null?l:"未知",s=new Map,r=new RegExp("<([A-Za-z_][\\w:.-]*)\\b","g");let o,a=!1;for(;o=r.exec(n);){const u=o[1];if(!a&&u===i){a=!0;continue}if(s.set(u,((h=s.get(u))!=null?h:0)+1),s.size>30)break}const c=Array.from(s.entries()).slice(0,20).map(([u,f])=>`${u} (${f})`).join("、");return`${e} 根元素 ${i}。直接或嵌套子元素:${c||"(无)"}。
351
- ${Se(n)}`}function Vn(n,e,t){var c;const i=n.split(/\r?\n/).filter(l=>l.length>0),s=(c=i[0])!=null?c:"",r=s?s.split(e).length:0,o=Math.max(i.length-1,0),a=i.slice(0,4).join(`
338
+ `);if(!(sr.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("-")?we(2,`python3: 浏览器环境不支持参数 ${r}
339
+ `):{mode:"file",target:rr(e,r),argv:[r,...o],stdin:t}}}return t.length>0?{mode:"c",target:new TextDecoder().decode(t),argv:[""],stdin:i}:we(2,`浏览器环境不支持交互式 Python,请用 python3 -c "…" 或脚本文件。
340
+ `)}function St(n){var e;return n&&typeof n=="object"?String((e=n.name)!=null?e:""):""}function Et(n){return n instanceof Error?n.message:String(n)}function qn(n,e){return new Promise((t,i)=>{if(!n)return;const s=()=>{e==null||e(),i(k("AbortError"))};n.aborted?s():n.addEventListener("abort",s,{once:!0})})}function ar(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 cr{constructor(e){y(this,"state");y(this,"queue",Promise.resolve());y(this,"nextId",0);this.options=e}get indexURL(){return this.options.indexURL||zs}loadError(e){return new m(g.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:ar)(er)}catch(o){throw this.loadError(`(${Et(o)})`)}let t;const i=new Promise((o,a)=>t={resolve:o,reject:a}),s={worker:e,ready:i,pending:new Map};return i.catch(()=>{}),e.onmessage=({data:o})=>{var c;const a=o;if(a.type==="ready")t.resolve();else if(a.type==="failed"){const l=this.loadError(`(${a.message})`);t.reject(l),this.dispose(s,l)}else a.type==="result"&&((c=s.pending.get(a.id))==null||c.resolve(a),s.pending.delete(a.id))},e.onerror=o=>{var l;const a=Et((l=o==null?void 0:o.message)!=null?l:o),c=this.loadError(`(${a})`);t.reject(c),this.dispose(s,new Error(`Python 运行环境意外退出:${a}`))},e.postMessage({type:"init",indexURL:this.indexURL,packages:ji,runner:Zs}),s}run(e){const t=this.queue.then(()=>this.runNow(e));return this.queue=t.catch(()=>{}),t}runNow(e){return d(this,null,function*(){var u,f,p;const t=ir(e.cwd),i=or(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 k("AbortError");const s=(p=this.state)!=null?p:this.state=this.spawn();yield Promise.race([s.ready,qn(e.signal)]);const r=yield this.collect(e.signal),o=this.nextId+=1,a=new Promise((w,_)=>s.pending.set(o,{resolve:w,reject:_}));s.worker.postMessage(b({type:"run",id:o,files:r.files,dirs:r.dirs,cwd:t},i),r.files.map(w=>w.data.buffer));const c=yield Promise.race([a,qn(e.signal,()=>this.dispose(s,k("AbortError")))]),l=[];if(r.skipped.length>0){const w=r.skipped.slice(0,5).map(v=>`/${v}`),_=r.skipped.length>w.length?` 等 ${r.skipped.length} 个`:"";l.push(`提示:${w.join("、")}${_}文件超过同步上限(单个 10 MB、合计 64 MB),Python 里看不到。`)}return{exitCode:(yield this.writeBack(c,r,l))&&c.exitCode===0?1:c.exitCode,stdout:c.stdout,stderr:c.stderr+l.map(w=>`${w}
341
+ `).join("")}})}collect(e){return d(this,null,function*(){const{adapter:t,sensitive:i}=this.options,s={files:[],dirs:[],synced:new Set,skipped:[]};let r=0;const o=a=>d(this,null,function*(){var l,h;let c;try{c=yield t.listEntries(a,e)}catch(u){if(St(u)==="NotFoundError"||St(u)==="TypeMismatchError")return;throw u}s.dirs.push(a?`${P}/${a}`:P);for(const u of c.sort((f,p)=>f.name.localeCompare(p.name))){const f=a?`${a}/${u.name}`:u.name;if(u.kind==="directory"){yield o(f);continue}if(i.match(f,"read"))continue;const p=(h=(l=u.size)!=null?l:(yield t.stat(f)).size)!=null?h:0;if(p>tr||r+p>nr){s.skipped.push(f);continue}const w=yield Y(yield t.readFile(f));r+=w.byteLength,s.files.push({path:`${P}/${f}`,data:w}),s.synced.add(f)}});return yield o(""),s})}exists(e){return d(this,null,function*(){try{return yield this.options.adapter.stat(e),!0}catch(t){return!1}})}writeBack(e,t,i){return d(this,null,function*(){const{adapter:s,sensitive:r}=this.options;let o=!1;const a=(l,h)=>{o=!0,i.push(`写回 ${l} 失败:${Et(h)}`)};for(const l of e.createdDirs.sort()){const h=Xe(l);!h||!s.createDirectory||(yield s.createDirectory(h).catch(u=>a(l,u)))}for(const{path:l,data:h}of e.written){const u=Xe(l);u&&(r.match(u,"write")?i.push(`没有写回 ${l}:敏感文件不能由命令修改。`):!t.synced.has(u)&&(yield this.exists(u))?i.push(`没有写回 ${l}:工作区里已有这个文件,但它没有同步进 Python,为避免覆盖已跳过。`):yield s.writeFile(u,h,{createDirectories:!0}).catch(f=>a(l,f)))}if(e.removed.length>0&&!s.remove)return i.push(`当前工作区不支持删除,${e.removed.join("、")} 仍然保留。`),o;for(const l of e.removed){const h=Xe(l);h&&(yield s.remove(h).catch(u=>{St(u)!=="NotFoundError"&&a(l,u)}))}const c=e.removedDirs.sort((l,h)=>h.split("/").length-l.split("/").length);for(const l of c){const h=Xe(l);h&&(yield s.remove(h).catch(()=>{}))}return o})}}const lr={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 O(n,e,t){var s;const i=new Error(`${n}: ${(s=lr[n])!=null?s:n}, ${e} '${t}'`);return i.code=n,i}function Ye(n){var e;return n&&typeof n=="object"?String((e=n.name)!=null?e:""):""}function It(n){const e=typeof n=="string"?n:n==null?void 0:n.encoding;return(e!=null?e:"utf8").toLowerCase()}function Hn(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return e}function dr(n,e){switch(e){case"binary":case"latin1":case"ascii":return Hn(n);case"base64":return btoa(Hn(n));case"hex":return Array.from(n,t=>t.toString(16).padStart(2,"0")).join("");default:return new TextDecoder().decode(n)}}function zn(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 ne(n){const e=[];for(const t of n.split("/"))!t||t==="."||(t===".."?e.pop():e.push(t));return`/${e.join("/")}`}class hr{constructor(e,t,i){this.adapter=e,this.root=t,this.sensitive=i}relative(e){const t=ne(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 ne(e)==="/"}guard(e,t,i){const s=this.relative(e);if(this.sensitive.match(s,t))throw O("EACCES",i,this.shown(e));return s}mapError(e,t,i){if(e&&typeof e=="object"&&typeof e.code=="string")return e;switch(Ye(e)){case"NotFoundError":return O("ENOENT",t,this.shown(i));case"TypeMismatchError":return O(t==="open"||t==="write"?"EISDIR":"ENOTDIR",t,this.shown(i));case"InvalidModificationError":return O(t==="rm"?"ENOTEMPTY":"EEXIST",t,this.shown(i));case"NotAllowedError":case"SecurityError":case"NoModificationAllowedError":return O("EACCES",t,this.shown(i));default:return O("EIO",t,this.shown(i))}}entry(e,t){return d(this,null,function*(){try{return yield this.adapter.stat(this.relative(e))}catch(i){if(this.isRoot(e)&&Ye(i)==="NotFoundError")return{name:this.root,kind:"directory"};throw this.mapError(i,t,e)}})}ensureRoot(){return d(this,null,function*(){if(this.root)try{yield this.adapter.stat(this.root)}catch(e){if(Ye(e)!=="NotFoundError")throw e;this.adapter.createDirectory&&(yield this.adapter.createDirectory(this.root))}})}readFileBuffer(e){return d(this,null,function*(){const t=this.guard(e,"read","open");if((yield this.entry(e,"open")).kind!=="file")throw O("EISDIR","read",this.shown(e));try{return yield Y(yield this.adapter.readFile(t))}catch(s){throw this.mapError(s,"open",e)}})}readFile(e,t){return d(this,null,function*(){return dr(yield this.readFileBuffer(e),It(t))})}writeFile(e,t,i){return d(this,null,function*(){if(this.isRoot(e))throw O("EISDIR","open",this.shown(e));const s=this.guard(e,"write","open"),r=ne(e).lastIndexOf("/")===0;try{r&&(yield this.ensureRoot()),yield this.adapter.writeFile(s,zn(t,It(i)),{createDirectories:!0})}catch(o){throw this.mapError(o,"open",e)}})}appendFile(e,t,i){return d(this,null,function*(){let s=new Uint8Array;(yield this.exists(e))&&(s=yield this.readFileBuffer(e));const r=zn(t,It(i)),o=new Uint8Array(s.byteLength+r.byteLength);o.set(s),o.set(r,s.byteLength),yield this.writeFile(e,o)})}exists(e){return d(this,null,function*(){try{return yield this.entry(e,"access"),!0}catch(t){return!1}})}stat(e){return d(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 d(this,null,function*(){if(!this.adapter.createDirectory)throw O("EPERM","mkdir",this.shown(e));if(yield this.exists(e)){if(t!=null&&t.recursive)return;throw O("EEXIST","mkdir",this.shown(e))}if(!(t!=null&&t.recursive)){const i=ne(e),s=i.slice(0,i.lastIndexOf("/"))||"/";if(!(yield this.exists(s)))throw O("ENOENT","mkdir",this.shown(e))}try{yield this.adapter.createDirectory(this.relative(e))}catch(i){throw this.mapError(i,"mkdir",e)}})}readdirWithFileTypes(e){return d(this,null,function*(){if((yield this.entry(e,"scandir")).kind!=="directory")throw O("ENOTDIR","scandir",this.shown(e));let i;try{i=yield this.adapter.listEntries(this.relative(e))}catch(s){if(this.isRoot(e)&&Ye(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 d(this,null,function*(){return(yield this.readdirWithFileTypes(e)).map(t=>t.name)})}rm(e,t){return d(this,null,function*(){if(this.isRoot(e))throw O("EPERM","rm",this.shown(e));const i=this.guard(e,"write","rm");if(!(yield this.exists(e))){if(t!=null&&t.force)return;throw O("ENOENT","rm",this.shown(e))}if(!this.adapter.remove)throw O("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 d(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 O("EISDIR","cp",this.shown(e));yield this.mkdir(t,{recursive:!0});for(const r of yield this.readdir(e))yield this.cp(`${ne(e)}/${r}`,`${ne(t)}/${r}`,i)})}mv(e,t){return d(this,null,function*(){if(this.isRoot(e)||this.isRoot(t))throw O("EPERM","rename",this.shown(e));const i=this.guard(e,"write","rename"),s=this.guard(t,"write","rename");if(!this.adapter.move)throw O("EPERM","rename",this.shown(e));try{yield this.adapter.move(i,s)}catch(r){throw this.mapError(r,"rename",e)}})}resolvePath(e,t){return ne(t.startsWith("/")?t:`${e}/${t}`)}getAllPaths(){return[]}chmod(e){return d(this,null,function*(){yield this.entry(e,"chmod")})}symlink(e,t){return d(this,null,function*(){throw O("EPERM","symlink",this.shown(t))})}link(e,t){return d(this,null,function*(){throw O("EPERM","link",this.shown(t))})}readlink(e){return d(this,null,function*(){throw yield this.entry(e,"readlink"),O("EINVAL","readlink",this.shown(e))})}realpath(e){return d(this,null,function*(){return yield this.entry(e,"realpath"),ne(e)})}utimes(e){return d(this,null,function*(){yield this.entry(e,"utime")})}}const ur=`当前环境没有 Node,请改用 python3 或 shell 命令。
342
+ `,fr=new Set(["writeFile","appendFile","mkdir","rm","cp","mv","chmod","symlink","link","utimes","createExclusive"]),pr="dev|bin|usr|proc|etc|System|Library|private|var|opt|sbin|tmp|Applications|Volumes|cores|net|home",mr=new RegExp(`(^|[\\s'"=(;|&<>\`:])/(?!${pr}(?=$|[/\\s'"\`;|&)<>:]))(?!/)`,"g");function gr(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:(...a)=>{var l;const c=String((l=a[0])!=null?l:"");if(e&&fr.has(String(s))&&!c.startsWith("/dev/"))throw Object.assign(new Error(`EROFS: 只能写入工作区下的路径, open '${c}'`),{code:"EROFS"});return o.apply(i,a)}}}),lock:()=>e=!0}}function yr(n){return n instanceof Uint8Array?n:Uint8Array.from(String(n!=null?n:""),e=>e.charCodeAt(0)&255)}function wr(n){return n instanceof DOMException&&n.name==="AbortError"}function vr(n){if(!n)return;if(n===P)return".";if(!n.startsWith(`${P}/`))return;const e=n.slice(P.length+1).replace(/\/+$/,"");if(!e)return".";const t=e.split("/");if(!t.some(i=>!i||i==="."||i===".."))return t.join("/")}function Wn(n){return!n||n==="."?P:n===P||n.startsWith(`${P}/`)?n:`${P}/${n.replace(/^\/+/,"")}`}function br(n){return n.replace(mr,(e,t)=>`${t}${P}/`)}function At(n){return n.replace(/\/workspace(?![\p{L}\p{N}_.\-])/gu,(e,t,i)=>i[t+e.length]==="/"?"":"/")}class _r{constructor(e){y(this,"python");this.options=e,this.python=new cr({adapter:e.adapter,sensitive:e.sensitive,indexURL:e.pyodideIndexURL,createWorker:e.createWorker})}load(){return d(this,null,function*(){const e=this.options.moduleURL||qs;try{return yield Vs(e)}catch(t){throw new m(g.NotImplemented,`命令运行时加载失败,请确认页面能访问 ${e}(CSP 需在 script-src 放行该地址)。`)}})}create(e,t,i,s){const{adapter:r,sensitive:o}=this.options,a=gr(new e.InMemoryFs),c=new e.MountableFs({base:a.fs});c.mount(P,new hr(r,"",o));const l=(f,p,w)=>e.defineCommand(f,()=>d(this,null,function*(){return{stdout:"",stderr:p,exitCode:w}})),h=f=>e.defineCommand(f,(p,w)=>d(this,null,function*(){var _;try{return yield this.python.run({args:p,cwd:w.cwd,stdin:yr(w.stdin),signal:i})}catch(v){return v instanceof m||wr(v)?((_=s.fatal)!=null||(s.fatal=v),{stdout:"",stderr:"",exitCode:1}):{stdout:"",stderr:`${f}: ${v instanceof Error?v.message:String(v)}
343
+ `,exitCode:1}}})),u=new e.Bash({fs:c,cwd:t,env:{HOME:"/tmp",LANG:"C.UTF-8"},customCommands:[l("node",ur,127),l("pip",zt,1),l("pip3",zt,1),h("python3"),h("python")],defenseInDepth:!1});return a.lock(),u}exec(e){return d(this,null,function*(){var h,u,f,p,w,_,v,A,E;if(an(e.cwd)||ct((h=e.command)!=null?h:"")||ct((f=(u=e.argv)==null?void 0:u[1])!=null?f:""))return{exitCode:1,stdout:"",stderr:`${on}
344
+ `};const t=yield this.load();if((p=e.signal)!=null&&p.aborted)throw k("AbortError");const i=Wn(e.cwd),s={},r=this.create(t,i,e.signal,s),[o,a,...c]=(w=e.argv)!=null?w:[];let l;try{l=e.argv?yield r.exec(o,{cwd:i,signal:e.signal,args:[Wn(a),...c]}):yield r.exec(br((_=e.command)!=null?_:""),{cwd:i,signal:e.signal,rawScript:!0})}catch(I){if(s.fatal)throw s.fatal;if((v=e.signal)!=null&&v.aborted)throw k("AbortError");const M=I instanceof Error?I.message:String(I);return{exitCode:1,stdout:"",stderr:`bash: ${At(M)}
345
+ `}}if(s.fatal)throw s.fatal;if((A=e.signal)!=null&&A.aborted)throw k("AbortError");return{exitCode:l.exitCode,stdout:At(l.stdout),stderr:At(l.stderr),cwd:vr((E=l.env)==null?void 0:E.PWD)}})}}const oe=n=>({type:"string",minLength:1,description:n}),xt="脚本能否联网由运行环境决定;被宿主网络策略拒绝的地址会在结果里列出。",ve="必填。工作区内路径。以 / 开头,例如 /说明.md;也可以不写开头的斜杠,例如 notes/a.md。不要使用 input、output、uploads、tmp,也不要新建这些目录。",fn={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 把大文件正文打到标准输出。${xt}`,parameters:{type:"object",required:["command"],properties:{command:{type:"string",minLength:1,maxLength:Ns,description:"必填。一条不超过 20000 字的 shell 命令。当前目录已是工作区根目录。可以包含短的 python 或 heredoc。读取文件正文请改用 read_file。"}}}},read_file:{functionCode:"read_file",name:"读取文件",description:"读取工作区内的文本文件并返回内容;读不到时返回失败原因。path 可以以 / 开头,也可以不写开头的斜杠。未超过上限的文本按原文返回;超过单次读取上限的结构化文本(JSON/XML/SVG/CSV/TSV)会先附带通用结构概览和短预览,需要特定片段时再用 start_line 和 end_line。PDF 和图片只返回文件摘要,不返回正文。",parameters:{type:"object",required:["path"],properties:{path:oe(ve),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 可以是以 / 开头的工作区路径,也可以不带开头斜杠,例如 /说明.md、notes/a.md。文件已存在时覆盖。单次覆盖写入按 UTF-8 字节计,默认不超过 ${at} 字节。超限时先写一段,再用 edit_file 修改,或用 append_file 追加下一段。SVG 和整页 HTML 由工作区里的脚本生成,不要直接放进 content。`,parameters:{type:"object",required:["path","content"],properties:{path:oe(ve),content:{type:"string",description:`必填。覆盖写入的文本,UTF-8 不超过 ${at} 字节。不要放入 SVG 或整页 HTML。`}}}},append_file:{functionCode:"append_file",name:"追加文件",description:"把一段文本追加到工作区内文件末尾。path 可以以 / 开头,也可以不写开头的斜杠。文件不存在时创建。覆盖写入超过字节上限时,用本工具把下一段接到同一文件。追加不设字节上限,但不要在一次调用里放入整份 HTML 或 SVG。",parameters:{type:"object",required:["path","content"],properties:{path:oe(ve),content:{type:"string",description:"必填。要追加到文件末尾的文本。不受覆盖写入的字节上限约束。"}}}},run_file:{functionCode:"run_file",name:"执行文件",description:`执行工作区里已经存在的 .py、.sh、.bash、.js、.mjs 或 .cjs 脚本文件。生成 SVG、HTML、JSON 等产物时优先使用:先用 write_file 写脚本,脚本自行读取工作区文件并写出产物,再调用本工具。脚本运行时当前目录是工作区根目录,脚本里访问工作区文件要写相对路径,例如 data.json、notes/a.py。不要使用或新建 input、output、uploads、tmp。需要查看文件正文时用 read_file,不要把整份文件打印到标准输出。${xt}`,parameters:{type:"object",required:["path"],properties:{path:oe("必填。要执行的 .py、.sh、.bash、.js、.mjs 或 .cjs 文件。可以是 /scripts/gen.py,也可以是 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:oe(ve),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:oe(ve),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:oe(ve),name:{type:"string",minLength:1,description:"必填。find -name 通配,例如 *.svg 或 *.html。"}}}},load_skill:{functionCode:"load_skill",name:"加载技能",description:"按技能名称加载平台技能的完整说明(SKILL.md),并附上技能包内全部文件的相对路径。技能不在工程目录里。之后用 read_skill_resource 按这些路径读取,或用 grep_skill 搜索。",parameters:{type:"object",required:["skill_name"],properties:{skill_name:{type:"string",minLength:1,description:"必填。要加载的技能名称。"}}}},read_skill_resource:{functionCode:"read_skill_resource",name:"读取技能资源",description:"读取技能包内的文本。resource_name 是相对技能根目录的路径。传目录则列出该目录下的文件;传 . 列出整个技能包;以 grep: 开头则按基本正则搜索,例如 grep:portrait。",parameters:{type:"object",required:["skill_name","resource_name"],properties:{skill_name:{type:"string",minLength:1,description:"必填。技能名称。"},resource_name:{type:"string",minLength:1,description:"必填。要读取的技能资源相对路径名称。"}}}},list_skill_files:{functionCode:"list_skill_files",name:"列出技能文件",description:"列出平台技能包内的文件和目录。不传 path 时列出整个技能包。技能不在工程目录里。",parameters:{type:"object",required:["skill_name"],properties:{skill_name:{type:"string",minLength:1,description:"必填。技能名称。"},path:{type:"string",description:"可选。技能包内的相对目录,例如 skills 或 tools/dwgkit。省略则从技能根目录列出。"}}}},grep_skill:{functionCode:"grep_skill",name:"搜索技能内容",description:"在平台技能包内按 grep 基本正则搜索文本,返回路径、行号和匹配行。",parameters:{type:"object",required:["skill_name","pattern"],properties:{skill_name:{type:"string",minLength:1,description:"必填。技能名称。"},pattern:{type:"string",minLength:1,description:"必填。grep 基本正则,例如 portrait 或 def .*。"},path:{type:"string",description:"可选。只搜索该相对目录或文件,例如 skills/cad-drawing-understanding。"}}}},run_skill_script:{functionCode:"run_skill_script",name:"运行技能脚本",description:`执行平台技能包内的脚本并返回输出。当前目录是工作区根目录,参数里的用户文件按相对工作区根目录传,例如 docs/a.docx。技能自己的资源按脚本文件所在目录查找,不在工程的 skills 目录里。${xt}`,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:"单个脚本参数。"}}}}}},Vn=Object.keys(fn);if(Vn.length!==qt.length||qt.some(n=>!Vn.includes(n)))throw new Error("BUILTIN_TOOL_SCHEMAS 与 BUILTIN_FUNCTION_CODES 不一致");const Gn=500;function Ie(n){return`预览:
346
+ ${n.length>Gn?n.slice(0,Gn):n}`}function kr(n){let e;try{e=JSON.parse(n)}catch(t){return`JSON 无法完整解析。
347
+ ${Ie(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}
348
+ ${Ie(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}
349
+ ${Ie(n)}`}return`JSON ${e===null?"null":typeof e}。
350
+ ${Ie(n)}`}function Xn(n,e){var l,h;const t=n.match(/<([A-Za-z_][\w:.-]*)\b/),i=(l=t==null?void 0:t[1])!=null?l:"未知",s=new Map,r=new RegExp("<([A-Za-z_][\\w:.-]*)\\b","g");let o,a=!1;for(;o=r.exec(n);){const u=o[1];if(!a&&u===i){a=!0;continue}if(s.set(u,((h=s.get(u))!=null?h:0)+1),s.size>30)break}const c=Array.from(s.entries()).slice(0,20).map(([u,f])=>`${u} (${f})`).join("、");return`${e} 根元素 ${i}。直接或嵌套子元素:${c||"(无)"}。
351
+ ${Ie(n)}`}function Yn(n,e,t){var c;const i=n.split(/\r?\n/).filter(l=>l.length>0),s=(c=i[0])!=null?c:"",r=s?s.split(e).length:0,o=Math.max(i.length-1,0),a=i.slice(0,4).join(`
352
352
  `);return`${t},${r} 列,数据行 ${o}。表头:${s}
353
353
  预览:
354
- ${a}`}function br(n){const e=He(n);return e===".json"||e===".xml"||e===".svg"||e===".csv"||e===".tsv"}function _r(n,e){const t=He(n);return t===".json"?vr(e):t===".svg"?Wn(e,"SVG"):t===".xml"?Wn(e,"XML"):t===".tsv"?Vn(e," ","TSV"):t===".csv"?Vn(e,",","CSV"):Se(e)}function He(n){var i;const e=(i=n.split("/").pop())!=null?i:"",t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}const kr=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".tif",".tiff"]);function qi(n){return kr.has(He(n))}function Hi(n,e){return He(n)===".pdf"?!0:!e||e.byteLength<4?!1:e[0]===37&&e[1]===80&&e[2]===68&&e[3]===70}function zi(n){return!!n&&typeof n=="object"&&n.name==="NotFoundError"}function ze(n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch(e){throw new m(g.BadRequest,"文件不是 UTF-8 文本。")}}function hn(n){return n===""?[]:(n.endsWith(`
354
+ ${a}`}function Sr(n){const e=ze(n);return e===".json"||e===".xml"||e===".svg"||e===".csv"||e===".tsv"}function Er(n,e){const t=ze(n);return t===".json"?kr(e):t===".svg"?Xn(e,"SVG"):t===".xml"?Xn(e,"XML"):t===".tsv"?Yn(e," ","TSV"):t===".csv"?Yn(e,",","CSV"):Ie(e)}function ze(n){var i;const e=(i=n.split("/").pop())!=null?i:"",t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}const Ir=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".tif",".tiff"]);function zi(n){return Ir.has(ze(n))}function Wi(n,e){return ze(n)===".pdf"?!0:!e||e.byteLength<4?!1:e[0]===37&&e[1]===80&&e[2]===68&&e[3]===70}function Vi(n){return!!n&&typeof n=="object"&&n.name==="NotFoundError"}function We(n){try{return new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch(e){throw new m(g.BadRequest,"文件不是 UTF-8 文本。")}}function pn(n){return n===""?[]:(n.endsWith(`
355
355
  `)?n.slice(0,-1):n).split(`
356
- `)}function Er(n,e,t){if(e!==void 0&&t!==void 0&&t<e)throw new m(g.BadRequest,"end_line 不能小于 start_line。");const i=hn(n),s=Math.max((e!=null?e:1)-1,0),r=t!=null?t:i.length;return i.slice(s,r).join(`
357
- `)}function Gn(n){if(ln(n)<=jt)return{text:n,truncated:!1};const e=new TextEncoder().encode(n);let t=jt;for(;t>0&&(e[t]&192)===128;)t-=1;const i=new TextDecoder().decode(e.slice(0,t)),s=i.lastIndexOf(`
358
- `);return{text:s>0?i.slice(0,s):i,truncated:!0}}function We(n,e){return d(this,null,function*(){const t=yield n.stat(e);if(t.kind!=="file")throw new m(g.BadRequest,"目标是目录,不是文件。");const i=yield X(yield n.readFile(e));return{entry:t,bytes:i}})}function Xn(n,e,t){const i=typeof t=="number"?`${t} 字节,`:"";return`${n},${i}路径 ${rn(e)}。不返回正文。`}function at(n){const e=$n[He(n)];if(!e){const t=Object.keys($n),i=`${t.slice(0,-1).join("、")} 或 ${t.at(-1)}`;throw new m(g.BadRequest,`只能执行 ${i} 文件。`)}return e}function Wi(n){if(!n.runner)throw new m(g.NotImplemented,"当前环境不能执行命令或脚本,需要端侧宿主。");return n.runner}function un(n,e,t,i){return d(this,null,function*(){yield n.writeFile(e,t,{createDirectories:!0,signal:i})})}function Sr(n,e){return d(this,null,function*(){const t=Le(n.path);if(F(e.signal),qi(t)){const c=yield e.adapter.stat(t);if(c.kind!=="file")throw new m(g.BadRequest,"目标是目录,不是文件。");return{data:{content:Xn("图片",t,c.size),truncated:!1}}}const{entry:i,bytes:s}=yield We(e.adapter,t);if(Hi(t,s))return{data:{content:Xn("PDF",t,i.size),truncated:!1}};if(fe(s))throw new m(g.BadRequest,"文件不是文本,无法读取正文。");const r=ze(s);if(n.start_line!==void 0||n.end_line!==void 0){const c=Er(r,n.start_line,n.end_line),l=Gn(c);return{data:{content:l.text,truncated:l.truncated}}}if(s.byteLength>jt&&br(t))return{data:{content:_r(t,r),truncated:!0}};const a=Gn(r);return{data:{content:a.text,truncated:a.truncated}}})}function Ir(n,e){return d(this,null,function*(){const t=Le(n.path);if(ln(n.content)>st)throw new m(g.TooLarge,`content 按 UTF-8 计超过 ${st} 字节。请缩短后写入,或改用 append_file、edit_file。`);return F(e.signal),yield un(e.adapter,t,n.content,e.signal),{data:{}}})}function xr(n,e){return d(this,null,function*(){const t=Le(n.path);F(e.signal);let i="";try{const{bytes:s}=yield We(e.adapter,t);if(fe(s))throw new m(g.BadRequest,"文件不是文本,无法追加。");i=ze(s)}catch(s){if(!zi(s))throw s}return yield un(e.adapter,t,i+n.content,e.signal),{data:{}}})}function Ar(n,e){return d(this,null,function*(){const t=Le(n.path);F(e.signal);const{bytes:i}=yield We(e.adapter,t);if(fe(i))throw new m(g.BadRequest,"文件不是文本,无法修改。");const s=ze(i),r=s.indexOf(n.old_text);if(r<0){const a=Tr(s,n.old_text);throw new m(g.BadRequest,`找不到与 old_text 完全相同的内容。最接近的原文从第 ${a.line} 行开始,可复制后重试:
359
- ${a.excerpt}`,{line:a.line,excerpt:a.excerpt})}const o=s.slice(0,r)+n.new_text+s.slice(r+n.old_text.length);return yield un(e.adapter,t,o,e.signal),{data:{}}})}function Tr(n,e){var c;const t=hn(n);if(t.length===0)return{line:1,excerpt:""};const i=e.split(`
360
- `),s=((c=i[0])!=null?c:"").slice(0,200);let r=0,o=-1;for(let l=0;l<t.length;l+=1){const h=Lr(t[l],s);h>o&&(o=h,r=l)}const a=Math.min(Math.max(i.length,1),8);return{line:r+1,excerpt:t.slice(r,r+a).join(`
361
- `)}}function Lr(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 Mr(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":qt(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:qt(i)}return new RegExp(e)}function qt(n){return/[\\^$.*+?()[\]{}|]/.test(n)?`\\${n}`:n}function Rr(n){try{return Mr(n)}catch(e){throw new m(g.BadRequest,"pattern 不是合法的 grep 基本正则。")}}function fn(n,e,t,i,s){return d(this,null,function*(){if(i>16)return;F(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((a,c)=>a.name<c.name?-1:a.name>c.name?1:0);for(const a of o){const c=e?`${e}/${a.name}`:a.name;yield fn(n,c,t,i+1,s)}})}function Cr(n,e){return d(this,null,function*(){const t=Le(n.path),i=Rr(n.pattern),s=[];yield fn(e.adapter,t,e.signal,0,(o,a)=>d(this,null,function*(){if(a!=="file"||s.length>=200)return;const{bytes:c}=yield We(e.adapter,o);if(fe(c)||qi(o)||Hi(o,c))return;let l;try{l=ze(c)}catch(u){return}const h=hn(l);for(let u=0;u<h.length&&s.length<200;u+=1){if(!i.test(h[u]))continue;const f=h[u].length>500?`${h[u].slice(0,500)}…`:h[u];s.push(`${rn(o)}:${u+1}:${f}`)}}));const r=s.join(`
356
+ `)}function Ar(n,e,t){if(e!==void 0&&t!==void 0&&t<e)throw new m(g.BadRequest,"end_line 不能小于 start_line。");const i=pn(n),s=Math.max((e!=null?e:1)-1,0),r=t!=null?t:i.length;return i.slice(s,r).join(`
357
+ `)}function Kn(n){if(un(n)<=Ht)return{text:n,truncated:!1};const e=new TextEncoder().encode(n);let t=Ht;for(;t>0&&(e[t]&192)===128;)t-=1;const i=new TextDecoder().decode(e.slice(0,t)),s=i.lastIndexOf(`
358
+ `);return{text:s>0?i.slice(0,s):i,truncated:!0}}function Ve(n,e){return d(this,null,function*(){const t=yield n.stat(e);if(t.kind!=="file")throw new m(g.BadRequest,"目标是目录,不是文件。");const i=yield Y(yield n.readFile(e));return{entry:t,bytes:i}})}function Jn(n,e,t){const i=typeof t=="number"?`${t} 字节,`:"";return`${n},${i}路径 ${cn(e)}。不返回正文。`}function dt(n){const e=Bn[ze(n)];if(!e){const t=Object.keys(Bn),i=`${t.slice(0,-1).join("、")} 或 ${t.at(-1)}`;throw new m(g.BadRequest,`只能执行 ${i} 文件。`)}return e}function Gi(n){if(!n.runner)throw new m(g.NotImplemented,"当前环境不能执行命令或脚本,需要端侧宿主。");return n.runner}function mn(n,e,t,i){return d(this,null,function*(){yield n.writeFile(e,t,{createDirectories:!0,signal:i})})}function xr(n,e){return d(this,null,function*(){const t=Me(n.path);if(N(e.signal),zi(t)){const c=yield e.adapter.stat(t);if(c.kind!=="file")throw new m(g.BadRequest,"目标是目录,不是文件。");return{data:{content:Jn("图片",t,c.size),truncated:!1}}}const{entry:i,bytes:s}=yield Ve(e.adapter,t);if(Wi(t,s))return{data:{content:Jn("PDF",t,i.size),truncated:!1}};if(fe(s))throw new m(g.BadRequest,"文件不是文本,无法读取正文。");const r=We(s);if(n.start_line!==void 0||n.end_line!==void 0){const c=Ar(r,n.start_line,n.end_line),l=Kn(c);return{data:{content:l.text,truncated:l.truncated}}}if(s.byteLength>Ht&&Sr(t))return{data:{content:Er(t,r),truncated:!0}};const a=Kn(r);return{data:{content:a.text,truncated:a.truncated}}})}function Tr(n,e){return d(this,null,function*(){const t=Me(n.path);if(un(n.content)>at)throw new m(g.TooLarge,`content 按 UTF-8 计超过 ${at} 字节。请缩短后写入,或改用 append_file、edit_file。`);return N(e.signal),yield mn(e.adapter,t,n.content,e.signal),{data:{}}})}function Lr(n,e){return d(this,null,function*(){const t=Me(n.path);N(e.signal);let i="";try{const{bytes:s}=yield Ve(e.adapter,t);if(fe(s))throw new m(g.BadRequest,"文件不是文本,无法追加。");i=We(s)}catch(s){if(!Vi(s))throw s}return yield mn(e.adapter,t,i+n.content,e.signal),{data:{}}})}function Rr(n,e){return d(this,null,function*(){const t=Me(n.path);N(e.signal);const{bytes:i}=yield Ve(e.adapter,t);if(fe(i))throw new m(g.BadRequest,"文件不是文本,无法修改。");const s=We(i),r=s.indexOf(n.old_text);if(r<0){const a=Mr(s,n.old_text);throw new m(g.BadRequest,`找不到与 old_text 完全相同的内容。最接近的原文从第 ${a.line} 行开始,可复制后重试:
359
+ ${a.excerpt}`,{line:a.line,excerpt:a.excerpt})}const o=s.slice(0,r)+n.new_text+s.slice(r+n.old_text.length);return yield mn(e.adapter,t,o,e.signal),{data:{}}})}function Mr(n,e){var c;const t=pn(n);if(t.length===0)return{line:1,excerpt:""};const i=e.split(`
360
+ `),s=((c=i[0])!=null?c:"").slice(0,200);let r=0,o=-1;for(let l=0;l<t.length;l+=1){const h=Cr(t[l],s);h>o&&(o=h,r=l)}const a=Math.min(Math.max(i.length,1),8);return{line:r+1,excerpt:t.slice(r,r+a).join(`
361
+ `)}}function Cr(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 Fr(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":Wt(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:Wt(i)}return new RegExp(e)}function Wt(n){return/[\\^$.*+?()[\]{}|]/.test(n)?`\\${n}`:n}function Or(n){try{return Fr(n)}catch(e){throw new m(g.BadRequest,"pattern 不是合法的 grep 基本正则。")}}function gn(n,e,t,i,s){return d(this,null,function*(){if(i>16)return;N(t);const r=yield n.stat(e);if(yield s(e,r.kind),r.kind!=="directory")return;const o=yield n.listEntries(e,t);o.sort((a,c)=>a.name<c.name?-1:a.name>c.name?1:0);for(const a of o){const c=e?`${e}/${a.name}`:a.name;yield gn(n,c,t,i+1,s)}})}function Nr(n,e){return d(this,null,function*(){const t=Me(n.path),i=Or(n.pattern),s=[];yield gn(e.adapter,t,e.signal,0,(o,a)=>d(this,null,function*(){if(a!=="file"||s.length>=200)return;const{bytes:c}=yield Ve(e.adapter,o);if(fe(c)||zi(o)||Wi(o,c))return;let l;try{l=We(c)}catch(u){return}const h=pn(l);for(let u=0;u<h.length&&s.length<200;u+=1){if(!i.test(h[u]))continue;const f=h[u].length>500?`${h[u].slice(0,500)}…`:h[u];s.push(`${cn(o)}:${u+1}:${f}`)}}));const r=s.join(`
362
362
  `);return{data:{matches:s.length>=200?`${r}
363
- (匹配过多,已截断)`:r}}})}function Fr(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+=qt(s)}return new RegExp(`${t}$`).test(e)}function Or(n,e){return d(this,null,function*(){const t=Le(n.path),i=[];yield fn(e.adapter,t,e.signal,0,r=>d(this,null,function*(){var a;if(i.length>=500)return;const o=(a=r.split("/").pop())!=null?a:r;Fr(n.name,o)&&i.push(rn(r))})),i.sort();const s=i.join(`
363
+ (匹配过多,已截断)`:r}}})}function $r(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+=Wt(s)}return new RegExp(`${t}$`).test(e)}function Pr(n,e){return d(this,null,function*(){const t=Me(n.path),i=[];yield gn(e.adapter,t,e.signal,0,r=>d(this,null,function*(){var a;if(i.length>=500)return;const o=(a=r.split("/").pop())!=null?a:r;$r(n.name,o)&&i.push(cn(r))})),i.sort();const s=i.join(`
364
364
  `);return{data:{files:i.length>=500?`${s}
365
- (结果过多,已截断)`:s}}})}function Nr(n,e,t){return d(this,null,function*(){const i=Wi(t);yield We(t.adapter,n);const s=yield i.exec({argv:[at(n),n,...e],cwd:tn,timeoutMs:t.timeoutMs,signal:t.signal});return{data:{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr}}})}function $r(n,e){return d(this,null,function*(){const t=$s(n.path);return at(t),Nr(t,[],e)})}function Pr(n,e){return d(this,null,function*(){if(Pn(n.command)||Pn(e.shellCwd.cwd))throw new m(g.Forbidden,"技能文件只能通过技能工具访问。");if(rt(n.command)||rt(e.shellCwd.cwd))return{data:{exitCode:1,stdout:"",stderr:`${nn}
366
- `}};const i=yield Wi(e).exec({command:n.command,cwd:e.shellCwd.cwd,timeoutMs:e.timeoutMs,signal:e.signal});return i.cwd&&Ps(i.cwd)&&(e.shellCwd.cwd=i.cwd),{data:{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}})}function Re(n){if(!n.skills)throw new m(g.NotImplemented,"当前环境不能加载平台技能,需要端侧宿主。");return n.skills}const Dr="技能包文件(相对技能根目录)。用 read_skill_resource 按路径读取;resource_name 传目录则列出其中文件;以 grep: 开头则按基本正则搜索整个技能包,例如 grep:portrait。";function pn(n){return pt(n,"SKILL.md"),""}function mn(n,e){return pt(n,e).slice(`skills/${n}/`.length)}function Br(n){return!!n&&typeof n=="object"&&"name"in n&&n.name==="TypeMismatchError"}function gn(n){const e=n&&typeof n=="object"&&"name"in n?String(n.name):"",t=n instanceof Error?n.message:"";throw e==="TypeError"?new m(g.BadRequest,t||"搜索表达式不合法。"):e==="NotFoundError"?new m(g.NotFound,"技能或资源不存在。"):n}function Vi(n,e,t){return d(this,null,function*(){pt(n,e);const i=yield Re(t).read(n,e,t.signal);if(fe(i))throw new m(g.BadRequest,"技能资源不是文本。");return ze(i)})}function Ht(n,e,t){return d(this,null,function*(){try{return yield Re(t).list(n,e,t.signal)}catch(i){gn(i)}})}function jr(n){if(!n.skillRunner)throw new m(g.NotImplemented,"当前环境不能加载平台技能,需要端侧宿主。");return n.skillRunner}function Ur(n,e){return d(this,null,function*(){const t=yield Vi(n.skill_name,"SKILL.md",e);let i="";try{i=yield Re(e).list(n.skill_name,"",e.signal)}catch(s){i=""}return i?{data:{content:`${t}
365
+ (结果过多,已截断)`:s}}})}function Dr(n,e,t){return d(this,null,function*(){const i=Gi(t);yield Ve(t.adapter,n);const s=yield i.exec({argv:[dt(n),n,...e],cwd:rn,timeoutMs:t.timeoutMs,signal:t.signal});return{data:{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr}}})}function Br(n,e){return d(this,null,function*(){const t=Bs(n.path);return dt(t),Dr(t,[],e)})}function jr(n,e){return d(this,null,function*(){if(jn(n.command)||jn(e.shellCwd.cwd))throw new m(g.Forbidden,"技能文件只能通过技能工具访问。");if(ct(n.command)||ct(e.shellCwd.cwd))return{data:{exitCode:1,stdout:"",stderr:`${on}
366
+ `}};const i=yield Gi(e).exec({command:n.command,cwd:e.shellCwd.cwd,timeoutMs:e.timeoutMs,signal:e.signal});return i.cwd&&js(i.cwd)&&(e.shellCwd.cwd=i.cwd),{data:{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}})}function Fe(n){if(!n.skills)throw new m(g.NotImplemented,"当前环境不能加载平台技能,需要端侧宿主。");return n.skills}const Ur="技能包文件(相对技能根目录)。用 read_skill_resource 按路径读取;resource_name 传目录则列出其中文件;以 grep: 开头则按基本正则搜索整个技能包,例如 grep:portrait。";function yn(n){return yt(n,"SKILL.md"),""}function wn(n,e){return yt(n,e).slice(`skills/${n}/`.length)}function qr(n){return!!n&&typeof n=="object"&&"name"in n&&n.name==="TypeMismatchError"}function vn(n){const e=n&&typeof n=="object"&&"name"in n?String(n.name):"",t=n instanceof Error?n.message:"";throw e==="TypeError"?new m(g.BadRequest,t||"搜索表达式不合法。"):e==="NotFoundError"?new m(g.NotFound,"技能或资源不存在。"):n}function Xi(n,e,t){return d(this,null,function*(){yt(n,e);const i=yield Fe(t).read(n,e,t.signal);if(fe(i))throw new m(g.BadRequest,"技能资源不是文本。");return We(i)})}function Vt(n,e,t){return d(this,null,function*(){try{return yield Fe(t).list(n,e,t.signal)}catch(i){vn(i)}})}function Hr(n){if(!n.skillRunner)throw new m(g.NotImplemented,"当前环境不能加载平台技能,需要端侧宿主。");return n.skillRunner}function zr(n,e){return d(this,null,function*(){const t=yield Xi(n.skill_name,"SKILL.md",e);let i="";try{i=yield Fe(e).list(n.skill_name,"",e.signal)}catch(s){i=""}return i?{data:{content:`${t}
367
367
 
368
- ${Dr}
369
- ${i}`}}:{data:{content:t}}})}function qr(n,e){return d(this,null,function*(){const t=n.path?mn(n.skill_name,n.path):pn(n.skill_name);return{data:{files:yield Ht(n.skill_name,t,e)}}})}function Hr(n,e){return d(this,null,function*(){const t=n.path?mn(n.skill_name,n.path):pn(n.skill_name);let i="";try{i=yield Re(e).grep(n.skill_name,n.pattern,t,e.signal)}catch(s){gn(s)}return{data:{matches:i}}})}function zr(n,e){return d(this,null,function*(){if(n.resource_name.startsWith("grep:")){const i=n.resource_name.slice(5);if(!i)throw new m(g.BadRequest,"grep: 后面要写搜索表达式。");pn(n.skill_name);let s="";try{s=yield Re(e).grep(n.skill_name,i,"",e.signal)}catch(r){gn(r)}return{data:{content:s||"没有匹配。"}}}if(n.resource_name==="."||n.resource_name==="./")return{data:{content:(yield Ht(n.skill_name,"",e))||"(空目录)"}};const t=mn(n.skill_name,n.resource_name.replace(/\/+$/,""));try{return{data:{content:yield Vi(n.skill_name,t,e)}}}catch(i){if(!Br(i))throw i;return{data:{content:(yield Ht(n.skill_name,t,e))||"(空目录)"}}}})}function Wr(n,e){return d(this,null,function*(){var o;const t=Re(e);pt(n.skill_name,n.script_name),at(n.script_name);const i=jr(e),s=yield t.target(n.skill_name,e.signal),r=t.track(s.skillId,s.version);try{const a=yield i.exec({argv:[at(n.script_name),n.script_name,...(o=n.args)!=null?o:[]],cwd:tn,timeoutMs:e.timeoutMs,signal:e.signal,skill:s});return{data:{exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}}catch(a){throw zi(a)?new m(g.NotFound,"技能脚本不存在。"):a}finally{r()}})}const Vr={shell:Pr,read_file:Sr,write_file:Ir,append_file:xr,run_file:$r,edit_file:Ar,grep:Cr,find:Or,load_skill:Ur,read_skill_resource:zr,list_skill_files:qr,grep_skill:Hr,run_skill_script:Wr},$e=new q("[BuiltinTools] "),It=new Set(["shell","run_file","run_skill_script"]);function Gr(n,e,t){var i,s;if(n.commandRunner)return Pt(n.commandRunner);if(e instanceof qe){if(e.protocolMismatch){const r=`${(i=e.sandboxVersion)!=null?i:""}@${(s=e.sandboxProtocol)!=null?s:""}`;t.rejectedSandbox!==r&&(t.rejectedSandbox=r,$e.error("sandbox-protocol",{sandboxVersion:e.sandboxVersion,sandboxProtocol:e.sandboxProtocol,supported:Ee}))}if(!e.canExec){const r=e.unavailableMessage();return{exec:()=>Promise.reject(k("NotAllowedError",r))}}return{exec:r=>e.exec(r)}}if(n.browserRuntime.enabled)return(t.adapter!==e||!t.runner)&&(t.adapter=e,t.runner=Pt(new wr({adapter:e,sensitive:n.sensitive,moduleURL:n.browserRuntime.bashModuleURL,pyodideIndexURL:n.browserRuntime.pyodideIndexURL}))),t.runner}function Xr(n,e){if(n.commandRunner)return Pt(n.commandRunner);if(e instanceof qe){if(!e.canExec){const t=e.unavailableMessage();return{exec:()=>Promise.reject(k("NotAllowedError",t))}}return{exec:t=>e.exec(t)}}}function Yr(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch(e){throw new m(g.BadRequest,"参数不是合法的 JSON 对象。")}}function Kr(n){const e=n instanceof DOMException?n.name:"",t=n instanceof Error?n.message:"";if(e==="NotFoundError")return new m(g.NotFound,"脚本或目录不存在。");if(e==="SecurityError")return new m(g.Forbidden,"命令路径不在工作区内。");if(e==="AbortError")return t.includes("超时")?new m(g.Timeout,"命令运行超时,已中止。"):t.includes("已有")||t.includes("上限")?new m(g.TooManyRequests,t):B();if(e==="NotAllowedError"){const i=t.trim();return i&&i!=="NotAllowedError"?new m(g.NotImplemented,i):new m(g.NotImplemented,"当前环境不能执行命令或脚本,需要端侧宿主。")}}function Jr(n){return new Promise((e,t)=>{n.aborted&&t(B()),n.addEventListener("abort",()=>t(B()),{once:!0})})}function Gi(n,e=160){return n.length>e?`${n.slice(0,e)}…`:n}function Qr(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=Gi(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 Zr(n){return b({code:n.code,message:n.message},n.data?{data:n.data}:{})}function eo({pluginCode:n,workspace:e}){const t=new Map,i={},s={};return Bt.forEach(r=>{s[r]=(o,a,c)=>{let l=!1;to(e,t,i,r,o,u=>{if(!l){l=!0;try{a(u)}catch(f){console.error("[BuiltinTools] callback failed",f)}}},E(b({},c),{pluginCode:n}))}}),{[n]:s}}function to(n,e,t,i,s,r,o){return d(this,null,function*(){var I,S,L,j,$;const a={requestId:o.requestId||ne.v4(),applicationId:o.applicationId||n.applicationId,sessionId:o.sessionId||"",pluginCode:o.pluginCode,functionCode:i,signal:o.signal},c={requestId:a.requestId,sessionId:a.sessionId,functionCode:i},l=new AbortController;let h=!1;const u=It.has(i)?n.limits.commandTimeoutMs:n.limits.toolTimeoutMs,f=setTimeout(()=>{h=!0,l.abort()},u),p=()=>l.abort();(I=a.signal)==null||I.addEventListener("abort",p,{once:!0}),(S=a.signal)!=null&&S.aborted&&l.abort();let y=null,w=null,_;const A=Date.now();try{const M=Yr(s),T=Ni(M,dn[i].parameters);if(typeof T.path=="string"&&(c.path=T.path),$e.log("start",b(b({},c),Qr(T))),yield n.ready,l.signal.aborted)throw B();const R=n.adapter;if(!R)throw ut();if(It.has(i)){if(w=n.acquireCommand(),!w)throw new m(g.TooManyRequests,"已有一个命令在运行,请等它结束后再试。")}else if(y=n.acquireSlot(),!y)throw new m(g.TooManyRequests,"同时进行的文件操作过多,请稍后重试。");_=n.track(l),n.emit("tool:start",b({},c));const H=a.sessionId||"default";let U=e.get(H);U||(U={cwd:tn},e.set(H,U));const pe=Gr(n,R,t),Ce=U.cwd,Fe={adapter:R,runner:pe,signal:l.signal,timeoutMs:u,shellCwd:U,skills:n.platformSkills,skillRunner:Xr(n,R)},me=yield Promise.race([Vr[i](T,Fe),Jr(l.signal)]),En={code:g.Ok,message:"ok",data:me.data};me.truncated&&(En.truncated=!0);const ms=Date.now()-A,Sn=me.data.exitCode;$e.log("finish",b(b(b(E(b({},c),{elapsedMs:ms,code:g.Ok}),me.truncated?{truncated:!0}:{}),typeof Sn=="number"?{exitCode:Sn}:{}),i==="shell"?{cwd:U.cwd,cwdChanged:U.cwd!==Ce}:{})),n.emit("tool:finish",E(b({},c),{code:g.Ok})),It.has(i)&&n.notifyFilesChanged(),r(En)}catch(M){let T=(L=Kr(M))!=null?L:Ae(M);h?T=new m(g.Timeout,"操作超时,已中止。"):l.signal.aborted&&T.code!==g.Cancelled&&(T=B());const R=Date.now()-A;T.code===g.Cancelled?($e.log("cancelled",E(b({},c),{elapsedMs:R,timedOut:h})),n.emit("tool:cancelled",b({},c))):($e.error("error",E(b({},c),{elapsedMs:R,code:T.code,message:Gi(T.message,300)})),n.emit("tool:error",E(b({},c),{code:T.code,message:T.message,reason:(j=T.data)==null?void 0:j.reason}))),r(Zr(T))}finally{clearTimeout(f),($=a.signal)==null||$.removeEventListener("abort",p),y==null||y(),w==null||w(),_==null||_()}})}const Yn="MCP",mt=new Map;let V=null;function no(n,e,t){mt.set(n,e),V=E(b({},V!=null?V:{}),{[n]:t})}function Kn(n){mt.clear(),V=null;for(const e of n)no(e.name,e.binding,e.handler);V&&!Object.keys(V).length&&(V=null)}function io(n){return mt.get(n)}function so(){return[...mt.values()]}function ro(n){var e;!V||!Object.keys(V).length||(n[Yn]=b(b({},(e=n[Yn])!=null?e:{}),V))}const oo=new q("[Config] ");var Xi=(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))(Xi||{});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 Ie,Q;const zt=new Set;function Jn(n){Ie!==n&&(Ie=n,Q=void 0,zt.clear())}function ao(){if(!Q)return;const{pluginCode:n,table:e}=Q,t=exports.configuration.plugins[n],i=e[n];if(!(!t||t.shell!==i.shell))return n}function Yi(n,e){return(n==null?void 0:n.pluginCode)||gi[e]}function co(){var o,a;const n=(o=exports.configuration.businessPlugins)!=null?o:{},e=(a=exports.configuration.builtinPlugins)==null?void 0:a.localFiles,t=[],i=b({},n);if(!!!(e!=null&&e.enabled))return xt(i),t;if(!Ie)return t.push("[BuiltinTools] 内置工具依赖已启用的本地工作区。工具未注册。"),xt(i),t;const r=e!=null&&e.enabled?Yi(e,exports.configuration.env):void 0;return r?n[r]?t.push(`[BuiltinTools] 业务插件中已存在 pluginCode「${r}」,已保留业务插件,内置工具未注册。`):(((Q==null?void 0:Q.workspace)!==Ie||Q.pluginCode!==r)&&(Q={workspace:Ie,pluginCode:r,table:eo({pluginCode:r,workspace:Ie})}),i[r]=Q.table[r]):t.push(`[BuiltinTools] 当前环境(env: ${exports.configuration.env})没有默认的内置工具插件编码,请配置 builtinPlugins.localFiles.pluginCode。内置工具未注册。`),xt(i),t}function xt(n){ro(n),exports.configuration.plugins=n}function je(){return co().filter(n=>!zt.has(n)).map(n=>(zt.add(n),console.error(n),new Error(n)))}function Wt(n,e={}){var t,i,s;q.debug=(n==null?void 0:n.debug)||!1,exports.configuration=E(b(b({},exports.configuration),n),{apiRoot:(n==null?void 0:n.apiRoot)||exports.configuration.apiRoot||(n!=null&&n.env?Xi[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&&je(),q.debug&&oo.log("updated",exports.configuration)}const ct=n=>JSON.parse(vs.decode(n.split(".")[1])),Ki=n=>{const e=ct(n).exp;return new Date().valueOf()/1e3>=e},lo=n=>n==null?void 0:n.replace(/[\r\n]+/gm,""),ho=n=>n.replace(/\\|\\/g,""),uo=(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,a=[];return s&&a.push(`问题:${i}`),o&&a.push(`回答:${t}`),a.join(`
370
- `)};function Ji(n,e,t){return new x.CVForceApi(Qi(n,"/data/v1",e,t),Zi(t))}function fo(n,e,t){return new x.AIShopApi(Qi(n,"/aishop",e,t),Zi(t))}function Qi(n,e,t,i){const s=o=>{var a;return t&&(Ki(t)&&i(403,"aiotToken is timeout"),o.headers=(a=o.headers)!=null?a:{},o.headers=E(b({},o.headers),{Authorization:t?`Bearer ${t}`:""})),o};function r(o,a=!0){const c=`${n}${o}`,l=bs.create({baseURL:c});return a&&l.interceptors.request.use(s),l}return r(e)}function Zi(n){return{onHttpStatusError:(i,s)=>{i===401&&n(i,"aiotToken is invalid")},onAppStatusError:(i,s)=>{i!==10001&&i!==10215&&n(i,s)}}}const po=20*1024*1024,es=/^[A-Za-z0-9._-]+$/;function At(n){const e=n==null?void 0:n.skills;return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"):[]}function mo(n){if(!n)return!1;try{return!Ki(n)}catch(e){return!1}}function Qn(n){if(!(typeof n.skillId!="string"||!es.test(n.skillId))&&!(typeof n.name!="string"||!n.name||/[\\/\0]/.test(n.name)||n.name==="."||n.name==="..")&&!(typeof n.version!="number"||!Number.isInteger(n.version)||n.version<1))return{skillId:n.skillId,name:n.name,version:n.version}}function go(n){return Array.isArray(n)?n.flatMap(e=>{if(!e||typeof e!="object")return[];const t=e;return typeof t.skillId!="string"||typeof t.name!="string"||typeof t.version!="number"?[]:[{skillId:t.skillId,name:t.name,version:t.version}]}):[]}class yo{constructor(e){v(this,"inflight",new Map);v(this,"busy",new Set);this.options=e}sync(){return this.reconcile().catch(()=>{})}read(e,t,i){return d(this,null,function*(){const s=yield this.prepare(e,i);return this.requireSandbox().skillRead(this.options.applicationId(),s.skillId,s.version,t,i)})}list(e,t,i){return d(this,null,function*(){const s=yield this.prepare(e,i);return this.requireSandbox().skillList(this.options.applicationId(),s.skillId,s.version,t,i)})}grep(e,t,i,s){return d(this,null,function*(){const r=yield this.prepare(e,s);return this.requireSandbox().skillGrep(this.options.applicationId(),r.skillId,r.version,i,t,s)})}target(e,t){return d(this,null,function*(){const i=yield this.prepare(e,t);return{applicationId:this.options.applicationId(),skillId:i.skillId,version:i.version,name:i.name}})}track(e,t){const i=`${e}/${t}`;this.busy.add(i);let s=!1;return()=>{s||(s=!0,this.busy.delete(i),this.prune().catch(()=>{}))}}requireSandbox(){const e=this.options.getSandbox();if(!e)throw new m(g.NotImplemented,"当前环境不能加载平台技能,需要端侧宿主。");return e}prepare(e,t){return d(this,null,function*(){const i=this.bound(e);if(!i)throw new m(g.NotFound,"技能或资源不存在。");return yield this.ensure(i,t),i})}bound(e){if(!es.test(this.options.applicationId()))return;const t=At({skills:this.options.getSkills()}).find(i=>i.name===e);return t?Qn(t):void 0}reconcile(){return d(this,null,function*(){if(!this.options.getSandbox())return;const t=At({skills:this.options.getSkills()}).flatMap(i=>{const s=Qn(i);return s?[s]:[]});yield Promise.all(t.map(i=>this.ensure(i).catch(()=>{}))),yield this.prune()})}ensure(e,t){return d(this,null,function*(){const i=`${this.options.applicationId()}/${e.skillId}/${e.version}`,s=this.inflight.get(i);if(s)return s;const r=this.installIfNeeded(e,t).finally(()=>{this.inflight.get(i)===r&&this.inflight.delete(i)});return this.inflight.set(i,r),r})}installIfNeeded(e,t){return d(this,null,function*(){var c;const i=this.requireSandbox();if(i.ready&&(yield this.alreadyInstalled(i,e,t)))return;const s=this.options.getToken();if(!mo(s))throw new m(g.Forbidden,"技能下载令牌不可用。");const r=this.options.apiRoot().replace(/\/$/,""),o=yield((c=this.options.fetch)!=null?c:fetch)(`${r}/skill/v1/skills/${encodeURIComponent(e.skillId)}/versions/${e.version}/download`,{headers:{Authorization:`Bearer ${s}`},signal:t});if(!o.ok)throw new m(g.BadRequest,`技能下载失败(${o.status})。`);const a=new Uint8Array(yield o.arrayBuffer());if(a.byteLength>po)throw new m(g.BadRequest,"技能压缩包超过 20 MB。");yield this.waitReady(i,t),!(yield this.alreadyInstalled(i,e,t))&&(yield i.installSkill({applicationId:this.options.applicationId(),skillId:e.skillId,version:e.version,name:e.name},a,t))})}alreadyInstalled(e,t,i){return d(this,null,function*(){return go(yield e.skillStatus(this.options.applicationId(),i)).some(r=>r.skillId===t.skillId&&r.version===t.version&&r.name===t.name)})}prune(){return d(this,null,function*(){const e=this.options.getSandbox();if(!(e!=null&&e.ready))return;const t=At({skills:this.options.getSkills()}).flatMap(s=>typeof s.skillId!="string"||typeof s.version!="number"||s.version<1?[]:[{skillId:s.skillId,version:s.version}]),i=[...this.busy].map(s=>{const[r,o]=s.split("/");return{skillId:r,version:Number(o)}});yield e.skillPrune(this.options.applicationId(),t,i)})}waitReady(e,t){return d(this,null,function*(){e.ready||(yield new Promise((i,s)=>{const r=setInterval(()=>{if(t!=null&&t.aborted){clearInterval(r),s(new m(g.Cancelled,"已取消。"));return}e.ready&&(clearInterval(r),i())},50)}))})}}function wo(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 oe;function vo(n){oe==null||oe(),oe=void 0;const e=Fi();if(!e)return()=>{};const t=new qe(e),i=r=>{const o=Ci(r.data);if(o){if(o.type==="workspace"){const a=o.granted===!0,c=typeof o.displayName=="string"?o.displayName:"";t.setCapabilities(o.capabilities,{version:o.sandboxVersion}),t.applySandbox(wo(o.sandbox)),a?(t.displayName=c||"工程目录",(n.status!=="granted"||n.displayName!==t.displayName)&&n.attachAdapter(t,t.displayName)):n.status==="granted"&&n.clear();return}if(o.type==="fs-changed"){const a=Array.isArray(o.paths)?o.paths.filter(c=>typeof c=="string"):[];n.notifyFilesChanged(a);return}}};e.addEventListener("message",i),e.postMessage({channel:en,type:"hello"});const s=()=>{e.removeEventListener("message",i),oe===s&&(oe=void 0)};return oe=s,s}const Vt=new Set;let tt,ts=[],ae,Ye;function Tt(){return{revision:tt,servers:ts}}function bo(n){return Vt.add(n),()=>Vt.delete(n)}function _o(n){let e;try{e=new URL(n)}catch(s){return}if(e.protocol!=="http:"||e.username||e.password||!e.port)return;const t=Number(e.port);if(!Number.isInteger(t)||t<1||t>65535)return;const i=e.hostname.toLowerCase();if(!(i!=="127.0.0.1"&&i!=="localhost"&&i!=="::1"&&i!=="[::1]"))return e.href}function Lt(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function ko(n){var t;if(!Array.isArray(n))return[];const e=[];for(const i of n){if(!i||typeof i!="object")continue;const s=i,r=Lt(s.code),o=(t=Lt(s.id))!=null?t:r,a=typeof s.url=="string"?_o(s.url):void 0;if(!o||!a)continue;const c=Lt(s.token);e.push(b(b({id:o,url:a},r?{code:r}:{}),c?{token:c}:{}))}return e}function Eo(n){const e=n.revision;return typeof e!="number"||!Number.isFinite(e)||tt!==void 0&&e<=tt||!Array.isArray(n.servers)?!1:(tt=e,ts=ko(n.servers),Vt.forEach(t=>t()),!0)}function ns(){const n=Fi();if(!n)return()=>{};if(Ye===n&&ae)return ae;ae==null||ae();const e=i=>{const s=Ci(i.data);!s||s.type!=="local-mcps"||Eo(s)};n.addEventListener("message",e),Ye=n;const t=()=>{n.removeEventListener("message",e),Ye===n&&(Ye=void 0,ae=void 0)};return ae=t,t}const ce=new q("[EventBus] ");class yn{constructor(e=!1){v(this,"eventListenerMap",{});e&&ce.disable()}getEventListenerMap(){return b({},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),ce.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?ce.log(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(i,1),ce.log(`remove event ${e} listener`))}else ce.log(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){ce.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))}),ce.log(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`)}removeAllListeners(){this.eventListenerMap={}}}const So="路径必须是工作区内的相对路径,不能包含 ..、绝对路径或盘符。";function Ke(){return new m(g.Forbidden,So,{reason:"path_outside_workspace"})}function Io(n){if(n!==xe)throw new m(g.Forbidden,`未知的工作区 grantId,当前仅支持 ${xe}。`,{reason:"path_outside_workspace"})}function ee(n,{allowRoot:e=!1,field:t="path"}={}){if(n==null){if(e)return"";throw new m(g.BadRequest,`缺少参数 ${t}。`)}if(typeof n!="string")throw new m(g.BadRequest,`参数 ${t} 必须是字符串。`);if(n.includes("\0")||/%(2e|2f|5c|00)/i.test(n))throw Ke();const i=n.normalize("NFC").replace(/\\/g,"/").trim();if(i.startsWith("/")||/^[a-zA-Z]:/.test(i))throw Ke();const s=[];for(const o of i.split("/"))if(!(o===""||o===".")){if(o==="..")throw Ke();s.push(o)}const r=s.join("/");if(!r&&!e)throw new m(g.BadRequest,`参数 ${t} 不能指向工作区根目录。`);return r}function O(n){return n?n.split("/"):[]}function le(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}function is(n,e){return n?`${n}/${e}`:e}function Pe(n,e){return!!n&&typeof n=="object"&&n.name===e}class Gt{constructor(e){this.root=e}get displayName(){return this.root.name}resolveDirectory(e,t=!1){return d(this,null,function*(){let i=this.root;for(const s of e)i=yield i.getDirectoryHandle(s,{create:t});return i})}resolveFile(e){return d(this,null,function*(){const t=O(e),i=t.pop();if(!i)throw k("TypeMismatchError");return(yield this.resolveDirectory(t)).getFileHandle(i)})}stat(e){return d(this,null,function*(){const t=O(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 d(this,null,function*(){const i=yield this.resolveDirectory(O(e)),s=[];try{for(var r=G(i.values()),o,a,c;o=!(a=yield r.next()).done;o=!1){const l=a.value;F(t),s.push({name:l.name,kind:l.kind==="directory"?"directory":"file"})}}catch(a){c=[a]}finally{try{o&&(a=r.return)&&(yield a.call(r))}finally{if(c)throw c[0]}}return s})}readFile(e){return d(this,null,function*(){return(yield this.resolveFile(e)).getFile()})}writeFile(s,r){return d(this,arguments,function*(e,t,i={}){const o=O(e),a=o.pop();if(!a)throw k("TypeMismatchError");const c=yield this.resolveDirectory(o,i.createDirectories);let l=!0;try{yield c.getFileHandle(a)}catch(_){if(!Pe(_,"NotFoundError"))throw _;l=!1}const h=yield c.getFileHandle(a,{create:!0});let u;try{u=yield h.createWritable();try{for(var f=G(ft(t)),p,y,w;p=!(y=yield f.next()).done;p=!1){const _=y.value;F(i.signal),yield u.write(_)}}catch(y){w=[y]}finally{try{p&&(y=f.return)&&(yield y.call(f))}finally{if(w)throw w[0]}}F(i.signal),yield u.close()}catch(_){throw yield u==null?void 0:u.abort().catch(()=>{}),l||(yield c.removeEntry(a).catch(()=>{})),_}})}createDirectory(e){return d(this,null,function*(){yield this.resolveDirectory(O(e),!0)})}remove(i){return d(this,arguments,function*(e,t={}){const s=O(e),r=s.pop();if(!r)throw k("InvalidModificationError");yield(yield this.resolveDirectory(s)).removeEntry(r,{recursive:t.recursive===!0})})}move(e,t){return d(this,null,function*(){const i=O(e),s=O(t),r=i.pop(),o=s.pop();if(!r||!o)throw k("InvalidModificationError");const a=yield this.resolveDirectory(i),c=yield Zn(a,r),l=yield this.resolveDirectory(s);if(Mi(e,t))throw k("InvalidModificationError");let h;try{h=yield Zn(l,o)}catch(u){if(!Pe(u,"NotFoundError"))throw u}if(h&&(h.kind==="directory"||c.kind==="directory"))throw k("InvalidModificationError");if(!h&&typeof c.move=="function")try{yield c.move(l,o);return}catch(u){if(!Pe(u,"NotSupportedError")&&!(u instanceof TypeError))throw u}yield ss(c,l,o),yield a.removeEntry(r,{recursive:!0})})}}function Zn(n,e){return d(this,null,function*(){try{return yield n.getFileHandle(e)}catch(t){if(!Pe(t,"TypeMismatchError"))throw t;return n.getDirectoryHandle(e)}})}function ss(n,e,t){return d(this,null,function*(){if(n.kind==="file"){const c=yield n.getFile(),l=yield(yield e.getFileHandle(t,{create:!0})).createWritable();try{yield l.write(c),yield l.close()}catch(h){throw yield l.abort().catch(()=>{}),h}return}const i=yield e.getDirectoryHandle(t,{create:!0});try{for(var s=G(n.values()),r,o,a;r=!(o=yield s.next()).done;r=!1){const c=o.value;yield ss(c,i,c.name)}}catch(o){a=[o]}finally{try{r&&(o=s.return)&&(yield o.call(s))}finally{if(a)throw a[0]}}})}function ei(){return{kind:"directory",children:new Map}}class xo{constructor(e,t){v(this,"root",ei());var i;this.displayName=t;for(const s of e){const r=Ao(s,t);r&&this.writeNode(r,s.blob,(i=s.lastModified)!=null?i:Date.now())}}writeNode(e,t,i){const s=e.split("/").filter(Boolean),r=s.pop();if(!r)return;this.resolveDirectory(s,!0).children.set(r,{kind:"file",blob:t,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 k("NotFoundError");r=ei(),i.children.set(s,r)}if(r.kind!=="directory")throw k("TypeMismatchError");i=r}return i}resolveNode(e){const t=O(e),i=t.pop();if(i===void 0)return this.root;const s=this.resolveDirectory(t).children.get(i);if(!s)throw k("NotFoundError");return s}stat(e){return d(this,null,function*(){var s;const t=this.resolveNode(e),i=(s=O(e).pop())!=null?s:this.displayName;return t.kind==="directory"?{name:i,kind:"directory"}:{name:i,kind:"file",size:t.blob.size,lastModified:t.lastModified}})}listEntries(e,t){return d(this,null,function*(){F(t);const i=this.resolveDirectory(O(e));return Array.from(i.children.entries()).map(([s,r])=>r.kind==="directory"?{name:s,kind:"directory"}:{name:s,kind:"file",size:r.blob.size,lastModified:r.lastModified})})}readFile(e){return d(this,null,function*(){const t=this.resolveNode(e);if(t.kind!=="file")throw k("TypeMismatchError");return t.blob})}writeFile(s,r){return d(this,arguments,function*(e,t,i={}){const o=O(e),a=o.pop();if(!a)throw k("TypeMismatchError");const c=this.resolveDirectory(o,i.createDirectories),l=c.children.get(a);if((l==null?void 0:l.kind)==="directory")throw k("TypeMismatchError");const h=[];try{for(var f=G(ft(t)),p,y,w;p=!(y=yield f.next()).done;p=!1){const _=y.value;F(i.signal),h.push(_)}}catch(y){w=[y]}finally{try{p&&(y=f.return)&&(yield y.call(f))}finally{if(w)throw w[0]}}const u=new Blob(h);c.children.set(a,{kind:"file",blob:u,lastModified:Date.now()})})}}function Ao(n,e){const t=(n.webkitRelativePath||n.name).replace(/\\/g,"/").replace(/^\/+/,"");if(!t)return"";const i=`${e}/`;return t.startsWith(i)?t.slice(i.length):t}function To(){if(typeof window=="undefined")return;const n=window.showDirectoryPicker;return typeof n=="function"?n.bind(window):void 0}const Lo=/^[a-z0-9-]+(\.[a-z0-9-]+)+$/;function Mo(n){if(typeof n!="string")return null;const e=n.trim().toLowerCase().replace(/^\*?\./,"").replace(/\.$/,"");return!Lo.test(e)||rs(e)?null:e}function rs(n){return n.startsWith("[")||n.includes(":")?!0:/^[0-9.]+$/.test(n)||/^0x[0-9a-f.]+$/i.test(n)}function wn(n=[]){const e=new Set(Ii);for(const t of n){const i=Mo(t);i&&e.add(i)}return Array.from(e)}function Ro(n,e){return Xt(n,wn(e))}function Xt(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||rs(i)||i==="localhost"||i.endsWith(".localhost")?!1:e.some(s=>i===s||i.endsWith(`.${s}`))}function Co(n={}){const e=b({},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 _e(){return new m(g.Internal,"平台文件服务请求失败,请稍后重试。")}function vn(n,e=()=>{}){const t=()=>{const r=n();if(!r)throw _e();return r},i=()=>{const r=e();if(!r)throw _e();return r};return{upload(r,o,a){return d(this,null,function*(){if(!o.sessionId)throw new m(g.BadRequest,"当前没有可用的会话,无法上传文件。");try{a==null||a({loaded:0,total:r.size});const c=yield i().postFile(r,(l,h)=>a==null?void 0:a({loaded:l,total:h}));if(!(c!=null&&c.id)||!c.url)throw _e();return a==null||a({loaded:r.size,total:r.size}),{fileId:c.id,url:c.url}}catch(c){throw c instanceof m?c:_e()}})},resolveDownload(r,o){return d(this,null,function*(){if(r.type==="platformFile")return Fo(i(),r.fileId);if(!o.sessionId)throw new m(g.BadRequest,"当前没有可用的会话,无法下载会话文件。");let a;try{a=yield t().getApplicationIdSessionFile(o.applicationId,o.sessionId,r.fileId)}catch(c){throw _e()}if(!(a!=null&&a.url))throw new m(g.NotFound,"会话文件不存在或暂不可下载。");return{url:a.url,name:a.name,size:a.size}})}}}function Fo(n,e){return d(this,null,function*(){let t;try{t=yield n.getFile(e)}catch(s){throw _e()}if(!(t!=null&&t.url))throw new m(g.NotFound,"平台文件不存在或暂不可下载。");let i;try{i=new URL(t.url)}catch(s){throw new m(g.Internal,"平台返回的下载地址无效。")}if(i.protocol!=="https:")throw new m(g.Internal,"平台返回的下载地址无效。");return{url:t.url,size:t.bytes}})}const Oo="glodon-aiot-local-workspace",Mt="kv";function bn(){const n=new Map;return{get(t){return d(this,null,function*(){return n.get(t)})},set(t,i){return d(this,null,function*(){n.set(t,i)})},delete(t){return d(this,null,function*(){n.delete(t)})}}}function No(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}function os(n=Oo){if(typeof indexedDB=="undefined")return bn();let e;const t=()=>(e||(e=new Promise((r,o)=>{const a=indexedDB.open(n,1);a.onupgradeneeded=()=>{a.result.createObjectStore(Mt)},a.onsuccess=()=>r(a.result),a.onerror=()=>{e=void 0,o(a.error)}})),e),i=(r,o)=>d(this,null,function*(){const a=yield t();return No(o(a.transaction(Mt,r).objectStore(Mt)))});return{get(r){return d(this,null,function*(){return yield i("readonly",o=>o.get(r))})},set(r,o){return d(this,null,function*(){yield i("readwrite",a=>a.put(o,r))})},delete(r){return d(this,null,function*(){yield i("readwrite",o=>o.delete(r))})}}}function ti(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 $o(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 a=ti(o.relativePathComponents),c=ti(o.relativePathMovedFrom);if(a===void 0&&c===void 0){e();return}a!==void 0&&r.add(a),c!==void 0&&r.add(c)}r.size&&e([...r])})}catch(s){return()=>{}}return i.observe(n,{recursive:!0}).catch(()=>i.disconnect()),()=>i.disconnect()}const Po={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",bmp:"image/bmp",avif:"image/avif",ico:"image/x-icon",svg:"image/svg+xml",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",m4v:"video/mp4",ogv:"video/ogg",pdf:"application/pdf"},Do="只能预览图片、音视频和 PDF。";function Bo(n){var i;const e=(i=n.split("/").pop())!=null?i:"",t=e.lastIndexOf(".");if(!(t<=0))return Po[e.slice(t+1).toLowerCase()]}const jo="路径必须在工作区内,不能包含 ..、盘符或空字符。";function Rt(){return new m(g.Forbidden,jo,{reason:"path_outside_workspace"})}function W(n,e){if(n==null||n===""){if(e)return"";throw new m(g.BadRequest,"缺少参数 path。")}if(typeof n!="string")throw new m(g.BadRequest,"path 必须是字符串。");if(n.includes("\0")||/%(2e|2f|5c|00)/i.test(n))throw Rt();const t=n.normalize("NFC").replace(/\\/g,"/").trim();if(/^[a-zA-Z]:/.test(t))throw Rt();const i=[];for(const r of t.split("/"))if(!(r===""||r===".")){if(r==="..")throw Rt();i.push(r)}const s=i.join("/");if(!s&&!e)throw new m(g.BadRequest,"path 不能指向工作区根目录。");return s}function Ct(n){return new m(g.NotImplemented,`当前工作区不能${n}。`)}function ni(n,e,t){return{name:t.name,path:e,kind:t.kind,size:t.size,lastModified:t.lastModified,sensitive:t.kind==="file"&&n.sensitive.isSensitive(e)}}class as{constructor(e){v(this,"previews",new Map);v(this,"previewByPath",new Map);this.host=e}stat(e=""){return d(this,null,function*(){const t=W(e,!0),i=yield this.run(s=>s.stat(t));return ni(this.host,t,i)})}list(){return d(this,arguments,function*(e="",t={}){const i=W(e,!0);return(yield this.run(r=>r.listEntries(i,t.signal))).map(r=>{const o=i?`${i}/${r.name}`:r.name;return ni(this.host,o,r)})})}url(e){return d(this,null,function*(){var c,l;const t=W(e,!1);if(this.assertAccess(t,"read"),!Bo(t))throw new m(g.BadRequest,Do);const i=yield this.stat(t);if(i.kind!=="file")throw new m(g.BadRequest,"目标是目录,不是文件。");const s=`${(c=i.size)!=null?c:""}:${(l=i.lastModified)!=null?l:""}`,r=this.previewByPath.get(t);if((r==null?void 0:r.stamp)===s)return r.refs+=1,r.url;const o=yield this.openPreview(t),a={url:o.url,path:t,stamp:s,refs:1,release:o.release};return this.previews.set(a.url,a),this.previewByPath.set(t,a),a.url})}releaseUrl(e){const t=this.previews.get(e);t&&(t.refs-=1,!(t.refs>0)&&this.dropPreview(t))}releaseAllUrls(){const e=[...this.previews.values()];this.previews.clear(),this.previewByPath.clear(),e.forEach(t=>t.release())}read(e){return d(this,null,function*(){const t=W(e,!1);return this.assertAccess(t,"read"),this.run(i=>d(this,null,function*(){if((yield i.stat(t)).kind!=="file")throw new m(g.BadRequest,"目标是目录,不是文件。");return i.readFile(t)}))})}readText(e){return d(this,null,function*(){return(yield this.read(e)).text()})}write(s,r){return d(this,arguments,function*(e,t,i={}){const o=W(e,!1);this.assertAccess(o,"write"),yield this.run(a=>a.writeFile(o,t,{createDirectories:i.createDirectories!==!1,signal:i.signal})),this.host.notifyFilesChanged([le(o)])})}append(s,r){return d(this,arguments,function*(e,t,i={}){const o=W(e,!1);this.assertAccess(o,"write");const a=typeof t=="string"?new TextEncoder().encode(t):t;yield this.run(c=>d(this,null,function*(){let l=new Uint8Array;try{if((yield c.stat(o)).kind!=="file")throw new m(g.BadRequest,"目标是目录,不是文件。");l=new Uint8Array(yield(yield c.readFile(o)).arrayBuffer())}catch(u){if(u instanceof m||Ae(u).code!==g.NotFound)throw u}const h=new Uint8Array(l.byteLength+a.byteLength);h.set(l),h.set(a,l.byteLength),yield c.writeFile(o,h,{createDirectories:!0,signal:i.signal})})),this.host.notifyFilesChanged([le(o)])})}mkdir(e){return d(this,null,function*(){const t=W(e,!0);t&&(yield this.run(i=>d(this,null,function*(){if(!i.createDirectory)throw Ct("创建目录");yield i.createDirectory(t)})),this.host.notifyFilesChanged([le(t)]))})}remove(i){return d(this,arguments,function*(e,t={}){const s=W(e,!1);this.assertAccess(s,"write"),yield this.run(r=>d(this,null,function*(){if(!r.remove)throw Ct("删除");yield r.remove(s,t)})),this.host.notifyFilesChanged([le(s)])})}move(e,t){return d(this,null,function*(){const i=W(e,!1),s=W(t,!1);this.assertAccess(i,"write"),this.assertAccess(s,"write"),yield this.run(r=>d(this,null,function*(){if(!r.move)throw Ct("移动");yield r.move(i,s)})),this.host.notifyFilesChanged([le(i),le(s)])})}openPreview(e){return d(this,null,function*(){return this.run(t=>d(this,null,function*(){if(t.url)return t.url(e);const i=yield t.readFile(e),s=URL.createObjectURL(i);return{url:s,release:()=>URL.revokeObjectURL(s)}}))})}dropPreview(e){e.release(),this.previews.delete(e.url),this.previewByPath.get(e.path)===e&&this.previewByPath.delete(e.path)}assertAccess(e,t){const i=this.host.sensitive.match(e,t);if(i)throw new m(g.Forbidden,an.reasonOf(i),{reason:"sensitive_file",ruleId:i.id})}run(e){return d(this,null,function*(){var i;const t=this.host.adapter;if(!t)throw ut();try{return yield e(t)}catch(s){if(s instanceof m)throw s;const r=Ae(s);throw((i=r.data)==null?void 0:i.reason)==="workspace_not_granted"&&(yield this.host.handlePermissionLost()),r}})}}const Ft={mode:"readwrite"};function Uo(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 qo(n){return!!n&&typeof n=="object"&&n.name==="AbortError"}class cs{constructor(e){v(this,"applicationId");v(this,"limits");v(this,"sensitive");v(this,"downloadUrlAllowlist");v(this,"allowWorkspaceWideTextSearch");v(this,"transfer");v(this,"fetch");v(this,"commandRunner");v(this,"platformSkills");v(this,"browserRuntime");v(this,"files");v(this,"store");v(this,"picker");v(this,"event",new yn(!0));v(this,"_status");v(this,"_displayName");v(this,"_adapter",null);v(this,"pendingHandle",null);v(this,"approvalHandler");v(this,"activeCalls",0);v(this,"activeCommands",0);v(this,"inflight",new Set);v(this,"_ready",Promise.resolve());v(this,"stopWatching",()=>{});v(this,"pendingChangePaths",new Set);v(this,"changeTimer");v(this,"refreshAllVisible",!1);v(this,"epoch",0);var o,a,c,l,h,u,f,p,y,w;const t=(o=e.config)!=null?o:{};this.applicationId=e.applicationId,this.store=(a=e.store)!=null?a:bn(),this.picker=e.picker===null?void 0:(c=e.picker)!=null?c:To(),this.limits=Co(t.limits),this.sensitive=new an(t.sensitiveRulesAppend),this.downloadUrlAllowlist=wn(t.downloadUrlAllowlistAppend),this.allowWorkspaceWideTextSearch=!!t.allowWorkspaceWideTextSearch,this.approvalHandler=t.onApprovalRequired;const i=(l=e.transfer)!=null?l:vn(()=>{});this.transfer={upload:(u=(h=t.transfer)==null?void 0:h.upload)!=null?u:i.upload,resolveDownload:(p=(f=t.transfer)==null?void 0:f.resolveDownload)!=null?p:i.resolveDownload};const s=(y=e.fetch)!=null?y:typeof fetch=="function"?fetch:void 0;this.fetch=s?s.bind(globalThis):()=>Promise.reject(new Error("fetch is not available")),this.commandRunner=e.commandRunner;const r=(w=t.commandRuntime)==null?void 0:w.browser;this.browserRuntime={enabled:(r==null?void 0:r.enabled)!==!1,bashModuleURL:r==null?void 0:r.bashModuleURL,pyodideIndexURL:r==null?void 0:r.pyodideIndexURL},this._status=this.picker?"none":"unsupported",this.files=new as(this)}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}))}replaceAdapter(e){this._adapter!==e&&this.files.releaseAllUrls(),this._adapter=e}attachHandle(e){this.cancelFilesChanged(),this.pendingHandle=e,this.replaceAdapter(new Gt(e)),this.setStatus("granted",e.name),this.unwatchDirectory(),this.stopWatching=$o(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=>(this.epoch+=1,this.cancelAll(),this.attachHandle(t),this.store.set(this.handleKey,{handle:t,displayName:t.name,savedAt:Date.now()}).catch(()=>{}),!0),t=>{if(qo(t))return!1;throw t})}restore(){return this._ready=this.doRestore(),this._ready}doRestore(){return d(this,null,function*(){var s,r,o;const e=this.epoch;if(!this.picker){this._adapter||this.setStatus("unsupported");return}let t;try{t=yield this.store.get(this.handleKey)}catch(a){t=void 0}if(e!==this.epoch)return;if(!(t!=null&&t.handle)){this.pendingHandle=null,this.replaceAdapter(null),this.setStatus("none",void 0);return}let i;try{i=(o=yield(r=(s=t.handle).queryPermission)==null?void 0:r.call(s,Ft))!=null?o:"prompt"}catch(a){i="prompt"}if(e===this.epoch){if(i==="granted"||i==="prompt"&&(yield this.canList(t.handle))){if(e!==this.epoch)return;this.attachHandle(t.handle);return}this.pendingHandle=t.handle,this.replaceAdapter(null),this.setStatus(i==="denied"?"denied":"prompt",t.displayName)}})}canList(e){return d(this,null,function*(){const t=new Gt(e);let i;const s=new Promise(a=>{i=setTimeout(()=>a(!1),2e3)}),r=t.listEntries("").then(()=>!0).catch(()=>!1),o=yield Promise.race([r,s]);return clearTimeout(i),o})}requestPermission(){const e=this.pendingHandle;if(!(e!=null&&e.requestPermission))return Promise.resolve(!1);let t;try{t=e.requestPermission(Ft)}catch(i){return Promise.reject(i)}return t.then(i=>i==="granted"?(this.attachHandle(e),!0):(this.replaceAdapter(null),this.setStatus(i==="denied"?"denied":"prompt",e.name),!1))}clear(){return d(this,null,function*(){this.epoch+=1,this.cancelAll(),this.cancelFilesChanged(),this.unwatchDirectory(),this.pendingHandle=null,this.replaceAdapter(null),this.setStatus(this.picker?"none":"unsupported",void 0),yield this.store.delete(this.handleKey).catch(()=>{})})}attachFileSnapshot(e,t){var o,a,c;const i=Array.from(e),s=t||((a=(o=i[0])==null?void 0:o.webkitRelativePath)==null?void 0:a.split(/[/\\]/)[0])||((c=i[0])==null?void 0:c.name)||"工作文件夹",r=i.map(l=>({name:l.name,webkitRelativePath:l.webkitRelativePath,lastModified:l.lastModified,blob:l}));this.attachAdapter(new xo(r,s),s)}attachAdapter(e,t=e.displayName){this.epoch+=1,this.cancelAll(),this.cancelFilesChanged(),this.unwatchDirectory(),this.pendingHandle=null,this.replaceAdapter(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=Uo(t);i===void 0?this.refreshAllVisible=!0:this.pendingChangePaths.add(i)}clearTimeout(this.changeTimer),this.changeTimer=setTimeout(()=>this.flushFilesChanged(),150)}}handlePermissionLost(){return d(this,null,function*(){const e=this.pendingHandle;if(!(e!=null&&e.queryPermission))return;const t=yield e.queryPermission(Ft).catch(()=>"prompt");if(t!=="granted"){if(t==="prompt"&&this._adapter)try{yield this._adapter.listEntries("");return}catch(i){if((i&&typeof i=="object"?i.name:void 0)!=="NotAllowedError")return}this.cancelAll(),this.cancelFilesChanged(),this.unwatchDirectory(),this.replaceAdapter(null),this.setStatus(t==="denied"?"denied":"prompt",e.name)}})}isDisclosureAcknowledged(){return d(this,null,function*(){try{return!!(yield this.store.get(this.disclosureKey))}catch(e){return!1}})}acknowledgeDisclosure(){return d(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._adapter instanceof qe)return()=>{};if(this.activeCommands>=1)return null;this.activeCommands++;let e=!1;return()=>{e||(e=!0,this.activeCommands--)}}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(Jt.map(t=>[t,!0]));return{protocolVersion:"1.0",capabilities:E(b({},e),{cancellation:!0,atomicWrite:!0}),limits:b({},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 ke=(n=>(n[n.Normal=0]="Normal",n[n.Debug=1]="Debug",n))(ke||{});function Ho(n,e,t){return d(this,null,function*(){var a;if(!e)throw new Error("session is not avalible. id is undefined");const i=zo(t.name),s=yield n.postUploadTicket({files:[i],isv:"minio",knowledgeId:e,type:1}),o=(yield n.uploadMinioFile(s.minio,t))||((a=s.minio.fileKeys)==null?void 0:a[0]);return{url:Wo(s.minio,o),name:t.name||i,size:t.size}})}function zo(n){const e=n.split(/[/\\]/).pop()||"",t=/\.([A-Za-z0-9]{1,16})$/.exec(e);return t?`${ne.v4()}.${t[1].toLowerCase()}`:ne.v4()}function Wo(n,e){var s;const t=(s=n.endpoints)==null?void 0:s[0];if(!t||!n.bucket||!e)throw new Error("上传没有返回文件地址。");return`${n.useSSL?"https:":typeof location!="undefined"&&location.protocol?location.protocol:"http:"}//${t}/${n.bucket}/${e}`}const ii=100,P=new q("[Session] ");var De=(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))(De||{});class _n{constructor(e,t="",i,s,r,o){v(this,"_id");v(this,"_frozen",!1);v(this,"inactivating",!1);v(this,"_ready",!1);v(this,"event",new yn);v(this,"_applicationId");v(this,"_application",null);v(this,"data",null);v(this,"client",null);v(this,"messages",[]);v(this,"_loadingMessages",!1);v(this,"_loadingMessagesSize",10);v(this,"cvforceApi");v(this,"socket",null);v(this,"_promptVariables",[]);v(this,"active",!1);v(this,"activing",!1);v(this,"_stopAnswer",!1);v(this,"_dataLoading",!1);v(this,"_dataLoaded",!1);v(this,"_mcpServers",null);this.token=e,this.lazyload=s,this.client=o||null,this._applicationId=ct(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 a;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(c=>d(this,null,function*(){this.data=c,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>d(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(c=>d(this,null,function*(){this.data=c,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>d(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 c=(i==null?void 0:i.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:c}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:c,netOpen:i==null?void 0:i.netOpen,knowledgeIdList:(a=i==null?void 0:i.knowledges)==null?void 0:a.map(l=>l.id),applicationId:this._applicationId}).then(l=>d(this,null,function*(){var h;this._id=l.id,this.data=E(b({},l),{knowledges:i==null?void 0:i.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id);try{yield(()=>d(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,w;const p=((w=(y=i.promptVariables)==null?void 0:y.find(_=>_.key===f.key&&_.type===f.type))==null?void 0:w.value)||"";return E(b({},f),{value:p})}).sort((f,p)=>f.key.localeCompare(p.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),((h=this.application)==null?void 0:h.type)!==x.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}fetchData(){return d(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=>d(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 d(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 a,c;const o=(c=(a=r.fileIds)==null?void 0:a.length)!=null?c:0;return s+(o>0?o:1)},0)>ii)throw Error(`knowledges and fileIds total count cannot exceed ${ii}`);return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(t=>t.status===x.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>!(e.type===x.PromptVariableType.User&&e.key==="query")&&!(e.type===x.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return d(this,null,function*(){const t=e==null?void 0:e.map(r=>r.type?r:E(b({},r),{type:"instruction"})),i=this._promptVariables.map(r=>{var a;const o=((a=t==null?void 0:t.find(c=>c.key===r.key&&c.type===r.type))==null?void 0:a.value)||r.value;return E(b({},r),{value:o})}).sort((r,o)=>r.key.localeCompare(o.key));if(!(yield Promise.all(i.filter(r=>!(r.type===x.PromptVariableType.User&&r.key==="query")&&!(r.type===x.PromptVariableType.System&&r.key==="datetime")).map(r=>{if(!this.data)throw Error("session data is not loaded");if(!(!r.id||!r.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,r.id,{value:r.value})})).then(()=>!0).catch(r=>!1)))return!1;if(!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return d(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)===x.ApplicationTypes.Agent){console.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((s=this._application)==null?void 0:s.arrange[0].enableNetOpen)===!1){console.warn("This Application is disabled to change netOpen.");return}if(!this.data)throw Error("session data is not loaded");return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{netOpen:e?1:2}),this.data.netOpen=e,P.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return Ji(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 d(this,arguments,function*(e={}){var i,s;const t={pageSize:this._loadingMessagesSize};if(this._id){e=b(b({},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((c,l)=>{var f,p;let h=[],u;return typeof((f=c.agentHistoryList)==null?void 0:f.agentList)=="string"&&(h=JSON.parse(c.agentHistoryList.agentList).reduce((w,_)=>(w[_.data.step-1]||(w[_.data.step-1]=[]),w[_.data.step-1].push(_),w),[])),l===r.length-1&&(u=(p=this.data)==null?void 0:p.lastRelatedQuestion),E(b({},c),{actions:h,relatedQuesion:u,fromHistory:!0})});if(!e.endTime&&!e.startTime){const c=this.messages[this.messages.length-1];c&&!c.relatedQuesion&&(c.relatedQuesion=(i=this.data)==null?void 0:i.lastRelatedQuestion),this.messages=[...o,...this.messages]}else if(e.endTime&&!e.startTime){const c=this.messages.findIndex(l=>l.ts===e.endTime);this.messages.splice(0,c+1),this.messages=[...o,...this.messages]}else if(!e.endTime&&e.startTime){const c=this.messages.findLastIndex(l=>l.ts===e.endTime);this.messages.splice(c,this.messages.length-c-1),this.messages=[...this.messages,...o]}else{const c=this.messages.findIndex(h=>h.ts===e.endTime),l=this.messages.findLastIndex(h=>h.ts===e.endTime);this.messages.splice(c,l-c+1,...o)}const a=this.messages[this.messages.length-1];return a&&!a.relatedQuesion&&(a.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 d(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 d(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=>d(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(()=>d(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 d(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return d(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 d(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=>d(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}upload(e){return d(this,null,function*(){if(!this._id)throw Error("session is not avalible. id is undefined");return Ho(this.cvforceApi,this._id,e)})}send(i){return d(this,arguments,function*(e,t={stream:exports.configuration.stream}){var y;try{this.validateConfigs()}catch(w){console.error(w)}const{stream:s=exports.configuration.stream,referenceFirst:r=!1}=t,o=e.uuid||ne.v4(),a=((y=e.text)==null?void 0:y.trim())||"",c=e.files||[],l=e.fileIds,h=e.imageContent;if(!a&&!c.length&&!(l!=null&&l.length)){const w=new Error("failed at sending empty content");return P.error(w),this.event.emit("error",w),!1}if(!this._id){const w=new Error("session id is not defined");return P.error(w),this.event.emit("error",w),!1}if(this.frozen){const w=new Error("session is frozen");return P.error(w),this.event.emit("error",w),!1}this.frozen=!0,this._stopAnswer=!1;const u={sessionId:this.id,role:2,content:a,messageId:o,reference:[],searchReference:[],messageTime:"",files:c,imageContent:h},f={content:a,stream:s,requestId:o,fileIds:l,referenceFirst:r,imageContent:h};this.pushMessage(u),this.event.emit("question:content",a);const p=w=>d(this,null,function*(){if(w.role!==x.ChatMessageRole.Robot)return;switch(this.removeEventListener("answer:finish",p),this._id&&w.content&&w.index&&w.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:w.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:w.content})),yield this.fillMessageReference(w),w.code){case 11915:w.content="请您换个问题问我吧~",w.index=-1,w.isSensitive=!0,w.isLoading=!1,w.sessionId=this._id||"",this.event.emit("message:error",w);break;case 11916:w.content="尊敬的用户您好,让我们换个话题再聊聊吧。",w.index=-1,w.isSensitive=!0,w.isLoading=!1,w.sessionId=this._id||"",this.event.emit("message:error",w);break;case 200:w.index=-1,w.isLoading=!1;break;default:w.content=w.message||"未知错误",w.isLoading=!1,w.index=-1,this.event.emit("message:error",w)}this.getRelatedQuesion(w),w.isLoading=!1;let _=this.messages[this.messages.length-1];if(_&&_.role===x.ChatMessageRole.Robot){const A=b(b({},_),w);this.messages[this.messages.length-1]=A,this.event.emit("message:updated",A)}else this.pushMessage(w);this.frozen=!1});return this.addEventListener("answer:finish",p),this.sendQuestion(f,E(b({},t),{stream:s,referenceFirst:r})),u})}currentUserQuestion(){for(let e=this.messages.length-1;e>=0;e-=1){const t=this.messages[e];if(t.role===x.ChatMessageRole.User)return t.content||""}return""}getRelatedQuesion(e){return d(this,null,function*(){var a,c;if(!e.content||e.isSensitive||e.code!==200)return e;const t=(a=this.application)==null?void 0:a.arrange[0],i=uo(t==null?void 0:t.recommendQuestionOpen,t==null?void 0:t.relatedQuestionApp,e.content,this.currentUserQuestion());if(i===null)return e;this.event.emit("message:relatedQuesion:loading",e);const s=yield this.cvforceApi.postGeneques({content:i}).catch(l=>null);if(!s){const l=[],h=E(b({},e),{relatedQuesion:l,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:l}),this.event.emit("message:updated",h),h}const r=(c=s.content)==null?void 0:c.split("*").map(lo).map(ho).filter(l=>!!l);e.relatedQuesion=r,e.index=-3,e.isLoading=!1;const o=E(b({},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 d(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)=>b(b({},i),t[s]))}catch(t){console.error("Failed to fill message reference:",t)}return this.event.emit("message:updated",e),e})}answerAgain(){return d(this,arguments,function*(e={stream:exports.configuration.stream}){const t=this.messages[this.messages.length-1];if(!t)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1;const{stream:i=exports.configuration.stream}=e;let s;t.role!==x.ChatMessageRole.User&&(s=e.oldMessageId||t.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",t),this.event.emit("history:remove",t));const r=this.messages[this.messages.length-1],o={content:r.content,fileIds:r.fileIds,requestId:r.messageId,stream:i,oldMessageId:s},a=c=>d(this,null,function*(){if(c.role===x.ChatMessageRole.Robot&&c.index===-1){switch(this._id&&c.content&&c.index&&c.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:c.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:c.content})),yield this.fillMessageReference(c),c.code){case 11915:c.content="请您换个问题问我吧~",c.index=-1,c.isSensitive=!0,c.isLoading=!1,c.sessionId=this._id||"",this.event.emit("message:error",c);break;case 11916:c.content="尊敬的用户您好,让我们换个话题再聊聊吧。",c.index=-1,c.isSensitive=!0,c.isLoading=!1,c.sessionId=this._id||"",this.event.emit("message:error",c);break;case 200:c.index=-1,c.isLoading=!1;break;default:c.content=c.message||"未知错误",c.isLoading=!1,c.index=-1,this.event.emit("message:error",c)}this.getRelatedQuesion(c),this.removeEventListener("message:content",a),this.frozen=!1}});this.addEventListener("message:content",a),this.sendQuestion(o,E(b({},e),{stream:i}))})}setTop(e){return d(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:ne.v4(),isLoading:!1,index:-2,messageTime:Kt(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:x.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const s=e.actions[((i=e.actions)==null?void 0:i.length)-1];if(s){const r=s[s.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:o,pluginCode:a,funcCode:c,funcName:l}=r.data;s.push({data:{pluginName:o,pluginCode:a,funcCode:c,funcName:l,step:r.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:s})}}}e=b(b({},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 c=s.choices[0];t.reasoningContent=(t.reasoningContent||"")+((o=c.delta.reasoningContent)!=null?o:"")}if(i==="thinkingOver"){t.thinkingStatus="end";const a=s.thinkingSecs;t.thinkingSecs=a}if(i==="text"){const c=s.choices[0];t.content=(t.content||"")+c.delta.content}if(i==="reference"&&(t.reference=s),i==="updateSession"&&s&&this.data&&(this.data=b(b({},this.data),s),this.event.emit("data:updated",this.data)),i==="result"){const a=s.messageId,c=s.llmModel,l=s.messageTime;t.messageId=a,t.llmModel=c,t.messageTime=l}i==="over"?t.index=-1:(t.code=e.code,t.message=e.message)}getArtifacts(){return d(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 d(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 ue=new Map,Vo=2e4;function Go(n){if(typeof AbortSignal!="undefined"&&typeof AbortSignal.timeout=="function"){const e=AbortSignal.timeout(Vo);if(!n)return e;const t=new AbortController,i=()=>t.abort();return e.addEventListener("abort",i,{once:!0}),n.addEventListener("abort",i,{once:!0}),t.signal}return n}function Ue(n){return`${n.url}
371
- ${JSON.stringify(n.headers)}`}function Xo(n){const e=n.trim();if(!e)return{};if(e.startsWith("{")||e.startsWith("["))return JSON.parse(e);const t=e.split(/\n\n/);for(let i=t.length-1;i>=0;i-=1){const s=t[i].split(`
368
+ ${Ur}
369
+ ${i}`}}:{data:{content:t}}})}function Wr(n,e){return d(this,null,function*(){const t=n.path?wn(n.skill_name,n.path):yn(n.skill_name);return{data:{files:yield Vt(n.skill_name,t,e)}}})}function Vr(n,e){return d(this,null,function*(){const t=n.path?wn(n.skill_name,n.path):yn(n.skill_name);let i="";try{i=yield Fe(e).grep(n.skill_name,n.pattern,t,e.signal)}catch(s){vn(s)}return{data:{matches:i}}})}function Gr(n,e){return d(this,null,function*(){if(n.resource_name.startsWith("grep:")){const i=n.resource_name.slice(5);if(!i)throw new m(g.BadRequest,"grep: 后面要写搜索表达式。");yn(n.skill_name);let s="";try{s=yield Fe(e).grep(n.skill_name,i,"",e.signal)}catch(r){vn(r)}return{data:{content:s||"没有匹配。"}}}if(n.resource_name==="."||n.resource_name==="./")return{data:{content:(yield Vt(n.skill_name,"",e))||"(空目录)"}};const t=wn(n.skill_name,n.resource_name.replace(/\/+$/,""));try{return{data:{content:yield Xi(n.skill_name,t,e)}}}catch(i){if(!qr(i))throw i;return{data:{content:(yield Vt(n.skill_name,t,e))||"(空目录)"}}}})}function Xr(n,e){return d(this,null,function*(){var o;const t=Fe(e);yt(n.skill_name,n.script_name),dt(n.script_name);const i=Hr(e),s=yield t.target(n.skill_name,e.signal),r=t.track(s.skillId,s.version);try{const a=yield i.exec({argv:[dt(n.script_name),n.script_name,...(o=n.args)!=null?o:[]],cwd:rn,timeoutMs:e.timeoutMs,signal:e.signal,skill:s});return{data:{exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}}catch(a){throw Vi(a)?new m(g.NotFound,"技能脚本不存在。"):a}finally{r()}})}const Yr={shell:jr,read_file:xr,write_file:Tr,append_file:Lr,run_file:Br,edit_file:Rr,grep:Nr,find:Pr,load_skill:zr,read_skill_resource:Gr,list_skill_files:Wr,grep_skill:Vr,run_skill_script:Xr},Ae=new B("[BuiltinTools] "),Tt=new Set(["shell","run_file","run_skill_script"]);function Kr(n,e,t){var i,s;if(n.commandRunner)return jt(n.commandRunner);if(e instanceof He){if(e.protocolMismatch){const r=`${(i=e.sandboxVersion)!=null?i:""}@${(s=e.sandboxProtocol)!=null?s:""}`;t.rejectedSandbox!==r&&(t.rejectedSandbox=r,Ae.error("sandbox-protocol",{sandboxVersion:e.sandboxVersion,sandboxProtocol:e.sandboxProtocol,supported:Ee}))}if(!e.canExec){const r=e.unavailableMessage();return{exec:()=>Promise.reject(k("NotAllowedError",r))}}return{exec:r=>e.exec(r)}}if(n.browserRuntime.enabled)return(t.adapter!==e||!t.runner)&&(t.adapter=e,t.runner=jt(new _r({adapter:e,sensitive:n.sensitive,moduleURL:n.browserRuntime.bashModuleURL,pyodideIndexURL:n.browserRuntime.pyodideIndexURL}))),t.runner}function Jr(n,e){if(n.commandRunner)return jt(n.commandRunner);if(e instanceof He){if(!e.canExec){const t=e.unavailableMessage();return{exec:()=>Promise.reject(k("NotAllowedError",t))}}return{exec:t=>e.exec(t)}}}function Qr(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch(e){throw new m(g.BadRequest,"参数不是合法的 JSON 对象。")}}function Zr(n){const e=n instanceof DOMException?n.name:"",t=n instanceof Error?n.message:"";if(e==="NotFoundError")return new m(g.NotFound,"脚本或目录不存在。");if(e==="SecurityError")return new m(g.Forbidden,"命令路径不在工作区内。");if(e==="AbortError")return t.includes("超时")?new m(g.Timeout,"命令运行超时,已中止。"):t.includes("已有")||t.includes("上限")?new m(g.TooManyRequests,t):U();if(e==="NotAllowedError"){const i=t.trim();return i&&i!=="NotAllowedError"?new m(g.NotImplemented,i):new m(g.NotImplemented,"当前环境不能执行命令或脚本,需要端侧宿主。")}}function eo(n){return new Promise((e,t)=>{n.aborted&&t(U()),n.addEventListener("abort",()=>t(U()),{once:!0})})}function Yi(n,e=160){return n.length>e?`${n.slice(0,e)}…`:n}function to(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=Yi(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 no(n){return b({code:n.code,message:n.message},n.data?{data:n.data}:{})}function io({pluginCode:n,workspace:e}){const t=new Map,i={},s={};return qt.forEach(r=>{s[r]=(o,a,c)=>{let l=!1;so(e,t,i,r,o,u=>{if(!l){l=!0;try{a(u)}catch(f){Ae.report("callback failed",f)}}},S(b({},c),{pluginCode:n}))}}),{[n]:s}}function so(n,e,t,i,s,r,o){return d(this,null,function*(){var E,I,M,q,D;const a={requestId:o.requestId||ie.v4(),applicationId:o.applicationId||n.applicationId,sessionId:o.sessionId||"",pluginCode:o.pluginCode,functionCode:i,signal:o.signal},c={requestId:a.requestId,sessionId:a.sessionId,functionCode:i},l=new AbortController;let h=!1;const u=Tt.has(i)?n.limits.commandTimeoutMs:n.limits.toolTimeoutMs,f=setTimeout(()=>{h=!0,l.abort()},u),p=()=>l.abort();(E=a.signal)==null||E.addEventListener("abort",p,{once:!0}),(I=a.signal)!=null&&I.aborted&&l.abort();let w=null,_=null,v;const A=Date.now();try{const C=Qr(s),R=Pi(C,fn[i].parameters);if(typeof R.path=="string"&&(c.path=R.path),Ae.log("start",b(b({},c),to(R))),yield n.ready,l.signal.aborted)throw U();const F=n.adapter;if(!F)throw mt();if(Tt.has(i)){if(_=n.acquireCommand(),!_)throw new m(g.TooManyRequests,"已有一个命令在运行,请等它结束后再试。")}else if(w=n.acquireSlot(),!w)throw new m(g.TooManyRequests,"同时进行的文件操作过多,请稍后重试。");v=n.track(l),n.emit("tool:start",b({},c));const W=a.sessionId||"default";let H=e.get(W);H||(H={cwd:rn},e.set(W,H));const pe=Kr(n,F,t),Oe=H.cwd,Ne={adapter:F,runner:pe,signal:l.signal,timeoutMs:u,shellCwd:H,skills:n.platformSkills,skillRunner:Jr(n,F)},me=yield Promise.race([Yr[i](R,Ne),eo(l.signal)]),An={code:g.Ok,message:"ok",data:me.data};me.truncated&&(An.truncated=!0);const ws=Date.now()-A,xn=me.data.exitCode;Ae.log("finish",b(b(b(S(b({},c),{elapsedMs:ws,code:g.Ok}),me.truncated?{truncated:!0}:{}),typeof xn=="number"?{exitCode:xn}:{}),i==="shell"?{cwd:H.cwd,cwdChanged:H.cwd!==Oe}:{})),n.emit("tool:finish",S(b({},c),{code:g.Ok})),Tt.has(i)&&n.notifyFilesChanged(),r(An)}catch(C){let R=(M=Zr(C))!=null?M:Le(C);h?R=new m(g.Timeout,"操作超时,已中止。"):l.signal.aborted&&R.code!==g.Cancelled&&(R=U());const F=Date.now()-A;R.code===g.Cancelled?(Ae.log("cancelled",S(b({},c),{elapsedMs:F,timedOut:h})),n.emit("tool:cancelled",b({},c))):(Ae.error("error",S(b({},c),{elapsedMs:F,code:R.code,message:Yi(R.message,300)})),n.emit("tool:error",S(b({},c),{code:R.code,message:R.message,reason:(q=R.data)==null?void 0:q.reason}))),r(no(R))}finally{clearTimeout(f),(D=a.signal)==null||D.removeEventListener("abort",p),w==null||w(),_==null||_(),v==null||v()}})}const Qn="MCP",wt=new Map;let G=null;function ro(n,e,t){wt.set(n,e),G=S(b({},G!=null?G:{}),{[n]:t})}function Zn(n){wt.clear(),G=null;for(const e of n)ro(e.name,e.binding,e.handler);G&&!Object.keys(G).length&&(G=null)}function oo(n){return wt.get(n)}function ao(){return[...wt.values()]}function co(n){var e;!G||!Object.keys(G).length||(n[Qn]=b(b({},(e=n[Qn])!=null?e:{}),G))}const Ki=new B("[Config] ");var Ji=(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))(Ji||{});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 xe,Z;const Gt=new Set;function ei(n){xe!==n&&(xe=n,Z=void 0,Gt.clear())}function lo(){if(!Z)return;const{pluginCode:n,table:e}=Z,t=exports.configuration.plugins[n],i=e[n];if(!(!t||t.shell!==i.shell))return n}function Qi(n,e){return(n==null?void 0:n.pluginCode)||wi[e]}function ho(){var o,a;const n=(o=exports.configuration.businessPlugins)!=null?o:{},e=(a=exports.configuration.builtinPlugins)==null?void 0:a.localFiles,t=[],i=b({},n);if(!!!(e!=null&&e.enabled))return Lt(i),t;if(!xe)return t.push("[BuiltinTools] 内置工具依赖已启用的本地工作区。工具未注册。"),Lt(i),t;const r=e!=null&&e.enabled?Qi(e,exports.configuration.env):void 0;return r?n[r]?t.push(`[BuiltinTools] 业务插件中已存在 pluginCode「${r}」,已保留业务插件,内置工具未注册。`):(((Z==null?void 0:Z.workspace)!==xe||Z.pluginCode!==r)&&(Z={workspace:xe,pluginCode:r,table:io({pluginCode:r,workspace:xe})}),i[r]=Z.table[r]):t.push(`[BuiltinTools] 当前环境(env: ${exports.configuration.env})没有默认的内置工具插件编码,请配置 builtinPlugins.localFiles.pluginCode。内置工具未注册。`),Lt(i),t}function Lt(n){co(n),exports.configuration.plugins=n}function Ue(){return ho().filter(n=>!Gt.has(n)).map(n=>(Gt.add(n),Ki.report(n),new Error(n)))}function Xt(n,e={}){var t,i,s;B.debug=(n==null?void 0:n.debug)||!1,exports.configuration=S(b(b({},exports.configuration),n),{apiRoot:(n==null?void 0:n.apiRoot)||exports.configuration.apiRoot||(n!=null&&n.env?Ji[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&&Ue(),Ki.log("updated",exports.configuration)}const ht=n=>JSON.parse(ks.decode(n.split(".")[1])),Zi=n=>{const e=ht(n).exp;return new Date().valueOf()/1e3>=e},uo=n=>n==null?void 0:n.replace(/[\r\n]+/gm,""),fo=n=>n.replace(/\\|\\/g,""),po=(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,a=[];return s&&a.push(`问题:${i}`),o&&a.push(`回答:${t}`),a.join(`
370
+ `)};function es(n,e,t){return new x.CVForceApi(ts(n,"/data/v1",e,t),ns(t))}function mo(n,e,t){return new x.AIShopApi(ts(n,"/aishop",e,t),ns(t))}function ts(n,e,t,i){const s=o=>{var a;return t&&(Zi(t)&&i(403,"aiotToken is timeout"),o.headers=(a=o.headers)!=null?a:{},o.headers=S(b({},o.headers),{Authorization:t?`Bearer ${t}`:""})),o};function r(o,a=!0){const c=`${n}${o}`,l=Ss.create({baseURL:c});return a&&l.interceptors.request.use(s),l}return r(e)}function ns(n){return{onHttpStatusError:(i,s)=>{i===401&&n(i,"aiotToken is invalid")},onAppStatusError:(i,s)=>{i!==10001&&i!==10215&&n(i,s)}}}const Pe=new B("[PlatformSkills] "),go=20*1024*1024,is=/^[A-Za-z0-9._-]+$/;function Ke(n){const e=n==null?void 0:n.skills;return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"):[]}function yo(n,e){e&&(n.skills=e.skills)}function wo(n){return d(this,null,function*(){var t;if(!n.arrange)return;const e=yield n.fetchApplication();n.stillCurrent&&!n.stillCurrent()||yo(n.arrange,(t=e==null?void 0:e.arrange)==null?void 0:t[0])})}function vo(n){if(!n)return!1;try{return!Zi(n)}catch(e){return!1}}function ti(n){if(!(typeof n.skillId!="string"||!is.test(n.skillId))&&!(typeof n.name!="string"||!n.name||/[\\/\0]/.test(n.name)||n.name==="."||n.name==="..")&&!(typeof n.version!="number"||!Number.isInteger(n.version)||n.version<1))return{skillId:n.skillId,name:n.name,version:n.version}}function bo(n){return Array.isArray(n)?n.flatMap(e=>{if(!e||typeof e!="object")return[];const t=e;return typeof t.skillId!="string"||typeof t.name!="string"||typeof t.version!="number"?[]:[{skillId:t.skillId,name:t.name,version:t.version}]}):[]}class _o{constructor(e){y(this,"inflight",new Map);y(this,"busy",new Set);this.options=e}sync(){const e=Ke({skills:this.options.getSkills()});return Pe.log("sync",{count:e.length,sandbox:!!this.options.getSandbox()}),this.reconcile().catch(t=>{Pe.error("sync failed",t instanceof Error?t.message:String(t))})}read(e,t,i){return d(this,null,function*(){const s=yield this.prepare(e,i);return this.requireSandbox().skillRead(this.options.applicationId(),s.skillId,s.version,t,i)})}list(e,t,i){return d(this,null,function*(){const s=yield this.prepare(e,i);return this.requireSandbox().skillList(this.options.applicationId(),s.skillId,s.version,t,i)})}grep(e,t,i,s){return d(this,null,function*(){const r=yield this.prepare(e,s);return this.requireSandbox().skillGrep(this.options.applicationId(),r.skillId,r.version,i,t,s)})}target(e,t){return d(this,null,function*(){const i=yield this.prepare(e,t);return{applicationId:this.options.applicationId(),skillId:i.skillId,version:i.version,name:i.name}})}track(e,t){const i=`${e}/${t}`;this.busy.add(i);let s=!1;return()=>{s||(s=!0,this.busy.delete(i),this.prune().catch(()=>{}))}}requireSandbox(){const e=this.options.getSandbox();if(!e)throw new m(g.NotImplemented,"当前环境不能加载平台技能,需要端侧宿主。");return e}prepare(e,t){return d(this,null,function*(){const i=this.bound(e);if(!i)throw new m(g.NotFound,"技能或资源不存在。");return yield this.ensure(i,t),i})}bound(e){if(!is.test(this.options.applicationId()))return;const t=Ke({skills:this.options.getSkills()}).find(i=>i.name===e);return t?ti(t):void 0}reconcile(){return d(this,null,function*(){if(!this.options.getSandbox())return;const t=Ke({skills:this.options.getSkills()}).flatMap(i=>{const s=ti(i);return s?[s]:[]});yield Promise.all(t.map(i=>this.ensure(i).catch(s=>{Pe.error("install failed",i.name,s instanceof Error?s.message:String(s))}))),yield this.prune()})}ensure(e,t){return d(this,null,function*(){const i=`${this.options.applicationId()}/${e.skillId}/${e.version}`,s=this.inflight.get(i);if(s)return s;const r=this.installIfNeeded(e,t).finally(()=>{this.inflight.get(i)===r&&this.inflight.delete(i)});return this.inflight.set(i,r),r})}installIfNeeded(e,t){return d(this,null,function*(){var c;const i=this.requireSandbox();if(i.ready&&(yield this.alreadyInstalled(i,e,t))){Pe.log("installed",e.name,e.version);return}Pe.log("download",e.name,e.skillId,e.version);const s=this.options.getToken();if(!vo(s))throw new m(g.Forbidden,"技能下载令牌不可用。");const r=this.options.apiRoot().replace(/\/$/,""),o=yield((c=this.options.fetch)!=null?c:fetch)(`${r}/skill/v1/skills/${encodeURIComponent(e.skillId)}/versions/${e.version}/download`,{headers:{Authorization:`Bearer ${s}`},signal:t});if(!o.ok)throw new m(g.BadRequest,`技能下载失败(${o.status})。`);const a=new Uint8Array(yield o.arrayBuffer());if(a.byteLength>go)throw new m(g.BadRequest,"技能压缩包超过 20 MB。");yield this.waitReady(i,t),!(yield this.alreadyInstalled(i,e,t))&&(yield i.installSkill({applicationId:this.options.applicationId(),skillId:e.skillId,version:e.version,name:e.name},a,t))})}alreadyInstalled(e,t,i){return d(this,null,function*(){return bo(yield e.skillStatus(this.options.applicationId(),i)).some(r=>r.skillId===t.skillId&&r.version===t.version&&r.name===t.name)})}prune(){return d(this,null,function*(){const e=this.options.getSandbox();if(!(e!=null&&e.ready))return;const t=Ke({skills:this.options.getSkills()}).flatMap(s=>typeof s.skillId!="string"||typeof s.version!="number"||s.version<1?[]:[{skillId:s.skillId,version:s.version}]),i=[...this.busy].map(s=>{const[r,o]=s.split("/");return{skillId:r,version:Number(o)}});yield e.skillPrune(this.options.applicationId(),t,i)})}waitReady(e,t){return d(this,null,function*(){e.ready||(yield new Promise((i,s)=>{const r=setInterval(()=>{if(t!=null&&t.aborted){clearInterval(r),s(new m(g.Cancelled,"已取消。"));return}e.ready&&(clearInterval(r),i())},50)}))})}}function ko(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}}const Rt=new B("[HostBridge] ");let ae;function So(n){ae==null||ae(),ae=void 0;const e=Ni();if(!e)return Rt.log("missing"),()=>{};const t=new He(e),i=r=>{const o=Oi(r.data);if(o){if(o.type==="workspace"){const a=o.granted===!0,c=typeof o.displayName=="string"?o.displayName:"";t.setCapabilities(o.capabilities,{version:o.sandboxVersion}),t.applySandbox(ko(o.sandbox)),Rt.log("workspace",{granted:a,displayName:c}),a?(t.displayName=c||"工程目录",(n.status!=="granted"||n.displayName!==t.displayName)&&n.attachAdapter(t,t.displayName)):n.status==="granted"&&n.clear();return}if(o.type==="fs-changed"){const a=Array.isArray(o.paths)?o.paths.filter(c=>typeof c=="string"):[];n.notifyFilesChanged(a);return}}};e.addEventListener("message",i),Rt.log("hello"),e.postMessage({channel:sn,type:"hello"});const s=()=>{e.removeEventListener("message",i),ae===s&&(ae=void 0)};return ae=s,s}const Yt=new Set;let it,ss=[],ce,Je;function Mt(){return{revision:it,servers:ss}}function Eo(n){return Yt.add(n),()=>Yt.delete(n)}function Io(n){let e;try{e=new URL(n)}catch(s){return}if(e.protocol!=="http:"||e.username||e.password||!e.port)return;const t=Number(e.port);if(!Number.isInteger(t)||t<1||t>65535)return;const i=e.hostname.toLowerCase();if(!(i!=="127.0.0.1"&&i!=="localhost"&&i!=="::1"&&i!=="[::1]"))return e.href}function Ct(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function Ao(n){var t;if(!Array.isArray(n))return[];const e=[];for(const i of n){if(!i||typeof i!="object")continue;const s=i,r=Ct(s.code),o=(t=Ct(s.id))!=null?t:r,a=typeof s.url=="string"?Io(s.url):void 0;if(!o||!a)continue;const c=Ct(s.token);e.push(b(b({id:o,url:a},r?{code:r}:{}),c?{token:c}:{}))}return e}function xo(n){const e=n.revision;return typeof e!="number"||!Number.isFinite(e)||it!==void 0&&e<=it||!Array.isArray(n.servers)?!1:(it=e,ss=Ao(n.servers),Yt.forEach(t=>t()),!0)}function rs(){const n=Ni();if(!n)return()=>{};if(Je===n&&ce)return ce;ce==null||ce();const e=i=>{const s=Oi(i.data);!s||s.type!=="local-mcps"||xo(s)};n.addEventListener("message",e),Je=n;const t=()=>{n.removeEventListener("message",e),Je===n&&(Je=void 0,ce=void 0)};return ce=t,t}const To=new B("[EventBus] ");class bn{constructor(e=!1){y(this,"eventListenerMap",{});this.disableLog=e}trace(e,...t){this.disableLog||To.log(e,...t)}getEventListenerMap(){return b({},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),this.trace(`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?this.trace(`event ${e} listener ${t.name} is not found`):(this.eventListenerMap[e].splice(i,1),this.trace(`remove event ${e} listener`))}else this.trace(`event ${e} listeners is empty`)}emit(e,t){if(!this.eventListenerMap[e]){this.trace(`event ${e} listeners is empty`,t);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))}),this.trace(`event ${e} is fired, has ${this.eventListenerMap[e].length} listeners`,t)}removeAllListeners(){this.eventListenerMap={}}}const Lo="路径必须是工作区内的相对路径,不能包含 ..、绝对路径或盘符。";function Qe(){return new m(g.Forbidden,Lo,{reason:"path_outside_workspace"})}function Ro(n){if(n!==Te)throw new m(g.Forbidden,`未知的工作区 grantId,当前仅支持 ${Te}。`,{reason:"path_outside_workspace"})}function te(n,{allowRoot:e=!1,field:t="path"}={}){if(n==null){if(e)return"";throw new m(g.BadRequest,`缺少参数 ${t}。`)}if(typeof n!="string")throw new m(g.BadRequest,`参数 ${t} 必须是字符串。`);if(n.includes("\0")||/%(2e|2f|5c|00)/i.test(n))throw Qe();const i=n.normalize("NFC").replace(/\\/g,"/").trim();if(i.startsWith("/")||/^[a-zA-Z]:/.test(i))throw Qe();const s=[];for(const o of i.split("/"))if(!(o===""||o===".")){if(o==="..")throw Qe();s.push(o)}const r=s.join("/");if(!r&&!e)throw new m(g.BadRequest,`参数 ${t} 不能指向工作区根目录。`);return r}function $(n){return n?n.split("/"):[]}function le(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}function os(n,e){return n?`${n}/${e}`:e}function Be(n,e){return!!n&&typeof n=="object"&&n.name===e}class Kt{constructor(e){this.root=e}get displayName(){return this.root.name}resolveDirectory(e,t=!1){return d(this,null,function*(){let i=this.root;for(const s of e)i=yield i.getDirectoryHandle(s,{create:t});return i})}resolveFile(e){return d(this,null,function*(){const t=$(e),i=t.pop();if(!i)throw k("TypeMismatchError");return(yield this.resolveDirectory(t)).getFileHandle(i)})}stat(e){return d(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(!Be(r,"TypeMismatchError"))throw r;return yield s.getDirectoryHandle(i),{name:i,kind:"directory"}}})}listEntries(e,t){return d(this,null,function*(){const i=yield this.resolveDirectory($(e)),s=[];try{for(var r=X(i.values()),o,a,c;o=!(a=yield r.next()).done;o=!1){const l=a.value;N(t),s.push({name:l.name,kind:l.kind==="directory"?"directory":"file"})}}catch(a){c=[a]}finally{try{o&&(a=r.return)&&(yield a.call(r))}finally{if(c)throw c[0]}}return s})}readFile(e){return d(this,null,function*(){return(yield this.resolveFile(e)).getFile()})}writeFile(s,r){return d(this,arguments,function*(e,t,i={}){const o=$(e),a=o.pop();if(!a)throw k("TypeMismatchError");const c=yield this.resolveDirectory(o,i.createDirectories);let l=!0;try{yield c.getFileHandle(a)}catch(v){if(!Be(v,"NotFoundError"))throw v;l=!1}const h=yield c.getFileHandle(a,{create:!0});let u;try{u=yield h.createWritable();try{for(var f=X(gt(t)),p,w,_;p=!(w=yield f.next()).done;p=!1){const v=w.value;N(i.signal),yield u.write(v)}}catch(w){_=[w]}finally{try{p&&(w=f.return)&&(yield w.call(f))}finally{if(_)throw _[0]}}N(i.signal),yield u.close()}catch(v){throw yield u==null?void 0:u.abort().catch(()=>{}),l||(yield c.removeEntry(a).catch(()=>{})),v}})}createDirectory(e){return d(this,null,function*(){yield this.resolveDirectory($(e),!0)})}remove(i){return d(this,arguments,function*(e,t={}){const s=$(e),r=s.pop();if(!r)throw k("InvalidModificationError");yield(yield this.resolveDirectory(s)).removeEntry(r,{recursive:t.recursive===!0})})}move(e,t){return d(this,null,function*(){const i=$(e),s=$(t),r=i.pop(),o=s.pop();if(!r||!o)throw k("InvalidModificationError");const a=yield this.resolveDirectory(i),c=yield ni(a,r),l=yield this.resolveDirectory(s);if(Ci(e,t))throw k("InvalidModificationError");let h;try{h=yield ni(l,o)}catch(u){if(!Be(u,"NotFoundError"))throw u}if(h&&(h.kind==="directory"||c.kind==="directory"))throw k("InvalidModificationError");if(!h&&typeof c.move=="function")try{yield c.move(l,o);return}catch(u){if(!Be(u,"NotSupportedError")&&!(u instanceof TypeError))throw u}yield as(c,l,o),yield a.removeEntry(r,{recursive:!0})})}}function ni(n,e){return d(this,null,function*(){try{return yield n.getFileHandle(e)}catch(t){if(!Be(t,"TypeMismatchError"))throw t;return n.getDirectoryHandle(e)}})}function as(n,e,t){return d(this,null,function*(){if(n.kind==="file"){const c=yield n.getFile(),l=yield(yield e.getFileHandle(t,{create:!0})).createWritable();try{yield l.write(c),yield l.close()}catch(h){throw yield l.abort().catch(()=>{}),h}return}const i=yield e.getDirectoryHandle(t,{create:!0});try{for(var s=X(n.values()),r,o,a;r=!(o=yield s.next()).done;r=!1){const c=o.value;yield as(c,i,c.name)}}catch(o){a=[o]}finally{try{r&&(o=s.return)&&(yield o.call(s))}finally{if(a)throw a[0]}}})}function ii(){return{kind:"directory",children:new Map}}class Mo{constructor(e,t){y(this,"root",ii());var i;this.displayName=t;for(const s of e){const r=Co(s,t);r&&this.writeNode(r,s.blob,(i=s.lastModified)!=null?i:Date.now())}}writeNode(e,t,i){const s=e.split("/").filter(Boolean),r=s.pop();if(!r)return;this.resolveDirectory(s,!0).children.set(r,{kind:"file",blob:t,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 k("NotFoundError");r=ii(),i.children.set(s,r)}if(r.kind!=="directory")throw k("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 k("NotFoundError");return s}stat(e){return d(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.blob.size,lastModified:t.lastModified}})}listEntries(e,t){return d(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.blob.size,lastModified:r.lastModified})})}readFile(e){return d(this,null,function*(){const t=this.resolveNode(e);if(t.kind!=="file")throw k("TypeMismatchError");return t.blob})}writeFile(s,r){return d(this,arguments,function*(e,t,i={}){const o=$(e),a=o.pop();if(!a)throw k("TypeMismatchError");const c=this.resolveDirectory(o,i.createDirectories),l=c.children.get(a);if((l==null?void 0:l.kind)==="directory")throw k("TypeMismatchError");const h=[];try{for(var f=X(gt(t)),p,w,_;p=!(w=yield f.next()).done;p=!1){const v=w.value;N(i.signal),h.push(v)}}catch(w){_=[w]}finally{try{p&&(w=f.return)&&(yield w.call(f))}finally{if(_)throw _[0]}}const u=new Blob(h);c.children.set(a,{kind:"file",blob:u,lastModified:Date.now()})})}}function Co(n,e){const t=(n.webkitRelativePath||n.name).replace(/\\/g,"/").replace(/^\/+/,"");if(!t)return"";const i=`${e}/`;return t.startsWith(i)?t.slice(i.length):t}function Fo(){if(typeof window=="undefined")return;const n=window.showDirectoryPicker;return typeof n=="function"?n.bind(window):void 0}const Oo=/^[a-z0-9-]+(\.[a-z0-9-]+)+$/;function No(n){if(typeof n!="string")return null;const e=n.trim().toLowerCase().replace(/^\*?\./,"").replace(/\.$/,"");return!Oo.test(e)||cs(e)?null:e}function cs(n){return n.startsWith("[")||n.includes(":")?!0:/^[0-9.]+$/.test(n)||/^0x[0-9a-f.]+$/i.test(n)}function _n(n=[]){const e=new Set(xi);for(const t of n){const i=No(t);i&&e.add(i)}return Array.from(e)}function $o(n,e){return Jt(n,_n(e))}function Jt(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||cs(i)||i==="localhost"||i.endsWith(".localhost")?!1:e.some(s=>i===s||i.endsWith(`.${s}`))}function Po(n={}){const e=b({},Ze);return Object.keys(Ze).forEach(t=>{const i=n[t];typeof i=="number"&&Number.isFinite(i)&&i>0&&(e[t]=Math.min(i,Ze[t]))}),e}function ke(){return new m(g.Internal,"平台文件服务请求失败,请稍后重试。")}function kn(n,e=()=>{}){const t=()=>{const r=n();if(!r)throw ke();return r},i=()=>{const r=e();if(!r)throw ke();return r};return{upload(r,o,a){return d(this,null,function*(){if(!o.sessionId)throw new m(g.BadRequest,"当前没有可用的会话,无法上传文件。");try{a==null||a({loaded:0,total:r.size});const c=yield i().postFile(r,(l,h)=>a==null?void 0:a({loaded:l,total:h}));if(!(c!=null&&c.id)||!c.url)throw ke();return a==null||a({loaded:r.size,total:r.size}),{fileId:c.id,url:c.url}}catch(c){throw c instanceof m?c:ke()}})},resolveDownload(r,o){return d(this,null,function*(){if(r.type==="platformFile")return Do(i(),r.fileId);if(!o.sessionId)throw new m(g.BadRequest,"当前没有可用的会话,无法下载会话文件。");let a;try{a=yield t().getApplicationIdSessionFile(o.applicationId,o.sessionId,r.fileId)}catch(c){throw ke()}if(!(a!=null&&a.url))throw new m(g.NotFound,"会话文件不存在或暂不可下载。");return{url:a.url,name:a.name,size:a.size}})}}}function Do(n,e){return d(this,null,function*(){let t;try{t=yield n.getFile(e)}catch(s){throw ke()}if(!(t!=null&&t.url))throw new m(g.NotFound,"平台文件不存在或暂不可下载。");let i;try{i=new URL(t.url)}catch(s){throw new m(g.Internal,"平台返回的下载地址无效。")}if(i.protocol!=="https:")throw new m(g.Internal,"平台返回的下载地址无效。");return{url:t.url,size:t.bytes}})}const Bo="glodon-aiot-local-workspace",Ft="kv";function Sn(){const n=new Map;return{get(t){return d(this,null,function*(){return n.get(t)})},set(t,i){return d(this,null,function*(){n.set(t,i)})},delete(t){return d(this,null,function*(){n.delete(t)})}}}function jo(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}function ls(n=Bo){if(typeof indexedDB=="undefined")return Sn();let e;const t=()=>(e||(e=new Promise((r,o)=>{const a=indexedDB.open(n,1);a.onupgradeneeded=()=>{a.result.createObjectStore(Ft)},a.onsuccess=()=>r(a.result),a.onerror=()=>{e=void 0,o(a.error)}})),e),i=(r,o)=>d(this,null,function*(){const a=yield t();return jo(o(a.transaction(Ft,r).objectStore(Ft)))});return{get(r){return d(this,null,function*(){return yield i("readonly",o=>o.get(r))})},set(r,o){return d(this,null,function*(){yield i("readwrite",a=>a.put(o,r))})},delete(r){return d(this,null,function*(){yield i("readwrite",o=>o.delete(r))})}}}function si(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 Uo(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 a=si(o.relativePathComponents),c=si(o.relativePathMovedFrom);if(a===void 0&&c===void 0){e();return}a!==void 0&&r.add(a),c!==void 0&&r.add(c)}r.size&&e([...r])})}catch(s){return()=>{}}return i.observe(n,{recursive:!0}).catch(()=>i.disconnect()),()=>i.disconnect()}const qo={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",bmp:"image/bmp",avif:"image/avif",ico:"image/x-icon",svg:"image/svg+xml",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",m4v:"video/mp4",ogv:"video/ogg",pdf:"application/pdf"},Ho="只能预览图片、音视频和 PDF。";function zo(n){var i;const e=(i=n.split("/").pop())!=null?i:"",t=e.lastIndexOf(".");if(!(t<=0))return qo[e.slice(t+1).toLowerCase()]}const Wo="路径必须在工作区内,不能包含 ..、盘符或空字符。";function Ot(){return new m(g.Forbidden,Wo,{reason:"path_outside_workspace"})}function V(n,e){if(n==null||n===""){if(e)return"";throw new m(g.BadRequest,"缺少参数 path。")}if(typeof n!="string")throw new m(g.BadRequest,"path 必须是字符串。");if(n.includes("\0")||/%(2e|2f|5c|00)/i.test(n))throw Ot();const t=n.normalize("NFC").replace(/\\/g,"/").trim();if(/^[a-zA-Z]:/.test(t))throw Ot();const i=[];for(const r of t.split("/"))if(!(r===""||r===".")){if(r==="..")throw Ot();i.push(r)}const s=i.join("/");if(!s&&!e)throw new m(g.BadRequest,"path 不能指向工作区根目录。");return s}function Nt(n){return new m(g.NotImplemented,`当前工作区不能${n}。`)}function ri(n,e,t){return{name:t.name,path:e,kind:t.kind,size:t.size,lastModified:t.lastModified,sensitive:t.kind==="file"&&n.sensitive.isSensitive(e)}}class ds{constructor(e){y(this,"previews",new Map);y(this,"previewByPath",new Map);this.host=e}stat(e=""){return d(this,null,function*(){const t=V(e,!0),i=yield this.run(s=>s.stat(t));return ri(this.host,t,i)})}list(){return d(this,arguments,function*(e="",t={}){const i=V(e,!0);return(yield this.run(r=>r.listEntries(i,t.signal))).map(r=>{const o=i?`${i}/${r.name}`:r.name;return ri(this.host,o,r)})})}url(e){return d(this,null,function*(){var c,l;const t=V(e,!1);if(this.assertAccess(t,"read"),!zo(t))throw new m(g.BadRequest,Ho);const i=yield this.stat(t);if(i.kind!=="file")throw new m(g.BadRequest,"目标是目录,不是文件。");const s=`${(c=i.size)!=null?c:""}:${(l=i.lastModified)!=null?l:""}`,r=this.previewByPath.get(t);if((r==null?void 0:r.stamp)===s)return r.refs+=1,r.url;const o=yield this.openPreview(t),a={url:o.url,path:t,stamp:s,refs:1,release:o.release};return this.previews.set(a.url,a),this.previewByPath.set(t,a),a.url})}releaseUrl(e){const t=this.previews.get(e);t&&(t.refs-=1,!(t.refs>0)&&this.dropPreview(t))}releaseAllUrls(){const e=[...this.previews.values()];this.previews.clear(),this.previewByPath.clear(),e.forEach(t=>t.release())}read(e){return d(this,null,function*(){const t=V(e,!1);return this.assertAccess(t,"read"),this.run(i=>d(this,null,function*(){if((yield i.stat(t)).kind!=="file")throw new m(g.BadRequest,"目标是目录,不是文件。");return i.readFile(t)}))})}readText(e){return d(this,null,function*(){return(yield this.read(e)).text()})}write(s,r){return d(this,arguments,function*(e,t,i={}){const o=V(e,!1);this.assertAccess(o,"write"),yield this.run(a=>a.writeFile(o,t,{createDirectories:i.createDirectories!==!1,signal:i.signal})),this.host.notifyFilesChanged([le(o)])})}append(s,r){return d(this,arguments,function*(e,t,i={}){const o=V(e,!1);this.assertAccess(o,"write");const a=typeof t=="string"?new TextEncoder().encode(t):t;yield this.run(c=>d(this,null,function*(){let l=new Uint8Array;try{if((yield c.stat(o)).kind!=="file")throw new m(g.BadRequest,"目标是目录,不是文件。");l=new Uint8Array(yield(yield c.readFile(o)).arrayBuffer())}catch(u){if(u instanceof m||Le(u).code!==g.NotFound)throw u}const h=new Uint8Array(l.byteLength+a.byteLength);h.set(l),h.set(a,l.byteLength),yield c.writeFile(o,h,{createDirectories:!0,signal:i.signal})})),this.host.notifyFilesChanged([le(o)])})}mkdir(e){return d(this,null,function*(){const t=V(e,!0);t&&(yield this.run(i=>d(this,null,function*(){if(!i.createDirectory)throw Nt("创建目录");yield i.createDirectory(t)})),this.host.notifyFilesChanged([le(t)]))})}remove(i){return d(this,arguments,function*(e,t={}){const s=V(e,!1);this.assertAccess(s,"write"),yield this.run(r=>d(this,null,function*(){if(!r.remove)throw Nt("删除");yield r.remove(s,t)})),this.host.notifyFilesChanged([le(s)])})}move(e,t){return d(this,null,function*(){const i=V(e,!1),s=V(t,!1);this.assertAccess(i,"write"),this.assertAccess(s,"write"),yield this.run(r=>d(this,null,function*(){if(!r.move)throw Nt("移动");yield r.move(i,s)})),this.host.notifyFilesChanged([le(i),le(s)])})}openPreview(e){return d(this,null,function*(){return this.run(t=>d(this,null,function*(){if(t.url)return t.url(e);const i=yield t.readFile(e),s=URL.createObjectURL(i);return{url:s,release:()=>URL.revokeObjectURL(s)}}))})}dropPreview(e){e.release(),this.previews.delete(e.url),this.previewByPath.get(e.path)===e&&this.previewByPath.delete(e.path)}assertAccess(e,t){const i=this.host.sensitive.match(e,t);if(i)throw new m(g.Forbidden,dn.reasonOf(i),{reason:"sensitive_file",ruleId:i.id})}run(e){return d(this,null,function*(){var i;const t=this.host.adapter;if(!t)throw mt();try{return yield e(t)}catch(s){if(s instanceof m)throw s;const r=Le(s);throw((i=r.data)==null?void 0:i.reason)==="workspace_not_granted"&&(yield this.host.handlePermissionLost()),r}})}}const $t={mode:"readwrite"};function Vo(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 Go(n){return!!n&&typeof n=="object"&&n.name==="AbortError"}const oi=new B("[LocalWorkspace] ");class hs{constructor(e){y(this,"applicationId");y(this,"limits");y(this,"sensitive");y(this,"downloadUrlAllowlist");y(this,"allowWorkspaceWideTextSearch");y(this,"transfer");y(this,"fetch");y(this,"commandRunner");y(this,"platformSkills");y(this,"browserRuntime");y(this,"files");y(this,"store");y(this,"picker");y(this,"event",new bn(!0));y(this,"_status");y(this,"_displayName");y(this,"_adapter",null);y(this,"pendingHandle",null);y(this,"approvalHandler");y(this,"activeCalls",0);y(this,"activeCommands",0);y(this,"inflight",new Set);y(this,"_ready",Promise.resolve());y(this,"stopWatching",()=>{});y(this,"pendingChangePaths",new Set);y(this,"changeTimer");y(this,"refreshAllVisible",!1);y(this,"epoch",0);var o,a,c,l,h,u,f,p,w,_;const t=(o=e.config)!=null?o:{};this.applicationId=e.applicationId,this.store=(a=e.store)!=null?a:Sn(),this.picker=e.picker===null?void 0:(c=e.picker)!=null?c:Fo(),this.limits=Po(t.limits),this.sensitive=new dn(t.sensitiveRulesAppend),this.downloadUrlAllowlist=_n(t.downloadUrlAllowlistAppend),this.allowWorkspaceWideTextSearch=!!t.allowWorkspaceWideTextSearch,this.approvalHandler=t.onApprovalRequired;const i=(l=e.transfer)!=null?l:kn(()=>{});this.transfer={upload:(u=(h=t.transfer)==null?void 0:h.upload)!=null?u:i.upload,resolveDownload:(p=(f=t.transfer)==null?void 0:f.resolveDownload)!=null?p:i.resolveDownload};const s=(w=e.fetch)!=null?w: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=(_=t.commandRuntime)==null?void 0:_.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",this.files=new ds(this)}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,oi.log("status",{status:e,displayName:t}),this.emit("workspace:changed",{status:e,displayName:t}))}replaceAdapter(e){this._adapter!==e&&this.files.releaseAllUrls(),this._adapter=e}attachHandle(e){this.cancelFilesChanged(),this.pendingHandle=e,this.replaceAdapter(new Kt(e)),this.setStatus("granted",e.name),this.unwatchDirectory(),this.stopWatching=Uo(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=>(this.epoch+=1,this.cancelAll(),this.attachHandle(t),this.store.set(this.handleKey,{handle:t,displayName:t.name,savedAt:Date.now()}).catch(()=>{}),!0),t=>{if(Go(t))return!1;throw t})}restore(){return this._ready=this.doRestore(),this._ready}doRestore(){return d(this,null,function*(){var s,r,o;const e=this.epoch;if(!this.picker){this._adapter||this.setStatus("unsupported");return}let t;try{t=yield this.store.get(this.handleKey)}catch(a){t=void 0}if(e!==this.epoch)return;if(!(t!=null&&t.handle)){this.pendingHandle=null,this.replaceAdapter(null),this.setStatus("none",void 0);return}let i;try{i=(o=yield(r=(s=t.handle).queryPermission)==null?void 0:r.call(s,$t))!=null?o:"prompt"}catch(a){i="prompt"}if(e===this.epoch){if(i==="granted"||i==="prompt"&&(yield this.canList(t.handle))){if(e!==this.epoch)return;this.attachHandle(t.handle);return}this.pendingHandle=t.handle,this.replaceAdapter(null),this.setStatus(i==="denied"?"denied":"prompt",t.displayName)}})}canList(e){return d(this,null,function*(){const t=new Kt(e);let i;const s=new Promise(a=>{i=setTimeout(()=>a(!1),2e3)}),r=t.listEntries("").then(()=>!0).catch(()=>!1),o=yield Promise.race([r,s]);return clearTimeout(i),o})}requestPermission(){const e=this.pendingHandle;if(!(e!=null&&e.requestPermission))return Promise.resolve(!1);let t;try{t=e.requestPermission($t)}catch(i){return Promise.reject(i)}return t.then(i=>i==="granted"?(this.attachHandle(e),!0):(this.replaceAdapter(null),this.setStatus(i==="denied"?"denied":"prompt",e.name),!1))}clear(){return d(this,null,function*(){this.epoch+=1,this.cancelAll(),this.cancelFilesChanged(),this.unwatchDirectory(),this.pendingHandle=null,this.replaceAdapter(null),this.setStatus(this.picker?"none":"unsupported",void 0),yield this.store.delete(this.handleKey).catch(()=>{})})}attachFileSnapshot(e,t){var o,a,c;const i=Array.from(e),s=t||((a=(o=i[0])==null?void 0:o.webkitRelativePath)==null?void 0:a.split(/[/\\]/)[0])||((c=i[0])==null?void 0:c.name)||"工作文件夹",r=i.map(l=>({name:l.name,webkitRelativePath:l.webkitRelativePath,lastModified:l.lastModified,blob:l}));this.attachAdapter(new Mo(r,s),s)}attachAdapter(e,t=e.displayName){this.epoch+=1,this.cancelAll(),this.cancelFilesChanged(),this.unwatchDirectory(),this.pendingHandle=null,this.replaceAdapter(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=Vo(t);i===void 0?this.refreshAllVisible=!0:this.pendingChangePaths.add(i)}clearTimeout(this.changeTimer),this.changeTimer=setTimeout(()=>this.flushFilesChanged(),150)}}handlePermissionLost(){return d(this,null,function*(){const e=this.pendingHandle;if(!(e!=null&&e.queryPermission))return;const t=yield e.queryPermission($t).catch(()=>"prompt");if(t!=="granted"){if(t==="prompt"&&this._adapter)try{yield this._adapter.listEntries("");return}catch(i){if((i&&typeof i=="object"?i.name:void 0)!=="NotAllowedError")return}this.cancelAll(),this.cancelFilesChanged(),this.unwatchDirectory(),this.replaceAdapter(null),this.setStatus(t==="denied"?"denied":"prompt",e.name)}})}isDisclosureAcknowledged(){return d(this,null,function*(){try{return!!(yield this.store.get(this.disclosureKey))}catch(e){return!1}})}acknowledgeDisclosure(){return d(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._adapter instanceof He)return()=>{};if(this.activeCommands>=1)return null;this.activeCommands++;let e=!1;return()=>{e||(e=!0,this.activeCommands--)}}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(en.map(t=>[t,!0]));return{protocolVersion:"1.0",capabilities:S(b({},e),{cancellation:!0,atomicWrite:!0}),limits:b({},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){oi.report(`${e} listener failed`,i)}}}var Se=(n=>(n[n.Normal=0]="Normal",n[n.Debug=1]="Debug",n))(Se||{});function Xo(n,e,t){return d(this,null,function*(){var a;if(!e)throw new Error("session is not avalible. id is undefined");const i=Yo(t.name),s=yield n.postUploadTicket({files:[i],isv:"minio",knowledgeId:e,type:1}),o=(yield n.uploadMinioFile(s.minio,t))||((a=s.minio.fileKeys)==null?void 0:a[0]);return{url:Ko(s.minio,o),name:t.name||i,size:t.size}})}function Yo(n){const e=n.split(/[/\\]/).pop()||"",t=/\.([A-Za-z0-9]{1,16})$/.exec(e);return t?`${ie.v4()}.${t[1].toLowerCase()}`:ie.v4()}function Ko(n,e){var s;const t=(s=n.endpoints)==null?void 0:s[0];if(!t||!n.bucket||!e)throw new Error("上传没有返回文件地址。");return`${n.useSSL?"https:":typeof location!="undefined"&&location.protocol?location.protocol:"http:"}//${t}/${n.bucket}/${e}`}const ai=100,L=new B("[Session] ");var st=(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))(st||{});class En{constructor(e,t="",i,s,r,o){y(this,"_id");y(this,"_frozen",!1);y(this,"inactivating",!1);y(this,"_ready",!1);y(this,"event",new bn);y(this,"_applicationId");y(this,"_application",null);y(this,"data",null);y(this,"client",null);y(this,"messages",[]);y(this,"_loadingMessages",!1);y(this,"_loadingMessagesSize",10);y(this,"cvforceApi");y(this,"socket",null);y(this,"_promptVariables",[]);y(this,"_sessionActive",!1);y(this,"activing",!1);y(this,"_stopAnswer",!1);y(this,"_dataLoading",!1);y(this,"_dataLoaded",!1);y(this,"_mcpServers",null);this.token=e,this.lazyload=s,this.client=o||null,this._applicationId=ht(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 a;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(c=>d(this,null,function*(){this.data=c,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>d(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(c=>d(this,null,function*(){this.data=c,this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,t)})).then(()=>d(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 c=(i==null?void 0:i.name)||"新建会话";this.event.emit("data:creating",{applicationId:this._applicationId,name:c}),this.event.emit("data:loading"),this.cvforceApi.postSession(this.applicationId,{name:c,netOpen:i==null?void 0:i.netOpen,knowledgeIdList:(a=i==null?void 0:i.knowledges)==null?void 0:a.map(l=>l.id),applicationId:this._applicationId}).then(l=>d(this,null,function*(){var h;this._id=l.id,this.data=S(b({},l),{knowledges:i==null?void 0:i.knowledges}),this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this._id);try{yield(()=>d(this,null,function*(){if(i!=null&&i.knowledges)return this.setKnowledges((i==null?void 0:i.knowledges)||void 0)}))()}catch(u){L.error(u)}yield(()=>{if(i!=null&&i.promptVariables){const u=this._promptVariables.map(f=>{var w,_;const p=((_=(w=i.promptVariables)==null?void 0:w.find(v=>v.key===f.key&&v.type===f.type))==null?void 0:_.value)||"";return S(b({},f),{value:p})}).sort((f,p)=>f.key.localeCompare(p.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),((h=this.application)==null?void 0:h.type)!==x.ApplicationTypes.Agent&&(this._ready=!0,this.event.emit("ready"))}))}})}get active(){return this._sessionActive}fetchData(){return d(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=>d(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 d(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 a,c;const o=(c=(a=r.fileIds)==null?void 0:a.length)!=null?c:0;return s+(o>0?o:1)},0)>ai)throw Error(`knowledges and fileIds total count cannot exceed ${ai}`);return yield this.cvforceApi.patchSessionsId(this._applicationId,this.data.id,{knowledges:e}),this.data.knowledges=e,this.event.emit("data:updated",this.data),this.event.emit("data:updated:knowledges",{knowledges:e}),e})}validateConfigs(){if(!this._id)throw Error("session id is not defined");if(!this.data)throw Error("session data is not loaded");const e=this.promptVariables.filter(t=>t.status===x.PromptStatus.Quoted).filter(t=>!t.value);if(e.length)throw Error(`在提示词中被引用的变量值不能为空, 请检查以下变量: ${e.map(t=>t.key).join(", ")}`)}get promptVariables(){return this._promptVariables.filter(e=>!(e.type===x.PromptVariableType.User&&e.key==="query")&&!(e.type===x.PromptVariableType.System&&e.key==="datetime"))}setPromptVariables(e){return d(this,null,function*(){const t=e==null?void 0:e.map(r=>r.type?r:S(b({},r),{type:"instruction"})),i=this._promptVariables.map(r=>{var a;const o=((a=t==null?void 0:t.find(c=>c.key===r.key&&c.type===r.type))==null?void 0:a.value)||r.value;return S(b({},r),{value:o})}).sort((r,o)=>r.key.localeCompare(o.key));if(!(yield Promise.all(i.filter(r=>!(r.type===x.PromptVariableType.User&&r.key==="query")&&!(r.type===x.PromptVariableType.System&&r.key==="datetime")).map(r=>{if(!this.data)throw Error("session data is not loaded");if(!(!r.id||!r.key))return this.cvforceApi.patchApplicationIdSessionpromptVariablesId(this._applicationId,this.data.id,r.id,{value:r.value})})).then(()=>!0).catch(r=>!1)))return!1;if(!this.data)throw Error("session data is not loaded");return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,this.data.id),this.event.emit("data:updated",this.data),this.event.emit("data:updated:promptVariables",{promptVariables:this._promptVariables}),this._promptVariables})}get netOpen(){if(!this.data)throw Error("session data is not loaded");return this.data.netOpen||!1}setNetOpen(e){return d(this,null,function*(){var t,i,s;if(L.log("setNetOpen:",e),L.log("application arrange setting value: ",(t=this._application)==null?void 0:t.arrange[0].enableNetOpen),((i=this._application)==null?void 0:i.type)===x.ApplicationTypes.Agent){L.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((s=this._application)==null?void 0:s.arrange[0].enableNetOpen)===!1){L.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,L.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}getService(){return es(exports.configuration.apiRoot,this.token,(e,t)=>{const i=new Error("data request error",{cause:{status:e,message:t}});L.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 d(this,arguments,function*(e={}){var i,s;const t={pageSize:this._loadingMessagesSize};if(this._id){e=b(b({},t),e),this.event.emit("history:loading"),L.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),L.log("history:moreloading",e)),this._loadingMessages=!0;const r=yield this.cvforceApi.getChatHistorySessionId(this._applicationId,this._id,e),o=r.map((c,l)=>{var f,p;let h=[],u;return typeof((f=c.agentHistoryList)==null?void 0:f.agentList)=="string"&&(h=JSON.parse(c.agentHistoryList.agentList).reduce((_,v)=>(_[v.data.step-1]||(_[v.data.step-1]=[]),_[v.data.step-1].push(v),_),[])),l===r.length-1&&(u=(p=this.data)==null?void 0:p.lastRelatedQuestion),S(b({},c),{actions:h,relatedQuesion:u,fromHistory:!0})});if(!e.endTime&&!e.startTime){const c=this.messages[this.messages.length-1];c&&!c.relatedQuesion&&(c.relatedQuesion=(i=this.data)==null?void 0:i.lastRelatedQuestion),this.messages=[...o,...this.messages]}else if(e.endTime&&!e.startTime){const c=this.messages.findIndex(l=>l.ts===e.endTime);this.messages.splice(0,c+1),this.messages=[...o,...this.messages]}else if(!e.endTime&&e.startTime){const c=this.messages.findLastIndex(l=>l.ts===e.endTime);this.messages.splice(c,this.messages.length-c-1),this.messages=[...this.messages,...o]}else{const c=this.messages.findIndex(h=>h.ts===e.endTime),l=this.messages.findLastIndex(h=>h.ts===e.endTime);this.messages.splice(c,l-c+1,...o)}const a=this.messages[this.messages.length-1];return a&&!a.relatedQuesion&&(a.relatedQuesion=(s=this.data)==null?void 0:s.lastRelatedQuestion),this.event.emit("history:moreloaded",o),L.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 L.error(r),this.event.emit("error",r),!1}})}rename(e){return d(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}),L.log("data:updated",this.messages),this.event.emit("data:updated",this.data),this.event.emit("data:updated:name",{name:e}),!0})}pushMessage(e){return d(this,null,function*(){this.messages.push(e),L.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=>d(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),L.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.data})).then(()=>d(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 d(this,null,function*(){return yield this.reloadSessionInfo(),this.socket?(this.inactivate(!0),this.activate()):(this.inactivate(!0),this.activate())})}delete(){return d(this,null,function*(){if(!this.id){const e=new Error("session id is not defined");return L.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 d(this,null,function*(){var t;if(this.activing)return new Promise(i=>{this.addEventListener("activated",()=>{i(!0)},!0)});if(!this._id)throw Error("session is not avalible. id is undefined");L.log("activate",this._id),this.activing=!0;const e=this._id;return this._dataLoading=!0,this._dataLoaded=!1,this.data=yield this.cvforceApi.getSession(this.applicationId,e).then(i=>d(this,null,function*(){return this._promptVariables=yield this.cvforceApi.getApplicationIdSessionIdPromptVariables(this.applicationId,e),i})),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,(t=this.socket)!=null&&t.connected||(this.frozen=!0),yield this.prepareConnection(),this.event.emit("activated",this.socket),L.log("activated",this._id),this._sessionActive=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?(L.log("inactivate",this.id),this._frozen?(e||(this.inactivating=!0),this.activing=!1,!0):(this.socket.close(),this.socket=null,this.event.emit("inactivated"),this._sessionActive=!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}upload(e){return d(this,null,function*(){if(!this._id)throw Error("session is not avalible. id is undefined");return Xo(this.cvforceApi,this._id,e)})}send(i){return d(this,arguments,function*(e,t={stream:exports.configuration.stream}){var w,_;try{this.validateConfigs()}catch(v){L.report(v)}const{stream:s=exports.configuration.stream,referenceFirst:r=!1}=t,o=e.uuid||ie.v4(),a=((w=e.text)==null?void 0:w.trim())||"",c=e.files||[],l=e.fileIds,h=e.imageContent;if(!a&&!c.length&&!(l!=null&&l.length)){const v=new Error("failed at sending empty content");return L.error(v),this.event.emit("error",v),!1}if(!this._id){const v=new Error("session id is not defined");return L.error(v),this.event.emit("error",v),!1}if(this.frozen){const v=new Error("session is frozen");return L.error(v),this.event.emit("error",v),!1}this.frozen=!0,this._stopAnswer=!1,L.log("send",{sessionId:this._id,stream:s,contentLength:a.length,fileCount:c.length,fileIdCount:(_=l==null?void 0:l.length)!=null?_:0});const u={sessionId:this.id,role:2,content:a,messageId:o,reference:[],searchReference:[],messageTime:"",files:c,imageContent:h},f={content:a,stream:s,requestId:o,fileIds:l,referenceFirst:r,imageContent:h};this.pushMessage(u),this.event.emit("question:content",a);const p=v=>d(this,null,function*(){if(v.role===x.ChatMessageRole.Robot){this.removeEventListener("answer:finish",p);try{switch(this._id&&v.content&&v.index&&v.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:v.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:v.content})),yield this.fillMessageReference(v),v.code){case 11915:v.content="请您换个问题问我吧~",v.index=-1,v.isSensitive=!0,v.isLoading=!1,v.sessionId=this._id||"",this.event.emit("message:error",v);break;case 11916:v.content="尊敬的用户您好,让我们换个话题再聊聊吧。",v.index=-1,v.isSensitive=!0,v.isLoading=!1,v.sessionId=this._id||"",this.event.emit("message:error",v);break;case 200:v.index=-1,v.isLoading=!1;break;default:v.content=v.message||"未知错误",v.isLoading=!1,v.index=-1,this.event.emit("message:error",v)}this.getRelatedQuesion(v),v.isLoading=!1;let A=this.messages[this.messages.length-1];if(A&&A.role===x.ChatMessageRole.Robot){const E=b(b({},A),v);this.messages[this.messages.length-1]=E,this.event.emit("message:updated",E)}else this.pushMessage(v)}finally{this.frozen=!1}}});return this.addEventListener("answer:finish",p),this.sendQuestion(f,S(b({},t),{stream:s,referenceFirst:r})),u})}currentUserQuestion(){for(let e=this.messages.length-1;e>=0;e-=1){const t=this.messages[e];if(t.role===x.ChatMessageRole.User)return t.content||""}return""}getRelatedQuesion(e){return d(this,null,function*(){var a,c;const t=(a=this.application)==null?void 0:a.arrange[0];if(!e.content||e.isSensitive||e.code!==200)return L.log("related:skip",{code:e.code,sensitive:!!e.isSensitive,hasContent:!!e.content}),e;const i=po(t==null?void 0:t.recommendQuestionOpen,t==null?void 0:t.relatedQuestionApp,e.content,this.currentUserQuestion());if(i===null)return L.log("related:skip",{recommendQuestionOpen:t==null?void 0:t.recommendQuestionOpen}),e;L.log("related:request",i),this.event.emit("message:relatedQuesion:loading",e);const s=yield this.cvforceApi.postGeneques({content:i}).catch(l=>(L.error("related:failed",l),null));if(L.log("related:response",s),!s){const l=[],h=S(b({},e),{relatedQuesion:l,index:-3,isLoading:!1});return this.event.emit("message:relatedQuesion:loaded",{relatedQuesion:l}),this.event.emit("message:updated",h),h}const r=(c=s.content)==null?void 0:c.split("*").map(uo).map(fo).filter(l=>!!l);e.relatedQuesion=r,e.index=-3,e.isLoading=!1;const o=S(b({},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 d(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)=>b(b({},i),t[s]))}catch(t){L.error("Failed to fill message reference:",t)}return this.event.emit("message:updated",e),e})}answerAgain(){return d(this,arguments,function*(e={stream:exports.configuration.stream}){var c;const t=this.messages[this.messages.length-1];if(!t)throw Error("message list is empty");this.frozen=!0,this._stopAnswer=!1,L.log("answerAgain",{sessionId:this._id,stream:(c=e.stream)!=null?c:exports.configuration.stream});const{stream:i=exports.configuration.stream}=e;let s;t.role!==x.ChatMessageRole.User&&(s=e.oldMessageId||t.messageId,this.messages.splice(this.messages.length-1,1),this.event.emit("message:remove",t),this.event.emit("history:remove",t));const r=this.messages[this.messages.length-1],o={content:r.content,fileIds:r.fileIds,requestId:r.messageId,stream:i,oldMessageId:s},a=l=>d(this,null,function*(){if(l.role===x.ChatMessageRole.Robot&&l.index===-1)try{switch(this._id&&l.content&&l.index&&l.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:l.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:l.content})),yield this.fillMessageReference(l),l.code){case 11915:l.content="请您换个问题问我吧~",l.index=-1,l.isSensitive=!0,l.isLoading=!1,l.sessionId=this._id||"",this.event.emit("message:error",l);break;case 11916:l.content="尊敬的用户您好,让我们换个话题再聊聊吧。",l.index=-1,l.isSensitive=!0,l.isLoading=!1,l.sessionId=this._id||"",this.event.emit("message:error",l);break;case 200:l.index=-1,l.isLoading=!1;break;default:l.content=l.message||"未知错误",l.isLoading=!1,l.index=-1,this.event.emit("message:error",l)}this.getRelatedQuesion(l)}finally{this.removeEventListener("message:content",a),this.frozen=!1}});this.addEventListener("message:content",a),this.sendQuestion(o,S(b({},e),{stream:i}))})}setTop(e){return d(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:ie.v4(),isLoading:!1,index:-2,messageTime:Zt(new Date).format("YYYY-MM-DD HH:ss:mm"),content:"",role:x.ChatMessageRole.System,sessionId:this.id||"",reference:[],searchReference:[]};if(e&&!e.messageId){if(e.index===-2)return;if(e.actions){const s=e.actions[((i=e.actions)==null?void 0:i.length)-1];if(s){const r=s[s.length-1];if(r&&(r.type==="BEFORE_CALL"||r.type==="FUNCTION_CALL")){const{pluginName:o,pluginCode:a,funcCode:c,funcName:l}=r.data;s.push({data:{pluginName:o,pluginCode:a,funcCode:c,funcName:l,step:r.data.step+1},type:"ABORT"}),this.event.emit("message:action",{messageId:e.messageId,action:s})}}}e=b(b({},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 c=s.choices[0];t.reasoningContent=(t.reasoningContent||"")+((o=c.delta.reasoningContent)!=null?o:"")}if(i==="thinkingOver"){t.thinkingStatus="end";const a=s.thinkingSecs;t.thinkingSecs=a}if(i==="text"){const c=s.choices[0];t.content=(t.content||"")+c.delta.content}if(i==="reference"&&(t.reference=s),i==="updateSession"&&s&&this.data&&(this.data=b(b({},this.data),s),this.event.emit("data:updated",this.data)),i==="result"){const a=s.messageId,c=s.llmModel,l=s.messageTime;t.messageId=a,t.llmModel=c,t.messageTime=l}i==="over"&&(t.index=-1),e.code!=null&&(t.code=e.code,t.message=e.message)}getArtifacts(){return d(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 d(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 ue=new Map,Jo=2e4;function Qo(n){if(typeof AbortSignal!="undefined"&&typeof AbortSignal.timeout=="function"){const e=AbortSignal.timeout(Jo);if(!n)return e;const t=new AbortController,i=()=>t.abort();return e.addEventListener("abort",i,{once:!0}),n.addEventListener("abort",i,{once:!0}),t.signal}return n}function qe(n){return`${n.url}
371
+ ${JSON.stringify(n.headers)}`}function Zo(n){const e=n.trim();if(!e)return{};if(e.startsWith("{")||e.startsWith("["))return JSON.parse(e);const t=e.split(/\n\n/);for(let i=t.length-1;i>=0;i-=1){const s=t[i].split(`
372
372
  `).filter(r=>r.startsWith("data:")).map(r=>r.slice(5).trim()).join(`
373
- `);if(s.startsWith("{")||s.startsWith("["))return JSON.parse(s)}throw new Error("MCP 响应不是 JSON")}function Yo(n){if(typeof n=="string")return n;if(!n||typeof n!="object")return JSON.stringify(n!=null?n:"");const e=n.content;return Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?t.text:JSON.stringify(t)).join(`
374
- `):JSON.stringify(n)}function Ko(n){return d(this,null,function*(){if(!(n.headers.get("content-type")||"").includes("text/event-stream")||!n.body)return n.text();const t=n.body.getReader(),i=new TextDecoder;let s="";try{for(;s.length<2e6;){const{done:r,value:o}=yield t.read();if(r)break;s+=i.decode(o,{stream:!0});const a=s.split(/\n\n/).filter(c=>/^\s*data:/m.test(c));if(a.length>0)return a[a.length-1]}return s}finally{yield t.cancel().catch(()=>{})}})}function lt(n,e,t,i,s){return d(this,null,function*(){const r=E(b({},n.headers),{"content-type":"application/json",accept:"application/json, text/event-stream"});t!=null&&t.id&&(r["mcp-session-id"]=t.id),t!=null&&t.protocol&&(r["mcp-protocol-version"]=t.protocol);const o=yield s(n.url,{method:"POST",headers:r,body:JSON.stringify(e),signal:Go(i)}),a=yield Ko(o);if(!o.ok)throw new Error(`MCP HTTP ${o.status}: ${a.slice(0,300)}`);const c=Xo(a),l=o.headers.get("mcp-session-id");return t&&l&&(t.id=l),c})}function dt(n){const e=n.error;if(!e||typeof e!="object")return;const t=e.message;return typeof t=="string"&&t?t:"MCP 调用失败"}function Jo(n){const e=n instanceof Error?n.message:String(n);return/session/i.test(e)||e.includes("MCP HTTP 404")}function nt(n,e,t){return d(this,null,function*(){const i=Ue(n),s=ue.get(i);if(s!=null&&s.id)return s;const r={protocol:"2024-11-05",nextId:1},o=yield lt(n,{jsonrpc:"2.0",id:r.nextId,method:"initialize",params:{protocolVersion:r.protocol,capabilities:{},clientInfo:{name:"bot-client-sdk",version:"1.0.0"}}},r,e,t);r.nextId+=1;const a=dt(o);if(a)throw new Error(a);const c=o.result;if(c&&typeof c=="object"){const l=c.protocolVersion;typeof l=="string"&&l&&(r.protocol=l)}return yield lt(n,{jsonrpc:"2.0",method:"notifications/initialized"},r,e,t),ue.set(i,r),r})}function Qo(t){return d(this,arguments,function*(n,e=fetch){var a;const i=yield nt(n,void 0,e),s=yield lt(n,{jsonrpc:"2.0",id:i.nextId,method:"tools/list",params:{}},i,void 0,e);i.nextId+=1;const r=dt(s);if(r)throw new Error(r);const o=s.result;return((a=o==null?void 0:o.tools)!=null?a:[]).filter(c=>c.name).map(c=>({name:c.name,description:c.description||"",inputSchema:c.inputSchema||{type:"object",properties:{}}}))})}function Zo(r,o,a,c){return d(this,arguments,function*(n,e,t,i,s=fetch){const l=Ue(n);let h=yield nt(n,i,s);const u=()=>lt(n,{jsonrpc:"2.0",id:h.nextId,method:"tools/call",params:{name:e,arguments:t&&typeof t=="object"?t:{}}},h,i,s);let f;try{f=yield u(),h.nextId+=1}catch(y){if(!Jo(y))throw y;ue.delete(l),h=yield nt(n,i,s),f=yield u(),h.nextId+=1}let p=dt(f);if(p&&/session/i.test(p)&&(ue.delete(l),h=yield nt(n,i,s),f=yield u(),h.nextId+=1,p=dt(f)),p)throw new Error(p);return Yo(f.result)})}function si(n){const e=new Set(n.map(t=>Ue(t)));for(const t of ue.keys())e.has(t)||ue.delete(t)}function ea(n,e){const t=Ue(n);e.some(i=>Ue(i)===t)||ue.delete(t)}const be=new q("[LocalMcp] ",!0);function ta(n){const e=n==null?void 0:n.mcps;return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"&&t.runtime==="local"&&t.id):[]}function na(n,e,t){return n==null||n.includes(e)?!0:!!t&&n.includes(t)}function ia(n){if(!n||typeof n!="object")return{};const e={};for(const[t,i]of Object.entries(n))typeof i=="string"&&(e[t]=i);return e}function sa(n){var o,a;if(!n||typeof n!="object")return null;const e=n;if(typeof e.code=="number"&&e.code!==200)return null;const t=e.data&&typeof e.data=="object"?e.data:e,i=typeof t.code=="string"?t.code:"",s=i?(o=t.mcpServers)==null?void 0:o[i]:void 0,r=typeof(s==null?void 0:s.url)=="string"?s.url:void 0;return{code:i,deployType:typeof((a=t.deployConfig)==null?void 0:a.type)=="string"?t.deployConfig.type:void 0,url:r,headers:ia(s==null?void 0:s.headers)}}function ra(s,r,o){return d(this,arguments,function*(n,e,t,i=fetch){const a=n.replace(/\/$/,""),c=e.startsWith("Bearer ")?e:`Bearer ${e}`,l=yield i(`${a}/mcpmgr/v1/mcpserver/${encodeURIComponent(t)}`,{headers:{Authorization:c}}),h=yield l.json().catch(()=>null);if(!l.ok)throw new Error(`MCP 详情 HTTP ${l.status}`);const u=sa(h);if(!u)throw new Error("MCP 详情不可用");return u})}function oa(n){return/^[A-Za-z][A-Za-z0-9.+-]* /.test(n)?n:`Bearer ${n}`}function aa(n,e){if(!(e!=null&&e.token))return b({},n);const t={};for(const[i,s]of Object.entries(n))i.toLowerCase()!=="authorization"&&(t[i]=s);return t.Authorization=oa(e.token),t}function ca(n,e,t){const i=n.find(s=>!e.has(s)&&t(s));return i&&e.add(i),i}function la(n,e,t){return ca(n,e,i=>i.code===t||i.id===t)}function da(n,e,t){var r;const i=n==null?void 0:n.mcpServers;if(!i)return;const s=(r=i[t])!=null?r:i[e];return(s==null?void 0:s.url)||void 0}function ha(n,e){return(t,i,s)=>{const r=io(n);if(!r){i({code:500,message:"缺少 MCP 地址"});return}Zo(r,n,t,s==null?void 0:s.signal,e).then(o=>i({code:0,message:"ok",data:o})).catch(o=>{i({code:500,message:o instanceof Error?o.message:String(o)})})}}function ua(n){return d(this,null,function*(){var u,f;const e=(u=n.fetchImpl)!=null?u:fetch,t=n.initMcp?Object.keys((f=n.initMcp.mcpServers)!=null?f:{}):null,i=ta(n.arrange),s=Tt().revision,r=()=>Tt().revision!==s||(n.isCurrent?!n.isCurrent():!1);if(!i.length){if(r())return;be.log("编排里没有 runtime=local 的 MCP,不发送 register_client_mcp_tools"),Kn([]),si([]),je();return}const o=[...Tt().servers],a=new Set,c=yield Promise.all(i.map(p=>d(this,null,function*(){var A,I;const y=p.id;let w;const _=()=>{w&&(a.delete(w),w=void 0)};try{const S=yield ra(n.apiRoot,n.token,y,e);if(!na(t,y,S.code))return null;w=S.code?la(o,a,S.code):void 0;const L=(I=(A=w==null?void 0:w.url)!=null?A:da(n.initMcp,y,S.code))!=null?I:S.url;if(S.deployType!=="streamableHttp"||!S.code||!L)return be.log("skip local mcp",y),_(),null;const j={code:S.code,url:L,headers:aa(S.headers,w)},$=yield Qo(j,e);return $.length?{code:S.code,url:j.url,binding:j,tools:$}:(_(),null)}catch(S){return _(),be.error("local mcp failed",y,S instanceof Error?S.message:String(S)),null}})));if(r()){const p=so();for(const y of c)y&&ea(y.binding,p);return}const l={},h=[];for(const p of c)if(p){l[p.code]={type:"streamableHttp",url:p.url,tools:p.tools};for(const y of p.tools)h.push({name:y.name,binding:p.binding,handler:ha(y.name,e)})}if(Kn(h),si(h.map(p=>p.binding)),je(),!Object.keys(l).length||!n.socket){be.log("没有可注册的本地 MCP 工具,不发送 register_client_mcp_tools");return}be.log("发送 register_client_mcp_tools",Object.entries(l).map(([p,y])=>`${p}: ${y.tools.map(w=>w.name).join(", ")}`).join("; ")),n.socket.emit("register_client_mcp_tools",{mcpServers:l},p=>{const y=p&&typeof p=="object"?p.code:void 0;typeof y=="number"&&y!==200&&be.error("register_client_mcp_tools",y)})})}const z=new q("[AgentSession] ");function ri(n){if(typeof n!="string")return n;const e=n.trim();if(e)try{return JSON.parse(e)}catch(t){return n}}function oi(n){return n==null||n===""||typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function fa(n,e){const t=ri(n==null?void 0:n.query);if(!oi(t))return t;const i=ri(e);return oi(i)&&t!=null?t:i}class pa extends _n{constructor(t,i="",s,r,o,a){super(t,i,s,r,o,a);v(this,"inflightCalls",new Set);v(this,"localMcpTicket",0);v(this,"stopLocalMcpUpdates")}prepareConnection(){return new Promise(t=>d(this,null,function*(){this.socket&&t(!0);const i={version:"1.0",stream:JSON.stringify(exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?ke.Debug:ke.Normal},s=new URL(exports.configuration.apiRoot),r=yield _s.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:i,transports:["websocket"]});r.on("connect",()=>{z.log("socket:connect"),this.event.emit("socket:connect"),r.emit("init")}),r.on("disconnect",()=>{z.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),r.on("ready",o=>{if(o.code===200){z.log("ready");const a=exports.configuration.debug?ke.Debug:ke.Normal;a===ke.Debug&&o.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),this.registerLocalMcp(),t(!0)}else{this._ready&&(this._ready=!1);const a=new Error(De.SocketConnectionFailed);z.error("error",a),this.event.emit("error",a),t(!1)}}),r.on("action",(o,a)=>d(this,null,function*(){var w;if(this._stopAnswer||!this.id)return;const{type:c,data:{runnerIsClient:l,pluginCode:h,funcCode:u,parameters:f,requestBody:p}}=o,y=this.messages[this.messages.length-1];if(!y.messageId)y.actions||(y.actions=[]),y.actions[o.data.step-1]||(y.actions[o.data.step-1]=[]),y.actions[o.data.step-1].push(o),this.event.emit("message:action",{messageId:y.messageId,action:o}),this.event.emit("message:updated",y);else{const _={messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[o]],comment:{isAgree:0},isReplying:!0};this.pushMessage(_),this.event.emit("message:action",{messageId:_.messageId,action:o})}if(this.inactivating){const _=new Error(De.Inactive);z.warn("error",_),this.event.emit("error",_)}else if(c==="FUNCTION_CALL"&&l){z.log(`calling function ${u} of plugin ${h} with argument:
375
- ${JSON.stringify(f)}`);const _=(w=exports.configuration.plugins)==null?void 0:w[h];if(!_){a({code:404,message:"没有找到插件。"});return}const A=_[u];if(typeof A!="function"){a({code:404,message:"没有找到插件方法。"});return}const I=fa(f,p);this.invokeClientPlugin(A,I,a,{requestId:o.requestId,pluginCode:h,functionCode:u})}})),r.on("answer",o=>{if(!this._stopAnswer)if(o.data.code!==200&&(o.data.index=-1),o.data.stream||o.data.stream===void 0){let a=this.messages[this.messages.length-1];if(a&&a.role===x.ChatMessageRole.Robot)this.handleStreamAnswer(o.data,a),this.messages[this.messages.length-1]=a,this.event.emit("message:content",a),this.event.emit("message:updated",a),a.index===-1&&(a.isReplying=!1,this.event.emit("answer:finish",a));else{const c={content:"",role:x.ChatMessageRole.Robot,reference:[],searchReference:[],messageId:"",sessionId:this.id,messageTime:Kt(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""};this.handleStreamAnswer(o.data,c),this.pushMessage(c),this.event.emit("message:content",c),c.index===-1&&(c.isReplying=!1,this.event.emit("answer:finish",c))}}else if(o.data.updateSession&&this.data&&(this.data=b(b({},this.data),o.data.updateSession),this.event.emit("data:updated",this.data)),o.data.index===-1){let a=this.messages[this.messages.length-1];if(a&&!a.messageId)a=b(b({},a),o.data),this.event.emit("message:content",a),this.event.emit("message:updated",a),this.event.emit("answer:finish",a);else{const c=b({messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.data);this.event.emit("message:content",c),this.pushMessage(c),this.event.emit("answer:finish",c)}}else{let a=this.messages[this.messages.length-1];a&&!a.messageId?(a=b(b({},a),o.data),this.messages[this.messages.length-1]=a,this.event.emit("message:content",a),this.event.emit("message:updated",a)):(this.pushMessage(b({messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.data)),this.event.emit("message:content",o.data))}}),r.on("reference",o=>d(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const f=new Error(De.IdUndefined);z.error(f),this.event.emit("error",f),this.frozen=!1;return}const{type:a,data:c,requestId:l}=o,h=this.messages.findIndex(f=>f.messageId===l&&f.role===x.ChatMessageRole.User);if(h<0)return;const u=h+1;if(u>=this.messages.length){const f={messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0};this.pushMessage(f)}a==="KG"?(this.messages[u]=E(b({},this.messages[u]),{reference:c.knowledgeReference}),yield this.fillMessageReference(this.messages[u]),this.event.emit("message:reference",c.knowledgeReference),this.event.emit("message:updated",this.messages[u])):a==="WEB_SEARCH"&&(this.messages[u]=E(b({},this.messages[u]),{searchReference:c.knowledgeReference}),this.event.emit("message:searchreference",c.searchReference),this.event.emit("message:updated",this.messages[u]))})),this.socket=r,r.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((t,i)=>{if(!this.socket){i("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,s=>{s.code===200?(Object.keys(s.data).forEach(r=>{s.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",s.data[r])}),t(!0)):(console.error("MCP Server 注册失败。",s),i(s))})}):Promise.resolve(!0)}registerLocalMcp(){var s,r;const t=this.socket;if(!t)return;ns(),this.stopLocalMcpUpdates||(this.stopLocalMcpUpdates=bo(()=>this.registerLocalMcp()));const i=++this.localMcpTicket;ua({arrange:(r=(s=this.application)==null?void 0:s.arrange)==null?void 0:r[0],initMcp:exports.configuration.mcp,apiRoot:exports.configuration.apiRoot,token:this.token,socket:t,isCurrent:()=>i===this.localMcpTicket}).catch(o=>{z.error("local mcp",o instanceof Error?o.message:String(o))})}addMcpServers(t){return d(this,null,function*(){return this.ready?this.socket?new Promise((i,s)=>{this.socket&&this.socket.emit("add_mcp_servers",t,r=>{r.code===200?(Object.keys(r.data).forEach(o=>{r.data[o].code!==200&&console.error(o,"MCP Server 注册失败。",r.data[o])}),i(!0)):(console.error("MCP Server 注册失败。",r),s(r))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return d(this,null,function*(){return this.ready?this.socket?new Promise((t,i)=>{this.socket&&this.socket.emit("list_mcp_servers",s=>{s.code===200?t(s.data):i(s)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(t,i){return d(this,null,function*(){var r,o,a;this.convertKnowledgesToChatFormat(this.knowledges);let s=E(b({},t),{promptVariables:this.promptVariables.filter(c=>c.type===x.PromptVariableType.User).reduce((c,l)=>E(b({},c),{[l.key]:l.value}),{}),systemPromptVariables:this.promptVariables.filter(c=>c.type===x.PromptVariableType.System).reduce((c,l)=>E(b({},c),{[l.key]:l.value}),{}),knowledges:(r=this.knowledges)==null?void 0:r.map(c=>c.id),enableTitleSummary:this.resolveEnableTitleSummary()});if(!this.active){if(yield this.activate(),!this.socket){const c=new Error(De.SocketConnectionFailed);return z.warn("error",c),this.event.emit("error",c),!1}(o=this.socket)==null||o.emit("question",s);return}(a=this.socket)==null||a.emit("question",s)})}invokeClientPlugin(t,i,s,r){const o=new AbortController;this.inflightCalls.add(o);let a=!1;const c=(...h)=>{a||(a=!0,this.inflightCalls.delete(o),!(this._stopAnswer||o.signal.aborted)&&s(...h))},l={requestId:r.requestId||ne.v4(),applicationId:this._applicationId,sessionId:this.id,pluginCode:r.pluginCode,functionCode:r.functionCode,signal:o.signal};try{const h=t(i,c,l);h&&typeof h.catch=="function"&&h.catch(u=>{z.error("client plugin failed",u),c({code:500,message:"客户端插件执行失败。"})})}catch(h){z.error("client plugin failed",h),c({code:500,message:"客户端插件执行失败。"})}}abortClientPluginCalls(){const t=Array.from(this.inflightCalls);this.inflightCalls.clear(),t.forEach(i=>i.abort())}stopAnswer(){var t;this.abortClientPluginCalls(),(t=this.socket)==null||t.emit("stop_answer")}inactivate(t=!1){return this.abortClientPluginCalls(),super.inactivate(t)}destroy(){var t;return(t=this.stopLocalMcpUpdates)==null||t.call(this),this.stopLocalMcpUpdates=void 0,this.abortClientPluginCalls(),super.destroy()}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}function ma(n,e){return d(this,null,function*(){const t=n.getReader();let i;for(;!(i=yield t.read()).done;)e(i.value)})}function ga(n){let e,t,i,s=!1,r;return function(a){e===void 0?(e=a,t=0,i=-1,r=!1):e=wa(e,a);const c=e.length;let l=0;for(;t<c;){s&&(e[t]===10&&(l=++t),s=!1);let h=-1;for(;t<c&&h===-1;++t)switch(e[t]){case 58:i===-1&&(i=t-l);break;case 13:s=!1,t+4<c&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(r=!0);case 10:h=t;break}if(h===-1)break;n(e.subarray(l,h),i,r),l=t,i=-1,r=!1}l===c?e=void 0:l!==0&&(e=e.subarray(l),t-=l)}}function ya(n,e,t){let i=ai();const s=new TextDecoder;return function(o,a,c){if(o.length===0)t==null||t(i),i=ai();else if(a>0){const l=s.decode(o.subarray(0,a)),h=a+(o[a+1]===32?2:1);let u=s.decode(o.subarray(h));switch(c&&(u+=`
373
+ `);if(s.startsWith("{")||s.startsWith("["))return JSON.parse(s)}throw new Error("MCP 响应不是 JSON")}function ea(n){if(typeof n=="string")return n;if(!n||typeof n!="object")return JSON.stringify(n!=null?n:"");const e=n.content;return Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&typeof t.text=="string"?t.text:JSON.stringify(t)).join(`
374
+ `):JSON.stringify(n)}function ta(n){return d(this,null,function*(){if(!(n.headers.get("content-type")||"").includes("text/event-stream")||!n.body)return n.text();const t=n.body.getReader(),i=new TextDecoder;let s="";try{for(;s.length<2e6;){const{done:r,value:o}=yield t.read();if(r)break;s+=i.decode(o,{stream:!0});const a=s.split(/\n\n/).filter(c=>/^\s*data:/m.test(c));if(a.length>0)return a[a.length-1]}return s}finally{yield t.cancel().catch(()=>{})}})}function ut(n,e,t,i,s){return d(this,null,function*(){const r=S(b({},n.headers),{"content-type":"application/json",accept:"application/json, text/event-stream"});t!=null&&t.id&&(r["mcp-session-id"]=t.id),t!=null&&t.protocol&&(r["mcp-protocol-version"]=t.protocol);const o=yield s(n.url,{method:"POST",headers:r,body:JSON.stringify(e),signal:Qo(i)}),a=yield ta(o);if(!o.ok)throw new Error(`MCP HTTP ${o.status}: ${a.slice(0,300)}`);const c=Zo(a),l=o.headers.get("mcp-session-id");return t&&l&&(t.id=l),c})}function ft(n){const e=n.error;if(!e||typeof e!="object")return;const t=e.message;return typeof t=="string"&&t?t:"MCP 调用失败"}function na(n){const e=n instanceof Error?n.message:String(n);return/session/i.test(e)||e.includes("MCP HTTP 404")}function rt(n,e,t){return d(this,null,function*(){const i=qe(n),s=ue.get(i);if(s!=null&&s.id)return s;const r={protocol:"2024-11-05",nextId:1},o=yield ut(n,{jsonrpc:"2.0",id:r.nextId,method:"initialize",params:{protocolVersion:r.protocol,capabilities:{},clientInfo:{name:"bot-client-sdk",version:"1.0.0"}}},r,e,t);r.nextId+=1;const a=ft(o);if(a)throw new Error(a);const c=o.result;if(c&&typeof c=="object"){const l=c.protocolVersion;typeof l=="string"&&l&&(r.protocol=l)}return yield ut(n,{jsonrpc:"2.0",method:"notifications/initialized"},r,e,t),ue.set(i,r),r})}function ia(t){return d(this,arguments,function*(n,e=fetch){var a;const i=yield rt(n,void 0,e),s=yield ut(n,{jsonrpc:"2.0",id:i.nextId,method:"tools/list",params:{}},i,void 0,e);i.nextId+=1;const r=ft(s);if(r)throw new Error(r);const o=s.result;return((a=o==null?void 0:o.tools)!=null?a:[]).filter(c=>c.name).map(c=>({name:c.name,description:c.description||"",inputSchema:c.inputSchema||{type:"object",properties:{}}}))})}function sa(r,o,a,c){return d(this,arguments,function*(n,e,t,i,s=fetch){const l=qe(n);let h=yield rt(n,i,s);const u=()=>ut(n,{jsonrpc:"2.0",id:h.nextId,method:"tools/call",params:{name:e,arguments:t&&typeof t=="object"?t:{}}},h,i,s);let f;try{f=yield u(),h.nextId+=1}catch(w){if(!na(w))throw w;ue.delete(l),h=yield rt(n,i,s),f=yield u(),h.nextId+=1}let p=ft(f);if(p&&/session/i.test(p)&&(ue.delete(l),h=yield rt(n,i,s),f=yield u(),h.nextId+=1,p=ft(f)),p)throw new Error(p);return ea(f.result)})}function ci(n){const e=new Set(n.map(t=>qe(t)));for(const t of ue.keys())e.has(t)||ue.delete(t)}function ra(n,e){const t=qe(n);e.some(i=>qe(i)===t)||ue.delete(t)}const be=new B("[LocalMcp] ");function oa(n){const e=n==null?void 0:n.mcps;return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"&&t.runtime==="local"&&t.id):[]}function aa(n,e,t){return n==null||n.includes(e)?!0:!!t&&n.includes(t)}function ca(n){if(!n||typeof n!="object")return{};const e={};for(const[t,i]of Object.entries(n))typeof i=="string"&&(e[t]=i);return e}function la(n){var o,a;if(!n||typeof n!="object")return null;const e=n;if(typeof e.code=="number"&&e.code!==200)return null;const t=e.data&&typeof e.data=="object"?e.data:e,i=typeof t.code=="string"?t.code:"",s=i?(o=t.mcpServers)==null?void 0:o[i]:void 0,r=typeof(s==null?void 0:s.url)=="string"?s.url:void 0;return{code:i,deployType:typeof((a=t.deployConfig)==null?void 0:a.type)=="string"?t.deployConfig.type:void 0,url:r,headers:ca(s==null?void 0:s.headers)}}function da(s,r,o){return d(this,arguments,function*(n,e,t,i=fetch){const a=n.replace(/\/$/,""),c=e.startsWith("Bearer ")?e:`Bearer ${e}`,l=yield i(`${a}/mcpmgr/v1/mcpserver/${encodeURIComponent(t)}`,{headers:{Authorization:c}}),h=yield l.json().catch(()=>null);if(!l.ok)throw new Error(`MCP 详情 HTTP ${l.status}`);const u=la(h);if(!u)throw new Error("MCP 详情不可用");return u})}function ha(n){return/^[A-Za-z][A-Za-z0-9.+-]* /.test(n)?n:`Bearer ${n}`}function ua(n,e){if(!(e!=null&&e.token))return b({},n);const t={};for(const[i,s]of Object.entries(n))i.toLowerCase()!=="authorization"&&(t[i]=s);return t.Authorization=ha(e.token),t}function fa(n,e,t){const i=n.find(s=>!e.has(s)&&t(s));return i&&e.add(i),i}function pa(n,e,t){return fa(n,e,i=>i.code===t||i.id===t)}function ma(n,e,t){var r;const i=n==null?void 0:n.mcpServers;if(!i)return;const s=(r=i[t])!=null?r:i[e];return(s==null?void 0:s.url)||void 0}function ga(n,e){return(t,i,s)=>{const r=oo(n);if(!r){i({code:500,message:"缺少 MCP 地址"});return}sa(r,n,t,s==null?void 0:s.signal,e).then(o=>i({code:0,message:"ok",data:o})).catch(o=>{i({code:500,message:o instanceof Error?o.message:String(o)})})}}function ya(n){return d(this,null,function*(){var u,f;const e=(u=n.fetchImpl)!=null?u:fetch,t=n.initMcp?Object.keys((f=n.initMcp.mcpServers)!=null?f:{}):null,i=oa(n.arrange),s=Mt().revision,r=()=>Mt().revision!==s||(n.isCurrent?!n.isCurrent():!1);if(!i.length){if(r())return;be.log("编排里没有 runtime=local 的 MCP,不发送 register_client_mcp_tools"),Zn([]),ci([]),Ue();return}const o=[...Mt().servers],a=new Set,c=yield Promise.all(i.map(p=>d(this,null,function*(){var A,E;const w=p.id;let _;const v=()=>{_&&(a.delete(_),_=void 0)};try{const I=yield da(n.apiRoot,n.token,w,e);if(!aa(t,w,I.code))return null;_=I.code?pa(o,a,I.code):void 0;const M=(E=(A=_==null?void 0:_.url)!=null?A:ma(n.initMcp,w,I.code))!=null?E:I.url;if(I.deployType!=="streamableHttp"||!I.code||!M)return be.log("skip local mcp",w),v(),null;const q={code:I.code,url:M,headers:ua(I.headers,_)},D=yield ia(q,e);return D.length?{code:I.code,url:q.url,binding:q,tools:D}:(v(),null)}catch(I){return v(),be.report("local mcp failed",w,I instanceof Error?I.message:String(I)),null}})));if(r()){const p=ao();for(const w of c)w&&ra(w.binding,p);return}const l={},h=[];for(const p of c)if(p){l[p.code]={type:"streamableHttp",url:p.url,tools:p.tools};for(const w of p.tools)h.push({name:w.name,binding:p.binding,handler:ga(w.name,e)})}if(Zn(h),ci(h.map(p=>p.binding)),Ue(),!Object.keys(l).length||!n.socket){be.log("没有可注册的本地 MCP 工具,不发送 register_client_mcp_tools");return}be.log("发送 register_client_mcp_tools",Object.entries(l).map(([p,w])=>`${p}: ${w.tools.map(_=>_.name).join(", ")}`).join("; ")),n.socket.emit("register_client_mcp_tools",{mcpServers:l},p=>{const w=p&&typeof p=="object"?p.code:void 0;typeof w=="number"&&w!==200&&be.report("register_client_mcp_tools",w)})})}const T=new B("[AgentSession] ");function li(n){if(typeof n!="string")return n;const e=n.trim();if(e)try{return JSON.parse(e)}catch(t){return n}}function wa(n){const e=n.imageContent;return Array.isArray(e)?S(b({},n),{imageContent:`[${e.length}]`}):n}function di(n){return n==null||n===""||typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function va(n,e){const t=li(n==null?void 0:n.query);if(!di(t))return t;const i=li(e);return di(i)&&t!=null?t:i}class ba extends En{constructor(t,i="",s,r,o,a){super(t,i,s,r,o,a);y(this,"inflightCalls",new Set);y(this,"localMcpTicket",0);y(this,"stopLocalMcpUpdates")}prepareConnection(){return new Promise(t=>d(this,null,function*(){var o;if((o=this.socket)!=null&&o.connected){T.log("socket:reuse",this.id),t(!0);return}this.socket&&(this.socket.removeAllListeners(),this.socket.close(),this.socket=null);const i={version:"1.0",stream:JSON.stringify(exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?Se.Debug:Se.Normal},s=new URL(exports.configuration.apiRoot);T.log("socket:connecting",{sessionId:this.id,origin:s.origin});const r=yield Es.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:i,transports:["websocket"]});r.on("connect",()=>{T.log("socket:connect"),this.event.emit("socket:connect"),r.emit("init")}),r.on("disconnect",()=>{T.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),r.on("ready",a=>{if(a.code===200){T.log("ready");const c=exports.configuration.debug?Se.Debug:Se.Normal;c===Se.Debug&&a.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),this.registerLocalMcp(),t(!0)}else{this._ready&&(this._ready=!1);const c=new Error(st.SocketConnectionFailed);T.error("error",c),this.event.emit("error",c),t(!1)}}),r.on("action",(a,c)=>d(this,null,function*(){var v;if(this._stopAnswer||!this.id)return;const{type:l,data:{runnerIsClient:h,pluginCode:u,funcCode:f,parameters:p,requestBody:w}}=a,_=this.messages[this.messages.length-1];if(!_.messageId)_.actions||(_.actions=[]),_.actions[a.data.step-1]||(_.actions[a.data.step-1]=[]),_.actions[a.data.step-1].push(a),this.event.emit("message:action",{messageId:_.messageId,action:a}),this.event.emit("message:updated",_);else{const A={messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[a]],comment:{isAgree:0},isReplying:!0};this.pushMessage(A),this.event.emit("message:action",{messageId:A.messageId,action:a})}if(l==="FUNCTION_CALL"&&!h&&T.log("server function",u,f),l==="FUNCTION_CALL"&&h){T.log(`calling function ${f} of plugin ${u} with argument:
375
+ ${JSON.stringify(p)}`);const A=(v=exports.configuration.plugins)==null?void 0:v[u];if(!A){T.error("plugin not found",u,f),c({code:404,message:"没有找到插件。"});return}const E=A[f];if(typeof E!="function"){T.error("plugin function not found",u,f),c({code:404,message:"没有找到插件方法。"});return}const I=va(p,w);this.invokeClientPlugin(E,I,c,{requestId:a.requestId,pluginCode:u,functionCode:f})}})),r.on("answer",a=>{if(T.log("answer",a==null?void 0:a.data),!this._stopAnswer)if(a.data.code!==200&&(a.data.index=-1),a.data.stream||a.data.stream===void 0){let c=this.messages[this.messages.length-1];if(c&&c.role===x.ChatMessageRole.Robot)this.handleStreamAnswer(a.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 l={content:"",role:x.ChatMessageRole.Robot,reference:[],searchReference:[],messageId:"",sessionId:this.id,messageTime:Zt(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""};this.handleStreamAnswer(a.data,l),this.pushMessage(l),this.event.emit("message:content",l),l.index===-1&&(l.isReplying=!1,this.event.emit("answer:finish",l))}}else if(a.data.updateSession&&this.data&&(this.data=b(b({},this.data),a.data.updateSession),this.event.emit("data:updated",this.data)),a.data.index===-1){let c=this.messages[this.messages.length-1];if(c&&!c.messageId)c=b(b({},c),a.data),this.event.emit("message:content",c),this.event.emit("message:updated",c),this.event.emit("answer:finish",c);else{const l=b({messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},a.data);this.event.emit("message:content",l),this.pushMessage(l),this.event.emit("answer:finish",l)}}else{let c=this.messages[this.messages.length-1];c&&!c.messageId?(c=b(b({},c),a.data),this.messages[this.messages.length-1]=c,this.event.emit("message:content",c),this.event.emit("message:updated",c)):(this.pushMessage(b({messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},a.data)),this.event.emit("message:content",a.data))}}),r.on("reference",a=>d(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const p=new Error(st.IdUndefined);T.error(p),this.event.emit("error",p),this.frozen=!1;return}const{type:c,data:l,requestId:h}=a;T.log("reference",{type:c,requestId:h,data:l});const u=this.messages.findIndex(p=>p.messageId===h&&p.role===x.ChatMessageRole.User);if(u<0)return;const f=u+1;if(f>=this.messages.length){const p={messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0};this.pushMessage(p)}c==="KG"?(this.messages[f]=S(b({},this.messages[f]),{reference:l.knowledgeReference}),yield this.fillMessageReference(this.messages[f]),this.event.emit("message:reference",l.knowledgeReference),this.event.emit("message:updated",this.messages[f])):c==="WEB_SEARCH"&&(this.messages[f]=S(b({},this.messages[f]),{searchReference:l.knowledgeReference}),this.event.emit("message:searchreference",l.searchReference),this.event.emit("message:updated",this.messages[f]))})),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&&T.report(r,"MCP Server 注册失败。",s.data[r])}),T.log("mcp:registered",Object.keys(s.data)),t(!0)):(T.error("MCP Server 注册失败。",s),i(s))})}):(T.log("mcp:skip"),Promise.resolve(!0))}registerLocalMcp(){var s,r;const t=this.socket;if(!t)return;rs(),this.stopLocalMcpUpdates||(this.stopLocalMcpUpdates=Eo(()=>this.registerLocalMcp()));const i=++this.localMcpTicket;ya({arrange:(r=(s=this.application)==null?void 0:s.arrange)==null?void 0:r[0],initMcp:exports.configuration.mcp,apiRoot:exports.configuration.apiRoot,token:this.token,socket:t,isCurrent:()=>i===this.localMcpTicket}).catch(o=>{T.report("local mcp",o instanceof Error?o.message:String(o))})}addMcpServers(t){return d(this,null,function*(){return this.ready?this.socket?new Promise((i,s)=>{this.socket&&this.socket.emit("add_mcp_servers",t,r=>{r.code===200?(Object.keys(r.data).forEach(o=>{r.data[o].code!==200&&T.report(o,"MCP Server 注册失败。",r.data[o])}),T.log("mcp:registered",Object.keys(r.data)),i(!0)):(T.error("MCP Server 注册失败。",r),s(r))})}):(T.error("socket is undefined."),Promise.reject("socket is undefined")):(T.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return d(this,null,function*(){return this.ready?this.socket?new Promise((t,i)=>{this.socket&&this.socket.emit("list_mcp_servers",s=>{s.code===200?t(s.data):i(s)})}):(T.error("socket is undefined."),Promise.reject("socket is undefined")):(T.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(t,i){return d(this,null,function*(){var r;this.convertKnowledgesToChatFormat(this.knowledges);let s=S(b({},t),{promptVariables:this.promptVariables.filter(o=>o.type===x.PromptVariableType.User).reduce((o,a)=>S(b({},o),{[a.key]:a.value}),{}),systemPromptVariables:this.promptVariables.filter(o=>o.type===x.PromptVariableType.System).reduce((o,a)=>S(b({},o),{[a.key]:a.value}),{}),knowledges:(r=this.knowledges)==null?void 0:r.map(o=>o.id),enableTitleSummary:this.resolveEnableTitleSummary()});if(!this.active){if(yield this.activate(),!this.socket){const o=new Error(st.SocketConnectionFailed);return T.warn("error",o),this.event.emit("error",o),!1}this.emitQuestion(s);return}this.emitQuestion(s)})}emitQuestion(t){var i;T.log("question:request",wa(t)),(i=this.socket)==null||i.emit("question",t),T.log("question:sent",{sessionId:this.id})}invokeClientPlugin(t,i,s,r){const o=new AbortController;this.inflightCalls.add(o);let a=!1;const c=(...h)=>{a||(a=!0,this.inflightCalls.delete(o),!(this._stopAnswer||o.signal.aborted)&&s(...h))},l={requestId:r.requestId||ie.v4(),applicationId:this._applicationId,sessionId:this.id,pluginCode:r.pluginCode,functionCode:r.functionCode,signal:o.signal};try{const h=t(i,c,l);h&&typeof h.catch=="function"&&h.catch(u=>{T.error("client plugin failed",u),c({code:500,message:"客户端插件执行失败。"})})}catch(h){T.error("client plugin failed",h),c({code:500,message:"客户端插件执行失败。"})}}abortClientPluginCalls(){const t=Array.from(this.inflightCalls);this.inflightCalls.clear(),t.forEach(i=>i.abort())}stopAnswer(){var t;T.log("stopAnswer",this.id),this.abortClientPluginCalls(),(t=this.socket)==null||t.emit("stop_answer")}inactivate(t=!1){return!t&&this.frozen&&!!this.socket||this.abortClientPluginCalls(),super.inactivate(t)}destroy(){var t;return(t=this.stopLocalMcpUpdates)==null||t.call(this),this.stopLocalMcpUpdates=void 0,this.abortClientPluginCalls(),super.destroy()}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}function _a(n,e){return d(this,null,function*(){const t=n.getReader();let i;for(;!(i=yield t.read()).done;)e(i.value)})}function ka(n){let e,t,i,s=!1,r;return function(a){e===void 0?(e=a,t=0,i=-1,r=!1):e=Ea(e,a);const c=e.length;let l=0;for(;t<c;){s&&(e[t]===10&&(l=++t),s=!1);let h=-1;for(;t<c&&h===-1;++t)switch(e[t]){case 58:i===-1&&(i=t-l);break;case 13:s=!1,t+4<c&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(r=!0);case 10:h=t;break}if(h===-1)break;n(e.subarray(l,h),i,r),l=t,i=-1,r=!1}l===c?e=void 0:l!==0&&(e=e.subarray(l),t-=l)}}function Sa(n,e,t){let i=hi();const s=new TextDecoder;return function(o,a,c){if(o.length===0)t==null||t(i),i=hi();else if(a>0){const l=s.decode(o.subarray(0,a)),h=a+(o[a+1]===32?2:1);let u=s.decode(o.subarray(h));switch(c&&(u+=`
376
376
  `),l){case"data":i.data=i.data?i.data+`
377
- `+u:u;break;case"event":i.event=u;break;case"id":n(i.id=u);break;case"retry":const f=parseInt(u,10);isNaN(f)||e(i.retry=f);break}}}}function wa(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function ai(){return{data:"",event:"",id:"",retry:void 0}}const Yt="text/event-stream",va=1e3,ci="last-event-id";function li(n,h){var u=h,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:a,fetch:c}=u,l=An(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,p)=>{const y=b({},t);y.accept||(y.accept=Yt);let w;function _(){w.abort(),document.hidden||$()}a||document.addEventListener("visibilitychange",_);let A=va,I=0;function S(){document.removeEventListener("visibilitychange",_),window.clearTimeout(I),w.abort()}e==null||e.addEventListener("abort",()=>{S(),f()});const L=c!=null?c:window.fetch,j=i!=null?i:ba;function $(){return d(this,null,function*(){var M;w=new AbortController;try{const T=yield L(n,E(b({},l),{headers:y,signal:w.signal}));yield j(T),yield ma(T.body,ga(ya(R=>{R?y[ci]=R:delete y[ci]},R=>{A=R},s))),r==null||r(),S(),f()}catch(T){if(!w.signal.aborted)try{const R=(M=o==null?void 0:o(T))!=null?M:A;window.clearTimeout(I),I=window.setTimeout($,R)}catch(R){S(),p(R)}}})}$()})}function ba(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith(Yt)))throw new Error(`Expected content-type to be ${Yt}, Actual: ${e}`)}const di=new q("[DialogSession] ");class _a extends _n{constructor(t,i="",s,r,o,a){super(t,i,s,r,o,a);v(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>d(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c={code:0,content:"",role:x.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},l=E(b({},s),{stream:exports.configuration.stream});li(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(l),openWhenHidden:!0,signal:r,onopen(h){return h.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(h){if(!h.data.includes('{"code": ')){let f={};try{f=JSON.parse(h.data)}catch(y){}(f==null?void 0:f.mtype)==="search"?c.searchReference.push(f):c.content=c.content+h.data;const p={content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:Kt(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(o==null?void 0:o.onmessage)&&o.onmessage(p)}const u=JSON.parse(h.data);if(c.reference=u.data.reference,c.searchReference=u.data.searchReference,c.messageTime=u.data.messageTime,c.messageId=u.data.messageId,c.llmModel=u.data.llmModel,c.content=u.data.content,c.code=u.code,u.code===200){const f={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,isReplying:!0};o!=null&&o.onmessage&&o.onmessage(f)}else return o!=null&&o.onclose&&o.onclose(c),a&&a({code:c.code,message:c.message})},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const h={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};o!=null&&o.onclose&&o.onclose(h)}})})}postChatV3EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c=this,l={code:0,content:"",role:x.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},h=E(b({},s),{stream:exports.configuration.stream});li(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(h),openWhenHidden:!0,signal:r,onopen(u){return u.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(u){if(!u.data&&!u.event&&!u.id&&!u.retry)return;let f={};try{f=JSON.parse(u.data)}catch(p){console.error("parse eventData to JSON failed. ",u.data)}if(f.code!==200)return l.index=-1,l.code=f.code,l.message=f.message,o!=null&&o.onmessage&&o.onmessage(l),a&&a({code:f.code,message:f.message});c.handleStreamAnswer(f,l),o!=null&&o.onmessage&&o.onmessage(l)},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const u=E(b({},l),{isReplying:!1});o!=null&&o.onclose&&o.onclose(u)}})})}sendQuestion(t,i){return d(this,null,function*(){const{content:s,fileIds:r,oldMessageId:o,imageContent:a}=t,{stream:c,referenceFirst:l}=i;if(this.active||(yield this.activate()),this._id){const h=this.convertKnowledgesToChatFormat(this.knowledges);let u={content:s,fileIds:r,referenceFirst:l,oldMessageId:o,promptVariables:this.promptVariables.filter(f=>f.type===x.PromptVariableType.User).reduce((f,p)=>E(b({},f),{[p.key]:p.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===x.PromptVariableType.System).reduce((f,p)=>E(b({},f),{[p.key]:p.value}),{}),knowledges:h,enableTitleSummary:this.resolveEnableTitleSummary(),imageContent:a};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,u,this.ctrl.signal,{onopen:()=>{di.log("open",this.ctrl)},onmessage:f=>{if(this._stopAnswer)return;let p=this.messages[this.messages.length-1];p&&p.role===x.ChatMessageRole.Robot?(p=b(b({},p),f),this.messages[this.messages.length-1]=p,this.event.emit("message:content",p),this.event.emit("message:updated",p)):(this.pushMessage(f),this.event.emit("message:content",f))},onclose:f=>d(this,null,function*(){this._stopAnswer||(di.log(f,"onclose"),this.event.emit("answer:finish",f))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}const ka="@glodon-aiot/bot-client-sdk",Ea="3.26.0-alpha.33",Sa="glodoncv",Ia="aiot bot client js sdk",xa="module",Aa=!1,Ta=["aiot","bot","bot client","sdk"],La=["dist"],Ma="./dist/es/index.mjs",Ra="./dist/lib/index.js",Ca="./dist/src/index.d.ts",Fa={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},Oa="MIT",Na={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"},$a={"@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"},Pa={access:"public",registry:"https://registry.npmjs.org/"},Da={"@glodon-aiot/apis":"^3.26.0-alpha.33",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"},Ba={name:ka,version:Ea,author:Sa,description:Ia,type:xa,sideEffects:Aa,keywords:Ta,files:La,module:Ma,main:Ra,typings:Ca,exports:Fa,license:Oa,scripts:Na,devDependencies:$a,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:Pa,dependencies:Da},hi=new q("[BotClient] ");class ja{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){v(this,"event",new yn);v(this,"cvforceApi");v(this,"_applicationId");v(this,"_application",null);v(this,"_sessions",[]);v(this,"_activeSession");v(this,"_ready",!1);v(this,"_questionContextMaxLength",4e3);v(this,"_promptVariables",[]);v(this,"_localWorkspace");v(this,"_disconnectHost");if(this._token=e,this.lazyload=i,this.sdkConfigs=s,Wt(t,{refreshBuiltinPlugins:!1}),this._applicationId=ct(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),ns(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{Wt(E(b({},t),{stream:t.stream===void 0?(r==null?void 0:r.type)===x.ApplicationTypes.Dialog||(r==null?void 0:r.type)===x.ApplicationTypes.Agent:t.stream})),this.event.emit("ready")})}setupLocalWorkspace(){var s,r;const e=(s=exports.configuration.builtinPlugins)==null?void 0:s.localFiles;if(!(e!=null&&e.enabled)){Jn(void 0),je();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=fo(exports.configuration.apiRoot,this.token,(a,c)=>hi.error(c));this._localWorkspace=new cs({applicationId:this._applicationId,config:e,store:os(),picker:i==="host-bridge"?null:void 0,transfer:vn(()=>this.cvforceApi,()=>o)}),Jn(this._localWorkspace),this._localWorkspace.platformSkills=new yo({applicationId:()=>this._applicationId,getToken:()=>this.token,getSkills:()=>{var a,c,l,h;return(h=(l=(c=(a=this._application)==null?void 0:a.arrange)==null?void 0:c[0])==null?void 0:l.skills)!=null?h:[]},apiRoot:()=>exports.configuration.apiRoot,getSandbox:()=>{var c;const a=(c=this._localWorkspace)==null?void 0:c.adapter;return a instanceof qe?a.sandbox:void 0}}),i==="host-bridge"?this._disconnectHost=vo(this._localWorkspace):this._localWorkspace.restore()}t.push(...je()),t.length&&Promise.resolve().then(()=>t.forEach(o=>this.event.emit("error",o)))}get localWorkspace(){return this._localWorkspace}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return d(this,null,function*(){var t,i,s,r,o;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(i=this.sdkConfigs.ui)==null?void 0:i.version,sdkVersion:Ba.version}).then(a=>(typeof a.arrange[0].thinkingModeOpen!="boolean"&&(a.arrange[0].thinkingModeOpen=!0),typeof a.arrange[0].thinkingTextOpen!="boolean"&&(a.arrange[0].thinkingTextOpen=!0),E(b({},a),{arrange:[E(b({},a.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&a.arrange[0].recommendQuestionOpen})]})));const e=(o=(r=(s=this._application)==null?void 0:s.arrange)==null?void 0:r[0])==null?void 0:o.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(a=>a.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type:x.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:x.PromptVariableType.System})]).then(([a,c])=>[...a,...c]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:Ji(exports.configuration.apiRoot,this.token,(e,t)=>hi.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=ct(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,i,s,r){return d(this,null,function*(){const o=this;return new Promise((a,c)=>{const l=h=>d(this,null,function*(){if(h===x.ApplicationTypes.Agent)a(new pa(e,t,i,s,r,o));else if(h===x.ApplicationTypes.Dialog)a(new _a(e,t,i,s,r,o));else throw Error(`不支持的应用类型:${h}`)});if(this.ready){if(!this._application)throw Error("client is not ready");l(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");l(this._application.type)},!0)})})}getArtifacts(e){return d(this,null,function*(){var r,o;this.checkReady();const t=e||((r=this._activeSession)==null?void 0:r.id);if(!t)throw new Error("session id is not defined");const i=this._sessions.find(a=>a.id===t);if(i)return i.getArtifacts();const s=yield this.cvforceApi.getSessionArtifacts(this._applicationId,t);return(o=s==null?void 0:s.artifacts)!=null?o:[]})}getSessions(e){return d(this,null,function*(){return new Promise((t,i)=>{const s=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>d(this,null,function*(){const o=[];for(const a of r){const c=this._sessions.find(l=>l.id===a.id);if(c)c.data=a,this._application?c.application=this._application:yield c.loadApplicationInfo(),o.push(c);else{const l=yield this.createSession(this.token,a.id,a,this.lazyload,this._application||void 0);o.push(l)}}if(e!=null&&e.pageSize){const a=[...this._sessions,...o],c=new Map;for(const l of a)c.set(l.id,l);return this.sessions=Array.from(c.values()),this.sessions}else return this.sessions=o,o}));if(this.ready){if(!this._application)throw Error("_application is null");t(s())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(s())},!0)})})}loadSession(e="",t){return d(this,null,function*(){var s,r;this.checkReady(),(r=(s=this._localWorkspace)==null?void 0:s.platformSkills)==null||r.sync();let i=this.sessions.find(o=>o.id===e);if(i||(i=yield this.createSession(this.token,e,t),this._sessions.push(i)),this._activeSession){if(this._activeSession===i)return i;this._activeSession.inactivate()}return i.id?(this._activeSession=i,yield i.activate()):i.addEventListener("data:loaded",()=>{this._activeSession!==i&&(i==null||i.activate(),this._activeSession=i)},!0),i})}reload(){return this.loadApplication().then(()=>d(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return d(this,null,function*(){yield this.reload();let t=this._sessions.find(i=>i.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,i="top_time desc, sort_status desc, updated_at desc"){return d(this,null,function*(){let s=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!s){console.warn("setTop session failed.");return}return yield s.setTop(t),this.getSessions({order:i})})}addEventListener(e,t,i=!1){if(typeof t!="function")throw Error("event listener is not a function");if(i){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return d(this,null,function*(){this.checkReady();let i=-1;if(typeof e=="string"?i=this._sessions.findIndex(s=>s.id===e):i=this._sessions.findIndex(s=>s.id===e.id),i>-1){const s=this._sessions[i];t&&(yield s.delete()),this._sessions.splice(i,1)}else console.warn("session delete failed, session is not exist.")})}clean(){var e;(e=this._disconnectHost)==null||e.call(this),this._disconnectHost=void 0,this._sessions.forEach(t=>t.destroy()),this.sessions=[]}}class Ua{constructor(e,t={},i){v(this,"code");v(this,"description","");v(this,"loaded",!1);v(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}const Y="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",K={type:"string",enum:[xe],description:`工作区 ID。省略时按 ${xe} 处理,传其他值会被拒绝。`},J=n=>({type:"string",description:`${n}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),Ot={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},ls={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${Y}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:K,path:J('要列出的目录,省略或传 "." 表示工作区根目录。'),offset:{type:"integer",minimum:0,description:"分页起始位置,默认 0。"},limit:{type:"integer",minimum:1,maximum:1e3,description:"每页条数,默认 200。"}}}},read_file:{functionCode:"read_file",name:"读取本地文件",description:`${Y}按行读取文本文件,单次最多返回 1 MiB,超出部分会被截断(truncated: true)。返回内容的 hash 可用于后续修改。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:K,path:J("要读取的文件。"),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:`${Y}返回文件或目录的类型、大小、修改时间,可选返回 hash。不返回文件内容。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:K,path:J("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${Y}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:K,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:J("搜索起点目录,默认工作区根目录。"),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:`${Y}在指定文件或目录(递归)中搜索普通文本(不支持正则),返回所在文件、行号与该行内容。必须指定 path,不能搜索整个文件夹。`,parameters:{type:"object",required:["grantId","path","query"],properties:{grantId:K,path:J("搜索范围,可以是文件或目录。"),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:`${Y}以查找替换的方式修改 UTF-8 文本文件。每条修改的 oldText 必须在文件中唯一出现(或设置 replaceAll)。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","expectedHash","edits"],properties:{grantId:K,path:J("要修改的文件。"),expectedHash:Ot,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:`${Y}新建文件,或整体覆盖已有文件(覆盖时必须提供 expectedHash)。修改已有文件优先使用 apply_patch。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","content"],properties:{grantId:K,path:J("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:Ot,createDirectories:{type:"boolean",description:"父目录不存在时是否自动创建,默认否。"}}}},upload_file:{functionCode:"upload_file",name:"上传本地文件",description:`${Y}把本地文件夹中的文件上传到平台文件服务,返回 fileId、name、size 和 url。url 是文件访问地址,可直接用于后续推理或对话。下载回本地文件夹时使用 download_file,source.type 为 platformFile。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:K,path:J("要上传的文件。"),target:{type:"string",description:"上传目标,目前只支持 session(默认),其他值返回 501。"},mimeHint:{type:"string",description:"可选的 MIME 类型。"}}}},download_file:{functionCode:"download_file",name:"下载到本地文件夹",description:`${Y}把会话文件、平台文件或 https 地址保存到本地文件夹。source.type 为 url 时必须同时填写 source.url(完整地址),为 sessionFile 或 platformFile 时必须同时填写 source.fileId。不要只传 type。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","destPath","source"],properties:{grantId:K,destPath:J("保存位置(文件路径)。"),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:Ot}}}},qa=new TextEncoder;function ie(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const Ha=(n,e)=>d(exports,null,function*(){const t=ee(n.path,{allowRoot:!0});if((yield e.adapter.stat(t)).kind!=="directory")throw new m(g.BadRequest,"目标是文件,不是目录。");const s=ie(n.offset,0,0,Number.MAX_SAFE_INTEGER),r=ie(n.limit,vi,1,bi),o=yield e.adapter.listEntries(t,e.signal);o.sort((c,l)=>c.kind!==l.kind?c.kind==="directory"?-1:1:c.name<l.name?-1:c.name>l.name?1:0);const a=o.slice(s,s+r).map(c=>{const l=is(t,c.name),h={name:c.name,path:l,kind:c.kind};return c.kind==="file"&&(h.size=c.size,h.lastModified=c.lastModified,e.sensitive.isSensitive(l)&&(h.sensitive=!0)),h});return{data:{path:t,entries:a,total:o.length,hasMore:s+a.length<o.length}}});function za(n,e,t){return ge(this,null,function*(){var a;const i=new TextDecoder(e),s=n.stream().getReader();let r="",o=!1;try{for(;;){F(t);const{done:c,value:l}=yield new se(s.read());r+=c?i.decode():i.decode(l,{stream:!0});const h=r.split(`
378
- `);r=(a=h.pop())!=null?a:"";for(const u of h)o=!0,yield u;if(c)break}}finally{s.releaseLock()}(r||!o)&&(yield r)})}const Wa=(n,e)=>d(exports,null,function*(){var S,L;const t=ee(n.path);Me(e,t,"read");const i=yield cn(e.adapter,t),s=yield e.adapter.readFile(t),r=(S=i.size)!=null?S:s.size;if(yield Gs(s))throw new m(g.BadRequest,"这是二进制文件,不能按文本读取。可以使用 stat_file 查看信息,或使用 upload_file 上传到会话。");const o=yield X(s.slice(0,3)),a=ji(o)?"utf-8":(L=n.encoding)!=null?L:"utf-8",c=ie(n.startLine,1,1,Number.MAX_SAFE_INTEGER),l=n.endLine===void 0?Number.MAX_SAFE_INTEGER:Math.max(Math.trunc(n.endLine),c),h=ie(n.maxBytes,e.limits.maxReadBytes,1,e.limits.maxReadBytes),u=r<=e.limits.maxTransferBytes,f=[];let p=0,y=0,w=c-1,_=!1,A=!1;try{for(var j=G(za(s,a,e.signal)),$,M,T;$=!(M=yield j.next()).done;$=!1){const R=M.value;y++;const H=R.endsWith("\r")?R.slice(0,-1):R;if(H!==R&&(A=!0),y<c||y>l||_){if(!u&&(_||y>l))break;continue}const U=ln(H)+(f.length?1:0);if(p+U>h){if(_=!0,f.length||(f.push(Va(H,h)),w=y),!u)break;continue}f.push(H),p+=U,w=y}}catch(M){T=[M]}finally{try{$&&(M=j.return)&&(yield M.call(j))}finally{if(T)throw T[0]}}const I={path:t,content:f.join(`
379
- `),startLine:c,endLine:Math.max(w,c-1),size:r,encoding:a,lineEnding:A?"crlf":"lf"};return u&&(I.totalLines=y),r<=e.limits.maxWriteBytes&&(I.hash=yield Te(yield X(s))),{data:I,truncated:_||void 0}});function Va(n,e){const t=qa.encode(n);return t.byteLength<=e?n:new TextDecoder().decode(t.slice(0,e)).replace(/\uFFFD$/,"")}const Ga=(n,e)=>d(exports,null,function*(){var r;const t=ee(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 Te(yield X(yield e.adapter.readFile(t))))),{data:s}});function Xa(n){return Ai.some(e=>ot(e,n))}function ds(n,e,t){return ge(this,null,function*(){const i=[{path:e,depth:0}];let s=0;for(;i.length;){const r=i.shift();F(n.signal),++s%20===0&&(yield new se(Ui()));const o=yield new se(n.adapter.listEntries(r.path,n.signal));o.sort((a,c)=>a.name<c.name?-1:a.name>c.name?1:0);for(const a of o){const c=is(r.path,a.name);if(a.kind==="directory"){r.depth+1<t&&!xi.includes(a.name)&&i.push({path:c,depth:r.depth+1});continue}Xa(a.name)||n.sensitive.match(c,"search")||(yield{path:c,relativePath:e?c.slice(e.length+1):c,name:a.name,size:a.size,lastModified:a.lastModified})}}})}function hs(n,e){return n.includes("/")?ot(n,e.relativePath):ot(n,e.name)}const Ya=(n,e)=>d(exports,null,function*(){const t=ee(n.path,{allowRoot:!0});if(!n.pattern.trim())throw new m(g.BadRequest,"参数 pattern 不能为空。");const i=n.pattern.replace(/\\/g,"/").replace(/^\.\//,"");if((yield e.adapter.stat(t)).kind!=="directory")throw new m(g.BadRequest,"参数 path 必须是目录。");const r=ie(n.maxDepth,_i,1,Qt),o=ie(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),a=[];let c=!1;try{for(var l=G(ds(e,t,r)),h,u,f;h=!(u=yield l.next()).done;h=!1){const p=u.value;if(hs(i,p)){if(a.length>=o){c=!0;break}a.push({path:p.path,size:p.size,lastModified:p.lastModified})}}}catch(u){f=[u]}finally{try{h&&(u=l.return)&&(yield u.call(l))}finally{if(f)throw f[0]}}return{data:{matches:a},truncated:c||void 0}});function Nt(n,e){if(n.length<=Qe)return n;const t=Math.max(0,Math.min(e-100,n.length-Qe));return n.slice(t,t+Qe)}const Ka=(n,e)=>d(exports,null,function*(){var f;const t=ee(n.path,{allowRoot:!0});if(!t&&!e.allowWorkspaceWideTextSearch)throw new m(g.BadRequest,"不支持在整个工作区内搜索文本,请把 path 缩小到具体的子目录或文件。");if(n.isRegex)throw new m(g.NotImplemented,"暂不支持正则搜索,请使用普通文本搜索。");if(!n.query)throw new m(g.BadRequest,"参数 query 不能为空。");const i=n.caseSensitive===!0,s=i?n.query:n.query.toLowerCase(),r=ie(n.contextLines,0,0,Si),o=ie(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),a=yield e.adapter.stat(t);let c;a.kind==="file"?(Me(e,t,"search"),c=function(){return ge(this,null,function*(){yield{path:t,relativePath:t,name:a.name,size:a.size}})}()):c=ds(e,t,Qt);const l=[];let h=0,u=!1;e:try{for(var p=G(c),y,w,_;y=!(w=yield p.next()).done;y=!1){const A=w.value;if(n.glob&&!hs(n.glob,A)||((f=A.size)!=null?f:0)>Ei)continue;if(h>=ki){u=!0;break}h++,h%20===0&&(yield Ui()),F(e.signal);const I=yield X(yield e.adapter.readFile(A.path));if(fe(I))continue;const S=new TextDecoder("utf-8").decode(I).split(/\r?\n/);for(let L=0;L<S.length;L++){const $=(i?S[L]:S[L].toLowerCase()).indexOf(s);if($<0)continue;if(l.length>=o){u=!0;break e}const M={path:A.path,line:L+1,column:$+1,text:Nt(S[L],$)};r&&(M.before=S.slice(Math.max(0,L-r),L).map(T=>Nt(T,0)),M.after=S.slice(L+1,L+1+r).map(T=>Nt(T,0))),l.push(M)}}}catch(w){_=[w]}finally{try{y&&(w=p.return)&&(yield w.call(p))}finally{if(_)throw _[0]}}return{data:{matches:l,filesScanned:h},truncated:u||void 0}});function ui(){return new m(g.Forbidden,"下载地址不在允许范围内:只允许 https 协议且域名在白名单中的地址。",{reason:"url_not_allowed"})}const Ja=(n,e)=>d(exports,null,function*(){var u,f;const t=ee(n.path);if(((u=n.target)!=null?u:"session")!=="session")throw new m(g.NotImplemented,"目前只支持上传到当前会话(target: session)。");Me(e,t,"read");const s=yield cn(e.adapter,t),r=(f=s.size)!=null?f:0;if(r>e.limits.maxTransferBytes)throw he(e.limits.maxTransferBytes);const o=on(t);yield e.requestApproval(t,{type:"upload",name:o,size:r,target:"session"}),e.progress({stage:"reading",loaded:0,total:r,path:t});const a=yield e.adapter.readFile(t);F(e.signal);const c=new File([a],o,{type:n.mimeHint||a.type||"application/octet-stream",lastModified:s.lastModified}),{fileId:l,url:h}=yield e.transfer.upload(c,e.context,({loaded:p,total:y})=>e.progress({stage:"uploading",loaded:p,total:y,path:t}));return F(e.signal),e.progress({stage:"done",loaded:r,total:r,path:t}),{data:{fileId:l,name:o,size:r,url:h}}});function Qa(n){const e=n;if(!e||typeof e!="object")throw new m(g.BadRequest,"缺少参数 source。");if(e.type==="sessionFile"||e.type==="platformFile"){if(typeof e.fileId!="string"||!e.fileId)throw new m(g.BadRequest,"source.fileId 必须是非空字符串。");return{type:e.type,fileId:e.fileId}}if(e.type==="url"){if(typeof e.url!="string"||!e.url)throw new m(g.BadRequest,"source.url 必须是非空字符串。");return{type:"url",url:e.url}}throw new m(g.BadRequest,"source.type 必须是 sessionFile、platformFile 或 url 之一。")}function Za(n){return n.type==="sessionFile"?"会话文件":n.type==="platformFile"?"平台文件":new URL(n.url).hostname}function ec(n,e,t,i,s){return ge(this,null,function*(){const r=n.getReader();let o=0;try{for(;;){F(e.signal);const{done:a,value:c}=yield new se(r.read());if(a)break;if(o+=c.byteLength,o>e.limits.maxTransferBytes)throw he(e.limits.maxTransferBytes,"下载内容");s.push(c),e.progress({stage:"downloading",loaded:o,total:i,path:t}),yield c}}finally{r.cancel().catch(()=>{})}})}const tc=(n,e)=>d(exports,null,function*(){var w,_,A;const t=ee(n.destPath,{field:"destPath"}),i=Qa(n.source);if(i.type==="url"&&!Xt(i.url,e.downloadUrlAllowlist))throw ui();Me(e,t,"write");const s=yield et(e.adapter,t);if((s==null?void 0:s.kind)==="directory")throw new m(g.BadRequest,"目标是目录,不能写入文件。");if(s&&!n.overwrite)throw new m(g.Conflict,"目标文件已存在。如需覆盖,请设置 overwrite: true。");const r=()=>d(exports,null,function*(){if(!s||!n.expectedHash)return;const I=yield Te(yield X(yield e.adapter.readFile(t)));if(I!==n.expectedHash)throw new m(g.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 he(e.limits.maxTransferBytes);const a={type:"download",source:{type:i.type,label:Za(i)},name:(w=o.name)!=null?w:on(t),size:o.size,overwrite:!!s};yield e.requestApproval(t,a),yield r();let c;try{c=yield e.fetch(o.url,{headers:o.headers,credentials:"omit",redirect:"follow",signal:e.signal})}catch(I){throw F(e.signal),new m(g.Internal,"下载失败,无法连接到文件地址。")}if(i.type==="url"&&c.url&&!Xt(c.url,e.downloadUrlAllowlist))throw(_=c.body)==null||_.cancel().catch(()=>{}),ui();if(!c.ok||!c.body)throw(A=c.body)==null||A.cancel().catch(()=>{}),new m(c.status===404?g.NotFound:g.Internal,`下载失败(HTTP ${c.status})。`);const l=Number(c.headers.get("content-length")),h=Number.isFinite(l)&&l>0?l:void 0;if(h!==void 0&&h>e.limits.maxTransferBytes)throw c.body.cancel().catch(()=>{}),he(e.limits.maxTransferBytes);const u=[];yield e.adapter.writeFile(t,ec(c.body,e,t,h,u),{signal:e.signal});const f=u.reduce((I,S)=>I+S.byteLength,0),p=new Uint8Array(f);let y=0;return u.forEach(I=>{p.set(I,y),y+=I.byteLength}),e.progress({stage:"done",loaded:f,total:f,path:t}),{data:{path:t,size:f,hash:yield Te(p)}}}),$t=new Uint8Array([239,187,191]);function ht(n,e){return new m(g.Conflict,e,{currentHash:n})}function kn(n,e){return d(this,null,function*(){var s;if(((s=(yield cn(n.adapter,e)).size)!=null?s:0)>n.limits.maxWriteBytes)throw he(n.limits.maxWriteBytes,"目标文件");const i=yield X(yield n.adapter.readFile(e));return{bytes:i,hash:yield Te(i)}})}function us(n,e,t){return d(this,null,function*(){const{hash:i}=yield kn(n,e);if(i!==t)throw ht(i,"文件在确认期间已被修改,本次写入已取消。请重新读取后再修改。")})}function nc(n,e){const t=new TextEncoder().encode(n);if(!e)return t;const i=new Uint8Array($t.byteLength+t.byteLength);return i.set($t,0),i.set(t,$t.byteLength),i}function ic(n,e){let t=0,i=n.indexOf(e);for(;i>=0;)t++,i=n.indexOf(e,i+e.length);return t}function fi(n,e){return!e||n.includes(`\r
377
+ `+u:u;break;case"event":i.event=u;break;case"id":n(i.id=u);break;case"retry":const f=parseInt(u,10);isNaN(f)||e(i.retry=f);break}}}}function Ea(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function hi(){return{data:"",event:"",id:"",retry:void 0}}const Qt="text/event-stream",Ia=1e3,ui="last-event-id";function fi(n,h){var u=h,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:a,fetch:c}=u,l=Rn(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,p)=>{const w=b({},t);w.accept||(w.accept=Qt);let _;function v(){_.abort(),document.hidden||D()}a||document.addEventListener("visibilitychange",v);let A=Ia,E=0;function I(){document.removeEventListener("visibilitychange",v),window.clearTimeout(E),_.abort()}e==null||e.addEventListener("abort",()=>{I(),f()});const M=c!=null?c:window.fetch,q=i!=null?i:Aa;function D(){return d(this,null,function*(){var C;_=new AbortController;try{const R=yield M(n,S(b({},l),{headers:w,signal:_.signal}));yield q(R),yield _a(R.body,ka(Sa(F=>{F?w[ui]=F:delete w[ui]},F=>{A=F},s))),r==null||r(),I(),f()}catch(R){if(!_.signal.aborted)try{const F=(C=o==null?void 0:o(R))!=null?C:A;window.clearTimeout(E),E=window.setTimeout(D,F)}catch(F){I(),p(F)}}})}D()})}function Aa(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith(Qt)))throw new Error(`Expected content-type to be ${Qt}, Actual: ${e}`)}const _e=new B("[DialogSession] ");class xa extends En{constructor(t,i="",s,r,o,a){super(t,i,s,r,o,a);y(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>d(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c={code:0,content:"",role:x.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},l=S(b({},s),{stream:exports.configuration.stream});fi(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(l),openWhenHidden:!0,signal:r,onopen(h){return h.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(h){if(!h.data.includes('{"code": ')){let f={};try{f=JSON.parse(h.data)}catch(w){}(f==null?void 0:f.mtype)==="search"?c.searchReference.push(f):c.content=c.content+h.data;const p={content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:Zt(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(o==null?void 0:o.onmessage)&&o.onmessage(p)}const u=JSON.parse(h.data);if(c.reference=u.data.reference,c.searchReference=u.data.searchReference,c.messageTime=u.data.messageTime,c.messageId=u.data.messageId,c.llmModel=u.data.llmModel,c.content=u.data.content,c.code=u.code,u.code===200){const f={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,isReplying:!0};o!=null&&o.onmessage&&o.onmessage(f)}else return o!=null&&o.onclose&&o.onclose(c),a&&a({code:c.code,message:c.message})},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const h={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};o!=null&&o.onclose&&o.onclose(h)}})})}postChatV3EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c=this,l={code:0,content:"",role:x.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},h=S(b({},s),{stream:exports.configuration.stream}),u=h.imageContent;_e.log("question:request",Array.isArray(u)?S(b({},h),{imageContent:`[${u.length}]`}):h),fi(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(h),openWhenHidden:!0,signal:r,onopen(f){return _e.log("question:opened",{ok:f.ok,status:f.status}),f.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(f){if(!f.data&&!f.event&&!f.id&&!f.retry)return;let p={};try{p=JSON.parse(f.data)}catch(w){_e.error("parse eventData to JSON failed. ",f.data)}if(_e.log("response",p),p.code!==200)return l.index=-1,l.code=p.code,l.message=p.message,o!=null&&o.onmessage&&o.onmessage(l),a&&a({code:p.code,message:p.message});c.handleStreamAnswer(p,l),o!=null&&o.onmessage&&o.onmessage(l)},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const f=S(b({},l),{isReplying:!1});o!=null&&o.onclose&&o.onclose(f)}})})}sendQuestion(t,i){return d(this,null,function*(){const{content:s,fileIds:r,oldMessageId:o,imageContent:a}=t,{stream:c,referenceFirst:l}=i;if(this.active||(yield this.activate()),this._id){const h=this.convertKnowledgesToChatFormat(this.knowledges);let u={content:s,fileIds:r,referenceFirst:l,oldMessageId:o,promptVariables:this.promptVariables.filter(f=>f.type===x.PromptVariableType.User).reduce((f,p)=>S(b({},f),{[p.key]:p.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===x.PromptVariableType.System).reduce((f,p)=>S(b({},f),{[p.key]:p.value}),{}),knowledges:h,enableTitleSummary:this.resolveEnableTitleSummary(),imageContent:a};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,u,this.ctrl.signal,{onopen:()=>{_e.log("open",this.ctrl)},onmessage:f=>{if(this._stopAnswer)return;let p=this.messages[this.messages.length-1];p&&p.role===x.ChatMessageRole.Robot?(p=b(b({},p),f),this.messages[this.messages.length-1]=p,this.event.emit("message:content",p),this.event.emit("message:updated",p)):(this.pushMessage(f),this.event.emit("message:content",f))},onclose:f=>d(this,null,function*(){this._stopAnswer||(_e.log(f,"onclose"),this.event.emit("answer:finish",f))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}const Ta="@glodon-aiot/bot-client-sdk",La="3.26.0-alpha.34",Ra="glodoncv",Ma="aiot bot client js sdk",Ca="module",Fa=!1,Oa=["aiot","bot","bot client","sdk"],Na=["dist"],$a="./dist/es/index.mjs",Pa="./dist/lib/index.js",Da="./dist/src/index.d.ts",Ba={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},ja="MIT",Ua={watch:"yarn build --watch",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",check:"yarn prettier --check .",write:"yarn prettier --write .",lint:"eslint --ext .ts src -c .eslintrc.cjs","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"},qa={"@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","@typescript-eslint/eslint-plugin":"^5.35.1","@typescript-eslint/parser":"^5.35.1",eslint:"^8.0.1","eslint-config-prettier":"^8.5.0","just-bash":"3.6.0",prettier:"2.7.1",pyodide:"314.0.7",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0",vitest:"^0.34.6"},Ha={access:"public",registry:"https://registry.npmjs.org/"},za={"@glodon-aiot/apis":"^3.26.0-alpha.34",axios:"0.24.0",dayjs:"^1.11.13","js-base64":"^3.7.7","socket.io-client":"^4.7.5",uuid:"^11.1.0"},Wa={name:Ta,version:La,author:Ra,description:Ma,type:Ca,sideEffects:Fa,keywords:Oa,files:Na,module:$a,main:Pa,typings:Da,exports:Ba,license:ja,scripts:Ua,devDependencies:qa,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:Ha,dependencies:za},z=new B("[BotClient] ");class Va{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){y(this,"event",new bn);y(this,"cvforceApi");y(this,"_applicationId");y(this,"_application",null);y(this,"_sessions",[]);y(this,"_activeSession");y(this,"_ready",!1);y(this,"_questionContextMaxLength",4e3);y(this,"_promptVariables",[]);y(this,"_localWorkspace");y(this,"_disconnectHost");y(this,"arrangeSkillEpoch",0);if(this._token=e,this.lazyload=i,this.sdkConfigs=s,Xt(t,{refreshBuiltinPlugins:!1}),this._applicationId=ht(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),rs(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{Xt(S(b({},t),{stream:t.stream===void 0?(r==null?void 0:r.type)===x.ApplicationTypes.Dialog||(r==null?void 0:r.type)===x.ApplicationTypes.Agent:t.stream})),this.logReady(),this.event.emit("ready")})}logReady(){var e,t;z.log("ready",{applicationId:this._applicationId,type:(e=this._application)==null?void 0:e.type,stream:exports.configuration.stream,workspace:(t=this._localWorkspace)==null?void 0:t.status})}setupLocalWorkspace(){var s,r,o;const e=(s=exports.configuration.builtinPlugins)==null?void 0:s.localFiles;if(!(e!=null&&e.enabled)){z.log("workspace:disabled"),ei(void 0),Ue();return}z.log("workspace:setup",{backend:(r=e.backend)!=null?r:"file-system-access"});const t=[],i=(o=e.backend)!=null?o:"file-system-access";if(i!=="file-system-access"&&i!=="host-bridge")t.push(new Error(`[LocalFiles] 不支持的 backend:${e.backend}`));else{const a=mo(exports.configuration.apiRoot,this.token,(c,l)=>z.error(l));this._localWorkspace=new hs({applicationId:this._applicationId,config:e,store:ls(),picker:i==="host-bridge"?null:void 0,transfer:kn(()=>this.cvforceApi,()=>a)}),ei(this._localWorkspace),this._localWorkspace.platformSkills=new _o({applicationId:()=>this._applicationId,getToken:()=>this.token,getSkills:()=>{var c,l,h,u;return(u=(h=(l=(c=this._application)==null?void 0:c.arrange)==null?void 0:l[0])==null?void 0:h.skills)!=null?u:[]},apiRoot:()=>exports.configuration.apiRoot,getSandbox:()=>{var l;const c=(l=this._localWorkspace)==null?void 0:l.adapter;return c instanceof He?c.sandbox:void 0}}),i==="host-bridge"?this._disconnectHost=So(this._localWorkspace):this._localWorkspace.restore()}t.push(...Ue()),t.length&&Promise.resolve().then(()=>t.forEach(a=>this.event.emit("error",a)))}get localWorkspace(){return this._localWorkspace}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return d(this,null,function*(){var t,i,s,r,o;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(i=this.sdkConfigs.ui)==null?void 0:i.version,sdkVersion:Wa.version}).then(a=>(typeof a.arrange[0].thinkingModeOpen!="boolean"&&(a.arrange[0].thinkingModeOpen=!0),typeof a.arrange[0].thinkingTextOpen!="boolean"&&(a.arrange[0].thinkingTextOpen=!0),S(b({},a),{arrange:[S(b({},a.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&a.arrange[0].recommendQuestionOpen})]})));const e=(o=(r=(s=this._application)==null?void 0:s.arrange)==null?void 0:r[0])==null?void 0:o.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(a=>a.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type:x.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:x.PromptVariableType.System})]).then(([a,c])=>[...a,...c]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:es(exports.configuration.apiRoot,this.token,(e,t)=>z.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=ht(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.logReady(),this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,i,s,r){return d(this,null,function*(){const o=this;return new Promise((a,c)=>{const l=h=>d(this,null,function*(){if(h===x.ApplicationTypes.Agent)a(new ba(e,t,i,s,r,o));else if(h===x.ApplicationTypes.Dialog)a(new xa(e,t,i,s,r,o));else throw Error(`不支持的应用类型:${h}`)});if(this.ready){if(!this._application)throw Error("client is not ready");l(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");l(this._application.type)},!0)})})}getArtifacts(e){return d(this,null,function*(){var r,o;this.checkReady();const t=e||((r=this._activeSession)==null?void 0:r.id);if(!t)throw new Error("session id is not defined");const i=this._sessions.find(a=>a.id===t);if(i)return i.getArtifacts();const s=yield this.cvforceApi.getSessionArtifacts(this._applicationId,t);return(o=s==null?void 0:s.artifacts)!=null?o:[]})}getSessions(e){return d(this,null,function*(){return new Promise((t,i)=>{const s=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>d(this,null,function*(){const o=[];for(const a of r){const c=this._sessions.find(l=>l.id===a.id);if(c)c.data=a,this._application?c.application=this._application:yield c.loadApplicationInfo(),o.push(c);else{const l=yield this.createSession(this.token,a.id,a,this.lazyload,this._application||void 0);o.push(l)}}if(z.log("sessions",{count:o.length,paged:!!(e!=null&&e.pageSize)}),e!=null&&e.pageSize){const a=[...this._sessions,...o],c=new Map;for(const l of a)c.set(l.id,l);return this.sessions=Array.from(c.values()),this.sessions}else return this.sessions=o,o}));if(this.ready){if(!this._application)throw Error("_application is null");t(s())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(s())},!0)})})}refreshArrangeSkills(){return d(this,null,function*(){var i,s,r;const e=(s=(i=this._application)==null?void 0:i.arrange)==null?void 0:s[0],t=++this.arrangeSkillEpoch;try{yield wo({arrange:e,fetchApplication:()=>this.cvforceApi.getApplicationId(this._applicationId),stillCurrent:()=>{var a,c;return t===this.arrangeSkillEpoch&&((c=(a=this._application)==null?void 0:a.arrange)==null?void 0:c[0])===e}});const o=(r=e==null?void 0:e.skills)!=null?r:[];z.log("arrange:skills",o.map(a=>a.name).filter(Boolean))}catch(o){z.error("刷新编排技能失败",o)}})}loadSession(e="",t){return d(this,null,function*(){var s,r;this.checkReady(),yield this.refreshArrangeSkills(),(r=(s=this._localWorkspace)==null?void 0:s.platformSkills)==null||r.sync();let i=this.sessions.find(o=>o.id===e);if(z.log("loadSession",{sessionId:e||"(new)",existing:!!i}),i||(i=yield this.createSession(this.token,e,t),this._sessions.push(i)),this._activeSession){if(this._activeSession===i)return i;this._activeSession.inactivate()}return i.id?(this._activeSession=i,yield i.activate()):i.addEventListener("data:loaded",()=>{this._activeSession!==i&&(i==null||i.activate(),this._activeSession=i)},!0),i})}reload(){return this.loadApplication().then(()=>d(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return d(this,null,function*(){yield this.reload();let t=this._sessions.find(i=>i.id===e)||this._activeSession;if(!t){z.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,i="top_time desc, sort_status desc, updated_at desc"){return d(this,null,function*(){let s=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!s){z.warn("setTop session failed.");return}return yield s.setTop(t),this.getSessions({order:i})})}addEventListener(e,t,i=!1){if(typeof t!="function")throw Error("event listener is not a function");if(i){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return d(this,null,function*(){this.checkReady();let i=-1;if(typeof e=="string"?i=this._sessions.findIndex(s=>s.id===e):i=this._sessions.findIndex(s=>s.id===e.id),i>-1){const s=this._sessions[i];t&&(yield s.delete()),this._sessions.splice(i,1)}else z.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 Ga{constructor(e,t={},i){y(this,"code");y(this,"description","");y(this,"loaded",!1);y(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}const K="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",J={type:"string",enum:[Te],description:`工作区 ID。省略时按 ${Te} 处理,传其他值会被拒绝。`},Q=n=>({type:"string",description:`${n}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),Pt={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},us={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${K}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:J,path:Q('要列出的目录,省略或传 "." 表示工作区根目录。'),offset:{type:"integer",minimum:0,description:"分页起始位置,默认 0。"},limit:{type:"integer",minimum:1,maximum:1e3,description:"每页条数,默认 200。"}}}},read_file:{functionCode:"read_file",name:"读取本地文件",description:`${K}按行读取文本文件,单次最多返回 1 MiB,超出部分会被截断(truncated: true)。返回内容的 hash 可用于后续修改。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:J,path:Q("要读取的文件。"),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:`${K}返回文件或目录的类型、大小、修改时间,可选返回 hash。不返回文件内容。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:J,path:Q("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${K}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:J,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:Q("搜索起点目录,默认工作区根目录。"),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:`${K}在指定文件或目录(递归)中搜索普通文本(不支持正则),返回所在文件、行号与该行内容。必须指定 path,不能搜索整个文件夹。`,parameters:{type:"object",required:["grantId","path","query"],properties:{grantId:J,path:Q("搜索范围,可以是文件或目录。"),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:`${K}以查找替换的方式修改 UTF-8 文本文件。每条修改的 oldText 必须在文件中唯一出现(或设置 replaceAll)。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","expectedHash","edits"],properties:{grantId:J,path:Q("要修改的文件。"),expectedHash:Pt,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:`${K}新建文件,或整体覆盖已有文件(覆盖时必须提供 expectedHash)。修改已有文件优先使用 apply_patch。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","content"],properties:{grantId:J,path:Q("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:Pt,createDirectories:{type:"boolean",description:"父目录不存在时是否自动创建,默认否。"}}}},upload_file:{functionCode:"upload_file",name:"上传本地文件",description:`${K}把本地文件夹中的文件上传到平台文件服务,返回 fileId、name、size 和 url。url 是文件访问地址,可直接用于后续推理或对话。下载回本地文件夹时使用 download_file,source.type 为 platformFile。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:J,path:Q("要上传的文件。"),target:{type:"string",description:"上传目标,目前只支持 session(默认),其他值返回 501。"},mimeHint:{type:"string",description:"可选的 MIME 类型。"}}}},download_file:{functionCode:"download_file",name:"下载到本地文件夹",description:`${K}把会话文件、平台文件或 https 地址保存到本地文件夹。source.type 为 url 时必须同时填写 source.url(完整地址),为 sessionFile 或 platformFile 时必须同时填写 source.fileId。不要只传 type。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","destPath","source"],properties:{grantId:J,destPath:Q("保存位置(文件路径)。"),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:Pt}}}},Xa=new TextEncoder;function se(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const Ya=(n,e)=>d(exports,null,function*(){const t=te(n.path,{allowRoot:!0});if((yield e.adapter.stat(t)).kind!=="directory")throw new m(g.BadRequest,"目标是文件,不是目录。");const s=se(n.offset,0,0,Number.MAX_SAFE_INTEGER),r=se(n.limit,_i,1,ki),o=yield e.adapter.listEntries(t,e.signal);o.sort((c,l)=>c.kind!==l.kind?c.kind==="directory"?-1:1:c.name<l.name?-1:c.name>l.name?1:0);const a=o.slice(s,s+r).map(c=>{const l=os(t,c.name),h={name:c.name,path:l,kind:c.kind};return c.kind==="file"&&(h.size=c.size,h.lastModified=c.lastModified,e.sensitive.isSensitive(l)&&(h.sensitive=!0)),h});return{data:{path:t,entries:a,total:o.length,hasMore:s+a.length<o.length}}});function Ka(n,e,t){return ge(this,null,function*(){var a;const i=new TextDecoder(e),s=n.stream().getReader();let r="",o=!1;try{for(;;){N(t);const{done:c,value:l}=yield new re(s.read());r+=c?i.decode():i.decode(l,{stream:!0});const h=r.split(`
378
+ `);r=(a=h.pop())!=null?a:"";for(const u of h)o=!0,yield u;if(c)break}}finally{s.releaseLock()}(r||!o)&&(yield r)})}const Ja=(n,e)=>d(exports,null,function*(){var I,M;const t=te(n.path);Ce(e,t,"read");const i=yield hn(e.adapter,t),s=yield e.adapter.readFile(t),r=(I=i.size)!=null?I:s.size;if(yield Ks(s))throw new m(g.BadRequest,"这是二进制文件,不能按文本读取。可以使用 stat_file 查看信息,或使用 upload_file 上传到会话。");const o=yield Y(s.slice(0,3)),a=qi(o)?"utf-8":(M=n.encoding)!=null?M:"utf-8",c=se(n.startLine,1,1,Number.MAX_SAFE_INTEGER),l=n.endLine===void 0?Number.MAX_SAFE_INTEGER:Math.max(Math.trunc(n.endLine),c),h=se(n.maxBytes,e.limits.maxReadBytes,1,e.limits.maxReadBytes),u=r<=e.limits.maxTransferBytes,f=[];let p=0,w=0,_=c-1,v=!1,A=!1;try{for(var q=X(Ka(s,a,e.signal)),D,C,R;D=!(C=yield q.next()).done;D=!1){const F=C.value;w++;const W=F.endsWith("\r")?F.slice(0,-1):F;if(W!==F&&(A=!0),w<c||w>l||v){if(!u&&(v||w>l))break;continue}const H=un(W)+(f.length?1:0);if(p+H>h){if(v=!0,f.length||(f.push(Qa(W,h)),_=w),!u)break;continue}f.push(W),p+=H,_=w}}catch(C){R=[C]}finally{try{D&&(C=q.return)&&(yield C.call(q))}finally{if(R)throw R[0]}}const E={path:t,content:f.join(`
379
+ `),startLine:c,endLine:Math.max(_,c-1),size:r,encoding:a,lineEnding:A?"crlf":"lf"};return u&&(E.totalLines=w),r<=e.limits.maxWriteBytes&&(E.hash=yield Re(yield Y(s))),{data:E,truncated:v||void 0}});function Qa(n,e){const t=Xa.encode(n);return t.byteLength<=e?n:new TextDecoder().decode(t.slice(0,e)).replace(/\uFFFD$/,"")}const Za=(n,e)=>d(exports,null,function*(){var r;const t=te(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 Re(yield Y(yield e.adapter.readFile(t))))),{data:s}});function ec(n){return Li.some(e=>lt(e,n))}function fs(n,e,t){return ge(this,null,function*(){const i=[{path:e,depth:0}];let s=0;for(;i.length;){const r=i.shift();N(n.signal),++s%20===0&&(yield new re(Hi()));const o=yield new re(n.adapter.listEntries(r.path,n.signal));o.sort((a,c)=>a.name<c.name?-1:a.name>c.name?1:0);for(const a of o){const c=os(r.path,a.name);if(a.kind==="directory"){r.depth+1<t&&!Ti.includes(a.name)&&i.push({path:c,depth:r.depth+1});continue}ec(a.name)||n.sensitive.match(c,"search")||(yield{path:c,relativePath:e?c.slice(e.length+1):c,name:a.name,size:a.size,lastModified:a.lastModified})}}})}function ps(n,e){return n.includes("/")?lt(n,e.relativePath):lt(n,e.name)}const tc=(n,e)=>d(exports,null,function*(){const t=te(n.path,{allowRoot:!0});if(!n.pattern.trim())throw new m(g.BadRequest,"参数 pattern 不能为空。");const i=n.pattern.replace(/\\/g,"/").replace(/^\.\//,"");if((yield e.adapter.stat(t)).kind!=="directory")throw new m(g.BadRequest,"参数 path 必须是目录。");const r=se(n.maxDepth,Si,1,tn),o=se(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),a=[];let c=!1;try{for(var l=X(fs(e,t,r)),h,u,f;h=!(u=yield l.next()).done;h=!1){const p=u.value;if(ps(i,p)){if(a.length>=o){c=!0;break}a.push({path:p.path,size:p.size,lastModified:p.lastModified})}}}catch(u){f=[u]}finally{try{h&&(u=l.return)&&(yield u.call(l))}finally{if(f)throw f[0]}}return{data:{matches:a},truncated:c||void 0}});function Dt(n,e){if(n.length<=et)return n;const t=Math.max(0,Math.min(e-100,n.length-et));return n.slice(t,t+et)}const nc=(n,e)=>d(exports,null,function*(){var f;const t=te(n.path,{allowRoot:!0});if(!t&&!e.allowWorkspaceWideTextSearch)throw new m(g.BadRequest,"不支持在整个工作区内搜索文本,请把 path 缩小到具体的子目录或文件。");if(n.isRegex)throw new m(g.NotImplemented,"暂不支持正则搜索,请使用普通文本搜索。");if(!n.query)throw new m(g.BadRequest,"参数 query 不能为空。");const i=n.caseSensitive===!0,s=i?n.query:n.query.toLowerCase(),r=se(n.contextLines,0,0,Ai),o=se(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),a=yield e.adapter.stat(t);let c;a.kind==="file"?(Ce(e,t,"search"),c=function(){return ge(this,null,function*(){yield{path:t,relativePath:t,name:a.name,size:a.size}})}()):c=fs(e,t,tn);const l=[];let h=0,u=!1;e:try{for(var p=X(c),w,_,v;w=!(_=yield p.next()).done;w=!1){const A=_.value;if(n.glob&&!ps(n.glob,A)||((f=A.size)!=null?f:0)>Ii)continue;if(h>=Ei){u=!0;break}h++,h%20===0&&(yield Hi()),N(e.signal);const E=yield Y(yield e.adapter.readFile(A.path));if(fe(E))continue;const I=new TextDecoder("utf-8").decode(E).split(/\r?\n/);for(let M=0;M<I.length;M++){const D=(i?I[M]:I[M].toLowerCase()).indexOf(s);if(D<0)continue;if(l.length>=o){u=!0;break e}const C={path:A.path,line:M+1,column:D+1,text:Dt(I[M],D)};r&&(C.before=I.slice(Math.max(0,M-r),M).map(R=>Dt(R,0)),C.after=I.slice(M+1,M+1+r).map(R=>Dt(R,0))),l.push(C)}}}catch(_){v=[_]}finally{try{w&&(_=p.return)&&(yield _.call(p))}finally{if(v)throw v[0]}}return{data:{matches:l,filesScanned:h},truncated:u||void 0}});function pi(){return new m(g.Forbidden,"下载地址不在允许范围内:只允许 https 协议且域名在白名单中的地址。",{reason:"url_not_allowed"})}const ic=(n,e)=>d(exports,null,function*(){var u,f;const t=te(n.path);if(((u=n.target)!=null?u:"session")!=="session")throw new m(g.NotImplemented,"目前只支持上传到当前会话(target: session)。");Ce(e,t,"read");const s=yield hn(e.adapter,t),r=(f=s.size)!=null?f:0;if(r>e.limits.maxTransferBytes)throw he(e.limits.maxTransferBytes);const o=ln(t);yield e.requestApproval(t,{type:"upload",name:o,size:r,target:"session"}),e.progress({stage:"reading",loaded:0,total:r,path:t});const a=yield e.adapter.readFile(t);N(e.signal);const c=new File([a],o,{type:n.mimeHint||a.type||"application/octet-stream",lastModified:s.lastModified}),{fileId:l,url:h}=yield e.transfer.upload(c,e.context,({loaded:p,total:w})=>e.progress({stage:"uploading",loaded:p,total:w,path:t}));return N(e.signal),e.progress({stage:"done",loaded:r,total:r,path:t}),{data:{fileId:l,name:o,size:r,url:h}}});function sc(n){const e=n;if(!e||typeof e!="object")throw new m(g.BadRequest,"缺少参数 source。");if(e.type==="sessionFile"||e.type==="platformFile"){if(typeof e.fileId!="string"||!e.fileId)throw new m(g.BadRequest,"source.fileId 必须是非空字符串。");return{type:e.type,fileId:e.fileId}}if(e.type==="url"){if(typeof e.url!="string"||!e.url)throw new m(g.BadRequest,"source.url 必须是非空字符串。");return{type:"url",url:e.url}}throw new m(g.BadRequest,"source.type 必须是 sessionFile、platformFile 或 url 之一。")}function rc(n){return n.type==="sessionFile"?"会话文件":n.type==="platformFile"?"平台文件":new URL(n.url).hostname}function oc(n,e,t,i,s){return ge(this,null,function*(){const r=n.getReader();let o=0;try{for(;;){N(e.signal);const{done:a,value:c}=yield new re(r.read());if(a)break;if(o+=c.byteLength,o>e.limits.maxTransferBytes)throw he(e.limits.maxTransferBytes,"下载内容");s.push(c),e.progress({stage:"downloading",loaded:o,total:i,path:t}),yield c}}finally{r.cancel().catch(()=>{})}})}const ac=(n,e)=>d(exports,null,function*(){var _,v,A;const t=te(n.destPath,{field:"destPath"}),i=sc(n.source);if(i.type==="url"&&!Jt(i.url,e.downloadUrlAllowlist))throw pi();Ce(e,t,"write");const s=yield nt(e.adapter,t);if((s==null?void 0:s.kind)==="directory")throw new m(g.BadRequest,"目标是目录,不能写入文件。");if(s&&!n.overwrite)throw new m(g.Conflict,"目标文件已存在。如需覆盖,请设置 overwrite: true。");const r=()=>d(exports,null,function*(){if(!s||!n.expectedHash)return;const E=yield Re(yield Y(yield e.adapter.readFile(t)));if(E!==n.expectedHash)throw new m(g.Conflict,"expectedHash 与目标文件当前内容不一致。",{currentHash:E})});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 he(e.limits.maxTransferBytes);const a={type:"download",source:{type:i.type,label:rc(i)},name:(_=o.name)!=null?_:ln(t),size:o.size,overwrite:!!s};yield e.requestApproval(t,a),yield r();let c;try{c=yield e.fetch(o.url,{headers:o.headers,credentials:"omit",redirect:"follow",signal:e.signal})}catch(E){throw N(e.signal),new m(g.Internal,"下载失败,无法连接到文件地址。")}if(i.type==="url"&&c.url&&!Jt(c.url,e.downloadUrlAllowlist))throw(v=c.body)==null||v.cancel().catch(()=>{}),pi();if(!c.ok||!c.body)throw(A=c.body)==null||A.cancel().catch(()=>{}),new m(c.status===404?g.NotFound:g.Internal,`下载失败(HTTP ${c.status})。`);const l=Number(c.headers.get("content-length")),h=Number.isFinite(l)&&l>0?l:void 0;if(h!==void 0&&h>e.limits.maxTransferBytes)throw c.body.cancel().catch(()=>{}),he(e.limits.maxTransferBytes);const u=[];yield e.adapter.writeFile(t,oc(c.body,e,t,h,u),{signal:e.signal});const f=u.reduce((E,I)=>E+I.byteLength,0),p=new Uint8Array(f);let w=0;return u.forEach(E=>{p.set(E,w),w+=E.byteLength}),e.progress({stage:"done",loaded:f,total:f,path:t}),{data:{path:t,size:f,hash:yield Re(p)}}}),Bt=new Uint8Array([239,187,191]);function pt(n,e){return new m(g.Conflict,e,{currentHash:n})}function In(n,e){return d(this,null,function*(){var s;if(((s=(yield hn(n.adapter,e)).size)!=null?s:0)>n.limits.maxWriteBytes)throw he(n.limits.maxWriteBytes,"目标文件");const i=yield Y(yield n.adapter.readFile(e));return{bytes:i,hash:yield Re(i)}})}function ms(n,e,t){return d(this,null,function*(){const{hash:i}=yield In(n,e);if(i!==t)throw pt(i,"文件在确认期间已被修改,本次写入已取消。请重新读取后再修改。")})}function cc(n,e){const t=new TextEncoder().encode(n);if(!e)return t;const i=new Uint8Array(Bt.byteLength+t.byteLength);return i.set(Bt,0),i.set(t,Bt.byteLength),i}function lc(n,e){let t=0,i=n.indexOf(e);for(;i>=0;)t++,i=n.indexOf(e,i+e.length);return t}function mi(n,e){return!e||n.includes(`\r
380
380
  `)?n:n.replace(/\n/g,`\r
381
- `)}function fs(n,e,t,i=!1){return d(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 Te(t),size:t.byteLength}})}const sc=(n,e)=>d(exports,null,function*(){const t=ee(n.path);if(Me(e,t,"write"),!n.edits.length)throw new m(g.BadRequest,"参数 edits 不能为空。");const{bytes:i,hash:s}=yield kn(e,t);if(s!==n.expectedHash)throw ht(s,"expectedHash 与文件当前内容不一致,请重新读取文件后再修改。");const r=ji(i),o=Xs(r?i.subarray(3):i),a=o.includes(`\r
382
- `);let c=o;n.edits.forEach((h,u)=>{if(typeof(h==null?void 0:h.oldText)!="string"||!h.oldText||typeof h.newText!="string")throw new m(g.BadRequest,`第 ${u+1} 条修改无效:oldText 必须是非空字符串,newText 必须是字符串。`);const f=fi(h.oldText,a),p=fi(h.newText,a),y=ic(c,f);if(y===0)throw new m(g.Conflict,`第 ${u+1} 条修改的 oldText 在文件中不存在,请重新读取文件确认当前内容。`);if(y>1&&!h.replaceAll)throw new m(g.BadRequest,`第 ${u+1} 条修改的 oldText 在文件中出现了 ${y} 次,请补充上下文使其唯一,或设置 replaceAll。`);c=h.replaceAll?c.split(f).join(p):c.replace(f,()=>p)});const l=nc(c,r);if(l.byteLength>e.limits.maxWriteBytes)throw he(e.limits.maxWriteBytes,"修改后的内容");return yield e.requestApproval(t,{type:"text",before:o,after:c,created:!1}),yield us(e,t,s),{data:yield fs(e,t,l)}}),rc=(n,e)=>d(exports,null,function*(){const t=ee(n.path);Me(e,t,"write");const i=yield et(e.adapter,t);if((i==null?void 0:i.kind)==="directory")throw new m(g.BadRequest,"目标是目录,不能写入文件。");let s,r;if(i){const c=yield kn(e,t);if(r=c.hash,!n.expectedHash)throw ht(r,"目标文件已存在,覆盖前需要提供 expectedHash(可通过 read_file 或 stat_file 获取)。");if(n.expectedHash!==r)throw ht(r,"expectedHash 与文件当前内容不一致,请重新读取文件后再写入。");s=new TextDecoder("utf-8").decode(c.bytes)}else if(!n.createDirectories){const c=le(t),l=c?yield et(e.adapter,c):{kind:"directory"};if(!l)throw new m(g.NotFound,"父目录不存在,可设置 createDirectories 自动创建。");if(l.kind!=="directory")throw new m(g.BadRequest,"父路径不是目录。")}const o=new TextEncoder().encode(n.content);if(o.byteLength>e.limits.maxWriteBytes)throw he(e.limits.maxWriteBytes,"写入内容");if(yield e.requestApproval(t,{type:"text",before:s,after:n.content,created:!i}),r)yield us(e,t,r);else if(yield et(e.adapter,t))throw new m(g.Conflict,"目标文件在确认期间被创建,本次写入已取消。请重新检查后再写入。");const a=yield fs(e,t,o,n.createDirectories);return{data:E(b({},a),{created:!i})}}),oc={list_directory:Ha,read_file:Wa,stat_file:Ga,search_files:Ya,search_text:Ka,apply_patch:sc,write_file:rc,upload_file:Ja,download_file:tc};class ac{constructor(e,t){v(this,"remaining");v(this,"startedAt",0);v(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 cc(n,e){return Li.includes(e)?n.limits.transferTimeoutMs:Ti.includes(e)?n.limits.searchTimeoutMs:n.limits.toolTimeoutMs}function lc(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch(e){throw new m(g.BadRequest,"参数不是合法的 JSON 对象。")}}function dc(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=xe),e.grantId}function ps(n){return new Promise((e,t)=>{n.aborted&&t(B()),n.addEventListener("abort",()=>t(B()),{once:!0})})}function hc(n){return b({code:n.code,message:n.message},n.data?{data:n.data}:{})}function uc(n,e,t,i,s){return d(this,null,function*(){var y,w,_,A,I,S,L,j;const r={requestId:s.requestId||ne.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},a=new AbortController;let c=!1;const l=new ac(cc(n,e),()=>{c=!0,a.abort()}),h=()=>a.abort();(y=r.signal)==null||y.addEventListener("abort",h,{once:!0}),(w=r.signal)!=null&&w.aborted&&a.abort();let u=null,f,p=!1;try{const $=lc(t),M=dc($);M!=null&&Io(M);const T=Ni($,ls[e].parameters),R=(_=T.path)!=null?_:T.destPath;if(typeof R=="string"&&(o.path=R),yield n.ready,a.signal.aborted)throw B();const H=n.adapter;if(!H)throw ut();if(u=n.acquireSlot(),!u)throw new m(g.TooManyRequests,"同时进行的文件操作过多,请稍后重试。");f=n.track(a),p=!0,n.emit("tool:start",b({},o)),l.resume();const U={adapter:H,workspaceName:(A=n.displayName)!=null?A:H.displayName,limits:n.limits,sensitive:n.sensitive,downloadUrlAllowlist:n.downloadUrlAllowlist,allowWorkspaceWideTextSearch:n.allowWorkspaceWideTextSearch,transfer:n.transfer,fetch:n.fetch,context:E(b({},r),{signal:a.signal}),signal:a.signal,requestApproval:(Fe,me)=>fc(n,{approvalPath:Fe,preview:me,context:r,functionCode:e,signal:a.signal,timer:l,base:o}),progress:Fe=>n.emit("tool:progress",b(b({},o),Fe))},pe=yield Promise.race([oc[e](T,U),ps(a.signal)]),Ce={code:g.Ok,message:"ok",data:pe.data};pe.truncated&&(Ce.truncated=!0),(I=pe.warnings)!=null&&I.length&&(Ce.warnings=pe.warnings),n.emit("tool:finish",E(b({},o),{code:g.Ok})),i(Ce)}catch($){let M=Ae($);c?M=new m(g.Timeout,"操作超时,已中止。"):a.signal.aborted&&M.code!==g.Cancelled&&(M=B()),((S=M.data)==null?void 0:S.reason)==="workspace_not_granted"&&p&&n.handlePermissionLost(),M.code===g.Cancelled?n.emit("tool:cancelled",b({},o)):n.emit("tool:error",E(b({},o),{code:M.code,message:M.message,reason:(L=M.data)==null?void 0:L.reason})),i(hc(M))}finally{l.clear(),(j=r.signal)==null||j.removeEventListener("abort",h),u==null||u(),f==null||f()}})}function fc(n,e){return d(this,null,function*(){var a;const t=n.getApprovalHandler();if(!t)throw new m(g.Forbidden,"当前环境未提供操作确认能力,无法执行写入或传输操作。",{reason:"approval_unavailable"});if(e.signal.aborted)throw B();const i=new AbortController,s=()=>i.abort();e.signal.addEventListener("abort",s,{once:!0});const r={id:ne.v4(),requestId:e.context.requestId,sessionId:e.context.sessionId,functionCode:e.functionCode,path:e.approvalPath,workspaceName:(a=n.displayName)!=null?a:"",preview:e.preview,signal:i.signal};e.timer.pause(),n.emit("tool:approval-required",E(b({},e.base),{path:e.approvalPath,approvalId:r.id}));let o;try{const c=yield Promise.race([Promise.resolve().then(()=>t(r)),ps(i.signal),new Promise(l=>{o=setTimeout(()=>l(!1),n.limits.approvalTimeoutMs)})]);if(e.signal.aborted)throw B();if(c!==!0)throw new m(g.Forbidden,"用户拒绝了本次操作。",{reason:"user_rejected"})}catch(c){throw c instanceof m?c:new m(g.Forbidden,"操作确认失败,已取消本次操作。",{reason:"user_rejected"})}finally{clearTimeout(o),e.signal.removeEventListener("abort",s),i.abort(),e.timer.resume()}})}function pc({pluginCode:n,workspace:e}){const t={};return Jt.forEach(i=>{t[i]=(s,r,o)=>{let a=!1;uc(e,i,s,l=>{if(!a){a=!0;try{r(l)}catch(h){console.error("[LocalFiles] callback failed",h)}}},E(b({},o),{pluginCode:n}))}}),{[n]:t}}function pi(){return{kind:"directory",children:new Map}}class mc{constructor(e={},t="memory-workspace"){v(this,"root",pi());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),a=typeof t=="string"?new TextEncoder().encode(t):t;o.children.set(r,{kind:"file",data:a,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 k("NotFoundError");r=pi(),i.children.set(s,r)}if(r.kind!=="directory")throw k("TypeMismatchError");i=r}return i}resolveNode(e){const t=O(e),i=t.pop();if(i===void 0)return this.root;const s=this.resolveDirectory(t).children.get(i);if(!s)throw k("NotFoundError");return s}stat(e){return d(this,null,function*(){var s;const t=this.resolveNode(e),i=(s=O(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 d(this,null,function*(){F(t);const i=this.resolveDirectory(O(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 d(this,null,function*(){const t=this.resolveNode(e);if(t.kind!=="file")throw k("TypeMismatchError");return new Blob([t.data])})}writeFile(s,r){return d(this,arguments,function*(e,t,i={}){const o=O(e),a=o.pop();if(!a)throw k("TypeMismatchError");const c=this.resolveDirectory(o,i.createDirectories),l=c.children.get(a);if((l==null?void 0:l.kind)==="directory")throw k("TypeMismatchError");const h=[];let u=0;try{for(var y=G(ft(t)),w,_,A;w=!(_=yield y.next()).done;w=!1){const I=_.value;F(i.signal),h.push(I),u+=I.byteLength}}catch(_){A=[_]}finally{try{w&&(_=y.return)&&(yield _.call(y))}finally{if(A)throw A[0]}}F(i.signal);const f=new Uint8Array(u);let p=0;h.forEach(I=>{f.set(I,p),p+=I.byteLength}),c.children.set(a,{kind:"file",data:f,lastModified:Date.now()})})}createDirectory(e){return d(this,null,function*(){this.resolveDirectory(O(e),!0)})}remove(i){return d(this,arguments,function*(e,t={}){const s=O(e),r=s.pop();if(r===void 0)throw k("InvalidModificationError");const o=this.resolveDirectory(s),a=o.children.get(r);if(!a)throw k("NotFoundError");if(a.kind==="directory"&&a.children.size>0&&!t.recursive)throw k("InvalidModificationError");o.children.delete(r)})}move(e,t){return d(this,null,function*(){const i=O(e),s=O(t),r=i.pop(),o=s.pop();if(r===void 0||o===void 0)throw k("InvalidModificationError");const a=this.resolveDirectory(i),c=a.children.get(r);if(!c)throw k("NotFoundError");const l=this.resolveDirectory(s);if(Mi(e,t))throw k("InvalidModificationError");const h=l.children.get(o);if(h&&(h.kind==="directory"||c.kind==="directory"))throw k("InvalidModificationError");a.children.delete(r),l.children.set(o,c)})}}exports.AgentPlugin=Ua;exports.BINARY_SNIFF_BYTES=Zt;exports.BUILTIN_TOOLS_PLUGIN_CODE=Ne;exports.BUILTIN_TOOLS_PLUGIN_CODES=mi;exports.BUILTIN_TOOL_SCHEMAS=dn;exports.BotClient=ja;exports.DEFAULT_DOWNLOAD_URL_ALLOWLIST=Ii;exports.DEFAULT_IGNORED_DIRECTORIES=xi;exports.DEFAULT_IGNORED_FILE_PATTERNS=Ai;exports.DEFAULT_LIMITS=Je;exports.FileSystemAccessAdapter=Gt;exports.HOST_BRIDGE_GLOBAL=it;exports.HOST_CHANNEL=en;exports.KiB=yi;exports.LIST_DIRECTORY_DEFAULT_LIMIT=vi;exports.LIST_DIRECTORY_MAX_LIMIT=bi;exports.LOCAL_FILES_FUNCTION_CODES=Jt;exports.LOCAL_FILES_PLUGIN_CODES=gi;exports.LOCAL_FILE_TOOL_SCHEMAS=ls;exports.LocalWorkspace=cs;exports.MemoryWorkspaceAdapter=mc;exports.MiB=Be;exports.SANDBOX_MAX_FILE_BYTES=Ri;exports.SDK_SENSITIVE_BASELINE=Bi;exports.SEARCH_DEFAULT_DEPTH=_i;exports.SEARCH_FUNCTION_CODES=Ti;exports.SEARCH_MAX_DEPTH=Qt;exports.Session=_n;exports.TEXT_SEARCH_MAX_CONTEXT_LINES=Si;exports.TEXT_SEARCH_MAX_FILES=ki;exports.TEXT_SEARCH_MAX_FILE_BYTES=Ei;exports.TEXT_SEARCH_MAX_LINE_CHARS=Qe;exports.TRANSFER_FILE_SIZE_LIMIT_MB=wi;exports.TRANSFER_FUNCTION_CODES=Li;exports.ToolCode=g;exports.ToolError=m;exports.WORKSPACE_GRANT_ID=xe;exports.WRITE_FUNCTION_CODES=ks;exports.WorkspaceFiles=as;exports.configure=Wt;exports.createDefaultSessionFileTransfer=vn;exports.createIndexedDbStore=os;exports.createLocalFilesPlugin=pc;exports.createMemoryStore=bn;exports.getDownloadUrlAllowlist=wn;exports.getRegisteredLocalFilesPluginCode=ao;exports.isDownloadUrlAllowed=Ro;exports.normalizeFilePath=W;exports.registerHostBridge=Is;exports.resolveLocalFilesPluginCode=Yi;exports.toToolError=Ae;
381
+ `)}function gs(n,e,t,i=!1){return d(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 Re(t),size:t.byteLength}})}const dc=(n,e)=>d(exports,null,function*(){const t=te(n.path);if(Ce(e,t,"write"),!n.edits.length)throw new m(g.BadRequest,"参数 edits 不能为空。");const{bytes:i,hash:s}=yield In(e,t);if(s!==n.expectedHash)throw pt(s,"expectedHash 与文件当前内容不一致,请重新读取文件后再修改。");const r=qi(i),o=Js(r?i.subarray(3):i),a=o.includes(`\r
382
+ `);let c=o;n.edits.forEach((h,u)=>{if(typeof(h==null?void 0:h.oldText)!="string"||!h.oldText||typeof h.newText!="string")throw new m(g.BadRequest,`第 ${u+1} 条修改无效:oldText 必须是非空字符串,newText 必须是字符串。`);const f=mi(h.oldText,a),p=mi(h.newText,a),w=lc(c,f);if(w===0)throw new m(g.Conflict,`第 ${u+1} 条修改的 oldText 在文件中不存在,请重新读取文件确认当前内容。`);if(w>1&&!h.replaceAll)throw new m(g.BadRequest,`第 ${u+1} 条修改的 oldText 在文件中出现了 ${w} 次,请补充上下文使其唯一,或设置 replaceAll。`);c=h.replaceAll?c.split(f).join(p):c.replace(f,()=>p)});const l=cc(c,r);if(l.byteLength>e.limits.maxWriteBytes)throw he(e.limits.maxWriteBytes,"修改后的内容");return yield e.requestApproval(t,{type:"text",before:o,after:c,created:!1}),yield ms(e,t,s),{data:yield gs(e,t,l)}}),hc=(n,e)=>d(exports,null,function*(){const t=te(n.path);Ce(e,t,"write");const i=yield nt(e.adapter,t);if((i==null?void 0:i.kind)==="directory")throw new m(g.BadRequest,"目标是目录,不能写入文件。");let s,r;if(i){const c=yield In(e,t);if(r=c.hash,!n.expectedHash)throw pt(r,"目标文件已存在,覆盖前需要提供 expectedHash(可通过 read_file 或 stat_file 获取)。");if(n.expectedHash!==r)throw pt(r,"expectedHash 与文件当前内容不一致,请重新读取文件后再写入。");s=new TextDecoder("utf-8").decode(c.bytes)}else if(!n.createDirectories){const c=le(t),l=c?yield nt(e.adapter,c):{kind:"directory"};if(!l)throw new m(g.NotFound,"父目录不存在,可设置 createDirectories 自动创建。");if(l.kind!=="directory")throw new m(g.BadRequest,"父路径不是目录。")}const o=new TextEncoder().encode(n.content);if(o.byteLength>e.limits.maxWriteBytes)throw he(e.limits.maxWriteBytes,"写入内容");if(yield e.requestApproval(t,{type:"text",before:s,after:n.content,created:!i}),r)yield ms(e,t,r);else if(yield nt(e.adapter,t))throw new m(g.Conflict,"目标文件在确认期间被创建,本次写入已取消。请重新检查后再写入。");const a=yield gs(e,t,o,n.createDirectories);return{data:S(b({},a),{created:!i})}}),uc=new B("[LocalFiles] "),fc={list_directory:Ya,read_file:Ja,stat_file:Za,search_files:tc,search_text:nc,apply_patch:dc,write_file:hc,upload_file:ic,download_file:ac};class pc{constructor(e,t){y(this,"remaining");y(this,"startedAt",0);y(this,"handle");this.onTimeout=t,this.remaining=e}resume(){this.handle!==void 0||this.remaining<=0||(this.startedAt=Date.now(),this.handle=setTimeout(()=>{this.handle=void 0,this.remaining=0,this.onTimeout()},this.remaining))}pause(){this.handle!==void 0&&(clearTimeout(this.handle),this.handle=void 0,this.remaining-=Date.now()-this.startedAt)}clear(){this.pause(),this.remaining=0}}function mc(n,e){return Mi.includes(e)?n.limits.transferTimeoutMs:Ri.includes(e)?n.limits.searchTimeoutMs:n.limits.toolTimeoutMs}function gc(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch(e){throw new m(g.BadRequest,"参数不是合法的 JSON 对象。")}}function yc(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=Te),e.grantId}function ys(n){return new Promise((e,t)=>{n.aborted&&t(U()),n.addEventListener("abort",()=>t(U()),{once:!0})})}function wc(n){return b({code:n.code,message:n.message},n.data?{data:n.data}:{})}function vc(n,e,t,i,s){return d(this,null,function*(){var w,_,v,A,E,I,M,q;const r={requestId:s.requestId||ie.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},a=new AbortController;let c=!1;const l=new pc(mc(n,e),()=>{c=!0,a.abort()}),h=()=>a.abort();(w=r.signal)==null||w.addEventListener("abort",h,{once:!0}),(_=r.signal)!=null&&_.aborted&&a.abort();let u=null,f,p=!1;try{const D=gc(t),C=yc(D);C!=null&&Ro(C);const R=Pi(D,us[e].parameters),F=(v=R.path)!=null?v:R.destPath;if(typeof F=="string"&&(o.path=F),yield n.ready,a.signal.aborted)throw U();const W=n.adapter;if(!W)throw mt();if(u=n.acquireSlot(),!u)throw new m(g.TooManyRequests,"同时进行的文件操作过多,请稍后重试。");f=n.track(a),p=!0,n.emit("tool:start",b({},o)),l.resume();const H={adapter:W,workspaceName:(A=n.displayName)!=null?A:W.displayName,limits:n.limits,sensitive:n.sensitive,downloadUrlAllowlist:n.downloadUrlAllowlist,allowWorkspaceWideTextSearch:n.allowWorkspaceWideTextSearch,transfer:n.transfer,fetch:n.fetch,context:S(b({},r),{signal:a.signal}),signal:a.signal,requestApproval:(Ne,me)=>bc(n,{approvalPath:Ne,preview:me,context:r,functionCode:e,signal:a.signal,timer:l,base:o}),progress:Ne=>n.emit("tool:progress",b(b({},o),Ne))},pe=yield Promise.race([fc[e](R,H),ys(a.signal)]),Oe={code:g.Ok,message:"ok",data:pe.data};pe.truncated&&(Oe.truncated=!0),(E=pe.warnings)!=null&&E.length&&(Oe.warnings=pe.warnings),n.emit("tool:finish",S(b({},o),{code:g.Ok})),i(Oe)}catch(D){let C=Le(D);c?C=new m(g.Timeout,"操作超时,已中止。"):a.signal.aborted&&C.code!==g.Cancelled&&(C=U()),((I=C.data)==null?void 0:I.reason)==="workspace_not_granted"&&p&&n.handlePermissionLost(),C.code===g.Cancelled?n.emit("tool:cancelled",b({},o)):n.emit("tool:error",S(b({},o),{code:C.code,message:C.message,reason:(M=C.data)==null?void 0:M.reason})),i(wc(C))}finally{l.clear(),(q=r.signal)==null||q.removeEventListener("abort",h),u==null||u(),f==null||f()}})}function bc(n,e){return d(this,null,function*(){var a;const t=n.getApprovalHandler();if(!t)throw new m(g.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:ie.v4(),requestId:e.context.requestId,sessionId:e.context.sessionId,functionCode:e.functionCode,path:e.approvalPath,workspaceName:(a=n.displayName)!=null?a:"",preview:e.preview,signal:i.signal};e.timer.pause(),n.emit("tool:approval-required",S(b({},e.base),{path:e.approvalPath,approvalId:r.id}));let o;try{const c=yield Promise.race([Promise.resolve().then(()=>t(r)),ys(i.signal),new Promise(l=>{o=setTimeout(()=>l(!1),n.limits.approvalTimeoutMs)})]);if(e.signal.aborted)throw U();if(c!==!0)throw new m(g.Forbidden,"用户拒绝了本次操作。",{reason:"user_rejected"})}catch(c){throw c instanceof m?c:new m(g.Forbidden,"操作确认失败,已取消本次操作。",{reason:"user_rejected"})}finally{clearTimeout(o),e.signal.removeEventListener("abort",s),i.abort(),e.timer.resume()}})}function _c({pluginCode:n,workspace:e}){const t={};return en.forEach(i=>{t[i]=(s,r,o)=>{let a=!1;vc(e,i,s,l=>{if(!a){a=!0;try{r(l)}catch(h){uc.report("callback failed",h)}}},S(b({},o),{pluginCode:n}))}}),{[n]:t}}function gi(){return{kind:"directory",children:new Map}}class kc{constructor(e={},t="memory-workspace"){y(this,"root",gi());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),a=typeof t=="string"?new TextEncoder().encode(t):t;o.children.set(r,{kind:"file",data:a,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 k("NotFoundError");r=gi(),i.children.set(s,r)}if(r.kind!=="directory")throw k("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 k("NotFoundError");return s}stat(e){return d(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 d(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 d(this,null,function*(){const t=this.resolveNode(e);if(t.kind!=="file")throw k("TypeMismatchError");return new Blob([t.data])})}writeFile(s,r){return d(this,arguments,function*(e,t,i={}){const o=$(e),a=o.pop();if(!a)throw k("TypeMismatchError");const c=this.resolveDirectory(o,i.createDirectories),l=c.children.get(a);if((l==null?void 0:l.kind)==="directory")throw k("TypeMismatchError");const h=[];let u=0;try{for(var w=X(gt(t)),_,v,A;_=!(v=yield w.next()).done;_=!1){const E=v.value;N(i.signal),h.push(E),u+=E.byteLength}}catch(v){A=[v]}finally{try{_&&(v=w.return)&&(yield v.call(w))}finally{if(A)throw A[0]}}N(i.signal);const f=new Uint8Array(u);let p=0;h.forEach(E=>{f.set(E,p),p+=E.byteLength}),c.children.set(a,{kind:"file",data:f,lastModified:Date.now()})})}createDirectory(e){return d(this,null,function*(){this.resolveDirectory($(e),!0)})}remove(i){return d(this,arguments,function*(e,t={}){const s=$(e),r=s.pop();if(r===void 0)throw k("InvalidModificationError");const o=this.resolveDirectory(s),a=o.children.get(r);if(!a)throw k("NotFoundError");if(a.kind==="directory"&&a.children.size>0&&!t.recursive)throw k("InvalidModificationError");o.children.delete(r)})}move(e,t){return d(this,null,function*(){const i=$(e),s=$(t),r=i.pop(),o=s.pop();if(r===void 0||o===void 0)throw k("InvalidModificationError");const a=this.resolveDirectory(i),c=a.children.get(r);if(!c)throw k("NotFoundError");const l=this.resolveDirectory(s);if(Ci(e,t))throw k("InvalidModificationError");const h=l.children.get(o);if(h&&(h.kind==="directory"||c.kind==="directory"))throw k("InvalidModificationError");a.children.delete(r),l.children.set(o,c)})}}exports.AgentPlugin=Ga;exports.BINARY_SNIFF_BYTES=nn;exports.BUILTIN_TOOLS_PLUGIN_CODE=De;exports.BUILTIN_TOOLS_PLUGIN_CODES=yi;exports.BUILTIN_TOOL_SCHEMAS=fn;exports.BotClient=Va;exports.DEFAULT_DOWNLOAD_URL_ALLOWLIST=xi;exports.DEFAULT_IGNORED_DIRECTORIES=Ti;exports.DEFAULT_IGNORED_FILE_PATTERNS=Li;exports.DEFAULT_LIMITS=Ze;exports.FileSystemAccessAdapter=Kt;exports.HOST_BRIDGE_GLOBAL=ot;exports.HOST_CHANNEL=sn;exports.KiB=vi;exports.LIST_DIRECTORY_DEFAULT_LIMIT=_i;exports.LIST_DIRECTORY_MAX_LIMIT=ki;exports.LOCAL_FILES_FUNCTION_CODES=en;exports.LOCAL_FILES_PLUGIN_CODES=wi;exports.LOCAL_FILE_TOOL_SCHEMAS=us;exports.LocalWorkspace=hs;exports.MemoryWorkspaceAdapter=kc;exports.MiB=je;exports.SANDBOX_MAX_FILE_BYTES=Fi;exports.SDK_SENSITIVE_BASELINE=Ui;exports.SEARCH_DEFAULT_DEPTH=Si;exports.SEARCH_FUNCTION_CODES=Ri;exports.SEARCH_MAX_DEPTH=tn;exports.Session=En;exports.TEXT_SEARCH_MAX_CONTEXT_LINES=Ai;exports.TEXT_SEARCH_MAX_FILES=Ei;exports.TEXT_SEARCH_MAX_FILE_BYTES=Ii;exports.TEXT_SEARCH_MAX_LINE_CHARS=et;exports.TRANSFER_FILE_SIZE_LIMIT_MB=bi;exports.TRANSFER_FUNCTION_CODES=Mi;exports.ToolCode=g;exports.ToolError=m;exports.WORKSPACE_GRANT_ID=Te;exports.WRITE_FUNCTION_CODES=Is;exports.WorkspaceFiles=ds;exports.configure=Xt;exports.createDefaultSessionFileTransfer=kn;exports.createIndexedDbStore=ls;exports.createLocalFilesPlugin=_c;exports.createMemoryStore=Sn;exports.getDownloadUrlAllowlist=_n;exports.getRegisteredLocalFilesPluginCode=lo;exports.isDownloadUrlAllowed=$o;exports.normalizeFilePath=V;exports.registerHostBridge=Ts;exports.resolveLocalFilesPluginCode=Qi;exports.toToolError=Le;