agent-tool-chat 1.1.3 → 1.1.4
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/index.cjs +4 -4
- package/dist/index.js +20 -6
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";var ci=Object.defineProperty;var ui=(e,t,n)=>t in e?ci(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var L=(e,t,n)=>ui(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("vue"),ft=require("element-plus");function hi(e){let t="";return typeof e.content=="string"?t=e.content:e.content!=null&&(t=JSON.stringify(e.content)),e.tool_calls&&(t+=JSON.stringify(e.tool_calls)),e.name&&(t+=e.name),Math.ceil(t.length/2)||1}function di(e,t){const n=e.length;if(n===0)return e;let i=0,o=n-1;for(let s=n-1;s>=0;s--)if(i+=hi(e[s]),o=s,i>t){o=Math.min(s+1,n-1);break}return o>0&&e[o].role==="tool"&&(o-=1),e.slice(o)}class Zo{constructor(t){L(this,"messages",[]);L(this,"config");L(this,"listeners",new Set);L(this,"abortController",null);L(this,"_loading",!1);this.config={...t,maxToolRounds:t.maxToolRounds??6}}get loading(){return this._loading}updateProviderConfig(t){this.config.providerConfig={...this.config.providerConfig,...t}}initialize(t){this.messages.length=0,this.messages.push(...t)}clear(){var t;this.stop(),this.messages.length=0,(t=this.config.storage)==null||t.save([])}on(t){return this.listeners.add(t),()=>this.listeners.delete(t)}emit(t){this.listeners.forEach(n=>n(t))}async sendMessage(t){var o;const n=t.trim();if(!n||this._loading)return;this._loading=!0,this.abortController=new AbortController,this.emit({type:"status",loading:!0});const i={role:"user",content:n};this.messages.push(i),this.emit({type:"message",message:i});try{let s=0;const l=this.config.maxToolRounds;for(;s<l;){s++;const A={role:"assistant",content:""};this.messages.push(A),this.emit({type:"message",message:A});const a=this.buildApiMessages(),u=await this.config.provider.streamChat({config:this.config.providerConfig,messages:a,tools:this.config.tools.getDefinitions(),signal:this.abortController.signal,onContent:d=>{A.content+=d,this.emit({type:"stream:delta",delta:{content:d}})},onReasoning:d=>{this.emit({type:"stream:delta",delta:{reasoning:d}})}});if(A.content=u.content,this.emit({type:"stream:end",content:u.content,reasoning:u.reasoning}),u.tool_calls.length>0){A.tool_calls=u.tool_calls;for(const d of u.tool_calls){this.emit({type:"tool:start",call:d});const f=await this.config.tools.execute(d.function.name,d.function.arguments);this.emit({type:"tool:end",call:d,output:f}),this.messages.push({role:"tool",tool_call_id:d.id,content:f.result,name:d.function.name})}continue}break}await((o=this.config.storage)==null?void 0:o.save(this.messages))}catch(s){if((s==null?void 0:s.name)!=="AbortError")this.emit({type:"error",error:(s==null?void 0:s.message)||"请求出错"});else{const l=this.messages[this.messages.length-1];(l==null?void 0:l.role)==="assistant"&&!l.content&&(l.content="(已停止生成)")}}finally{this._loading=!1,this.abortController=null,this.emit({type:"status",loading:!1})}}stop(){var t;(t=this.abortController)==null||t.abort()}buildApiMessages(){const t=this.messages;let i=t.length>0&&t[t.length-1].role==="assistant"&&t[t.length-1].content===""&&!t[t.length-1].tool_calls?t.slice(0,-1):t;const o=this.config.maxHistoryMessages??0;o>0&&i.length>o&&(i=i.slice(i.length-o));const s=this.config.maxContextTokens??0;for(s>0&&(i=di(i,s));i.length&&i[0].role==="tool";)i=i.slice(1);return this.config.systemPrompt?[{role:"system",content:this.config.systemPrompt},...i]:[...i]}}class Po{constructor(){L(this,"_definitions",[]);L(this,"_handlers",new Map)}register(t,n){const i=t.function.name,o=this._definitions.findIndex(s=>s.function.name===i);return o!==-1&&this._definitions.splice(o,1),this._definitions.push(t),this._handlers.set(i,n),this}registerBatch(t){for(const n of t)this.register(n.definition,n.handler);return this}getDefinitions(){return[...this._definitions]}async execute(t,n){const i=this._handlers.get(t);if(!i)return{success:!1,result:`未知工具:${t}`};try{const o=n?JSON.parse(n):{};return await i(o)}catch(o){return{success:!1,result:`工具执行异常:${(o==null?void 0:o.message)||String(o)}`}}}}function fi(e){let t=e.trim().replace(/\/+$/,"");return t=t.replace(/\/v1$/,""),t}function zo(){return{async streamChat(e){var w;const{config:{baseUrl:t,apiKey:n,model:i,temperature:o,thinking:s},messages:l,tools:A,signal:a,onContent:u,onReasoning:d}=e;if(!n)throw new Error("未配置 API Key");const f=`${fi(t)}/chat/completions`,_={model:i,messages:l,stream:!0};typeof o=="number"&&(_.temperature=o),_.thinking={type:(s==null?void 0:s.type)==="enabled"?"enabled":"disabled"},(s==null?void 0:s.type)==="enabled"&&s.effort&&(_.reasoning_effort=s.effort),A!=null&&A.length&&(_.tools=A,_.tool_choice="auto");const m=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(_),signal:a});if(!m.ok||!m.body){let E=`请求失败(HTTP ${m.status})`;try{const x=await m.json();(w=x==null?void 0:x.error)!=null&&w.message&&(E=x.error.message)}catch{}throw new Error(E)}const h=m.body.getReader(),k=new TextDecoder("utf-8");let b="",g="",I="",S="stop";const C=new Map,B=E=>{if(!E)return;const x=E.index??0;C.has(x)||C.set(x,{id:"",type:"function",function:{name:"",arguments:""}});const R=C.get(x);E.id&&(R.id=E.id),E.type&&(R.type=E.type),E.function&&(E.function.name&&(R.function.name+=E.function.name),E.function.arguments&&(R.function.arguments+=E.function.arguments))},K=E=>{var J;const x=(J=E==null?void 0:E.choices)==null?void 0:J[0];if(!x)return;const R=x.delta||{};typeof R.content=="string"&&R.content&&(g+=R.content,u==null||u(R.content)),typeof R.reasoning_content=="string"&&R.reasoning_content&&(I+=R.reasoning_content,d==null||d(R.reasoning_content)),Array.isArray(R.tool_calls)&&R.tool_calls.forEach(z=>B(z)),x.finish_reason&&(S=x.finish_reason)};for(;;){const{done:E,value:x}=await h.read();if(E)break;b+=k.decode(x,{stream:!0});let R;for(;(R=b.indexOf(`
|
|
2
|
-
`))!==-1;){const J=b.slice(0,R).replace(/\r$/,"").trim();if(b=b.slice(R+1),!J||J.startsWith(":")||!J.startsWith("data:"))continue;const z=J.slice(5).trim();if(z==="[DONE]")return N();try{K(JSON.parse(z))}catch{}}}return N();function N(){const E=Array.from(C.values()).filter(x=>x.function.name);return{content:g,reasoning:I,tool_calls:E,finish_reason:S}}}}}function jo(){return{async streamChat(e){var N;const{config:{baseUrl:t,model:n,temperature:i,thinking:o},messages:s,tools:l,signal:A,onContent:a,onReasoning:u}=e,d=`${t.trim().replace(/\/+$/,"")}`,f={model:n,messages:s,stream:!0};typeof i=="number"&&(f.temperature=i),f.thinking={type:(o==null?void 0:o.type)==="enabled"?"enabled":"disabled"},(o==null?void 0:o.type)==="enabled"&&o.effort&&(f.reasoning_effort=o.effort),l!=null&&l.length&&(f.tools=l,f.tool_choice="auto");const _=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f),signal:A});if(!_.ok||!_.body){let w=`请求失败(HTTP ${_.status})`;try{const E=await _.json();(N=E==null?void 0:E.error)!=null&&N.message&&(w=E.error.message)}catch{}throw new Error(w)}const m=_.body.getReader(),h=new TextDecoder("utf-8");let k="",b="",g="",I="stop";const S=new Map,C=w=>{if(!w)return;const E=w.index??0;S.has(E)||S.set(E,{id:"",type:"function",function:{name:"",arguments:""}});const x=S.get(E);w.id&&(x.id=w.id),w.type&&(x.type=w.type),w.function&&(w.function.name&&(x.function.name+=w.function.name),w.function.arguments&&(x.function.arguments+=w.function.arguments))},B=w=>{var R;const E=(R=w==null?void 0:w.choices)==null?void 0:R[0];if(!E)return;const x=E.delta||{};typeof x.content=="string"&&x.content&&(b+=x.content,a==null||a(x.content)),typeof x.reasoning_content=="string"&&x.reasoning_content&&(g+=x.reasoning_content,u==null||u(x.reasoning_content)),Array.isArray(x.tool_calls)&&x.tool_calls.forEach(J=>C(J)),E.finish_reason&&(I=E.finish_reason)};for(;;){const{done:w,value:E}=await m.read();if(w)break;k+=h.decode(E,{stream:!0});let x;for(;(x=k.indexOf(`
|
|
2
|
+
`))!==-1;){const J=b.slice(0,R).replace(/\r$/,"").trim();if(b=b.slice(R+1),!J||J.startsWith(":")||!J.startsWith("data:"))continue;const z=J.slice(5).trim();if(z==="[DONE]")return N();try{K(JSON.parse(z))}catch{}}}return N();function N(){const E=Array.from(C.values()).filter(x=>x.function.name);return{content:g,reasoning:I,tool_calls:E,finish_reason:S}}}}}function jo(){return{async streamChat(e){var N;const{config:{baseUrl:t,model:n,temperature:i,thinking:o},messages:s,tools:l,signal:A,onContent:a,onReasoning:u}=e,d=`${t.trim().replace(/\/+$/,"")}`,f={model:n,messages:s,stream:!0};typeof i=="number"&&(f.temperature=i),f.thinking={type:(o==null?void 0:o.type)==="enabled"?"enabled":"disabled"},(o==null?void 0:o.type)==="enabled"&&o.effort&&(f.reasoning_effort=o.effort),l!=null&&l.length&&(f.tools=l,f.tool_choice="auto");const _=await fetch(d+"/api/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f),signal:A});if(!_.ok||!_.body){let w=`请求失败(HTTP ${_.status})`;try{const E=await _.json();(N=E==null?void 0:E.error)!=null&&N.message&&(w=E.error.message)}catch{}throw new Error(w)}const m=_.body.getReader(),h=new TextDecoder("utf-8");let k="",b="",g="",I="stop";const S=new Map,C=w=>{if(!w)return;const E=w.index??0;S.has(E)||S.set(E,{id:"",type:"function",function:{name:"",arguments:""}});const x=S.get(E);w.id&&(x.id=w.id),w.type&&(x.type=w.type),w.function&&(w.function.name&&(x.function.name+=w.function.name),w.function.arguments&&(x.function.arguments+=w.function.arguments))},B=w=>{var R;const E=(R=w==null?void 0:w.choices)==null?void 0:R[0];if(!E)return;const x=E.delta||{};typeof x.content=="string"&&x.content&&(b+=x.content,a==null||a(x.content)),typeof x.reasoning_content=="string"&&x.reasoning_content&&(g+=x.reasoning_content,u==null||u(x.reasoning_content)),Array.isArray(x.tool_calls)&&x.tool_calls.forEach(J=>C(J)),E.finish_reason&&(I=E.finish_reason)};for(;;){const{done:w,value:E}=await m.read();if(w)break;k+=h.decode(E,{stream:!0});let x;for(;(x=k.indexOf(`
|
|
3
3
|
`))!==-1;){const R=k.slice(0,x).replace(/\r$/,"").trim();if(k=k.slice(x+1),!R||R.startsWith(":")||!R.startsWith("data:"))continue;const J=R.slice(5).trim();if(J==="[DONE]")return K();try{B(JSON.parse(J))}catch{}}}return K();function K(){const w=Array.from(S.values()).filter(E=>E.function.name);return{content:b,reasoning:g,tool_calls:w,finish_reason:I}}}}}function pi(e){var n,i,o,s,l;const t=[];return(n=e.displayHints)!=null&&n.suggestComponent&&t.push(`展示建议: 使用 ${e.displayHints.suggestComponent} 组件`),(i=e.displayHints)!=null&&i.resultFormat&&t.push(`格式: ${e.displayHints.resultFormat}`),(s=(o=e.displayHints)==null?void 0:o.previewFields)!=null&&s.length&&t.push(`预览字段: ${e.displayHints.previewFields.join(", ")}`),(l=e.displayHints)!=null&&l.summaryTemplate&&t.push(`概要模板: ${e.displayHints.summaryTemplate}`),t.length?t.join(" | "):""}function Xo(e){const t=[`【${e.name}】${e.description}`];for(const n of e.tools){const i=pi(n);t.push(` - ${n.name}: ${n.description}`),i&&t.push(` ${i}`)}return t.join(`
|
|
4
|
-
`)}function $o(e){const t=["你是一个 AI 助手,可以帮助用户完成各种操作。","","你可以使用以下工具包:",""];for(const n of e)t.push(Xo(n)),t.push("");return t.push("注意:"),t.push("1. 所有回复与思考/推理过程(reasoning / thinking)一律使用中文(禁止使用英文),保持简洁清晰;除非用户明确要求使用其他语言,此时思考与回复也相应使用该语言。"),t.push("2. 当你需要查询或操作数据时,调用对应工具包中的函数。"),t.push("3. 工具函数由宿主系统执行,你只需要传递正确的参数。"),t.push("4. 获取到工具结果后,回复用户并告知结果。"),t.push("5. 如果工具返回了结构化数据(如订单信息、系统状态等),在回复中清晰地展示给用户。"),t.push("6. 根据结果动态建议用户接下来可以做什么。"),t.push("7. 如果用户上传了文件,文件格式为(.txt、.json、.geojson等格式),你必须调用 open_mapview_file 工具在地图上展示,不要只回复文字。"),t.push(""),t.push("--- 文件上传规则 ---"),t.push("用户可能上传文件,文件以如下格式出现在消息中:"),t.push("已上传文件:"),t.push("1. **文件名**(类型,大小KB),文件ID:`fileId`"),t.push("你无法查看文件内容,只能看到文件名和类型。"),t.push("你必须根据文件名、扩展名和用户的文字指令,调用对应的工具来处理文件。"),t.push("如果某个工具需要处理该文件,在工具参数中传入 fileId。"),t.push('不要回复假性成功消息(如"已在地图上显示"),如果不调用工具,文件不会被实际处理。'),t.push("不要编造文件内容,不要假装你看到了文件数据。"),t.join(`
|
|
4
|
+
`)}function $o(e){const t=["你是一个 AI 助手,可以帮助用户完成各种操作。","","你可以使用以下工具包:",""];for(const n of e)t.push(Xo(n)),t.push("");return t.push("注意:"),t.push("1. 所有回复与思考/推理过程(reasoning / thinking)一律使用中文(禁止使用英文),保持简洁清晰;除非用户明确要求使用其他语言,此时思考与回复也相应使用该语言。"),t.push("2. 当你需要查询或操作数据时,调用对应工具包中的函数。"),t.push("3. 工具函数由宿主系统执行,你只需要传递正确的参数。"),t.push("4. 获取到工具结果后,回复用户并告知结果。"),t.push("5. 如果工具返回了结构化数据(如订单信息、系统状态等),在回复中清晰地展示给用户。"),t.push("6. 根据结果动态建议用户接下来可以做什么。"),t.push("7. 你返回的建议必须是中文,不能是英文或其他语言。"),t.push("8. 你返回的建议中涉及到工具要分条目,每个条目占一行,方便用户点击执行。"),t.push("9. 如果用户上传了文件,文件格式为(.txt、.json、.geojson等格式),你必须调用 open_mapview_file 工具在地图上展示,不要只回复文字。"),t.push(""),t.push("--- 文件上传规则 ---"),t.push("用户可能上传文件,文件以如下格式出现在消息中:"),t.push("已上传文件:"),t.push("1. **文件名**(类型,大小KB),文件ID:`fileId`"),t.push("你无法查看文件内容,只能看到文件名和类型。"),t.push("你必须根据文件名、扩展名和用户的文字指令,调用对应的工具来处理文件。"),t.push("如果某个工具需要处理该文件,在工具参数中传入 fileId。"),t.push('不要回复假性成功消息(如"已在地图上显示"),如果不调用工具,文件不会被实际处理。'),t.push("不要编造文件内容,不要假装你看到了文件数据。"),t.join(`
|
|
5
5
|
`)}const mi=`--- 重复指令处理规则 ---
|
|
6
6
|
如果用户再次发送相同或类似的指令(即使之前已经执行过),必须重新调用对应的工具再次执行。
|
|
7
7
|
不得以"已经执行过""之前做过"等理由拒绝,也不能用历史中的工具结果代替重新执行。`;function gi(e){const t=String(e).replace(/\s+/g,"");if(!t||!/^[\d+\-*/%().]+$/.test(t))throw new Error("表达式含非法字符");return Ci(t)}function Ci(e){let t=0;function n(){return e[t]??""}function i(u){return e[t]===u?(t++,!0):!1}function o(){const u=t;for(;/[\d.]/.test(n());)t++;const d=e.slice(u,t);if(!d)throw new Error("预期数字");const f=Number(d);if(Number.isNaN(f))throw new Error("无效数字");return f}function s(){if(i("-"))return-s();if(i("+"))return s();if(i("(")){const u=A();if(!i(")"))throw new Error("括号不匹配");return u}return o()}function l(){let u=s();for(;;)if(i("*"))u*=s();else if(i("/"))u/=s();else if(i("%"))u=(u%s()+s())%s();else break;return u}function A(){let u=l();for(;;)if(i("+"))u+=l();else if(i("-"))u-=l();else break;return u}const a=A();if(t!==e.length)throw new Error("无法解析的表达式");return a}const wt={id:"__builtin",name:"内置工具",description:"开箱即用的通用工具(时间、计算、UUID、客户端信息)",tools:[{name:"get_current_time",description:"获取用户当前的时间、日期、时区与星期",parameters:{type:"object",properties:{}},displayHints:{resultFormat:"card"}},{name:"calculate_expression",description:"安全计算数学表达式(支持 + - * / % 和括号)",parameters:{type:"object",properties:{expression:{type:"string",description:"数学表达式,如 (1+2)*3"}},required:["expression"]},displayHints:{resultFormat:"text"}},{name:"generate_uuid",description:"生成一个 UUID v4 随机标识符",parameters:{type:"object",properties:{}},displayHints:{resultFormat:"text"}},{name:"get_client_info",description:"获取用户浏览器的基本信息(UA、平台、语言、屏幕尺寸)",parameters:{type:"object",properties:{}},displayHints:{resultFormat:"card"}}]};function _i(){return{get_current_time:()=>{const e=new Date;return{time:e.toLocaleTimeString(),date:e.toLocaleDateString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,weekday:e.toLocaleDateString("zh-CN",{weekday:"long"})}},calculate_expression:e=>{if(!(e!=null&&e.expression))throw new Error("缺少 expression 参数");const t=gi(String(e.expression));return{expression:e.expression,result:t}},generate_uuid:()=>{let e=[];const t="0123456789abcdef";for(let n=0;n<36;n++)e[n]=t.charAt(Math.floor(Math.random()*16));return e[14]="4",e[19]=t.charAt(parseInt(e[19],16)&3|8),e[8]=e[13]=e[18]=e[23]="-",{uuid:e.join("")}},get_client_info:()=>{var e;return{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,languages:(e=navigator.languages)==null?void 0:e.join(", "),screen:`${window.screen.width}×${window.screen.height}`}}}}const ki=_i();function qo(e,t){const n=ki[e];if(!n)throw new Error(`未知内置工具:${e}`);return n(t)}function yi(e,t,n){var s;let i=null;if(e.type==="auto"&&(e={...e,type:Qn(e.data)}),e.type==="component"&&e.componentName){let l;e.packageId&&(l=t.find(A=>A.id===e.packageId)),!l&&n&&(l=t.find(A=>A.id===n)),(s=l==null?void 0:l.components)!=null&&s[e.componentName]&&(i=l.components[e.componentName])}const o=Ei(e);return{component:i,block:e,fallbackText:o}}function Qn(e){const t=Qt(e);return t&&t.length===1?"none":"table"}function Ei(e){switch(e.type){case"table":return bi(e);case"card":return Di(e);case"list":return Ii(e);case"none":return"";default:return JSON.stringify(e.data,null,2)}}function Qt(e){return e==null?null:Array.isArray(e)?e:typeof e!="object"?null:Array.isArray(e.data)?e.data:Array.isArray(e.list)?e.list:Array.isArray(e.items)?e.items:[e]}function bi(e){const t=Qt(e.data);if(!(t!=null&&t.length))return"(无数据)";const n=e.title?`**${e.title}**
|
|
@@ -19,11 +19,11 @@ ${l}`}function Di(e){const t=Qt(e.data);if(!(t!=null&&t.length))return"(无数
|
|
|
19
19
|
`);return`${n}${i}`}function Ii(e){const t=Qt(e.data);if(!(t!=null&&t.length))return"(无数据)";const n=e.title?`**${e.title}**
|
|
20
20
|
|
|
21
21
|
`:"",i=t.map(o=>`- ${typeof o=="string"?o:Object.values(o).join(" - ")}`).join(`
|
|
22
|
-
`);return`${n}${i}`}class Kn{constructor(){L(this,"exactHandlers",new Map);L(this,"regexHandlers",[]);L(this,"isChatOpen",()=>!0)}setChatOpenGetter(t){this.isChatOpen=t}on(t,n){return typeof t=="string"?(this.exactHandlers.has(t)||this.exactHandlers.set(t,new Set),this.exactHandlers.get(t).add(n),()=>this.off(t,n)):(this.regexHandlers.push({pattern:t,handler:n}),()=>this.off(t,n))}off(t,n){var i;if(typeof t=="string"){(i=this.exactHandlers.get(t))==null||i.delete(n);return}this.regexHandlers=this.regexHandlers.filter(o=>o.pattern!==t||o.handler!==n)}dispatch(t,n=!1){var i;if(!(n&&!this.isChatOpen())){(i=this.exactHandlers.get(t.type))==null||i.forEach(o=>o(t));for(const{pattern:o,handler:s}of this.regexHandlers)o.test(t.type)&&s(t)}}clear(){this.exactHandlers.clear(),this.regexHandlers=[]}}function Bi(){return new Kn}let fn=null;function $t(){return fn||(fn=new Kn),fn}const er="agent:page-action";let io=0,Ft=null,Gn=$t(),pn=null;function tr(e){pn&&pn(),pn=Gn.on(er,t=>{e.pendingAction.value=t.payload})}function nr(){const e=r.ref(null),t={pendingAction:e,dispatch(n){io++,Gn.dispatch({type:er,timestamp:Date.now(),payload:{...n,actionId:io}})},consume(){e.value=null}};return tr(t),t}function or(){return Ft||(Ft=nr()),Ft}function rr(e){Gn=e||$t(),Ft&&tr(Ft)}function wi(e){const t=e.bridge||or();function n(o){const s=o.actionName&&e.handlers[o.actionName]||e.handlers["*"];s&&s(o)}function i(){const o=t.pendingAction.value;!o||o.page!==e.page||(t.consume(),r.nextTick(()=>n(o)))}r.onMounted(()=>{i()}),r.watch(()=>{var o;return(o=t.pendingAction.value)==null?void 0:o.actionId},o=>{o&&i()})}class Fi{constructor(t,n){L(this,"bus");L(this,"rules");L(this,"cooldowns",new Map);L(this,"unsubscribers",[]);this.bus=t,this.rules=n}start(t){for(const n of this.rules){const i=this.bus.on(n.event,o=>{if(this.isOnCooldown(n)||(this.setCooldown(n),n.autoPopup&&t.onAutoPopup(),n.action==="silent"))return;const s=this.buildPrompt(n,o);s&&t.onRespond(s)});this.unsubscribers.push(i)}}stop(){for(const t of this.unsubscribers)t();this.unsubscribers=[],this.cooldowns.clear()}getBus(){return this.bus}isOnCooldown(t){if(!t.cooldown)return!1;const n=typeof t.event=="string"?t.event:t.event.source,i=this.cooldowns.get(n);return i?Date.now()<i:!1}setCooldown(t){if(!t.cooldown)return;const n=typeof t.event=="string"?t.event:t.event.source;this.cooldowns.set(n,Date.now()+t.cooldown)}buildPrompt(t,n){return t.prompt?t.prompt.replace(/\{\{payload\.([^}]+)\}\}/g,(i,o)=>{const s=n.payload[o];return s!==void 0?String(s):`{{payload.${o}}}`}):""}}const zt={apiKey:"",baseUrl:"https://api.deepseek.com",model:"deepseek-v4-flash",temperature:0,providerMode:"direct",proxyUrl:"http://localhost:3001/api/chat",thinking:!1,thinkingEffort:"low",mdTableClick:!0,mdListClick:!0};function xi(e){return{type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}}}function mn(){return`m_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function vi(){let e=[],t="0123456789abcdef";for(let i=0;i<36;i++)e[i]=t.substr(Math.floor(Math.random()*16),1);return e[14]="4",e[19]=t.substr(e[19]&3|8,1),e[8]=e[13]=e[18]=e[23]="-",e.join("")}const so="agent_chat_device_id";function Lt(){let e=localStorage.getItem(so);return e||(e=vi(),localStorage.setItem(so,e)),e}function gn(e){try{return
|
|
22
|
+
`);return`${n}${i}`}class Kn{constructor(){L(this,"exactHandlers",new Map);L(this,"regexHandlers",[]);L(this,"isChatOpen",()=>!0)}setChatOpenGetter(t){this.isChatOpen=t}on(t,n){return typeof t=="string"?(this.exactHandlers.has(t)||this.exactHandlers.set(t,new Set),this.exactHandlers.get(t).add(n),()=>this.off(t,n)):(this.regexHandlers.push({pattern:t,handler:n}),()=>this.off(t,n))}off(t,n){var i;if(typeof t=="string"){(i=this.exactHandlers.get(t))==null||i.delete(n);return}this.regexHandlers=this.regexHandlers.filter(o=>o.pattern!==t||o.handler!==n)}dispatch(t,n=!1){var i;if(!(n&&!this.isChatOpen())){(i=this.exactHandlers.get(t.type))==null||i.forEach(o=>o(t));for(const{pattern:o,handler:s}of this.regexHandlers)o.test(t.type)&&s(t)}}clear(){this.exactHandlers.clear(),this.regexHandlers=[]}}function Bi(){return new Kn}let fn=null;function $t(){return fn||(fn=new Kn),fn}const er="agent:page-action";let io=0,Ft=null,Gn=$t(),pn=null;function tr(e){pn&&pn(),pn=Gn.on(er,t=>{e.pendingAction.value=t.payload})}function nr(){const e=r.ref(null),t={pendingAction:e,dispatch(n){io++,Gn.dispatch({type:er,timestamp:Date.now(),payload:{...n,actionId:io}})},consume(){e.value=null}};return tr(t),t}function or(){return Ft||(Ft=nr()),Ft}function rr(e){Gn=e||$t(),Ft&&tr(Ft)}function wi(e){const t=e.bridge||or();function n(o){const s=o.actionName&&e.handlers[o.actionName]||e.handlers["*"];s&&s(o)}function i(){const o=t.pendingAction.value;!o||o.page!==e.page||(t.consume(),r.nextTick(()=>n(o)))}r.onMounted(()=>{i()}),r.watch(()=>{var o;return(o=t.pendingAction.value)==null?void 0:o.actionId},o=>{o&&i()})}class Fi{constructor(t,n){L(this,"bus");L(this,"rules");L(this,"cooldowns",new Map);L(this,"unsubscribers",[]);this.bus=t,this.rules=n}start(t){for(const n of this.rules){const i=this.bus.on(n.event,o=>{if(this.isOnCooldown(n)||(this.setCooldown(n),n.autoPopup&&t.onAutoPopup(),n.action==="silent"))return;const s=this.buildPrompt(n,o);s&&t.onRespond(s)});this.unsubscribers.push(i)}}stop(){for(const t of this.unsubscribers)t();this.unsubscribers=[],this.cooldowns.clear()}getBus(){return this.bus}isOnCooldown(t){if(!t.cooldown)return!1;const n=typeof t.event=="string"?t.event:t.event.source,i=this.cooldowns.get(n);return i?Date.now()<i:!1}setCooldown(t){if(!t.cooldown)return;const n=typeof t.event=="string"?t.event:t.event.source;this.cooldowns.set(n,Date.now()+t.cooldown)}buildPrompt(t,n){return t.prompt?t.prompt.replace(/\{\{payload\.([^}]+)\}\}/g,(i,o)=>{const s=n.payload[o];return s!==void 0?String(s):`{{payload.${o}}}`}):""}}const zt={apiKey:"",baseUrl:"https://api.deepseek.com",model:"deepseek-v4-flash",temperature:0,providerMode:"direct",proxyUrl:"http://localhost:3001/api/chat",thinking:!1,thinkingEffort:"low",mdTableClick:!0,mdListClick:!0};function xi(e){return{type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}}}function mn(){return`m_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function vi(){let e=[],t="0123456789abcdef";for(let i=0;i<36;i++)e[i]=t.substr(Math.floor(Math.random()*16),1);return e[14]="4",e[19]=t.substr(e[19]&3|8,1),e[8]=e[13]=e[18]=e[23]="-",e.join("")}const so="agent_chat_device_id";function Lt(){let e=localStorage.getItem(so);return e||(e=vi(),localStorage.setItem(so,e)),e}function gn(e){try{return e}catch{return""}}function Cn(e){const t=[];for(const n of e)if(n.role==="user")t.push({role:"user",content:n.content});else if(n.role==="assistant"&&(t.push({role:"assistant",content:n.content,tool_calls:n.tool_calls}),n.toolResults))for(const i of n.toolResults)t.push({role:"tool",tool_call_id:i.callId,content:i.result,name:i.name});return t}function ir(e){return e===!0?wt:Array.isArray(e)&&e.length?{...wt,tools:wt.tools.filter(t=>e.includes(t.name))}:null}function Si(e,t){const n=ir(t);return!n||!n.tools.length?e:[n,...e]}function sr(e){var xe,O,M;const{toolPackages:t,onToolCall:n=async()=>({success:!0}),provider:i,providerConfig:o,systemPrompt:s,storagePrefix:l="agent_chat_",sendFileToLLM:A=!1,suggestedCommands:a=[],builtInTools:u=!0,maxContextTokens:d=48e3,maxHistoryMessages:f=60}=e,_=Si(t,u),m={messages:`${l}messages`,settings:`${l}settings`},h=r.ref([]),k=r.ref({...zt}),b=r.ref(!1),g=r.ref(""),I=new Map,S=r.ref(!1);let C=null;const B=((xe=e.businessEvents)==null?void 0:xe.bus)||$t();B.setChatOpenGetter(()=>S.value),(O=e.businessEvents)!=null&&O.bus&&rr(e.businessEvents.bus),(M=e.businessEvents)!=null&&M.rules.length&&(C=new Fi(B,e.businessEvents.rules),C.start({onAutoPopup:()=>{S.value=!0},onRespond:y=>{g.value="",!(!k.value.apiKey&&k.value.providerMode!=="proxy")&&it(y)}})),r.onUnmounted(()=>{C==null||C.stop(),nt()});const K=new Po;for(const y of _){const T=y.id==="__builtin";for(const W of y.tools){const F=xi(W);K.register(F,async H=>{if(T)return await Pe(W,H);const V={packageId:y.id,toolName:W.name,args:H};return await Se(V,y,W)})}}const N=zo(),w=jo(),E=i||{streamChat(y){return(k.value.providerMode==="proxy"?w:N).streamChat(y)}};function x(){const y={...o},T=k.value.thinking?{type:"enabled",effort:k.value.thinkingEffort??"low"}:{type:"disabled"};return k.value.providerMode==="proxy"?{...y,baseUrl:k.value.proxyUrl,apiKey:"",model:k.value.model,temperature:k.value.temperature,thinking:T}:{...y,baseUrl:k.value.baseUrl,apiKey:k.value.apiKey,model:k.value.model,temperature:k.value.temperature,thinking:T}}const R=ir(u);let J=s?R!=null&&R.tools.length?`${s}
|
|
23
23
|
|
|
24
24
|
${Xo(R)}`:s:$o(_);J=`${J}
|
|
25
25
|
|
|
26
|
-
${mi}`;const z=new Zo({provider:E,providerConfig:x(),tools:K,systemPrompt:J,maxContextTokens:d,maxHistoryMessages:f});let $=[],ue=!1;const de=[];async function Se(y,T,W){const F={toolCallId:`${Date.now()}_${Math.random().toString(36).slice(2,6)}`,packageId:y.packageId,toolName:y.toolName,args:y.args};try{const H=await n(F);$.push({pkg:T,toolDef:W,data:H,args:y.args});const V=W.displayHints;return ue=(V==null?void 0:V.showModelContent)===!1&&(!!V.suggestComponent||["table","card","list"].includes(V.resultFormat)),{success:!0,result:typeof H=="string"?H:JSON.stringify(H)}}catch(H){return{success:!1,result:(H==null?void 0:H.message)||"工具执行失败"}}}async function Pe(y,T){try{const W=await qo(y.name,T);$.push({pkg:wt,toolDef:y,data:W,args:T});const F=y.displayHints;return ue=(F==null?void 0:F.showModelContent)===!1&&(!!F.suggestComponent||["table","card","list"].includes(F.resultFormat)),{success:!0,result:typeof W=="string"?W:JSON.stringify(W)}}catch(W){return{success:!1,result:(W==null?void 0:W.message)||"内置工具执行失败"}}}function _t(){var F,H;const y=h.value[h.value.length-1];if(!y||y.role!=="assistant"){$=[];return}const T=[];let W=!1;for(const{pkg:V,toolDef:fe,data:te,args:Ae}of $){const q=fe.displayHints;if(q){if(q.suggestComponent){let Ce=te;if(q.resultFormat==="map"){if((F=te==null?void 0:te.data)!=null&&F.fileId){const ae=I.get(te.data.fileId);ae&&(Ce=ae.name.endsWith(".geojson")||ae.name.endsWith(".json")?{data:{id:te.data.fileId,wkt:"",geojson:ae.data}}:{data:{id:te.data.fileId,wkt:ae.data,geojson:""}})}else if((H=te==null?void 0:te.data)!=null&&H.fileIds){const ae=te.data.fileIds.map(he=>I.get(he));if(ae.filter(he=>!he).length)continue;const Ne=[];ae.forEach(he=>{he.name.endsWith(".geojson")||he.name.endsWith(".json")?Ne.push({id:he.id,data:he.data,type:"geojson"}):he.name.endsWith(".txt")?Ne.push({id:he.id,data:he.data,type:"wkt"}):he.name.endsWith(".tif")?Ne.push({id:he.id,data:he,type:"tif"}):Ne.push({id:he.id,data:he.data,type:"unknown"})}),Ce={...te,data:Ne}}}T.push({type:"component",packageId:V.id,componentName:q.suggestComponent,data:Ce})}else if(q.resultFormat==="table"||q.resultFormat==="card"||q.resultFormat==="list"||q.resultFormat==="auto"){const Ce=Qt(te);if(Ce!=null&&Ce.length){const ae=q.resultFormat==="auto"?Qn(te):q.resultFormat;if(ae==="none")continue;T.push({type:ae,title:j(q.summaryTemplate,Ae),data:Ce,fields:q.previewFields,labelField:q.labelField,selectable:q.selectable})}}if(q.showModelContent===!1&&(q.suggestComponent||["table","card","list","auto"].includes(q.resultFormat))&&(W=!0),q.suggestedNext)if(q.suggestedNextEvent){const Ce=q.suggestedNextEvent,ae=B.on(Ce,()=>kt(Ce));de.push({event:Ce,text:q.suggestedNext,unsub:ae})}else y.suggestedNext=q.suggestedNext}}W&&!T.length&&(W=!1),y.renderBlocks=T,y.hideMarkdown=W,$=[]}function kt(y){const T=de.findIndex(F=>F.event===y);if(T===-1)return;const W=de[T];W.unsub(),de.splice(T,1);for(let F=h.value.length-1;F>=0;F--){const H=h.value[F];if(H.role==="assistant"){H.suggestedNext=W.text;break}}}function nt(){for(const y of de)y.unsub();de.length=0}function j(y,T){if(y)return y.replace(/\{(\w+)\}/g,(W,F)=>T[F]!==void 0?String(T[F]):W)}const le=new Map;z.on(y=>{var T,W;switch(y.type){case"message":{if(y.message.role==="tool")break;const F={id:mn(),role:y.message.role,content:y.message.content,reasoning:"",status:y.message.role==="assistant"?"streaming":"done",timestamp:Date.now(),tool_calls:y.message.tool_calls};y.message.role==="assistant"&&ue&&(F.hideMarkdown=!0,ue=!1),h.value.push(F);break}case"stream:delta":{const F=h.value[h.value.length-1];(F==null?void 0:F.role)==="assistant"&&F.status==="streaming"&&(y.delta.content&&(F.content+=y.delta.content),y.delta.reasoning&&(F.reasoning=(F.reasoning||"")+y.delta.reasoning));break}case"stream:end":{const F=h.value[h.value.length-1];(F==null?void 0:F.role)==="assistant"&&(F.content=y.content,y.reasoning&&(F.reasoning=y.reasoning),F.status==="streaming"&&(F.status="done"));break}case"tool:start":{const F=h.value[h.value.length-1];if(!F||F.role!=="assistant")break;F.tool_calls||(F.tool_calls=[]),F.toolResults||(F.toolResults=[]);const H=F.toolResults.length;F.toolResults.push({callId:y.call.id,name:y.call.function.name,arguments:y.call.function.arguments,result:"",success:!1,status:"running"}),le.set(y.call.id,{msgIndex:h.value.length-1,toolIndex:H}),F.tool_calls.find(V=>V.id===y.call.id)||F.tool_calls.push({id:y.call.id,type:"function",function:{name:y.call.function.name,arguments:y.call.function.arguments}});break}case"tool:end":{const F=le.get(y.call.id);if(!F)break;const H=(W=(T=h.value[F.msgIndex])==null?void 0:T.toolResults)==null?void 0:W[F.toolIndex];H&&(H.result=y.output.result,H.success=y.output.success,H.status=y.output.success?"success":"error"),le.delete(y.call.id);break}case"error":{g.value=y.error;const F=h.value[h.value.length-1];(F==null?void 0:F.role)==="assistant"&&(F.status="error",F.error=y.error);break}case"status":{if(b.value=y.loading,!y.loading){let F=null;for(const H of h.value)H.role==="assistant"&&H.status==="streaming"&&(H.status="done",!H.content&&!F&&(F=H));F&&(F.content="(已停止生成)"),_t()}break}}});function Be(){try{const y=localStorage.getItem(m.settings);k.value={...zt,...e.settings??{},...y?JSON.parse(y):{}}}catch{k.value={...zt,...e.settings??{}}}}function Fe(y){for(const T of y)if(T.files)for(const W of T.files)W.id&&I.set(W.id,W)}async function ze(){if(k.value.providerMode==="proxy"){try{const y=gn(k.value.proxyUrl);if(!y)return;const T=await fetch(`${y}/api/messages?device_id=${encodeURIComponent(Lt())}
|
|
26
|
+
${mi}`;const z=new Zo({provider:E,providerConfig:x(),tools:K,systemPrompt:J,maxContextTokens:d,maxHistoryMessages:f});let $=[],ue=!1;const de=[];async function Se(y,T,W){const F={toolCallId:`${Date.now()}_${Math.random().toString(36).slice(2,6)}`,packageId:y.packageId,toolName:y.toolName,args:y.args};try{const H=await n(F);$.push({pkg:T,toolDef:W,data:H,args:y.args});const V=W.displayHints;return ue=(V==null?void 0:V.showModelContent)===!1&&(!!V.suggestComponent||["table","card","list"].includes(V.resultFormat)),{success:!0,result:typeof H=="string"?H:JSON.stringify(H)}}catch(H){return{success:!1,result:(H==null?void 0:H.message)||"工具执行失败"}}}async function Pe(y,T){try{const W=await qo(y.name,T);$.push({pkg:wt,toolDef:y,data:W,args:T});const F=y.displayHints;return ue=(F==null?void 0:F.showModelContent)===!1&&(!!F.suggestComponent||["table","card","list"].includes(F.resultFormat)),{success:!0,result:typeof W=="string"?W:JSON.stringify(W)}}catch(W){return{success:!1,result:(W==null?void 0:W.message)||"内置工具执行失败"}}}function _t(){var F,H;const y=h.value[h.value.length-1];if(!y||y.role!=="assistant"){$=[];return}const T=[];let W=!1;for(const{pkg:V,toolDef:fe,data:te,args:Ae}of $){const q=fe.displayHints;if(q){if(q.suggestComponent){let Ce=te;if(q.resultFormat==="map"){if((F=te==null?void 0:te.data)!=null&&F.fileId){const ae=I.get(te.data.fileId);ae&&(Ce=ae.name.endsWith(".geojson")||ae.name.endsWith(".json")?{data:{id:te.data.fileId,wkt:"",geojson:ae.data}}:{data:{id:te.data.fileId,wkt:ae.data,geojson:""}})}else if((H=te==null?void 0:te.data)!=null&&H.fileIds){const ae=te.data.fileIds.map(he=>I.get(he));if(ae.filter(he=>!he).length)continue;const Ne=[];ae.forEach(he=>{he.name.endsWith(".geojson")||he.name.endsWith(".json")?Ne.push({id:he.id,data:he.data,type:"geojson"}):he.name.endsWith(".txt")?Ne.push({id:he.id,data:he.data,type:"wkt"}):he.name.endsWith(".tif")?Ne.push({id:he.id,data:he,type:"tif"}):Ne.push({id:he.id,data:he.data,type:"unknown"})}),Ce={...te,data:Ne}}}T.push({type:"component",packageId:V.id,componentName:q.suggestComponent,data:Ce})}else if(q.resultFormat==="table"||q.resultFormat==="card"||q.resultFormat==="list"||q.resultFormat==="auto"){const Ce=Qt(te);if(Ce!=null&&Ce.length){const ae=q.resultFormat==="auto"?Qn(te):q.resultFormat;if(ae==="none")continue;T.push({type:ae,title:j(q.summaryTemplate,Ae),data:Ce,fields:q.previewFields,labelField:q.labelField,selectable:q.selectable})}}if(q.showModelContent===!1&&(q.suggestComponent||["table","card","list","auto"].includes(q.resultFormat))&&(W=!0),q.suggestedNext)if(q.suggestedNextEvent){const Ce=q.suggestedNextEvent,ae=B.on(Ce,()=>kt(Ce));de.push({event:Ce,text:q.suggestedNext,unsub:ae})}else y.suggestedNext=q.suggestedNext}}W&&!T.length&&(W=!1),y.renderBlocks=T,y.hideMarkdown=W,$=[]}function kt(y){const T=de.findIndex(F=>F.event===y);if(T===-1)return;const W=de[T];W.unsub(),de.splice(T,1);for(let F=h.value.length-1;F>=0;F--){const H=h.value[F];if(H.role==="assistant"){H.suggestedNext=W.text;break}}}function nt(){for(const y of de)y.unsub();de.length=0}function j(y,T){if(y)return y.replace(/\{(\w+)\}/g,(W,F)=>T[F]!==void 0?String(T[F]):W)}const le=new Map;z.on(y=>{var T,W;switch(y.type){case"message":{if(y.message.role==="tool")break;const F={id:mn(),role:y.message.role,content:y.message.content,reasoning:"",status:y.message.role==="assistant"?"streaming":"done",timestamp:Date.now(),tool_calls:y.message.tool_calls};y.message.role==="assistant"&&ue&&(F.hideMarkdown=!0,ue=!1),h.value.push(F);break}case"stream:delta":{const F=h.value[h.value.length-1];(F==null?void 0:F.role)==="assistant"&&F.status==="streaming"&&(y.delta.content&&(F.content+=y.delta.content),y.delta.reasoning&&(F.reasoning=(F.reasoning||"")+y.delta.reasoning));break}case"stream:end":{const F=h.value[h.value.length-1];(F==null?void 0:F.role)==="assistant"&&(F.content=y.content,y.reasoning&&(F.reasoning=y.reasoning),F.status==="streaming"&&(F.status="done"));break}case"tool:start":{const F=h.value[h.value.length-1];if(!F||F.role!=="assistant")break;F.tool_calls||(F.tool_calls=[]),F.toolResults||(F.toolResults=[]);const H=F.toolResults.length;F.toolResults.push({callId:y.call.id,name:y.call.function.name,arguments:y.call.function.arguments,result:"",success:!1,status:"running"}),le.set(y.call.id,{msgIndex:h.value.length-1,toolIndex:H}),F.tool_calls.find(V=>V.id===y.call.id)||F.tool_calls.push({id:y.call.id,type:"function",function:{name:y.call.function.name,arguments:y.call.function.arguments}});break}case"tool:end":{const F=le.get(y.call.id);if(!F)break;const H=(W=(T=h.value[F.msgIndex])==null?void 0:T.toolResults)==null?void 0:W[F.toolIndex];H&&(H.result=y.output.result,H.success=y.output.success,H.status=y.output.success?"success":"error"),le.delete(y.call.id);break}case"error":{g.value=y.error;const F=h.value[h.value.length-1];(F==null?void 0:F.role)==="assistant"&&(F.status="error",F.error=y.error);break}case"status":{if(b.value=y.loading,!y.loading){let F=null;for(const H of h.value)H.role==="assistant"&&H.status==="streaming"&&(H.status="done",!H.content&&!F&&(F=H));F&&(F.content="(已停止生成)"),_t()}break}}});function Be(){try{const y=localStorage.getItem(m.settings);k.value={...zt,...e.settings??{},...y?JSON.parse(y):{}}}catch{k.value={...zt,...e.settings??{}}}}function Fe(y){for(const T of y)if(T.files)for(const W of T.files)W.id&&I.set(W.id,W)}async function ze(){if(k.value.providerMode==="proxy"){try{const y=gn(k.value.proxyUrl);if(!y)return;const T=await fetch(`${y}/api/messages?device_id=${encodeURIComponent(Lt())}`,{method:"GET",credentials:"include"});if(!T.ok)return;const W=await T.json(),F=W==null?void 0:W.messages;Array.isArray(F)&&(h.value=F,Fe(F),z.initialize(Cn(F)))}catch{}return}try{const y=localStorage.getItem(m.messages);if(y){const T=JSON.parse(y);Array.isArray(T)&&(h.value=T,Fe(T),z.initialize(Cn(T)))}}catch{}}function ot(y){k.value={...y},localStorage.setItem(m.settings,JSON.stringify(y)),y.providerMode==="proxy"?z.updateProviderConfig({baseUrl:y.proxyUrl,apiKey:"",model:y.model,temperature:y.temperature}):z.updateProviderConfig({baseUrl:y.baseUrl,apiKey:y.apiKey,model:y.model,temperature:y.temperature})}async function Ye(){if(k.value.providerMode==="proxy"){try{const y=gn(k.value.proxyUrl);if(!y)return;await fetch(`${y}/api/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_id:Lt(),messages:h.value})})}catch{}return}try{localStorage.setItem(m.messages,JSON.stringify(h.value))}catch{}}function rt(y){return y.startsWith("data:")}async function it(y,T){const W=y.trim();if(!W&&(!T||T.length===0))return;if(g.value="",k.value.providerMode==="direct"&&!k.value.apiKey){g.value="请先配置 API Key。";return}if(z.updateProviderConfig(x()),$=[],le.clear(),T&&T.length>0){for(const V of T)V.id=mn(),I.set(V.id,{...V});const H={id:mn(),role:"user",content:W,status:"done",timestamp:Date.now(),files:T};h.value.push(H),z.initialize(Cn(h.value))}let F=W;T&&T.length>0&&(A?F=`已上传文件:
|
|
27
27
|
${T.map((V,fe)=>{const te=`${fe+1}. **${V.name}**(${V.type},${(V.size/1024).toFixed(1)}KB),文件ID:\`${V.id}\``;return rt(V.data)?`${te}
|
|
28
28
|
${V.data}`:`${te}
|
|
29
29
|
\`\`\`
|
package/dist/index.js
CHANGED
|
@@ -232,7 +232,7 @@ function Ss() {
|
|
|
232
232
|
onReasoning: c
|
|
233
233
|
} = e, h = `${t.trim().replace(/\/+$/, "")}`, f = { model: n, messages: s, stream: !0 };
|
|
234
234
|
typeof i == "number" && (f.temperature = i), f.thinking = { type: (o == null ? void 0 : o.type) === "enabled" ? "enabled" : "disabled" }, (o == null ? void 0 : o.type) === "enabled" && o.effort && (f.reasoning_effort = o.effort), r != null && r.length && (f.tools = r, f.tool_choice = "auto");
|
|
235
|
-
const C = await fetch(h, {
|
|
235
|
+
const C = await fetch(h + "/api/chat", {
|
|
236
236
|
method: "POST",
|
|
237
237
|
headers: { "Content-Type": "application/json" },
|
|
238
238
|
body: JSON.stringify(f),
|
|
@@ -312,7 +312,7 @@ function Qs(e) {
|
|
|
312
312
|
t.push(di(n)), t.push("");
|
|
313
313
|
return t.push("注意:"), t.push(
|
|
314
314
|
"1. 所有回复与思考/推理过程(reasoning / thinking)一律使用中文(禁止使用英文),保持简洁清晰;除非用户明确要求使用其他语言,此时思考与回复也相应使用该语言。"
|
|
315
|
-
), t.push("2. 当你需要查询或操作数据时,调用对应工具包中的函数。"), t.push("3. 工具函数由宿主系统执行,你只需要传递正确的参数。"), t.push("4. 获取到工具结果后,回复用户并告知结果。"), t.push("5. 如果工具返回了结构化数据(如订单信息、系统状态等),在回复中清晰地展示给用户。"), t.push("6. 根据结果动态建议用户接下来可以做什么。"), t.push("7. 如果用户上传了文件,文件格式为(.txt、.json、.geojson等格式),你必须调用 open_mapview_file 工具在地图上展示,不要只回复文字。"), t.push(""), t.push("--- 文件上传规则 ---"), t.push("用户可能上传文件,文件以如下格式出现在消息中:"), t.push("已上传文件:"), t.push("1. **文件名**(类型,大小KB),文件ID:`fileId`"), t.push("你无法查看文件内容,只能看到文件名和类型。"), t.push("你必须根据文件名、扩展名和用户的文字指令,调用对应的工具来处理文件。"), t.push("如果某个工具需要处理该文件,在工具参数中传入 fileId。"), t.push('不要回复假性成功消息(如"已在地图上显示"),如果不调用工具,文件不会被实际处理。'), t.push("不要编造文件内容,不要假装你看到了文件数据。"), t.join(`
|
|
315
|
+
), t.push("2. 当你需要查询或操作数据时,调用对应工具包中的函数。"), t.push("3. 工具函数由宿主系统执行,你只需要传递正确的参数。"), t.push("4. 获取到工具结果后,回复用户并告知结果。"), t.push("5. 如果工具返回了结构化数据(如订单信息、系统状态等),在回复中清晰地展示给用户。"), t.push("6. 根据结果动态建议用户接下来可以做什么。"), t.push("7. 你返回的建议必须是中文,不能是英文或其他语言。"), t.push("8. 你返回的建议中涉及到工具要分条目,每个条目占一行,方便用户点击执行。"), t.push("9. 如果用户上传了文件,文件格式为(.txt、.json、.geojson等格式),你必须调用 open_mapview_file 工具在地图上展示,不要只回复文字。"), t.push(""), t.push("--- 文件上传规则 ---"), t.push("用户可能上传文件,文件以如下格式出现在消息中:"), t.push("已上传文件:"), t.push("1. **文件名**(类型,大小KB),文件ID:`fileId`"), t.push("你无法查看文件内容,只能看到文件名和类型。"), t.push("你必须根据文件名、扩展名和用户的文字指令,调用对应的工具来处理文件。"), t.push("如果某个工具需要处理该文件,在工具参数中传入 fileId。"), t.push('不要回复假性成功消息(如"已在地图上显示"),如果不调用工具,文件不会被实际处理。'), t.push("不要编造文件内容,不要假装你看到了文件数据。"), t.join(`
|
|
316
316
|
`);
|
|
317
317
|
}
|
|
318
318
|
const Ms = `--- 重复指令处理规则 ---
|
|
@@ -687,7 +687,7 @@ function An() {
|
|
|
687
687
|
}
|
|
688
688
|
function Qn(e) {
|
|
689
689
|
try {
|
|
690
|
-
return
|
|
690
|
+
return e;
|
|
691
691
|
} catch {
|
|
692
692
|
return "";
|
|
693
693
|
}
|
|
@@ -820,7 +820,12 @@ ${Ms}`;
|
|
|
820
820
|
};
|
|
821
821
|
try {
|
|
822
822
|
const L = await n(B);
|
|
823
|
-
ie.push({
|
|
823
|
+
ie.push({
|
|
824
|
+
pkg: N,
|
|
825
|
+
toolDef: U,
|
|
826
|
+
data: L,
|
|
827
|
+
args: y.args
|
|
828
|
+
});
|
|
824
829
|
const z = U.displayHints;
|
|
825
830
|
return Ie = (z == null ? void 0 : z.showModelContent) === !1 && (!!z.suggestComponent || ["table", "card", "list"].includes(z.resultFormat)), {
|
|
826
831
|
success: !0,
|
|
@@ -865,7 +870,11 @@ ${Ms}`;
|
|
|
865
870
|
if (se.resultFormat === "map") {
|
|
866
871
|
if ((B = Ae == null ? void 0 : Ae.data) != null && B.fileId) {
|
|
867
872
|
const _e = k.get(Ae.data.fileId);
|
|
868
|
-
_e && (ve = _e.name.endsWith(".geojson") || _e.name.endsWith(".json") ? {
|
|
873
|
+
_e && (ve = _e.name.endsWith(".geojson") || _e.name.endsWith(".json") ? {
|
|
874
|
+
data: { id: Ae.data.fileId, wkt: "", geojson: _e.data }
|
|
875
|
+
} : {
|
|
876
|
+
data: { id: Ae.data.fileId, wkt: _e.data, geojson: "" }
|
|
877
|
+
});
|
|
869
878
|
} else if ((L = Ae == null ? void 0 : Ae.data) != null && L.fileIds) {
|
|
870
879
|
const _e = Ae.data.fileIds.map(
|
|
871
880
|
(De) => k.get(De)
|
|
@@ -1038,7 +1047,12 @@ ${Ms}`;
|
|
|
1038
1047
|
const y = Qn(_.value.proxyUrl);
|
|
1039
1048
|
if (!y) return;
|
|
1040
1049
|
const N = await fetch(
|
|
1041
|
-
`${y}/api/messages?device_id=${encodeURIComponent(An())}
|
|
1050
|
+
`${y}/api/messages?device_id=${encodeURIComponent(An())}`,
|
|
1051
|
+
{
|
|
1052
|
+
method: "GET",
|
|
1053
|
+
credentials: "include"
|
|
1054
|
+
// 关键:允许携带跨域 Cookie
|
|
1055
|
+
}
|
|
1042
1056
|
);
|
|
1043
1057
|
if (!N.ok) return;
|
|
1044
1058
|
const U = await N.json(), B = U == null ? void 0 : U.messages;
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "agent-tool-chat",
|
|
3
3
|
"description": "An agent-driven chat plugin with ToolPackage architecture and host-controlled execution",
|
|
4
4
|
"author": "kangjinrui <1092014304@qq.com>",
|
|
5
|
-
"version": "1.1.
|
|
5
|
+
"version": "1.1.4",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"private": false,
|
|
8
8
|
"type": "module",
|