import { randomUUID, createHash } from 'node:crypto' import { SEAT_IDS, SEATS, SEAT_GROUPS } from '../shared/roles.js' import { emptyTask, emptyArtifact } from '../shared/schema.js' import { mergeProjectMemory, normalizeProjectMemory, renderProjectMemory } from '../shared/project-memory.js' import { applyModel, normalizeSelection } from './model.js' export class ServiceError extends Error { constructor(code, message) { super(message); this.name = 'ServiceError'; this.code = code } } export function seatView(seatId, seat) { 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, instructions: seat.instructions ?? '', error: seat.error ?? null, } } export function projectView(project) { return { revision: project.revision ?? 0, project: { id: project.id, name: project.name, workspaceId: project.workspaceId ?? null, path: project.path ?? null, status: project.status, seats: SEAT_IDS.map(id => seatView(id, project.seats[id])), groups: { lead: [...SEAT_GROUPS.lead], sansheng: [...SEAT_GROUPS.sansheng], liubu: [...SEAT_GROUPS.liubu], }, }, } } 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 return { providers, default: def && (def.provider || def.model) ? { provider: def.provider ?? null, model: def.model ?? null } : null, failures: catalog?.failures ?? catalog?.isolated ?? [], } } export class SanshengService { constructor({ store, host, provisioner }) { this.store = store this.host = host this.provisioner = provisioner } 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} 不存在`) await this.provisioner.ensureTitles(projectId) return projectView(this.store.get(projectId)) } 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} 不存在`) const seat = project.seats[seatId] let normalized let applied = null if (model !== undefined) { normalized = normalizeSelection(model) // 可能抛 sansheng/model-invalid if (seat.sessionId) applied = await applyModel(this.host, seat.sessionId, normalized) } if (instructions !== undefined && typeof instructions !== 'string') { throw new ServiceError('sansheng/invalid', 'instructions 必须是字符串') } 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 }) return { seat: seatView(seatId, this.store.get(projectId).seats[seatId]), 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 ?? [])] } } // 只读任务汇总:按状态/主责席位统计,并返回可追溯的任务明细。 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', })), } } // 轻量版尚书汇总:只把当前真实任务快照发给尚书汇总,不改变丞相直派流程,不创建新任务。 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?.prompt !== 'function') { throw new ServiceError('sansheng/delivery-failed', '宿主未提供 prompt 接口,无法发送尚书汇总请求') } 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') const requestId = randomUUID() try { await controller.prompt({ requestId, sessionId: seat.sessionId, mode: 'queue', content: [{ type: 'text', text }], }, new AbortController().signal) } catch (error) { throw new ServiceError('sansheng/delivery-failed', `尚书汇总请求发送失败:${error?.message ?? error}`) } return { ok: true, sessionId: seat.sessionId, summary } } 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 }) 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() 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} 不存在`) if (task.status === 'done' || task.status === 'cancelled') throw new ServiceError('sansheng/invalid', '已完成或已取消的任务不能再次派工;请新建任务保留历史结果') // 同一任务已成功投递时不重复刷屏;修改要求后由 taskRevise 显式 force 重发。 if (task.deliveryState === 'accepted' && task.status === 'dispatched' && !options.force) { return { task: { ...task }, delivered: true, duplicate: true } } 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}」的会话还没开启成功,请稍后重试`) } } const memory = normalizeProjectMemory(project.memory, projectId) const memoryText = renderProjectMemory(memory) const detail = [ `【任务】${task.title}`, task.goal ? `任务说明:${task.goal}` : '', task.requirement ? `用户原话:${task.requirement}` : '', ].filter(Boolean).join('\n') const text = [memoryText, detail].filter(Boolean).join('\n\n') const deliveryId = randomUUID() let delivered = false let note = '' const controller = this.host.sessionController if (typeof controller?.prompt === 'function') { try { await controller.prompt({ requestId: deliveryId, sessionId: seat.sessionId, mode: 'queue', content: [{ type: 'text', text }], }, new AbortController().signal) delivered = true } catch (error) { note = `发送失败:${error?.message ?? error}` } } else { note = '宿主未提供 prompt 接口,已记录待执行' } const activeDecisions = memory.decisions.filter(item => item.status === 'active').map(item => item.id) const next = await this.store.mutate(s => { const target = s.projects[projectId].tasks.find(item => item.id === taskId) target.status = delivered ? 'dispatched' : 'prepared' target.note = delivered ? '' : note target.sessionId = seat.sessionId target.dispatchedAt = Date.now() target.updatedAt = Date.now() target.contextRevision = memory.revision target.contextHash = memory.contentHash target.decisionIds = activeDecisions target.sourceRefs = memory.sources.slice(0, 20) target.deliveryId = deliveryId target.deliveryState = delivered ? 'accepted' : 'unknown' target.contextSyncState = delivered ? 'provided' : 'observed' s.projects[projectId].updatedAt = Date.now() s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1 return { ...target } }) return { task: next, delivered, duplicate: 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: { ...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 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 (input.seatId && task.ownerSeatId !== input.seatId) { throw new ServiceError('sansheng/forbidden', `只有主责部门 ${task.ownerSeatId} 可以报告这个任务`) } if (task.status === 'done' && status !== 'done') throw new ServiceError('sansheng/invalid', '已完成的任务不能回退状态') // 已取消任务的结果迟到:保留取消状态,但把真实结果留档,不假装没发生。 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 } 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 return { ...task, late } }) 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' task.deliveryState = 'none' 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' 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 } } }