2877 lines
150 KiB
JavaScript
2877 lines
150 KiB
JavaScript
import { randomUUID, createHash } from 'node:crypto'
|
||
import { basename } from 'node:path'
|
||
import { SEAT_IDS, SEATS, SEAT_GROUPS } from '../shared/roles.js'
|
||
import { emptyTask, emptyArtifact, emptyRequirement } from '../shared/schema.js'
|
||
import { mergeProjectMemory, normalizeProjectMemory, renderProjectMemory } from '../shared/project-memory.js'
|
||
import { applyModel, normalizeSelection } from './model.js'
|
||
import { internalSource } from './message-source.js'
|
||
import { getCommand, putCommand } from './command-ledger.js'
|
||
import { recordLeadReportInState } from './lead-reporter.js'
|
||
import { workflowBlockageOf } from './workflow-blockage.js'
|
||
|
||
export class ServiceError extends Error {
|
||
constructor(code, message) { super(message); this.name = 'ServiceError'; this.code = code }
|
||
}
|
||
|
||
export function seatView(seatId, seat, extra = {}) {
|
||
const def = SEATS[seatId]
|
||
return {
|
||
id: seatId,
|
||
label: def.label,
|
||
duty: def.duty,
|
||
responsibility: def.responsibility,
|
||
status: seat.status,
|
||
sessionId: seat.sessionId ?? null,
|
||
previousSessionIds: Array.isArray(seat.previousSessionIds) ? [...seat.previousSessionIds] : [],
|
||
model: seat.model ?? null,
|
||
configuredModel: extra.configuredModel ?? seat.model ?? null,
|
||
modelSource: extra.modelSource ?? (seat.model ? 'project' : 'none'),
|
||
sessionModel: extra.sessionModel ?? null,
|
||
modelSync: extra.modelSync ?? null,
|
||
runtimeState: extra.runtimeState ?? null,
|
||
instructions: seat.instructions ?? '',
|
||
error: seat.error ?? null,
|
||
}
|
||
}
|
||
|
||
export function projectView(project, seatExtras = {}) {
|
||
return {
|
||
revision: project.revision ?? 0,
|
||
project: {
|
||
id: project.id,
|
||
name: project.name,
|
||
workspaceId: project.workspaceId ?? null,
|
||
path: project.path ?? null,
|
||
status: project.status,
|
||
avatars: { ...(project.avatars ?? {}) },
|
||
seats: SEAT_IDS.map(id => seatView(id, project.seats[id], seatExtras[id] ?? {})),
|
||
groups: {
|
||
lead: [...SEAT_GROUPS.lead],
|
||
sansheng: [...SEAT_GROUPS.sansheng],
|
||
liubu: [...SEAT_GROUPS.liubu],
|
||
},
|
||
},
|
||
}
|
||
}
|
||
|
||
const REQUIREMENT_TEXT_FIELDS = [
|
||
'title', 'summary', 'originalText', 'judgement', 'judgementReason', 'scope',
|
||
'nonGoals', 'acceptanceCriteria', 'risks', 'dependencies', 'missingInfo',
|
||
]
|
||
// 中书拟案时只能补这些空缺字段;标题、用户原话和判断仍由丞相维护。
|
||
const REQUIREMENT_FILL_FIELDS = ['scope', 'nonGoals', 'acceptanceCriteria', 'risks', 'dependencies', 'missingInfo']
|
||
const OPEN_TASK_STATUS = new Set(['draft', 'dispatched', 'running', 'prepared', 'waiting_user', 'returned', 'reconfirm'])
|
||
const CARD_LIMIT = 200
|
||
const CARD_KINDS = new Set(['question', 'approval'])
|
||
// 议政:三省代表按固定顺序轮转;上限可配,0 表示不设上限。
|
||
const DELIBERATION_SEATS = Object.freeze(['zhongshu', 'menxia', 'shangshu'])
|
||
const DELIBERATION_STANCES = new Set(['agree', 'dissent', 'neutral'])
|
||
const DELIBERATION_LIMIT = 60
|
||
const DELIBERATION_TIMEOUT_MS = 180000
|
||
const DELIBERATION_MAX_ROUNDS = 20
|
||
const DELIBERATION_DEFAULT_ROUNDS = 3
|
||
const AVATAR_MAX_BYTES = 120 * 1024
|
||
const AVATAR_CHAR_MAX = 8
|
||
|
||
function normalizeCardOptions(raw, kind) {
|
||
const options = (Array.isArray(raw) ? raw : []).map(item => ({
|
||
label: cleanText(item?.label),
|
||
value: cleanText(item?.value),
|
||
description: cleanText(item?.description),
|
||
})).filter(item => item.label && item.value)
|
||
if (kind === 'approval') {
|
||
if (options.length === 0) {
|
||
return [
|
||
{ label: '同意', value: 'allow', description: '允许这次操作' },
|
||
{ label: '拒绝', value: 'reject', description: '拒绝这次操作' },
|
||
]
|
||
}
|
||
if (options.length !== 2 || options.some(item => !['allow', 'reject'].includes(item.value))
|
||
|| new Set(options.map(item => item.value)).size !== 2) {
|
||
throw new ServiceError('sansheng/card-invalid', '审批卡必须提供 allow 和 reject 两个选项')
|
||
}
|
||
return options
|
||
}
|
||
if (options.length < 2 || options.length > 5 || new Set(options.map(item => item.value)).size !== options.length) {
|
||
throw new ServiceError('sansheng/card-invalid', '问题卡需要 2 到 5 个不重复选项')
|
||
}
|
||
return options
|
||
}
|
||
|
||
function capCards(list) {
|
||
if (list.length > CARD_LIMIT) list.splice(0, list.length - CARD_LIMIT)
|
||
}
|
||
|
||
function deliberationSeatLabel(seatId) {
|
||
return SEATS[seatId]?.label ?? seatId
|
||
}
|
||
|
||
function deliberationStanceLabel(stance) {
|
||
if (stance === 'agree') return '同意'
|
||
if (stance === 'dissent') return '有分歧'
|
||
return '未表态'
|
||
}
|
||
|
||
function deliberationSummary(record) {
|
||
return {
|
||
id: record.id,
|
||
topic: record.topic,
|
||
status: record.status,
|
||
round: record.round,
|
||
maxRounds: record.maxRounds,
|
||
currentSeatId: record.currentSeatId ?? null,
|
||
currentSeatLabel: record.currentSeatId ? deliberationSeatLabel(record.currentSeatId) : null,
|
||
turn: record.turn ? {
|
||
round: record.turn.round,
|
||
seatId: record.turn.seatId,
|
||
status: record.turn.status,
|
||
attempts: record.turn.attempts ?? 0,
|
||
startedAt: record.turn.startedAt ?? null,
|
||
error: record.turn.error ?? null,
|
||
} : null,
|
||
speechCount: (record.speeches ?? []).length,
|
||
missing: (record.missing ?? []).map(item => ({ ...item })),
|
||
stoppedTurn: record.stoppedTurn ? { ...record.stoppedTurn, seatLabel: deliberationSeatLabel(record.stoppedTurn.seatId) } : null,
|
||
stoppedAt: record.stoppedAt ?? null,
|
||
stoppedBy: record.stoppedBy ?? null,
|
||
stoppedNote: record.stoppedNote ?? null,
|
||
conclusion: record.conclusion ? { ...record.conclusion } : null,
|
||
linked: {
|
||
taskId: record.taskId ?? null,
|
||
requirementId: record.requirementId ?? null,
|
||
requirementRevision: record.requirementRevision ?? null,
|
||
},
|
||
originSessionId: record.originSessionId ?? null,
|
||
startedBy: record.startedBy ?? 'user',
|
||
createdAt: record.createdAt ?? null,
|
||
updatedAt: record.updatedAt ?? null,
|
||
concludedAt: record.concludedAt ?? null,
|
||
}
|
||
}
|
||
|
||
function deliberationTranscript(record) {
|
||
const speeches = record.speeches ?? []
|
||
if (speeches.length === 0) return '(尚无发言)'
|
||
const rounds = [...new Set(speeches.map(item => item.round))].sort((a, b) => a - b)
|
||
return rounds.map(round => {
|
||
const lines = speeches.filter(item => item.round === round).map(item => {
|
||
const tags = [deliberationStanceLabel(item.stance)]
|
||
if (item.pending) tags.push('仍有待决问题')
|
||
const head = '- ' + deliberationSeatLabel(item.seatId) + '(' + tags.join(',') + '):' + item.text
|
||
return item.openIssues ? head + '\n 未决:' + item.openIssues : head
|
||
})
|
||
return '第 ' + round + ' 轮\n' + lines.join('\n')
|
||
}).join('\n\n')
|
||
}
|
||
|
||
function deliberationLinkText(project, record) {
|
||
const task = record.taskId ? (project.tasks ?? []).find(item => item.id === record.taskId) : null
|
||
const requirement = record.requirementId ? (project.requirements ?? []).find(item => item.id === record.requirementId) : null
|
||
if (!task && !requirement) return '本次议政不关联任务或需求。'
|
||
const lines = []
|
||
if (task) lines.push('关联任务:' + task.id + ' · ' + task.title + '(' + task.status + ')')
|
||
if (requirement) lines.push('关联需求:' + requirement.id + ' v' + requirement.revision + ' · ' + requirement.title)
|
||
const snapshot = task?.requirementSnapshot ?? {}
|
||
const originalText = requirement?.originalText || snapshot.originalText || task?.requirement || ''
|
||
const scope = requirement?.scope || snapshot.scope || ''
|
||
const acceptance = requirement?.acceptanceCriteria || snapshot.acceptanceCriteria || ''
|
||
if (originalText) lines.push('用户原话/要求:' + String(originalText).slice(0, 1200))
|
||
if (scope) lines.push('已确认范围:' + String(scope).slice(0, 1200))
|
||
if (acceptance) lines.push('已确认验收:' + String(acceptance).slice(0, 1200))
|
||
return lines.join('\n')
|
||
}
|
||
|
||
function deliberationMessage(project, record, seatId, round) {
|
||
const maxText = record.maxRounds > 0 ? String(record.maxRounds) : '不限'
|
||
return [
|
||
'【三省议政】' + record.id + ' · ' + record.topic,
|
||
deliberationLinkText(project, record),
|
||
'轮次:第 ' + round + ' 轮,上限 ' + maxText + ' 轮。当前当值:' + deliberationSeatLabel(seatId) + '。',
|
||
'已登记发言:',
|
||
deliberationTranscript(record),
|
||
round === 1
|
||
? '这是第一轮,请先说明本省判断:同意、反对,或还有待决问题。'
|
||
: '请只回应尚未解决的分歧,不要重复已经达成的内容;如果已经没有待决问题,明确说同意。',
|
||
'提交方式:调用 sansheng_deliberation_speak,参数 deliberationId=' + record.id + ',round=' + round
|
||
+ ',text=你的发言,stance=agree|dissent|neutral,pending=是否仍有待决问题(true/false),openIssues=未决点(没有就留空)。',
|
||
'只有当前当值代表能提交本轮,提交一次即可;不要发布、批准、派工或修改任务。',
|
||
].join('\n')
|
||
}
|
||
|
||
function deliberationConclusion(record, reason, note = '') {
|
||
const latestBySeat = new Map()
|
||
for (const speech of record.speeches ?? []) latestBySeat.set(speech.seatId, speech)
|
||
const lines = []
|
||
for (const seatId of DELIBERATION_SEATS) {
|
||
const speech = latestBySeat.get(seatId)
|
||
if (!speech) continue
|
||
const tags = [deliberationStanceLabel(speech.stance)]
|
||
if (speech.pending) tags.push('仍有待决问题')
|
||
lines.push(deliberationSeatLabel(seatId) + ':' + speech.text + '(' + tags.join(',') + ')')
|
||
if (speech.openIssues) lines.push(' ' + deliberationSeatLabel(seatId) + '未决:' + speech.openIssues)
|
||
}
|
||
const missing = record.missing ?? []
|
||
if (missing.length) {
|
||
lines.push('未回:' + missing.map(item => deliberationSeatLabel(item.seatId) + '(第 ' + item.round + ' 轮 '
|
||
+ (item.reason === 'timeout' ? '超时' : '失败') + ')').join(';'))
|
||
}
|
||
const hasObjection = [...latestBySeat.values()].some(speech => speech.stance !== 'agree' || speech.pending || speech.openIssues)
|
||
const needsUserDecision = hasObjection || missing.length > 0
|
||
let head
|
||
if (reason === 'consensus') head = '三省一致,议政收束。'
|
||
else if (reason === 'max-rounds') head = '已达到配置的 ' + record.maxRounds + ' 轮上限,仍未完全一致。'
|
||
else if (reason === 'stopped') {
|
||
const at = record.stoppedTurn
|
||
? '停在第 ' + record.stoppedTurn.round + ' 轮 · ' + deliberationSeatLabel(record.stoppedTurn.seatId) + ',本轮不再叫下一位。'
|
||
: '已停止,本轮不再叫下一位。'
|
||
head = note ? '用户叫停议政:' + note + '(' + at + ')' : '用户叫停议政。' + at
|
||
} else head = note ? '发起人结束议政:' + note : '发起人结束议政。'
|
||
return {
|
||
text: [head, lines.join('\n')].filter(Boolean).join('\n'),
|
||
at: Date.now(),
|
||
by: reason === 'ended' ? 'initiator' : (reason === 'stopped' ? 'user' : 'system'),
|
||
needsUserDecision,
|
||
missing: missing.map(item => ({ ...item })),
|
||
stopped: reason === 'stopped' ? (record.stoppedTurn ?? null) : null,
|
||
}
|
||
}
|
||
|
||
function cleanText(value) { return typeof value === 'string' ? value.trim() : '' }
|
||
|
||
function leadReportEventOf(task, event, summary, extra = {}) {
|
||
return {
|
||
taskId: task.id,
|
||
transitionId: task.lastTransitionId || (task.id + ':' + (task.stage ?? '') + ':' + event),
|
||
event,
|
||
stage: task.stage ?? null,
|
||
ownerSeatId: task.ownerSeatId ?? null,
|
||
requirementId: task.requirementId ?? null,
|
||
requirementRevision: task.requirementRevision ?? null,
|
||
summary: String(summary ?? '').slice(0, 800),
|
||
textSnapshot: String(summary ?? '').slice(0, 800),
|
||
sourceKind: 'sansheng-report',
|
||
...extra,
|
||
}
|
||
}
|
||
|
||
function appendLeadReport(state, projectId, task, event, summary, extra = {}) {
|
||
if (!state?.projects?.[projectId] || !task) return null
|
||
return recordLeadReportInState(state, projectId, leadReportEventOf(task, event, summary, extra), Date.now())
|
||
}
|
||
|
||
// 下派只需用户明确授权、标题和用户原话;范围与验收标准由中书拟案补齐。
|
||
// 只有丞相明确判断 not_now 时才继续阻止下派,空白或默认 needs_discussion 都放行。
|
||
function requirementReadyProblem(req) {
|
||
if (!req || !cleanText(req.title)) return '缺少需求标题'
|
||
if (!cleanText(req.originalText)) return '缺少用户原始要求'
|
||
if (req.judgement === 'not_now') return '丞相判断暂不可做'
|
||
return ''
|
||
}
|
||
|
||
function requirementStatusOf(req) {
|
||
if (req.status === 'cancelled') return 'cancelled'
|
||
if (req.status === 'published') return 'published'
|
||
if (req.status === 'returned') return 'returned'
|
||
return requirementReadyProblem(req) ? 'discussing' : 'ready'
|
||
}
|
||
|
||
function requirementBlockedReason(req) {
|
||
if (req.status === 'cancelled') return '已取消'
|
||
if (req.status === 'published') return req.blockedReason || '已发布,等待流程推进'
|
||
if (req.status === 'returned') return req.blockedReason || '已退回,等待重新商讨或拟案'
|
||
if (req.judgement === 'not_now') return req.judgementReason || '丞相判断暂不可做'
|
||
return '可以交中书拟案,范围与验收标准由中书补齐'
|
||
}
|
||
|
||
|
||
function requirementSnapshot(req) {
|
||
return {
|
||
id: req.id, revision: req.revision, title: req.title, summary: req.summary,
|
||
originalText: req.originalText, scope: req.scope, nonGoals: req.nonGoals,
|
||
acceptanceCriteria: req.acceptanceCriteria, risks: req.risks, dependencies: req.dependencies, missingInfo: req.missingInfo,
|
||
}
|
||
}
|
||
|
||
// 列表按当前门槛重算非终态需求:旧数据存成 discussing、但已可下派的条目也显示为 ready。
|
||
function requirementView(req) {
|
||
const view = structuredClone(req)
|
||
if (!['published', 'cancelled', 'returned'].includes(view.status)) {
|
||
view.status = requirementStatusOf(view)
|
||
view.blockedReason = requirementBlockedReason(view)
|
||
}
|
||
return view
|
||
}
|
||
|
||
// 中书补缺只存在任务上:只认需求里仍为空的字段,用户已确认的内容永远优先。
|
||
function requirementFillOf(task, req) {
|
||
const fill = {}
|
||
for (const field of REQUIREMENT_FILL_FIELDS) {
|
||
const value = cleanText(task?.requirementFill?.[field])
|
||
if (value && !cleanText(req?.[field])) fill[field] = value
|
||
}
|
||
return fill
|
||
}
|
||
|
||
// 批准、派发和六部回报共用这一份有效快照:需求原字段 + 中书补缺。
|
||
function effectiveRequirementSnapshot(task, req) {
|
||
return { ...requirementSnapshot(req), ...requirementFillOf(task, req) }
|
||
}
|
||
|
||
// 作废当前投递:回写只认投递标识与领取者,清掉领取者即可让迟到回写失效。
|
||
function voidDelivery(task) {
|
||
if (!task) return
|
||
task.deliveryState = 'none'
|
||
task.sendingOwner = null
|
||
task.deliveryOwner = null
|
||
}
|
||
|
||
// 阶段切换统一登记一次待发投递,并记下发送成功后要写入的状态(恢复时直接沿用)。
|
||
function queueDelivery(task, status, now = Date.now()) {
|
||
task.deliveryId = randomUUID()
|
||
task.deliveryState = 'pending'
|
||
task.deliveryStatus = status
|
||
task.deliveryOwner = null
|
||
task.sendingOwner = null
|
||
task.deliveryAttemptAt = now
|
||
return task.deliveryId
|
||
}
|
||
|
||
function readyForDepartmentSummary(project, task) {
|
||
if (task.kind !== 'workflow' || task.ownerSeatId !== 'shangshu' || task.stage !== 'department_exec'
|
||
|| task.status !== 'running' || task.deliveryState !== 'none') return false
|
||
const children = project.tasks.filter(child => child.kind === 'execution' && child.parentTaskId === task.id)
|
||
return children.length > 0 && children.every(child => !OPEN_TASK_STATUS.has(child.status))
|
||
}
|
||
|
||
// 首发与重投共用同一份正文:任务说明、需求快照、阶段提示和项目记忆。
|
||
function taskDeliveryText(task, memoryText) {
|
||
const detail = [
|
||
`【任务 ${task.id}】${task.title}`,
|
||
task.goal ? `任务说明:${task.goal}` : '',
|
||
task.requirement ? `用户原话:${task.requirement}` : '',
|
||
task.requirementSnapshot?.scope ? `范围:${task.requirementSnapshot.scope}` : '',
|
||
task.requirementSnapshot?.nonGoals ? `非目标:${task.requirementSnapshot.nonGoals}` : '',
|
||
task.requirementSnapshot?.acceptanceCriteria ? `验收标准:${task.requirementSnapshot.acceptanceCriteria}` : '',
|
||
workflowStageHint(task),
|
||
].filter(Boolean).join('\n')
|
||
return [memoryText, detail].filter(Boolean).join('\n\n')
|
||
}
|
||
|
||
function invalidateRequirementWork(project, requirementId, nextRevision, now) {
|
||
for (const approval of project.approvals ?? []) {
|
||
if (approval.requirementId === requirementId && approval.status === 'approved') {
|
||
approval.status = 'invalidated'
|
||
approval.invalidatedAt = now
|
||
approval.invalidateReason = `需求已更新到 v${nextRevision},旧批准失效`
|
||
}
|
||
}
|
||
for (const task of project.tasks ?? []) {
|
||
if (task.requirementId !== requirementId) continue
|
||
if (task.status === 'done' || task.status === 'cancelled') continue
|
||
if (task.kind === 'workflow') {
|
||
task.status = 'reconfirm'
|
||
task.stage = 'reconfirm'
|
||
task.blockedReason = `需求已更新到 v${nextRevision},旧发布与批准失效;需重新商讨并发布`
|
||
} else if (task.kind === 'execution') {
|
||
task.status = 'returned'
|
||
task.blockedReason = `需求已更新到 v${nextRevision},停止新增工作并报告是否需要重新确认`
|
||
}
|
||
voidDelivery(task)
|
||
task.updatedAt = now
|
||
}
|
||
}
|
||
|
||
function handOffReviewedTask(project, task, requirement, now, approvedBy) {
|
||
project.approvalSeq = (project.approvalSeq ?? 0) + 1
|
||
// 批准范围取任务上的有效快照:中书补缺或退回后的修订都以这一份为准。
|
||
const approvedScope = cleanText(task.requirementSnapshot?.scope) || cleanText(requirement.scope)
|
||
const approval = {
|
||
id: 'AP-' + String(project.approvalSeq).padStart(3, '0'),
|
||
requirementId: requirement.id, requirementRevision: requirement.revision, scope: approvedScope,
|
||
status: 'approved', approvedAt: now, approvedBy,
|
||
}
|
||
project.approvals ??= []
|
||
project.approvals.push(approval)
|
||
task.approvalId = approval.id
|
||
task.approvalScope = approval.scope
|
||
task.stage = 'shangshu_dispatch'
|
||
task.ownerSeatId = 'shangshu'
|
||
task.status = 'draft'
|
||
task.blockedReason = '方案已通过,等待尚书派工'
|
||
requirement.status = 'published'
|
||
requirement.blockedReason = task.blockedReason
|
||
requirement.updatedAt = now
|
||
}
|
||
|
||
function legacyApprovalDecision(now) {
|
||
return {
|
||
id: randomUUID(), kind: 'legacy-approval', status: 'pending', createdAt: now,
|
||
question: '是否按已审核的方案继续执行?',
|
||
options: [{ label: '继续执行', value: 'continue' }, { label: '结束任务', value: 'cancel' }],
|
||
}
|
||
}
|
||
|
||
function taskDecisionBlock(task) {
|
||
if (task.awaitingLeadDecision || task.decisions?.some(item => item.status === 'pending')) {
|
||
throw new ServiceError('sansheng/decision-pending', '任务正在等待会商决定')
|
||
}
|
||
}
|
||
|
||
function projectTask(project, task) {
|
||
if (!task.workflowBlockage) return { ...task }
|
||
const { workflowBlockage, ...rest } = task
|
||
const current = workflowBlockageOf(project, task)
|
||
return current ? { ...rest, workflowBlockage: current } : rest
|
||
}
|
||
|
||
function workflowStageHint(task) {
|
||
const hints = {
|
||
zhongshu_draft: '根据用户原话和已确认内容给出简短拟案;需求缺少范围、非目标或验收标准时,用 sansheng_workflow_submit 的结构化字段补入任务快照后再交门下,退回后可修订自己补的字段。拟案阶段只读。',
|
||
menxia_review: '用 sansheng_workflow_review 提交审核,批准前确认范围与验收标准齐全。通过后系统交尚书,发现实质问题时说明原因退回中书补齐。',
|
||
awaiting_execution_approval: '此方案等待用户在「待你处理」中确认。',
|
||
shangshu_dispatch: '门下已通过方案。请使用 sansheng_workflow_dispatch 向六部分派获批任务;不得超出批准范围。',
|
||
department_exec: task.kind === 'workflow'
|
||
? '六部子任务均已结束。请用 sansheng_task_list 查看本任务的各子任务真实结果和失败原因,再用 sansheng_workflow_summarize 汇总并提交门下验收。'
|
||
: '按获批范围执行。用 sansheng_task_report 提交完成结果或具体失败原因。',
|
||
menxia_acceptance: '请使用 sansheng_workflow_accept 验收;未通过则退回尚书省。',
|
||
lead_delivery: '请向用户交付真实结果;不得代替部门伪造或改写执行结果。',
|
||
reconfirm: '需求已变更,旧授权失效;请与用户重新商讨。',
|
||
}
|
||
const extra = []
|
||
if (hints[task.stage]) extra.push(hints[task.stage])
|
||
if (task.draft && (task.stage === 'menxia_review' || task.stage === 'shangshu_dispatch')) extra.push(`中书拟案:\n${task.draft}`)
|
||
if (task.reviewNote && task.stage === 'zhongshu_draft') extra.push(`门下退回意见:${task.reviewNote}`)
|
||
if (task.summary && (task.stage === 'menxia_acceptance' || task.stage === 'lead_delivery')) extra.push(`尚书汇总:\n${task.summary}`)
|
||
if (task.approvalId) extra.push(`批准编号:${task.approvalId};需求版本:v${task.requirementRevision ?? '?'}`)
|
||
return extra.join('\n')
|
||
}
|
||
|
||
function effortValuesOf(value) {
|
||
if (!value) return []
|
||
if (typeof value === 'string') return value.trim() ? [value] : []
|
||
if (Array.isArray(value)) return value.flatMap(item => {
|
||
if (typeof item === 'string') return item.trim() ? [item] : []
|
||
if (item && typeof item === 'object') {
|
||
const id = item.id ?? item.value ?? item.name
|
||
return typeof id === 'string' && id.trim() ? [id] : []
|
||
}
|
||
return []
|
||
})
|
||
if (typeof value === 'object') {
|
||
if (value.efforts !== undefined) return effortValuesOf(value.efforts)
|
||
if (value.values !== undefined) return effortValuesOf(value.values)
|
||
if (value.options !== undefined) return effortValuesOf(value.options)
|
||
return Object.keys(value).filter(key => key !== 'defaultEffort' && key.trim() !== '' && typeof value[key] !== 'object')
|
||
}
|
||
return []
|
||
}
|
||
|
||
export function normalizeCatalog(catalog) {
|
||
const providers = []
|
||
const entryFor = provider => {
|
||
let entry = providers.find(p => p.provider === provider)
|
||
if (!entry) { entry = { provider, models: [] }; providers.push(entry) }
|
||
return entry
|
||
}
|
||
const groups = catalog?.providers ?? catalog?.groups ?? catalog?.entries ?? []
|
||
if (Array.isArray(groups)) {
|
||
for (const g of groups) {
|
||
const provider = g?.provider ?? g?.id ?? g?.ref ?? g?.name
|
||
const list = g?.models ?? g?.entries ?? []
|
||
for (const m of Array.isArray(list) ? list : []) {
|
||
const modelId = typeof m === 'string' ? m : (m?.model ?? m?.id ?? m?.name)
|
||
if (!provider || !modelId) continue
|
||
const entry = entryFor(provider)
|
||
if (entry.models.some(x => x.model === modelId)) continue
|
||
const effort = typeof m === 'object' ? (m.reasoningEfforts ?? m.reasoningEffort ?? m.reasoning) : undefined
|
||
const effortValues = effortValuesOf(effort)
|
||
entry.models.push(effortValues.length > 0 ? { model: modelId, reasoningEffort: effortValues } : { model: modelId })
|
||
}
|
||
}
|
||
}
|
||
const def = catalog?.default ?? catalog?.deploymentDefault ?? null
|
||
// 部署默认只有在 provider 与 model 都是非空字符串时才完整;半截对象不能当有效路由。
|
||
const defProvider = typeof def?.provider === 'string' && def.provider.trim() !== '' ? def.provider : null
|
||
const defModel = typeof def?.model === 'string' && def.model.trim() !== '' ? def.model : null
|
||
return {
|
||
providers,
|
||
default: defProvider && defModel ? { provider: defProvider, model: defModel } : null,
|
||
defaultError: !def || (!defProvider && !defModel) ? (def ? 'incomplete' : 'missing') : (defProvider && defModel ? null : 'incomplete'),
|
||
failures: catalog?.failures ?? catalog?.isolated ?? [],
|
||
}
|
||
}
|
||
|
||
export class SanshengService {
|
||
constructor({ store, host, provisioner, globalStore = null, modelSync = null, seatActivity = null, approvalCenter = null, leadReporter = null, seatDelivery = null, provinceAgents = null, leadSecretaries = null }) {
|
||
this.store = store
|
||
this.host = host
|
||
this.provisioner = provisioner
|
||
this.globalStore = globalStore
|
||
this.modelSync = modelSync
|
||
this.seatActivity = seatActivity
|
||
this.approvalCenter = approvalCenter
|
||
this.leadReporter = leadReporter
|
||
this.seatDelivery = seatDelivery
|
||
this.provinceAgents = provinceAgents
|
||
this.leadSecretaries = leadSecretaries
|
||
this._seedStatus = { status: 'unknown', candidates: [] }
|
||
// 每个项目一条议政后台队列:发起和发言只落盘并回执,叫下一位在队列里跑,不挡住调用方。
|
||
this._deliberationJobs = new Map()
|
||
}
|
||
|
||
// 把叫席、收束通知排进后台队列。同一个项目的议政动作按顺序执行,避免两次点击交错。
|
||
_scheduleDeliberation(projectId, label, run) {
|
||
const previous = this._deliberationJobs.get(projectId) ?? Promise.resolve()
|
||
const next = previous
|
||
.then(() => run())
|
||
.catch(error => {
|
||
console.warn('[sansheng] 议政后台任务失败(' + label + '):', error?.message ?? error)
|
||
})
|
||
this._deliberationJobs.set(projectId, next)
|
||
void next.finally(() => {
|
||
if (this._deliberationJobs.get(projectId) === next) this._deliberationJobs.delete(projectId)
|
||
})
|
||
return next
|
||
}
|
||
|
||
// 测试与停止操作用:等这个项目已排队的议政后台动作全部跑完。
|
||
async waitForDeliberation(projectId) {
|
||
while (this._deliberationJobs.has(projectId)) {
|
||
await this._deliberationJobs.get(projectId)
|
||
}
|
||
}
|
||
|
||
// 组合每席的配置来源、实际会话模型、同步状态与运行状态。
|
||
_seatExtras(projectId, statusMap = {}) {
|
||
const project = this.store.get(projectId)
|
||
const out = {}
|
||
for (const seatId of SEAT_IDS) {
|
||
const seat = project?.seats?.[seatId]
|
||
const sync = statusMap?.[seatId] ?? null
|
||
let configuredModel = null
|
||
let modelSource = 'none'
|
||
if (seat?.model) { configuredModel = seat.model; modelSource = 'project' }
|
||
else if (this.globalStore?.getSeat?.(seatId)) { configuredModel = this.globalStore.getSeat(seatId); modelSource = 'global' }
|
||
else if (sync?.targetModel) { configuredModel = sync.targetModel; modelSource = sync.targetSource ?? 'none' }
|
||
out[seatId] = {
|
||
configuredModel,
|
||
modelSource,
|
||
sessionModel: sync?.currentModel ?? null,
|
||
modelSync: sync ? {
|
||
status: sync.status, error: sync.error ?? null, updatedAt: sync.updatedAt ?? null,
|
||
targetModel: sync.targetModel ?? null, targetSource: sync.targetSource ?? null,
|
||
} : null,
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
|
||
async memory(projectId) {
|
||
await this.store.ensureLoaded()
|
||
const project = this.store.get(projectId)
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
return { memory: normalizeProjectMemory(project.memory, projectId) }
|
||
}
|
||
|
||
async memoryUpdate(projectId, patch = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
return this.store.mutate(s => {
|
||
const project = s.projects[projectId]
|
||
const current = normalizeProjectMemory(project.memory, projectId)
|
||
const expected = patch?.expectedRevision
|
||
if (expected !== undefined && expected !== null && expected !== current.revision) {
|
||
throw new ServiceError('sansheng/memory-conflict', `项目共识已更新(当前 v${current.revision},提交基于 v${String(expected)}),请重新读取后再改`)
|
||
}
|
||
const next = mergeProjectMemory(current, patch, { makeId: () => randomUUID() })
|
||
next.contentHash = createHash('sha256').update(JSON.stringify(next)).digest('hex')
|
||
project.memory = next
|
||
project.updatedAt = Date.now()
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return { memory: next }
|
||
})
|
||
}
|
||
|
||
async list() {
|
||
await this.store.ensureLoaded()
|
||
return {
|
||
projects: [...this.store.list()]
|
||
.sort((a, b) => String(a.name).localeCompare(String(b.name), 'zh-Hans-CN'))
|
||
.map(p => ({ id: p.id, name: p.name, status: p.status, revision: p.revision ?? 0 })),
|
||
}
|
||
}
|
||
|
||
async open({ workspaceId, name, path } = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (!workspaceId && !path) throw new ServiceError('sansheng/invalid', '需要 workspaceId 或 path')
|
||
const registry = this.host.workspaceRegistry
|
||
let ws
|
||
if (workspaceId) {
|
||
ws = registry.get(workspaceId)
|
||
if (!ws) throw new ServiceError('sansheng/not-found', `未找到工作区 ${workspaceId}`)
|
||
} else {
|
||
ws = await registry.resolveByPath(path)
|
||
if (!ws) ws = await registry.create(path, name)
|
||
}
|
||
const id = ws.id ?? ws.workspaceId
|
||
await this.store.mutate(() => {
|
||
this.store.ensureProjectRecord({
|
||
id,
|
||
name: name ?? ws.title ?? ws.name ?? id,
|
||
workspaceId: id,
|
||
path: ws.path ?? path ?? null,
|
||
})
|
||
})
|
||
await this.provisioner.ensureTitles(id)
|
||
return projectView(this.store.get(id))
|
||
}
|
||
|
||
async project(projectId) {
|
||
await this.store.ensureLoaded()
|
||
const p = this.store.get(projectId)
|
||
if (!p) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
if (this.modelSync?.syncProject) {
|
||
try { await this.modelSync.syncProject(projectId) } catch (error) {
|
||
console.warn('[sansheng] 模型同步失败:', error?.message ?? error)
|
||
}
|
||
}
|
||
await this.provisioner.ensureTitles(projectId)
|
||
const statusMap = this.modelSync?.statusOf?.(projectId) ?? {}
|
||
const extras = this._seatExtras(projectId, statusMap)
|
||
if (this.seatActivity?.reconcileProject) {
|
||
try {
|
||
const activity = await this.seatActivity.reconcileProject(projectId)
|
||
for (const seatId of SEAT_IDS) if (activity?.[seatId]) extras[seatId].runtimeState = activity[seatId]
|
||
} catch { /* 运行状态读取失败不阻断项目视图 */ }
|
||
}
|
||
return projectView(this.store.get(projectId), extras)
|
||
}
|
||
|
||
async enable(projectId) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
await this.provisioner.enable(projectId)
|
||
return this.project(projectId)
|
||
}
|
||
|
||
async enableSeat(projectId, seatId) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', `未知席 ${String(seatId)}`)
|
||
await this.provisioner.enableSeat(projectId, seatId)
|
||
return this.project(projectId)
|
||
}
|
||
|
||
async openSeat(projectId, seatId) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', `未知席 ${String(seatId)}`)
|
||
const result = await this.provisioner.openSeat(projectId, seatId)
|
||
return { ...this.project(projectId), sessionId: result.sessionId, seatId: result.seatId }
|
||
}
|
||
|
||
async rebuildSeat(projectId, seatId, { expectedSessionId } = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', `未知席 ${String(seatId)}`)
|
||
const result = await this.provisioner.rebuildSeat(projectId, seatId, { expectedSessionId })
|
||
return {
|
||
...this.project(projectId),
|
||
sessionId: result.sessionId,
|
||
seatId: result.seatId,
|
||
previousSessionId: result.previousSessionId ?? null,
|
||
}
|
||
}
|
||
|
||
async configure(projectId, seatId, { model, instructions } = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', `未知席 ${seatId}`)
|
||
const project = this.store.get(projectId)
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
|
||
let normalized
|
||
if (model !== undefined) {
|
||
normalized = normalizeSelection(model) // null=清除项目覆盖;非法抛 sansheng/model-invalid
|
||
// 非空选择必须在写状态前验证路由;清除覆盖不需要。
|
||
if (normalized !== null) await this.host.llm.resolveCallConfig(normalized)
|
||
}
|
||
if (instructions !== undefined && typeof instructions !== 'string') {
|
||
throw new ServiceError('sansheng/invalid', 'instructions 必须是字符串')
|
||
}
|
||
// 兼容无 modelSync 的旧调用路径:仍在写状态前把选择应用到已绑定会话。
|
||
let applied = null
|
||
if (model !== undefined && normalized && !this.modelSync?.syncSeat && project.seats[seatId].sessionId) {
|
||
applied = await applyModel(this.host, project.seats[seatId].sessionId, normalized)
|
||
}
|
||
|
||
await this.store.mutate(s => {
|
||
const target = s.projects[projectId].seats[seatId]
|
||
if (model !== undefined) target.model = normalized
|
||
if (instructions !== undefined) target.instructions = instructions
|
||
target.updatedAt = Date.now()
|
||
s.projects[projectId].updatedAt = Date.now()
|
||
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||
})
|
||
let sync = null
|
||
if (model !== undefined && this.modelSync?.syncSeat) {
|
||
try { sync = await this.modelSync.syncSeat(projectId, seatId, 'configure') } catch (error) {
|
||
sync = { status: 'failed', error: error?.message ?? String(error) }
|
||
}
|
||
}
|
||
const extras = this._seatExtras(projectId, sync ? { [seatId]: sync } : {})
|
||
return { seat: seatView(seatId, this.store.get(projectId).seats[seatId], extras[seatId] ?? {}), sync, applied }
|
||
}
|
||
|
||
async models() {
|
||
await this.store.ensureLoaded()
|
||
const catalog = await this.host.sessionController.modelCatalog()
|
||
return normalizeCatalog(catalog)
|
||
}
|
||
|
||
async tasks(projectId) {
|
||
await this.store.ensureLoaded()
|
||
const project = this.store.get(projectId)
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
return { tasks: (project.tasks ?? []).map(task => projectTask(project, task)) }
|
||
}
|
||
|
||
// 只读任务汇总:按状态/主责席位统计,并返回可追溯的任务明细。
|
||
async taskSummary(projectId) {
|
||
await this.store.ensureLoaded()
|
||
const project = this.store.get(projectId)
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
const tasks = Array.isArray(project.tasks) ? project.tasks : []
|
||
const statusCounts = {}
|
||
const seatCounts = {}
|
||
for (const task of tasks) {
|
||
const status = typeof task.status === 'string' ? task.status : 'unknown'
|
||
statusCounts[status] = (statusCounts[status] ?? 0) + 1
|
||
const seatId = task.ownerSeatId
|
||
if (!seatCounts[seatId]) seatCounts[seatId] = { total: 0, done: 0, running: 0, open: 0 }
|
||
const row = seatCounts[seatId]
|
||
row.total += 1
|
||
if (status === 'done') row.done += 1
|
||
else if (status === 'running') row.running += 1
|
||
else if (status !== 'cancelled') row.open += 1
|
||
}
|
||
return {
|
||
projectId,
|
||
projectName: project.name,
|
||
revision: project.revision ?? 0,
|
||
total: tasks.length,
|
||
statusCounts,
|
||
seatCounts,
|
||
openTasks: tasks
|
||
.filter(task => task.status !== 'done' && task.status !== 'cancelled')
|
||
.map(task => task.id),
|
||
tasks: tasks.map(task => ({
|
||
id: task.id,
|
||
title: task.title,
|
||
status: task.status,
|
||
ownerSeatId: task.ownerSeatId,
|
||
ownerLabel: SEATS[task.ownerSeatId]?.label ?? task.ownerSeatId,
|
||
goal: task.goal ?? '',
|
||
requirement: task.requirement ?? '',
|
||
result: task.result ?? '',
|
||
note: task.note ?? '',
|
||
resultSessionId: task.resultSessionId ?? null,
|
||
deliveryState: task.deliveryState ?? 'none',
|
||
workflowBlockage: workflowBlockageOf(project, task),
|
||
})),
|
||
}
|
||
}
|
||
|
||
// 内部投递统一入口:先 resolveAgent,再以 source 标记为非用户消息;优先 followup。
|
||
async _deliverInternal(sessionId, text, source) {
|
||
const controller = this.host.sessionController
|
||
let resolved = null
|
||
try { resolved = await controller.resolveAgent(sessionId) } catch (error) {
|
||
throw new ServiceError('sansheng/delivery-failed', '会话不可用:' + (error?.message ?? error))
|
||
}
|
||
if (!resolved || ('error' in resolved && resolved.error)) {
|
||
throw new ServiceError('sansheng/seat-unbound', '会话不可用:' + (resolved?.error?.message ?? resolved?.error?.code ?? 'resolve failed'))
|
||
}
|
||
const agent = resolved.agent
|
||
if (this.host.agents?.get?.(sessionId) !== agent) throw new ServiceError('sansheng/conflict', '投递期间 Agent 已变化')
|
||
const content = [{ type: 'text', text }]
|
||
const factory = typeof this.host.createUserMessage === 'function' ? this.host.createUserMessage : null
|
||
const message = factory ? await Promise.resolve(factory({ content, source })) : { role: 'user', content, source }
|
||
if (typeof agent?.followup === 'function') {
|
||
await agent.followup(message)
|
||
return
|
||
}
|
||
if (typeof controller.prompt === 'function') {
|
||
await controller.prompt({ requestId: randomUUID(), sessionId, mode: 'queue', content, source }, new AbortController().signal)
|
||
return
|
||
}
|
||
throw new ServiceError('sansheng/delivery-failed', '宿主未提供 followup/prompt 接口')
|
||
}
|
||
|
||
// 轻量版尚书汇总:只把当前真实任务快照发给尚书汇总,不改变丞相直派流程,不创建新任务。
|
||
async shangshuSummary(projectId) {
|
||
const summary = await this.taskSummary(projectId)
|
||
let project = this.store.get(projectId)
|
||
let seat = project?.seats?.shangshu
|
||
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||
await this.provisioner.enableSeat(projectId, 'shangshu')
|
||
project = this.store.get(projectId)
|
||
seat = project?.seats?.shangshu
|
||
}
|
||
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||
throw new ServiceError('sansheng/seat-unbound', '「尚书」的会话还没开启成功,请稍后重试')
|
||
}
|
||
const controller = this.host.sessionController
|
||
if (typeof controller?.resolveAgent !== 'function' && typeof controller?.prompt !== 'function') {
|
||
throw new ServiceError('sansheng/delivery-failed', '宿主未提供会话投递接口,无法发送尚书汇总请求')
|
||
}
|
||
const clip = (value, max = 800) => {
|
||
const raw = typeof value === 'string' ? value.trim() : ''
|
||
return raw.length > max ? `${raw.slice(0, max)}…` : raw
|
||
}
|
||
const detail = summary.tasks.length === 0
|
||
? '当前项目还没有任务记录。'
|
||
: summary.tasks.map(task => {
|
||
const parts = [`${task.id} [${task.status}] ${task.ownerLabel}:${task.title}`]
|
||
if (task.goal) parts.push(`目标:${clip(task.goal)}`)
|
||
if (task.requirement) parts.push(`用户原话:${clip(task.requirement)}`)
|
||
if (task.result) parts.push(`结果:${clip(task.result)}`)
|
||
if (task.note) parts.push(`备注:${clip(task.note)}`)
|
||
return `- ${parts.join(';')}`
|
||
}).join('\n')
|
||
const statusText = Object.entries(summary.statusCounts).map(([status, count]) => `${status} ${count}`).join(',') || '无'
|
||
const text = [
|
||
`【尚书汇总】请汇总项目「${summary.projectName ?? projectId}」的真实任务进度。`,
|
||
`任务总数:${summary.total};状态统计:${statusText}。`,
|
||
'任务明细:',
|
||
detail,
|
||
'',
|
||
'汇总要求:',
|
||
'1. 按已完成 / 执行中 / 已派工 / 待执行 / 失败或取消分组汇总,列出任务 ID、主责部门、当前状态和关键结果。',
|
||
'2. 明确区分「已派工/已收到」和「已完成」,不要把已派工当成完成。',
|
||
'3. 只做汇总,不重派任务;按需求门控流程报告真实阻塞、完成与待复核事项。',
|
||
].join('\n')
|
||
try {
|
||
await this._deliverInternal(seat.sessionId, text, internalSource('sansheng-report', { seatId: 'shangshu' }))
|
||
} catch (error) {
|
||
throw new ServiceError('sansheng/delivery-failed', `尚书汇总请求发送失败:${error?.message ?? error}`)
|
||
}
|
||
return { ok: true, sessionId: seat.sessionId, summary }
|
||
}
|
||
|
||
async requirements(projectId) {
|
||
await this.store.ensureLoaded()
|
||
const project = this.store.get(projectId)
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
return {
|
||
requirements: (project.requirements ?? []).map(requirementView),
|
||
approvals: structuredClone(project.approvals ?? []),
|
||
}
|
||
}
|
||
|
||
async requirementUpsert(projectId, input = {}, actor = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
if (actor.seatId && actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以整理需求清单')
|
||
const id = cleanText(input.id)
|
||
const expectedRevision = input.expectedRevision === undefined || input.expectedRevision === null ? null : Number(input.expectedRevision)
|
||
return this.store.mutate(s => {
|
||
const project = s.projects[projectId]
|
||
let req
|
||
let created = false
|
||
if (id) {
|
||
req = (project.requirements ?? []).find(item => item.id === id)
|
||
if (!req) throw new ServiceError('sansheng/not-found', `需求 ${id} 不存在`)
|
||
if (expectedRevision !== null && req.revision !== expectedRevision) {
|
||
throw new ServiceError('sansheng/requirement-conflict', `需求已更新(当前 v${req.revision},提交基于 v${expectedRevision}),请重新读取后再改`)
|
||
}
|
||
} else {
|
||
const title = cleanText(input.title)
|
||
if (!title) throw new ServiceError('sansheng/invalid', '需求标题不能为空')
|
||
project.requirementSeq = (project.requirementSeq ?? 0) + 1
|
||
req = emptyRequirement({
|
||
id: `R-${String(project.requirementSeq).padStart(3, '0')}`,
|
||
title,
|
||
summary: cleanText(input.summary),
|
||
originalText: cleanText(input.originalText) || title,
|
||
})
|
||
if (!Array.isArray(project.requirements)) project.requirements = []
|
||
project.requirements.push(req)
|
||
created = true
|
||
}
|
||
const originalText = req.originalText
|
||
const before = JSON.stringify(REQUIREMENT_TEXT_FIELDS.map(field => req[field] ?? ''))
|
||
for (const field of REQUIREMENT_TEXT_FIELDS) {
|
||
if (input[field] !== undefined) req[field] = cleanText(input[field])
|
||
}
|
||
if (!req.originalText) req.originalText = req.title
|
||
const after = JSON.stringify(REQUIREMENT_TEXT_FIELDS.map(field => req[field] ?? ''))
|
||
const previousAuthorization = req.dispatchAuthorization
|
||
if (input.dispatchAfterClarification === true && actor.command?.seq != null && actor.sessionId && !previousAuthorization) {
|
||
req.dispatchAuthorization = { sessionId: actor.sessionId, seq: actor.command.seq }
|
||
} else if (input.dispatchAfterClarification === false || req.originalText !== originalText || req.status === 'published' || req.status === 'cancelled') {
|
||
delete req.dispatchAuthorization
|
||
}
|
||
if (!created && before === after && previousAuthorization === req.dispatchAuthorization) {
|
||
return { requirement: { ...req }, created: false, changed: false }
|
||
}
|
||
const now = Date.now()
|
||
if (!created && (req.status === 'published' || (project.tasks ?? []).some(task => task.requirementId === req.id && OPEN_TASK_STATUS.has(task.status)))) {
|
||
invalidateRequirementWork(project, req.id, req.revision + 1, now)
|
||
}
|
||
if (!created && (req.status === 'published' || req.status === 'returned')) req.status = 'discussing'
|
||
if (created) req.revision = 1
|
||
else req.revision = (req.revision ?? 1) + 1
|
||
req.status = requirementStatusOf(req)
|
||
req.blockedReason = requirementBlockedReason(req)
|
||
req.updatedAt = now
|
||
project.updatedAt = now
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return { requirement: { ...req }, created, changed: true }
|
||
})
|
||
}
|
||
|
||
async requirementCancel(projectId, requirementId, actor = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
if (actor.seatId && actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以取消需求')
|
||
return this.store.mutate(s => {
|
||
const project = s.projects[projectId]
|
||
const req = (project.requirements ?? []).find(item => item.id === requirementId)
|
||
if (!req) throw new ServiceError('sansheng/not-found', `需求 ${requirementId} 不存在`)
|
||
const now = Date.now()
|
||
req.status = 'cancelled'
|
||
delete req.dispatchAuthorization
|
||
req.cancelledAt = now
|
||
req.blockedReason = '已取消'
|
||
req.updatedAt = now
|
||
invalidateRequirementWork(project, req.id, req.revision, now)
|
||
project.updatedAt = now
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return { requirement: { ...req } }
|
||
})
|
||
}
|
||
|
||
async requirementPublish(projectId, requirementId, input = {}, actor = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
if (actor.seatId && actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以发布需求给中书省')
|
||
const command = cleanText(input.command)
|
||
const commandRef = input.commandRef && typeof input.commandRef === 'object' ? input.commandRef : null
|
||
const commandSeq = commandRef?.seq ?? null
|
||
const sessionId = actor.sessionId ?? null
|
||
const existing = getCommand(this.store.get(projectId), sessionId, commandSeq)
|
||
if (existing) {
|
||
if (existing.outcome === 'published') {
|
||
return { ok: true, duplicate: true, taskId: existing.taskId, deliveryId: existing.deliveryId, requirementId: existing.requirementId }
|
||
}
|
||
throw new ServiceError('sansheng/command-used', `该发布命令已处理(${existing.outcome})${existing.error ? ':' + existing.error : ''}`)
|
||
}
|
||
// 丞相根据当前对话选定需求,只有存在唯一候选时才允许省略编号。
|
||
let effectiveId = cleanText(requirementId).toUpperCase()
|
||
if (/^\d{3,}$/.test(effectiveId)) effectiveId = 'R-' + effectiveId
|
||
const fullIds = Array.from(command.matchAll(/\bR-(\d{3,})\b/gi), match => 'R-' + match[1])
|
||
const shortIds = Array.from(command.matchAll(/(?:发布|下派)\s*(\d{3,})\b/g), match => 'R-' + match[1])
|
||
const mentioned = [...new Set([...fullIds, ...shortIds])]
|
||
if (mentioned.length === 1) {
|
||
if (effectiveId && mentioned[0] !== effectiveId) throw new ServiceError('sansheng/requirement-conflict', '消息中的需求编号与待下派需求不一致')
|
||
effectiveId = mentioned[0]
|
||
}
|
||
const projectBefore = this.store.get(projectId)
|
||
if (!effectiveId && command) {
|
||
const ready = (projectBefore.requirements ?? []).filter(item => requirementStatusOf(item) === 'ready')
|
||
if (ready.length === 1) effectiveId = ready[0].id
|
||
else if (ready.length > 1) {
|
||
await this._recordRejectedCommand(projectId, sessionId, commandSeq, commandRef, 'rejected-ambiguous', { candidates: ready.map(item => item.id), error: '多个待发布需求' })
|
||
throw new ServiceError('sansheng/requirement-ambiguous', `当前有多个待发布需求:${ready.map(item => item.id).join('、')};请确认要下派哪一项`)
|
||
} else {
|
||
await this._recordRejectedCommand(projectId, sessionId, commandSeq, commandRef, 'rejected-not-ready', { error: '没有待发布需求' })
|
||
throw new ServiceError('sansheng/requirement-not-ready', '当前没有待发布的需求')
|
||
}
|
||
}
|
||
if (!effectiveId) {
|
||
await this._recordRejectedCommand(projectId, sessionId, commandSeq, commandRef, 'rejected-invalid', { error: '未识别需求编号' })
|
||
throw new ServiceError('sansheng/publish-not-explicit', '请先确认要下派哪一项')
|
||
}
|
||
if (!command || !sessionId || !Number.isSafeInteger(commandSeq) || !commandRef?.messageId) {
|
||
await this._recordRejectedCommand(projectId, sessionId, commandSeq, commandRef, 'rejected-invalid', { error: '未检测到明确发布命令' })
|
||
throw new ServiceError('sansheng/current-user-message-unavailable', '宿主未能验证本轮用户消息,本次下派没有执行')
|
||
}
|
||
const expectedRevision = Number(input.expectedRevision)
|
||
let published
|
||
try {
|
||
published = await this.store.mutate(s => {
|
||
const project = s.projects[projectId]
|
||
const used = getCommand(project, sessionId, commandSeq)
|
||
if (used) throw new ServiceError('sansheng/command-used', '该用户消息已处理')
|
||
const req = (project.requirements ?? []).find(item => item.id === effectiveId)
|
||
if (!req) throw new ServiceError('sansheng/not-found', `需求 ${effectiveId} 不存在`)
|
||
if (Number.isFinite(expectedRevision) && req.revision !== expectedRevision) throw new ServiceError('sansheng/requirement-conflict', `需求已更新到 v${req.revision},发布命令基于 v${expectedRevision},已失效`)
|
||
const currentStatus = requirementStatusOf(req)
|
||
if (currentStatus !== 'ready') throw new ServiceError('sansheng/requirement-not-ready', `需求 ${req.id} 当前状态为 ${currentStatus},只有「待发布」的需求可以发布`)
|
||
if (input.authorization === 'clarified' && (req.dispatchAuthorization?.sessionId !== sessionId || req.dispatchAuthorization.seq >= commandSeq)) {
|
||
throw new ServiceError('sansheng/publish-not-explicit', '这项需求缺少同一会话中有效的澄清后下派授权')
|
||
}
|
||
const problem = requirementReadyProblem(req)
|
||
if (problem) throw new ServiceError('sansheng/requirement-incomplete', `需求不可发布:${problem}`)
|
||
const duplicate = (project.tasks ?? []).find(task => task.requirementId === req.id && task.requirementRevision === req.revision && task.kind === 'workflow' && OPEN_TASK_STATUS.has(task.status))
|
||
if (duplicate) throw new ServiceError('sansheng/requirement-duplicate', `需求 ${req.id} v${req.revision} 已发布,不能重复发布`)
|
||
const now = Date.now()
|
||
project.taskSeq = (project.taskSeq ?? 0) + 1
|
||
const task = emptyTask({
|
||
id: `task-${project.taskSeq}`,
|
||
title: `${req.id} · ${req.title}`,
|
||
goal: req.summary || req.scope || req.title,
|
||
requirement: req.originalText,
|
||
ownerSeatId: 'zhongshu',
|
||
kind: 'workflow',
|
||
requirementId: req.id,
|
||
requirementRevision: req.revision,
|
||
stage: 'zhongshu_draft',
|
||
now,
|
||
})
|
||
task.requirementSnapshot = requirementSnapshot(req)
|
||
task.blockedReason = '中书省拟案中'
|
||
task.executionAuthorizedAtDispatch = true
|
||
task.publishCommandRef = commandRef.messageId
|
||
const deliveryId = queueDelivery(task, 'dispatched', now)
|
||
if (this.secretaryRouting) task.secretaryPublishDeliveryId = deliveryId
|
||
if (!Array.isArray(project.tasks)) project.tasks = []
|
||
project.tasks.push(task)
|
||
delete req.dispatchAuthorization
|
||
req.status = 'published'
|
||
req.publishedRevision = req.revision
|
||
req.publishedAt = now
|
||
req.blockedReason = '已发布,等待中书省拟案'
|
||
req.updatedAt = now
|
||
project.updatedAt = now
|
||
project.revision = (project.revision ?? 0) + 1
|
||
putCommand(project, {
|
||
sessionId, seq: commandSeq, messageId: commandRef?.messageId ?? null,
|
||
outcome: 'published', requirementId: req.id, requirementRevision: req.revision,
|
||
taskId: task.id, deliveryId, at: now,
|
||
})
|
||
return { task: { ...task }, requirement: { ...req }, deliveryId }
|
||
})
|
||
} catch (error) {
|
||
await this._recordRejectedCommand(projectId, sessionId, commandSeq, commandRef, error?.code === 'sansheng/requirement-duplicate' ? 'rejected-duplicate' : 'rejected-invalid', { error: error?.message ?? String(error) })
|
||
throw error
|
||
}
|
||
void this.taskDispatch(projectId, published.task.id, { deliveryId: published.deliveryId }).catch(async error => {
|
||
await this.store.mutate(state => {
|
||
const task = state.projects[projectId]?.tasks?.find(item => item.id === published.task.id)
|
||
if (task?.deliveryId !== published.deliveryId || task.deliveryState !== 'pending') return
|
||
task.note = error?.message ?? String(error)
|
||
task.blockedReason = task.note
|
||
task.updatedAt = Date.now()
|
||
})
|
||
}).catch(error => console.warn('[sansheng] 后台投递状态保存失败:', error))
|
||
return { ok: true, queued: true, taskId: published.task.id, deliveryId: published.deliveryId, requirement: published.requirement }
|
||
}
|
||
|
||
async _recordRejectedCommand(projectId, sessionId, seq, commandRef, outcome, extra = {}) {
|
||
if (!sessionId || seq === null || seq === undefined) return
|
||
try {
|
||
await this.store.mutate(s => {
|
||
const project = s.projects[projectId]
|
||
if (!project || getCommand(project, sessionId, seq)) return
|
||
putCommand(project, {
|
||
sessionId, seq, messageId: commandRef?.messageId ?? null, outcome,
|
||
requirementId: extra.requirementId ?? null, requirementRevision: extra.requirementRevision ?? null,
|
||
error: extra.error ?? null, at: Date.now(),
|
||
})
|
||
})
|
||
} catch { /* 拒绝记录失败不能掩盖原始业务错误 */ }
|
||
}
|
||
|
||
|
||
async workflowSubmitDraft(projectId, taskId, input = {}, actor = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (actor.seatId !== 'zhongshu') throw new ServiceError('sansheng/forbidden', '只有中书省可以提交拟案')
|
||
const draft = cleanText(input.draft)
|
||
if (!draft) throw new ServiceError('sansheng/invalid', '拟案内容不能为空')
|
||
const fill = {}
|
||
for (const field of REQUIREMENT_FILL_FIELDS) fill[field] = cleanText(input[field])
|
||
const next = await this.store.mutate(s => {
|
||
const project = s.projects[projectId]
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||
if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`)
|
||
if (task.ownerSeatId !== 'zhongshu' || task.stage !== 'zhongshu_draft' || task.status === 'done' || task.status === 'cancelled') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在中书拟案阶段,不能提交拟案')
|
||
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||
if (!req || req.revision !== task.requirementRevision) throw new ServiceError('sansheng/requirement-changed', '需求版本已变化,旧任务不能再推进')
|
||
const now = Date.now()
|
||
// 中书补缺只写任务快照:需求正文、标题、原话和版本都不动;退回重提时可改自己补的字段。
|
||
const filledFields = []
|
||
const keptFields = []
|
||
const nextFill = { ...(task.requirementFill ?? {}) }
|
||
for (const field of REQUIREMENT_FILL_FIELDS) {
|
||
if (!fill[field]) continue
|
||
if (cleanText(req[field])) { keptFields.push(field); continue }
|
||
nextFill[field] = fill[field]
|
||
filledFields.push(field)
|
||
}
|
||
task.requirementFill = nextFill
|
||
task.draft = draft
|
||
task.stage = 'menxia_review'
|
||
task.ownerSeatId = 'menxia'
|
||
task.status = 'draft'
|
||
task.blockedReason = '待门下省审核'
|
||
task.lastTransitionId = randomUUID()
|
||
appendLeadReport(s, projectId, task, 'zhongshu_submit', draft)
|
||
queueDelivery(task, 'dispatched', now)
|
||
task.result = null
|
||
task.resultAt = null
|
||
task.updatedAt = now
|
||
// 有效快照 = 同版本需求字段 + 中书补缺;门下、会商、批准和派发都读这一份。
|
||
task.requirementSnapshot = effectiveRequirementSnapshot(task, req)
|
||
req.status = 'published'
|
||
req.blockedReason = '门下省审核中'
|
||
req.updatedAt = now
|
||
project.updatedAt = now
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return { task: { ...task }, filledFields, keptFields }
|
||
})
|
||
const dispatched = await this.taskDispatch(projectId, taskId, { deliveryId: next.task.deliveryId })
|
||
return { ok: dispatched.delivered, delivered: dispatched.delivered, task: dispatched.task, filledFields: next.filledFields, keptFields: next.keptFields }
|
||
}
|
||
|
||
async workflowReview(projectId, taskId, input = {}, actor = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (actor.seatId !== 'menxia') throw new ServiceError('sansheng/forbidden', '只有门下省可以审核拟案')
|
||
const action = cleanText(input.action)
|
||
if (!['approve', 'return'].includes(action)) throw new ServiceError('sansheng/invalid', '审核动作必须是 approve 或 return')
|
||
const note = cleanText(input.note)
|
||
if (action === 'return' && !note) throw new ServiceError('sansheng/invalid', '退回应写明原因')
|
||
const next = await this.store.mutate(s => {
|
||
const project = s.projects[projectId]
|
||
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||
if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`)
|
||
if (task.ownerSeatId !== 'menxia' || task.stage !== 'menxia_review') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在门下审核阶段')
|
||
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||
if (!req || req.revision !== task.requirementRevision) throw new ServiceError('sansheng/requirement-changed', '需求版本已变化,旧任务不能继续审核')
|
||
const now = Date.now()
|
||
taskDecisionBlock(task)
|
||
if (action === 'return' && task.reviewReturns) throw new ServiceError('sansheng/consultation-required', '已有一次退回,请先三省会商,有分歧交丞相')
|
||
if (action === 'return') {
|
||
task.reviewReturns = 1
|
||
task.stage = 'zhongshu_draft'
|
||
task.ownerSeatId = 'zhongshu'
|
||
task.status = 'returned'
|
||
task.reviewNote = note
|
||
task.blockedReason = '门下退回中书省修订'
|
||
req.status = 'returned'
|
||
req.blockedReason = `门下退回:${note}`
|
||
} else {
|
||
if (!cleanText(task.draft)) throw new ServiceError('sansheng/invalid', '中书尚未提交拟案,不能审核通过')
|
||
// 执行批准使用任务上的有效快照:需求字段优先,中书补缺或退回后的修订随任务走。
|
||
const effective = effectiveRequirementSnapshot(task, req)
|
||
if (!cleanText(effective.scope) || !cleanText(effective.acceptanceCriteria)) {
|
||
throw new ServiceError('sansheng/requirement-incomplete', '需求缺少范围或验收标准,请退回中书省在拟案中补齐后再批准')
|
||
}
|
||
task.requirementSnapshot = effective
|
||
if (task.executionAuthorizedAtDispatch) {
|
||
handOffReviewedTask(project, task, req, now, 'menxia')
|
||
} else {
|
||
task.stage = 'awaiting_execution_approval'
|
||
task.ownerSeatId = 'lead'
|
||
task.status = 'waiting_user'
|
||
task.blockedReason = '待你处理:确认旧方案是否执行'
|
||
req.status = 'published'
|
||
req.blockedReason = task.blockedReason
|
||
task.decisions ??= []
|
||
task.decisions.push(legacyApprovalDecision(now))
|
||
}
|
||
task.reviewNote = note
|
||
}
|
||
task.lastTransitionId = randomUUID()
|
||
appendLeadReport(s, projectId, task, action === 'return' ? 'menxia_return' : 'menxia_approve', note || '审核通过')
|
||
queueDelivery(task, task.status, now)
|
||
task.updatedAt = now
|
||
req.updatedAt = now
|
||
project.updatedAt = now
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return { task: { ...task } }
|
||
})
|
||
const dispatched = await this.taskDispatch(projectId, taskId, { deliveryId: next.task.deliveryId })
|
||
return { ok: dispatched.delivered, delivered: dispatched.delivered, task: dispatched.task }
|
||
}
|
||
|
||
async consultTask(projectId, taskId, input, actor) {
|
||
const text = cleanText(input.text)
|
||
const toSeatIds = [...new Set(input.toSeatIds ?? [])]
|
||
if (!text || !toSeatIds.length || toSeatIds.includes(actor.seatId)) {
|
||
throw new ServiceError('sansheng/invalid', '请指定商议对象及问题或结论')
|
||
}
|
||
const router = this.secretaryRouting
|
||
const canRoute = seatId => typeof router?.consult === 'function' && (
|
||
(seatId === 'lead' && SEAT_GROUPS.sansheng.includes(actor.seatId))
|
||
|| (actor.seatId === 'lead' && SEAT_GROUPS.sansheng.includes(seatId))
|
||
)
|
||
const requiresDecision = toSeatIds.includes('lead') && (
|
||
input.requiresDecision === true || (input.requiresDecision === undefined && !canRoute('lead'))
|
||
)
|
||
const { task, entry } = await this.store.mutate(state => {
|
||
const project = state.projects[projectId]
|
||
const task = project?.tasks?.find(item => item.id === taskId && item.kind === 'workflow')
|
||
const requirement = project?.requirements?.find(item => item.id === task?.requirementId)
|
||
if (!task || ['done', 'cancelled', 'reconfirm'].includes(task.status) || requirement?.revision !== task.requirementRevision) {
|
||
throw new ServiceError('sansheng/stage-forbidden', '任务已结束或需求已更新')
|
||
}
|
||
const seats = new Set(['lead', 'zhongshu', 'menxia', 'shangshu'])
|
||
for (const child of project.tasks) if (child.parentTaskId === taskId) seats.add(child.ownerSeatId)
|
||
if (![actor.seatId, ...toSeatIds].every(seat => seats.has(seat))) {
|
||
throw new ServiceError('sansheng/forbidden', '只有本任务相关席位可以会商')
|
||
}
|
||
const entry = { id: randomUUID(), fromSeatId: actor.seatId, toSeatIds, text, requiresDecision, createdAt: Date.now() }
|
||
task.consultations ??= []
|
||
task.consultations.push(entry)
|
||
if (requiresDecision) task.awaitingLeadDecision = true
|
||
if (actor.seatId === 'lead') task.awaitingLeadDecision = false
|
||
task.updatedAt = entry.createdAt
|
||
project.revision += 1
|
||
return structuredClone({ task, entry })
|
||
})
|
||
const snapshot = task.requirementSnapshot ?? {}
|
||
const context = [snapshot.originalText || task.requirement, snapshot.scope, snapshot.acceptanceCriteria].filter(Boolean).join('\n')
|
||
const message = [
|
||
'【任务会商】' + task.id + ' · ' + task.title,
|
||
'用户原话与要求:' + context,
|
||
(SEATS[actor.seatId]?.label ?? actor.seatId) + ':' + text,
|
||
'回复用 sansheng_task_consult,填写同一个 taskId。向丞相请示时说明分歧和可选做法。',
|
||
].join('\n')
|
||
const currentProject = () => {
|
||
const project = this.store.get(projectId)
|
||
const latest = project?.tasks?.find(item => item.id === taskId)
|
||
const requirement = project?.requirements?.find(item => item.id === task.requirementId)
|
||
if (!latest || latest.requirementRevision !== task.requirementRevision || requirement?.revision !== task.requirementRevision
|
||
|| ['done', 'cancelled', 'reconfirm'].includes(latest.status)) {
|
||
throw new ServiceError('sansheng/stage-forbidden', '任务已变化')
|
||
}
|
||
return project
|
||
}
|
||
const delivery = await Promise.allSettled(toSeatIds.map(async seatId => {
|
||
if (canRoute(seatId)) {
|
||
currentProject()
|
||
const handled = await router.consult({
|
||
...structuredClone({ task, entry }), projectId, seatId, message,
|
||
needsUserDecision: seatId === 'lead' && requiresDecision,
|
||
})
|
||
if (handled === true) return
|
||
if (handled !== false) throw new ServiceError('sansheng/delivery-failed', '秘书会商路由必须返回布尔值')
|
||
}
|
||
await this.provisioner.enableSeat(projectId, seatId)
|
||
const project = currentProject()
|
||
return this._deliverInternal(project.seats[seatId].sessionId, message, internalSource('sansheng-task', { seatId, taskId }))
|
||
}))
|
||
return { entry, failedSeatIds: toSeatIds.filter((_id, i) => delivery[i].status === 'rejected') }
|
||
}
|
||
|
||
async deliberations(projectId) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
await this._expireDeliberation(projectId)
|
||
const project = this.store.get(projectId)
|
||
return { deliberations: (project.deliberations ?? []).slice().reverse().map(deliberationSummary) }
|
||
}
|
||
|
||
async deliberation(projectId, deliberationId) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
await this._expireDeliberation(projectId)
|
||
const record = (this.store.get(projectId)?.deliberations ?? []).find(item => item.id === deliberationId)
|
||
if (!record) throw new ServiceError('sansheng/deliberation-not-found', '议政不存在')
|
||
return { deliberation: structuredClone(record) }
|
||
}
|
||
|
||
// 读取时把已超时的当值回合标出来,不自动推进,交给用户重试或带缺失收束。
|
||
async _expireDeliberation(projectId) {
|
||
const project = this.store.get(projectId)
|
||
const running = (project?.deliberations ?? []).find(item => item.status === 'running'
|
||
&& item.turn && ['waiting', 'delivering', 'delivered'].includes(item.turn.status))
|
||
if (!running) return
|
||
const startedAt = Number(running.turn.startedAt ?? 0)
|
||
if (!startedAt || Date.now() - startedAt < DELIBERATION_TIMEOUT_MS) return
|
||
await this.store.mutate(state => {
|
||
const current = state.projects[projectId]
|
||
const record = (current?.deliberations ?? []).find(item => item.id === running.id)
|
||
if (!record || record.status !== 'running' || !record.turn
|
||
|| !['waiting', 'delivering', 'delivered'].includes(record.turn.status)) return
|
||
const now = Date.now()
|
||
if (!Number(record.turn.startedAt) || now - Number(record.turn.startedAt) < DELIBERATION_TIMEOUT_MS) return
|
||
const delivery = (record.deliveries ?? []).find(item => item.id === record.turn.deliveryId)
|
||
const unknown = delivery?.status === 'sending'
|
||
if (unknown) delivery.status = 'unknown'
|
||
record.turn.status = 'timeout'
|
||
record.turn.error = unknown ? '发送结果未知,等待回执超时' : '等待发言超时'
|
||
record.updatedAt = now
|
||
record.missing ??= []
|
||
if (!record.missing.some(item => item.round === record.turn.round && item.seatId === record.turn.seatId)) {
|
||
record.missing.push({
|
||
round: record.turn.round, seatId: record.turn.seatId,
|
||
reason: unknown ? 'unknown' : 'timeout', at: now,
|
||
})
|
||
}
|
||
current.revision = (current.revision ?? 0) + 1
|
||
})
|
||
}
|
||
|
||
async startDeliberation(projectId, input = {}, actor = {}) {
|
||
await this.store.ensureLoaded()
|
||
const topic = cleanText(input.topic).slice(0, 2000)
|
||
if (!topic) throw new ServiceError('sansheng/deliberation-invalid', '请填写议政议题')
|
||
const rawRounds = input.maxRounds === undefined || input.maxRounds === null || input.maxRounds === ''
|
||
? DELIBERATION_DEFAULT_ROUNDS : Number(input.maxRounds)
|
||
if (!Number.isInteger(rawRounds) || rawRounds < 0 || rawRounds > DELIBERATION_MAX_ROUNDS) {
|
||
throw new ServiceError('sansheng/deliberation-invalid', '轮次上限必须是 0 到 ' + DELIBERATION_MAX_ROUNDS + ' 的整数,0 表示不限')
|
||
}
|
||
const taskId = cleanText(input.taskId)
|
||
const requirementId = cleanText(input.requirementId)
|
||
const created = await this.store.mutate(state => {
|
||
const project = state.projects[projectId]
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
if ((project.deliberations ?? []).some(item => item.status === 'running')) {
|
||
throw new ServiceError('sansheng/deliberation-busy', '当前项目已有一场进行中的议政,请先结束或等它收束')
|
||
}
|
||
let task = null
|
||
let requirement = null
|
||
if (taskId) {
|
||
task = (project.tasks ?? []).find(item => item.id === taskId) ?? null
|
||
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||
}
|
||
if (requirementId) {
|
||
requirement = (project.requirements ?? []).find(item => item.id === requirementId) ?? null
|
||
if (!requirement) throw new ServiceError('sansheng/not-found', `需求 ${requirementId} 不存在`)
|
||
} else if (task?.requirementId) {
|
||
requirement = (project.requirements ?? []).find(item => item.id === task.requirementId) ?? null
|
||
}
|
||
const now = Date.now()
|
||
const seq = (project.deliberationSeq ?? 0) + 1
|
||
project.deliberationSeq = seq
|
||
const record = {
|
||
id: 'D-' + String(seq).padStart(3, '0'),
|
||
topic,
|
||
status: 'running',
|
||
maxRounds: rawRounds,
|
||
round: 1,
|
||
currentSeatId: 'zhongshu',
|
||
turn: { round: 1, seatId: 'zhongshu', startedAt: now, attempts: 0, status: 'waiting', error: null },
|
||
speeches: [],
|
||
missing: [],
|
||
taskId: task?.id ?? null,
|
||
requirementId: requirement?.id ?? null,
|
||
requirementRevision: requirement?.revision ?? null,
|
||
originSessionId: cleanText(input.originSessionId) || cleanText(actor.sessionId) || null,
|
||
startedBy: cleanText(actor.seatId) || 'user',
|
||
deliveries: [],
|
||
conclusion: null,
|
||
createdAt: now,
|
||
updatedAt: now,
|
||
concludedAt: null,
|
||
}
|
||
project.deliberations ??= []
|
||
project.deliberations.push(record)
|
||
if (project.deliberations.length > DELIBERATION_LIMIT) {
|
||
project.deliberations.splice(0, project.deliberations.length - DELIBERATION_LIMIT)
|
||
}
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return structuredClone(record)
|
||
})
|
||
// 先回执、后叫席:叫席(含新建席位会话)在后台队列里跑,工具调用和页面请求都不被它占住。
|
||
this._scheduleDeliberation(projectId, 'start ' + created.id, () => this._deliverDeliberationTurn(projectId, created.id))
|
||
return {
|
||
deliberation: created,
|
||
receipt: {
|
||
text: '议政 ' + created.id + ' 已发起,已叫' + deliberationSeatLabel(created.currentSeatId) + '。发言回来会显示在议政页。',
|
||
round: created.round,
|
||
seatId: created.currentSeatId,
|
||
},
|
||
}
|
||
}
|
||
|
||
async _deliverDeliberationTurn(projectId, deliberationId) {
|
||
await this.store.ensureLoaded()
|
||
let project = this.store.get(projectId)
|
||
let record = (project?.deliberations ?? []).find(item => item.id === deliberationId)
|
||
if (!record || record.status !== 'running' || !record.currentSeatId) {
|
||
return { ok: false, error: '议政已结束或没有当值代表' }
|
||
}
|
||
const seatId = record.currentSeatId
|
||
const round = record.round
|
||
try {
|
||
await this.provisioner.enableSeat(projectId, seatId)
|
||
} catch (error) {
|
||
const message = String(error?.message ?? error).slice(0, 900)
|
||
await this.store.mutate(state => {
|
||
const current = state.projects[projectId]
|
||
const latest = (current?.deliberations ?? []).find(item => item.id === deliberationId)
|
||
if (!latest || latest.status !== 'running' || latest.currentSeatId !== seatId || latest.round !== round) return
|
||
const now = Date.now()
|
||
latest.turn = { round, seatId, startedAt: now, attempts: Number(latest.turn?.attempts ?? 0) + 1, status: 'failed', error: message, deliveryId: null }
|
||
latest.missing ??= []
|
||
if (!latest.missing.some(item => item.round === round && item.seatId === seatId)) {
|
||
latest.missing.push({ round, seatId, reason: 'failed', at: now })
|
||
}
|
||
latest.updatedAt = now
|
||
current.revision = (current.revision ?? 0) + 1
|
||
}).catch(() => {})
|
||
return { ok: false, error: message }
|
||
}
|
||
project = this.store.get(projectId)
|
||
record = (project?.deliberations ?? []).find(item => item.id === deliberationId)
|
||
if (!record || record.status !== 'running' || record.currentSeatId !== seatId || record.round !== round) {
|
||
return { ok: false, error: '议政轮次已变化' }
|
||
}
|
||
const seat = project.seats?.[seatId]
|
||
if (!seat || seat.status !== 'bound' || !seat.sessionId) return { ok: false, error: '席位尚未绑定会话' }
|
||
|
||
// 先把本次发送落成 sending 记录,再真正投递;崩溃后据此识别已发/未知,不自动重发。
|
||
const deliveryId = randomUUID()
|
||
const preparedAt = Date.now()
|
||
const prepared = await this.store.mutate(state => {
|
||
const current = state.projects[projectId]
|
||
const latest = (current?.deliberations ?? []).find(item => item.id === deliberationId)
|
||
if (!latest || latest.status !== 'running' || latest.currentSeatId !== seatId || latest.round !== round) return false
|
||
latest.deliveries ??= []
|
||
const attempt = latest.deliveries.filter(item => item.round === round && item.seatId === seatId).length + 1
|
||
latest.deliveries.push({ id: deliveryId, round, seatId, status: 'sending', attempt, at: preparedAt, confirmedAt: null, error: null })
|
||
if (latest.deliveries.length > 200) latest.deliveries.splice(0, latest.deliveries.length - 200)
|
||
latest.turn = {
|
||
round, seatId, startedAt: preparedAt, attempts: attempt,
|
||
status: 'delivering', error: null, deliveryId,
|
||
}
|
||
latest.updatedAt = preparedAt
|
||
current.revision = (current.revision ?? 0) + 1
|
||
return true
|
||
})
|
||
if (!prepared) return { ok: false, error: '议政轮次已变化' }
|
||
|
||
// 落完 sending 之后、真正发送之前再看一眼:用户可能刚点了停止。
|
||
const beforeSend = this.store.get(projectId)?.deliberations?.find(item => item.id === deliberationId)
|
||
if (!beforeSend || beforeSend.status !== 'running' || beforeSend.currentSeatId !== seatId || beforeSend.round !== round) {
|
||
await this.store.mutate(state => {
|
||
const latest = (state.projects[projectId]?.deliberations ?? []).find(item => item.id === deliberationId)
|
||
const delivery = (latest?.deliveries ?? []).find(item => item.id === deliveryId)
|
||
if (delivery && delivery.status === 'sending') {
|
||
delivery.status = 'cancelled'
|
||
delivery.error = '议政已停止,不再叫下一位'
|
||
}
|
||
}).catch(() => {})
|
||
return { ok: false, error: '议政已停止或轮次已变化' }
|
||
}
|
||
|
||
try {
|
||
// 省级子 Agent 可用时由它们当议政代表;否则退回席位会话本人(单测和旧项目仍走这条路)。
|
||
let delegate = null
|
||
const message = deliberationMessage(project, record, seatId, round)
|
||
if (this.provinceAgents) {
|
||
delegate = await this.provinceAgents.startDeliberationTurn({ projectId, seatId, deliberationId, round, prompt: message })
|
||
} else {
|
||
await this._deliverInternal(seat.sessionId, message, internalSource('sansheng-deliberation', { seatId, deliberationId }))
|
||
}
|
||
await this.store.mutate(state => {
|
||
const current = state.projects[projectId]
|
||
const latest = (current?.deliberations ?? []).find(item => item.id === deliberationId)
|
||
if (!latest) return
|
||
const delivery = (latest.deliveries ?? []).find(item => item.id === deliveryId)
|
||
if (latest.status !== 'running' || latest.currentSeatId !== seatId || latest.round !== round) {
|
||
if (delivery && delivery.status === 'sending') {
|
||
delivery.status = 'cancelled'
|
||
delivery.error = '议政已停止,不再叫下一位'
|
||
}
|
||
return
|
||
}
|
||
const now = Date.now()
|
||
if (delivery) { delivery.status = 'sent'; delivery.confirmedAt = now }
|
||
latest.turn = {
|
||
round, seatId, startedAt: now, attempts: Number(latest.turn?.attempts ?? 0),
|
||
status: 'delivered', error: null, deliveryId,
|
||
delegateRunId: delegate?.runId ?? null, delegateChildId: delegate?.childId ?? null,
|
||
}
|
||
latest.missing = (latest.missing ?? []).filter(item => !(item.round === round && item.seatId === seatId))
|
||
latest.updatedAt = now
|
||
current.revision = (current.revision ?? 0) + 1
|
||
})
|
||
return { ok: true, sessionId: delegate?.childId ?? seat.sessionId, deliveryId, delegate }
|
||
} catch (error) {
|
||
const message = String(error?.message ?? error).slice(0, 900)
|
||
await this.store.mutate(state => {
|
||
const current = state.projects[projectId]
|
||
const latest = (current?.deliberations ?? []).find(item => item.id === deliberationId)
|
||
if (!latest) return
|
||
const delivery = (latest.deliveries ?? []).find(item => item.id === deliveryId)
|
||
if (latest.status !== 'running' || latest.currentSeatId !== seatId || latest.round !== round) {
|
||
if (delivery && delivery.status === 'sending') {
|
||
delivery.status = 'cancelled'
|
||
delivery.error = '议政已停止,不再叫下一位'
|
||
}
|
||
return
|
||
}
|
||
const now = Date.now()
|
||
if (delivery) { delivery.status = 'failed'; delivery.error = message }
|
||
latest.turn = {
|
||
round, seatId, startedAt: now, attempts: Number(latest.turn?.attempts ?? 0),
|
||
status: 'failed', error: message, deliveryId,
|
||
}
|
||
latest.missing ??= []
|
||
if (!latest.missing.some(item => item.round === round && item.seatId === seatId)) {
|
||
latest.missing.push({ round, seatId, reason: 'failed', at: now })
|
||
}
|
||
latest.updatedAt = now
|
||
current.revision = (current.revision ?? 0) + 1
|
||
}).catch(() => {})
|
||
return { ok: false, error: message, deliveryId }
|
||
}
|
||
}
|
||
|
||
async deliberationSpeak(projectId, deliberationId, input = {}, actor = {}, callId = null) {
|
||
await this.store.ensureLoaded()
|
||
if (!DELIBERATION_SEATS.includes(actor.seatId)) {
|
||
throw new ServiceError('sansheng/forbidden', '只有中书、门下、尚书的当值代表可以发言')
|
||
}
|
||
await this._expireDeliberation(projectId)
|
||
const result = await this.store.mutate(state => {
|
||
const project = state.projects[projectId]
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
const record = (project.deliberations ?? []).find(item => item.id === deliberationId)
|
||
if (!record) throw new ServiceError('sansheng/deliberation-not-found', '议政不存在')
|
||
const delegate = actor.delegate ?? null
|
||
if (delegate) {
|
||
if (delegate.deliberationId !== deliberationId || delegate.seatId !== actor.seatId
|
||
|| delegate.runId !== record.turn?.delegateRunId) {
|
||
throw new ServiceError('sansheng/forbidden', '当前省级子 Agent 不是本轮当值代表')
|
||
}
|
||
const located = this.provinceAgents?.locateBySession(actor.sessionId)
|
||
if (!located || located.run.id !== delegate.runId) {
|
||
throw new ServiceError('sansheng/forbidden', '省级子 Agent 运行记录已失效')
|
||
}
|
||
} else {
|
||
const seat = project.seats?.[actor.seatId]
|
||
if (!seat || seat.sessionId !== actor.sessionId) {
|
||
throw new ServiceError('sansheng/forbidden', '当前会话不是该席绑定的会话')
|
||
}
|
||
}
|
||
const round = Number(input.round)
|
||
const existing = (record.speeches ?? []).find(item => item.round === round && item.seatId === actor.seatId)
|
||
if (existing) {
|
||
return { speech: existing, record: structuredClone(record), duplicate: true, nextSeatId: null, concluded: false }
|
||
}
|
||
if (record.status !== 'running') throw new ServiceError('sansheng/deliberation-ended', '议政已结束')
|
||
if (!Number.isInteger(round) || round !== record.round) {
|
||
throw new ServiceError('sansheng/deliberation-turn', '不是当前轮次')
|
||
}
|
||
if (record.currentSeatId !== actor.seatId || !record.turn || record.turn.round !== round) {
|
||
throw new ServiceError('sansheng/deliberation-turn', '还没轮到你发言')
|
||
}
|
||
const text = cleanText(input.text).slice(0, 6000)
|
||
if (!text) throw new ServiceError('sansheng/deliberation-invalid', '发言不能为空')
|
||
const stance = cleanText(input.stance) || 'neutral'
|
||
if (!DELIBERATION_STANCES.has(stance)) {
|
||
throw new ServiceError('sansheng/deliberation-invalid', 'stance 必须是 agree、dissent 或 neutral')
|
||
}
|
||
const now = Date.now()
|
||
const speech = {
|
||
id: randomUUID(), round, seatId: actor.seatId, text, stance,
|
||
pending: input.pending === true,
|
||
openIssues: cleanText(input.openIssues).slice(0, 1200),
|
||
callId: cleanText(callId) || null,
|
||
via: actor.delegate ? 'subagent' : 'seat',
|
||
runId: actor.delegate?.runId ?? null,
|
||
at: now,
|
||
}
|
||
record.speeches ??= []
|
||
record.speeches.push(speech)
|
||
record.missing = (record.missing ?? []).filter(item => !(item.round === round && item.seatId === actor.seatId))
|
||
record.turn = null
|
||
record.currentSeatId = null
|
||
record.updatedAt = now
|
||
const roundSpeeches = record.speeches.filter(item => item.round === round)
|
||
let nextSeatId = null
|
||
let concluded = false
|
||
if (roundSpeeches.length < DELIBERATION_SEATS.length) {
|
||
nextSeatId = DELIBERATION_SEATS.find(id => !roundSpeeches.some(item => item.seatId === id))
|
||
record.currentSeatId = nextSeatId
|
||
record.turn = { round, seatId: nextSeatId, startedAt: now, attempts: 0, status: 'waiting', error: null }
|
||
} else {
|
||
const consensus = roundSpeeches.every(item => item.stance === 'agree' && !item.pending && !item.openIssues)
|
||
const maxed = record.maxRounds > 0 && round >= record.maxRounds
|
||
if (consensus || maxed) {
|
||
concluded = true
|
||
record.status = 'concluded'
|
||
record.concludedAt = now
|
||
record.conclusion = deliberationConclusion(record, consensus ? 'consensus' : 'max-rounds')
|
||
} else {
|
||
record.round = round + 1
|
||
nextSeatId = 'zhongshu'
|
||
record.currentSeatId = nextSeatId
|
||
record.turn = { round: record.round, seatId: nextSeatId, startedAt: now, attempts: 0, status: 'waiting', error: null }
|
||
}
|
||
}
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return { speech, record: structuredClone(record), duplicate: false, nextSeatId, concluded }
|
||
})
|
||
if (result.duplicate) {
|
||
return { ok: true, duplicate: true, speech: result.speech, deliberation: result.record }
|
||
}
|
||
if (actor.delegate && typeof this.provinceAgents?.finishRun === 'function') {
|
||
await this.provinceAgents.finishRun(projectId, actor.delegate.runId, '发言已提交')
|
||
}
|
||
// 发言只落盘并回执;叫下一位、收束通知都排进后台队列,当前席位不再被下一席的启动拖住。
|
||
if (result.nextSeatId) {
|
||
this._scheduleDeliberation(projectId, 'turn ' + deliberationId, () => this._deliverDeliberationTurn(projectId, deliberationId))
|
||
}
|
||
if (result.concluded) {
|
||
this._scheduleDeliberation(projectId, 'notify ' + deliberationId, () => this._notifyDeliberationConclusion(projectId, deliberationId))
|
||
}
|
||
const receipt = result.concluded
|
||
? { text: '发言已记录,议政已收束,结论会回到发起会话。', concluded: true }
|
||
: { text: '发言已记录,已叫' + deliberationSeatLabel(result.nextSeatId) + '。', round: result.record.round, seatId: result.nextSeatId }
|
||
return { ok: true, duplicate: false, speech: result.speech, deliberation: result.record, delivery: null, receipt, concluded: result.concluded }
|
||
}
|
||
|
||
async endDeliberation(projectId, deliberationId, input = {}) {
|
||
await this.store.ensureLoaded()
|
||
await this._expireDeliberation(projectId)
|
||
const record = await this.store.mutate(state => {
|
||
const project = state.projects[projectId]
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
const current = (project.deliberations ?? []).find(item => item.id === deliberationId)
|
||
if (!current) throw new ServiceError('sansheng/deliberation-not-found', '议政不存在')
|
||
if (current.status !== 'running') throw new ServiceError('sansheng/deliberation-ended', '议政已结束')
|
||
const now = Date.now()
|
||
current.status = 'concluded'
|
||
current.concludedAt = now
|
||
current.currentSeatId = null
|
||
current.turn = null
|
||
current.conclusion = deliberationConclusion(current, 'ended', cleanText(input.note).slice(0, 1200))
|
||
current.updatedAt = now
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return structuredClone(current)
|
||
})
|
||
this._scheduleDeliberation(projectId, 'notify ' + deliberationId, () => this._notifyDeliberationConclusion(projectId, deliberationId))
|
||
return { deliberation: record }
|
||
}
|
||
|
||
// 用户叫停:先落“已停止”并清空当值,再真正取消当前席位的回合;
|
||
// 后台队列在每次叫席前后都会看状态,停止后不会再投递下一位。
|
||
async stopDeliberation(projectId, deliberationId, input = {}) {
|
||
await this.store.ensureLoaded()
|
||
await this._expireDeliberation(projectId)
|
||
let delegateRunId = null
|
||
const stopped = await this.store.mutate(state => {
|
||
const project = state.projects[projectId]
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
const record = (project.deliberations ?? []).find(item => item.id === deliberationId)
|
||
if (!record) throw new ServiceError('sansheng/deliberation-not-found', '议政不存在')
|
||
if (record.status !== 'running') throw new ServiceError('sansheng/deliberation-ended', '议政已结束')
|
||
const now = Date.now()
|
||
const turn = record.turn ?? null
|
||
delegateRunId = turn?.delegateRunId ?? null
|
||
record.status = 'stopped'
|
||
record.stoppedAt = now
|
||
record.stoppedBy = cleanText(input.by) || 'user'
|
||
record.stoppedNote = cleanText(input.note).slice(0, 600) || null
|
||
record.stoppedTurn = turn
|
||
? { round: turn.round, seatId: turn.seatId, status: 'stopped', attempts: turn.attempts ?? 0, startedAt: turn.startedAt ?? now }
|
||
: (record.currentSeatId
|
||
? { round: record.round, seatId: record.currentSeatId, status: 'stopped', attempts: 0, startedAt: now }
|
||
: null)
|
||
for (const delivery of record.deliveries ?? []) {
|
||
if (delivery.status === 'sending') {
|
||
delivery.status = 'cancelled'
|
||
delivery.error = '议政已停止,不再叫下一位'
|
||
}
|
||
}
|
||
record.currentSeatId = null
|
||
record.turn = null
|
||
record.concludedAt = now
|
||
record.conclusion = deliberationConclusion(record, 'stopped', record.stoppedNote ?? '')
|
||
record.updatedAt = now
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return structuredClone(record)
|
||
})
|
||
let cancelled = false
|
||
if (delegateRunId && this.provinceAgents) {
|
||
try {
|
||
const result = await this.provinceAgents.stopRun(projectId, delegateRunId, '议政已停止')
|
||
cancelled = Boolean(result?.cancelled)
|
||
} catch {}
|
||
}
|
||
if (!cancelled) {
|
||
cancelled = this._cancelSeatTurn(this.store.get(projectId)?.seats?.[stopped.stoppedTurn?.seatId]?.sessionId)
|
||
}
|
||
return {
|
||
deliberation: stopped,
|
||
cancelled,
|
||
receipt: {
|
||
text: stopped.stoppedTurn
|
||
? '已停止,停在第 ' + stopped.stoppedTurn.round + ' 轮 · ' + deliberationSeatLabel(stopped.stoppedTurn.seatId) + ',不会再叫下一位。'
|
||
: '已停止,不会再叫下一位。',
|
||
},
|
||
}
|
||
}
|
||
|
||
// 真中断:宿主公开的 agent.cancel 就是用户点“停止”时走的那条路;拿不到就只保证不再投递。
|
||
_cancelSeatTurn(sessionId) {
|
||
if (!sessionId) return false
|
||
try {
|
||
const agent = this.host.agents?.get?.(sessionId)
|
||
if (!agent || typeof agent.cancel !== 'function') return false
|
||
agent.cancel({ kind: 'user' })
|
||
return true
|
||
} catch {
|
||
return false
|
||
}
|
||
}
|
||
|
||
async retryDeliberation(projectId, deliberationId) {
|
||
await this.store.ensureLoaded()
|
||
await this._expireDeliberation(projectId)
|
||
const record = (this.store.get(projectId)?.deliberations ?? []).find(item => item.id === deliberationId)
|
||
if (!record) throw new ServiceError('sansheng/deliberation-not-found', '议政不存在')
|
||
if (record.status !== 'running') throw new ServiceError('sansheng/deliberation-ended', '议政已结束')
|
||
if (!record.turn || !['failed', 'timeout'].includes(record.turn.status)) {
|
||
throw new ServiceError('sansheng/deliberation-turn', '当前回合没有失败或超时,无需重试')
|
||
}
|
||
await this.store.mutate(state => {
|
||
const current = state.projects[projectId]
|
||
const latest = (current?.deliberations ?? []).find(item => item.id === deliberationId)
|
||
if (!latest || latest.status !== 'running') return
|
||
const old = (latest.deliveries ?? []).find(item => item.id === latest.turn?.deliveryId)
|
||
if (old?.status === 'sending') {
|
||
old.status = 'unknown'
|
||
old.error = '重试前未确认原投递结果'
|
||
}
|
||
})
|
||
const delivery = await this._deliverDeliberationTurn(projectId, deliberationId)
|
||
const fresh = await this.deliberation(projectId, deliberationId)
|
||
return { deliberation: fresh.deliberation, delivery }
|
||
}
|
||
|
||
async _notifyDeliberationConclusion(projectId, deliberationId) {
|
||
try {
|
||
const project = this.store.get(projectId)
|
||
const record = (project?.deliberations ?? []).find(item => item.id === deliberationId)
|
||
if (!record) return
|
||
const seats = Object.values(project?.seats ?? {})
|
||
const originSeat = record.originSessionId
|
||
? seats.find(seat => seat.sessionId === record.originSessionId)
|
||
: null
|
||
const lead = project?.seats?.lead
|
||
const target = originSeat?.sessionId ? originSeat.sessionId : (lead?.status === 'bound' ? lead.sessionId : null)
|
||
if (!target) return
|
||
const conclusion = record.conclusion ?? { text: '议政已结束。', needsUserDecision: false }
|
||
const text = [
|
||
'【三省议政结束】' + record.id + ' · ' + record.topic,
|
||
'结论:' + conclusion.text,
|
||
'是否需要用户决定:' + (conclusion.needsUserDecision ? '是' : '否'),
|
||
'请用零基础白话向用户说明:达成了什么、还差什么、是否需要用户拍板。',
|
||
conclusion.needsUserDecision
|
||
? '有分歧时用 sansheng_card 挂问题卡,把可选做法写进选项;不要代用户决定。'
|
||
: '纯共识不要挂需要点选的卡,直接说明结论和议政入口。',
|
||
].join('\n')
|
||
await this._deliverInternal(target, text, internalSource('sansheng-deliberation', { seatId: 'lead', deliberationId }))
|
||
} catch {
|
||
// 通知失败不影响议政落盘;用户仍可在工作台查看转写和结论。
|
||
}
|
||
}
|
||
|
||
// 丞相把指令交给中书接令子 Agent:先回执,接令再把原话和要点交回中书主席。
|
||
async startOrder(projectId, input = {}, actor = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
if (!this.provinceAgents) throw new ServiceError('sansheng/province-unavailable', '宿主未提供省级子 Agent,无法启动中书接令')
|
||
const instruction = cleanText(input.instruction)
|
||
if (!instruction) throw new ServiceError('sansheng/order-invalid', '请说明要下达的指令')
|
||
const seatId = cleanText(input.seatId) || 'zhongshu'
|
||
if (this.secretaryRouting?.order) {
|
||
return this.secretaryRouting.order({ projectId, seatId, instruction,
|
||
taskId: cleanText(input.taskId) || null, requirementId: cleanText(input.requirementId) || null,
|
||
sourceSessionId: cleanText(actor.sessionId) || null })
|
||
}
|
||
return this.provinceAgents.startOrder({
|
||
seatId,
|
||
projectId,
|
||
instruction,
|
||
taskId: cleanText(input.taskId) || null,
|
||
requirementId: cleanText(input.requirementId) || null,
|
||
sourceSessionId: cleanText(input.originSessionId) || cleanText(actor.sessionId) || null,
|
||
})
|
||
}
|
||
|
||
// 统一列出后台能停的运行:主簿、记室、省级接令与议政代表。
|
||
async agentRuns(projectId) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
const secretaries = typeof this.leadSecretaries?.list === 'function' ? await this.leadSecretaries.list(projectId) : []
|
||
const province = this.provinceAgents ? await this.provinceAgents.list(projectId) : []
|
||
return { runs: [...secretaries, ...province] }
|
||
}
|
||
|
||
async stopAgentRun(projectId, runId, kind = '') {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
const id = cleanText(runId)
|
||
if (!id) throw new ServiceError('sansheng/agent-run-not-found', '缺少运行编号')
|
||
if (kind === 'secretary' || (kind !== 'province' && typeof this.leadSecretaries?.hasRun === 'function'
|
||
&& await this.leadSecretaries.hasRun(projectId, id))) {
|
||
if (!this.leadSecretaries) throw new ServiceError('sansheng/agent-run-not-found', '主簿与记室未启用')
|
||
return this.leadSecretaries.stop(projectId, id)
|
||
}
|
||
if (this.provinceAgents) return this.provinceAgents.stopRun(projectId, id)
|
||
throw new ServiceError('sansheng/agent-run-not-found', '后台子 Agent 运行不存在')
|
||
}
|
||
|
||
// 头像:字符或已缩放图片;图片超出上限直接拒绝,客户端负责缩放到 256×256。
|
||
async setAvatar(projectId, seatId, input = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/avatar-invalid', '未知席位')
|
||
const char = cleanText(input.char)
|
||
const dataUrl = cleanText(input.dataUrl)
|
||
let avatar
|
||
if (char) {
|
||
if ([...char].length > AVATAR_CHAR_MAX) {
|
||
throw new ServiceError('sansheng/avatar-invalid', '头像字符最多 8 个,emoji 也算一个')
|
||
}
|
||
avatar = { type: 'char', char }
|
||
} else if (dataUrl) {
|
||
const match = /^data:(image\/(?:png|jpeg|webp));base64,([A-Za-z0-9+/=]+)$/.exec(dataUrl)
|
||
if (!match) throw new ServiceError('sansheng/avatar-invalid', '头像只支持 PNG、JPEG 或 WebP 图片')
|
||
const bytes = Buffer.from(match[2], 'base64').length
|
||
if (bytes === 0) throw new ServiceError('sansheng/avatar-invalid', '图片内容为空')
|
||
if (bytes > AVATAR_MAX_BYTES) {
|
||
throw new ServiceError('sansheng/avatar-invalid', '图片超过 120KB,请换一张小一点的图片')
|
||
}
|
||
avatar = { type: 'image', mime: match[1], dataUrl, bytes }
|
||
} else {
|
||
throw new ServiceError('sansheng/avatar-invalid', '请提供图片或字符头像')
|
||
}
|
||
await this.store.mutate(state => {
|
||
const project = state.projects[projectId]
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
project.avatars ??= {}
|
||
project.avatars[seatId] = avatar
|
||
project.updatedAt = Date.now()
|
||
project.revision = (project.revision ?? 0) + 1
|
||
})
|
||
return { seatId, avatar }
|
||
}
|
||
|
||
async clearAvatar(projectId, seatId) {
|
||
await this.store.ensureLoaded()
|
||
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/avatar-invalid', '未知席位')
|
||
await this.store.mutate(state => {
|
||
const project = state.projects[projectId]
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
if (project.avatars?.[seatId]) {
|
||
delete project.avatars[seatId]
|
||
project.updatedAt = Date.now()
|
||
project.revision = (project.revision ?? 0) + 1
|
||
}
|
||
})
|
||
return { seatId, avatar: null }
|
||
}
|
||
|
||
async requestTaskDecision(projectId, taskId, input, actor) {
|
||
if (actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '请先把分歧交给丞相')
|
||
const question = cleanText(input.question)
|
||
const options = (input.options ?? []).map((label, index) => ({ label: cleanText(label), value: String(index + 1) }))
|
||
if (!question || options.length < 2 || options.length > 5 || options.some(option => !option.label)) {
|
||
throw new ServiceError('sansheng/invalid', '请说明需要用户选择的问题并给出 2 到 5 个选项')
|
||
}
|
||
return this.store.mutate(state => {
|
||
const project = state.projects[projectId]
|
||
const task = project?.tasks?.find(item => item.id === taskId && item.kind === 'workflow')
|
||
if (!task || ['done', 'cancelled', 'reconfirm'].includes(task.status)) throw new ServiceError('sansheng/stage-forbidden', '任务已结束或需求已更新')
|
||
task.decisions ??= []
|
||
const existing = task.decisions.find(item => item.status === 'pending' && item.question === question)
|
||
if (existing) return { decision: existing }
|
||
const decision = { id: randomUUID(), question, options, status: 'pending', createdAt: Date.now() }
|
||
task.decisions.push(decision)
|
||
task.awaitingLeadDecision = false
|
||
task.updatedAt = decision.createdAt
|
||
project.revision += 1
|
||
return { decision }
|
||
})
|
||
}
|
||
|
||
async surfaceLegacyApprovals() {
|
||
await this.store.ensureLoaded()
|
||
const waiting = task => task.stage === 'awaiting_execution_approval' && task.status === 'waiting_user' && !task.decisions?.some(item => item.kind === 'legacy-approval')
|
||
if (!this.store.list().some(project => project.tasks?.some(waiting))) return
|
||
await this.store.mutate(state => {
|
||
for (const project of Object.values(state.projects)) {
|
||
for (const task of (project.tasks ?? []).filter(waiting)) {
|
||
task.decisions ??= []
|
||
task.decisions.push(legacyApprovalDecision(Date.now()))
|
||
project.revision = (project.revision ?? 0) + 1
|
||
}
|
||
}
|
||
})
|
||
}
|
||
|
||
async answerTaskDecision(projectId, taskId, decisionId, value) {
|
||
const result = await this.store.mutate(state => {
|
||
const project = state.projects[projectId]
|
||
const task = project?.tasks?.find(item => item.id === taskId)
|
||
const decision = task?.decisions?.find(item => item.id === decisionId)
|
||
const option = decision?.options.find(item => item.value === value)
|
||
if (!option || ['done', 'cancelled', 'reconfirm'].includes(task.status)) throw new ServiceError('sansheng/invalid', '决定已失效或选项无效')
|
||
if (decision.status === 'answered') {
|
||
if (decision.answer !== value) throw new ServiceError('sansheng/conflict', '这项决定已有答复')
|
||
return { decision, duplicate: true }
|
||
}
|
||
decision.status = 'answered'
|
||
decision.answer = value
|
||
decision.answeredAt = Date.now()
|
||
task.updatedAt = decision.answeredAt
|
||
project.revision += 1
|
||
if (decision.kind === 'legacy-approval') {
|
||
const requirement = project.requirements.find(item => item.id === task.requirementId)
|
||
if (task.stage !== 'awaiting_execution_approval' || requirement?.revision !== task.requirementRevision) {
|
||
throw new ServiceError('sansheng/conflict', '方案已变化,请刷新任务')
|
||
}
|
||
if (value === 'cancel') {
|
||
task.status = 'cancelled'
|
||
task.blockedReason = '用户结束旧任务'
|
||
voidDelivery(task)
|
||
requirement.status = 'ready'
|
||
requirement.blockedReason = requirementBlockedReason(requirement)
|
||
requirement.updatedAt = decision.answeredAt
|
||
return { decision }
|
||
}
|
||
handOffReviewedTask(project, task, requirement, decision.answeredAt, 'user')
|
||
const deliveryId = queueDelivery(task, 'dispatched', decision.answeredAt)
|
||
return { decision, deliveryId }
|
||
}
|
||
const request = task.consultations?.findLast(entry => entry.toSeatIds.includes('lead'))
|
||
const toSeatIds = [...new Set([task.ownerSeatId, request?.fromSeatId].filter(seat => seat && seat !== 'lead'))]
|
||
return { decision, toSeatIds, text: decision.question + ':' + option.label }
|
||
})
|
||
if (result.deliveryId) {
|
||
void this.taskDispatch(projectId, taskId, { deliveryId: result.deliveryId }).catch(error => console.warn('[sansheng] 尚书投递失败:', error))
|
||
}
|
||
if (result.text && result.toSeatIds.length) {
|
||
void this.consultTask(projectId, taskId, { text: '用户决定:' + result.text, toSeatIds: result.toSeatIds }, { seatId: 'lead' })
|
||
.then(outcome => { if (outcome.failedSeatIds.length) console.warn('[sansheng] 决定通知未送达:', outcome.failedSeatIds) })
|
||
.catch(error => console.warn('[sansheng] 决定通知失败:', error))
|
||
}
|
||
return { decision: result.decision }
|
||
}
|
||
|
||
async workflowDispatch(projectId, taskId, input = {}, actor = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (actor.seatId !== 'shangshu') throw new ServiceError('sansheng/forbidden', '只有尚书省可以调度六部')
|
||
const assignments = Array.isArray(input.assignments) ? input.assignments : []
|
||
if (assignments.length === 0) throw new ServiceError('sansheng/invalid', '至少需要给一个六部席位分派任务')
|
||
const liubu = new Set(SEAT_GROUPS.liubu)
|
||
for (const assignment of assignments) {
|
||
const seatId = cleanText(assignment?.seatId)
|
||
if (!liubu.has(seatId)) throw new ServiceError('sansheng/route-forbidden', `尚书省只能调度六部,不能派给 ${seatId || '空目标'}`)
|
||
if (!cleanText(assignment?.title)) throw new ServiceError('sansheng/invalid', '每个六部任务必须有标题')
|
||
}
|
||
const assignmentSummary = assignments.map(item => `${SEATS[item.seatId]?.label ?? item.seatId}:${item.title}`).join(';')
|
||
const result = await this.store.mutate(s => {
|
||
const project = s.projects[projectId]
|
||
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||
if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`)
|
||
if (task.ownerSeatId !== 'shangshu' || task.stage !== 'shangshu_dispatch') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在尚书调度阶段')
|
||
taskDecisionBlock(task)
|
||
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||
if (!req || req.revision !== task.requirementRevision) throw new ServiceError('sansheng/requirement-changed', '需求版本已变化,批准失效')
|
||
const approval = (project.approvals ?? []).find(item => item.id === task.approvalId)
|
||
if (!approval || approval.status !== 'approved' || approval.requirementRevision !== req.revision || approval.scope !== task.approvalScope) {
|
||
throw new ServiceError('sansheng/approval-invalid', '执行批准无效或已过期,不能向六部派工')
|
||
}
|
||
const now = Date.now()
|
||
// 派发沿用批准时的有效快照:用户需求字段优先,中书补缺或修订随任务走。
|
||
const effective = effectiveRequirementSnapshot(task, req)
|
||
task.requirementSnapshot = effective
|
||
const children = []
|
||
for (const assignment of assignments) {
|
||
const seatId = cleanText(assignment.seatId)
|
||
project.taskSeq = (project.taskSeq ?? 0) + 1
|
||
const child = emptyTask({
|
||
id: `task-${project.taskSeq}`,
|
||
title: cleanText(assignment.title),
|
||
goal: cleanText(assignment.goal) || effective.scope || effective.title,
|
||
requirement: req.originalText,
|
||
ownerSeatId: seatId,
|
||
kind: 'execution',
|
||
requirementId: req.id,
|
||
requirementRevision: req.revision,
|
||
approvalId: approval.id,
|
||
parentTaskId: task.id,
|
||
stage: 'department_exec',
|
||
now,
|
||
})
|
||
child.approvalScope = approval.scope
|
||
child.requirementSnapshot = { ...effective }
|
||
child.blockedReason = '六部执行中'
|
||
queueDelivery(child, 'dispatched', now)
|
||
project.tasks.push(child)
|
||
children.push({ ...child })
|
||
}
|
||
task.stage = 'department_exec'
|
||
task.status = 'running'
|
||
task.blockedReason = '六部执行中'
|
||
task.lastTransitionId = randomUUID()
|
||
appendLeadReport(s, projectId, task, 'shangshu_dispatch', assignmentSummary)
|
||
voidDelivery(task)
|
||
task.updatedAt = now
|
||
req.blockedReason = '六部执行中'
|
||
req.updatedAt = now
|
||
project.updatedAt = now
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return { task: { ...task }, children }
|
||
})
|
||
const deliveries = await Promise.all(result.children.map(async child => {
|
||
try {
|
||
const delivered = await this.taskDispatch(projectId, child.id, { deliveryId: child.deliveryId })
|
||
return { taskId: child.id, seatId: child.ownerSeatId, delivered: delivered.delivered }
|
||
} catch (error) {
|
||
return { taskId: child.id, seatId: child.ownerSeatId, delivered: false, error: error?.message ?? String(error) }
|
||
}
|
||
}))
|
||
return { ok: deliveries.every(item => item.delivered), task: result.task, children: result.children, deliveries }
|
||
}
|
||
|
||
async workflowSummarize(projectId, taskId, input = {}, actor = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (actor.seatId !== 'shangshu') throw new ServiceError('sansheng/forbidden', '只有尚书省可以汇总六部结果')
|
||
const summaryInput = cleanText(input.summary)
|
||
const next = await this.store.mutate(s => {
|
||
const project = s.projects[projectId]
|
||
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||
if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`)
|
||
if (task.ownerSeatId !== 'shangshu' || task.stage !== 'department_exec') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在六部执行阶段,不能汇总')
|
||
const children = (project.tasks ?? []).filter(item => item.parentTaskId === task.id && item.kind === 'execution')
|
||
if (children.length === 0) throw new ServiceError('sansheng/invalid', '没有六部执行任务可汇总')
|
||
const open = children.filter(item => OPEN_TASK_STATUS.has(item.status))
|
||
if (open.length > 0) throw new ServiceError('sansheng/tasks-open', `还有 ${open.length} 个六部任务未结束,不能汇总:${open.map(item => item.id).join('、')}`)
|
||
const summary = summaryInput || children.map(item => `- ${item.id} ${SEATS[item.ownerSeatId]?.label ?? item.ownerSeatId} [${item.status}]:${item.result || item.note || '无结果'}`).join('\n')
|
||
const now = Date.now()
|
||
task.summary = summary
|
||
task.stage = 'menxia_acceptance'
|
||
task.ownerSeatId = 'menxia'
|
||
task.status = 'draft'
|
||
task.blockedReason = '待门下省验收'
|
||
task.lastTransitionId = randomUUID()
|
||
appendLeadReport(s, projectId, task, 'shangshu_summarize', summary)
|
||
queueDelivery(task, 'dispatched', now)
|
||
task.updatedAt = now
|
||
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||
if (req) { req.blockedReason = '门下验收中'; req.updatedAt = now }
|
||
project.updatedAt = now
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return { task: { ...task } }
|
||
})
|
||
const dispatched = await this.taskDispatch(projectId, taskId, { deliveryId: next.task.deliveryId })
|
||
return { ok: dispatched.delivered, delivered: dispatched.delivered, task: dispatched.task }
|
||
}
|
||
|
||
async workflowAccept(projectId, taskId, input = {}, actor = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (actor.seatId !== 'menxia') throw new ServiceError('sansheng/forbidden', '只有门下省可以验收')
|
||
const action = cleanText(input.action)
|
||
if (!['accept', 'reject'].includes(action)) throw new ServiceError('sansheng/invalid', '验收动作必须是 accept 或 reject')
|
||
const note = cleanText(input.note)
|
||
if (action === 'reject' && !note) throw new ServiceError('sansheng/invalid', '验收退回必须写明原因')
|
||
const next = await this.store.mutate(s => {
|
||
const project = s.projects[projectId]
|
||
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||
if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`)
|
||
if (task.ownerSeatId !== 'menxia' || task.stage !== 'menxia_acceptance') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在门下验收阶段')
|
||
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||
const now = Date.now()
|
||
task.reviewNote = note
|
||
if (action === 'reject') {
|
||
task.stage = 'shangshu_dispatch'
|
||
task.ownerSeatId = 'shangshu'
|
||
task.status = 'returned'
|
||
task.blockedReason = '验收退回尚书省重新调度'
|
||
if (req) { req.blockedReason = `验收退回:${note}`; req.updatedAt = now }
|
||
} else {
|
||
task.stage = 'lead_delivery'
|
||
task.ownerSeatId = 'lead'
|
||
task.status = 'prepared'
|
||
task.blockedReason = '待丞相交付'
|
||
if (req) { req.blockedReason = '待丞相交付'; req.updatedAt = now }
|
||
}
|
||
task.lastTransitionId = randomUUID()
|
||
appendLeadReport(s, projectId, task, action === 'reject' ? 'menxia_accept_return' : 'menxia_accept', note || '验收通过')
|
||
queueDelivery(task, task.status, now)
|
||
task.updatedAt = now
|
||
project.updatedAt = now
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return { task: { ...task } }
|
||
})
|
||
const dispatched = await this.taskDispatch(projectId, taskId, { deliveryId: next.task.deliveryId })
|
||
return { ok: dispatched.delivered, delivered: dispatched.delivered, task: dispatched.task }
|
||
}
|
||
|
||
async workflowDeliver(projectId, taskId, input = {}, actor = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以交付')
|
||
const deliveryNote = cleanText(input.delivery)
|
||
if (!deliveryNote) throw new ServiceError('sansheng/invalid', '交付内容不能为空')
|
||
return this.store.mutate(s => {
|
||
const project = s.projects[projectId]
|
||
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||
if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`)
|
||
if (task.ownerSeatId !== 'lead' || task.stage !== 'lead_delivery') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在丞相交付阶段')
|
||
const now = Date.now()
|
||
task.stage = 'delivered'
|
||
task.status = 'done'
|
||
task.deliveryNote = deliveryNote
|
||
task.deliveredAt = now
|
||
voidDelivery(task)
|
||
task.deliveredBySessionId = actor.sessionId ?? null
|
||
task.lastTransitionId = randomUUID()
|
||
task.blockedReason = ''
|
||
task.updatedAt = now
|
||
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||
if (req) { req.blockedReason = '已交付'; req.updatedAt = now }
|
||
project.updatedAt = now
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return { ok: true, task: { ...task } }
|
||
})
|
||
}
|
||
|
||
async taskCreate(projectId, input = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
const title = String(input.title ?? '').trim()
|
||
if (!title) throw new ServiceError('sansheng/invalid', '任务标题不能为空')
|
||
if (!SEAT_IDS.includes(input.ownerSeatId)) throw new ServiceError('sansheng/invalid', `未知主责席 ${String(input.ownerSeatId)}`)
|
||
const goal = typeof input.goal === 'string' ? input.goal : ''
|
||
const requirement = typeof input.requirement === 'string' ? input.requirement : ''
|
||
const task = await this.store.mutate(s => {
|
||
const project = s.projects[projectId]
|
||
project.taskSeq = (project.taskSeq ?? 0) + 1
|
||
const next = emptyTask({
|
||
id: `task-${project.taskSeq}`, title, goal, requirement, ownerSeatId: input.ownerSeatId,
|
||
kind: input.kind === 'workflow' || input.kind === 'execution' ? input.kind : 'legacy',
|
||
requirementId: input.requirementId ?? null, requirementRevision: input.requirementRevision ?? null,
|
||
approvalId: input.approvalId ?? null, parentTaskId: input.parentTaskId ?? null, stage: input.stage ?? null,
|
||
})
|
||
if (input.requirementSnapshot && typeof input.requirementSnapshot === 'object') next.requirementSnapshot = structuredClone(input.requirementSnapshot)
|
||
if (typeof input.approvalScope === 'string') next.approvalScope = input.approvalScope
|
||
if (typeof input.blockedReason === 'string') next.blockedReason = input.blockedReason
|
||
if (!Array.isArray(project.tasks)) project.tasks = []
|
||
project.tasks.push(next)
|
||
project.updatedAt = Date.now()
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return { ...next }
|
||
})
|
||
return { task }
|
||
}
|
||
|
||
async taskDispatch(projectId, taskId, options = {}) {
|
||
await this.store.ensureLoaded()
|
||
let project = this.store.get(projectId)
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
let task = (project.tasks ?? []).find(item => item.id === taskId)
|
||
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||
const redispatch = options.redispatch === true
|
||
const requestedId = typeof options.deliveryId === 'string' && options.deliveryId.trim() ? options.deliveryId.trim() : null
|
||
if (redispatch) {
|
||
// 重投只认投递结果未知、且任务没有结束的记录;同一 deliveryId 人工核对后只发一次。
|
||
if (!requestedId || task.deliveryId !== requestedId) throw new ServiceError('sansheng/conflict', '任务投递标识已变化,拒绝重投')
|
||
if (task.deliveryState !== 'unknown') throw new ServiceError('sansheng/invalid', '只有投递结果未知的任务可以重投')
|
||
if (['cancelled', 'done', 'reconfirm'].includes(task.status)) throw new ServiceError('sansheng/invalid', '已取消、已完成或待重新确认的任务不能重投')
|
||
} else {
|
||
if (task.status === 'done' || task.status === 'cancelled') throw new ServiceError('sansheng/invalid', '已完成或已取消的任务不能再次派工;请新建任务保留历史结果')
|
||
// 同一投递标识(或未指定标识)的已接收任务不重复刷屏;改要求与阶段切换会先作废旧投递。
|
||
if (task.deliveryState === 'accepted' && (!requestedId || task.deliveryId === requestedId)) {
|
||
return { task: { ...task }, delivered: true, duplicate: true, deliveryState: 'accepted' }
|
||
}
|
||
if (requestedId && task.deliveryId !== requestedId) throw new ServiceError('sansheng/conflict', '任务投递标识已变化,拒绝重复投递')
|
||
if (task.deliveryState === 'sending') {
|
||
return { task: { ...task }, delivered: false, duplicate: false, pending: true, reason: 'sending', deliveryState: 'sending' }
|
||
}
|
||
if (task.deliveryState === 'unknown') {
|
||
return { task: { ...task }, delivered: false, duplicate: false, unknown: true, reason: 'delivery-unknown', deliveryState: 'unknown' }
|
||
}
|
||
}
|
||
if (this.secretaryRouting && !options.viaSecretary && !redispatch
|
||
&& task.deliveryState === 'pending' && task.deliveryId === task.secretaryPublishDeliveryId) {
|
||
await this.secretaryRouting.publish({ projectId, task })
|
||
return { task: { ...task }, delivered: false, pending: true, deliveryState: 'pending', reason: 'secretary-handoff' }
|
||
}
|
||
let seat = project.seats[task.ownerSeatId]
|
||
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||
// 按需开启:丞相派工时只给出主责部门,由系统用该部门预配置的模型开启会话;丞相不选模型。
|
||
await this.provisioner.enableSeat(projectId, task.ownerSeatId)
|
||
seat = this.store.get(projectId)?.seats?.[task.ownerSeatId]
|
||
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||
throw new ServiceError('sansheng/seat-unbound', `「${SEATS[task.ownerSeatId]?.label ?? task.ownerSeatId}」的会话还没开启成功,请稍后重试`)
|
||
}
|
||
}
|
||
if (typeof this.seatDelivery?.deliverToSeat !== 'function') {
|
||
throw new ServiceError('sansheng/delivery-unavailable', '宿主未提供任务投递接口')
|
||
}
|
||
project = this.store.get(projectId)
|
||
task = (project.tasks ?? []).find(item => item.id === taskId)
|
||
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||
const expected = {
|
||
ownerSeatId: task.ownerSeatId,
|
||
stage: task.stage ?? null,
|
||
requirementRevision: task.requirementRevision ?? null,
|
||
}
|
||
const deliveryId = requestedId
|
||
?? (task.deliveryState === 'pending' && task.deliveryId ? task.deliveryId : randomUUID())
|
||
const attemptId = randomUUID()
|
||
const memory = normalizeProjectMemory(project.memory, projectId)
|
||
const text = taskDeliveryText(task, renderProjectMemory(memory))
|
||
const claim = await this.store.mutate(s => {
|
||
const targetProject = s.projects[projectId]
|
||
const target = (targetProject.tasks ?? []).find(item => item.id === taskId)
|
||
if (!target) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||
if (target.status === 'done' || target.status === 'cancelled') return { claimed: false, reason: 'task-closed', task: { ...target } }
|
||
if (redispatch) {
|
||
if (target.deliveryId !== deliveryId) return { claimed: false, reason: 'delivery-mismatch', task: { ...target } }
|
||
if (target.deliveryState !== 'unknown') return { claimed: false, reason: 'not-redispatchable', task: { ...target } }
|
||
if (['cancelled', 'done', 'reconfirm'].includes(target.status)) return { claimed: false, reason: 'task-closed', task: { ...target } }
|
||
} else {
|
||
if (target.deliveryState === 'accepted' && (!requestedId || target.deliveryId === deliveryId)) {
|
||
return { claimed: false, duplicate: true, task: { ...target } }
|
||
}
|
||
if (target.deliveryState === 'sending') return { claimed: false, reason: 'sending', task: { ...target } }
|
||
if (target.deliveryState === 'unknown') return { claimed: false, reason: 'delivery-unknown', task: { ...target } }
|
||
if (requestedId && target.deliveryId !== requestedId) return { claimed: false, reason: 'delivery-mismatch', task: { ...target } }
|
||
// 阶段切换登记的是 pending;若中途被取消或改要求作废,就不能再发。
|
||
if (requestedId && target.deliveryState !== 'pending') return { claimed: false, reason: 'stage-changed', task: { ...target } }
|
||
}
|
||
if (target.ownerSeatId !== expected.ownerSeatId
|
||
|| (target.stage ?? null) !== expected.stage
|
||
|| (target.requirementRevision ?? null) !== expected.requirementRevision) {
|
||
return { claimed: false, reason: 'stage-changed', task: { ...target } }
|
||
}
|
||
const now = Date.now()
|
||
target.deliveryId = deliveryId
|
||
target.deliveryState = 'sending'
|
||
target.sendingOwner = attemptId
|
||
target.sendingAt = now
|
||
target.deliveryOwner = attemptId
|
||
target.deliveryAttemptId = attemptId
|
||
target.deliveryAttemptAt = now
|
||
// 重投保留阶段切换时存下的目标状态;只有旧数据缺字段时才补 dispatched。
|
||
if (redispatch) target.deliveryStatus ??= 'dispatched'
|
||
target.updatedAt = now
|
||
targetProject.updatedAt = now
|
||
targetProject.revision = (targetProject.revision ?? 0) + 1
|
||
return { claimed: true, deliveryId, attemptId, task: { ...target } }
|
||
})
|
||
if (!claim.claimed) {
|
||
if (claim.duplicate) return { task: claim.task, delivered: true, duplicate: true, deliveryState: 'accepted' }
|
||
if (claim.reason === 'sending') return { task: claim.task, delivered: false, duplicate: false, pending: true, reason: 'sending', deliveryState: 'sending' }
|
||
if (claim.reason === 'delivery-unknown') return { task: claim.task, delivered: false, duplicate: false, unknown: true, reason: 'delivery-unknown', deliveryState: 'unknown' }
|
||
if (claim.reason === 'task-closed') throw new ServiceError('sansheng/invalid', '任务已结束,不能投递')
|
||
if (claim.reason === 'not-redispatchable') throw new ServiceError('sansheng/invalid', '任务已不在可重投状态')
|
||
throw new ServiceError('sansheng/conflict', '投递领取失败:' + (claim.reason === 'stage-changed' ? '任务阶段已变化' : '投递标识已变化'))
|
||
}
|
||
let delivery
|
||
try {
|
||
delivery = await this.seatDelivery.deliverToSeat({
|
||
sessionId: seat.sessionId, text, taskId: task.id, deliveryId, attemptId,
|
||
sourceKind: 'sansheng-task', seatId: task.ownerSeatId,
|
||
// 同步复核:领取仍属于本次尝试、席位仍是同一会话;返回后立即 followup。
|
||
verifyClaim: () => {
|
||
const latest = this.store.get(projectId)
|
||
const current = latest?.tasks?.find(item => item.id === taskId)
|
||
const currentSeat = latest?.seats?.[task.ownerSeatId]
|
||
return !!current && current.deliveryId === deliveryId
|
||
&& current.deliveryState === 'sending' && current.sendingOwner === attemptId
|
||
&& currentSeat?.sessionId === seat.sessionId
|
||
},
|
||
})
|
||
} catch (error) {
|
||
delivery = { status: 'unknown', reason: 'delivery-error', error: error?.message ?? String(error) }
|
||
}
|
||
const outcome = delivery.status === 'sent' ? 'sent' : (delivery.status === 'not-sent' ? 'not-sent' : 'unknown')
|
||
const activeDecisions = memory.decisions.filter(item => item.status === 'active').map(item => item.id)
|
||
const written = await this.store.mutate(s => {
|
||
const target = s.projects[projectId].tasks.find(item => item.id === taskId)
|
||
if (!target) return { applied: false, task: null }
|
||
// 回写只认同一次投递的 deliveryId 与领取者;取消、改要求、阶段切换会清掉领取者。
|
||
if (target.deliveryId !== deliveryId || target.sendingOwner !== attemptId) {
|
||
return { applied: false, task: { ...target } }
|
||
}
|
||
const now = Date.now()
|
||
target.sendingOwner = null
|
||
target.deliveryOwner = null
|
||
if (outcome === 'sent') {
|
||
// 部门可能在发送回写之前就开始执行或提交结果。
|
||
if (!['running', 'done', 'failed'].includes(target.reportStatus)) {
|
||
target.status = target.deliveryStatus ?? (target.status === 'draft' ? 'dispatched' : target.status)
|
||
target.note = ''
|
||
}
|
||
if (target.secretaryPublishDeliveryId === deliveryId) target.blockedReason = '中书省拟案中'
|
||
target.sessionId = seat.sessionId
|
||
target.dispatchedAt = now
|
||
target.contextRevision = memory.revision
|
||
target.contextHash = memory.contentHash
|
||
target.decisionIds = activeDecisions
|
||
target.sourceRefs = memory.sources.slice(0, 20)
|
||
target.deliveryState = 'accepted'
|
||
target.contextSyncState = 'provided'
|
||
} else {
|
||
target.deliveryState = outcome === 'not-sent' ? 'pending' : 'unknown'
|
||
target.contextSyncState = 'observed'
|
||
target.note = (outcome === 'not-sent' ? '未发出:' : '发送结果未知:')
|
||
+ (delivery.reason ?? delivery.status ?? 'unknown')
|
||
+ (delivery.error ? '(' + delivery.error + ')' : '')
|
||
}
|
||
target.updatedAt = now
|
||
s.projects[projectId].updatedAt = now
|
||
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||
return { applied: true, task: { ...target } }
|
||
})
|
||
return {
|
||
task: written.task ?? { ...task },
|
||
delivered: outcome === 'sent',
|
||
duplicate: false,
|
||
applied: written.applied !== false,
|
||
deliveryState: outcome === 'sent' ? 'accepted' : (outcome === 'not-sent' ? 'pending' : 'unknown'),
|
||
reason: delivery.reason ?? null,
|
||
}
|
||
}
|
||
|
||
// R-002:启动/重连恢复。pending 表示尚未开始发送,可条件领取一次;sending 遗留只标 unknown,绝不自动重发。
|
||
async recoverPendingDeliveries() {
|
||
await this.store.ensureLoaded()
|
||
// 旧版可能已收齐六部结果,但从未登记尚书通知。
|
||
if (this.store.list().some(project => project.tasks?.some(task => readyForDepartmentSummary(project, task)))) {
|
||
await this.store.mutate(s => {
|
||
for (const project of Object.values(s.projects)) {
|
||
for (const task of project.tasks ?? []) {
|
||
if (!readyForDepartmentSummary(project, task)) continue
|
||
const now = Date.now()
|
||
queueDelivery(task, task.status, now)
|
||
task.updatedAt = project.updatedAt = now
|
||
project.revision = (project.revision ?? 0) + 1
|
||
}
|
||
}
|
||
})
|
||
}
|
||
const pending = []
|
||
const sending = []
|
||
for (const project of this.store.list()) {
|
||
for (const task of project.tasks ?? []) {
|
||
if (task.deliveryState === 'pending' && !['done', 'cancelled', 'reconfirm'].includes(task.status)) {
|
||
pending.push({ projectId: project.id, taskId: task.id, deliveryId: task.deliveryId })
|
||
} else if (task.deliveryState === 'sending') {
|
||
sending.push({ projectId: project.id, taskId: task.id, deliveryId: task.deliveryId })
|
||
}
|
||
}
|
||
}
|
||
if (sending.length > 0) {
|
||
await this.store.mutate(s => {
|
||
for (const item of sending) {
|
||
const target = s.projects[item.projectId]?.tasks?.find(task => task.id === item.taskId)
|
||
if (!target || target.deliveryState !== 'sending') continue
|
||
target.deliveryState = 'unknown'
|
||
target.deliveryOwner = null
|
||
target.sendingOwner = null
|
||
target.note = '发送中断,结果未知'
|
||
target.updatedAt = Date.now()
|
||
s.projects[item.projectId].revision = (s.projects[item.projectId].revision ?? 0) + 1
|
||
}
|
||
})
|
||
}
|
||
const recovered = []
|
||
for (const item of pending) {
|
||
try {
|
||
const options = item.deliveryId ? { deliveryId: item.deliveryId } : {}
|
||
const result = await this.taskDispatch(item.projectId, item.taskId, options)
|
||
recovered.push({ projectId: item.projectId, taskId: item.taskId, delivered: result.delivered, reason: result.reason ?? null })
|
||
} catch (error) {
|
||
recovered.push({ projectId: item.projectId, taskId: item.taskId, delivered: false, error: error?.message ?? String(error) })
|
||
}
|
||
}
|
||
return { recovered, staleSending: sending.length }
|
||
}
|
||
|
||
|
||
// R-007:只对投递结果未知且未结束的任务,按 expectedDeliveryId 人工核对后重投一次。
|
||
async redispatchTask(projectId, taskId, input = {}) {
|
||
await this.store.ensureLoaded()
|
||
const project = this.store.get(projectId)
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||
const expectedDeliveryId = typeof input.expectedDeliveryId === 'string' ? input.expectedDeliveryId.trim() : ''
|
||
if (!expectedDeliveryId || task.deliveryId !== expectedDeliveryId) {
|
||
throw new ServiceError('sansheng/conflict', '任务投递标识已变化,拒绝重投')
|
||
}
|
||
const seat = project.seats?.[task.ownerSeatId]
|
||
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||
throw new ServiceError('sansheng/seat-unbound', '主责部门会话未就绪,不能重投')
|
||
}
|
||
const result = await this.taskDispatch(projectId, taskId, { deliveryId: expectedDeliveryId, redispatch: true })
|
||
const status = result.deliveryState === 'accepted'
|
||
? 'sent'
|
||
: (result.deliveryState === 'unknown' || result.reason === 'sending' ? 'unknown' : 'not-sent')
|
||
return { task: result.task, delivery: { status, reason: result.reason ?? null }, applied: result.applied !== false }
|
||
}
|
||
|
||
async taskGet(projectId, taskId) {
|
||
await this.store.ensureLoaded()
|
||
const project = this.store.get(projectId)
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||
return { task: projectTask(project, task) }
|
||
}
|
||
|
||
async taskReport(projectId, taskId, input = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
const status = input.status
|
||
if (!['running', 'done', 'failed'].includes(status)) throw new ServiceError('sansheng/invalid', '报告状态必须是 running、done 或 failed')
|
||
const result = typeof input.result === 'string' ? input.result.trim() : ''
|
||
if (status === 'done' && !result) throw new ServiceError('sansheng/invalid', '完成报告必须包含真实结果,不能只写“已完成”')
|
||
const { task: next, summaryDelivery } = await this.store.mutate(s => {
|
||
const project = s.projects[projectId]
|
||
const task = project.tasks.find(item => item.id === taskId)
|
||
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||
if (input.seatId && task.ownerSeatId !== input.seatId) {
|
||
throw new ServiceError('sansheng/forbidden', `只有主责部门 ${task.ownerSeatId} 可以报告这个任务`)
|
||
}
|
||
if (task.kind === 'execution') {
|
||
const approval = (project.approvals ?? []).find(item => item.id === task.approvalId)
|
||
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||
if (!approval || approval.status !== 'approved') throw new ServiceError('sansheng/approval-invalid', '执行批准无效或已失效,不能执行或报告')
|
||
if (!req || req.revision !== task.requirementRevision || approval.requirementRevision !== task.requirementRevision) {
|
||
throw new ServiceError('sansheng/approval-invalid', '需求版本与批准版本不一致,旧任务不能继续执行')
|
||
}
|
||
if (!task.approvalScope || task.approvalScope !== approval.scope) throw new ServiceError('sansheng/approval-invalid', '任务超出批准范围,不能报告')
|
||
}
|
||
if (task.status === 'done' && status !== 'done') throw new ServiceError('sansheng/invalid', '已完成的任务不能回退状态')
|
||
if ((status === 'done' || status === 'failed') && task.status === status && task.reportStatus === status) {
|
||
const parent = project.tasks.find(item => item.id === task.parentTaskId)
|
||
const summaryDelivery = parent?.stage === 'department_exec' && parent.deliveryState === 'pending'
|
||
? { taskId: parent.id, deliveryId: parent.deliveryId } : null
|
||
return { task: { ...task, late: false, duplicate: true }, summaryDelivery }
|
||
}
|
||
// 已取消任务的结果迟到:保留取消状态,但把真实结果留档,不假装没发生。
|
||
const late = task.status === 'cancelled'
|
||
if (!late) task.status = status
|
||
if (result) task.result = result
|
||
if (late || status === 'done' || status === 'failed') {
|
||
task.resultAt = Date.now()
|
||
task.resultSessionId = input.sessionId ?? null
|
||
task.reportStatus = late ? 'late' : status
|
||
task.lastTransitionId = randomUUID()
|
||
appendLeadReport(s, projectId, task, status === 'done' ? 'dept_done' : 'dept_failed', result || input.note || '')
|
||
} else {
|
||
task.reportStatus = 'running'
|
||
}
|
||
if (typeof input.note === 'string' && input.note.trim()) task.note = input.note.trim()
|
||
task.updatedAt = Date.now()
|
||
s.projects[projectId].updatedAt = Date.now()
|
||
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||
const parent = task.kind === 'execution' && !late && status !== 'running'
|
||
? project.tasks.find(item => item.id === task.parentTaskId) : null
|
||
const summaryDelivery = parent && readyForDepartmentSummary(project, parent)
|
||
? { taskId: parent.id, deliveryId: queueDelivery(parent, parent.status, task.updatedAt) } : null
|
||
if (summaryDelivery) parent.updatedAt = task.updatedAt
|
||
return { task: { ...task, late }, summaryDelivery }
|
||
})
|
||
if (summaryDelivery) {
|
||
try {
|
||
await this.taskDispatch(projectId, summaryDelivery.taskId, { deliveryId: summaryDelivery.deliveryId })
|
||
} catch (error) {
|
||
console.warn('[sansheng] 尚书汇总通知发送失败:', summaryDelivery.taskId, error?.message ?? error)
|
||
}
|
||
}
|
||
return { task: next, late: Boolean(next.late) }
|
||
}
|
||
|
||
async taskRevise(projectId, taskId, input = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
const goal = typeof input.goal === 'string' ? input.goal.trim() : undefined
|
||
const requirement = typeof input.requirement === 'string' ? input.requirement.trim() : undefined
|
||
if (goal === undefined && requirement === undefined) throw new ServiceError('sansheng/invalid', '修改要求需要提供 goal 或 requirement')
|
||
const next = await this.store.mutate(s => {
|
||
const task = s.projects[projectId].tasks.find(item => item.id === taskId)
|
||
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||
if (task.status === 'done' || task.status === 'cancelled') throw new ServiceError('sansheng/invalid', '已完成或已取消的任务不能修改要求;请新建任务保留历史结果')
|
||
if (goal !== undefined) task.goal = goal
|
||
if (requirement !== undefined) task.requirement = requirement
|
||
task.status = 'draft'
|
||
task.result = null
|
||
task.resultAt = null
|
||
task.resultSessionId = null
|
||
task.reportStatus = 'none'
|
||
voidDelivery(task)
|
||
task.updatedAt = Date.now()
|
||
s.projects[projectId].updatedAt = Date.now()
|
||
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||
return { ...task }
|
||
})
|
||
return { task: next }
|
||
}
|
||
|
||
async taskCancel(projectId, taskId) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
const next = await this.store.mutate(s => {
|
||
const target = s.projects[projectId].tasks.find(item => item.id === taskId)
|
||
if (!target) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||
if (target.status === 'done') throw new ServiceError('sansheng/invalid', '已完成的任务不能取消')
|
||
target.status = 'cancelled'
|
||
voidDelivery(target)
|
||
target.updatedAt = Date.now()
|
||
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||
return { ...target }
|
||
})
|
||
return { task: next }
|
||
}
|
||
|
||
async artifacts(projectId) {
|
||
await this.store.ensureLoaded()
|
||
const project = this.store.get(projectId)
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
return { artifacts: [...(project.artifacts ?? [])] }
|
||
}
|
||
|
||
async artifactAdd(projectId, input = {}) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
const title = String(input.title ?? '').trim()
|
||
if (!title) throw new ServiceError('sansheng/invalid', '成果名称不能为空')
|
||
const artifact = await this.store.mutate(s => {
|
||
const project = s.projects[projectId]
|
||
if (input.taskId && !(project.tasks ?? []).some(item => item.id === input.taskId)) {
|
||
throw new ServiceError('sansheng/invalid', `关联任务 ${input.taskId} 不存在`)
|
||
}
|
||
project.artifactSeq = (project.artifactSeq ?? 0) + 1
|
||
const next = emptyArtifact({
|
||
id: `artifact-${project.artifactSeq}`,
|
||
title,
|
||
path: typeof input.path === 'string' ? input.path : '',
|
||
summary: typeof input.summary === 'string' ? input.summary : '',
|
||
taskId: input.taskId ?? null,
|
||
})
|
||
if (!Array.isArray(project.artifacts)) project.artifacts = []
|
||
project.artifacts.push(next)
|
||
project.updatedAt = Date.now()
|
||
project.revision = (project.revision ?? 0) + 1
|
||
return { ...next }
|
||
})
|
||
return { artifact }
|
||
}
|
||
|
||
// ---- R-001:全局默认模型与同步 ----
|
||
async globalDefaults() {
|
||
await this.store.ensureLoaded()
|
||
if (!this.globalStore) throw new ServiceError('sansheng/global-setting-missing', '未配置全局默认模型存储')
|
||
await this.globalStore.ensureLoaded()
|
||
if (this.globalStore.exists && this._seedStatus?.status === 'unknown') this._seedStatus = { status: 'existing' }
|
||
return {
|
||
...this.globalStore.snapshot(),
|
||
path: this.globalStore.file,
|
||
seedStatus: this._seedStatus?.status ?? 'unknown',
|
||
candidates: this._seedStatus?.candidates ?? [],
|
||
sourceProjectId: this._seedStatus?.sourceProjectId ?? null,
|
||
}
|
||
}
|
||
|
||
async setGlobalDefault(seatId, model) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.globalStore) throw new ServiceError('sansheng/global-setting-missing', '未配置全局默认模型存储')
|
||
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', '未知席 ' + seatId)
|
||
const normalized = normalizeSelection(model)
|
||
if (!normalized) throw new ServiceError('sansheng/model-invalid', '全局默认模型不能为空;清除请使用 clearGlobalDefault')
|
||
await this.host.llm.resolveCallConfig(normalized)
|
||
await this.globalStore.setSeat(seatId, normalized)
|
||
return { globalDefaults: await this.globalDefaults(), ...(await this._syncInheritors(seatId)) }
|
||
}
|
||
|
||
async clearGlobalDefault(seatId) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.globalStore) throw new ServiceError('sansheng/global-setting-missing', '未配置全局默认模型存储')
|
||
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', '未知席 ' + seatId)
|
||
await this.globalStore.clearSeat(seatId)
|
||
return { globalDefaults: await this.globalDefaults(), ...(await this._syncInheritors(seatId)) }
|
||
}
|
||
|
||
async _syncInheritors(seatId) {
|
||
const targets = []
|
||
for (const project of this.store.list()) {
|
||
const seat = project.seats?.[seatId]
|
||
if (!seat || seat.model || seat.status !== 'bound' || !seat.sessionId) continue
|
||
targets.push(project.id)
|
||
}
|
||
const applied = []
|
||
const failed = []
|
||
const pending = []
|
||
const started = Date.now()
|
||
for (const projectId of targets) {
|
||
if (Date.now() - started > 5000) { pending.push(projectId); continue }
|
||
try {
|
||
const sync = await this.modelSync.syncSeat(projectId, seatId, 'global-default')
|
||
if (sync?.status === 'synced') applied.push(projectId)
|
||
else if (sync?.status === 'pending') pending.push(projectId)
|
||
else failed.push({ projectId, error: sync?.error ?? sync?.status })
|
||
} catch (error) { failed.push({ projectId, error: error?.message ?? String(error) }) }
|
||
}
|
||
return { applied, failed, pending }
|
||
}
|
||
|
||
async seedGlobalDefaults(projectId = undefined) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.globalStore) throw new ServiceError('sansheng/global-setting-missing', '未配置全局默认模型存储')
|
||
await this.globalStore.ensureLoaded()
|
||
if (this.globalStore.exists) {
|
||
this._seedStatus = { status: 'existing' }
|
||
return { seeded: false, status: 'existing', globalDefaults: await this.globalDefaults() }
|
||
}
|
||
const projects = this.store.list()
|
||
let target = null
|
||
let status = 'seeded'
|
||
let candidates = []
|
||
if (projectId === null) {
|
||
// 显式 null 表示创建一个十席均为 null 的空白基线,不自动选择 dsh-brain。
|
||
await this.globalStore.mutate(state => {
|
||
for (const seatId of SEAT_IDS) state.seats[seatId] = null
|
||
})
|
||
this._seedStatus = { status: 'seeded', sourceProjectId: null }
|
||
return { seeded: true, status: 'seeded', sourceProjectId: null, globalDefaults: await this.globalDefaults() }
|
||
}
|
||
if (projectId !== undefined) {
|
||
target = projects.find(project => project.id === projectId) ?? null
|
||
if (!target) throw new ServiceError('sansheng/not-found', '项目 ' + projectId + ' 不存在')
|
||
} else {
|
||
const byPath = projects.filter(project => {
|
||
if (typeof project.path !== 'string' || !project.path.trim()) return false
|
||
return basename(project.path).toLowerCase() === 'dsh-brain'
|
||
})
|
||
const byName = projects.filter(project => String(project.name ?? '').trim().toLowerCase() === 'dsh-brain')
|
||
if (byPath.length === 1) target = byPath[0]
|
||
else if (byPath.length > 1) { status = 'ambiguous-baseline'; candidates = byPath.map(p => ({ id: p.id, name: p.name, path: p.path })) }
|
||
else if (byName.length === 1) target = byName[0]
|
||
else if (byName.length > 1) { status = 'ambiguous-baseline'; candidates = byName.map(p => ({ id: p.id, name: p.name, path: p.path })) }
|
||
else status = 'missing-baseline'
|
||
}
|
||
if (!target) {
|
||
this._seedStatus = { status, candidates }
|
||
return { seeded: false, status, candidates, globalDefaults: await this.globalDefaults() }
|
||
}
|
||
await this.globalStore.mutate(state => {
|
||
for (const seatId of SEAT_IDS) state.seats[seatId] = target.seats?.[seatId]?.model ?? null
|
||
})
|
||
this._seedStatus = { status: 'seeded', sourceProjectId: target.id }
|
||
return { seeded: true, status: 'seeded', sourceProjectId: target.id, globalDefaults: await this.globalDefaults() }
|
||
}
|
||
|
||
async retrySeatModel(projectId, seatId) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', '项目 ' + projectId + ' 不存在')
|
||
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', '未知席 ' + seatId)
|
||
const sync = await this.modelSync.retrySeat(projectId, seatId)
|
||
return { sync, seat: seatView(seatId, this.store.get(projectId).seats[seatId], this._seatExtras(projectId, { [seatId]: sync })[seatId] ?? {}) }
|
||
}
|
||
|
||
async statusSnapshot(projectId) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.seatActivity) return { projects: {}, available: false }
|
||
if (projectId) {
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', '项目 ' + projectId + ' 不存在')
|
||
return { projectId, seats: await this.seatActivity.reconcileProject(projectId), available: true }
|
||
}
|
||
return { projects: await this.seatActivity.reconcileAll(), available: true }
|
||
}
|
||
|
||
async cards(projectId) {
|
||
await this.store.ensureLoaded()
|
||
const project = this.store.get(projectId)
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
return { cards: structuredClone(project.cards ?? []) }
|
||
}
|
||
|
||
async cardGet(cardId) {
|
||
await this.store.ensureLoaded()
|
||
const id = cleanText(cardId)
|
||
if (!id) throw new ServiceError('sansheng/card-invalid', '缺少 cardId')
|
||
for (const project of this.store.list()) {
|
||
const card = (project.cards ?? []).find(item => item.id === id)
|
||
if (card) return { ok: true, card: structuredClone(card) }
|
||
}
|
||
throw new ServiceError('sansheng/card-not-found', `卡片 ${id} 不存在`)
|
||
}
|
||
|
||
// 丞相只能为当前项目挂卡;审批卡的结论仍回到 approval-center 的同一个原生请求。
|
||
async cardCreate(projectId, input = {}, actor = {}) {
|
||
await this.store.ensureLoaded()
|
||
const project = this.store.get(projectId)
|
||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||
if (actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以挂卡片')
|
||
const lead = project.seats?.lead
|
||
if (lead?.status !== 'bound' || !lead.sessionId) throw new ServiceError('sansheng/seat-unbound', '丞相会话未就绪,不能挂卡片')
|
||
if (actor.sessionId && actor.sessionId !== lead.sessionId) throw new ServiceError('sansheng/forbidden', '丞相会话已变化')
|
||
const kind = cleanText(input.kind)
|
||
if (!CARD_KINDS.has(kind)) throw new ServiceError('sansheng/card-invalid', '卡片类型必须是 question 或 approval')
|
||
const title = cleanText(input.title)
|
||
const body = cleanText(input.body)
|
||
if (!title || title.length > 200) throw new ServiceError('sansheng/card-invalid', '卡片标题必须为 1 至 200 字符')
|
||
if (!body || body.length > 4000) throw new ServiceError('sansheng/card-invalid', '卡片正文必须为 1 至 4000 字符')
|
||
const options = normalizeCardOptions(input.options, kind)
|
||
const now = Date.now()
|
||
let approval = null
|
||
if (kind === 'approval') {
|
||
if (!this.approvalCenter) throw new ServiceError('sansheng/approval-degraded', '审批中心不可用,不能挂审批卡')
|
||
const approvalId = cleanText(input.approvalId)
|
||
if (!approvalId) throw new ServiceError('sansheng/card-invalid', '审批卡需要 approvalId')
|
||
approval = this.approvalCenter.list(projectId).find(item => item.id === approvalId) ?? null
|
||
if (!approval) throw new ServiceError('sansheng/approval-stale', '审批已处理或不存在,不能挂卡')
|
||
}
|
||
const card = {
|
||
id: cleanText(input.callId) || randomUUID(),
|
||
kind, title, body,
|
||
options,
|
||
approvalId: approval?.id ?? null,
|
||
seatId: approval?.seatId ?? null,
|
||
seatLabel: approval?.seatId ? (SEATS[approval.seatId]?.label ?? approval.seatId) : null,
|
||
tool: approval?.tool ?? null,
|
||
reason: approval?.reason ?? null,
|
||
detail: approval?.detail ?? null,
|
||
projectId,
|
||
sessionId: lead.sessionId,
|
||
status: 'pending',
|
||
answer: null,
|
||
answerLabel: null,
|
||
createdAt: now,
|
||
answeredAt: null,
|
||
}
|
||
await this.store.mutate(state => {
|
||
const current = state.projects[projectId]
|
||
if (!current) return
|
||
current.cards ??= []
|
||
current.cards.push(card)
|
||
capCards(current.cards)
|
||
current.updatedAt = now
|
||
current.revision = (current.revision ?? 0) + 1
|
||
})
|
||
return { ok: true, card: structuredClone(card) }
|
||
}
|
||
|
||
// 答题是普通用户消息(会唤醒丞相);审题结论只走 approval-center,不另造第二套决定。
|
||
async cardAnswer(cardId, choice, actor = {}) {
|
||
await this.store.ensureLoaded()
|
||
const id = cleanText(cardId)
|
||
const value = cleanText(choice)
|
||
if (!id || !value) throw new ServiceError('sansheng/card-invalid', '缺少 cardId 或选择')
|
||
let project = null
|
||
let card = null
|
||
for (const candidate of this.store.list()) {
|
||
const found = (candidate.cards ?? []).find(item => item.id === id)
|
||
if (found) { project = candidate; card = found; break }
|
||
}
|
||
if (!project || !card) throw new ServiceError('sansheng/card-not-found', `卡片 ${id} 不存在`)
|
||
if (card.status === 'answered') return { ok: true, duplicate: true, card: structuredClone(card) }
|
||
const option = card.options.find(item => item.value === value)
|
||
if (!option) throw new ServiceError('sansheng/card-invalid', '卡片没有这个选项')
|
||
const lead = project.seats?.lead
|
||
if (lead?.status !== 'bound' || !lead.sessionId) throw new ServiceError('sansheng/seat-unbound', '丞相会话未就绪,不能回答卡片')
|
||
if (actor.seatId && actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以回答卡片')
|
||
if (actor.sessionId && actor.sessionId !== lead.sessionId) throw new ServiceError('sansheng/forbidden', '丞相会话已变化')
|
||
if (card.kind === 'approval') {
|
||
if (!this.approvalCenter) throw new ServiceError('sansheng/approval-degraded', '审批中心不可用')
|
||
await this.approvalCenter.answer(card.approvalId, { projectId: project.id, seatId: 'lead', sessionId: lead.sessionId }, value)
|
||
} else {
|
||
const agent = this.host?.agents?.get?.(lead.sessionId)
|
||
if (!agent || typeof agent.followup !== 'function') throw new ServiceError('sansheng/card-session-unavailable', '丞相会话不可用,回答未送达')
|
||
const message = this.host?.createUserMessage
|
||
? await Promise.resolve(this.host.createUserMessage({
|
||
content: [{ type: 'text', text: `[卡片回答] ${card.title}\n用户选择:${option.label}` }],
|
||
source: { kind: 'sansheng-card-answer', cardId: card.id, choice: value },
|
||
}))
|
||
: { role: 'user', content: [{ type: 'text', text: `[卡片回答] ${card.title}\n用户选择:${option.label}` }], source: { kind: 'sansheng-card-answer', cardId: card.id, choice: value } }
|
||
await agent.followup(message)
|
||
}
|
||
const answered = await this.store.mutate(state => {
|
||
const current = state.projects[project.id]
|
||
const target = (current.cards ?? []).find(item => item.id === id)
|
||
if (!target) throw new ServiceError('sansheng/card-not-found', `卡片 ${id} 不存在`)
|
||
target.status = 'answered'
|
||
target.answer = value
|
||
target.answerLabel = option.label
|
||
target.answeredAt = Date.now()
|
||
current.updatedAt = target.answeredAt
|
||
current.revision = (current.revision ?? 0) + 1
|
||
return structuredClone(target)
|
||
})
|
||
return { ok: true, card: answered }
|
||
}
|
||
|
||
async leadReports(projectId) {
|
||
await this.store.ensureLoaded()
|
||
const project = this.store.get(projectId)
|
||
if (!project) throw new ServiceError('sansheng/not-found', '项目 ' + projectId + ' 不存在')
|
||
if (this.leadReporter) return { reports: await this.leadReporter.list(projectId) }
|
||
return { reports: structuredClone(project.leadReports ?? []) }
|
||
}
|
||
|
||
async _notifyLead(projectId, taskId, eventName, summary) {
|
||
if (!this.leadReporter) return null
|
||
try {
|
||
const project = this.store.get(projectId)
|
||
const task = project?.tasks?.find(item => item.id === taskId) ?? null
|
||
const report = await this.leadReporter.record(projectId, {
|
||
taskId,
|
||
transitionId: task?.lastTransitionId ?? (taskId + ':' + (task?.stage ?? '') + ':' + eventName),
|
||
event: eventName,
|
||
stage: task?.stage ?? null,
|
||
ownerSeatId: task?.ownerSeatId ?? null,
|
||
requirementId: task?.requirementId ?? null,
|
||
requirementRevision: task?.requirementRevision ?? null,
|
||
summary: String(summary ?? '').slice(0, 800),
|
||
textSnapshot: String(summary ?? '').slice(0, 800),
|
||
sourceKind: 'sansheng-report',
|
||
})
|
||
void this.leadReporter.flush(projectId).catch(error => console.warn('[sansheng] 回报发送失败:', error?.message ?? error))
|
||
return report
|
||
} catch (error) {
|
||
console.warn('[sansheng] 记录丞相回报失败:', error?.message ?? error)
|
||
return null
|
||
}
|
||
}
|
||
|
||
async approvals(projectId) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', '项目 ' + projectId + ' 不存在')
|
||
const status = this.approvalCenter?.status?.() ?? { available: false, degraded: true, pendingCount: 0, reason: 'approval-center-unavailable' }
|
||
return { approvals: status.available ? this.approvalCenter.list(projectId) : [], status }
|
||
}
|
||
|
||
async approvalAnswer(projectId, seatId, input = {}) {
|
||
await this.store.ensureLoaded()
|
||
const project = this.store.get(projectId)
|
||
if (!project) throw new ServiceError('sansheng/not-found', '项目 ' + projectId + ' 不存在')
|
||
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', '未知席 ' + seatId)
|
||
if (!this.approvalCenter) throw new ServiceError('sansheng/approval-degraded', '审批中心不可用,请使用原生审批卡')
|
||
const seat = project.seats?.[seatId]
|
||
const sessionId = cleanText(input.sessionId)
|
||
if (!sessionId || seat?.sessionId !== sessionId) throw new ServiceError('sansheng/approval-stale', '审批会话已变化,请刷新')
|
||
return this.approvalCenter.answer(input.id, { projectId, seatId, sessionId }, input.choice)
|
||
}
|
||
|
||
async modelStatus(projectId) {
|
||
await this.store.ensureLoaded()
|
||
if (!this.modelSync) return { projects: {}, globalDefaults: this.globalStore ? await this.globalDefaults() : null }
|
||
if (projectId) {
|
||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', '项目 ' + projectId + ' 不存在')
|
||
await this.modelSync.syncProject(projectId)
|
||
return { projectId, seats: this.modelSync.statusOf(projectId), globalDefaults: this.globalStore ? await this.globalDefaults() : null }
|
||
}
|
||
const projects = {}
|
||
for (const project of this.store.list()) {
|
||
try { await this.modelSync.syncProject(project.id); projects[project.id] = this.modelSync.statusOf(project.id) } catch (error) { projects[project.id] = { error: error?.message ?? String(error) } }
|
||
}
|
||
return { projects, globalDefaults: this.globalStore ? await this.globalDefaults() : null }
|
||
}
|
||
}
|