mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +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
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Agent Hub 入站文本的**纯路由**:无 LLM、无副作用、可单测。
|
||||
* 明确的产物 / 群成员分析 / 会话列表请求各走确定性 Action,其余一律进 Query Agent Runtime。
|
||||
*
|
||||
* **"总结" 不等于 Report**:只有同时提到"群"与明确产物才触发 Report Action。
|
||||
* 查询类问题直接进 Query Agent,不做意图分类 —— 避免"先分类一次 LLM、再查询一次 LLM"。
|
||||
*/
|
||||
import type { AskWechatQueryResult } from '../../shared/query-agent'
|
||||
|
||||
export interface GroupReportIntent {
|
||||
group: string
|
||||
range: 'today' | 'yesterday' | '7days'
|
||||
}
|
||||
|
||||
export interface GroupMemberChatIntent {
|
||||
group: string
|
||||
member: string
|
||||
range: 'today' | 'yesterday' | '7days'
|
||||
days: number
|
||||
goal: string
|
||||
}
|
||||
|
||||
export type InboundRoute =
|
||||
| { kind: 'report_action'; intent: GroupReportIntent }
|
||||
| { kind: 'group_member_action'; intent: GroupMemberChatIntent }
|
||||
| { kind: 'recent_list'; limit: number }
|
||||
| { kind: 'knowledge_query' }
|
||||
|
||||
/**
|
||||
* Report Action 快捷匹配。
|
||||
*
|
||||
* 必须同时满足:提到"群" + 提到明确的**产物**(图片 / 长图 / 日报 / 报告)。
|
||||
* 只提到"总结"不算 —— 那是 Query Agent 的 conversation_overview 场景。
|
||||
*/
|
||||
export function matchGroupReportIntent(text: string): GroupReportIntent | null {
|
||||
const normalized = text.trim()
|
||||
if (!normalized.includes('群') || !/(图片|长图|日报|报告)/.test(normalized)) return null
|
||||
const range = /(7天|七天|一周)/.test(normalized)
|
||||
? '7days'
|
||||
: /(昨天|昨日)/.test(normalized)
|
||||
? 'yesterday'
|
||||
: 'today'
|
||||
const group = normalized
|
||||
.replace(
|
||||
/请|帮我|生成|做一份|做个|今天的|今日的|今天|今日|昨天的|昨日的|昨天|昨日|最近7天的|最近七天的|最近7天|最近七天|近7天的|近七天的|近7天|近七天|消息|聊天记录|聊天|群聊总结|群总结|群日报|群报告|总结|日报|报告|图片|长图/g,
|
||||
''
|
||||
)
|
||||
.replace(/[,。!??::]/g, '')
|
||||
.trim()
|
||||
.replace(/成$/, '')
|
||||
.replace(/群$/, '')
|
||||
.trim()
|
||||
return group ? { group, range } : null
|
||||
}
|
||||
|
||||
/** 群成员专用分析的快捷匹配(保留为 Action:它有自己的 goal 与输出形态)。 */
|
||||
export function matchGroupMemberChatIntent(text: string): GroupMemberChatIntent | null {
|
||||
const normalized = text.trim().replace(/[,。!??::]/g, '')
|
||||
const timePattern = '(今天|今日|昨天|昨日|最近\\d{1,2}天|近\\d{1,2}天|最近|近来|这几天)'
|
||||
const actionPattern = '(?:说了什么|聊了什么|发言|说过什么|都聊什么|都说什么|干了什么)'
|
||||
const patterns = [
|
||||
new RegExp(
|
||||
`(?:看一下|看看|看下|查一下|总结一下)?(.+?群(?:聊)?)[\\s,,]+(.+?)${timePattern}${actionPattern}`
|
||||
),
|
||||
new RegExp(
|
||||
`(?:看一下|看看|看下|查一下|总结一下)?(.+?群(?:聊)?)(?:里|中的)(.+?)${timePattern}${actionPattern}`
|
||||
)
|
||||
]
|
||||
for (const pattern of patterns) {
|
||||
const match = normalized.match(pattern)
|
||||
if (match?.[1]?.trim() && match[2]?.trim()) {
|
||||
const range = /昨天|昨日/.test(match[3] || '')
|
||||
? 'yesterday'
|
||||
: /今天|今日/.test(match[3] || '')
|
||||
? 'today'
|
||||
: '7days'
|
||||
const days = Math.max(1, Math.min(30, Number((match[3] || '').match(/\d{1,2}/)?.[0]) || 7))
|
||||
return {
|
||||
group: match[1].trim(),
|
||||
member: match[2].trim(),
|
||||
range,
|
||||
days,
|
||||
goal: normalized
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* "最近有哪些会话"类请求。
|
||||
*
|
||||
* 这是**确定性能力**(列出会话),不是消息内容查询 —— Query Agent 无法表达,
|
||||
* 因此保留为不经过模型的无 LLM 快捷路径。
|
||||
*/
|
||||
export function matchRecentChatIntent(text: string): number | null {
|
||||
const normalized = text.replace(/\s+/g, '')
|
||||
if (!normalized.includes('最近') || !/(消息|会话|聊天)/.test(normalized)) return null
|
||||
const limit = Number(normalized.match(/\d{1,2}/)?.[0] || 5)
|
||||
return Math.max(1, Math.min(20, limit))
|
||||
}
|
||||
|
||||
export function resolveInboundRoute(text: string): InboundRoute {
|
||||
const report = matchGroupReportIntent(text)
|
||||
if (report) return { kind: 'report_action', intent: report }
|
||||
const member = matchGroupMemberChatIntent(text)
|
||||
if (member) return { kind: 'group_member_action', intent: member }
|
||||
const recent = matchRecentChatIntent(text)
|
||||
if (recent !== null) return { kind: 'recent_list', limit: recent }
|
||||
return { kind: 'knowledge_query' }
|
||||
}
|
||||
|
||||
/** 查询大脑不可用时的统一文案(不暴露 stack / provider raw response / 内部 id)。 */
|
||||
export const QUERY_AGENT_UNAVAILABLE_TEXT = '当前 AI 查询服务暂时不可用,请稍后再试。'
|
||||
|
||||
/**
|
||||
* 把 Query Agent 结果映射成**微信文字回复**。
|
||||
* 只输出用户可读文本;Tool trace / temporalBasis / Evidence / 诊断字段一律不下发。
|
||||
*/
|
||||
export function queryAgentReplyText(result: AskWechatQueryResult): string {
|
||||
if (result.status === 'answered') return result.answer
|
||||
if (result.status === 'provider_unavailable' || result.status === 'error') return result.message
|
||||
// Agent Hub 没有 Legacy runner,不会产生 legacy 结果;真出现时按服务不可用处理,不暴露内部结构。
|
||||
return QUERY_AGENT_UNAVAILABLE_TEXT
|
||||
}
|
||||
@@ -15,6 +15,15 @@ import type {
|
||||
import type { AppSettings } from './settings-store'
|
||||
import { generateAgentGroupReport } from './agent-group-report-service'
|
||||
import { AIProviderService } from './ai-provider-service'
|
||||
import { QueryAgentService } from './query-agent-service'
|
||||
import { AskWechatService } from './ask-wechat-service'
|
||||
import {
|
||||
QUERY_AGENT_UNAVAILABLE_TEXT,
|
||||
queryAgentReplyText,
|
||||
resolveInboundRoute,
|
||||
type GroupMemberChatIntent,
|
||||
type GroupReportIntent
|
||||
} from './agent-hub-routing'
|
||||
import { isPackagedRuntime } from '../runtime-mode'
|
||||
import {
|
||||
getGroupSnapshot,
|
||||
@@ -53,30 +62,6 @@ export interface AgentHubNotificationResult {
|
||||
error?: string
|
||||
}
|
||||
|
||||
interface GroupReportIntent {
|
||||
group: string
|
||||
range: 'today' | 'yesterday' | '7days'
|
||||
}
|
||||
|
||||
interface ContactChatIntent {
|
||||
contact: string
|
||||
limit: number
|
||||
summarize: boolean
|
||||
}
|
||||
|
||||
interface GroupMemberChatIntent {
|
||||
group: string
|
||||
member: string
|
||||
range: 'today' | 'yesterday' | '7days'
|
||||
days: number
|
||||
goal: string
|
||||
}
|
||||
|
||||
interface NaturalLanguageResult {
|
||||
command?: string
|
||||
reply?: string
|
||||
}
|
||||
|
||||
const agentAIProvider = new AIProviderService()
|
||||
|
||||
function resolveBundledBinary(
|
||||
@@ -127,6 +112,24 @@ export class AgentHubService {
|
||||
updatedAt: Date.now()
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询大脑。由主进程注入**同一个** QueryAgentRuntime 实例(桌面问问微信也用它),
|
||||
* Agent Hub 只负责把微信问题送进去、把回答发回去。
|
||||
*/
|
||||
private queryAgent: AskWechatService | null = null
|
||||
|
||||
/**
|
||||
* 注入生产 Query Agent Runtime(桌面与微信机器人共用同一实现,避免第二套 Query 语义)。
|
||||
*/
|
||||
setQueryAgentService(runtime: QueryAgentService): void {
|
||||
this.queryAgent = new AskWechatService(runtime, {
|
||||
entry: 'agent-hub',
|
||||
// Agent Hub 没有 Legacy AI Search 通道:查询失败时给出明确文案,绝不误触 Report Action。
|
||||
log: (record) =>
|
||||
this.addLog('agent-hub', record.level === 'info' ? 'info' : record.level, record.message)
|
||||
})
|
||||
}
|
||||
|
||||
async start(settings: AppSettings): Promise<boolean> {
|
||||
void settings
|
||||
this.stopping = false
|
||||
@@ -397,301 +400,82 @@ export class AgentHubService {
|
||||
.join(' ')
|
||||
this.addLog('agent-hub', 'info', `收到微信消息 message_id=${messageId || 'unknown'}`)
|
||||
|
||||
const reportIntent = this.matchGroupReportIntent(text)
|
||||
// 三路边界:明确产物 → Report / 成员分析 Action;会话列表 → 确定性能力;其余 → Query Agent。
|
||||
// 注意:这里**不再**先跑意图分类 LLM,查询类问题直接进入 Query Agent(避免双重 LLM 语义系统)。
|
||||
const route = resolveInboundRoute(text)
|
||||
|
||||
if (reportIntent) {
|
||||
if (route.kind === 'report_action') {
|
||||
if (messageId) this.processedMessages.set(messageId, Date.now())
|
||||
this.addLog(
|
||||
'agent-hub',
|
||||
'info',
|
||||
`匹配群聊总结:${reportIntent.group}(${reportIntent.range})`
|
||||
`匹配群聊总结:${route.intent.group}(${route.intent.range})`
|
||||
)
|
||||
await this.sendConnector(inbound, '收到!正在生成群聊总结,请等待…').catch((error) => {
|
||||
this.addLog('agent-hub', 'warn', `等待提示发送失败:${this.errorMessage(error)}`)
|
||||
})
|
||||
void this.generateAndSendReport(inbound, reportIntent)
|
||||
void this.generateAndSendReport(inbound, route.intent)
|
||||
return this.sendHubJson(response, 202, { status: 'generating' })
|
||||
}
|
||||
|
||||
const groupMemberIntent = this.matchGroupMemberChatIntent(text)
|
||||
if (groupMemberIntent) {
|
||||
if (route.kind === 'group_member_action') {
|
||||
if (messageId) this.processedMessages.set(messageId, Date.now())
|
||||
void this.summarizeGroupMemberChat(inbound, groupMemberIntent)
|
||||
void this.summarizeGroupMemberChat(inbound, route.intent)
|
||||
return this.sendHubJson(response, 202, { status: 'generating', mode: 'group-member-summary' })
|
||||
}
|
||||
|
||||
const contactChatIntent = this.matchContactChatIntent(text)
|
||||
if (contactChatIntent) {
|
||||
if (messageId) this.processedMessages.set(messageId, Date.now())
|
||||
if (contactChatIntent.summarize) {
|
||||
void this.summarizeContactChat(inbound, contactChatIntent)
|
||||
return this.sendHubJson(response, 202, { status: 'generating', mode: 'contact-summary' })
|
||||
if (route.kind === 'recent_list') {
|
||||
if (!isReady()) return this.sendHubJson(response, 502, { error: 'upstream query failed' })
|
||||
const items = listRecentChat(route.limit)
|
||||
const lines = items.map((item, index) => {
|
||||
const name = item.m_nsNickName.trim() || item.m_nsUsrName.trim()
|
||||
return `${index + 1}. ${name}(${item.type === 'group' ? '群聊' : '联系人'})`
|
||||
})
|
||||
const reply = lines.length
|
||||
? `最近 ${items.length} 个会话:\n${lines.join('\n')}`
|
||||
: '暂时没有找到最近会话。'
|
||||
try {
|
||||
await this.sendConnector(inbound, reply)
|
||||
} catch (error) {
|
||||
this.addLog('agent-hub', 'error', `回复发送失败:${this.errorMessage(error)}`)
|
||||
return this.sendHubJson(response, 502, { error: 'reply delivery failed' })
|
||||
}
|
||||
await this.replyContactChat(inbound, contactChatIntent)
|
||||
if (messageId) this.processedMessages.set(messageId, Date.now())
|
||||
this.addLog('agent-hub', 'info', `最近会话回复已发送(${items.length} 条)`)
|
||||
return this.sendHubJson(response, 200, { status: 'ok' })
|
||||
}
|
||||
|
||||
const recentChatLimit = this.matchRecentChatIntent(text)
|
||||
if (recentChatLimit === null && text.trim()) {
|
||||
if (messageId) this.processedMessages.set(messageId, Date.now())
|
||||
void this.handleNaturalLanguage(inbound, text)
|
||||
return this.sendHubJson(response, 202, {
|
||||
status: 'processing',
|
||||
mode: 'natural-language'
|
||||
})
|
||||
}
|
||||
if (recentChatLimit === null) {
|
||||
this.addLog('agent-hub', 'info', '消息已忽略:没有匹配到支持的意图')
|
||||
return this.sendHubJson(response, 202, { status: 'ignored', reason: 'no matching intent' })
|
||||
}
|
||||
if (!isReady()) return this.sendHubJson(response, 502, { error: 'upstream query failed' })
|
||||
const items = listRecentChat(recentChatLimit)
|
||||
const lines = items.map((item, index) => {
|
||||
const name = item.m_nsNickName.trim() || item.m_nsUsrName.trim()
|
||||
return `${index + 1}. ${name}(${item.type === 'group' ? '群聊' : '联系人'})`
|
||||
})
|
||||
const reply = lines.length
|
||||
? `最近 ${items.length} 个会话:\n${lines.join('\n')}`
|
||||
: '暂时没有找到最近会话。'
|
||||
try {
|
||||
await this.sendConnector(inbound, reply)
|
||||
} catch (error) {
|
||||
this.addLog('agent-hub', 'error', `回复发送失败:${this.errorMessage(error)}`)
|
||||
return this.sendHubJson(response, 502, { error: 'reply delivery failed' })
|
||||
if (!text.trim()) {
|
||||
this.addLog('agent-hub', 'info', '消息已忽略:内容为空')
|
||||
return this.sendHubJson(response, 202, { status: 'ignored', reason: 'empty text' })
|
||||
}
|
||||
if (messageId) this.processedMessages.set(messageId, Date.now())
|
||||
this.addLog('agent-hub', 'info', `最近会话回复已发送(${items.length} 条)`)
|
||||
this.sendHubJson(response, 200, { status: 'ok' })
|
||||
void this.handleKnowledgeQuery(inbound, text)
|
||||
return this.sendHubJson(response, 202, { status: 'processing', mode: 'query-agent' })
|
||||
}
|
||||
|
||||
private async handleNaturalLanguage(inbound: InboundMessage, text: string): Promise<void> {
|
||||
try {
|
||||
const result = await this.resolveNaturalLanguage(text)
|
||||
if (result.reply) {
|
||||
await this.sendConnector(inbound, this.formatAIReply(result.reply))
|
||||
this.addLog('agent-hub', 'info', '自然语言回复已发送')
|
||||
return
|
||||
}
|
||||
if (!result.command) {
|
||||
await this.sendConnector(inbound, '暂时没有理解你的意思,可以换一种说法再试。')
|
||||
return
|
||||
}
|
||||
|
||||
this.addLog('agent-hub', 'info', `自然语言已理解为:${result.command}`)
|
||||
const reportIntent = this.matchGroupReportIntent(result.command)
|
||||
if (reportIntent) {
|
||||
await this.sendConnector(inbound, '收到!正在生成群聊总结,请等待…').catch(() => undefined)
|
||||
await this.generateAndSendReport(inbound, reportIntent)
|
||||
return
|
||||
}
|
||||
|
||||
const groupMemberIntent = this.matchGroupMemberChatIntent(result.command)
|
||||
if (groupMemberIntent) {
|
||||
await this.summarizeGroupMemberChat(inbound, groupMemberIntent)
|
||||
return
|
||||
}
|
||||
|
||||
const contactIntent = this.matchContactChatIntent(result.command)
|
||||
if (contactIntent) {
|
||||
if (contactIntent.summarize) await this.summarizeContactChat(inbound, contactIntent)
|
||||
else await this.replyContactChat(inbound, contactIntent)
|
||||
return
|
||||
}
|
||||
|
||||
const recentLimit = this.matchRecentChatIntent(result.command)
|
||||
if (recentLimit !== null) {
|
||||
await this.replyRecentChats(inbound, recentLimit)
|
||||
return
|
||||
}
|
||||
await this.sendConnector(inbound, '暂时没有理解你的意思,可以换一种说法再试。')
|
||||
} catch (error) {
|
||||
this.addLog('agent-hub', 'error', `自然语言处理失败:${this.errorMessage(error)}`)
|
||||
await this.sendConnector(inbound, `处理失败:${this.errorMessage(error)}`).catch(
|
||||
() => undefined
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private async replyRecentChats(inbound: InboundMessage, limit: number): Promise<void> {
|
||||
if (!isReady()) {
|
||||
await this.sendConnector(inbound, 'TraceMemo 本地数据库尚未连接,请连接后再试。')
|
||||
/**
|
||||
* 查询类问题("微信里发生了什么"、普通闲聊)统一走 Query Agent Runtime。
|
||||
* 失败时不回退 Report Action,只给用户明确文案。
|
||||
*/
|
||||
private async handleKnowledgeQuery(inbound: InboundMessage, text: string): Promise<void> {
|
||||
const service = this.queryAgent
|
||||
if (!service) {
|
||||
this.addLog('agent-hub', 'error', '查询大脑尚未初始化')
|
||||
await this.sendConnector(inbound, QUERY_AGENT_UNAVAILABLE_TEXT).catch(() => undefined)
|
||||
return
|
||||
}
|
||||
const items = listRecentChat(limit)
|
||||
const lines = items.map((item, index) => {
|
||||
const name = item.m_nsNickName.trim() || item.m_nsUsrName.trim()
|
||||
return `${index + 1}. ${name}(${item.type === 'group' ? '群聊' : '联系人'})`
|
||||
})
|
||||
await this.sendConnector(
|
||||
inbound,
|
||||
lines.length ? `最近 ${items.length} 个会话:\n${lines.join('\n')}` : '暂时没有找到最近会话。'
|
||||
)
|
||||
this.addLog('agent-hub', 'info', `最近会话回复已发送(${items.length} 条)`)
|
||||
}
|
||||
|
||||
private async resolveNaturalLanguage(text: string): Promise<NaturalLanguageResult> {
|
||||
const result = await agentAIProvider.chat([
|
||||
{
|
||||
role: 'system',
|
||||
content: `你是 TraceMemo 微信机器人的意图理解器。只能输出一行 JSON,不要 Markdown。
|
||||
支持的工具:
|
||||
1. recent:查看最近会话,参数 limit 为 1-20。
|
||||
2. contact:查看我与某个联系人的最近聊天,参数 contact 和 limit。
|
||||
3. report:生成某个群的群聊总结图片,参数 group 和 range(today、yesterday、7days)。
|
||||
4. group_member:分析某个群里某位成员的发言,参数 group、member、range(today、yesterday、7days)、days(1-30)和 goal(保留用户希望总结、研究人物、提取观点等完整目标)。只要用户同时提到群聊和群成员,应优先使用 group_member,不能识别成 contact。
|
||||
5. chat:不需要工具的普通对话,reply 用简洁中文直接回答。
|
||||
输出格式:{"type":"recent|contact|report|group_member|chat","limit":5,"contact":"","group":"","member":"","range":"today","days":3,"goal":"","reply":""}
|
||||
不要声称已经读取未调用的聊天记录,不要执行电脑控制、文件操作、付款或发送给其他联系人。`
|
||||
},
|
||||
{ role: 'user', content: text.slice(0, 1000) }
|
||||
])
|
||||
if (!result.success || !result.data) {
|
||||
this.addLog('agent-hub', 'warn', `自然语言理解不可用:${result.error || 'AI 未返回内容'}`)
|
||||
return {}
|
||||
}
|
||||
|
||||
try {
|
||||
const json = result.data.match(/\{[\s\S]*\}/)?.[0]
|
||||
if (!json) return {}
|
||||
const parsed = JSON.parse(json) as Record<string, unknown>
|
||||
const limit = Math.max(1, Math.min(20, Number(parsed['limit']) || 5))
|
||||
if (parsed['type'] === 'recent') return { command: `最近${limit}条消息` }
|
||||
if (parsed['type'] === 'contact' && String(parsed['contact'] || '').trim()) {
|
||||
return { command: `我和${String(parsed['contact']).trim()}最近${limit}条聊了什么` }
|
||||
}
|
||||
if (parsed['type'] === 'report' && String(parsed['group'] || '').trim()) {
|
||||
const range =
|
||||
parsed['range'] === '7days'
|
||||
? '最近7天'
|
||||
: parsed['range'] === 'yesterday'
|
||||
? '昨天'
|
||||
: '今天'
|
||||
return { command: `生成${String(parsed['group']).trim()}${range}的群聊总结图片` }
|
||||
}
|
||||
if (
|
||||
parsed['type'] === 'group_member' &&
|
||||
String(parsed['group'] || '').trim() &&
|
||||
String(parsed['member'] || '').trim()
|
||||
) {
|
||||
const range =
|
||||
parsed['range'] === 'yesterday'
|
||||
? '昨天'
|
||||
: parsed['range'] === 'today'
|
||||
? '今天'
|
||||
: '最近7天'
|
||||
const group = String(parsed['group'] || '')
|
||||
.trim()
|
||||
.replace(/(?:群聊|群)+$/g, '')
|
||||
const days = Math.max(1, Math.min(30, Number(parsed['days']) || 7))
|
||||
const goal = String(parsed['goal'] || '总结发言').trim()
|
||||
return {
|
||||
command: `看看${group}群里${String(parsed['member']).trim()}${range === '最近7天' ? `最近${days}天` : range}说了什么,${goal}`
|
||||
}
|
||||
}
|
||||
if (parsed['type'] === 'chat') {
|
||||
const reply = String(parsed['reply'] || '').trim()
|
||||
return reply ? { reply: reply.slice(0, 1500) } : {}
|
||||
}
|
||||
const conversationKey = `${String(inbound.account_id || '')}::${String(inbound.from_user_id || '')}`
|
||||
const result = await service.ask(
|
||||
{ requestId: `agent-hub-${Date.now()}-${this.nextLogId}`, text },
|
||||
conversationKey
|
||||
)
|
||||
await this.sendConnector(inbound, this.formatAIReply(queryAgentReplyText(result)))
|
||||
this.addLog('agent-hub', 'info', `查询回答已发送(${result.status})`)
|
||||
} catch (error) {
|
||||
this.addLog('agent-hub', 'warn', `自然语言结果解析失败:${this.errorMessage(error)}`)
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
private async replyContactChat(
|
||||
inbound: InboundMessage,
|
||||
intent: ContactChatIntent
|
||||
): Promise<void> {
|
||||
if (!isReady()) {
|
||||
await this.sendConnector(inbound, 'TraceMemo 本地数据库尚未连接,请连接后再试。')
|
||||
return
|
||||
}
|
||||
|
||||
const contact = resolveMd5(intent.contact)
|
||||
if (!contact || contact.type !== 'user') {
|
||||
this.addLog('agent-hub', 'info', `没有匹配到联系人:${intent.contact}`)
|
||||
await this.sendConnector(inbound, `没有找到联系人“${intent.contact}”。`)
|
||||
return
|
||||
}
|
||||
|
||||
this.addLog(
|
||||
'agent-hub',
|
||||
'info',
|
||||
`匹配联系人聊天查询:${contact.m_nsNickName}(最近 ${intent.limit} 条)`
|
||||
)
|
||||
const messages = listMessages(contact.md5, undefined, undefined, { limit: intent.limit })
|
||||
const recent = messages.slice(-intent.limit)
|
||||
const lines = recent.map((message) => {
|
||||
const speaker = message.isSender ? '我' : contact.m_nsNickName
|
||||
const content = this.describeChatMessage(message.content, message.type)
|
||||
return `${speaker}:${content}`
|
||||
})
|
||||
const reply = lines.length
|
||||
? `我和${contact.m_nsNickName}最近聊了这些:\n${lines.join('\n')}`
|
||||
: `暂时没有找到和${contact.m_nsNickName}的聊天记录。`
|
||||
await this.sendConnector(inbound, reply)
|
||||
this.addLog('agent-hub', 'info', `联系人聊天回复已发送(${recent.length} 条)`)
|
||||
}
|
||||
|
||||
private async summarizeContactChat(
|
||||
inbound: InboundMessage,
|
||||
intent: ContactChatIntent
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (!isReady()) {
|
||||
await this.sendConnector(inbound, 'TraceMemo 本地数据库尚未连接,请连接后再试。')
|
||||
return
|
||||
}
|
||||
const contact = resolveMd5(intent.contact)
|
||||
if (!contact || contact.type !== 'user') {
|
||||
await this.sendConnector(inbound, `没有找到联系人“${intent.contact}”。`)
|
||||
return
|
||||
}
|
||||
|
||||
await this.sendConnector(
|
||||
inbound,
|
||||
`收到!正在整理和${contact.m_nsNickName}的近期聊天,请等待…`
|
||||
)
|
||||
const endTime = Math.floor(Date.now() / 1000)
|
||||
const startTime = endTime - 7 * 24 * 60 * 60
|
||||
const messages = listMessages(contact.md5, startTime, endTime, { limit: 300 }).slice(-300)
|
||||
if (!messages.length) {
|
||||
await this.sendConnector(inbound, `最近 7 天没有找到和${contact.m_nsNickName}的聊天记录。`)
|
||||
return
|
||||
}
|
||||
|
||||
const transcript = messages
|
||||
.map((message) => {
|
||||
const speaker = message.isSender ? '我' : contact.m_nsNickName
|
||||
return `[${message.datetime}] ${speaker}:${this.describeChatMessage(message.content, message.type)}`
|
||||
})
|
||||
.join('\n')
|
||||
const summary = await agentAIProvider.chat([
|
||||
{
|
||||
role: 'system',
|
||||
content:
|
||||
'你是私人聊天记录总结助手。仅根据提供的记录总结,不编造。按日期或主题整理关键进展、双方观点、决定、待办和未解决问题;忽略无意义表情,保留重要数字与事实。使用适合微信阅读的简洁中文。'
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: `请总结我和“${contact.m_nsNickName}”最近 7 天聊了什么。\n\n聊天记录:\n${transcript}`
|
||||
}
|
||||
])
|
||||
if (!summary.success || !summary.data?.trim()) {
|
||||
throw new Error(summary.error || 'AI 未返回总结')
|
||||
}
|
||||
await this.sendConnector(
|
||||
inbound,
|
||||
this.formatAIReply(
|
||||
`和${contact.m_nsNickName}最近聊天总结(近 7 天,共 ${messages.length} 条):\n\n${summary.data.trim().slice(0, 3500)}`
|
||||
)
|
||||
)
|
||||
this.addLog('agent-hub', 'info', `联系人聊天总结已发送(${messages.length} 条)`)
|
||||
} catch (error) {
|
||||
this.addLog('agent-hub', 'error', `联系人聊天总结失败:${this.errorMessage(error)}`)
|
||||
await this.sendConnector(inbound, `聊天总结失败:${this.errorMessage(error)}`).catch(
|
||||
() => undefined
|
||||
)
|
||||
this.addLog('agent-hub', 'error', `查询处理失败:${this.errorMessage(error)}`)
|
||||
await this.sendConnector(inbound, QUERY_AGENT_UNAVAILABLE_TEXT).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -881,65 +665,6 @@ export class AgentHubService {
|
||||
return { ok: response.ok, status: response.status, body: await response.text() }
|
||||
}
|
||||
|
||||
private matchRecentChatIntent(text: string): number | null {
|
||||
const normalized = text.replace(/\s+/g, '')
|
||||
if (!normalized.includes('最近') || !/(消息|会话|聊天)/.test(normalized)) return null
|
||||
const limit = Number(normalized.match(/\d{1,2}/)?.[0] || 5)
|
||||
return Math.max(1, Math.min(20, limit))
|
||||
}
|
||||
|
||||
private matchContactChatIntent(text: string): ContactChatIntent | null {
|
||||
const normalized = text.replace(/\s+/g, '').replace(/[,。!??::]/g, '')
|
||||
if (!normalized.includes('最近') || !/(聊|消息|会话)/.test(normalized)) return null
|
||||
|
||||
const patterns = [
|
||||
/(?:看一下|看看|查一下|查询)?我和(.+?)最近(?:\d{1,2}条)?(?:聊了什么|聊什么|的聊天|的消息|聊天|消息)/,
|
||||
/(?:看一下|看看|查一下|查询)?(?:我)?最近(?:\d{1,2}条)?和(.+?)(?:聊了什么|聊什么|的聊天|的消息|聊天|消息)/,
|
||||
/(?:看一下|看看|查一下|查询)?和(.+?)最近(?:\d{1,2}条)?(?:聊了什么|聊什么|的聊天|的消息|聊天|消息)/
|
||||
]
|
||||
const contact = patterns
|
||||
.map((pattern) => normalized.match(pattern)?.[1]?.trim())
|
||||
.find((value): value is string => Boolean(value))
|
||||
if (!contact) return null
|
||||
|
||||
const limit = Number(normalized.match(/最近(\d{1,2})条/)?.[1] || 10)
|
||||
const summarize = /(聊了什么|聊什么|说了什么|谈了什么|总结)/.test(normalized)
|
||||
return { contact, limit: Math.max(1, Math.min(20, limit)), summarize }
|
||||
}
|
||||
|
||||
private matchGroupMemberChatIntent(text: string): GroupMemberChatIntent | null {
|
||||
const normalized = text.trim().replace(/[,。!??::]/g, '')
|
||||
const timePattern = '(今天|今日|昨天|昨日|最近\\d{1,2}天|近\\d{1,2}天|最近|近来|这几天)'
|
||||
const actionPattern = '(?:说了什么|聊了什么|发言|说过什么|都聊什么|都说什么|干了什么)'
|
||||
const patterns = [
|
||||
new RegExp(
|
||||
`(?:看一下|看看|看下|查一下|总结一下)?(.+?群(?:聊)?)[\\s,,]+(.+?)${timePattern}${actionPattern}`
|
||||
),
|
||||
new RegExp(
|
||||
`(?:看一下|看看|看下|查一下|总结一下)?(.+?群(?:聊)?)(?:里|中的)(.+?)${timePattern}${actionPattern}`
|
||||
)
|
||||
]
|
||||
for (const pattern of patterns) {
|
||||
const match = normalized.match(pattern)
|
||||
if (match?.[1]?.trim() && match[2]?.trim()) {
|
||||
const range = /昨天|昨日/.test(match[3] || '')
|
||||
? 'yesterday'
|
||||
: /今天|今日/.test(match[3] || '')
|
||||
? 'today'
|
||||
: '7days'
|
||||
const days = Math.max(1, Math.min(30, Number((match[3] || '').match(/\d{1,2}/)?.[0]) || 7))
|
||||
return {
|
||||
group: match[1].trim(),
|
||||
member: match[2].trim(),
|
||||
range,
|
||||
days,
|
||||
goal: normalized
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private resolveGroup(query: string): ReturnType<typeof resolveMd5> {
|
||||
const normalize = (value: string): string =>
|
||||
value
|
||||
@@ -961,27 +686,6 @@ export class AgentHubService {
|
||||
)
|
||||
}
|
||||
|
||||
private matchGroupReportIntent(text: string): GroupReportIntent | null {
|
||||
const normalized = text.trim()
|
||||
if (!normalized.includes('群') || !/(总结|日报|报告)/.test(normalized)) return null
|
||||
const range = /(7天|七天|一周)/.test(normalized)
|
||||
? '7days'
|
||||
: /(昨天|昨日)/.test(normalized)
|
||||
? 'yesterday'
|
||||
: 'today'
|
||||
const group = normalized
|
||||
.replace(
|
||||
/请|帮我|生成|做一份|做个|今天的|今日的|今天|今日|昨天的|昨日的|昨天|昨日|最近7天的|最近七天的|最近7天|最近七天|近7天的|近七天的|近7天|近七天|消息|聊天记录|聊天|群聊总结|群总结|群日报|群报告|总结|日报|报告|图片|长图/g,
|
||||
''
|
||||
)
|
||||
.replace(/[,。!??::]/g, '')
|
||||
.trim()
|
||||
.replace(/成$/, '')
|
||||
.replace(/群$/, '')
|
||||
.trim()
|
||||
return group ? { group, range } : null
|
||||
}
|
||||
|
||||
private authorized(header: string | undefined): boolean {
|
||||
if (!header?.startsWith('Bearer ')) return false
|
||||
const expected = Buffer.from(this.inboundToken)
|
||||
|
||||
@@ -586,6 +586,9 @@ export class AiSearchPipelineService {
|
||||
state: 'ready',
|
||||
indexedMessageCount: 0,
|
||||
indexedChunkCount: 0,
|
||||
// Legacy 路径不消费 freshness 口径;显式写 null,避免与 Query Agent 的覆盖语义混淆。
|
||||
indexLatestAt: null,
|
||||
sourceLatestAt: null,
|
||||
totalMessages: 0,
|
||||
evidence: [],
|
||||
timings: emptyKnowledgeSearchTimings()
|
||||
@@ -1379,6 +1382,8 @@ export class AiSearchPipelineService {
|
||||
state: 'unavailable',
|
||||
indexedMessageCount: 0,
|
||||
indexedChunkCount: 0,
|
||||
indexLatestAt: null,
|
||||
sourceLatestAt: null,
|
||||
totalMessages: 0,
|
||||
evidence: [],
|
||||
timings: emptyKnowledgeSearchTimings()
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
import type { AiSearchPipelineRequest, AiSearchPipelineResult } from '../../shared/ai-search'
|
||||
import type {
|
||||
AskWechatEvidenceItem,
|
||||
AskWechatOutcome,
|
||||
AskWechatFallbackReason,
|
||||
AskWechatQueryRequest,
|
||||
AskWechatQueryResult,
|
||||
AskWechatScope,
|
||||
AskWechatStats,
|
||||
QueryAgentDiagnostics,
|
||||
QueryAgentEntry,
|
||||
QueryAgentProgressEvent
|
||||
} from '../../shared/query-agent'
|
||||
import { QueryAgentService, type QueryAgentResult } from './query-agent-service'
|
||||
import { QueryAgentConversationMemory } from './query-agent-conversation-memory'
|
||||
|
||||
/** Provider 不可用时的用户可见文案。不下发内部错误、stack、raw provider response。 */
|
||||
const PROVIDER_UNAVAILABLE_MESSAGE = '当前 AI 查询服务暂时不可用,请稍后再试。'
|
||||
/** Runtime 不可恢复错误(且无法回退)时的用户可见文案。 */
|
||||
const RUNTIME_FAILURE_MESSAGE = '本次查询没有完成,请稍后再试或换一种问法。'
|
||||
const EMPTY_QUESTION_MESSAGE = '请先输入想了解的问题。'
|
||||
|
||||
export type AskWechatLegacyRunner = (
|
||||
request: AiSearchPipelineRequest
|
||||
) => Promise<AiSearchPipelineResult>
|
||||
|
||||
export interface AskWechatLogRecord {
|
||||
level: 'info' | 'warn' | 'error'
|
||||
message: string
|
||||
details?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface AskWechatServiceOptions {
|
||||
/** 入口标记,只用于诊断。 */
|
||||
entry: QueryAgentEntry
|
||||
/**
|
||||
* 仅桌面使用:Runtime 不可恢复错误时允许回退 Legacy。
|
||||
* 不传表示该入口没有 Legacy fallback(Agent Hub 就没传)。
|
||||
*/
|
||||
runLegacy?: AskWechatLegacyRunner
|
||||
log?: (record: AskWechatLogRecord) => void
|
||||
memory?: QueryAgentConversationMemory
|
||||
}
|
||||
|
||||
/**
|
||||
* 「问问微信」/ Agent Hub 查询入口的 Adapter。
|
||||
*
|
||||
* 职责:调用 Query Agent Runtime、维护有界的澄清上下文、把结构化结果映射成可展示的形状、
|
||||
* 并决定是否允许 Legacy fallback。它**不含**任何 prompt / tool / temporalBasis 语义。
|
||||
*
|
||||
* Fallback 规则:只在 Runtime 不可恢复错误(异常 / tool limit)时回退 Legacy。
|
||||
* Provider 失败不回退(Legacy 用同一个 Provider,只会更慢);0 结果、模型说"没找到"、
|
||||
* 要求澄清、答案很短 —— 一律不回退。
|
||||
*/
|
||||
export class AskWechatService {
|
||||
private readonly memory: QueryAgentConversationMemory
|
||||
|
||||
constructor(
|
||||
private readonly runtime: QueryAgentService,
|
||||
private readonly options: AskWechatServiceOptions
|
||||
) {
|
||||
this.memory = options.memory || new QueryAgentConversationMemory()
|
||||
}
|
||||
|
||||
async ask(
|
||||
request: AskWechatQueryRequest,
|
||||
conversationKey = 'default',
|
||||
/**
|
||||
* 真实 Runtime 进度(ADDITIVE)。由 IPC 层转发给 renderer。
|
||||
* 不传时行为与之前完全一致;回调抛异常不会影响查询本身(Runtime 侧已兜住)。
|
||||
*/
|
||||
onProgress?: (event: QueryAgentProgressEvent) => void
|
||||
): Promise<AskWechatQueryResult> {
|
||||
const startedAt = Date.now()
|
||||
const question = String(request.text || '').trim()
|
||||
let result: QueryAgentResult
|
||||
try {
|
||||
result = await this.runtime.run(question, {
|
||||
history: this.memory.history(conversationKey),
|
||||
// 搜索范围:UI 决定的数据边界,Runtime 透传给 Engine 并结构性强制。
|
||||
...(request.scope ? { conversationScope: request.scope } : {}),
|
||||
...(onProgress ? { onProgress } : {})
|
||||
})
|
||||
} catch {
|
||||
// Runtime 抛出未分类异常 = UNEXPECTED_INTERNAL_ERROR,允许 Legacy fallback。
|
||||
const diagnostics = this.diagnostics(
|
||||
{ provider: '', model: '', modelCallCount: 0, toolCallCount: 0, traces: [] },
|
||||
startedAt,
|
||||
'runtime_error'
|
||||
)
|
||||
this.writeLog('error', `Query Agent Runtime 异常(${this.options.entry})`, diagnostics)
|
||||
return this.fallback(request, 'runtime_error', diagnostics)
|
||||
}
|
||||
|
||||
if (result.errorKind === 'invalid_question') {
|
||||
return {
|
||||
engine: 'query-agent',
|
||||
status: 'error',
|
||||
message: EMPTY_QUESTION_MESSAGE,
|
||||
diagnostics: this.diagnostics(result, startedAt, 'invalid_question')
|
||||
}
|
||||
}
|
||||
|
||||
if (result.errorKind === 'provider_unavailable' || result.errorKind === 'provider_failure') {
|
||||
const outcome: AskWechatOutcome = result.errorKind
|
||||
const diagnostics = this.diagnostics(result, startedAt, outcome)
|
||||
this.writeLog('warn', `查询 Provider 不可用(${this.options.entry})`, diagnostics)
|
||||
return {
|
||||
engine: 'query-agent',
|
||||
status: 'provider_unavailable',
|
||||
message: PROVIDER_UNAVAILABLE_MESSAGE,
|
||||
diagnostics
|
||||
}
|
||||
}
|
||||
|
||||
if (result.errorKind === 'tool_limit') {
|
||||
const diagnostics = this.diagnostics(result, startedAt, 'tool_limit')
|
||||
this.writeLog('warn', `查询超出工具调用上限(${this.options.entry})`, diagnostics)
|
||||
return this.fallback(request, 'runtime_error', diagnostics)
|
||||
}
|
||||
|
||||
if (!result.answer?.trim()) {
|
||||
const diagnostics = this.diagnostics(result, startedAt, 'runtime_error')
|
||||
this.writeLog('warn', `Query Agent 未返回回答(${this.options.entry})`, diagnostics)
|
||||
return this.fallback(request, 'runtime_error', diagnostics)
|
||||
}
|
||||
|
||||
const answer = result.answer.trim()
|
||||
// 澄清回答也记录:下一句("是 BOBO")需要接得上上文。
|
||||
this.memory.record(conversationKey, question, answer)
|
||||
const diagnostics = this.diagnostics(result, startedAt, 'answered')
|
||||
this.writeLog('info', `Query Agent 回答完成(${this.options.entry})`, diagnostics)
|
||||
return {
|
||||
engine: 'query-agent',
|
||||
status: 'answered',
|
||||
answer,
|
||||
// 直接透传 Runtime 收集的真实证据:UI 不允许从 answer 文本反解析。
|
||||
evidence: (result.evidence || []) as AskWechatEvidenceItem[],
|
||||
stats: buildAskWechatStats(result, request.scope, startedAt),
|
||||
diagnostics
|
||||
}
|
||||
}
|
||||
|
||||
/** 桌面点「新问题」时清掉当前会话的澄清上下文。 */
|
||||
forgetConversation(conversationKey = 'default'): void {
|
||||
this.memory.forget(conversationKey)
|
||||
}
|
||||
|
||||
private async fallback(
|
||||
request: AskWechatQueryRequest,
|
||||
reason: AskWechatFallbackReason,
|
||||
diagnostics: QueryAgentDiagnostics
|
||||
): Promise<AskWechatQueryResult> {
|
||||
if (!this.options.runLegacy) {
|
||||
return {
|
||||
engine: 'query-agent',
|
||||
status: 'error',
|
||||
message: RUNTIME_FAILURE_MESSAGE,
|
||||
diagnostics
|
||||
}
|
||||
}
|
||||
try {
|
||||
const legacyResult = await this.options.runLegacy({
|
||||
scope: 'global',
|
||||
range: 'all',
|
||||
...request.legacy,
|
||||
requestId: request.requestId,
|
||||
text: request.text
|
||||
})
|
||||
this.writeLog('warn', `Query Agent 失败后回退 Legacy(${this.options.entry})`, diagnostics, reason)
|
||||
return { engine: 'legacy', status: 'legacy', reason, result: legacyResult }
|
||||
} catch {
|
||||
this.writeLog('error', `Legacy fallback 也失败(${this.options.entry})`, diagnostics, reason)
|
||||
return {
|
||||
engine: 'query-agent',
|
||||
status: 'error',
|
||||
message: RUNTIME_FAILURE_MESSAGE,
|
||||
diagnostics
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private diagnostics(
|
||||
result: Pick<
|
||||
QueryAgentResult,
|
||||
'provider' | 'model' | 'modelCallCount' | 'toolCallCount' | 'traces'
|
||||
> &
|
||||
Partial<Pick<QueryAgentResult, 'totalMs'>>,
|
||||
startedAt: number,
|
||||
outcome: AskWechatOutcome
|
||||
): QueryAgentDiagnostics {
|
||||
return {
|
||||
entry: this.options.entry,
|
||||
provider: result.provider,
|
||||
model: result.model,
|
||||
modelCallCount: result.modelCallCount,
|
||||
toolCallCount: result.toolCallCount,
|
||||
tools: (result.traces || []).map((trace) => trace.toolName),
|
||||
totalMs: result.totalMs || Date.now() - startedAt,
|
||||
outcome
|
||||
}
|
||||
}
|
||||
|
||||
private writeLog(
|
||||
level: AskWechatLogRecord['level'],
|
||||
message: string,
|
||||
details: QueryAgentDiagnostics,
|
||||
fallbackReason?: AskWechatFallbackReason
|
||||
): void {
|
||||
// 展开成匿名对象:只传形态字段(入口 / provider / 次数 / 耗时 / 结果),不含聊天内容。
|
||||
this.options.log?.({
|
||||
level,
|
||||
message,
|
||||
details: { ...details, ...(fallbackReason ? { fallbackReason } : {}) }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 顶部统计只用**真实执行**产生的数字:三个 Query Tool 的数据来源不同
|
||||
* (`query_messages` 直读 WCDB,`search_messages` / `conversation_overview` 走检索),
|
||||
* 统计口径必须各自如实,不能套用统一的"已收录 / 读取"文案。
|
||||
*/
|
||||
export function buildAskWechatStats(
|
||||
result: Pick<
|
||||
QueryAgentResult,
|
||||
'traces' | 'evidence' | 'modelCallCount' | 'toolCallCount' | 'totalMs' | 'modelDurationsMs'
|
||||
>,
|
||||
scope: AskWechatScope | undefined,
|
||||
startedAt: number
|
||||
): AskWechatStats {
|
||||
let messageCount = 0
|
||||
let matchedCount = 0
|
||||
let overviewSourceCount = 0
|
||||
const tools: string[] = []
|
||||
for (const trace of result.traces || []) {
|
||||
tools.push(trace.toolName)
|
||||
if (trace.toolName === 'query_messages') {
|
||||
messageCount += trace.resultCount || 0
|
||||
} else {
|
||||
matchedCount += trace.evidenceCount || 0
|
||||
overviewSourceCount += trace.sourceMessageCount || 0
|
||||
}
|
||||
}
|
||||
const totalMs = result.totalMs || Date.now() - startedAt
|
||||
// 真实拆解:模型总耗时直接来自每次模型调用的测量;本地查询 = 所有 Tool 的 durationMs 之和。
|
||||
// 两者不互相推算(用 total - model 反推会把"框架开销"混进"本地查询",那是另一种谎)。
|
||||
const modelDurationsMs = (result.modelDurationsMs || []).filter((value) =>
|
||||
Number.isFinite(value)
|
||||
)
|
||||
const toolDurationsMs = (result.traces || [])
|
||||
.map((trace) => trace.durationMs)
|
||||
.filter((value) => Number.isFinite(value))
|
||||
return {
|
||||
tools,
|
||||
reads: {
|
||||
messageCount,
|
||||
matchedCount,
|
||||
overviewSourceCount,
|
||||
evidenceCount: (result.evidence || []).length
|
||||
},
|
||||
...(scope
|
||||
? { scope: { kind: scope.scope.kind, ...(scope.label ? { label: scope.label } : {}) } }
|
||||
: {}),
|
||||
modelCallCount: result.modelCallCount,
|
||||
toolCallCount: result.toolCallCount,
|
||||
totalMs,
|
||||
timings: {
|
||||
modelMs: modelDurationsMs.reduce((sum, value) => sum + value, 0),
|
||||
localQueryMs: toolDurationsMs.reduce((sum, value) => sum + value, 0),
|
||||
totalMs,
|
||||
...(modelDurationsMs.length ? { modelDurationsMs } : {}),
|
||||
...(toolDurationsMs.length ? { toolDurationsMs } : {})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -192,6 +192,61 @@ export function isReady(): boolean {
|
||||
return dbRef !== null
|
||||
}
|
||||
|
||||
/** Session 行的时间字段可能是秒,也可能是毫秒;1e11 以下按秒换算。 */
|
||||
function sessionTimeToEpochMs(value: unknown): number | null {
|
||||
const numeric = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN
|
||||
if (!Number.isFinite(numeric) || numeric <= 0) return null
|
||||
return Math.round(numeric < 1e11 ? numeric * 1000 : numeric)
|
||||
}
|
||||
|
||||
/**
|
||||
* 源数据(WCDB Session)里最新的活跃时间(epoch ms)。
|
||||
*
|
||||
* Session 列表本来就带着 `last_timestamp`,所以这是**零额外 WCDB 调用**的 freshness 信号:
|
||||
* 有了它才能区分「源数据本来就没有新消息」和「有新消息但派生索引还没追到」。
|
||||
* 只读取会话级的活跃时间戳,不读取任何消息内容。
|
||||
*/
|
||||
export function getSourceLatestActivityMs(): number | null {
|
||||
if (!dbRef) return null
|
||||
try {
|
||||
let latest = 0
|
||||
for (const session of dbRef.getWcdb4Client().getSessions()) {
|
||||
const value = sessionTimeToEpochMs(session.raw?.['last_timestamp'])
|
||||
if (value !== null && value > latest) latest = value
|
||||
}
|
||||
return latest > 0 ? latest : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 每个会话在源数据里最后的活跃时间(epoch ms),按会话 md5 索引。
|
||||
*
|
||||
* 与 `getSourceLatestActivityMs` 同源(Session 行的 `last_timestamp`),同样是**零额外
|
||||
* WCDB 调用**。增量索引 pass 用它判断「这个会话自上次索引以来有没有新消息」,
|
||||
* 从而整段跳过没有变化的会话 —— 这是增量同步名副其实的前提。
|
||||
*/
|
||||
export function getConversationActivityMs(): Map<string, number> {
|
||||
const result = new Map<string, number>()
|
||||
if (!dbRef) return result
|
||||
try {
|
||||
for (const session of dbRef.getWcdb4Client().getSessions()) {
|
||||
const username = typeof session.username === 'string' ? session.username : ''
|
||||
if (!username) continue
|
||||
const value = sessionTimeToEpochMs(session.raw?.['last_timestamp'])
|
||||
if (value === null) continue
|
||||
const md5 = dbRef.md5(username)
|
||||
if (!md5) continue
|
||||
const existing = result.get(md5)
|
||||
if (existing === undefined || value > existing) result.set(md5, value)
|
||||
}
|
||||
} catch {
|
||||
return result
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export function listContacts(filter?: string): FormattedContact[] {
|
||||
if (!dbRef) return []
|
||||
|
||||
@@ -700,6 +755,35 @@ export async function getGroupMemberIdsAsync(
|
||||
return memberIds ? { roomId, memberIds } : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Evidence sender enrichment 专用:只解析**请求到的** wxid 的显示名。
|
||||
*
|
||||
* **不**走 `getGroupSnapshotAsync` —— 后者会 materialize 整群成员并 hydrate 头像,
|
||||
* 为拿 1~N 个名字付整群成本。返回结构故意与 `GroupSnapshot['members']` 一致,
|
||||
* 这样调用方可以复用同一套显示名优先级规则,不会把「张三」退化成「wxid_xxx」。
|
||||
* `avatar` 恒为 `''`:头像若将来需要,走 lazy UI 路径,不进入 Query Tool 成本。
|
||||
*/
|
||||
export async function getGroupMemberNamesAsync(
|
||||
userMd5: string,
|
||||
wxids: string[]
|
||||
): Promise<GroupSnapshot['members']> {
|
||||
if (!dbRef) return []
|
||||
const requested = Array.from(new Set((wxids || []).filter(Boolean)))
|
||||
if (requested.length === 0) return []
|
||||
const wcdb4Client = dbRef.getWcdb4Client()
|
||||
const roomId = wcdb4Client.getUsernameByMd5(userMd5)
|
||||
if (!roomId || !roomId.endsWith('@chatroom')) return []
|
||||
const members = await wcdb4Client.getGroupMemberNamesAsync(roomId, requested)
|
||||
return members.map((member) => ({
|
||||
wxid: member.m_nsUsrName,
|
||||
nickname: member.nickname || '',
|
||||
groupNickname: member.groupNickname || '',
|
||||
wechatNickname: member.wechatNickname || '',
|
||||
remark: member.remark || '',
|
||||
avatar: member.m_nsHeadImgUrl || ''
|
||||
}))
|
||||
}
|
||||
|
||||
export function isGroupMemberIdsBatchAvailable(): boolean {
|
||||
return Boolean(dbRef?.getWcdb4Client().isGroupMemberIdsBatchAvailable())
|
||||
}
|
||||
|
||||
@@ -2,12 +2,128 @@ import { listContactsAsync, listMessagesAsync, isReady, type FormattedContact, t
|
||||
import { resolveContact } from './contact-resolution-service'
|
||||
import type { KnowledgeSearchService } from '../knowledge/knowledge-search-service'
|
||||
import { inferAiSearchTimeRange } from '../../shared/ai-search'
|
||||
import type { QueryCapabilitiesResponse, QueryMessage, QueryMessageType, QueryTimeRange, ResolvedTimeRange, QueryMessagesRequest, SearchMessagesRequest, MessageContextRequest, ConversationOverviewRequest } from '../../shared/local-query-api'
|
||||
import { KNOWLEDGE_FRESHNESS_TOLERANCE_MS } from '../../shared/knowledge'
|
||||
import type {
|
||||
QueryCapabilitiesResponse,
|
||||
QueryCorpusScope,
|
||||
QueryEvidenceItem,
|
||||
QueryMessage,
|
||||
QueryMessageType,
|
||||
QueryTimeRange,
|
||||
ResolvedCorpusScope,
|
||||
ResolvedTimeRange,
|
||||
QueryIndexCoverage,
|
||||
QuerySearchTimings,
|
||||
QueryMessagesRequest,
|
||||
SearchMessagesRequest,
|
||||
MessageContextRequest,
|
||||
ConversationOverviewRequest
|
||||
} from '../../shared/local-query-api'
|
||||
// messageRef 编解码是 main 与 renderer 共用的契约,只定义一次(`src/shared/local-query-api.ts`):
|
||||
// 两侧各写一份 base64url 实现会悄悄漂移,那会让「跳转到原聊天」偶发失效。
|
||||
import {
|
||||
encodeMessageRef as toRef,
|
||||
decodeMessageRef as fromRef,
|
||||
normalizeMessageIdentity
|
||||
} from '../../shared/local-query-api'
|
||||
|
||||
const LIMIT_MAX = 200
|
||||
const CONTEXT_MAX = 50
|
||||
/** 会话概览直读源数据时的上限(与派生索引的会话概览同量级)。 */
|
||||
const OVERVIEW_SOURCE_CAP = 2000
|
||||
/** 会话概览最多挑选多少条代表证据(与派生索引的候选上限一致)。 */
|
||||
const OVERVIEW_EVIDENCE_TARGET = 60
|
||||
const OVERVIEW_CHUNK_GAP_MS = 2 * 60 * 60 * 1000
|
||||
const OVERVIEW_CHUNK_MAX_MESSAGES = 24
|
||||
const kinds: QueryMessageType[] = ['text', 'image', 'voice', 'video', 'file', 'link', 'sticker', 'system', 'other']
|
||||
|
||||
/**
|
||||
* 查询触发追赶同步后最多等待多久(`QUERY_FRESHNESS_WAIT_BUDGET`)。
|
||||
*
|
||||
* 一次完整 pass 的耗时以分钟计,远超任何交互预算。所以这个预算只用来兜住「已经很接近追平」
|
||||
* 的情况:追不上就按当前覆盖如实回答并让后台继续追,而不是把查询卡在索引上。
|
||||
*/
|
||||
const QUERY_FRESHNESS_WAIT_BUDGET_MS = 2000
|
||||
|
||||
/**
|
||||
* 两次由查询触发的追赶之间的最小间隔,避免每个 Query 都重跑一遍索引。
|
||||
*/
|
||||
const QUERY_CATCH_UP_MIN_INTERVAL_MS = 30 * 1000
|
||||
|
||||
/**
|
||||
* 值得为它跑一遍索引的最小落后量(下限)。
|
||||
*
|
||||
* 追赶一遍的成本以分钟计,因此几秒钟/一两分钟的落后并不值得触发。真正的门槛是
|
||||
* `max(这个下限, 上一遍实际耗时)` —— 见 `LocalQueryApiService.ensureFreshness`。
|
||||
* 这样在"源数据一直在长"的情况下会自然收敛:一遍跑完后剩下的落后量约等于这一遍的耗时,
|
||||
* 于是不会立刻再触发一遍(否则会变成永不停止的连续索引)。
|
||||
*/
|
||||
const QUERY_CATCH_UP_MIN_LAG_MS = 2 * 60 * 1000
|
||||
|
||||
/**
|
||||
* 请求的时间范围是否已经被派生索引覆盖。
|
||||
*
|
||||
* 需要覆盖的真实边界是 `min(requestedEnd, sourceLatestAt)`:
|
||||
* - 请求范围早于源数据最新时间 → 必须覆盖到 requestedEnd;
|
||||
* - 请求范围延伸到"现在" → 覆盖到源数据最新就已经完整(其后本来没有内容)。
|
||||
*
|
||||
* freshness 与 coverage 共用这**一处**判据,避免两套口径漂移。
|
||||
*/
|
||||
function indexCovers(indexLatestAt: number | null, requestedEnd: number, sourceLatestAt: number | null): boolean {
|
||||
if (indexLatestAt === null) return false
|
||||
const requiredEnd = sourceLatestAt === null ? requestedEnd : Math.min(requestedEnd, sourceLatestAt)
|
||||
return indexLatestAt + KNOWLEDGE_FRESHNESS_TOLERANCE_MS >= requiredEnd
|
||||
}
|
||||
|
||||
/**
|
||||
* `ResolvedTimeRange` 用的是 **epoch 秒**(Local Query API contract),
|
||||
* 而 freshness 口径(indexLatestAt / sourceLatestAt)是 **epoch 毫秒**。
|
||||
* 这里统一到毫秒,避免混单位把"落后"误判成"已覆盖"。
|
||||
*/
|
||||
function rangeEndMs(range: ResolvedTimeRange, fallbackNowMs: number): number {
|
||||
return range.endTime === undefined ? fallbackNowMs : range.endTime * 1000
|
||||
}
|
||||
|
||||
/** 本地时间(`MM-DD HH:mm`);只用于给模型一句可引用的人话,不参与任何判断。 */
|
||||
function formatLocalMinute(ms: number): string {
|
||||
const date = new Date(ms)
|
||||
const pad = (value: number): string => String(value).padStart(2, '0')
|
||||
return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 索引覆盖结论:模型直接引用,不要自己换算时间、也不要输出 epoch 数字。
|
||||
* 落后时必须把"这段时间暂时无法确认"写进结论句,避免被读成"整段时间都没有"。
|
||||
*/
|
||||
function buildIndexCoverage(
|
||||
indexLatestAt: number | null,
|
||||
sourceLatestAt: number | null,
|
||||
covered: boolean
|
||||
): QueryIndexCoverage | undefined {
|
||||
if (indexLatestAt === null) return undefined
|
||||
const indexLabel = formatLocalMinute(indexLatestAt)
|
||||
return {
|
||||
covered,
|
||||
indexLatestAtLabel: indexLabel,
|
||||
...(sourceLatestAt !== null ? { sourceLatestAtLabel: formatLocalMinute(sourceLatestAt) } : {}),
|
||||
summary: covered
|
||||
? `可搜索索引已覆盖所问的时间范围(索引最新到 ${indexLabel})。`
|
||||
: `可搜索索引只更新到 ${indexLabel},这之后的聊天还没进索引,这段时间是否聊过暂时无法确认。`
|
||||
}
|
||||
}
|
||||
|
||||
const KIND_LABELS: Record<QueryMessageType, string> = {
|
||||
text: '文本',
|
||||
image: '图片',
|
||||
voice: '语音',
|
||||
video: '视频',
|
||||
file: '文件',
|
||||
link: '链接',
|
||||
sticker: '表情',
|
||||
system: '系统消息',
|
||||
other: '消息'
|
||||
}
|
||||
|
||||
function kindOf(message: FormattedMessage): QueryMessageType {
|
||||
if (message.contentData?.type === 'system') return 'system'
|
||||
if (message.exportMediaType) return message.exportMediaType
|
||||
@@ -21,32 +137,6 @@ function kindOf(message: FormattedMessage): QueryMessageType {
|
||||
if (message.content?.trim()) return 'text'
|
||||
return 'other'
|
||||
}
|
||||
interface CanonicalMessageIdentity {
|
||||
conversationId: string
|
||||
messageId: string
|
||||
}
|
||||
|
||||
function normalizeMessageIdentity(conversationId: string, messageId: string): CanonicalMessageIdentity | null {
|
||||
const normalizedConversationId = conversationId.trim()
|
||||
const normalizedMessageId = messageId.trim().replace(/^local:/, '')
|
||||
if (!normalizedConversationId || !normalizedMessageId) return null
|
||||
return { conversationId: normalizedConversationId, messageId: normalizedMessageId }
|
||||
}
|
||||
|
||||
function toRef(conversationId: string, messageId: string): string {
|
||||
const identity = normalizeMessageIdentity(conversationId, messageId)
|
||||
if (!identity) throw new Error('消息引用无效')
|
||||
return Buffer.from(JSON.stringify({ c: identity.conversationId, m: identity.messageId }), 'utf8').toString('base64url')
|
||||
}
|
||||
|
||||
function fromRef(value: string): CanonicalMessageIdentity | null {
|
||||
try {
|
||||
const parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'))
|
||||
return typeof parsed?.c === 'string' && typeof parsed?.m === 'string'
|
||||
? normalizeMessageIdentity(parsed.c, parsed.m)
|
||||
: null
|
||||
} catch { return null }
|
||||
}
|
||||
function contactView(contact: FormattedContact) { return { displayName: contact.m_nsNickName || contact.m_nsUsrName, type: contact.type } as const }
|
||||
function resolvedTimeRange(input: QueryTimeRange, now = new Date()): ResolvedTimeRange {
|
||||
if (input.kind === 'absolute') {
|
||||
@@ -76,54 +166,490 @@ function toQueryMessage(conversationId: string, message: FormattedMessage, targe
|
||||
return { messageRef: toRef(conversationId, message.id), timestamp: (message.createTime || 0) * 1000, datetime: message.datetime, sender: message.isSender ? '我' : (message.name || target.m_nsNickName), direction: message.isSender ? 'to_target' : 'from_target', messageType: kind, sourceKind: kind, ...(attachment ? { attachment } : {}), ...(text ? { text } : {}) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 单条证据的展示形态:群消息必须带**群名 + 发送者**,否则模型无法回答"谁聊过"。
|
||||
* 不含 wxid / md5 / DB id;messageRef 保持 opaque。
|
||||
*/
|
||||
function toEvidenceItem(contact: FormattedContact, message: FormattedMessage): QueryEvidenceItem {
|
||||
const view = toQueryMessage(contact.md5, message, contact)
|
||||
const name = contactView(contact).displayName
|
||||
return {
|
||||
messageRef: view.messageRef,
|
||||
timestamp: view.timestamp,
|
||||
sender: view.sender,
|
||||
sourceKind: view.sourceKind,
|
||||
text: view.text || `[${KIND_LABELS[view.messageType]}]`,
|
||||
conversationName: name,
|
||||
conversationType: contact.type
|
||||
}
|
||||
}
|
||||
|
||||
/** 语料边界的解析结果。 */
|
||||
interface ResolvedCorpus {
|
||||
/** undefined = 不限会话(全部可读会话)。 */
|
||||
conversationIds?: string[]
|
||||
scope: ResolvedCorpusScope
|
||||
/** contact / current 命中的会话。 */
|
||||
contact?: FormattedContact
|
||||
error?: { status: string; [key: string]: unknown }
|
||||
}
|
||||
|
||||
function describeScope(scope: ResolvedCorpusScope): string {
|
||||
if (scope.kind === 'all') return '所有聊天记录'
|
||||
if (scope.kind === 'groups') return '群聊专属'
|
||||
return `${scope.kind === 'contact' ? '单聊专属' : '当前会话'}:${scope.displayName || '未知会话'}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 语料边界违规 → 返回**可修正**的 invalid_tool_arguments(Runtime 会重开该 Tool 让模型改)。
|
||||
* 这是结构性约束:模型无法用 prompt 绕过。
|
||||
*/
|
||||
function outsideScopeError(scope: ResolvedCorpusScope, actual: string): { status: string; [key: string]: unknown } {
|
||||
return {
|
||||
status: 'invalid_tool_arguments',
|
||||
field: 'target',
|
||||
constraint: 'target_outside_scope',
|
||||
expected: describeScope(scope),
|
||||
actual,
|
||||
hint: 'target 必须落在应用当前的搜索范围内。需要查其他会话时,请让用户切换搜索范围;不要自行扩大范围。'
|
||||
}
|
||||
}
|
||||
|
||||
export class LocalQueryApiService {
|
||||
constructor(private readonly knowledge?: KnowledgeSearchService, private readonly nowProvider: () => Date = () => new Date()) {}
|
||||
capabilities(): QueryCapabilitiesResponse {
|
||||
return { version: 1, tools: { query_messages: { operation: '读取指定联系人的确定性消息', directions: ['any', 'from_target', 'to_target'], messageTypes: kinds, timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX }, search_messages: { operation: '受限 Knowledge 关键词检索', timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX }, message_context: { operation: '读取消息前后文', timeRanges: ['all'], limitMax: CONTEXT_MAX }, conversation_overview: { operation: '按会话时间片提取概览证据', timeRanges: ['all', 'today', 'yesterday', 'this_week', 'last_7_days', 'this_month', 'previous_month', 'this_year', 'previous_year', 'absolute'], limitMax: LIMIT_MAX } } }
|
||||
}
|
||||
private async resolve(target: { query: string }) {
|
||||
const contacts = await listContactsAsync()
|
||||
const result = resolveContact(target.query, contacts)
|
||||
return { contacts, result }
|
||||
|
||||
/**
|
||||
* 解析语料边界。`scope` 由调用方(UI / Host)提供;省略 = 不限。
|
||||
* 这里只做**确定性**展开(群列表 / 会话身份校验),不做任何语义推断。
|
||||
*/
|
||||
private async resolveCorpus(scope: QueryCorpusScope | undefined, contacts: FormattedContact[]): Promise<ResolvedCorpus> {
|
||||
if (!scope || scope.kind === 'all') {
|
||||
return { scope: { kind: 'all', conversationCount: contacts.length } }
|
||||
}
|
||||
if (scope.kind === 'groups') {
|
||||
const ids = contacts.filter((contact) => contact.type === 'group').map((contact) => contact.md5)
|
||||
return { conversationIds: ids, scope: { kind: 'groups', conversationCount: ids.length } }
|
||||
}
|
||||
const contact = contacts.find((item) => item.md5 === scope.conversationId)
|
||||
if (!contact) {
|
||||
return { scope: { kind: scope.kind, conversationCount: 0 }, error: { status: 'scope_conversation_not_found', kind: scope.kind } }
|
||||
}
|
||||
if (scope.kind === 'contact' && contact.type !== 'user') {
|
||||
return { scope: { kind: scope.kind, conversationCount: 0 }, error: { status: 'scope_contact_requires_direct', actual: contact.type } }
|
||||
}
|
||||
return {
|
||||
conversationIds: [contact.md5],
|
||||
contact,
|
||||
scope: { kind: scope.kind, conversationCount: 1, displayName: contactView(contact).displayName, conversationType: contact.type }
|
||||
}
|
||||
}
|
||||
|
||||
async messages(request: QueryMessagesRequest) {
|
||||
if (!request?.target?.query?.trim() || !request.timeRange || !['any', 'from_target', 'to_target'].includes(request.direction || 'any') || (request.messageTypes || []).some((type) => !kinds.includes(type))) return { status: 'invalid_request' as const }
|
||||
if (!request?.timeRange || !['any', 'from_target', 'to_target'].includes(request.direction || 'any') || (request.messageTypes || []).some((type) => !kinds.includes(type))) return { status: 'invalid_request' as const }
|
||||
if (!isReady()) return { status: 'knowledge_unavailable' as const }
|
||||
const { contacts, result } = await this.resolve(request.target)
|
||||
if (!result.matched || !result.conversationId) return { status: result.ambiguous ? 'ambiguous_contact' as const : 'contact_not_found' as const, candidates: result.candidates.map((candidate) => ({ displayName: candidate.displayName, type: contacts.find((c) => c.md5 === candidate.conversationId)?.type || 'user' })) }
|
||||
const contact = contacts.find((c) => c.md5 === result.conversationId)!; if (contact.type === 'group' && request.direction && request.direction !== 'any') return { status: 'unsupported_query' as const }; const range = resolvedTimeRange(request.timeRange, this.nowProvider())
|
||||
const contacts = await listContactsAsync()
|
||||
const corpus = await this.resolveCorpus(request.scope, contacts)
|
||||
if (corpus.error) return corpus.error as { status: string }
|
||||
const targetQuery = request.target?.query?.trim()
|
||||
let contact: FormattedContact | undefined
|
||||
if (targetQuery) {
|
||||
const result = resolveContact(targetQuery, contacts)
|
||||
if (!result.matched || !result.conversationId) return { status: result.ambiguous ? 'ambiguous_contact' as const : 'contact_not_found' as const, candidates: result.candidates.map((candidate) => ({ displayName: candidate.displayName, type: contacts.find((c) => c.md5 === candidate.conversationId)?.type || 'user' })) }
|
||||
contact = contacts.find((c) => c.md5 === result.conversationId)!
|
||||
if (corpus.conversationIds && !corpus.conversationIds.includes(contact.md5)) {
|
||||
return outsideScopeError(corpus.scope, contactView(contact).displayName) as { status: string }
|
||||
}
|
||||
} else if (corpus.contact) {
|
||||
// 省略 target:范围恰好只有一个会话(单聊专属 / 当前会话)时直接查它,避免让模型重新拼会话名。
|
||||
contact = corpus.contact
|
||||
} else if (corpus.conversationIds && corpus.conversationIds.length === 1) {
|
||||
contact = contacts.find((c) => c.md5 === corpus.conversationIds![0])
|
||||
}
|
||||
if (!contact) {
|
||||
return {
|
||||
status: 'invalid_tool_arguments',
|
||||
field: 'target',
|
||||
constraint: 'target_required_for_scope',
|
||||
expected: describeScope(corpus.scope),
|
||||
actual: '省略 target',
|
||||
hint: '当前搜索范围包含多个会话。精确读取消息必须指定 target(必须在该范围内),或改用 search_messages 做跨会话检索。'
|
||||
}
|
||||
}
|
||||
if (contact.type === 'group' && request.direction && request.direction !== 'any') return { status: 'unsupported_query' as const }; const range = resolvedTimeRange(request.timeRange, this.nowProvider())
|
||||
const raw = await listMessagesAsync(contact.md5, range.startTime, range.endTime)
|
||||
const direction = request.direction || 'any'; const allowed = new Set(request.messageTypes || kinds)
|
||||
const filtered = raw.filter((message) => !(request.excludeSystem !== false && kindOf(message) === 'system')).filter((message) => allowed.has(kindOf(message))).filter((message) => direction === 'any' || (direction === 'to_target' ? message.isSender : !message.isSender)).sort((a, b) => ((a.createTime || 0) - (b.createTime || 0)) * ((request.order || 'asc') === 'asc' ? 1 : -1)).slice(0, Math.min(LIMIT_MAX, Math.max(1, request.limit || 20)))
|
||||
return { status: 'completed' as const, target: contactView(contact), query: { direction, messageTypes: request.messageTypes || [], order: request.order || 'asc', limit: Math.min(LIMIT_MAX, Math.max(1, request.limit || 20)), excludeSystem: request.excludeSystem !== false, resolvedTimeRange: range }, coverage: { state: 'complete' as const }, returnedCount: filtered.length, messages: filtered.map((message) => toQueryMessage(contact.md5, message, contact)) }
|
||||
return { status: 'completed' as const, target: contactView(contact), query: { direction, messageTypes: request.messageTypes || [], order: request.order || 'asc', limit: Math.min(LIMIT_MAX, Math.max(1, request.limit || 20)), excludeSystem: request.excludeSystem !== false, resolvedTimeRange: range }, coverage: { state: 'complete' as const }, returnedCount: filtered.length, messages: filtered.map((message) => toQueryMessage(contact.md5, message, contact)), scope: corpus.scope }
|
||||
}
|
||||
async search(request: SearchMessagesRequest) {
|
||||
if (!request?.target?.query?.trim() || !request.timeRange || typeof request.query !== 'string' || !request.query.trim() || (request.variants || []).some((value) => typeof value !== 'string')) return { status: 'invalid_request' as const }
|
||||
const { contacts, result } = await this.resolve(request.target)
|
||||
if (!result.matched || !result.conversationId) return { status: result.ambiguous ? 'ambiguous_contact' as const : 'contact_not_found' as const, candidates: result.candidates.map((candidate) => ({ displayName: candidate.displayName, type: contacts.find((c) => c.md5 === candidate.conversationId)?.type || 'user' })) }
|
||||
const requestStartedAt = Date.now()
|
||||
if (!request?.timeRange || typeof request.query !== 'string' || !request.query.trim() || (request.variants || []).some((value) => typeof value !== 'string')) return { status: 'invalid_request' as const }
|
||||
// 真实耗时分解:每一段都用 Date.now() 实测,不做任何推断。
|
||||
const scopeStartedAt = Date.now()
|
||||
const contacts = await listContactsAsync()
|
||||
const corpus = await this.resolveCorpus(request.scope, contacts)
|
||||
if (corpus.error) return corpus.error as { status: string }
|
||||
let conversationIds = corpus.conversationIds
|
||||
let targetView: { displayName: string; type: 'user' | 'group' } | undefined
|
||||
const targetQuery = request.target?.query?.trim()
|
||||
if (targetQuery) {
|
||||
const resolved = resolveContact(targetQuery, contacts)
|
||||
if (!resolved.matched || !resolved.conversationId) {
|
||||
return { status: resolved.ambiguous ? 'ambiguous_contact' as const : 'contact_not_found' as const, candidates: resolved.candidates.map((candidate) => ({ displayName: candidate.displayName, type: contacts.find((c) => c.md5 === candidate.conversationId)?.type || 'user' })) }
|
||||
}
|
||||
const target = contacts.find((c) => c.md5 === resolved.conversationId)!
|
||||
if (corpus.conversationIds && !corpus.conversationIds.includes(target.md5)) {
|
||||
return outsideScopeError(corpus.scope, contactView(target).displayName) as { status: string }
|
||||
}
|
||||
conversationIds = [target.md5]
|
||||
targetView = contactView(target)
|
||||
} else if (corpus.conversationIds && corpus.conversationIds.length === 0) {
|
||||
// 范围内没有任何会话(例如没有任何群聊):明确返回空,而不是悄悄退化成全局搜索。
|
||||
return { status: 'completed' as const, coverage: { state: 'unknown' as const }, probeCount: 0, evidenceCount: 0, evidence: [], scope: corpus.scope }
|
||||
}
|
||||
const scopeMs = Date.now() - scopeStartedAt
|
||||
if (!this.knowledge) return { status: 'knowledge_unavailable' as const }
|
||||
const contact = contacts.find((c) => c.md5 === result.conversationId)!; const range = resolvedTimeRange(request.timeRange, this.nowProvider()); const probes = [request.query, ...(request.variants || [])]
|
||||
const range = resolvedTimeRange(request.timeRange, this.nowProvider()); const probes = [request.query, ...(request.variants || [])]
|
||||
if (probes.length > 5) return { status: 'invalid_request' as const }
|
||||
const all = new Map<string, any>(); let coverage: 'complete' | 'partial' | 'unknown' = 'unknown'
|
||||
for (const probe of probes) { const found = await this.knowledge.search({ text: probe, terms: [probe], conversationIds: [contact.md5], startTime: range.startTime, endTime: range.endTime, limit: Math.min(LIMIT_MAX, Math.max(1, request.limit || 20)) }); coverage = found.state === 'ready' ? 'complete' : found.evidence.length ? 'partial' : 'unknown'; for (const item of found.evidence) all.set(`${item.conversationId}:${item.messageId}`, { messageRef: toRef(item.conversationId, item.messageId), messageId: item.messageId, timestamp: item.timestamp, sender: item.sender, sourceKind: item.sourceKind, text: item.text }) }
|
||||
return { status: 'completed' as const, target: contactView(contact), resolvedTimeRange: range, coverage: { state: coverage }, probeCount: probes.length, evidenceCount: all.size, evidence: Array.from(all.values()).map(({ messageId: _messageId, ...item }) => item).slice(0, request.limit || 20) }
|
||||
const contactByMd5 = new Map(contacts.map((contact) => [contact.md5, contact]))
|
||||
const limit = Math.min(LIMIT_MAX, Math.max(1, request.limit || 20))
|
||||
// 一次查询内多个 probe 共用同一个 retrieval session:Knowledge 会按它缓存
|
||||
// "群会话 → 成员昵称" 的解析结果,否则每个 probe 都要重读一遍群成员快照,
|
||||
// 跨会话检索会被放大成 N 倍。
|
||||
const retrievalSessionId = `query-${this.nowProvider().getTime()}-${Math.random().toString(36).slice(2, 8)}`
|
||||
|
||||
// Freshness:请求的时间范围越过索引覆盖时,先请求既有增量通道去追一次;
|
||||
// 这属于 Engine/Host 的确定性处理,**不增加 LLM 往返**。
|
||||
//
|
||||
// 整段交互检索期间必须让后台索引让路:追赶同步会遍历上千个会话,
|
||||
// 否则本次查询会和它抢 Worker 与 WCDB,被拖成几十秒。
|
||||
this.knowledge.beginInteractiveQuery()
|
||||
const probeMs: number[] = []
|
||||
let mergeMs = 0
|
||||
let enrichmentMs = 0
|
||||
let knowledgeTiming: NonNullable<QuerySearchTimings['knowledge']> | undefined
|
||||
let found: Awaited<ReturnType<LocalQueryApiService['probe']>>
|
||||
let freshness: { resynced: boolean; catchUp: 'none' | 'reused' | 'skipped' | 'completed' | 'pending' }
|
||||
let freshnessMs = 0
|
||||
try {
|
||||
found = await this.probe(probes, conversationIds, range, limit, contactByMd5, retrievalSessionId)
|
||||
probeMs.push(...found.probeMs)
|
||||
mergeMs = found.mergeMs
|
||||
enrichmentMs = found.enrichmentMs
|
||||
knowledgeTiming = found.knowledge
|
||||
const requestedEnd = rangeEndMs(range, this.nowProvider().getTime())
|
||||
const freshnessStartedAt = Date.now()
|
||||
freshness = await this.ensureFreshness(found, requestedEnd)
|
||||
freshnessMs = Date.now() - freshnessStartedAt
|
||||
// 触发过追赶就必须用(可能已更新的)索引重新检索,不能拿同步前的结果回答。
|
||||
if (freshness.resynced) {
|
||||
const reProbe = await this.probe(probes, conversationIds, range, limit, contactByMd5, retrievalSessionId)
|
||||
probeMs.push(...reProbe.probeMs)
|
||||
mergeMs += reProbe.mergeMs
|
||||
enrichmentMs += reProbe.enrichmentMs
|
||||
found = reProbe
|
||||
}
|
||||
} finally {
|
||||
this.knowledge.endInteractiveQuery()
|
||||
}
|
||||
const requestedEnd = rangeEndMs(range, this.nowProvider().getTime())
|
||||
|
||||
const covered = indexCovers(found.indexLatestAt, requestedEnd, found.sourceLatestAt)
|
||||
const indexCoverage = buildIndexCoverage(found.indexLatestAt, found.sourceLatestAt, covered)
|
||||
const timings: QuerySearchTimings = {
|
||||
totalMs: Date.now() - requestStartedAt,
|
||||
scopeMs,
|
||||
freshnessMs,
|
||||
probeMs,
|
||||
mergeMs,
|
||||
enrichmentMs,
|
||||
...(knowledgeTiming ? { knowledge: knowledgeTiming } : {})
|
||||
}
|
||||
return {
|
||||
status: 'completed' as const,
|
||||
...(targetView ? { target: targetView } : {}),
|
||||
resolvedTimeRange: range,
|
||||
coverage: { state: this.searchCoverage(found, requestedEnd) },
|
||||
probeCount: probes.length,
|
||||
evidenceCount: found.evidence.size,
|
||||
evidence: Array.from(found.evidence.values()).slice(0, limit),
|
||||
scope: corpus.scope,
|
||||
indexLatestAt: found.indexLatestAt,
|
||||
sourceLatestAt: found.sourceLatestAt,
|
||||
freshness: { catchUp: freshness.catchUp },
|
||||
...(indexCoverage ? { indexCoverage } : {}),
|
||||
timings
|
||||
}
|
||||
}
|
||||
|
||||
/** 逐 probe 检索并合并去重;同时记录派生索引的覆盖口径与真实耗时分解。 */
|
||||
private async probe(
|
||||
probes: string[],
|
||||
conversationIds: string[] | undefined,
|
||||
range: ResolvedTimeRange,
|
||||
limit: number,
|
||||
contactByMd5: Map<string, FormattedContact>,
|
||||
retrievalSessionId: string
|
||||
): Promise<{
|
||||
evidence: Map<string, QueryEvidenceItem>
|
||||
indexLatestAt: number | null
|
||||
sourceLatestAt: number | null
|
||||
derivedReady: boolean
|
||||
probeMs: number[]
|
||||
mergeMs: number
|
||||
enrichmentMs: number
|
||||
knowledge?: NonNullable<QuerySearchTimings['knowledge']>
|
||||
}> {
|
||||
let indexLatestAt: number | null = null
|
||||
let sourceLatestAt: number | null = null
|
||||
let derivedReady = false
|
||||
let enrichmentMs = 0
|
||||
const probeMs: number[] = []
|
||||
const knowledge = {
|
||||
shortTermSearchMs: 0,
|
||||
ftsMs: 0,
|
||||
messageLoadMs: 0,
|
||||
statusMs: 0,
|
||||
voiceCoverageMs: 0,
|
||||
workerExecutionMs: 0
|
||||
}
|
||||
// 先逐 probe 收证据,再统一合并:这样「probe 检索」与「合并去重」的耗时是分开测量的,
|
||||
// 不会把合并成本摊到最后一个 probe 上(诊断时最容易被误读的地方)。
|
||||
const perProbe: Array<Array<[string, QueryEvidenceItem]>> = []
|
||||
for (const probe of probes) {
|
||||
const probeStartedAt = Date.now()
|
||||
const found = await this.knowledge!.search({
|
||||
text: probe,
|
||||
terms: [probe],
|
||||
conversationIds,
|
||||
startTime: range.startTime,
|
||||
endTime: range.endTime,
|
||||
limit,
|
||||
retrievalSessionId
|
||||
})
|
||||
probeMs.push(Date.now() - probeStartedAt)
|
||||
if (found.state === 'ready') derivedReady = true
|
||||
if (typeof found.indexLatestAt === 'number' && (indexLatestAt === null || found.indexLatestAt > indexLatestAt)) indexLatestAt = found.indexLatestAt
|
||||
if (typeof found.sourceLatestAt === 'number' && (sourceLatestAt === null || found.sourceLatestAt > sourceLatestAt)) sourceLatestAt = found.sourceLatestAt
|
||||
const measured = found.timings
|
||||
if (measured) {
|
||||
knowledge.shortTermSearchMs += measured.shortTermSearchMs || 0
|
||||
knowledge.ftsMs += measured.ftsMs || 0
|
||||
knowledge.messageLoadMs += measured.messageLoadMs || 0
|
||||
knowledge.statusMs += measured.statusMs || 0
|
||||
knowledge.voiceCoverageMs += measured.voiceCoverageMs || 0
|
||||
knowledge.workerExecutionMs += measured.workerExecutionMs || measured.totalMs || 0
|
||||
enrichmentMs += measured.senderEnrichmentMs || 0
|
||||
}
|
||||
perProbe.push(
|
||||
found.evidence.map((item) => {
|
||||
const owner = contactByMd5.get(item.conversationId)
|
||||
return [
|
||||
`${item.conversationId}:${item.messageId}`,
|
||||
{
|
||||
messageRef: toRef(item.conversationId, item.messageId),
|
||||
timestamp: item.timestamp,
|
||||
sender: item.sender,
|
||||
sourceKind: item.sourceKind,
|
||||
text: item.text,
|
||||
conversationName: owner ? contactView(owner).displayName : undefined,
|
||||
conversationType: owner?.type
|
||||
} satisfies QueryEvidenceItem
|
||||
] as [string, QueryEvidenceItem]
|
||||
})
|
||||
)
|
||||
}
|
||||
const mergeStartedAt = Date.now()
|
||||
const all = new Map<string, QueryEvidenceItem>()
|
||||
for (const entries of perProbe) for (const [key, item] of entries) all.set(key, item)
|
||||
const mergeMs = Date.now() - mergeStartedAt
|
||||
const hasKnowledgeTiming =
|
||||
knowledge.shortTermSearchMs > 0 ||
|
||||
knowledge.ftsMs > 0 ||
|
||||
knowledge.messageLoadMs > 0 ||
|
||||
knowledge.workerExecutionMs > 0
|
||||
return {
|
||||
evidence: all,
|
||||
indexLatestAt,
|
||||
sourceLatestAt,
|
||||
derivedReady,
|
||||
probeMs,
|
||||
mergeMs,
|
||||
enrichmentMs,
|
||||
...(hasKnowledgeTiming ? { knowledge } : {})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 索引新鲜度处理。
|
||||
*
|
||||
* 派生索引是异步的,可能停在几天前。请求范围越过索引覆盖时,**不能**直接把 0 条 Evidence
|
||||
* 当成"没有",而是请求既有增量通道去追一次,并在有界预算内等它。
|
||||
*/
|
||||
private async ensureFreshness(
|
||||
found: { indexLatestAt: number | null; sourceLatestAt: number | null; derivedReady: boolean },
|
||||
requestedEnd: number
|
||||
): Promise<{ resynced: boolean; catchUp: 'none' | 'reused' | 'skipped' | 'completed' | 'pending' }> {
|
||||
if (!this.knowledge || !found.derivedReady) return { resynced: false, catchUp: 'none' }
|
||||
if (indexCovers(found.indexLatestAt, requestedEnd, found.sourceLatestAt)) {
|
||||
return { resynced: false, catchUp: 'none' }
|
||||
}
|
||||
// 落后量是否值得再跑一遍索引:门槛同时受"上一遍实际耗时"约束,
|
||||
// 这样"源数据一直在长"时不会退化成永不停止的连续索引。
|
||||
const lag = found.sourceLatestAt !== null && found.indexLatestAt !== null ? found.sourceLatestAt - found.indexLatestAt : Number.POSITIVE_INFINITY
|
||||
const worthThreshold = Math.max(QUERY_CATCH_UP_MIN_LAG_MS, this.knowledge.lastPassDurationMs())
|
||||
if (lag <= worthThreshold) return { resynced: false, catchUp: 'skipped' }
|
||||
|
||||
const request = this.knowledge.requestCatchUp(QUERY_CATCH_UP_MIN_INTERVAL_MS)
|
||||
if (!request.triggered) {
|
||||
// 已经在跑 → 复用;刚触发过 → 节流。两种都不阻塞本次查询,后台继续追。
|
||||
return { resynced: false, catchUp: request.inProgress ? 'reused' : 'skipped' }
|
||||
}
|
||||
const completed = await this.knowledge.waitForIndexingComplete(QUERY_FRESHNESS_WAIT_BUDGET_MS)
|
||||
return { resynced: true, catchUp: completed ? 'completed' : 'pending' }
|
||||
}
|
||||
|
||||
/**
|
||||
* 覆盖度。
|
||||
*
|
||||
* 只有「派生索引可用 + 请求范围被索引完整覆盖」才是 `complete`。
|
||||
* `complete` 是 0 结果时允许说"没有找到"的唯一前提;索引落后时必须 `partial`。
|
||||
*/
|
||||
private searchCoverage(
|
||||
found: { indexLatestAt: number | null; sourceLatestAt: number | null; derivedReady: boolean; evidence: Map<string, QueryEvidenceItem> },
|
||||
requestedEnd: number
|
||||
): 'complete' | 'partial' | 'unknown' {
|
||||
if (!found.derivedReady) {
|
||||
// 派生索引不可用(未建立 / 直读源数据的 fallback):有证据也只能算 partial。
|
||||
return found.evidence.size ? 'partial' : 'unknown'
|
||||
}
|
||||
// 索引可用但覆盖口径缺失时不能宣称完整;此时按 partial 处理(宁可保守)。
|
||||
if (found.indexLatestAt === null) return 'partial'
|
||||
return indexCovers(found.indexLatestAt, requestedEnd, found.sourceLatestAt) ? 'complete' : 'partial'
|
||||
}
|
||||
async context(request: MessageContextRequest) {
|
||||
const ref = fromRef(request.messageRef); if (!ref) return { status: 'invalid_request' as const }
|
||||
if (request.scope && request.scope.kind !== 'all') {
|
||||
const contacts = await listContactsAsync()
|
||||
const corpus = await this.resolveCorpus(request.scope, contacts)
|
||||
if (corpus.error) return corpus.error as { status: string }
|
||||
if (corpus.conversationIds && !corpus.conversationIds.includes(ref.conversationId)) {
|
||||
return outsideScopeError(corpus.scope, '其他会话的消息') as { status: string }
|
||||
}
|
||||
}
|
||||
const before = Math.min(CONTEXT_MAX, Math.max(0, request.before ?? 10)); const after = Math.min(CONTEXT_MAX, Math.max(0, request.after ?? 10)); const messages = await listMessagesAsync(ref.conversationId); const index = messages.findIndex((message) => normalizeMessageIdentity(ref.conversationId, message.id)?.messageId === ref.messageId); if (index < 0) return { status: 'contact_not_found' as const }
|
||||
const contact = (await listContactsAsync()).find((item) => item.md5 === ref.conversationId); if (!contact) return { status: 'contact_not_found' as const }; const map = (message: FormattedMessage) => toQueryMessage(ref.conversationId, message, contact)
|
||||
return { status: 'completed' as const, anchor: map(messages[index]), before: messages.slice(Math.max(0, index - before), index).map(map), after: messages.slice(index + 1, index + 1 + after).map(map) }
|
||||
}
|
||||
/**
|
||||
* 会话概览。
|
||||
*
|
||||
* **事实来源是 WCDB(源数据),不是派生 Knowledge 索引**:索引是异步派生的、可能滞后,
|
||||
* 把"索引里 0 行"当成"完整范围内没有"会产生高置信度的错误否定。这里改为直读源数据
|
||||
* 并显式区分 complete / partial。
|
||||
*/
|
||||
async overview(request: ConversationOverviewRequest) {
|
||||
if (!request?.target?.query?.trim() || !request.timeRange) return { status: 'invalid_request' as const }
|
||||
const { contacts, result } = await this.resolve(request.target); if (!result.matched || !result.conversationId) return { status: result.ambiguous ? 'ambiguous_contact' as const : 'contact_not_found' as const, candidates: result.candidates.map((candidate) => ({ displayName: candidate.displayName, type: contacts.find((c) => c.md5 === candidate.conversationId)?.type || 'user' })) }; if (!this.knowledge) return { status: 'knowledge_unavailable' as const }
|
||||
const contact = contacts.find((c) => c.md5 === result.conversationId)!; const range = resolvedTimeRange(request.timeRange, this.nowProvider()); const found = await this.knowledge.search({ text: '', terms: [], conversationIds: [contact.md5], startTime: range.startTime, endTime: range.endTime, limit: LIMIT_MAX }); const retrieval = found.conversationRetrieval
|
||||
const sourceMessageCount = retrieval?.totalMessages || 0
|
||||
const evidence = found.evidence
|
||||
.map((item, index) => ({ messageRef: toRef(item.conversationId, item.messageId), timestamp: item.timestamp, sender: item.sender, sourceKind: item.sourceKind, text: item.text, index }))
|
||||
.sort((left, right) => left.timestamp - right.timestamp || left.index - right.index)
|
||||
.map(({ index: _index, ...item }) => item)
|
||||
const sourceState = retrieval?.complete ? 'complete' as const : 'partial' as const
|
||||
return { status: found.state === 'ready' ? 'completed' as const : 'retrieval_incomplete' as const, target: contactView(contact), resolvedTimeRange: range, coverage: { state: sourceState }, sourceMessageCount, evidenceCount: evidence.length, sourceCoverage: { state: sourceState, sourceMessageCount }, selection: { mode: 'temporal_coverage' as const, selectedEvidenceCount: evidence.length, sampled: evidence.length < sourceMessageCount }, voiceCoverage: found.voiceCoverage, evidence }
|
||||
if (!request?.timeRange) return { status: 'invalid_request' as const }
|
||||
if (!isReady()) return { status: 'knowledge_unavailable' as const }
|
||||
const contacts = await listContactsAsync()
|
||||
const corpus = await this.resolveCorpus(request.scope, contacts)
|
||||
if (corpus.error) return corpus.error as { status: string }
|
||||
const targetQuery = request.target?.query?.trim()
|
||||
let contact: FormattedContact | undefined
|
||||
if (targetQuery) {
|
||||
const resolved = resolveContact(targetQuery, contacts)
|
||||
if (!resolved.matched || !resolved.conversationId) {
|
||||
return { status: resolved.ambiguous ? 'ambiguous_contact' as const : 'contact_not_found' as const, candidates: resolved.candidates.map((candidate) => ({ displayName: candidate.displayName, type: contacts.find((c) => c.md5 === candidate.conversationId)?.type || 'user' })) }
|
||||
}
|
||||
contact = contacts.find((c) => c.md5 === resolved.conversationId)!
|
||||
if (corpus.conversationIds && !corpus.conversationIds.includes(contact.md5)) {
|
||||
return outsideScopeError(corpus.scope, contactView(contact).displayName) as { status: string }
|
||||
}
|
||||
} else if (corpus.contact) {
|
||||
contact = corpus.contact
|
||||
} else if (corpus.conversationIds && corpus.conversationIds.length === 1) {
|
||||
contact = contacts.find((c) => c.md5 === corpus.conversationIds![0])
|
||||
}
|
||||
if (!contact) {
|
||||
return {
|
||||
status: 'invalid_tool_arguments',
|
||||
field: 'target',
|
||||
constraint: 'target_required_for_scope',
|
||||
expected: describeScope(corpus.scope),
|
||||
actual: '省略 target',
|
||||
hint: '当前搜索范围包含多个会话,会话概览只能针对单个会话。请显式指定 target(必须在该范围内),或改用 search_messages。'
|
||||
}
|
||||
}
|
||||
const range = resolvedTimeRange(request.timeRange, this.nowProvider())
|
||||
// 注意:这里**不能**给 listMessagesAsync 传 limit —— 实测在有界时间范围下
|
||||
// `{ limit }` 会让 WCDB 读取返回 0 条(而同一范围不传 limit 能正常返回)。
|
||||
// 与 query_messages 保持一致:读完整区间,再在 JS 侧截断/采样。
|
||||
const raw = await listMessagesAsync(contact.md5, range.startTime, range.endTime)
|
||||
const messages = raw.length > OVERVIEW_SOURCE_CAP ? raw.slice(-OVERVIEW_SOURCE_CAP) : raw
|
||||
const truncated = raw.length > OVERVIEW_SOURCE_CAP
|
||||
const evidence = selectTemporalCoverageEvidence(contact, messages, OVERVIEW_EVIDENCE_TARGET)
|
||||
const state: 'complete' | 'partial' = truncated ? 'partial' : 'complete'
|
||||
return {
|
||||
status: 'completed' as const,
|
||||
target: contactView(contact),
|
||||
resolvedTimeRange: range,
|
||||
coverage: { state },
|
||||
sourceMessageCount: raw.length,
|
||||
evidenceCount: evidence.length,
|
||||
sourceCoverage: { state, sourceMessageCount: raw.length },
|
||||
selection: { mode: 'temporal_coverage' as const, selectedEvidenceCount: evidence.length, sampled: truncated || evidence.length < messages.length },
|
||||
evidence,
|
||||
scope: corpus.scope,
|
||||
origin: 'wcdb' as const
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 时间片代表证据:按时间间隔切块,每块取"最长文本 / 首条 / 末条",再轮转挑选,
|
||||
* 保证每个时间片都至少有一条代表,避免长会话里最近的时间片被整体丢弃。
|
||||
*/
|
||||
export function selectTemporalCoverageEvidence(
|
||||
contact: FormattedContact,
|
||||
messages: FormattedMessage[],
|
||||
target: number
|
||||
): QueryEvidenceItem[] {
|
||||
if (!messages.length || target <= 0) return []
|
||||
const chunks: FormattedMessage[][] = []
|
||||
for (const message of messages) {
|
||||
const current = chunks.at(-1)
|
||||
const previous = current?.at(-1)
|
||||
const gapMs = ((message.createTime || 0) - (previous?.createTime || 0)) * 1000
|
||||
const isNewChunk = !current || gapMs > OVERVIEW_CHUNK_GAP_MS || current.length >= OVERVIEW_CHUNK_MAX_MESSAGES
|
||||
if (isNewChunk) chunks.push([])
|
||||
chunks.at(-1)!.push(message)
|
||||
}
|
||||
const representativesByChunk = chunks.map((chunk) => {
|
||||
const preferred = chunk.filter((message) => kindOf(message) !== 'system')
|
||||
const pool = preferred.length ? preferred : chunk
|
||||
const ranked = [...pool].sort(
|
||||
(left, right) =>
|
||||
String(right.content || '').length - String(left.content || '').length ||
|
||||
(right.createTime || 0) - (left.createTime || 0)
|
||||
)
|
||||
return [ranked[0], pool[0], pool.at(-1)].filter(
|
||||
(value, index, items): value is FormattedMessage => Boolean(value) && items.indexOf(value) === index
|
||||
)
|
||||
})
|
||||
const selected: FormattedMessage[] = []
|
||||
for (let representativeIndex = 0; selected.length < target; representativeIndex += 1) {
|
||||
let added = false
|
||||
for (const representatives of representativesByChunk) {
|
||||
const representative = representatives[representativeIndex]
|
||||
if (representative && selected.length < target) {
|
||||
selected.push(representative)
|
||||
added = true
|
||||
}
|
||||
}
|
||||
if (!added) break
|
||||
}
|
||||
return selected.map((message) => toEvidenceItem(contact, message))
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type {
|
||||
ConversationOverviewRequest,
|
||||
MessageContextRequest,
|
||||
QueryMessagesRequest,
|
||||
SearchMessagesRequest
|
||||
} from '../../shared/local-query-api'
|
||||
import type { LocalQueryApiService } from './local-query-api-service'
|
||||
import type {
|
||||
QueryAgentToolContext,
|
||||
QueryAgentToolExecutor,
|
||||
QueryAgentToolResult
|
||||
} from './query-agent-service'
|
||||
|
||||
/**
|
||||
* 进程内 Tool Executor:把 Query Agent 的 Tool 调用直接映射到 Local Query API Service。
|
||||
*
|
||||
* 桌面问问微信与 Agent Hub 共用这一份;不经过 HTTP、不需要 token、不依赖 6131 端口。
|
||||
* Local Query API 的 public contract 未改变:时间仍是 epoch seconds(absolute 的 ISO-8601
|
||||
* 已由 Runtime 在 Host 侧换算),temporalBasis 已在 Host 侧剥离。
|
||||
*
|
||||
* CLI 仍使用自己的 HTTP executor(它跑在独立进程里),属于 Adapter 层差异。
|
||||
*/
|
||||
export function createLocalQueryToolExecutor(
|
||||
queryApi: LocalQueryApiService
|
||||
): QueryAgentToolExecutor {
|
||||
return async (
|
||||
name: string,
|
||||
input: Record<string, unknown>,
|
||||
context?: QueryAgentToolContext
|
||||
): Promise<QueryAgentToolResult> => {
|
||||
// 语料边界由 Host 注入(LLM 无法提供,Tool schema 里也没有这个字段)。
|
||||
// 越界 target 由 Engine 结构化拒绝,这里不做语义判断。
|
||||
const request = context?.conversationScope
|
||||
? { ...input, scope: context.conversationScope }
|
||||
: input
|
||||
switch (name) {
|
||||
case 'query_messages':
|
||||
// Local Query API 的 response 是显式 interface,没有 index signature,
|
||||
// 这里显式窄化到 Runtime 的宽松 Tool Result 形状(Runtime 只读 status 与计数字段)。
|
||||
return (await queryApi.messages(
|
||||
request as unknown as QueryMessagesRequest
|
||||
)) as unknown as QueryAgentToolResult
|
||||
case 'search_messages':
|
||||
return (await queryApi.search(
|
||||
request as unknown as SearchMessagesRequest
|
||||
)) as unknown as QueryAgentToolResult
|
||||
case 'message_context':
|
||||
return (await queryApi.context(
|
||||
request as unknown as MessageContextRequest
|
||||
)) as unknown as QueryAgentToolResult
|
||||
case 'conversation_overview':
|
||||
return (await queryApi.overview(
|
||||
request as unknown as ConversationOverviewRequest
|
||||
)) as unknown as QueryAgentToolResult
|
||||
default:
|
||||
throw new Error(`不允许的工具: ${name}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { normalizeMessageIdentity } from '../../shared/local-query-api'
|
||||
|
||||
/**
|
||||
* 「跳到原消息」的时间窗口规则。
|
||||
*
|
||||
* 抽成纯函数是因为它承载一条必须成立的性质:**锚点加载必须围绕 messageRef 的时间位置,
|
||||
* 不能退化成加载整段会话历史** —— 最大会话可达数十万条消息,整段读既慢又会挤爆 IPC。
|
||||
*/
|
||||
export const MESSAGES_AROUND_MAX_WINDOW = 2000
|
||||
|
||||
/** 默认锚点半径 6 小时;真实数据上时间窗口是稀疏的,±6h 的量级很小。 */
|
||||
export const MESSAGES_AROUND_DEFAULT_RADIUS_SECONDS = 6 * 3600
|
||||
export const MESSAGES_AROUND_MIN_RADIUS_SECONDS = 60
|
||||
export const MESSAGES_AROUND_MAX_RADIUS_SECONDS = 24 * 3600
|
||||
export const MESSAGES_AROUND_MAX_WIDEN_FACTOR = 12
|
||||
export const MESSAGES_AROUND_MAX_WIDEN_SECONDS = 3 * 24 * 3600
|
||||
|
||||
export const normalizeRadiusSeconds = (radiusSeconds?: number): number =>
|
||||
Math.max(
|
||||
MESSAGES_AROUND_MIN_RADIUS_SECONDS,
|
||||
Math.min(radiusSeconds || MESSAGES_AROUND_DEFAULT_RADIUS_SECONDS, MESSAGES_AROUND_MAX_RADIUS_SECONDS)
|
||||
)
|
||||
|
||||
export const widenRadiusSeconds = (baseRadius: number): number =>
|
||||
Math.min(baseRadius * MESSAGES_AROUND_MAX_WIDEN_FACTOR, MESSAGES_AROUND_MAX_WIDEN_SECONDS)
|
||||
|
||||
/**
|
||||
* 需要尝试的半径列表。
|
||||
*
|
||||
* **没有时间锚点时返回空数组** —— 这不是"退化成一个半径为 0 的查询"。
|
||||
* 半径 0 会变成 `start=undefined / end=undefined`,也就是整段会话历史;
|
||||
* 调用方必须据此直接给出「已打开对应会话,但暂时无法定位原消息」的降级文案。
|
||||
*/
|
||||
export const messagesAroundRadii = (
|
||||
anchorSeconds: number | undefined,
|
||||
baseRadius: number,
|
||||
widenRadius: number
|
||||
): number[] => (anchorSeconds && anchorSeconds > 0 ? [baseRadius, widenRadius] : [])
|
||||
|
||||
/** 有界窗口 + 精确身份定位。窗口按上限截断,绝不返回整段历史。 */
|
||||
export const sliceMessagesAroundWindow = <T extends { id?: unknown }>(
|
||||
messages: T[],
|
||||
conversationId: string,
|
||||
targetMessageId: string,
|
||||
maxWindowMessages: number = MESSAGES_AROUND_MAX_WINDOW
|
||||
): { window: T[]; index: number; truncated: boolean } => {
|
||||
const truncated = messages.length > maxWindowMessages
|
||||
const window = truncated ? messages.slice(0, maxWindowMessages) : messages
|
||||
const index = window.findIndex(
|
||||
(message) =>
|
||||
normalizeMessageIdentity(conversationId, String(message.id ?? ''))?.messageId === targetMessageId
|
||||
)
|
||||
return { window, index, truncated }
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { QueryAgentHistoryTurn } from './query-agent-service'
|
||||
|
||||
/**
|
||||
* 最小多轮澄清上下文的边界(刻意写成显式常量,便于审计)。
|
||||
*
|
||||
* 只保留极少数轮次、极短文本、极短有效期 —— 目的是让"你说的是哪位联系人?"这类
|
||||
* 澄清之后的下一句能被接上,而不是实现 Agent 长期记忆。
|
||||
*/
|
||||
export const CONVERSATION_MEMORY_MAX_TURNS = 2
|
||||
export const CONVERSATION_MEMORY_QUESTION_MAX_CHARS = 300
|
||||
export const CONVERSATION_MEMORY_ANSWER_MAX_CHARS = 800
|
||||
export const CONVERSATION_MEMORY_TTL_MS = 10 * 60 * 1000
|
||||
|
||||
interface ConversationEntry {
|
||||
turns: QueryAgentHistoryTurn[]
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
function truncate(value: string, maxChars: number): string {
|
||||
const normalized = String(value || '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
return normalized.length > maxChars ? `${normalized.slice(0, maxChars)}…` : normalized
|
||||
}
|
||||
|
||||
/**
|
||||
* 有界的问答上下文。
|
||||
*
|
||||
* 隐私边界:
|
||||
* - 只保存「用户问题 + Query Agent 最终回答」,**不保存** Tool 结果 / Evidence / 聊天原文;
|
||||
* - 只存在内存,不落盘、不进日志、不跨进程;
|
||||
* - 超过 TTL 或超过轮次上限即丢弃。
|
||||
*/
|
||||
export class QueryAgentConversationMemory {
|
||||
private readonly entries = new Map<string, ConversationEntry>()
|
||||
|
||||
constructor(private readonly now: () => number = () => Date.now()) {}
|
||||
|
||||
history(key: string): QueryAgentHistoryTurn[] {
|
||||
const entry = this.entries.get(key)
|
||||
if (!entry) return []
|
||||
if (this.now() - entry.updatedAt > CONVERSATION_MEMORY_TTL_MS) {
|
||||
this.entries.delete(key)
|
||||
return []
|
||||
}
|
||||
return entry.turns.map((turn) => ({ ...turn }))
|
||||
}
|
||||
|
||||
record(key: string, question: string, answer: string): void {
|
||||
const turn: QueryAgentHistoryTurn = {
|
||||
question: truncate(question, CONVERSATION_MEMORY_QUESTION_MAX_CHARS),
|
||||
answer: truncate(answer, CONVERSATION_MEMORY_ANSWER_MAX_CHARS)
|
||||
}
|
||||
if (!turn.question || !turn.answer) return
|
||||
const previous = this.history(key)
|
||||
this.entries.set(key, {
|
||||
turns: [...previous, turn].slice(-CONVERSATION_MEMORY_MAX_TURNS),
|
||||
updatedAt: this.now()
|
||||
})
|
||||
}
|
||||
|
||||
/** 只忘记某一路会话(例如用户点了「新问题」)。不传 key 时清空全部。 */
|
||||
forget(key?: string): void {
|
||||
if (key === undefined) {
|
||||
this.entries.clear()
|
||||
return
|
||||
}
|
||||
this.entries.delete(key)
|
||||
}
|
||||
}
|
||||
+314
-21
@@ -1,5 +1,21 @@
|
||||
/**
|
||||
* Shared Query Agent runtime used by Ask WeChat, Agent Hub, and the CLI harness.
|
||||
* Query semantics and tool orchestration are centralized here — prompt, tool mapping,
|
||||
* validation, temporal policy, retry/stopping, and the bounded model loop — so every
|
||||
* entry point behaves consistently; they differ only by injected tool executor and adapter.
|
||||
*/
|
||||
import type { AIChatToolCall, AIChatToolDefinition } from './ai-provider-service'
|
||||
import { LOCAL_QUERY_TOOL_DEFINITIONS, type QueryTemporalBasisKind } from '../../shared/local-query-api'
|
||||
import {
|
||||
LOCAL_QUERY_TOOL_DEFINITIONS,
|
||||
type QueryCorpusScope,
|
||||
type QuerySearchTimings,
|
||||
type QueryTemporalBasisKind
|
||||
} from '../../shared/local-query-api'
|
||||
// 进度事件定义在 shared(renderer 也要用),这里只是把它带进本文件作用域。
|
||||
import type {
|
||||
QueryAgentProgressEvent,
|
||||
QueryAgentProgressStage
|
||||
} from '../../shared/query-agent'
|
||||
|
||||
const MAX_TOOL_CALLS = 5
|
||||
const FORBIDDEN_INPUT_KEYS = new Set(['apiKey', 'authorization', 'token', 'databasePath', 'sql', 'wxid', 'md5'])
|
||||
@@ -70,6 +86,8 @@ export interface QueryAgentTraceItem {
|
||||
status: string
|
||||
resultCount?: number
|
||||
evidenceCount?: number
|
||||
/** 会话概览覆盖的源消息条数(additive,用于 UI 顶部真实统计)。 */
|
||||
sourceMessageCount?: number
|
||||
/** LLM 声明的 temporalBasis。Host 消费它决定 policy,但不会传给 Local Query API。 */
|
||||
temporalBasis?: { kind: QueryTemporalBasisKind; sourceText?: string }
|
||||
/** Host 自动执行的扩大查询(当前仅 temporalBasis.kind=recall_hint + 有界范围 + 0 结果)。 */
|
||||
@@ -81,6 +99,13 @@ export interface QueryAgentTraceItem {
|
||||
resultCount?: number
|
||||
evidenceCount?: number
|
||||
}
|
||||
/**
|
||||
* Engine 侧的真实耗时分解(ADDITIVE 诊断)。
|
||||
*
|
||||
* 由 `search_messages` 的 Tool Result 携带,**不会进入模型上下文**(`toolResultForModel`
|
||||
* 会剥离)。用途:把不透明的 Tool 总耗时拆成 scope / freshness / 每个 probe / 合并 / 证据补全。
|
||||
*/
|
||||
searchTimings?: QuerySearchTimings
|
||||
}
|
||||
|
||||
export interface QueryAgentModelCallDiagnostic {
|
||||
@@ -95,7 +120,24 @@ export interface QueryAgentModelCallDiagnostic {
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface QueryAgentPocResult {
|
||||
/**
|
||||
* 失败分类(additive 诊断字段,供 Adapter 决定展示与是否允许 Legacy fallback)。
|
||||
*
|
||||
* 'provider_unavailable' = Provider 未配置;'provider_failure' = 模型请求本身失败
|
||||
* (网络 / 上游 / 超时)。未分类的异常由 Adapter 归类为 runtime_error。
|
||||
*/
|
||||
export type QueryAgentErrorKind = 'invalid_question' | 'provider_unavailable' | 'provider_failure' | 'tool_limit'
|
||||
|
||||
/**
|
||||
* 多轮澄清所需的最小历史。**由 Adapter 提供**,Runtime 只负责按顺序放进 messages。
|
||||
* Runtime 自身仍然是无状态单轮执行器;历史长度 / 保留时间的边界由调用方负责。
|
||||
*/
|
||||
export interface QueryAgentHistoryTurn {
|
||||
question: string
|
||||
answer: string
|
||||
}
|
||||
|
||||
export interface QueryAgentResult {
|
||||
question: string
|
||||
provider: string
|
||||
model: string
|
||||
@@ -112,13 +154,54 @@ export interface QueryAgentPocResult {
|
||||
traces: QueryAgentTraceItem[]
|
||||
answer?: string
|
||||
error?: string
|
||||
/** 失败分类;additive 诊断字段,成功时为 undefined */
|
||||
errorKind?: QueryAgentErrorKind
|
||||
/** 本次回答实际依据的证据(additive);按首次命中顺序去重。 */
|
||||
evidence?: QueryAgentEvidenceItem[]
|
||||
}
|
||||
|
||||
/**
|
||||
* 语料边界(conversation scope):由 UI / Adapter 传入,**不是** LLM 的输入。
|
||||
* `label` 只用于给模型描述"当前范围是什么",强制逻辑完全在 Engine(target 越界会被拒绝)。
|
||||
*/
|
||||
export interface QueryAgentConversationScope {
|
||||
scope: QueryCorpusScope
|
||||
label?: string
|
||||
}
|
||||
|
||||
/** 单次 Tool 执行的上下文(由 Runtime 注入,LLM 无法提供)。 */
|
||||
export interface QueryAgentToolContext {
|
||||
conversationScope?: QueryCorpusScope
|
||||
}
|
||||
|
||||
export type QueryAgentToolExecutor = (
|
||||
name: string,
|
||||
input: Record<string, unknown>
|
||||
input: Record<string, unknown>,
|
||||
context?: QueryAgentToolContext
|
||||
) => Promise<QueryAgentToolResult>
|
||||
|
||||
/**
|
||||
* 本次回答实际依据的证据(ADDITIVE,供 Adapter 展示)。
|
||||
* 只保留可展示字段;messageRef 仍是 opaque 引用。
|
||||
*/
|
||||
export interface QueryAgentEvidenceItem {
|
||||
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 名(诊断 / UI 分组用)。 */
|
||||
source: string
|
||||
}
|
||||
|
||||
/** 一次回答最多带出多少条证据(IPC 体积与 UI 噪声控制)。 */
|
||||
const MAX_EVIDENCE_ITEMS = 40
|
||||
|
||||
|
||||
const SYSTEM_PROMPT = `你是 TraceMemo 的本地聊天查询助手,只能使用提供的四个 Query Tool 获取事实,最终回答只基于 Tool Result。
|
||||
|
||||
规划原则:
|
||||
@@ -131,6 +214,11 @@ const SYSTEM_PROMPT = `你是 TraceMemo 的本地聊天查询助手,只能使
|
||||
- 普通聊天查询不是 exhaustive investigation。经过合理的检索或可选 context 仍不足以形成强结论时,直接说明证据范围和不确定性,不要循环调用 search、overview、context。
|
||||
|
||||
事实边界:不得编造未返回的消息、猜测联系人、修改 resolvedTimeRange,或把 partial/unknown 当作 complete。coverage complete 且结果为 0 时,可以说明当前可读取的完整范围没有找到;coverage partial/unknown 且结果为 0 时,必须说明无法确认绝对不存在。不要把 sampled Evidence 当作完整聊天,也不要把 source message count 和 selected evidence count 混为一谈。
|
||||
索引新鲜度:search_messages 的 indexLatestAt / sourceLatestAt 是**结构化事实**,indexCoverage 是 Engine 给出的结论句。规则:
|
||||
- 覆盖边界只能引用 indexCoverage(含本地时间与结论),**不要自己换算时间,也不要把 epoch 数字写进回答**。
|
||||
- indexCoverage.covered 为 false 时,说明这段时间还没进索引:此时即使结果为 0 也只能说"索引尚未覆盖这段时间,暂时无法确认",**绝不能**说成"没有"。必须如实引用结论里的索引更新时间。
|
||||
- 已经检索到 Evidence 时,只有当这个覆盖边界真的会影响结论时才补一句说明,不要机械附加警告。
|
||||
- 只有 coverage.state 为 complete(indexCoverage.covered 为 true)且结果为 0,才可以下"没有找到"的结论。不要自己把 partial 说成 complete。
|
||||
缺少必要信息时用自然语言澄清;超出工具能力时说明不能可靠完成,并给出当前工具可以执行的替代方向。`
|
||||
|
||||
function toolDefinitions(): AIChatToolDefinition[] {
|
||||
@@ -299,12 +387,10 @@ interface CanonicalTemporalBasis {
|
||||
}
|
||||
|
||||
/**
|
||||
* LLM Tool Adapter 的 canonicalization:
|
||||
* - temporalBasis 是 LLM-facing 元数据:Host 用它决定 policy,但**剥离**后不传给 Local Query API
|
||||
* - absolute 的 ISO-8601 → Local Query API 的 epoch seconds
|
||||
* - search_messages 的 queries[] → Local Query API 的 query + variants
|
||||
* LLM Tool Adapter 的 canonicalization:剥离 LLM-facing 元数据(temporalBasis)、把 absolute 的
|
||||
* ISO-8601 换成 Local Query API 的 epoch seconds、把 `queries[]` 摊平成 query + variants。
|
||||
*
|
||||
* 这里只做**纯 lexical** 校验(sourceText 是否为用户问题子串 + kind 与 timeRange 是否自洽),
|
||||
* 这里只做**纯 lexical** 校验(sourceText 是否为用户问题子串、kind 与 timeRange 是否自洽),
|
||||
* 不解释时间短语的意思。
|
||||
*/
|
||||
function canonicalizeToolInput(
|
||||
@@ -482,10 +568,12 @@ export function validateToolArguments(
|
||||
return canonicalizeToolInput(name, value as Record<string, unknown>, now, question)
|
||||
}
|
||||
|
||||
function resultCount(result: QueryAgentToolResult): { resultCount?: number; evidenceCount?: number } {
|
||||
function resultCount(result: QueryAgentToolResult): { resultCount?: number; evidenceCount?: number; sourceMessageCount?: number } {
|
||||
return {
|
||||
resultCount: typeof result.returnedCount === 'number' ? result.returnedCount : undefined,
|
||||
evidenceCount: typeof result.evidenceCount === 'number' ? result.evidenceCount : Array.isArray(result.evidence) ? result.evidence.length : undefined
|
||||
evidenceCount: typeof result.evidenceCount === 'number' ? result.evidenceCount : Array.isArray(result.evidence) ? result.evidence.length : undefined,
|
||||
// 会话概览用它说明"覆盖了多少条源消息",UI 顶部统计需要真实数字。
|
||||
sourceMessageCount: typeof result.sourceMessageCount === 'number' ? result.sourceMessageCount : undefined
|
||||
}
|
||||
}
|
||||
|
||||
@@ -551,31 +639,220 @@ function nextToolDefinitions(name: string, result: QueryAgentToolResult, state:
|
||||
return []
|
||||
}
|
||||
|
||||
export class QueryAgentPocService {
|
||||
/** 进度阶段的类型定义在 `src/shared/query-agent.ts`(renderer 也要消费它,放这里会让 renderer 反向依赖 main)。 */
|
||||
export type { QueryAgentProgressEvent, QueryAgentProgressStage } from '../../shared/query-agent'
|
||||
|
||||
export interface QueryAgentRunOptions {
|
||||
/**
|
||||
* 最小多轮澄清支持:前几轮(问 + 答)的问答对,由 Adapter 负责长度 / 时间 / 隐私边界。
|
||||
* 不传时 messages = [system, user]。
|
||||
*/
|
||||
history?: QueryAgentHistoryTurn[]
|
||||
/**
|
||||
* 语料边界(搜索范围)。由 UI 决定;Runtime 负责把它传给 Engine 并在 prompt 里说明,
|
||||
* 但**强制**发生在 Engine(target 越界 → 可修正的 invalid_tool_arguments)。
|
||||
* 不传则不限制范围、不加范围说明。
|
||||
*/
|
||||
conversationScope?: QueryAgentConversationScope
|
||||
/**
|
||||
* 真实进度回调(ADDITIVE)。由 Adapter 转发给 UI;不传则零额外开销。
|
||||
* 回调抛出的异常不会影响查询本身。
|
||||
*/
|
||||
onProgress?: (event: QueryAgentProgressEvent) => void
|
||||
}
|
||||
|
||||
/** 给模型的范围说明:只描述边界,不做"请遵守"的祈祷式约束(约束由 Engine 强制)。 */
|
||||
function conversationScopeNote(input: QueryAgentConversationScope): string {
|
||||
const { scope } = input
|
||||
const label = input.label?.trim()
|
||||
const header = label ? `当前搜索范围(由应用界面决定):${label}。` : '当前搜索范围由应用界面决定。'
|
||||
const rules = [
|
||||
'所有工具调用都会被强制限制在这个范围内;target 若不在范围内会被拒绝,被拒绝时请如实说明范围限制,不要试图绕过。',
|
||||
'范围之外还有别的会话,但你**看不到**它们,也不要在回答里声称它们的情况。'
|
||||
]
|
||||
if (scope.kind === 'groups') {
|
||||
rules.push(
|
||||
'范围是群聊专属:包含全部群会话以及群成员实际发送的消息。问"谁聊过某话题"时应省略 search_messages 的 target 做跨群检索,并在回答里保留群名与发送者。'
|
||||
)
|
||||
} else if (scope.kind === 'contact' || scope.kind === 'current') {
|
||||
rules.push(
|
||||
'范围只有一个会话:所有工具都可以省略 target(query_messages 也可以),省略即在该会话内检索;不要猜会话名,也不要指定其他会话。'
|
||||
)
|
||||
}
|
||||
return `${header}\n${rules.map((rule) => `- ${rule}`).join('\n')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 证据收集器(Host 侧)。
|
||||
*
|
||||
* 从 Tool Result 中提取**真实**证据供 UI 展示 —— UI 不允许从回答文本里反解析证据。
|
||||
* - 按 `messageRef` 去重(search 与 context 命中同一条消息只显示一次);
|
||||
* - 顺序 = 首次命中顺序;上限 MAX_EVIDENCE_ITEMS;
|
||||
* - 只保留展示字段,不携带 wxid / md5 / DB id / raw Tool JSON。
|
||||
*/
|
||||
class EvidenceCollector {
|
||||
private readonly items = new Map<string, QueryAgentEvidenceItem>()
|
||||
|
||||
addFromToolResult(toolName: string, result: QueryAgentToolResult): void {
|
||||
const target = result.target && typeof result.target === 'object' ? (result.target as Record<string, unknown>) : undefined
|
||||
const defaults: { conversationName?: string; conversationType?: 'user' | 'group' } = {
|
||||
conversationName: typeof target?.displayName === 'string' ? target.displayName : undefined,
|
||||
conversationType: target?.type === 'user' || target?.type === 'group' ? target.type : undefined
|
||||
}
|
||||
const push = (value: unknown): void => {
|
||||
const item = this.normalize(value, toolName, defaults)
|
||||
if (item) this.merge(item)
|
||||
}
|
||||
if (Array.isArray(result.messages)) result.messages.forEach(push)
|
||||
if (Array.isArray(result.evidence)) result.evidence.forEach(push)
|
||||
// message_context:只收 anchor(被补充语境的那条证据),前后文不是本次结论的依据。
|
||||
if (result.anchor) push(result.anchor)
|
||||
// recall_hint 自动扩大的那次查询也是真实证据。
|
||||
const fallback = result.fallbackLookup && typeof result.fallbackLookup === 'object' ? (result.fallbackLookup as Record<string, unknown>) : undefined
|
||||
if (Array.isArray(fallback?.messages)) fallback.messages.forEach(push)
|
||||
}
|
||||
|
||||
list(): QueryAgentEvidenceItem[] {
|
||||
return Array.from(this.items.values()).slice(0, MAX_EVIDENCE_ITEMS)
|
||||
}
|
||||
|
||||
private merge(item: QueryAgentEvidenceItem): void {
|
||||
const existing = this.items.get(item.messageRef)
|
||||
if (!existing) {
|
||||
this.items.set(item.messageRef, item)
|
||||
return
|
||||
}
|
||||
// 同一消息被不同 Tool 命中:补齐缺失字段,保留首次的 source。
|
||||
const merged = existing as unknown as Record<string, unknown>
|
||||
for (const key of Object.keys(item)) {
|
||||
if (key === 'source') continue
|
||||
const value = (item as unknown as Record<string, unknown>)[key]
|
||||
if (value !== undefined && merged[key] === undefined) merged[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
private normalize(
|
||||
value: unknown,
|
||||
source: string,
|
||||
defaults: { conversationName?: string; conversationType?: 'user' | 'group' }
|
||||
): QueryAgentEvidenceItem | undefined {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined
|
||||
const record = value as Record<string, unknown>
|
||||
const messageRef = typeof record.messageRef === 'string' ? record.messageRef : undefined
|
||||
if (!messageRef) return undefined
|
||||
const attachment =
|
||||
record.attachment && typeof record.attachment === 'object' && !Array.isArray(record.attachment)
|
||||
? (record.attachment as Record<string, unknown>)
|
||||
: undefined
|
||||
const attachmentView = attachment
|
||||
? {
|
||||
...(typeof attachment.kind === 'string' ? { kind: attachment.kind } : {}),
|
||||
...(typeof attachment.name === 'string' ? { name: attachment.name } : {}),
|
||||
...(typeof attachment.url === 'string' ? { url: attachment.url } : {}),
|
||||
...(typeof attachment.sizeBytes === 'number' ? { sizeBytes: attachment.sizeBytes } : {})
|
||||
}
|
||||
: undefined
|
||||
return {
|
||||
messageRef,
|
||||
...(typeof record.conversationName === 'string'
|
||||
? { conversationName: record.conversationName }
|
||||
: defaults.conversationName
|
||||
? { conversationName: defaults.conversationName }
|
||||
: {}),
|
||||
...(record.conversationType === 'user' || record.conversationType === 'group'
|
||||
? { conversationType: record.conversationType }
|
||||
: defaults.conversationType
|
||||
? { conversationType: defaults.conversationType }
|
||||
: {}),
|
||||
...(typeof record.sender === 'string' ? { sender: record.sender } : {}),
|
||||
...(typeof record.timestamp === 'number' ? { timestamp: record.timestamp } : {}),
|
||||
...(typeof record.messageType === 'string'
|
||||
? { messageType: record.messageType }
|
||||
: typeof record.sourceKind === 'string'
|
||||
? { messageType: record.sourceKind }
|
||||
: {}),
|
||||
...(typeof record.text === 'string' && record.text ? { text: record.text } : {}),
|
||||
...(attachmentView && Object.keys(attachmentView).length ? { attachment: attachmentView } : {}),
|
||||
source
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class QueryAgentService {
|
||||
constructor(
|
||||
private readonly provider: QueryAgentProvider,
|
||||
private readonly executeTool: QueryAgentToolExecutor,
|
||||
private readonly nowProvider: () => Date = () => new Date()
|
||||
) {}
|
||||
|
||||
async run(question: string): Promise<QueryAgentPocResult> {
|
||||
async run(question: string, options: QueryAgentRunOptions = {}): Promise<QueryAgentResult> {
|
||||
const startedAt = Date.now()
|
||||
// 计数用可变持有者:`completed` 由 finally 发出,那时 result 已经离开作用域。
|
||||
const counters = { modelCallCount: 0, toolCallCount: 0 }
|
||||
const emit = (stage: QueryAgentProgressStage, extra: { toolName?: string } = {}): void => {
|
||||
const onProgress = options.onProgress
|
||||
if (!onProgress) return
|
||||
const at = Date.now()
|
||||
try {
|
||||
onProgress({
|
||||
stage,
|
||||
elapsedMs: at - startedAt,
|
||||
at,
|
||||
...(extra.toolName ? { toolName: extra.toolName } : {}),
|
||||
modelCallCount: counters.modelCallCount,
|
||||
toolCallCount: counters.toolCallCount
|
||||
})
|
||||
} catch {
|
||||
// 进度上报失败绝不能影响查询本身。
|
||||
}
|
||||
}
|
||||
try {
|
||||
return await this.runLoop(question, options, emit, counters)
|
||||
} finally {
|
||||
// 成功、Provider 失败、tool_limit、异常 —— 一律以 completed 收尾,
|
||||
// 避免 UI 永远停在某个中间阶段。
|
||||
emit('completed')
|
||||
}
|
||||
}
|
||||
|
||||
private async runLoop(
|
||||
question: string,
|
||||
options: QueryAgentRunOptions,
|
||||
emit: (stage: QueryAgentProgressStage, extra?: { toolName?: string }) => void,
|
||||
counters: { modelCallCount: number; toolCallCount: number }
|
||||
): Promise<QueryAgentResult> {
|
||||
const trimmed = question.trim()
|
||||
const startedAt = Date.now()
|
||||
const runtime = this.provider.getRuntimeConfig()
|
||||
const result: QueryAgentPocResult = { question: trimmed, provider: runtime.providerName, model: runtime.modelName || runtime.model, modelCallCount: 0, toolCallCount: 0, toolTotalMs: 0, totalMs: 0, traces: [], modelDurationsMs: [], modelDiagnostics: [] }
|
||||
if (!trimmed) return { ...result, error: '请输入查询问题', totalMs: Date.now() - startedAt }
|
||||
if (!runtime.configured) return { ...result, error: '当前 AI Provider 尚未配置', totalMs: Date.now() - startedAt }
|
||||
const result: QueryAgentResult = { question: trimmed, provider: runtime.providerName, model: runtime.modelName || runtime.model, modelCallCount: 0, toolCallCount: 0, toolTotalMs: 0, totalMs: 0, traces: [], modelDurationsMs: [], modelDiagnostics: [] }
|
||||
if (!trimmed) return { ...result, error: '请输入查询问题', errorKind: 'invalid_question', totalMs: Date.now() - startedAt }
|
||||
if (!runtime.configured) return { ...result, error: '当前 AI Provider 尚未配置', errorKind: 'provider_unavailable', totalMs: Date.now() - startedAt }
|
||||
|
||||
const history = options.history || []
|
||||
const scopeNote = options.conversationScope ? conversationScopeNote(options.conversationScope) : undefined
|
||||
const messages: Array<Record<string, unknown>> = [
|
||||
{ role: 'system', content: SYSTEM_PROMPT },
|
||||
// 范围说明是**上下文**,不是强制执行手段:真正的边界由 Engine 拒绝越界 target 来保证。
|
||||
...(scopeNote ? [{ role: 'system', content: scopeNote }] : []),
|
||||
...history.flatMap((turn) => [
|
||||
{ role: 'user', content: turn.question },
|
||||
{ role: 'assistant', content: turn.answer }
|
||||
]),
|
||||
{ role: 'user', content: trimmed }
|
||||
]
|
||||
const toolContext: QueryAgentToolContext = options.conversationScope
|
||||
? { conversationScope: options.conversationScope.scope }
|
||||
: {}
|
||||
const evidence = new EvidenceCollector()
|
||||
let tools = toolDefinitions()
|
||||
const retry = newRetryState()
|
||||
const now = this.nowProvider()
|
||||
let firstModelAt: number | undefined
|
||||
let finalModelDuration: number | undefined
|
||||
while (result.toolCallCount < MAX_TOOL_CALLS) {
|
||||
// 真实生命周期边界:还没有任何 Tool 结果 → 这次模型调用是"理解问题";
|
||||
// 已经有结果 → 这次是在消化证据并**生成回答**。不用定时器、不猜进度。
|
||||
emit(result.toolCallCount === 0 ? 'understanding' : 'generating_answer')
|
||||
const modelStartedAt = Date.now()
|
||||
const model = await this.provider.chatWithTools(messages, tools)
|
||||
result.modelCallCount += 1
|
||||
@@ -594,7 +871,7 @@ export class QueryAgentPocService {
|
||||
...(model.success ? {} : { error: model.error || '模型调用失败' })
|
||||
})
|
||||
if (firstModelAt === undefined) firstModelAt = Date.now()
|
||||
if (!model.success) return { ...result, error: model.error || '模型调用失败', firstModelMs: firstModelAt - startedAt, totalMs: Date.now() - startedAt }
|
||||
if (!model.success) return { ...result, error: model.error || '模型调用失败', errorKind: 'provider_failure', firstModelMs: firstModelAt - startedAt, totalMs: Date.now() - startedAt }
|
||||
const calls = model.toolCalls || []
|
||||
if (calls.length === 0) {
|
||||
finalModelDuration = modelDuration
|
||||
@@ -605,7 +882,7 @@ export class QueryAgentPocService {
|
||||
return result
|
||||
}
|
||||
if (result.toolCallCount + calls.length > MAX_TOOL_CALLS) {
|
||||
return { ...result, error: `超过最大工具调用次数(${MAX_TOOL_CALLS})`, firstModelMs: firstModelAt - startedAt, totalMs: Date.now() - startedAt }
|
||||
return { ...result, error: `超过最大工具调用次数(${MAX_TOOL_CALLS})`, errorKind: 'tool_limit', firstModelMs: firstModelAt - startedAt, totalMs: Date.now() - startedAt }
|
||||
}
|
||||
messages.push({ role: 'assistant', content: model.data || '', tool_calls: calls.map((call) => ({ id: call.id, type: 'function', function: { name: call.name, arguments: call.arguments } })) })
|
||||
for (const call of calls) {
|
||||
@@ -639,13 +916,17 @@ export class QueryAgentPocService {
|
||||
toolResult = { status: 'invalid_tool_arguments', field: '$', constraint: 'duplicate_retry', expected: '与上一次实质不同的条件', actual: '与上一次完全相同的条件' }
|
||||
} else {
|
||||
recordAttempt(call.name, traceInput, retry)
|
||||
const primary = await this.executeTool(call.name, traceInput)
|
||||
// Tool 真正开始执行 = "在搜索聊天记录"。跨会话范围会明显更慢,
|
||||
// UI 用范围(不是调用次数)决定副提示文案。
|
||||
emit('searching', { toolName: call.name })
|
||||
const primary = await this.executeTool(call.name, traceInput, toolContext)
|
||||
toolResult = primary
|
||||
// recall_hint + 有界范围 + 0 结果 → Host 自动做一次“全部历史”corrective lookup。
|
||||
// 这是一次本地 Query API 调用:不增加 LLM 往返,也不占用 MAX_TOOL_CALLS。
|
||||
// 注意:自动补查必须沿用同一个语料边界,不能借它逃出当前搜索范围。
|
||||
if (shouldAutoBroaden(call.name, temporalBasis, traceInput, primary)) {
|
||||
const fallbackStartedAt = Date.now()
|
||||
const fallbackResult = await this.executeTool('query_messages', { ...traceInput, timeRange: { kind: 'all' } })
|
||||
const fallbackResult = await this.executeTool('query_messages', { ...traceInput, timeRange: { kind: 'all' } }, toolContext)
|
||||
const fallbackCounts = resultCount(fallbackResult)
|
||||
autoFallback = { reason: AUTO_FALLBACK_REASON, timeRange: { kind: 'all' }, status: fallbackResult.status, durationMs: Date.now() - fallbackStartedAt, ...fallbackCounts }
|
||||
toolResult = {
|
||||
@@ -672,9 +953,21 @@ export class QueryAgentPocService {
|
||||
const completedToolResult = toolResult || { status: 'invalid_request', error: '工具调用失败' }
|
||||
const durationMs = Date.now() - inputStartedAt
|
||||
result.toolCallCount += 1
|
||||
counters.toolCallCount = result.toolCallCount
|
||||
result.toolTotalMs += durationMs
|
||||
// Tool Result 已经拿到 → 真实进入"整理证据"阶段。
|
||||
emit('organizing_evidence', { toolName: call.name })
|
||||
// 收集真实证据(去重、限量),供 UI 展示;不进入模型上下文。
|
||||
evidence.addFromToolResult(call.name, completedToolResult)
|
||||
result.evidence = evidence.list()
|
||||
const counts = resultCount(completedToolResult)
|
||||
result.traces.push({ toolName: call.name, input: sanitizeInput(traceInput), durationMs, status: completedToolResult.status, ...counts, ...(temporalBasis ? { temporalBasis } : {}), ...(autoFallback ? { autoFallback } : {}) })
|
||||
// 引擎耗时分解留在 Host 侧(诊断 / UI),不进入模型上下文。
|
||||
const rawTimings = completedToolResult.timings
|
||||
const searchTimings: QuerySearchTimings | undefined =
|
||||
rawTimings && typeof rawTimings === 'object' && !Array.isArray(rawTimings)
|
||||
? (rawTimings as QuerySearchTimings)
|
||||
: undefined
|
||||
result.traces.push({ toolName: call.name, input: sanitizeInput(traceInput), durationMs, status: completedToolResult.status, ...counts, ...(temporalBasis ? { temporalBasis } : {}), ...(autoFallback ? { autoFallback } : {}), ...(searchTimings ? { searchTimings } : {}) })
|
||||
const nextTools = completedToolResult.constraint === 'tool_availability'
|
||||
? tools
|
||||
: nextToolDefinitions(call.name, completedToolResult, retry, rangeKind(traceInput) === 'all')
|
||||
@@ -685,6 +978,6 @@ export class QueryAgentPocService {
|
||||
}
|
||||
result.firstModelMs = firstModelAt ? firstModelAt - startedAt : undefined
|
||||
result.totalMs = Date.now() - startedAt
|
||||
return { ...result, error: `超过最大工具调用次数(${MAX_TOOL_CALLS})` }
|
||||
return { ...result, error: `超过最大工具调用次数(${MAX_TOOL_CALLS})`, errorKind: 'tool_limit' }
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,12 @@ export interface AppSettings {
|
||||
/** Keep a running personal-WeChat OneBot process across app restarts. */
|
||||
keepPersonalWechatProcess?: boolean
|
||||
windowsWechatPort: string
|
||||
/**
|
||||
* Query Agent 是否为桌面「问问微信」与 Agent Hub 查询类问题的主路径。
|
||||
* 默认开启;关闭后回退到 Legacy AI Search Pipeline(仅作 runtime regression 时的回退开关,
|
||||
* 不在用户界面暴露实验性名称)。
|
||||
*/
|
||||
queryAgentEnabled: boolean
|
||||
}
|
||||
|
||||
function getDefaultDbRoot(): string {
|
||||
@@ -125,7 +131,8 @@ const DEFAULT_SETTINGS: AppSettings = {
|
||||
ttsSelectedVoiceId: '',
|
||||
ttsModel: 's2.1-pro-free',
|
||||
keepPersonalWechatProcess: false,
|
||||
windowsWechatPort: ''
|
||||
windowsWechatPort: '',
|
||||
queryAgentEnabled: true
|
||||
}
|
||||
|
||||
const SETTINGS_FILE = path.join(
|
||||
|
||||
Reference in new issue
Block a user