mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: 修复定时日报错误通知微信机器人功能
增加定时日报debug 修复定时日报历史头像显示并区分定时日报标题
This commit is contained in:
1 parent
1c8bbae1f0
commit
7c8b45a24a
32 files changed
+2975
-213
No files matched your search
+22
-1
@@ -460,6 +460,27 @@ function createScheduledReportRoute(
|
||||
}
|
||||
}
|
||||
|
||||
const retryPrefix = `${SCHEDULED_REPORTS_ROUTE}/executions/`
|
||||
if (pathname.startsWith(retryPrefix)) {
|
||||
const segments = pathname.slice(retryPrefix.length).split('/').filter(Boolean)
|
||||
if (segments.length !== 2 || segments[1] !== 'retry-send') return undefined
|
||||
let executionId: string
|
||||
try {
|
||||
executionId = decodeURIComponent(segments[0])
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
return async ({ req, res }) => {
|
||||
if (req.method !== 'POST') return sendError(res, 405, '需要 POST 请求')
|
||||
try {
|
||||
const execution = await api.retrySend(executionId)
|
||||
sendJson(res, 200, { success: execution.status !== 'failed', execution })
|
||||
} catch (error) {
|
||||
sendScheduledError(res, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const prefix = `${SCHEDULED_REPORTS_ROUTE}/`
|
||||
if (!pathname.startsWith(prefix)) return undefined
|
||||
const segments = pathname.slice(prefix.length).split('/').filter(Boolean)
|
||||
@@ -500,7 +521,7 @@ function createScheduledReportRoute(
|
||||
}
|
||||
if (action === 'run' && req.method === 'POST') {
|
||||
const execution = await api.run(taskId)
|
||||
sendJson(res, 200, { success: execution.status === 'success', execution })
|
||||
sendJson(res, 200, { success: execution.status !== 'failed', execution })
|
||||
return
|
||||
}
|
||||
if (action === 'executions' && req.method === 'GET') {
|
||||
|
||||
@@ -122,6 +122,7 @@ import type {
|
||||
ScheduledReportCreateInput,
|
||||
ScheduledReportUpdateInput
|
||||
} from '../shared/scheduled-report'
|
||||
import { isTruthyDebugFlag } from '../shared/debug-flags'
|
||||
import { TextToSpeechSettingsService } from './services/text-to-speech-settings-service'
|
||||
import type {
|
||||
ListTextToSpeechVoicesRequest,
|
||||
@@ -1315,6 +1316,12 @@ app.whenReady().then(async () => {
|
||||
ipcMain.handle('scheduled-report:listExecutions', (_, taskId?: string) =>
|
||||
scheduledReportService.listExecutions(taskId)
|
||||
)
|
||||
ipcMain.handle('scheduled-report:getNotificationSettings', () =>
|
||||
scheduledReportService.getNotificationSettings()
|
||||
)
|
||||
ipcMain.handle('scheduled-report:setNotificationEnabled', (_, enabled: boolean) =>
|
||||
scheduledReportService.setNotificationEnabled(Boolean(enabled))
|
||||
)
|
||||
ipcMain.handle('scheduled-report:create', (_, request: ScheduledReportCreateInput) =>
|
||||
scheduledReportService.createTask(request)
|
||||
)
|
||||
@@ -1332,6 +1339,18 @@ app.whenReady().then(async () => {
|
||||
ipcMain.handle('scheduled-report:runNow', (_, taskId: string) =>
|
||||
scheduledReportService.runScheduledReportNow(taskId)
|
||||
)
|
||||
ipcMain.handle('scheduled-report:retrySend', (_, executionId: string) =>
|
||||
scheduledReportService.retryScheduledReportSend(executionId)
|
||||
)
|
||||
ipcMain.handle('scheduled-report:testErrorNotification', (_, taskId: string) => {
|
||||
if (!isTruthyDebugFlag(import.meta.env.VITE_SCHEDULED_REPORT_DEBUG)) {
|
||||
return Promise.resolve({
|
||||
success: false,
|
||||
error: '调试测试按钮未开启,请在 .env 中设置 VITE_SCHEDULED_REPORT_DEBUG=true。'
|
||||
})
|
||||
}
|
||||
return scheduledReportService.testScheduledReportErrorNotification(taskId)
|
||||
})
|
||||
|
||||
ipcMain.handle('report:reveal', async (_, filePath: string) => {
|
||||
try {
|
||||
|
||||
@@ -171,6 +171,7 @@ export async function saveGeneratedReport(
|
||||
contactId: request.contactId,
|
||||
contactName: request.contactName,
|
||||
contactAvatar: request.contactAvatar,
|
||||
source: request.source,
|
||||
dateRange: request.dateRange,
|
||||
messageCount: request.messageCount,
|
||||
generatedAt: timestamp.toISOString(),
|
||||
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
ScheduledReportMemberNameMode,
|
||||
ScheduledReportMessageType
|
||||
} from '../../shared/scheduled-report'
|
||||
import type { ScheduledReportExecutionStage } from '../../shared/scheduled-report'
|
||||
import type { SelectableReportTemplateId } from '../../shared/report-templates'
|
||||
import { resolveMemberName } from '../../shared/member-names'
|
||||
import {
|
||||
@@ -47,6 +48,10 @@ export interface AgentGroupReportResult {
|
||||
}
|
||||
duration?: number
|
||||
error?: string
|
||||
errorCode?: string
|
||||
errorStage?: ScheduledReportExecutionStage
|
||||
errorStatus?: number
|
||||
errorType?: string
|
||||
}
|
||||
|
||||
export async function generateAgentGroupReport(
|
||||
@@ -57,11 +62,11 @@ export async function generateAgentGroupReport(
|
||||
.trim()
|
||||
.replace(/群聊?$/, '')
|
||||
.trim()
|
||||
if (!query) return { success: false, error: '缺少群聊名称' }
|
||||
if (!query) return reportFailure('缺少群聊名称', 'data', 'CHAT_NOT_FOUND')
|
||||
const contact = resolveMd5(query)
|
||||
if (!contact) return { success: false, error: `没有找到群聊“${query}”` }
|
||||
if (!contact) return reportFailure(`没有找到群聊“${query}”`, 'data', 'CHAT_NOT_FOUND')
|
||||
if (contact.type !== 'group' && !contact.m_nsUsrName.endsWith('@chatroom')) {
|
||||
return { success: false, error: `“${query}”不是群聊` }
|
||||
return reportFailure(`“${query}”不是群聊`, 'data', 'CHAT_NOT_FOUND')
|
||||
}
|
||||
|
||||
const range = request.range === 'yesterday' || request.range === '7days' ? request.range : 'today'
|
||||
@@ -73,7 +78,7 @@ export async function generateAgentGroupReport(
|
||||
})()
|
||||
: getSummaryDateRange(range)
|
||||
let messages = listMessages(contact.md5, startTime, endTime) as Message[]
|
||||
if (!messages.length) return { success: false, error: '所选时间范围没有可总结的消息' }
|
||||
if (!messages.length) return reportFailure('所选时间范围没有可总结的消息', 'data', 'NO_MESSAGES')
|
||||
|
||||
const messageTypeMap: Record<ScheduledReportMessageType, string[]> = {
|
||||
text: ['普通文本'],
|
||||
@@ -91,7 +96,7 @@ export async function generateAgentGroupReport(
|
||||
).flatMap((type) => messageTypeMap[type] || [])
|
||||
)
|
||||
messages = messages.filter((message) => selectedTypes.has(message.type))
|
||||
if (!messages.length) return { success: false, error: '所选时间范围没有可总结的消息' }
|
||||
if (!messages.length) return reportFailure('所选时间范围没有可总结的消息', 'data', 'NO_MESSAGES')
|
||||
|
||||
const snapshot = getGroupSnapshot(contact.md5)
|
||||
if (snapshot) {
|
||||
@@ -122,7 +127,13 @@ export async function generateAgentGroupReport(
|
||||
],
|
||||
{ timeoutMs: Math.max(30, Math.min(1800, request.timeoutSeconds || 300)) * 1000 }
|
||||
)
|
||||
if (!ai.success || !ai.data) return { success: false, error: ai.error || 'AI 总结失败' }
|
||||
if (!ai.success || !ai.data) {
|
||||
return {
|
||||
...reportFailure(ai.error || 'AI 总结失败', 'ai', ai.errorCode),
|
||||
...(ai.errorStatus !== undefined ? { errorStatus: ai.errorStatus } : {}),
|
||||
...(ai.errorType ? { errorType: ai.errorType } : {})
|
||||
}
|
||||
}
|
||||
let tokenUsage = ai.usage
|
||||
const parseReport = (raw: string): ReturnType<typeof parseGroupDailyReport> =>
|
||||
parseGroupDailyReport(
|
||||
@@ -147,18 +158,24 @@ export async function generateAgentGroupReport(
|
||||
if (!repaired.success || !repaired.data) {
|
||||
const cause = parseError instanceof Error ? parseError.message : String(parseError)
|
||||
return {
|
||||
success: false,
|
||||
error: `${repaired.error || 'AI 修复日报 JSON 失败'}(原始错误:${cause})`
|
||||
...reportFailure(
|
||||
`${repaired.error || 'AI 修复日报 JSON 失败'}(原始错误:${cause})`,
|
||||
'ai',
|
||||
repaired.errorCode
|
||||
),
|
||||
...(repaired.errorStatus !== undefined ? { errorStatus: repaired.errorStatus } : {}),
|
||||
...(repaired.errorType ? { errorType: repaired.errorType } : {})
|
||||
}
|
||||
}
|
||||
tokenUsage = mergeTokenUsage(tokenUsage, repaired.usage)
|
||||
try {
|
||||
report = parseReport(repaired.data)
|
||||
} catch (repairError) {
|
||||
return {
|
||||
success: false,
|
||||
error: repairError instanceof Error ? repairError.message : String(repairError)
|
||||
}
|
||||
return reportFailure(
|
||||
repairError instanceof Error ? repairError.message : String(repairError),
|
||||
'report',
|
||||
'REPORT_GENERATION_FAILED'
|
||||
)
|
||||
}
|
||||
}
|
||||
const exported = await exportGroupReport({
|
||||
@@ -167,7 +184,7 @@ export async function generateAgentGroupReport(
|
||||
templateId: request.templateId
|
||||
})
|
||||
if (!exported.success || !exported.pngPath) {
|
||||
return { success: false, error: exported.error || '总结图片生成失败' }
|
||||
return reportFailure(exported.error || '总结图片生成失败', 'report', 'REPORT_GENERATION_FAILED')
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
@@ -196,3 +213,16 @@ function mergeTokenUsage(
|
||||
estimated: Boolean(first.estimated || second.estimated)
|
||||
}
|
||||
}
|
||||
|
||||
function reportFailure(
|
||||
error: string,
|
||||
errorStage: ScheduledReportExecutionStage,
|
||||
errorCode?: string
|
||||
): AgentGroupReportResult {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
errorStage,
|
||||
...(errorCode ? { errorCode } : {})
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { app, BrowserWindow } from 'electron'
|
||||
import { ChildProcess, execFile, spawn } from 'child_process'
|
||||
import { randomBytes, timingSafeEqual } from 'crypto'
|
||||
import { appendFileSync, existsSync, mkdirSync, writeFileSync } from 'fs'
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
|
||||
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'
|
||||
import { dirname, join } from 'path'
|
||||
import { promisify } from 'util'
|
||||
@@ -40,6 +40,19 @@ interface InboundMessage {
|
||||
items?: Array<{ type?: number; text?: string }>
|
||||
}
|
||||
|
||||
interface AgentHubNotificationRecipient {
|
||||
accountId?: string
|
||||
userId: string
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export interface AgentHubNotificationResult {
|
||||
success: boolean
|
||||
status: 'sent' | 'recipient_unavailable' | 'connector_offline' | 'token_expired' | 'send_failed'
|
||||
recipient?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
interface GroupReportIntent {
|
||||
group: string
|
||||
range: 'today' | 'yesterday' | '7days'
|
||||
@@ -94,7 +107,7 @@ export function resolveWechatConnectorBinaryPath(
|
||||
)
|
||||
}
|
||||
|
||||
class AgentHubService {
|
||||
export class AgentHubService {
|
||||
private hubServer: Server | null = null
|
||||
private connectorChild: ChildProcess | null = null
|
||||
private loginChild: ChildProcess | null = null
|
||||
@@ -103,6 +116,8 @@ class AgentHubService {
|
||||
private logs: AgentHubLogEntry[] = []
|
||||
private nextLogId = 1
|
||||
private readonly processedMessages = new Map<string, number>()
|
||||
private notificationRecipient: AgentHubNotificationRecipient | null = null
|
||||
private notificationRecipientLoaded = false
|
||||
private readonly inboundToken =
|
||||
process.env['AGENT_HUB_INBOUND_TOKEN'] || randomBytes(32).toString('hex')
|
||||
private status: AgentHubStatus = {
|
||||
@@ -115,6 +130,7 @@ class AgentHubService {
|
||||
async start(settings: AppSettings): Promise<boolean> {
|
||||
void settings
|
||||
this.stopping = false
|
||||
this.loadNotificationRecipient()
|
||||
const hubStarted = await this.startHub()
|
||||
await this.initializeConnector()
|
||||
return hubStarted
|
||||
@@ -124,6 +140,53 @@ class AgentHubService {
|
||||
return { ...this.status }
|
||||
}
|
||||
|
||||
/** The last user who sent an inbound message to this Agent Hub bot. */
|
||||
getNotificationRecipient(): string | undefined {
|
||||
this.loadNotificationRecipient()
|
||||
return this.notificationRecipient?.userId
|
||||
}
|
||||
|
||||
async sendNotification(input: {
|
||||
to?: string
|
||||
text: string
|
||||
}): Promise<AgentHubNotificationResult> {
|
||||
const to = String(input.to || this.getNotificationRecipient() || '').trim()
|
||||
const text = String(input.text || '').trim()
|
||||
if (!to || !text) {
|
||||
return {
|
||||
success: false,
|
||||
status: 'recipient_unavailable',
|
||||
error: 'Agent Hub 尚未记录可靠的通知接收者'
|
||||
}
|
||||
}
|
||||
const accountId = this.notificationRecipient?.accountId || this.status.accountId
|
||||
try {
|
||||
const response = await this.postConnectorMessage({
|
||||
accountId,
|
||||
to,
|
||||
text,
|
||||
timeoutMs: 30_000
|
||||
})
|
||||
if (response.ok) return { success: true, status: 'sent', recipient: to }
|
||||
const expired = /token|session|expired|unauthorized/i.test(response.body)
|
||||
return {
|
||||
success: false,
|
||||
status: expired ? 'token_expired' : 'send_failed',
|
||||
recipient: to,
|
||||
error: expired
|
||||
? 'Agent Hub 微信连接器登录凭证已失效'
|
||||
: `Agent Hub 通知发送失败:${response.body || response.status}`
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
status: 'connector_offline',
|
||||
recipient: to,
|
||||
error: `Agent Hub 微信连接器不可用:${this.errorMessage(error)}`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getLogs(): AgentHubLogEntry[] {
|
||||
return [...this.logs]
|
||||
}
|
||||
@@ -154,29 +217,24 @@ class AgentHubService {
|
||||
}
|
||||
}
|
||||
try {
|
||||
const response = await fetch(`http://${CONNECTOR_ADDR}/api/send`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
account_id: this.status.accountId,
|
||||
to,
|
||||
text: text || undefined,
|
||||
media_url: mediaUrl || undefined
|
||||
}),
|
||||
signal: AbortSignal.timeout(30_000)
|
||||
const response = await this.postConnectorMessage({
|
||||
accountId: this.status.accountId,
|
||||
to,
|
||||
text: text || undefined,
|
||||
mediaUrl: mediaUrl || undefined,
|
||||
timeoutMs: 30_000
|
||||
})
|
||||
const body = await response.text()
|
||||
if (response.ok) {
|
||||
this.addLog('system', 'info', 'API 页面发送测试成功')
|
||||
return { success: true, status: 'sent', message: '发送成功' }
|
||||
}
|
||||
const expired = /token|session|expired|unauthorized/i.test(body)
|
||||
const expired = /token|session|expired|unauthorized/i.test(response.body)
|
||||
return {
|
||||
success: false,
|
||||
status: expired ? 'token_expired' : 'send_failed',
|
||||
message: expired
|
||||
? '微信登录凭证已失效,请重新扫码登录'
|
||||
: `发送失败:${body || response.status}`
|
||||
: `发送失败:${response.body || response.status}`
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
@@ -326,6 +384,7 @@ class AgentHubService {
|
||||
}
|
||||
const from = String(inbound.from_user_id || '').trim()
|
||||
if (!from) return this.sendHubJson(response, 400, { error: 'from_user_id is required' })
|
||||
this.rememberNotificationRecipient(inbound.account_id, from)
|
||||
|
||||
const messageId = String(inbound.message_id || '')
|
||||
this.cleanProcessedMessages()
|
||||
@@ -791,18 +850,35 @@ class AgentHubService {
|
||||
text?: string,
|
||||
mediaUrl?: string
|
||||
): Promise<void> {
|
||||
const response = await this.postConnectorMessage({
|
||||
accountId: inbound.account_id || this.status.accountId,
|
||||
to: String(inbound.from_user_id || '').trim(),
|
||||
text,
|
||||
mediaUrl,
|
||||
timeoutMs: mediaUrl ? 60_000 : 30_000
|
||||
})
|
||||
if (!response.ok) throw new Error(response.body || `HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
private async postConnectorMessage(input: {
|
||||
accountId?: string
|
||||
to: string
|
||||
text?: string
|
||||
mediaUrl?: string
|
||||
timeoutMs: number
|
||||
}): Promise<{ ok: boolean; status: number; body: string }> {
|
||||
const response = await fetch(`http://${CONNECTOR_ADDR}/api/send`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
account_id: inbound.account_id,
|
||||
to: inbound.from_user_id,
|
||||
text,
|
||||
media_url: mediaUrl
|
||||
account_id: input.accountId,
|
||||
to: input.to,
|
||||
text: input.text,
|
||||
media_url: input.mediaUrl
|
||||
}),
|
||||
signal: AbortSignal.timeout(mediaUrl ? 60_000 : 30_000)
|
||||
signal: AbortSignal.timeout(input.timeoutMs)
|
||||
})
|
||||
if (!response.ok) throw new Error((await response.text()) || `HTTP ${response.status}`)
|
||||
return { ok: response.ok, status: response.status, body: await response.text() }
|
||||
}
|
||||
|
||||
private matchRecentChatIntent(text: string): number | null {
|
||||
@@ -965,6 +1041,51 @@ class AgentHubService {
|
||||
}
|
||||
}
|
||||
|
||||
private loadNotificationRecipient(): void {
|
||||
if (this.notificationRecipientLoaded) return
|
||||
this.notificationRecipientLoaded = true
|
||||
try {
|
||||
const stored = JSON.parse(readFileSync(this.notificationRecipientPath(), 'utf8')) as {
|
||||
accountId?: unknown
|
||||
userId?: unknown
|
||||
updatedAt?: unknown
|
||||
}
|
||||
const userId = String(stored.userId || '').trim()
|
||||
if (userId) {
|
||||
this.notificationRecipient = {
|
||||
userId,
|
||||
accountId: String(stored.accountId || '').trim() || undefined,
|
||||
updatedAt: Number(stored.updatedAt) || Date.now()
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
this.notificationRecipient = null
|
||||
}
|
||||
}
|
||||
|
||||
private rememberNotificationRecipient(accountId: string | undefined, userId: string): void {
|
||||
const normalizedUserId = String(userId || '').trim()
|
||||
if (!normalizedUserId) return
|
||||
const recipient: AgentHubNotificationRecipient = {
|
||||
userId: normalizedUserId,
|
||||
accountId: String(accountId || this.status.accountId || '').trim() || undefined,
|
||||
updatedAt: Date.now()
|
||||
}
|
||||
this.notificationRecipient = recipient
|
||||
this.notificationRecipientLoaded = true
|
||||
try {
|
||||
const filePath = this.notificationRecipientPath()
|
||||
mkdirSync(dirname(filePath), { recursive: true })
|
||||
writeFileSync(filePath, JSON.stringify(recipient, null, 2), 'utf8')
|
||||
} catch (error) {
|
||||
this.addLog('agent-hub', 'warn', `通知接收者保存失败:${this.errorMessage(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
private notificationRecipientPath(): string {
|
||||
return join(app.getPath('userData'), 'agent-hub', 'notification-recipient.json')
|
||||
}
|
||||
|
||||
private async loadAccounts(): Promise<{ accountId: string; wechatUserId: string }[]> {
|
||||
const executable = resolveWechatConnectorBinaryPath()
|
||||
if (!existsSync(executable)) throw new Error(`微信连接器不存在:${executable}`)
|
||||
|
||||
@@ -31,7 +31,7 @@ type AIRequestResult = {
|
||||
usage?: { input?: number; output?: number; total?: number; estimated?: boolean }
|
||||
}
|
||||
interface OpenAIResponsePayload {
|
||||
error?: { message?: string }
|
||||
error?: { message?: string; code?: string | number; type?: string }
|
||||
choices?: Array<{
|
||||
message?: {
|
||||
content?: string | Array<{ type?: string; text?: string }> | null
|
||||
@@ -42,12 +42,12 @@ interface OpenAIResponsePayload {
|
||||
usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number }
|
||||
}
|
||||
interface OpenAIStreamPayload {
|
||||
error?: { message?: string }
|
||||
error?: { message?: string; code?: string | number; type?: string }
|
||||
choices?: Array<{ delta?: { content?: string }; finish_reason?: string }>
|
||||
usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number }
|
||||
}
|
||||
interface OpenAIResponsesPayload {
|
||||
error?: { message?: string }
|
||||
error?: { message?: string; code?: string | number; type?: string }
|
||||
incomplete_details?: { reason?: string }
|
||||
status?: string
|
||||
output_text?: string
|
||||
@@ -61,16 +61,35 @@ interface OpenAIResponsesStreamPayload {
|
||||
type?: string
|
||||
delta?: string
|
||||
message?: string
|
||||
error?: { message?: string }
|
||||
error?: { message?: string; code?: string | number; type?: string }
|
||||
response?: OpenAIResponsesPayload
|
||||
}
|
||||
interface AnthropicResponsePayload {
|
||||
error?: { message?: string }
|
||||
error?: { message?: string; type?: string }
|
||||
content?: Array<{ type?: string; text?: string }>
|
||||
stop_reason?: string
|
||||
usage?: { input_tokens?: number; output_tokens?: number }
|
||||
}
|
||||
|
||||
export class AIProviderRequestError extends Error {
|
||||
readonly status?: number
|
||||
readonly code?: string
|
||||
readonly type?: string
|
||||
readonly responseBody?: unknown
|
||||
|
||||
constructor(
|
||||
message: string,
|
||||
details: { status?: number; code?: unknown; type?: unknown; responseBody?: unknown } = {}
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'AIProviderRequestError'
|
||||
this.status = details.status
|
||||
this.code = typeof details.code === 'string' ? details.code : undefined
|
||||
this.type = typeof details.type === 'string' ? details.type : undefined
|
||||
this.responseBody = details.responseBody
|
||||
}
|
||||
}
|
||||
|
||||
export class AIProviderService {
|
||||
constructor(private readonly keyStore = new AIProviderKeyStore()) {}
|
||||
|
||||
@@ -272,12 +291,15 @@ export class AIProviderService {
|
||||
finishReason?: string
|
||||
usage?: { input?: number; output?: number; total?: number; estimated?: boolean }
|
||||
error?: string
|
||||
errorCode?: string
|
||||
errorStatus?: number
|
||||
errorType?: string
|
||||
}> {
|
||||
try {
|
||||
return { success: true, ...(await this.request(messages, options, false, signal, onDelta)) }
|
||||
} catch (error) {
|
||||
if (signal?.aborted) throw error
|
||||
return { success: false, error: safeAIError(error) }
|
||||
return { success: false, error: safeAIError(error), ...aiProviderErrorDetails(error) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -752,7 +774,15 @@ async function requestOpenAICompatible(
|
||||
async (response) => {
|
||||
if (!response.ok) {
|
||||
const payload = await parseJsonResponse<OpenAIResponsePayload>(response)
|
||||
throw new Error(payload.error?.message || `AI 请求失败 (${response.status})`)
|
||||
throw new AIProviderRequestError(
|
||||
payload.error?.message || `AI 请求失败 (${response.status})`,
|
||||
{
|
||||
status: response.status,
|
||||
code: payload.error?.code,
|
||||
type: payload.error?.type,
|
||||
responseBody: payload.error
|
||||
}
|
||||
)
|
||||
}
|
||||
if (
|
||||
provider.advanced.stream &&
|
||||
@@ -810,7 +840,15 @@ async function requestOpenAIResponses(
|
||||
async (response) => {
|
||||
if (!response.ok) {
|
||||
const payload = await parseJsonResponse<OpenAIResponsesPayload>(response)
|
||||
throw new Error(payload.error?.message || `AI 请求失败 (${response.status})`)
|
||||
throw new AIProviderRequestError(
|
||||
payload.error?.message || `AI 请求失败 (${response.status})`,
|
||||
{
|
||||
status: response.status,
|
||||
code: payload.error?.code,
|
||||
type: payload.error?.type,
|
||||
responseBody: payload.error
|
||||
}
|
||||
)
|
||||
}
|
||||
if (provider.advanced.stream) return parseOpenAIResponsesStream(response, onDelta)
|
||||
const payload = await parseJsonResponse<OpenAIResponsesPayload>(response)
|
||||
@@ -867,7 +905,14 @@ async function requestAnthropic(
|
||||
async (response) => {
|
||||
const payload = await parseJsonResponse<AnthropicResponsePayload>(response)
|
||||
if (!response.ok)
|
||||
throw new Error(payload.error?.message || `Anthropic 请求失败 (${response.status})`)
|
||||
throw new AIProviderRequestError(
|
||||
payload.error?.message || `Anthropic 请求失败 (${response.status})`,
|
||||
{
|
||||
status: response.status,
|
||||
type: payload.error?.type,
|
||||
responseBody: payload.error
|
||||
}
|
||||
)
|
||||
return {
|
||||
data: Array.isArray(payload.content)
|
||||
? payload.content
|
||||
@@ -1156,6 +1201,27 @@ function safeAIError(error: unknown): string {
|
||||
return message.replace(/sk-[a-z0-9_-]+/gi, '***').slice(0, 300)
|
||||
}
|
||||
|
||||
function aiProviderErrorDetails(error: unknown): {
|
||||
errorCode?: string
|
||||
errorStatus?: number
|
||||
errorType?: string
|
||||
} {
|
||||
if (error instanceof AIProviderRequestError) {
|
||||
return {
|
||||
...(error.code ? { errorCode: error.code } : {}),
|
||||
...(error.status !== undefined ? { errorStatus: error.status } : {}),
|
||||
...(error.type ? { errorType: error.type } : {})
|
||||
}
|
||||
}
|
||||
const record = error && typeof error === 'object' ? (error as Record<string, unknown>) : undefined
|
||||
const status = Number(record?.status)
|
||||
return {
|
||||
...(typeof record?.code === 'string' ? { errorCode: record.code } : {}),
|
||||
...(Number.isFinite(status) && status > 0 ? { errorStatus: status } : {}),
|
||||
...(typeof record?.type === 'string' ? { errorType: record.type } : {})
|
||||
}
|
||||
}
|
||||
|
||||
function parseVisionImage(dataUrl: string): { mimeType: string; base64: string; bytes: number } {
|
||||
const match = /^data:(image\/(?:png|jpeg|webp));base64,([a-z0-9+/=]+)$/i.exec(dataUrl)
|
||||
if (!match) throw new Error('图片格式不受支持,请选择 PNG、JPG、JPEG 或 WebP')
|
||||
|
||||
@@ -27,7 +27,8 @@ export interface ScheduledReportApiDependencies {
|
||||
| 'deleteTask'
|
||||
| 'setTaskEnabled'
|
||||
| 'runScheduledReportNow'
|
||||
>
|
||||
> &
|
||||
Partial<Pick<ScheduledReportService, 'retryScheduledReportSend'>>
|
||||
getCapability: () => Promise<PersonalWechatSendCapability>
|
||||
listContacts: () => FormattedContact[]
|
||||
isDatabaseReady: () => boolean
|
||||
@@ -102,7 +103,6 @@ export class ScheduledReportApiService {
|
||||
request: ScheduledReportApiCreateRequest
|
||||
): Promise<ScheduledReportApiTask> {
|
||||
this.assertDatabaseReady()
|
||||
await this.assertCapabilityReady()
|
||||
if (!isRecord(request))
|
||||
throw new ScheduledReportApiError(400, 'invalid_request', '请求体格式无效')
|
||||
|
||||
@@ -250,6 +250,18 @@ export class ScheduledReportApiService {
|
||||
return result.data
|
||||
}
|
||||
|
||||
async retrySend(executionId: string): Promise<ScheduledReportExecution> {
|
||||
const retry = this.deps.service.retryScheduledReportSend
|
||||
if (!retry) {
|
||||
throw new ScheduledReportApiError(501, 'not_supported', '当前运行时不支持重新发送日报')
|
||||
}
|
||||
const result = await retry.call(this.deps.service, executionId)
|
||||
if (!result.data) {
|
||||
throw new ScheduledReportApiError(404, 'not_found', result.error || '未找到定时日报执行记录')
|
||||
}
|
||||
return result.data
|
||||
}
|
||||
|
||||
async executions(taskId: string): Promise<ScheduledReportApiExecution[]> {
|
||||
this.assertDatabaseReady()
|
||||
const task = await this.findTask(taskId)
|
||||
@@ -277,27 +289,6 @@ export class ScheduledReportApiService {
|
||||
}
|
||||
}
|
||||
|
||||
private async assertCapabilityReady(): Promise<void> {
|
||||
let capability: PersonalWechatSendCapability
|
||||
try {
|
||||
capability = this.applyPlatformCapability(await this.deps.getCapability())
|
||||
} catch (error) {
|
||||
throw new ScheduledReportApiError(
|
||||
503,
|
||||
'wechat_capability_unavailable',
|
||||
'微信发送能力检测失败,请在 TraceMemo 设置中检查个人微信。',
|
||||
error instanceof Error ? error.message : String(error)
|
||||
)
|
||||
}
|
||||
if (capability.ready && capability.capabilities.image) return
|
||||
throw new ScheduledReportApiError(
|
||||
409,
|
||||
'wechat_not_ready',
|
||||
capability.message || 'TraceMemo 当前还没有完成微信消息发送能力配置',
|
||||
{ capability: publicCapability(capability) }
|
||||
)
|
||||
}
|
||||
|
||||
private applyPlatformCapability(
|
||||
capability: PersonalWechatSendCapability
|
||||
): PersonalWechatSendCapability {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user