koishi-plugin-oni-sync-bot 0.10.1 → 0.11.0
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.js +1 -1
- package/lib/config.d.ts +47 -1
- package/lib/index.js +1481 -30
- package/lib/plugins/aiQueryCommands.d.ts +82 -0
- package/lib/plugins/databaseExtension.d.ts +18 -0
- package/lib/plugins/syncCommands.d.ts +36 -5
- package/lib/plugins/todoList.d.ts +15 -1
- package/lib/plugins/updateCommands.d.ts +12 -1
- package/lib/services/aiMemory.d.ts +50 -0
- package/lib/services/aiService.d.ts +54 -0
- package/lib/services/vectorService.d.ts +84 -0
- package/lib/services/wikiBotService.d.ts +7 -0
- package/lib/sync/pageSync.d.ts +10 -0
- package/lib/sync/textSync.d.ts +118 -0
- package/lib/utils/renderText.d.ts +47 -0
- package/lib/utils/tools.d.ts +8 -1
- package/package.json +7 -4
- package/readme.md +206 -9
package/lib/index.js
CHANGED
|
@@ -35,7 +35,7 @@ __export(src_exports, {
|
|
|
35
35
|
name: () => name
|
|
36
36
|
});
|
|
37
37
|
module.exports = __toCommonJS(src_exports);
|
|
38
|
-
var
|
|
38
|
+
var import_path2 = require("path");
|
|
39
39
|
|
|
40
40
|
// src/config.ts
|
|
41
41
|
var import_koishi = require("koishi");
|
|
@@ -60,11 +60,70 @@ var NotifyConfig = import_koishi.Schema.object({
|
|
|
60
60
|
var ScheduleConfig = import_koishi.Schema.object({
|
|
61
61
|
updateCron: import_koishi.Schema.string().description("页面缓存自动更新 cron 表达式(默认每天凌晨 2 点)").default("0 2 * * *")
|
|
62
62
|
});
|
|
63
|
+
var WikiTextConfig = import_koishi.Schema.object({
|
|
64
|
+
textSyncOnChange: import_koishi.Schema.boolean().description("页面同步成功后,自动抓取 BWiki 渲染文本并写入向量库").default(true),
|
|
65
|
+
textApiUrl: import_koishi.Schema.string().description(
|
|
66
|
+
"BWiki 的 api.php 地址;留空则由 bwiki_site 自动拼接为 https://<bwiki_site>/api.php"
|
|
67
|
+
).default(""),
|
|
68
|
+
textTableMode: import_koishi.Schema.union([
|
|
69
|
+
import_koishi.Schema.const("flatten").description(
|
|
70
|
+
"信息框抽成「标签:值」,正文表格压平成「单元格 | 单元格」(保留耗电/产热/材料等数值)"
|
|
71
|
+
),
|
|
72
|
+
import_koishi.Schema.const("drop").description(
|
|
73
|
+
"丢弃全部表格(信息框里的关键数值也会一并丢失)"
|
|
74
|
+
)
|
|
75
|
+
]).description("正文表格处理方式").default("flatten"),
|
|
76
|
+
textMaxLength: import_koishi.Schema.natural().description("单页最多保留的纯文本字数(超出截断,防止超长页面撑爆内存)").default(2e4),
|
|
77
|
+
textSyncInterval: import_koishi.Schema.natural().description("批量抓取渲染文本时,每个页面之间的间隔(毫秒)").default(300)
|
|
78
|
+
});
|
|
79
|
+
var VectorConfig = import_koishi.Schema.object({
|
|
80
|
+
vectorEnabled: import_koishi.Schema.boolean().description("启用本地向量库(关闭后 .ai 退化为标题匹配的降级检索)").default(true),
|
|
81
|
+
vectorIndexPath: import_koishi.Schema.string().description("vectra 索引目录(相对 Koishi 工作目录)").default("data/oni-vector"),
|
|
82
|
+
embeddingModel: import_koishi.Schema.string().description("本地 Embedding 模型(transformers.js 的模型名或本地目录)").default("Xenova/bge-small-zh-v1.5"),
|
|
83
|
+
embeddingDtype: import_koishi.Schema.union([
|
|
84
|
+
import_koishi.Schema.const("q8").description("8bit 量化,最小最快(推荐 2G 内存服务器)"),
|
|
85
|
+
import_koishi.Schema.const("fp32").description("全精度,最准但更占内存"),
|
|
86
|
+
import_koishi.Schema.const("fp16").description("半精度"),
|
|
87
|
+
import_koishi.Schema.const("q4").description("4bit 量化,最小但精度略降")
|
|
88
|
+
]).description("Embedding 模型精度").default("q8"),
|
|
89
|
+
embeddingCacheDir: import_koishi.Schema.string().description("模型缓存目录(首次运行会自动下载模型)").default("data/oni-models"),
|
|
90
|
+
embeddingRemoteHost: import_koishi.Schema.string().description(
|
|
91
|
+
"模型下载源;默认使用 hf-mirror 镜像,留空则用官方 huggingface.co"
|
|
92
|
+
).default("https://hf-mirror.com"),
|
|
93
|
+
chunkSize: import_koishi.Schema.natural().description("单块文本的目标字数").default(350).min(80),
|
|
94
|
+
chunkOverlap: import_koishi.Schema.natural().description("相邻文本块的重叠字数").default(60),
|
|
95
|
+
maxChunksPerPage: import_koishi.Schema.natural().description(
|
|
96
|
+
"单页最多切分的块数(直接决定索引体积与内存占用,2G 机器建议 12~16)"
|
|
97
|
+
).default(16).min(1),
|
|
98
|
+
retrieveTopK: import_koishi.Schema.natural().description("检索时返回的文本块数量(建议 2-3)").default(3).min(1),
|
|
99
|
+
retrieveMinScore: import_koishi.Schema.number().description("检索结果的最低余弦相似度,低于该值视为无关").default(0.2).min(0).max(1),
|
|
100
|
+
queryInstruction: import_koishi.Schema.string().description("BGE 系列模型的查询指令前缀,用于提升检索命中率").default("为这个句子生成表示以用于检索相关文章:"),
|
|
101
|
+
embedBatchSize: import_koishi.Schema.natural().description("单次送入 Embedding 模型的文本条数(内存紧张时调小)").default(4).min(1)
|
|
102
|
+
});
|
|
103
|
+
var AiConfig = import_koishi.Schema.object({
|
|
104
|
+
aiEnabled: import_koishi.Schema.boolean().description("启用 .ai 问答命令").default(true),
|
|
105
|
+
deepseekApiKey: import_koishi.Schema.string().description("DeepSeek API Key(也可用环境变量 DEEPSEEK_API_KEY)").role("secret").default(""),
|
|
106
|
+
deepseekBaseUrl: import_koishi.Schema.string().description("DeepSeek API 地址").default("https://api.deepseek.com"),
|
|
107
|
+
deepseekModel: import_koishi.Schema.string().description("使用的模型").default("deepseek-chat"),
|
|
108
|
+
aiTemperature: import_koishi.Schema.number().description("采样温度,越低越保守(防幻觉建议 0~0.3)").default(0.2).min(0).max(2),
|
|
109
|
+
aiMaxTokens: import_koishi.Schema.natural().description("回答的最大 token 数").default(700),
|
|
110
|
+
aiTimeout: import_koishi.Schema.natural().description("调用 DeepSeek 的超时时间(毫秒)").default(6e4),
|
|
111
|
+
aiCooldown: import_koishi.Schema.natural().description("同一用户连续提问的冷却时间(秒)").default(5),
|
|
112
|
+
aiMaxQuestionLength: import_koishi.Schema.natural().description("问题最大长度(字符),超出直接拒绝").default(200),
|
|
113
|
+
aiMemoryTurns: import_koishi.Schema.natural().description("短期记忆保留的问答轮数(0 表示不记忆;建议 2~3)").default(2).max(5),
|
|
114
|
+
aiMemoryTtl: import_koishi.Schema.natural().description("短期记忆的过期时间(秒),超过则视为新话题").default(600),
|
|
115
|
+
aiChannelMemory: import_koishi.Schema.boolean().description(
|
|
116
|
+
"允许群内承接话题:用户自己没提问记录时,用群里上一条问答的语境回答「那它…」这类追问"
|
|
117
|
+
).default(true)
|
|
118
|
+
});
|
|
63
119
|
var Config = import_koishi.Schema.intersect([
|
|
64
120
|
AccountConfig,
|
|
65
121
|
SiteConfig,
|
|
66
122
|
NotifyConfig,
|
|
67
|
-
ScheduleConfig
|
|
123
|
+
ScheduleConfig,
|
|
124
|
+
WikiTextConfig,
|
|
125
|
+
VectorConfig,
|
|
126
|
+
AiConfig
|
|
68
127
|
]);
|
|
69
128
|
|
|
70
129
|
// src/services/wikiBotService.ts
|
|
@@ -227,6 +286,12 @@ function stripImagePrefix(fileName) {
|
|
|
227
286
|
return trimmed;
|
|
228
287
|
}
|
|
229
288
|
__name(stripImagePrefix, "stripImagePrefix");
|
|
289
|
+
function siteUrl(site) {
|
|
290
|
+
const trimmed = (site ?? "").trim().replace(/\/+$/, "");
|
|
291
|
+
if (!trimmed) return "";
|
|
292
|
+
return /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
|
|
293
|
+
}
|
|
294
|
+
__name(siteUrl, "siteUrl");
|
|
230
295
|
|
|
231
296
|
// src/utils/async.ts
|
|
232
297
|
var import_koishi3 = require("koishi");
|
|
@@ -517,9 +582,440 @@ var WikiBotService = class _WikiBotService extends import_koishi4.Service {
|
|
|
517
582
|
return proxy;
|
|
518
583
|
}
|
|
519
584
|
};
|
|
585
|
+
function tryGetBWikiBot(ctx) {
|
|
586
|
+
try {
|
|
587
|
+
const service = ctx.wikiBot;
|
|
588
|
+
if (!service || !service.isBWikiBotReady()) return void 0;
|
|
589
|
+
return service.getBWikiBot();
|
|
590
|
+
} catch {
|
|
591
|
+
return void 0;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
__name(tryGetBWikiBot, "tryGetBWikiBot");
|
|
520
595
|
|
|
521
|
-
// src/services/
|
|
596
|
+
// src/services/vectorService.ts
|
|
522
597
|
var import_koishi5 = require("koishi");
|
|
598
|
+
var import_path = require("path");
|
|
599
|
+
|
|
600
|
+
// src/utils/renderText.ts
|
|
601
|
+
var import_cheerio = require("cheerio");
|
|
602
|
+
var NOISE_SELECTOR = [
|
|
603
|
+
"script",
|
|
604
|
+
"style",
|
|
605
|
+
"noscript",
|
|
606
|
+
"iframe",
|
|
607
|
+
"svg",
|
|
608
|
+
"form",
|
|
609
|
+
"audio",
|
|
610
|
+
"video",
|
|
611
|
+
".mw-editsection",
|
|
612
|
+
".mw-jump-link",
|
|
613
|
+
".printfooter",
|
|
614
|
+
".catlinks",
|
|
615
|
+
".navbox",
|
|
616
|
+
".navbox-inner",
|
|
617
|
+
".vertical-navbox",
|
|
618
|
+
".sidebar",
|
|
619
|
+
".toc",
|
|
620
|
+
"#toc",
|
|
621
|
+
".metadata",
|
|
622
|
+
".ambox",
|
|
623
|
+
".noprint",
|
|
624
|
+
".reference",
|
|
625
|
+
".mw-collapsible-toggle",
|
|
626
|
+
".mw-empty-elt"
|
|
627
|
+
].join(",");
|
|
628
|
+
var NOISE_TABLE_SELECTOR = [
|
|
629
|
+
".navbox",
|
|
630
|
+
".vertical-navbox",
|
|
631
|
+
".sidebar",
|
|
632
|
+
".metadata",
|
|
633
|
+
".ambox"
|
|
634
|
+
].join(",");
|
|
635
|
+
var BLOCK_SELECTOR = "h1,h2,h3,h4,h5,h6,p,li,dt,dd,blockquote,pre";
|
|
636
|
+
var BOUNDARY_SEPARATORS = ["\n", "。", "!", "?", ";", ","];
|
|
637
|
+
function flattenInfobox($, box) {
|
|
638
|
+
const lines = [];
|
|
639
|
+
box.find(".mw-collapsible-toggle").remove();
|
|
640
|
+
box.find(".infobox-material-grid").remove();
|
|
641
|
+
const title = squashInline(box.find(".infobox-title").first().text());
|
|
642
|
+
if (title) lines.push(`【${title}】`);
|
|
643
|
+
box.find(".infobox-caption, .infobox-data-full").each((_, node) => {
|
|
644
|
+
const text = squashInline($(node).text());
|
|
645
|
+
if (text && text !== title) lines.push(text);
|
|
646
|
+
});
|
|
647
|
+
box.find(".infobox-group").each((_, group) => {
|
|
648
|
+
const groupNode = $(group);
|
|
649
|
+
const groupTitle = squashInline(
|
|
650
|
+
groupNode.find(".infobox-group-title").first().text()
|
|
651
|
+
);
|
|
652
|
+
const children = [];
|
|
653
|
+
groupNode.find(".infobox-group-child").each((__, child) => {
|
|
654
|
+
const childNode = $(child);
|
|
655
|
+
const label = squashInline(childNode.find(".infobox-th").first().text());
|
|
656
|
+
const value = squashInline(childNode.find(".infobox-td").first().text());
|
|
657
|
+
if (value) children.push(label ? `${label}:${value}` : value);
|
|
658
|
+
});
|
|
659
|
+
if (children.length > 0) {
|
|
660
|
+
lines.push(groupTitle ? `[${groupTitle}]` : "", ...children);
|
|
661
|
+
}
|
|
662
|
+
});
|
|
663
|
+
box.find("tr").each((_, tr) => {
|
|
664
|
+
const row = $(tr);
|
|
665
|
+
if (row.parents(".infobox-group").length) return;
|
|
666
|
+
if (row.find(".infobox-group, .infobox-group-child").length) return;
|
|
667
|
+
const label = squashInline(row.children("th").not(".infobox-title").text());
|
|
668
|
+
const values = row.children("td").filter(
|
|
669
|
+
(__, td) => !$(td).is(
|
|
670
|
+
".infobox-image-cell, .infobox-data-full, .infobox-group-cell"
|
|
671
|
+
)
|
|
672
|
+
).toArray().map((td) => squashInline($(td).text())).filter(Boolean);
|
|
673
|
+
if (label && values.length) {
|
|
674
|
+
for (const value of values) lines.push(`${label}:${value}`);
|
|
675
|
+
} else if (label && label.length <= 12) {
|
|
676
|
+
lines.push(label);
|
|
677
|
+
} else if (values.length) {
|
|
678
|
+
lines.push(...values);
|
|
679
|
+
}
|
|
680
|
+
});
|
|
681
|
+
return lines;
|
|
682
|
+
}
|
|
683
|
+
__name(flattenInfobox, "flattenInfobox");
|
|
684
|
+
function extractPlainText(html, options = {}) {
|
|
685
|
+
const { tableMode = "flatten", maxLength = 0 } = options;
|
|
686
|
+
if (!html) return "";
|
|
687
|
+
const $ = (0, import_cheerio.load)(html);
|
|
688
|
+
const root = $(".mw-parser-output").length ? $(".mw-parser-output").first() : $("body");
|
|
689
|
+
if (tableMode === "drop") {
|
|
690
|
+
root.find("table").remove();
|
|
691
|
+
} else {
|
|
692
|
+
root.find(".infobox").each((_, element) => {
|
|
693
|
+
const node = $(element);
|
|
694
|
+
node.replaceWith($("<p></p>").text(flattenInfobox($, node).join("\n")));
|
|
695
|
+
});
|
|
696
|
+
root.find("table").each((_, table) => {
|
|
697
|
+
const node = $(table);
|
|
698
|
+
if (node.is(NOISE_TABLE_SELECTOR)) {
|
|
699
|
+
node.remove();
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
const rows = [];
|
|
703
|
+
node.find("tr").each((__, tr) => {
|
|
704
|
+
const cells = [];
|
|
705
|
+
$(tr).find("th,td").each((___, cell) => {
|
|
706
|
+
const value = squashInline($(cell).text());
|
|
707
|
+
if (value) cells.push(value);
|
|
708
|
+
});
|
|
709
|
+
if (cells.length) rows.push(cells.join(" | "));
|
|
710
|
+
});
|
|
711
|
+
node.replaceWith($("<p></p>").text(rows.join("\n")));
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
root.find(NOISE_SELECTOR).remove();
|
|
715
|
+
const blocks = [];
|
|
716
|
+
root.find(BLOCK_SELECTOR).each((_, element) => {
|
|
717
|
+
const node = $(element);
|
|
718
|
+
const tag = "tagName" in element ? String(element.tagName).toLowerCase() : "";
|
|
719
|
+
const raw = tag === "li" || tag === "dt" || tag === "dd" ? node.clone().find("ul,ol,dl,table").remove().end().text() : node.text();
|
|
720
|
+
const text = squash(raw);
|
|
721
|
+
if (!text) return;
|
|
722
|
+
if (/^h[1-6]$/.test(tag)) {
|
|
723
|
+
blocks.push(`${"#".repeat(Number(tag[1]))} ${text}`);
|
|
724
|
+
} else {
|
|
725
|
+
blocks.push(text);
|
|
726
|
+
}
|
|
727
|
+
});
|
|
728
|
+
let plain = blocks.length ? blocks.join("\n") : squash(root.text());
|
|
729
|
+
plain = squash(plain);
|
|
730
|
+
if (maxLength > 0 && plain.length > maxLength) {
|
|
731
|
+
plain = plain.slice(0, maxLength).trimEnd();
|
|
732
|
+
}
|
|
733
|
+
return plain;
|
|
734
|
+
}
|
|
735
|
+
__name(extractPlainText, "extractPlainText");
|
|
736
|
+
function chunkText(text, options = {}) {
|
|
737
|
+
const source = squash(text ?? "");
|
|
738
|
+
if (!source) return [];
|
|
739
|
+
const size = Math.max(80, Math.floor(options.size ?? 350));
|
|
740
|
+
const overlap = Math.max(
|
|
741
|
+
0,
|
|
742
|
+
Math.min(Math.floor(options.overlap ?? 60), Math.floor(size / 2))
|
|
743
|
+
);
|
|
744
|
+
const maxChunks = Math.max(1, Math.floor(options.maxChunks ?? 24));
|
|
745
|
+
const chunks = [];
|
|
746
|
+
let cursor = 0;
|
|
747
|
+
while (cursor < source.length && chunks.length < maxChunks) {
|
|
748
|
+
let end = Math.min(source.length, cursor + size);
|
|
749
|
+
if (end < source.length) {
|
|
750
|
+
end = cursor + findBoundary(source.slice(cursor, end), size);
|
|
751
|
+
}
|
|
752
|
+
const piece = source.slice(cursor, end).trim();
|
|
753
|
+
if (piece) chunks.push({ index: chunks.length, text: piece });
|
|
754
|
+
if (end >= source.length) break;
|
|
755
|
+
let next = end - overlap;
|
|
756
|
+
if (next <= cursor) next = end;
|
|
757
|
+
const window = source.slice(next, end);
|
|
758
|
+
const lineBreak = window.indexOf("\n");
|
|
759
|
+
if (lineBreak >= 0) next += lineBreak + 1;
|
|
760
|
+
while (next < source.length && /\s/.test(source[next])) next++;
|
|
761
|
+
cursor = next;
|
|
762
|
+
}
|
|
763
|
+
return chunks;
|
|
764
|
+
}
|
|
765
|
+
__name(chunkText, "chunkText");
|
|
766
|
+
function squash(text) {
|
|
767
|
+
return text.replace(/\u00a0/g, " ").split(/\r?\n/).map((line) => squashInline(line)).filter(Boolean).join("\n").trim();
|
|
768
|
+
}
|
|
769
|
+
__name(squash, "squash");
|
|
770
|
+
function squashInline(text) {
|
|
771
|
+
return text.replace(/[ \t\u3000]+/g, " ").trim();
|
|
772
|
+
}
|
|
773
|
+
__name(squashInline, "squashInline");
|
|
774
|
+
function findBoundary(slice, size) {
|
|
775
|
+
const minimum = Math.floor(size / 2);
|
|
776
|
+
for (const separator of BOUNDARY_SEPARATORS) {
|
|
777
|
+
const at = slice.lastIndexOf(separator);
|
|
778
|
+
if (at >= minimum) return at + 1;
|
|
779
|
+
}
|
|
780
|
+
return slice.length;
|
|
781
|
+
}
|
|
782
|
+
__name(findBoundary, "findBoundary");
|
|
783
|
+
|
|
784
|
+
// src/services/vectorService.ts
|
|
785
|
+
var VectorService = class extends import_koishi5.Service {
|
|
786
|
+
static {
|
|
787
|
+
__name(this, "VectorService");
|
|
788
|
+
}
|
|
789
|
+
static inject = [];
|
|
790
|
+
settings;
|
|
791
|
+
indexPromise;
|
|
792
|
+
embedderPromise;
|
|
793
|
+
/** 串行化 Embedding / 索引写入,避免并发推理 */
|
|
794
|
+
queue = Promise.resolve();
|
|
795
|
+
constructor(ctx, config) {
|
|
796
|
+
super(ctx, "vector", true);
|
|
797
|
+
this.settings = config;
|
|
798
|
+
}
|
|
799
|
+
get enabled() {
|
|
800
|
+
return this.settings.vectorEnabled;
|
|
801
|
+
}
|
|
802
|
+
get indexPath() {
|
|
803
|
+
return (0, import_path.resolve)(process.cwd(), this.settings.vectorIndexPath);
|
|
804
|
+
}
|
|
805
|
+
// ------------------------------------------------------------ 检索 / 写入
|
|
806
|
+
/**
|
|
807
|
+
* 把一个页面的纯文本切块、向量化并写入索引(同标题的旧块会被替换)。
|
|
808
|
+
* @returns 写入的文本块数量
|
|
809
|
+
*/
|
|
810
|
+
async indexPage(page) {
|
|
811
|
+
if (!this.enabled) return 0;
|
|
812
|
+
return this.enqueue(async () => {
|
|
813
|
+
const chunks = chunkText(page.text, {
|
|
814
|
+
size: this.settings.chunkSize,
|
|
815
|
+
overlap: this.settings.chunkOverlap,
|
|
816
|
+
maxChunks: this.settings.maxChunksPerPage
|
|
817
|
+
});
|
|
818
|
+
const index = await this.getIndex();
|
|
819
|
+
await this.deleteChunks(index, page.id);
|
|
820
|
+
if (chunks.length === 0) return 0;
|
|
821
|
+
const items = [];
|
|
822
|
+
const batchSize = Math.max(1, this.settings.embedBatchSize);
|
|
823
|
+
for (let start = 0; start < chunks.length; start += batchSize) {
|
|
824
|
+
const batch = chunks.slice(start, start + batchSize);
|
|
825
|
+
const vectors = await this.embed(batch.map((chunk) => chunk.text));
|
|
826
|
+
batch.forEach((chunk, offset) => {
|
|
827
|
+
const vector = vectors[offset];
|
|
828
|
+
if (!vector) return;
|
|
829
|
+
items.push({
|
|
830
|
+
id: `${page.id}#${chunk.index}`,
|
|
831
|
+
vector,
|
|
832
|
+
metadata: {
|
|
833
|
+
documentId: page.id,
|
|
834
|
+
title: page.title,
|
|
835
|
+
url: page.url,
|
|
836
|
+
chunkIndex: chunk.index,
|
|
837
|
+
text: chunk.text
|
|
838
|
+
}
|
|
839
|
+
});
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
if (items.length === 0) return 0;
|
|
843
|
+
await index.batchInsertItems(items);
|
|
844
|
+
logger.debug(`[vector] ${page.title}:写入 ${items.length} 个文本块`);
|
|
845
|
+
return items.length;
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
/** 删除某个页面的全部文本块 */
|
|
849
|
+
async removePage(documentId) {
|
|
850
|
+
if (!this.enabled) return;
|
|
851
|
+
await this.enqueue(async () => {
|
|
852
|
+
const index = await this.getIndex();
|
|
853
|
+
await this.deleteChunks(index, documentId);
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
/** 语义检索:返回最相关的若干文本块(同一页面最多取 2 块,保证覆盖面) */
|
|
857
|
+
async search(question, topK = this.settings.retrieveTopK) {
|
|
858
|
+
const keyword = question.trim();
|
|
859
|
+
if (!this.enabled || !keyword) return [];
|
|
860
|
+
const index = await this.getIndex();
|
|
861
|
+
if (!await index.isIndexCreated()) return [];
|
|
862
|
+
const stats = await index.getIndexStats();
|
|
863
|
+
if (stats.items === 0) return [];
|
|
864
|
+
const query = `${this.settings.queryInstruction}${keyword}`.trim();
|
|
865
|
+
const [vector] = await this.enqueue(() => this.embed([query]));
|
|
866
|
+
if (!vector) return [];
|
|
867
|
+
const candidates = await index.queryItems(
|
|
868
|
+
vector,
|
|
869
|
+
keyword,
|
|
870
|
+
Math.max(topK * 4, topK),
|
|
871
|
+
void 0,
|
|
872
|
+
false
|
|
873
|
+
);
|
|
874
|
+
const hits = [];
|
|
875
|
+
const perDocument = /* @__PURE__ */ new Map();
|
|
876
|
+
for (const candidate of candidates) {
|
|
877
|
+
if (candidate.score < this.settings.retrieveMinScore) continue;
|
|
878
|
+
const { documentId, title, url, text } = candidate.item.metadata;
|
|
879
|
+
if (!documentId || !text) continue;
|
|
880
|
+
const used = perDocument.get(documentId) ?? 0;
|
|
881
|
+
if (used >= 2) continue;
|
|
882
|
+
perDocument.set(documentId, used + 1);
|
|
883
|
+
hits.push({
|
|
884
|
+
documentId,
|
|
885
|
+
title: title || documentId,
|
|
886
|
+
url: url || "",
|
|
887
|
+
text,
|
|
888
|
+
score: candidate.score
|
|
889
|
+
});
|
|
890
|
+
if (hits.length >= topK) break;
|
|
891
|
+
}
|
|
892
|
+
return hits;
|
|
893
|
+
}
|
|
894
|
+
/** 索引现状,供 `.ai.status` 与日志使用 */
|
|
895
|
+
async stats() {
|
|
896
|
+
if (!this.enabled) {
|
|
897
|
+
return { enabled: false, path: this.indexPath, items: 0, bytes: 0 };
|
|
898
|
+
}
|
|
899
|
+
const index = await this.getIndex();
|
|
900
|
+
const created = await index.isIndexCreated();
|
|
901
|
+
const items = created ? (await index.getIndexStats()).items : 0;
|
|
902
|
+
let bytes = 0;
|
|
903
|
+
try {
|
|
904
|
+
const { stat } = await import("node:fs/promises");
|
|
905
|
+
bytes = (await stat((0, import_path.resolve)(index.folderPath, index.indexName))).size;
|
|
906
|
+
} catch {
|
|
907
|
+
bytes = 0;
|
|
908
|
+
}
|
|
909
|
+
return { enabled: true, path: index.folderPath, items, bytes };
|
|
910
|
+
}
|
|
911
|
+
/** 清空索引(重建前调用) */
|
|
912
|
+
async reset() {
|
|
913
|
+
if (!this.enabled) return;
|
|
914
|
+
await this.enqueue(async () => {
|
|
915
|
+
const index = await this.getIndex();
|
|
916
|
+
await index.deleteIndex();
|
|
917
|
+
this.indexPromise = void 0;
|
|
918
|
+
logger.info(`[vector] 索引已清空:${this.indexPath}`);
|
|
919
|
+
});
|
|
920
|
+
}
|
|
921
|
+
/** 插件卸载时释放模型,避免热重载反复占用内存 */
|
|
922
|
+
async stop() {
|
|
923
|
+
this.indexPromise = void 0;
|
|
924
|
+
const embedder = this.embedderPromise;
|
|
925
|
+
this.embedderPromise = void 0;
|
|
926
|
+
if (!embedder) return;
|
|
927
|
+
try {
|
|
928
|
+
const extractor = await embedder;
|
|
929
|
+
await extractor.dispose?.();
|
|
930
|
+
} catch (error) {
|
|
931
|
+
logger.debug(`[vector] 释放 Embedding 模型失败:${getErrorMessage(error)}`);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
// ---------------------------------------------------------------- 内部实现
|
|
935
|
+
enqueue(task) {
|
|
936
|
+
const result = this.queue.then(task, task);
|
|
937
|
+
this.queue = result.then(
|
|
938
|
+
() => void 0,
|
|
939
|
+
() => void 0
|
|
940
|
+
);
|
|
941
|
+
return result;
|
|
942
|
+
}
|
|
943
|
+
getIndex() {
|
|
944
|
+
if (!this.indexPromise) {
|
|
945
|
+
const promise = (async () => {
|
|
946
|
+
const { LocalIndex } = await import("vectra");
|
|
947
|
+
const index = new LocalIndex(this.indexPath);
|
|
948
|
+
if (!await index.isIndexCreated()) {
|
|
949
|
+
await index.createIndex({ version: 1 });
|
|
950
|
+
logger.info(`[vector] 已创建向量索引:${index.folderPath}`);
|
|
951
|
+
}
|
|
952
|
+
return index;
|
|
953
|
+
})();
|
|
954
|
+
this.indexPromise = promise;
|
|
955
|
+
promise.catch(() => {
|
|
956
|
+
if (this.indexPromise === promise) this.indexPromise = void 0;
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
return this.indexPromise;
|
|
960
|
+
}
|
|
961
|
+
getEmbedder() {
|
|
962
|
+
if (!this.embedderPromise) {
|
|
963
|
+
const promise = (async () => {
|
|
964
|
+
const transformers = await import("@huggingface/transformers");
|
|
965
|
+
const { env } = transformers;
|
|
966
|
+
if (this.settings.embeddingRemoteHost) {
|
|
967
|
+
env.remoteHost = this.settings.embeddingRemoteHost;
|
|
968
|
+
}
|
|
969
|
+
if (this.settings.embeddingCacheDir) {
|
|
970
|
+
env.cacheDir = (0, import_path.resolve)(process.cwd(), this.settings.embeddingCacheDir);
|
|
971
|
+
}
|
|
972
|
+
logger.info(
|
|
973
|
+
`[vector] 加载 Embedding 模型 ${this.settings.embeddingModel}(首次运行会自动下载)`
|
|
974
|
+
);
|
|
975
|
+
const extractor = await transformers.pipeline(
|
|
976
|
+
"feature-extraction",
|
|
977
|
+
this.settings.embeddingModel,
|
|
978
|
+
{
|
|
979
|
+
device: "cpu",
|
|
980
|
+
dtype: this.settings.embeddingDtype
|
|
981
|
+
}
|
|
982
|
+
);
|
|
983
|
+
logger.info("[vector] Embedding 模型加载完成");
|
|
984
|
+
return extractor;
|
|
985
|
+
})();
|
|
986
|
+
this.embedderPromise = promise;
|
|
987
|
+
promise.catch(() => {
|
|
988
|
+
if (this.embedderPromise === promise) this.embedderPromise = void 0;
|
|
989
|
+
});
|
|
990
|
+
}
|
|
991
|
+
return this.embedderPromise;
|
|
992
|
+
}
|
|
993
|
+
async embed(texts) {
|
|
994
|
+
if (texts.length === 0) return [];
|
|
995
|
+
const extractor = await this.getEmbedder();
|
|
996
|
+
const output = await extractor(texts, {
|
|
997
|
+
pooling: "mean",
|
|
998
|
+
normalize: true
|
|
999
|
+
});
|
|
1000
|
+
const [batch, dimension] = output.dims;
|
|
1001
|
+
const data = output.data;
|
|
1002
|
+
const vectors = [];
|
|
1003
|
+
for (let i = 0; i < batch; i++) {
|
|
1004
|
+
vectors.push(Array.from(data.subarray(i * dimension, (i + 1) * dimension)));
|
|
1005
|
+
}
|
|
1006
|
+
return vectors;
|
|
1007
|
+
}
|
|
1008
|
+
async deleteChunks(index, documentId) {
|
|
1009
|
+
const existing = await index.listItemsByMetadata({
|
|
1010
|
+
documentId
|
|
1011
|
+
});
|
|
1012
|
+
if (existing.length === 0) return;
|
|
1013
|
+
await index.deleteItems(existing.map((item) => item.id));
|
|
1014
|
+
}
|
|
1015
|
+
};
|
|
1016
|
+
|
|
1017
|
+
// src/services/consoleLogProvider.ts
|
|
1018
|
+
var import_koishi6 = require("koishi");
|
|
523
1019
|
var import_plugin_console = require("@koishijs/plugin-console");
|
|
524
1020
|
var MAX_RECORDS = 1e3;
|
|
525
1021
|
var LOG_SCOPE = "oni-sync";
|
|
@@ -558,10 +1054,10 @@ var ConsoleLogProvider = class {
|
|
|
558
1054
|
ctx.get("console")?.patch("onilogs", this.buffer);
|
|
559
1055
|
}, "record")
|
|
560
1056
|
};
|
|
561
|
-
|
|
1057
|
+
import_koishi6.Logger.targets.push(target);
|
|
562
1058
|
ctx.on("dispose", () => {
|
|
563
|
-
const index =
|
|
564
|
-
if (index > -1)
|
|
1059
|
+
const index = import_koishi6.Logger.targets.indexOf(target);
|
|
1060
|
+
if (index > -1) import_koishi6.Logger.targets.splice(index, 1);
|
|
565
1061
|
});
|
|
566
1062
|
}
|
|
567
1063
|
};
|
|
@@ -581,6 +1077,19 @@ var DatabaseExtension = class {
|
|
|
581
1077
|
contributor: "string",
|
|
582
1078
|
change_time: "string"
|
|
583
1079
|
});
|
|
1080
|
+
ctx.model.extend(
|
|
1081
|
+
"wikitexts",
|
|
1082
|
+
{
|
|
1083
|
+
id: "string",
|
|
1084
|
+
title: "string",
|
|
1085
|
+
pageid: "integer",
|
|
1086
|
+
revid: "integer",
|
|
1087
|
+
hash: "string",
|
|
1088
|
+
text: "text",
|
|
1089
|
+
updated_at: "string"
|
|
1090
|
+
},
|
|
1091
|
+
{ primary: "id" }
|
|
1092
|
+
);
|
|
584
1093
|
}
|
|
585
1094
|
};
|
|
586
1095
|
|
|
@@ -911,6 +1420,7 @@ var PageSyncer = class {
|
|
|
911
1420
|
this.options = { ...DEFAULT_OPTIONS2, ...deps.options };
|
|
912
1421
|
this.database = deps.database;
|
|
913
1422
|
this.notify = deps.notify;
|
|
1423
|
+
this.onSynced = deps.onSynced;
|
|
914
1424
|
this.images = new ImageSyncer(source, target);
|
|
915
1425
|
}
|
|
916
1426
|
static {
|
|
@@ -919,7 +1429,19 @@ var PageSyncer = class {
|
|
|
919
1429
|
options;
|
|
920
1430
|
database;
|
|
921
1431
|
notify;
|
|
1432
|
+
onSynced;
|
|
922
1433
|
images;
|
|
1434
|
+
/** 同步成功后的后续处理;失败只记日志,绝不影响同步结果 */
|
|
1435
|
+
async runSyncedHook(title) {
|
|
1436
|
+
if (!this.onSynced) return;
|
|
1437
|
+
try {
|
|
1438
|
+
await this.onSynced(title);
|
|
1439
|
+
} catch (error) {
|
|
1440
|
+
logger.warn(
|
|
1441
|
+
`[syncSinglePage] 页面 ${title} 的同步后处理失败: ${getErrorMessage(error)}`
|
|
1442
|
+
);
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
923
1445
|
// ---------------------------------------------------------------- 数据库
|
|
924
1446
|
/** 带重试的数据库操作 */
|
|
925
1447
|
retryDb(fn) {
|
|
@@ -1001,6 +1523,7 @@ var PageSyncer = class {
|
|
|
1001
1523
|
`由:${user} 触发更改,此时同步`
|
|
1002
1524
|
);
|
|
1003
1525
|
logger.info(`[syncSinglePage] ✅ 页面 ${pageTitle} 同步成功`);
|
|
1526
|
+
await this.runSyncedHook(pageTitle);
|
|
1004
1527
|
return { success: true, reason: "synced" };
|
|
1005
1528
|
} catch (error) {
|
|
1006
1529
|
const errMsg = getErrorMessage(error);
|
|
@@ -1426,6 +1949,256 @@ var ModuleSyncer = class {
|
|
|
1426
1949
|
}
|
|
1427
1950
|
};
|
|
1428
1951
|
|
|
1952
|
+
// src/sync/textSync.ts
|
|
1953
|
+
var import_node_crypto = require("node:crypto");
|
|
1954
|
+
var DEFAULT_OPTIONS4 = {
|
|
1955
|
+
apiUrl: "https://wiki.biligame.com/oni/api.php",
|
|
1956
|
+
pageUrlBase: "https://wiki.biligame.com/oni/",
|
|
1957
|
+
tableMode: "flatten",
|
|
1958
|
+
maxLength: 2e4,
|
|
1959
|
+
interval: 300,
|
|
1960
|
+
timeout: 3e4,
|
|
1961
|
+
userAgent: "OniSyncBot/1.0 (https://klei.vip; Charles@klei.vip)",
|
|
1962
|
+
maxPages: 5e3
|
|
1963
|
+
};
|
|
1964
|
+
var RenderedTextSyncer = class {
|
|
1965
|
+
static {
|
|
1966
|
+
__name(this, "RenderedTextSyncer");
|
|
1967
|
+
}
|
|
1968
|
+
http;
|
|
1969
|
+
bot;
|
|
1970
|
+
database;
|
|
1971
|
+
vector;
|
|
1972
|
+
options;
|
|
1973
|
+
constructor(deps) {
|
|
1974
|
+
this.http = deps.http;
|
|
1975
|
+
this.bot = deps.bot;
|
|
1976
|
+
this.database = deps.database;
|
|
1977
|
+
this.vector = deps.vector;
|
|
1978
|
+
this.options = { ...DEFAULT_OPTIONS4, ...deps.options };
|
|
1979
|
+
}
|
|
1980
|
+
/** 页面在 bwiki 上的访问地址(用于回答里的「资料来源」) */
|
|
1981
|
+
pageUrl(title) {
|
|
1982
|
+
return buildPageUrl(this.options.pageUrlBase, title);
|
|
1983
|
+
}
|
|
1984
|
+
/**
|
|
1985
|
+
* 抓取并保存单个页面的渲染文本。
|
|
1986
|
+
*
|
|
1987
|
+
* 文本的 sha1 与库中一致时直接返回 `unchanged`,
|
|
1988
|
+
* 既省掉一次 Embedding,也避免每小时的增量任务重复写索引。
|
|
1989
|
+
*/
|
|
1990
|
+
async syncOne(title) {
|
|
1991
|
+
const pageTitle = title.trim();
|
|
1992
|
+
if (!pageTitle) return { success: false, reason: "empty", message: "标题为空" };
|
|
1993
|
+
try {
|
|
1994
|
+
const parsed = await this.fetchRenderedHtml(pageTitle);
|
|
1995
|
+
if (!parsed) {
|
|
1996
|
+
logger.debug(`[textSync] ${pageTitle}:bwiki 上不存在该页面,跳过`);
|
|
1997
|
+
return { success: false, reason: "missing" };
|
|
1998
|
+
}
|
|
1999
|
+
const text = extractPlainText(parsed.html, {
|
|
2000
|
+
tableMode: this.options.tableMode,
|
|
2001
|
+
maxLength: this.options.maxLength
|
|
2002
|
+
});
|
|
2003
|
+
if (!text) {
|
|
2004
|
+
logger.warn(`[textSync] ${pageTitle}:抽出正文为空,跳过`);
|
|
2005
|
+
return { success: false, reason: "empty" };
|
|
2006
|
+
}
|
|
2007
|
+
const hash = hashText(text);
|
|
2008
|
+
const existing = await this.database.get("wikitexts", {
|
|
2009
|
+
id: pageTitle
|
|
2010
|
+
});
|
|
2011
|
+
if (existing[0]?.hash === hash) {
|
|
2012
|
+
logger.debug(`[textSync] ${pageTitle}:正文未变化,跳过`);
|
|
2013
|
+
return { success: true, reason: "unchanged" };
|
|
2014
|
+
}
|
|
2015
|
+
const record = {
|
|
2016
|
+
id: pageTitle,
|
|
2017
|
+
title: parsed.resolvedTitle || pageTitle,
|
|
2018
|
+
pageid: parsed.pageid,
|
|
2019
|
+
revid: parsed.revid,
|
|
2020
|
+
hash,
|
|
2021
|
+
text,
|
|
2022
|
+
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
2023
|
+
};
|
|
2024
|
+
await this.database.upsert("wikitexts", [record]);
|
|
2025
|
+
logger.info(
|
|
2026
|
+
`[textSync] ${pageTitle}:正文已入库(${text.length} 字,${hash.slice(0, 8)})`
|
|
2027
|
+
);
|
|
2028
|
+
if (this.vector) {
|
|
2029
|
+
try {
|
|
2030
|
+
await this.vector.indexPage({
|
|
2031
|
+
id: record.id,
|
|
2032
|
+
title: record.title,
|
|
2033
|
+
url: this.pageUrl(pageTitle),
|
|
2034
|
+
text
|
|
2035
|
+
});
|
|
2036
|
+
} catch (error) {
|
|
2037
|
+
logger.warn(
|
|
2038
|
+
`[textSync] ${pageTitle}:向量化失败(文本已入库):${getErrorMessage(error)}`
|
|
2039
|
+
);
|
|
2040
|
+
return {
|
|
2041
|
+
success: true,
|
|
2042
|
+
reason: "synced",
|
|
2043
|
+
message: "文本已入库,但向量化失败"
|
|
2044
|
+
};
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
return { success: true, reason: "synced" };
|
|
2048
|
+
} catch (error) {
|
|
2049
|
+
const message = getErrorMessage(error);
|
|
2050
|
+
logger.error(`[textSync] ${pageTitle}:抓取渲染文本失败:${message}`);
|
|
2051
|
+
return { success: false, reason: "failed", message };
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
/** 批量抓取(按配置的间隔串行执行,避免把小机器和 bwiki 打满) */
|
|
2055
|
+
async syncMany(titles) {
|
|
2056
|
+
const summary = {
|
|
2057
|
+
total: titles.length,
|
|
2058
|
+
synced: 0,
|
|
2059
|
+
unchanged: 0,
|
|
2060
|
+
missing: 0,
|
|
2061
|
+
failed: 0
|
|
2062
|
+
};
|
|
2063
|
+
for (let index = 0; index < titles.length; index++) {
|
|
2064
|
+
const result = await this.syncOne(titles[index]);
|
|
2065
|
+
if (result.success && result.reason === "synced") summary.synced++;
|
|
2066
|
+
else if (result.success && result.reason === "unchanged") summary.unchanged++;
|
|
2067
|
+
else if (result.reason === "missing") summary.missing++;
|
|
2068
|
+
else summary.failed++;
|
|
2069
|
+
const processed = index + 1;
|
|
2070
|
+
if (processed % 20 === 0 || processed === titles.length) {
|
|
2071
|
+
logger.info(
|
|
2072
|
+
`[textSync] 进度 ${processed}/${titles.length}:新增/更新 ${summary.synced},未变 ${summary.unchanged},页面不存在 ${summary.missing},失败 ${summary.failed}`
|
|
2073
|
+
);
|
|
2074
|
+
}
|
|
2075
|
+
if (processed < titles.length && this.options.interval > 0) {
|
|
2076
|
+
await (0, import_koishi3.sleep)(this.options.interval);
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
return summary;
|
|
2080
|
+
}
|
|
2081
|
+
/**
|
|
2082
|
+
* 对本地缓存的全部页面执行一次渲染文本抓取(首次部署 / 全量重建时使用)。
|
|
2083
|
+
*
|
|
2084
|
+
* 本地 `wikipages` 为空(还没执行过 `update`)时,直接向 BWiki 的 `allpages`
|
|
2085
|
+
* 枚举主命名空间页面——`ai.sync` 因此不依赖页面缓存也能跑起来。
|
|
2086
|
+
*/
|
|
2087
|
+
async syncAll() {
|
|
2088
|
+
let titles = (await this.database.get("wikipages", {})).map((page) => page.title);
|
|
2089
|
+
if (titles.length === 0) {
|
|
2090
|
+
logger.warn(
|
|
2091
|
+
"[textSync] 本地页面缓存为空,改为从 BWiki 的 allpages 枚举页面(建议之后执行 update 补全缓存)"
|
|
2092
|
+
);
|
|
2093
|
+
titles = await this.listAllPageTitles();
|
|
2094
|
+
}
|
|
2095
|
+
logger.info(`[textSync] 开始抓取 ${titles.length} 个页面的渲染文本`);
|
|
2096
|
+
return this.syncMany(titles);
|
|
2097
|
+
}
|
|
2098
|
+
// ---------------------------------------------------------------- 内部实现
|
|
2099
|
+
/**
|
|
2100
|
+
* 统一的 API 请求入口。
|
|
2101
|
+
*
|
|
2102
|
+
* 首选已登录的 bwiki 客户端(mwn,自带 Referer / Cookie,且与 `sync.*` 走同一条链路),
|
|
2103
|
+
* 没有就退回 `ctx.http` 并**手动补上 Referer**——缺 Referer 会被 bwiki 的 WAF 直接 567。
|
|
2104
|
+
*/
|
|
2105
|
+
async apiRequest(params) {
|
|
2106
|
+
const payload = { ...params, format: "json" };
|
|
2107
|
+
return withRetry(
|
|
2108
|
+
async () => {
|
|
2109
|
+
const bot = this.bot?.();
|
|
2110
|
+
if (bot) {
|
|
2111
|
+
return await bot.request(payload);
|
|
2112
|
+
}
|
|
2113
|
+
if (!this.http) {
|
|
2114
|
+
throw new Error(
|
|
2115
|
+
"既没有可用的 wikiBot 也没有 http 服务,无法请求 BWiki(请检查登录与 @koishijs/plugin-http)"
|
|
2116
|
+
);
|
|
2117
|
+
}
|
|
2118
|
+
return this.http.get(this.options.apiUrl, {
|
|
2119
|
+
params: payload,
|
|
2120
|
+
headers: {
|
|
2121
|
+
"User-Agent": this.options.userAgent,
|
|
2122
|
+
Referer: this.options.pageUrlBase
|
|
2123
|
+
},
|
|
2124
|
+
timeout: this.options.timeout
|
|
2125
|
+
});
|
|
2126
|
+
},
|
|
2127
|
+
{
|
|
2128
|
+
attempts: 3,
|
|
2129
|
+
delayMs: 1500,
|
|
2130
|
+
onRetry: /* @__PURE__ */ __name((error, attempt, attempts) => logger.warn(
|
|
2131
|
+
`[textSync] 请求 BWiki 失败,重试中 (${attempt}/${attempts}):${getErrorMessage(error)}`
|
|
2132
|
+
), "onRetry")
|
|
2133
|
+
}
|
|
2134
|
+
);
|
|
2135
|
+
}
|
|
2136
|
+
/** 通过 MediaWiki `list=allpages` 枚举主命名空间页面标题(含 continue 翻页) */
|
|
2137
|
+
async listAllPageTitles() {
|
|
2138
|
+
const titles = [];
|
|
2139
|
+
let apcontinue;
|
|
2140
|
+
while (titles.length < this.options.maxPages) {
|
|
2141
|
+
const data = await this.apiRequest({
|
|
2142
|
+
action: "query",
|
|
2143
|
+
list: "allpages",
|
|
2144
|
+
apnamespace: 0,
|
|
2145
|
+
aplimit: "max",
|
|
2146
|
+
formatversion: 2,
|
|
2147
|
+
...apcontinue ? { apcontinue } : {}
|
|
2148
|
+
});
|
|
2149
|
+
if (data?.error) {
|
|
2150
|
+
throw new Error(
|
|
2151
|
+
`allpages 查询报错:${data.error.code ?? "unknown"} ${data.error.info ?? ""}`.trim()
|
|
2152
|
+
);
|
|
2153
|
+
}
|
|
2154
|
+
for (const page of data?.query?.allpages ?? []) {
|
|
2155
|
+
if (page.title && titles.length < this.options.maxPages) {
|
|
2156
|
+
titles.push(page.title);
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
apcontinue = data?.continue?.apcontinue;
|
|
2160
|
+
if (!apcontinue || titles.length >= this.options.maxPages) break;
|
|
2161
|
+
}
|
|
2162
|
+
logger.info(`[textSync] allpages 枚举到 ${titles.length} 个页面`);
|
|
2163
|
+
return titles;
|
|
2164
|
+
}
|
|
2165
|
+
async fetchRenderedHtml(title) {
|
|
2166
|
+
const data = await this.apiRequest({
|
|
2167
|
+
action: "parse",
|
|
2168
|
+
page: title,
|
|
2169
|
+
prop: "text|revid",
|
|
2170
|
+
formatversion: 2,
|
|
2171
|
+
redirects: 1,
|
|
2172
|
+
disableeditsection: 1,
|
|
2173
|
+
disabletoc: 1,
|
|
2174
|
+
disablelimitreport: 1
|
|
2175
|
+
});
|
|
2176
|
+
if (data?.error) {
|
|
2177
|
+
if (data.error.code === "missingtitle") return null;
|
|
2178
|
+
throw new Error(
|
|
2179
|
+
`解析接口报错:${data.error.code ?? "unknown"} ${data.error.info ?? ""}`.trim()
|
|
2180
|
+
);
|
|
2181
|
+
}
|
|
2182
|
+
const parse = data?.parse;
|
|
2183
|
+
const html = typeof parse?.text === "string" ? parse.text : parse?.text?.["*"] ?? "";
|
|
2184
|
+
if (!parse || !html) return null;
|
|
2185
|
+
return {
|
|
2186
|
+
html,
|
|
2187
|
+
resolvedTitle: parse.title,
|
|
2188
|
+
pageid: parse.pageid,
|
|
2189
|
+
revid: parse.revid
|
|
2190
|
+
};
|
|
2191
|
+
}
|
|
2192
|
+
};
|
|
2193
|
+
function hashText(text) {
|
|
2194
|
+
return (0, import_node_crypto.createHash)("sha1").update(text, "utf8").digest("hex");
|
|
2195
|
+
}
|
|
2196
|
+
__name(hashText, "hashText");
|
|
2197
|
+
function buildPageUrl(pageUrlBase, title) {
|
|
2198
|
+
return `${pageUrlBase}${encodeURIComponent(title.trim().replace(/ /g, "_"))}`;
|
|
2199
|
+
}
|
|
2200
|
+
__name(buildPageUrl, "buildPageUrl");
|
|
2201
|
+
|
|
1429
2202
|
// src/services/syncNotifier.ts
|
|
1430
2203
|
var SyncNotifier = class {
|
|
1431
2204
|
constructor(ctx, groupIds = [], platform = "qq") {
|
|
@@ -1503,9 +2276,23 @@ var SyncCommands = class {
|
|
|
1503
2276
|
static {
|
|
1504
2277
|
__name(this, "SyncCommands");
|
|
1505
2278
|
}
|
|
1506
|
-
|
|
2279
|
+
/**
|
|
2280
|
+
* `cron` / `http` / `vector` 都是**可选**依赖:
|
|
2281
|
+
* 任何一项没装,同步命令仍必须可用(只是少了定时任务 / 渲染文本抽取)。
|
|
2282
|
+
* 早期把它们写成必需项,曾在实例未启用 koishi-plugin-cron 时导致
|
|
2283
|
+
* 整个子插件一直 pending,`sync` 系列命令凭空消失。
|
|
2284
|
+
*/
|
|
2285
|
+
static inject = {
|
|
2286
|
+
wikiBot: { required: true },
|
|
2287
|
+
database: { required: true },
|
|
2288
|
+
cron: { required: false },
|
|
2289
|
+
http: { required: false },
|
|
2290
|
+
vector: { required: false }
|
|
2291
|
+
};
|
|
1507
2292
|
config;
|
|
1508
2293
|
notifyFn;
|
|
2294
|
+
/** 同步成功后抽取渲染文本(未开启时为空) */
|
|
2295
|
+
textSync;
|
|
1509
2296
|
constructor(ctx, config) {
|
|
1510
2297
|
this.config = config;
|
|
1511
2298
|
logger.info("WikiBot 服务已就绪,初始化定时任务和指令");
|
|
@@ -1515,21 +2302,59 @@ var SyncCommands = class {
|
|
|
1515
2302
|
config.notifyBotPlatform
|
|
1516
2303
|
);
|
|
1517
2304
|
this.notifyFn = notifier.enabled ? (items) => void notifier.notify(items) : void 0;
|
|
2305
|
+
this.textSync = this.createTextSyncer(ctx);
|
|
1518
2306
|
this.registerScheduledTasks(ctx);
|
|
1519
2307
|
this.registerCommands(ctx);
|
|
1520
2308
|
}
|
|
2309
|
+
/**
|
|
2310
|
+
* 构造「渲染文本同步器」:页面同步成功后再回 bwiki 取一次渲染结果。
|
|
2311
|
+
* `textSyncOnChange` 关闭时不创建(同步后不做任何额外请求)。
|
|
2312
|
+
*/
|
|
2313
|
+
createTextSyncer(ctx) {
|
|
2314
|
+
const config = this.config;
|
|
2315
|
+
if (!config.textSyncOnChange) return void 0;
|
|
2316
|
+
const bwiki = siteUrl(config.bwiki_site || "wiki.biligame.com/oni");
|
|
2317
|
+
return new RenderedTextSyncer({
|
|
2318
|
+
http: ctx.http,
|
|
2319
|
+
// 惰性取用已登录的 bwiki 客户端:构造时登录通常还没完成
|
|
2320
|
+
bot: /* @__PURE__ */ __name(() => tryGetBWikiBot(ctx), "bot"),
|
|
2321
|
+
database: ctx.database,
|
|
2322
|
+
vector: config.vectorEnabled ? ctx.vector : void 0,
|
|
2323
|
+
options: {
|
|
2324
|
+
apiUrl: config.textApiUrl || `${bwiki}/api.php`,
|
|
2325
|
+
pageUrlBase: `${bwiki}/`,
|
|
2326
|
+
tableMode: config.textTableMode,
|
|
2327
|
+
maxLength: config.textMaxLength,
|
|
2328
|
+
interval: config.textSyncInterval
|
|
2329
|
+
}
|
|
2330
|
+
});
|
|
2331
|
+
}
|
|
2332
|
+
/** 统一的 PageSyncer 构造:数据库、通知与「同步后抽取文本」钩子都在这里装配 */
|
|
2333
|
+
createPageSyncer(ctx) {
|
|
2334
|
+
return new PageSyncer(ctx.wikiBot.getGGBot(), ctx.wikiBot.getBWikiBot(), {
|
|
2335
|
+
database: ctx.database,
|
|
2336
|
+
notify: this.notifyFn,
|
|
2337
|
+
onSynced: this.textSync ? async (title) => {
|
|
2338
|
+
if (title.includes(":")) return;
|
|
2339
|
+
await this.textSync?.syncOne(title);
|
|
2340
|
+
} : void 0
|
|
2341
|
+
});
|
|
2342
|
+
}
|
|
1521
2343
|
/** 同步相关的定时任务;cron 表达式即调度策略,集中在一处便于对照 */
|
|
1522
2344
|
registerScheduledTasks(ctx) {
|
|
2345
|
+
if (typeof ctx.cron !== "function") {
|
|
2346
|
+
logger.warn(
|
|
2347
|
+
"未检测到 cron 服务(koishi.yml 未启用 koishi-plugin-cron),定时同步任务已跳过;手动命令不受影响"
|
|
2348
|
+
);
|
|
2349
|
+
return;
|
|
2350
|
+
}
|
|
1523
2351
|
ctx.cron("15 * * * *", async () => {
|
|
1524
2352
|
if (!await this.ensureBotsReady(ctx, "增量更新")) return;
|
|
1525
|
-
await
|
|
1526
|
-
database: ctx.database,
|
|
1527
|
-
notify: this.notifyFn
|
|
1528
|
-
}).incrementalUpdate();
|
|
2353
|
+
await this.createPageSyncer(ctx).incrementalUpdate();
|
|
1529
2354
|
});
|
|
1530
2355
|
ctx.cron("30 8 * * 4", async () => {
|
|
1531
2356
|
if (!await this.ensureBotsReady(ctx, "同步所有页面")) return;
|
|
1532
|
-
await
|
|
2357
|
+
await this.createPageSyncer(ctx).syncAll().then(() => {
|
|
1533
2358
|
logger.info("自动任务:尝试同步所有页面,从 WIKIGG 到 bwiki");
|
|
1534
2359
|
}).catch((err) => {
|
|
1535
2360
|
logger.error(`同步所有页面失败,错误信息:${err}`);
|
|
@@ -1568,10 +2393,7 @@ var SyncCommands = class {
|
|
|
1568
2393
|
return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
|
|
1569
2394
|
}
|
|
1570
2395
|
try {
|
|
1571
|
-
await
|
|
1572
|
-
ctx.wikiBot.getGGBot(),
|
|
1573
|
-
ctx.wikiBot.getBWikiBot()
|
|
1574
|
-
).syncOne(pageTitle, "sync-bot");
|
|
2396
|
+
await this.createPageSyncer(ctx).syncOne(pageTitle, "sync-bot");
|
|
1575
2397
|
return `✅ 已尝试同步页面:${pageTitle},请前往控制台查看:${this.config.logsUrl}`;
|
|
1576
2398
|
} catch (err) {
|
|
1577
2399
|
logger.error(`同步页面 ${pageTitle} 失败,错误信息:${err}`);
|
|
@@ -1585,11 +2407,7 @@ var SyncCommands = class {
|
|
|
1585
2407
|
return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
|
|
1586
2408
|
}
|
|
1587
2409
|
try {
|
|
1588
|
-
await
|
|
1589
|
-
ctx.wikiBot.getGGBot(),
|
|
1590
|
-
ctx.wikiBot.getBWikiBot(),
|
|
1591
|
-
{ notify: this.notifyFn }
|
|
1592
|
-
).incrementalUpdate();
|
|
2410
|
+
await this.createPageSyncer(ctx).incrementalUpdate();
|
|
1593
2411
|
return `✅ 已尝试获取三小时前的编辑并同步,请前往控制台查看:${this.config.logsUrl}`;
|
|
1594
2412
|
} catch (err) {
|
|
1595
2413
|
logger.error(`增量更新失败,错误信息:${err}`);
|
|
@@ -1601,10 +2419,7 @@ var SyncCommands = class {
|
|
|
1601
2419
|
return "❌ Wiki 机器人未就绪,请检查登录配置或查看日志";
|
|
1602
2420
|
}
|
|
1603
2421
|
try {
|
|
1604
|
-
await
|
|
1605
|
-
ctx.wikiBot.getGGBot(),
|
|
1606
|
-
ctx.wikiBot.getBWikiBot()
|
|
1607
|
-
).syncAll();
|
|
2422
|
+
await this.createPageSyncer(ctx).syncAll();
|
|
1608
2423
|
return `✅ 已尝试同步所有页面,请前往控制台查看:${this.config.logsUrl}`;
|
|
1609
2424
|
} catch (err) {
|
|
1610
2425
|
logger.error(`同步所有页面失败,错误信息:${err}`);
|
|
@@ -2173,10 +2988,21 @@ var UpdateCommands = class {
|
|
|
2173
2988
|
static {
|
|
2174
2989
|
__name(this, "UpdateCommands");
|
|
2175
2990
|
}
|
|
2176
|
-
|
|
2991
|
+
/** `cron` 可选:定时刷新缓存是增强项,命令本身必须始终可用 */
|
|
2992
|
+
static inject = {
|
|
2993
|
+
database: { required: true },
|
|
2994
|
+
wikiBot: { required: true },
|
|
2995
|
+
cron: { required: false }
|
|
2996
|
+
};
|
|
2177
2997
|
config;
|
|
2178
2998
|
log;
|
|
2179
2999
|
registerCronJobs(ctx) {
|
|
3000
|
+
if (typeof ctx.cron !== "function") {
|
|
3001
|
+
this.log.warn(
|
|
3002
|
+
"未检测到 cron 服务(koishi.yml 未启用 koishi-plugin-cron),页面缓存的定时更新已跳过"
|
|
3003
|
+
);
|
|
3004
|
+
return;
|
|
3005
|
+
}
|
|
2180
3006
|
const cronExpression = this.config.updateCron || "0 2 * * *";
|
|
2181
3007
|
ctx.cron(cronExpression, async () => {
|
|
2182
3008
|
if (!this.ctx.wikiBot.isReady) {
|
|
@@ -2321,9 +3147,21 @@ var TodoList = class {
|
|
|
2321
3147
|
static {
|
|
2322
3148
|
__name(this, "TodoList");
|
|
2323
3149
|
}
|
|
2324
|
-
|
|
3150
|
+
/** `cron` 可选:未启用定时任务插件时,TodoList 的命令与控制台仍需可用 */
|
|
3151
|
+
static inject = {
|
|
3152
|
+
database: { required: true },
|
|
3153
|
+
console: { required: true },
|
|
3154
|
+
wikiBot: { required: true },
|
|
3155
|
+
cron: { required: false }
|
|
3156
|
+
};
|
|
2325
3157
|
log;
|
|
2326
3158
|
registerCronJobs(ctx) {
|
|
3159
|
+
if (typeof ctx.cron !== "function") {
|
|
3160
|
+
this.log.warn(
|
|
3161
|
+
"未检测到 cron 服务(koishi.yml 未启用 koishi-plugin-cron),TodoList 的定时任务已跳过"
|
|
3162
|
+
);
|
|
3163
|
+
return;
|
|
3164
|
+
}
|
|
2327
3165
|
ctx.cron("0 0 * * 1", async () => {
|
|
2328
3166
|
if (!this.ctx.wikiBot.isReady) {
|
|
2329
3167
|
this.log.warn("定时任务:WikiBot 服务未就绪,跳过同步模块");
|
|
@@ -2696,17 +3534,630 @@ var TodoList = class {
|
|
|
2696
3534
|
}
|
|
2697
3535
|
};
|
|
2698
3536
|
|
|
3537
|
+
// src/services/aiService.ts
|
|
3538
|
+
var SYSTEM_PROMPT = [
|
|
3539
|
+
"你是一个缺氧游戏助手。请【严格且仅】根据以下提供的 BWIKI 资料回答用户的问题。",
|
|
3540
|
+
"绝对禁止使用现实世界的物理化学知识,绝对禁止编造。",
|
|
3541
|
+
"如果资料中未提及,请直接回答:抱歉,资料中未提及相关信息。",
|
|
3542
|
+
"请用简洁、分点的中文回答。以专业玩家的口吻适当润色",
|
|
3543
|
+
"补充约束:",
|
|
3544
|
+
"1. 只能引用资料中出现的名称与数值,不得换算、不得补充资料外的机制;",
|
|
3545
|
+
"2. 资料中没有的信息一律视为「未提及」,不得猜测;",
|
|
3546
|
+
"3. 不要提及这些规则本身,也不要复述资料原文的整段内容;",
|
|
3547
|
+
"4. 若用户的问题是对上一轮的追问(如「它」「这个」「那它能干什么」),结合对话历史理解指代,但仍然只能使用资料中的信息。"
|
|
3548
|
+
].join("\n");
|
|
3549
|
+
var NO_ANSWER_TEXT = "抱歉,资料中未提及相关信息。";
|
|
3550
|
+
function isNoAnswer(answer) {
|
|
3551
|
+
const normalized = answer.replace(/[\s。!?!?,,、.]/g, "");
|
|
3552
|
+
const target = NO_ANSWER_TEXT.replace(/[\s。!?!?,,、.]/g, "");
|
|
3553
|
+
return normalized.length > 0 && normalized.startsWith(target);
|
|
3554
|
+
}
|
|
3555
|
+
__name(isNoAnswer, "isNoAnswer");
|
|
3556
|
+
function buildContext(chunks) {
|
|
3557
|
+
return chunks.map((chunk, index) => {
|
|
3558
|
+
const source = chunk.url ? `${chunk.title}(${chunk.url})` : chunk.title;
|
|
3559
|
+
return `[资料${index + 1}] 页面:${source}
|
|
3560
|
+
${chunk.text}`;
|
|
3561
|
+
}).join("\n\n");
|
|
3562
|
+
}
|
|
3563
|
+
__name(buildContext, "buildContext");
|
|
3564
|
+
function buildMessages(question, chunks, history = []) {
|
|
3565
|
+
const messages = [
|
|
3566
|
+
{
|
|
3567
|
+
role: "system",
|
|
3568
|
+
content: `${SYSTEM_PROMPT}
|
|
3569
|
+
|
|
3570
|
+
【BWIKI 资料开始】
|
|
3571
|
+
${buildContext(chunks)}
|
|
3572
|
+
【BWIKI 资料结束】`
|
|
3573
|
+
}
|
|
3574
|
+
];
|
|
3575
|
+
for (const turn of history) {
|
|
3576
|
+
if (turn.question && turn.answer) {
|
|
3577
|
+
messages.push({ role: "user", content: turn.question });
|
|
3578
|
+
messages.push({ role: "assistant", content: turn.answer });
|
|
3579
|
+
}
|
|
3580
|
+
}
|
|
3581
|
+
messages.push({ role: "user", content: question });
|
|
3582
|
+
return messages;
|
|
3583
|
+
}
|
|
3584
|
+
__name(buildMessages, "buildMessages");
|
|
3585
|
+
var AiService = class {
|
|
3586
|
+
constructor(ctx, settings) {
|
|
3587
|
+
this.ctx = ctx;
|
|
3588
|
+
this.settings = settings;
|
|
3589
|
+
}
|
|
3590
|
+
static {
|
|
3591
|
+
__name(this, "AiService");
|
|
3592
|
+
}
|
|
3593
|
+
get apiKey() {
|
|
3594
|
+
const configured = this.settings.deepseekApiKey?.trim();
|
|
3595
|
+
return configured || (process.env.DEEPSEEK_API_KEY ?? "").trim();
|
|
3596
|
+
}
|
|
3597
|
+
get enabled() {
|
|
3598
|
+
return Boolean(this.settings.aiEnabled && this.apiKey);
|
|
3599
|
+
}
|
|
3600
|
+
async chat(messages, options = {}) {
|
|
3601
|
+
if (!this.settings.aiEnabled) {
|
|
3602
|
+
throw new Error("AI 问答未启用(aiEnabled=false)");
|
|
3603
|
+
}
|
|
3604
|
+
const apiKey = this.apiKey;
|
|
3605
|
+
if (!apiKey) {
|
|
3606
|
+
throw new Error(
|
|
3607
|
+
"未配置 DeepSeek API Key,请填写 deepseekApiKey 或设置环境变量 DEEPSEEK_API_KEY"
|
|
3608
|
+
);
|
|
3609
|
+
}
|
|
3610
|
+
const baseUrl = (this.settings.deepseekBaseUrl || "https://api.deepseek.com").replace(/\/+$/, "");
|
|
3611
|
+
let response;
|
|
3612
|
+
try {
|
|
3613
|
+
response = await this.ctx.http.post(
|
|
3614
|
+
`${baseUrl}/chat/completions`,
|
|
3615
|
+
{
|
|
3616
|
+
model: this.settings.deepseekModel,
|
|
3617
|
+
messages,
|
|
3618
|
+
temperature: options.temperature ?? this.settings.aiTemperature,
|
|
3619
|
+
max_tokens: options.maxTokens ?? this.settings.aiMaxTokens,
|
|
3620
|
+
stream: false
|
|
3621
|
+
},
|
|
3622
|
+
{
|
|
3623
|
+
headers: {
|
|
3624
|
+
Authorization: `Bearer ${apiKey}`,
|
|
3625
|
+
"Content-Type": "application/json"
|
|
3626
|
+
},
|
|
3627
|
+
timeout: this.settings.aiTimeout
|
|
3628
|
+
}
|
|
3629
|
+
);
|
|
3630
|
+
} catch (error) {
|
|
3631
|
+
throw new Error(`调用 DeepSeek 失败:${describeHttpError(error)}`);
|
|
3632
|
+
}
|
|
3633
|
+
const content = response?.choices?.[0]?.message?.content?.trim();
|
|
3634
|
+
if (!content) {
|
|
3635
|
+
throw new Error(
|
|
3636
|
+
`DeepSeek 返回了空回答:${response?.error?.message ?? "未知原因"}`
|
|
3637
|
+
);
|
|
3638
|
+
}
|
|
3639
|
+
return content;
|
|
3640
|
+
}
|
|
3641
|
+
};
|
|
3642
|
+
function describeHttpError(error) {
|
|
3643
|
+
const response = error?.response;
|
|
3644
|
+
const detail = response?.data?.error?.message ?? response?.data?.message ?? (typeof response?.data === "string" ? response.data : void 0);
|
|
3645
|
+
if (detail) {
|
|
3646
|
+
return response?.status ? `HTTP ${response.status} - ${detail}` : detail;
|
|
3647
|
+
}
|
|
3648
|
+
return getErrorMessage(error);
|
|
3649
|
+
}
|
|
3650
|
+
__name(describeHttpError, "describeHttpError");
|
|
3651
|
+
|
|
3652
|
+
// src/services/aiMemory.ts
|
|
3653
|
+
var AiMemory = class {
|
|
3654
|
+
constructor(maxTurns, ttlMs, now = () => Date.now()) {
|
|
3655
|
+
this.maxTurns = maxTurns;
|
|
3656
|
+
this.ttlMs = ttlMs;
|
|
3657
|
+
this.now = now;
|
|
3658
|
+
}
|
|
3659
|
+
static {
|
|
3660
|
+
__name(this, "AiMemory");
|
|
3661
|
+
}
|
|
3662
|
+
store = /* @__PURE__ */ new Map();
|
|
3663
|
+
get enabled() {
|
|
3664
|
+
return this.maxTurns > 0;
|
|
3665
|
+
}
|
|
3666
|
+
/** 读取最近的记忆轮次(已剔除过期项,并按 `maxTurns` 截断) */
|
|
3667
|
+
get(key) {
|
|
3668
|
+
if (!key || !this.enabled) return [];
|
|
3669
|
+
const stored = this.store.get(key);
|
|
3670
|
+
if (!stored?.length) return [];
|
|
3671
|
+
const fresh = this.prune(stored);
|
|
3672
|
+
if (fresh.length === 0) {
|
|
3673
|
+
this.store.delete(key);
|
|
3674
|
+
return [];
|
|
3675
|
+
}
|
|
3676
|
+
if (fresh.length !== stored.length) this.store.set(key, fresh);
|
|
3677
|
+
return fresh;
|
|
3678
|
+
}
|
|
3679
|
+
/** 追加一轮问答;超出上限时丢弃最旧的一轮 */
|
|
3680
|
+
add(key, turn) {
|
|
3681
|
+
if (!key || !this.enabled) return;
|
|
3682
|
+
const stored = this.store.get(key) ?? [];
|
|
3683
|
+
stored.push({ ...turn, at: this.now() });
|
|
3684
|
+
this.store.set(key, stored.slice(-this.maxTurns));
|
|
3685
|
+
if (this.store.size > 500) this.evictStale();
|
|
3686
|
+
}
|
|
3687
|
+
clear(key) {
|
|
3688
|
+
this.store.delete(key);
|
|
3689
|
+
}
|
|
3690
|
+
prune(turns) {
|
|
3691
|
+
if (this.ttlMs <= 0) return turns;
|
|
3692
|
+
const now = this.now();
|
|
3693
|
+
return turns.filter((turn) => now - turn.at <= this.ttlMs);
|
|
3694
|
+
}
|
|
3695
|
+
/** 防止长期运行下 Map 无限增长:清理已过期的键 */
|
|
3696
|
+
evictStale() {
|
|
3697
|
+
if (this.ttlMs <= 0) return;
|
|
3698
|
+
const now = this.now();
|
|
3699
|
+
for (const [key, turns] of this.store) {
|
|
3700
|
+
const lastAt = turns[turns.length - 1]?.at ?? 0;
|
|
3701
|
+
if (now - lastAt > this.ttlMs) this.store.delete(key);
|
|
3702
|
+
}
|
|
3703
|
+
}
|
|
3704
|
+
};
|
|
3705
|
+
function pickContext(own, shared, channelMemoryEnabled) {
|
|
3706
|
+
if (own.length > 0) return { turns: own };
|
|
3707
|
+
if (!channelMemoryEnabled || shared.length === 0) return { turns: [] };
|
|
3708
|
+
return {
|
|
3709
|
+
turns: shared,
|
|
3710
|
+
inheritedFrom: shared[shared.length - 1].question
|
|
3711
|
+
};
|
|
3712
|
+
}
|
|
3713
|
+
__name(pickContext, "pickContext");
|
|
3714
|
+
|
|
3715
|
+
// src/plugins/aiQueryCommands.ts
|
|
3716
|
+
var MAX_CONTEXT_CHARS = 1200;
|
|
3717
|
+
var AiQueryCommands = class {
|
|
3718
|
+
constructor(ctx, config) {
|
|
3719
|
+
this.ctx = ctx;
|
|
3720
|
+
this.config = config;
|
|
3721
|
+
this.renderer = new MessageRenderer(ctx, config.domain);
|
|
3722
|
+
this.ai = new AiService(ctx, config);
|
|
3723
|
+
const bwiki = siteUrl(config.bwiki_site || "wiki.biligame.com/oni");
|
|
3724
|
+
this.pageUrlBase = `${bwiki}/`;
|
|
3725
|
+
this.memory = new AiMemory(config.aiMemoryTurns, config.aiMemoryTtl * 1e3);
|
|
3726
|
+
this.channelMemory = new AiMemory(
|
|
3727
|
+
Math.min(1, Math.max(0, config.aiMemoryTurns)),
|
|
3728
|
+
config.aiMemoryTtl * 1e3
|
|
3729
|
+
);
|
|
3730
|
+
this.textSync = new RenderedTextSyncer({
|
|
3731
|
+
http: ctx.http,
|
|
3732
|
+
// 惰性取用已登录的 bwiki 客户端:构造时登录通常还没完成
|
|
3733
|
+
bot: /* @__PURE__ */ __name(() => tryGetBWikiBot(ctx), "bot"),
|
|
3734
|
+
database: ctx.database,
|
|
3735
|
+
vector: config.vectorEnabled ? ctx.vector : void 0,
|
|
3736
|
+
options: {
|
|
3737
|
+
apiUrl: config.textApiUrl || `${bwiki}/api.php`,
|
|
3738
|
+
pageUrlBase: this.pageUrlBase,
|
|
3739
|
+
tableMode: config.textTableMode,
|
|
3740
|
+
maxLength: config.textMaxLength,
|
|
3741
|
+
interval: config.textSyncInterval
|
|
3742
|
+
}
|
|
3743
|
+
});
|
|
3744
|
+
this.registerCommands(ctx);
|
|
3745
|
+
}
|
|
3746
|
+
static {
|
|
3747
|
+
__name(this, "AiQueryCommands");
|
|
3748
|
+
}
|
|
3749
|
+
/** `http` / `vector` 可选:缺任意一项时 `.ai` 仍应能给出明确提示,而不是整组命令消失 */
|
|
3750
|
+
static inject = {
|
|
3751
|
+
database: { required: true },
|
|
3752
|
+
wikiBot: { required: false },
|
|
3753
|
+
http: { required: false },
|
|
3754
|
+
vector: { required: false }
|
|
3755
|
+
};
|
|
3756
|
+
config;
|
|
3757
|
+
renderer;
|
|
3758
|
+
ai;
|
|
3759
|
+
textSync;
|
|
3760
|
+
pageUrlBase;
|
|
3761
|
+
/** 用户 → 上次提问时间,用于冷却 */
|
|
3762
|
+
lastAskedAt = /* @__PURE__ */ new Map();
|
|
3763
|
+
/** 用户 → 最近几轮问答(含当轮检索到的资料),用于追问 */
|
|
3764
|
+
memory;
|
|
3765
|
+
/** 频道 → 最近一轮问答,用于「群里别人刚问过,我接着问」 */
|
|
3766
|
+
channelMemory;
|
|
3767
|
+
registerCommands(ctx) {
|
|
3768
|
+
ctx.command("ai <question:text>", "基于缺氧 BWIKI 资料的 AI 问答").alias("/问缺氧").alias("问缺氧").action(async ({ session }, question = "") => {
|
|
3769
|
+
const keyword = question.trim();
|
|
3770
|
+
if (!keyword) {
|
|
3771
|
+
return this.renderer.send(
|
|
3772
|
+
session,
|
|
3773
|
+
"📖 用法:ai <你的问题>\n例如:ai 电解器耗电多少?\n(回答仅依据 BWIKI 资料,数据来源:缺氧 BWIKI)"
|
|
3774
|
+
);
|
|
3775
|
+
}
|
|
3776
|
+
if (keyword.length > this.config.aiMaxQuestionLength) {
|
|
3777
|
+
return this.renderer.send(
|
|
3778
|
+
session,
|
|
3779
|
+
`❌ 问题太长了,请精简到 ${this.config.aiMaxQuestionLength} 字以内`
|
|
3780
|
+
);
|
|
3781
|
+
}
|
|
3782
|
+
if (!this.ctx.http) {
|
|
3783
|
+
return this.renderer.send(
|
|
3784
|
+
session,
|
|
3785
|
+
"❌ 未启用 http 服务(@koishijs/plugin-http),无法调用 AI 接口"
|
|
3786
|
+
);
|
|
3787
|
+
}
|
|
3788
|
+
if (!this.ai.enabled) {
|
|
3789
|
+
return this.renderer.send(
|
|
3790
|
+
session,
|
|
3791
|
+
"❌ AI 问答未启用:请在插件配置里填写 deepseekApiKey,或设置环境变量 DEEPSEEK_API_KEY"
|
|
3792
|
+
);
|
|
3793
|
+
}
|
|
3794
|
+
const waitSeconds = this.cooldownLeft(session);
|
|
3795
|
+
if (waitSeconds > 0) {
|
|
3796
|
+
return this.renderer.send(
|
|
3797
|
+
session,
|
|
3798
|
+
`⏳ 提问太频繁了,请 ${waitSeconds} 秒后再试`
|
|
3799
|
+
);
|
|
3800
|
+
}
|
|
3801
|
+
const context = this.resolveContext(session);
|
|
3802
|
+
const chunks = await this.retrieve(keyword, context.turns);
|
|
3803
|
+
if (chunks.length === 0) {
|
|
3804
|
+
logger.info(`[ai] 「${keyword}」未检索到资料,直接返回未提及`);
|
|
3805
|
+
return this.renderer.send(
|
|
3806
|
+
session,
|
|
3807
|
+
`${NO_ANSWER_TEXT}
|
|
3808
|
+
|
|
3809
|
+
数据来源:缺氧 BWIKI`
|
|
3810
|
+
);
|
|
3811
|
+
}
|
|
3812
|
+
try {
|
|
3813
|
+
const answer = await this.ai.chat(
|
|
3814
|
+
buildMessages(
|
|
3815
|
+
keyword,
|
|
3816
|
+
chunks,
|
|
3817
|
+
context.turns.map((turn) => ({
|
|
3818
|
+
question: turn.question,
|
|
3819
|
+
answer: turn.answer
|
|
3820
|
+
}))
|
|
3821
|
+
)
|
|
3822
|
+
);
|
|
3823
|
+
this.remember(session, keyword, answer, chunks);
|
|
3824
|
+
return this.renderAnswer(session, answer, chunks, context.inheritedFrom);
|
|
3825
|
+
} catch (error) {
|
|
3826
|
+
logger.error(`[ai] 「${keyword}」回答失败:${getErrorMessage(error)}`);
|
|
3827
|
+
return this.renderer.send(
|
|
3828
|
+
session,
|
|
3829
|
+
"❌ AI 服务暂时不可用,请稍后再试(管理员可查看日志)"
|
|
3830
|
+
);
|
|
3831
|
+
}
|
|
3832
|
+
});
|
|
3833
|
+
ctx.command("ai.status", "查看 AI 问答与向量索引状态", { authority: 1 }).action(async () => {
|
|
3834
|
+
const stats = this.ctx.vector ? await this.ctx.vector.stats() : { enabled: false, path: "-", items: 0, bytes: 0 };
|
|
3835
|
+
const rows = await ctx.database.get("wikitexts", {}, ["id"]);
|
|
3836
|
+
const indexSize = `${(stats.bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
3837
|
+
const lines = [
|
|
3838
|
+
"📊 AI 问答状态",
|
|
3839
|
+
`├─ AI 问答:${this.ai.enabled ? "✅ 已启用" : "❌ 未配置 API Key"}`,
|
|
3840
|
+
`├─ 模型:${this.config.deepseekModel}`,
|
|
3841
|
+
`├─ 向量检索:${stats.enabled ? "✅ 已启用" : "❌ 已关闭"}`,
|
|
3842
|
+
`├─ Embedding:${this.config.embeddingModel}(${this.config.embeddingDtype})`,
|
|
3843
|
+
`├─ 索引目录:${stats.path}`,
|
|
3844
|
+
`├─ 索引文本块:${stats.items}`,
|
|
3845
|
+
`├─ 索引体积:${indexSize}`,
|
|
3846
|
+
`├─ 会话记忆:${this.config.aiMemoryTurns > 0 ? `${this.config.aiMemoryTurns} 轮 / ${Math.round(this.config.aiMemoryTtl / 60)} 分钟` : "已关闭"}`,
|
|
3847
|
+
`├─ 群内追问:${this.config.aiChannelMemory && this.config.aiMemoryTurns > 0 ? "✅ 开启" : "❌ 关闭"}`,
|
|
3848
|
+
`└─ 已入库页面:${rows.length}`
|
|
3849
|
+
];
|
|
3850
|
+
if (stats.items > 2e4) {
|
|
3851
|
+
lines.push(
|
|
3852
|
+
"",
|
|
3853
|
+
`⚠️ 索引已较大(${stats.items} 个文本块,约 ${indexSize}),`,
|
|
3854
|
+
"2G 内存机器建议把 maxChunksPerPage 调到 12 后执行 ai.reindex。"
|
|
3855
|
+
);
|
|
3856
|
+
}
|
|
3857
|
+
return lines.join("\n");
|
|
3858
|
+
});
|
|
3859
|
+
ctx.command("ai.sync [pageTitle:text]", "抓取 BWiki 渲染文本(不填页面则全量)", {
|
|
3860
|
+
authority: 4
|
|
3861
|
+
}).action(async ({ session }, pageTitle) => {
|
|
3862
|
+
const title = (pageTitle ?? "").trim();
|
|
3863
|
+
const syncer = this.textSync;
|
|
3864
|
+
if (title) {
|
|
3865
|
+
const result = await syncer.syncOne(title);
|
|
3866
|
+
if (!result.success) {
|
|
3867
|
+
return this.renderer.send(
|
|
3868
|
+
session,
|
|
3869
|
+
`❌ 页面「${title}」渲染文本抓取失败:${result.reason}${result.message ? `(${result.message})` : ""}`
|
|
3870
|
+
);
|
|
3871
|
+
}
|
|
3872
|
+
return this.renderer.send(
|
|
3873
|
+
session,
|
|
3874
|
+
result.reason === "synced" ? `✅ 页面「${title}」的渲染文本已更新并写入索引` : `🟡 页面「${title}」的正文没有变化,已跳过`
|
|
3875
|
+
);
|
|
3876
|
+
}
|
|
3877
|
+
await session?.send(
|
|
3878
|
+
"🚀 开始全量抓取 BWiki 渲染文本,耗时较长,完成后我会再回复一次"
|
|
3879
|
+
);
|
|
3880
|
+
let summary;
|
|
3881
|
+
try {
|
|
3882
|
+
summary = await syncer.syncAll();
|
|
3883
|
+
} catch (error) {
|
|
3884
|
+
logger.error(`[ai] 全量渲染文本抓取失败:${getErrorMessage(error)}`);
|
|
3885
|
+
return this.renderer.send(
|
|
3886
|
+
session,
|
|
3887
|
+
`❌ 全量抓取失败:${getErrorMessage(error)}`
|
|
3888
|
+
);
|
|
3889
|
+
}
|
|
3890
|
+
logger.info(`[ai] 全量渲染文本抓取完成:${JSON.stringify(summary)}`);
|
|
3891
|
+
if (summary.total === 0) {
|
|
3892
|
+
return this.renderer.send(
|
|
3893
|
+
session,
|
|
3894
|
+
"❌ 没有抓到任何页面:BWiki 的 allpages 查询为空,请检查 textApiUrl / 网络"
|
|
3895
|
+
);
|
|
3896
|
+
}
|
|
3897
|
+
return this.renderer.send(
|
|
3898
|
+
session,
|
|
3899
|
+
`✅ 渲染文本抓取完成
|
|
3900
|
+
├─ 总计:${summary.total} 个页面
|
|
3901
|
+
├─ 新增/更新:${summary.synced}
|
|
3902
|
+
├─ 未变化:${summary.unchanged}
|
|
3903
|
+
├─ 页面不存在:${summary.missing}
|
|
3904
|
+
└─ 失败:${summary.failed}`
|
|
3905
|
+
);
|
|
3906
|
+
});
|
|
3907
|
+
ctx.command("ai.reindex", "用本地已存的正文重建向量索引", { authority: 4 }).action(async ({ session }) => {
|
|
3908
|
+
const vector = this.ctx.vector;
|
|
3909
|
+
if (!this.config.vectorEnabled || !vector) {
|
|
3910
|
+
return this.renderer.send(
|
|
3911
|
+
session,
|
|
3912
|
+
"❌ 向量检索未启用(vectra 未加载或 vectorEnabled=false)"
|
|
3913
|
+
);
|
|
3914
|
+
}
|
|
3915
|
+
const rows = await ctx.database.get("wikitexts", {});
|
|
3916
|
+
if (rows.length === 0) {
|
|
3917
|
+
return this.renderer.send(
|
|
3918
|
+
session,
|
|
3919
|
+
"❌ 本地还没有渲染文本,请先执行 ai.sync"
|
|
3920
|
+
);
|
|
3921
|
+
}
|
|
3922
|
+
await session?.send(
|
|
3923
|
+
`🚀 开始重建向量索引(${rows.length} 个页面),请耐心等待`
|
|
3924
|
+
);
|
|
3925
|
+
await vector.reset();
|
|
3926
|
+
let chunks = 0;
|
|
3927
|
+
for (let index = 0; index < rows.length; index++) {
|
|
3928
|
+
const row = rows[index];
|
|
3929
|
+
chunks += await vector.indexPage({
|
|
3930
|
+
id: row.id,
|
|
3931
|
+
title: row.title || row.id,
|
|
3932
|
+
url: this.pageUrl(row.id),
|
|
3933
|
+
text: row.text
|
|
3934
|
+
});
|
|
3935
|
+
if ((index + 1) % 20 === 0 || index === rows.length - 1) {
|
|
3936
|
+
logger.info(
|
|
3937
|
+
`[ai] 索引重建进度 ${index + 1}/${rows.length}(${chunks} 个文本块)`
|
|
3938
|
+
);
|
|
3939
|
+
}
|
|
3940
|
+
}
|
|
3941
|
+
return this.renderer.send(
|
|
3942
|
+
session,
|
|
3943
|
+
`✅ 向量索引重建完成:${rows.length} 个页面 / ${chunks} 个文本块`
|
|
3944
|
+
);
|
|
3945
|
+
});
|
|
3946
|
+
}
|
|
3947
|
+
// ------------------------------------------------------------ 检索与回复
|
|
3948
|
+
/**
|
|
3949
|
+
* 检索当前问题需要的资料。
|
|
3950
|
+
*
|
|
3951
|
+
* 追问场景(「那它能干什么」)单独检索会丢掉主语,因此:
|
|
3952
|
+
* 1. 把上一轮问题拼进检索串,让 Embedding 仍然指向同一个对象;
|
|
3953
|
+
* 2. 本轮真的什么都没检索到时,沿用上一轮的资料,避免直接答「未提及」。
|
|
3954
|
+
*/
|
|
3955
|
+
async retrieve(question, history = []) {
|
|
3956
|
+
const topK = this.config.retrieveTopK;
|
|
3957
|
+
const query = this.buildRetrievalQuery(question, history);
|
|
3958
|
+
const chunks = await this.searchChunks(query, topK);
|
|
3959
|
+
if (chunks.length > 0) return chunks;
|
|
3960
|
+
const previous = history[history.length - 1];
|
|
3961
|
+
if (previous?.chunks.length) {
|
|
3962
|
+
logger.info(
|
|
3963
|
+
`[ai] 「${question}」未检索到新资料,沿用上一轮「${previous.question}」的片段`
|
|
3964
|
+
);
|
|
3965
|
+
return previous.chunks.slice(0, topK);
|
|
3966
|
+
}
|
|
3967
|
+
return [];
|
|
3968
|
+
}
|
|
3969
|
+
/** 把上一轮问题并入检索串;保留结尾(即当前问题)优先 */
|
|
3970
|
+
buildRetrievalQuery(question, history) {
|
|
3971
|
+
if (history.length === 0) return question;
|
|
3972
|
+
const merged = `${history[history.length - 1].question} ${question}`.trim();
|
|
3973
|
+
return merged.length > 150 ? merged.slice(-150) : merged;
|
|
3974
|
+
}
|
|
3975
|
+
async searchChunks(query, topK) {
|
|
3976
|
+
const vector = this.ctx.vector;
|
|
3977
|
+
if (this.config.vectorEnabled && vector) {
|
|
3978
|
+
try {
|
|
3979
|
+
const hits = await vector.search(query, topK);
|
|
3980
|
+
if (hits.length > 0) {
|
|
3981
|
+
return hits.map((hit) => ({
|
|
3982
|
+
title: hit.title,
|
|
3983
|
+
url: hit.url || this.pageUrl(hit.documentId),
|
|
3984
|
+
text: hit.text
|
|
3985
|
+
}));
|
|
3986
|
+
}
|
|
3987
|
+
} catch (error) {
|
|
3988
|
+
logger.warn(
|
|
3989
|
+
`[ai] 向量检索失败,改用标题匹配兜底:${getErrorMessage(error)}`
|
|
3990
|
+
);
|
|
3991
|
+
}
|
|
3992
|
+
}
|
|
3993
|
+
return this.fallbackRetrieve(query, topK);
|
|
3994
|
+
}
|
|
3995
|
+
async fallbackRetrieve(question, limit) {
|
|
3996
|
+
const pages = await this.ctx.database.get("wikipages", {});
|
|
3997
|
+
if (pages.length === 0) return [];
|
|
3998
|
+
const queryKey = question.toLowerCase();
|
|
3999
|
+
const { pinyin_full, pinyin_first } = generatePinyinInfo(question);
|
|
4000
|
+
const matches = findFuzzyMatches(
|
|
4001
|
+
pages,
|
|
4002
|
+
queryKey,
|
|
4003
|
+
pinyin_full,
|
|
4004
|
+
pinyin_first,
|
|
4005
|
+
limit
|
|
4006
|
+
);
|
|
4007
|
+
const chunks = [];
|
|
4008
|
+
for (const match of matches) {
|
|
4009
|
+
const rows = await this.ctx.database.get("wikitexts", {
|
|
4010
|
+
id: match.title
|
|
4011
|
+
});
|
|
4012
|
+
const row = rows[0];
|
|
4013
|
+
if (!row?.text) continue;
|
|
4014
|
+
chunks.push({
|
|
4015
|
+
title: row.title || match.title,
|
|
4016
|
+
url: this.pageUrl(match.title),
|
|
4017
|
+
text: row.text.slice(0, MAX_CONTEXT_CHARS)
|
|
4018
|
+
});
|
|
4019
|
+
}
|
|
4020
|
+
return chunks;
|
|
4021
|
+
}
|
|
4022
|
+
async renderAnswer(session, answer, chunks, inheritedFrom) {
|
|
4023
|
+
const noAnswer = isNoAnswer(answer);
|
|
4024
|
+
const sources = [];
|
|
4025
|
+
if (!noAnswer) {
|
|
4026
|
+
for (const chunk of chunks) {
|
|
4027
|
+
if (sources.some((source) => source.title === chunk.title)) continue;
|
|
4028
|
+
sources.push({ title: chunk.title, url: chunk.url || "" });
|
|
4029
|
+
if (sources.length >= 3) break;
|
|
4030
|
+
}
|
|
4031
|
+
}
|
|
4032
|
+
const inherited = inheritedFrom ? `💭 承接群内上一问:${inheritedFrom}` : void 0;
|
|
4033
|
+
if (this.renderer.isQQ(session)) {
|
|
4034
|
+
let markdown = `**🤖 AI 回答**
|
|
4035
|
+
${truncateForQQ(answer)}`;
|
|
4036
|
+
if (inherited) markdown += `
|
|
4037
|
+
|
|
4038
|
+
> ${inherited}`;
|
|
4039
|
+
if (sources.length > 0) {
|
|
4040
|
+
markdown += `
|
|
4041
|
+
|
|
4042
|
+
---
|
|
4043
|
+
> 📚 **数据来源:缺氧 BWIKI**`;
|
|
4044
|
+
for (const source of sources) {
|
|
4045
|
+
markdown += source.url ? `
|
|
4046
|
+
> 🔗 [${source.title}](${source.url})` : `
|
|
4047
|
+
> 🔗 ${source.title}`;
|
|
4048
|
+
}
|
|
4049
|
+
} else {
|
|
4050
|
+
markdown += `
|
|
4051
|
+
|
|
4052
|
+
> 📚 数据来源:缺氧 BWIKI`;
|
|
4053
|
+
}
|
|
4054
|
+
return this.renderer.send(session, markdown);
|
|
4055
|
+
}
|
|
4056
|
+
let message = `🤖 AI 回答
|
|
4057
|
+
${answer}`;
|
|
4058
|
+
if (inherited) message += `
|
|
4059
|
+
|
|
4060
|
+
${inherited}`;
|
|
4061
|
+
if (sources.length === 0) {
|
|
4062
|
+
message += `
|
|
4063
|
+
|
|
4064
|
+
📚 数据来源:缺氧 BWIKI`;
|
|
4065
|
+
return message;
|
|
4066
|
+
}
|
|
4067
|
+
message += `
|
|
4068
|
+
|
|
4069
|
+
📚 数据来源:缺氧 BWIKI`;
|
|
4070
|
+
for (const source of sources) {
|
|
4071
|
+
message += source.url ? `
|
|
4072
|
+
🔗 ${source.title}:${source.url}` : `
|
|
4073
|
+
🔗 ${source.title}`;
|
|
4074
|
+
}
|
|
4075
|
+
return message;
|
|
4076
|
+
}
|
|
4077
|
+
pageUrl(title) {
|
|
4078
|
+
return buildPageUrl(this.pageUrlBase, title);
|
|
4079
|
+
}
|
|
4080
|
+
/** 返回剩余冷却秒数,0 表示可以提问 */
|
|
4081
|
+
cooldownLeft(session) {
|
|
4082
|
+
const cooldown = this.config.aiCooldown * 1e3;
|
|
4083
|
+
if (!session || cooldown <= 0) return 0;
|
|
4084
|
+
const key = this.sessionKey(session);
|
|
4085
|
+
const now = Date.now();
|
|
4086
|
+
const last = this.lastAskedAt.get(key) ?? 0;
|
|
4087
|
+
const remaining = last + cooldown - now;
|
|
4088
|
+
if (remaining > 0) {
|
|
4089
|
+
return Math.ceil(remaining / 1e3);
|
|
4090
|
+
}
|
|
4091
|
+
this.lastAskedAt.set(key, now);
|
|
4092
|
+
if (this.lastAskedAt.size > 1e3) {
|
|
4093
|
+
for (const [storedKey, at] of this.lastAskedAt) {
|
|
4094
|
+
if (now - at > cooldown * 10) this.lastAskedAt.delete(storedKey);
|
|
4095
|
+
}
|
|
4096
|
+
}
|
|
4097
|
+
return 0;
|
|
4098
|
+
}
|
|
4099
|
+
// ------------------------------------------------------------ 短期记忆
|
|
4100
|
+
/**
|
|
4101
|
+
* 记忆键:平台 + 频道 + 用户。
|
|
4102
|
+
*
|
|
4103
|
+
* 按用户隔离而不是按频道,避免群里 A 的追问被 B 的问题串了话题;
|
|
4104
|
+
* 控制台/无会话调用时返回空串,此时不记也不读。
|
|
4105
|
+
*/
|
|
4106
|
+
sessionKey(session) {
|
|
4107
|
+
if (!session) return "";
|
|
4108
|
+
return `${session.platform}:${session.channelId}:${session.userId ?? ""}`;
|
|
4109
|
+
}
|
|
4110
|
+
/** 群话题键:平台 + 频道(不含用户),用于跨用户的追问承接 */
|
|
4111
|
+
channelKey(session) {
|
|
4112
|
+
if (!session) return "";
|
|
4113
|
+
return `topic:${session.platform}:${session.channelId}`;
|
|
4114
|
+
}
|
|
4115
|
+
/** 取最近的若干轮记忆(已剔除过期项) */
|
|
4116
|
+
history(session) {
|
|
4117
|
+
return this.memory.get(this.sessionKey(session));
|
|
4118
|
+
}
|
|
4119
|
+
/**
|
|
4120
|
+
* 决定这一问用哪段上下文。
|
|
4121
|
+
*
|
|
4122
|
+
* - 自己刚问过 → 用**自己的**历史(优先,避免被别人的话题带偏);
|
|
4123
|
+
* - 自己没记录、且开启了 `aiChannelMemory` → 承接**群里上一轮**,
|
|
4124
|
+
* 这样 alice 问「氧石精炼炉是什么」,bob 接着问「那它耗电多少」也能答;
|
|
4125
|
+
* - 都没有 → 单轮问答。
|
|
4126
|
+
*/
|
|
4127
|
+
resolveContext(session) {
|
|
4128
|
+
return pickContext(
|
|
4129
|
+
this.history(session),
|
|
4130
|
+
this.channelMemory.get(this.channelKey(session)),
|
|
4131
|
+
this.config.aiChannelMemory
|
|
4132
|
+
);
|
|
4133
|
+
}
|
|
4134
|
+
/** 记录一轮问答:同时写用户记忆与群话题(后者供其他人追问) */
|
|
4135
|
+
remember(session, question, answer, chunks) {
|
|
4136
|
+
const turn = { question, answer, chunks };
|
|
4137
|
+
this.memory.add(this.sessionKey(session), turn);
|
|
4138
|
+
if (!isNoAnswer(answer)) {
|
|
4139
|
+
this.channelMemory.add(this.channelKey(session), turn);
|
|
4140
|
+
}
|
|
4141
|
+
}
|
|
4142
|
+
};
|
|
4143
|
+
function truncateForQQ(text, max = 1e3) {
|
|
4144
|
+
return text.length <= max ? text : `${text.slice(0, max)}…`;
|
|
4145
|
+
}
|
|
4146
|
+
__name(truncateForQQ, "truncateForQQ");
|
|
4147
|
+
|
|
2699
4148
|
// src/index.ts
|
|
2700
4149
|
var name = "oni-sync-bot";
|
|
2701
4150
|
var SUB_PLUGINS = [
|
|
2702
4151
|
WikiBotService,
|
|
4152
|
+
VectorService,
|
|
2703
4153
|
ConsoleLogProvider,
|
|
2704
4154
|
DatabaseExtension,
|
|
2705
4155
|
RouteRedirect,
|
|
2706
4156
|
SyncCommands,
|
|
2707
4157
|
QueryCommands,
|
|
2708
4158
|
UpdateCommands,
|
|
2709
|
-
TodoList
|
|
4159
|
+
TodoList,
|
|
4160
|
+
AiQueryCommands
|
|
2710
4161
|
];
|
|
2711
4162
|
function apply(ctx, config) {
|
|
2712
4163
|
for (const plugin of SUB_PLUGINS) {
|
|
@@ -2714,8 +4165,8 @@ function apply(ctx, config) {
|
|
|
2714
4165
|
}
|
|
2715
4166
|
ctx.inject(["console"], (ctx2) => {
|
|
2716
4167
|
ctx2.console.addEntry({
|
|
2717
|
-
dev: (0,
|
|
2718
|
-
prod: (0,
|
|
4168
|
+
dev: (0, import_path2.resolve)(__dirname, "../client/index.ts"),
|
|
4169
|
+
prod: (0, import_path2.resolve)(__dirname, "../dist")
|
|
2719
4170
|
});
|
|
2720
4171
|
});
|
|
2721
4172
|
}
|