@zhengxs/wechaty-plugin-assistant
Version:
249 lines (210 loc) • 51.9 kB
JavaScript
"use strict";var Lt=Object.defineProperty;var qe=n=>{throw TypeError(n)};var Bt=(n,t,e)=>t in n?Lt(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var u=(n,t,e)=>Bt(n,typeof t!="symbol"?t+"":t,e),Me=(n,t,e)=>t.has(n)||qe("Cannot "+e);var c=(n,t,e)=>(Me(n,t,"read from private field"),e?e.call(n):t.get(n)),M=(n,t,e)=>t.has(n)?qe("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),g=(n,t,e,s)=>(Me(n,t,"write to private field"),s?s.call(n,e):t.set(n,e),e),f=(n,t,e)=>(Me(n,t,"access private method"),e);var W=(n,t,e,s)=>({set _(a){g(n,t,a,e)},get _(){return c(n,t,s)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const be=require("node:assert"),m=require("common-tags"),Ot=require("minimist"),Ut=require("languagedetect"),B=require("wechaty"),Ee=require("keyv"),qt=require("eventemitter3"),Nt=require("openai"),ne=require("node:crypto"),je=require("js-tiktoken"),Rt=require("@zhengxs/erniebot"),ye=require("@zhengxs/ai"),zt=require("file-box");class Ie{constructor(t,e={}){u(this,"name");u(this,"alias");u(this,"type");u(this,"description");u(this,"assistant");this.name=t,this.alias=e.alias,this.type=e.type,this.description=e.description||""}toString(){const t=[];return this.alias?t.push(`-${this.alias}, --${this.name}`):t.push(`--${this.name}`),this.type&&t.push(`[${this.type}]`),this.description&&t.push(this.description),t.join().trim()}}var D,G,J,V,X,oe;const K=class K{constructor(t,e={}){u(this,"name");u(this,"required");u(this,"disabled");u(this,"default");u(this,"parent");M(this,D);M(this,G);M(this,J,new Map);M(this,V,new Map);M(this,X);M(this,oe);this.name=t,g(this,D,e.summary||""),g(this,G,e.description),this.required=e.required===!0,this.disabled=e.disabled===!0,this.default=e.default===!0,g(this,oe,new Ie("help",{type:"boolean",alias:"H",description:"帮助"}))}get commands(){return c(this,V)}summary(t){return t?(g(this,D,t),this):c(this,D)}usage(){const t=[];if(c(this,V).forEach(a=>{if(a.disabled)return;const r=a.summary();r?t.push(` - ${a.name} ${r}`):t.push(` - ${a.name}`)}),!this.parent)return t.length?m.codeBlock`
${this.summary()||"使用说明"}
Commands:
${t.join(`
`)}`:"暂无可用的有效指令!";const e=[];c(this,J).forEach(a=>{e.push(a.toString())});const s=[m.codeBlock`
使用说明
Usage: /${this.name} [options]${this.required?" <input>":""}`];return c(this,D)&&s.push(c(this,D)),e.length&&s.push(m.codeBlock`
Options:
${e.join(`
`)}`),t.length&&s.push(m.codeBlock`
Commands:
${t.join(`
`)}`),c(this,G)&&s.push(c(this,G)),s.join(`
`)}addCommand(t){return t.parent=this,c(this,V).set(t.name,t),this}add(t,e){const s=t instanceof K?t:new K(t,e);return this.addCommand(s),s}register(t,...e){let s;return typeof e[0]=="function"?(s=new K(t),s.action(e[0])):(s=new K(t,e[0]),s.action(e[1])),this.addCommand(s),s}option(t,e){return c(this,J).set(t,new Ie(t,e)),this}parseArgs(t){const e={boolean:[],string:[],alias:{}};return[...c(this,J).values(),c(this,oe)].forEach(r=>{const i=r.alias;i&&(e.alias[i]=r.name);const o=e[r.type];Array.isArray(o)&&o.push(r.name)}),{...Ot(t,e),raw:t}}async action(t){return g(this,X,t),this}parse(t,e){const s=c(this,V);if(s.size>0){const[r,...i]=e;let o=r.startsWith("/")?s.get(r.slice(1)):s.get(r);if(o||s.forEach(l=>{l.default&&(o=l)}),o)return o.parse(t,i)}const a=this.parseArgs(e);if(!a.help&&c(this,X)){c(this,X).call(this,t,a);return}return t.reply(this.usage())}};D=new WeakMap,G=new WeakMap,J=new WeakMap,V=new WeakMap,X=new WeakMap,oe=new WeakMap;let z=K;class Qe{constructor(){u(this,"lang",new Ut);u(this,"languagesToCodes",new Map([["bulgarian","bg"],["czech","cs"],["danish","da"],["dutch","nl"],["english","en"],["hawaiian","en"],["estonian","et"],["finnish","fi"],["french","fr"],["german","de"],["hungarian","hu"],["italian","it"],["latvian","lv"],["lithuanian","lt"],["polish","pl"],["portuguese","pt"],["romanian","ro"],["russian","ru"],["slovak","sk"],["slovene","sl"],["spanish","es"],["swedish","sv"]]));u(this,"supportedLanguages",new Map([["auto","自动检测"],["zh","中文 🇨🇳"],["en","英语 🇬🇧"],["de","德语 🇩🇪"],["es","西班牙语 🇪🇸"],["fr","法语 🇫🇷"],["it","意大利语 🇮🇹"],["ja","日语 🇯🇵"],["ko","韩语 🇰🇷"],["nl","荷兰语 🇳🇱"],["pl","波兰语 🇵🇱"],["pt","葡萄牙语 🇵🇹"],["ru","俄语 🇷🇺"],["bg","保加利亚语 🇧🇬"],["cs","捷克语 🇨🇿"],["da","丹麦语 🇩🇰"],["el","希腊语 🇬🇷"],["et","爱沙尼亚语 🇪🇪"],["fi","芬兰语 🇫🇮"],["hu","匈牙利语 🇭🇺"],["lt","立陶宛 🇱🇹"],["lv","拉脱维亚语 🇱🇻"],["ro","罗马尼亚语 🇷🇴"],["sk","斯洛伐克语 🇸🇰"],["sl","斯洛文尼亚语 🇸🇮"],["sv","瑞典 🇸🇪"]]))}translate(t,e={}){const s=e.from??this.getCanonicalLocale(t),a=e.to??(s==="zh"?"en":"zh");return be.ok(this.isSupported(s),`Unsupported language: ${s}`),be.ok(this.isSupported(a),`Unsupported language: ${a}`),this.request(t,s,a)}getCanonicalLocale(t){const e=this.detectedLanguages(t);for(const[s]of e){const a=this.languagesToCodes.get(s);if(a)return a}return"zh"}isSupported(t){return this.supportedLanguages.has(t.toLowerCase())}detectedLanguages(t,e=5){return this.lang.detect(t,e)}}class Ve extends Qe{async request(t,e,s){const a=this.random(),r={id:a,jsonrpc:"2.0",method:"LMT_handle_texts",params:{texts:[{text:t,requestAlternatives:3}],splitting:"newlines",lang:{source_lang_user_selected:e,target_lang:s},timestamp:this.timestamp(t)}};let i=JSON.stringify(r);(a+5)%29===0||(a+3)%13===0?i=i.replace('"method":"','"method" : "'):i=i.replace('"method":"','"method": "');const o=await fetch("https://www2.deepl.com/jsonrpc",{method:"POST",headers:{"Content-Type":"application/json"},body:i}).then(async y=>{if(y.ok)return y.json();const p=await y.text().catch(()=>y.statusText);throw new Error(`Fetch error: ${p} (${y.status})`)}),{lang:l,texts:h}=o.result,[d]=h;return{lang:l,result:d.text,alternatives:d.alternatives.map(y=>y.text)}}random(){return(Math.floor(Math.random()*99999)+1e5)*1e3}timestamp(t){let e=t.split("i").length-1;const s=Date.now();return e===0?s:(e=e+1,s-s%e+e)}}const Ye=new Ve,me=new z("deepl",{required:!0,summary:"DeepL 翻译",description:m.codeBlock`
支持语言列表:
${Array.from(Ye.supportedLanguages).map(([n,t])=>` ${n} - ${t}`)}
输入语言代码,可以手动指定翻译语言,例如:
/deepl -f zh 你好
/deepl -f zh -t en 你好
/deepl -t zh hello
如果不指定语言代码,会自动检测文本语言,但是这会导致一些特殊语言的翻译出现问题`});me.option("from",{alias:"f",description:"源语言代码"});me.option("to",{alias:"t",description:"目标语言代码"});me.action(async(n,t)=>{const e=t._.join(" ").trim();if(e.length===0)return n.reply(m.codeBlock`
⊶ 系统提示
﹊
请输入要翻译的文本`,!0);try{const s=await Ye.translate(e,t),{result:a,alternatives:r=[]}=s;return r.length>0?n.reply(m.codeBlock`
⊶ 翻译结果
﹊
${a}
备选结果:
${r.map(i=>` - ${i}`)}`):n.reply(m.codeBlock`
⊶ 翻译结果
﹊
${a}`)}catch(s){return s instanceof be.AssertionError?n.reply(m.codeBlock`
⊶ 系统提示
﹊
${s.message}`,!0):(console.error("deepl",s),n.reply(m.codeBlock`
⊶ 系统提示
﹊
翻译服务无法使用,稍后再试试吧`,!0))}});const We=new z("dict",{required:!0,summary:"汉字词典"});We.action(async(n,t)=>{const e=t._[0];if(!e)return n.reply(m.codeBlock`
⊶ 系统提示
﹊
请输入要查询的汉字`,!0);const s=new URL("https://api.pearktrue.cn/api/word/parse.php");s.searchParams.set("word",e);const a=await fetch(s).then(d=>{if(d.ok)return d.json();B.log.error("词典服务异常 %d %s",d.status,r)},d=>{B.log.error("error",d)});if(!a||a.code!==200)return n.reply(m.codeBlock`
⊶ 系统提示
﹊
${(a==null?void 0:a.msg)||"词典服务无法使用,稍后再试试吧"}`,!0);const{word:r,pinyin:i,mean:o,parse:l}=a.data,h=[r,i?` - 拼音:${i}`:"",l.wubi?` - 五笔:${l.wubi}`:"",l.radical?` - 部首:${l.radical}`:"",l.five_elements?` - 五行:${l.five_elements}`:"",l.strokes?` - 笔画:${l.strokes}`:""].filter(Boolean);n.reply(m.codeBlock`
汉字词典
====================
${h.join(`
`)}
解 义
﹊
${o||"暂无解释"}`,!0)});const Dt=new Map([["hp","huPu"],["zh","zhihuHot"],["36","36Ke"],["bd","baiduRD"],["bl","bili"],["jt","history"],["tb","baiduRY"],["wb","wbHot"],["dy","douyinHot"],["db","douban"],["sp","ssPai"],["it","itInfo"],["itn","itNews"]]),Ke=new z("hot",{required:!0,summary:"热搜",description:m.codeBlock`
数据来源
- hp: 虎扑步行街
- zh: 知乎热榜
- 36: 36氪
- bd: 百度热点
- bl: 哔哩哔哩
- jt: 历史上的今天
- tb: 贴吧热议
- wb: 微博热搜
- dy: 抖音热点
- db: 豆瓣小组
- sp: 少数派
- it: IT之家
- itn: IT之家新闻
输出代号即可,如:/hot hp
`});Ke.action(async(n,t)=>{const e=Dt.get(t._[0])||"wbHot",s=await fetch(`https://api.vvhan.com/api/hotlist?type=${e}`).then(i=>{if(i.ok)return i.json();B.log.error("热搜服务异常 %d %s",i.status,e)},i=>{B.log.error("error",i)});if(!s||!s.success)return n.reply(m.codeBlock`
⊶ 系统提示
﹊
${(s==null?void 0:s.message)||"热搜服务器暂时无法使用,稍后再试试吧"}`,!0);const[a,...r]=s.data;n.reply(m.codeBlock`
${s.title}
====================
🔥 ${a.title}
${a.desc?`
${a.desc}
`:""}
${r.slice(0,9).map((i,o)=>` ${o+1}. ${i.title}`).join(`
`)}
更新时间:${s.update_time}
`,!0)});const Ge=new z("kfc",{required:!0,summary:"疯狂星期四"});Ge.action(async n=>{const t=await fetch("https://api.001500.cn/API/kfc.php?type=json").then(e=>{if(e.ok)return e.json();B.log.error("疯狂星期四 %d %s",e.status)},e=>{B.log.error("error",e)});return t&&t.data?n.reply(t.data.msg):(console.error("疯狂星期四 error",t),n.reply(m.codeBlock`
⊶ 系统提示
﹊
星期四文学暂时无法使用,稍后再试试吧`,!0))});const Je=new z("my",{summary:"摸鱼日历"});Je.action(n=>{fetch("https://api.vvhan.com/api/moyu").then(t=>{t.ok?(console.log(t.url),n.sendFileFromUrl(t.url)):n.reply(m.codeBlock`
⊶ 系统提示
﹊
服务器出错了,稍后再试试吧`,!0)})});const N=n=>{const t=[];return{name:n,items:t,add:s=>{t.push(s)},process:async(s,...a)=>{const r=[];for(const i of t){if(s.signal.aborted)break;try{const o=await i.hook(s,...a);o!==void 0&&r.push(o)}catch{console.error(`error in hook ${n} from ${i.pluginName}`)}}return r}}},Xe=()=>({onMessage:N("onMessage"),onRoomMessage:N("onRoomMessage"),onRoomMentionSelfMessage:N("onRoomMentionSelfMessage"),onIndividualMessage:N("onIndividualMessage"),onContextCreated:N("onContextCreated"),onContextDestroyed:N("onContextDestroyed"),onPrepareTextMessage:N("onPrepareTextMessage"),onPrepareFileMessage:N("onPrepareFileMessage")});function Ze(){const n=new Map;return{started:!1,startupTime:new Date,running:!1,stats:{success:0,failure:0,total:0,skipped:0,message:0,command:0},get size(){return n.size},defineLock(e){if(n.has(e.id))return n.get(e.id);const s=new AbortController,a={...e,controller:s,createdAt:Date.now(),abort(r){s.abort(r),n.delete(e.id)},dispose(){n.delete(e.id)}};return n.set(e.id,a),a},releaseLock(e){n.delete(e)},isLocked(e){return n.has(e)}}}const Ft={newConversation:["新对话","新聊天","重新开始","重新对话","重新聊天","重新对话","重新开始对话","重新开始聊天","重新开始对话"],stopConversation:["停","停止","停止回复"],help:["帮助","获取帮助"],sourceCode:["获取源码","查看源码"]};function Ht(n,t,e){let s=0,a=n.length;for(;a>0;){const r=Math.trunc(a/2);let i=s+r;e(n[i],t)<=0?(s=++i,a-=r+1):a=r}return s}var U;class jt{constructor(){M(this,U,[])}enqueue(t,e){e={priority:0,...e};const s={priority:e.priority,run:t};if(this.size&&c(this,U)[this.size-1].priority>=e.priority){c(this,U).push(s);return}const a=Ht(c(this,U),s,(r,i)=>i.priority-r.priority);c(this,U).splice(a,0,s)}dequeue(){const t=c(this,U).shift();return t==null?void 0:t.run}filter(t){return c(this,U).filter(e=>e.priority===t.priority).map(e=>e.run)}get size(){return c(this,U).length}}U=new WeakMap;let et=class extends Error{constructor(e){super(e);u(this,"name","TimeoutError")}},Qt=class extends Error{constructor(e){super(e);u(this,"name","TimeoutError")}};const Ne=n=>globalThis.DOMException===void 0?new Qt(n):new DOMException(n),Re=n=>{const t=n.reason===void 0?Ne("This operation was aborted."):n.reason;return t instanceof Error?t:Ne(t)};function Vt(n,t){const{milliseconds:e,fallback:s,message:a,customTimers:r={setTimeout,clearTimeout}}=t;let i;const l=new Promise((h,d)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){const{signal:p}=t;p.aborted&&d(Re(p)),p.addEventListener("abort",()=>{d(Re(p))})}if(e===Number.POSITIVE_INFINITY){n.then(h,d);return}const y=new et;i=r.setTimeout.call(void 0,()=>{if(s){try{h(s())}catch(p){d(p)}return}typeof n.cancel=="function"&&n.cancel(),a===!1?h():a instanceof Error?d(a):(y.message=a??`Promise timed out after ${e} milliseconds`,d(y))},e),(async()=>{try{h(await n)}catch(p){d(p)}})()}).finally(()=>{l.clear()});return l.clear=()=>{r.clearTimeout.call(void 0,i),i=void 0},l}let Te=class extends Error{};var Z,ee,F,ce,te,le,P,se,x,ue,E,ae,R,he,k,tt,st,at,nt,rt,pe,ve,Ce,ge,it,fe;class Q extends qt.EventEmitter{constructor(e){var s,a;super();M(this,k);M(this,Z);M(this,ee);M(this,F,0);M(this,ce);M(this,te);M(this,le,0);M(this,P);M(this,se);M(this,x);M(this,ue);M(this,E,0);M(this,ae);M(this,R);M(this,he);u(this,"timeout");if(e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:jt,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${((s=e.intervalCap)==null?void 0:s.toString())??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${((a=e.interval)==null?void 0:a.toString())??""}\` (${typeof e.interval})`);g(this,Z,e.carryoverConcurrencyCount),g(this,ee,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0),g(this,ce,e.intervalCap),g(this,te,e.interval),g(this,x,new e.queueClass),g(this,ue,e.queueClass),this.concurrency=e.concurrency,this.timeout=e.timeout,g(this,he,e.throwOnTimeout===!0),g(this,R,e.autoStart===!1)}get concurrency(){return c(this,ae)}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);g(this,ae,e),f(this,k,ge).call(this)}async add(e,s={}){return s={timeout:this.timeout,throwOnTimeout:c(this,he),...s},new Promise((a,r)=>{c(this,x).enqueue(async()=>{var i;W(this,E)._++,W(this,F)._++;try{if((i=s.signal)!=null&&i.aborted)throw new Te("The task was aborted.");let o=e({signal:s.signal});s.timeout&&(o=Vt(Promise.resolve(o),{message:void 0,milliseconds:s.timeout,signal:s.signal})),s.signal&&(o=Promise.race([o,f(this,k,it).call(this,s.signal)]));const l=await o;a(l),this.emit("completed",l)}catch(o){if(o instanceof et&&!s.throwOnTimeout){a();return}r(o),this.emit("error",o)}finally{f(this,k,at).call(this)}},s),this.emit("add"),f(this,k,pe).call(this)})}async addAll(e,s){return Promise.all(e.map(async a=>this.add(a,s)))}start(){return c(this,R)?(g(this,R,!1),f(this,k,ge).call(this),this):this}pause(){g(this,R,!0)}clear(){g(this,x,new(c(this,ue)))}async onEmpty(){c(this,x).size!==0&&await f(this,k,fe).call(this,"empty")}async onSizeLessThan(e){c(this,x).size<e||await f(this,k,fe).call(this,"next",()=>c(this,x).size<e)}async onIdle(){c(this,E)===0&&c(this,x).size===0||await f(this,k,fe).call(this,"idle")}get size(){return c(this,x).size}sizeBy(e){return c(this,x).filter(e).length}get pending(){return c(this,E)}get isPaused(){return c(this,R)}}Z=new WeakMap,ee=new WeakMap,F=new WeakMap,ce=new WeakMap,te=new WeakMap,le=new WeakMap,P=new WeakMap,se=new WeakMap,x=new WeakMap,ue=new WeakMap,E=new WeakMap,ae=new WeakMap,R=new WeakMap,he=new WeakMap,k=new WeakSet,tt=function(){return c(this,ee)||c(this,F)<c(this,ce)},st=function(){return c(this,E)<c(this,ae)},at=function(){W(this,E)._--,f(this,k,pe).call(this),this.emit("next")},nt=function(){f(this,k,Ce).call(this),f(this,k,ve).call(this),g(this,se,void 0)},rt=function(){const e=Date.now();if(c(this,P)===void 0){const s=c(this,le)-e;if(s<0)g(this,F,c(this,Z)?c(this,E):0);else return c(this,se)===void 0&&g(this,se,setTimeout(()=>{f(this,k,nt).call(this)},s)),!0}return!1},pe=function(){if(c(this,x).size===0)return c(this,P)&&clearInterval(c(this,P)),g(this,P,void 0),this.emit("empty"),c(this,E)===0&&this.emit("idle"),!1;if(!c(this,R)){const e=!c(this,k,rt);if(c(this,k,tt)&&c(this,k,st)){const s=c(this,x).dequeue();return s?(this.emit("active"),s(),e&&f(this,k,ve).call(this),!0):!1}}return!1},ve=function(){c(this,ee)||c(this,P)!==void 0||(g(this,P,setInterval(()=>{f(this,k,Ce).call(this)},c(this,te))),g(this,le,Date.now()+c(this,te)))},Ce=function(){c(this,F)===0&&c(this,E)===0&&c(this,P)&&(clearInterval(c(this,P)),g(this,P,void 0)),g(this,F,c(this,Z)?c(this,E):0),f(this,k,ge).call(this)},ge=function(){for(;f(this,k,pe).call(this););},it=async function(e){return new Promise((s,a)=>{e.addEventListener("abort",()=>{a(new Te("The task was aborted."))},{once:!0})})},fe=async function(e,s){return new Promise(a=>{const r=()=>{s&&!s()||(this.off(e,r),a())};this.on(e,r)})};var S,b,I,H,de,j,w,$e,L,ot,xe,_e,Ae,ct,Pe;class we extends Map{constructor(e){super();M(this,w);M(this,S,0);M(this,b,new Map);M(this,I,new Map);M(this,H);M(this,de);M(this,j);if(!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");g(this,H,e.maxSize),g(this,de,e.maxAge||Number.POSITIVE_INFINITY),g(this,j,e.onEviction)}get __oldCache(){return c(this,I)}get(e){if(c(this,b).has(e)){const s=c(this,b).get(e);return f(this,w,xe).call(this,e,s)}if(c(this,I).has(e)){const s=c(this,I).get(e);if(f(this,w,L).call(this,e,s)===!1)return f(this,w,ct).call(this,e,s),s.value}}set(e,s,a={}){const{maxAge:r=c(this,de)}=a,i=typeof r=="number"&&r!==Number.POSITIVE_INFINITY?Date.now()+r:void 0;return c(this,b).has(e)?c(this,b).set(e,{value:s,expiry:i}):f(this,w,Ae).call(this,e,{value:s,expiry:i}),this}has(e){return c(this,b).has(e)?!f(this,w,L).call(this,e,c(this,b).get(e)):c(this,I).has(e)?!f(this,w,L).call(this,e,c(this,I).get(e)):!1}peek(e){if(c(this,b).has(e))return f(this,w,_e).call(this,e,c(this,b));if(c(this,I).has(e))return f(this,w,_e).call(this,e,c(this,I))}delete(e){const s=c(this,b).delete(e);return s&&W(this,S)._--,c(this,I).delete(e)||s}clear(){c(this,b).clear(),c(this,I).clear(),g(this,S,0)}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");const s=[...f(this,w,Pe).call(this)],a=s.length-e;a<0?(g(this,b,new Map(s)),g(this,I,new Map),g(this,S,s.length)):(a>0&&f(this,w,$e).call(this,s.slice(0,a)),g(this,I,new Map(s.slice(a))),g(this,b,new Map),g(this,S,0)),g(this,H,e)}*keys(){for(const[e]of this)yield e}*values(){for(const[,e]of this)yield e}*[Symbol.iterator](){for(const e of c(this,b)){const[s,a]=e;f(this,w,L).call(this,s,a)===!1&&(yield[s,a.value])}for(const e of c(this,I)){const[s,a]=e;c(this,b).has(s)||f(this,w,L).call(this,s,a)===!1&&(yield[s,a.value])}}*entriesDescending(){let e=[...c(this,b)];for(let s=e.length-1;s>=0;--s){const a=e[s],[r,i]=a;f(this,w,L).call(this,r,i)===!1&&(yield[r,i.value])}e=[...c(this,I)];for(let s=e.length-1;s>=0;--s){const a=e[s],[r,i]=a;c(this,b).has(r)||f(this,w,L).call(this,r,i)===!1&&(yield[r,i.value])}}*entriesAscending(){for(const[e,s]of f(this,w,Pe).call(this))yield[e,s.value]}get size(){if(!c(this,S))return c(this,I).size;let e=0;for(const s of c(this,I).keys())c(this,b).has(s)||e++;return Math.min(c(this,S)+e,c(this,H))}get maxSize(){return c(this,H)}entries(){return this.entriesAscending()}forEach(e,s=this){for(const[a,r]of this.entriesAscending())e.call(s,r,a,this)}get[Symbol.toStringTag](){return JSON.stringify([...this.entriesAscending()])}}S=new WeakMap,b=new WeakMap,I=new WeakMap,H=new WeakMap,de=new WeakMap,j=new WeakMap,w=new WeakSet,$e=function(e){if(typeof c(this,j)=="function")for(const[s,a]of e)c(this,j).call(this,s,a.value)},L=function(e,s){return typeof s.expiry=="number"&&s.expiry<=Date.now()?(typeof c(this,j)=="function"&&c(this,j).call(this,e,s.value),this.delete(e)):!1},ot=function(e,s){if(f(this,w,L).call(this,e,s)===!1)return s.value},xe=function(e,s){return s.expiry?f(this,w,ot).call(this,e,s):s.value},_e=function(e,s){const a=s.get(e);return f(this,w,xe).call(this,e,a)},Ae=function(e,s){c(this,b).set(e,s),W(this,S)._++,c(this,S)>=c(this,H)&&(g(this,S,0),f(this,w,$e).call(this,c(this,I)),g(this,I,c(this,b)),g(this,b,new Map))},ct=function(e,s){c(this,I).delete(e),f(this,w,Ae).call(this,e,s)},Pe=function*(){for(const e of c(this,I)){const[s,a]=e;c(this,b).has(s)||f(this,w,L).call(this,s,a)===!1&&(yield e)}for(const e of c(this,b)){const[s,a]=e;f(this,w,L).call(this,s,a)===!1&&(yield e)}};function Yt(n,t){let e="",s=!1,a,r="",i="";r="'",i='"';for(let o=0;o<n.length;o++){const l=n[o],h=n[o+1];l==='"'||l==="'"?s?a===l?(e+=r,s=!1):e+="\\"+r:(a=l,s=!0,e+=r):l==="\\"&&(h==="'"||h==='"')?h===r?(e+=s&&a===r?"\\"+r:"\\\\"+r,o++):h===i?(e+=s?i:r,o++):e+=l:l==="\\"&&h==="\\"?(e+="\\\\",o++):e+=l}return e}function lt(n){return Yt(n)}class Wt extends Error{constructor(t){super(t),this.name="TimeoutError"}}class Kt extends Error{constructor(t){super(),this.name="AbortError",this.message=t}}const ze=n=>globalThis.DOMException===void 0?new Kt(n):new DOMException(n),De=n=>{const t=n.reason===void 0?ze("This operation was aborted."):n.reason;return t instanceof Error?t:ze(t)};function Gt(n,t){const{milliseconds:e,fallback:s,message:a,customTimers:r={setTimeout,clearTimeout}}=t;let i;const l=new Promise((h,d)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){const{signal:p}=t;p.aborted&&d(De(p)),p.addEventListener("abort",()=>{d(De(p))})}if(e===Number.POSITIVE_INFINITY){n.then(h,d);return}const y=new Wt;i=r.setTimeout.call(void 0,()=>{if(s){try{h(s())}catch(p){d(p)}return}typeof n.cancel=="function"&&n.cancel(),a===!1?h():a instanceof Error?d(a):(y.message=a??`Promise timed out after ${e} milliseconds`,d(y))},e),(async()=>{try{h(await n)}catch(p){d(p)}})()}).finally(()=>{l.clear()});return l.clear=()=>{r.clearTimeout.call(void 0,i),i=void 0},l}function ut(){return new Ee({store:new we({maxSize:1e4})})}var $=(n=>(n.Text="text",n.Image="image",n.Audio="audio",n.Video="video",n.File="file",n.Unknown="unknown",n))($||{});class re{constructor(t){u(this,"debug");u(this,"systemMessage");u(this,"chatParams");u(this,"maxModelTokens");u(this,"maxResponseTokens");u(this,"userLabel");u(this,"assistantLabel");u(this,"getMessageById");u(this,"upsertMessage");u(this,"messageStore");u(this,"tokenizer");const{debug:e=!1,systemMessage:s,chatParams:a,maxModelTokens:r=4e3,maxResponseTokens:i=1e3,userLabel:o="User",assistantLabel:l="Assistant",messageStore:h,encoding:d="cl100k_base",getMessageById:y,upsertMessage:p}=t;this.debug=e,this.systemMessage=s,this.chatParams=a||{},this.userLabel=o,this.assistantLabel=l,this.maxModelTokens=r,this.maxResponseTokens=i,this.tokenizer=je.getEncoding(d),this.getMessageById=y??this.defaultGetMessageById,this.upsertMessage=p??this.defaultUpsertMessage,h?this.messageStore=h:this.messageStore=new Ee({store:new we({maxSize:1e4})})}async sendMessage(t,e={}){const{sessionId:s,conversationId:a,parentMessageId:r,messageId:i=ne.randomUUID(),...o}=e,l={sessionId:s,conversationId:a,id:i,parentMessageId:r,role:"user",type:"text",text:t,files:[]},h={sessionId:s,conversationId:a,id:ne.randomUUID(),parentMessageId:l.id,role:"assistant",type:"text",text:"",files:[]};return this.makeRequest(l,h,{sessionId:s,conversationId:a,parentMessageId:r,messageId:i,...o}).then(async()=>h.needClearHistory||h.error?h:Promise.all([this.upsertMessage(l),this.upsertMessage(h)]).then(()=>h))}async buildMessages(t,{parentMessageId:e,systemMessage:s=this.systemMessage}){const a=this.userLabel,r=this.assistantLabel,i=this.maxModelTokens-this.maxResponseTokens;let o=[];s&&o.push({role:"system",content:s});const l=o.length;let h=t?o.concat([{role:"user",content:t}]):o,d=0;do{const p=h.reduce((O,A)=>{switch(A.role){case"system":return O.concat([`Instructions:
${A.content}`]);case"user":return O.concat([`${a}:
${A.content}`]);default:return O.concat([`${r}:
${A.content}`])}},[]).join(`
`),v=await this.getTokenCount(p),T=v<=i;if(p&&!T||(o=h,d=v,!T)||!e)break;const _=await this.getMessageById(e);if(!_)break;const Y=_.role||"user";h=h.slice(0,l).concat([{role:Y,content:_.text},...h.slice(l)]),e=_.parentMessageId}while(!0);const y=Math.max(1,Math.min(this.maxModelTokens-d,this.maxResponseTokens));return{messages:o,maxTokens:y,numTokens:d}}async getTokenCount(t){return t=t.replace(/<\|endoftext\|>/g,""),this.tokenizer.encode(t).length}async defaultGetMessageById(t){return await this.messageStore.get(t)}async defaultUpsertMessage(t){await this.messageStore.set(t.id,t)}}class ht extends re{constructor(e={}){const{debug:s,chatParams:a,maxModelTokens:r,maxResponseTokens:i,messageStore:o,userLabel:l,assistantLabel:h,encoding:d,getMessageById:y,upsertMessage:p,systemMessage:v,...T}=e;super({debug:s,chatParams:{model:"gpt-3.5-turbo",temperature:.8,top_p:1,...a},maxModelTokens:r,maxResponseTokens:i,messageStore:o,systemMessage:v,userLabel:l,assistantLabel:h,encoding:d,getMessageById:y,upsertMessage:p});u(this,"api");this.api=new Nt.OpenAI(T)}async makeRequest(e,s,a){const{chatParams:r}=a,{messages:i}=await this.buildMessages(e.text,a),l=(await this.api.chat.completions.create({...this.chatParams,...r,messages:i,stream:!1})).choices[0];s.text=l.message.content}}const Jt=je.getEncoding("cl100k_base"),Xt="ernie-bot",Zt="User",es="ERNIE Bot";class dt{constructor(t){u(this,"_maxModelTokens");u(this,"_maxResponseTokens");u(this,"_getMessageById");u(this,"_upsertMessage");u(this,"_messageStore");u(this,"api");const{maxModelTokens:e=4e3,maxResponseTokens:s=1e3,messageStore:a,getMessageById:r,upsertMessage:i,model:o=Xt,...l}=t;this.api=new Rt.ERNIEBot({...l,model:o}),this._maxModelTokens=e,this._maxResponseTokens=s,this._getMessageById=r??this._defaultGetMessageById,this._upsertMessage=i??this._defaultUpsertMessage,a?this._messageStore=a:this._messageStore=new Ee({store:new we({maxSize:1e4})})}async sendMessage(t,e={}){const{conversationId:s,parentMessageId:a,messageId:r=ne.randomUUID(),...i}=e,o={role:"user",id:r,conversationId:s,parentMessageId:a,text:t,type:"text",files:[]},{messages:l}=await this._buildMessages(t,e),h=await this.api.chat.completions.create({...i,model:"ernie-bot",messages:l,stream:!1},{signal:e.abortSignal}),d={role:"assistant",id:h.id,conversationId:s,parentMessageId:r,text:h.result,type:"text",files:[]};return Promise.all([this._upsertMessage(o),this._upsertMessage(d)]).then(()=>d)}async _buildMessages(t,e){let{parentMessageId:s}=e;const a=Zt,r=es,i=this._maxModelTokens-this._maxResponseTokens;let o=[];const l=o.length;let h=t?o.concat([{role:"user",content:t}]):o,d=0;do{const p=h.reduce((O,A)=>{switch(A.role){case"system":return O.concat([`Instructions:
${A.content}`]);case"user":return O.concat([`${a}:
${A.content}`]);default:return O.concat([`${r}:
${A.content}`])}},[]).join(`
`),v=await this._getTokenCount(p),T=v<=i;if(p&&!T||(o=h,d=v,!T)||!s)break;const _=await this._getMessageById(s);if(!_)break;const Y=_.role||"user";h=h.slice(0,l).concat([{role:Y,content:_.text,name:_.name},...h.slice(l)]),s=_.parentMessageId}while(!0);const y=Math.max(1,Math.min(this._maxModelTokens-d,this._maxResponseTokens));return{messages:o,maxTokens:y,numTokens:d}}async _getTokenCount(t){return t=t.replace(/<\|endoftext\|>/g,""),Jt.encode(t).length}async _defaultGetMessageById(t){return await this._messageStore.get(t)}async _defaultUpsertMessage(t){await this._messageStore.set(t.id,t)}}const ts="claude-2";class mt extends Error{constructor(){super(...arguments);u(this,"statusCode");u(this,"statusText")}}class pt{constructor(t){u(this,"_apiBaseUrl");u(this,"_sessionKey");u(this,"_apiOrg");u(this,"_completionParams");const{sessionKey:e,apiOrg:s,apiBaseUrl:a="https://claude.ai/api",model:r=ts,timezone:i="Asia/Shanghai"}=t;if(this._apiBaseUrl=a,this._sessionKey=e,this._apiOrg=s,this._completionParams={model:r,timezone:i},!this._sessionKey)throw new Error("ClaudeAI missing required sessionKey");if(!this._apiOrg)throw new Error("ClaudeAI missing required apiOrg")}async sendMessage(t,e){const{messageId:s=ne.randomUUID(),parentMessageId:a,attachments:r=[],completionParams:i,abortSignal:o}=e||{},{conversationId:l}=await this.upsertChatConversations(e),h={role:"user",id:s,conversationId:l,parentMessageId:a,text:t,type:"text",files:[]},d=await this.request("/append_message",{body:JSON.stringify({organization_uuid:this._apiOrg,conversation_uuid:l,text:t,attachments:r,completion:{...this._completionParams,...i,prompt:t}}),signal:o}).then(p=>p.text());return{role:"assistant",id:ne.randomUUID(),conversationId:l,parentMessageId:h.id,text:d,type:"text",files:[]}}async upsertChatConversations(t){const{conversationId:e}=t??{};if(e)return{conversationId:e};const{uuid:s}=await this.createChatConversations();return{conversationId:s}}createChatConversations(){return this.request(`/organizations/${this._apiOrg}/chat_conversations`,{method:"POST",body:JSON.stringify({name:"chat"})}).then(t=>t.json())}async request(t,e){const s=await fetch(`${this._apiBaseUrl}${t}`,{method:"POST",...e,headers:{...this.defaultHeaders(),...e.headers}});if(!s.ok){let a;try{a=await s.text()}catch{a=s.statusText}const r=`Claude error ${s.status}: ${a}`,i=new mt(r,{cause:s});throw i.statusCode=s.status,i.statusText=s.statusText,i}return s}defaultHeaders(){return{"Content-Type":"application/json","User-Agent":this.userAgent(),...this.authHeaders()}}authHeaders(){return{Cookie:`sessionKey=${this._sessionKey};`}}userAgent(){return"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"}}class gt extends re{constructor(e={}){const{debug:s,systemMessage:a,chatParams:r,maxModelTokens:i,maxResponseTokens:o,messageStore:l,userLabel:h,assistantLabel:d,encoding:y,getMessageById:p,upsertMessage:v,...T}=e;super({debug:s,systemMessage:a,chatParams:{model:"hunyuan",temperature:.8,top_p:1,...r},maxModelTokens:i,maxResponseTokens:o,messageStore:l,userLabel:h,assistantLabel:d,encoding:y,getMessageById:p,upsertMessage:v});u(this,"api");this.api=new ye.HunYuanAI(T)}async makeRequest(e,s,a){const{chatParams:r}=a,{messages:i}=await this.buildMessages(e.text,a),l=(await this.api.chat.completions.create({...this.chatParams,...r,messages:i,stream:!1})).choices[0];s.text=l.message.content}}class ft extends re{constructor(e={}){const{debug:s,systemMessage:a,chatParams:r,maxModelTokens:i,maxResponseTokens:o,messageStore:l,userLabel:h,assistantLabel:d,encoding:y,getMessageById:p,upsertMessage:v,...T}=e;super({debug:s,systemMessage:a,chatParams:{model:"abab5-chat",temperature:.8,top_p:1,...r},maxModelTokens:i,maxResponseTokens:o,messageStore:l,userLabel:h,assistantLabel:d,encoding:y,getMessageById:p,upsertMessage:v});u(this,"api");this.api=new ye.MinimaxAI(T)}async makeRequest(e,s,a){const{chatParams:r}=a,{messages:i}=await this.buildMessages(e.text,a),l=(await this.api.chat.completions.create({...this.chatParams,...r,messages:i,stream:!1})).choices[0];s.text=l.message.content}}class yt extends re{constructor(e={}){const{debug:s,systemMessage:a,chatParams:r,maxModelTokens:i,maxResponseTokens:o,messageStore:l,userLabel:h,assistantLabel:d,encoding:y,getMessageById:p,upsertMessage:v,...T}=e;super({debug:s,systemMessage:a,chatParams:{model:"qwen-max",temperature:.8,...r},maxModelTokens:i,maxResponseTokens:o,messageStore:l,userLabel:h,assistantLabel:d,encoding:y,getMessageById:p,upsertMessage:v});u(this,"api");this.api=new ye.QWenAI(T)}async makeRequest(e,s,a){const{chatParams:r}=a,{messages:i}=await this.buildMessages(e.text,a),l=(await this.api.chat.completions.create({...this.chatParams,...r,messages:i,stream:!1})).choices[0];s.text=l.message.content}}class wt extends re{constructor(e={}){const{debug:s,systemMessage:a,chatParams:r,maxModelTokens:i,maxResponseTokens:o,messageStore:l,userLabel:h,assistantLabel:d,encoding:y,getMessageById:p,upsertMessage:v,...T}=e;super({debug:s,systemMessage:a,chatParams:{model:"spark-3",temperature:.8,top_p:1,...r},maxModelTokens:i,maxResponseTokens:o,messageStore:l,userLabel:h,assistantLabel:d,encoding:y,getMessageById:p,upsertMessage:v});u(this,"api");this.api=new ye.SparkAI(T)}async makeRequest(e,s,a){const{chatParams:r}=a,{messages:i}=await this.buildMessages(e.text,a),l=(await this.api.chat.completions.create({...this.chatParams,...r,messages:i,stream:!1})).choices[0];s.text=l.message.content}}class ss{constructor(t){u(this,"name","claude-web-api");u(this,"human_name","Claude AI");u(this,"input_type",[$.Text]);u(this,"api");u(this,"limiter");const{concurrency:e=3,interval:s=1e3,apiBaseUrl:a="https://openai.aihey.cc/claude",...r}=t;this.api=new pt({...r,apiBaseUrl:a}),this.limiter=new Q({concurrency:e,interval:s})}async call(t){const{message:e,session:s}=t,{api:a,limiter:r}=this,i=e.text(),o=s.claude??(s.claude={}),l=await r.add(({signal:h})=>a.sendMessage(i,{parentMessageId:o.parentMessageId,abortSignal:h}),{signal:t.signal,throwOnTimeout:!0});o.parentMessageId=l.id,t.reply(m.codeBlock`
${l.text}
-------------------
以上内容来自 ${this.human_name},与开发者无关`,!0)}}class as{constructor(t){u(this,"name","ernie-bot");u(this,"human_name","文心一言");u(this,"input_type",[$.Text]);u(this,"api");u(this,"limiter");const{concurrency:e=3,interval:s=1e3,...a}=t;this.api=new dt(a),this.limiter=new Q({concurrency:e,interval:s})}async call(t){var i;const{message:e,session:s}=t,a=s[i=this.name]??(s[i]={}),r=await this.limiter.add(({signal:o})=>this.api.sendMessage(e.text(),{parentMessageId:a.parentMessageId,abortSignal:o}),{signal:t.signal,throwOnTimeout:!0});a.parentMessageId=r.id,t.reply(m.codeBlock`
${r.text}
-------------------
以上内容来自 ${this.human_name},与开发者无关`,!0)}}class ns{constructor(t={}){u(this,"name","hunyuan-api");u(this,"human_name","混元助手");u(this,"input_type",[$.Text]);u(this,"api");u(this,"limiter");const{concurrency:e=3,interval:s=1e3,...a}=t;this.api=new gt(a),this.limiter=new Q({concurrency:e,interval:s})}async call(t){var i;const{message:e,session:s}=t,a=s[i=this.name]??(s[i]={}),r=await this.limiter.add(({signal:o})=>this.api.sendMessage(e.text(),{parentMessageId:a.parentMessageId,abortSignal:o}),{signal:t.signal,throwOnTimeout:!0});a.parentMessageId=r.id,t.reply(m.codeBlock`
${r.text}
-------------------
以上内容来自 ${this.human_name},与开发者无关`,!0)}}class rs{constructor(t={}){u(this,"name","minmax-api");u(this,"human_name","MM智能助理");u(this,"input_type",[$.Text]);u(this,"api");u(this,"limiter");const{concurrency:e=3,interval:s=1e3,...a}=t;this.api=new ft(a),this.limiter=new Q({concurrency:e,interval:s})}async call(t){var i;const{message:e,session:s}=t,a=s[i=this.name]??(s[i]={}),r=await this.limiter.add(({signal:o})=>this.api.sendMessage(e.text(),{parentMessageId:a.parentMessageId,abortSignal:o}),{signal:t.signal,throwOnTimeout:!0});a.parentMessageId=r.id,t.reply(m.codeBlock`
${r.text}
-------------------
以上内容来自 ${this.human_name},与开发者无关`,!0)}}class kt{constructor(t){u(this,"name","multi-model");u(this,"human_name","多模型管理");u(this,"input_type",[]);u(this,"llms");u(this,"llmMap",new Map);u(this,"llm");this.llm=t[0],this.llms=t,this.llmMap=new Map(t.map(e=>[e.name,e])),this.input_type=Array.from(new Set(t.map(e=>e.input_type).flat()))}onPrepareTextMessage(t,e){var i;const{message:s,userConfig:a}=e,r=s.text();if(r==="查看模型"){const o=this.resolve(a.model);return t.abort(),e.reply(m.codeBlock`
⊶ 系统提示
﹊
当前模型: ${(o==null?void 0:o.human_name)||"暂无可用模型"}。
模型列表
${Array.from(this.llms.values()).map(l=>` - ${l.human_name}`).join(`
`)}
-------------------
输入 "帮助" 获取更详细的使用说明。`)}if(r.startsWith("切换")){t.abort();const o=(i=r.split("切换")[1])==null?void 0:i.toLowerCase().trim();if(!o)return e.reply(m.codeBlock`
⊶ 系统提示
﹊
模型列表
${Array.from(this.llms.values()).map(h=>` - ${h.human_name}`).join(`
`)}
-------------------
输入 "帮助" 获取更详细的使用说明。`);const l=this.find(o.toString());return l?(a.model=l.name,l.greeting?e.reply(l.greeting):e.reply(m.codeBlock`
⊶ 系统提示
﹊
已切换至 ${l.human_name}`)):e.reply(m.codeBlock`
⊶ 系统提示
﹊
需要切换至的模型不存在或不可用,请选择其他模型。
模型列表
${Array.from(this.llms.values()).map(h=>` - ${h.human_name}`).join(`
`)}
-------------------
输入 "帮助" 获取更详细的使用说明。`)}}async call(t,e){const s=this.resolve(t.userConfig.model);if(!s)return t.reply(m.codeBlock`
⊶ 系统提示
﹊
暂无可用的 AI 模型!
-------------------
输入 "帮助" 获取更详细的使用说明。`);s.input_type.includes(t.type)===!1&&t.reply(m.codeBlock`
⊶ 系统提示
﹊
${s.human_name} 暂不支持处理此类消息!
请切换至其他模型后再试。
-------------------
输入 "帮助" 获取更详细的使用说明。`);const a=this.llms.filter(r=>r.input_type.includes(t.type)&&s!==r);return this.calling(t,e,s,a)}async calling(t,e,s,a=this.llms){try{return await s.call(t,e)}catch(r){if(console.error(`${s.human_name} 模型调用失败`,r),a.length>0)return t.reply(m.codeBlock`
⊶ 系统提示
﹊
${s.human_name} 模型调用失败,将尝试其他模型。`),this.callWithFallback(t,e,a);t.reply(m.codeBlock`
⊶ 系统提示
﹊
${s.human_name} 模型调用失败,可以试试其他模型。
-------------------
输入 "帮助" 获取更详细的使用说明。`)}}async callWithFallback(t,e,s=this.llms){const a=s.shift();try{return await(a==null?void 0:a.call(t,e))}catch(r){if(s.length>0)return await this.callWithFallback(t,e,s);throw r}}resolve(t){return t?this.llmMap.get(t)||this.llm:this.llm}find(t){for(const e of this.llms)if(e.name.toLowerCase().includes(t)||e.human_name.toLowerCase().includes(t))return e}}class is{constructor(t){u(this,"name","openai-api");u(this,"human_name","ChatGPT");u(this,"input_type",[$.Text]);u(this,"api");u(this,"limiter");const{concurrency:e=3,interval:s=1e3,baseURL:a="https://openai.aihey.cc/openai/v1",...r}=t;this.api=new ht({...r,baseURL:a}),this.limiter=new Q({concurrency:e,interval:s})}async call(t){const{message:e,session:s}=t,a=s.openai??(s.openai={}),r=await this.limiter.add(({signal:i})=>this.api.sendMessage(e.text(),{parentMessageId:a.parentMessageId,abortSignal:i}),{signal:t.signal,throwOnTimeout:!0});a.parentMessageId=r.id,t.reply(m.codeBlock`
${r.text}
-------------------
以上内容来自 ${this.human_name},与开发者无关`,!0)}}class os{constructor(t={}){u(this,"name","qwen-api");u(this,"human_name","通义千问");u(this,"input_type",[$.Text]);u(this,"api");u(this,"limiter");const{concurrency:e=3,interval:s=1e3,...a}=t;this.api=new yt(a),this.limiter=new Q({concurrency:e,interval:s})}async call(t){var i;const{message:e,session:s}=t,a=s[i=this.name]??(s[i]={}),r=await this.limiter.add(({signal:o})=>this.api.sendMessage(e.text(),{parentMessageId:a.parentMessageId,abortSignal:o}),{signal:t.signal,throwOnTimeout:!0});a.parentMessageId=r.id,t.reply(m.codeBlock`
${r.text}
-------------------
以上内容来自 ${this.human_name},与开发者无关`,!0)}}class cs{constructor(t={}){u(this,"name","spark-api");u(this,"human_name","星火认知");u(this,"input_type",[$.Text]);u(this,"api");u(this,"limiter");const{concurrency:e=3,interval:s=1e3,...a}=t;this.api=new wt(a),this.limiter=new Q({concurrency:e,interval:s})}async call(t){var i;const{message:e,session:s}=t,a=s[i=this.name]??(s[i]={}),r=await this.limiter.add(({signal:o})=>this.api.sendMessage(e.text(),{parentMessageId:a.parentMessageId,abortSignal:o}),{signal:t.signal,throwOnTimeout:!0});a.parentMessageId=r.id,t.reply(m.codeBlock`
${r.text}
-------------------
以上内容来自 ${this.human_name},与开发者无关`,!0)}}function ls(n){const{llm:t}=n,e=t instanceof kt?t.llms:[t],s=Array.from(n.assistant.command.commands.values());return n.reply(m.codeBlock`
⊶ 帮助信息
﹊
口令
☛ 重新开始
☛ 停止
☛ 查看模型
☛ 切换 <模型名称>
☛ 帮助
☛ 查看源码
指令
${s.map(a=>` ☛ ${a.name}`)}
模型列表
${e.map(a=>` ☛ ${a.summary||a.human_name}`)}
如恶意使用,将拉入黑名单,敬请谅解。`)}const Mt=({debug:n=!1,testing:t=!1,disabledOutdatedDetection:e=!1,cache:s=ut(),maintainers:a=[],help:r=ls,...i})=>({...i,debug:n,testing:t,disabledOutdatedDetection:e,cache:s,help:r,maintainers:a});function us(n,t){const e=[{name:"UserConfig",...n},n.llm],s=Object.entries(t.hooks);for(const a of e)for(const[r,i]of s){const o=a[r];o&&typeof o=="function"&&i.add({pluginName:a.name,hook:o.bind(a)})}}function Se(n){return ne.createHash("md5").update(n).digest("hex")}const bt=n=>n instanceof Error?n:new Error(n);function It(n){return new Promise(t=>setTimeout(t,n))}async function Tt(n,t){const e=`assistant:session:${t}`,s=await n.get(e)||{};return Object.defineProperties(s,{clear:{configurable:!1,enumerable:!1,writable:!1,value:async()=>{for(const i in s)delete s[i];await n.delete(e)}},restore:{configurable:!1,enumerable:!1,writable:!1,value:async()=>{await n.set(e,s)}}}),s}async function vt(n,t,e){const s=`user:config:${t}`,a=await n.get(s)||{};return a.user_name=e,Object.defineProperties(a,{clear:{configurable:!1,enumerable:!1,writable:!1,value:async()=>{for(const o in a)delete a[o];await n.delete(s)}},restore:{configurable:!1,enumerable:!1,writable:!1,value:async()=>{await n.set(s,a)}}}),a}async function Ct(n,t,e){const s=e.talker(),a=s.id,r=s.name(),i=e.room(),o=i==null?void 0:i.id,l=Se(o?`${o}:${a}`:a),{monitor:h,llm:d,options:{debug:y,maintainers:p,cache:v}}=t,[T,_,Y,O]=await Promise.all([i==null?void 0:i.topic(),e.wechaty.currentUser.name(),vt(v,a,r),Tt(v,l)]);y&&(i?B.log.info(`🤖️ [${e.id}] 在房间 (${T}) 收到(${r}@${a})的消息`):B.log.info(`🤖️ [${e.id}] 收到(${r}@${a})的消息`));async function A(C,ie,ke){q.aborted||(i?typeof C=="string"||ke===!1?await i.say(`
${C}`,s):await i.say(C):await s.say(C),ie&&y&&(i?B.log.info(`🤖️ [${e.id}] 在房间 (${T}) 回复 (${r}@${a}) 的消息`):B.log.info(`🤖️ [${e.id}] 回复(${r}@${a})的消息`)))}const Et=async()=>{await t.hooks.onContextDestroyed.process(n,q,t),O.restore(),Y.restore()};async function Oe(C,ie){await A(C).then(()=>It(460),ke=>ie(ke))}async function St(C,ie){await Oe(zt.FileBox.fromUrl(C,{name:ie}),()=>q.reply(C))}function Ue(){return q.lock=h.defineLock({id:l,messageId:e.id,conversationTitle:T,talkerId:a,talkerName:r}),q.lock}const q={assistant:t,llm:d,conversationId:l,conversationTitle:T,talkerId:a,talkerName:r,chatbotUserName:_,isAdmin:p.includes(a),userConfig:Y,session:O,type:Le(e),message:e,reply:A,sendFileBox:Oe,sendFileFromUrl:St,lock:null,createLock:Ue,releaseLock(){h.releaseLock(l)},get isLocked(){return h.isLocked(l)},get signal(){var C;return(C=q.lock)==null?void 0:C.controller.signal},abort(C){Ue().abort(C)},get aborted(){var C;return((C=q.lock)==null?void 0:C.controller.signal.aborted)??!1},dispose:Et};return await t.hooks.onContextCreated.process(n,q,t),q}function Le(n){const t=n.wechaty.Message.Type;switch(n.type()){case t.Text:return $.Text;case t.Image:return $.Image;case t.Audio:return $.Audio;case t.Video:return $.Video;case t.Attachment:return $.File;default:return $.Unknown}}async function hs(n,t,e){if(await t.hooks.onPrepareFileMessage.process(n,e,t),!n.signal.aborted){if(e.isLocked)return e.reply(m.codeBlock`
⊶ 系统提示
﹊
稍等一下,还在思考中...`);e.createLock();try{await t.call(e)}finally{e.releaseLock()}}}const Fe="- - - - - - - - - - - - - - -";function He(n){return lt(n).replace(/\n+/gm," ").trim()}async function $t(n,t,e){const{message:s}=e,{monitor:a,keywords:r}=t;e.conversationTitle&&(s.payload.text=s.text().replaceAll(`@${e.chatbotUserName}`,"").replaceAll(/@(\S*)/gmu,"$1").trim());const i=s.text();if(!i)return e.reply(m.codeBlock`
⊶ 系统提示
﹊
👀 你想要说什么?`);if(i.startsWith("/"))return a.stats.command+=1,t.command.parse(e,i.split(" "));if(r.help.includes(i))return t.options.help(e);if(r.sourceCode.includes(i))return e.reply(m.codeBlock`
项目地址:
https://github.com/zhengxs2018/wechaty-plugin-assistant
欢迎 Star 和 Fork。`);if(r.stopConversation.includes(i))return e.isLocked&&(a.stats.skipped+=1,e.abort()),e.reply(m.codeBlock`
⊶ 系统提示
﹊
好的,我将不再回复。如果你有其他问题或需要帮助,请随时告诉我,我将竭诚为您服务。`);if(r.newConversation.includes(i))return e.session.clear(),e.isLocked&&(e.abort(),a.stats.skipped+=1),e.reply(m.codeBlock`
⊶ 系统提示
﹊
好的,新的对话从现在开始,期待与您的交流。
如有任何问题或需要帮助,请随时提出.`);if(await t.hooks.onPrepareTextMessage.process(n,e,t),!n.signal.aborted){if(e.isLocked)return e.reply(m.codeBlock`
⊶ 系统提示
﹊
稍等一下,还在思考中...`);if(e.createLock(),i.includes(Fe)){const[o,l]=i.split(Fe),h=o.split(":").slice(1).join("").trim().replace(/」$/,"");s.payload.text=m.codeBlock`
我会发送一个被引用消息和一个问题;
你需要根据我引用的消息,来回答我发送的问题;
你应该仅返回和我引用消息和问题相关的内容;
被引用的消息: """ ${He(h)}; """;
这是我的问题: """ ${He(l)}; """ `}try{await t.call(e)}finally{e.releaseLock()}}}async function xt(n,t){return t.reply(m.codeBlock`
⊶ 系统提示
﹊
暂时无法处理该类型的消息`)}async function _t(n,t){const{monitor:e,options:{disabledOutdatedDetection:s}}=n;if(!e.running||!s&&e.startupTime>t.date()||t.self())return;const{wechaty:{Message:a,Contact:r}}=t;if(t.talker().type()!==r.Type.Individual)return;const i=new AbortController;if(await n.hooks.onMessage.process(i,n,t),i.signal.aborted)return;if(t.room()){if(await n.hooks.onRoomMessage.process(i,n,t),i.signal.aborted||!await t.mentionSelf()||(await n.hooks.onRoomMentionSelfMessage.process(i,n,t),i.signal.aborted))return}else if(await n.hooks.onIndividualMessage.process(i,n,t),i.signal.aborted)return;e.stats.message+=1;const o=await Ct(i,n,t);if(!i.signal.aborted)try{switch(t.type()){case a.Type.Attachment:case a.Type.Audio:case a.Type.Image:case a.Type.Video:await hs(i,n,o);break;case a.Type.Text:await $t(i,n,o);break;default:await xt(n,o)}e.stats.success+=1}catch(l){if(i.signal.aborted||o.aborted)return;e.stats.failure+=1;const h=bt(l);B.log.error(h.message),o.reply(m.codeBlock`
⊶ 系统提示
﹊
系统错误,请稍后再试!`)}finally{o.dispose()}}async function At(n,t){const{monitor:e}=n;n.wechaty=t,t.on("message",n.handler),t.on("login",s=>{e.started=!0,e.startupTime=new Date,e.running=!0,n.chatbotUser=s}),t.on("logout",()=>{e.started=!1,e.running=!1,n.chatbotUser=void 0})}function ds(n){const t=Mt(n),e=Xe(),s=Ze(),a=new z("program"),{llm:r}=t,i={options:t,monitor:s,hooks:e,chatbotUser:null,wechaty:null,command:a,keywords:Ft,llm:r,handler:o=>_t(i,o),callback:()=>o=>void At(i,o),async call(o){r.input_type.includes(o.type)?await r.call(o,i):o.reply(m.codeBlock`
⊶ 系统提示
﹊
${r.human_name} 暂不支持处理此类消息!
-------------------
输入 "帮助" 获取更详细的使用说明。`)},run(){s.running=!0,s.startupTime=new Date},stop(){s.running=!1}};return a.addCommand(me),us(t,i),i}const Pt=n=>n,ms=n=>n,Be=(n,t={})=>{const e={text:n||"hello"};return{id:"testMessageId",payload:e,text:()=>e.text,type:()=>7,say:s=>Promise.resolve(console.log(s)),talker:()=>({id:t.talkerId??"mockTalkerId",name:()=>t.talkerName??"mockTalkerName",type:()=>1,say:s=>Promise.resolve(console.log(s))}),room(){},mentionSelf:()=>Promise.resolve(!0),conversation:()=>({id:"testConversationId"}),self:()=>!1,date:()=>Date.now(),wechaty:{Message:{Type:{Text:7}},Contact:{Type:{Individual:1}},currentUser:{name:()=>"testChatbotUserName"}}}};function ps(n,t={}){const e=Be(n,t);return e.room=()=>({id:t.roomId??"mockRoomId",topic:()=>Promise.resolve(t.roomName??"mockRoomName"),say:s=>Promise.resolve(console.log(s))}),e}const gs=(n=Be())=>{const t=n.talker(),e=t.id,s=t.name(),a=n.room(),r=a==null?void 0:a.id,i=Se(r?`${r}:${e}`:e),o=new AbortController;return{conversationId:i,talkerId:e,talkerName:s,chatbotUserName:n.wechaty.currentUser.name(),isAdmin:!1,type:Le(n),message:n,session:{},userConfig:{},createLock(){return{id:"testLockId",createdAt:Date.now(),controller:o,abort:()=>o.abort(),dispose:()=>{}}},releaseLock:()=>{},isLocked:!1,get aborted(){return o.signal.aborted},abort:()=>o.abort(),async reply(l){n.say(l)},sendFileFromUrl(l,h){return console.log("sendFileFromUrl",l,h),Promise.resolve()},sendFileBox(l,h){return console.log("sendFileBox",l,h),Promise.resolve()},dispose:()=>{}}},fs=Pt({name:"mock",human_name:"mock",input_type:[$.Text],async call(n){console.log("收到消息",n.message.text()),n.reply("MockLLM: 收到消息")}});exports.APIError=mt;exports.AbortError=Te;exports.ChatClaudeAI=ss;exports.ChatERNIEBot=as;exports.ChatGPTAPI=ht;exports.ChatHunYuan=ns;exports.ChatLLMAPI=re;exports.ChatMinimax=rs;exports.ChatOpenAI=is;exports.ChatQWen=os;exports.ChatSpark=cs;exports.ChatType=$;exports.ClaudeAI=pt;exports.Command=z;exports.DeepL=Ve;exports.ERNIEBotAPI=dt;exports.HunYuanAPI=gt;exports.MinimaxAPI=ft;exports.MultiChatModelSwitch=kt;exports.Option=Ie;exports.PQueue=Q;exports.QWenAPI=yt;exports.QuickLRU=we;exports.SparkAPI=wt;exports.Translation=Qe;exports.castToError=bt;exports.createAssistant=ds;exports.createAssistantHookQueue=N;exports.createAssistantHooks=Xe;exports.createAssistantMonitor=Ze;exports.createConversationContext=Ct;exports.createConversationSession=Tt;exports.createMemoryCache=ut;exports.createMockContext=gs;exports.createMockTextMessage=Be;exports.createRoomTextMockMessage=ps;exports.createUserConfig=vt;exports.deepl=me;exports.defineConfig=ms;exports.defineLLM=Pt;exports.dict=We;exports.hot=Ke;exports.kfc=Ge;exports.md5=Se;exports.mockLLM=fs;exports.moyu=Je;exports.pTimeout=Gt;exports.processTextMessage=$t;exports.processUnknownMessage=xt;exports.resolveAssistantOptions=Mt;exports.resolveChatType=Le;exports.sleep=It;exports.toSingleQuotes=lt;exports.wechatyMessageHandler=_t;exports.wechatyPluginCallback=At;