test: 暂存代码

This commit is contained in:
电摇小子 committed 2026-08-06 20:29:25 +08:00
1 parent 17417aa9d6
commit 4967cff3c0
43 files changed
+9978 -512

No files matched your search

+185
View File
@@ -0,0 +1,185 @@
import type { AiSearchAgentToolName, AiSearchAgentTraceItem } from '../../shared/ai-search'
export const MAX_AGENT_TOOL_CALLS = 5
export type AgentAction =
| { action: 'tool'; tool: AiSearchAgentToolName; arguments: Record<string, unknown> }
| { action: 'finalize'; reason: string }
export interface AgentToolResult {
summary: Record<string, unknown>
candidateCount: number
/** A host-owned coverage signal, never supplied by the model. */
finalizeReason?: string
}
export interface ControlledSearchAgentOptions {
question: string
scopeLabel: string
rangeLabel: string
maxToolCalls?: number
decide: (prompt: string) => Promise<string | undefined>
execute: (action: Extract<AgentAction, { action: 'tool' }>) => Promise<AgentToolResult>
onTrace: (item: Omit<AiSearchAgentTraceItem, 'sequence'>) => void
}
export interface ControlledSearchAgentResult {
status: 'finalized' | 'exhausted' | 'invalid'
toolCalls: number
reason: string
}
const TOOL_NAMES = new Set<AiSearchAgentToolName>([
'search_conversations',
'search_people',
'search_messages',
'get_conversation_messages',
'get_messages_by_time',
'get_message_context'
])
const parseAction = (value: string | undefined): AgentAction | null => {
if (!value) return null
const match = value.match(/\{[\s\S]*\}/)
if (!match) return null
try {
const parsed = JSON.parse(match[0]) as Record<string, unknown>
if (parsed.action === 'finalize' && typeof parsed.reason === 'string' && parsed.reason.trim()) {
return { action: 'finalize', reason: parsed.reason.trim().slice(0, 240) }
}
if (
parsed.action === 'tool' &&
typeof parsed.tool === 'string' &&
TOOL_NAMES.has(parsed.tool as AiSearchAgentToolName) &&
parsed.arguments &&
typeof parsed.arguments === 'object' &&
!Array.isArray(parsed.arguments)
) {
return {
action: 'tool',
tool: parsed.tool as AiSearchAgentToolName,
arguments: parsed.arguments as Record<string, unknown>
}
}
} catch {
// Invalid model output is rejected by the caller and triggers legacy fallback.
}
return null
}
const agentSystemPrompt = (
question: string,
scopeLabel: string,
rangeLabel: string
): string => `你是 WechatExplorer 的受控本地聊天搜索代理,只负责决定下一步检索,不回答用户问题。
用户问题:${question}
允许范围:${scopeLabel};时间范围:${rangeLabel}。
你只能输出一个 JSON 对象,不能输出 Markdown、解释、代码、SQL、文件路径或任何系统操作。
唯一合法格式:
{"action":"tool","tool":"search_people|search_conversations|search_messages|get_conversation_messages|get_messages_by_time|get_message_context","arguments":{...}}
或:
{"action":"finalize","reason":"已有足够证据"}
规则:
- 只能使用此前 Tool 返回的 conversationRef/messageRef;不得猜测或创建引用。
- 问“我和某人最近聊了什么”时,优先 search_people 或 search_conversations,再 get_conversation_messages;不要把联系人名当消息关键词。
- 搜索会话没有结果时,可根据结果自行尝试更短或更自然的名称表达,但最多五次 Tool 调用。
- Tool 结果不足时可以改 Tool 或查询策略;结果充分时 finalize。
- 不要请求全部聊天记录;遵守 Tool 返回的受限结果。`
const traceArguments = (
argumentsValue: Record<string, unknown>
): Record<string, string | number | boolean> => {
const result: Record<string, string | number | boolean> = {}
if (typeof argumentsValue.query === 'string') result.query = argumentsValue.query.slice(0, 80)
if (typeof argumentsValue.limit === 'number') result.limit = argumentsValue.limit
if (typeof argumentsValue.startTime === 'number') result.startTime = argumentsValue.startTime
if (typeof argumentsValue.endTime === 'number') result.endTime = argumentsValue.endTime
if (typeof argumentsValue.conversationRef === 'string') result.target = '已选择会话'
if (typeof argumentsValue.messageRef === 'string') result.context = '已选择消息'
return result
}
export async function runControlledSearchAgent(
options: ControlledSearchAgentOptions
): Promise<ControlledSearchAgentResult> {
let toolCalls = 0
let previousResult = '尚未执行 Tool。'
options.onTrace({ event: 'agentStart', label: '开始规划本次本地检索' })
const maxToolCalls = options.maxToolCalls || MAX_AGENT_TOOL_CALLS
while (toolCalls < maxToolCalls) {
const decisionStartedAt = Date.now()
const decisionInput = `${agentSystemPrompt(options.question, options.scopeLabel, options.rangeLabel)}\n\n上一次 Tool 结果:${previousResult}`
const output = await options.decide(decisionInput)
const decisionElapsedMs = Date.now() - decisionStartedAt
const action = parseAction(output)
if (!action) return { status: 'invalid', toolCalls, reason: 'Agent 返回的控制协议无效' }
if (action.action === 'finalize') {
options.onTrace({
event: 'agentDecision',
label: 'Agent 判断现有结果足够',
decision: action.reason,
decisionInput: decisionInput.slice(0, 8_000),
elapsedMs: decisionElapsedMs
})
return { status: 'finalized', toolCalls, reason: action.reason }
}
options.onTrace({
event: 'agentDecision',
label: 'Agent 选择下一次检索',
toolName: action.tool,
elapsedMs: decisionElapsedMs,
decisionInput: decisionInput.slice(0, 8_000)
})
toolCalls += 1
options.onTrace({
event: 'toolCallStart',
label: '正在执行本地检索',
toolName: action.tool,
arguments: traceArguments(action.arguments)
})
const toolStartedAt = Date.now()
try {
const result = await options.execute(action)
const elapsedMs = Date.now() - toolStartedAt
options.onTrace({
event: 'toolCallEnd',
label: '本地检索完成',
toolName: action.tool,
resultCount: result.candidateCount,
elapsedMs
})
previousResult = JSON.stringify(result.summary)
if (result.finalizeReason) {
options.onTrace({
event: 'agentDecision',
label: '本地资料已覆盖所选时间范围,可直接整理回答',
decision: result.finalizeReason,
elapsedMs: 0
})
return { status: 'finalized', toolCalls, reason: result.finalizeReason }
}
} catch (error) {
const elapsedMs = Date.now() - toolStartedAt
const message = error instanceof Error ? error.message : '本次本地检索不可用'
options.onTrace({
event: 'toolCallEnd',
label: '本地检索未返回结果',
toolName: action.tool,
resultCount: 0,
elapsedMs,
decision: message.slice(0, 160)
})
previousResult = JSON.stringify({ error: message.slice(0, 160), results: [] })
}
}
options.onTrace({
event: 'agentDecision',
label: '已达到本次检索上限',
decision: `最多允许 ${maxToolCalls} 次本地检索`
})
return { status: 'exhausted', toolCalls, reason: '已达到本次检索上限' }
}
+217
View File
@@ -0,0 +1,217 @@
import type {
AiSearchAggregation,
AiSearchFinalEvidence,
AiSearchPipelineEvidence
} from '../../shared/ai-search'
export type EvidenceBuildResult = {
evidence: AiSearchFinalEvidence[]
aggregation: AiSearchAggregation
candidateCount: number
deduplicatedCount: number
candidateRankingMs: number
evidenceBuildMs: number
aggregationMs: number
}
export type CitationValidationResult = {
answer: string
invalidCitationIds: string[]
status: 'valid' | 'sanitized'
}
export const evidenceIdentity = (
item: Pick<AiSearchPipelineEvidence, 'conversationId' | 'messageId'>
): string => `${item.conversationId}\u0000${item.messageId}`
const compareEvidence = (left: AiSearchPipelineEvidence, right: AiSearchPipelineEvidence): number =>
(left.score ?? 0) - (right.score ?? 0) ||
right.timestamp - left.timestamp ||
evidenceIdentity(left).localeCompare(evidenceIdentity(right))
const personIdentity = (item: AiSearchFinalEvidence): string =>
item.senderId
? `sender:${item.senderId}`
: `conversation:${item.conversationId}:name:${item.sender}`
export function buildEvidenceAggregation(evidence: AiSearchFinalEvidence[]): AiSearchAggregation {
const people = new Map<
string,
{
id: string
name: string
messageCount: number
conversationIds: Set<string>
lastMessageAt: number
evidenceIds: AiSearchFinalEvidence['id'][]
}
>()
const conversations = new Map<
string,
{
id: string
name: string
type: 'user' | 'group'
messageCount: number
people: Set<string>
lastMessageAt: number
evidenceIds: AiSearchFinalEvidence['id'][]
}
>()
for (const item of evidence) {
const personId = personIdentity(item)
const person = people.get(personId) || {
id: personId,
name: item.sender,
messageCount: 0,
conversationIds: new Set<string>(),
lastMessageAt: item.timestamp,
evidenceIds: []
}
person.messageCount += 1
person.conversationIds.add(item.conversationId)
person.lastMessageAt = Math.max(person.lastMessageAt, item.timestamp)
person.evidenceIds.push(item.id)
people.set(personId, person)
const conversation = conversations.get(item.conversationId) || {
id: item.conversationId,
name: item.conversationName,
type: item.conversationType,
messageCount: 0,
people: new Set<string>(),
lastMessageAt: item.timestamp,
evidenceIds: []
}
conversation.messageCount += 1
conversation.people.add(personId)
conversation.lastMessageAt = Math.max(conversation.lastMessageAt, item.timestamp)
conversation.evidenceIds.push(item.id)
conversations.set(item.conversationId, conversation)
}
return {
messageCount: evidence.length,
peopleCount: people.size,
conversationCount: conversations.size,
people: Array.from(people.values())
.map((person) => ({
id: person.id,
name: person.name,
messageCount: person.messageCount,
conversationCount: person.conversationIds.size,
lastMessageAt: person.lastMessageAt,
evidenceIds: person.evidenceIds
}))
.sort(
(left, right) =>
right.messageCount - left.messageCount || right.lastMessageAt - left.lastMessageAt
),
conversations: Array.from(conversations.values())
.map((conversation) => ({
id: conversation.id,
name: conversation.name,
type: conversation.type,
messageCount: conversation.messageCount,
peopleCount: conversation.people.size,
lastMessageAt: conversation.lastMessageAt,
evidenceIds: conversation.evidenceIds
}))
.sort(
(left, right) =>
right.messageCount - left.messageCount || right.lastMessageAt - left.lastMessageAt
)
}
}
/**
* Performs all candidate ordering, identity de-duplication, final limiting and
* program-owned citation assignment in one place. Nothing downstream receives
* the candidate list as an AI context.
*/
export function buildFinalEvidence(
candidates: AiSearchPipelineEvidence[],
limit: number,
options?: { strategy?: 'ranked' | 'conversation_coverage' }
): EvidenceBuildResult {
const rankingStartedAt = Date.now()
const ranked = [...candidates].sort(compareEvidence)
const candidateRankingMs = Date.now() - rankingStartedAt
const evidenceStartedAt = Date.now()
const unique = new Map<string, AiSearchPipelineEvidence>()
for (const item of ranked) {
const identity = evidenceIdentity(item)
if (!unique.has(identity)) unique.set(identity, item)
}
const uniqueEvidence = Array.from(unique.values())
const selected =
options?.strategy === 'conversation_coverage'
? selectConversationCoverage(uniqueEvidence, limit)
: uniqueEvidence.slice(0, Math.max(1, limit))
const evidence = selected.map((item, index) => ({ ...item, id: `E${index + 1}` as const }))
const evidenceBuildMs = Date.now() - evidenceStartedAt
const aggregationStartedAt = Date.now()
const aggregation = buildEvidenceAggregation(evidence)
const aggregationMs = Date.now() - aggregationStartedAt
return {
evidence,
aggregation,
candidateCount: candidates.length,
deduplicatedCount: unique.size,
candidateRankingMs,
evidenceBuildMs,
aggregationMs
}
}
/**
* A recent-conversation answer should cover separate local conversation chunks,
* not merely pick eight adjacent newest messages from one exchange.
*/
function selectConversationCoverage(
evidence: AiSearchPipelineEvidence[],
limit: number
): AiSearchPipelineEvidence[] {
const max = Math.max(1, limit)
const byChunk = new Map<string, AiSearchPipelineEvidence[]>()
for (const item of evidence) {
const chunk = byChunk.get(item.chunkId) || []
chunk.push(item)
byChunk.set(item.chunkId, chunk)
}
const representatives = Array.from(byChunk.values())
.map((items) => [...items].sort(compareEvidence)[0])
.sort((left, right) => left.timestamp - right.timestamp)
if (representatives.length <= max) return representatives
const selected: AiSearchPipelineEvidence[] = []
for (let index = 0; index < max; index += 1) {
const position = Math.round((index * (representatives.length - 1)) / (max - 1 || 1))
const item = representatives[position]
if (item && !selected.includes(item)) selected.push(item)
}
return selected
}
/** Do not expose citations that cannot resolve to program-owned Final Evidence. */
export function sanitizeAnswerCitations(
answer: string,
evidence: Array<Pick<AiSearchFinalEvidence, 'id'>>
): CitationValidationResult {
const allowed = new Set(evidence.map((item) => item.id))
const invalidCitationIds = new Set<string>()
const sanitized = answer.replace(/\[E(\d+)\]/g, (citation, number: string) => {
const id = `E${number}`
if (allowed.has(id as AiSearchFinalEvidence['id'])) return citation
invalidCitationIds.add(id)
return ''
})
return {
answer: sanitized,
invalidCitationIds: Array.from(invalidCitationIds),
status: invalidCitationIds.size ? 'sanitized' : 'valid'
}
}
File diff suppressed because it is too large. Load diff
+20 -1
View File
@@ -7,6 +7,11 @@ import type { CacheClearScope, CacheSummary, CacheSummaryItem } from '../../shar
export type { CacheClearScope } from '../../shared/cache'
const BOOTSTRAP_CACHE_DIR = path.join(app.getPath('userData'), 'cache', 'bootstrap')
const KNOWLEDGE_CACHE_DIR = path.join(app.getPath('userData'), 'knowledge')
export interface CacheClearOptions {
beforeClearKnowledge?: () => Promise<void>
}
function inspectDirectory(directory: string): { sizeBytes: number; fileCount: number } {
if (!fs.existsSync(directory)) return { sizeBytes: 0, fileCount: 0 }
@@ -40,6 +45,7 @@ function inspectDirectory(directory: string): { sizeBytes: number; fileCount: nu
export function getCacheSummary(): CacheSummary {
const bootstrap = inspectDirectory(BOOTSTRAP_CACHE_DIR)
const electron = inspectDirectory(path.join(app.getPath('userData'), 'Cache'))
const knowledge = inspectDirectory(KNOWLEDGE_CACHE_DIR)
const items: CacheSummaryItem[] = [
{
id: 'bootstrap',
@@ -52,6 +58,12 @@ export function getCacheSummary(): CacheSummary {
label: '应用临时缓存',
description: 'Electron 页面资源缓存,清理后会自动重新生成。',
...electron
},
{
id: 'knowledge',
label: '本地知识库索引',
description: '为问问微信建立的所有账号本地检索索引。清理后需手动重新建立,不影响微信原始数据。',
...knowledge
}
]
return {
@@ -61,7 +73,10 @@ export function getCacheSummary(): CacheSummary {
}
}
export async function clearCache(scope: CacheClearScope): Promise<CacheSummary> {
export async function clearCache(
scope: CacheClearScope,
options: CacheClearOptions = {}
): Promise<CacheSummary> {
if (scope === 'bootstrap' || scope === 'all') {
clearBootstrapCache()
await fs.remove(BOOTSTRAP_CACHE_DIR)
@@ -69,5 +84,9 @@ export async function clearCache(scope: CacheClearScope): Promise<CacheSummary>
if (scope === 'electron' || scope === 'all') {
await session.defaultSession.clearCache()
}
if (scope === 'knowledge' || scope === 'all') {
await options.beforeClearKnowledge?.()
await fs.remove(KNOWLEDGE_CACHE_DIR)
}
return getCacheSummary()
}
@@ -0,0 +1,86 @@
import type { Contact } from '../../shared/types'
import {
emptyContactResolution,
normalizeContactName,
type ContactResolutionCandidate,
type ContactResolutionMatch,
type ContactResolutionResult
} from '../../shared/contact-resolution'
export type ContactResolutionScope = 'any' | 'person' | 'group'
const displayName = (contact: Contact): string =>
contact.m_nsNickName || contact.remark || contact.wechatNickname || contact.m_nsUsrName
const aliases = (contact: Contact): Array<{ value: string; primary: boolean }> =>
[
{ value: contact.m_nsNickName, primary: true },
{ value: contact.remark || '', primary: false },
{ value: contact.wechatNickname || '', primary: false },
{ value: contact.m_nsUsrName, primary: false }
].filter((item) => Boolean(normalizeContactName(item.value)))
/**
* The one main-process authority that converts a user/Agent supplied name to
* an existing conversation. It only auto-confirms an exact canonical alias.
* Fuzzy discovery intentionally returns candidates rather than a guessed ID.
*/
export function resolveContact(
query: string,
contacts: Contact[],
scope: ContactResolutionScope = 'any'
): ContactResolutionResult {
const normalizedQuery = normalizeContactName(query)
if (!normalizedQuery) return emptyContactResolution()
const matches = new Map<string, { contact: Contact; matchedBy: ContactResolutionMatch }>()
for (const contact of contacts) {
if (!contact.md5) continue
if (scope === 'person' && contact.type !== 'user') continue
if (scope === 'group' && contact.type !== 'group') continue
for (const alias of aliases(contact)) {
if (normalizeContactName(alias.value) !== normalizedQuery) continue
const rawExact =
alias.value.trim().normalize('NFKC').toLocaleLowerCase() ===
query.trim().normalize('NFKC').toLocaleLowerCase()
const matchedBy: ContactResolutionMatch = rawExact
? 'exact'
: alias.primary
? 'normalized'
: 'alias'
const current = matches.get(contact.md5)
if (!current || (current.matchedBy === 'alias' && matchedBy !== 'alias')) {
matches.set(contact.md5, { contact, matchedBy })
}
}
}
const candidates: ContactResolutionCandidate[] = Array.from(matches.values())
.map(({ contact, matchedBy }) => ({
conversationId: contact.md5,
displayName: displayName(contact),
matchedBy,
confidence: 1
}))
.sort((left, right) => left.displayName.localeCompare(right.displayName, 'zh-CN'))
if (candidates.length !== 1) {
return {
...emptyContactResolution(),
candidates,
ambiguous: candidates.length > 1
}
}
const candidate = candidates[0]
const contact = matches.get(candidate.conversationId)!.contact
return {
matched: true,
personId: contact.m_nsUsrName,
conversationId: contact.md5,
canonicalName: displayName(contact),
displayName: candidate.displayName,
matchedBy: candidate.matchedBy,
confidence: candidate.confidence,
candidates,
ambiguous: false
}
}