mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 09:15:41 +08:00
feat: 自动化
This commit is contained in:
1 parent
766cd94788
commit
95384a4a92
32 files changed
+6420
-1
No files matched your search
@@ -112,6 +112,10 @@ import { agentHubService } from './services/agent-hub-service'
|
||||
import { WechatConnectorService } from './services/wechat-ilink'
|
||||
import { wechatSendGateway } from './services/wechat-send-gateway'
|
||||
import { groupExitMonitorService } from './services/group-exit-monitor-service'
|
||||
import { MessageListenerService } from './services/message-listener-service'
|
||||
import { automationRuleStore } from './services/automation-rule-store'
|
||||
import { automationExecutionLogService } from './services/automation-execution-log-service'
|
||||
import { initAutomationService, getAutomationService } from './services/automation-service'
|
||||
import { GroupStatsService } from './services/group-stats-service'
|
||||
import { wechatActionLogService } from './services/wechat-action-log-service'
|
||||
import { wechatActionGateway } from './services/wechat-action-gateway'
|
||||
@@ -1002,6 +1006,50 @@ app.whenReady().then(async () => {
|
||||
return { success: false, error: '应用正在退出,数据库连接已取消', monitoring: false }
|
||||
}
|
||||
const wcdb4Client = nextWechatDb.getWcdb4Client()
|
||||
/**
|
||||
* 正式 MessageListener(Observation Mode 接入)。
|
||||
*
|
||||
* 本轮**只监听、回读、规范化、去重、统计**,不触发任何业务:
|
||||
* 不匹配关键词、不判断 @我、不出日报、不回复、不调 AI / Agent、不发送。
|
||||
* 下一层的 Trigger 由后续任务接入。
|
||||
*/
|
||||
const messageListener = new MessageListenerService(wcdb4Client)
|
||||
/**
|
||||
* Automation v1(@我生成日报)。
|
||||
*
|
||||
* `isListening` 要等下面 `startMonitor` 有结果才知道,所以先用闭包变量占位。
|
||||
*/
|
||||
let automationListening = false
|
||||
initAutomationService(wcdb4Client, { isListening: () => automationListening })
|
||||
messageListener.onMessage((message) => {
|
||||
// 日志只允许出现「类型 / 群或私聊 / 是否自己发 / @ 数量」这类不可逆标识,
|
||||
// 不含 wxid、昵称、群名、正文与 source。
|
||||
console.log(
|
||||
`[MessageListener] incoming messageType=${message.messageType}` +
|
||||
` group=${message.isGroup} self=${message.isSelf}` +
|
||||
` mentions=${message.mentionTargets.length}`
|
||||
)
|
||||
// Automation 自带 isSelf / cooldown / 同消息幂等三重闸,不会形成回复循环。
|
||||
// 用 try 包住同步那一段:`getAutomationService()` 在未初始化时会抛,
|
||||
// 而 `.catch()` 只能接住异步拒绝 —— 漏了这层就会把异常抛进 MessageListener 的投递循环。
|
||||
try {
|
||||
void getAutomationService()
|
||||
.handleMessage(message)
|
||||
.catch((error) => {
|
||||
console.warn(
|
||||
`[Automation] handleMessage failed: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
})
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[Automation] 未初始化,已跳过本次消息: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
}
|
||||
})
|
||||
const sessions = await wcdb4Client.getSessionsAsync({ hydrateDisplayNames: false })
|
||||
configureRecallProtection(wcdb4Client, resolvedRoot, settings.recallProtectionEnabled)
|
||||
voiceService = new VoiceService(wcdb4Client, resolvedRoot)
|
||||
@@ -1010,12 +1058,15 @@ app.whenReady().then(async () => {
|
||||
videoAssetService = new VideoAssetService(wcdb4Client)
|
||||
const monitoring = await wcdb4Client.startMonitor((type, json) => {
|
||||
wcdb4Client.invalidateSessionCache()
|
||||
// 正式 MessageListener:只做 coalesce + 有界回读 + dedup + 投递,不触发业务。
|
||||
messageListener.handleNativeChange()
|
||||
groupExitMonitorService.notifyDatabaseChanged(json)
|
||||
recallArchiveMonitor?.handleDatabaseChange(json)
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) window.webContents.send('wcdb-change', { type, json })
|
||||
}
|
||||
})
|
||||
automationListening = monitoring === true
|
||||
void groupExitMonitorService.start(monitoring)
|
||||
const recentSession = sessions[0]
|
||||
if (recentSession?.username) {
|
||||
@@ -1540,6 +1591,61 @@ app.whenReady().then(async () => {
|
||||
)
|
||||
ipcMain.handle('wechat-action-log:list', () => wechatActionLogService.list())
|
||||
|
||||
/**
|
||||
* Automation v1(@我生成日报)。
|
||||
*
|
||||
* 规则与执行日志都是纯文件存储,**不依赖数据库**,所以这两组 handler 在数据库
|
||||
* 解锁前也可以安全调用;只有 `getStatus` / `listGroups` 需要会话数据,因此用
|
||||
* `tryAutomationService()` 兜底,避免渲染层在启动阶段拿到一个 rejected promise。
|
||||
*/
|
||||
const tryAutomationService = (): ReturnType<typeof getAutomationService> | null => {
|
||||
try {
|
||||
return getAutomationService()
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
ipcMain.handle('automation:listRules', () => automationRuleStore.listRules())
|
||||
ipcMain.handle('automation:createRule', (_, draft: unknown) =>
|
||||
automationRuleStore.createRule(draft)
|
||||
)
|
||||
ipcMain.handle('automation:updateRule', (_, input: unknown) => {
|
||||
const payload = (input || {}) as { id?: unknown; draft?: unknown }
|
||||
return automationRuleStore.updateRule(String(payload.id || ''), payload.draft) ?? null
|
||||
})
|
||||
ipcMain.handle('automation:deleteRule', (_, id: string) => automationRuleStore.deleteRule(id))
|
||||
ipcMain.handle('automation:setRuleEnabled', (_, input: unknown) => {
|
||||
const payload = (input || {}) as { id?: unknown; enabled?: unknown }
|
||||
return automationRuleStore.setRuleEnabled(String(payload.id || ''), payload.enabled === true) ?? null
|
||||
})
|
||||
ipcMain.handle('automation:listExecutions', (_, query: unknown) => {
|
||||
const input = (query || {}) as { limit?: unknown }
|
||||
return automationExecutionLogService.list({ limit: Number(input.limit) })
|
||||
})
|
||||
ipcMain.handle('automation:clearExecutions', () => automationExecutionLogService.clear())
|
||||
ipcMain.handle('automation:listGroups', () => tryAutomationService()?.listGroups() ?? [])
|
||||
ipcMain.handle('automation:getStatus', async () => {
|
||||
const service = tryAutomationService()
|
||||
if (service) return service.getStatus()
|
||||
// 数据库尚未就绪:如实返回「未监听 + 能力未知」,而不是假装一切正常。
|
||||
const todayStart = new Date()
|
||||
todayStart.setHours(0, 0, 0, 0)
|
||||
const counts = automationExecutionLogService.countSince(todayStart.getTime())
|
||||
return {
|
||||
listening: false,
|
||||
listeningDegraded: true,
|
||||
todayExecutions: counts.total,
|
||||
todaySuccesses: counts.success,
|
||||
sendCapability: {
|
||||
supported: false,
|
||||
ready: false,
|
||||
canSendText: false,
|
||||
canSendImage: false,
|
||||
message: '数据库尚未就绪,暂时无法获知微信发送能力'
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle('db:search', (_, keyword: string) => chat.searchMessages(keyword))
|
||||
ipcMain.handle(
|
||||
'knowledge:search',
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
import {
|
||||
AUTOMATION_STEP_LABELS,
|
||||
AUTOMATION_SEND_ORIGIN,
|
||||
AUTOMATION_SEND_PURPOSE,
|
||||
DEFAULT_REPLY_TEXT,
|
||||
automationIdempotencyKey,
|
||||
type AutomationAction,
|
||||
type AutomationRule,
|
||||
type AutomationStep,
|
||||
type AutomationStepKey
|
||||
} from '../../shared/automation'
|
||||
import type { WechatActionContent, WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
|
||||
import {
|
||||
generateAgentGroupReport,
|
||||
type AgentGroupReportRequest,
|
||||
type AgentGroupReportResult
|
||||
} from './agent-group-report-service'
|
||||
import { wechatActionGateway } from './wechat-action-gateway'
|
||||
|
||||
/**
|
||||
* AutomationActionRunner —— 把一次命中跑成**步骤序列**。
|
||||
*
|
||||
* 两条硬要求:
|
||||
*
|
||||
* 1. **每一步都有独立的状态、起止时间与耗时。** 用户层日志的全部价值就在于此:
|
||||
* 只告诉用户「失败了」等于没说,得告诉他是「生成日报」那步坏了。
|
||||
* 2. **失败必须切断后续。** 日报没生成出来就绝不能继续发图 —— 那会发出一条
|
||||
* 空的 / 过期的 / 上一条的消息,比不发更糟。所以失败后剩下的步骤一律 `skipped`。
|
||||
*/
|
||||
|
||||
/** 一步执行完毕后,后续步骤的处置方式。 */
|
||||
const STEP_ORDER: AutomationStepKey[] = ['received', 'matched', 'reply', 'report', 'send']
|
||||
|
||||
export interface AutomationRunInput {
|
||||
executionId: string
|
||||
rule: AutomationRule
|
||||
/** 会话标识:群为 `xxx@chatroom`,私聊为 wxid。同时也是发送对象。 */
|
||||
conversationId: string
|
||||
isGroup: boolean
|
||||
/** 用户可读的来源名(群名 / 昵称)。**不是** id。 */
|
||||
sourceDisplayName: string
|
||||
}
|
||||
|
||||
export interface AutomationRunResult {
|
||||
steps: AutomationStep[]
|
||||
status: 'success' | 'failed'
|
||||
errorSummary?: string
|
||||
pngPath?: string
|
||||
}
|
||||
|
||||
export interface AutomationActionRunnerDependencies {
|
||||
generateReport?: (request: AgentGroupReportRequest) => Promise<AgentGroupReportResult>
|
||||
executeAction?: (request: WechatActionRequest) => Promise<WechatActionResult>
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
/** 策略层的错误码 → 用户可读短句。UI 直接展示这些文案,不做二次翻译。 */
|
||||
const ACTION_ERROR_MESSAGES: Record<string, string> = {
|
||||
INVALID_REQUEST: '发送请求不合法',
|
||||
INVALID_RECIPIENT: '找不到有效的发送对象',
|
||||
ACTION_NOT_ALLOWED: '该自动化动作未被允许执行',
|
||||
RECIPIENT_SCOPE_VIOLATION: '发送对象与触发来源不一致',
|
||||
SEND_CAPABILITY_UNAVAILABLE: '当前环境没有可用的微信发送能力',
|
||||
SEND_NOT_READY: '微信发送能力尚未就绪,请先绑定个人微信',
|
||||
SEND_FAILED: '微信发送失败',
|
||||
POLICY_BLOCKED: '该发送动作未通过策略检查',
|
||||
UNKNOWN: '发送失败(未知原因)'
|
||||
}
|
||||
|
||||
function createStep(key: AutomationStepKey): AutomationStep {
|
||||
return { key, label: AUTOMATION_STEP_LABELS[key], status: 'pending' }
|
||||
}
|
||||
|
||||
function markSuccess(step: AutomationStep, at: number): void {
|
||||
step.status = 'success'
|
||||
step.startedAt = step.startedAt ?? at
|
||||
step.finishedAt = at
|
||||
step.durationMs = Math.max(0, at - step.startedAt)
|
||||
}
|
||||
|
||||
function markFailed(step: AutomationStep, at: number, error: string): void {
|
||||
step.status = 'failed'
|
||||
step.startedAt = step.startedAt ?? at
|
||||
step.finishedAt = at
|
||||
step.durationMs = Math.max(0, at - step.startedAt)
|
||||
step.error = error
|
||||
}
|
||||
|
||||
function markSkipped(step: AutomationStep): void {
|
||||
step.status = 'skipped'
|
||||
}
|
||||
|
||||
function actionErrorMessage(code: string | undefined, fallback: string | undefined): string {
|
||||
if (fallback && fallback.trim()) {
|
||||
// 策略层给的 reason 已是中文短句;直接用,避免二次包装丢信息。
|
||||
return fallback.trim()
|
||||
}
|
||||
return (code && ACTION_ERROR_MESSAGES[code]) || ACTION_ERROR_MESSAGES.UNKNOWN
|
||||
}
|
||||
|
||||
export class AutomationActionRunner {
|
||||
private readonly generateReport: (request: AgentGroupReportRequest) => Promise<AgentGroupReportResult>
|
||||
private readonly executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
|
||||
private readonly now: () => number
|
||||
|
||||
constructor(dependencies: AutomationActionRunnerDependencies = {}) {
|
||||
this.generateReport = dependencies.generateReport ?? generateAgentGroupReport
|
||||
this.executeAction = dependencies.executeAction ?? ((request) => wechatActionGateway.execute(request))
|
||||
this.now = dependencies.now ?? (() => Date.now())
|
||||
}
|
||||
|
||||
async run(input: AutomationRunInput): Promise<AutomationRunResult> {
|
||||
const steps = STEP_ORDER.map((key) => createStep(key))
|
||||
const stepAt = (key: AutomationStepKey): AutomationStep =>
|
||||
steps.find((step) => step.key === key) as AutomationStep
|
||||
|
||||
markSuccess(stepAt('received'), this.now())
|
||||
markSuccess(stepAt('matched'), this.now())
|
||||
|
||||
const replyAction = findAction(input.rule, 'replyText')
|
||||
const reportAction = findAction(input.rule, 'generateReport')
|
||||
const sendAction = findAction(input.rule, 'sendReportImage')
|
||||
|
||||
// ---- 步骤 3:回复确认 ----
|
||||
if (!replyAction) {
|
||||
markSkipped(stepAt('reply'))
|
||||
} else {
|
||||
const replyStep = stepAt('reply')
|
||||
replyStep.status = 'running'
|
||||
replyStep.startedAt = this.now()
|
||||
const sent = await this.sendThroughGateway(input, 'reply', {
|
||||
type: 'text',
|
||||
text: replyAction.text?.trim() || DEFAULT_REPLY_TEXT
|
||||
})
|
||||
if (!sent.ok) {
|
||||
markFailed(replyStep, this.now(), sent.error || '回复确认失败')
|
||||
markRemainingSkipped(steps, 'reply')
|
||||
return { steps, status: 'failed', errorSummary: replyStep.error }
|
||||
}
|
||||
markSuccess(replyStep, this.now())
|
||||
}
|
||||
|
||||
// ---- 步骤 4:生成日报 ----
|
||||
let pngPath: string | undefined
|
||||
if (!reportAction) {
|
||||
markSkipped(stepAt('report'))
|
||||
} else {
|
||||
const reportStep = stepAt('report')
|
||||
reportStep.status = 'running'
|
||||
reportStep.startedAt = this.now()
|
||||
let result: AgentGroupReportResult
|
||||
try {
|
||||
result = await this.generateReport({ group: input.conversationId, range: 'today' })
|
||||
} catch (error) {
|
||||
result = {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
}
|
||||
if (!result.success || !result.pngPath) {
|
||||
markFailed(reportStep, this.now(), result.error || '日报生成失败')
|
||||
markRemainingSkipped(steps, 'report')
|
||||
return { steps, status: 'failed', errorSummary: reportStep.error }
|
||||
}
|
||||
pngPath = result.pngPath
|
||||
markSuccess(reportStep, this.now())
|
||||
}
|
||||
|
||||
// ---- 步骤 5:发送日报图片 ----
|
||||
// 日报被跳过(或没产出图片)时,这一条也必须 skipped —— 不能凭空发图。
|
||||
if (!sendAction || !pngPath) {
|
||||
markSkipped(stepAt('send'))
|
||||
return { steps, status: 'success', ...(pngPath ? { pngPath } : {}) }
|
||||
}
|
||||
const sendStep = stepAt('send')
|
||||
sendStep.status = 'running'
|
||||
sendStep.startedAt = this.now()
|
||||
const sent = await this.sendThroughGateway(input, 'report', { type: 'image', path: pngPath })
|
||||
if (!sent.ok) {
|
||||
markFailed(sendStep, this.now(), sent.error || '发送日报图片失败')
|
||||
return { steps, status: 'failed', errorSummary: sendStep.error, pngPath }
|
||||
}
|
||||
markSuccess(sendStep, this.now())
|
||||
return { steps, status: 'success', pngPath }
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一发送出口。
|
||||
*
|
||||
* **刻意不直接调 `WechatSendGateway`,而是走 `WechatActionGateway`**:后者在
|
||||
* `WechatSendGateway` 之上多给了三样本功能必须的东西 ——
|
||||
* 幂等(同一 executionId 不会重复发)、自动化发送节流(3s 间隔,防刷屏)、
|
||||
* 审计落盘。底层实际发送仍然经由 `WechatSendGateway.sendPersonal`,
|
||||
* 所以「所有发送统一走 WechatSendGateway」这条约束依然成立。
|
||||
*/
|
||||
private async sendThroughGateway(
|
||||
input: AutomationRunInput,
|
||||
kind: 'reply' | 'report',
|
||||
content: WechatActionContent
|
||||
): Promise<{ ok: boolean; error?: string }> {
|
||||
try {
|
||||
const result = await this.executeAction({
|
||||
idempotencyKey: automationIdempotencyKey(kind, input.executionId),
|
||||
origin: AUTOMATION_SEND_ORIGIN,
|
||||
purpose: AUTOMATION_SEND_PURPOSE[kind],
|
||||
triggerType: 'automation',
|
||||
executionId: input.executionId,
|
||||
recipient: {
|
||||
type: input.isGroup ? 'group' : 'contact',
|
||||
id: input.conversationId,
|
||||
name: input.sourceDisplayName
|
||||
},
|
||||
content
|
||||
})
|
||||
if (result.status === 'sent') return { ok: true }
|
||||
return { ok: false, error: actionErrorMessage(result.errorCode, result.reason) }
|
||||
} catch (error) {
|
||||
// execute() 本身刻意不抛,这里兜的是注入实现或意外异常。
|
||||
return { ok: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function findAction(rule: AutomationRule, type: AutomationAction['type']): AutomationAction | undefined {
|
||||
return rule.actions.find((action) => action.type === type && action.enabled)
|
||||
}
|
||||
|
||||
/** 把 `after` 之后的步骤全部标成 `skipped`(前一步挂了,后面的不许再动)。 */
|
||||
function markRemainingSkipped(steps: AutomationStep[], after: AutomationStepKey): void {
|
||||
const from = STEP_ORDER.indexOf(after) + 1
|
||||
for (const key of STEP_ORDER.slice(from)) {
|
||||
const step = steps.find((item) => item.key === key)
|
||||
if (step) markSkipped(step)
|
||||
}
|
||||
}
|
||||
|
||||
export const automationActionRunner = new AutomationActionRunner()
|
||||
@@ -0,0 +1,127 @@
|
||||
import path from 'node:path'
|
||||
import { app } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import type { AutomationExecution } from '../../shared/automation'
|
||||
|
||||
/**
|
||||
* AutomationExecutionLogService —— **用户层**执行日志。
|
||||
*
|
||||
* 与 debug 日志的区别:这份记录是给用户看「哪一步坏了」的,所以
|
||||
* - 只保留用户可读字段(规则名、来源显示名、步骤状态、耗时、错误);
|
||||
* - **不含** wxid / localId / serverId / source XML / raw payload / 图片绝对路径;
|
||||
* - 必须落盘,重启后还能看到近期记录。
|
||||
*
|
||||
* 容量有界(`MAX_RECORDS`),否则长期运行会把文件撑到几十兆。
|
||||
*/
|
||||
|
||||
const STORAGE_DIR = 'automation'
|
||||
const EXECUTIONS_FILE = 'executions.json'
|
||||
const MAX_RECORDS = 200
|
||||
|
||||
export interface AutomationExecutionLogDependencies {
|
||||
userDataPath?: () => string
|
||||
}
|
||||
|
||||
function normalizeExecution(value: unknown): AutomationExecution | null {
|
||||
if (!value || typeof value !== 'object') return null
|
||||
const record = value as Partial<AutomationExecution>
|
||||
const executionId = String(record.executionId || '').trim()
|
||||
if (!executionId) return null
|
||||
return {
|
||||
executionId,
|
||||
ruleId: String(record.ruleId || ''),
|
||||
ruleName: String(record.ruleName || ''),
|
||||
triggerTime: Number(record.triggerTime) || 0,
|
||||
sourceDisplayName: String(record.sourceDisplayName || ''),
|
||||
status: record.status === 'success' || record.status === 'failed' ? record.status : 'running',
|
||||
durationMs: Number(record.durationMs) || 0,
|
||||
steps: Array.isArray(record.steps) ? record.steps : [],
|
||||
...(record.errorSummary ? { errorSummary: String(record.errorSummary) } : {})
|
||||
}
|
||||
}
|
||||
|
||||
export class AutomationExecutionLogService {
|
||||
private readonly userDataPath: () => string
|
||||
private records: AutomationExecution[] = []
|
||||
private loaded = false
|
||||
|
||||
constructor(dependencies: AutomationExecutionLogDependencies = {}) {
|
||||
this.userDataPath = dependencies.userDataPath ?? (() => app.getPath('userData'))
|
||||
}
|
||||
|
||||
list(query: { limit?: number } = {}): AutomationExecution[] {
|
||||
this.ensureLoaded()
|
||||
const requested = Number(query?.limit)
|
||||
const limit = Number.isFinite(requested) && requested > 0 ? Math.floor(requested) : MAX_RECORDS
|
||||
return this.records.slice(0, Math.min(limit, MAX_RECORDS)).map((record) => structuredClone(record))
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入(或按 `executionId` 覆盖)一条执行记录。
|
||||
*
|
||||
* 覆盖语义是必需的:执行是「先建 running、跑完再回落终态」,
|
||||
* 中间态与终态共用同一个 `executionId`。
|
||||
*/
|
||||
record(execution: AutomationExecution): void {
|
||||
this.ensureLoaded()
|
||||
const normalized = normalizeExecution(execution)
|
||||
if (!normalized) return
|
||||
const withoutSame = this.records.filter((item) => item.executionId !== normalized.executionId)
|
||||
this.records = [normalized, ...withoutSame].slice(0, MAX_RECORDS)
|
||||
this.persist()
|
||||
}
|
||||
|
||||
clear(): boolean {
|
||||
this.ensureLoaded()
|
||||
this.records = []
|
||||
this.persist()
|
||||
return true
|
||||
}
|
||||
|
||||
/** 统计 `sinceMs` 之后(含)的记录数与成功数。用于顶部「今日执行」。 */
|
||||
countSince(sinceMs: number): { total: number; success: number } {
|
||||
this.ensureLoaded()
|
||||
const from = Number(sinceMs) || 0
|
||||
let total = 0
|
||||
let success = 0
|
||||
for (const record of this.records) {
|
||||
if (record.triggerTime < from) continue
|
||||
total += 1
|
||||
if (record.status === 'success') success += 1
|
||||
}
|
||||
return { total, success }
|
||||
}
|
||||
|
||||
private ensureLoaded(): void {
|
||||
if (this.loaded) return
|
||||
this.loaded = true
|
||||
try {
|
||||
const raw = fs.readJsonSync(this.executionsFilePath()) as unknown
|
||||
const values = Array.isArray(raw) ? raw : []
|
||||
this.records = values
|
||||
.map((value) => normalizeExecution(value))
|
||||
.filter((value): value is AutomationExecution => value !== null)
|
||||
.slice(0, MAX_RECORDS)
|
||||
} catch {
|
||||
this.records = []
|
||||
}
|
||||
}
|
||||
|
||||
private executionsFilePath(): string {
|
||||
return path.join(this.userDataPath(), STORAGE_DIR, EXECUTIONS_FILE)
|
||||
}
|
||||
|
||||
private persist(): void {
|
||||
try {
|
||||
const filePath = this.executionsFilePath()
|
||||
fs.ensureDirSync(path.dirname(filePath))
|
||||
fs.writeJsonSync(filePath, this.records, { spaces: 2 })
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[Automation] 保存执行日志失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const automationExecutionLogService = new AutomationExecutionLogService()
|
||||
@@ -0,0 +1,166 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import path from 'node:path'
|
||||
import { app } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import {
|
||||
createDefaultDailyReportRule,
|
||||
normalizeRuleDraft,
|
||||
type AutomationRule
|
||||
} from '../../shared/automation'
|
||||
|
||||
/**
|
||||
* AutomationRuleStore —— 自动化规则的持久化与增删改查。
|
||||
*
|
||||
* 存储形态刻意做到最简:一个 JSON 文件(`{userData}/automation/rules.json`)。
|
||||
* 规则总量是个位数到几十条,引入数据库只会增加迁移负担。
|
||||
*
|
||||
* **内置规则的播种标记(`builtinSeeded`)单独存**:
|
||||
* 如果靠"文件里有没有那条内置规则"来判断是否播种,用户一旦删掉它,
|
||||
* 下次启动就会被重新塞回来 —— 用户会认为删除功能坏了。
|
||||
*/
|
||||
|
||||
const STORAGE_DIR = 'automation'
|
||||
const RULES_FILE = 'rules.json'
|
||||
|
||||
interface StoredRules {
|
||||
version: number
|
||||
/** 内置规则是否已经播种过。**即使随后被删除也保持 true**。 */
|
||||
builtinSeeded: boolean
|
||||
rules: AutomationRule[]
|
||||
}
|
||||
|
||||
export interface AutomationRuleStoreDependencies {
|
||||
userDataPath?: () => string
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
function emptyState(): StoredRules {
|
||||
return { version: 1, builtinSeeded: false, rules: [] }
|
||||
}
|
||||
|
||||
/** 读盘容错:任何字段可疑都降级成安全值,绝不因为一个坏文件让功能整体不可用。 */
|
||||
function normalizeStored(value: unknown): StoredRules {
|
||||
if (!value || typeof value !== 'object') return emptyState()
|
||||
const input = value as Partial<StoredRules>
|
||||
const rules = Array.isArray(input.rules)
|
||||
? input.rules.filter(
|
||||
(rule): rule is AutomationRule =>
|
||||
Boolean(rule && typeof rule === 'object' && String(rule.id || '').trim())
|
||||
)
|
||||
: []
|
||||
return {
|
||||
version: Number(input.version) || 1,
|
||||
builtinSeeded: input.builtinSeeded === true,
|
||||
rules
|
||||
}
|
||||
}
|
||||
|
||||
export class AutomationRuleStore {
|
||||
private readonly userDataPath: () => string
|
||||
private readonly now: () => number
|
||||
private state: StoredRules = emptyState()
|
||||
private loaded = false
|
||||
|
||||
constructor(dependencies: AutomationRuleStoreDependencies = {}) {
|
||||
this.userDataPath = dependencies.userDataPath ?? (() => app.getPath('userData'))
|
||||
this.now = dependencies.now ?? (() => Date.now())
|
||||
}
|
||||
|
||||
listRules(): AutomationRule[] {
|
||||
this.ensureLoaded()
|
||||
return this.state.rules.map((rule) => structuredClone(rule))
|
||||
}
|
||||
|
||||
getRule(id: string): AutomationRule | undefined {
|
||||
const key = String(id || '').trim()
|
||||
if (!key) return undefined
|
||||
const found = this.listRules().find((rule) => rule.id === key)
|
||||
return found
|
||||
}
|
||||
|
||||
createRule(draft: unknown): AutomationRule {
|
||||
this.ensureLoaded()
|
||||
const timestamp = this.now()
|
||||
const normalized = normalizeRuleDraft(draft)
|
||||
const rule: AutomationRule = {
|
||||
...normalized,
|
||||
id: randomUUID(),
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp
|
||||
}
|
||||
this.state.rules = [...this.state.rules, rule]
|
||||
this.persist()
|
||||
return structuredClone(rule)
|
||||
}
|
||||
|
||||
updateRule(id: string, draft: unknown): AutomationRule | undefined {
|
||||
this.ensureLoaded()
|
||||
const key = String(id || '').trim()
|
||||
const index = this.state.rules.findIndex((rule) => rule.id === key)
|
||||
if (index < 0) return undefined
|
||||
const current = this.state.rules[index]
|
||||
// 名字留空时沿用原名,而不是变成「未命名自动化」—— 编辑页只改开关时不该改名。
|
||||
const normalized = normalizeRuleDraft(draft, current.name)
|
||||
const rule: AutomationRule = {
|
||||
...current,
|
||||
...normalized,
|
||||
id: current.id,
|
||||
createdAt: current.createdAt,
|
||||
updatedAt: this.now()
|
||||
}
|
||||
this.state.rules = this.state.rules.map((item, at) => (at === index ? rule : item))
|
||||
this.persist()
|
||||
return structuredClone(rule)
|
||||
}
|
||||
|
||||
deleteRule(id: string): boolean {
|
||||
this.ensureLoaded()
|
||||
const key = String(id || '').trim()
|
||||
const before = this.state.rules.length
|
||||
this.state.rules = this.state.rules.filter((rule) => rule.id !== key)
|
||||
if (this.state.rules.length === before) return false
|
||||
this.persist()
|
||||
return true
|
||||
}
|
||||
|
||||
setRuleEnabled(id: string, enabled: boolean): AutomationRule | undefined {
|
||||
const rule = this.getRule(id)
|
||||
if (!rule) return undefined
|
||||
return this.updateRule(id, { ...rule, enabled: enabled === true })
|
||||
}
|
||||
|
||||
private ensureLoaded(): void {
|
||||
if (this.loaded) return
|
||||
this.loaded = true
|
||||
let stored: StoredRules
|
||||
try {
|
||||
stored = normalizeStored(fs.readJsonSync(this.rulesFilePath()) as unknown)
|
||||
} catch {
|
||||
stored = emptyState()
|
||||
}
|
||||
if (!stored.builtinSeeded) {
|
||||
stored.builtinSeeded = true
|
||||
stored.rules = [...stored.rules, createDefaultDailyReportRule(this.now())]
|
||||
}
|
||||
this.state = stored
|
||||
this.persist()
|
||||
}
|
||||
|
||||
private rulesFilePath(): string {
|
||||
return path.join(this.userDataPath(), STORAGE_DIR, RULES_FILE)
|
||||
}
|
||||
|
||||
private persist(): void {
|
||||
try {
|
||||
const filePath = this.rulesFilePath()
|
||||
fs.ensureDirSync(path.dirname(filePath))
|
||||
fs.writeJsonSync(filePath, this.state, { spaces: 2 })
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[Automation] 保存规则失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const automationRuleStore = new AutomationRuleStore()
|
||||
@@ -0,0 +1,422 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import {
|
||||
matchAutomationRule,
|
||||
type AutomationMatchInput
|
||||
} from '../../shared/automation-matcher'
|
||||
import type {
|
||||
AutomationExecution,
|
||||
AutomationRule,
|
||||
AutomationStatusSummary
|
||||
} from '../../shared/automation'
|
||||
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
|
||||
import type { Wcdb4Client } from '../wcdb4-client'
|
||||
import type { NormalizedIncomingMessage } from './message-listener-service'
|
||||
import { listContacts } from './chat-service'
|
||||
import { getPersonalWechatSendCapability } from './personal-wechat-capability-service'
|
||||
import {
|
||||
automationRuleStore,
|
||||
type AutomationRuleStore
|
||||
} from './automation-rule-store'
|
||||
import {
|
||||
automationExecutionLogService,
|
||||
type AutomationExecutionLogService
|
||||
} from './automation-execution-log-service'
|
||||
import {
|
||||
automationActionRunner,
|
||||
type AutomationActionRunner
|
||||
} from './automation-action-runner'
|
||||
|
||||
/**
|
||||
* AutomationService —— Automation v1 的编排层。
|
||||
*
|
||||
* ```text
|
||||
* MessageListener
|
||||
* ↓ NormalizedIncomingMessage
|
||||
* AutomationService.handleMessage
|
||||
* ↓ TriggerMatcher(shared,纯函数;规则编辑页的预览共用同一份)
|
||||
* ↓ cooldown → 同消息幂等 → 发送能力预检
|
||||
* AutomationActionRunner
|
||||
* ↓
|
||||
* Execution Log
|
||||
* ```
|
||||
*
|
||||
* 刻意不引入 EventBus / RxJS / MQ / 工作流引擎 —— 这条链路的每一步都是同步可读的。
|
||||
*
|
||||
* **防循环 / 防刷屏四道闸**(缺一不可):
|
||||
* 1. `isSelf` 防护:自己发的消息不触发(TriggerMatcher 内);
|
||||
* 2. MessageListener dedup:同一条消息不会重复投递;
|
||||
* 3. cooldown:同一规则 + 同一会话的最小间隔;
|
||||
* 4. 同消息幂等:`ruleId:sessionId:localId` 只执行一次。
|
||||
*
|
||||
* 第 1 条是关键:TraceMemo 回复的那句「收到,正在生成今日日报」本身含关键词「日报」,
|
||||
* 少了它就会自己触发自己,形成死循环。
|
||||
*/
|
||||
|
||||
/** 幂等登记表的存活时间与容量上限(与 MessageListener 的 dedup 同思路)。 */
|
||||
const CLAIM_TTL_MS = 10 * 60 * 1000
|
||||
const CLAIM_MAX_ENTRIES = 5_000
|
||||
/** 自己的 username 候选集缓存时长 —— 这个值几乎不变,没必要每条消息都查。 */
|
||||
const SELF_USERNAME_TTL_MS = 30_000
|
||||
|
||||
export interface AutomationServiceDependencies {
|
||||
ruleStore?: AutomationRuleStore
|
||||
executionLog?: AutomationExecutionLogService
|
||||
runner?: AutomationActionRunner
|
||||
getCapability?: () => Promise<PersonalWechatSendCapability>
|
||||
/** 由主进程注入:MessageListener 是否在运行。 */
|
||||
isListening?: () => boolean
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
interface ClaimEntry {
|
||||
at: number
|
||||
}
|
||||
|
||||
export class AutomationService {
|
||||
private readonly ruleStore: AutomationRuleStore
|
||||
private readonly executionLog: AutomationExecutionLogService
|
||||
private readonly runner: AutomationActionRunner
|
||||
private readonly getCapability: () => Promise<PersonalWechatSendCapability>
|
||||
private readonly isListening: () => boolean
|
||||
private readonly now: () => number
|
||||
|
||||
/** `ruleId:sessionId:localId` → 登记时间。 */
|
||||
private readonly claims = new Map<string, ClaimEntry>()
|
||||
/** `${ruleId}:${conversationId}` → 上次真正开始执行的毫秒时间戳。 */
|
||||
private readonly cooldowns = new Map<string, number>()
|
||||
|
||||
private selfUsernames: string[] = []
|
||||
private selfUsernamesAt = 0
|
||||
|
||||
constructor(
|
||||
private readonly client: Wcdb4Client,
|
||||
dependencies: AutomationServiceDependencies = {}
|
||||
) {
|
||||
this.ruleStore = dependencies.ruleStore ?? automationRuleStore
|
||||
this.executionLog = dependencies.executionLog ?? automationExecutionLogService
|
||||
this.runner = dependencies.runner ?? automationActionRunner
|
||||
this.getCapability = dependencies.getCapability ?? getPersonalWechatSendCapability
|
||||
this.isListening = dependencies.isListening ?? (() => true)
|
||||
this.now = dependencies.now ?? (() => Date.now())
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息入口。**绝不抛** —— 它挂在 MessageListener 的回调上,
|
||||
* 抛出去会影响后续监听者。
|
||||
*/
|
||||
async handleMessage(message: NormalizedIncomingMessage): Promise<void> {
|
||||
let rules: AutomationRule[]
|
||||
try {
|
||||
rules = this.ruleStore.listRules()
|
||||
} catch (error) {
|
||||
this.warn(`读取规则失败: ${errorText(error)}`)
|
||||
return
|
||||
}
|
||||
if (!rules.length) return
|
||||
|
||||
const selfUsernames = this.resolveSelfUsernames()
|
||||
const input: AutomationMatchInput = {
|
||||
...(message.content !== undefined ? { content: message.content } : {}),
|
||||
mentionTargets: message.mentionTargets,
|
||||
isSelf: message.isSelf,
|
||||
isGroup: message.isGroup,
|
||||
// conversationId 与规则里的 conversationIds 同口径:群为 `xxx@chatroom`。
|
||||
conversationId: message.sessionId
|
||||
}
|
||||
|
||||
for (const rule of rules) {
|
||||
let matched: boolean
|
||||
try {
|
||||
matched = matchAutomationRule(rule, input, selfUsernames).matched
|
||||
} catch (error) {
|
||||
this.warn(`规则匹配异常 ruleId=${rule.id}: ${errorText(error)}`)
|
||||
continue
|
||||
}
|
||||
if (!matched) continue
|
||||
|
||||
// 三道闸全部是**同步**的,必须在任何 await 之前完成登记,
|
||||
// 否则同一批并发消息会同时穿过检查。
|
||||
if (this.isCoolingDown(rule, message.sessionId)) continue
|
||||
if (!this.claim(rule, message)) continue
|
||||
|
||||
const sourceDisplayName = this.resolveDisplayName(message)
|
||||
await this.execute(rule, message, sourceDisplayName)
|
||||
}
|
||||
}
|
||||
|
||||
/** 顶部状态条数据。全部来自真实能力,不做渲染层平台猜测。 */
|
||||
async getStatus(): Promise<AutomationStatusSummary> {
|
||||
const now = this.now()
|
||||
const startOfToday = new Date(now)
|
||||
startOfToday.setHours(0, 0, 0, 0)
|
||||
const counts = this.executionLog.countSince(startOfToday.getTime())
|
||||
let capability: PersonalWechatSendCapability | null = null
|
||||
try {
|
||||
capability = await this.getCapability()
|
||||
} catch {
|
||||
capability = null
|
||||
}
|
||||
return {
|
||||
listening: this.isListening(),
|
||||
// 底层只能回读「最近活跃会话」(见 message-listener-service.ts 的 BLOCKER 注释),
|
||||
// UI 必须如实告知,不允许把它包装成「全局监听」。
|
||||
listeningDegraded: true,
|
||||
todayExecutions: counts.total,
|
||||
todaySuccesses: counts.success,
|
||||
sendCapability: {
|
||||
supported: Boolean(capability?.supported),
|
||||
ready: Boolean(capability?.ready),
|
||||
canSendText: Boolean(capability?.capabilities?.text),
|
||||
canSendImage: Boolean(capability?.capabilities?.image),
|
||||
message: capability?.message ?? '暂时无法获知微信发送能力'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 「在哪些聊天生效」的可选项。`id` 必须是 `xxx@chatroom`,与 message.sessionId 对齐。 */
|
||||
listGroups(): Array<{ id: string; name: string }> {
|
||||
try {
|
||||
return listContacts()
|
||||
.filter((contact) => contact.type === 'group' || contact.m_nsUsrName?.endsWith('@chatroom'))
|
||||
.map((contact) => ({
|
||||
id: String(contact.m_nsUsrName || ''),
|
||||
name: String(contact.m_nsNickName || contact.m_nsUsrName || '')
|
||||
}))
|
||||
.filter((group) => group.id)
|
||||
.sort((a, b) => a.name.localeCompare(b.name, 'zh-Hans-CN'))
|
||||
} catch (error) {
|
||||
this.warn(`读取群列表失败: ${errorText(error)}`)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 内部
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private async execute(
|
||||
rule: AutomationRule,
|
||||
message: NormalizedIncomingMessage,
|
||||
sourceDisplayName: string
|
||||
): Promise<void> {
|
||||
const executionId = randomUUID()
|
||||
const startedAt = this.now()
|
||||
const isGroup = message.isGroup
|
||||
|
||||
// 发送能力预检:环境发不出去时**不要执行**,直接留下一条说明清楚的失败记录。
|
||||
// 「假装规则正常运行」比直接报错更糟 —— 用户会以为发出去了。
|
||||
const missing = await this.checkSendCapability(rule, isGroup)
|
||||
if (missing) {
|
||||
this.executionLog.record(
|
||||
this.buildExecution({
|
||||
executionId,
|
||||
rule,
|
||||
startedAt,
|
||||
sourceDisplayName,
|
||||
status: 'failed',
|
||||
durationMs: this.now() - startedAt,
|
||||
steps: [],
|
||||
errorSummary: missing
|
||||
})
|
||||
)
|
||||
this.warn(`发送能力不足,跳过执行 ruleId=${rule.id} code=capability_missing`)
|
||||
return
|
||||
}
|
||||
|
||||
this.cooldowns.set(`${rule.id}:${message.sessionId}`, this.now())
|
||||
|
||||
let result: Awaited<ReturnType<AutomationActionRunner['run']>>
|
||||
try {
|
||||
result = await this.runner.run({
|
||||
executionId,
|
||||
rule,
|
||||
conversationId: message.sessionId,
|
||||
isGroup,
|
||||
sourceDisplayName
|
||||
})
|
||||
} catch (error) {
|
||||
result = {
|
||||
steps: [],
|
||||
status: 'failed',
|
||||
errorSummary: `执行过程异常:${errorText(error)}`
|
||||
}
|
||||
}
|
||||
|
||||
this.executionLog.record(
|
||||
this.buildExecution({
|
||||
executionId,
|
||||
rule,
|
||||
startedAt,
|
||||
sourceDisplayName,
|
||||
status: result.status,
|
||||
durationMs: this.now() - startedAt,
|
||||
steps: result.steps,
|
||||
...(result.errorSummary ? { errorSummary: result.errorSummary } : {})
|
||||
})
|
||||
)
|
||||
|
||||
// 隐私红线:日志里只允许出现 ruleId / executionId / 状态 / 耗时 / 步骤状态。
|
||||
// 群名、昵称、wxid、正文、source、文件路径一律不进日志。
|
||||
const trail = result.steps.map((step) => `${step.key}=${step.status}`).join(' ')
|
||||
this.info(
|
||||
`executed ruleId=${rule.id} executionId=${executionId} status=${result.status}` +
|
||||
` durationMs=${this.now() - startedAt}${trail ? ` ${trail}` : ''}`
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查当前环境是否具备规则所需的发送能力。
|
||||
*
|
||||
* 返回「缺失的能力」说明;返回 `undefined` 表示可以执行。
|
||||
* 私聊场景下 `sendReportImage` 同样受限,所以不做特殊豁免。
|
||||
*/
|
||||
private async checkSendCapability(
|
||||
rule: AutomationRule,
|
||||
isGroup: boolean
|
||||
): Promise<string | undefined> {
|
||||
const needsText = rule.actions.some((action) => action.type === 'replyText' && action.enabled)
|
||||
const needsImage = rule.actions.some(
|
||||
(action) => action.type === 'sendReportImage' && action.enabled
|
||||
)
|
||||
if (!needsText && !needsImage) return undefined
|
||||
|
||||
let capability: PersonalWechatSendCapability | null = null
|
||||
try {
|
||||
capability = await this.getCapability()
|
||||
} catch {
|
||||
return '暂时无法获知微信发送能力,已跳过本次执行'
|
||||
}
|
||||
if (!capability?.supported) {
|
||||
return capability?.message || '当前系统不支持微信消息发送'
|
||||
}
|
||||
const target = isGroup ? '群聊' : '联系人'
|
||||
if (needsText && !capability.capabilities?.text) {
|
||||
return `当前环境无法发送文字,已跳过本次执行(无法回复${target})`
|
||||
}
|
||||
if (needsImage && !capability.capabilities?.image) {
|
||||
return '当前环境无法发送图片,已跳过本次执行(无法发送日报)'
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
private buildExecution(input: {
|
||||
executionId: string
|
||||
rule: AutomationRule
|
||||
startedAt: number
|
||||
sourceDisplayName: string
|
||||
status: AutomationExecution['status']
|
||||
durationMs: number
|
||||
steps: AutomationExecution['steps']
|
||||
errorSummary?: string
|
||||
}): AutomationExecution {
|
||||
return {
|
||||
executionId: input.executionId,
|
||||
ruleId: input.rule.id,
|
||||
ruleName: input.rule.name,
|
||||
triggerTime: input.startedAt,
|
||||
sourceDisplayName: input.sourceDisplayName,
|
||||
status: input.status,
|
||||
durationMs: input.durationMs,
|
||||
steps: input.steps,
|
||||
...(input.errorSummary ? { errorSummary: input.errorSummary } : {})
|
||||
}
|
||||
}
|
||||
|
||||
private isCoolingDown(rule: AutomationRule, conversationId: string): boolean {
|
||||
const seconds = Number(rule.cooldownSeconds)
|
||||
if (!Number.isFinite(seconds) || seconds <= 0) return false
|
||||
const last = this.cooldowns.get(`${rule.id}:${conversationId}`)
|
||||
if (last === undefined) return false
|
||||
return this.now() - last < seconds * 1000
|
||||
}
|
||||
|
||||
/** 登记「这条消息已经被这条规则处理过」。返回 false 表示重复,应当跳过。 */
|
||||
private claim(rule: AutomationRule, message: NormalizedIncomingMessage): boolean {
|
||||
const key = `${rule.id}:${message.sessionId}:${message.localId}`
|
||||
const now = this.now()
|
||||
if (this.claims.has(key)) return false
|
||||
this.claims.set(key, { at: now })
|
||||
if (this.claims.size > CLAIM_MAX_ENTRIES) this.evictClaims(now)
|
||||
return true
|
||||
}
|
||||
|
||||
/** 先按 TTL 清理;仍超限则按插入顺序丢最旧的一批。 */
|
||||
private evictClaims(now: number): void {
|
||||
for (const [key, entry] of this.claims) {
|
||||
if (now - entry.at > CLAIM_TTL_MS) this.claims.delete(key)
|
||||
}
|
||||
if (this.claims.size <= CLAIM_MAX_ENTRIES) return
|
||||
const overflow = this.claims.size - CLAIM_MAX_ENTRIES
|
||||
let removed = 0
|
||||
for (const key of this.claims.keys()) {
|
||||
this.claims.delete(key)
|
||||
removed += 1
|
||||
if (removed >= overflow) break
|
||||
}
|
||||
}
|
||||
|
||||
private resolveSelfUsernames(): string[] {
|
||||
const now = this.now()
|
||||
if (this.selfUsernames.length && now - this.selfUsernamesAt < SELF_USERNAME_TTL_MS) {
|
||||
return this.selfUsernames
|
||||
}
|
||||
try {
|
||||
this.selfUsernames = (this.client.getMyUsernameCandidates?.() ?? []).filter(Boolean)
|
||||
this.selfUsernamesAt = now
|
||||
} catch (error) {
|
||||
this.warn(`读取自身 username 失败: ${errorText(error)}`)
|
||||
}
|
||||
return this.selfUsernames
|
||||
}
|
||||
|
||||
/**
|
||||
* 会话显示名。
|
||||
*
|
||||
* 拿不到会话昵称时**降级成「群聊 / 联系人」**,绝不回落到 wxid ——
|
||||
* 那个值一旦漏进执行日志就等于把隐私写进了用户可见的界面。
|
||||
*/
|
||||
private resolveDisplayName(message: NormalizedIncomingMessage): string {
|
||||
try {
|
||||
const session = this.client.getSessions().find((item) => item.username === message.sessionId)
|
||||
const nickname = String(session?.nickname || '').trim()
|
||||
if (nickname) return nickname
|
||||
} catch {
|
||||
// 忽略:走下面的通用降级名
|
||||
}
|
||||
return message.isGroup ? '群聊' : '联系人'
|
||||
}
|
||||
|
||||
/** 日志统一出口:只允许不可逆的运维信息,禁止任何身份信息。 */
|
||||
private info(message: string): void {
|
||||
console.log(`[Automation] ${message}`)
|
||||
}
|
||||
|
||||
private warn(message: string): void {
|
||||
console.warn(`[Automation] ${message}`)
|
||||
}
|
||||
}
|
||||
|
||||
function errorText(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
|
||||
let instance: AutomationService | null = null
|
||||
|
||||
/**
|
||||
* 主进程启动时调用一次。
|
||||
*
|
||||
* 用惰性初始化而不是模块级单例,是因为它需要 `Wcdb4Client`,
|
||||
* 而那个实例要等数据库解锁后才存在。
|
||||
*/
|
||||
export function initAutomationService(
|
||||
client: Wcdb4Client,
|
||||
dependencies: AutomationServiceDependencies = {}
|
||||
): AutomationService {
|
||||
instance = new AutomationService(client, dependencies)
|
||||
return instance
|
||||
}
|
||||
|
||||
export function getAutomationService(): AutomationService {
|
||||
if (!instance) throw new Error('AutomationService 尚未初始化')
|
||||
return instance
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
import { decompress as zstdDecompress } from 'fzstd'
|
||||
import type { Wcdb4Client, Wcdb4Message } from '../wcdb4-client'
|
||||
|
||||
/**
|
||||
* MessageListener —— 实时消息回读底座。
|
||||
*
|
||||
* **职责边界(刻意很窄)**:
|
||||
*
|
||||
* ```
|
||||
* WCDB native change
|
||||
* ↓
|
||||
* coalesce
|
||||
* ↓
|
||||
* bounded DB readback
|
||||
* ↓
|
||||
* dedup
|
||||
* ↓
|
||||
* NormalizedIncomingMessage → onMessage(callback)
|
||||
* ```
|
||||
*
|
||||
* **不负责**(这些属于下一层,本模块不许碰):关键词匹配、@我业务判断、日报、
|
||||
* 自动回复、AI 调用、Agent 调度、发送消息。
|
||||
*
|
||||
* 设计约束全部来自 2026-09-20 的真实环境 Spike(见
|
||||
* `.ai-local/reports/2026-09-20-realtime-message-spike-result.md`):
|
||||
* 一条真实消息平均触发 **≈17 个** native event,所以**绝不能**一个事件触发一次业务动作。
|
||||
*/
|
||||
|
||||
/** zstd 帧魔数(微信 `source` 列是 zstd 压缩)。 */
|
||||
const ZSTD_MAGIC = [0x28, 0xb5, 0x2f, 0xfd]
|
||||
|
||||
/**
|
||||
* coalesce 窗口。
|
||||
*
|
||||
* 实测同一批 native event 会**同时**到达(同一毫秒内十几个),所以只需要一个极短的
|
||||
* 合并窗口就能把它们收敛成一次回读。取 120ms:
|
||||
* - 足够吃掉同一批事件(实测事件间隔 < 5ms);
|
||||
* - 相对「event → 可读」本身就有 ~1.2s 的落库延迟,这点等待**不构成额外延迟**;
|
||||
* - 与项目既有 `wcdb-change` 消费端的 350ms debounce 相比更短,不会叠加成明显卡顿。
|
||||
*/
|
||||
const DEFAULT_COALESCE_MS = 120
|
||||
|
||||
/** 回读窗口:只看最近这么久,绝不扫历史。 */
|
||||
const DEFAULT_LOOKBACK_SEC = 30
|
||||
/** 未来容忍(时钟漂移 + 秒级取整)。 */
|
||||
const DEFAULT_LOOKAHEAD_SEC = 2
|
||||
/** 单次回读条数上限。 */
|
||||
const DEFAULT_READ_LIMIT = 50
|
||||
|
||||
/** dedup 条目存活时间:超过它就可以被淘汰(同一条消息不会在窗口外再被读到)。 */
|
||||
const DEFAULT_DEDUP_TTL_MS = 5 * 60 * 1000
|
||||
/** dedup 容量上限,防止长时间运行后无限增长。 */
|
||||
const DEFAULT_DEDUP_MAX_ENTRIES = 5_000
|
||||
|
||||
/**
|
||||
* 规范化后的入站消息。
|
||||
*
|
||||
* 刻意**克制**:只包含 Trigger 后续真正需要的字段,不做「万能 Message DTO」。
|
||||
* 原始行(`raw`)、未解压的 Buffer、头像等一律不往外传。
|
||||
*/
|
||||
export interface NormalizedIncomingMessage {
|
||||
sessionId: string
|
||||
/** 会话内序号。**单独不保证跨 shard 唯一**,去重必须带上 sessionId。 */
|
||||
localId: string
|
||||
/** 服务器侧全局标识。**可能缺失**,所以只作强标识、不作必需字段。 */
|
||||
serverId?: string
|
||||
/**
|
||||
* Unix **epoch 秒** —— 与 WCDB `create_time` / `getMessages` 参数同口径。
|
||||
*
|
||||
* ⚠️ 本项目另有模块使用 epoch 毫秒。**换算只允许集中在本层**:
|
||||
* 凡是需要毫秒的消费者,自己明确 `/1000` 的**唯一**位置就是这里之后的调用点,
|
||||
* 不许在任意函数里散落 `* 1000` / `/ 1000`。
|
||||
*/
|
||||
createTime: number
|
||||
messageType: number
|
||||
/** `mesDes === 0` 表示自己发送(字段语义与直觉相反)。 */
|
||||
isSelf: boolean
|
||||
senderId?: string
|
||||
senderNickname?: string
|
||||
content?: string
|
||||
/** **已解压**的 source XML;原始 zstd Buffer 不往外传。 */
|
||||
source?: string
|
||||
isGroup: boolean
|
||||
/**
|
||||
* 从 `source` 解析出的 @ 目标(**微信 username,不是昵称**)。
|
||||
*
|
||||
* 本轮只产出数据,**不做「是否 @ 我」的业务判断** —— 那需要与
|
||||
* `getMyUsernameCandidates()` 求交集,属于下一层。
|
||||
*/
|
||||
mentionTargets: string[]
|
||||
}
|
||||
|
||||
/** 监听统计(不含任何身份信息,可安全记录)。 */
|
||||
export interface MessageListenerStats {
|
||||
/** 收到的 native change event 数。 */
|
||||
nativeEvents: number
|
||||
/** 被 coalesce 合并掉的事件数(未单独触发回读)。 */
|
||||
coalescedEvents: number
|
||||
/** 实际执行的回读次数。 */
|
||||
readbacks: number
|
||||
/** 通过 dedup 并投递出去的消息数。 */
|
||||
delivered: number
|
||||
/** 因 dedup 被丢弃的重复投递数。 */
|
||||
deduped: number
|
||||
}
|
||||
|
||||
export interface MessageListenerOptions {
|
||||
coalesceMs?: number
|
||||
lookbackSec?: number
|
||||
lookaheadSec?: number
|
||||
readLimit?: number
|
||||
dedupTtlMs?: number
|
||||
dedupMaxEntries?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 `source`(**已解压的 XML 文本**)提取 @ 目标。
|
||||
*
|
||||
* 纯函数:不依赖任何运行时状态,便于单测。
|
||||
*
|
||||
* 实测两种形式都真实存在,**都必须支持**:
|
||||
* ```xml
|
||||
* <atuserlist><![CDATA[SELF_USERNAME]]></atuserlist>
|
||||
* <atuserlist>SELF_USERNAME</atuserlist>
|
||||
* ```
|
||||
*
|
||||
* ⚠️ 三条硬规则:
|
||||
* 1. **CDATA 外壳必须剥掉**,否则拿到的是 `<![CDATA[xxx]]>` 字面量;
|
||||
* 2. **值就是微信 username,不保证以 `wxid_` 开头** —— 绝不能用前缀做过滤/校验;
|
||||
* 3. **不允许多人分隔符的猜测** —— 多人 @ 的格式尚未在真实样本中验证过,
|
||||
* 这里按「单个值原样返回」处理;一旦拿到真实多人样本需补解析与测试
|
||||
* (当前形状已经预留为 `string[]`)。
|
||||
*/
|
||||
export function extractMentionTargets(source: string | undefined): string[] {
|
||||
const text = String(source ?? '')
|
||||
if (!text) return []
|
||||
const match = /<atuserlist>([\s\S]*?)<\/atuserlist>/i.exec(text)
|
||||
if (!match) return []
|
||||
const inner = match[1].trim()
|
||||
const unwrapped = inner.replace(/^<!\[CDATA\[/, '').replace(/\]\]>$/, '').trim()
|
||||
return unwrapped ? [unwrapped] : []
|
||||
}
|
||||
|
||||
/** 把 WCDB 的 `source` 列(zstd 压缩的 Buffer)还原成 XML 文本。 */
|
||||
export function decodeSourcePayload(value: unknown): string | undefined {
|
||||
let buffer: Buffer | null = null
|
||||
if (Buffer.isBuffer(value)) {
|
||||
buffer = value
|
||||
} else {
|
||||
const candidate = value as { type?: string; data?: unknown } | null
|
||||
if (candidate?.type === 'Buffer' && Array.isArray(candidate.data)) {
|
||||
buffer = Buffer.from(candidate.data as number[])
|
||||
}
|
||||
}
|
||||
if (!buffer || buffer.length === 0) return undefined
|
||||
const isZstd = ZSTD_MAGIC.every((byte, index) => buffer![index] === byte)
|
||||
if (!isZstd) return buffer.toString('utf8')
|
||||
try {
|
||||
return Buffer.from(zstdDecompress(buffer)).toString('utf8')
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 实时消息监听。
|
||||
*
|
||||
* ⚠️ **已知 BLOCKER(必须如实标注)**:
|
||||
* 本实现**无法从 native event 判断是哪个会话发生了变化** —— 事件 payload 只有
|
||||
* `{db, table, action}`(native 侧 `MonitorEvent` 结构就这两个字段)。
|
||||
* 因此当前策略是**回读「最近活跃会话」**(`sessions[0]`,按 `last_timestamp` 排序),
|
||||
* 这在「刚刚收到消息的会话」这一场景下成立,但:
|
||||
*
|
||||
* - **不是**「全局监听所有微信会话」;
|
||||
* - 若同一窗口内有**多个会话**同时来消息,只会回读到其中最近的那个;
|
||||
* - 正式扩展需要解决「如何从 table event 推断需要回读哪些会话」。
|
||||
*
|
||||
* 详见 `NEXT_STEPS` 注释与 Spike 报告。
|
||||
*/
|
||||
export class MessageListenerService {
|
||||
private readonly listeners = new Set<(message: NormalizedIncomingMessage) => void>()
|
||||
/**
|
||||
* dedup 缓存:`sessionId:localId` → 首次见到的时间戳。
|
||||
*
|
||||
* 必须有界 —— Spike 里用的是无上限 `Set`,长时间运行会持续吃内存。
|
||||
*/
|
||||
private readonly seen = new Map<string, number>()
|
||||
private coalesceTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private readbackInFlight = false
|
||||
private disposed = false
|
||||
|
||||
private readonly coalesceMs: number
|
||||
private readonly lookbackSec: number
|
||||
private readonly lookaheadSec: number
|
||||
private readonly readLimit: number
|
||||
private readonly dedupTtlMs: number
|
||||
private readonly dedupMaxEntries: number
|
||||
|
||||
private counters: MessageListenerStats = {
|
||||
nativeEvents: 0,
|
||||
coalescedEvents: 0,
|
||||
readbacks: 0,
|
||||
delivered: 0,
|
||||
deduped: 0
|
||||
}
|
||||
|
||||
constructor(
|
||||
private readonly client: Wcdb4Client,
|
||||
options: MessageListenerOptions = {}
|
||||
) {
|
||||
this.coalesceMs = options.coalesceMs ?? DEFAULT_COALESCE_MS
|
||||
this.lookbackSec = options.lookbackSec ?? DEFAULT_LOOKBACK_SEC
|
||||
this.lookaheadSec = options.lookaheadSec ?? DEFAULT_LOOKAHEAD_SEC
|
||||
this.readLimit = options.readLimit ?? DEFAULT_READ_LIMIT
|
||||
this.dedupTtlMs = options.dedupTtlMs ?? DEFAULT_DEDUP_TTL_MS
|
||||
this.dedupMaxEntries = options.dedupMaxEntries ?? DEFAULT_DEDUP_MAX_ENTRIES
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅新消息。返回取消订阅函数。
|
||||
*
|
||||
* 刻意**只提供回调**:当前规模不需要 EventEmitter / RxJS / 内部队列。
|
||||
*/
|
||||
onMessage(listener: (message: NormalizedIncomingMessage) => void): () => void {
|
||||
this.listeners.add(listener)
|
||||
return () => this.listeners.delete(listener)
|
||||
}
|
||||
|
||||
stats(): MessageListenerStats {
|
||||
return { ...this.counters }
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.disposed = true
|
||||
if (this.coalesceTimer) {
|
||||
clearTimeout(this.coalesceTimer)
|
||||
this.coalesceTimer = null
|
||||
}
|
||||
this.listeners.clear()
|
||||
this.seen.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* 接 native change event。
|
||||
*
|
||||
* 只做计数与 coalesce —— **绝不**在这里回读,更不触发任何业务。
|
||||
*/
|
||||
handleNativeChange(): void {
|
||||
if (this.disposed) return
|
||||
this.counters.nativeEvents += 1
|
||||
if (this.coalesceTimer) {
|
||||
// 已经在同一个窗口里:直接合并掉,这就是 17:1 那个比值的收敛点。
|
||||
this.counters.coalescedEvents += 1
|
||||
return
|
||||
}
|
||||
this.coalesceTimer = setTimeout(() => {
|
||||
this.coalesceTimer = null
|
||||
void this.readback()
|
||||
}, this.coalesceMs)
|
||||
}
|
||||
|
||||
/**
|
||||
* 有界回读 → normalize → dedup → 投递。
|
||||
*
|
||||
* 回读范围严格受限:**单会话** + **小时间窗口** + **条数上限**。
|
||||
* 不遍历会话、不扫全库。
|
||||
*/
|
||||
private async readback(): Promise<void> {
|
||||
if (this.disposed || this.readbackInFlight) return
|
||||
this.readbackInFlight = true
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
const nowSec = Math.floor(startedAt / 1000)
|
||||
const sessions = this.client.getSessions()
|
||||
const session = sessions[0]
|
||||
if (!session?.username) return
|
||||
|
||||
this.counters.readbacks += 1
|
||||
const messages = await this.client.getMessagesAsync(
|
||||
session.username,
|
||||
nowSec - this.lookbackSec,
|
||||
nowSec + this.lookaheadSec,
|
||||
{ limit: this.readLimit }
|
||||
)
|
||||
if (this.disposed) return
|
||||
|
||||
let delivered = 0
|
||||
for (const message of messages) {
|
||||
const normalized = this.normalize(session.username, message)
|
||||
if (!normalized) continue
|
||||
// dedup:同一条消息可能在多个读回窗口中反复出现。
|
||||
if (!this.markSeen(normalized)) {
|
||||
this.counters.deduped += 1
|
||||
continue
|
||||
}
|
||||
this.counters.delivered += 1
|
||||
delivered += 1
|
||||
this.deliver(normalized)
|
||||
}
|
||||
|
||||
if (delivered > 0) {
|
||||
// 日志只记录数量与耗时,**不含** wxid / 群名 / 昵称 / 正文 / source。
|
||||
console.log(
|
||||
`[MessageListener] delivered=${delivered} readbackMs=${Date.now() - startedAt}` +
|
||||
` sessionType=${session.username.endsWith('@chatroom') ? 'group' : 'direct'}` +
|
||||
` events=${this.counters.nativeEvents} coalesced=${this.counters.coalescedEvents}`
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[MessageListener] readback failed: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
} finally {
|
||||
this.readbackInFlight = false
|
||||
}
|
||||
}
|
||||
|
||||
private deliver(message: NormalizedIncomingMessage): void {
|
||||
for (const listener of this.listeners) {
|
||||
try {
|
||||
listener(message)
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[MessageListener] listener threw: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 把 WCDB 行规范化为克制的 DTO。返回 null 表示这条行缺关键标识,无法投递。 */
|
||||
private normalize(
|
||||
sessionUsername: string,
|
||||
message: Wcdb4Message
|
||||
): NormalizedIncomingMessage | null {
|
||||
const localId = message.mesLocalID === undefined ? '' : String(message.mesLocalID)
|
||||
if (!localId) return null
|
||||
|
||||
const createTime = Number(message.msgCreateTime) || 0
|
||||
if (!createTime) return null
|
||||
|
||||
const raw = (message.raw ?? {}) as Record<string, unknown>
|
||||
const source = decodeSourcePayload(raw.source)
|
||||
const senderId = message.sender ? String(message.sender) : undefined
|
||||
|
||||
return {
|
||||
sessionId: sessionUsername,
|
||||
localId,
|
||||
serverId: message.serverId ? String(message.serverId) : undefined,
|
||||
createTime,
|
||||
messageType: Number(message.messageType) || 0,
|
||||
// `mesDes === 0` 是自己发送。不用昵称 / sender 文本 / content / username 前缀判断。
|
||||
isSelf: Number(message.mesDes) === 0,
|
||||
senderId,
|
||||
senderNickname: message.senderNickname ? String(message.senderNickname) : undefined,
|
||||
content: message.msgContent ? String(message.msgContent) : undefined,
|
||||
source,
|
||||
isGroup: sessionUsername.endsWith('@chatroom'),
|
||||
mentionTargets: extractMentionTargets(source)
|
||||
}
|
||||
}
|
||||
|
||||
/** 登记并返回「是否是第一次见到」。同时做 TTL + 容量淘汰。 */
|
||||
private markSeen(message: NormalizedIncomingMessage): boolean {
|
||||
const key = `${message.sessionId}:${message.localId}`
|
||||
const now = Date.now()
|
||||
if (this.seen.has(key)) return false
|
||||
|
||||
this.seen.set(key, now)
|
||||
if (this.seen.size > this.dedupMaxEntries) this.evict(now)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 淘汰策略:先按 TTL 清理过期条目;若仍然超限,再按插入顺序丢掉最旧的一批
|
||||
* (Map 保持插入顺序,所以从头删就是删最旧)。
|
||||
*/
|
||||
private evict(now: number): void {
|
||||
for (const [key, seenAt] of this.seen) {
|
||||
if (now - seenAt > this.dedupTtlMs) this.seen.delete(key)
|
||||
}
|
||||
if (this.seen.size <= this.dedupMaxEntries) return
|
||||
const overflow = this.seen.size - this.dedupMaxEntries
|
||||
let removed = 0
|
||||
for (const key of this.seen.keys()) {
|
||||
this.seen.delete(key)
|
||||
removed += 1
|
||||
if (removed >= overflow) break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* NEXT STEPS(不在本轮范围)
|
||||
*
|
||||
* 1. **会话定位(BLOCKER)**:目前只能回读「最近活跃会话」。要真正监听全部会话,
|
||||
* 需要解决「从 table event 推断变更会话」。可能的路线:
|
||||
* - 观察 native 侧能否在事件里补上 table 所属的会话标识(需改 dll);
|
||||
* - 或改成按 `Session` 表的 `last_timestamp` 变化做「有界的多会话回读」。
|
||||
* 2. **多人 @**:`extractMentionTargets` 目前按单值返回,多人格式**未验证**,不得猜分隔符。
|
||||
* 3. **isMentionedMe**:`mentionTargets` ∩ `getMyUsernameCandidates()`,再接 Trigger。
|
||||
* 4. 本轮**不做**:关键词 / @触发 / 自动回复 / 日报 / AI / Agent / 发送。
|
||||
*/
|
||||
@@ -22,7 +22,15 @@ import { wechatSendGateway } from './wechat-send-gateway'
|
||||
const MAX_AUDIT_RECORDS = 500
|
||||
const MAX_CONTENT_PREVIEW_LENGTH = 240
|
||||
export const AUTOMATION_SEND_INTERVAL_MS = 3_000
|
||||
const AUTOMATION_PURPOSE_ALLOWLIST = new Set(['scheduled_report', 'member_left_notification'])
|
||||
const AUTOMATION_PURPOSE_ALLOWLIST = new Set([
|
||||
'scheduled_report',
|
||||
'member_left_notification',
|
||||
// Automation v1(@我生成日报)。必须与 `src/shared/automation.ts` 的
|
||||
// `AUTOMATION_SEND_PURPOSE` 保持一致,否则会被下面 evaluateWechatActionPolicy
|
||||
// 以 ACTION_NOT_ALLOWED 拦下 —— 那是有意的闸门,不是 bug。
|
||||
'automation_reply',
|
||||
'automation_report'
|
||||
])
|
||||
|
||||
export interface WechatActionGatewayDependencies {
|
||||
getCapability?: () => Promise<PersonalWechatSendCapability>
|
||||
|
||||
Reference in new issue
Block a user