332 lines
15 KiB
JavaScript
332 lines
15 KiB
JavaScript
import { randomUUID } from 'node:crypto'
|
||
import { clampInt, instructionsFor, ROOM_NOTICE } from './texts.js'
|
||
import { ROLE_COLOR, ROLE_IDS, ROLE_LABEL } from './roles.js'
|
||
|
||
function clip(text, max) {
|
||
const value = String(text ?? '').trim()
|
||
return value.length <= max ? value : value.slice(0, max - 1) + '…'
|
||
}
|
||
|
||
function projectId() {
|
||
return `prj-${randomUUID().replace(/-/g, '').slice(0, 8)}`
|
||
}
|
||
|
||
function botNameCandidates(base, projectName, id) {
|
||
const shortName = clip(projectName, 12)
|
||
return [...new Set([
|
||
base,
|
||
`${base}·${shortName}`.slice(0, 40),
|
||
`${base}·${shortName}·${id.slice(-4)}`.slice(0, 40),
|
||
`${base}·${id.slice(-6)}`.slice(0, 40),
|
||
])]
|
||
}
|
||
|
||
/** 全局 Bot 名唯一:先查已有名字,创建时再兜住宿主的重名异常。 */
|
||
async function createUniqueBot(rt, options, projectName, id) {
|
||
let lastError
|
||
for (const name of botNameCandidates(options.name, projectName, id)) {
|
||
try {
|
||
if (typeof rt.findBot === 'function' && rt.findBot(name)) continue
|
||
} catch { /* findBot 不可用时直接尝试创建 */ }
|
||
try {
|
||
return await rt.createBot({ ...options, name })
|
||
} catch (error) {
|
||
lastError = error
|
||
if (!/already exists|已存在|同名/i.test(String(error?.message ?? error))) throw error
|
||
}
|
||
}
|
||
throw lastError ?? new Error('无法为 Bot 找到唯一名字。')
|
||
}
|
||
|
||
async function uniqueRoomName(rt, dsbot, base) {
|
||
const desired = clip(base, 40)
|
||
const rooms = Object.values(dsbot.snapshot?.().rooms ?? {})
|
||
if (!rooms.some(room => room.name === desired)) return desired
|
||
for (let index = 2; index < 100; index += 1) {
|
||
const next = `${clip(base, 36)}·${index}`
|
||
if (!rooms.some(room => room.name === next)) return next
|
||
}
|
||
return `${clip(base, 32)}·${Date.now().toString(36).slice(-4)}`
|
||
}
|
||
|
||
function checkProjectName(store, name, selfId) {
|
||
const existing = Object.values(store.peek().projects).find(project => project.name === name && project.id !== selfId)
|
||
if (existing) return `项目「${name}」已经存在(${existing.id},群 ${existing.roomId});换一个名字。`
|
||
return undefined
|
||
}
|
||
|
||
/**
|
||
* 创建三省六部项目:三 Bot + 项目群(尚书 admin)+ 绑定。
|
||
* 账号/工作区只登记,不改宿主项目树;失败只清理本次新建对象。
|
||
*/
|
||
export async function provisionProject({ ctx, store, dsbot, args, actor }) {
|
||
if (actor?.kind === 'bot') return { ok: false, text: '只有用户能创建项目;Bot 在现有项目群里工作。' }
|
||
const rt = ctx.get('dsbot-runtime', false)
|
||
if (!rt || typeof rt.createBot !== 'function') {
|
||
return { ok: false, text: '没有找到 DS-Bot 运行时(dsbot-runtime 服务)。请先安装并启用 ds-bot,再重启 DSH;并用带 ctx.provide 的基线补丁(见 docs/p0/README.md)。' }
|
||
}
|
||
await rt.load()
|
||
|
||
const projectName = String(args.project ?? args.name ?? '').trim()
|
||
if (projectName === '') return { ok: false, text: '请提供 project(项目名)。' }
|
||
if (projectName.length > 40) return { ok: false, text: '项目名最多 40 个字符。' }
|
||
const nameError = checkProjectName(store, projectName)
|
||
if (nameError) return { ok: false, text: nameError }
|
||
|
||
const id = projectId()
|
||
const botNames = {
|
||
lead: String(args.leadName ?? '丞相').trim(),
|
||
shangshu: String(args.shangshuName ?? '尚书').trim(),
|
||
gongbu: String(args.gongbuName ?? '工部').trim(),
|
||
}
|
||
for (const role of ROLE_IDS) {
|
||
if (botNames[role] === '') return { ok: false, text: `缺少${ROLE_LABEL[role]}的名字。` }
|
||
if (botNames[role].length > 40) return { ok: false, text: `${ROLE_LABEL[role]}的名字最多 40 个字符。` }
|
||
}
|
||
if (new Set(ROLE_IDS.map(role => botNames[role])).size !== 3) return { ok: false, text: '三个 Bot 的名字必须不同。' }
|
||
|
||
const models = {}
|
||
for (const role of ROLE_IDS) {
|
||
const raw = args.models?.[role]
|
||
if (raw === undefined || raw === null || String(raw).trim() === '') continue
|
||
try {
|
||
models[role] = await rt.resolveModel(String(raw).trim())
|
||
} catch (error) {
|
||
return { ok: false, text: `${ROLE_LABEL[role]}的模型“${raw}”不可用:${error?.message ?? error}` }
|
||
}
|
||
}
|
||
|
||
const groupName = await uniqueRoomName(rt, dsbot, String(args.groupName ?? `${projectName} · 三省六部`))
|
||
const workDir = args.workDir === undefined || args.workDir === null || String(args.workDir).trim() === ''
|
||
? undefined
|
||
: String(args.workDir).trim()
|
||
const workspaceId = args.workspaceId === undefined || args.workspaceId === null || String(args.workspaceId).trim() === ''
|
||
? null
|
||
: String(args.workspaceId).trim()
|
||
const hostWorkspaceId = args.hostWorkspaceId === undefined || args.hostWorkspaceId === null || String(args.hostWorkspaceId).trim() === ''
|
||
? workspaceId
|
||
: String(args.hostWorkspaceId).trim()
|
||
const maxReworks = clampInt(args.maxReworks, 3, 1, 10)
|
||
|
||
const created = []
|
||
let room
|
||
try {
|
||
for (const role of ROLE_IDS) {
|
||
const bot = await createUniqueBot(rt, {
|
||
name: botNames[role],
|
||
role: ROLE_LABEL[role],
|
||
instructions: instructionsFor(role, projectName, groupName),
|
||
color: ROLE_COLOR[role],
|
||
brief: `「${projectName}」项目的${ROLE_LABEL[role]}。`,
|
||
model: models[role],
|
||
...(workDir === undefined ? {} : { workDir }),
|
||
}, projectName, id)
|
||
created.push(bot.id)
|
||
}
|
||
room = await rt.createRoom({
|
||
members: created,
|
||
name: groupName,
|
||
admin: created[1],
|
||
mode: 'admin',
|
||
createdBy: null,
|
||
notice: ROOM_NOTICE,
|
||
})
|
||
} catch (error) {
|
||
for (const botId of created) {
|
||
try { await rt.deleteBot(botId) } catch { /* 回滚尽力而为 */ }
|
||
}
|
||
return { ok: false, text: `创建失败:${error?.message ?? error}。已回滚本次新建的 Bot。` }
|
||
}
|
||
|
||
const project = {
|
||
id,
|
||
schemaVersion: 3,
|
||
name: projectName,
|
||
workspaceId,
|
||
hostWorkspaceId,
|
||
projectTreeId: args.projectTreeId ?? null,
|
||
workDir: workDir ?? null,
|
||
roomId: room.id,
|
||
bots: { lead: created[0], shangshu: created[1], gongbu: created[2] },
|
||
models,
|
||
maxReworks,
|
||
autoRework: args.autoRework !== false,
|
||
delivery: { include: Array.isArray(args.include) ? args.include : [], exclude: Array.isArray(args.exclude) ? args.exclude : [] },
|
||
createdAt: Date.now(),
|
||
}
|
||
try {
|
||
await store.saveProject(project)
|
||
} catch (error) {
|
||
if (typeof rt.deleteRoom === 'function') {
|
||
try { await rt.deleteRoom(room.id) } catch { /* 回滚尽力而为 */ }
|
||
}
|
||
for (const botId of created) {
|
||
try { await rt.deleteBot(botId) } catch { /* 回滚尽力而为 */ }
|
||
}
|
||
return { ok: false, text: `保存项目绑定失败:${error?.message ?? error}。已回滚群与 Bot。` }
|
||
}
|
||
|
||
const actualNames = await Promise.all(created.map(async botId => rt.botOf?.(botId)?.name ?? botId))
|
||
return {
|
||
ok: true,
|
||
project,
|
||
text: [
|
||
`已创建项目「${projectName}」${project.id}。`,
|
||
`群「${room.name}」:管理员=尚书 ${actualNames[1] ?? botNames.shangshu}。`,
|
||
`Bot:丞相 ${actualNames[0] ?? botNames.lead} / 尚书 ${actualNames[1] ?? botNames.shangshu} / 工部 ${actualNames[2] ?? botNames.gongbu}。`,
|
||
`模型:${ROLE_IDS.map(role => `${ROLE_LABEL[role]}=${models[role] ?? 'DS Bot 默认'}`).join(',')}。`,
|
||
`工作目录:${workDir ?? '未设置(成果快照只按项目记账)'}${workspaceId ? `;工作区 ${workspaceId}` : ''}。`,
|
||
`返工预算 ${maxReworks} 轮(按整个目标累计)。`,
|
||
'下一步:在项目群发需求,让丞相对齐目标;尚书用 group_goal 起草/启动,并按阶段 @工部 派工。',
|
||
].join('\n'),
|
||
}
|
||
}
|
||
|
||
/** 把已有群绑定为项目:角色互异、群管理员正确、Bot/群唯一。 */
|
||
export async function bindProject({ store, dsbot, rt, args }) {
|
||
const roomRef = String(args.room ?? '').trim()
|
||
if (roomRef === '') return { ok: false, text: '请提供 room(项目群名或 id)。' }
|
||
const state = dsbot.snapshot()
|
||
const rooms = Object.values(state.rooms ?? {})
|
||
const unquote = text => String(text ?? '').trim().replace(/^["'“”「『《]+|["'“”」』》]+$/g, '').trim()
|
||
const room = rooms.find(item => item.id === roomRef)
|
||
?? rooms.find(item => unquote(item.name) === unquote(roomRef))
|
||
?? rooms.find(item => unquote(item.name).toLocaleLowerCase() === unquote(roomRef).toLocaleLowerCase())
|
||
if (!room) return { ok: false, text: `找不到群「${roomRef}」。确认群名,或先在 DS Bot 里建群。` }
|
||
const existing = store.projectByRoom(room.id)
|
||
if (existing) return { ok: false, text: `群「${room.name}」已绑定项目「${existing.name}」(${existing.id})。` }
|
||
|
||
const findBot = ref => {
|
||
const key = String(ref ?? '').trim()
|
||
if (key === '') return undefined
|
||
return state.bots?.[key] ?? dsbot.botByName(key)
|
||
}
|
||
const bots = {}
|
||
for (const role of ROLE_IDS) {
|
||
let bot = findBot(args[role])
|
||
if (!bot) {
|
||
bot = Object.values(state.bots ?? {}).find(item =>
|
||
(room.members ?? []).includes(item.id) && (item.role === ROLE_LABEL[role] || item.name === ROLE_LABEL[role]))
|
||
}
|
||
if (!bot) return { ok: false, text: `没找到${ROLE_LABEL[role]} Bot:请用 ${role} 参数给名字或 id,或先把它加入群。` }
|
||
if (!(room.members ?? []).includes(bot.id)) return { ok: false, text: `${ROLE_LABEL[role]}「${bot.name}」不在群「${room.name}」里。` }
|
||
const bound = store.projectsByBot(bot.id)
|
||
if (bound.length > 0) return { ok: false, text: `Bot「${bot.name}」已属于项目「${bound[0].name}」(${bound[0].id}),一个 Bot 只能属于一个项目。` }
|
||
bots[role] = bot.id
|
||
}
|
||
if (new Set(Object.values(bots)).size !== 3) return { ok: false, text: '丞相/尚书/工部必须是三个不同的 Bot。' }
|
||
if (room.admin !== bots.shangshu) {
|
||
const admin = room.admin ? state.bots?.[room.admin]?.name ?? room.admin : '无'
|
||
return { ok: false, text: `群管理员当前是 ${admin},必须是尚书。先在 DS Bot 的群设置里把管理员改成${ROLE_LABEL.shangshu},再绑定。` }
|
||
}
|
||
|
||
const projectName = String(args.project ?? room.name).trim().slice(0, 40)
|
||
const nameError = checkProjectName(store, projectName)
|
||
if (nameError) return { ok: false, text: nameError }
|
||
const workDir = args.workDir === undefined || args.workDir === null || String(args.workDir).trim() === ''
|
||
? null
|
||
: String(args.workDir).trim()
|
||
// 绑定已有 Bot 时把工作根落到 Bot 的会话上,文件边界才真正生效(不能只写提示词)。
|
||
if (workDir && rt && typeof rt.updateBot === 'function') {
|
||
for (const role of ROLE_IDS) {
|
||
try {
|
||
await rt.updateBot(bots[role], { workDir }, undefined)
|
||
} catch (error) {
|
||
return { ok: false, text: `设置${ROLE_LABEL[role]}工作目录失败:${error?.message ?? error}` }
|
||
}
|
||
}
|
||
}
|
||
const id = projectId()
|
||
const project = {
|
||
id,
|
||
schemaVersion: 3,
|
||
name: projectName,
|
||
workspaceId: args.workspaceId === undefined || args.workspaceId === null ? null : String(args.workspaceId),
|
||
hostWorkspaceId: args.hostWorkspaceId === undefined || args.hostWorkspaceId === null ? null : String(args.hostWorkspaceId),
|
||
projectTreeId: args.projectTreeId ?? null,
|
||
workDir,
|
||
roomId: room.id,
|
||
bots,
|
||
models: args.models ?? {},
|
||
maxReworks: clampInt(args.maxReworks, 3, 1, 10),
|
||
autoRework: args.autoRework !== false,
|
||
delivery: { include: Array.isArray(args.include) ? args.include : [], exclude: Array.isArray(args.exclude) ? args.exclude : [] },
|
||
createdAt: Date.now(),
|
||
}
|
||
try {
|
||
await store.saveProject(project)
|
||
} catch (error) {
|
||
return { ok: false, text: `绑定失败:${error?.message ?? error}` }
|
||
}
|
||
return {
|
||
ok: true,
|
||
project,
|
||
text: [
|
||
`已把群「${room.name}」绑定为项目「${project.name}」(${project.id})。`,
|
||
`丞相=${state.bots?.[bots.lead]?.name},尚书=${state.bots?.[bots.shangshu]?.name}(管理员),工部=${state.bots?.[bots.gongbu]?.name}。`,
|
||
'从下一次 group_goal 起,角色、审查记录与返工预算开始生效。',
|
||
].join('\n'),
|
||
}
|
||
}
|
||
|
||
/** 只影响本项目的模型/预算/自动返工/交付范围配置。 */
|
||
export async function updateProjectConfig({ ctx, store, args }) {
|
||
const project = store.resolveProject(args.project ?? args.projectId)
|
||
if (!project) return { ok: false, text: `找不到项目「${args.project ?? args.projectId ?? ''}」。` }
|
||
const rt = ctx.get('dsbot-runtime', false)
|
||
const patch = {}
|
||
const changed = []
|
||
|
||
if (args.models && typeof args.models === 'object') {
|
||
const models = { ...project.models }
|
||
const applied = []
|
||
for (const role of ROLE_IDS) {
|
||
const raw = args.models[role]
|
||
if (raw === undefined || raw === null || String(raw).trim() === '') continue
|
||
let resolved = String(raw).trim()
|
||
try {
|
||
if (rt && typeof rt.resolveModel === 'function') resolved = await rt.resolveModel(resolved)
|
||
} catch (error) {
|
||
return { ok: false, text: `${ROLE_LABEL[role]}的模型“${raw}”不可用:${error?.message ?? error}` }
|
||
}
|
||
const botId = project.bots?.[role]
|
||
if (rt && typeof rt.updateBot === 'function' && botId) {
|
||
try {
|
||
await rt.updateBot(botId, { model: resolved }, undefined)
|
||
} catch (error) {
|
||
for (const undo of applied) {
|
||
try { await rt.updateBot(undo.botId, { model: undo.previous }, undefined) } catch { /* 尽力回滚 */ }
|
||
}
|
||
return { ok: false, text: `更新${ROLE_LABEL[role]}模型失败:${error?.message ?? error}` }
|
||
}
|
||
applied.push({ botId, previous: project.models?.[role] ?? null })
|
||
}
|
||
models[role] = resolved
|
||
changed.push(`${ROLE_LABEL[role]}模型=${resolved}`)
|
||
}
|
||
patch.models = models
|
||
}
|
||
if (args.maxReworks !== undefined) {
|
||
patch.maxReworks = clampInt(args.maxReworks, project.maxReworks ?? 3, 1, 10)
|
||
changed.push(`返工预算=${patch.maxReworks}`)
|
||
}
|
||
if (args.autoRework !== undefined) {
|
||
patch.autoRework = args.autoRework !== false
|
||
changed.push(`自动返工=${patch.autoRework ? '开' : '关'}`)
|
||
}
|
||
if (args.include !== undefined || args.exclude !== undefined) {
|
||
patch.delivery = {
|
||
include: Array.isArray(args.include) ? args.include : project.delivery?.include ?? [],
|
||
exclude: Array.isArray(args.exclude) ? args.exclude : project.delivery?.exclude ?? [],
|
||
}
|
||
changed.push('交付范围已更新')
|
||
}
|
||
if (changed.length === 0) return { ok: false, text: '没有要修改的配置。可改 models / maxReworks / autoRework / include / exclude。' }
|
||
try {
|
||
await store.updateProject(project.id, patch)
|
||
} catch (error) {
|
||
return { ok: false, text: `保存配置失败:${error?.message ?? error}` }
|
||
}
|
||
return { ok: true, text: `已更新项目「${project.name}」(${project.id}):${changed.join(',')}。只影响本项目,其他项目与正在运行的会话不受影响。` }
|
||
}
|