koishi-plugin-oni-sync-bot 0.10.0 → 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.
@@ -0,0 +1,82 @@
1
+ import { Context } from "koishi";
2
+ import type { AiConfig, SiteConfig, VectorConfig, WikiTextConfig } from "../config";
3
+ export type AiQueryConfig = AiConfig & VectorConfig & Pick<WikiTextConfig, "textApiUrl" | "textTableMode" | "textMaxLength" | "textSyncInterval"> & Pick<SiteConfig, "domain" | "bwiki_site">;
4
+ /**
5
+ * `.ai` 问答:本地向量检索 + DeepSeek 总结。
6
+ *
7
+ * 数据链路(源码永远不参与 AI):
8
+ * `BWiki action=parse` → HTML → 纯文本(`wikitexts` 表)→ vectra 索引 → 检索片段 → DeepSeek。
9
+ *
10
+ * 为什么单独做成子插件而不是塞进 QueryCommands:
11
+ * `QueryCommands` 只依赖数据库、回复的是页面链接;AI 问答额外依赖 http + 向量库 + 外部 API,
12
+ * 单独成插件后,任何一环没配好都不会影响原有的 `x` 拼音查询。
13
+ */
14
+ export declare class AiQueryCommands {
15
+ private readonly ctx;
16
+ /** `http` / `vector` 可选:缺任意一项时 `.ai` 仍应能给出明确提示,而不是整组命令消失 */
17
+ static readonly inject: {
18
+ database: {
19
+ required: boolean;
20
+ };
21
+ wikiBot: {
22
+ required: boolean;
23
+ };
24
+ http: {
25
+ required: boolean;
26
+ };
27
+ vector: {
28
+ required: boolean;
29
+ };
30
+ };
31
+ private readonly config;
32
+ private readonly renderer;
33
+ private readonly ai;
34
+ private readonly textSync;
35
+ private readonly pageUrlBase;
36
+ /** 用户 → 上次提问时间,用于冷却 */
37
+ private readonly lastAskedAt;
38
+ /** 用户 → 最近几轮问答(含当轮检索到的资料),用于追问 */
39
+ private readonly memory;
40
+ /** 频道 → 最近一轮问答,用于「群里别人刚问过,我接着问」 */
41
+ private readonly channelMemory;
42
+ constructor(ctx: Context, config: AiQueryConfig);
43
+ private registerCommands;
44
+ /**
45
+ * 检索当前问题需要的资料。
46
+ *
47
+ * 追问场景(「那它能干什么」)单独检索会丢掉主语,因此:
48
+ * 1. 把上一轮问题拼进检索串,让 Embedding 仍然指向同一个对象;
49
+ * 2. 本轮真的什么都没检索到时,沿用上一轮的资料,避免直接答「未提及」。
50
+ */
51
+ private retrieve;
52
+ /** 把上一轮问题并入检索串;保留结尾(即当前问题)优先 */
53
+ private buildRetrievalQuery;
54
+ private searchChunks;
55
+ private fallbackRetrieve;
56
+ private renderAnswer;
57
+ private pageUrl;
58
+ /** 返回剩余冷却秒数,0 表示可以提问 */
59
+ private cooldownLeft;
60
+ /**
61
+ * 记忆键:平台 + 频道 + 用户。
62
+ *
63
+ * 按用户隔离而不是按频道,避免群里 A 的追问被 B 的问题串了话题;
64
+ * 控制台/无会话调用时返回空串,此时不记也不读。
65
+ */
66
+ private sessionKey;
67
+ /** 群话题键:平台 + 频道(不含用户),用于跨用户的追问承接 */
68
+ private channelKey;
69
+ /** 取最近的若干轮记忆(已剔除过期项) */
70
+ private history;
71
+ /**
72
+ * 决定这一问用哪段上下文。
73
+ *
74
+ * - 自己刚问过 → 用**自己的**历史(优先,避免被别人的话题带偏);
75
+ * - 自己没记录、且开启了 `aiChannelMemory` → 承接**群里上一轮**,
76
+ * 这样 alice 问「氧石精炼炉是什么」,bob 接着问「那它耗电多少」也能答;
77
+ * - 都没有 → 单轮问答。
78
+ */
79
+ private resolveContext;
80
+ /** 记录一轮问答:同时写用户记忆与群话题(后者供其他人追问) */
81
+ private remember;
82
+ }
@@ -2,6 +2,7 @@ import { Context } from "koishi";
2
2
  declare module "koishi" {
3
3
  interface Tables {
4
4
  wikipages: WikiPages;
5
+ wikitexts: WikiTexts;
5
6
  }
6
7
  }
