333 lines
14 KiB
JavaScript
333 lines
14 KiB
JavaScript
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,
|
|
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],
|
|
},
|
|
},
|
|
}
|
|
}
|
|
|
|
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.reasoningEffort ?? m.reasoning) : undefined
|
|
entry.models.push(effort ? { model: modelId, reasoningEffort: effort } : { 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,
|
|
})
|
|
})
|
|
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} 不存在`)
|
|
return projectView(p)
|
|
}
|
|
|
|
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 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 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 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, 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) {
|
|
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', '已完成或已取消的任务不能再次派工')
|
|
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 text = [memoryText, `【任务】${task.title}${task.goal ? '\n' + task.goal : ''}`].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 }
|
|
}
|
|
|
|
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 }
|
|
}
|
|
}
|