dsh-sansheng-liubu/panel/lib/model.js

249 lines
9.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 三省六部:纯逻辑层(不依赖 React / DOM),便于在 node --test 中直接验证。
// 这些函数只做数据投影与协议拼装:成员编排、状态归并、下旨文本、模型目录展开。
export const ROLE_IDS = Object.freeze(['lead', 'zhongshu', 'menxia', 'shangshu', 'gongbu', 'libu', 'bingbu'])
export const ROLE_LABELS = Object.freeze({
lead: '丞相',
zhongshu: '中书省',
menxia: '门下省',
shangshu: '尚书省',
gongbu: '工部',
libu: '礼部',
bingbu: '兵部',
})
export const ROLE_MARKS = Object.freeze({
lead: '丞',
zhongshu: '中',
menxia: '门',
shangshu: '尚',
gongbu: '工',
libu: '礼',
bingbu: '兵',
})
export const ROLE_DUTIES = Object.freeze({
lead: '统筹全局,向用户汇报,最终交付',
zhongshu: '拟案规划,拆解任务与验收标准',
menxia: '审议准奏与交付验收,可否决',
shangshu: '派工调度,合成各部门成果',
gongbu: '编码与工程实现',
libu: '文档、汇报与可视化产出',
bingbu: '调试、测试与问题定位',
})
/** 朝堂图布局:丞相居中在顶,三省为中层(左中书、中尚书、右门下),六部直隶尚书。 */
export const LAYOUT = Object.freeze({
lead: { row: 0, column: 'lead' },
zhongshu: { row: 1, column: 'zhongshu' },
shangshu: { row: 1, column: 'shangshu' },
menxia: { row: 1, column: 'menxia' },
gongbu: { row: 2, column: 'gongbu' },
libu: { row: 2, column: 'libu' },
bingbu: { row: 2, column: 'bingbu' },
})
export const STATUS_LABELS = Object.freeze({
running: '运行中',
inactive: '空闲',
provisioning: '创建中',
failed: '失败',
absent: '未设官',
})
export const TASK_STATUS_LABELS = Object.freeze({
pending: '待办',
in_progress: '执行中',
completed: '已完成',
})
/** 把 agentTeam 投影按官职编排成固定七席,缺员以 absent 占位,保证图结构稳定。 */
export function arrangeRoster(team) {
const members = Array.isArray(team?.members) ? team.members : []
const byRole = new Map()
for (const member of members) {
if (member?.name === undefined) continue
byRole.set(member.name, member)
}
return ROLE_IDS.map((role) => {
const member = byRole.get(role)
return {
role,
label: ROLE_LABELS[role],
mark: ROLE_MARKS[role],
duty: ROLE_DUTIES[role],
layout: LAYOUT[role],
id: member?.id,
member,
present: member !== undefined,
}
})
}
/** 运行状态(会话是否在跑)与任务状态(共享任务)必须分开表达,不能互相覆盖。 */
export function memberStatus(member, running, summaryRunning) {
if (member === undefined) return 'absent'
if (member.phase !== undefined && member.phase !== 'active') return member.phase
return running === true || summaryRunning === true ? 'running' : 'inactive'
}
export function roleLabel(role) {
return ROLE_LABELS[role] ?? '成员'
}
export function roleMark(role) {
return ROLE_MARKS[role] ?? '员'
}
export function modelLabel(model) {
if (typeof model === 'string') return model
if (!model || typeof model !== 'object') return ''
if (typeof model.name === 'string') return model.name
if (typeof model.model === 'string') return model.model
if (typeof model.id === 'string') return model.id
return ''
}
export function effortLabel(effort) {
if (typeof effort !== 'string') return ''
const table = { minimal: '极低', low: '低', medium: '中', high: '高', max: '最高', xhigh: '极高' }
return table[effort] ?? effort
}
export function taskBuckets(team) {
const tasks = Array.isArray(team?.tasks) ? team.tasks : []
const buckets = { pending: [], in_progress: [], completed: [] }
for (const task of tasks) {
const key = task?.status
if (key === 'pending' || key === 'in_progress' || key === 'completed') buckets[key].push(task)
else buckets.pending.push(task)
}
return buckets
}
export function tasksOfRole(team, role) {
const tasks = Array.isArray(team?.tasks) ? team.tasks : []
return tasks.filter((task) => task?.ownerName === role || task?.ownerName === roleLabel(role))
}
/** 所选成员的运行状态 + 任务状态摘要,供图下配置区展示。 */
export function statusSummary(seat, team, running, summaryRunning) {
const status = memberStatus(seat?.member, running, summaryRunning)
const owned = seat?.role === undefined ? [] : tasksOfRole(team, seat.role)
const buckets = taskBuckets({ tasks: owned })
return {
status,
statusLabel: STATUS_LABELS[status] ?? status,
owned,
runningCount: buckets.in_progress.length,
pendingCount: buckets.pending.length,
completedCount: buckets.completed.length,
}
}
/** 模型目录展开成扁平选项:每组 id 即 provider,行 id 为 provider/model。 */
export function modelOptions(catalog) {
const options = []
const groups = Array.isArray(catalog?.groups) ? catalog.groups : []
for (const group of groups) {
const provider = group?.id ?? group?.provider
for (const model of Array.isArray(group?.models) ? group.models : []) {
if (!provider || !model?.id) continue
const efforts = Array.isArray(model.reasoning?.efforts)
? model.reasoning.efforts.map((effort) => ({ id: effort.id, name: effort.name ?? effortLabel(effort.id) }))
: []
options.push({
provider,
model: model.id,
rowId: `${provider}/${model.id}`,
label: model.name ?? model.id,
efforts,
defaultEffort: model.reasoning?.defaultEffort,
})
}
}
return options
}
export function findModelOption(options, current) {
if (!current?.provider || !current?.model) return undefined
return options.find((option) => option.provider === current.provider && option.model === current.model)
}
/**
* 下旨文本:把用户输入包装成明确的“切到某部门执行”指令,并附带当前朝堂上下文。
* 部门会话是受控子会话,直接投递文本仍受角色提示词约束。
*/
export function decreeText(role, text, team) {
const body = String(text ?? '').trim()
if (body === '') return ''
const buckets = taskBuckets(team)
const active = buckets.in_progress.map((task) => task.subject ?? task.title ?? task.id).filter(Boolean)
const head = `【丞相下旨 · ${roleLabel(role)}】`
const context = active.length > 0 ? `\n当前在办:${active.join(';')}` : ''
return `${head}\n${body}${context}`
}
/** 交付物“部分 → 主责部门”清单:把共享任务按负责人归组成部门小结。 */
export function deliverySummary(team) {
const tasks = Array.isArray(team?.tasks) ? team.tasks : []
const byRole = new Map()
for (const task of tasks) {
const owner = task?.ownerName ?? 'lead'
const key = ROLE_IDS.includes(owner) ? owner : 'lead'
if (!byRole.has(key)) byRole.set(key, [])
byRole.get(key).push(task)
}
return ROLE_IDS.filter((role) => byRole.has(role)).map((role) => ({
role,
label: ROLE_LABELS[role],
tasks: byRole.get(role),
completed: byRole.get(role).filter((task) => task?.status === 'completed').length,
}))
}
export function shortText(value, limit = 120) {
const text = String(value ?? '').replace(/\s+/g, ' ').trim()
return text.length <= limit ? text : `${text.slice(0, limit - 1)}…`
}
/** 从 chat 快照里取最后一条用户指令与最后一条助手文本,用于卡片上的“最近动静”。 */
export function lastExchange(snapshot) {
if (!snapshot || typeof snapshot !== 'object') return { lastUser: '', lastAssistant: '' }
const nodes = []
const values = typeof snapshot.nodes?.values === 'function' ? snapshot.nodes.values() : []
for (const key of Array.isArray(values) ? values : Array.from(values ?? [])) {
const node = typeof snapshot.nodes?.get === 'function' ? snapshot.nodes.get(key) : undefined
if (node !== undefined) nodes.push(node)
}
let lastUser = ''
let lastAssistant = ''
for (const node of nodes) {
if (node.kind === 'user') {
const text = (Array.isArray(node.data?.content) ? node.data.content : [])
.filter((block) => block?.type === 'text')
.map((block) => block.text)
.join('\n')
if (text.trim() !== '') lastUser = shortText(text, 160)
} else if (node.kind === 'assistant-step') {
const text = (Array.isArray(node.data?.blocks) ? node.data.blocks : [])
.filter((block) => block?.kind === 'text')
.map((block) => block.text)
.join('\n')
if (text.trim() !== '') lastAssistant = shortText(text, 200)
}
}
return { lastUser, lastAssistant }
}
/** 校验一次模型切换请求;子代理会话不允许改模型,返回原因便于提示。 */
export function modelSwitchPlan(current, next, addressesSubagent) {
if (addressesSubagent === true) return { ok: false, reason: '子会话不能单独更换模型,请在丞相会话或新建会话时设置' }
if (!next?.provider || !next?.model) return { ok: false, reason: '未选择模型' }
const same = current?.provider === next.provider && current?.model === next.model
const effort = next.reasoningEffort ?? undefined
if (same && (current?.reasoningEffort ?? undefined) === effort) return { ok: false, reason: '与当前设置相同' }
return { ok: true, payload: { provider: next.provider, model: next.model, ...(effort === undefined ? {} : { reasoningEffort: effort }) } }
}