7
8
  export interface WikiPages {
@@ -12,6 +13,23 @@ export interface WikiPages {
12
13
  contributor?: string;
13
14
  change_time?: string;
14
15
  }
16
+ /**
17
+ * BWiki 渲染后的纯文本(AI 检索的唯一数据来源)。
18
+ *
19
+ * 主键用**页面标题**而不是自增 id:标题与 `wikipages.title` 天然对齐,
20
+ * `upsert` 可以直接按标题覆盖,不需要额外查询。
21
+ */
22
+ export interface WikiTexts {
23
+ /** 主键:页面标题 */
24
+ id: string;
25
+ title: string;
26
+ pageid?: number;
27
+ revid?: number;
28
+ /** 正文的 sha1,用于跳过未变化的页面(避免重复 Embedding) */
29
+ hash: string;
30
+ text: string;
31
+ updated_at: string;
32
+ }
15
33
  export declare class DatabaseExtension {
16
34
  static readonly inject: string[];
17
35
  constructor(ctx: Context);
@@ -1,15 +1,46 @@
1
1
  import { Context } from "koishi";
2
- import type { NotifyConfig } from "../config";
2
+ import type { NotifyConfig, SiteConfig, VectorConfig, WikiTextConfig } from "../config";
3
3
  /**
4
- * 实际只消费日志地址与通知字段;账号与站点配置由其它子插件使用,
5
- * 因此这里不再重复声明(详见 src/config.ts)。
4
+ * 实际只消费日志地址 / 通知字段 / 站点域名 / 渲染文本与向量相关开关;
5
+ * 账号配置由 WikiBotService 使用,因此这里不再重复声明(详见 src/config.ts)。
6
6
  */
7
- export type SyncCommandsConfig = NotifyConfig;
7
+ export type SyncCommandsConfig = NotifyConfig & Pick<SiteConfig, "bwiki_site"> & Pick<VectorConfig, "vectorEnabled"> & Pick<WikiTextConfig, "textSyncOnChange" | "textApiUrl" | "textTableMode" | "textMaxLength" | "textSyncInterval">;
8
8
  export declare class SyncCommands {
9
- static readonly inject: string[];
9
+ /**
10
+ * `cron` / `http` / `vector` 都是**可选**依赖:
11
+ * 任何一项没装,同步命令仍必须可用(只是少了定时任务 / 渲染文本抽取)。
12
+ * 早期把它们写成必需项,曾在实例未启用 koishi-plugin-cron 时导致
13
+ * 整个子插件一直 pending,`sync` 系列命令凭空消失。
14
+ */
15
+ static readonly inject: {
16
+ wikiBot: {
17
+ required: boolean;
18
+ };
19
+ database: {
20
+ required: boolean;
21
+ };
22
+ cron: {
23
+ required: boolean;
24
+ };
25
+ http: {
26
+ required: boolean;
27
+ };
28
+ vector: {
29
+ required: boolean;
30
+ };
31
+ };
10
32
  config: SyncCommandsConfig;
11
33
  private notifyFn?;
34
+ /** 同步成功后抽取渲染文本(未开启时为空) */
35
+ private textSync?;
12
36
  constructor(ctx: Context, config: SyncCommandsConfig);
37
+ /**
38
+ * 构造「渲染文本同步器」:页面同步成功后再回 bwiki 取一次渲染结果。
39
+ * `textSyncOnChange` 关闭时不创建(同步后不做任何额外请求)。
40
+ */
41
+ private createTextSyncer;
42
+ /** 统一的 PageSyncer 构造:数据库、通知与「同步后抽取文本」钩子都在这里装配 */
43
+ private createPageSyncer;
13
44
  /** 同步相关的定时任务;cron 表达式即调度策略,集中在一处便于对照 */
14
45
  private registerScheduledTasks;
15
46
  private ensureBotsReady;
@@ -34,7 +34,21 @@ export interface OniTodoItem {
34
34
  }
35
35
  export declare class TodoList {
36
36
  ctx: Context;
37
- static readonly inject: string[];
37
+ /** `cron` 可选:未启用定时任务插件时,TodoList 的命令与控制台仍需可用 */
38
+ static readonly inject: {
39
+ database: {
40
+ required: boolean;
41
+ };
42
+ console: {
43
+ required: boolean;
44
+ };
45
+ wikiBot: {
46
+ required: boolean;
47
+ };
48
+ cron: {
49
+ required: boolean;
50
+ };
51
+ };
38
52
  log: Logger;
39
53
  constructor(ctx: Context);
40
54
  private registerCronJobs;
@@ -5,7 +5,18 @@ export interface UpdateCommandsConfig extends Pick<NotifyConfig, "logsUrl">, Sch
5
5
  }
6
6
  export declare class UpdateCommands {
7
7
  ctx: Context;
8
- static readonly inject: string[];
8
+ /** `cron` 可选:定时刷新缓存是增强项,命令本身必须始终可用 */
9
+ static readonly inject: {
10
+ database: {
11
+ required: boolean;
12
+ };
13
+ wikiBot: {
14
+ required: boolean;
15
+ };
16
+ cron: {
17
+ required: boolean;
18
+ };
19
+ };
9
20
  config: UpdateCommandsConfig;
10
21
  log: Logger;
11
22
  constructor(ctx: Context, config: UpdateCommandsConfig);
@@ -0,0 +1,50 @@
1
+ import type { AiContextChunk } from "./aiService";
2
+ /** 一轮短期记忆:问题、回答,以及当轮用到的资料(供追问时复用) */
3
+ export interface MemoryTurn {
4
+ question: string;
5
+ answer: string;
6
+ chunks: AiContextChunk[];
7
+ at: number;
8
+ }
9
+ /**
10
+ * `.ai` 的短期记忆(纯内存,重启即清空)。
11
+ *
12
+ * 为什么需要它:`ai 电解器耗电多少` 之后接一句「那它能干什么」,
13
+ * 单轮检索拿不到主语,模型也无从知道「它」指谁。
14
+ *
15
+ * 边界约定:
16
+ * - `maxTurns <= 0` 表示关闭记忆;
17
+ * - 每轮超过 `ttlMs` 视为新话题(默认 10 分钟),避免很早之前的问答污染当前问题;
18
+ * - 每个键(平台:频道:用户)只保留最近 `maxTurns` 轮;
19
+ * - 不做持久化——记忆只是对话顺畅度,不值得写库。
20
+ */
21
+ export declare class AiMemory {
22
+ private readonly maxTurns;
23
+ private readonly ttlMs;
24
+ private readonly now;
25
+ private readonly store;
26
+ constructor(maxTurns: number, ttlMs: number, now?: () => number);
27
+ get enabled(): boolean;
28
+ /** 读取最近的记忆轮次(已剔除过期项,并按 `maxTurns` 截断) */
29
+ get(key: string | undefined): MemoryTurn[];
30
+ /** 追加一轮问答;超出上限时丢弃最旧的一轮 */
31
+ add(key: string | undefined, turn: {
32
+ question: string;
33
+ answer: string;
34
+ chunks: AiContextChunk[];
35
+ }): void;
36
+ clear(key: string): void;
37
+ private prune;
38
+ /** 防止长期运行下 Map 无限增长:清理已过期的键 */
39
+ private evictStale;
40
+ }
41
+ /**
42
+ * 决定这一问使用哪段上下文。
43
+ *
44
+ * 优先级:**自己的历史** > **群内上一轮**(可关闭)> 单轮问答。
45
+ * 自己的历史优先,避免用户正在聊 A 时被群里刚聊过的 B 带偏。
46
+ */
47
+ export declare function pickContext(own: MemoryTurn[], shared: MemoryTurn[], channelMemoryEnabled: boolean): {
48
+ turns: MemoryTurn[];
49
+ inheritedFrom?: string;
50
+ };
@@ -0,0 +1,54 @@
1
+ import { Context } from "koishi";
2
+ import type { AiConfig } from "../config";
3
+ export interface ChatMessage {
4
+ role: "system" | "user" | "assistant";
5
+ content: string;
6
+ }
7
+ /** 送进模型的检索片段 */
8
+ export interface AiContextChunk {
9
+ title: string;
10
+ url?: string;
11
+ text: string;
12
+ }
13
+ /**
14
+ * 防幻觉用的系统提示词。
15
+ *
16
+ * 要求逐字保留「严格且仅根据资料回答 / 资料中未提及就直说」这两条硬约束,
17
+ * 因为在缺氧这种数值密集的游戏里,模型一旦动用现实世界的物理直觉就会编造数值。
18
+ */
19
+ export declare const SYSTEM_PROMPT: string;
20
+ /** 检索为空时直接使用该文案,避免无意义的模型调用 */
21
+ export declare const NO_ANSWER_TEXT = "\u62B1\u6B49\uFF0C\u8D44\u6599\u4E2D\u672A\u63D0\u53CA\u76F8\u5173\u4FE1\u606F\u3002";
22
+ /** 判断模型回答是否就是「资料未提及」(用于决定要不要展示来源) */
23
+ export declare function isNoAnswer(answer: string): boolean;
24
+ /** 一轮历史问答(用于多轮追问) */
25
+ export interface AiHistoryTurn {
26
+ question: string;
27
+ answer: string;
28
+ }
29
+ /** 把检索片段拼成提示词里的「资料」区块 */
30
+ export declare function buildContext(chunks: AiContextChunk[]): string;
31
+ /**
32
+ * 组装 DeepSeek 的 messages:资料进 system,历史问答按轮次回放,用户问题进 user。
33
+ *
34
+ * 多轮时把之前的问答作为 `user`/`assistant` 交替插入,模型才能理解「它」指的是谁;
35
+ * 但每轮的**资料仍然是当前检索到的那一份**,避免历史回答被当成新事实。
36
+ */
37
+ export declare function buildMessages(question: string, chunks: AiContextChunk[], history?: AiHistoryTurn[]): ChatMessage[];
38
+ /**
39
+ * DeepSeek 对话客户端。
40
+ *
41
+ * 只用 `ctx.http`,不额外引入 SDK:请求体就是标准的 chat/completions,
42
+ * 这样在 2G 小机器上少一个依赖、少一份常驻内存。
43
+ */
44
+ export declare class AiService {
45
+ private readonly ctx;
46
+ private readonly settings;
47
+ constructor(ctx: Context, settings: AiConfig);
48
+ get apiKey(): string;
49
+ get enabled(): boolean;
50
+ chat(messages: ChatMessage[], options?: {
51
+ temperature?: number;
52
+ maxTokens?: number;
53
+ }): Promise<string>;
54
+ }
@@ -0,0 +1,24 @@
1
+ import type { Mwn } from "mwn";
2
+ export interface ReloginAwareProxyOptions {
3
+ /** 取当前 bot;未就绪时抛错 */
4
+ getBot: () => Mwn;
5
+ /** 登录态失效时调用,用于重新登录 */
6
+ relogin: () => Promise<void>;
7
+ /** 出错信息里使用的站点名 */
8
+ label: string;
9
+ }
10
+ /**
11
+ * 生成一个「登录态永远有效」的客户端代理。
12
+ *
13
+ * 为什么必须是代理而不是普通对象:Mwn 的方法很多,调用方还需要
14
+ * `continuedQueryGen` 这类**异步生成器**以及 `options` 这类**非函数属性**。
15
+ * 代理可以完整转发任意成员,同时把「assert=user 失败 → 重新登录 → 重放调用」
16
+ * 这件事对调用方完全隐藏。
17
+ *
18
+ * ⚠️ 转发时**必须保留 `this` 绑定**:一律用 `fn.apply(bot, args)`,
19
+ * 不能把方法先取出来再裸调(`const f = bot.f; f(...)`)。
20
+ * Mwn 的方法内部会访问 `this.request` 等成员,丢失 `this` 会直接抛
21
+ * `Cannot read properties of undefined (reading 'request')`。
22
+ * 该约束由 tests/reloginAwareProxy.spec.ts 覆盖。
23
+ */
24
+ export declare function createReloginAwareProxy(options: ReloginAwareProxyOptions): Mwn;
@@ -0,0 +1,84 @@
1
+ import { Context, Service } from "koishi";
2
+ import type { VectorConfig } from "../config";
3
+ declare module "koishi" {
4
+ interface Context {
5
+ vector: VectorService;
6
+ }
7
+ }
8
+ /** 索引里每个文本块携带的元数据(id 形如 `页面标题#块序号`) */
9
+ export interface VectorChunkMetadata {
10
+ [key: string]: string | number | boolean;
11
+ documentId: string;
12
+ title: string;
13
+ url: string;
14
+ chunkIndex: number;
15
+ text: string;
16
+ }
17
+ /** 写入索引所需的页面内容 */
18
+ export interface VectorPage {
19
+ /** 与 `wikitexts.id` 一致:页面标题 */
20
+ id: string;
21
+ title: string;
22
+ url: string;
23
+ text: string;
24
+ }
25
+ /** 一次检索命中的文本块 */
26
+ export interface VectorHit {
27
+ documentId: string;
28
+ title: string;
29
+ url: string;
30
+ text: string;
31
+ score: number;
32
+ }
33
+ /** VectorService 对外暴露的最小能力,便于在单元测试里替换成替身 */
34
+ export interface VectorIndexer {
35
+ indexPage(page: VectorPage): Promise<number>;
36
+ removePage(documentId: string): Promise<void>;
37
+ }
38
+ /**
39
+ * 本地向量库服务(`ctx.vector`)。
40
+ *
41
+ * 设计取舍(面向 2 核 2G 的小机器):
42
+ * - 索引是**纯文件**(vectra),不引入任何数据库进程;
43
+ * - Embedding 用 transformers.js 在 CPU 上跑 `bge-small-zh`,不依赖外部 API;
44
+ * - `vectra` 与 `@huggingface/transformers` 都是**按需动态加载**,
45
+ * 功能没被用到时不会占用内存;
46
+ * - 所有 Embedding 调用串行排队,避免小机器上并发推理把内存打满;
47
+ * - 查询走同步接口,因此索引一旦加载过就会常驻(约几十 MB),这是有意的取舍。
48
+ */
49
+ export declare class VectorService extends Service implements VectorIndexer {
50
+ static readonly inject: never[];
51
+ private readonly settings;
52
+ private indexPromise?;
53
+ private embedderPromise?;
54
+ /** 串行化 Embedding / 索引写入,避免并发推理 */
55
+ private queue;
56
+ constructor(ctx: Context, config: VectorConfig);
57
+ get enabled(): boolean;
58
+ get indexPath(): string;
59
+ /**
60
+ * 把一个页面的纯文本切块、向量化并写入索引(同标题的旧块会被替换)。
61
+ * @returns 写入的文本块数量
62
+ */
63
+ indexPage(page: VectorPage): Promise<number>;
64
+ /** 删除某个页面的全部文本块 */
65
+ removePage(documentId: string): Promise<void>;
66
+ /** 语义检索:返回最相关的若干文本块(同一页面最多取 2 块,保证覆盖面) */
67
+ search(question: string, topK?: number): Promise<VectorHit[]>;
68
+ /** 索引现状,供 `.ai.status` 与日志使用 */
69
+ stats(): Promise<{
70
+ enabled: boolean;
71
+ path: string;
72
+ items: number;
73
+ bytes: number;
74
+ }>;
75
+ /** 清空索引(重建前调用) */
76
+ reset(): Promise<void>;
77
+ /** 插件卸载时释放模型,避免热重载反复占用内存 */
78
+ stop(): Promise<void>;
79
+ private enqueue;
80
+ private getIndex;
81
+ private getEmbedder;
82
+ private embed;
83
+ private deleteChunks;
84
+ }
@@ -53,14 +53,6 @@ export declare class WikiBotService extends Service {
53
53
  get isReady(): boolean;
54
54
  isGGBotReady(): boolean;
55
55
  isBWikiBotReady(): boolean;
56
- /**
57
- * 生成一个"登录态永远有效"的客户端代理。
58
- *
59
- * 设计说明(为什么必须是代理而不是普通对象):
60
- * Mwn 的方法很多,且调用方需要 `continuedQueryGen` 这类**异步生成器**以及
61
- * `options` 这类**非函数属性**。用代理可以完整转发任意成员,同时把
62
- * "assert=user 失败 → 重新登录 → 重放调用" 这件事对调用方完全隐藏。
63
- */
64
56
  private createBotProxy;
65
57
  /** WIKIGG 客户端(透明处理登录过期) */
66
58
  getGGBot(): Mwn;
@@ -70,3 +62,10 @@ export declare class WikiBotService extends Service {
70
62
  }
71
63
  /** 账号配置来自共享分组,键名与默认值见 src/config.ts */
72
64
  export type WikiBotServiceConfig = AccountConfig;
65
+ /**
66
+ * bwiki 客户端的「就绪版」获取:未登录时返回 `undefined` 而不是抛错。
67
+ *
68
+ * 供把 bwiki 当作**可选**依赖的子插件使用(例如抓取 `action=parse` 渲染文本)。
69
+ * 调用方需要在 `inject` 中声明 `wikiBot`,否则访问 `ctx.wikiBot` 会触发 cordis 警告。
70
+ */
71
+ export declare function tryGetBWikiBot(ctx: Context): Mwn | undefined;
@@ -41,6 +41,13 @@ export interface PageSyncerDependencies {
41
41
  database?: Database;
42
42
  /** 增量更新结束时一次性回调(仅包含 reason==="synced" 的条目) */
43
43
  notify?: (items: SyncNotifyItem[]) => void;
44
+ /**
45
+ * 单页同步成功(reason==="synced")后的回调。
46
+ *
47
+ * 用于「同步完再抽取渲染文本 / 更新向量库」这类后续步骤;
48
+ * 回调抛错不会影响同步本身的成败。
49
+ */
50
+ onSynced?: (title: string) => void | Promise<void>;
44
51
  options?: Partial<PageSyncOptions>;
45
52
  }
46
53
  /**
@@ -55,8 +62,11 @@ export declare class PageSyncer {
55
62
  private readonly options;
56
63
  private readonly database?;
57
64
  private readonly notify?;
65
+ private readonly onSynced?;
58
66
  private readonly images;
59
67
  constructor(source: Mwn, target: Mwn, deps?: PageSyncerDependencies);
68
+ /** 同步成功后的后续处理;失败只记日志,绝不影响同步结果 */
69
+ private runSyncedHook;
60
70
  /** 带重试的数据库操作 */
61
71
  private retryDb;
62
72
  /** 若数据库中不存在该页面,先写入基本数据(含拼音索引) */
@@ -0,0 +1,118 @@
1
+ import { type TableMode } from "../utils/renderText";
2
+ import type { VectorIndexer } from "../services/vectorService";
3
+ /** 本模块需要的数据库能力(最小接口) */
4
+ export interface TextDatabase {
5
+ get<T = unknown>(table: string, query: object): Promise<T[]>;
6
+ upsert(table: string, data: object | object[]): Promise<unknown>;
7
+ }
8
+ /** 本模块需要的 HTTP 能力(`ctx.http` 结构上兼容) */
9
+ export interface TextHttp {
10
+ get<T = any>(url: string, config?: {
11
+ params?: Record<string, unknown>;
12
+ headers?: Record<string, string>;
13
+ timeout?: number;
14
+ }): Promise<T>;
15
+ }
16
+ /**
17
+ * 本模块需要的 Wiki 客户端能力(`wikiBot.getBWikiBot()` 结构上兼容)。
18
+ *
19
+ * 优先用它做 `action=parse`:mwn 会自动带上 bwiki 需要的 `Referer` 与登录 Cookie,
20
+ * 而裸 `ctx.http` 不带 `Referer` 时会被 WAF 以 **HTTP 567** 拦掉。
21
+ */
22
+ export interface TextBot {
23
+ request(params: Record<string, unknown>): Promise<any>;
24
+ }
25
+ export interface TextSyncOptions {
26
+ /** BWiki 的 api.php 地址 */
27
+ apiUrl: string;
28
+ /** 页面链接前缀,用于给检索结果生成可点击来源 */
29
+ pageUrlBase: string;
30
+ /** 正文表格处理方式 */
31
+ tableMode: TableMode;
32
+ /** 单页最多保留的字数 */
33
+ maxLength: number;
34
+ /** 批量抓取的页间间隔(毫秒) */
35
+ interval: number;
36
+ /** 单次请求超时(毫秒) */
37
+ timeout: number;
38
+ userAgent: string;
39
+ /** 本地缓存为空时,最多从 BWiki 枚举多少个页面 */
40
+ maxPages: number;
41
+ }
42
+ export type TextSyncReason = "synced" | "unchanged" | "empty" | "missing" | "failed";
43
+ export interface TextSyncResult {
44
+ success: boolean;
45
+ reason: TextSyncReason;
46
+ message?: string;
47
+ }
48
+ export interface TextSyncSummary {
49
+ total: number;
50
+ synced: number;
51
+ unchanged: number;
52
+ /** 页面在 bwiki 上不存在(missingtitle),不算失败 */
53
+ missing: number;
54
+ failed: number;
55
+ }
56
+ export interface TextSyncDependencies {
57
+ /** 兜底通道:没有 wikiBot 时用它(会自动补 Referer,避免 567) */
58
+ http?: TextHttp;
59
+ /**
60
+ * 首选通道:已登录的 bwiki 客户端(mwn),自带 Referer / Cookie / 重试。
61
+ *
62
+ * 用**惰性 getter** 而不是直接传实例:插件构造时 `wikiBot` 往往还没完成登录,
63
+ * 直接取值会永远是 `undefined`,等真正发请求时再取才拿得到。
64
+ */
65
+ bot?: () => TextBot | undefined;
66
+ database: TextDatabase;
67
+ /** 向量库(可选):提供时页面文本变化后会自动重建该页的向量 */
68
+ vector?: VectorIndexer;
69
+ options?: Partial<TextSyncOptions>;
70
+ }
71
+ /**
72
+ * 把 BWiki `action=parse&prop=text` 的**渲染结果**抽成纯文本并落库。
73
+ *
74
+ * 与 `pageSync` 的分工:
75
+ * - `PageSyncer` 负责 Wikitext 源码的 GG → bwiki 同步;
76
+ * - 本类在同步成功之后,回到 bwiki 取「渲染后的正文」,剔除表格噪音/脚本,
77
+ * 写入 `wikitexts` 表并(可选)更新向量索引。
78
+ *
79
+ * 传给 AI 的永远只有这里的纯文本,Wikitext 源码不会进入检索链路。
80
+ */
81
+ export declare class RenderedTextSyncer {
82
+ private readonly http?;
83
+ private readonly bot?;
84
+ private readonly database;
85
+ private readonly vector?;
86
+ private readonly options;
87
+ constructor(deps: TextSyncDependencies);
88
+ /** 页面在 bwiki 上的访问地址(用于回答里的「资料来源」) */
89
+ pageUrl(title: string): string;
90
+ /**
91
+ * 抓取并保存单个页面的渲染文本。
92
+ *
93
+ * 文本的 sha1 与库中一致时直接返回 `unchanged`,
94
+ * 既省掉一次 Embedding,也避免每小时的增量任务重复写索引。
95
+ */
96
+ syncOne(title: string): Promise<TextSyncResult>;
97
+ /** 批量抓取(按配置的间隔串行执行,避免把小机器和 bwiki 打满) */
98
+ syncMany(titles: string[]): Promise<TextSyncSummary>;
99
+ /**
100
+ * 对本地缓存的全部页面执行一次渲染文本抓取(首次部署 / 全量重建时使用)。
101
+ *
102
+ * 本地 `wikipages` 为空(还没执行过 `update`)时,直接向 BWiki 的 `allpages`
103
+ * 枚举主命名空间页面——`ai.sync` 因此不依赖页面缓存也能跑起来。
104
+ */
105
+ syncAll(): Promise<TextSyncSummary>;
106
+ /**
107
+ * 统一的 API 请求入口。
108
+ *
109
+ * 首选已登录的 bwiki 客户端(mwn,自带 Referer / Cookie,且与 `sync.*` 走同一条链路),
110
+ * 没有就退回 `ctx.http` 并**手动补上 Referer**——缺 Referer 会被 bwiki 的 WAF 直接 567。
111
+ */
112
+ private apiRequest;
113
+ /** 通过 MediaWiki `list=allpages` 枚举主命名空间页面标题(含 continue 翻页) */
114
+ private listAllPageTitles;
115
+ private fetchRenderedHtml;
116
+ }
117
+ /** 拼接 BWiki 页面地址(站内链接约定:空格换成下划线) */
118
+ export declare function buildPageUrl(pageUrlBase: string, title: string): string;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * HTML → 纯文本 / 文本切块。
3
+ *
4
+ * 这里只放**纯函数**:不依赖 Koishi Context、不发请求,因此可以被单元测试直接覆盖
5
+ * (见 tests/renderText.spec.ts)。
6
+ *
7
+ * 表格策略(针对 bwiki 的实际结构):
8
+ * - **信息框 `.infobox` 必须保留**:耗电、温度、尺寸、建筑血量这些数值只在信息框里,
9
+ * 直接删掉等于把答案删了。这里把它抽成 `标签:值` 的文本行;
10
+ * - 正文数据表压平成 `单元格 | 单元格` 的行;
11
+ * - 导航框 / 目录 / 脚本 / 脚注标记等确实的噪音才丢弃;
12
+ * - 想完全按「剔除所有表格」处理时把 `tableMode` 设为 `"drop"`。
13
+ */
14
+ export type TableMode = "flatten" | "drop";
15
+ export interface ExtractTextOptions {
16
+ /** 表格处理方式,默认 `"flatten"`(压平保留数值) */
17
+ tableMode?: TableMode;
18
+ /** 最大保留字数,0 或省略表示不限制 */
19
+ maxLength?: number;
20
+ }
21
+ /**
22
+ * 把 MediaWiki `action=parse&prop=text` 返回的 HTML 抽成纯净正文。
23
+ *
24
+ * 标题会被写成 `## 标题` 的形式保留层级,方便模型理解上下文。
25
+ */
26
+ export declare function extractPlainText(html: string, options?: ExtractTextOptions): string;
27
+ export interface TextChunk {
28
+ index: number;
29
+ text: string;
30
+ }
31
+ export interface ChunkOptions {
32
+ /** 目标块大小(字符数) */
33
+ size?: number;
34
+ /** 相邻块的重叠字符数 */
35
+ overlap?: number;
36
+ /** 最多产出多少块 */
37
+ maxChunks?: number;
38
+ }
39
+ /**
40
+ * 按段落/句号切块,块与块之间保留少量重叠,避免答案被切断在边界上。
41
+ *
42
+ * 中文没有空格分词,按字符长度切比按 token 切更简单也更可控;
43
+ * `bge-small-zh` 的输入上限是 512 token,默认 350 字符留有余量。
44
+ */
45
+ export declare function chunkText(text: string, options?: ChunkOptions): TextChunk[];
46
+ /** 归一化空白:行内多空格压成一个,保留换行表达段落结构 */
47
+ export declare function squash(text: string): string;
@@ -52,4 +52,11 @@ declare function normalizeImageTitle(fileName: string): string;
52
52
  * @returns 纯文件名
53
53
  */
54
54
  declare function stripImagePrefix(fileName: string): string;
55
- export { getAndProcessPageContent, generatePinyinInfo, logger, getErrorMessage, formatWikiTime, normalizeChannelId, truncateComment, normalizeImageTitle, stripImagePrefix, };
55
+ /**
56
+ * 把配置里的站点域名规范成带协议的 URL。
57
+ * 允许配置成 `wiki.biligame.com/oni`、`https://wiki.biligame.com/oni/` 等写法。
58
+ * @param site 站点域名
59
+ * @returns 规范化后的 URL(空输入返回空串)
60
+ */
61
+ declare function siteUrl(site: string): string;
62
+ export { getAndProcessPageContent, generatePinyinInfo, logger, getErrorMessage, formatWikiTime, normalizeChannelId, truncateComment, normalizeImageTitle, stripImagePrefix, siteUrl, };