430 lines
18 KiB
JavaScript
430 lines
18 KiB
JavaScript
// R-003:流程席位完成后自动回报丞相。
|
||
// 唯一发送路径:业务只写 project.leadReports,LeadReportDispatcher 条件领取后经
|
||
// createUserMessage + agent.followup 排队到丞相会话;页面轮询只读,不驱动发送。
|
||
import { randomUUID } from 'node:crypto'
|
||
|
||
export class LeadReporterError extends Error {
|
||
constructor(code, message) {
|
||
super(message)
|
||
this.name = 'LeadReporterError'
|
||
this.code = code
|
||
}
|
||
}
|
||
|
||
export const LEAD_REPORT_LEASE_MS = 30_000
|
||
export const LEAD_REPORT_SUMMARY_LIMIT = 800
|
||
export const LEAD_REPORT_SOURCE_KINDS = Object.freeze(['sansheng-report', 'sansheng-task'])
|
||
export const LEAD_REPORT_STATUSES = Object.freeze(['pending', 'claimed', 'sending', 'delivered', 'unknown', 'failed'])
|
||
|
||
const SOURCE_KIND_SET = new Set(LEAD_REPORT_SOURCE_KINDS)
|
||
|
||
function isObject(value) { return value !== null && typeof value === 'object' && !Array.isArray(value) }
|
||
function cleanText(value) { return typeof value === 'string' ? value.trim() : '' }
|
||
function copy(value) {
|
||
try { return structuredClone(value) } catch { return JSON.parse(JSON.stringify(value)) }
|
||
}
|
||
function truncateSummary(value) {
|
||
const chars = Array.from(String(value ?? ''))
|
||
if (chars.length <= LEAD_REPORT_SUMMARY_LIMIT) return chars.join('')
|
||
return chars.slice(0, LEAD_REPORT_SUMMARY_LIMIT).join('')
|
||
}
|
||
function snapshotText(value) {
|
||
if (typeof value === 'string') return value
|
||
if (value === null || value === undefined) return ''
|
||
if (typeof value === 'object') {
|
||
try { return JSON.stringify(value) } catch { return String(value) }
|
||
}
|
||
return String(value)
|
||
}
|
||
function projectOf(state, projectId) {
|
||
const project = state?.projects?.[projectId]
|
||
if (!project) throw new LeadReporterError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
return project
|
||
}
|
||
function reportsOf(project) {
|
||
if (!Array.isArray(project.leadReports)) project.leadReports = []
|
||
return project.leadReports
|
||
}
|
||
function findReport(project, reportId) {
|
||
return (project.leadReports ?? []).find(item => item.reportId === reportId || item.id === reportId)
|
||
}
|
||
function findTask(project, taskId) {
|
||
if (!taskId) return null
|
||
return (project.tasks ?? []).find(item => item.id === taskId) ?? null
|
||
}
|
||
|
||
// 消息字段在 record 时冻结;这里绝不读取后续任务状态,只拼报告快照。
|
||
export function buildLeadReportMessage(report) {
|
||
const requirement = report?.requirementId
|
||
? `${report.requirementId}${report.requirementRevision === null || report.requirementRevision === undefined ? '' : ` v${report.requirementRevision}`}`
|
||
: '无'
|
||
return [
|
||
'【丞相回报】',
|
||
`任务:${report?.taskId ?? '无'}`,
|
||
`需求:${requirement}`,
|
||
`事件:${report?.event ?? ''}`,
|
||
`阶段:${report?.stage ?? '无'}`,
|
||
`执行席位:${report?.ownerSeatId ?? '无'}`,
|
||
`结果摘要:${truncateSummary(report?.summary ?? report?.textSnapshot ?? '')}`,
|
||
`下一步:${report?.nextStep || '无'}`,
|
||
`需要用户决策:${report?.needsUserDecision ? '是' : '否'}`,
|
||
].join('\n')
|
||
}
|
||
|
||
function defaultCreateUserMessage(input) {
|
||
return { role: 'user', content: input.content, source: input.source }
|
||
}
|
||
|
||
function readAgentEvents(agent) {
|
||
const events = []
|
||
const append = value => { if (Array.isArray(value)) events.push(...value) }
|
||
try { append(agent?.session?.deriveMessages?.()) } catch { /* 会话不可读时按无事件处理 */ }
|
||
try { append(agent?.deriveMessages?.()) } catch { /* 同上 */ }
|
||
append(agent?.messages)
|
||
append(agent?.session?.messages)
|
||
append(agent?.session?.events)
|
||
return events
|
||
}
|
||
|
||
// 在事件对象里深搜 reportId;只扫描会话事件,且限制节点数,避免大历史拖慢恢复。
|
||
function containsReportId(value, reportId, maxNodes = 5000) {
|
||
const stack = [value]
|
||
let seen = 0
|
||
while (stack.length > 0 && seen < maxNodes) {
|
||
const current = stack.pop()
|
||
seen += 1
|
||
if (!current || typeof current !== 'object') continue
|
||
if (isObject(current.source) && current.source.reportId === reportId) return true
|
||
if (current.reportId === reportId) return true
|
||
if (Array.isArray(current)) {
|
||
for (const item of current) stack.push(item)
|
||
continue
|
||
}
|
||
for (const child of Object.values(current)) {
|
||
if (child && typeof child === 'object') stack.push(child)
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
function taskStateProblem(project, report) {
|
||
if (!report.taskId) return ''
|
||
const task = findTask(project, report.taskId)
|
||
if (!task) return 'task-not-found'
|
||
if (report.transitionId && task.lastTransitionId && task.lastTransitionId !== report.transitionId) {
|
||
return 'task-transition-changed'
|
||
}
|
||
if (report.requirementRevision !== null && report.requirementRevision !== undefined
|
||
&& task.requirementRevision !== null && task.requirementRevision !== undefined
|
||
&& String(task.requirementRevision) !== String(report.requirementRevision)) {
|
||
return 'task-requirement-changed'
|
||
}
|
||
// 没有 lastTransitionId 的旧任务退化为阶段对比;有 lastTransitionId 时以它为准。
|
||
if (!task.lastTransitionId && report.stage && task.stage && String(task.stage) !== String(report.stage)) {
|
||
return 'task-stage-changed'
|
||
}
|
||
return ''
|
||
}
|
||
|
||
// 供 service 在既有业务事务内同步调用:只写 project.leadReports,不做任何异步/宿主调用。
|
||
export function recordLeadReportInState(state, projectId, event, now = Date.now()) {
|
||
if (!isObject(event)) throw new LeadReporterError('sansheng/lead-report-invalid', '回报事件必须是对象')
|
||
const at = typeof now === 'function' ? now() : Number(now)
|
||
return recordIntoProject(projectOf(state, projectId), projectId, event, at)
|
||
}
|
||
|
||
function recordIntoProject(project, projectId, event, at) {
|
||
const taskRef = isObject(event.task) ? event.task : null
|
||
const taskId = cleanText(event.taskId) || cleanText(taskRef?.id) || null
|
||
const task = taskRef ?? findTask(project, taskId)
|
||
const transitionId = cleanText(event.transitionId)
|
||
|| cleanText(event.lastTransitionId)
|
||
|| cleanText(task?.lastTransitionId)
|
||
|| cleanText(event.reportId)
|
||
if (!transitionId) throw new LeadReporterError('sansheng/lead-report-invalid', '回报事件缺少 transitionId')
|
||
const requestedReportId = cleanText(event.reportId)
|
||
const reports = reportsOf(project)
|
||
const existing = reports.find(item => item.transitionId === transitionId
|
||
|| (requestedReportId && item.reportId === requestedReportId))
|
||
if (existing) {
|
||
const snapshot = copy(existing)
|
||
return { ...copy(snapshot), report: snapshot, created: false, duplicate: true }
|
||
}
|
||
const reportId = requestedReportId || randomUUID()
|
||
const textSnapshot = snapshotText(event.textSnapshot ?? '')
|
||
const sourceKind = SOURCE_KIND_SET.has(event.sourceKind) ? event.sourceKind : 'sansheng-report'
|
||
const report = {
|
||
id: reportId,
|
||
reportId,
|
||
projectId,
|
||
transitionId,
|
||
taskId,
|
||
requirementId: event.requirementId ?? task?.requirementId ?? null,
|
||
requirementRevision: event.requirementRevision ?? task?.requirementRevision ?? null,
|
||
event: cleanText(event.event),
|
||
stage: event.stage ?? task?.stage ?? null,
|
||
ownerSeatId: event.ownerSeatId ?? task?.ownerSeatId ?? null,
|
||
textSnapshot,
|
||
sourceKind,
|
||
status: 'pending',
|
||
claimedBy: null,
|
||
leaseUntil: null,
|
||
attempts: 0,
|
||
summary: truncateSummary(cleanText(event.summary) || textSnapshot),
|
||
nextStep: cleanText(event.nextStep),
|
||
needsUserDecision: Boolean(event.needsUserDecision),
|
||
error: null,
|
||
createdAt: at,
|
||
updatedAt: at,
|
||
}
|
||
reports.push(report)
|
||
const snapshot = copy(report)
|
||
return { ...copy(snapshot), report: snapshot, created: true, duplicate: false }
|
||
}
|
||
|
||
export function createLeadReporter({ store, host = {}, now = () => Date.now() } = {}) {
|
||
if (!store || typeof store.get !== 'function' || typeof store.mutate !== 'function') {
|
||
throw new LeadReporterError('sansheng/lead-report-store', 'createLeadReporter 需要 store.ensureLoaded/get/mutate/snapshot')
|
||
}
|
||
const clock = typeof now === 'function' ? now : () => Number(now)
|
||
const ensureLoaded = async () => { if (typeof store.ensureLoaded === 'function') await store.ensureLoaded() }
|
||
|
||
async function locateReport(input) {
|
||
const reportId = typeof input === 'string' ? cleanText(input) : cleanText(input?.reportId ?? input?.id)
|
||
if (!reportId) throw new LeadReporterError('sansheng/lead-report-invalid', '缺少 reportId')
|
||
let projectId = typeof input === 'string' ? '' : cleanText(input?.projectId)
|
||
if (!projectId) {
|
||
const snapshot = typeof store.snapshot === 'function' ? store.snapshot() : { projects: {} }
|
||
for (const [id, project] of Object.entries(snapshot.projects ?? {})) {
|
||
if (findReport(project, reportId)) { projectId = id; break }
|
||
}
|
||
}
|
||
if (!projectId) throw new LeadReporterError('sansheng/lead-report-not-found', `回报 ${reportId} 不存在`)
|
||
return { reportId, projectId }
|
||
}
|
||
|
||
// record 自己开事务;若调用方已有业务事务,请改用 recordLeadReportInState(state, ...)。
|
||
async function record(projectId, event = {}) {
|
||
await ensureLoaded()
|
||
if (!isObject(event)) throw new LeadReporterError('sansheng/lead-report-invalid', '回报事件必须是对象')
|
||
let outcome = null
|
||
await store.mutate(state => {
|
||
outcome = recordIntoProject(projectOf(state, projectId), projectId, event, clock())
|
||
})
|
||
return outcome
|
||
}
|
||
|
||
// 只读列表:页面轮询只能读 leadReports,不能顺便领取/发送。
|
||
async function list(projectId) {
|
||
await ensureLoaded()
|
||
const project = store.get(projectId)
|
||
if (!project) throw new LeadReporterError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
return (project.leadReports ?? []).map(item => copy(item))
|
||
}
|
||
|
||
async function claimNext(projectId, options = {}) {
|
||
await ensureLoaded()
|
||
const owner = cleanText(options.owner) || `lead-report-dispatcher-${randomUUID()}`
|
||
return store.mutate(state => {
|
||
const project = projectOf(state, projectId)
|
||
const reports = reportsOf(project)
|
||
const at = clock()
|
||
for (const report of reports) {
|
||
if (report.status === 'claimed'
|
||
&& (!Number.isFinite(report.leaseUntil) || report.leaseUntil <= at)) {
|
||
report.status = 'pending'
|
||
report.claimedBy = null
|
||
report.leaseUntil = null
|
||
report.updatedAt = at
|
||
}
|
||
}
|
||
const next = reports
|
||
.filter(report => report.status === 'pending')
|
||
.sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0))[0]
|
||
if (!next) return null
|
||
next.status = 'claimed'
|
||
next.claimedBy = owner
|
||
next.leaseUntil = at + LEAD_REPORT_LEASE_MS
|
||
next.updatedAt = at
|
||
return copy(next)
|
||
})
|
||
}
|
||
|
||
async function resolveLeadAgent(sessionId) {
|
||
let agent = host.agents?.get?.(sessionId)
|
||
if (!agent && typeof host.sessionController?.resolveAgent === 'function') {
|
||
try {
|
||
const resolved = await host.sessionController.resolveAgent(sessionId)
|
||
if (resolved && !('error' in resolved)) agent = resolved.agent
|
||
} catch { /* 宿主未提供可解析会话时按不可用处理 */ }
|
||
}
|
||
return agent
|
||
}
|
||
|
||
async function reportSeenInLeadSession(projectId, reportId) {
|
||
const project = store.get(projectId)
|
||
const sessionId = project?.seats?.lead?.sessionId
|
||
if (!sessionId) return false
|
||
if (typeof host.findReportEvent === 'function') {
|
||
try {
|
||
if (await host.findReportEvent({ projectId, sessionId, reportId })) return true
|
||
} catch { /* 自定义查询失败时退回扫描会话事件 */ }
|
||
}
|
||
const agent = await resolveLeadAgent(sessionId)
|
||
if (!agent) return false
|
||
return readAgentEvents(agent).some(event => containsReportId(event, reportId))
|
||
}
|
||
|
||
async function trySend(input) {
|
||
await ensureLoaded()
|
||
const located = await locateReport(input)
|
||
const expectedClaimedBy = isObject(input) ? cleanText(input.claimedBy) : ''
|
||
if (!expectedClaimedBy) {
|
||
return { ok: false, status: 'claimed', reason: 'missing-claimer' }
|
||
}
|
||
const phase = await store.mutate(state => {
|
||
const project = projectOf(state, located.projectId)
|
||
const report = findReport(project, located.reportId)
|
||
if (!report) return { reason: 'not-found' }
|
||
if (report.status === 'delivered') return { done: true, report: copy(report) }
|
||
if (report.status !== 'claimed') return { reason: 'not-claimed', status: report.status, report: copy(report) }
|
||
if (report.claimedBy !== expectedClaimedBy) return { reason: 'not-claimed', status: report.status, report: copy(report) }
|
||
const at = clock()
|
||
if (!Number.isFinite(report.leaseUntil) || report.leaseUntil <= at) {
|
||
return { reason: 'lease-expired', status: report.status, report: copy(report) }
|
||
}
|
||
const problem = taskStateProblem(project, report)
|
||
if (problem) {
|
||
report.status = 'failed'
|
||
report.error = problem
|
||
report.leaseUntil = null
|
||
report.updatedAt = at
|
||
return { reason: problem, status: 'failed', report: copy(report) }
|
||
}
|
||
const lead = project.seats?.lead
|
||
if (!lead || lead.status !== 'bound' || !lead.sessionId) {
|
||
report.status = 'failed'
|
||
report.error = 'lead-seat-unbound'
|
||
report.leaseUntil = null
|
||
report.updatedAt = at
|
||
return { reason: 'lead-seat-unbound', status: 'failed', report: copy(report) }
|
||
}
|
||
report.status = 'sending'
|
||
report.attempts = (report.attempts ?? 0) + 1
|
||
report.leaseUntil = at + LEAD_REPORT_LEASE_MS
|
||
report.updatedAt = at
|
||
report.error = null
|
||
return { report: copy(report), sessionId: lead.sessionId }
|
||
})
|
||
if (phase.done) return { ok: true, status: 'delivered', duplicate: true, report: phase.report }
|
||
if (!phase.report || !phase.sessionId) {
|
||
return { ok: false, status: phase.status ?? 'pending', reason: phase.reason, report: phase.report }
|
||
}
|
||
|
||
const sending = phase.report
|
||
let sendError = null
|
||
try {
|
||
const factory = typeof host.createUserMessage === 'function' ? host.createUserMessage : defaultCreateUserMessage
|
||
const message = await Promise.resolve(factory({
|
||
content: [{ type: 'text', text: buildLeadReportMessage(sending) }],
|
||
source: { kind: sending.sourceKind, reportId: sending.reportId, taskId: sending.taskId },
|
||
}))
|
||
const agent = await resolveLeadAgent(phase.sessionId)
|
||
if (!agent || typeof agent.followup !== 'function') {
|
||
throw new LeadReporterError('sansheng/lead-session-unavailable', `丞相会话不可用:${phase.sessionId}`)
|
||
}
|
||
await agent.followup(message)
|
||
} catch (error) {
|
||
sendError = error
|
||
}
|
||
|
||
// 只有调用过 followup 之后才可能“已入队未落账”:找不到事件就记 unknown,绝不自动重送。
|
||
const status = sendError
|
||
? (await reportSeenInLeadSession(located.projectId, located.reportId) ? 'delivered' : 'unknown')
|
||
: 'delivered'
|
||
const finalized = await store.mutate(state => {
|
||
const report = findReport(projectOf(state, located.projectId), located.reportId)
|
||
if (!report) return null
|
||
const at = clock()
|
||
report.status = status
|
||
report.leaseUntil = null
|
||
report.updatedAt = at
|
||
if (status === 'delivered') {
|
||
report.deliveredAt = at
|
||
report.error = null
|
||
} else {
|
||
report.error = String(sendError?.message ?? sendError)
|
||
}
|
||
return copy(report)
|
||
})
|
||
return {
|
||
ok: status === 'delivered',
|
||
status,
|
||
report: finalized,
|
||
error: sendError ? String(sendError?.message ?? sendError) : undefined,
|
||
}
|
||
}
|
||
|
||
// 恢复:claimed 超时退回 pending;sending 遗留只按 reportId 核实,不重送。
|
||
async function recover(projectId) {
|
||
await ensureLoaded()
|
||
const at = clock()
|
||
const sending = []
|
||
await store.mutate(state => {
|
||
const project = projectOf(state, projectId)
|
||
for (const report of reportsOf(project)) {
|
||
if (report.status === 'claimed'
|
||
&& (!Number.isFinite(report.leaseUntil) || report.leaseUntil <= at)) {
|
||
report.status = 'pending'
|
||
report.claimedBy = null
|
||
report.leaseUntil = null
|
||
report.updatedAt = at
|
||
} else if (report.status === 'sending'
|
||
&& (!Number.isFinite(report.leaseUntil) || report.leaseUntil <= at)) {
|
||
sending.push(copy(report))
|
||
}
|
||
}
|
||
})
|
||
const recovered = []
|
||
for (const report of sending) {
|
||
const found = await reportSeenInLeadSession(projectId, report.reportId)
|
||
const status = found ? 'delivered' : 'unknown'
|
||
await store.mutate(state => {
|
||
const current = findReport(projectOf(state, projectId), report.reportId)
|
||
if (!current || current.status !== 'sending') return
|
||
const nowAt = clock()
|
||
if (Number.isFinite(current.leaseUntil) && current.leaseUntil > nowAt) return
|
||
current.status = status
|
||
current.leaseUntil = null
|
||
current.updatedAt = nowAt
|
||
if (found) {
|
||
current.deliveredAt = nowAt
|
||
current.error = null
|
||
} else {
|
||
current.error = current.error ?? 'sending result not found in lead session'
|
||
}
|
||
})
|
||
recovered.push({ reportId: report.reportId, status })
|
||
}
|
||
return recovered
|
||
}
|
||
|
||
async function flush(projectId) {
|
||
const recovered = await recover(projectId)
|
||
const sent = []
|
||
for (let index = 0; index < 500; index += 1) {
|
||
const claimed = await claimNext(projectId)
|
||
if (!claimed) break
|
||
const result = await trySend(claimed)
|
||
sent.push({ reportId: claimed.reportId, ...result })
|
||
if (!result.ok && result.status === 'claimed') break
|
||
}
|
||
const output = sent.slice()
|
||
output.sent = sent
|
||
output.recovered = recovered
|
||
return output
|
||
}
|
||
|
||
return { record, flush, claimNext, trySend, list, recover }
|
||
}
|