mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: 新增 API(capabilities / 退群监控 / 自动化 / 群统计)
This commit is contained in:
1 parent
e83e85fe64
commit
713232bd62
20 files changed
+3637
-135
No files matched your search
+417
-66
@@ -1,5 +1,6 @@
|
||||
import crypto from 'crypto'
|
||||
import http, { IncomingMessage, ServerResponse, Server } from 'http'
|
||||
import { app } from 'electron'
|
||||
import {
|
||||
isReady,
|
||||
listContacts,
|
||||
@@ -28,6 +29,11 @@ import { safeError, safeLog, safeWarn } from './safe-log'
|
||||
import { apiTokenStore } from './api-token-store'
|
||||
import { HttpMediaError, readImageMedia, type HttpImageResult } from './http-media-service'
|
||||
import { LocalQueryApiService } from './services/local-query-api-service'
|
||||
import { automationRuleStore, AutomationRulePersistenceError } from './services/automation-rule-store'
|
||||
import { automationExecutionLogService } from './services/automation-execution-log-service'
|
||||
import { groupExitMonitorService } from './services/group-exit-monitor-service'
|
||||
import { LocalAgentApiError, LocalAgentApiService } from './services/local-agent-api-service'
|
||||
import type { GroupStatsService } from './services/group-stats-service'
|
||||
|
||||
export const DEFAULT_HTTP_HOST = '127.0.0.1'
|
||||
export const DEFAULT_HTTP_PORT = 6131
|
||||
@@ -45,6 +51,11 @@ interface RouteContext {
|
||||
body?: unknown
|
||||
}
|
||||
|
||||
type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE'
|
||||
type RouteHandler = ((ctx: RouteContext) => void | Promise<void>) & {
|
||||
allowedMethods: readonly HttpMethod[]
|
||||
}
|
||||
|
||||
export interface HttpServerOptions {
|
||||
tokenProvider?: () => string | null
|
||||
mediaProvider?: (messageId: string) => Promise<HttpImageResult>
|
||||
@@ -54,21 +65,56 @@ export interface HttpServerOptions {
|
||||
scheduledReportDatabaseReadyProvider?: ScheduledReportApiDependencies['isDatabaseReady']
|
||||
scheduledReportPlatform?: NodeJS.Platform
|
||||
queryApiService?: LocalQueryApiService
|
||||
agentApiService?: LocalAgentApiService
|
||||
groupStatsService?: Pick<GroupStatsService, 'getMemberStats'>
|
||||
appVersionProvider?: () => string
|
||||
}
|
||||
|
||||
let configuredQueryApiService: LocalQueryApiService | undefined
|
||||
let configuredGroupStatsService: Pick<GroupStatsService, 'getMemberStats'> | undefined
|
||||
export function setLocalQueryApiService(service: LocalQueryApiService | undefined): void {
|
||||
configuredQueryApiService = service
|
||||
}
|
||||
|
||||
type RouteHandler = (ctx: RouteContext) => void | Promise<void>
|
||||
export function setLocalGroupStatsService(
|
||||
service: Pick<GroupStatsService, 'getMemberStats'> | undefined
|
||||
): void {
|
||||
configuredGroupStatsService = service
|
||||
}
|
||||
|
||||
const MAX_JSON_BODY_BYTES = 1024 * 1024
|
||||
|
||||
class RequestBodyTooLargeError extends Error {
|
||||
constructor() {
|
||||
super('Request body exceeds the maximum size')
|
||||
this.name = 'RequestBodyTooLargeError'
|
||||
}
|
||||
}
|
||||
|
||||
function withMethods(
|
||||
methods: readonly HttpMethod[],
|
||||
handler: (ctx: RouteContext) => void | Promise<void>
|
||||
): RouteHandler {
|
||||
return Object.assign(handler, { allowedMethods: methods })
|
||||
}
|
||||
|
||||
function sendMethodNotAllowed(res: ServerResponse, methods: readonly HttpMethod[]): void {
|
||||
res.setHeader('Allow', methods.join(', '))
|
||||
sendError(res, 405, `请求方法不受支持;允许的方法:${methods.join(', ')}`)
|
||||
}
|
||||
|
||||
function sendJson(res: ServerResponse, status: number, payload: unknown): void {
|
||||
const body = JSON.stringify(payload, null, 2)
|
||||
const requestId = String(res.getHeader('X-Request-Id') || '')
|
||||
let responsePayload = payload
|
||||
if (status >= 400 && payload && typeof payload === 'object' && !('requestId' in payload)) {
|
||||
responsePayload = { ...(payload as Record<string, unknown>), requestId }
|
||||
}
|
||||
const body = JSON.stringify(responsePayload, null, 2)
|
||||
res.writeHead(status, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
'Cache-Control': 'no-store'
|
||||
'Cache-Control': 'no-store',
|
||||
...(requestId ? { 'X-Request-Id': requestId } : {})
|
||||
})
|
||||
res.end(body)
|
||||
}
|
||||
@@ -91,8 +137,8 @@ function applyCorsHeaders(req: IncomingMessage, res: ServerResponse): boolean {
|
||||
if (!isAllowedCorsOrigin(origin)) return false
|
||||
res.setHeader('Access-Control-Allow-Origin', origin)
|
||||
res.setHeader('Vary', 'Origin')
|
||||
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS')
|
||||
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization')
|
||||
res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, POST, PATCH, DELETE, OPTIONS')
|
||||
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Request-Id')
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -112,6 +158,20 @@ function sendUnauthorized(res: ServerResponse): void {
|
||||
})
|
||||
}
|
||||
|
||||
function sendAgentHttpError(
|
||||
res: ServerResponse,
|
||||
status: number,
|
||||
code: string,
|
||||
message: string,
|
||||
details?: unknown
|
||||
): void {
|
||||
const requestId = String(res.getHeader('X-Request-Id') || '')
|
||||
sendJson(res, status, {
|
||||
error: { code, message, ...(details !== undefined ? { details } : {}) },
|
||||
requestId
|
||||
})
|
||||
}
|
||||
|
||||
function sendError(res: ServerResponse, status: number, message: string, extra?: unknown): void {
|
||||
sendJson(res, status, { error: message, status, ...(extra ? { details: extra } : {}) })
|
||||
}
|
||||
@@ -121,7 +181,8 @@ function sendBinary(res: ServerResponse, status: number, result: HttpImageResult
|
||||
'Content-Type': result.mimeType,
|
||||
'Content-Length': result.buffer.length,
|
||||
'Cache-Control': 'private, no-store',
|
||||
'X-Content-Type-Options': 'nosniff'
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'X-Request-Id': String(res.getHeader('X-Request-Id') || '')
|
||||
})
|
||||
res.end(result.buffer)
|
||||
}
|
||||
@@ -136,10 +197,26 @@ function sanitizeChatlogMessage(message: Record<string, unknown>): Record<string
|
||||
return { ...message, contentData: safeContentData }
|
||||
}
|
||||
|
||||
function readBody(req: IncomingMessage): Promise<string> {
|
||||
function readBody(req: IncomingMessage, maxBytes = MAX_JSON_BODY_BYTES): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const contentLength = Number(req.headers['content-length'])
|
||||
if (Number.isFinite(contentLength) && contentLength > maxBytes) {
|
||||
req.pause()
|
||||
reject(new RequestBodyTooLargeError())
|
||||
return
|
||||
}
|
||||
const chunks: Buffer[] = []
|
||||
req.on('data', (chunk: Buffer) => chunks.push(chunk))
|
||||
let size = 0
|
||||
req.on('data', (chunk: Buffer) => {
|
||||
size += chunk.length
|
||||
if (size > maxBytes) {
|
||||
chunks.length = 0
|
||||
req.pause()
|
||||
reject(new RequestBodyTooLargeError())
|
||||
return
|
||||
}
|
||||
chunks.push(chunk)
|
||||
})
|
||||
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')))
|
||||
req.on('error', reject)
|
||||
})
|
||||
@@ -208,18 +285,26 @@ function parseNumeric(value: string | null, fallback: number): number {
|
||||
return Number.isFinite(n) ? n : fallback
|
||||
}
|
||||
|
||||
function getApplicationVersion(): string {
|
||||
try {
|
||||
return typeof app.getVersion === 'function' ? app.getVersion() : 'unknown'
|
||||
} catch {
|
||||
return 'unknown'
|
||||
}
|
||||
}
|
||||
|
||||
const routes: Record<string, RouteHandler> = {
|
||||
'/api/v1/health': ({ res }) => {
|
||||
'/api/v1/health': withMethods(['GET'], ({ res }) => {
|
||||
sendJson(res, 200, {
|
||||
ok: true,
|
||||
ready: isReady(),
|
||||
service: 'TraceMemo Reader',
|
||||
version: '1.0.0',
|
||||
version: getApplicationVersion(),
|
||||
timestamp: new Date().toISOString()
|
||||
})
|
||||
},
|
||||
}),
|
||||
|
||||
'/api/v1/current_time': ({ res }) => {
|
||||
'/api/v1/current_time': withMethods(['GET'], ({ res }) => {
|
||||
const now = new Date()
|
||||
sendJson(res, 200, {
|
||||
time: now.toISOString(),
|
||||
@@ -229,9 +314,9 @@ const routes: Record<string, RouteHandler> = {
|
||||
now.getDate()
|
||||
).padStart(2, '0')}`
|
||||
})
|
||||
},
|
||||
}),
|
||||
|
||||
'/api/v1/contact': async ({ res, url }) => {
|
||||
'/api/v1/contact': withMethods(['GET'], async ({ res, url }) => {
|
||||
if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化')
|
||||
const filter = url.searchParams.get('filter') || undefined
|
||||
const type = url.searchParams.get('type') || undefined
|
||||
@@ -243,9 +328,9 @@ const routes: Record<string, RouteHandler> = {
|
||||
contacts = contacts.filter((c) => c.type === type)
|
||||
}
|
||||
sendJson(res, 200, { count: contacts.length, contacts })
|
||||
},
|
||||
}),
|
||||
|
||||
'/api/v1/chatroom': async ({ res, url }) => {
|
||||
'/api/v1/chatroom': withMethods(['GET'], async ({ res, url }) => {
|
||||
if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化')
|
||||
const keyword = url.searchParams.get('keyword') || ''
|
||||
// Same hydration requirement as /api/v1/contact: group display names are
|
||||
@@ -260,16 +345,16 @@ const routes: Record<string, RouteHandler> = {
|
||||
)
|
||||
}
|
||||
sendJson(res, 200, { count: groups.length, chatrooms: groups })
|
||||
},
|
||||
}),
|
||||
|
||||
'/api/v1/recent_chat': ({ res, url }) => {
|
||||
'/api/v1/recent_chat': withMethods(['GET'], ({ res, url }) => {
|
||||
if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化')
|
||||
const limit = parseNumeric(url.searchParams.get('limit'), 50)
|
||||
const items = listRecentChat(limit)
|
||||
sendJson(res, 200, { count: items.length, items })
|
||||
},
|
||||
}),
|
||||
|
||||
'/api/v1/chatlog': ({ res, url }) => {
|
||||
'/api/v1/chatlog': withMethods(['GET'], ({ res, url }) => {
|
||||
if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化')
|
||||
const talker = url.searchParams.get('talker')
|
||||
if (!talker) return sendError(res, 400, '缺少必要参数 talker')
|
||||
@@ -307,27 +392,27 @@ const routes: Record<string, RouteHandler> = {
|
||||
sanitizeChatlogMessage(message as unknown as Record<string, unknown>)
|
||||
)
|
||||
})
|
||||
},
|
||||
}),
|
||||
|
||||
'/api/v1/group_snapshot': ({ res, url }) => {
|
||||
'/api/v1/group_snapshot': withMethods(['GET'], ({ res, url }) => {
|
||||
if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化')
|
||||
const md5 = url.searchParams.get('md5')
|
||||
if (!md5) return sendError(res, 400, '缺少必要参数 md5')
|
||||
const snapshot = getGroupSnapshot(md5)
|
||||
if (!snapshot) return sendError(res, 404, `未找到群聊: ${md5}`)
|
||||
sendJson(res, 200, snapshot)
|
||||
},
|
||||
}),
|
||||
|
||||
'/api/v1/resolve': ({ res, url }) => {
|
||||
'/api/v1/resolve': withMethods(['GET'], ({ res, url }) => {
|
||||
if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化')
|
||||
const q = url.searchParams.get('q')
|
||||
if (!q) return sendError(res, 400, '缺少必要参数 q')
|
||||
const contact = resolveMd5(q)
|
||||
if (!contact) return sendError(res, 404, `未匹配到联系人: ${q}`)
|
||||
sendJson(res, 200, contact)
|
||||
},
|
||||
}),
|
||||
|
||||
'/api/v1/report': async ({ req, res, body }) => {
|
||||
'/api/v1/report': withMethods(['POST'], async ({ req, res, body }) => {
|
||||
if (req.method !== 'POST') return sendError(res, 405, '需要 POST 请求')
|
||||
if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化')
|
||||
if (typeof body !== 'string' || !body.trim()) {
|
||||
@@ -354,9 +439,9 @@ const routes: Record<string, RouteHandler> = {
|
||||
}
|
||||
const result = await exportGroupReport(request)
|
||||
sendJson(res, result.success ? 200 : 500, result)
|
||||
},
|
||||
}),
|
||||
|
||||
'/api/v1/agent/group-report': async ({ req, res, body }) => {
|
||||
'/api/v1/agent/group-report': withMethods(['POST'], async ({ req, res, body }) => {
|
||||
if (req.method !== 'POST') return sendError(res, 405, '需要 POST 请求')
|
||||
if (!isReady()) return sendError(res, 503, 'TraceMemo 数据库未初始化')
|
||||
let request: { group?: string; range?: 'today' | 'yesterday' | '7days' }
|
||||
@@ -370,9 +455,9 @@ const routes: Record<string, RouteHandler> = {
|
||||
range: request.range
|
||||
})
|
||||
sendJson(res, result.success ? 200 : 400, result)
|
||||
},
|
||||
}),
|
||||
|
||||
'/api/v1/agent/status': ({ res }) => {
|
||||
'/api/v1/agent/status': withMethods(['GET'], ({ res }) => {
|
||||
const status = agentHubService.getStatus()
|
||||
sendJson(res, 200, {
|
||||
ok: status.hub === 'online' && status.connector === 'online',
|
||||
@@ -382,9 +467,9 @@ const routes: Record<string, RouteHandler> = {
|
||||
databaseReady: status.databaseReady,
|
||||
accountId: status.accountId
|
||||
})
|
||||
},
|
||||
}),
|
||||
|
||||
'/api/v1/agent/send': async ({ req, res, body }) => {
|
||||
'/api/v1/agent/send': withMethods(['POST'], async ({ req, res, body }) => {
|
||||
if (req.method !== 'POST') return sendError(res, 405, '需要 POST 请求')
|
||||
let request: { to?: string; text?: string; media_url?: string }
|
||||
try {
|
||||
@@ -398,7 +483,7 @@ const routes: Record<string, RouteHandler> = {
|
||||
mediaUrl: request.media_url
|
||||
})
|
||||
sendJson(res, result.success ? 200 : result.status === 'token_expired' ? 401 : 503, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const SCHEDULED_REPORTS_ROUTE = '/api/v1/scheduled-reports'
|
||||
@@ -448,18 +533,18 @@ function createScheduledReportRoute(
|
||||
api: ScheduledReportApiService
|
||||
): RouteHandler | undefined {
|
||||
if (pathname === WECHAT_SEND_CAPABILITY_ROUTE) {
|
||||
return async ({ req, res }) => {
|
||||
return withMethods(['GET'], async ({ req, res }) => {
|
||||
if (req.method !== 'GET') return sendError(res, 405, '需要 GET 请求')
|
||||
try {
|
||||
sendJson(res, 200, { capability: await api.getCapability() })
|
||||
} catch (error) {
|
||||
sendScheduledError(res, error)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (pathname === SCHEDULED_REPORTS_ROUTE) {
|
||||
return async ({ req, res, body }) => {
|
||||
return withMethods(['GET', 'POST'], async ({ req, res, body }) => {
|
||||
try {
|
||||
if (req.method === 'GET') {
|
||||
const tasks = await api.list()
|
||||
@@ -475,7 +560,7 @@ function createScheduledReportRoute(
|
||||
} catch (error) {
|
||||
sendScheduledError(res, error)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const retryPrefix = `${SCHEDULED_REPORTS_ROUTE}/executions/`
|
||||
@@ -488,7 +573,7 @@ function createScheduledReportRoute(
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
return async ({ req, res }) => {
|
||||
return withMethods(['POST'], async ({ req, res }) => {
|
||||
if (req.method !== 'POST') return sendError(res, 405, '需要 POST 请求')
|
||||
try {
|
||||
const execution = await api.retrySend(executionId)
|
||||
@@ -496,7 +581,7 @@ function createScheduledReportRoute(
|
||||
} catch (error) {
|
||||
sendScheduledError(res, error)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const prefix = `${SCHEDULED_REPORTS_ROUTE}/`
|
||||
@@ -510,8 +595,15 @@ function createScheduledReportRoute(
|
||||
return undefined
|
||||
}
|
||||
const action = segments[1]
|
||||
if (action && !['enable', 'disable', 'run', 'executions'].includes(action)) return undefined
|
||||
|
||||
return async ({ req, res, body }) => {
|
||||
const methods: HttpMethod[] = !action
|
||||
? ['GET', 'PATCH', 'DELETE']
|
||||
: action === 'executions'
|
||||
? ['GET']
|
||||
: ['POST']
|
||||
|
||||
return withMethods(methods, async ({ req, res, body }) => {
|
||||
try {
|
||||
if (!action && req.method === 'GET') {
|
||||
sendJson(res, 200, { task: await api.get(taskId) })
|
||||
@@ -551,7 +643,7 @@ function createScheduledReportRoute(
|
||||
} catch (error) {
|
||||
sendScheduledError(res, error)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const MEDIA_ROUTE_PREFIX = '/api/v1/media/'
|
||||
@@ -566,42 +658,46 @@ function queryStatusCode(status: string): number {
|
||||
return 400
|
||||
}
|
||||
|
||||
function createQueryRoute(api: LocalQueryApiService): RouteHandler | undefined {
|
||||
return async ({ req, res, body }) => {
|
||||
const pathname = new URL(req.url || '/', 'http://localhost').pathname
|
||||
if (pathname === '/api/v1/query/capabilities') {
|
||||
if (req.method !== 'GET') return sendError(res, 405, '需要 GET 请求')
|
||||
function createQueryRoute(pathname: string, api: LocalQueryApiService): RouteHandler | undefined {
|
||||
if (pathname === '/api/v1/query/capabilities') {
|
||||
return withMethods(['GET'], ({ res }) => {
|
||||
return sendJson(res, 200, api.capabilities())
|
||||
}
|
||||
if (req.method !== 'POST') return sendError(res, 405, '需要 POST 请求')
|
||||
let payload: any
|
||||
})
|
||||
}
|
||||
type QueryOperationResult =
|
||||
| Awaited<ReturnType<LocalQueryApiService['messages']>>
|
||||
| Awaited<ReturnType<LocalQueryApiService['search']>>
|
||||
| Awaited<ReturnType<LocalQueryApiService['context']>>
|
||||
| Awaited<ReturnType<LocalQueryApiService['overview']>>
|
||||
const operations: Record<string, (payload: unknown) => Promise<QueryOperationResult>> = {
|
||||
'/api/v1/query/messages': (payload) =>
|
||||
api.messages(payload as Parameters<LocalQueryApiService['messages']>[0]),
|
||||
'/api/v1/query/search': (payload) =>
|
||||
api.search(payload as Parameters<LocalQueryApiService['search']>[0]),
|
||||
'/api/v1/query/message-context': (payload) =>
|
||||
api.context(payload as Parameters<LocalQueryApiService['context']>[0]),
|
||||
'/api/v1/query/conversation-overview': (payload) =>
|
||||
api.overview(payload as Parameters<LocalQueryApiService['overview']>[0])
|
||||
}
|
||||
const operation = operations[pathname]
|
||||
if (!operation) return undefined
|
||||
return withMethods(['POST'], async ({ res, body }) => {
|
||||
let payload: unknown
|
||||
try { payload = JSON.parse(typeof body === 'string' ? body : '') } catch { return sendError(res, 400, 'invalid_request') }
|
||||
if (!payload || typeof payload !== 'object') return sendError(res, 400, 'invalid_request')
|
||||
try {
|
||||
const result = pathname === '/api/v1/query/messages'
|
||||
? await api.messages(payload)
|
||||
: pathname === '/api/v1/query/search'
|
||||
? await api.search(payload)
|
||||
: pathname === '/api/v1/query/message-context'
|
||||
? await api.context(payload)
|
||||
: pathname === '/api/v1/query/conversation-overview'
|
||||
? await api.overview(payload)
|
||||
: undefined
|
||||
if (!result) return sendError(res, 404, `端点不存在: ${pathname}`)
|
||||
const result = await operation(payload)
|
||||
return sendJson(res, queryStatusCode(result.status), result)
|
||||
} catch (error) {
|
||||
return sendError(res, 400, error instanceof Error ? error.message : 'invalid_request')
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function createMediaRoute(
|
||||
mediaProvider: (messageId: string) => Promise<HttpImageResult>
|
||||
): RouteHandler {
|
||||
return async ({ req, res, url }) => {
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
return sendError(res, 405, '需要 GET 请求')
|
||||
}
|
||||
return withMethods(['GET', 'HEAD'], async ({ req, res, url }) => {
|
||||
const encodedMessageId = url.pathname.slice(MEDIA_ROUTE_PREFIX.length)
|
||||
let messageId: string
|
||||
try {
|
||||
@@ -640,7 +736,218 @@ function createMediaRoute(
|
||||
safeError('[HttpServer] media request failed:', error)
|
||||
return sendError(res, 500, '图片读取失败')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function createAgentApiService(options: HttpServerOptions): LocalAgentApiService {
|
||||
const groupStats = options.groupStatsService || configuredGroupStatsService
|
||||
return options.agentApiService || new LocalAgentApiService({
|
||||
automationRuleStore,
|
||||
automationExecutionLogService,
|
||||
listContacts: listContactsAsync,
|
||||
isDatabaseReady: isReady,
|
||||
getVersion: options.appVersionProvider || getApplicationVersion,
|
||||
getPersonalWechatCapability: () =>
|
||||
personalWechatCapabilityService.getPersonalWechatSendCapability(),
|
||||
getAgentHubStatus: () => agentHubService.getStatus(),
|
||||
getGroupExitMonitorState: () => {
|
||||
const state = groupExitMonitorService.getState()
|
||||
return { ...state, monitoredRoomIds: state.monitoredRoomIds || [] }
|
||||
},
|
||||
configureGroupExitMonitor: (configuration) =>
|
||||
groupExitMonitorService.configure(configuration),
|
||||
setGroupExitMonitorRoomIds: (roomIds) => groupExitMonitorService.setMonitoredRoomIds(roomIds),
|
||||
setGroupExitMonitorEnabled: (enabled) => groupExitMonitorService.setEnabled(enabled),
|
||||
listGroupExitMonitorEvents: (query) => groupExitMonitorService.listEvents(query),
|
||||
...(groupStats ? { getGroupMemberStats: (query) => groupStats.getMemberStats(query) } : {})
|
||||
})
|
||||
}
|
||||
|
||||
function sendAgentApiError(res: ServerResponse, error: unknown): void {
|
||||
const requestId = String(res.getHeader('X-Request-Id') || '')
|
||||
if (error instanceof LocalAgentApiError) {
|
||||
sendAgentHttpError(res, error.status, error.code, error.message, error.details)
|
||||
return
|
||||
}
|
||||
if (error instanceof AutomationRulePersistenceError) {
|
||||
sendAgentHttpError(res, 500, 'PERSISTENCE_FAILED', '自动化规则未能保存到本地')
|
||||
return
|
||||
}
|
||||
safeError(`[HttpServer requestId=${requestId}] Agent API request failed:`, error)
|
||||
sendAgentHttpError(res, 500, 'INTERNAL_ERROR', 'Agent API 请求失败')
|
||||
}
|
||||
|
||||
async function handleAgentApi<T>(
|
||||
res: ServerResponse,
|
||||
operation: () => Promise<T> | T,
|
||||
respond: (value: T) => void
|
||||
): Promise<void> {
|
||||
try {
|
||||
respond(await operation())
|
||||
} catch (error) {
|
||||
sendAgentApiError(res, error)
|
||||
}
|
||||
}
|
||||
|
||||
function parseAgentJson(body: unknown): unknown {
|
||||
if (typeof body !== 'string' || !body.trim()) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', '请求体不能为空')
|
||||
}
|
||||
try {
|
||||
return JSON.parse(body)
|
||||
} catch {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', '请求体 JSON 格式无效')
|
||||
}
|
||||
}
|
||||
|
||||
function createAgentApiRoute(
|
||||
pathname: string,
|
||||
api: LocalAgentApiService
|
||||
): RouteHandler | undefined {
|
||||
if (pathname === '/api/v1/capabilities') {
|
||||
return withMethods(['GET'], ({ res }) =>
|
||||
void handleAgentApi(res, () => api.getCapabilities(), (capabilities) =>
|
||||
sendJson(res, 200, capabilities)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
const groupExitMonitorPath = '/api/v1/monitors/group-exits'
|
||||
if (pathname === groupExitMonitorPath) {
|
||||
return withMethods(['GET', 'PATCH'], async ({ req, res, body }) => {
|
||||
if (req.method === 'GET') {
|
||||
await handleAgentApi(res, () => api.getGroupExitMonitorState(), (state) =>
|
||||
sendJson(res, 200, state)
|
||||
)
|
||||
return
|
||||
}
|
||||
await handleAgentApi(res, () => api.updateGroupExitMonitor(parseAgentJson(body)), (state) =>
|
||||
sendJson(res, 200, state)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
if (pathname === `${groupExitMonitorPath}/events`) {
|
||||
return withMethods(['GET'], ({ res, url }) =>
|
||||
void handleAgentApi(res, () => api.listGroupExitMonitorEvents(url.searchParams), (result) =>
|
||||
sendJson(res, 200, result)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
const groupStatsPrefix = '/api/v1/groups/'
|
||||
if (pathname.startsWith(groupStatsPrefix)) {
|
||||
const segments = pathname.slice(groupStatsPrefix.length).split('/')
|
||||
if (segments.length === 2 && segments[1] === 'member-stats' && segments[0]) {
|
||||
let conversationId: string
|
||||
try {
|
||||
conversationId = decodeURIComponent(segments[0])
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
return withMethods(['GET'], ({ res, url }) =>
|
||||
void handleAgentApi(
|
||||
res,
|
||||
() => api.getGroupMemberStats(conversationId, url.searchParams),
|
||||
(result) => sendJson(res, 200, result)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const automationCollection = '/api/v1/automations'
|
||||
if (pathname === automationCollection) {
|
||||
return withMethods(['GET', 'POST'], async ({ req, res, url, body }) => {
|
||||
if (req.method === 'GET') {
|
||||
await handleAgentApi(
|
||||
res,
|
||||
() => api.listAutomations({
|
||||
type: url.searchParams.get('type'),
|
||||
enabled: url.searchParams.get('enabled')
|
||||
}),
|
||||
(rules) => sendJson(res, 200, { count: rules.length, rules })
|
||||
)
|
||||
return
|
||||
}
|
||||
await handleAgentApi(res, () => api.createAutomation(parseAgentJson(body)), (rule) =>
|
||||
sendJson(res, 201, { created: true, rule })
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
if (pathname === `${automationCollection}/validate`) {
|
||||
return withMethods(['POST'], async ({ res, body }) => {
|
||||
await handleAgentApi(res, () => api.validateAutomation(parseAgentJson(body)), (result) =>
|
||||
sendJson(res, 200, result)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
if (pathname === `${automationCollection}/executions`) {
|
||||
return withMethods(['GET'], ({ res, url }) =>
|
||||
void handleAgentApi(res, () => api.listExecutions(url.searchParams), (result) =>
|
||||
sendJson(res, 200, result)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
const prefix = `${automationCollection}/`
|
||||
if (!pathname.startsWith(prefix)) return undefined
|
||||
const segments = pathname.slice(prefix.length).split('/').filter(Boolean)
|
||||
if (segments.length < 1 || segments.length > 2) return undefined
|
||||
let id: string
|
||||
try {
|
||||
id = decodeURIComponent(segments[0])
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
if (!id || id.includes('/') || id.includes('\\')) return undefined
|
||||
const action = segments[1]
|
||||
if (action && action !== 'enable' && action !== 'disable') return undefined
|
||||
|
||||
if (action) {
|
||||
return withMethods(['POST'], ({ res }) =>
|
||||
void handleAgentApi(res, () => api.setAutomationEnabled(id, action === 'enable'), (rule) =>
|
||||
sendJson(res, 200, { updated: true, rule })
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
return withMethods(['GET', 'PATCH', 'DELETE'], async ({ req, res, body }) => {
|
||||
if (req.method === 'GET') {
|
||||
await handleAgentApi(res, () => api.getAutomation(id), (rule) =>
|
||||
sendJson(res, 200, { rule })
|
||||
)
|
||||
return
|
||||
}
|
||||
if (req.method === 'PATCH') {
|
||||
await handleAgentApi(
|
||||
res,
|
||||
() => api.updateAutomation(id, parseAgentJson(body)),
|
||||
(rule) => sendJson(res, 200, { updated: true, rule })
|
||||
)
|
||||
return
|
||||
}
|
||||
await handleAgentApi(res, () => api.deleteAutomation(id), (result) =>
|
||||
sendJson(res, 200, { deleted: true, ...result })
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
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)
|
||||
? incoming
|
||||
: crypto.randomUUID()
|
||||
}
|
||||
|
||||
function isAgentApiPath(pathname: string): boolean {
|
||||
return pathname === '/api/v1/capabilities' ||
|
||||
pathname === '/api/v1/monitors/group-exits' ||
|
||||
pathname.startsWith('/api/v1/monitors/group-exits/') ||
|
||||
pathname.startsWith('/api/v1/groups/') ||
|
||||
pathname === '/api/v1/automations' ||
|
||||
pathname.startsWith('/api/v1/automations/')
|
||||
}
|
||||
|
||||
export function startHttpServer(
|
||||
@@ -652,11 +959,19 @@ export function startHttpServer(
|
||||
const mediaProvider = options.mediaProvider || readImageMedia
|
||||
const scheduledReportApi = createScheduledReportApi(options)
|
||||
const queryApi = options.queryApiService || configuredQueryApiService || new LocalQueryApiService()
|
||||
const agentApi = createAgentApiService(options)
|
||||
return new Promise((resolve, reject) => {
|
||||
const server: Server = http.createServer(async (req, res) => {
|
||||
const requestId = requestIdFor(req)
|
||||
res.setHeader('X-Request-Id', requestId)
|
||||
let agentApiRequest = false
|
||||
try {
|
||||
const url = new URL(req.url || '/', `http://${host}:${port}`)
|
||||
agentApiRequest = isAgentApiPath(url.pathname)
|
||||
if (!applyCorsHeaders(req, res)) {
|
||||
if (agentApiRequest) {
|
||||
return sendAgentHttpError(res, 403, 'FORBIDDEN', 'Origin 不允许访问本地 API')
|
||||
}
|
||||
return sendError(res, 403, 'Origin 不允许访问本地 API')
|
||||
}
|
||||
if (req.method === 'OPTIONS') {
|
||||
@@ -665,15 +980,37 @@ export function startHttpServer(
|
||||
}
|
||||
const handler =
|
||||
routes[url.pathname] ||
|
||||
createAgentApiRoute(url.pathname, agentApi) ||
|
||||
createScheduledReportRoute(url.pathname, scheduledReportApi) ||
|
||||
(url.pathname.startsWith(QUERY_ROUTE_PREFIX) ? createQueryRoute(queryApi) : undefined) ||
|
||||
(url.pathname.startsWith(QUERY_ROUTE_PREFIX)
|
||||
? createQueryRoute(url.pathname, queryApi)
|
||||
: undefined) ||
|
||||
(url.pathname.startsWith(MEDIA_ROUTE_PREFIX)
|
||||
? createMediaRoute(mediaProvider)
|
||||
: undefined)
|
||||
if (!handler) {
|
||||
if (agentApiRequest) {
|
||||
return sendAgentHttpError(res, 404, 'NOT_FOUND', `端点不存在: ${url.pathname}`)
|
||||
}
|
||||
return sendError(res, 404, `端点不存在: ${url.pathname}`)
|
||||
}
|
||||
if (!handler.allowedMethods.includes(req.method as HttpMethod)) {
|
||||
if (agentApiRequest) {
|
||||
res.setHeader('Allow', handler.allowedMethods.join(', '))
|
||||
return sendAgentHttpError(
|
||||
res,
|
||||
405,
|
||||
'METHOD_NOT_ALLOWED',
|
||||
`请求方法不受支持;允许的方法:${handler.allowedMethods.join(', ')}`,
|
||||
{ allowedMethods: handler.allowedMethods }
|
||||
)
|
||||
}
|
||||
return sendMethodNotAllowed(res, handler.allowedMethods)
|
||||
}
|
||||
if (url.pathname !== '/api/v1/health' && !isAuthorized(req, tokenProvider())) {
|
||||
if (agentApiRequest) {
|
||||
return sendAgentHttpError(res, 401, 'UNAUTHORIZED', 'Valid API token required')
|
||||
}
|
||||
return sendUnauthorized(res)
|
||||
}
|
||||
let body: string | undefined
|
||||
@@ -683,8 +1020,22 @@ export function startHttpServer(
|
||||
const ctx: RouteContext = { req, res, url, body }
|
||||
await handler(ctx)
|
||||
} catch (error) {
|
||||
safeError('[HttpServer] 请求处理失败:', error)
|
||||
if (error instanceof RequestBodyTooLargeError) {
|
||||
res.setHeader('Connection', 'close')
|
||||
res.shouldKeepAlive = false
|
||||
if (agentApiRequest) {
|
||||
sendAgentHttpError(res, 413, 'PAYLOAD_TOO_LARGE', '请求体不能超过 1 MiB')
|
||||
return
|
||||
}
|
||||
sendError(res, 413, '请求体不能超过 1 MiB')
|
||||
return
|
||||
}
|
||||
safeError(`[HttpServer requestId=${requestId}] 请求处理失败:`, error)
|
||||
if (!res.headersSent) {
|
||||
if (agentApiRequest) {
|
||||
sendAgentHttpError(res, 500, 'INTERNAL_ERROR', 'Agent API 请求失败')
|
||||
return
|
||||
}
|
||||
sendError(res, 500, error instanceof Error ? error.message : String(error))
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -76,7 +76,7 @@ import type { SystemOcrCapability, SystemOcrRequest, SystemOcrResult } from '../
|
||||
import { KeyServiceMac } from './key-service-mac'
|
||||
import { KeyService as KeyServiceWin } from './key-service-win'
|
||||
import * as chat from './services/chat-service'
|
||||
import { apiServer, setLocalQueryApiService } from './http-server'
|
||||
import { apiServer, setLocalGroupStatsService, setLocalQueryApiService } from './http-server'
|
||||
import { skillResourceService } from './services/skill-resource-service'
|
||||
import { buildLocalApiCurlCommand, testLocalApiRequest } from './services/local-api-test-service'
|
||||
import { isWechatRunning } from './services/wechat-process-status'
|
||||
@@ -805,6 +805,7 @@ app.whenReady().then(async () => {
|
||||
// 群员统计复用同一个 Knowledge 实例:它只是「读派生库 + 读成员名单」的编排,
|
||||
// 不持有自己的数据库,也不新建索引。
|
||||
groupStatsService = new GroupStatsService(knowledgeSearchService)
|
||||
setLocalGroupStatsService(groupStatsService)
|
||||
// 图片文字索引覆盖度是**独立覆盖维度**:接到 search_messages 的 tool result 上,
|
||||
// 让 Query Agent 在图片索引没做完时不能凭 0 条证据断言"没有"。
|
||||
localQueryApiService.setImageTextCoverageProvider(() =>
|
||||
|
||||
@@ -50,6 +50,13 @@ const LEGACY_SCHEDULED_TASKS_FILE = 'tasks.json'
|
||||
const SCHEDULED_MIGRATION_BACKUP_FILE = 'scheduled-report-migration-backup.json'
|
||||
const CURRENT_VERSION = 4
|
||||
|
||||
export class AutomationRulePersistenceError extends Error {
|
||||
constructor() {
|
||||
super('自动化规则保存失败')
|
||||
this.name = 'AutomationRulePersistenceError'
|
||||
}
|
||||
}
|
||||
|
||||
interface StoredRules {
|
||||
version: number
|
||||
/** 内置「@我生成日报」是否已经播种过。**即使随后被删除也保持 true**。 */
|
||||
@@ -231,7 +238,8 @@ export class AutomationRuleStore {
|
||||
this.legacyConversationResolver = resolver
|
||||
if (!this.loaded) return
|
||||
if (this.state.scheduledReportMigrated) return
|
||||
if (this.runScheduledReportMigration(this.state)) this.persist()
|
||||
const next = structuredClone(this.state)
|
||||
if (this.runScheduledReportMigration(next)) this.commitState(next)
|
||||
}
|
||||
|
||||
/** 旧定时日报迁移是否仍在等待解析器(仅用于启动日志与测试断言)。 */
|
||||
@@ -274,8 +282,7 @@ export class AutomationRuleStore {
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp
|
||||
}
|
||||
this.state.rules = [...this.state.rules, rule]
|
||||
this.persist()
|
||||
this.commitRules([...this.state.rules, rule])
|
||||
return structuredClone(rule)
|
||||
}
|
||||
|
||||
@@ -316,8 +323,7 @@ export class AutomationRuleStore {
|
||||
} else {
|
||||
delete rule.leaveNotification
|
||||
}
|
||||
this.state.rules = this.state.rules.map((item, at) => (at === index ? rule : item))
|
||||
this.persist()
|
||||
this.commitRules(this.state.rules.map((item, at) => (at === index ? rule : item)))
|
||||
return structuredClone(rule)
|
||||
}
|
||||
|
||||
@@ -346,8 +352,7 @@ export class AutomationRuleStore {
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp
|
||||
}
|
||||
this.state.rules = [...this.state.rules, rule]
|
||||
this.persist()
|
||||
this.commitRules([...this.state.rules, rule])
|
||||
return structuredClone(rule)
|
||||
}
|
||||
|
||||
@@ -355,9 +360,9 @@ export class AutomationRuleStore {
|
||||
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()
|
||||
const rules = this.state.rules.filter((rule) => rule.id !== key)
|
||||
if (rules.length === before) return false
|
||||
this.commitRules(rules)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -394,8 +399,7 @@ export class AutomationRuleStore {
|
||||
},
|
||||
updatedAt: this.now()
|
||||
}
|
||||
this.state.rules = this.state.rules.map((item, at) => (at === index ? next : item))
|
||||
this.persist()
|
||||
this.commitRules(this.state.rules.map((item, at) => (at === index ? next : item)))
|
||||
return structuredClone(next)
|
||||
}
|
||||
|
||||
@@ -428,7 +432,11 @@ export class AutomationRuleStore {
|
||||
this.runScheduledReportMigration(stored)
|
||||
stored.version = CURRENT_VERSION
|
||||
this.state = stored
|
||||
this.persist()
|
||||
try {
|
||||
this.persist()
|
||||
} catch {
|
||||
// Keep the in-memory defaults available; later writes report persistence failures.
|
||||
}
|
||||
}
|
||||
|
||||
/** 旧退群通知配置 → 内置退群通知规则。**只跑一次**,且先备份旧配置。 */
|
||||
@@ -641,6 +649,22 @@ export class AutomationRuleStore {
|
||||
console.warn(
|
||||
`[Automation] 保存规则失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
throw new AutomationRulePersistenceError()
|
||||
}
|
||||
}
|
||||
|
||||
private commitRules(rules: AutomationRule[]): void {
|
||||
this.commitState({ ...this.state, rules })
|
||||
}
|
||||
|
||||
private commitState(next: StoredRules): void {
|
||||
const previous = this.state
|
||||
this.state = next
|
||||
try {
|
||||
this.persist()
|
||||
} catch (error) {
|
||||
this.state = previous
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,49 +237,72 @@ class GroupExitMonitorService {
|
||||
* 本服务不再持有任何通知配置。
|
||||
*/
|
||||
async setMonitoredRoomIds(roomIds: string[]): Promise<GroupExitMonitorState> {
|
||||
return this.configure({ monitoredRoomIds: roomIds })
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically update the monitor scope and enabled state.
|
||||
*
|
||||
* Agent API PATCH validates the whole request before calling this method. Keeping the
|
||||
* two mutations in one service operation also means persistence and the renderer broadcast
|
||||
* observe one final configuration rather than an intermediate half-patched state.
|
||||
*/
|
||||
async configure(configuration: {
|
||||
monitoredRoomIds?: string[]
|
||||
enabled?: boolean
|
||||
}): Promise<GroupExitMonitorState> {
|
||||
this.ensureLoaded()
|
||||
this.eventSequence += 1
|
||||
this.scopeGeneration += 1
|
||||
this.monitorSelectionConfigured = true
|
||||
const nextMonitoredRoomIds = normalizeRoomIds(roomIds)
|
||||
for (const roomId of this.snapshots.keys()) {
|
||||
if (!nextMonitoredRoomIds.has(roomId)) this.snapshots.delete(roomId)
|
||||
const hasScope = configuration.monitoredRoomIds !== undefined
|
||||
const hasEnabled = configuration.enabled !== undefined
|
||||
if (!hasScope && !hasEnabled) return this.getState()
|
||||
if (hasEnabled && !hasScope && this.enabled === configuration.enabled) return this.getState()
|
||||
|
||||
if (hasScope) {
|
||||
this.eventSequence += 1
|
||||
this.scopeGeneration += 1
|
||||
this.monitorSelectionConfigured = true
|
||||
const nextMonitoredRoomIds = normalizeRoomIds(configuration.monitoredRoomIds || [])
|
||||
for (const roomId of this.snapshots.keys()) {
|
||||
if (!nextMonitoredRoomIds.has(roomId)) this.snapshots.delete(roomId)
|
||||
}
|
||||
for (const roomId of this.hydrationQueue) {
|
||||
if (!nextMonitoredRoomIds.has(roomId)) this.hydrationQueue.delete(roomId)
|
||||
}
|
||||
this.monitoredRoomIds = nextMonitoredRoomIds
|
||||
this.groupNamesRefreshPending = true
|
||||
this.lastCheckedAt = undefined
|
||||
}
|
||||
for (const roomId of this.hydrationQueue) {
|
||||
if (!nextMonitoredRoomIds.has(roomId)) this.hydrationQueue.delete(roomId)
|
||||
|
||||
if (hasEnabled && this.enabled !== configuration.enabled) {
|
||||
this.enabled = configuration.enabled === true
|
||||
this.eventSequence += 1
|
||||
this.scopeGeneration += 1
|
||||
this.checkQueued = false
|
||||
this.hydrationQueue.clear()
|
||||
if (this.changeTimer) clearTimeout(this.changeTimer)
|
||||
this.changeTimer = null
|
||||
|
||||
if (this.enabled) {
|
||||
// 用户主动暂停期间的成员变化不补报;重新开启后从当前状态建立新基线。
|
||||
this.snapshots.clear()
|
||||
this.lastCheckedAt = undefined
|
||||
this.groupNamesRefreshPending = true
|
||||
}
|
||||
}
|
||||
this.monitoredRoomIds = nextMonitoredRoomIds
|
||||
this.groupNamesRefreshPending = true
|
||||
this.lastCheckedAt = undefined
|
||||
|
||||
this.save()
|
||||
this.broadcast()
|
||||
// 建立基线放到后台,保存配置可以立即返回。
|
||||
if (this.enabled && this.active) void this.check()
|
||||
// 仅修改范围时保持原有的后台基线行为;涉及 enabled 的 PATCH 等待一次检查,
|
||||
// 让调用方拿到的是最终运行状态。
|
||||
if (this.enabled && this.active && chat.isReady()) {
|
||||
if (hasEnabled) await this.check()
|
||||
else void this.check()
|
||||
}
|
||||
return this.getState()
|
||||
}
|
||||
|
||||
async setEnabled(enabled: boolean): Promise<GroupExitMonitorState> {
|
||||
this.ensureLoaded()
|
||||
if (this.enabled === enabled) return this.getState()
|
||||
|
||||
this.enabled = enabled
|
||||
this.eventSequence += 1
|
||||
this.scopeGeneration += 1
|
||||
this.checkQueued = false
|
||||
this.hydrationQueue.clear()
|
||||
if (this.changeTimer) clearTimeout(this.changeTimer)
|
||||
this.changeTimer = null
|
||||
|
||||
if (enabled) {
|
||||
// 用户主动暂停期间的成员变化不补报;重新开启后从当前状态建立新基线。
|
||||
this.snapshots.clear()
|
||||
this.lastCheckedAt = undefined
|
||||
this.groupNamesRefreshPending = true
|
||||
}
|
||||
this.save()
|
||||
this.broadcast()
|
||||
if (enabled && this.active && chat.isReady()) await this.check()
|
||||
return this.getState()
|
||||
return this.configure({ enabled })
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,967 @@
|
||||
import {
|
||||
BUILTIN_DAILY_REPORT_RULE_ID,
|
||||
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
|
||||
calculateNextRunAt,
|
||||
type AutomationExecution,
|
||||
type AutomationRule,
|
||||
type AutomationRuleDraft,
|
||||
type AutomationRuleType
|
||||
} from '../../shared/automation'
|
||||
import { resolveContact } from './contact-resolution-service'
|
||||
import { validateAutomationDraftShape } from '../../shared/agent-api/automation-validation'
|
||||
import type {
|
||||
AgentAutomationExecution,
|
||||
AgentAutomationValidationIssue,
|
||||
AgentAutomationValidationResult,
|
||||
ApplicationCapabilities
|
||||
} from '../../shared/agent-api/contracts'
|
||||
import type {
|
||||
AgentGroupExitMonitorEvent,
|
||||
AgentGroupExitMonitorState
|
||||
} from '../../shared/agent-api/group-exit-monitor'
|
||||
import type { AgentGroupMemberStats } from '../../shared/agent-api/group-stats'
|
||||
import type { GroupExitMonitorEvent } from '../../shared/group-exit-monitor'
|
||||
import type { GroupMemberStatsQuery, GroupMemberStatsResult } from '../../shared/group-stats'
|
||||
import type { Contact } from '../../shared/types'
|
||||
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
|
||||
import type { AutomationExecutionLogService } from './automation-execution-log-service'
|
||||
import type { AutomationRuleStore } from './automation-rule-store'
|
||||
|
||||
type AutomationRuleStoreApi = Pick<
|
||||
AutomationRuleStore,
|
||||
'listRules' | 'getRule' | 'createRule' | 'updateRule' | 'deleteRule' | 'setRuleEnabled'
|
||||
>
|
||||
type AutomationExecutionLogApi = Pick<AutomationExecutionLogService, 'list'>
|
||||
type RuleScope = 'any' | 'person' | 'group'
|
||||
|
||||
type GroupExitMonitorStateSource = {
|
||||
enabled: boolean
|
||||
running: boolean
|
||||
monitoredRoomIds?: string[]
|
||||
nativeMonitorActive?: boolean
|
||||
monitoredGroupCount?: number
|
||||
monitorSelectionConfigured?: boolean
|
||||
lastCheckedAt?: number
|
||||
lastReadAt?: number
|
||||
unreadCount?: number
|
||||
totalEventCount?: number
|
||||
events?: GroupExitMonitorEvent[]
|
||||
}
|
||||
|
||||
type GroupExitMonitorConfiguration = {
|
||||
enabled?: boolean
|
||||
monitoredRoomIds?: string[]
|
||||
}
|
||||
|
||||
type GroupExitMonitorEventQuery = {
|
||||
roomId?: string
|
||||
sinceMs?: number
|
||||
untilMs?: number
|
||||
limit?: number
|
||||
}
|
||||
|
||||
export class LocalAgentApiError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly code: string,
|
||||
message: string,
|
||||
readonly details?: unknown
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'LocalAgentApiError'
|
||||
}
|
||||
}
|
||||
|
||||
export interface LocalAgentApiDependencies {
|
||||
automationRuleStore: AutomationRuleStoreApi
|
||||
automationExecutionLogService: AutomationExecutionLogApi
|
||||
listContacts: () => Promise<Contact[]>
|
||||
isDatabaseReady: () => boolean
|
||||
getVersion: () => string
|
||||
getPersonalWechatCapability: () => Promise<PersonalWechatSendCapability>
|
||||
getAgentHubStatus: () => { connector: string }
|
||||
getGroupExitMonitorState: () => GroupExitMonitorStateSource
|
||||
/** Preferred atomic monitor configuration operation. */
|
||||
configureGroupExitMonitor?: (
|
||||
configuration: GroupExitMonitorConfiguration
|
||||
) => Promise<GroupExitMonitorStateSource> | GroupExitMonitorStateSource
|
||||
setGroupExitMonitorRoomIds?: (roomIds: string[]) => Promise<GroupExitMonitorStateSource>
|
||||
setGroupExitMonitorEnabled?: (enabled: boolean) => Promise<GroupExitMonitorStateSource>
|
||||
listGroupExitMonitorEvents?: (query: GroupExitMonitorEventQuery) => GroupExitMonitorEvent[]
|
||||
getGroupMemberStats?: (query: GroupMemberStatsQuery) => Promise<GroupMemberStatsResult>
|
||||
}
|
||||
|
||||
const RULE_TYPES: AutomationRuleType[] = ['daily_report', 'scheduled_report', 'leave_notification']
|
||||
const EXECUTION_STATUSES: AutomationExecution['status'][] = ['running', 'success', 'failed']
|
||||
const UPDATE_FIELDS = new Set([
|
||||
'name',
|
||||
'trigger',
|
||||
'scope',
|
||||
'conditions',
|
||||
'actions',
|
||||
'cooldownSeconds',
|
||||
'replyDelaySeconds',
|
||||
'leaveNotification',
|
||||
'scheduledReport'
|
||||
])
|
||||
|
||||
function record(value: unknown): Record<string, unknown> | undefined {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: undefined
|
||||
}
|
||||
|
||||
function toDraft(rule: AutomationRule): AutomationRuleDraft {
|
||||
return {
|
||||
name: rule.name,
|
||||
enabled: false,
|
||||
ruleType: rule.ruleType,
|
||||
trigger: rule.trigger,
|
||||
scope: rule.scope,
|
||||
conditions: structuredClone(rule.conditions),
|
||||
actions: structuredClone(rule.actions),
|
||||
cooldownSeconds: rule.cooldownSeconds,
|
||||
replyDelaySeconds: rule.replyDelaySeconds,
|
||||
...(rule.leaveNotification
|
||||
? { leaveNotification: structuredClone(rule.leaveNotification) }
|
||||
: {}),
|
||||
...(rule.scheduledReport ? { scheduledReport: structuredClone(rule.scheduledReport) } : {})
|
||||
}
|
||||
}
|
||||
|
||||
function deepMergeDraft(
|
||||
current: AutomationRuleDraft,
|
||||
patch: Record<string, unknown>
|
||||
): Record<string, unknown> {
|
||||
const next: Record<string, unknown> = { ...current, ...patch, enabled: false }
|
||||
if (patch.conditions !== undefined) {
|
||||
next.conditions = { ...current.conditions, ...record(patch.conditions) }
|
||||
}
|
||||
if (patch.leaveNotification !== undefined && current.leaveNotification) {
|
||||
const leavePatch = record(patch.leaveNotification) || {}
|
||||
next.leaveNotification = {
|
||||
...current.leaveNotification,
|
||||
...leavePatch,
|
||||
...(leavePatch.target !== undefined ? { target: leavePatch.target } : {})
|
||||
}
|
||||
if (record(leavePatch.target)?.type !== undefined) {
|
||||
delete (next.leaveNotification as Record<string, unknown>).targetNeedsReview
|
||||
}
|
||||
}
|
||||
if (patch.scheduledReport !== undefined && current.scheduledReport) {
|
||||
const schedulePatch = record(patch.scheduledReport) || {}
|
||||
const currentConfig = current.scheduledReport
|
||||
next.scheduledReport = {
|
||||
...currentConfig,
|
||||
...schedulePatch,
|
||||
schedule: { ...currentConfig.schedule, ...record(schedulePatch.schedule) },
|
||||
report: { ...currentConfig.report, ...record(schedulePatch.report) },
|
||||
...(schedulePatch.target !== undefined ? { target: schedulePatch.target } : {})
|
||||
}
|
||||
if (record(schedulePatch.target)?.type !== undefined) {
|
||||
delete (next.scheduledReport as Record<string, unknown>).targetNeedsReview
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
function stableId(contact: Contact): string {
|
||||
return contact.type === 'user' ? contact.wxid || contact.m_nsUsrName : contact.m_nsUsrName
|
||||
}
|
||||
|
||||
function toIsoTimestamp(value: number | undefined): string | null {
|
||||
if (!Number.isFinite(value) || Number(value) <= 0) return null
|
||||
const date = new Date(Number(value))
|
||||
return Number.isNaN(date.getTime()) ? null : date.toISOString()
|
||||
}
|
||||
|
||||
export class LocalAgentApiService {
|
||||
private readonly deps: LocalAgentApiDependencies
|
||||
|
||||
constructor(dependencies: LocalAgentApiDependencies) {
|
||||
this.deps = dependencies
|
||||
}
|
||||
|
||||
async getCapabilities(): Promise<ApplicationCapabilities> {
|
||||
const databaseReady = this.deps.isDatabaseReady()
|
||||
const hub = this.deps.getAgentHubStatus()
|
||||
const monitor = this.deps.getGroupExitMonitorState()
|
||||
let personal: Pick<
|
||||
PersonalWechatSendCapability,
|
||||
'supported' | 'ready' | 'status' | 'capabilities'
|
||||
>
|
||||
try {
|
||||
personal = await this.deps.getPersonalWechatCapability()
|
||||
} catch {
|
||||
personal = {
|
||||
supported: true,
|
||||
ready: false,
|
||||
status: 'error',
|
||||
capabilities: { text: false, image: false, voice: false }
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
version: this.deps.getVersion(),
|
||||
apiVersion: 'v1',
|
||||
database: { ready: databaseReady },
|
||||
query: {
|
||||
supported: true,
|
||||
available: databaseReady,
|
||||
...(!databaseReady ? { reason: 'database_not_ready' } : {})
|
||||
},
|
||||
automations: {
|
||||
supported: true,
|
||||
available: true,
|
||||
ruleTypes: [...RULE_TYPES],
|
||||
operations: [
|
||||
'list',
|
||||
'get',
|
||||
'create',
|
||||
'update',
|
||||
'validate',
|
||||
'enable',
|
||||
'disable',
|
||||
'delete',
|
||||
'executions'
|
||||
]
|
||||
},
|
||||
groupExitMonitor: {
|
||||
supported: true,
|
||||
available: databaseReady && monitor.running,
|
||||
operations: [
|
||||
'read_state',
|
||||
'configure_scope',
|
||||
'enable',
|
||||
'disable',
|
||||
'list_events'
|
||||
],
|
||||
...(!databaseReady
|
||||
? { reason: 'database_not_ready' }
|
||||
: !monitor.enabled
|
||||
? { reason: 'disabled' }
|
||||
: !monitor.running
|
||||
? { reason: 'not_running' }
|
||||
: {})
|
||||
},
|
||||
groupStats: {
|
||||
supported: true,
|
||||
available: databaseReady,
|
||||
operations: ['member_stats'],
|
||||
...(!databaseReady ? { reason: 'database_not_ready' } : {})
|
||||
},
|
||||
wechat: {
|
||||
personal: {
|
||||
supported: personal.supported,
|
||||
available: personal.ready,
|
||||
status: personal.status,
|
||||
content: { ...personal.capabilities },
|
||||
...(!personal.ready ? { reason: personal.status } : {})
|
||||
},
|
||||
ilink: {
|
||||
supported: true,
|
||||
available: hub.connector === 'online',
|
||||
status: hub.connector,
|
||||
...(hub.connector !== 'online' ? { reason: 'connector_not_online' } : {})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getGroupExitMonitorState(): AgentGroupExitMonitorState {
|
||||
const state = this.deps.getGroupExitMonitorState()
|
||||
return {
|
||||
enabled: state.enabled === true,
|
||||
running: state.running === true,
|
||||
nativeMonitorActive: state.nativeMonitorActive === true,
|
||||
monitoredConversationIds: [...(state.monitoredRoomIds || [])],
|
||||
monitoredGroupCount: Number.isFinite(state.monitoredGroupCount)
|
||||
? Number(state.monitoredGroupCount)
|
||||
: state.monitoredRoomIds?.length || 0,
|
||||
monitorSelectionConfigured: state.monitorSelectionConfigured !== false,
|
||||
lastCheckedAt: toIsoTimestamp(state.lastCheckedAt),
|
||||
lastReadAt: toIsoTimestamp(state.lastReadAt),
|
||||
eventCount: Number.isFinite(state.totalEventCount)
|
||||
? Number(state.totalEventCount)
|
||||
: state.events?.length || 0,
|
||||
unreadCount: Number.isFinite(state.unreadCount) ? Number(state.unreadCount) : 0
|
||||
}
|
||||
}
|
||||
|
||||
async updateGroupExitMonitor(input: unknown): Promise<AgentGroupExitMonitorState> {
|
||||
const patch = record(input)
|
||||
if (!patch) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', '请求体必须是 JSON 对象')
|
||||
}
|
||||
const keys = Object.keys(patch)
|
||||
const allowed = new Set(['enabled', 'monitoredConversationIds'])
|
||||
const unknown = keys.find((key) => !allowed.has(key))
|
||||
if (unknown) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', `不支持字段:${unknown}`)
|
||||
}
|
||||
if (keys.length === 0) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', '至少提供 enabled 或 monitoredConversationIds')
|
||||
}
|
||||
|
||||
const enabled = patch.enabled
|
||||
if (enabled !== undefined && typeof enabled !== 'boolean') {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'enabled 必须是布尔值')
|
||||
}
|
||||
|
||||
let monitoredRoomIds: string[] | undefined
|
||||
if (patch.monitoredConversationIds !== undefined) {
|
||||
if (!Array.isArray(patch.monitoredConversationIds)) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'monitoredConversationIds 必须是数组')
|
||||
}
|
||||
monitoredRoomIds = []
|
||||
const seen = new Set<string>()
|
||||
for (const value of patch.monitoredConversationIds) {
|
||||
if (typeof value !== 'string' || !value.trim()) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', '监控群 ID 不能为空')
|
||||
}
|
||||
const roomId = value.trim()
|
||||
if (seen.has(roomId)) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', `监控群 ID 重复:${roomId}`)
|
||||
}
|
||||
if (!roomId.endsWith('@chatroom') || roomId.includes('/') || roomId.includes('\\')) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', `无效的群会话 ID:${roomId}`)
|
||||
}
|
||||
seen.add(roomId)
|
||||
monitoredRoomIds.push(roomId)
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.deps.isDatabaseReady()) {
|
||||
throw new LocalAgentApiError(409, 'DATABASE_NOT_READY', '数据库未就绪,无法修改退群监控配置')
|
||||
}
|
||||
if (monitoredRoomIds !== undefined) {
|
||||
const contacts = await this.deps.listContacts()
|
||||
const groups = new Set(
|
||||
contacts
|
||||
.filter((contact) => contact.type === 'group')
|
||||
.map((contact) => contact.m_nsUsrName)
|
||||
)
|
||||
const missing = monitoredRoomIds.find((roomId) => !groups.has(roomId))
|
||||
if (missing) {
|
||||
throw new LocalAgentApiError(
|
||||
422,
|
||||
'VALIDATION_FAILED',
|
||||
`监控群不存在或不是群联系人:${missing}`,
|
||||
[{ path: 'monitoredConversationIds', code: 'group_not_found', message: missing }]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const configuration: GroupExitMonitorConfiguration = {
|
||||
...(enabled !== undefined ? { enabled } : {}),
|
||||
...(monitoredRoomIds !== undefined ? { monitoredRoomIds } : {})
|
||||
}
|
||||
let nextState: GroupExitMonitorStateSource | undefined
|
||||
if (this.deps.configureGroupExitMonitor) {
|
||||
nextState = await this.deps.configureGroupExitMonitor(configuration)
|
||||
} else {
|
||||
// Test adapters and older embedders may only expose the two primitive operations.
|
||||
// All validation is complete before this fallback starts mutating state.
|
||||
const previous = this.deps.getGroupExitMonitorState()
|
||||
try {
|
||||
if (monitoredRoomIds !== undefined) {
|
||||
if (!this.deps.setGroupExitMonitorRoomIds) {
|
||||
throw new LocalAgentApiError(503, 'CAPABILITY_UNAVAILABLE', '退群监控配置能力尚未就绪')
|
||||
}
|
||||
nextState = await this.deps.setGroupExitMonitorRoomIds(monitoredRoomIds)
|
||||
}
|
||||
if (enabled !== undefined) {
|
||||
if (!this.deps.setGroupExitMonitorEnabled) {
|
||||
throw new LocalAgentApiError(503, 'CAPABILITY_UNAVAILABLE', '退群监控配置能力尚未就绪')
|
||||
}
|
||||
nextState = await this.deps.setGroupExitMonitorEnabled(enabled)
|
||||
}
|
||||
} catch (error) {
|
||||
// Best-effort rollback for legacy adapters. Production uses the atomic operation above.
|
||||
try {
|
||||
if (monitoredRoomIds !== undefined && this.deps.setGroupExitMonitorRoomIds) {
|
||||
await this.deps.setGroupExitMonitorRoomIds(previous.monitoredRoomIds || [])
|
||||
}
|
||||
if (enabled !== undefined && this.deps.setGroupExitMonitorEnabled) {
|
||||
await this.deps.setGroupExitMonitorEnabled(previous.enabled)
|
||||
}
|
||||
} catch {
|
||||
// Preserve the original error; an adapter that cannot roll back is non-atomic by definition.
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
return this.toGroupExitMonitorState(nextState || this.deps.getGroupExitMonitorState())
|
||||
}
|
||||
|
||||
listGroupExitMonitorEvents(query: URLSearchParams): {
|
||||
count: number
|
||||
events: AgentGroupExitMonitorEvent[]
|
||||
} {
|
||||
if (!this.deps.listGroupExitMonitorEvents) {
|
||||
throw new LocalAgentApiError(503, 'CAPABILITY_UNAVAILABLE', '退群事件查询能力尚未就绪')
|
||||
}
|
||||
const rawConversationId = query.get('conversationId')
|
||||
let roomId: string | undefined
|
||||
if (rawConversationId !== null) {
|
||||
roomId = rawConversationId.trim()
|
||||
if (!roomId || !roomId.endsWith('@chatroom') || roomId.includes('/') || roomId.includes('\\')) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'conversationId 必须是有效的群会话 ID')
|
||||
}
|
||||
}
|
||||
const since = this.parseDateFilter(query.get('since'), 'since')
|
||||
const until = this.parseDateFilter(query.get('until'), 'until')
|
||||
if (since !== undefined && until !== undefined && since > until) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'since 不能晚于 until')
|
||||
}
|
||||
const rawLimit = query.get('limit')
|
||||
const limit = rawLimit === null ? 50 : Number(rawLimit)
|
||||
if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'limit 必须是 1 到 200 之间的整数')
|
||||
}
|
||||
const events = this.deps
|
||||
.listGroupExitMonitorEvents({ roomId, sinceMs: since, untilMs: until, limit })
|
||||
.slice()
|
||||
.sort((left, right) => left.detectedAt - right.detectedAt)
|
||||
.map((event) => this.toAgentGroupExitEvent(event))
|
||||
return { count: events.length, events }
|
||||
}
|
||||
|
||||
async getGroupMemberStats(
|
||||
conversationId: string,
|
||||
query: URLSearchParams
|
||||
): Promise<AgentGroupMemberStats> {
|
||||
if (!this.deps.isDatabaseReady()) {
|
||||
throw new LocalAgentApiError(409, 'DATABASE_NOT_READY', '数据库未就绪,无法查询群员统计')
|
||||
}
|
||||
const normalizedConversationId = conversationId.trim()
|
||||
if (!normalizedConversationId || normalizedConversationId.includes('/') || normalizedConversationId.includes('\\')) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'conversationId 格式无效')
|
||||
}
|
||||
const start = this.parseDateFilter(query.get('start'), 'start')
|
||||
const end = this.parseDateFilter(query.get('end'), 'end')
|
||||
if (start === undefined || end === undefined) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'start 和 end 必须同时提供')
|
||||
}
|
||||
if (start > end) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'start 不能晚于 end')
|
||||
}
|
||||
|
||||
const contacts = await this.deps.listContacts()
|
||||
const matches = contacts.filter((contact) => contact.m_nsUsrName === normalizedConversationId)
|
||||
if (matches.length === 0) {
|
||||
throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到指定会话')
|
||||
}
|
||||
if (matches.length > 1) {
|
||||
throw new LocalAgentApiError(409, 'AMBIGUOUS_CONTACT', 'conversationId 匹配到多个会话')
|
||||
}
|
||||
const contact = matches[0]
|
||||
if (contact.type !== 'group') {
|
||||
throw new LocalAgentApiError(422, 'NOT_GROUP_CONVERSATION', 'conversationId 不是群会话')
|
||||
}
|
||||
if (!contact.m_nsUsrName.endsWith('@chatroom')) {
|
||||
throw new LocalAgentApiError(422, 'NOT_GROUP_CONVERSATION', 'conversationId 不是有效的群会话 ID')
|
||||
}
|
||||
if (!this.deps.getGroupMemberStats) {
|
||||
throw new LocalAgentApiError(503, 'CAPABILITY_UNAVAILABLE', '群员统计能力尚未就绪')
|
||||
}
|
||||
|
||||
const result = await this.deps.getGroupMemberStats({
|
||||
userMd5: contact.md5,
|
||||
startTime: start,
|
||||
endTime: end
|
||||
})
|
||||
return this.toAgentGroupMemberStats(contact, result)
|
||||
}
|
||||
|
||||
async listAutomations(filter: {
|
||||
type?: string | null
|
||||
enabled?: string | null
|
||||
}): Promise<unknown[]> {
|
||||
if (filter.type && !RULE_TYPES.includes(filter.type as AutomationRuleType)) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'type 不受支持')
|
||||
}
|
||||
let enabled: boolean | undefined
|
||||
if (filter.enabled !== undefined && filter.enabled !== null) {
|
||||
if (filter.enabled !== 'true' && filter.enabled !== 'false') {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'enabled 必须是 true 或 false')
|
||||
}
|
||||
enabled = filter.enabled === 'true'
|
||||
}
|
||||
const rules = this.deps.automationRuleStore
|
||||
.listRules()
|
||||
.filter(
|
||||
(rule) =>
|
||||
(!filter.type || rule.ruleType === filter.type) &&
|
||||
(enabled === undefined || rule.enabled === enabled)
|
||||
)
|
||||
return this.toApiRules(rules)
|
||||
}
|
||||
|
||||
async getAutomation(id: string): Promise<unknown> {
|
||||
const rule = this.deps.automationRuleStore.getRule(id)
|
||||
if (!rule) throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到自动化规则')
|
||||
return (await this.toApiRules([rule]))[0]
|
||||
}
|
||||
|
||||
async validateAutomation(input: unknown): Promise<AgentAutomationValidationResult> {
|
||||
const structural = validateAutomationDraftShape(input)
|
||||
if (!structural.valid || !structural.normalized) {
|
||||
return { valid: false, issues: structural.issues }
|
||||
}
|
||||
|
||||
const issues = [...structural.issues]
|
||||
const draft = structuredClone(structural.normalized)
|
||||
const references = await this.resolveDraftReferences(draft, issues)
|
||||
if (issues.length) return { valid: false, issues }
|
||||
|
||||
const config = draft.scheduledReport
|
||||
const nextRunAt = config ? calculateNextRunAt(config.schedule.time) : null
|
||||
const effects = this.describeEffects(draft)
|
||||
return {
|
||||
valid: true,
|
||||
issues: [],
|
||||
normalized: draft,
|
||||
effects,
|
||||
nextRunAt,
|
||||
capabilities: {
|
||||
databaseReady: this.deps.isDatabaseReady(),
|
||||
referencedConversationsResolved: references
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async createAutomation(input: unknown): Promise<unknown> {
|
||||
const raw = record(input)
|
||||
if (raw?.ruleType === 'leave_notification') {
|
||||
throw new LocalAgentApiError(409, 'SINGLETON_RULE', '退群通知是系统单例规则,请修改现有规则')
|
||||
}
|
||||
const validation = await this.validateAutomation(input)
|
||||
if (!validation.valid || !validation.normalized) {
|
||||
throw new LocalAgentApiError(
|
||||
422,
|
||||
'VALIDATION_FAILED',
|
||||
'自动化规则校验失败',
|
||||
validation.issues
|
||||
)
|
||||
}
|
||||
const contacts = await this.deps.listContacts()
|
||||
const storedDraft = this.toStoreDraft(validation.normalized as AutomationRuleDraft, contacts)
|
||||
storedDraft.enabled = false
|
||||
const created = this.deps.automationRuleStore.createRule(storedDraft)
|
||||
return (await this.toApiRules([created]))[0]
|
||||
}
|
||||
|
||||
async updateAutomation(id: string, patchInput: unknown): Promise<unknown> {
|
||||
const current = this.deps.automationRuleStore.getRule(id)
|
||||
if (!current) throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到自动化规则')
|
||||
const patch = record(patchInput)
|
||||
if (!patch) throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', '请求体必须是 JSON 对象')
|
||||
for (const key of Object.keys(patch)) {
|
||||
if (key === 'ruleType') {
|
||||
throw new LocalAgentApiError(400, 'RULE_TYPE_IMMUTABLE', 'ruleType 不可修改')
|
||||
}
|
||||
if (key === 'id' || key === 'createdAt' || key === 'updatedAt') {
|
||||
throw new LocalAgentApiError(400, 'IMMUTABLE_FIELD', `${key} 不允许由客户端修改`)
|
||||
}
|
||||
if (key === 'enabled') {
|
||||
throw new LocalAgentApiError(400, 'USE_ENABLE_OPERATION', '请使用 enable 或 disable 操作')
|
||||
}
|
||||
if (!UPDATE_FIELDS.has(key)) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', `不支持字段:${key}`)
|
||||
}
|
||||
}
|
||||
for (const configKey of ['leaveNotification', 'scheduledReport']) {
|
||||
if (Object.hasOwn(record(patch[configKey]) || {}, 'targetNeedsReview')) {
|
||||
throw new LocalAgentApiError(
|
||||
400,
|
||||
'IMMUTABLE_FIELD',
|
||||
`${configKey}.targetNeedsReview 只能通过更新 target 清除`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const apiCurrent = (await this.toApiRules([current]))[0] as AutomationRule & {
|
||||
requiresReview?: boolean
|
||||
}
|
||||
const candidate = deepMergeDraft(toDraft(apiCurrent), patch)
|
||||
const validation = await this.validateAutomation(candidate)
|
||||
if (!validation.valid || !validation.normalized) {
|
||||
throw new LocalAgentApiError(
|
||||
422,
|
||||
'VALIDATION_FAILED',
|
||||
'自动化规则校验失败',
|
||||
validation.issues
|
||||
)
|
||||
}
|
||||
|
||||
const contacts = await this.deps.listContacts()
|
||||
const storedDraft = this.toStoreDraft(validation.normalized as AutomationRuleDraft, contacts)
|
||||
storedDraft.enabled = current.enabled
|
||||
const updated = this.deps.automationRuleStore.updateRule(id, storedDraft)
|
||||
if (!updated) throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到自动化规则')
|
||||
return (await this.toApiRules([updated]))[0]
|
||||
}
|
||||
|
||||
async setAutomationEnabled(id: string, enabled: boolean): Promise<unknown> {
|
||||
const current = this.deps.automationRuleStore.getRule(id)
|
||||
if (!current) throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到自动化规则')
|
||||
if (enabled) {
|
||||
if (!this.deps.isDatabaseReady()) {
|
||||
throw new LocalAgentApiError(409, 'VALIDATION_FAILED', '数据库未就绪,无法启用自动化规则', [
|
||||
{ path: 'database', code: 'database_not_ready', message: 'TraceMemo 数据库未初始化' }
|
||||
])
|
||||
}
|
||||
const apiCurrent = (await this.toApiRules([current]))[0] as AutomationRule
|
||||
const draft = toDraft(apiCurrent)
|
||||
const validation = await this.validateAutomation(draft)
|
||||
if (!validation.valid) {
|
||||
throw new LocalAgentApiError(
|
||||
409,
|
||||
'VALIDATION_FAILED',
|
||||
'自动化规则校验失败,未启用',
|
||||
validation.issues
|
||||
)
|
||||
}
|
||||
}
|
||||
const updated = this.deps.automationRuleStore.setRuleEnabled(id, enabled)
|
||||
if (!updated) throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到自动化规则')
|
||||
return (await this.toApiRules([updated]))[0]
|
||||
}
|
||||
|
||||
async deleteAutomation(id: string): Promise<{ deletedId: string }> {
|
||||
if (id === BUILTIN_DAILY_REPORT_RULE_ID || id === BUILTIN_LEAVE_NOTIFICATION_RULE_ID) {
|
||||
throw new LocalAgentApiError(409, 'PROTECTED_RULE', '系统内置自动化规则不能删除')
|
||||
}
|
||||
const rule = this.deps.automationRuleStore.getRule(id)
|
||||
if (!rule) throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到自动化规则')
|
||||
if (rule.ruleType === 'leave_notification') {
|
||||
throw new LocalAgentApiError(409, 'PROTECTED_RULE', '退群通知是系统单例规则,不能删除')
|
||||
}
|
||||
const deleted = this.deps.automationRuleStore.deleteRule(id)
|
||||
if (!deleted) throw new LocalAgentApiError(404, 'NOT_FOUND', '未找到自动化规则')
|
||||
return { deletedId: id }
|
||||
}
|
||||
|
||||
listExecutions(query: URLSearchParams): {
|
||||
count: number
|
||||
executions: AgentAutomationExecution[]
|
||||
} {
|
||||
const ruleId = query.get('ruleId') || undefined
|
||||
const status = query.get('status') || undefined
|
||||
if (status && !EXECUTION_STATUSES.includes(status as AutomationExecution['status'])) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'status 不受支持')
|
||||
}
|
||||
const since = this.parseDateFilter(query.get('since'), 'since')
|
||||
const until = this.parseDateFilter(query.get('until'), 'until')
|
||||
if (since !== undefined && until !== undefined && since > until) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'since 不能晚于 until')
|
||||
}
|
||||
const rawLimit = query.get('limit')
|
||||
const limit = rawLimit === null ? 50 : Number(rawLimit)
|
||||
if (!Number.isInteger(limit) || limit < 1 || limit > 200) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', 'limit 必须是 1 到 200 之间的整数')
|
||||
}
|
||||
const rulesById = new Map(
|
||||
this.deps.automationRuleStore.listRules().map((rule) => [rule.id, rule])
|
||||
)
|
||||
const executions = this.deps.automationExecutionLogService
|
||||
.list({ limit: 200 })
|
||||
.filter((item) => !ruleId || item.ruleId === ruleId)
|
||||
.filter((item) => !status || item.status === status)
|
||||
.filter((item) => since === undefined || item.triggerTime >= since)
|
||||
.filter((item) => until === undefined || item.triggerTime <= until)
|
||||
.slice(0, limit)
|
||||
.map((item) => this.toApiExecution(item, rulesById.get(item.ruleId)?.ruleType))
|
||||
return { count: executions.length, executions }
|
||||
}
|
||||
|
||||
private toGroupExitMonitorState(state: GroupExitMonitorStateSource): AgentGroupExitMonitorState {
|
||||
const eventCount = Number.isFinite(state.totalEventCount)
|
||||
? Number(state.totalEventCount)
|
||||
: state.events?.length || 0
|
||||
return {
|
||||
enabled: state.enabled === true,
|
||||
running: state.running === true,
|
||||
nativeMonitorActive: state.nativeMonitorActive === true,
|
||||
monitoredConversationIds: [...(state.monitoredRoomIds || [])],
|
||||
monitoredGroupCount: Number.isFinite(state.monitoredGroupCount)
|
||||
? Number(state.monitoredGroupCount)
|
||||
: state.monitoredRoomIds?.length || 0,
|
||||
monitorSelectionConfigured: state.monitorSelectionConfigured !== false,
|
||||
lastCheckedAt: toIsoTimestamp(state.lastCheckedAt),
|
||||
lastReadAt: toIsoTimestamp(state.lastReadAt),
|
||||
eventCount,
|
||||
unreadCount: Number.isFinite(state.unreadCount) ? Number(state.unreadCount) : 0
|
||||
}
|
||||
}
|
||||
|
||||
private toAgentGroupExitEvent(event: GroupExitMonitorEvent): AgentGroupExitMonitorEvent {
|
||||
return {
|
||||
eventId: event.id,
|
||||
conversationId: event.roomId,
|
||||
groupName: event.groupName,
|
||||
memberId: event.memberWxid,
|
||||
memberName: event.memberName,
|
||||
wechatName: event.wechatName || '',
|
||||
groupRemark: event.groupRemark || '',
|
||||
contactRemark: event.contactRemark || '',
|
||||
previousCount: event.previousCount,
|
||||
currentCount: event.currentCount,
|
||||
delta: event.delta,
|
||||
message: event.message,
|
||||
detectedAt: new Date(event.detectedAt).toISOString()
|
||||
}
|
||||
}
|
||||
|
||||
private toAgentGroupMemberStats(contact: Contact, result: GroupMemberStatsResult): AgentGroupMemberStats {
|
||||
const conversationName =
|
||||
contact.m_nsNickName || contact.remark || contact.wechatNickname || contact.m_nsUsrName
|
||||
return {
|
||||
conversation: { id: contact.m_nsUsrName, name: conversationName },
|
||||
conversationId: contact.m_nsUsrName,
|
||||
range: {
|
||||
start: new Date(result.startTime).toISOString(),
|
||||
end: new Date(result.endTime).toISOString()
|
||||
},
|
||||
memberCount: result.memberCount,
|
||||
activeMemberCount: result.activeMemberCount,
|
||||
silentMemberCount: result.silentMemberCount,
|
||||
activeMembers: result.activeMembers.map((member) => ({
|
||||
memberId: member.senderId,
|
||||
displayName: member.displayName,
|
||||
groupNickname: member.groupNickname,
|
||||
messageCount: member.messageCount,
|
||||
lastMessageAt: toIsoTimestamp(member.lastMessageTime)
|
||||
})),
|
||||
silentMembers: result.silentMembers.map((member) => ({
|
||||
memberId: member.senderId,
|
||||
displayName: member.displayName,
|
||||
groupNickname: member.groupNickname
|
||||
})),
|
||||
freshness: result.freshness,
|
||||
complete: result.complete,
|
||||
limitations: [...result.limitations],
|
||||
unattributedMessages: result.unattributedMessages,
|
||||
excludedSystemMessages: result.excludedSystemMessages,
|
||||
firstMessageAt:
|
||||
toIsoTimestamp(result.firstMessageTime ?? undefined)
|
||||
}
|
||||
}
|
||||
|
||||
private parseDateFilter(value: string | null, name: string): number | undefined {
|
||||
if (value === null) return undefined
|
||||
if (!/T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', `${name} 必须是带时区的 ISO-8601 时间`)
|
||||
}
|
||||
const timestamp = Date.parse(value)
|
||||
if (!Number.isFinite(timestamp)) {
|
||||
throw new LocalAgentApiError(400, 'INVALID_ARGUMENT', `${name} 不是有效时间`)
|
||||
}
|
||||
return timestamp
|
||||
}
|
||||
|
||||
private toApiExecution(
|
||||
execution: AutomationExecution,
|
||||
ruleType?: AutomationRuleType
|
||||
): AgentAutomationExecution {
|
||||
return {
|
||||
executionId: execution.executionId,
|
||||
ruleId: execution.ruleId,
|
||||
ruleName: execution.ruleName,
|
||||
...(ruleType ? { ruleType } : {}),
|
||||
...(execution.trigger ? { trigger: execution.trigger } : {}),
|
||||
status: execution.status,
|
||||
triggerTime: execution.triggerTime,
|
||||
durationMs: execution.durationMs,
|
||||
sourceDisplayName: execution.sourceDisplayName,
|
||||
startedAt: new Date(execution.triggerTime).toISOString(),
|
||||
finishedAt:
|
||||
execution.status === 'running'
|
||||
? null
|
||||
: new Date(execution.triggerTime + execution.durationMs).toISOString(),
|
||||
...(execution.errorSummary ? { error: execution.errorSummary } : {})
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveDraftReferences(
|
||||
draft: AutomationRuleDraft,
|
||||
issues: AgentAutomationValidationIssue[]
|
||||
): Promise<boolean> {
|
||||
const needsContacts =
|
||||
(draft.ruleType === 'daily_report' && draft.conditions.conversationIds.length > 0) ||
|
||||
draft.ruleType === 'scheduled_report' ||
|
||||
(draft.ruleType === 'leave_notification' &&
|
||||
(draft.leaveNotification?.target.type === 'contact' ||
|
||||
(draft.leaveNotification?.notifyRoomIds.length ?? 0) > 0))
|
||||
if (!needsContacts) return true
|
||||
if (!this.deps.isDatabaseReady()) {
|
||||
issues.push({
|
||||
path: 'database',
|
||||
code: 'database_not_ready',
|
||||
message: 'TraceMemo 数据库未初始化,无法解析联系人或群聊 ID'
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
const contacts = await this.deps.listContacts()
|
||||
let resolved = true
|
||||
const resolve = (query: string, scope: RuleScope, path: string): Contact | undefined => {
|
||||
const direct = contacts.filter((contact) => {
|
||||
const identifiers = [
|
||||
contact.md5,
|
||||
contact.m_nsUsrName,
|
||||
contact.wxid,
|
||||
contact.wechatId,
|
||||
contact.alias
|
||||
]
|
||||
return identifiers.some(
|
||||
(identifier) => identifier?.toLocaleLowerCase() === query.toLocaleLowerCase()
|
||||
)
|
||||
})
|
||||
const scopedDirect = direct.filter(
|
||||
(contact) =>
|
||||
scope === 'any' ||
|
||||
(scope === 'person' ? contact.type === 'user' : contact.type === 'group')
|
||||
)
|
||||
if (scopedDirect.length === 1) return scopedDirect[0]
|
||||
|
||||
const result = resolveContact(query, contacts, scope)
|
||||
if (result.matched && result.conversationId) {
|
||||
return contacts.find((contact) => contact.md5 === result.conversationId)
|
||||
}
|
||||
resolved = false
|
||||
issues.push({
|
||||
path,
|
||||
code: result.ambiguous ? 'ambiguous_contact' : 'contact_not_found',
|
||||
message: result.ambiguous
|
||||
? '标识匹配到多个联系人,请使用稳定 ID'
|
||||
: '无法解析到现有联系人或群聊',
|
||||
...(result.ambiguous
|
||||
? {
|
||||
details: {
|
||||
candidates: result.candidates.map((candidate) => {
|
||||
const contact = contacts.find((item) => item.md5 === candidate.conversationId)
|
||||
return contact
|
||||
? { id: stableId(contact), name: candidate.displayName }
|
||||
: { id: candidate.conversationId, name: candidate.displayName }
|
||||
})
|
||||
}
|
||||
}
|
||||
: {})
|
||||
})
|
||||
return undefined
|
||||
}
|
||||
|
||||
if (draft.ruleType === 'daily_report') {
|
||||
const scope: RuleScope =
|
||||
draft.scope === 'group' ? 'group' : draft.scope === 'direct' ? 'person' : 'any'
|
||||
const ids: string[] = []
|
||||
for (const [index, query] of draft.conditions.conversationIds.entries()) {
|
||||
const contact = resolve(query, scope, `conditions.conversationIds[${index}]`)
|
||||
if (contact) ids.push(stableId(contact))
|
||||
}
|
||||
draft.conditions.conversationIds = ids
|
||||
}
|
||||
|
||||
if (draft.ruleType === 'scheduled_report' && draft.scheduledReport) {
|
||||
const source = resolve(
|
||||
draft.scheduledReport.report.sourceConversationId,
|
||||
'group',
|
||||
'scheduledReport.report.sourceConversationId'
|
||||
)
|
||||
if (source) draft.scheduledReport.report.sourceConversationId = source.m_nsUsrName
|
||||
if (draft.scheduledReport.target.type === 'contact') {
|
||||
const target = resolve(
|
||||
draft.scheduledReport.target.contactId || '',
|
||||
'person',
|
||||
'scheduledReport.target.contactId'
|
||||
)
|
||||
if (target) draft.scheduledReport.target.contactId = stableId(target)
|
||||
}
|
||||
}
|
||||
|
||||
if (draft.ruleType === 'leave_notification' && draft.leaveNotification) {
|
||||
if (draft.leaveNotification.target.type === 'contact') {
|
||||
const target = resolve(
|
||||
draft.leaveNotification.target.contactId || '',
|
||||
'person',
|
||||
'leaveNotification.target.contactId'
|
||||
)
|
||||
if (target) draft.leaveNotification.target.contactId = stableId(target)
|
||||
}
|
||||
const ids: string[] = []
|
||||
for (const [index, query] of draft.leaveNotification.notifyRoomIds.entries()) {
|
||||
const group = resolve(query, 'group', `leaveNotification.notifyRoomIds[${index}]`)
|
||||
if (group) ids.push(group.m_nsUsrName)
|
||||
}
|
||||
draft.leaveNotification.notifyRoomIds = ids
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
private toStoreDraft(draft: AutomationRuleDraft, contacts: Contact[]): AutomationRuleDraft {
|
||||
const stored = structuredClone(draft)
|
||||
if (stored.ruleType === 'daily_report') {
|
||||
stored.conditions.conversationIds = stored.conditions.conversationIds.map(
|
||||
(id) => contacts.find((contact) => stableId(contact) === id)?.md5 || id
|
||||
)
|
||||
}
|
||||
return stored
|
||||
}
|
||||
|
||||
private async toApiRules(rules: AutomationRule[]): Promise<unknown[]> {
|
||||
const contacts = await this.deps.listContacts().catch(() => [])
|
||||
return rules.map((rule) => {
|
||||
const copy = structuredClone(rule) as AutomationRule & { requiresReview?: boolean }
|
||||
if (copy.ruleType === 'daily_report') {
|
||||
copy.conditions.conversationIds = copy.conditions.conversationIds.map((id) =>
|
||||
contacts.find((contact) => contact.md5 === id)
|
||||
? stableId(contacts.find((contact) => contact.md5 === id)!)
|
||||
: id
|
||||
)
|
||||
}
|
||||
if (copy.ruleType === 'scheduled_report' && copy.scheduledReport) {
|
||||
copy.requiresReview = copy.scheduledReport.targetNeedsReview === true
|
||||
delete copy.scheduledReport.legacyTarget
|
||||
delete copy.scheduledReport.legacySourceGroup
|
||||
delete copy.scheduledReport.lastRunAt
|
||||
delete copy.scheduledReport.lastScheduledSlot
|
||||
}
|
||||
if (copy.ruleType === 'leave_notification' && copy.leaveNotification) {
|
||||
copy.requiresReview = copy.leaveNotification.targetNeedsReview === true
|
||||
}
|
||||
return copy
|
||||
})
|
||||
}
|
||||
|
||||
private describeEffects(draft: AutomationRuleDraft): Record<string, unknown> {
|
||||
if (draft.ruleType === 'scheduled_report' && draft.scheduledReport) {
|
||||
const config = draft.scheduledReport
|
||||
return {
|
||||
generatesReport: true,
|
||||
sendsWechatMessage: true,
|
||||
sourceConversationId: config.report.sourceConversationId,
|
||||
target: config.target
|
||||
}
|
||||
}
|
||||
if (draft.ruleType === 'leave_notification' && draft.leaveNotification) {
|
||||
return {
|
||||
sendsWechatMessage: true,
|
||||
monitorScope: 'configured_in_group_exit_monitor',
|
||||
notificationScope: draft.leaveNotification.notifyScope,
|
||||
notificationRoomIds:
|
||||
draft.leaveNotification.notifyScope === 'selected'
|
||||
? draft.leaveNotification.notifyRoomIds
|
||||
: undefined,
|
||||
target: draft.leaveNotification.target
|
||||
}
|
||||
}
|
||||
return {
|
||||
actions: draft.actions.filter((action) => action.enabled).map((action) => action.type),
|
||||
sendsWechatMessage: draft.actions.some(
|
||||
(action) => action.enabled && action.type === 'sendReportImage'
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,21 @@ function parseBody(bodyText: string, contentType?: string): { json?: unknown; bo
|
||||
return { bodyText }
|
||||
}
|
||||
|
||||
function materializeEndpointPath(pathname: string, query: Record<string, string>): string {
|
||||
return pathname.replace('{conversationId}', encodeURIComponent(query.conversationId || ''))
|
||||
}
|
||||
|
||||
function appendQueryParameters(
|
||||
url: URL,
|
||||
endpointPath: string,
|
||||
entries: Array<[string, string]>
|
||||
): void {
|
||||
for (const [key, value] of entries) {
|
||||
if (endpointPath.includes(`{${key}}`)) continue
|
||||
if (value.trim()) url.searchParams.set(key, value.trim())
|
||||
}
|
||||
}
|
||||
|
||||
export function buildLocalApiCurlCommand(payload: unknown): {
|
||||
success: boolean
|
||||
command?: string
|
||||
@@ -71,18 +86,17 @@ export function buildLocalApiCurlCommand(payload: unknown): {
|
||||
const service = apiServer.getState()
|
||||
const targetHost = requestHost(service.host)
|
||||
const hostPart = targetHost.includes(':') ? `[${targetHost}]` : targetHost
|
||||
const url = new URL(endpoint.path, `http://${hostPart}:${service.port}`)
|
||||
entries.forEach(([key, value]) => {
|
||||
if (value.trim()) url.searchParams.set(key, value.trim())
|
||||
})
|
||||
const endpointPath = materializeEndpointPath(endpoint.path, query as Record<string, string>)
|
||||
const url = new URL(endpointPath, `http://${hostPart}:${service.port}`)
|
||||
appendQueryParameters(url, endpoint.path, entries)
|
||||
const token = endpointId === 'health' ? null : apiTokenStore.getTokenForAuthentication()
|
||||
if (endpointId !== 'health' && !token) {
|
||||
return { success: false, error: 'API Token 安全存储不可用,请在 API Center 检查 Token 状态' }
|
||||
}
|
||||
const authHeader = token ? ` -H 'Authorization: Bearer ${token}'` : ''
|
||||
const command =
|
||||
endpoint.method === 'POST'
|
||||
? `curl -X POST '${url.toString()}'${authHeader} -H 'Content-Type: application/json' -d '${body.replaceAll("'", "\\'")}'`
|
||||
endpoint.method === 'POST' || endpoint.method === 'PATCH'
|
||||
? `curl -X ${endpoint.method} '${url.toString()}'${authHeader} -H 'Content-Type: application/json' -d '${body.replaceAll("'", "\\'")}'`
|
||||
: `curl '${url.toString()}'${authHeader}`
|
||||
return { success: true, command }
|
||||
}
|
||||
@@ -110,10 +124,9 @@ export async function testLocalApiRequest(payload: unknown): Promise<LocalApiTes
|
||||
const targetHost = requestHost(service.host)
|
||||
const targetPort = service.port
|
||||
const hostPart = targetHost.includes(':') ? `[${targetHost}]` : targetHost
|
||||
const url = new URL(endpoint.path, `http://${hostPart}:${targetPort}`)
|
||||
entries.forEach(([key, value]) => {
|
||||
if (value.trim()) url.searchParams.set(key, value.trim())
|
||||
})
|
||||
const endpointPath = materializeEndpointPath(endpoint.path, query as Record<string, string>)
|
||||
const url = new URL(endpointPath, `http://${hostPart}:${targetPort}`)
|
||||
appendQueryParameters(url, endpoint.path, entries)
|
||||
|
||||
if (!service.running) {
|
||||
return {
|
||||
@@ -150,7 +163,9 @@ export async function testLocalApiRequest(payload: unknown): Promise<LocalApiTes
|
||||
})
|
||||
}
|
||||
const headers: Record<string, string> = {}
|
||||
if (endpoint.method === 'POST') headers['Content-Type'] = 'application/json'
|
||||
if (endpoint.method === 'POST' || endpoint.method === 'PATCH') {
|
||||
headers['Content-Type'] = 'application/json'
|
||||
}
|
||||
if (token) headers.Authorization = `Bearer ${token}`
|
||||
const request = http.request(
|
||||
url,
|
||||
@@ -208,7 +223,7 @@ export async function testLocalApiRequest(payload: unknown): Promise<LocalApiTes
|
||||
error: error.message
|
||||
})
|
||||
})
|
||||
if (endpoint.method === 'POST') request.write(body)
|
||||
if (endpoint.method === 'POST' || endpoint.method === 'PATCH') request.write(body)
|
||||
request.end()
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user