mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: 增加消息事件 SSE 订阅与 WorkBuddy 任务接入
- 实时事件代理与 SSE 订阅:断线重放、有界数据库回补、多订阅者 - WorkBuddy /ai 任务投递:默认禁用、白名单、任务幂等与状态持久化
This commit is contained in:
1 parent
bc3a560830
commit
0edbf60b2e
16 files changed
+3987
-44
No files matched your search
@@ -47,6 +47,14 @@ import type {
|
||||
VoiceTranscriptState
|
||||
} from '../shared/voice-recognition'
|
||||
import { voiceMessageReferenceOf } from './voice-pipeline/voice-message-identity'
|
||||
import type {
|
||||
MessageBrokerStatus,
|
||||
MessageEventBroker,
|
||||
MessageEventRecord,
|
||||
MessageGap,
|
||||
MessageSubscription
|
||||
} from './services/message-event-broker'
|
||||
import type { AgentTaskRecord, AgentTaskView } from '../shared/agent-task'
|
||||
|
||||
export const DEFAULT_HTTP_HOST = '127.0.0.1'
|
||||
export const DEFAULT_HTTP_PORT = 6131
|
||||
@@ -83,14 +91,41 @@ export interface HttpServerOptions {
|
||||
appVersionProvider?: () => string
|
||||
wechatSendCapabilityProvider?: () => Promise<PersonalWechatSendCapability>
|
||||
wechatSendExecutor?: (request: WechatActionRequest) => Promise<WechatActionResult>
|
||||
/** 实时消息事件代理。未注入时 `/api/v1/events/messages` 返回 503。 */
|
||||
messageEventBroker?: MessageEventBroker
|
||||
/** SSE 心跳间隔(毫秒)。测试用;生产默认 15s。 */
|
||||
messageEventsHeartbeatMs?: number
|
||||
}
|
||||
|
||||
let configuredQueryApiService: LocalQueryApiService | undefined
|
||||
let configuredGroupStatsService: Pick<GroupStatsService, 'getMemberStats'> | undefined
|
||||
let configuredMessageEventBroker: MessageEventBroker | undefined
|
||||
export function setLocalQueryApiService(service: LocalQueryApiService | undefined): void {
|
||||
configuredQueryApiService = service
|
||||
}
|
||||
|
||||
/**
|
||||
* 注入实时消息事件代理。
|
||||
*
|
||||
* 刻意用模块级注入而不是每次 `startHttpServer` 传参:API server 可能在数据库
|
||||
* 初始化之前启动,事件代理必须在数据库就绪前就存在,才能在 SSE 里如实报告
|
||||
* `database: unavailable` 而不是把连接直接打回 503。
|
||||
*/
|
||||
export function setMessageEventBroker(broker: MessageEventBroker | undefined): void {
|
||||
configuredMessageEventBroker = broker
|
||||
}
|
||||
|
||||
export interface AgentTaskInspector {
|
||||
list(limit: number): AgentTaskRecord[]
|
||||
get(id: string): AgentTaskRecord | undefined
|
||||
}
|
||||
|
||||
let configuredAgentTaskInspector: AgentTaskInspector | undefined
|
||||
/** 注入只读任务视图。写入仍由 AgentTaskDispatcher 独占。 */
|
||||
export function setAgentTaskInspector(inspector: AgentTaskInspector | undefined): void {
|
||||
configuredAgentTaskInspector = inspector
|
||||
}
|
||||
|
||||
export function setLocalGroupStatsService(
|
||||
service: Pick<GroupStatsService, 'getMemberStats'> | undefined
|
||||
): void {
|
||||
@@ -1364,6 +1399,263 @@ function createAgentApiRoute(
|
||||
})
|
||||
}
|
||||
|
||||
const MESSAGE_EVENTS_ROUTE = '/api/v1/events/messages'
|
||||
const AGENT_TASKS_ROUTE = '/api/v1/agent-tasks'
|
||||
const DEFAULT_MESSAGE_EVENTS_HEARTBEAT_MS = 15_000
|
||||
const MESSAGE_EVENTS_MAX_FILTERS = 20
|
||||
|
||||
/** SSE 连接句柄:`close` 优雅结束,`destroy` 用于服务停止时强制释放。 */
|
||||
interface MessageEventStreamHandle {
|
||||
close(): void
|
||||
destroy(): void
|
||||
}
|
||||
|
||||
function writeSseFrame(
|
||||
res: ServerResponse,
|
||||
frame: { id?: string; event?: string; data?: unknown }
|
||||
): boolean {
|
||||
try {
|
||||
let text = ''
|
||||
if (frame.id) text += `id: ${frame.id}\n`
|
||||
if (frame.event) text += `event: ${frame.event}\n`
|
||||
if (frame.data !== undefined) text += `data: ${JSON.stringify(frame.data)}\n`
|
||||
res.write(`${text}\n`)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析会话过滤参数。
|
||||
*
|
||||
* 只接受 `conversation_id` / `conversation_ids`(可重复、可逗号分隔),
|
||||
* 值必须是会话 md5 —— 与 `messageRef.c` 同口径。username 不接受:
|
||||
* 事件层无法把 username 当作稳定会话标识交给下游。
|
||||
*/
|
||||
function parseConversationFilter(url: URL): string[] {
|
||||
const raw = [
|
||||
...url.searchParams.getAll('conversation_id'),
|
||||
...url.searchParams.getAll('conversation_ids')
|
||||
]
|
||||
const ids: string[] = []
|
||||
for (const value of raw) {
|
||||
for (const part of value.split(',')) {
|
||||
const trimmed = part.trim()
|
||||
if (!trimmed) continue
|
||||
if (!/^[A-Za-z0-9_-]{1,128}$/.test(trimmed)) {
|
||||
throw new Error('会话标识格式无效:需要 conversation md5')
|
||||
}
|
||||
if (!ids.includes(trimmed)) ids.push(trimmed)
|
||||
}
|
||||
}
|
||||
if (ids.length > MESSAGE_EVENTS_MAX_FILTERS) {
|
||||
throw new Error(`conversation_id 最多 ${MESSAGE_EVENTS_MAX_FILTERS} 个`)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
function createMessageEventsRoute(
|
||||
pathname: string,
|
||||
brokerProvider: () => MessageEventBroker | undefined,
|
||||
trackStream: (handle: MessageEventStreamHandle) => () => void,
|
||||
heartbeatMs: number
|
||||
): RouteHandler | undefined {
|
||||
if (pathname !== MESSAGE_EVENTS_ROUTE) return undefined
|
||||
|
||||
return withMethods(['GET'], async ({ req, res, url }) => {
|
||||
const broker = brokerProvider()
|
||||
if (!broker) {
|
||||
return sendJson(res, 503, {
|
||||
error: 'events_unavailable',
|
||||
message: '实时消息事件服务尚未就绪'
|
||||
})
|
||||
}
|
||||
|
||||
let conversationIds: string[]
|
||||
try {
|
||||
conversationIds = parseConversationFilter(url)
|
||||
} catch (error) {
|
||||
return sendError(res, 400, error instanceof Error ? error.message : String(error))
|
||||
}
|
||||
|
||||
const headerLastEventId = req.headers['last-event-id']
|
||||
const lastEventId =
|
||||
(typeof headerLastEventId === 'string' ? headerLastEventId : undefined) ||
|
||||
url.searchParams.get('last_event_id') ||
|
||||
undefined
|
||||
const backfillEnabled = url.searchParams.get('backfill') !== '0'
|
||||
const filterMode = conversationIds.length > 0 ? 'conversation' : 'all'
|
||||
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||||
'Cache-Control': 'no-cache, no-transform',
|
||||
Connection: 'keep-alive',
|
||||
'X-Accel-Buffering': 'no',
|
||||
'X-Request-Id': String(res.getHeader('X-Request-Id') || '')
|
||||
})
|
||||
res.flushHeaders?.()
|
||||
req.socket?.setNoDelay(true)
|
||||
// 重连间隔由服务端给出,客户端不必自己猜。
|
||||
res.write('retry: 3000\n\n')
|
||||
|
||||
let closed = false
|
||||
let subscription: MessageSubscription | null = null
|
||||
let heartbeat: ReturnType<typeof setInterval> | null = null
|
||||
let untrack: (() => void) | null = null
|
||||
|
||||
const cleanup = (): void => {
|
||||
if (closed) return
|
||||
closed = true
|
||||
if (heartbeat) {
|
||||
clearInterval(heartbeat)
|
||||
heartbeat = null
|
||||
}
|
||||
subscription?.close()
|
||||
untrack?.()
|
||||
try {
|
||||
res.end()
|
||||
} catch {
|
||||
// 连接可能已经被对端关掉,这里只是幂等收尾。
|
||||
}
|
||||
}
|
||||
|
||||
const destroy = (): void => {
|
||||
cleanup()
|
||||
try {
|
||||
res.destroy()
|
||||
} catch {
|
||||
// 同上。
|
||||
}
|
||||
}
|
||||
|
||||
untrack = trackStream({ close: cleanup, destroy })
|
||||
req.on('close', cleanup)
|
||||
res.on('close', cleanup)
|
||||
res.on('error', cleanup)
|
||||
|
||||
try {
|
||||
subscription = broker.subscribe(
|
||||
{ conversationIds, lastEventId, backfill: backfillEnabled },
|
||||
{
|
||||
onStatus(status: MessageBrokerStatus & { subscriptionId: string }) {
|
||||
writeSseFrame(res, {
|
||||
event: 'status',
|
||||
data: {
|
||||
...status,
|
||||
filter: filterMode,
|
||||
conversationCount: conversationIds.length,
|
||||
heartbeatMs,
|
||||
backfill: backfillEnabled ? 'enabled' : 'disabled'
|
||||
}
|
||||
})
|
||||
},
|
||||
onEvent(event: MessageEventRecord, origin: 'live' | 'replay' | 'db_backfill') {
|
||||
if (closed) return
|
||||
if (
|
||||
!writeSseFrame(res, {
|
||||
id: String(event.seq),
|
||||
event: 'message',
|
||||
data: { ...event, origin }
|
||||
})
|
||||
) {
|
||||
cleanup()
|
||||
}
|
||||
},
|
||||
onGap(gap: MessageGap) {
|
||||
writeSseFrame(res, { event: 'gap', data: gap })
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
writeSseFrame(res, {
|
||||
event: 'error',
|
||||
data: {
|
||||
error: 'too_many_subscribers',
|
||||
message: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
})
|
||||
cleanup()
|
||||
return
|
||||
}
|
||||
|
||||
let lastDatabase = broker.status().database
|
||||
heartbeat = setInterval(() => {
|
||||
if (closed) return
|
||||
res.write(`: heartbeat ${Date.now()}\n\n`)
|
||||
/*
|
||||
* 数据库断开/重连不是错误,是订阅状态的一部分:
|
||||
* 只在这个状态真的变化时补发一条 status,避免每 15s 刷一次无信息事件。
|
||||
*/
|
||||
const nextDatabase = broker.status().database
|
||||
if (nextDatabase !== lastDatabase) {
|
||||
lastDatabase = nextDatabase
|
||||
writeSseFrame(res, {
|
||||
event: 'status',
|
||||
data: { ...broker.status(), subscriptionId: subscription?.id ?? '', filter: filterMode }
|
||||
})
|
||||
}
|
||||
}, heartbeatMs)
|
||||
heartbeat.unref?.()
|
||||
})
|
||||
}
|
||||
|
||||
/** 记录 → 对外视图。`triggerKey` 属于内部幂等键,不对外暴露。 */
|
||||
function toAgentTaskView(record: AgentTaskRecord): AgentTaskView {
|
||||
return {
|
||||
id: record.id,
|
||||
provider: record.provider,
|
||||
conversationId: record.conversationId,
|
||||
status: record.status,
|
||||
prompt: record.prompt,
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt,
|
||||
...(record.submittedAt !== undefined ? { submittedAt: record.submittedAt } : {}),
|
||||
...(record.completedAt !== undefined ? { completedAt: record.completedAt } : {}),
|
||||
...(record.externalMessageId ? { externalMessageId: record.externalMessageId } : {}),
|
||||
...(record.errorKind ? { errorKind: record.errorKind } : {}),
|
||||
...(record.errorMessage ? { errorMessage: record.errorMessage } : {}),
|
||||
replies: record.replies
|
||||
}
|
||||
}
|
||||
|
||||
function createAgentTaskRoute(
|
||||
pathname: string,
|
||||
inspectorProvider: () => AgentTaskInspector | undefined
|
||||
): RouteHandler | undefined {
|
||||
if (pathname === AGENT_TASKS_ROUTE) {
|
||||
return withMethods(['GET'], ({ res, url }) => {
|
||||
const inspector = inspectorProvider()
|
||||
if (!inspector) return sendError(res, 503, '任务服务尚未就绪')
|
||||
const requested = Number(url.searchParams.get('limit') ?? '20')
|
||||
const limit = Number.isFinite(requested)
|
||||
? Math.max(1, Math.min(Math.floor(requested), 100))
|
||||
: 20
|
||||
const tasks = inspector.list(limit).map(toAgentTaskView)
|
||||
sendJson(res, 200, { count: tasks.length, tasks })
|
||||
})
|
||||
}
|
||||
|
||||
const prefix = `${AGENT_TASKS_ROUTE}/`
|
||||
if (!pathname.startsWith(prefix)) return undefined
|
||||
const rawId = pathname.slice(prefix.length)
|
||||
if (!rawId || rawId.includes('/')) return undefined
|
||||
|
||||
return withMethods(['GET'], ({ res }) => {
|
||||
const inspector = inspectorProvider()
|
||||
if (!inspector) return sendError(res, 503, '任务服务尚未就绪')
|
||||
let id: string
|
||||
try {
|
||||
id = decodeURIComponent(rawId)
|
||||
} catch {
|
||||
return sendError(res, 400, '任务 ID 无效')
|
||||
}
|
||||
const task = inspector.get(id)
|
||||
if (!task) return sendError(res, 404, '任务不存在')
|
||||
sendJson(res, 200, { task: toAgentTaskView(task) })
|
||||
})
|
||||
}
|
||||
|
||||
function requestIdFor(req: IncomingMessage): string {
|
||||
const incoming = req.headers['x-request-id']
|
||||
return typeof incoming === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(incoming)
|
||||
@@ -1396,6 +1688,13 @@ export function startHttpServer(
|
||||
(() => personalWechatCapabilityService.getPersonalWechatSendCapability()),
|
||||
execute: options.wechatSendExecutor || ((request) => wechatActionGateway.execute(request))
|
||||
}
|
||||
const messageEventBroker = options.messageEventBroker
|
||||
? () => options.messageEventBroker
|
||||
: () => configuredMessageEventBroker
|
||||
const messageEventsHeartbeatMs =
|
||||
options.messageEventsHeartbeatMs ?? DEFAULT_MESSAGE_EVENTS_HEARTBEAT_MS
|
||||
/** 活着的 SSE 连接。`server.close()` 会等长连接自然结束,必须先主动释放。 */
|
||||
const eventStreams = new Set<MessageEventStreamHandle>()
|
||||
return new Promise((resolve, reject) => {
|
||||
const server: Server = http.createServer(async (req, res) => {
|
||||
const requestId = requestIdFor(req)
|
||||
@@ -1419,6 +1718,16 @@ export function startHttpServer(
|
||||
createAgentApiRoute(url.pathname, agentApi) ||
|
||||
createWechatSendRoute(url.pathname, wechatSendApi) ||
|
||||
createScheduledReportRoute(url.pathname, scheduledReportApi) ||
|
||||
createMessageEventsRoute(
|
||||
url.pathname,
|
||||
messageEventBroker,
|
||||
(handle) => {
|
||||
eventStreams.add(handle)
|
||||
return () => eventStreams.delete(handle)
|
||||
},
|
||||
messageEventsHeartbeatMs
|
||||
) ||
|
||||
createAgentTaskRoute(url.pathname, () => configuredAgentTaskInspector) ||
|
||||
(url.pathname.startsWith(QUERY_ROUTE_PREFIX)
|
||||
? createQueryRoute(url.pathname, queryApi)
|
||||
: undefined) ||
|
||||
@@ -1503,6 +1812,9 @@ export function startHttpServer(
|
||||
}
|
||||
// HTTP keep-alive 或长连接会阻塞 server.close(),退出时主动断开全部连接。
|
||||
const timer = setTimeout(finish, 1_500)
|
||||
// SSE 是长连接:先按订阅句柄释放,再交给 server.close 收尾。
|
||||
for (const stream of eventStreams) stream.destroy()
|
||||
eventStreams.clear()
|
||||
server.close(() => finish())
|
||||
server.closeIdleConnections?.()
|
||||
server.closeAllConnections?.()
|
||||
|
||||
+120
-1
@@ -82,9 +82,11 @@ import { KeyService as KeyServiceWin } from './key-service-win'
|
||||
import * as chat from './services/chat-service'
|
||||
import {
|
||||
apiServer,
|
||||
setAgentTaskInspector,
|
||||
setLocalGroupStatsService,
|
||||
setLocalQueryApiService,
|
||||
setLocalVoiceTranscriptSnapshotProvider
|
||||
setLocalVoiceTranscriptSnapshotProvider,
|
||||
setMessageEventBroker
|
||||
} from './http-server'
|
||||
import { skillResourceService } from './services/skill-resource-service'
|
||||
import { buildLocalApiCurlCommand, testLocalApiRequest } from './services/local-api-test-service'
|
||||
@@ -187,6 +189,14 @@ import {
|
||||
configureWechatLocalExitNotice,
|
||||
wechatLocalExitNoticeService
|
||||
} from './services/wechat-local-exit-notice-service'
|
||||
import { MessageEventBroker } from './services/message-event-broker'
|
||||
import { AgentTaskDispatcher } from './services/agent-task-dispatcher'
|
||||
import { AgentTaskStore } from './services/agent-task-store'
|
||||
import {
|
||||
loadWorkBuddyAgentSettings,
|
||||
loadWorkBuddyCredentials
|
||||
} from './services/agent-task-config'
|
||||
import { WorkBuddyAgentTaskProvider } from './services/workbuddy-agent-provider'
|
||||
|
||||
/** 「微信内退群监控消息」覆盖的群聊数(开关卡片的范围说明用,不是覆盖率)。 */
|
||||
function exitNoticeGroupCount(): number {
|
||||
@@ -691,6 +701,90 @@ let recallArchiveMonitor: RecallArchiveMonitor | null = null
|
||||
let recallProtectionGeneration = 0
|
||||
let recallJournalTimer: NodeJS.Timeout | null = null
|
||||
let wcdbBootstrapPromise: Promise<unknown> | null = null
|
||||
|
||||
/**
|
||||
* 会话 username → md5。
|
||||
*
|
||||
* `messageRef` 的 `c` 字段是 **contact.md5**(见 `local-query-api-service` 的
|
||||
* `toQueryMessage(contact.md5, ...)`),而 MessageListener 只持有 username。
|
||||
* 事件层必须在这里换一次,否则发出去的 messageRef 无法被
|
||||
* `/api/v1/query/message-context` 反查到会话。
|
||||
*/
|
||||
function resolveConversationMd5(sessionId: string): string | undefined {
|
||||
try {
|
||||
return chat.getChatDb()?.getWcdb4Client()?.md5(sessionId) || undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
let messageEventBroker: MessageEventBroker | null = null
|
||||
|
||||
/**
|
||||
* 实时事件代理(单例)。
|
||||
*
|
||||
* 复用 MessageListener 已经产生的事件,**不监听数据库**——数据库监控只有
|
||||
* `startMonitor` 一处。DB 句柄通过 `chat.getChatDb()` 动态取得,
|
||||
* 所以切账号 / 重连后不需要重建 broker,已有 SSE 订阅也不会被切断。
|
||||
*/
|
||||
function ensureMessageEventBroker(): MessageEventBroker {
|
||||
if (messageEventBroker) return messageEventBroker
|
||||
messageEventBroker = new MessageEventBroker({
|
||||
resolveConversationId: resolveConversationMd5,
|
||||
isDatabaseReady: () => chat.isReady(),
|
||||
readMessages: async (sessionIdOrMd5, startTimeSec, endTimeSec, limit) => {
|
||||
const client = chat.getChatDb()?.getWcdb4Client()
|
||||
if (!client) return []
|
||||
return client.getMessagesAsync(sessionIdOrMd5, startTimeSec, endTimeSec, { limit })
|
||||
},
|
||||
resolveSessionId: (conversationId) => {
|
||||
const client = chat.getChatDb()?.getWcdb4Client()
|
||||
if (!client) return undefined
|
||||
try {
|
||||
return client.getSessions().find((session) => client.md5(session.username) === conversationId)
|
||||
?.username
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
})
|
||||
setMessageEventBroker(messageEventBroker)
|
||||
return messageEventBroker
|
||||
}
|
||||
|
||||
let agentTaskDispatcher: AgentTaskDispatcher | null = null
|
||||
|
||||
/**
|
||||
* `/ai` 任务投递。
|
||||
*
|
||||
* 配置默认 `enabled: false`;没有白名单会话时**不处理任何消息**。
|
||||
* 凭证只从环境变量读取,缺凭证时任务会被记成 `auth_failed`,不会静默跳过。
|
||||
*/
|
||||
function ensureAgentTaskDispatcher(): AgentTaskDispatcher {
|
||||
if (agentTaskDispatcher) return agentTaskDispatcher
|
||||
const settings = loadWorkBuddyAgentSettings()
|
||||
const store = new AgentTaskStore({
|
||||
filePath: path.join(app.getPath('userData'), 'agent-tasks.json')
|
||||
})
|
||||
const dispatcher = new AgentTaskDispatcher({
|
||||
settings,
|
||||
store,
|
||||
provider: new WorkBuddyAgentTaskProvider({
|
||||
baseUrl: settings.baseUrl,
|
||||
timeoutMs: settings.timeoutMs,
|
||||
credentials: loadWorkBuddyCredentials()
|
||||
}),
|
||||
resolveConversationId: resolveConversationMd5
|
||||
})
|
||||
setAgentTaskInspector({
|
||||
list: (limit) => store.list(limit),
|
||||
get: (id) => store.get(id)
|
||||
})
|
||||
if (settings.enabled) dispatcher.start()
|
||||
agentTaskDispatcher = dispatcher
|
||||
return dispatcher
|
||||
}
|
||||
|
||||
type ColdImageLoadItem = {
|
||||
priority: number
|
||||
sequence: number
|
||||
@@ -1113,6 +1207,10 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
|
||||
}
|
||||
|
||||
try {
|
||||
// 事件代理必须在数据库初始化之前就存在:API server 可能先启动,
|
||||
// 此时 SSE 应当能如实报告 database=unavailable,而不是把连接打回 503。
|
||||
ensureMessageEventBroker()
|
||||
ensureAgentTaskDispatcher()
|
||||
const migration = isUserDataIsolated ? null : await runFirstLaunchMigration(appDataRoots)
|
||||
apiTokenStore.setAutomaticGenerationBlocked(migration?.tokenBlockReason)
|
||||
if (!migration) {
|
||||
@@ -1746,6 +1844,27 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
|
||||
` group=${message.isGroup} self=${message.isSelf}` +
|
||||
` mentions=${message.mentionTargets.length}`
|
||||
)
|
||||
/*
|
||||
* 实时事件是 Automation 之外的第二个消费者,两者互不依赖:
|
||||
* broker 只搬运已经回读并规范化的消息,不触发自动化、不调 AI。
|
||||
* 放在 Automation 之前,保证后者异常不会让 SSE 订阅者漏事件。
|
||||
*/
|
||||
ensureMessageEventBroker().publish(message)
|
||||
try {
|
||||
void agentTaskDispatcher?.handleMessage(message).catch((error) => {
|
||||
console.warn(
|
||||
`[AgentTask] handleMessage failed: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
})
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[AgentTask] 未初始化,已跳过本次消息: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
}
|
||||
// Automation 自带 isSelf / cooldown / 同消息幂等三重闸,不会形成回复循环。
|
||||
// 用 try 包住同步那一段:`getAutomationService()` 在未初始化时会抛,
|
||||
// 而 `.catch()` 只能接住异步拒绝 —— 漏了这层就会把异常抛进 MessageListener 的投递循环。
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { app } from 'electron'
|
||||
|
||||
/**
|
||||
* WorkBuddy Agent 接入配置。
|
||||
*
|
||||
* **默认禁用**:`enabled` 为 false 时 dispatcher 不读任何消息,也不会做在线检测。
|
||||
*
|
||||
* 配置来源(只认这两种):
|
||||
* 1. `<userData>/workbuddy-agent.json` —— 非敏感开关;
|
||||
* 2. 环境变量 —— **只放凭证**,不落盘、不进 Git、不进日志。
|
||||
*
|
||||
* 配置文件里出现的 `accessToken` / `clientSecret` 等字段会被忽略:
|
||||
* 凭证的唯一合法入口是环境变量,避免用户把 secret 写进可同步的目录。
|
||||
*/
|
||||
|
||||
export interface WorkBuddyAgentSettings {
|
||||
enabled: boolean
|
||||
/** 允许触发 `/ai` 的会话 md5 白名单;为空 = 不触发任何会话。 */
|
||||
allowedConversations: string[]
|
||||
/** 命令前缀,默认 `/ai`。只接受「前缀 + 空白」或整条等于前缀。 */
|
||||
commandPrefix: string
|
||||
baseUrl: string
|
||||
timeoutMs: number
|
||||
pollIntervalMs: number
|
||||
/** 单任务最长等待回复时间(毫秒)。超时后状态置 `timeout`,不再轮询。 */
|
||||
maxPollDurationMs: number
|
||||
}
|
||||
|
||||
export interface WorkBuddyCredentials {
|
||||
accessToken?: string
|
||||
refreshToken?: string
|
||||
clientId?: string
|
||||
clientSecret?: string
|
||||
}
|
||||
|
||||
export const WORKBUDDY_AGENT_CONFIG_FILE = 'workbuddy-agent.json'
|
||||
|
||||
export const DEFAULT_WORKBUDDY_AGENT_SETTINGS: WorkBuddyAgentSettings = Object.freeze({
|
||||
enabled: false,
|
||||
allowedConversations: [],
|
||||
commandPrefix: '/ai',
|
||||
baseUrl: 'https://www.workbuddy.cn',
|
||||
timeoutMs: 15_000,
|
||||
pollIntervalMs: 3_000,
|
||||
maxPollDurationMs: 120_000
|
||||
})
|
||||
|
||||
function asString(value: unknown, fallback: string): string {
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : fallback
|
||||
}
|
||||
|
||||
function asPositiveInt(value: unknown, fallback: number, max: number): number {
|
||||
const parsed = typeof value === 'number' ? value : Number(value)
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) return fallback
|
||||
return Math.min(Math.floor(parsed), max)
|
||||
}
|
||||
|
||||
function asConversationList(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) return []
|
||||
const ids: string[] = []
|
||||
for (const item of value) {
|
||||
if (typeof item !== 'string') continue
|
||||
const trimmed = item.trim()
|
||||
if (!trimmed || ids.includes(trimmed)) continue
|
||||
ids.push(trimmed)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
export function resolveWorkBuddyAgentConfigPath(userDataDir?: string): string {
|
||||
const root = userDataDir || app.getPath('userData')
|
||||
return path.join(root, WORKBUDDY_AGENT_CONFIG_FILE)
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取配置。文件不存在 / JSON 损坏 / 字段类型不对,一律回落到默认值(**禁用**),
|
||||
* 不抛错 —— 一个坏配置文件不应该让主进程启动失败。
|
||||
*/
|
||||
export function loadWorkBuddyAgentSettings(
|
||||
userDataDir?: string,
|
||||
defaults: WorkBuddyAgentSettings = DEFAULT_WORKBUDDY_AGENT_SETTINGS
|
||||
): WorkBuddyAgentSettings {
|
||||
let parsed: Record<string, unknown> = {}
|
||||
try {
|
||||
const filePath = resolveWorkBuddyAgentConfigPath(userDataDir)
|
||||
if (fs.existsSync(filePath)) {
|
||||
const raw = fs.readFileSync(filePath, 'utf8')
|
||||
const value = JSON.parse(raw) as unknown
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
parsed = value as Record<string, unknown>
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
parsed = {}
|
||||
}
|
||||
|
||||
return {
|
||||
enabled: parsed.enabled === true,
|
||||
allowedConversations: asConversationList(parsed.allowedConversations),
|
||||
commandPrefix: asString(parsed.commandPrefix, defaults.commandPrefix),
|
||||
baseUrl: asString(parsed.baseUrl, defaults.baseUrl).replace(/\/+$/, ''),
|
||||
timeoutMs: asPositiveInt(parsed.timeoutMs, defaults.timeoutMs, 60_000),
|
||||
pollIntervalMs: asPositiveInt(parsed.pollIntervalMs, defaults.pollIntervalMs, 60_000),
|
||||
maxPollDurationMs: asPositiveInt(
|
||||
parsed.maxPollDurationMs,
|
||||
defaults.maxPollDurationMs,
|
||||
30 * 60_000
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 只从环境变量读取凭证。
|
||||
*
|
||||
* 返回值可能全部为空 —— 调用方必须把这种情况当作 `auth_missing` 处理,
|
||||
* 而不是回落到某个内置默认值。
|
||||
*/
|
||||
export function loadWorkBuddyCredentials(
|
||||
env: NodeJS.ProcessEnv = process.env
|
||||
): WorkBuddyCredentials {
|
||||
const pick = (key: string): string | undefined => {
|
||||
const value = env[key]
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : undefined
|
||||
}
|
||||
return {
|
||||
accessToken: pick('TRACEMEMO_WORKBUDDY_ACCESS_TOKEN'),
|
||||
refreshToken: pick('TRACEMEMO_WORKBUDDY_REFRESH_TOKEN'),
|
||||
clientId: pick('TRACEMEMO_WORKBUDDY_CLIENT_ID'),
|
||||
clientSecret: pick('TRACEMEMO_WORKBUDDY_CLIENT_SECRET')
|
||||
}
|
||||
}
|
||||
|
||||
/** 是否具备可用的凭证组合(无需真的请求成功)。 */
|
||||
export function hasWorkBuddyCredentials(credentials: WorkBuddyCredentials): boolean {
|
||||
if (credentials.accessToken) return true
|
||||
return Boolean(credentials.refreshToken && credentials.clientId && credentials.clientSecret)
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { AgentTaskRecord, AgentTaskReply } from '../../shared/agent-task'
|
||||
import type { NormalizedIncomingMessage } from './message-listener-service'
|
||||
import { classifyProviderError, type AgentTaskProvider } from './agent-task-provider'
|
||||
import type { AgentTaskStore } from './agent-task-store'
|
||||
import type { WorkBuddyAgentSettings } from './agent-task-config'
|
||||
|
||||
/**
|
||||
* AgentTaskDispatcher —— `/ai` 命令闸门 + 任务投递 + 回复轮询。
|
||||
*
|
||||
* **默认关闭,且只认白名单会话**。这是刻意的产品边界:
|
||||
* 收到任意普通微信消息就唤醒 AI,等于把聊天记录变成无人监督的指令流。
|
||||
*
|
||||
* ```text
|
||||
* NormalizedIncomingMessage
|
||||
* ├─ enabled? no → 丢弃
|
||||
* ├─ 白名单会话? no → 丢弃
|
||||
* ├─ 自己发的? yes → 丢弃(防自触发循环)
|
||||
* ├─ 以 `/ai ` 开头? no → 丢弃
|
||||
* └─ triggerKey 已提交? yes → 丢弃(同一条消息只投一次)
|
||||
* ↓
|
||||
* AgentTaskProvider.submitTask
|
||||
* ↓
|
||||
* 状态持久化(submitting → submitted → completed / timeout / auth_failed ...)
|
||||
* ```
|
||||
*
|
||||
* **不做的事**:不执行 shell、不删文件、不推代码、不发微信。
|
||||
* 任务内容只是转交给远端助理的一段文本;本模块不解释、不放行任何高风险动作。
|
||||
*/
|
||||
|
||||
const MAX_REPLIES_PER_TASK = 50
|
||||
const MAX_PROMPT_CHARS = 4000
|
||||
|
||||
export type AgentTaskDispatchOutcome =
|
||||
| 'disabled'
|
||||
| 'ignored'
|
||||
| 'duplicate'
|
||||
| 'submitted'
|
||||
| 'offline'
|
||||
| 'auth_failed'
|
||||
| 'failed'
|
||||
|
||||
export interface AgentTaskDispatcherOptions {
|
||||
settings: WorkBuddyAgentSettings
|
||||
store: AgentTaskStore
|
||||
provider: AgentTaskProvider
|
||||
resolveConversationId: (sessionId: string) => string | undefined
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
export class AgentTaskDispatcher {
|
||||
private readonly now: () => number
|
||||
private pollTimer: ReturnType<typeof setInterval> | null = null
|
||||
private polling = false
|
||||
|
||||
constructor(private readonly options: AgentTaskDispatcherOptions) {
|
||||
this.now = options.now ?? Date.now
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理一条已规范化的消息。
|
||||
*
|
||||
* 前置判断全部同步完成(没有 await),保证同一批事件里重复投递的同一条消息
|
||||
* 会在第二次调用时直接命中去重表。
|
||||
*/
|
||||
async handleMessage(message: NormalizedIncomingMessage): Promise<AgentTaskDispatchOutcome> {
|
||||
const settings = this.options.settings
|
||||
if (!settings.enabled) return 'disabled'
|
||||
if (message.isSelf) return 'ignored'
|
||||
|
||||
const prompt = matchCommand(message.content, settings.commandPrefix)
|
||||
if (!prompt) return 'ignored'
|
||||
|
||||
const conversationId = this.options.resolveConversationId(message.sessionId)
|
||||
if (!conversationId) return 'ignored'
|
||||
if (!settings.allowedConversations.includes(conversationId)) return 'ignored'
|
||||
|
||||
await this.options.store.load()
|
||||
|
||||
const triggerKey = `${message.sessionId}:${message.localId}`
|
||||
if (this.options.store.findByTrigger(triggerKey)) return 'duplicate'
|
||||
|
||||
const now = this.now()
|
||||
const record: AgentTaskRecord = {
|
||||
id: randomUUID(),
|
||||
provider: this.options.provider.id,
|
||||
conversationId,
|
||||
triggerKey,
|
||||
prompt: prompt.slice(0, MAX_PROMPT_CHARS),
|
||||
status: 'submitting',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
replies: []
|
||||
}
|
||||
this.options.store.upsert(record)
|
||||
/*
|
||||
* 必须在发请求前落盘。debounce 的写入不足以支撑「不重复提交」——
|
||||
* 崩溃窗口正是发生在这两步之间。
|
||||
*/
|
||||
await this.options.store.flush()
|
||||
|
||||
let online: boolean
|
||||
try {
|
||||
online = await this.options.provider.checkOnline()
|
||||
} catch (error) {
|
||||
return this.finishFailure(record, error, 'online_check')
|
||||
}
|
||||
if (!online) {
|
||||
this.update(record, {
|
||||
status: 'offline',
|
||||
errorKind: 'offline',
|
||||
errorMessage: 'WorkBuddy 本机助理不在线,未提交'
|
||||
})
|
||||
await this.options.store.flush()
|
||||
return 'offline'
|
||||
}
|
||||
|
||||
try {
|
||||
const { messageId } = await this.options.provider.submitTask({ content: record.prompt })
|
||||
this.update(record, {
|
||||
status: 'submitted',
|
||||
submittedAt: this.now(),
|
||||
externalMessageId: messageId,
|
||||
lastReplyId: messageId,
|
||||
errorKind: undefined,
|
||||
errorMessage: undefined
|
||||
})
|
||||
await this.options.store.flush()
|
||||
return 'submitted'
|
||||
} catch (error) {
|
||||
return this.finishFailure(record, error, 'submit')
|
||||
}
|
||||
}
|
||||
|
||||
/** 启动轮询。重复调用是幂等的。 */
|
||||
start(): void {
|
||||
if (this.pollTimer) return
|
||||
this.pollTimer = setInterval(() => {
|
||||
void this.pollOnce()
|
||||
}, this.options.settings.pollIntervalMs)
|
||||
this.pollTimer.unref?.()
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.pollTimer) {
|
||||
clearInterval(this.pollTimer)
|
||||
this.pollTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取所有 `submitted` 任务的增量回复。
|
||||
*
|
||||
* 返回本次处理的任务数(便于测试与诊断)。并发调用会被直接跳过。
|
||||
*/
|
||||
async pollOnce(): Promise<number> {
|
||||
if (this.polling) return 0
|
||||
this.polling = true
|
||||
try {
|
||||
await this.options.store.load()
|
||||
const pending = this.options.store
|
||||
.list(200)
|
||||
.filter((record) => record.status === 'submitted' && Boolean(record.externalMessageId))
|
||||
let processed = 0
|
||||
|
||||
for (const record of pending) {
|
||||
const startedAt = record.submittedAt ?? record.createdAt
|
||||
if (this.now() - startedAt > this.options.settings.maxPollDurationMs) {
|
||||
this.update(record, {
|
||||
status: 'timeout',
|
||||
errorKind: 'timeout',
|
||||
errorMessage: '等待 WorkBuddy 回复超时,已停止轮询'
|
||||
})
|
||||
processed += 1
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
const replies = await this.options.provider.fetchReplies(
|
||||
record.lastReplyId ?? String(record.externalMessageId)
|
||||
)
|
||||
const merged = mergeReplies(record.replies, replies)
|
||||
const assistant = merged.find((reply) => reply.role === 'assistant')
|
||||
this.update(record, {
|
||||
replies: merged,
|
||||
lastReplyId:
|
||||
merged.length > 0 ? merged[merged.length - 1].messageId : record.lastReplyId,
|
||||
...(assistant
|
||||
? {
|
||||
status: 'completed' as const,
|
||||
completedAt: this.now(),
|
||||
errorKind: undefined,
|
||||
errorMessage: undefined
|
||||
}
|
||||
: {})
|
||||
})
|
||||
processed += 1
|
||||
} catch (error) {
|
||||
this.finishFailure(record, error, 'poll')
|
||||
}
|
||||
}
|
||||
|
||||
if (processed > 0) await this.options.store.flush()
|
||||
return processed
|
||||
} finally {
|
||||
this.polling = false
|
||||
}
|
||||
}
|
||||
|
||||
private finishFailure(
|
||||
record: AgentTaskRecord,
|
||||
error: unknown,
|
||||
stage: 'online_check' | 'submit' | 'poll'
|
||||
): AgentTaskDispatchOutcome {
|
||||
const info = classifyProviderError(error)
|
||||
const authFailure = info.kind === 'auth_expired' || info.kind === 'auth_missing'
|
||||
|
||||
/*
|
||||
* 投递阶段只要发生「可能已经到达远端」的失败(超时 / 可重试的 5xx / 网络错误),
|
||||
* 就必须记成 ambiguous_submission —— 自动重试会造成重复任务。
|
||||
*/
|
||||
const ambiguous =
|
||||
stage === 'submit' &&
|
||||
(info.kind === 'timeout' || (info.kind === 'http_error' && info.retryable))
|
||||
|
||||
if (ambiguous) {
|
||||
this.update(record, {
|
||||
status: 'failed',
|
||||
errorKind: 'ambiguous_submission',
|
||||
errorMessage: `投递结果未知:${info.message};不会自动重试`
|
||||
})
|
||||
void this.options.store.flush()
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
/*
|
||||
* 轮询阶段的普通失败(5xx / 网络抖动)不应把任务判死:
|
||||
* 远端可能仍在执行,下一轮继续拉取即可。只有鉴权失败才改状态。
|
||||
*/
|
||||
if (stage === 'poll' && !authFailure) {
|
||||
this.update(record, {
|
||||
status: record.status,
|
||||
errorKind: info.kind,
|
||||
errorMessage: info.message
|
||||
})
|
||||
void this.options.store.flush()
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
this.update(record, {
|
||||
status: authFailure ? 'auth_failed' : 'failed',
|
||||
errorKind: info.kind,
|
||||
errorMessage: info.message
|
||||
})
|
||||
void this.options.store.flush()
|
||||
return authFailure ? 'auth_failed' : 'failed'
|
||||
}
|
||||
|
||||
private update(record: AgentTaskRecord, patch: Partial<AgentTaskRecord>): void {
|
||||
Object.assign(record, patch, { updatedAt: this.now() })
|
||||
if (record.errorKind === undefined) delete record.errorKind
|
||||
if (record.errorMessage === undefined) delete record.errorMessage
|
||||
this.options.store.upsert(record)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 只接受「前缀 + 空白」或整条等于前缀。
|
||||
*
|
||||
* `/ai写日报` 不触发:没有分隔符时无法区分命令与普通文本,
|
||||
* 宁可漏触发也不要把正常聊天吞掉。
|
||||
*/
|
||||
export function matchCommand(content: string | undefined, prefix: string): string | null {
|
||||
const text = String(content ?? '').trim()
|
||||
if (!text || !prefix) return null
|
||||
if (!text.toLowerCase().startsWith(prefix.toLowerCase())) return null
|
||||
const rest = text.slice(prefix.length)
|
||||
if (rest && !/^\s/.test(rest)) return null
|
||||
return rest.trim()
|
||||
}
|
||||
|
||||
function mergeReplies(existing: AgentTaskReply[], incoming: AgentTaskReply[]): AgentTaskReply[] {
|
||||
if (incoming.length === 0) return existing
|
||||
const seen = new Set(existing.map((reply) => reply.messageId))
|
||||
const merged = [...existing]
|
||||
for (const reply of incoming) {
|
||||
if (seen.has(reply.messageId)) continue
|
||||
seen.add(reply.messageId)
|
||||
merged.push(reply)
|
||||
}
|
||||
return merged.slice(-MAX_REPLIES_PER_TASK)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { AgentTaskErrorKind, AgentTaskReply } from '../../shared/agent-task'
|
||||
|
||||
/**
|
||||
* AgentTaskProvider —— 可替换的任务投递接口。
|
||||
*
|
||||
* 第一版实现是 WorkBuddy;接口刻意只包含三件事:在线检测、投递、拉回复。
|
||||
* 任何「执行 shell / 发微信 / 改仓库」的能力都**不属于**这个接口。
|
||||
*/
|
||||
|
||||
export interface AgentTaskProviderRequestOptions {
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export interface AgentTaskProvider {
|
||||
readonly id: string
|
||||
/** 远端助理是否在线。false 时调用方必须放弃提交,不能降级成「假装已提交」。 */
|
||||
checkOnline(options?: AgentTaskProviderRequestOptions): Promise<boolean>
|
||||
/**
|
||||
* 投递一条指令,返回远端消息 id。
|
||||
*
|
||||
* 该调用**不是幂等的**:调用方负责按 `triggerKey` 去重,
|
||||
* 并在失败时区分「确定没提交」与「不确定是否提交」。
|
||||
*/
|
||||
submitTask(
|
||||
input: { content: string },
|
||||
options?: AgentTaskProviderRequestOptions
|
||||
): Promise<{ messageId: string }>
|
||||
/** 按游标增量拉取回复。 */
|
||||
fetchReplies(
|
||||
afterMessageId: string,
|
||||
options?: AgentTaskProviderRequestOptions & { limit?: number }
|
||||
): Promise<AgentTaskReply[]>
|
||||
}
|
||||
|
||||
export class AgentTaskProviderError extends Error {
|
||||
constructor(
|
||||
readonly kind: AgentTaskErrorKind,
|
||||
message: string,
|
||||
readonly retryable = false,
|
||||
readonly httpStatus?: number
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'AgentTaskProviderError'
|
||||
}
|
||||
}
|
||||
|
||||
/** 把任意异常归类成可持久化的错误类型;未知异常一律 `internal`,不猜。 */
|
||||
export function classifyProviderError(error: unknown): {
|
||||
kind: AgentTaskErrorKind
|
||||
message: string
|
||||
retryable: boolean
|
||||
} {
|
||||
if (error instanceof AgentTaskProviderError) {
|
||||
return { kind: error.kind, message: error.message, retryable: error.retryable }
|
||||
}
|
||||
return {
|
||||
kind: 'internal',
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
retryable: false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import fs from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import type { AgentTaskRecord, AgentTaskReply } from '../../shared/agent-task'
|
||||
|
||||
/**
|
||||
* Agent 任务状态持久化。
|
||||
*
|
||||
* 目的只有一个:**重启后不重复提交**。
|
||||
* 因此写入顺序必须是「先落 `submitting`,再发请求」——崩溃发生时磁盘上留下的是
|
||||
* 「不确定是否已提交」,而不是一句「没提交过」。
|
||||
*
|
||||
* 文件为 JSON 数组,权限 0600,位于 `<userData>`;最多保留 `maxRecords` 条最新记录。
|
||||
*/
|
||||
|
||||
const DEFAULT_MAX_RECORDS = 200
|
||||
const DEFAULT_DEBOUNCE_MS = 200
|
||||
|
||||
export interface AgentTaskStoreOptions {
|
||||
filePath: string
|
||||
maxRecords?: number
|
||||
debounceMs?: number
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function sanitizeRecord(value: unknown): AgentTaskRecord | null {
|
||||
if (!isRecord(value)) return null
|
||||
const id = typeof value.id === 'string' ? value.id : ''
|
||||
const triggerKey = typeof value.triggerKey === 'string' ? value.triggerKey : ''
|
||||
const conversationId = typeof value.conversationId === 'string' ? value.conversationId : ''
|
||||
const prompt = typeof value.prompt === 'string' ? value.prompt : ''
|
||||
const status = typeof value.status === 'string' ? value.status : ''
|
||||
if (!id || !triggerKey || !conversationId || !status) return null
|
||||
return {
|
||||
id,
|
||||
provider: typeof value.provider === 'string' ? value.provider : 'workbuddy',
|
||||
conversationId,
|
||||
triggerKey,
|
||||
prompt,
|
||||
status: status as AgentTaskRecord['status'],
|
||||
createdAt: typeof value.createdAt === 'number' ? value.createdAt : 0,
|
||||
updatedAt: typeof value.updatedAt === 'number' ? value.updatedAt : 0,
|
||||
...(typeof value.submittedAt === 'number' ? { submittedAt: value.submittedAt } : {}),
|
||||
...(typeof value.completedAt === 'number' ? { completedAt: value.completedAt } : {}),
|
||||
...(typeof value.externalMessageId === 'string'
|
||||
? { externalMessageId: value.externalMessageId }
|
||||
: {}),
|
||||
...(typeof value.lastReplyId === 'string' ? { lastReplyId: value.lastReplyId } : {}),
|
||||
...(typeof value.errorKind === 'string'
|
||||
? { errorKind: value.errorKind as AgentTaskRecord['errorKind'] }
|
||||
: {}),
|
||||
...(typeof value.errorMessage === 'string' ? { errorMessage: value.errorMessage } : {}),
|
||||
replies: Array.isArray(value.replies)
|
||||
? value.replies
|
||||
.filter(isRecord)
|
||||
.map(
|
||||
(reply): AgentTaskReply => ({
|
||||
messageId: typeof reply.messageId === 'string' ? reply.messageId : '',
|
||||
role:
|
||||
reply.role === 'assistant' || reply.role === 'user'
|
||||
? reply.role
|
||||
: ('other' as const),
|
||||
text: typeof reply.text === 'string' ? reply.text : '',
|
||||
...(typeof reply.createdAt === 'string' ? { createdAt: reply.createdAt } : {})
|
||||
})
|
||||
)
|
||||
.filter((reply) => Boolean(reply.messageId))
|
||||
: []
|
||||
}
|
||||
}
|
||||
|
||||
export class AgentTaskStore {
|
||||
private readonly records = new Map<string, AgentTaskRecord>()
|
||||
private readonly maxRecords: number
|
||||
private readonly debounceMs: number
|
||||
private readonly now: () => number
|
||||
private loaded: Promise<void> | null = null
|
||||
private persistTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private writeChain: Promise<void> = Promise.resolve()
|
||||
|
||||
constructor(private readonly options: AgentTaskStoreOptions) {
|
||||
this.maxRecords = Math.max(1, options.maxRecords ?? DEFAULT_MAX_RECORDS)
|
||||
this.debounceMs = Math.max(0, options.debounceMs ?? DEFAULT_DEBOUNCE_MS)
|
||||
this.now = options.now ?? Date.now
|
||||
}
|
||||
|
||||
async load(): Promise<void> {
|
||||
if (!this.loaded) this.loaded = this.loadFromDisk()
|
||||
return this.loaded
|
||||
}
|
||||
|
||||
get(id: string): AgentTaskRecord | undefined {
|
||||
const record = this.records.get(id)
|
||||
return record ? { ...record, replies: [...record.replies] } : undefined
|
||||
}
|
||||
|
||||
findByTrigger(triggerKey: string): AgentTaskRecord | undefined {
|
||||
for (const record of this.records.values()) {
|
||||
if (record.triggerKey === triggerKey) return { ...record, replies: [...record.replies] }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
list(limit = 50): AgentTaskRecord[] {
|
||||
return Array.from(this.records.values())
|
||||
.sort((a, b) => b.createdAt - a.createdAt)
|
||||
.slice(0, Math.max(1, Math.min(limit, this.maxRecords)))
|
||||
.map((record) => ({ ...record, replies: [...record.replies] }))
|
||||
}
|
||||
|
||||
upsert(record: AgentTaskRecord): void {
|
||||
this.records.set(record.id, { ...record, replies: [...record.replies] })
|
||||
this.trim()
|
||||
this.schedulePersist()
|
||||
}
|
||||
|
||||
/** 强制写盘(测试与退出前调用)。 */
|
||||
async flush(): Promise<void> {
|
||||
if (this.persistTimer) {
|
||||
clearTimeout(this.persistTimer)
|
||||
this.persistTimer = null
|
||||
}
|
||||
const snapshot = JSON.stringify(this.list(this.maxRecords), null, 2)
|
||||
this.writeChain = this.writeChain.then(() => this.writeSnapshot(snapshot))
|
||||
await this.writeChain
|
||||
}
|
||||
|
||||
private async loadFromDisk(): Promise<void> {
|
||||
let raw = ''
|
||||
try {
|
||||
raw = await fs.readFile(this.options.filePath, 'utf8')
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(raw)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
if (!Array.isArray(parsed)) return
|
||||
|
||||
for (const item of parsed) {
|
||||
const record = sanitizeRecord(item)
|
||||
if (!record) continue
|
||||
/*
|
||||
* 恢复语义:`submitting` 表示「请求可能已经发出,但进程没等到响应」。
|
||||
* 这种情况绝不能重投,也不能谎称失败在本地 —— 标记为不可重试的
|
||||
* `ambiguous_submission`,让人工/后续阶段决定。
|
||||
*/
|
||||
if (record.status === 'submitting') {
|
||||
record.status = 'failed'
|
||||
record.errorKind = 'ambiguous_submission'
|
||||
record.errorMessage = '进程在投递过程中退出,无法确认远端是否已接收;不会自动重试'
|
||||
record.updatedAt = this.now()
|
||||
} else if (record.status === 'queued') {
|
||||
record.status = 'failed'
|
||||
record.errorKind = 'internal'
|
||||
record.errorMessage = '进程在投递前退出,未发送'
|
||||
record.updatedAt = this.now()
|
||||
}
|
||||
this.records.set(record.id, record)
|
||||
}
|
||||
this.trim()
|
||||
}
|
||||
|
||||
private trim(): void {
|
||||
if (this.records.size <= this.maxRecords) return
|
||||
const ordered = Array.from(this.records.values()).sort((a, b) => a.createdAt - b.createdAt)
|
||||
const overflow = this.records.size - this.maxRecords
|
||||
for (let index = 0; index < overflow; index += 1) {
|
||||
this.records.delete(ordered[index].id)
|
||||
}
|
||||
}
|
||||
|
||||
private schedulePersist(): void {
|
||||
if (this.persistTimer) return
|
||||
this.persistTimer = setTimeout(() => {
|
||||
this.persistTimer = null
|
||||
const snapshot = JSON.stringify(this.list(this.maxRecords), null, 2)
|
||||
this.writeChain = this.writeChain.then(() => this.writeSnapshot(snapshot))
|
||||
}, this.debounceMs)
|
||||
this.persistTimer.unref?.()
|
||||
}
|
||||
|
||||
private async writeSnapshot(snapshot: string): Promise<void> {
|
||||
const target = this.options.filePath
|
||||
const temp = `${target}.tmp`
|
||||
try {
|
||||
await fs.mkdir(path.dirname(target), { recursive: true })
|
||||
await fs.writeFile(temp, snapshot, { encoding: 'utf8', mode: 0o600 })
|
||||
await fs.rename(temp, target)
|
||||
await fs.chmod(target, 0o600).catch(() => undefined)
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[AgentTaskStore] persist failed: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import { encodeMessageRef } from '../../shared/local-query-api'
|
||||
import {
|
||||
normalizeIncomingMessage,
|
||||
type NormalizedIncomingMessage
|
||||
} from './message-listener-service'
|
||||
import type { Wcdb4Message } from '../wcdb4-client'
|
||||
|
||||
/**
|
||||
* MessageEventBroker —— 实时消息事件的唯一分发层。
|
||||
*
|
||||
* ```text
|
||||
* MessageListenerService.onMessage
|
||||
* ↓ NormalizedIncomingMessage
|
||||
* MessageEventBroker
|
||||
* ├─ 事件 ID / 规范化 / 有界环形缓冲 / 每订阅者游标
|
||||
* ├─ 已产生事件的重放(replay)
|
||||
* └─ 数据库消息回补(db_backfill,独立标记)
|
||||
* ```
|
||||
*
|
||||
* **刻意不做的事**:不监听数据库(监听只有 `MessageListenerService` 一套)、
|
||||
* 不触发自动化、不调用 AI、不发送微信消息。本模块只负责「把已经产生的事件可靠地交出去」。
|
||||
*
|
||||
* **两类补偿必须可区分**:
|
||||
* - `replay`:事件曾经真实产生过,仍在本进程的环形缓冲里;
|
||||
* - `db_backfill`:缓冲已经覆盖不到,只能从数据库按时间窗重读。它可能包含
|
||||
* 从未产生过事件的普通消息,也可能因为窗口/条数上限而不完整。
|
||||
*
|
||||
* **单位契约**:`timestamp` 是 epoch **秒**(与 WCDB `create_time`、`getMessagesAsync` 一致);
|
||||
* 缓冲 TTL / 去重 TTL 是毫秒。跨这条边界只允许在本文件里换算一次。
|
||||
*/
|
||||
|
||||
/** 单条事件的文本上限。超出时显式标记 `textTruncated`,不静默截断。 */
|
||||
const DEFAULT_MAX_TEXT_CHARS = 4000
|
||||
/** 环形缓冲默认容量(条)。 */
|
||||
const DEFAULT_BUFFER_SIZE = 500
|
||||
/** 环形缓冲默认存活时间(毫秒)。 */
|
||||
const DEFAULT_BUFFER_TTL_MS = 5 * 60 * 1000
|
||||
/** 发布去重表默认存活时间(毫秒)。 */
|
||||
const DEFAULT_SEEN_TTL_MS = 10 * 60 * 1000
|
||||
/** 发布去重表默认容量。 */
|
||||
const DEFAULT_SEEN_MAX_ENTRIES = 5000
|
||||
/** 单订阅者「已投递 ID」记忆容量,用于避免回补与实时重叠时重复投递。 */
|
||||
const DEFAULT_SUBSCRIBER_SEEN_MAX = 2000
|
||||
/** 数据库回补的时间窗默认值(秒)。 */
|
||||
const DEFAULT_BACKFILL_LOOKBACK_SEC = 300
|
||||
/** 单会话回补条数默认上限。 */
|
||||
const DEFAULT_BACKFILL_LIMIT = 100
|
||||
/** 单次回补最多涉及的会话数。 */
|
||||
const DEFAULT_BACKFILL_MAX_CONVERSATIONS = 20
|
||||
/** 单个进程允许的并发 SSE 订阅数。 */
|
||||
const DEFAULT_MAX_SUBSCRIBERS = 32
|
||||
|
||||
export type MessageEventOrigin = 'live' | 'replay' | 'db_backfill'
|
||||
|
||||
export interface MessageEventRecord {
|
||||
/** 确定性 ID:同一会话 + 同一条消息永远得到同一个值(跨进程稳定)。 */
|
||||
id: string
|
||||
/** 进程内单调序号,用于 SSE `Last-Event-ID` 的缓冲定位。 */
|
||||
seq: number
|
||||
/** **会话 md5**,与 `messageRef` 的 `c` 字段同口径(不是微信 username)。 */
|
||||
conversationId: string
|
||||
messageRef: string
|
||||
/** epoch 秒。 */
|
||||
timestamp: number
|
||||
messageType: number
|
||||
isSelf: boolean
|
||||
isGroup: boolean
|
||||
senderId?: string
|
||||
senderNickname?: string
|
||||
text?: string
|
||||
textTruncated?: boolean
|
||||
mentionTargets: string[]
|
||||
}
|
||||
|
||||
export interface MessageBrokerStatus {
|
||||
database: 'ready' | 'unavailable'
|
||||
subscribers: number
|
||||
buffered: number
|
||||
oldestSeq: number | null
|
||||
newestSeq: number | null
|
||||
}
|
||||
|
||||
export interface MessageGap {
|
||||
reason: 'buffer_overflow' | 'invalid_cursor' | 'cursor_from_previous_process'
|
||||
requestedLastEventId: string
|
||||
oldestSeq: number | null
|
||||
newestSeq: number | null
|
||||
/** 是否触发了数据库回补。为 false 时必须让客户端知道这段空档没有补齐。 */
|
||||
backfill:
|
||||
| 'scheduled'
|
||||
| 'skipped_no_conversation_filter'
|
||||
| 'skipped_database_unavailable'
|
||||
| 'skipped_no_reader'
|
||||
| 'disabled'
|
||||
}
|
||||
|
||||
export interface MessageEventSink {
|
||||
onStatus(status: MessageBrokerStatus & { subscriptionId: string }): void
|
||||
onEvent(event: MessageEventRecord, origin: MessageEventOrigin): void
|
||||
onGap(gap: MessageGap): void
|
||||
}
|
||||
|
||||
export interface MessageSubscribeOptions {
|
||||
/** 会话 md5 白名单;空/省略 = 全部会话(此时无法做有界回补)。 */
|
||||
conversationIds?: string[]
|
||||
/** 上一次收到的 SSE id(`Last-Event-ID`)。 */
|
||||
lastEventId?: string
|
||||
/** 是否允许在缓冲覆盖不到时从数据库回补。默认 true。 */
|
||||
backfill?: boolean
|
||||
}
|
||||
|
||||
export interface MessageSubscription {
|
||||
readonly id: string
|
||||
/** 该订阅已经投递到的最新序号(诊断用)。 */
|
||||
readonly lastDeliveredSeq: number
|
||||
close(): void
|
||||
}
|
||||
|
||||
export interface MessageEventBrokerOptions {
|
||||
/**
|
||||
* username → 会话 md5。
|
||||
*
|
||||
* 事件必须携带与 `encodeMessageRef()` 同口径的 conversationId(md5),
|
||||
* 否则 `/query/message-context` 无法反查会话。返回 undefined 表示当前无法映射,
|
||||
* 该消息会被计入 `unmapped` 并**不投递**(避免发出不可用的 messageRef)。
|
||||
*/
|
||||
resolveConversationId: (sessionId: string) => string | undefined
|
||||
/** 数据库当前是否可用。用于 status 事件,不做连接管理。 */
|
||||
isDatabaseReady?: () => boolean
|
||||
/** 回补读取器。参数与 `getMessagesAsync(usernameOrMd5, startSec, endSec, {limit})` 一致。 */
|
||||
readMessages?: (
|
||||
sessionIdOrMd5: string,
|
||||
startTimeSec: number,
|
||||
endTimeSec: number,
|
||||
limit: number
|
||||
) => Promise<Wcdb4Message[]>
|
||||
/** md5 → username,仅回补时用于还原 `isGroup` 与 sender 语义。 */
|
||||
resolveSessionId?: (conversationId: string) => string | undefined
|
||||
bufferSize?: number
|
||||
bufferTtlMs?: number
|
||||
seenTtlMs?: number
|
||||
seenMaxEntries?: number
|
||||
backfillLookbackSec?: number
|
||||
backfillLimit?: number
|
||||
backfillMaxConversations?: number
|
||||
maxSubscribers?: number
|
||||
maxTextChars?: number
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
interface SubscriberState {
|
||||
id: string
|
||||
conversationIds: Set<string> | null
|
||||
sink: MessageEventSink
|
||||
deliveredIds: Map<string, number>
|
||||
lastDeliveredSeq: number
|
||||
delivered: number
|
||||
closed: boolean
|
||||
backfillEnabled: boolean
|
||||
}
|
||||
|
||||
export class MessageEventBroker {
|
||||
private readonly subscribers = new Map<string, SubscriberState>()
|
||||
private buffer: MessageEventRecord[] = []
|
||||
/** 事件 ID → 序号。只保留仍在缓冲里的条目。 */
|
||||
private readonly index = new Map<string, number>()
|
||||
private nextSeq = 1
|
||||
private disposed = false
|
||||
|
||||
private readonly seen = new Map<string, number>()
|
||||
private readonly bufferSize: number
|
||||
private readonly bufferTtlMs: number
|
||||
private readonly seenTtlMs: number
|
||||
private readonly seenMaxEntries: number
|
||||
private readonly backfillLookbackSec: number
|
||||
private readonly backfillLimit: number
|
||||
private readonly backfillMaxConversations: number
|
||||
private readonly maxSubscribers: number
|
||||
private readonly maxTextChars: number
|
||||
private readonly now: () => number
|
||||
|
||||
private counters = {
|
||||
published: 0,
|
||||
duplicates: 0,
|
||||
unmapped: 0,
|
||||
backfilled: 0,
|
||||
gaps: 0,
|
||||
rejected: 0
|
||||
}
|
||||
|
||||
constructor(private readonly options: MessageEventBrokerOptions) {
|
||||
this.bufferSize = Math.max(1, options.bufferSize ?? DEFAULT_BUFFER_SIZE)
|
||||
this.bufferTtlMs = Math.max(1000, options.bufferTtlMs ?? DEFAULT_BUFFER_TTL_MS)
|
||||
this.seenTtlMs = Math.max(1000, options.seenTtlMs ?? DEFAULT_SEEN_TTL_MS)
|
||||
this.seenMaxEntries = Math.max(1, options.seenMaxEntries ?? DEFAULT_SEEN_MAX_ENTRIES)
|
||||
this.backfillLookbackSec = Math.max(
|
||||
1,
|
||||
options.backfillLookbackSec ?? DEFAULT_BACKFILL_LOOKBACK_SEC
|
||||
)
|
||||
this.backfillLimit = Math.max(1, options.backfillLimit ?? DEFAULT_BACKFILL_LIMIT)
|
||||
this.backfillMaxConversations = Math.max(
|
||||
1,
|
||||
options.backfillMaxConversations ?? DEFAULT_BACKFILL_MAX_CONVERSATIONS
|
||||
)
|
||||
this.maxSubscribers = Math.max(1, options.maxSubscribers ?? DEFAULT_MAX_SUBSCRIBERS)
|
||||
this.maxTextChars = Math.max(64, options.maxTextChars ?? DEFAULT_MAX_TEXT_CHARS)
|
||||
this.now = options.now ?? Date.now
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布一条已经由 MessageListener 回读并规范化的消息。
|
||||
*
|
||||
* 返回 null 表示消息无法形成可用事件(会话未映射 / messageRef 构造失败),
|
||||
* 或命中去重表(同一条消息被重复回读)。
|
||||
*/
|
||||
publish(message: NormalizedIncomingMessage): MessageEventRecord | null {
|
||||
if (this.disposed) return null
|
||||
const record = this.toRecord(message)
|
||||
if (!record) return null
|
||||
|
||||
this.evictSeen(this.now())
|
||||
if (this.seen.has(record.id)) {
|
||||
this.counters.duplicates += 1
|
||||
return null
|
||||
}
|
||||
|
||||
this.seen.set(record.id, this.now())
|
||||
this.trimSeen()
|
||||
|
||||
record.seq = this.nextSeq
|
||||
this.nextSeq += 1
|
||||
|
||||
this.buffer.push(record)
|
||||
this.index.set(record.id, record.seq)
|
||||
this.trimBuffer()
|
||||
|
||||
this.counters.published += 1
|
||||
this.deliverLive(record)
|
||||
return record
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅消息事件。
|
||||
*
|
||||
* 订阅会立刻收到一条 `status`;随后按 `lastEventId` 决定重放还是回补。
|
||||
* 返回的句柄必须由调用方在连接关闭时 `close()`,否则会占用订阅配额。
|
||||
*/
|
||||
subscribe(options: MessageSubscribeOptions, sink: MessageEventSink): MessageSubscription {
|
||||
if (this.subscribers.size >= this.maxSubscribers) {
|
||||
throw new Error('消息事件订阅数已达上限')
|
||||
}
|
||||
|
||||
const state: SubscriberState = {
|
||||
id: randomUUID(),
|
||||
conversationIds:
|
||||
options.conversationIds && options.conversationIds.length > 0
|
||||
? new Set(options.conversationIds)
|
||||
: null,
|
||||
sink,
|
||||
deliveredIds: new Map(),
|
||||
lastDeliveredSeq: 0,
|
||||
delivered: 0,
|
||||
closed: false,
|
||||
backfillEnabled: options.backfill !== false
|
||||
}
|
||||
this.subscribers.set(state.id, state)
|
||||
sink.onStatus({ ...this.status(), subscriptionId: state.id })
|
||||
void this.resume(state, options.lastEventId)
|
||||
|
||||
return {
|
||||
id: state.id,
|
||||
get lastDeliveredSeq(): number {
|
||||
return state.lastDeliveredSeq
|
||||
},
|
||||
close: () => {
|
||||
state.closed = true
|
||||
this.subscribers.delete(state.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
status(): MessageBrokerStatus {
|
||||
return {
|
||||
database: this.options.isDatabaseReady?.() === false ? 'unavailable' : 'ready',
|
||||
subscribers: this.subscribers.size,
|
||||
buffered: this.buffer.length,
|
||||
oldestSeq: this.buffer[0]?.seq ?? null,
|
||||
newestSeq: this.buffer[this.buffer.length - 1]?.seq ?? null
|
||||
}
|
||||
}
|
||||
|
||||
stats(): typeof this.counters & MessageBrokerStatus {
|
||||
return { ...this.counters, ...this.status() }
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.disposed = true
|
||||
for (const state of this.subscribers.values()) state.closed = true
|
||||
this.subscribers.clear()
|
||||
this.buffer = []
|
||||
this.index.clear()
|
||||
this.seen.clear()
|
||||
}
|
||||
|
||||
private async resume(state: SubscriberState, lastEventId?: string): Promise<void> {
|
||||
const raw = typeof lastEventId === 'string' ? lastEventId.trim() : ''
|
||||
// 没带游标 = 首次订阅,只接实时事件,不需要 gap。
|
||||
if (!raw) return
|
||||
if (state.closed) return
|
||||
|
||||
const oldest = this.buffer[0]?.seq ?? null
|
||||
const newest = this.buffer[this.buffer.length - 1]?.seq ?? null
|
||||
/** 本进程已经分配出去的最大序号(含未进缓冲的回补事件)。 */
|
||||
const maxAssigned = this.nextSeq - 1
|
||||
|
||||
const lastSeq = parseLastEventId(raw)
|
||||
/*
|
||||
* 带了游标但解析不了:不能当成「首次订阅」静默跳过 ——
|
||||
* 那等于把客户端明确声明的断点吞掉。
|
||||
*/
|
||||
if (lastSeq === null) {
|
||||
await this.emitGap(state, raw, 'invalid_cursor', oldest, newest)
|
||||
return
|
||||
}
|
||||
|
||||
/*
|
||||
* 序号只在**本进程内**单调。客户端如果拿着上一个进程的游标(重启后
|
||||
* 序号会从 1 重新开始),它可能大于本进程已分配的任何序号 —— 这时
|
||||
* 既不能当成「已经收到最新」,也不能假装能重放,只能走 gap。
|
||||
*/
|
||||
if (lastSeq > maxAssigned) {
|
||||
await this.emitGap(state, raw, 'cursor_from_previous_process', oldest, newest)
|
||||
return
|
||||
}
|
||||
|
||||
/*
|
||||
* 只有「游标落在缓冲区间内」或「游标正好是本进程最后一个被淘汰的序号」
|
||||
* 才能保证重放完整。`lastSeq < oldest - 1` 说明中间已经有事件被淘汰,
|
||||
* 必须显式报 gap,不能假装重放是连续的。
|
||||
*/
|
||||
if (oldest !== null && lastSeq >= oldest - 1) {
|
||||
for (const event of this.buffer) {
|
||||
if (state.closed) return
|
||||
if (event.seq <= lastSeq) continue
|
||||
this.deliver(state, event, 'replay')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
/*
|
||||
* 缓冲为空但有本进程分配过的序号:可能只发生过回补事件(不进缓冲),
|
||||
* 也可能事件已按 TTL 全部淘汰。前者没有漏消息,后者必须报 gap。
|
||||
*/
|
||||
if (oldest === null && lastSeq === maxAssigned) return
|
||||
|
||||
await this.emitGap(state, raw, 'buffer_overflow', oldest, newest)
|
||||
}
|
||||
|
||||
private async emitGap(
|
||||
state: SubscriberState,
|
||||
lastEventId: string,
|
||||
reason: MessageGap['reason'],
|
||||
oldest: number | null,
|
||||
newest: number | null
|
||||
): Promise<void> {
|
||||
this.counters.gaps += 1
|
||||
/*
|
||||
* 先发 gap,再回补。反过来会让客户端先收到一批「来源不明」的消息,
|
||||
* 然后才被告知中间有断档 —— 顺序本身就是语义的一部分。
|
||||
*/
|
||||
const plan = this.backfillPlan(state)
|
||||
state.sink.onGap({
|
||||
reason,
|
||||
requestedLastEventId: String(lastEventId),
|
||||
oldestSeq: oldest,
|
||||
newestSeq: newest,
|
||||
backfill: plan
|
||||
})
|
||||
if (plan === 'scheduled') await this.runBackfill(state)
|
||||
}
|
||||
|
||||
/**
|
||||
* 有界数据库回补的前置判定。
|
||||
*
|
||||
* 边界(全部不可协商):
|
||||
* - 只回补订阅时显式指定的会话;「全部会话」无法做有界回补;
|
||||
* - 时间窗 ≤ `backfillLookbackSec`,单会话 ≤ `backfillLimit` 条;
|
||||
* - 会话数 ≤ `backfillMaxConversations`;
|
||||
* - 数据库不可用 / 没有读取器时明确跳过,不伪造事件。
|
||||
*/
|
||||
private backfillPlan(state: SubscriberState): MessageGap['backfill'] {
|
||||
if (!state.backfillEnabled) return 'disabled'
|
||||
if (!state.conversationIds || state.conversationIds.size === 0) {
|
||||
return 'skipped_no_conversation_filter'
|
||||
}
|
||||
if (!this.options.readMessages) return 'skipped_no_reader'
|
||||
if (this.options.isDatabaseReady?.() === false) return 'skipped_database_unavailable'
|
||||
return 'scheduled'
|
||||
}
|
||||
|
||||
/** 执行已经通过 `backfillPlan` 判定的回补。 */
|
||||
private async runBackfill(state: SubscriberState): Promise<void> {
|
||||
if (!state.conversationIds || !this.options.readMessages) return
|
||||
|
||||
const nowMs = this.now()
|
||||
const endSec = Math.floor(nowMs / 1000)
|
||||
const startSec = endSec - this.backfillLookbackSec
|
||||
const conversations = Array.from(state.conversationIds).slice(0, this.backfillMaxConversations)
|
||||
|
||||
for (const conversationId of conversations) {
|
||||
if (state.closed) return
|
||||
const sessionId = this.options.resolveSessionId?.(conversationId) ?? conversationId
|
||||
let rows: Wcdb4Message[]
|
||||
try {
|
||||
rows = await this.options.readMessages(sessionId, startSec, endSec, this.backfillLimit)
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[MessageEventBroker] backfill read failed: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
continue
|
||||
}
|
||||
for (const row of rows) {
|
||||
if (state.closed) return
|
||||
const normalized = normalizeIncomingMessage(sessionId, row)
|
||||
if (!normalized) continue
|
||||
const record = this.toRecord(normalized)
|
||||
if (!record) continue
|
||||
// 回补事件不进入环形缓冲:它是补偿,不是「本进程产生过」的事实。
|
||||
record.seq = this.nextSeq
|
||||
this.nextSeq += 1
|
||||
this.counters.backfilled += 1
|
||||
this.deliver(state, record, 'db_backfill')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private deliverLive(record: MessageEventRecord): void {
|
||||
for (const state of this.subscribers.values()) {
|
||||
if (state.closed) continue
|
||||
if (state.conversationIds && !state.conversationIds.has(record.conversationId)) continue
|
||||
this.deliver(state, record, 'live')
|
||||
}
|
||||
}
|
||||
|
||||
private deliver(
|
||||
state: SubscriberState,
|
||||
record: MessageEventRecord,
|
||||
origin: MessageEventOrigin
|
||||
): void {
|
||||
if (state.closed) return
|
||||
if (state.conversationIds && !state.conversationIds.has(record.conversationId)) return
|
||||
if (state.deliveredIds.has(record.id)) return
|
||||
|
||||
state.deliveredIds.set(record.id, this.now())
|
||||
this.trimSubscriberSeen(state)
|
||||
state.lastDeliveredSeq = record.seq
|
||||
state.delivered += 1
|
||||
try {
|
||||
state.sink.onEvent(record, origin)
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[MessageEventBroker] subscriber sink threw: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private toRecord(message: NormalizedIncomingMessage): MessageEventRecord | null {
|
||||
const conversationId = this.options.resolveConversationId(message.sessionId)
|
||||
if (!conversationId) {
|
||||
this.counters.unmapped += 1
|
||||
return null
|
||||
}
|
||||
let messageRef: string
|
||||
try {
|
||||
messageRef = encodeMessageRef(conversationId, message.localId)
|
||||
} catch (error) {
|
||||
this.counters.rejected += 1
|
||||
console.warn(
|
||||
`[MessageEventBroker] messageRef rejected: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
const rawText = message.content ?? ''
|
||||
const truncated = rawText.length > this.maxTextChars
|
||||
return {
|
||||
id: eventIdFor(conversationId, message.localId),
|
||||
seq: 0,
|
||||
conversationId,
|
||||
messageRef,
|
||||
timestamp: message.createTime,
|
||||
messageType: message.messageType,
|
||||
isSelf: message.isSelf,
|
||||
isGroup: message.isGroup,
|
||||
...(message.senderId ? { senderId: message.senderId } : {}),
|
||||
...(message.senderNickname ? { senderNickname: message.senderNickname } : {}),
|
||||
...(rawText ? { text: truncated ? rawText.slice(0, this.maxTextChars) : rawText } : {}),
|
||||
...(truncated ? { textTruncated: true } : {}),
|
||||
mentionTargets: message.mentionTargets
|
||||
}
|
||||
}
|
||||
|
||||
private trimBuffer(): void {
|
||||
const cutoff = this.now() - this.bufferTtlMs
|
||||
while (this.buffer.length > 0) {
|
||||
const oldest = this.buffer[0]
|
||||
const expired = oldest.timestamp * 1000 < cutoff
|
||||
if (this.buffer.length <= this.bufferSize && !expired) break
|
||||
this.buffer.shift()
|
||||
if (this.index.get(oldest.id) === oldest.seq) this.index.delete(oldest.id)
|
||||
}
|
||||
}
|
||||
|
||||
private evictSeen(now: number): void {
|
||||
for (const [id, seenAt] of this.seen) {
|
||||
if (now - seenAt <= this.seenTtlMs) break
|
||||
this.seen.delete(id)
|
||||
}
|
||||
}
|
||||
|
||||
private trimSeen(): void {
|
||||
if (this.seen.size <= this.seenMaxEntries) return
|
||||
const overflow = this.seen.size - this.seenMaxEntries
|
||||
let removed = 0
|
||||
for (const id of this.seen.keys()) {
|
||||
this.seen.delete(id)
|
||||
removed += 1
|
||||
if (removed >= overflow) break
|
||||
}
|
||||
}
|
||||
|
||||
private trimSubscriberSeen(state: SubscriberState): void {
|
||||
if (state.deliveredIds.size <= DEFAULT_SUBSCRIBER_SEEN_MAX) return
|
||||
const overflow = state.deliveredIds.size - DEFAULT_SUBSCRIBER_SEEN_MAX
|
||||
let removed = 0
|
||||
for (const id of state.deliveredIds.keys()) {
|
||||
state.deliveredIds.delete(id)
|
||||
removed += 1
|
||||
if (removed >= overflow) break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 同一会话 + 同一条消息的确定性事件 ID。 */
|
||||
export function eventIdFor(conversationId: string, localId: string): string {
|
||||
return `evt_${createHash('sha256')
|
||||
.update(`${conversationId}\u0000${localId}`, 'utf8')
|
||||
.digest('hex')
|
||||
.slice(0, 24)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 SSE `Last-Event-ID`。
|
||||
*
|
||||
* 只接受纯数字序号;其它形态(含上一版本客户端可能发来的任意字符串)
|
||||
* 一律当成「没有游标」而不是猜一个位置 —— 猜错会导致静默漏消息。
|
||||
*/
|
||||
export function parseLastEventId(value: unknown): number | null {
|
||||
if (typeof value !== 'string' || !value.trim()) return null
|
||||
const trimmed = value.trim()
|
||||
if (!/^\d{1,15}$/.test(trimmed)) return null
|
||||
const parsed = Number(trimmed)
|
||||
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null
|
||||
}
|
||||
@@ -101,6 +101,8 @@ export interface MessageListenerStats {
|
||||
delivered: number
|
||||
/** 因 dedup 被丢弃的重复投递数。 */
|
||||
deduped: number
|
||||
/** 单个会话回读失败的次数(不中断同批其他会话)。 */
|
||||
failedReadbacks: number
|
||||
}
|
||||
|
||||
export interface MessageListenerOptions {
|
||||
@@ -186,6 +188,43 @@ export function decodeSourcePayload(value: unknown): string | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 WCDB 行规范化为克制的 DTO。返回 null 表示这条行缺关键标识,无法投递。
|
||||
*
|
||||
* 纯函数,**唯一**的规范化实现:实时回读与数据库回补都走这里,
|
||||
* 避免两条路径对同一条消息给出不同字段。
|
||||
*/
|
||||
export function normalizeIncomingMessage(
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 实时消息监听。
|
||||
*
|
||||
@@ -233,7 +272,8 @@ export class MessageListenerService {
|
||||
coalescedEvents: 0,
|
||||
readbacks: 0,
|
||||
delivered: 0,
|
||||
deduped: 0
|
||||
deduped: 0,
|
||||
failedReadbacks: 0
|
||||
}
|
||||
|
||||
constructor(
|
||||
@@ -323,12 +363,27 @@ export class MessageListenerService {
|
||||
try {
|
||||
let delivered = 0
|
||||
let sessions = 0
|
||||
let failures = 0
|
||||
|
||||
if (preciseSessions.length > 0) {
|
||||
for (const sessionId of preciseSessions) {
|
||||
if (this.disposed) return
|
||||
delivered += await this.readbackSession(sessionId)
|
||||
sessions += 1
|
||||
try {
|
||||
delivered += await this.readbackSession(sessionId)
|
||||
sessions += 1
|
||||
} catch (error) {
|
||||
/*
|
||||
* 单个会话读失败不能中断整批:pending 已在批次开始时清空,
|
||||
* 跳出循环会让本批其余会话静默丢失。
|
||||
*/
|
||||
failures += 1
|
||||
this.counters.failedReadbacks += 1
|
||||
console.warn(
|
||||
`[MessageListener] session readback failed: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// legacy:旧 runtime 的 payload 不带会话,只能回读「最近活跃会话」。
|
||||
@@ -338,11 +393,12 @@ export class MessageListenerService {
|
||||
sessions = 1
|
||||
}
|
||||
|
||||
if (delivered > 0) {
|
||||
if (delivered > 0 || failures > 0) {
|
||||
// 日志只记录协议版本、数量与耗时 —— **不含** wxid / 群名 / 昵称 / 正文 / source / sessionId。
|
||||
console.log(
|
||||
`[MessageListener] protocol=${preciseSessions.length > 0 ? 'v2' : 'v1'}` +
|
||||
` sessions=${sessions} delivered=${delivered} readbackMs=${Date.now() - startedAt}` +
|
||||
` sessions=${sessions} delivered=${delivered} failures=${failures}` +
|
||||
` readbackMs=${Date.now() - startedAt}` +
|
||||
` events=${this.counters.nativeEvents} coalesced=${this.counters.coalescedEvents}`
|
||||
)
|
||||
}
|
||||
@@ -411,31 +467,7 @@ export class MessageListenerService {
|
||||
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)
|
||||
}
|
||||
return normalizeIncomingMessage(sessionUsername, message)
|
||||
}
|
||||
|
||||
/** 登记并返回「是否是第一次见到」。同时做 TTL + 容量淘汰。 */
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
import type { AgentTaskReply, AgentTaskReplyRole } from '../../shared/agent-task'
|
||||
import {
|
||||
AgentTaskProvider,
|
||||
AgentTaskProviderError,
|
||||
type AgentTaskProviderRequestOptions
|
||||
} from './agent-task-provider'
|
||||
import type { WorkBuddyCredentials } from './agent-task-config'
|
||||
|
||||
/**
|
||||
* WorkBuddy Local Assistant 适配器。
|
||||
*
|
||||
* 契约来源(未在本仓库实测的部分会在下方逐条标注):
|
||||
* - `GET /openapi/v2/localassistant` → `data.online`
|
||||
* - `POST /openapi/v2/localassistant/message` → `data.message_id`
|
||||
* - `GET /openapi/v2/localassistant/message?message_id=...` → 增量回复
|
||||
* - `POST /openapi/v2/token` → refresh
|
||||
*
|
||||
* **未实测**:
|
||||
* 1. assistant 回复是否一定出现在 `message_id` 之后、是否保证只出现一次;
|
||||
* 2. 真实账号下 refresh_token 是否轮换;
|
||||
* 3. `content[]` 里除 `text` 之外的实际片段类型。
|
||||
* 因此第一版把「看到任意一条 assistant 回复」当作任务完成,而不是猜更细的状态机。
|
||||
*
|
||||
* **安全边界**:
|
||||
* - 凭证只从构造参数来(由 `loadWorkBuddyCredentials()` 读环境变量),本文件零硬编码;
|
||||
* - 错误信息里只放 HTTP 状态与业务 `code`,不回显请求头或 token。
|
||||
*/
|
||||
|
||||
const LOCAL_ASSISTANT_PATH = '/openapi/v2/localassistant'
|
||||
const LOCAL_ASSISTANT_MESSAGE_PATH = '/openapi/v2/localassistant/message'
|
||||
const TOKEN_PATH = '/openapi/v2/token'
|
||||
/** 提前 60 秒刷新,避免边界上刚好过期。 */
|
||||
const TOKEN_EXPIRY_SKEW_MS = 60_000
|
||||
|
||||
interface WorkBuddyEnvelope<T> {
|
||||
code?: number
|
||||
msg?: string
|
||||
request_id?: string
|
||||
data?: T
|
||||
}
|
||||
|
||||
export interface WorkBuddyProviderOptions {
|
||||
baseUrl: string
|
||||
timeoutMs: number
|
||||
credentials: WorkBuddyCredentials
|
||||
fetchImpl?: typeof fetch
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
export class WorkBuddyAccessTokenSource {
|
||||
private cached: { token: string; expiresAt: number } | null = null
|
||||
private readonly fetchImpl: typeof fetch
|
||||
private readonly now: () => number
|
||||
|
||||
constructor(private readonly options: WorkBuddyProviderOptions) {
|
||||
this.fetchImpl = options.fetchImpl ?? fetch
|
||||
this.now = options.now ?? Date.now
|
||||
}
|
||||
|
||||
/** 丢弃缓存。收到 401 时由 provider 调用,下一次会强制 refresh。 */
|
||||
invalidate(): void {
|
||||
this.cached = null
|
||||
}
|
||||
|
||||
async getAccessToken(forceRefresh = false): Promise<string> {
|
||||
const credentials = this.options.credentials
|
||||
|
||||
if (!forceRefresh && this.cached && this.now() < this.cached.expiresAt) {
|
||||
return this.cached.token
|
||||
}
|
||||
|
||||
if (!forceRefresh && credentials.accessToken) {
|
||||
// 静态 token 没有过期信息:先用,遇到 401 再走 refresh。
|
||||
this.cached = { token: credentials.accessToken, expiresAt: Number.POSITIVE_INFINITY }
|
||||
return credentials.accessToken
|
||||
}
|
||||
|
||||
if (credentials.refreshToken && credentials.clientId && credentials.clientSecret) {
|
||||
const token = await this.refresh(credentials)
|
||||
this.cached = {
|
||||
token: token.accessToken,
|
||||
expiresAt: this.now() + Math.max(60, token.expiresIn) * 1000 - TOKEN_EXPIRY_SKEW_MS
|
||||
}
|
||||
return token.accessToken
|
||||
}
|
||||
|
||||
if (credentials.accessToken) {
|
||||
throw new AgentTaskProviderError(
|
||||
'auth_expired',
|
||||
'WorkBuddy access_token 已失效,且没有配置 refresh_token',
|
||||
false,
|
||||
401
|
||||
)
|
||||
}
|
||||
throw new AgentTaskProviderError('auth_missing', '未配置 WorkBuddy 访问凭证', false)
|
||||
}
|
||||
|
||||
private async refresh(
|
||||
credentials: WorkBuddyCredentials
|
||||
): Promise<{ accessToken: string; expiresIn: number }> {
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: String(credentials.refreshToken),
|
||||
client_id: String(credentials.clientId),
|
||||
client_secret: String(credentials.clientSecret)
|
||||
})
|
||||
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), this.options.timeoutMs)
|
||||
let response: Response
|
||||
try {
|
||||
response = await this.fetchImpl(`${this.options.baseUrl}${TOKEN_PATH}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body,
|
||||
signal: controller.signal
|
||||
})
|
||||
} catch (error) {
|
||||
throw classifyTokenFailure(error)
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
|
||||
const envelope = await readEnvelope(response)
|
||||
if (!response.ok || (typeof envelope.code === 'number' && envelope.code !== 0)) {
|
||||
throw new AgentTaskProviderError(
|
||||
'auth_expired',
|
||||
`WorkBuddy 凭证刷新失败(HTTP ${response.status}${envelope.msg ? `:${envelope.msg}` : ''})`,
|
||||
false,
|
||||
response.status
|
||||
)
|
||||
}
|
||||
|
||||
const data = envelope.data as { access_token?: unknown; expires_in?: unknown } | undefined
|
||||
if (!data || typeof data.access_token !== 'string' || !data.access_token) {
|
||||
throw new AgentTaskProviderError('invalid_response', 'WorkBuddy 刷新响应缺少 access_token')
|
||||
}
|
||||
return {
|
||||
accessToken: data.access_token,
|
||||
expiresIn: typeof data.expires_in === 'number' ? data.expires_in : 3600
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkBuddyAgentTaskProvider implements AgentTaskProvider {
|
||||
readonly id = 'workbuddy'
|
||||
private readonly tokenSource: WorkBuddyAccessTokenSource
|
||||
private readonly fetchImpl: typeof fetch
|
||||
|
||||
constructor(private readonly options: WorkBuddyProviderOptions) {
|
||||
this.tokenSource = new WorkBuddyAccessTokenSource(options)
|
||||
this.fetchImpl = options.fetchImpl ?? fetch
|
||||
}
|
||||
|
||||
async checkOnline(options: AgentTaskProviderRequestOptions = {}): Promise<boolean> {
|
||||
const data = await this.request<{ online?: unknown }>(
|
||||
'GET',
|
||||
LOCAL_ASSISTANT_PATH,
|
||||
undefined,
|
||||
options
|
||||
)
|
||||
return data?.online === true
|
||||
}
|
||||
|
||||
async submitTask(
|
||||
input: { content: string },
|
||||
options: AgentTaskProviderRequestOptions = {}
|
||||
): Promise<{ messageId: string }> {
|
||||
const data = await this.request<{ message_id?: unknown }>(
|
||||
'POST',
|
||||
`${LOCAL_ASSISTANT_PATH}/message`,
|
||||
{ content: input.content, msg_type: 'text' },
|
||||
options
|
||||
)
|
||||
if (!data || typeof data.message_id !== 'string' || !data.message_id) {
|
||||
throw new AgentTaskProviderError('invalid_response', 'WorkBuddy 投递响应缺少 message_id')
|
||||
}
|
||||
return { messageId: data.message_id }
|
||||
}
|
||||
|
||||
async fetchReplies(
|
||||
afterMessageId: string,
|
||||
options: AgentTaskProviderRequestOptions & { limit?: number } = {}
|
||||
): Promise<AgentTaskReply[]> {
|
||||
const query = new URLSearchParams({
|
||||
message_id: afterMessageId,
|
||||
limit: String(Math.max(1, Math.min(options.limit ?? 20, 100)))
|
||||
})
|
||||
const data = await this.request<unknown>(
|
||||
'GET',
|
||||
`${LOCAL_ASSISTANT_MESSAGE_PATH}?${query.toString()}`,
|
||||
undefined,
|
||||
options
|
||||
)
|
||||
return parseReplies(data)
|
||||
}
|
||||
|
||||
private async request<T>(
|
||||
method: 'GET' | 'POST',
|
||||
path: string,
|
||||
body: unknown | undefined,
|
||||
options: AgentTaskProviderRequestOptions,
|
||||
retried = false
|
||||
): Promise<T> {
|
||||
const token = await this.tokenSource.getAccessToken(retried)
|
||||
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), this.options.timeoutMs)
|
||||
const signal = options.signal
|
||||
? AbortSignal.any([controller.signal, options.signal])
|
||||
: controller.signal
|
||||
|
||||
let response: Response
|
||||
try {
|
||||
response = await this.fetchImpl(`${this.options.baseUrl}${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
...(body !== undefined ? { 'Content-Type': 'application/json' } : {})
|
||||
},
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
signal
|
||||
})
|
||||
} catch (error) {
|
||||
throw classifyRequestFailure(error, options.signal)
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
|
||||
if (response.status === 401) {
|
||||
if (!retried) {
|
||||
this.tokenSource.invalidate()
|
||||
return this.request<T>(method, path, body, options, true)
|
||||
}
|
||||
throw new AgentTaskProviderError('auth_expired', 'WorkBuddy 鉴权失败(HTTP 401)', false, 401)
|
||||
}
|
||||
if (response.status === 403) {
|
||||
throw new AgentTaskProviderError(
|
||||
'auth_expired',
|
||||
'WorkBuddy 授权不足(HTTP 403,检查 scope)',
|
||||
false,
|
||||
403
|
||||
)
|
||||
}
|
||||
|
||||
const envelope = await readEnvelope(response)
|
||||
if (!response.ok) {
|
||||
const retryable = response.status === 429 || response.status >= 500
|
||||
throw new AgentTaskProviderError(
|
||||
'http_error',
|
||||
`WorkBuddy 请求失败(HTTP ${response.status}${envelope.msg ? `:${envelope.msg}` : ''})`,
|
||||
retryable,
|
||||
response.status
|
||||
)
|
||||
}
|
||||
if (typeof envelope.code === 'number' && envelope.code !== 0) {
|
||||
throw new AgentTaskProviderError(
|
||||
'http_error',
|
||||
`WorkBuddy 业务错误(code=${envelope.code}${envelope.msg ? `:${envelope.msg}` : ''})`
|
||||
)
|
||||
}
|
||||
return envelope.data as T
|
||||
}
|
||||
}
|
||||
|
||||
async function readEnvelope(response: Response): Promise<WorkBuddyEnvelope<unknown>> {
|
||||
let text = ''
|
||||
try {
|
||||
text = await response.text()
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
if (!text) return {}
|
||||
try {
|
||||
const parsed = JSON.parse(text) as unknown
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
return parsed as WorkBuddyEnvelope<unknown>
|
||||
}
|
||||
} catch {
|
||||
// 非 JSON 响应:保留 HTTP 状态,交给调用方按 invalid_response 处理。
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
function classifyTokenFailure(error: unknown): AgentTaskProviderError {
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
return new AgentTaskProviderError('timeout', 'WorkBuddy 凭证刷新超时', true)
|
||||
}
|
||||
return new AgentTaskProviderError(
|
||||
'http_error',
|
||||
`WorkBuddy 凭证刷新请求失败:${error instanceof Error ? error.message : String(error)}`,
|
||||
true
|
||||
)
|
||||
}
|
||||
|
||||
function classifyRequestFailure(
|
||||
error: unknown,
|
||||
externalSignal?: AbortSignal
|
||||
): AgentTaskProviderError {
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
if (externalSignal?.aborted) {
|
||||
return new AgentTaskProviderError('internal', 'WorkBuddy 请求已取消')
|
||||
}
|
||||
return new AgentTaskProviderError('timeout', 'WorkBuddy 请求超时', true)
|
||||
}
|
||||
return new AgentTaskProviderError(
|
||||
'http_error',
|
||||
`WorkBuddy 请求失败:${error instanceof Error ? error.message : String(error)}`,
|
||||
true
|
||||
)
|
||||
}
|
||||
|
||||
function roleOf(value: unknown): AgentTaskReplyRole {
|
||||
if (value === 'assistant') return 'assistant'
|
||||
if (value === 'user') return 'user'
|
||||
return 'other'
|
||||
}
|
||||
|
||||
function extractText(content: unknown): string {
|
||||
if (typeof content === 'string') return content
|
||||
if (!Array.isArray(content)) return ''
|
||||
const parts: string[] = []
|
||||
for (const part of content) {
|
||||
if (typeof part === 'string') {
|
||||
parts.push(part)
|
||||
continue
|
||||
}
|
||||
if (part && typeof part === 'object' && typeof (part as { text?: unknown }).text === 'string') {
|
||||
parts.push((part as { text: string }).text)
|
||||
}
|
||||
}
|
||||
return parts.join('\n').trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 `messages[]`。
|
||||
*
|
||||
* 兼容 `data.messages` 与 `data` 直接是数组两种形态(契约文档只写了前者,
|
||||
* 但历史接口在分页/增量下出现过裸数组,这里不做假设性拒绝)。
|
||||
*/
|
||||
export function parseReplies(data: unknown): AgentTaskReply[] {
|
||||
const list = Array.isArray(data)
|
||||
? data
|
||||
: data && typeof data === 'object' && Array.isArray((data as { messages?: unknown }).messages)
|
||||
? (data as { messages: unknown[] }).messages
|
||||
: []
|
||||
|
||||
const replies: AgentTaskReply[] = []
|
||||
for (const item of list) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
const record = item as Record<string, unknown>
|
||||
const messageId =
|
||||
typeof record.message_id === 'string'
|
||||
? record.message_id
|
||||
: typeof record.messageId === 'string'
|
||||
? record.messageId
|
||||
: ''
|
||||
if (!messageId) continue
|
||||
replies.push({
|
||||
messageId,
|
||||
role: roleOf(record.role),
|
||||
text: extractText(record.content),
|
||||
...(typeof record.created_at === 'string' ? { createdAt: record.created_at } : {})
|
||||
})
|
||||
}
|
||||
return replies
|
||||
}
|
||||
Reference in new issue
Block a user