UNPKG

@zhengxs/wechaty-plugin-assistant

Version:
1,904 lines (1,871 loc) 74.6 kB
var st = Object.defineProperty; var Ee = (n) => { throw TypeError(n); }; var at = (n, t, e) => t in n ? st(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e; var u = (n, t, e) => at(n, typeof t != "symbol" ? t + "" : t, e), we = (n, t, e) => t.has(n) || Ee("Cannot " + e); var c = (n, t, e) => (we(n, t, "read from private field"), e ? e.call(n) : t.get(n)), M = (n, t, e) => t.has(n) ? Ee("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(n) : t.set(n, e), f = (n, t, e, s) => (we(n, t, "write to private field"), s ? s.call(n, e) : t.set(n, e), e), g = (n, t, e) => (we(n, t, "access private method"), e); var Y = (n, t, e, s) => ({ set _(a) { f(n, t, a, e); }, get _() { return c(n, t, s); } }); import { ok as Ae, AssertionError as nt } from "node:assert"; import { codeBlock as d } from "common-tags"; import rt from "minimist"; import it from "languagedetect"; import { log as O } from "wechaty"; import _e from "keyv"; import { EventEmitter as ot } from "eventemitter3"; import { OpenAI as ct } from "openai"; import { randomUUID as re, createHash as lt } from "node:crypto"; import { getEncoding as Be } from "js-tiktoken"; import { ERNIEBot as ut } from "@zhengxs/erniebot"; import { HunYuanAI as ht, MinimaxAI as mt, QWenAI as dt, SparkAI as pt } from "@zhengxs/ai"; import { FileBox as ft } from "file-box"; class Se { 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 B, G, J, Q, X, ie; const W = class W { constructor(t, e = {}) { /** * 命令名称 */ u(this, "name"); /** * 是否需要输入项 */ u(this, "required"); /** * 是否禁用 */ u(this, "disabled"); /** * 是否默认命令 */ u(this, "default"); /** * 父级指令 */ u(this, "parent"); /** * 简短描述 */ M(this, B); /** * 详细描述 */ M(this, G); /** * 配置项 */ M(this, J, /* @__PURE__ */ new Map()); /** * 子命令 */ M(this, Q, /* @__PURE__ */ new Map()); /** * 处理器 */ M(this, X); /** * 帮助配置 */ M(this, ie); this.name = t, f(this, B, e.summary || ""), f(this, G, e.description), this.required = e.required === !0, this.disabled = e.disabled === !0, this.default = e.default === !0, f(this, ie, new Se("help", { type: "boolean", alias: "H", description: "帮助" })); } get commands() { return c(this, Q); } summary(t) { return t ? (f(this, B, t), this) : c(this, B); } usage() { const t = []; if (c(this, Q).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 ? d` ${this.summary() || "使用说明"} Commands: ${t.join(` `)}` : "暂无可用的有效指令!"; const e = []; c(this, J).forEach((a) => { e.push(a.toString()); }); const s = [ d` 使用说明 Usage: /${this.name} [options]${this.required ? " <input>" : ""}` ]; return c(this, B) && s.push(c(this, B)), e.length && s.push(d` Options: ${e.join(` `)}`), t.length && s.push(d` Commands: ${t.join(` `)}`), c(this, G) && s.push(c(this, G)), s.join(` `); } addCommand(t) { return t.parent = this, c(this, Q).set(t.name, t), this; } add(t, e) { const s = t instanceof W ? t : new W(t, e); return this.addCommand(s), s; } register(t, ...e) { let s; return typeof e[0] == "function" ? (s = new W(t), s.action(e[0])) : (s = new W(t, e[0]), s.action(e[1])), this.addCommand(s), s; } /** * @param name - 参数名 * @param opts - 参数 */ option(t, e) { return c(this, J).set(t, new Se(t, e)), this; } /** * @param argv - 原始参数 * @returns 解析好的参数 */ parseArgs(t) { const e = { boolean: [], string: [], alias: {} }; return [...c(this, J).values(), c(this, ie)].forEach((r) => { const i = r.alias; i && (e.alias[i] = r.name); const o = e[r.type]; Array.isArray(o) && o.push(r.name); }), { ...rt(t, e), raw: t }; } /** * @param handler - 处理函数 * @returns */ async action(t) { return f(this, X, t), this; } /** * @param argv - 原始参数 * @param params - 回应参数 * @example * * ```sh * $ /mj --help * ``` */ parse(t, e) { const s = c(this, Q); 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()); } }; B = new WeakMap(), G = new WeakMap(), J = new WeakMap(), Q = new WeakMap(), X = new WeakMap(), ie = new WeakMap(); let j = W; class gt { constructor() { u(this, "lang", new it()); u(this, "languagesToCodes", /* @__PURE__ */ 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", /* @__PURE__ */ 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 Ae(this.isSupported(s), `Unsupported language: ${s}`), Ae(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()); } /** * @param text - 要检测的文本 * @param limit - 最大匹配数 * @returns 返回匹配的语言列表 */ detectedLanguages(t, e = 5) { return this.lang.detect(t, e); } } class yt extends gt { 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, [m] = h; return { lang: l, result: m.text, alternatives: m.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 Fe = new yt(), ge = new j("deepl", { required: !0, summary: "DeepL 翻译", description: d` 支持语言列表: ${Array.from(Fe.supportedLanguages).map(([n, t]) => ` ${n} - ${t}`)} 输入语言代码,可以手动指定翻译语言,例如: /deepl -f zh 你好 /deepl -f zh -t en 你好 /deepl -t zh hello 如果不指定语言代码,会自动检测文本语言,但是这会导致一些特殊语言的翻译出现问题` }); ge.option("from", { alias: "f", description: "源语言代码" }); ge.option("to", { alias: "t", description: "目标语言代码" }); ge.action(async (n, t) => { const e = t._.join(" ").trim(); if (e.length === 0) return n.reply( d` ⊶ 系统提示 ﹊ 请输入要翻译的文本`, !0 ); try { const s = await Fe.translate( e, t ), { result: a, alternatives: r = [] } = s; return r.length > 0 ? n.reply(d` ⊶ 翻译结果 ﹊ ${a} 备选结果: ${r.map((i) => ` - ${i}`)}`) : n.reply(d` ⊶ 翻译结果 ﹊ ${a}`); } catch (s) { return s instanceof nt ? n.reply( d` ⊶ 系统提示 ﹊ ${s.message}`, !0 ) : (console.error("deepl", s), n.reply( d` ⊶ 系统提示 ﹊ 翻译服务无法使用,稍后再试试吧`, !0 )); } }); const wt = new j("dict", { required: !0, summary: "汉字词典" }); wt.action(async (n, t) => { const e = t._[0]; if (!e) return n.reply( d` ⊶ 系统提示 ﹊ 请输入要查询的汉字`, !0 ); const s = new URL("https://api.pearktrue.cn/api/word/parse.php"); s.searchParams.set("word", e); const a = await fetch(s).then( (m) => { if (m.ok) return m.json(); O.error("词典服务异常 %d %s", m.status, r); }, (m) => { O.error("error", m); } ); if (!a || a.code !== 200) return n.reply( d` ⊶ 系统提示 ﹊ ${(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( d` 汉字词典 ==================== ${h.join(` `)} 解 义 ﹊ ${o || "暂无解释"}`, !0 ); }); const bt = /* @__PURE__ */ 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"] ]), Mt = new j("hot", { required: !0, summary: "热搜", description: d` 数据来源 - hp: 虎扑步行街 - zh: 知乎热榜 - 36: 36氪 - bd: 百度热点 - bl: 哔哩哔哩 - jt: 历史上的今天 - tb: 贴吧热议 - wb: 微博热搜 - dy: 抖音热点 - db: 豆瓣小组 - sp: 少数派 - it: IT之家 - itn: IT之家新闻 输出代号即可,如:/hot hp ` }); Mt.action(async (n, t) => { const e = bt.get(t._[0]) || "wbHot", s = await fetch( `https://api.vvhan.com/api/hotlist?type=${e}` ).then( (i) => { if (i.ok) return i.json(); O.error("热搜服务异常 %d %s", i.status, e); }, (i) => { O.error("error", i); } ); if (!s || !s.success) return n.reply( d` ⊶ 系统提示 ﹊ ${(s == null ? void 0 : s.message) || "热搜服务器暂时无法使用,稍后再试试吧"}`, !0 ); const [a, ...r] = s.data; n.reply( d` ${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 kt = new j("kfc", { required: !0, summary: "疯狂星期四" }); kt.action(async (n) => { const t = await fetch( "https://api.001500.cn/API/kfc.php?type=json" ).then( (e) => { if (e.ok) return e.json(); O.error("疯狂星期四 %d %s", e.status); }, (e) => { O.error("error", e); } ); return t && t.data ? n.reply(t.data.msg) : (console.error("疯狂星期四 error", t), n.reply( d` ⊶ 系统提示 ﹊ 星期四文学暂时无法使用,稍后再试试吧`, !0 )); }); const It = new j("my", { summary: "摸鱼日历" }); It.action((n) => { fetch("https://api.vvhan.com/api/moyu").then((t) => { t.ok ? (console.log(t.url), n.sendFileFromUrl(t.url)) : n.reply( d` ⊶ 系统提示 ﹊ 服务器出错了,稍后再试试吧`, !0 ); }); }); const q = (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; } }; }, Tt = () => ({ onMessage: q("onMessage"), onRoomMessage: q("onRoomMessage"), onRoomMentionSelfMessage: q( "onRoomMentionSelfMessage" ), onIndividualMessage: q("onIndividualMessage"), onContextCreated: q("onContextCreated"), onContextDestroyed: q("onContextDestroyed"), onPrepareTextMessage: q("onPrepareTextMessage"), onPrepareFileMessage: q("onPrepareFileMessage") }); function vt() { const n = /* @__PURE__ */ new Map(); return { started: !1, startupTime: /* @__PURE__ */ 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 $t = { newConversation: [ "新对话", "新聊天", "重新开始", "重新对话", "重新聊天", "重新对话", "重新开始对话", "重新开始聊天", "重新开始对话" ], stopConversation: ["停", "停止", "停止回复"], help: ["帮助", "获取帮助"], sourceCode: ["获取源码", "查看源码"] }; function _t(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 N; class xt { constructor() { M(this, N, []); } enqueue(t, e) { e = { priority: 0, ...e }; const s = { priority: e.priority, run: t }; if (this.size && c(this, N)[this.size - 1].priority >= e.priority) { c(this, N).push(s); return; } const a = _t( c(this, N), s, (r, i) => i.priority - r.priority ); c(this, N).splice(a, 0, s); } dequeue() { const t = c(this, N).shift(); return t == null ? void 0 : t.run; } filter(t) { return c(this, N).filter( (e) => e.priority === t.priority ).map((e) => e.run); } get size() { return c(this, N).length; } } N = new WeakMap(); let De = class extends Error { constructor(e) { super(e); u(this, "name", "TimeoutError"); } }, Ct = class extends Error { constructor(e) { super(e); u(this, "name", "TimeoutError"); } }; const Le = (n) => globalThis.DOMException === void 0 ? new Ct(n) : new DOMException(n), Oe = (n) => { const t = n.reason === void 0 ? Le("This operation was aborted.") : n.reason; return t instanceof Error ? t : Le(t); }; function Pt(n, t) { const { milliseconds: e, fallback: s, message: a, customTimers: r = { setTimeout, clearTimeout } } = t; let i; const l = new Promise((h, m) => { 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 && m(Oe(p)), p.addEventListener("abort", () => { m(Oe(p)); }); } if (e === Number.POSITIVE_INFINITY) { n.then(h, m); return; } const y = new De(); i = r.setTimeout.call( void 0, () => { if (s) { try { h(s()); } catch (p) { m(p); } return; } typeof n.cancel == "function" && n.cancel(), a === !1 ? h() : a instanceof Error ? m(a) : (y.message = a ?? `Promise timed out after ${e} milliseconds`, m(y)); }, e ), (async () => { try { h(await n); } catch (p) { m(p); } })(); }).finally(() => { l.clear(); }); return l.clear = () => { r.clearTimeout.call(void 0, i), i = void 0; }, l; } let ze = class extends Error { }; var Z, ee, F, oe, te, ce, E, se, x, le, A, ae, U, ue, b, He, je, Qe, Ve, Ke, de, be, Me, pe, Ye, fe; class V extends ot { // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()` constructor(e) { var s, a; super(); M(this, b); M(this, Z); M(this, ee); M(this, F, 0); M(this, oe); M(this, te); M(this, ce, 0); M(this, E); M(this, se); M(this, x); M(this, le); M(this, A, 0); // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194 M(this, ae); M(this, U); M(this, ue); /** Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already. Applies to each future operation. */ u(this, "timeout"); if (e = { carryoverConcurrencyCount: !1, intervalCap: Number.POSITIVE_INFINITY, interval: 0, concurrency: Number.POSITIVE_INFINITY, autoStart: !0, queueClass: xt, ...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})` ); f(this, Z, e.carryoverConcurrencyCount), f(this, ee, e.intervalCap === Number.POSITIVE_INFINITY || e.interval === 0), f(this, oe, e.intervalCap), f(this, te, e.interval), f(this, x, new e.queueClass()), f(this, le, e.queueClass), this.concurrency = e.concurrency, this.timeout = e.timeout, f(this, ue, e.throwOnTimeout === !0), f(this, U, 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})` ); f(this, ae, e), g(this, b, pe).call(this); } async add(e, s = {}) { return s = { timeout: this.timeout, throwOnTimeout: c(this, ue), ...s }, new Promise((a, r) => { c(this, x).enqueue(async () => { var i; Y(this, A)._++, Y(this, F)._++; try { if ((i = s.signal) != null && i.aborted) throw new ze("The task was aborted."); let o = e({ signal: s.signal }); s.timeout && (o = Pt(Promise.resolve(o), { // @ts-ignore message: void 0, milliseconds: s.timeout, signal: s.signal })), s.signal && (o = Promise.race([ o, g(this, b, Ye).call(this, s.signal) ])); const l = await o; a(l), this.emit("completed", l); } catch (o) { if (o instanceof De && !s.throwOnTimeout) { a(); return; } r(o), this.emit("error", o); } finally { g(this, b, Qe).call(this); } }, s), this.emit("add"), g(this, b, de).call(this); }); } async addAll(e, s) { return Promise.all( e.map(async (a) => this.add(a, s)) ); } /** Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) */ start() { return c(this, U) ? (f(this, U, !1), g(this, b, pe).call(this), this) : this; } /** Put queue execution on hold. */ pause() { f(this, U, !0); } /** Clear the queue. */ clear() { f(this, x, new (c(this, le))()); } /** Can be called multiple times. Useful if you for example add additional items at a later time. @returns A promise that settles when the queue becomes empty. */ async onEmpty() { c(this, x).size !== 0 && await g(this, b, fe).call(this, "empty"); } /** @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`. If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item. Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation. */ async onSizeLessThan(e) { c(this, x).size < e || await g(this, b, fe).call(this, "next", () => c(this, x).size < e); } /** The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. */ async onIdle() { c(this, A) === 0 && c(this, x).size === 0 || await g(this, b, fe).call(this, "idle"); } /** Size of the queue, the number of queued items waiting to run. */ get size() { return c(this, x).size; } /** Size of the queue, filtered by the given options. For example, this can be used to find the number of items remaining in the queue with a specific priority level. */ sizeBy(e) { return c(this, x).filter(e).length; } /** Number of running items (no longer in the queue). */ get pending() { return c(this, A); } /** Whether the queue is currently paused. */ get isPaused() { return c(this, U); } } Z = new WeakMap(), ee = new WeakMap(), F = new WeakMap(), oe = new WeakMap(), te = new WeakMap(), ce = new WeakMap(), E = new WeakMap(), se = new WeakMap(), x = new WeakMap(), le = new WeakMap(), A = new WeakMap(), ae = new WeakMap(), U = new WeakMap(), ue = new WeakMap(), b = new WeakSet(), He = function() { return c(this, ee) || c(this, F) < c(this, oe); }, je = function() { return c(this, A) < c(this, ae); }, Qe = function() { Y(this, A)._--, g(this, b, de).call(this), this.emit("next"); }, Ve = function() { g(this, b, Me).call(this), g(this, b, be).call(this), f(this, se, void 0); }, Ke = function() { const e = Date.now(); if (c(this, E) === void 0) { const s = c(this, ce) - e; if (s < 0) f(this, F, c(this, Z) ? c(this, A) : 0); else return c(this, se) === void 0 && f(this, se, setTimeout(() => { g(this, b, Ve).call(this); }, s)), !0; } return !1; }, de = function() { if (c(this, x).size === 0) return c(this, E) && clearInterval(c(this, E)), f(this, E, void 0), this.emit("empty"), c(this, A) === 0 && this.emit("idle"), !1; if (!c(this, U)) { const e = !c(this, b, Ke); if (c(this, b, He) && c(this, b, je)) { const s = c(this, x).dequeue(); return s ? (this.emit("active"), s(), e && g(this, b, be).call(this), !0) : !1; } } return !1; }, be = function() { c(this, ee) || c(this, E) !== void 0 || (f(this, E, setInterval(() => { g(this, b, Me).call(this); }, c(this, te))), f(this, ce, Date.now() + c(this, te))); }, Me = function() { c(this, F) === 0 && c(this, A) === 0 && c(this, E) && (clearInterval(c(this, E)), f(this, E, void 0)), f(this, F, c(this, Z) ? c(this, A) : 0), g(this, b, pe).call(this); }, /** Executes all queued functions until it reaches the limit. */ pe = function() { for (; g(this, b, de).call(this); ) ; }, Ye = async function(e) { return new Promise((s, a) => { e.addEventListener( "abort", () => { a(new ze("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, k, I, D, he, H, w, ke, L, We, Ie, Te, ve, Ge, $e; class xe extends Map { /** Simple ["Least Recently Used" (LRU) cache](https://en.m.wikipedia.org/wiki/Cache_replacement_policies#Least_Recently_Used_.28LRU.29). The instance is an [`Iterable`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols) of `[key, value]` pairs so you can use it directly in a [`for…of`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of) loop. */ constructor(e) { super(); M(this, w); M(this, S, 0); M(this, k, /* @__PURE__ */ new Map()); M(this, I, /* @__PURE__ */ new Map()); M(this, D); M(this, he); /** Called right before an item is evicted from the cache. Useful for side effects or for items like object URLs that need explicit cleanup (`revokeObjectURL`). */ M(this, H); 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"); f(this, D, e.maxSize), f(this, he, e.maxAge || Number.POSITIVE_INFINITY), f(this, H, e.onEviction); } // For tests. get __oldCache() { return c(this, I); } /** Get an item. @returns The stored item or `undefined`. */ get(e) { if (c(this, k).has(e)) { const s = c(this, k).get(e); return g(this, w, Ie).call(this, e, s); } if (c(this, I).has(e)) { const s = c(this, I).get(e); if (g(this, w, L).call(this, e, s) === !1) return g(this, w, Ge).call(this, e, s), s.value; } } /** Set an item. Returns the instance. Individual expiration of an item can be specified with the `maxAge` option. If not specified, the global `maxAge` value will be used in case it is specified in the constructor, otherwise the item will never expire. @returns The list instance. */ set(e, s, a = {}) { const { maxAge: r = c(this, he) } = a, i = typeof r == "number" && r !== Number.POSITIVE_INFINITY ? Date.now() + r : void 0; return c(this, k).has(e) ? c(this, k).set(e, { value: s, expiry: i }) : g(this, w, ve).call(this, e, { value: s, expiry: i }), this; } has(e) { return c(this, k).has(e) ? !g(this, w, L).call(this, e, c(this, k).get(e)) : c(this, I).has(e) ? !g(this, w, L).call(this, e, c(this, I).get(e)) : !1; } peek(e) { if (c(this, k).has(e)) return g(this, w, Te).call(this, e, c(this, k)); if (c(this, I).has(e)) return g(this, w, Te).call(this, e, c(this, I)); } delete(e) { const s = c(this, k).delete(e); return s && Y(this, S)._--, c(this, I).delete(e) || s; } clear() { c(this, k).clear(), c(this, I).clear(), f(this, S, 0); } /** Update the `maxSize` in-place, discarding items as necessary. Insertion order is mostly preserved, though this is not a strong guarantee. Useful for on-the-fly tuning of cache sizes in live systems. */ resize(e) { if (!(e && e > 0)) throw new TypeError("`maxSize` must be a number greater than 0"); const s = [...g(this, w, $e).call(this)], a = s.length - e; a < 0 ? (f(this, k, new Map(s)), f(this, I, /* @__PURE__ */ new Map()), f(this, S, s.length)) : (a > 0 && g(this, w, ke).call(this, s.slice(0, a)), f(this, I, new Map(s.slice(a))), f(this, k, /* @__PURE__ */ new Map()), f(this, S, 0)), f(this, D, e); } /** Iterable for all the keys. */ *keys() { for (const [e] of this) yield e; } /** Iterable for all the values. */ *values() { for (const [, e] of this) yield e; } *[Symbol.iterator]() { for (const e of c(this, k)) { const [s, a] = e; g(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, k).has(s) || g(this, w, L).call(this, s, a) === !1 && (yield [s, a.value]); } } /** Iterable for all entries, starting with the newest (descending in recency). */ *entriesDescending() { let e = [...c(this, k)]; for (let s = e.length - 1; s >= 0; --s) { const a = e[s], [r, i] = a; g(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, k).has(r) || g(this, w, L).call(this, r, i) === !1 && (yield [r, i.value]); } } /** Iterable for all entries, starting with the oldest (ascending in recency). */ *entriesAscending() { for (const [e, s] of g(this, w, $e).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, k).has(s) || e++; return Math.min(c(this, S) + e, c(this, D)); } get maxSize() { return c(this, D); } 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(), k = new WeakMap(), I = new WeakMap(), D = new WeakMap(), he = new WeakMap(), H = new WeakMap(), w = new WeakSet(), ke = function(e) { if (typeof c(this, H) == "function") for (const [s, a] of e) c(this, H).call(this, s, a.value); }, L = function(e, s) { return typeof s.expiry == "number" && s.expiry <= Date.now() ? (typeof c(this, H) == "function" && c(this, H).call(this, e, s.value), this.delete(e)) : !1; }, We = function(e, s) { if (g(this, w, L).call(this, e, s) === !1) return s.value; }, Ie = function(e, s) { return s.expiry ? g(this, w, We).call(this, e, s) : s.value; }, Te = function(e, s) { const a = s.get(e); return g(this, w, Ie).call(this, e, a); }, ve = function(e, s) { c(this, k).set(e, s), Y(this, S)._++, c(this, S) >= c(this, D) && (f(this, S, 0), g(this, w, ke).call(this, c(this, I)), f(this, I, c(this, k)), f(this, k, /* @__PURE__ */ new Map())); }, Ge = function(e, s) { c(this, I).delete(e), g(this, w, ve).call(this, e, s); }, $e = function* () { for (const e of c(this, I)) { const [s, a] = e; c(this, k).has(s) || g(this, w, L).call(this, s, a) === !1 && (yield e); } for (const e of c(this, k)) { const [s, a] = e; g(this, w, L).call(this, s, a) === !1 && (yield e); } }; function Et(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 At(n) { return Et(n); } class St extends Error { constructor(t) { super(t), this.name = "TimeoutError"; } } class Lt extends Error { constructor(t) { super(), this.name = "AbortError", this.message = t; } } const Ne = (n) => globalThis.DOMException === void 0 ? new Lt(n) : new DOMException(n), Re = (n) => { const t = ( // @ts-ignore n.reason === void 0 ? Ne("This operation was aborted.") : ( // @ts-ignore n.reason ) ); return t instanceof Error ? t : Ne(t); }; function _s(n, t) { const { milliseconds: e, fallback: s, message: a, customTimers: r = { setTimeout, clearTimeout } } = t; let i; const l = new Promise((h, m) => { 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 && m(Re(p)), p.addEventListener("abort", () => { m(Re(p)); }); } if (e === Number.POSITIVE_INFINITY) { n.then(h, m); return; } const y = new St(); i = r.setTimeout.call( void 0, () => { if (s) { try { h(s()); } catch (p) { m(p); } return; } typeof n.cancel == "function" && n.cancel(), a === !1 ? h() : a instanceof Error ? m(a) : (y.message = a ?? `Promise timed out after ${e} milliseconds`, m(y)); }, e ), (async () => { try { h(await n); } catch (p) { m(p); } })(); }).finally(() => { l.clear(); }); return l.clear = () => { r.clearTimeout.call(void 0, i), i = void 0; }, l; } function Ot() { return new _e({ store: new xe({ maxSize: 1e4 }) }); } var _ = /* @__PURE__ */ ((n) => (n.Text = "text", n.Image = "image", n.Audio = "audio", n.Video = "video", n.File = "file", n.Unknown = "unknown", n))(_ || {}); class me { 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: m = "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 = Be(m), this.getMessageById = y ?? this.defaultGetMessageById, this.upsertMessage = p ?? this.defaultUpsertMessage, h ? this.messageStore = h : this.messageStore = new _e({ store: new xe({ maxSize: 1e4 }) }); } async sendMessage(t, e = {}) { const { sessionId: s, conversationId: a, parentMessageId: r, messageId: i = re(), ...o } = e, l = { sessionId: s, conversationId: a, id: i, parentMessageId: r, role: "user", type: "text", text: t, files: [] }, h = { sessionId: s, conversationId: a, id: re(), 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, m = 0; do { const p = h.reduce((z, P) => { switch (P.role) { case "system": return z.concat([`Instructions: ${P.content}`]); case "user": return z.concat([`${a}: ${P.content}`]); default: return z.concat([`${r}: ${P.content}`]); } }, []).join(` `), v = await this.getTokenCount(p), T = v <= i; if (p && !T || (o = h, m = v, !T) || !e) break; const C = await this.getMessageById(e); if (!C) break; const K = C.role || "user"; h = h.slice(0, l).concat([ { role: K, content: C.text }, ...h.slice(l) ]), e = C.parentMessageId; } while (!0); const y = Math.max( 1, Math.min(this.maxModelTokens - m, this.maxResponseTokens) ); return { messages: o, maxTokens: y, numTokens: m }; } 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 zt extends me { constructor(e = {}) { const { debug: s, chatParams: a, maxModelTokens: r, maxResponseTokens: i, messageStore: o, userLabel: l, assistantLabel: h, encoding: m, getMessageById: y, upsertMessage: p, systemMessage: v, ...T } = e; super({ debug: s, chatParams: { model: "gpt-3.5-turbo", temperature: 0.8, top_p: 1, ...a }, maxModelTokens: r, maxResponseTokens: i, messageStore: o, systemMessage: v, userLabel: l, assistantLabel: h, encoding: m, getMessageById: y, upsertMessage: p }); u(this, "api"); this.api = new ct(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 Nt = Be("cl100k_base"), Rt = "ernie-bot", Ut = "User", qt = "ERNIE Bot"; class Bt { 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 = Rt, ...l } = t; this.api = new ut({ ...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 _e({ store: new xe({ maxSize: 1e4 }) }); } /** * Sends a message to the OpenAI chat completions endpoint, waits for the response * to resolve, and returns the response. * * If you want your response to have historical context, you must provide a valid `parentMessageId`. * * If you want to receive a stream of partial responses, use `opts.onProgress`. * * Set `debug: true` in the `ChatGPTAPI` constructor to log more info on the full prompt sent to the OpenAI chat completions API. You can override the `systemMessage` in `opts` to customize the assistant's instructions. * * @param message - The prompt message to send * * @returns The response from ChatGPT */ async sendMessage(t, e = {}) { const { conversationId: s, parentMessageId: a, messageId: r = re(), ...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 } ), m = { role: "assistant", id: h.id, conversationId: s, parentMessageId: r, text: h.result, type: "text", files: [] }; return Promise.all([ this._upsertMessage(o), this._upsertMessage(m) ]).then(() => m); } async _buildMessages(t, e) { let { parentMessageId: s } = e; const a = Ut, r = qt, i = this._maxModelTokens - this._maxResponseTokens; let o = []; const l = o.length; let h = t ? o.concat([ { role: "user", content: t } ]) : o, m = 0; do { const p = h.reduce((z, P) => { switch (P.role) { case "system": return z.concat([`Instructions: ${P.content}`]); case "user": return z.concat([`${a}: ${P.content}`]); default: return z.concat([`${r}: ${P.content}`]); } }, []).join(` `), v = await this._getTokenCount(p), T = v <= i; if (p && !T || (o = h, m = v, !T) || !s) break; const C = await this._getMessageById(s); if (!C) break; const K = C.role || "user"; h = h.slice(0, l).concat([ { role: K, content: C.text, name: C.name }, ...h.slice(l) ]), s = C.parentMessageId; } while (!0); const y = Math.max( 1, Math.min(this._maxModelTokens - m, this._maxResponseTokens) ); return { messages: o, maxTokens: y, numTokens: m }; } async _getTokenCount(t) { return t = t.replace(/<\|endoftext\|>/g, ""), Nt.encode(t).length; } async _defaultGetMessageById(t) { return await this._messageStore.get(t); } async _defaultUpsertMessage(t) { await this._messageStore.set(t.id, t); } } const Ft = "claude-2"; class Dt extends Error { constructor() { super(...arguments); u(this, "statusCode"); u(this, "statusText"); } } class Ht { 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 = Ft, 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 = re(), 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: [] }, m = 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: re(), conversationId: l, parentMessageId: h.id, text: m, 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 Dt(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 jt extends me { constructor(e = {}) { const { debug: s, systemMessage: a, chatParams: r, maxModelTokens: i, maxResponseTokens: o, messageStore: l, userLabel: h, assistantLabel: m, encoding: y, getMessageById: p, upsertMessage: v, ...T } = e; super({ debug: s, systemMessage: a, chatParams: { model: "hunyuan", temperature: 0.8, top_p: 1, ...r }, maxModelTokens: i, maxResponseTokens: o, messageStore: l, userLabel: h, assistantLabel: m, encoding: y, getMessageById: p, upsertMessage: v }); u(this, "api"); this.api = new ht(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 Qt extends me { constructor(e = {}) { const { debug: s, systemMessage: a, chatParams: r, maxModelTokens: i, maxResponseTokens: o, messageStore: l, userLabel: h, assistantLabel: m, encoding: y, getMessageById: p, upsertMessage: v, ...T } = e; super({ debug: s, systemMessage: a, chatParams: { model: "abab5-chat", temperature: 0.8, top_p: 1, ...r }, maxModelTokens: i, maxResponseTokens: o, messageStore: l, userLabel: h, assistantLabel: m, encoding: y, getMessageById: p, upsertMessage: v }); u(this, "api"); this.api = new mt(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 Vt extends me { constructor(e = {}) { const { debug: s, systemMessage: a, chatParams: r, maxModelTokens: i, maxResponseTokens: o, messageStore: l, userLabel: h, assistantLabel: m, encoding: y, getMessageById: p, upsertMessage: v, ...T } = e; super({ debug: s, systemMessage: a, chatParams: { model: "qwen-max", temperature: 0.8, ...r }, maxModelTokens: i, maxResponseTokens: o, messageStore: l, userLabel: h, assistantLabel: m, encoding: y, getMessageById: p, upsertMessage: v }); u(this, "api"); this.api = new dt(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 Kt extends me { constructor(e = {}) { const { debug: s, systemMessage: a, chatParams: r, maxModelTokens: i, maxResponseTokens: o, messageStore: l, userLabel: h, assistantLabel: m, encoding: y, getMessageById: p, upsertMessage: v, ...T } = e; super({ debug: s, systemMessage: a, chatParams: { model: "spark-3", temperature: 0.8, top_p: 1, ...r }, maxModelTokens: i, maxResponseTokens: o, messageStore: l, userLabel: h, assistantLabel: m, encoding: y, getMessageById: p, upsertMessage: v }); u(this, "api"); this.api = new pt(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 xs { constructor(t) { u(this, "name", "claude-web-api"); u(this, "human_name"