mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
feat: 重构问问微信并完善知识库增量检索
统一问问微信与 Agent Hub 的查询链路 完善查询覆盖度、新鲜度和部分结果表达,避免索引滞后产生错误结论 基于会话实现真正的增量追新与历史补齐 支持后台同步、取消恢复、重启续传以及同步期间继续查询 优化知识库跨会话检索、同步状态、进度展示和侧栏布局
This commit is contained in:
1 parent
0c4932d740
commit
ab3b3731b7
69 files changed
+8317
-898
No files matched your search
+119
-2
@@ -100,6 +100,17 @@ export interface KnowledgeConversationInput {
|
||||
/** true means this is a complete read-only snapshot of the conversation. */
|
||||
completeSnapshot: boolean
|
||||
messages: KnowledgeSourceMessage[]
|
||||
/**
|
||||
* 这个会话在**源侧**(WCDB Session.last_timestamp)已经覆盖到的最后活跃时间(epoch ms)。
|
||||
*
|
||||
* 与 `KnowledgeIndexRequest.sourceLatestAt` 的区别:后者是整遍 pass 级别的边界,这里是
|
||||
* per-conversation checkpoint —— 增量 pass 用它判断「这个会话有没有新消息」,
|
||||
* 从而跳过整个会话(不读 WCDB、不传 IPC、不写索引)。
|
||||
*
|
||||
* 记录**源侧**时间而不是「索引里最后一条可建模消息的时间」:否则最后一条恰好落在
|
||||
* 图片/空正文上的会话会永远被判定为「有新消息」,增量永远跳不过它。
|
||||
*/
|
||||
sourceHighWaterTime?: number
|
||||
}
|
||||
|
||||
export interface KnowledgeIndexRequest {
|
||||
@@ -110,6 +121,13 @@ export interface KnowledgeIndexRequest {
|
||||
fts: KnowledgeFtsConfig
|
||||
/** Written only after a complete source pass; used for truthful coverage. */
|
||||
sourceMessageCount?: number
|
||||
/**
|
||||
* 这一遍完整 pass 实际扫到的源数据最新消息时间(epoch ms)。
|
||||
*
|
||||
* 与 `sourceMessageCount` 一样,只在读完全部会话的那一次写入。它是 freshness 的权威口径:
|
||||
* 拿它与当前源数据最新活跃时间比较,就能确定索引是否已经追上,而不必猜测派生索引的过滤落差。
|
||||
*/
|
||||
sourceLatestAt?: number
|
||||
}
|
||||
|
||||
export interface KnowledgeIndexProgress {
|
||||
@@ -236,6 +254,18 @@ export interface KnowledgeSearchTimings {
|
||||
responseSerializeMs: number
|
||||
/** FTS (or short-term database lookup) query time. */
|
||||
ftsMs: number
|
||||
/**
|
||||
* `ftsMs` 中**短词回退路径**(<3 字的中文词,走 `LIKE` 而非 FTS `MATCH`)占用的时间。
|
||||
*
|
||||
* 跨会话 lexical probe 里最常见的 2 字中文词只能走这条路径,没有这个分解就无法区分
|
||||
* 「FTS MATCH 慢」和「短词全表 LIKE 慢」。
|
||||
*/
|
||||
shortTermSearchMs?: number
|
||||
/**
|
||||
* `getSearchStatus()`(含统计快照判定)占用的时间。
|
||||
* 用于验证「搜索热路径不再做全表聚合」这一性能约束没有被回退。
|
||||
*/
|
||||
statusMs?: number
|
||||
/** Reading source message rows from matching chunks. */
|
||||
messageLoadMs: number
|
||||
/** Expanding chunk members, scoring terms and per-chunk de-duplication. */
|
||||
@@ -285,6 +315,13 @@ export interface KnowledgeSearchResult {
|
||||
evidence: KnowledgeEvidence[]
|
||||
indexedMessageCount: number
|
||||
indexedChunkCount: number
|
||||
/**
|
||||
* 派生索引里最新的消息时间(epoch ms);null 表示无法判定。
|
||||
*
|
||||
* `state: 'ready'` 只说明「这个派生库可以被查询」,**不等于**它已经追到源数据最新位置。
|
||||
* 调用方必须把它与请求的时间范围比较,才能判断本次检索是否覆盖了用户问的时间。
|
||||
*/
|
||||
indexLatestAt: number | null
|
||||
timings: KnowledgeSearchTimings
|
||||
conversationRetrieval?: KnowledgeConversationRetrieval
|
||||
voiceCoverage?: KnowledgeVoiceCoverage
|
||||
@@ -308,9 +345,53 @@ export interface KnowledgeSearchIpcResult extends KnowledgeSearchResult {
|
||||
source: 'knowledge' | 'fallback'
|
||||
totalMessages: number
|
||||
fallbackReason?: 'unavailable' | 'indexing' | 'error'
|
||||
/**
|
||||
* 源数据(WCDB Session)里最新的活跃时间(epoch ms);null 表示无法判定。
|
||||
*
|
||||
* 与 `indexLatestAt` 一起构成 freshness 判据:`sourceLatestAt > indexLatestAt`
|
||||
* 说明源数据里已经有了索引还没覆盖的内容。
|
||||
*/
|
||||
sourceLatestAt: number | null
|
||||
}
|
||||
|
||||
export type KnowledgeRuntimeState = 'unavailable' | 'building' | 'syncing' | 'ready' | 'error'
|
||||
export type KnowledgeRuntimeState = 'unavailable' | 'building' | 'syncing' | 'ready' | 'error' | 'cancelled'
|
||||
|
||||
/**
|
||||
* 一次后台索引 pass 的真实进度(ADDITIVE)。
|
||||
*
|
||||
* 与新鲜度(`indexLatestAt` / `sourceLatestAt`)回答的是不同问题:这里描述这一遍**在做什么、
|
||||
* 扫了多少、真正写了多少**。
|
||||
*/
|
||||
export interface KnowledgePassProgress {
|
||||
/**
|
||||
* 这一遍在做什么:
|
||||
* - `full` 首次全量建立(还没有任何可用分片)
|
||||
* - `catchup` 追最新:已建立 checkpoint 的会话出现了新消息
|
||||
* - `backfill` 补历史:从来没有 checkpoint 的会话(历史缺口)
|
||||
* - `cancelled` / `error` / `idle`
|
||||
*/
|
||||
phase: 'idle' | 'full' | 'catchup' | 'backfill' | 'cancelled' | 'error'
|
||||
/** 现在是否可以取消(真实在跑且未收到取消请求时才是 true)。 */
|
||||
cancellable: boolean
|
||||
/** 开始时间(epoch ms)。 */
|
||||
startedAt: number
|
||||
/** 这一遍从 WCDB **读取/扫描**的源消息条数(含被可索引性过滤掉的)。 */
|
||||
scannedMessages: number
|
||||
/** 这一遍真正**进入索引**的源消息条数。 */
|
||||
indexedMessages: number
|
||||
processedConversations: number
|
||||
totalConversations: number
|
||||
/** 因为「没有任何新消息」而整段跳过的会话数(增量 pass 的核心指标)。 */
|
||||
skippedConversations: number
|
||||
/** 需要「追最新」的会话数(已建立 checkpoint,且源侧有更新)。 */
|
||||
catchupConversations: number
|
||||
/** 需要「补历史」的会话数(从来没有 checkpoint,必须整段读)。 */
|
||||
backfillConversations: number
|
||||
/** 这一遍已经补齐的历史会话数。 */
|
||||
backfillCompletedConversations: number
|
||||
/** 主线程 event loop 在这一遍期间的最大滞后。用于验证重活没有压在 Main 上。 */
|
||||
mainLoopLagMs: number
|
||||
}
|
||||
|
||||
export interface KnowledgeRuntimeStatus {
|
||||
accountId: string
|
||||
@@ -328,6 +409,20 @@ export interface KnowledgeRuntimeStatus {
|
||||
walBytes: number
|
||||
shmBytes: number
|
||||
lastError?: string
|
||||
/**
|
||||
* 派生索引里最新的消息时间(epoch ms);null 表示无法判定。
|
||||
* `state: 'ready'`(READY)与「已追到源数据最新」(FRESH)是两个概念,它就是两者的判据之一。
|
||||
*/
|
||||
indexLatestAt: number | null
|
||||
/** 源数据(WCDB Session)最新活跃时间(epoch ms);null 表示无法判定。 */
|
||||
sourceLatestAt: number | null
|
||||
/**
|
||||
* 当前/最近一次后台索引 pass 的真实进度(ADDITIVE)。
|
||||
*
|
||||
* 与 `indexLatestAt` 是**两个不同维度**:前者回答"这一遍在补什么、进度多少",
|
||||
* 后者回答"索引已经覆盖到源数据的哪个时刻"。UI 不能再用一个「已同步」把两者混为一谈。
|
||||
*/
|
||||
pass?: KnowledgePassProgress
|
||||
}
|
||||
|
||||
export interface KnowledgeStatusRequest {
|
||||
@@ -336,9 +431,31 @@ export interface KnowledgeStatusRequest {
|
||||
fts: KnowledgeFtsConfig
|
||||
}
|
||||
|
||||
/**
|
||||
* 索引「已覆盖到的源数据时间」与源数据「当前最新活跃时间」之间允许的固定落差。
|
||||
*
|
||||
* 两侧都来自消息的 create_time(索引侧 = 完整 pass 扫到的最大 create_time,
|
||||
* 源侧 = Session 行的 last_timestamp),用于吸收 Session 元数据晚于消息落库的漂移。
|
||||
* main 与 renderer 共用这一份定义,避免 UI 与 Engine 的 freshness 口径漂移。
|
||||
*/
|
||||
export const KNOWLEDGE_FRESHNESS_TOLERANCE_MS = 60 * 1000
|
||||
|
||||
/**
|
||||
* 索引是否已经追到源数据最新(FRESH)。
|
||||
*
|
||||
* 注意与 `state === 'ready'`(READY:这个派生库**可以被查询**)区分:
|
||||
* READY 不代表 FRESH。任一侧口径缺失时返回 null 表示无法判定。
|
||||
*/
|
||||
export function isKnowledgeFresh(
|
||||
status: Pick<KnowledgeRuntimeStatus, 'indexLatestAt' | 'sourceLatestAt'>
|
||||
): boolean | null {
|
||||
if (status.indexLatestAt === null || status.sourceLatestAt === null) return null
|
||||
return status.indexLatestAt + KNOWLEDGE_FRESHNESS_TOLERANCE_MS >= status.sourceLatestAt
|
||||
}
|
||||
|
||||
export interface KnowledgeWorkerRequest {
|
||||
version: 1
|
||||
type: 'index' | 'preflight' | 'search' | 'status' | 'remove' | 'cancel' | 'close'
|
||||
type: 'index' | 'preflight' | 'search' | 'status' | 'remove' | 'cancel' | 'close' | 'highWater'
|
||||
requestId: string
|
||||
/** Parent monotonic wall-clock used only for transport timing. */
|
||||
sentAt?: number
|
||||
|
||||
@@ -55,25 +55,152 @@ const temporalBasisSchema = {
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* LLM-facing Tool schema。
|
||||
*
|
||||
* `search_messages` / `conversation_overview` 的 `target` 是**可选**的:省略表示"使用应用
|
||||
* 当前的搜索范围(conversation scope)"—— 范围由 UI/Host 决定并强制,模型无法用它切换范围,
|
||||
* 也拿不到它的实现细节。`query_messages` 仍是单会话结构化查询。
|
||||
*/
|
||||
export const LOCAL_QUERY_TOOL_DEFINITIONS: LocalQueryToolDefinition[] = [
|
||||
{ name: 'query_messages', description: '精确读取符合联系人、时间、方向、消息类型、顺序等结构条件的消息;适合具体事实和 earliest/latest 等时间边界查询,边界查询使用 order 与 limit。每次调用都必须声明 temporalBasis,说明这个时间范围来自用户的明确约束、模糊回忆线索,还是用户根本没给时间信息。', parameters: { type: 'object', required: ['target', 'timeRange', 'temporalBasis'], additionalProperties: false, properties: { target: targetSchema, timeRange: timeRangeSchema, temporalBasis: temporalBasisSchema, direction: { enum: ['any', 'from_target', 'to_target'] }, messageTypes: { type: 'array', items: { enum: ['text', 'image', 'voice', 'video', 'file', 'link', 'sticker', 'system', 'other'] } }, order: { enum: ['asc', 'desc'] }, limit: { type: 'integer', minimum: 1, maximum: 200 }, excludeSystem: { type: 'boolean' } } } },
|
||||
{ name: 'search_messages', description: '在指定联系人和时间范围内做关键词检索并返回相关 Evidence。queries 的每一项都是一次独立的字面检索:一项只放一个简短关键词,不要把多个近义词或整句话放进同一项,也不要指望一项内部被拆词理解。首次最多 4 项;只有在本次检索完全没有 Evidence 时,才允许再检索一次,且每一项都必须与上一次实质不同。', parameters: { type: 'object', required: ['target', 'timeRange', 'queries'], additionalProperties: false, properties: { target: targetSchema, timeRange: timeRangeSchema, queries: { type: 'array', description: '独立检索项列表,每项一个简短关键词,最多 4 项;每一项单独检索,不会组合成一句话理解。', minItems: 1, maxItems: 4, items: { type: 'string', minLength: 1 } }, limit: { type: 'integer', minimum: 1, maximum: 200 } } } },
|
||||
{ name: 'query_messages', description: '精确读取**单个**会话中符合联系人、时间、方向、消息类型、顺序等结构条件的消息;适合具体事实和 earliest/latest 等时间边界查询,边界查询使用 order 与 limit。省略 target 表示"当前搜索范围恰好只有一个会话"(例如单聊专属或当前会话)时直接查该会话;范围里有多个会话时必须显式指定 target,且 target 必须落在当前搜索范围内。每次调用都必须声明 temporalBasis,说明这个时间范围来自用户的明确约束、模糊回忆线索,还是用户根本没给时间信息。跨多个会话的"谁聊过某话题"请改用 search_messages。', parameters: { type: 'object', required: ['timeRange', 'temporalBasis'], additionalProperties: false, properties: { target: targetSchema, timeRange: timeRangeSchema, temporalBasis: temporalBasisSchema, direction: { enum: ['any', 'from_target', 'to_target'] }, messageTypes: { type: 'array', items: { enum: ['text', 'image', 'voice', 'video', 'file', 'link', 'sticker', 'system', 'other'] } }, order: { enum: ['asc', 'desc'] }, limit: { type: 'integer', minimum: 1, maximum: 200 }, excludeSystem: { type: 'boolean' } } } },
|
||||
{ name: 'search_messages', description: '在应用当前的搜索范围内做关键词检索并返回相关 Evidence。queries 的每一项都是一次独立的字面检索:一项只放一个简短关键词,不要把多个近义词或整句话放进同一项,也不要指望一项内部被拆词理解。首次最多 4 项;只有在本次检索完全没有 Evidence 时,才允许再检索一次,且每一项都必须与上一次实质不同。省略 target 表示在整个当前搜索范围(可能是多个会话,例如所有群聊)内检索——问"最近谁聊过某个话题"这类跨会话问题时应当省略 target;只有当问题明确指向某一个会话时才传 target,且该 target 必须在当前搜索范围内。', parameters: { type: 'object', required: ['timeRange', 'queries'], additionalProperties: false, properties: { target: targetSchema, timeRange: timeRangeSchema, queries: { type: 'array', description: '独立检索项列表,每项一个简短关键词,最多 4 项;每一项单独检索,不会组合成一句话理解。', minItems: 1, maxItems: 4, items: { type: 'string', minLength: 1 } }, limit: { type: 'integer', minimum: 1, maximum: 200 } } } },
|
||||
{ name: 'message_context', description: '补充已找到的单条有价值 Evidence 的前后消息;仅在该 Evidence 缺少语境、无法判断含义时使用,不是默认确认步骤。', parameters: { type: 'object', required: ['messageRef'], additionalProperties: false, properties: { messageRef: { type: 'string', minLength: 1 }, before: { type: 'integer', minimum: 0, maximum: 50 }, after: { type: 'integer', minimum: 0, maximum: 50 } } } },
|
||||
{ name: 'conversation_overview', description: '提取指定联系人和时间范围的整体聊天覆盖样本;只用于 broad summary,不是语义搜索 fallback,也不能确定 earliest/latest 等精确时间边界。', parameters: { type: 'object', required: ['target', 'timeRange'], additionalProperties: false, properties: { target: targetSchema, timeRange: timeRangeSchema } } }
|
||||
{ name: 'conversation_overview', description: '提取**单个**会话在一段时间内的整体聊天覆盖样本;只用于 broad summary,不是语义搜索 fallback,也不能确定 earliest/latest 等精确时间边界。省略 target 只在当前搜索范围恰好只有一个会话时成立(例如"当前会话");范围里有多个会话时必须显式指定 target,且目标必须落在该范围内。', parameters: { type: 'object', required: ['timeRange'], additionalProperties: false, properties: { target: targetSchema, timeRange: timeRangeSchema } } }
|
||||
]
|
||||
export type QueryTimeRange =
|
||||
| { kind: 'all' | 'today' | 'yesterday' | 'this_week' | 'last_7_days' | 'this_month' | 'previous_month' | 'this_year' | 'previous_year' }
|
||||
| { kind: 'absolute'; startTime?: number; endTime?: number }
|
||||
export interface QueryTarget { query: string }
|
||||
|
||||
/**
|
||||
* 语料边界(conversation scope)。
|
||||
*
|
||||
* 由**调用方(UI / Host)**决定,**不是** LLM 的输入 —— 它不进入 LLM-facing Tool schema,
|
||||
* 也不与 temporalBasis(时间语义)混在一起:scope 是"去哪里搜",时间是"搜什么时候"。
|
||||
*
|
||||
* - `all`:所有可读会话(单聊 + 群聊,群聊成员的每条消息都是普通可搜索消息)
|
||||
* - `groups`:只搜群聊语料(= 全部群会话及其成员消息),不是"群摘要 / metadata"
|
||||
* - `contact`:只搜指定的一对一会话(单聊专属)
|
||||
* - `current`:只搜当前打开的那个会话(可能是单聊或群)
|
||||
*
|
||||
* `conversationId` 使用应用内部会话身份(与 `Contact.md5` 一致)。
|
||||
*/
|
||||
export type QueryCorpusScope =
|
||||
| { kind: 'all' }
|
||||
| { kind: 'groups' }
|
||||
| { kind: 'contact'; conversationId: string }
|
||||
| { kind: 'current'; conversationId: string }
|
||||
|
||||
/** 解析后的语料边界(回显给调用方与模型,用于说明"这次只在哪个范围里查")。 */
|
||||
export interface ResolvedCorpusScope {
|
||||
kind: QueryCorpusScope['kind']
|
||||
/** 实际参与检索的会话数量;`all` 为可读会话总数。 */
|
||||
conversationCount: number
|
||||
/** `contact` / `current` 解析出的会话展示名。 */
|
||||
displayName?: string
|
||||
conversationType?: 'user' | 'group'
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool 返回的单条证据。
|
||||
* 群消息必须能归属到**具体群 + 具体成员**,否则模型无法回答"谁聊过"。
|
||||
*/
|
||||
export interface QueryEvidenceItem
|
||||
extends Pick<KnowledgeEvidence, 'timestamp' | 'sender' | 'sourceKind' | 'text'> {
|
||||
messageRef: string
|
||||
/** 该证据所属会话的展示名(群名 / 联系人名)。 */
|
||||
conversationName?: string
|
||||
conversationType?: 'user' | 'group'
|
||||
}
|
||||
|
||||
/**
|
||||
* 一条消息的**稳定身份**。
|
||||
*
|
||||
* 不靠「会话 + 秒级时间戳」定位:同一秒里可能有多条消息,时间戳也只能定位到"附近"。
|
||||
* `messageRef` 是 opaque 字符串(base64url 的 `{c,m}`),对模型只暴露成不可读 token,
|
||||
* 对本进程/渲染进程可以还原成稳定身份。
|
||||
*/
|
||||
export interface CanonicalMessageIdentity {
|
||||
conversationId: string
|
||||
messageId: string
|
||||
}
|
||||
|
||||
/** 归一化消息身份:`local:` 前缀是 WCDB 侧的本地 id 装饰,不属于身份本身。 */
|
||||
export function normalizeMessageIdentity(
|
||||
conversationId: string,
|
||||
messageId: string
|
||||
): CanonicalMessageIdentity | null {
|
||||
const normalizedConversationId = String(conversationId ?? '').trim()
|
||||
const normalizedMessageId = String(messageId ?? '')
|
||||
.trim()
|
||||
.replace(/^local:/, '')
|
||||
if (!normalizedConversationId || !normalizedMessageId) return null
|
||||
return { conversationId: normalizedConversationId, messageId: normalizedMessageId }
|
||||
}
|
||||
|
||||
/**
|
||||
* base64url 编解码。
|
||||
*
|
||||
* 刻意**不用 `Buffer`**:这份实现被 main 与 renderer 共用,而 renderer 在
|
||||
* `contextIsolation` + 无 nodeIntegration 下没有 `Buffer` 全局。`TextEncoder` /
|
||||
* `btoa` / `atob` 在 Node ≥16 与 Chromium 里都是标准全局,两侧行为一致。
|
||||
*/
|
||||
function bytesToBase64Url(bytes: Uint8Array): string {
|
||||
let binary = ''
|
||||
for (let index = 0; index < bytes.length; index += 1) binary += String.fromCharCode(bytes[index])
|
||||
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
||||
}
|
||||
|
||||
function base64UrlToBytes(value: string): Uint8Array | null {
|
||||
const normalized = value.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4)
|
||||
try {
|
||||
const binary = atob(padded)
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)
|
||||
return bytes
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** 生成 opaque messageRef。语义与 `decodeMessageRef` 严格互逆。 */
|
||||
export function encodeMessageRef(conversationId: string, messageId: string): string {
|
||||
const identity = normalizeMessageIdentity(conversationId, messageId)
|
||||
if (!identity) throw new Error('消息引用无效')
|
||||
return bytesToBase64Url(
|
||||
new TextEncoder().encode(JSON.stringify({ c: identity.conversationId, m: identity.messageId }))
|
||||
)
|
||||
}
|
||||
|
||||
/** 还原 opaque messageRef;无法解析(老缓存 / 伪造)时返回 null,调用方必须走降级路径。 */
|
||||
export function decodeMessageRef(value: unknown): CanonicalMessageIdentity | null {
|
||||
if (typeof value !== 'string' || !value) return null
|
||||
const bytes = base64UrlToBytes(value)
|
||||
if (!bytes) return null
|
||||
try {
|
||||
const parsed = JSON.parse(new TextDecoder().decode(bytes)) as { c?: unknown; m?: unknown }
|
||||
return typeof parsed?.c === 'string' && typeof parsed?.m === 'string'
|
||||
? normalizeMessageIdentity(parsed.c, parsed.m)
|
||||
: null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export interface ResolvedTimeRange { kind: QueryTimeRange['kind']; startTime?: number; endTime?: number; label: string }
|
||||
export interface QueryMessagesRequest {
|
||||
target: QueryTarget
|
||||
/** 省略 = 使用当前搜索范围(仅当范围恰好只有一个会话时成立)。 */
|
||||
target?: QueryTarget
|
||||
timeRange: QueryTimeRange
|
||||
direction?: QueryDirection
|
||||
messageTypes?: QueryMessageType[]
|
||||
order?: QueryOrder
|
||||
limit?: number
|
||||
excludeSystem?: boolean
|
||||
/** 语料边界;省略 = 不限制(等价于 all)。目标必须落在该边界内,否则被 Host 拒绝。 */
|
||||
scope?: QueryCorpusScope
|
||||
}
|
||||
export interface QueryMessage {
|
||||
messageRef: string
|
||||
@@ -99,6 +226,8 @@ export interface QueryMessagesResponse {
|
||||
returnedCount?: number
|
||||
messages?: QueryMessage[]
|
||||
candidates?: Array<{ displayName: string; type: 'user' | 'group' }>
|
||||
/** 本次实际使用的语料边界。 */
|
||||
scope?: ResolvedCorpusScope
|
||||
}
|
||||
export interface SearchMessagesRequest {
|
||||
target: QueryTarget
|
||||
@@ -106,25 +235,104 @@ export interface SearchMessagesRequest {
|
||||
query: string
|
||||
variants?: string[]
|
||||
limit?: number
|
||||
/** 语料边界;省略 = 全部可读会话。省略 target 时用它作为跨会话检索范围。 */
|
||||
scope?: QueryCorpusScope
|
||||
}
|
||||
export interface SearchMessagesResponse {
|
||||
status: string
|
||||
target?: { displayName: string; type: 'user' | 'group' }
|
||||
resolvedTimeRange?: ResolvedTimeRange
|
||||
/**
|
||||
* 本次检索的覆盖度。
|
||||
*
|
||||
* `complete` 需要同时满足:派生索引可用 **且** 请求的时间范围被索引完整覆盖
|
||||
* (索引已追到源数据最新,或 requested range 落在索引覆盖窗口内)。
|
||||
* 只要源数据在索引之后还有内容,就必须是 `partial` —— 此时 0 条 Evidence
|
||||
* **不能**被解释成「整个微信里没有」。
|
||||
*/
|
||||
coverage?: { state: 'complete' | 'partial' | 'unknown' }
|
||||
probeCount?: number
|
||||
evidenceCount?: number
|
||||
evidence?: Array<Pick<KnowledgeEvidence, 'timestamp' | 'sender' | 'sourceKind' | 'text'> & { messageRef: string }>
|
||||
evidence?: QueryEvidenceItem[]
|
||||
candidates?: Array<{ displayName: string; type: 'user' | 'group' }>
|
||||
scope?: ResolvedCorpusScope
|
||||
/**
|
||||
* 派生索引中最新一条消息的时间(epoch ms)。
|
||||
* 索引是**异步派生**数据:它落后于 WCDB 时必须能被调用方看见,不能冒充"完整"。
|
||||
*/
|
||||
indexLatestAt?: number | null
|
||||
/** 源数据(WCDB)里最新的活跃时间(epoch ms);与 indexLatestAt 比较即得 freshness。 */
|
||||
sourceLatestAt?: number | null
|
||||
/**
|
||||
* 本次为追赶索引新鲜度做了什么(诊断字段,不参与答案语义)。
|
||||
* - `none`:索引已覆盖请求范围,或没有可用的追赶通道
|
||||
* - `reused`:已有索引任务在跑,直接复用,不阻塞本次查询
|
||||
* - `skipped`:确实落后,但落后量不值得再跑一遍索引(低于门槛),按当前覆盖如实回答
|
||||
* - `completed`:本次触发的追赶在等待预算内完成,并已用新索引重新检索
|
||||
* - `pending`:本次触发了追赶但没在预算内完成;本次按当前覆盖如实回答,后台继续追
|
||||
*/
|
||||
freshness?: { catchUp: 'none' | 'reused' | 'skipped' | 'completed' | 'pending' }
|
||||
/**
|
||||
* 索引覆盖结论(模型可直接引用的一句话)。
|
||||
*
|
||||
* 只给结构化数字时模型会自己换算、甚至反过来宣称"覆盖完整"。这里由 Engine 直接给出
|
||||
* **本地时间**与结论,模型只需引用,不需要自己判断,也不需要输出 epoch 数字。
|
||||
*/
|
||||
indexCoverage?: QueryIndexCoverage
|
||||
/** 本次检索的真实耗时分解(ADDITIVE,用于诊断与 UI 展示;不进入模型上下文)。 */
|
||||
timings?: QuerySearchTimings
|
||||
}
|
||||
export interface MessageContextRequest { messageRef: string; before?: number; after?: number }
|
||||
|
||||
export interface QueryIndexCoverage {
|
||||
/** 索引是否已覆盖本次请求的时间范围。 */
|
||||
covered: boolean
|
||||
/** 索引覆盖到的时间(本地时间,`MM-DD HH:mm`)。 */
|
||||
indexLatestAtLabel?: string
|
||||
/** 源数据最新时间(本地时间,`MM-DD HH:mm`)。 */
|
||||
sourceLatestAtLabel?: string
|
||||
/** 可直接引用的结论句;`covered: false` 时明确说明这段时间暂时无法确认。 */
|
||||
summary: string
|
||||
}
|
||||
|
||||
/**
|
||||
* `search_messages` 的真实耗时分解(ADDITIVE 诊断字段)。
|
||||
*
|
||||
* 让 Tool 阶段可以被拆成 freshness 等待 / scope 解析 / 每个 probe / 证据补全,
|
||||
* 而不是一个不透明的总数。这些数字全部来自实际 `Date.now()` 测量,不做任何推测。
|
||||
*
|
||||
* **不进入模型上下文**:Host 在把 Tool Result 交给模型之前会剥离它。
|
||||
*/
|
||||
export interface QuerySearchTimings {
|
||||
/** 本次 search_messages 端到端耗时(含 freshness 处理与重检索)。 */
|
||||
totalMs: number
|
||||
/** 语料范围解析(联系人列表读取 + scope 展开成会话集合)。 */
|
||||
scopeMs: number
|
||||
/** 索引新鲜度判定 + 必要时触发追赶并在预算内等待。 */
|
||||
freshnessMs: number
|
||||
/** 每个 probe 的检索耗时,顺序与请求中的 probe 一致(可能含重检索后的第二次)。 */
|
||||
probeMs: number[]
|
||||
/** 跨 probe 证据合并 / 去重 / 排序。 */
|
||||
mergeMs: number
|
||||
/** 证据展示信息补全(群名 / 成员昵称)所等待的时间,主要是 WCDB 读取。 */
|
||||
enrichmentMs: number
|
||||
/** 派生库内部的分项(worker 侧测量)。 */
|
||||
knowledge?: {
|
||||
shortTermSearchMs: number
|
||||
ftsMs: number
|
||||
messageLoadMs: number
|
||||
statusMs: number
|
||||
voiceCoverageMs: number
|
||||
workerExecutionMs: number
|
||||
}
|
||||
}
|
||||
export interface MessageContextRequest { messageRef: string; before?: number; after?: number; scope?: QueryCorpusScope }
|
||||
export interface MessageContextResponse {
|
||||
status: string
|
||||
anchor?: QueryMessage
|
||||
before?: QueryMessage[]
|
||||
after?: QueryMessage[]
|
||||
}
|
||||
export interface ConversationOverviewRequest { target: QueryTarget; timeRange: QueryTimeRange }
|
||||
export interface ConversationOverviewRequest { target: QueryTarget; timeRange: QueryTimeRange; scope?: QueryCorpusScope }
|
||||
export interface ConversationOverviewResponse {
|
||||
status: string
|
||||
target?: { displayName: string; type: 'user' | 'group' }
|
||||
@@ -135,8 +343,14 @@ export interface ConversationOverviewResponse {
|
||||
sourceCoverage?: { state: 'complete' | 'partial' | 'unknown'; sourceMessageCount: number }
|
||||
selection?: { mode: 'temporal_coverage'; selectedEvidenceCount: number; sampled: boolean }
|
||||
voiceCoverage?: KnowledgeVoiceCoverage
|
||||
evidence?: Array<Pick<KnowledgeEvidence, 'timestamp' | 'sender' | 'sourceKind' | 'text'> & { messageRef: string }>
|
||||
evidence?: QueryEvidenceItem[]
|
||||
candidates?: Array<{ displayName: string; type: 'user' | 'group' }>
|
||||
scope?: ResolvedCorpusScope
|
||||
/**
|
||||
* 证据来源:`wcdb` = 直接读源数据(会话概览的事实来源);`knowledge` = 派生索引。
|
||||
* 派生索引可能滞后,故概览以源数据为准。
|
||||
*/
|
||||
origin?: 'wcdb' | 'knowledge'
|
||||
}
|
||||
export interface QueryCapabilitiesResponse {
|
||||
version: 1
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import type { AiSearchPipelineRequest, AiSearchPipelineResult } from './ai-search'
|
||||
import type { QueryCorpusScope } from './local-query-api'
|
||||
|
||||
/**
|
||||
* Query Agent 生产接入的跨层 contract。
|
||||
*
|
||||
* 只描述「入口 → QueryAgentRuntime → 回答」这一段:桌面问问微信与 Agent Hub 共用同一份定义。
|
||||
* 这里**不包含**任何 Tool / prompt / temporalBasis 语义 —— 那些属于
|
||||
* `src/main/services/query-agent-service.ts`,不跨层暴露。
|
||||
*/
|
||||
|
||||
export type QueryAgentEntry = 'desktop' | 'agent-hub'
|
||||
|
||||
/**
|
||||
* 搜索范围(WHERE TO SEARCH)。
|
||||
*
|
||||
* 与时间(WHEN)完全正交:时间是问题文本的一部分,由 temporalBasis 理解;
|
||||
* 范围是 UI 的确定性数据边界,由 Host 结构性强制(LLM 无法修改,越界 target 会被拒绝)。
|
||||
*/
|
||||
export interface AskWechatScope {
|
||||
scope: QueryCorpusScope
|
||||
/** 人类可读的范围说明(UI 本来就知道,用于向模型描述范围与展示统计)。 */
|
||||
label?: string
|
||||
}
|
||||
|
||||
/** 展示用证据:只含可读字段,不含 wxid / md5 / DB id / raw Tool JSON。 */
|
||||
export interface AskWechatEvidenceItem {
|
||||
messageRef: string
|
||||
conversationName?: string
|
||||
conversationType?: 'user' | 'group'
|
||||
sender?: string
|
||||
/** epoch ms */
|
||||
timestamp?: number
|
||||
messageType?: string
|
||||
text?: string
|
||||
attachment?: { kind?: string; name?: string; url?: string; sizeBytes?: number }
|
||||
/** 产生这条证据的 Tool(诊断 / 分组)。 */
|
||||
source: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 顶部统计用的**真实**读取数字。
|
||||
* 不再使用"知识库已收录"这类与具体 Tool 无关的 Legacy 文案:
|
||||
* query_messages 直读 WCDB,search / overview 走不同路径。
|
||||
*/
|
||||
export interface AskWechatStats {
|
||||
/** 本次实际使用的 Tool(顺序即调用顺序)。 */
|
||||
tools: string[]
|
||||
/** 各 Tool 的结构化计数。 */
|
||||
reads: {
|
||||
/** query_messages 读到的消息条数(多次求和)。 */
|
||||
messageCount: number
|
||||
/** search_messages / overview 命中的证据条数(多次求和)。 */
|
||||
matchedCount: number
|
||||
/** 会话概览覆盖的源消息条数。 */
|
||||
overviewSourceCount: number
|
||||
/** 去重后的证据条数。 */
|
||||
evidenceCount: number
|
||||
}
|
||||
/** 本次语料边界(用于"搜索所有群聊"这类文案)。 */
|
||||
scope?: { kind: QueryCorpusScope['kind']; label?: string }
|
||||
modelCallCount: number
|
||||
toolCallCount: number
|
||||
totalMs: number
|
||||
/**
|
||||
* 耗时拆解(ADDITIVE)。
|
||||
*
|
||||
* 只有总耗时时用户无法回答"这几十秒花在哪"。这里按用户能读懂的口径拆开
|
||||
* (AI / 本地查询 / 总耗时);更细的每次模型调用耗时留在诊断里,dev 模式才看。
|
||||
*/
|
||||
timings?: {
|
||||
/** 所有模型调用耗时之和(Model #1 + Model #2 + …)。 */
|
||||
modelMs: number
|
||||
/** 本地 Tool 执行耗时之和(检索 / 读取,不含模型)。 */
|
||||
localQueryMs: number
|
||||
/** 端到端总耗时。 */
|
||||
totalMs: number
|
||||
/** 每次模型调用的耗时(按顺序),仅用于 dev 模式的细分展示。 */
|
||||
modelDurationsMs?: number[]
|
||||
/** 每次 Tool 调用的耗时(按顺序),仅用于 dev 模式的细分展示。 */
|
||||
toolDurationsMs?: number[]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生产进度阶段。**只描述真实 Runtime 生命周期**:
|
||||
* - `understanding`:第 1 次模型调用正在进行(模型在决定要查什么)
|
||||
* - `searching`:正在执行一个 Query Tool(本地检索)
|
||||
* - `organizing_evidence`:刚拿到 Tool Result,在整理证据 / 决定是否继续
|
||||
* - `generating_answer`:模型在已有 Tool 结果之上组织最终回答
|
||||
* - `completed`:本次 run 结束(成功或失败)
|
||||
*
|
||||
* 刻意**没有**百分比、没有"预计剩余":事件只在真实边界发出,不存在"每 N 秒假装跳一步"
|
||||
* 的定时器 —— UI 阶段必须能对应到实际发生的事。
|
||||
*/
|
||||
export type QueryAgentProgressStage =
|
||||
| 'understanding'
|
||||
| 'searching'
|
||||
| 'organizing_evidence'
|
||||
| 'generating_answer'
|
||||
| 'completed'
|
||||
|
||||
export interface QueryAgentProgressEvent {
|
||||
stage: QueryAgentProgressStage
|
||||
/** 从本次 run 开始的已用时间。 */
|
||||
elapsedMs: number
|
||||
/** 真实进入该阶段的时间戳。 */
|
||||
at: number
|
||||
/**
|
||||
* 正在执行 / 刚完成的 Tool 名。
|
||||
*
|
||||
* 只用于 UI 侧把 `searching` 细分成"正在搜索聊天记录"/"正在搜索较大范围"等可读文案。
|
||||
* **绝不**直接呈现给用户(不能暴露 toolName / SQL / FTS 等内部概念)。
|
||||
*/
|
||||
toolName?: string
|
||||
/** 到目前为止已发生的模型调用次数(含正在进行的那次)。 */
|
||||
modelCallCount: number
|
||||
/** 到目前为止已完成的工具调用次数。 */
|
||||
toolCallCount: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 诊断摘要:只含**形态**信息(入口 / provider / 调用次数 / 耗时 / 工具路径 / 结果类型)。
|
||||
* 绝不含聊天原文、Evidence、messageRef、token、内部 id。
|
||||
*/
|
||||
export interface QueryAgentDiagnostics {
|
||||
entry: QueryAgentEntry
|
||||
provider: string
|
||||
model: string
|
||||
modelCallCount: number
|
||||
toolCallCount: number
|
||||
/** 本次实际使用到的 Tool 名称(顺序即调用顺序),不含参数。 */
|
||||
tools: string[]
|
||||
totalMs: number
|
||||
outcome: AskWechatOutcome
|
||||
}
|
||||
|
||||
export type AskWechatOutcome =
|
||||
| 'answered'
|
||||
| 'provider_unavailable'
|
||||
| 'provider_failure'
|
||||
| 'tool_limit'
|
||||
| 'invalid_question'
|
||||
| 'runtime_error'
|
||||
|
||||
export interface AskWechatQueryRequest {
|
||||
requestId: string
|
||||
text: string
|
||||
/** 搜索范围(UI 决定)。省略 = 不限制(等价于 all)。 */
|
||||
scope?: AskWechatScope
|
||||
/**
|
||||
* Legacy fallback 需要沿用 UI 当前的范围 / 会话选择(可选;缺省 global + all)。
|
||||
*
|
||||
* Query Agent 主路径**不消费**这些字段:时间语义来自问题本身(temporalBasis),
|
||||
* 不能被 UI 的时间开关覆盖。
|
||||
*/
|
||||
legacy?: Partial<Omit<AiSearchPipelineRequest, 'requestId' | 'text'>>
|
||||
}
|
||||
|
||||
/** 允许回退 Legacy 的原因(仅 Runtime 不可恢复错误)。 */
|
||||
export type AskWechatFallbackReason = 'runtime_error'
|
||||
|
||||
export type AskWechatQueryResult =
|
||||
/** Query Agent 正常回答(含 clarification:模型用自然语言追问,UI 当普通回复显示)。 */
|
||||
| {
|
||||
engine: 'query-agent'
|
||||
status: 'answered'
|
||||
answer: string
|
||||
/** 本次回答实际依据的证据(去重、限量);UI 不允许从 answer 反解析。 */
|
||||
evidence: AskWechatEvidenceItem[]
|
||||
stats: AskWechatStats
|
||||
diagnostics: QueryAgentDiagnostics
|
||||
}
|
||||
/**
|
||||
* Provider 不可用 / 未配置。
|
||||
* 不回退 Legacy:Legacy 走同一个 AIProviderService,同样会失败,只会增加等待时间。
|
||||
*/
|
||||
| {
|
||||
engine: 'query-agent'
|
||||
status: 'provider_unavailable'
|
||||
message: string
|
||||
diagnostics: QueryAgentDiagnostics
|
||||
}
|
||||
/** Runtime 抛出未分类异常 → 按既定规则回退 Legacy。 */
|
||||
| {
|
||||
engine: 'legacy'
|
||||
status: 'legacy'
|
||||
reason: AskWechatFallbackReason
|
||||
result: AiSearchPipelineResult
|
||||
}
|
||||
/** 无法回答且不回退(空问题等)。 */
|
||||
| { engine: 'query-agent'; status: 'error'; message: string; diagnostics: QueryAgentDiagnostics }
|
||||
|
||||
export interface AskWechatConfig {
|
||||
/** Query Agent 是否为桌面问问微信的主路径。 */
|
||||
queryAgentEnabled: boolean
|
||||
}
|
||||
@@ -56,6 +56,23 @@ export interface Message {
|
||||
exportConversationAvatarUrl?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 「跳转到原聊天」的锚点读取结果。
|
||||
*
|
||||
* `found: false` 是**有意义**的返回值,不是错误:它表示会话已经打开、窗口也加载了,
|
||||
* 但目标消息不在窗口里(被清理 / 时间戳口径漂移)。UI 必须据此诚实提示,
|
||||
* 而不是把"跳到了会话"说成"定位到了消息"。
|
||||
*/
|
||||
export interface MessagesAroundResult {
|
||||
messages: Message[]
|
||||
/** 窗口内精确匹配到目标消息(按规范化消息 id,不是按时间)。 */
|
||||
found: boolean
|
||||
/** 实际使用的窗口半径(秒);0 表示没有可用锚点时间、只做了兜底读取。 */
|
||||
radiusSeconds: number
|
||||
/** 窗口消息数超过单次上限被截断。 */
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
type TextContent = { type: 'text'; content: string }
|
||||
type VoiceContent = { type: 'voice'; duration?: number }
|
||||
type LocationContent = {
|
||||
|
||||
Reference in new issue
Block a user