@glodon-aiot/bot-client-sdk 3.26.1 → 3.26.3
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/es/Session.mjs +4 -4
- package/dist/es/package.json.mjs +2 -2
- package/dist/lib/index.js +2 -2
- package/package.json +2 -2
package/dist/es/Session.mjs
CHANGED
|
@@ -28,7 +28,7 @@ var l = (f, e, t) => new Promise((i, s) => {
|
|
|
28
28
|
r((t = t.apply(f, e)).next());
|
|
29
29
|
});
|
|
30
30
|
import { v4 as Q } from "uuid";
|
|
31
|
-
import { parseJWT as q, resolveRelatedQuestionContent as
|
|
31
|
+
import { parseJWT as q, resolveRelatedQuestionContent as U, removeNewlines as N, removeLeadingAndTrailingBackslashes as B } from "./utils.mjs";
|
|
32
32
|
import { ApplicationTypes as R, PromptStatus as H, PromptVariableType as L, ChatMessageRole as A } from "@glodon-aiot/apis";
|
|
33
33
|
import j from "./Logger.mjs";
|
|
34
34
|
import { configuration as S } from "./Config.mjs";
|
|
@@ -612,7 +612,7 @@ class re {
|
|
|
612
612
|
sensitive: !!e.isSensitive,
|
|
613
613
|
hasContent: !!e.content
|
|
614
614
|
}), e;
|
|
615
|
-
const i =
|
|
615
|
+
const i = U(t == null ? void 0 : t.recommendQuestionOpen, t == null ? void 0 : t.relatedQuestionApp, e.content, this.currentUserQuestion());
|
|
616
616
|
if (i === null)
|
|
617
617
|
return h.log("related:skip", {
|
|
618
618
|
recommendQuestionOpen: t == null ? void 0 : t.recommendQuestionOpen
|
|
@@ -631,7 +631,7 @@ class re {
|
|
|
631
631
|
relatedQuesion: o
|
|
632
632
|
}), this.event.emit("message:updated", p), p;
|
|
633
633
|
}
|
|
634
|
-
const a = (n = s.content) == null ? void 0 : n.split("*").map(
|
|
634
|
+
const a = (n = s.content) == null ? void 0 : n.split("*").map(N).map(B).filter((o) => !!o);
|
|
635
635
|
e.relatedQuesion = a, e.index = -3, e.isLoading = !1;
|
|
636
636
|
const c = y(u({}, e), {
|
|
637
637
|
relatedQuesion: a,
|
|
@@ -821,7 +821,7 @@ class re {
|
|
|
821
821
|
r !== void 0 && (t.messageId = r), n !== void 0 && (t.llmModel = n), o !== void 0 && (t.messageTime = o), (s == null ? void 0 : s.usageExtension) != null && (t.usageExtension = s.usageExtension);
|
|
822
822
|
}
|
|
823
823
|
if (i === "over" && (t.index = -1), e.code != null) {
|
|
824
|
-
const r = t.code != null && t.code !== 200;
|
|
824
|
+
const r = t.code != null && t.code !== 0 && t.code !== 200;
|
|
825
825
|
(e.code !== 200 || !r) && (t.code = e.code, t.message = e.message);
|
|
826
826
|
}
|
|
827
827
|
}
|
package/dist/es/package.json.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const s = "@glodon-aiot/bot-client-sdk", t = "3.26.
|
|
1
|
+
const s = "@glodon-aiot/bot-client-sdk", t = "3.26.3", e = "glodoncv", i = "aiot bot client js sdk", n = "module", y = !1, d = [
|
|
2
2
|
"aiot",
|
|
3
3
|
"bot",
|
|
4
4
|
"bot client",
|
|
@@ -49,7 +49,7 @@ const s = "@glodon-aiot/bot-client-sdk", t = "3.26.1", e = "glodoncv", i = "aiot
|
|
|
49
49
|
access: "public",
|
|
50
50
|
registry: "https://registry.npmjs.org/"
|
|
51
51
|
}, m = {
|
|
52
|
-
"@glodon-aiot/apis": "^3.26.
|
|
52
|
+
"@glodon-aiot/apis": "^3.26.3",
|
|
53
53
|
axios: "0.24.0",
|
|
54
54
|
dayjs: "^1.11.13",
|
|
55
55
|
"js-base64": "^3.7.7",
|
package/dist/lib/index.js
CHANGED
|
@@ -367,14 +367,14 @@ ${a.excerpt}`,{line:a.line,excerpt:a.excerpt})}const o=s.slice(0,r)+n.new_text+s
|
|
|
367
367
|
|
|
368
368
|
${zr}
|
|
369
369
|
${i}`}}:{data:{content:t}}})}function Xr(n,e){return d(this,null,function*(){const t=n.path?_n(n.skill_name,n.path):bn(n.skill_name);return{data:{files:yield Xt(n.skill_name,t,e)}}})}function Qr(n,e){return d(this,null,function*(){const t=n.path?_n(n.skill_name,n.path):bn(n.skill_name);let i="";try{i=yield Pe(e).grep(n.skill_name,n.pattern,t,e.signal)}catch(s){kn(s)}return{data:{matches:i}}})}function Yr(n,e){return d(this,null,function*(){if(n.resource_name.startsWith("grep:")){const i=n.resource_name.slice(5);if(!i)throw new g(m.BadRequest,"grep: 后面要写搜索表达式。");bn(n.skill_name);let s="";try{s=yield Pe(e).grep(n.skill_name,i,"",e.signal)}catch(r){kn(r)}return{data:{content:s||"没有匹配。"}}}if(n.resource_name==="."||n.resource_name==="./")return{data:{content:(yield Xt(n.skill_name,"",e))||"(空目录)"}};const t=_n(n.skill_name,n.resource_name.replace(/\/+$/,""));try{return{data:{content:yield Ji(n.skill_name,t,e)}}}catch(i){if(!Wr(i))throw i;return{data:{content:(yield Xt(n.skill_name,t,e))||"(空目录)"}}}})}function Jr(n,e){return d(this,null,function*(){var o;const t=Pe(e);vt(n.skill_name,n.script_name),ft(n.script_name);const i=Vr(e),s=yield t.target(n.skill_name,e.signal),r=t.track(s.skillId,s.version);try{const a=yield i.exec({argv:[ft(n.script_name),n.script_name,...(o=n.args)!=null?o:[]],cwd:cn,timeoutMs:e.timeoutMs,signal:e.signal,skill:s});return{data:{exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr}}}catch(a){throw Qi(a)?new g(m.NotFound,"技能脚本不存在。"):a}finally{r()}})}const Kr={shell:Hr,read_file:Lr,write_file:Mr,append_file:Cr,run_file:qr,edit_file:Fr,grep:Dr,find:jr,load_skill:Gr,read_skill_resource:Yr,list_skill_files:Xr,grep_skill:Qr,run_skill_script:Jr},xe=new B("[BuiltinTools] "),Lt=new Set(["shell","run_file","run_skill_script"]);function Zr(n,e,t){var i,s;if(n.commandRunner)return qt(n.commandRunner);if(e instanceof Ge){if(e.protocolMismatch){const r=`${(i=e.sandboxVersion)!=null?i:""}@${(s=e.sandboxProtocol)!=null?s:""}`;t.rejectedSandbox!==r&&(t.rejectedSandbox=r,xe.error("sandbox-protocol",{sandboxVersion:e.sandboxVersion,sandboxProtocol:e.sandboxProtocol,supported:Ie}))}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=qt(new Er({adapter:e,sensitive:n.sensitive,moduleURL:n.browserRuntime.bashModuleURL,pyodideIndexURL:n.browserRuntime.pyodideIndexURL}))),t.runner}function eo(n,e){if(n.commandRunner)return qt(n.commandRunner);if(e instanceof Ge){if(!e.canExec){const t=e.unavailableMessage();return{exec:()=>Promise.reject(k("NotAllowedError",t))}}return{exec:t=>e.exec(t)}}}function to(n){if(typeof n!="string")return n;try{return JSON.parse(n)}catch(e){throw new g(m.BadRequest,"参数不是合法的 JSON 对象。")}}function no(n){const e=n instanceof DOMException?n.name:"",t=n instanceof Error?n.message:"";if(e==="NotFoundError")return new g(m.NotFound,"脚本或目录不存在。");if(e==="SecurityError")return new g(m.Forbidden,"命令路径不在工作区内。");if(e==="AbortError")return t.includes("超时")?new g(m.Timeout,"命令运行超时,已中止。"):t.includes("已有")||t.includes("上限")?new g(m.TooManyRequests,t):U();if(e==="NotAllowedError"){const i=t.trim();return i&&i!=="NotAllowedError"?new g(m.NotImplemented,i):new g(m.NotImplemented,"当前环境不能执行命令或脚本,需要端侧宿主。")}}function io(n){return new Promise((e,t)=>{n.aborted&&t(U()),n.addEventListener("abort",()=>t(U()),{once:!0})})}function Ki(n,e=160){return n.length>e?`${n.slice(0,e)}…`:n}function so(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=Ki(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 ro(n){return w({code:n.code,message:n.message},n.data?{data:n.data}:{})}function oo({pluginCode:n,workspace:e}){const t=new Map,i={},s={};return zt.forEach(r=>{s[r]=(o,a,c)=>{let l=!1;ao(e,t,i,r,o,u=>{if(!l){l=!0;try{a(u)}catch(f){xe.report("callback failed",f)}}},S(w({},c),{pluginCode:n}))}}),{[n]:s}}function ao(n,e,t,i,s,r,o){return d(this,null,function*(){var E,I,M,q,D;const a={requestId:o.requestId||se.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=Lt.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 v=null,_=null,b;const A=Date.now();try{const C=to(s),L=ji(C,mn[i].parameters);if(typeof L.path=="string"&&(c.path=L.path),xe.log("start",w(w({},c),so(L))),yield n.ready,l.signal.aborted)throw U();const F=n.adapter;if(!F)throw yt();if(Lt.has(i)){if(_=n.acquireCommand(),!_)throw new g(m.TooManyRequests,"已有一个命令在运行,请等它结束后再试。")}else if(v=n.acquireSlot(),!v)throw new g(m.TooManyRequests,"同时进行的文件操作过多,请稍后重试。");b=n.track(l),n.emit("tool:start",w({},c));const W=a.sessionId||"default";let H=e.get(W);H||(H={cwd:cn},e.set(W,H));const ge=Zr(n,F,t),De=H.cwd,Be={adapter:F,runner:ge,signal:l.signal,timeoutMs:u,shellCwd:H,skills:n.platformSkills,skillRunner:eo(n,F)},me=yield Promise.race([Kr[i](L,Be),io(l.signal)]),Rn={code:m.Ok,message:"ok",data:me.data};me.truncated&&(Rn.truncated=!0);const _s=Date.now()-A,Ln=me.data.exitCode;xe.log("finish",w(w(w(S(w({},c),{elapsedMs:_s,code:m.Ok}),me.truncated?{truncated:!0}:{}),typeof Ln=="number"?{exitCode:Ln}:{}),i==="shell"?{cwd:H.cwd,cwdChanged:H.cwd!==De}:{})),n.emit("tool:finish",S(w({},c),{code:m.Ok})),Lt.has(i)&&n.notifyFilesChanged(),r(Rn)}catch(C){let L=(M=no(C))!=null?M:Ce(C);h?L=new g(m.Timeout,"操作超时,已中止。"):l.signal.aborted&&L.code!==m.Cancelled&&(L=U());const F=Date.now()-A;L.code===m.Cancelled?(xe.log("cancelled",S(w({},c),{elapsedMs:F,timedOut:h})),n.emit("tool:cancelled",w({},c))):(xe.error("error",S(w({},c),{elapsedMs:F,code:L.code,message:Ki(L.message,300)})),n.emit("tool:error",S(w({},c),{code:L.code,message:L.message,reason:(q=L.data)==null?void 0:q.reason}))),r(ro(L))}finally{clearTimeout(f),(D=a.signal)==null||D.removeEventListener("abort",p),v==null||v(),_==null||_(),b==null||b()}})}const ti="MCP",bt=new Map;let G=null;function co(n,e,t){bt.set(n,e),G=S(w({},G!=null?G:{}),{[n]:t})}function ni(n){bt.clear(),G=null;for(const e of n)co(e.name,e.binding,e.handler);G&&!Object.keys(G).length&&(G=null)}function lo(n){return bt.get(n)}function ho(){return[...bt.values()]}function uo(n){var e;!G||!Object.keys(G).length||(n[ti]=w(w({},(e=n[ti])!=null?e:{}),G))}const Zi=new B("[Config] ");var es=(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))(es||{});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 Te,ee;const Qt=new Set;function ii(n){Te!==n&&(Te=n,ee=void 0,Qt.clear())}function fo(){if(!ee)return;const{pluginCode:n,table:e}=ee,t=exports.configuration.plugins[n],i=e[n];if(!(!t||t.shell!==i.shell))return n}function ts(n,e){return(n==null?void 0:n.pluginCode)||_i[e]}function po(){var o,a;const n=(o=exports.configuration.businessPlugins)!=null?o:{},e=(a=exports.configuration.builtinPlugins)==null?void 0:a.localFiles,t=[],i=w({},n);if(!!!(e!=null&&e.enabled))return Mt(i),t;if(!Te)return t.push("[BuiltinTools] 内置工具依赖已启用的本地工作区。工具未注册。"),Mt(i),t;const r=e!=null&&e.enabled?ts(e,exports.configuration.env):void 0;return r?n[r]?t.push(`[BuiltinTools] 业务插件中已存在 pluginCode「${r}」,已保留业务插件,内置工具未注册。`):(((ee==null?void 0:ee.workspace)!==Te||ee.pluginCode!==r)&&(ee={workspace:Te,pluginCode:r,table:oo({pluginCode:r,workspace:Te})}),i[r]=ee.table[r]):t.push(`[BuiltinTools] 当前环境(env: ${exports.configuration.env})没有默认的内置工具插件编码,请配置 builtinPlugins.localFiles.pluginCode。内置工具未注册。`),Mt(i),t}function Mt(n){uo(n),exports.configuration.plugins=n}function We(){return po().filter(n=>!Qt.has(n)).map(n=>(Qt.add(n),Zi.report(n),new Error(n)))}function Yt(n,e={}){var t,i,s;B.debug=(n==null?void 0:n.debug)||!1,exports.configuration=S(w(w({},exports.configuration),n),{apiRoot:(n==null?void 0:n.apiRoot)||exports.configuration.apiRoot||(n!=null&&n.env?es[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&&We(),Zi.log("updated",exports.configuration)}const Oe=n=>JSON.parse(Is.decode(n.split(".")[1])),ns=n=>{const e=Oe(n).exp;return new Date().valueOf()/1e3>=e};function Re(n){if(n===null||typeof n!="object")return JSON.stringify(n);if(Array.isArray(n))return`[${n.map(Re).join(",")}]`;const e=n;return`{${Object.keys(e).sort().map(i=>`${JSON.stringify(i)}:${Re(e[i])}`).join(",")}}`}const go=(n,e)=>{const t=Oe(n),i=Oe(e);return t.rid===i.rid&&t.ten===i.ten&&Re(t.ext)===Re(i.ext)&&Re(t.label)===Re(i.label)},mo=n=>n==null?void 0:n.replace(/[\r\n]+/gm,""),yo=n=>n.replace(/\\|\\/g,""),wo=(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 is(n,e,t){return new x.CVForceApi(ss(n,"/data/v1",e,t),rs(t))}function vo(n,e,t){return new x.AIShopApi(ss(n,"/aishop",e,t),rs(t))}function ss(n,e,t,i){const s=o=>{var c;const a=t();return a&&(ns(a)&&i(403,"aiotToken is timeout"),o.headers=(c=o.headers)!=null?c:{},o.headers=S(w({},o.headers),{Authorization:a?`Bearer ${a}`:""})),o};function r(o,a=!0){const c=`${n}${o}`,l=As.create({baseURL:c});return a&&l.interceptors.request.use(s),l}return r(e)}function rs(n){return{onHttpStatusError:(i,s)=>{i===401&&n(i,"aiotToken is invalid")},onAppStatusError:(i,s)=>{i!==10001&&i!==10215&&n(i,s)}}}const Ue=new B("[PlatformSkills] "),bo=20*1024*1024,os=/^[A-Za-z0-9._-]+$/;function et(n){const e=n==null?void 0:n.skills;return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"):[]}function _o(n,e){e&&(n.skills=e.skills)}function ko(n){return d(this,null,function*(){var t;if(!n.arrange)return;const e=yield n.fetchApplication();n.stillCurrent&&!n.stillCurrent()||_o(n.arrange,(t=e==null?void 0:e.arrange)==null?void 0:t[0])})}function So(n){if(!n)return!1;try{return!ns(n)}catch(e){return!1}}function si(n){if(!(typeof n.skillId!="string"||!os.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 Eo(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 Io{constructor(e){y(this,"inflight",new Map);y(this,"busy",new Set);this.options=e}sync(){const e=et({skills:this.options.getSkills()});return Ue.log("sync",{count:e.length,sandbox:!!this.options.getSandbox()}),this.reconcile().catch(t=>{Ue.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 g(m.NotImplemented,"当前环境不能加载平台技能,需要端侧宿主。");return e}prepare(e,t){return d(this,null,function*(){const i=this.bound(e);if(!i)throw new g(m.NotFound,"技能或资源不存在。");return yield this.ensure(i,t),i})}bound(e){if(!os.test(this.options.applicationId()))return;const t=et({skills:this.options.getSkills()}).find(i=>i.name===e);return t?si(t):void 0}reconcile(){return d(this,null,function*(){if(!this.options.getSandbox())return;const t=et({skills:this.options.getSkills()}).flatMap(i=>{const s=si(i);return s?[s]:[]});yield Promise.all(t.map(i=>this.ensure(i).catch(s=>{Ue.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))){Ue.log("installed",e.name,e.version);return}Ue.log("download",e.name,e.skillId,e.version);const s=this.options.getToken();if(!So(s))throw new g(m.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 g(m.BadRequest,`技能下载失败(${o.status})。`);const a=new Uint8Array(yield o.arrayBuffer());if(a.byteLength>bo)throw new g(m.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 Eo(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=et({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 g(m.Cancelled,"已取消。"));return}e.ready&&(clearInterval(r),i())},50)}))})}}function Ao(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 Ct=new B("[HostBridge] ");let ce;function xo(n){ce==null||ce(),ce=void 0;const e=Di();if(!e)return Ct.log("missing"),()=>{};const t=new Ge(e),i=r=>{const o=Pi(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(Ao(o.sandbox)),Ct.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),Ct.log("hello"),e.postMessage({channel:an,type:"hello"});const s=()=>{e.removeEventListener("message",i),ce===s&&(ce=void 0)};return ce=s,s}const Jt=new Set;let at,as=[],le,tt;function Ft(){return{revision:at,servers:as}}function To(n){return Jt.add(n),()=>Jt.delete(n)}function Ro(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 Ot(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function Lo(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=Ot(s.code),o=(t=Ot(s.id))!=null?t:r,a=typeof s.url=="string"?Ro(s.url):void 0;if(!o||!a)continue;const c=Ot(s.token);e.push(w(w({id:o,url:a},r?{code:r}:{}),c?{token:c}:{}))}return e}function Mo(n){const e=n.revision;return typeof e!="number"||!Number.isFinite(e)||at!==void 0&&e<=at||!Array.isArray(n.servers)?!1:(at=e,as=Lo(n.servers),Jt.forEach(t=>t()),!0)}function cs(){const n=Di();if(!n)return()=>{};if(tt===n&&le)return le;le==null||le();const e=i=>{const s=Pi(i.data);!s||s.type!=="local-mcps"||Mo(s)};n.addEventListener("message",e),tt=n;const t=()=>{n.removeEventListener("message",e),tt===n&&(tt=void 0,le=void 0)};return le=t,t}const Co=new B("[EventBus] ");class Sn{constructor(e=!1){y(this,"eventListenerMap",{});this.disableLog=e}trace(e,...t){this.disableLog||Co.log(e,...t)}getEventListenerMap(){return w({},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 Fo="路径必须是工作区内的相对路径,不能包含 ..、绝对路径或盘符。";function nt(){return new g(m.Forbidden,Fo,{reason:"path_outside_workspace"})}function Oo(n){if(n!==Me)throw new g(m.Forbidden,`未知的工作区 grantId,当前仅支持 ${Me}。`,{reason:"path_outside_workspace"})}function ne(n,{allowRoot:e=!1,field:t="path"}={}){if(n==null){if(e)return"";throw new g(m.BadRequest,`缺少参数 ${t}。`)}if(typeof n!="string")throw new g(m.BadRequest,`参数 ${t} 必须是字符串。`);if(n.includes("\0")||/%(2e|2f|5c|00)/i.test(n))throw nt();const i=n.normalize("NFC").replace(/\\/g,"/").trim();if(i.startsWith("/")||/^[a-zA-Z]:/.test(i))throw nt();const s=[];for(const o of i.split("/"))if(!(o===""||o===".")){if(o==="..")throw nt();s.push(o)}const r=s.join("/");if(!r&&!e)throw new g(m.BadRequest,`参数 ${t} 不能指向工作区根目录。`);return r}function $(n){return n?n.split("/"):[]}function de(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}function ls(n,e){return n?`${n}/${e}`:e}function He(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(!He(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(b){if(!He(b,"NotFoundError"))throw b;l=!1}const h=yield c.getFileHandle(a,{create:!0});let u;try{u=yield h.createWritable();try{for(var f=X(wt(t)),p,v,_;p=!(v=yield f.next()).done;p=!1){const b=v.value;N(i.signal),yield u.write(b)}}catch(v){_=[v]}finally{try{p&&(v=f.return)&&(yield v.call(f))}finally{if(_)throw _[0]}}N(i.signal),yield u.close()}catch(b){throw yield u==null?void 0:u.abort().catch(()=>{}),l||(yield c.removeEntry(a).catch(()=>{})),b}})}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 ri(a,r),l=yield this.resolveDirectory(s);if(Ni(e,t))throw k("InvalidModificationError");let h;try{h=yield ri(l,o)}catch(u){if(!He(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(!He(u,"NotSupportedError")&&!(u instanceof TypeError))throw u}yield ds(c,l,o),yield a.removeEntry(r,{recursive:!0})})}}function ri(n,e){return d(this,null,function*(){try{return yield n.getFileHandle(e)}catch(t){if(!He(t,"TypeMismatchError"))throw t;return n.getDirectoryHandle(e)}})}function ds(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 ds(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 oi(){return{kind:"directory",children:new Map}}class No{constructor(e,t){y(this,"root",oi());var i;this.displayName=t;for(const s of e){const r=$o(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=oi(),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(wt(t)),p,v,_;p=!(v=yield f.next()).done;p=!1){const b=v.value;N(i.signal),h.push(b)}}catch(v){_=[v]}finally{try{p&&(v=f.return)&&(yield v.call(f))}finally{if(_)throw _[0]}}const u=new Blob(h);c.children.set(a,{kind:"file",blob:u,lastModified:Date.now()})})}}function $o(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 Po(){if(typeof window=="undefined")return;const n=window.showDirectoryPicker;return typeof n=="function"?n.bind(window):void 0}const Do=/^[a-z0-9-]+(\.[a-z0-9-]+)+$/;function Bo(n){if(typeof n!="string")return null;const e=n.trim().toLowerCase().replace(/^\*?\./,"").replace(/\.$/,"");return!Do.test(e)||hs(e)?null:e}function hs(n){return n.startsWith("[")||n.includes(":")?!0:/^[0-9.]+$/.test(n)||/^0x[0-9a-f.]+$/i.test(n)}function En(n=[]){const e=new Set(Li);for(const t of n){const i=Bo(t);i&&e.add(i)}return Array.from(e)}function jo(n,e){return Zt(n,En(e))}function Zt(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||hs(i)||i==="localhost"||i.endsWith(".localhost")?!1:e.some(s=>i===s||i.endsWith(`.${s}`))}function Uo(n={}){const e=w({},it);return Object.keys(it).forEach(t=>{const i=n[t];typeof i=="number"&&Number.isFinite(i)&&i>0&&(e[t]=Math.min(i,it[t]))}),e}function Se(){return new g(m.Internal,"平台文件服务请求失败,请稍后重试。")}function In(n,e=()=>{}){const t=()=>{const r=n();if(!r)throw Se();return r},i=()=>{const r=e();if(!r)throw Se();return r};return{upload(r,o,a){return d(this,null,function*(){if(!o.sessionId)throw new g(m.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 Se();return a==null||a({loaded:r.size,total:r.size}),{fileId:c.id,url:c.url}}catch(c){throw c instanceof g?c:Se()}})},resolveDownload(r,o){return d(this,null,function*(){if(r.type==="platformFile")return qo(i(),r.fileId);if(!o.sessionId)throw new g(m.BadRequest,"当前没有可用的会话,无法下载会话文件。");let a;try{a=yield t().getApplicationIdSessionFile(o.applicationId,o.sessionId,r.fileId)}catch(c){throw Se()}if(!(a!=null&&a.url))throw new g(m.NotFound,"会话文件不存在或暂不可下载。");return{url:a.url,name:a.name,size:a.size}})}}}function qo(n,e){return d(this,null,function*(){let t;try{t=yield n.getFile(e)}catch(s){throw Se()}if(!(t!=null&&t.url))throw new g(m.NotFound,"平台文件不存在或暂不可下载。");let i;try{i=new URL(t.url)}catch(s){throw new g(m.Internal,"平台返回的下载地址无效。")}if(i.protocol!=="https:")throw new g(m.Internal,"平台返回的下载地址无效。");return{url:t.url,size:t.bytes}})}const Ho="glodon-aiot-local-workspace",Nt="kv";function An(){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 zo(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}function us(n=Ho){if(typeof indexedDB=="undefined")return An();let e;const t=()=>(e||(e=new Promise((r,o)=>{const a=indexedDB.open(n,1);a.onupgradeneeded=()=>{a.result.createObjectStore(Nt)},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 zo(o(a.transaction(Nt,r).objectStore(Nt)))});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 ai(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 Wo(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=ai(o.relativePathComponents),c=ai(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 Vo={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"},Go="只能预览图片、音视频和 PDF。";function Xo(n){var i;const e=(i=n.split("/").pop())!=null?i:"",t=e.lastIndexOf(".");if(!(t<=0))return Vo[e.slice(t+1).toLowerCase()]}const Qo="路径必须在工作区内,不能包含 ..、盘符或空字符。";function $t(){return new g(m.Forbidden,Qo,{reason:"path_outside_workspace"})}function V(n,e){if(n==null||n===""){if(e)return"";throw new g(m.BadRequest,"缺少参数 path。")}if(typeof n!="string")throw new g(m.BadRequest,"path 必须是字符串。");if(n.includes("\0")||/%(2e|2f|5c|00)/i.test(n))throw $t();const t=n.normalize("NFC").replace(/\\/g,"/").trim();if(/^[a-zA-Z]:/.test(t))throw $t();const i=[];for(const r of t.split("/"))if(!(r===""||r===".")){if(r==="..")throw $t();i.push(r)}const s=i.join("/");if(!s&&!e)throw new g(m.BadRequest,"path 不能指向工作区根目录。");return s}function Pt(n){return new g(m.NotImplemented,`当前工作区不能${n}。`)}function ci(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 fs{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 ci(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 ci(this.host,o,r)})})}url(e){return d(this,null,function*(){var c,l;const t=V(e,!1);if(this.assertAccess(t,"read"),!Xo(t))throw new g(m.BadRequest,Go);const i=yield this.stat(t);if(i.kind!=="file")throw new g(m.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 g(m.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([de(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 g(m.BadRequest,"目标是目录,不是文件。");l=new Uint8Array(yield(yield c.readFile(o)).arrayBuffer())}catch(u){if(u instanceof g||Ce(u).code!==m.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([de(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 Pt("创建目录");yield i.createDirectory(t)})),this.host.notifyFilesChanged([de(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 Pt("删除");yield r.remove(s,t)})),this.host.notifyFilesChanged([de(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 Pt("移动");yield r.move(i,s)})),this.host.notifyFilesChanged([de(i),de(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 g(m.Forbidden,fn.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 yt();try{return yield e(t)}catch(s){if(s instanceof g)throw s;const r=Ce(s);throw((i=r.data)==null?void 0:i.reason)==="workspace_not_granted"&&(yield this.host.handlePermissionLost()),r}})}}const Dt={mode:"readwrite"};function Yo(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 Jo(n){return!!n&&typeof n=="object"&&n.name==="AbortError"}const li=new B("[LocalWorkspace] ");class ps{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 Sn(!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,v,_;const t=(o=e.config)!=null?o:{};this.applicationId=e.applicationId,this.store=(a=e.store)!=null?a:An(),this.picker=e.picker===null?void 0:(c=e.picker)!=null?c:Po(),this.limits=Uo(t.limits),this.sensitive=new fn(t.sensitiveRulesAppend),this.downloadUrlAllowlist=En(t.downloadUrlAllowlistAppend),this.allowWorkspaceWideTextSearch=!!t.allowWorkspaceWideTextSearch,this.approvalHandler=t.onApprovalRequired;const i=(l=e.transfer)!=null?l:In(()=>{});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=(v=e.fetch)!=null?v: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 fs(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,li.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=Wo(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(Jo(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,Dt))!=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(Dt)}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 No(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=Yo(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(Dt).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 Ge)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(sn.map(t=>[t,!0]));return{protocolVersion:"1.0",capabilities:S(w({},e),{cancellation:!0,atomicWrite:!0}),limits:w({},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){li.report(`${e} listener failed`,i)}}}var Ee=(n=>(n[n.Normal=0]="Normal",n[n.Debug=1]="Debug",n))(Ee||{}),Z=(n=>(n[n.InsufficientBalance=11937]="InsufficientBalance",n[n.ConversionFailed=11938]="ConversionFailed",n[n.QuotaCheckFailed=11939]="QuotaCheckFailed",n))(Z||{});const en={11937:"余额不足",11938:"用量换算失败",11939:"额度校验失败"};function Ko(n){return n===11937||n===11938||n===11939}function Zo(n,e,t){return d(this,null,function*(){var a;if(!e)throw new Error("session is not avalible. id is undefined");const i=ea(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:ta(s.minio,o),name:t.name||i,size:t.size}})}function ea(n){const e=n.split(/[/\\]/).pop()||"",t=/\.([A-Za-z0-9]{1,16})$/.exec(e);return t?`${se.v4()}.${t[1].toLowerCase()}`:se.v4()}function ta(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 di=100,R=new B("[Session] ");var Le=(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.UsageError="usage error",n))(Le||{});class xn{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 Sn);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=Oe(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(w({},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){R.error(u)}yield(()=>{if(i!=null&&i.promptVariables){const u=this._promptVariables.map(f=>{var v,_;const p=((_=(v=i.promptVariables)==null?void 0:v.find(b=>b.key===f.key&&b.type===f.type))==null?void 0:_.value)||"";return S(w({},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)>di)throw Error(`knowledges and fileIds total count cannot exceed ${di}`);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(w({},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(w({},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(R.log("setNetOpen:",e),R.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){R.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((s=this._application)==null?void 0:s.arrange[0].enableNetOpen)===!1){R.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,R.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}get requestToken(){var e,t;return(t=(e=this.client)==null?void 0:e.token)!=null?t:this.token}updateSocketResourceToken(e){}getService(){return is(exports.configuration.apiRoot,()=>this.requestToken,(e,t)=>{const i=new Error("data request error",{cause:{status:e,message:t}});R.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=w(w({},t),e),this.event.emit("history:loading"),R.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),R.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((_,b)=>(_[b.data.step-1]||(_[b.data.step-1]=[]),_[b.data.step-1].push(b),_),[])),l===r.length-1&&(u=(p=this.data)==null?void 0:p.lastRelatedQuestion),S(w({},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),R.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 R.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}),R.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),R.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),R.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 R.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");R.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),R.log("activated",this._id),this._sessionActive=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?(R.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 Zo(this.cvforceApi,this._id,e)})}send(i){return d(this,arguments,function*(e,t={stream:exports.configuration.stream}){var v,_;try{this.validateConfigs()}catch(b){R.report(b)}const{stream:s=exports.configuration.stream,referenceFirst:r=!1}=t,o=e.uuid||se.v4(),a=((v=e.text)==null?void 0:v.trim())||"",c=e.files||[],l=e.fileIds,h=e.imageContent;if(!a&&!c.length&&!(l!=null&&l.length)){const b=new Error("failed at sending empty content");return R.error(b),this.event.emit("error",b),!1}if(!this._id){const b=new Error("session id is not defined");return R.error(b),this.event.emit("error",b),!1}if(this.frozen){const b=new Error("session is frozen");return R.error(b),this.event.emit("error",b),!1}this.frozen=!0,this._stopAnswer=!1,R.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=b=>d(this,null,function*(){if(b.role===x.ChatMessageRole.Robot){this.removeEventListener("answer:finish",p);try{if(this._id&&b.content&&b.index&&b.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:b.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:b.content})),yield this.fillMessageReference(b),this.finalizeAnswerMessage(b),this.getRelatedQuesion(b),b.isLoading=!1,this.isEmptyQuotaRejection(b)){const A=this.messages[this.messages.length-1];A&&A.role===x.ChatMessageRole.Robot&&!A.content&&!(A.actions&&A.actions.length>0)&&this.messages.pop(),this.event.emit("message:updated",b)}else{let A=this.messages[this.messages.length-1];if(A&&A.role===x.ChatMessageRole.Robot){const E=w(w({},A),b);this.messages[this.messages.length-1]=E,this.event.emit("message:updated",E)}else this.pushMessage(b)}}finally{this.frozen=!1}}});return this.addEventListener("answer:finish",p),this.sendQuestion(f,S(w({},t),{stream:s,referenceFirst:r})),u})}isEmptyQuotaRejection(e){return(e.code===Z.InsufficientBalance||e.code===Z.QuotaCheckFailed)&&!e.content&&!(e.actions&&e.actions.length>0)}finalizeAnswerMessage(e){switch(e.code){case 11915:e.content="请您换个问题问我吧~",e.index=-1,e.isSensitive=!0,e.isLoading=!1,e.sessionId=this._id||"",this.event.emit("message:error",e);break;case 11916:e.content="尊敬的用户您好,让我们换个话题再聊聊吧。",e.index=-1,e.isSensitive=!0,e.isLoading=!1,e.sessionId=this._id||"",this.event.emit("message:error",e);break;case Z.ConversionFailed:{e.index=-1,e.isLoading=!1,e.sessionId=e.sessionId||this._id||"",this.event.emit("message:error",e);const t={code:Z.ConversionFailed,message:e.message||en[Z.ConversionFailed],usageExtension:e.usageExtension,messageId:e.messageId||void 0,sessionId:this._id||e.sessionId||void 0},i=new Error("usage error",{cause:t});R.error("usage error",t),this.event.emit("error",i);break}case Z.InsufficientBalance:case Z.QuotaCheckFailed:{e.index=-1,e.isLoading=!1,e.sessionId=e.sessionId||this._id||"",this.event.emit("message:error",e);const t=e.code,i={code:t,message:e.message||en[t],messageId:e.messageId||void 0,sessionId:this._id||e.sessionId||void 0},s=new Error("usage error",{cause:i});R.error("usage error",i),this.event.emit("error",s);break}case 200:e.index=-1,e.isLoading=!1;break;default:e.content=e.message||"未知错误",e.isLoading=!1,e.index=-1,this.event.emit("message:error",e)}}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 R.log("related:skip",{code:e.code,sensitive:!!e.isSensitive,hasContent:!!e.content}),e;const i=wo(t==null?void 0:t.recommendQuestionOpen,t==null?void 0:t.relatedQuestionApp,e.content,this.currentUserQuestion());if(i===null)return R.log("related:skip",{recommendQuestionOpen:t==null?void 0:t.recommendQuestionOpen}),e;R.log("related:request",i),this.event.emit("message:relatedQuesion:loading",e);const s=yield this.cvforceApi.postGeneques({content:i}).catch(l=>(R.error("related:failed",l),null));if(R.log("related:response",s),!s){const l=[],h=S(w({},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(mo).map(yo).filter(l=>!!l);e.relatedQuesion=r,e.index=-3,e.isLoading=!1;const o=S(w({},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)=>w(w({},i),t[s]))}catch(t){R.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,R.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{if(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),this.finalizeAnswerMessage(l),this.getRelatedQuesion(l),this.isEmptyQuotaRejection(l)){const h=this.messages[this.messages.length-1];h&&h.role===x.ChatMessageRole.Robot&&!h.content&&!(h.actions&&h.actions.length>0)&&this.messages.pop(),this.event.emit("message:updated",l)}else{const h=this.messages[this.messages.length-1];if(h&&h.role===x.ChatMessageRole.Robot){const u=w(w({},h),l);this.messages[this.messages.length-1]=u,this.event.emit("message:updated",u)}}}finally{this.removeEventListener("message:content",a),this.frozen=!1}});this.addEventListener("message:content",a),this.sendQuestion(o,S(w({},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:se.v4(),isLoading:!1,index:-2,messageTime:nn(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=w(w({},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){e.code!=null&&e.code!==200&&(t.code=e.code,t.message=e.message,t.index=-1);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=w(w({},this.data),s),this.event.emit("data:updated",this.data)),i==="result"){const a=s==null?void 0:s.messageId,c=s==null?void 0:s.llmModel,l=s==null?void 0:s.messageTime;a!==void 0&&(t.messageId=a),c!==void 0&&(t.llmModel=c),l!==void 0&&(t.messageTime=l),(s==null?void 0:s.usageExtension)!=null&&(t.usageExtension=s.usageExtension)}if(i==="over"&&(t.index=-1),e.code!=null){const a=t.code!=null&&t.code!==200;(e.code!==200||!a)&&(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 fe=new Map,na=2e4;function ia(n){if(typeof AbortSignal!="undefined"&&typeof AbortSignal.timeout=="function"){const e=AbortSignal.timeout(na);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 Ve(n){return`${n.url}
|
|
370
|
+
`)};function is(n,e,t){return new x.CVForceApi(ss(n,"/data/v1",e,t),rs(t))}function vo(n,e,t){return new x.AIShopApi(ss(n,"/aishop",e,t),rs(t))}function ss(n,e,t,i){const s=o=>{var c;const a=t();return a&&(ns(a)&&i(403,"aiotToken is timeout"),o.headers=(c=o.headers)!=null?c:{},o.headers=S(w({},o.headers),{Authorization:a?`Bearer ${a}`:""})),o};function r(o,a=!0){const c=`${n}${o}`,l=As.create({baseURL:c});return a&&l.interceptors.request.use(s),l}return r(e)}function rs(n){return{onHttpStatusError:(i,s)=>{i===401&&n(i,"aiotToken is invalid")},onAppStatusError:(i,s)=>{i!==10001&&i!==10215&&n(i,s)}}}const Ue=new B("[PlatformSkills] "),bo=20*1024*1024,os=/^[A-Za-z0-9._-]+$/;function et(n){const e=n==null?void 0:n.skills;return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"):[]}function _o(n,e){e&&(n.skills=e.skills)}function ko(n){return d(this,null,function*(){var t;if(!n.arrange)return;const e=yield n.fetchApplication();n.stillCurrent&&!n.stillCurrent()||_o(n.arrange,(t=e==null?void 0:e.arrange)==null?void 0:t[0])})}function So(n){if(!n)return!1;try{return!ns(n)}catch(e){return!1}}function si(n){if(!(typeof n.skillId!="string"||!os.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 Eo(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 Io{constructor(e){y(this,"inflight",new Map);y(this,"busy",new Set);this.options=e}sync(){const e=et({skills:this.options.getSkills()});return Ue.log("sync",{count:e.length,sandbox:!!this.options.getSandbox()}),this.reconcile().catch(t=>{Ue.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 g(m.NotImplemented,"当前环境不能加载平台技能,需要端侧宿主。");return e}prepare(e,t){return d(this,null,function*(){const i=this.bound(e);if(!i)throw new g(m.NotFound,"技能或资源不存在。");return yield this.ensure(i,t),i})}bound(e){if(!os.test(this.options.applicationId()))return;const t=et({skills:this.options.getSkills()}).find(i=>i.name===e);return t?si(t):void 0}reconcile(){return d(this,null,function*(){if(!this.options.getSandbox())return;const t=et({skills:this.options.getSkills()}).flatMap(i=>{const s=si(i);return s?[s]:[]});yield Promise.all(t.map(i=>this.ensure(i).catch(s=>{Ue.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))){Ue.log("installed",e.name,e.version);return}Ue.log("download",e.name,e.skillId,e.version);const s=this.options.getToken();if(!So(s))throw new g(m.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 g(m.BadRequest,`技能下载失败(${o.status})。`);const a=new Uint8Array(yield o.arrayBuffer());if(a.byteLength>bo)throw new g(m.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 Eo(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=et({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 g(m.Cancelled,"已取消。"));return}e.ready&&(clearInterval(r),i())},50)}))})}}function Ao(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 Ct=new B("[HostBridge] ");let ce;function xo(n){ce==null||ce(),ce=void 0;const e=Di();if(!e)return Ct.log("missing"),()=>{};const t=new Ge(e),i=r=>{const o=Pi(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(Ao(o.sandbox)),Ct.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),Ct.log("hello"),e.postMessage({channel:an,type:"hello"});const s=()=>{e.removeEventListener("message",i),ce===s&&(ce=void 0)};return ce=s,s}const Jt=new Set;let at,as=[],le,tt;function Ft(){return{revision:at,servers:as}}function To(n){return Jt.add(n),()=>Jt.delete(n)}function Ro(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 Ot(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function Lo(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=Ot(s.code),o=(t=Ot(s.id))!=null?t:r,a=typeof s.url=="string"?Ro(s.url):void 0;if(!o||!a)continue;const c=Ot(s.token);e.push(w(w({id:o,url:a},r?{code:r}:{}),c?{token:c}:{}))}return e}function Mo(n){const e=n.revision;return typeof e!="number"||!Number.isFinite(e)||at!==void 0&&e<=at||!Array.isArray(n.servers)?!1:(at=e,as=Lo(n.servers),Jt.forEach(t=>t()),!0)}function cs(){const n=Di();if(!n)return()=>{};if(tt===n&&le)return le;le==null||le();const e=i=>{const s=Pi(i.data);!s||s.type!=="local-mcps"||Mo(s)};n.addEventListener("message",e),tt=n;const t=()=>{n.removeEventListener("message",e),tt===n&&(tt=void 0,le=void 0)};return le=t,t}const Co=new B("[EventBus] ");class Sn{constructor(e=!1){y(this,"eventListenerMap",{});this.disableLog=e}trace(e,...t){this.disableLog||Co.log(e,...t)}getEventListenerMap(){return w({},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 Fo="路径必须是工作区内的相对路径,不能包含 ..、绝对路径或盘符。";function nt(){return new g(m.Forbidden,Fo,{reason:"path_outside_workspace"})}function Oo(n){if(n!==Me)throw new g(m.Forbidden,`未知的工作区 grantId,当前仅支持 ${Me}。`,{reason:"path_outside_workspace"})}function ne(n,{allowRoot:e=!1,field:t="path"}={}){if(n==null){if(e)return"";throw new g(m.BadRequest,`缺少参数 ${t}。`)}if(typeof n!="string")throw new g(m.BadRequest,`参数 ${t} 必须是字符串。`);if(n.includes("\0")||/%(2e|2f|5c|00)/i.test(n))throw nt();const i=n.normalize("NFC").replace(/\\/g,"/").trim();if(i.startsWith("/")||/^[a-zA-Z]:/.test(i))throw nt();const s=[];for(const o of i.split("/"))if(!(o===""||o===".")){if(o==="..")throw nt();s.push(o)}const r=s.join("/");if(!r&&!e)throw new g(m.BadRequest,`参数 ${t} 不能指向工作区根目录。`);return r}function $(n){return n?n.split("/"):[]}function de(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}function ls(n,e){return n?`${n}/${e}`:e}function He(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(!He(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(b){if(!He(b,"NotFoundError"))throw b;l=!1}const h=yield c.getFileHandle(a,{create:!0});let u;try{u=yield h.createWritable();try{for(var f=X(wt(t)),p,v,_;p=!(v=yield f.next()).done;p=!1){const b=v.value;N(i.signal),yield u.write(b)}}catch(v){_=[v]}finally{try{p&&(v=f.return)&&(yield v.call(f))}finally{if(_)throw _[0]}}N(i.signal),yield u.close()}catch(b){throw yield u==null?void 0:u.abort().catch(()=>{}),l||(yield c.removeEntry(a).catch(()=>{})),b}})}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 ri(a,r),l=yield this.resolveDirectory(s);if(Ni(e,t))throw k("InvalidModificationError");let h;try{h=yield ri(l,o)}catch(u){if(!He(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(!He(u,"NotSupportedError")&&!(u instanceof TypeError))throw u}yield ds(c,l,o),yield a.removeEntry(r,{recursive:!0})})}}function ri(n,e){return d(this,null,function*(){try{return yield n.getFileHandle(e)}catch(t){if(!He(t,"TypeMismatchError"))throw t;return n.getDirectoryHandle(e)}})}function ds(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 ds(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 oi(){return{kind:"directory",children:new Map}}class No{constructor(e,t){y(this,"root",oi());var i;this.displayName=t;for(const s of e){const r=$o(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=oi(),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(wt(t)),p,v,_;p=!(v=yield f.next()).done;p=!1){const b=v.value;N(i.signal),h.push(b)}}catch(v){_=[v]}finally{try{p&&(v=f.return)&&(yield v.call(f))}finally{if(_)throw _[0]}}const u=new Blob(h);c.children.set(a,{kind:"file",blob:u,lastModified:Date.now()})})}}function $o(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 Po(){if(typeof window=="undefined")return;const n=window.showDirectoryPicker;return typeof n=="function"?n.bind(window):void 0}const Do=/^[a-z0-9-]+(\.[a-z0-9-]+)+$/;function Bo(n){if(typeof n!="string")return null;const e=n.trim().toLowerCase().replace(/^\*?\./,"").replace(/\.$/,"");return!Do.test(e)||hs(e)?null:e}function hs(n){return n.startsWith("[")||n.includes(":")?!0:/^[0-9.]+$/.test(n)||/^0x[0-9a-f.]+$/i.test(n)}function En(n=[]){const e=new Set(Li);for(const t of n){const i=Bo(t);i&&e.add(i)}return Array.from(e)}function jo(n,e){return Zt(n,En(e))}function Zt(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||hs(i)||i==="localhost"||i.endsWith(".localhost")?!1:e.some(s=>i===s||i.endsWith(`.${s}`))}function Uo(n={}){const e=w({},it);return Object.keys(it).forEach(t=>{const i=n[t];typeof i=="number"&&Number.isFinite(i)&&i>0&&(e[t]=Math.min(i,it[t]))}),e}function Se(){return new g(m.Internal,"平台文件服务请求失败,请稍后重试。")}function In(n,e=()=>{}){const t=()=>{const r=n();if(!r)throw Se();return r},i=()=>{const r=e();if(!r)throw Se();return r};return{upload(r,o,a){return d(this,null,function*(){if(!o.sessionId)throw new g(m.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 Se();return a==null||a({loaded:r.size,total:r.size}),{fileId:c.id,url:c.url}}catch(c){throw c instanceof g?c:Se()}})},resolveDownload(r,o){return d(this,null,function*(){if(r.type==="platformFile")return qo(i(),r.fileId);if(!o.sessionId)throw new g(m.BadRequest,"当前没有可用的会话,无法下载会话文件。");let a;try{a=yield t().getApplicationIdSessionFile(o.applicationId,o.sessionId,r.fileId)}catch(c){throw Se()}if(!(a!=null&&a.url))throw new g(m.NotFound,"会话文件不存在或暂不可下载。");return{url:a.url,name:a.name,size:a.size}})}}}function qo(n,e){return d(this,null,function*(){let t;try{t=yield n.getFile(e)}catch(s){throw Se()}if(!(t!=null&&t.url))throw new g(m.NotFound,"平台文件不存在或暂不可下载。");let i;try{i=new URL(t.url)}catch(s){throw new g(m.Internal,"平台返回的下载地址无效。")}if(i.protocol!=="https:")throw new g(m.Internal,"平台返回的下载地址无效。");return{url:t.url,size:t.bytes}})}const Ho="glodon-aiot-local-workspace",Nt="kv";function An(){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 zo(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}function us(n=Ho){if(typeof indexedDB=="undefined")return An();let e;const t=()=>(e||(e=new Promise((r,o)=>{const a=indexedDB.open(n,1);a.onupgradeneeded=()=>{a.result.createObjectStore(Nt)},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 zo(o(a.transaction(Nt,r).objectStore(Nt)))});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 ai(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 Wo(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=ai(o.relativePathComponents),c=ai(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 Vo={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"},Go="只能预览图片、音视频和 PDF。";function Xo(n){var i;const e=(i=n.split("/").pop())!=null?i:"",t=e.lastIndexOf(".");if(!(t<=0))return Vo[e.slice(t+1).toLowerCase()]}const Qo="路径必须在工作区内,不能包含 ..、盘符或空字符。";function $t(){return new g(m.Forbidden,Qo,{reason:"path_outside_workspace"})}function V(n,e){if(n==null||n===""){if(e)return"";throw new g(m.BadRequest,"缺少参数 path。")}if(typeof n!="string")throw new g(m.BadRequest,"path 必须是字符串。");if(n.includes("\0")||/%(2e|2f|5c|00)/i.test(n))throw $t();const t=n.normalize("NFC").replace(/\\/g,"/").trim();if(/^[a-zA-Z]:/.test(t))throw $t();const i=[];for(const r of t.split("/"))if(!(r===""||r===".")){if(r==="..")throw $t();i.push(r)}const s=i.join("/");if(!s&&!e)throw new g(m.BadRequest,"path 不能指向工作区根目录。");return s}function Pt(n){return new g(m.NotImplemented,`当前工作区不能${n}。`)}function ci(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 fs{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 ci(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 ci(this.host,o,r)})})}url(e){return d(this,null,function*(){var c,l;const t=V(e,!1);if(this.assertAccess(t,"read"),!Xo(t))throw new g(m.BadRequest,Go);const i=yield this.stat(t);if(i.kind!=="file")throw new g(m.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 g(m.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([de(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 g(m.BadRequest,"目标是目录,不是文件。");l=new Uint8Array(yield(yield c.readFile(o)).arrayBuffer())}catch(u){if(u instanceof g||Ce(u).code!==m.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([de(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 Pt("创建目录");yield i.createDirectory(t)})),this.host.notifyFilesChanged([de(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 Pt("删除");yield r.remove(s,t)})),this.host.notifyFilesChanged([de(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 Pt("移动");yield r.move(i,s)})),this.host.notifyFilesChanged([de(i),de(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 g(m.Forbidden,fn.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 yt();try{return yield e(t)}catch(s){if(s instanceof g)throw s;const r=Ce(s);throw((i=r.data)==null?void 0:i.reason)==="workspace_not_granted"&&(yield this.host.handlePermissionLost()),r}})}}const Dt={mode:"readwrite"};function Yo(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 Jo(n){return!!n&&typeof n=="object"&&n.name==="AbortError"}const li=new B("[LocalWorkspace] ");class ps{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 Sn(!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,v,_;const t=(o=e.config)!=null?o:{};this.applicationId=e.applicationId,this.store=(a=e.store)!=null?a:An(),this.picker=e.picker===null?void 0:(c=e.picker)!=null?c:Po(),this.limits=Uo(t.limits),this.sensitive=new fn(t.sensitiveRulesAppend),this.downloadUrlAllowlist=En(t.downloadUrlAllowlistAppend),this.allowWorkspaceWideTextSearch=!!t.allowWorkspaceWideTextSearch,this.approvalHandler=t.onApprovalRequired;const i=(l=e.transfer)!=null?l:In(()=>{});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=(v=e.fetch)!=null?v: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 fs(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,li.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=Wo(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(Jo(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,Dt))!=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(Dt)}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 No(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=Yo(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(Dt).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 Ge)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(sn.map(t=>[t,!0]));return{protocolVersion:"1.0",capabilities:S(w({},e),{cancellation:!0,atomicWrite:!0}),limits:w({},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){li.report(`${e} listener failed`,i)}}}var Ee=(n=>(n[n.Normal=0]="Normal",n[n.Debug=1]="Debug",n))(Ee||{}),Z=(n=>(n[n.InsufficientBalance=11937]="InsufficientBalance",n[n.ConversionFailed=11938]="ConversionFailed",n[n.QuotaCheckFailed=11939]="QuotaCheckFailed",n))(Z||{});const en={11937:"余额不足",11938:"用量换算失败",11939:"额度校验失败"};function Ko(n){return n===11937||n===11938||n===11939}function Zo(n,e,t){return d(this,null,function*(){var a;if(!e)throw new Error("session is not avalible. id is undefined");const i=ea(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:ta(s.minio,o),name:t.name||i,size:t.size}})}function ea(n){const e=n.split(/[/\\]/).pop()||"",t=/\.([A-Za-z0-9]{1,16})$/.exec(e);return t?`${se.v4()}.${t[1].toLowerCase()}`:se.v4()}function ta(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 di=100,R=new B("[Session] ");var Le=(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.UsageError="usage error",n))(Le||{});class xn{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 Sn);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=Oe(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(w({},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){R.error(u)}yield(()=>{if(i!=null&&i.promptVariables){const u=this._promptVariables.map(f=>{var v,_;const p=((_=(v=i.promptVariables)==null?void 0:v.find(b=>b.key===f.key&&b.type===f.type))==null?void 0:_.value)||"";return S(w({},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)>di)throw Error(`knowledges and fileIds total count cannot exceed ${di}`);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(w({},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(w({},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(R.log("setNetOpen:",e),R.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){R.warn("Agent Application Sessions are disabled to setNetOpen.");return}if(((s=this._application)==null?void 0:s.arrange[0].enableNetOpen)===!1){R.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,R.log("data:updated",this.data),this.event.emit("data:updated",this.data),this.event.emit("data:updated:netOpen",{netOpen:e}),e})}get requestToken(){var e,t;return(t=(e=this.client)==null?void 0:e.token)!=null?t:this.token}updateSocketResourceToken(e){}getService(){return is(exports.configuration.apiRoot,()=>this.requestToken,(e,t)=>{const i=new Error("data request error",{cause:{status:e,message:t}});R.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=w(w({},t),e),this.event.emit("history:loading"),R.log("history:loading"),(e.endTime||e.startTime)&&(this.event.emit("history:moreloading",e),R.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((_,b)=>(_[b.data.step-1]||(_[b.data.step-1]=[]),_[b.data.step-1].push(b),_),[])),l===r.length-1&&(u=(p=this.data)==null?void 0:p.lastRelatedQuestion),S(w({},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),R.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 R.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}),R.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),R.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),R.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 R.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");R.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),R.log("activated",this._id),this._sessionActive=!0,this.activing=!1,this})}inactivate(e=!1){return this.socket?(R.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 Zo(this.cvforceApi,this._id,e)})}send(i){return d(this,arguments,function*(e,t={stream:exports.configuration.stream}){var v,_;try{this.validateConfigs()}catch(b){R.report(b)}const{stream:s=exports.configuration.stream,referenceFirst:r=!1}=t,o=e.uuid||se.v4(),a=((v=e.text)==null?void 0:v.trim())||"",c=e.files||[],l=e.fileIds,h=e.imageContent;if(!a&&!c.length&&!(l!=null&&l.length)){const b=new Error("failed at sending empty content");return R.error(b),this.event.emit("error",b),!1}if(!this._id){const b=new Error("session id is not defined");return R.error(b),this.event.emit("error",b),!1}if(this.frozen){const b=new Error("session is frozen");return R.error(b),this.event.emit("error",b),!1}this.frozen=!0,this._stopAnswer=!1,R.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=b=>d(this,null,function*(){if(b.role===x.ChatMessageRole.Robot){this.removeEventListener("answer:finish",p);try{if(this._id&&b.content&&b.index&&b.index<0&&(this.data=yield this.cvforceApi.patchSessionsId(this.applicationId,this._id,{finialMessage:b.content}),this.event.emit("data:updated",this.data),this.event.emit("data:updated:finialMessage",{finialMessage:b.content})),yield this.fillMessageReference(b),this.finalizeAnswerMessage(b),this.getRelatedQuesion(b),b.isLoading=!1,this.isEmptyQuotaRejection(b)){const A=this.messages[this.messages.length-1];A&&A.role===x.ChatMessageRole.Robot&&!A.content&&!(A.actions&&A.actions.length>0)&&this.messages.pop(),this.event.emit("message:updated",b)}else{let A=this.messages[this.messages.length-1];if(A&&A.role===x.ChatMessageRole.Robot){const E=w(w({},A),b);this.messages[this.messages.length-1]=E,this.event.emit("message:updated",E)}else this.pushMessage(b)}}finally{this.frozen=!1}}});return this.addEventListener("answer:finish",p),this.sendQuestion(f,S(w({},t),{stream:s,referenceFirst:r})),u})}isEmptyQuotaRejection(e){return(e.code===Z.InsufficientBalance||e.code===Z.QuotaCheckFailed)&&!e.content&&!(e.actions&&e.actions.length>0)}finalizeAnswerMessage(e){switch(e.code){case 11915:e.content="请您换个问题问我吧~",e.index=-1,e.isSensitive=!0,e.isLoading=!1,e.sessionId=this._id||"",this.event.emit("message:error",e);break;case 11916:e.content="尊敬的用户您好,让我们换个话题再聊聊吧。",e.index=-1,e.isSensitive=!0,e.isLoading=!1,e.sessionId=this._id||"",this.event.emit("message:error",e);break;case Z.ConversionFailed:{e.index=-1,e.isLoading=!1,e.sessionId=e.sessionId||this._id||"",this.event.emit("message:error",e);const t={code:Z.ConversionFailed,message:e.message||en[Z.ConversionFailed],usageExtension:e.usageExtension,messageId:e.messageId||void 0,sessionId:this._id||e.sessionId||void 0},i=new Error("usage error",{cause:t});R.error("usage error",t),this.event.emit("error",i);break}case Z.InsufficientBalance:case Z.QuotaCheckFailed:{e.index=-1,e.isLoading=!1,e.sessionId=e.sessionId||this._id||"",this.event.emit("message:error",e);const t=e.code,i={code:t,message:e.message||en[t],messageId:e.messageId||void 0,sessionId:this._id||e.sessionId||void 0},s=new Error("usage error",{cause:i});R.error("usage error",i),this.event.emit("error",s);break}case 200:e.index=-1,e.isLoading=!1;break;default:e.content=e.message||"未知错误",e.isLoading=!1,e.index=-1,this.event.emit("message:error",e)}}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 R.log("related:skip",{code:e.code,sensitive:!!e.isSensitive,hasContent:!!e.content}),e;const i=wo(t==null?void 0:t.recommendQuestionOpen,t==null?void 0:t.relatedQuestionApp,e.content,this.currentUserQuestion());if(i===null)return R.log("related:skip",{recommendQuestionOpen:t==null?void 0:t.recommendQuestionOpen}),e;R.log("related:request",i),this.event.emit("message:relatedQuesion:loading",e);const s=yield this.cvforceApi.postGeneques({content:i}).catch(l=>(R.error("related:failed",l),null));if(R.log("related:response",s),!s){const l=[],h=S(w({},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(mo).map(yo).filter(l=>!!l);e.relatedQuesion=r,e.index=-3,e.isLoading=!1;const o=S(w({},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)=>w(w({},i),t[s]))}catch(t){R.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,R.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{if(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),this.finalizeAnswerMessage(l),this.getRelatedQuesion(l),this.isEmptyQuotaRejection(l)){const h=this.messages[this.messages.length-1];h&&h.role===x.ChatMessageRole.Robot&&!h.content&&!(h.actions&&h.actions.length>0)&&this.messages.pop(),this.event.emit("message:updated",l)}else{const h=this.messages[this.messages.length-1];if(h&&h.role===x.ChatMessageRole.Robot){const u=w(w({},h),l);this.messages[this.messages.length-1]=u,this.event.emit("message:updated",u)}}}finally{this.removeEventListener("message:content",a),this.frozen=!1}});this.addEventListener("message:content",a),this.sendQuestion(o,S(w({},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:se.v4(),isLoading:!1,index:-2,messageTime:nn(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=w(w({},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){e.code!=null&&e.code!==200&&(t.code=e.code,t.message=e.message,t.index=-1);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=w(w({},this.data),s),this.event.emit("data:updated",this.data)),i==="result"){const a=s==null?void 0:s.messageId,c=s==null?void 0:s.llmModel,l=s==null?void 0:s.messageTime;a!==void 0&&(t.messageId=a),c!==void 0&&(t.llmModel=c),l!==void 0&&(t.messageTime=l),(s==null?void 0:s.usageExtension)!=null&&(t.usageExtension=s.usageExtension)}if(i==="over"&&(t.index=-1),e.code!=null){const a=t.code!=null&&t.code!==0&&t.code!==200;(e.code!==200||!a)&&(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 fe=new Map,na=2e4;function ia(n){if(typeof AbortSignal!="undefined"&&typeof AbortSignal.timeout=="function"){const e=AbortSignal.timeout(na);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 Ve(n){return`${n.url}
|
|
371
371
|
${JSON.stringify(n.headers)}`}function sa(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
373
|
`);if(s.startsWith("{")||s.startsWith("["))return JSON.parse(s)}throw new Error("MCP 响应不是 JSON")}function ra(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
374
|
`):JSON.stringify(n)}function oa(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 pt(n,e,t,i,s){return d(this,null,function*(){const r=S(w({},n.headers),{"content-type":"application/json",accept:"application/json, text/event-stream"});t!=null&&t.id&&(r["mcp-session-id"]=t.id),t!=null&&t.protocol&&(r["mcp-protocol-version"]=t.protocol);const o=yield s(n.url,{method:"POST",headers:r,body:JSON.stringify(e),signal:ia(i)}),a=yield oa(o);if(!o.ok)throw new Error(`MCP HTTP ${o.status}: ${a.slice(0,300)}`);const c=sa(a),l=o.headers.get("mcp-session-id");return t&&l&&(t.id=l),c})}function gt(n){const e=n.error;if(!e||typeof e!="object")return;const t=e.message;return typeof t=="string"&&t?t:"MCP 调用失败"}function aa(n){const e=n instanceof Error?n.message:String(n);return/session/i.test(e)||e.includes("MCP HTTP 404")}function ct(n,e,t){return d(this,null,function*(){const i=Ve(n),s=fe.get(i);if(s!=null&&s.id)return s;const r={protocol:"2024-11-05",nextId:1},o=yield pt(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=gt(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 pt(n,{jsonrpc:"2.0",method:"notifications/initialized"},r,e,t),fe.set(i,r),r})}function ca(t){return d(this,arguments,function*(n,e=fetch){var a;const i=yield ct(n,void 0,e),s=yield pt(n,{jsonrpc:"2.0",id:i.nextId,method:"tools/list",params:{}},i,void 0,e);i.nextId+=1;const r=gt(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 la(r,o,a,c){return d(this,arguments,function*(n,e,t,i,s=fetch){const l=Ve(n);let h=yield ct(n,i,s);const u=()=>pt(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(v){if(!aa(v))throw v;fe.delete(l),h=yield ct(n,i,s),f=yield u(),h.nextId+=1}let p=gt(f);if(p&&/session/i.test(p)&&(fe.delete(l),h=yield ct(n,i,s),f=yield u(),h.nextId+=1,p=gt(f)),p)throw new Error(p);return ra(f.result)})}function hi(n){const e=new Set(n.map(t=>Ve(t)));for(const t of fe.keys())e.has(t)||fe.delete(t)}function da(n,e){const t=Ve(n);e.some(i=>Ve(i)===t)||fe.delete(t)}const _e=new B("[LocalMcp] ");function ha(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 ua(n,e,t){return n==null||n.includes(e)?!0:!!t&&n.includes(t)}function fa(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 pa(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:fa(s==null?void 0:s.headers)}}function ga(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=pa(h);if(!u)throw new Error("MCP 详情不可用");return u})}function ma(n){return/^[A-Za-z][A-Za-z0-9.+-]* /.test(n)?n:`Bearer ${n}`}function ya(n,e){if(!(e!=null&&e.token))return w({},n);const t={};for(const[i,s]of Object.entries(n))i.toLowerCase()!=="authorization"&&(t[i]=s);return t.Authorization=ma(e.token),t}function wa(n,e,t){const i=n.find(s=>!e.has(s)&&t(s));return i&&e.add(i),i}function va(n,e,t){return wa(n,e,i=>i.code===t||i.id===t)}function ba(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 _a(n,e){return(t,i,s)=>{const r=lo(n);if(!r){i({code:500,message:"缺少 MCP 地址"});return}la(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 ka(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=ha(n.arrange),s=Ft().revision,r=()=>Ft().revision!==s||(n.isCurrent?!n.isCurrent():!1);if(!i.length){if(r())return;_e.log("编排里没有 runtime=local 的 MCP,不发送 register_client_mcp_tools"),ni([]),hi([]),We();return}const o=[...Ft().servers],a=new Set,c=yield Promise.all(i.map(p=>d(this,null,function*(){var A,E;const v=p.id;let _;const b=()=>{_&&(a.delete(_),_=void 0)};try{const I=yield ga(n.apiRoot,n.token,v,e);if(!ua(t,v,I.code))return null;_=I.code?va(o,a,I.code):void 0;const M=(E=(A=_==null?void 0:_.url)!=null?A:ba(n.initMcp,v,I.code))!=null?E:I.url;if(I.deployType!=="streamableHttp"||!I.code||!M)return _e.log("skip local mcp",v),b(),null;const q={code:I.code,url:M,headers:ya(I.headers,_)},D=yield ca(q,e);return D.length?{code:I.code,url:q.url,binding:q,tools:D}:(b(),null)}catch(I){return b(),_e.report("local mcp failed",v,I instanceof Error?I.message:String(I)),null}})));if(r()){const p=ho();for(const v of c)v&&da(v.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 v of p.tools)h.push({name:v.name,binding:p.binding,handler:_a(v.name,e)})}if(ni(h),hi(h.map(p=>p.binding)),We(),!Object.keys(l).length||!n.socket){_e.log("没有可注册的本地 MCP 工具,不发送 register_client_mcp_tools");return}_e.log("发送 register_client_mcp_tools",Object.entries(l).map(([p,v])=>`${p}: ${v.tools.map(_=>_.name).join(", ")}`).join("; ")),n.socket.emit("register_client_mcp_tools",{mcpServers:l},p=>{const v=p&&typeof p=="object"?p.code:void 0;typeof v=="number"&&v!==200&&_e.report("register_client_mcp_tools",v)})})}const T=new B("[AgentSession] ");function ui(n){if(typeof n!="string")return n;const e=n.trim();if(e)try{return JSON.parse(e)}catch(t){return n}}function Sa(n){const e=n.imageContent;return Array.isArray(e)?S(w({},n),{imageContent:`[${e.length}]`}):n}function fi(n){return n==null||n===""||typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function Ea(n,e){const t=ui(n==null?void 0:n.query);if(!fi(t))return t;const i=ui(e);return fi(i)&&t!=null?t:i}class Ia extends xn{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");y(this,"pendingTokenUpdate",!1)}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.requestToken}`,userMode:exports.configuration.debug?Ee.Debug:Ee.Normal},s=new URL(exports.configuration.apiRoot);T.log("socket:connecting",{sessionId:this.id,origin:s.origin});const r=yield xs.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,this.pendingTokenUpdate=!1}),r.on("ready",a=>{if(this.pendingTokenUpdate){this.handleResourceTokenUpdateResult(a);return}if(a.code===200){T.log("ready");const c=exports.configuration.debug?Ee.Debug:Ee.Normal;c===Ee.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(Le.SocketConnectionFailed);T.error("error",c),this.event.emit("error",c),t(!1)}}),r.on("action",(a,c)=>d(this,null,function*(){var b;if(this._stopAnswer||!this.id)return;const{type:l,data:{runnerIsClient:h,pluginCode:u,funcCode:f,parameters:p,requestBody:v}}=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
375
|
${JSON.stringify(p)}`);const A=(b=exports.configuration.plugins)==null?void 0:b[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=Ea(p,v);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:nn(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{const c=w({},a.data);if(c.usageExtension==null&&delete c.usageExtension,c.updateSession&&this.data&&(this.data=w(w({},this.data),c.updateSession),this.event.emit("data:updated",this.data)),c.index===-1){let l=this.messages[this.messages.length-1];if(l&&!l.messageId)l=w(w({},l),c),this.messages[this.messages.length-1]=l,this.event.emit("message:content",l),this.event.emit("message:updated",l),this.event.emit("answer:finish",l);else{const h=w({messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},c);this.event.emit("message:content",h),this.pushMessage(h),this.event.emit("answer:finish",h)}}else{let l=this.messages[this.messages.length-1];l&&!l.messageId?(l=w(w({},l),c),this.messages[this.messages.length-1]=l,this.event.emit("message:content",l),this.event.emit("message:updated",l)):(this.pushMessage(w({messageId:"",content:"",role:x.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},c)),this.event.emit("message:content",c))}}}),r.on("reference",a=>d(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const p=new Error(Le.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(w({},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(w({},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;cs(),this.stopLocalMcpUpdates||(this.stopLocalMcpUpdates=To(()=>this.registerLocalMcp()));const i=++this.localMcpTicket;ka({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.requestToken,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(w({},t),{promptVariables:this.promptVariables.filter(o=>o.type===x.PromptVariableType.User).reduce((o,a)=>S(w({},o),{[a.key]:a.value}),{}),systemPromptVariables:this.promptVariables.filter(o=>o.type===x.PromptVariableType.System).reduce((o,a)=>S(w({},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(Le.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",Sa(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||se.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())}updateSocketResourceToken(t){if(!this.socket)return;const i=this.socket.io.opts.query;i&&(i.Authorization=t),this.socket.connected&&(this.pendingTokenUpdate=!0,T.log("socket:update",this.id),this.socket.emit("update",{resourceToken:t},s=>{this.pendingTokenUpdate&&this.handleResourceTokenUpdateResult(s)}))}handleResourceTokenUpdateResult(t){if(this.pendingTokenUpdate=!1,!t||t.code===200){T.log("socket:update:ok",this.id);return}const i=new Error(Le.SocketConnectionFailed,{cause:t});T.error("socket:update:failed",t),this.event.emit("error",i)}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 Aa(n,e){return d(this,null,function*(){const t=n.getReader();let i;for(;!(i=yield t.read()).done;)e(i.value)})}function xa(n){let e,t,i,s=!1,r;return function(a){e===void 0?(e=a,t=0,i=-1,r=!1):e=Ra(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 Ta(n,e,t){let i=pi();const s=new TextDecoder;return function(o,a,c){if(o.length===0)t==null||t(i),i=pi();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 Ra(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function pi(){return{data:"",event:"",id:"",retry:void 0}}const tn="text/event-stream",La=1e3,gi="last-event-id";function mi(n,h){var u=h,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:a,fetch:c}=u,l=Fn(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,p)=>{const v=w({},t);v.accept||(v.accept=tn);let _;function b(){_.abort(),document.hidden||D()}a||document.addEventListener("visibilitychange",b);let A=La,E=0;function I(){document.removeEventListener("visibilitychange",b),window.clearTimeout(E),_.abort()}e==null||e.addEventListener("abort",()=>{I(),f()});const M=c!=null?c:window.fetch,q=i!=null?i:Ma;function D(){return d(this,null,function*(){var C;_=new AbortController;try{const L=yield M(n,S(w({},l),{headers:v,signal:_.signal}));yield q(L),yield Aa(L.body,xa(Ta(F=>{F?v[gi]=F:delete v[gi]},F=>{A=F},s))),r==null||r(),I(),f()}catch(L){if(!_.signal.aborted)try{const F=(C=o==null?void 0:o(L))!=null?C:A;window.clearTimeout(E),E=window.setTimeout(D,F)}catch(F){I(),p(F)}}})}D()})}function Ma(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith(tn)))throw new Error(`Expected content-type to be ${tn}, Actual: ${e}`)}const ke=new B("[DialogSession] ");class Ca extends xn{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(w({},s),{stream:exports.configuration.stream});mi(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.requestToken}`,"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(v){}(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:nn(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(w({},s),{stream:exports.configuration.stream}),u=h.imageContent;ke.log("question:request",Array.isArray(u)?S(w({},h),{imageContent:`[${u.length}]`}):h),mi(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.requestToken}`,"Content-Type":"application/json"},body:JSON.stringify(h),openWhenHidden:!0,signal:r,onopen(f){return ke.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(v){ke.error("parse eventData to JSON failed. ",f.data)}if(ke.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(w({},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(w({},f),{[p.key]:p.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===x.PromptVariableType.System).reduce((f,p)=>S(w({},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:()=>{ke.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=w(w({},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||(ke.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 Fa="@glodon-aiot/bot-client-sdk",Oa="3.26.1",Na="glodoncv",$a="aiot bot client js sdk",Pa="module",Da=!1,Ba=["aiot","bot","bot client","sdk"],ja=["dist"],Ua="./dist/es/index.mjs",qa="./dist/lib/index.js",Ha="./dist/src/index.d.ts",za={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},Wa="MIT",Va={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:e2e":"vitest run -c vitest.e2e.config.ts","test:watch":"vitest"},Ga={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@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","socket.io":"^4.7.5",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0",vitest:"^0.34.6"},Xa={access:"public",registry:"https://registry.npmjs.org/"},Qa={"@glodon-aiot/apis":"^3.26.1",axios:"0.24.0",dayjs:"^1.11.13","js-base64":"^3.7.7","socket.io-client":"^4.7.5",uuid:"^11.1.0"},Ya={name:Fa,version:Oa,author:Na,description:$a,type:Pa,sideEffects:Da,keywords:Ba,files:ja,module:Ua,main:qa,typings:Ha,exports:za,license:Wa,scripts:Va,devDependencies:Ga,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:Xa,dependencies:Qa},z=new B("[BotClient] ");class Ja{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){y(this,"event",new Sn);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,Yt(t,{refreshBuiltinPlugins:!1}),this._applicationId=Oe(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),cs(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{Yt(S(w({},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"),ii(void 0),We();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=vo(exports.configuration.apiRoot,()=>this.token,(c,l)=>z.error(l));this._localWorkspace=new ps({applicationId:this._applicationId,config:e,store:us(),picker:i==="host-bridge"?null:void 0,transfer:In(()=>this.cvforceApi,()=>a)}),ii(this._localWorkspace),this._localWorkspace.platformSkills=new Io({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 Ge?c.sandbox:void 0}}),i==="host-bridge"?this._disconnectHost=xo(this._localWorkspace):this._localWorkspace.restore()}t.push(...We()),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:Ya.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(w({},a),{arrange:[S(w({},a.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&a.arrange[0].recommendQuestionOpen})]})));const e=(o=(r=(s=this._application)==null?void 0:s.arrange)==null?void 0:r[0])==null?void 0:o.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(a=>a.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type: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:is(exports.configuration.apiRoot,()=>this.token,(e,t)=>z.error(t))}get token(){return this._token}set token(e){if(this.checkReady(),go(this._token,e)){this._token=e,this.notifySessionsResourceToken(e);return}this._token=e,this.ready=!1;const t=Oe(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 Ia(e,t,i,s,r,o));else if(h===x.ApplicationTypes.Dialog)a(new Ca(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 ko({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=[],this._activeSession=void 0,this.event.emit("sessions:updated",[])}notifySessionsResourceToken(e){const t=new Set(this._sessions);this._activeSession&&t.add(this._activeSession);for(const i of t)i.updateSocketResourceToken(e)}}class Ka{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 Y="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",J={type:"string",enum:[Me],description:`工作区 ID。省略时按 ${Me} 处理,传其他值会被拒绝。`},K=n=>({type:"string",description:`${n}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),Bt={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},gs={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${Y}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:J,path:K('要列出的目录,省略或传 "." 表示工作区根目录。'),offset:{type:"integer",minimum:0,description:"分页起始位置,默认 0。"},limit:{type:"integer",minimum:1,maximum:1e3,description:"每页条数,默认 200。"}}}},read_file:{functionCode:"read_file",name:"读取本地文件",description:`${Y}按行读取文本文件,单次最多返回 1 MiB,超出部分会被截断(truncated: true)。返回内容的 hash 可用于后续修改。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:J,path:K("要读取的文件。"),startLine:{type:"integer",minimum:1,description:"起始行(从 1 开始,含)。"},endLine:{type:"integer",minimum:1,description:"结束行(含)。"},maxBytes:{type:"integer",minimum:1,description:"返回内容的最大字节数,不超过 1 MiB。"},encoding:{type:"string",enum:["utf-8","gbk","gb18030"],description:"文本编码,默认 utf-8。"}}}},stat_file:{functionCode:"stat_file",name:"查看本地文件信息",description:`${Y}返回文件或目录的类型、大小、修改时间,可选返回 hash。不返回文件内容。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:J,path:K("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${Y}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:J,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:K("搜索起点目录,默认工作区根目录。"),maxDepth:{type:"integer",minimum:1,maximum:16,description:"最大目录深度,默认 8。"},maxResults:{type:"integer",minimum:1,maximum:200,description:"最多返回条数,默认 200。"}}}},search_text:{functionCode:"search_text",name:"搜索本地文本",description:`${Y}在指定文件或目录(递归)中搜索普通文本(不支持正则),返回所在文件、行号与该行内容。必须指定 path,不能搜索整个文件夹。`,parameters:{type:"object",required:["grantId","path","query"],properties:{grantId:J,path:K("搜索范围,可以是文件或目录。"),query:{type:"string",minLength:1,description:"要查找的文本。"},caseSensitive:{type:"boolean",description:"是否区分大小写,默认否。"},isRegex:{type:"boolean",description:"暂不支持正则,传 true 会返回 501。"},glob:{type:"string",description:"只搜索匹配该 glob 的文件,如 *.md。"},maxResults:{type:"integer",minimum:1,maximum:200,description:"最多返回条数,默认 200。"},contextLines:{type:"integer",minimum:0,maximum:3,description:"附带的上下文行数,默认 0。"}}}},apply_patch:{functionCode:"apply_patch",name:"修改本地文件",description:`${Y}以查找替换的方式修改 UTF-8 文本文件。每条修改的 oldText 必须在文件中唯一出现(或设置 replaceAll)。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","expectedHash","edits"],properties:{grantId:J,path:K("要修改的文件。"),expectedHash:Bt,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:J,path:K("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:Bt,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:J,path:K("要上传的文件。"),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:J,destPath:K("保存位置(文件路径)。"),source:{type:"object",required:["type"],description:"下载来源。type 为 url 时必填 url;type 为 sessionFile 或 platformFile 时必填 fileId。",properties:{type:{type:"string",enum:["sessionFile","platformFile","url"],description:"sessionFile:当前会话文件;platformFile:平台文件(upload_file 返回的 fileId);url:https 地址。"},fileId:{type:"string",description:"type 为 sessionFile 或 platformFile 时必填,不能只传 type。"},url:{type:"string",description:"type 为 url 时必填,填写完整 https 地址。不能只传 type。默认只允许 glodon.com 及其子域。"}}},overwrite:{type:"boolean",description:"目标已存在时是否覆盖,默认否。"},expectedHash:Bt}}}},Za=new TextEncoder;function re(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const ec=(n,e)=>d(exports,null,function*(){const t=ne(n.path,{allowRoot:!0});if((yield e.adapter.stat(t)).kind!=="directory")throw new g(m.BadRequest,"目标是文件,不是目录。");const s=re(n.offset,0,0,Number.MAX_SAFE_INTEGER),r=re(n.limit,Ei,1,Ii),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=ls(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 tc(n,e,t){return ye(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 oe(s.read());r+=c?i.decode():i.decode(l,{stream:!0});const h=r.split(`
|
|
377
|
+
`+u:u;break;case"event":i.event=u;break;case"id":n(i.id=u);break;case"retry":const f=parseInt(u,10);isNaN(f)||e(i.retry=f);break}}}}function Ra(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function pi(){return{data:"",event:"",id:"",retry:void 0}}const tn="text/event-stream",La=1e3,gi="last-event-id";function mi(n,h){var u=h,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:a,fetch:c}=u,l=Fn(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,p)=>{const v=w({},t);v.accept||(v.accept=tn);let _;function b(){_.abort(),document.hidden||D()}a||document.addEventListener("visibilitychange",b);let A=La,E=0;function I(){document.removeEventListener("visibilitychange",b),window.clearTimeout(E),_.abort()}e==null||e.addEventListener("abort",()=>{I(),f()});const M=c!=null?c:window.fetch,q=i!=null?i:Ma;function D(){return d(this,null,function*(){var C;_=new AbortController;try{const L=yield M(n,S(w({},l),{headers:v,signal:_.signal}));yield q(L),yield Aa(L.body,xa(Ta(F=>{F?v[gi]=F:delete v[gi]},F=>{A=F},s))),r==null||r(),I(),f()}catch(L){if(!_.signal.aborted)try{const F=(C=o==null?void 0:o(L))!=null?C:A;window.clearTimeout(E),E=window.setTimeout(D,F)}catch(F){I(),p(F)}}})}D()})}function Ma(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith(tn)))throw new Error(`Expected content-type to be ${tn}, Actual: ${e}`)}const ke=new B("[DialogSession] ");class Ca extends xn{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(w({},s),{stream:exports.configuration.stream});mi(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.requestToken}`,"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(v){}(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:nn(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(w({},s),{stream:exports.configuration.stream}),u=h.imageContent;ke.log("question:request",Array.isArray(u)?S(w({},h),{imageContent:`[${u.length}]`}):h),mi(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.requestToken}`,"Content-Type":"application/json"},body:JSON.stringify(h),openWhenHidden:!0,signal:r,onopen(f){return ke.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(v){ke.error("parse eventData to JSON failed. ",f.data)}if(ke.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(w({},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(w({},f),{[p.key]:p.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===x.PromptVariableType.System).reduce((f,p)=>S(w({},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:()=>{ke.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=w(w({},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||(ke.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 Fa="@glodon-aiot/bot-client-sdk",Oa="3.26.3",Na="glodoncv",$a="aiot bot client js sdk",Pa="module",Da=!1,Ba=["aiot","bot","bot client","sdk"],ja=["dist"],Ua="./dist/es/index.mjs",qa="./dist/lib/index.js",Ha="./dist/src/index.d.ts",za={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},Wa="MIT",Va={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:e2e":"vitest run -c vitest.e2e.config.ts","test:watch":"vitest"},Ga={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@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","socket.io":"^4.7.5",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0",vitest:"^0.34.6"},Xa={access:"public",registry:"https://registry.npmjs.org/"},Qa={"@glodon-aiot/apis":"^3.26.3",axios:"0.24.0",dayjs:"^1.11.13","js-base64":"^3.7.7","socket.io-client":"^4.7.5",uuid:"^11.1.0"},Ya={name:Fa,version:Oa,author:Na,description:$a,type:Pa,sideEffects:Da,keywords:Ba,files:ja,module:Ua,main:qa,typings:Ha,exports:za,license:Wa,scripts:Va,devDependencies:Ga,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:Xa,dependencies:Qa},z=new B("[BotClient] ");class Ja{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){y(this,"event",new Sn);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,Yt(t,{refreshBuiltinPlugins:!1}),this._applicationId=Oe(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),cs(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{Yt(S(w({},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"),ii(void 0),We();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=vo(exports.configuration.apiRoot,()=>this.token,(c,l)=>z.error(l));this._localWorkspace=new ps({applicationId:this._applicationId,config:e,store:us(),picker:i==="host-bridge"?null:void 0,transfer:In(()=>this.cvforceApi,()=>a)}),ii(this._localWorkspace),this._localWorkspace.platformSkills=new Io({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 Ge?c.sandbox:void 0}}),i==="host-bridge"?this._disconnectHost=xo(this._localWorkspace):this._localWorkspace.restore()}t.push(...We()),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:Ya.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(w({},a),{arrange:[S(w({},a.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&a.arrange[0].recommendQuestionOpen})]})));const e=(o=(r=(s=this._application)==null?void 0:s.arrange)==null?void 0:r[0])==null?void 0:o.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(a=>a.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type: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:is(exports.configuration.apiRoot,()=>this.token,(e,t)=>z.error(t))}get token(){return this._token}set token(e){if(this.checkReady(),go(this._token,e)){this._token=e,this.notifySessionsResourceToken(e);return}this._token=e,this.ready=!1;const t=Oe(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 Ia(e,t,i,s,r,o));else if(h===x.ApplicationTypes.Dialog)a(new Ca(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 ko({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=[],this._activeSession=void 0,this.event.emit("sessions:updated",[])}notifySessionsResourceToken(e){const t=new Set(this._sessions);this._activeSession&&t.add(this._activeSession);for(const i of t)i.updateSocketResourceToken(e)}}class Ka{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 Y="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",J={type:"string",enum:[Me],description:`工作区 ID。省略时按 ${Me} 处理,传其他值会被拒绝。`},K=n=>({type:"string",description:`${n}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),Bt={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},gs={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${Y}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:J,path:K('要列出的目录,省略或传 "." 表示工作区根目录。'),offset:{type:"integer",minimum:0,description:"分页起始位置,默认 0。"},limit:{type:"integer",minimum:1,maximum:1e3,description:"每页条数,默认 200。"}}}},read_file:{functionCode:"read_file",name:"读取本地文件",description:`${Y}按行读取文本文件,单次最多返回 1 MiB,超出部分会被截断(truncated: true)。返回内容的 hash 可用于后续修改。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:J,path:K("要读取的文件。"),startLine:{type:"integer",minimum:1,description:"起始行(从 1 开始,含)。"},endLine:{type:"integer",minimum:1,description:"结束行(含)。"},maxBytes:{type:"integer",minimum:1,description:"返回内容的最大字节数,不超过 1 MiB。"},encoding:{type:"string",enum:["utf-8","gbk","gb18030"],description:"文本编码,默认 utf-8。"}}}},stat_file:{functionCode:"stat_file",name:"查看本地文件信息",description:`${Y}返回文件或目录的类型、大小、修改时间,可选返回 hash。不返回文件内容。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:J,path:K("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${Y}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:J,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:K("搜索起点目录,默认工作区根目录。"),maxDepth:{type:"integer",minimum:1,maximum:16,description:"最大目录深度,默认 8。"},maxResults:{type:"integer",minimum:1,maximum:200,description:"最多返回条数,默认 200。"}}}},search_text:{functionCode:"search_text",name:"搜索本地文本",description:`${Y}在指定文件或目录(递归)中搜索普通文本(不支持正则),返回所在文件、行号与该行内容。必须指定 path,不能搜索整个文件夹。`,parameters:{type:"object",required:["grantId","path","query"],properties:{grantId:J,path:K("搜索范围,可以是文件或目录。"),query:{type:"string",minLength:1,description:"要查找的文本。"},caseSensitive:{type:"boolean",description:"是否区分大小写,默认否。"},isRegex:{type:"boolean",description:"暂不支持正则,传 true 会返回 501。"},glob:{type:"string",description:"只搜索匹配该 glob 的文件,如 *.md。"},maxResults:{type:"integer",minimum:1,maximum:200,description:"最多返回条数,默认 200。"},contextLines:{type:"integer",minimum:0,maximum:3,description:"附带的上下文行数,默认 0。"}}}},apply_patch:{functionCode:"apply_patch",name:"修改本地文件",description:`${Y}以查找替换的方式修改 UTF-8 文本文件。每条修改的 oldText 必须在文件中唯一出现(或设置 replaceAll)。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","expectedHash","edits"],properties:{grantId:J,path:K("要修改的文件。"),expectedHash:Bt,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:J,path:K("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:Bt,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:J,path:K("要上传的文件。"),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:J,destPath:K("保存位置(文件路径)。"),source:{type:"object",required:["type"],description:"下载来源。type 为 url 时必填 url;type 为 sessionFile 或 platformFile 时必填 fileId。",properties:{type:{type:"string",enum:["sessionFile","platformFile","url"],description:"sessionFile:当前会话文件;platformFile:平台文件(upload_file 返回的 fileId);url:https 地址。"},fileId:{type:"string",description:"type 为 sessionFile 或 platformFile 时必填,不能只传 type。"},url:{type:"string",description:"type 为 url 时必填,填写完整 https 地址。不能只传 type。默认只允许 glodon.com 及其子域。"}}},overwrite:{type:"boolean",description:"目标已存在时是否覆盖,默认否。"},expectedHash:Bt}}}},Za=new TextEncoder;function re(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const ec=(n,e)=>d(exports,null,function*(){const t=ne(n.path,{allowRoot:!0});if((yield e.adapter.stat(t)).kind!=="directory")throw new g(m.BadRequest,"目标是文件,不是目录。");const s=re(n.offset,0,0,Number.MAX_SAFE_INTEGER),r=re(n.limit,Ei,1,Ii),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=ls(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 tc(n,e,t){return ye(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 oe(s.read());r+=c?i.decode():i.decode(l,{stream:!0});const h=r.split(`
|
|
378
378
|
`);r=(a=h.pop())!=null?a:"";for(const u of h)o=!0,yield u;if(c)break}}finally{s.releaseLock()}(r||!o)&&(yield r)})}const nc=(n,e)=>d(exports,null,function*(){var I,M;const t=ne(n.path);$e(e,t,"read");const i=yield pn(e.adapter,t),s=yield e.adapter.readFile(t),r=(I=i.size)!=null?I:s.size;if(yield Zs(s))throw new g(m.BadRequest,"这是二进制文件,不能按文本读取。可以使用 stat_file 查看信息,或使用 upload_file 上传到会话。");const o=yield Q(s.slice(0,3)),a=Wi(o)?"utf-8":(M=n.encoding)!=null?M:"utf-8",c=re(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=re(n.maxBytes,e.limits.maxReadBytes,1,e.limits.maxReadBytes),u=r<=e.limits.maxTransferBytes,f=[];let p=0,v=0,_=c-1,b=!1,A=!1;try{for(var q=X(tc(s,a,e.signal)),D,C,L;D=!(C=yield q.next()).done;D=!1){const F=C.value;v++;const W=F.endsWith("\r")?F.slice(0,-1):F;if(W!==F&&(A=!0),v<c||v>l||b){if(!u&&(b||v>l))break;continue}const H=gn(W)+(f.length?1:0);if(p+H>h){if(b=!0,f.length||(f.push(ic(W,h)),_=v),!u)break;continue}f.push(W),p+=H,_=v}}catch(C){L=[C]}finally{try{D&&(C=q.return)&&(yield C.call(q))}finally{if(L)throw L[0]}}const E={path:t,content:f.join(`
|
|
379
379
|
`),startLine:c,endLine:Math.max(_,c-1),size:r,encoding:a,lineEnding:A?"crlf":"lf"};return u&&(E.totalLines=v),r<=e.limits.maxWriteBytes&&(E.hash=yield Fe(yield Q(s))),{data:E,truncated:b||void 0}});function ic(n,e){const t=Za.encode(n);return t.byteLength<=e?n:new TextDecoder().decode(t.slice(0,e)).replace(/\uFFFD$/,"")}const sc=(n,e)=>d(exports,null,function*(){var r;const t=ne(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 Fe(yield Q(yield e.adapter.readFile(t))))),{data:s}});function rc(n){return Ci.some(e=>ut(e,n))}function ms(n,e,t){return ye(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 oe(Vi()));const o=yield new oe(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=ls(r.path,a.name);if(a.kind==="directory"){r.depth+1<t&&!Mi.includes(a.name)&&i.push({path:c,depth:r.depth+1});continue}rc(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 ys(n,e){return n.includes("/")?ut(n,e.relativePath):ut(n,e.name)}const oc=(n,e)=>d(exports,null,function*(){const t=ne(n.path,{allowRoot:!0});if(!n.pattern.trim())throw new g(m.BadRequest,"参数 pattern 不能为空。");const i=n.pattern.replace(/\\/g,"/").replace(/^\.\//,"");if((yield e.adapter.stat(t)).kind!=="directory")throw new g(m.BadRequest,"参数 path 必须是目录。");const r=re(n.maxDepth,Ai,1,rn),o=re(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),a=[];let c=!1;try{for(var l=X(ms(e,t,r)),h,u,f;h=!(u=yield l.next()).done;h=!1){const p=u.value;if(ys(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 jt(n,e){if(n.length<=st)return n;const t=Math.max(0,Math.min(e-100,n.length-st));return n.slice(t,t+st)}const ac=(n,e)=>d(exports,null,function*(){var f;const t=ne(n.path,{allowRoot:!0});if(!t&&!e.allowWorkspaceWideTextSearch)throw new g(m.BadRequest,"不支持在整个工作区内搜索文本,请把 path 缩小到具体的子目录或文件。");if(n.isRegex)throw new g(m.NotImplemented,"暂不支持正则搜索,请使用普通文本搜索。");if(!n.query)throw new g(m.BadRequest,"参数 query 不能为空。");const i=n.caseSensitive===!0,s=i?n.query:n.query.toLowerCase(),r=re(n.contextLines,0,0,Ri),o=re(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),a=yield e.adapter.stat(t);let c;a.kind==="file"?($e(e,t,"search"),c=function(){return ye(this,null,function*(){yield{path:t,relativePath:t,name:a.name,size:a.size}})}()):c=ms(e,t,rn);const l=[];let h=0,u=!1;e:try{for(var p=X(c),v,_,b;v=!(_=yield p.next()).done;v=!1){const A=_.value;if(n.glob&&!ys(n.glob,A)||((f=A.size)!=null?f:0)>Ti)continue;if(h>=xi){u=!0;break}h++,h%20===0&&(yield Vi()),N(e.signal);const E=yield Q(yield e.adapter.readFile(A.path));if(pe(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:jt(I[M],D)};r&&(C.before=I.slice(Math.max(0,M-r),M).map(L=>jt(L,0)),C.after=I.slice(M+1,M+1+r).map(L=>jt(L,0))),l.push(C)}}}catch(_){b=[_]}finally{try{v&&(_=p.return)&&(yield _.call(p))}finally{if(b)throw b[0]}}return{data:{matches:l,filesScanned:h},truncated:u||void 0}});function yi(){return new g(m.Forbidden,"下载地址不在允许范围内:只允许 https 协议且域名在白名单中的地址。",{reason:"url_not_allowed"})}const cc=(n,e)=>d(exports,null,function*(){var u,f;const t=ne(n.path);if(((u=n.target)!=null?u:"session")!=="session")throw new g(m.NotImplemented,"目前只支持上传到当前会话(target: session)。");$e(e,t,"read");const s=yield pn(e.adapter,t),r=(f=s.size)!=null?f:0;if(r>e.limits.maxTransferBytes)throw ue(e.limits.maxTransferBytes);const o=un(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:v})=>e.progress({stage:"uploading",loaded:p,total:v,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 lc(n){const e=n;if(!e||typeof e!="object")throw new g(m.BadRequest,"缺少参数 source。");if(e.type==="sessionFile"||e.type==="platformFile"){if(typeof e.fileId!="string"||!e.fileId)throw new g(m.BadRequest,"source.fileId 必须是非空字符串。");return{type:e.type,fileId:e.fileId}}if(e.type==="url"){if(typeof e.url!="string"||!e.url)throw new g(m.BadRequest,"source.url 必须是非空字符串。");return{type:"url",url:e.url}}throw new g(m.BadRequest,"source.type 必须是 sessionFile、platformFile 或 url 之一。")}function dc(n){return n.type==="sessionFile"?"会话文件":n.type==="platformFile"?"平台文件":new URL(n.url).hostname}function hc(n,e,t,i,s){return ye(this,null,function*(){const r=n.getReader();let o=0;try{for(;;){N(e.signal);const{done:a,value:c}=yield new oe(r.read());if(a)break;if(o+=c.byteLength,o>e.limits.maxTransferBytes)throw ue(e.limits.maxTransferBytes,"下载内容");s.push(c),e.progress({stage:"downloading",loaded:o,total:i,path:t}),yield c}}finally{r.cancel().catch(()=>{})}})}const uc=(n,e)=>d(exports,null,function*(){var _,b,A;const t=ne(n.destPath,{field:"destPath"}),i=lc(n.source);if(i.type==="url"&&!Zt(i.url,e.downloadUrlAllowlist))throw yi();$e(e,t,"write");const s=yield ot(e.adapter,t);if((s==null?void 0:s.kind)==="directory")throw new g(m.BadRequest,"目标是目录,不能写入文件。");if(s&&!n.overwrite)throw new g(m.Conflict,"目标文件已存在。如需覆盖,请设置 overwrite: true。");const r=()=>d(exports,null,function*(){if(!s||!n.expectedHash)return;const E=yield Fe(yield Q(yield e.adapter.readFile(t)));if(E!==n.expectedHash)throw new g(m.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 ue(e.limits.maxTransferBytes);const a={type:"download",source:{type:i.type,label:dc(i)},name:(_=o.name)!=null?_:un(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 g(m.Internal,"下载失败,无法连接到文件地址。")}if(i.type==="url"&&c.url&&!Zt(c.url,e.downloadUrlAllowlist))throw(b=c.body)==null||b.cancel().catch(()=>{}),yi();if(!c.ok||!c.body)throw(A=c.body)==null||A.cancel().catch(()=>{}),new g(c.status===404?m.NotFound:m.Internal,`下载失败(HTTP ${c.status})。`);const l=Number(c.headers.get("content-length")),h=Number.isFinite(l)&&l>0?l:void 0;if(h!==void 0&&h>e.limits.maxTransferBytes)throw c.body.cancel().catch(()=>{}),ue(e.limits.maxTransferBytes);const u=[];yield e.adapter.writeFile(t,hc(c.body,e,t,h,u),{signal:e.signal});const f=u.reduce((E,I)=>E+I.byteLength,0),p=new Uint8Array(f);let v=0;return u.forEach(E=>{p.set(E,v),v+=E.byteLength}),e.progress({stage:"done",loaded:f,total:f,path:t}),{data:{path:t,size:f,hash:yield Fe(p)}}}),Ut=new Uint8Array([239,187,191]);function mt(n,e){return new g(m.Conflict,e,{currentHash:n})}function Tn(n,e){return d(this,null,function*(){var s;if(((s=(yield pn(n.adapter,e)).size)!=null?s:0)>n.limits.maxWriteBytes)throw ue(n.limits.maxWriteBytes,"目标文件");const i=yield Q(yield n.adapter.readFile(e));return{bytes:i,hash:yield Fe(i)}})}function ws(n,e,t){return d(this,null,function*(){const{hash:i}=yield Tn(n,e);if(i!==t)throw mt(i,"文件在确认期间已被修改,本次写入已取消。请重新读取后再修改。")})}function fc(n,e){const t=new TextEncoder().encode(n);if(!e)return t;const i=new Uint8Array(Ut.byteLength+t.byteLength);return i.set(Ut,0),i.set(t,Ut.byteLength),i}function pc(n,e){let t=0,i=n.indexOf(e);for(;i>=0;)t++,i=n.indexOf(e,i+e.length);return t}function wi(n,e){return!e||n.includes(`\r
|
|
380
380
|
`)?n:n.replace(/\n/g,`\r
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glodon-aiot/bot-client-sdk",
|
|
3
|
-
"version": "3.26.
|
|
3
|
+
"version": "3.26.3",
|
|
4
4
|
"author": "glodoncv",
|
|
5
5
|
"description": "aiot bot client js sdk",
|
|
6
6
|
"type": "module",
|
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
"registry": "https://registry.npmjs.org/"
|
|
70
70
|
},
|
|
71
71
|
"dependencies": {
|
|
72
|
-
"@glodon-aiot/apis": "^3.26.
|
|
72
|
+
"@glodon-aiot/apis": "^3.26.3",
|
|
73
73
|
"axios": "0.24.0",
|
|
74
74
|
"dayjs": "^1.11.13",
|
|
75
75
|
"js-base64": "^3.7.7",
|