Add Sansheng fast lane and lead assistants
This commit is contained in:
parent
2dac6ce609
commit
5e73255b49
|
|
@ -144,6 +144,12 @@ var PRESET_OPTIONS = Object.freeze([
|
||||||
label: "OPS PTC(代码批量)",
|
label: "OPS PTC(代码批量)",
|
||||||
shortLabel: "PTC",
|
shortLabel: "PTC",
|
||||||
description: "通过 run_code 沙盒批量并发调用工具,适合高频读写文件与工程检查"
|
description: "通过 run_code 沙盒批量并发调用工具,适合高频读写文件与工程检查"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: "minimal",
|
||||||
|
label: "极简模式(轻量直调)",
|
||||||
|
shortLabel: "极简",
|
||||||
|
description: "提供终端、图片读取和上下文压缩,适合轻量对话和简单任务"
|
||||||
}
|
}
|
||||||
]);
|
]);
|
||||||
var PRESET_LABELS = new Map(PRESET_OPTIONS.map((item) => [item.value, item.label]));
|
var PRESET_LABELS = new Map(PRESET_OPTIONS.map((item) => [item.value, item.label]));
|
||||||
|
|
@ -171,7 +177,7 @@ function presetSourceLabel(source) {
|
||||||
return PRESET_SOURCE_LABELS[source] ?? "跟随宿主默认";
|
return PRESET_SOURCE_LABELS[source] ?? "跟随宿主默认";
|
||||||
}
|
}
|
||||||
function normalizePresetValue(value) {
|
function normalizePresetValue(value) {
|
||||||
return value === "standard" || value === "ops-ptc" ? value : "";
|
return PRESET_LABELS.has(value) ? value : "";
|
||||||
}
|
}
|
||||||
function describeSeatPreset(seatId, rec, draftEntry, project) {
|
function describeSeatPreset(seatId, rec, draftEntry, project) {
|
||||||
const recommendedPreset = recommendedPresetForSeat(seatId);
|
const recommendedPreset = recommendedPresetForSeat(seatId);
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,9 @@ export function apply(ctx, config = {}) {
|
||||||
console.warn(`sansheng: ${error?.message ?? error}`)
|
console.warn(`sansheng: ${error?.message ?? error}`)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
let assistantReady = () => false
|
||||||
const host = {
|
const host = {
|
||||||
|
isLeadAssistantReady: (agent, role) => typeof ctx.systemPrompt.context === 'function' && assistantReady(agent, role),
|
||||||
workspaceRegistry: ctx.workspaceRegistry,
|
workspaceRegistry: ctx.workspaceRegistry,
|
||||||
sessionController: ctx.sessionController,
|
sessionController: ctx.sessionController,
|
||||||
agents: ctx.agents,
|
agents: ctx.agents,
|
||||||
|
|
@ -46,7 +48,8 @@ export function apply(ctx, config = {}) {
|
||||||
createUserMessage: ({ content, source }) => ({ id: randomUUID(), role: 'user', content, source }),
|
createUserMessage: ({ content, source }) => ({ id: randomUUID(), role: 'user', content, source }),
|
||||||
}
|
}
|
||||||
const modelSync = createModelSync({ store, globalStore, host, normalizeCatalog })
|
const modelSync = createModelSync({ store, globalStore, host, normalizeCatalog })
|
||||||
const leadReporter = createLeadReporter({ store, host })
|
const provisioner = createProvisioner({ store, host, globalStore, modelSync, leadAssistantModel: config.leadAssistantModel })
|
||||||
|
const leadReporter = createLeadReporter({ store, host, ensureLeadAssistant: provisioner.ensureLeadAssistant })
|
||||||
const approvalCenter = createApprovalCenter({
|
const approvalCenter = createApprovalCenter({
|
||||||
ctx,
|
ctx,
|
||||||
resolveSeatBySessionId: sessionId => {
|
resolveSeatBySessionId: sessionId => {
|
||||||
|
|
@ -62,6 +65,7 @@ export function apply(ctx, config = {}) {
|
||||||
taskId: null,
|
taskId: null,
|
||||||
transitionId: 'approval:' + entry.id,
|
transitionId: 'approval:' + entry.id,
|
||||||
event: 'approval_request',
|
event: 'approval_request',
|
||||||
|
approvalId: entry.id,
|
||||||
stage: null,
|
stage: null,
|
||||||
ownerSeatId: entry.seatId,
|
ownerSeatId: entry.seatId,
|
||||||
summary,
|
summary,
|
||||||
|
|
@ -74,7 +78,6 @@ export function apply(ctx, config = {}) {
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
const seatActivity = createSeatActivity({ store, host, approvalCenter })
|
const seatActivity = createSeatActivity({ store, host, approvalCenter })
|
||||||
const provisioner = createProvisioner({ store, host, globalStore, modelSync })
|
|
||||||
const seatDelivery = createSeatDelivery({ host })
|
const seatDelivery = createSeatDelivery({ host })
|
||||||
const service = new SanshengService({ store, host, provisioner, globalStore, modelSync, seatActivity, leadReporter, approvalCenter, seatDelivery })
|
const service = new SanshengService({ store, host, provisioner, globalStore, modelSync, seatActivity, leadReporter, approvalCenter, seatDelivery })
|
||||||
const handle = createApiHandler(service)
|
const handle = createApiHandler(service)
|
||||||
|
|
@ -96,8 +99,9 @@ export function apply(ctx, config = {}) {
|
||||||
ctx.effect(() => installPromptSection(ctx, { store }), 'sansheng: prompt section')
|
ctx.effect(() => installPromptSection(ctx, { store }), 'sansheng: prompt section')
|
||||||
ctx.effect(() => {
|
ctx.effect(() => {
|
||||||
const turnCommands = createTurnCommands(ctx, store)
|
const turnCommands = createTurnCommands(ctx, store)
|
||||||
const disposeTools = installSeatTools(ctx, { store, service, provisioner, turnCommands })
|
const disposeTools = installSeatTools(ctx, { store, service, provisioner, turnCommands, host, leadReporter })
|
||||||
return () => { disposeTools(); turnCommands.dispose() }
|
assistantReady = disposeTools.assistantReady
|
||||||
|
return () => { assistantReady = () => false; disposeTools(); turnCommands.dispose() }
|
||||||
}, 'sansheng: seat tools')
|
}, 'sansheng: seat tools')
|
||||||
|
|
||||||
// 复用宿主共享 /api 通道;浏览器带会话 Cookie 认证。
|
// 复用宿主共享 /api 通道;浏览器带会话 Cookie 认证。
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,12 @@ export const PRESET_OPTIONS = Object.freeze([
|
||||||
shortLabel: 'PTC',
|
shortLabel: 'PTC',
|
||||||
description: '通过 run_code 沙盒批量并发调用工具,适合高频读写文件与工程检查',
|
description: '通过 run_code 沙盒批量并发调用工具,适合高频读写文件与工程检查',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
value: 'minimal',
|
||||||
|
label: '极简模式(轻量直调)',
|
||||||
|
shortLabel: '极简',
|
||||||
|
description: '提供终端、图片读取和上下文压缩,适合轻量对话和简单任务',
|
||||||
|
},
|
||||||
])
|
])
|
||||||
|
|
||||||
const PRESET_LABELS = new Map(PRESET_OPTIONS.map(item => [item.value, item.label]))
|
const PRESET_LABELS = new Map(PRESET_OPTIONS.map(item => [item.value, item.label]))
|
||||||
|
|
@ -53,7 +59,7 @@ export function presetSourceLabel(source) {
|
||||||
}
|
}
|
||||||
|
|
||||||
export function normalizePresetValue(value) {
|
export function normalizePresetValue(value) {
|
||||||
return value === 'standard' || value === 'ops-ptc' ? value : ''
|
return PRESET_LABELS.has(value) ? value : ''
|
||||||
}
|
}
|
||||||
|
|
||||||
export function describeSeatPreset(seatId, rec, draftEntry, project) {
|
export function describeSeatPreset(seatId, rec, draftEntry, project) {
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,105 @@
|
||||||
|
import { randomUUID } from 'node:crypto'
|
||||||
|
import { cleanText } from '../shared/utils.js'
|
||||||
|
|
||||||
|
const GRANT_TTL_MS = 15 * 60_000
|
||||||
|
|
||||||
|
export function intakeRequirementIds(text) {
|
||||||
|
const ids = Array.from(text.matchAll(/\bR-(\d{3,})\b|(?:发布|下派|取消|撤销|撤回)\s*(\d{3,})/gi), match => 'R-' + (match[1] ?? match[2]))
|
||||||
|
return [...new Set(ids)]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function explicitIntakeIntent(text, operation) {
|
||||||
|
const command = cleanText(text).replace(/「[^」]*」|“[^”]*”|"[^"]*"|`[^`]*`/g, '')
|
||||||
|
if (operation === 'cancel') {
|
||||||
|
return /^(?:请|帮我|麻烦)?(?:取消|撤销|撤回)(?:需求)?/.test(command) && !/[??]|(?:如何|怎么|能否|是否)/.test(command)
|
||||||
|
}
|
||||||
|
if (/[??]|(?:如何|怎么|能否|是否|能不能)|(?:不要|不能|别|暂不|先不|不急着)(?:再|直接)?(?:发布|下派|安排|执行|开工|做)/.test(command)) return false
|
||||||
|
return /^(?:请|帮我|麻烦|劳烦|现在|可以|同意|确认|就|先)*(?:发布|下派|安排下去|执行|开工|直接(?:派|让|给|交|做)|走(?:快车道|(?:完整|正式|正常)?流程)|别走流程|按.{0,15}(?:做|执行)|照.{0,15}(?:做|执行)|把.{1,30}(?:改|修|加|删)|修复|修正|修改|调整|更新|替换|改一下|加上|去掉)/.test(command)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handOffToLeadAssistant({ store, host, provisioner, turnCommands }, projectId, role, args, exec) {
|
||||||
|
const command = turnCommands?.read(exec)
|
||||||
|
if (!command) return { ok: false, reason: 'current-user-message-unavailable', error: '当前回合没有已核验的用户消息。' }
|
||||||
|
const request = cleanText(args.request)
|
||||||
|
if (!request) return { ok: false, reason: 'invalid-handoff', error: '请简述用户需要助手处理的事项。' }
|
||||||
|
const operations = ['record', 'publish', 'list', 'cancel']
|
||||||
|
if (role === 'intake' && !operations.includes(args.operation)) {
|
||||||
|
return { ok: false, reason: 'invalid-handoff', error: '请选择书记官要处理的操作。' }
|
||||||
|
}
|
||||||
|
let requirementId = null
|
||||||
|
let requirementRevision = null
|
||||||
|
if (role === 'intake' && ['publish', 'cancel'].includes(args.operation)) {
|
||||||
|
const ids = intakeRequirementIds(command.text)
|
||||||
|
const clarified = args.clarified === true && args.operation === 'publish'
|
||||||
|
if (!clarified && !explicitIntakeIntent(command.text, args.operation)) {
|
||||||
|
return { ok: false, reason: 'sansheng/publish-not-explicit', error: '请先确认用户明确授权本次操作。' }
|
||||||
|
}
|
||||||
|
if (ids.length > 1 || (args.operation === 'cancel' && ids.length !== 1)) {
|
||||||
|
return { ok: false, reason: 'sansheng/requirement-ambiguous', error: '请确认要处理的唯一需求编号。' }
|
||||||
|
}
|
||||||
|
const requirements = store.get(projectId)?.requirements ?? []
|
||||||
|
const ready = requirements.filter(item => item.status === 'ready')
|
||||||
|
const current = ids.length === 1 ? requirements.find(item => item.id === ids[0]) : ready.length === 1 ? ready[0] : null
|
||||||
|
requirementId = current?.id ?? ids[0] ?? null
|
||||||
|
requirementRevision = current?.revision ?? null
|
||||||
|
if (clarified && (current?.dispatchAuthorization?.sessionId !== command.sessionId
|
||||||
|
|| current.dispatchAuthorization.seq >= command.seq)) {
|
||||||
|
return { ok: false, reason: 'sansheng/publish-not-explicit', error: '此需求缺少已核验的澄清后下派授权。' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let assistant
|
||||||
|
try { assistant = await provisioner.ensureLeadAssistant(projectId, role) } catch (error) {
|
||||||
|
return { ok: false, reason: 'assistant-unavailable', error: String(error?.message ?? error) }
|
||||||
|
}
|
||||||
|
const target = host.agents?.get?.(assistant.sessionId)
|
||||||
|
const expiresAt = Date.now() + GRANT_TTL_MS
|
||||||
|
const isCurrent = () => {
|
||||||
|
const project = store.state?.projects?.[projectId]
|
||||||
|
const binding = project?.leadAssistants?.[role]
|
||||||
|
return Date.now() < expiresAt && project?.seats?.lead?.sessionId === command.sessionId
|
||||||
|
&& host.agents?.get?.(command.sessionId) === exec.agent
|
||||||
|
&& binding?.status === 'bound' && binding.sessionId === assistant.sessionId
|
||||||
|
&& host.agents?.get?.(assistant.sessionId) === target
|
||||||
|
}
|
||||||
|
if (typeof target?.followup !== 'function' || host.isLeadAssistantReady?.(target, role) === false || !isCurrent()) {
|
||||||
|
return { ok: false, reason: 'assistant-unavailable', error: '助手会话不可用。' }
|
||||||
|
}
|
||||||
|
if (turnCommands.read(exec) !== command) return { ok: false, reason: 'current-user-message-unavailable', error: '用户回合已变化。' }
|
||||||
|
const message = {
|
||||||
|
id: randomUUID(), role: 'user',
|
||||||
|
content: [{ type: 'text', text: [
|
||||||
|
role === 'intake' ? '【书记官交接】操作:' + args.operation : '【联络官催办】',
|
||||||
|
'丞相交接:' + request.slice(0, 1600),
|
||||||
|
'用户原话:' + command.text,
|
||||||
|
].join('\n') }],
|
||||||
|
source: { kind: role === 'intake' ? 'sansheng-intake' : 'sansheng-task' },
|
||||||
|
}
|
||||||
|
if (role === 'intake') {
|
||||||
|
turnCommands.registerIntake(message.id, {
|
||||||
|
command, target, operation: args.operation, clarified: args.clarified === true, isCurrent,
|
||||||
|
get requirementId() { return requirementId },
|
||||||
|
get requirementRevision() { return requirementRevision },
|
||||||
|
bindRequirement(requirement) {
|
||||||
|
if (requirementId && requirementId !== requirement.id) return
|
||||||
|
requirementId = requirement.id
|
||||||
|
requirementRevision = requirement.revision
|
||||||
|
},
|
||||||
|
async reply(text) {
|
||||||
|
if (!isCurrent()) return
|
||||||
|
try {
|
||||||
|
await exec.agent.followup({
|
||||||
|
id: randomUUID(), role: 'user',
|
||||||
|
content: [{ type: 'text', text: '【书记官简报】' + text.slice(0, 500) }],
|
||||||
|
source: { kind: 'sansheng-summary' },
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[sansheng] 书记官简报投递结果未知:', error?.message ?? error)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
try { await target.followup(message) } catch (error) {
|
||||||
|
return { ok: false, reason: 'assistant-handoff-unknown', error: String(error?.message ?? error) }
|
||||||
|
}
|
||||||
|
return { ok: true, status: 'queued' }
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,177 @@
|
||||||
|
import { randomUUID } from 'node:crypto'
|
||||||
|
import { applyModel } from './model.js'
|
||||||
|
import { readSessionPreset } from './seat-preset.js'
|
||||||
|
|
||||||
|
const ASSISTANT_TITLES = Object.freeze({ intake: '相·需求', liaison: '相·联络' })
|
||||||
|
const ASSISTANT_PRESET = 'minimal'
|
||||||
|
|
||||||
|
function emptyAssistant() {
|
||||||
|
return { sessionId: null, plannedSessionId: null, status: 'pending', agentPreset: ASSISTANT_PRESET }
|
||||||
|
}
|
||||||
|
|
||||||
|
class LeadAssistantProvisionError extends Error {
|
||||||
|
constructor(code, message) {
|
||||||
|
super(message)
|
||||||
|
this.name = 'LeadAssistantProvisionError'
|
||||||
|
this.code = code
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSessionNotFound(error) {
|
||||||
|
const code = String(error?.code ?? '')
|
||||||
|
return /^(?:session[\/_-])?not[ _-]?found$/i.test(code) || code === 'ENOENT' ||
|
||||||
|
(!code && /(?:session not found|会话不存在)/i.test(String(error?.message ?? '')))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createLeadAssistantProvisioner({ store, host, model = null, now = () => Date.now(), onBound }) {
|
||||||
|
const inFlight = new Map()
|
||||||
|
const namedSessions = new Set()
|
||||||
|
const configuredAgents = new WeakSet()
|
||||||
|
|
||||||
|
function requireProject(project, projectId) {
|
||||||
|
if (project?.id !== projectId) {
|
||||||
|
throw new LeadAssistantProvisionError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
}
|
||||||
|
return project
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateAssistant(projectId, role, expected, change) {
|
||||||
|
return store.mutate(state => {
|
||||||
|
const project = requireProject(state.projects[projectId], projectId)
|
||||||
|
const current = project.leadAssistants?.[role] ?? emptyAssistant()
|
||||||
|
if ((current.sessionId ?? null) !== expected.sessionId ||
|
||||||
|
(current.plannedSessionId ?? null) !== expected.plannedSessionId || current.creationMismatch) {
|
||||||
|
throw new LeadAssistantProvisionError('sansheng/session-conflict', '助手会话记录已变化,请重试')
|
||||||
|
}
|
||||||
|
project.leadAssistants ??= { intake: emptyAssistant(), liaison: emptyAssistant() }
|
||||||
|
const updatedAt = now()
|
||||||
|
const assistant = { ...current, ...change, agentPreset: ASSISTANT_PRESET, updatedAt }
|
||||||
|
project.leadAssistants[role] = assistant
|
||||||
|
project.updatedAt = updatedAt
|
||||||
|
return { ...assistant }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resolveSession(sessionId) {
|
||||||
|
let resolved
|
||||||
|
try {
|
||||||
|
resolved = await host.sessionController.resolveAgent(sessionId)
|
||||||
|
} catch (error) {
|
||||||
|
if (isSessionNotFound(error)) return null
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
if (resolved?.error) {
|
||||||
|
if (isSessionNotFound(resolved.error)) return null
|
||||||
|
throw new Error(resolved.error.message ?? resolved.error.code ?? String(resolved.error))
|
||||||
|
}
|
||||||
|
if (!resolved?.agent) throw new Error('宿主未返回会话')
|
||||||
|
const actualId = resolved.agent.id ?? resolved.agent.session?.id
|
||||||
|
if (actualId != null && actualId !== sessionId) {
|
||||||
|
throw new Error(`宿主查询返回了其他会话:${actualId}`)
|
||||||
|
}
|
||||||
|
return resolved.agent
|
||||||
|
}
|
||||||
|
|
||||||
|
async function bindAssistant(projectId, role, assistant, sessionId, agent, reportedPreset) {
|
||||||
|
const actualPreset = reportedPreset ?? readSessionPreset(host, agent)
|
||||||
|
if (actualPreset && actualPreset !== ASSISTANT_PRESET) {
|
||||||
|
throw new LeadAssistantProvisionError('sansheng/session-preset-mismatch', '助手会话未使用 minimal 预设')
|
||||||
|
}
|
||||||
|
if (model && !configuredAgents.has(agent)) {
|
||||||
|
await applyModel(host, sessionId, model)
|
||||||
|
if (agent) configuredAgents.add(agent)
|
||||||
|
}
|
||||||
|
const needsBinding = assistant.status !== 'bound' || assistant.sessionId !== sessionId ||
|
||||||
|
assistant.plannedSessionId !== sessionId || assistant.agentPreset !== ASSISTANT_PRESET
|
||||||
|
const bound = needsBinding
|
||||||
|
? await updateAssistant(projectId, role, assistant, { sessionId, plannedSessionId: sessionId, status: 'bound', error: null })
|
||||||
|
: { ...assistant }
|
||||||
|
if (needsBinding && typeof onBound === 'function') {
|
||||||
|
try {
|
||||||
|
await onBound(projectId, role, sessionId)
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[sansheng] 助手会话绑定通知失败:', error?.message ?? error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!namedSessions.has(sessionId) && typeof host.sessionController.rename === 'function') {
|
||||||
|
try {
|
||||||
|
const result = await host.sessionController.rename({ sessionId, title: ASSISTANT_TITLES[role] })
|
||||||
|
if (result?.error) throw new Error(result.error.message ?? result.error.code ?? String(result.error))
|
||||||
|
namedSessions.add(sessionId)
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[sansheng] 助手会话标题设置失败:', error?.message ?? error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bound
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensure(projectId, role) {
|
||||||
|
await store.ensureLoaded()
|
||||||
|
const project = requireProject(store.get(projectId), projectId)
|
||||||
|
let assistant = { ...emptyAssistant(), ...project.leadAssistants?.[role] }
|
||||||
|
const title = ASSISTANT_TITLES[role]
|
||||||
|
if (assistant.creationMismatch ||
|
||||||
|
(assistant.sessionId && assistant.plannedSessionId && assistant.sessionId !== assistant.plannedSessionId)) {
|
||||||
|
throw new LeadAssistantProvisionError('sansheng/session-mismatch', `「${title}」的会话 ID 不一致,请先核对绑定记录`)
|
||||||
|
}
|
||||||
|
// 宿主调用前落盘;重试和重启都先核验同一个计划 ID。
|
||||||
|
if (!assistant.sessionId && !assistant.plannedSessionId) {
|
||||||
|
assistant = await updateAssistant(projectId, role, assistant, {
|
||||||
|
plannedSessionId: randomUUID(), status: 'creating', error: null,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const sessionId = assistant.sessionId ?? assistant.plannedSessionId
|
||||||
|
let agent
|
||||||
|
try {
|
||||||
|
agent = await resolveSession(sessionId)
|
||||||
|
} catch (error) {
|
||||||
|
const message = `无法确认「${title}」的会话:${error?.message ?? error}`
|
||||||
|
await updateAssistant(projectId, role, assistant, { status: 'failed', error: message })
|
||||||
|
throw new LeadAssistantProvisionError('sansheng/session-check-failed', message)
|
||||||
|
}
|
||||||
|
if (agent) return bindAssistant(projectId, role, assistant, sessionId, agent)
|
||||||
|
if (assistant.sessionId) {
|
||||||
|
const message = `「${title}」的会话已不存在:${sessionId}`
|
||||||
|
await updateAssistant(projectId, role, assistant, { status: 'missing', error: message })
|
||||||
|
throw new LeadAssistantProvisionError('sansheng/session-missing', message)
|
||||||
|
}
|
||||||
|
if (assistant.status !== 'creating') {
|
||||||
|
assistant = await updateAssistant(projectId, role, assistant, { status: 'creating', error: null })
|
||||||
|
}
|
||||||
|
let created
|
||||||
|
try {
|
||||||
|
created = await host.sessionController.create({ sessionId, workspaceId: project.workspaceId ?? undefined, agentPreset: ASSISTANT_PRESET })
|
||||||
|
} catch (error) {
|
||||||
|
let recoveryError
|
||||||
|
try { agent = await resolveSession(sessionId) } catch (checkError) { recoveryError = checkError }
|
||||||
|
if (agent) return bindAssistant(projectId, role, assistant, sessionId, agent)
|
||||||
|
const detail = recoveryError ? `;会话核验失败:${recoveryError?.message ?? recoveryError}` : ''
|
||||||
|
const message = `创建「${title}」会话失败:${error?.message ?? error}${detail}`
|
||||||
|
await updateAssistant(projectId, role, assistant, { status: 'failed', error: message })
|
||||||
|
throw new LeadAssistantProvisionError('sansheng/create-failed', message)
|
||||||
|
}
|
||||||
|
if (created?.sessionId !== sessionId) {
|
||||||
|
const actualSessionId = typeof created?.sessionId === 'string' ? created.sessionId : null
|
||||||
|
const message = `「${title}」的会话 ID 不一致:计划 ${sessionId},实际 ${actualSessionId ?? 'null'}`
|
||||||
|
await updateAssistant(projectId, role, assistant, {
|
||||||
|
status: 'failed', error: message, creationMismatch: { plannedSessionId: sessionId, actualSessionId },
|
||||||
|
})
|
||||||
|
throw new LeadAssistantProvisionError('sansheng/session-mismatch', message)
|
||||||
|
}
|
||||||
|
agent = await resolveSession(sessionId)
|
||||||
|
if (!agent) throw new LeadAssistantProvisionError('sansheng/session-missing', `宿主未能打开新建的「${title}」会话`)
|
||||||
|
return bindAssistant(projectId, role, assistant, sessionId, agent, created.agentPreset)
|
||||||
|
}
|
||||||
|
|
||||||
|
return async function ensureLeadAssistant(projectId, role) {
|
||||||
|
if (!Object.hasOwn(ASSISTANT_TITLES, role)) {
|
||||||
|
throw new LeadAssistantProvisionError('sansheng/invalid', `未知助手角色 ${String(role)}`)
|
||||||
|
}
|
||||||
|
const key = `${projectId}:${role}`
|
||||||
|
const pending = inFlight.get(key)
|
||||||
|
if (pending) return pending
|
||||||
|
const run = ensure(projectId, role).finally(() => inFlight.delete(key))
|
||||||
|
inFlight.set(key, run)
|
||||||
|
return run
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
import { LEAD_ASSISTANT_ROLES } from '../shared/schema.js'
|
||||||
|
|
||||||
|
export function leadAssistantBySession(projects, sessionId) {
|
||||||
|
if (!sessionId) return null
|
||||||
|
for (const project of Object.values(projects ?? {})) {
|
||||||
|
for (const role of LEAD_ASSISTANT_ROLES) {
|
||||||
|
const assistant = project.leadAssistants?.[role]
|
||||||
|
if (assistant?.status === 'bound' && assistant.sessionId === sessionId) return { project, role }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
// R-003:流程席位完成后直接向丞相主会话推送阶段与审批回报。
|
// 业务事务内同步落盘 project.leadReports,事务提交后交由联络助手接收。
|
||||||
// 业务事务内同步落盘 project.leadReports,事务提交后异步直投丞相。
|
|
||||||
import { randomUUID } from 'node:crypto'
|
import { randomUUID } from 'node:crypto'
|
||||||
import { isObject, cleanText } from '../shared/utils.js'
|
import { isObject, cleanText } from '../shared/utils.js'
|
||||||
|
|
||||||
|
|
@ -16,6 +15,24 @@ export const LEAD_REPORT_SOURCE_KINDS = Object.freeze(['sansheng-report', 'sansh
|
||||||
export const LEAD_REPORT_STATUSES = Object.freeze(['pending', 'delivered', 'failed'])
|
export const LEAD_REPORT_STATUSES = Object.freeze(['pending', 'delivered', 'failed'])
|
||||||
|
|
||||||
const SOURCE_KIND_SET = new Set(LEAD_REPORT_SOURCE_KINDS)
|
const SOURCE_KIND_SET = new Set(LEAD_REPORT_SOURCE_KINDS)
|
||||||
|
const BRIEF_EVENTS = new Set([
|
||||||
|
'approval_request', 'user_decision', 'decision_required',
|
||||||
|
'blocked', 'blockage', 'workflow_blocked', 'workflow_blockage',
|
||||||
|
'delivery', 'delivered', 'workflow_delivery', 'workflow_deliver', 'workflow_delivered',
|
||||||
|
'menxia_accept',
|
||||||
|
'fast_lane_done', 'fast_lane_failed', 'fast_lane_escalated',
|
||||||
|
])
|
||||||
|
|
||||||
|
function briefEligible(report) {
|
||||||
|
return report.needsUserDecision === true || BRIEF_EVENTS.has(report.event)
|
||||||
|
}
|
||||||
|
|
||||||
|
function approvalIdOf(report) {
|
||||||
|
if (report?.event !== 'approval_request') return ''
|
||||||
|
const transitionId = cleanText(report.transitionId)
|
||||||
|
const legacyId = transitionId.startsWith('approval:') ? cleanText(transitionId.slice('approval:'.length)) : ''
|
||||||
|
return cleanText(report.approvalId) || legacyId
|
||||||
|
}
|
||||||
|
|
||||||
function truncateSummary(value) {
|
function truncateSummary(value) {
|
||||||
const chars = Array.from(String(value ?? ''))
|
const chars = Array.from(String(value ?? ''))
|
||||||
|
|
@ -57,6 +74,8 @@ export function buildLeadReportMessage(report) {
|
||||||
: '无'
|
: '无'
|
||||||
return [
|
return [
|
||||||
'【丞相回报】',
|
'【丞相回报】',
|
||||||
|
`回报编号:${report?.reportId ?? ''}`,
|
||||||
|
...(approvalIdOf(report) ? [`审批编号:${approvalIdOf(report)}`] : []),
|
||||||
`任务:${report?.taskId ?? '无'}`,
|
`任务:${report?.taskId ?? '无'}`,
|
||||||
`需求:${requirement}`,
|
`需求:${requirement}`,
|
||||||
`事件:${report?.event ?? ''}`,
|
`事件:${report?.event ?? ''}`,
|
||||||
|
|
@ -84,7 +103,9 @@ function taskStateProblem(project, report) {
|
||||||
&& String(req.revision) !== String(report.requirementRevision)) {
|
&& String(req.revision) !== String(report.requirementRevision)) {
|
||||||
return 'task-requirement-changed'
|
return 'task-requirement-changed'
|
||||||
}
|
}
|
||||||
if (report.transitionId && task.lastTransitionId && task.lastTransitionId !== report.transitionId) {
|
if (report.decisionId && !task.decisions?.some(item => item.id === report.decisionId && item.status === 'pending')) return 'decision-closed'
|
||||||
|
if (report.consultationId && !task.consultations?.some(item => item.id === report.consultationId)) return 'consultation-unavailable'
|
||||||
|
if (!report.decisionId && !report.consultationId && report.transitionId && task.lastTransitionId && task.lastTransitionId !== report.transitionId) {
|
||||||
return 'task-transition-changed'
|
return 'task-transition-changed'
|
||||||
}
|
}
|
||||||
if (report.requirementRevision !== null && report.requirementRevision !== undefined
|
if (report.requirementRevision !== null && report.requirementRevision !== undefined
|
||||||
|
|
@ -126,6 +147,8 @@ function recordIntoProject(project, projectId, event, at) {
|
||||||
requirementId: event.requirementId ?? task?.requirementId ?? null,
|
requirementId: event.requirementId ?? task?.requirementId ?? null,
|
||||||
requirementRevision: event.requirementRevision ?? task?.requirementRevision ?? null,
|
requirementRevision: event.requirementRevision ?? task?.requirementRevision ?? null,
|
||||||
event: cleanText(event.event),
|
event: cleanText(event.event),
|
||||||
|
...(event.decisionId ? { decisionId: event.decisionId } : {}),
|
||||||
|
...(event.consultationId ? { consultationId: event.consultationId } : {}),
|
||||||
stage: event.stage ?? task?.stage ?? null,
|
stage: event.stage ?? task?.stage ?? null,
|
||||||
ownerSeatId: event.ownerSeatId ?? task?.ownerSeatId ?? null,
|
ownerSeatId: event.ownerSeatId ?? task?.ownerSeatId ?? null,
|
||||||
textSnapshot,
|
textSnapshot,
|
||||||
|
|
@ -138,6 +161,8 @@ function recordIntoProject(project, projectId, event, at) {
|
||||||
createdAt: at,
|
createdAt: at,
|
||||||
updatedAt: at,
|
updatedAt: at,
|
||||||
}
|
}
|
||||||
|
const approvalId = approvalIdOf(event)
|
||||||
|
if (approvalId) report.approvalId = approvalId
|
||||||
reports.push(report)
|
reports.push(report)
|
||||||
const snapshot = structuredClone(report)
|
const snapshot = structuredClone(report)
|
||||||
return { ...structuredClone(snapshot), report: snapshot, created: true, duplicate: false }
|
return { ...structuredClone(snapshot), report: snapshot, created: true, duplicate: false }
|
||||||
|
|
@ -150,7 +175,7 @@ export function recordLeadReportInState(state, projectId, event, now = Date.now(
|
||||||
return recordIntoProject(projectOf(state, projectId), projectId, event, at)
|
return recordIntoProject(projectOf(state, projectId), projectId, event, at)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createLeadReporter({ store, host = {}, now = () => Date.now() } = {}) {
|
export function createLeadReporter({ store, host = {}, ensureLeadAssistant, now = () => Date.now() } = {}) {
|
||||||
if (!store || typeof store.get !== 'function' || typeof store.mutate !== 'function') {
|
if (!store || typeof store.get !== 'function' || typeof store.mutate !== 'function') {
|
||||||
throw new LeadReporterError('sansheng/lead-report-store', 'createLeadReporter 需要 store.ensureLoaded/get/mutate')
|
throw new LeadReporterError('sansheng/lead-report-store', 'createLeadReporter 需要 store.ensureLoaded/get/mutate')
|
||||||
}
|
}
|
||||||
|
|
@ -190,89 +215,254 @@ export function createLeadReporter({ store, host = {}, now = () => Date.now() }
|
||||||
async function markFailed(projectId, reportId, reason) {
|
async function markFailed(projectId, reportId, reason) {
|
||||||
const saved = await store.mutate(state => {
|
const saved = await store.mutate(state => {
|
||||||
const current = findReport(projectOf(state, projectId), reportId)
|
const current = findReport(projectOf(state, projectId), reportId)
|
||||||
if (!current || current.status !== 'pending') return current ? structuredClone(current) : null
|
if (!current || current.status !== 'pending' || current.deliveryAttemptId) return current ? structuredClone(current) : null
|
||||||
current.status = 'failed'
|
current.status = 'failed'
|
||||||
current.error = reason
|
current.error = reason
|
||||||
current.updatedAt = clock()
|
current.updatedAt = clock()
|
||||||
return structuredClone(current)
|
return structuredClone(current)
|
||||||
})
|
})
|
||||||
|
if (saved?.status === 'delivered' || saved?.deliveryAttemptId) return reportResult(saved)
|
||||||
return { ok: false, status: saved?.status ?? 'failed', reason, error: reason, report: saved }
|
return { ok: false, status: saved?.status ?? 'failed', reason, error: reason, report: saved }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function boundSession(project, role) {
|
||||||
|
const binding = role === 'liaison' ? project?.leadAssistants?.liaison : project?.seats?.lead
|
||||||
|
return binding?.status === 'bound' ? binding.sessionId : null
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resolveTarget(role, sessionId) {
|
||||||
|
if (!sessionId) return null
|
||||||
|
const agent = await resolveLeadAgent(sessionId)
|
||||||
|
if (typeof agent?.followup !== 'function' || (agent.session?.id && agent.session.id !== sessionId)) return null
|
||||||
|
if (role === 'liaison' && host.isLeadAssistantReady?.(agent, role) === false) return null
|
||||||
|
return { role, sessionId, agent, registered: Boolean(host.agents?.get?.(sessionId)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
function targetIsCurrent(project, target) {
|
||||||
|
const currentAgent = host.agents?.get?.(target.sessionId)
|
||||||
|
return boundSession(project, target.role) === target.sessionId
|
||||||
|
&& (!(target.registered || currentAgent) || currentAgent === target.agent)
|
||||||
|
&& typeof target.agent.followup === 'function'
|
||||||
|
}
|
||||||
|
|
||||||
|
function reportResult(report) {
|
||||||
|
if (!report) return { ok: false, status: 'not-found', reason: 'not-found' }
|
||||||
|
if (report.status === 'delivered') return { ok: true, status: 'delivered', duplicate: true, report: structuredClone(report) }
|
||||||
|
if (report.status !== 'pending') return { ok: false, status: report.status, reason: 'not-pending', report: structuredClone(report) }
|
||||||
|
if (report.deliveryAttemptId) return { ok: false, status: 'unknown', reason: 'delivery-outcome-unknown', report: structuredClone(report) }
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function createMessage(text, source) {
|
||||||
|
const factory = typeof host.createUserMessage === 'function' ? host.createUserMessage : defaultCreateUserMessage
|
||||||
|
return factory({ content: [{ type: 'text', text }], source })
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendToTarget(projectId, id, target) {
|
||||||
|
const project = store.get(projectId)
|
||||||
|
const report = project ? findReport(project, id) : null
|
||||||
|
const settled = reportResult(report)
|
||||||
|
if (settled) return settled
|
||||||
|
const problem = taskStateProblem(project, report)
|
||||||
|
if (problem) return markFailed(projectId, id, problem)
|
||||||
|
if (!target || !targetIsCurrent(project, target)) return null
|
||||||
|
|
||||||
|
let message
|
||||||
|
try {
|
||||||
|
message = await createMessage(buildLeadReportMessage(report), {
|
||||||
|
kind: report.sourceKind, reportId: report.reportId, taskId: report.taskId,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
return markFailed(projectId, id, String(error?.message ?? error))
|
||||||
|
}
|
||||||
|
|
||||||
|
const attemptId = randomUUID()
|
||||||
|
const claimed = await store.mutate(state => {
|
||||||
|
const latest = projectOf(state, projectId)
|
||||||
|
const current = findReport(latest, id)
|
||||||
|
if (current?.status !== 'pending' || current.deliveryAttemptId || taskStateProblem(latest, current)
|
||||||
|
|| !targetIsCurrent(latest, target)) return false
|
||||||
|
current.deliveryAttemptId = attemptId
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
const latest = store.get(projectId)
|
||||||
|
const current = latest ? findReport(latest, id) : null
|
||||||
|
if (!claimed || current?.deliveryAttemptId !== attemptId) {
|
||||||
|
const result = reportResult(current)
|
||||||
|
if (result) return result
|
||||||
|
const latestProblem = taskStateProblem(latest, current)
|
||||||
|
return latestProblem ? markFailed(projectId, id, latestProblem) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
const latestProblem = taskStateProblem(latest, current)
|
||||||
|
if (current.status !== 'pending' || latestProblem || !targetIsCurrent(latest, target)) {
|
||||||
|
await store.mutate(state => {
|
||||||
|
const saved = findReport(projectOf(state, projectId), id)
|
||||||
|
if (saved?.deliveryAttemptId === attemptId) delete saved.deliveryAttemptId
|
||||||
|
})
|
||||||
|
const refreshed = store.get(projectId)
|
||||||
|
const refreshedReport = refreshed ? findReport(refreshed, id) : null
|
||||||
|
const result = reportResult(refreshedReport)
|
||||||
|
if (result) return result
|
||||||
|
const refreshedProblem = taskStateProblem(refreshed, refreshedReport)
|
||||||
|
return refreshedProblem ? markFailed(projectId, id, refreshedProblem) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
let sendError = null
|
||||||
|
try {
|
||||||
|
await target.agent.followup(message)
|
||||||
|
} catch (error) {
|
||||||
|
sendError = String(error?.message ?? error)
|
||||||
|
}
|
||||||
|
const finalized = await store.mutate(state => {
|
||||||
|
const saved = findReport(projectOf(state, projectId), id)
|
||||||
|
if (saved?.deliveryAttemptId !== attemptId || saved.status !== 'pending') return saved ? structuredClone(saved) : null
|
||||||
|
delete saved.deliveryAttemptId
|
||||||
|
const at = clock()
|
||||||
|
saved.updatedAt = at
|
||||||
|
saved.status = sendError === null ? 'delivered' : 'failed'
|
||||||
|
if (sendError === null) saved.deliveredAt = at
|
||||||
|
saved.error = sendError
|
||||||
|
return structuredClone(saved)
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
ok: sendError === null && finalized?.status === 'delivered',
|
||||||
|
status: finalized?.status ?? (sendError === null ? 'delivered' : 'failed'),
|
||||||
|
report: finalized,
|
||||||
|
error: sendError ?? undefined,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function send(projectId, reportId) {
|
async function send(projectId, reportId) {
|
||||||
await ensureLoaded()
|
await ensureLoaded()
|
||||||
const id = cleanText(reportId)
|
const id = cleanText(reportId)
|
||||||
if (!id) throw new LeadReporterError('sansheng/lead-report-invalid', '缺少 reportId')
|
if (!id) throw new LeadReporterError('sansheng/lead-report-invalid', '缺少 reportId')
|
||||||
const flightKey = `${projectId}:${id}`
|
const project = store.get(projectId)
|
||||||
|
if (!project) throw new LeadReporterError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
const report = findReport(project, id)
|
||||||
|
const flightKey = JSON.stringify([projectId, report?.reportId ?? id])
|
||||||
if (inFlight.has(flightKey)) return { ok: false, status: 'in-flight', reason: 'in-flight' }
|
if (inFlight.has(flightKey)) return { ok: false, status: 'in-flight', reason: 'in-flight' }
|
||||||
|
const settled = reportResult(report)
|
||||||
|
if (settled) return settled
|
||||||
|
const problem = taskStateProblem(project, report)
|
||||||
inFlight.add(flightKey)
|
inFlight.add(flightKey)
|
||||||
try {
|
try {
|
||||||
const project = store.get(projectId)
|
if (problem) return await markFailed(projectId, id, problem)
|
||||||
if (!project) throw new LeadReporterError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
if (typeof ensureLeadAssistant === 'function') {
|
||||||
const report = findReport(project, id)
|
let liaison
|
||||||
if (!report) return { ok: false, status: 'not-found', reason: 'not-found' }
|
try {
|
||||||
if (report.status === 'delivered') return { ok: true, status: 'delivered', duplicate: true, report: structuredClone(report) }
|
liaison = await ensureLeadAssistant(projectId, 'liaison')
|
||||||
if (report.status !== 'pending') return { ok: false, status: report.status, reason: 'not-pending', report: structuredClone(report) }
|
} catch (error) {
|
||||||
|
console.warn('[sansheng] 联络助手不可用,回报转投丞相:', error?.message ?? error)
|
||||||
const problem = taskStateProblem(project, report)
|
|
||||||
if (problem) return markFailed(projectId, id, problem)
|
|
||||||
const lead = project.seats?.lead
|
|
||||||
if (!lead || lead.status !== 'bound' || !lead.sessionId) return markFailed(projectId, id, 'lead-seat-unbound')
|
|
||||||
|
|
||||||
const agent = await resolveLeadAgent(lead.sessionId)
|
|
||||||
const latestProject = store.get(projectId)
|
|
||||||
const latestReport = latestProject ? findReport(latestProject, id) : null
|
|
||||||
if (!latestReport) return { ok: false, status: 'not-found', reason: 'not-found' }
|
|
||||||
if (latestReport.status === 'delivered') return { ok: true, status: 'delivered', duplicate: true, report: structuredClone(latestReport) }
|
|
||||||
if (latestReport.status !== 'pending') return { ok: false, status: latestReport.status, reason: 'not-pending', report: structuredClone(latestReport) }
|
|
||||||
const latestProblem = taskStateProblem(latestProject, latestReport)
|
|
||||||
if (latestProblem) return markFailed(projectId, id, latestProblem)
|
|
||||||
const latestLead = latestProject.seats?.lead
|
|
||||||
if (!latestLead || latestLead.status !== 'bound' || !latestLead.sessionId || latestLead.sessionId !== lead.sessionId) {
|
|
||||||
return markFailed(projectId, id, 'lead-seat-unbound')
|
|
||||||
}
|
|
||||||
|
|
||||||
let sendError = null
|
|
||||||
try {
|
|
||||||
if (!agent || typeof agent.followup !== 'function') {
|
|
||||||
throw new LeadReporterError('sansheng/lead-session-unavailable', `丞相会话不可用:${lead.sessionId}`)
|
|
||||||
}
|
}
|
||||||
const factory = typeof host.createUserMessage === 'function' ? host.createUserMessage : defaultCreateUserMessage
|
const target = liaison?.status === 'bound' ? await resolveTarget('liaison', liaison.sessionId) : null
|
||||||
const message = await Promise.resolve(factory({
|
const result = await sendToTarget(projectId, id, target)
|
||||||
content: [{ type: 'text', text: buildLeadReportMessage(latestReport) }],
|
if (result) return result
|
||||||
source: { kind: latestReport.sourceKind, reportId: latestReport.reportId, taskId: latestReport.taskId },
|
|
||||||
}))
|
|
||||||
await Promise.resolve(agent.followup(message))
|
|
||||||
} catch (error) {
|
|
||||||
sendError = String(error?.message ?? error)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const finalized = await store.mutate(state => {
|
const sessionId = boundSession(store.get(projectId), 'lead')
|
||||||
const current = findReport(projectOf(state, projectId), id)
|
if (!sessionId) return await markFailed(projectId, id, 'lead-seat-unbound')
|
||||||
if (!current || current.status !== 'pending') return current ? structuredClone(current) : null
|
const result = await sendToTarget(projectId, id, await resolveTarget('lead', sessionId))
|
||||||
const at = clock()
|
if (result) return result
|
||||||
current.updatedAt = at
|
const stillBound = boundSession(store.get(projectId), 'lead') === sessionId
|
||||||
if (sendError === null) {
|
return await markFailed(projectId, id, stillBound ? `丞相会话不可用:${sessionId}` : 'lead-seat-unbound')
|
||||||
current.status = 'delivered'
|
|
||||||
current.deliveredAt = at
|
|
||||||
current.error = null
|
|
||||||
} else {
|
|
||||||
current.status = 'failed'
|
|
||||||
current.error = sendError
|
|
||||||
}
|
|
||||||
return structuredClone(current)
|
|
||||||
})
|
|
||||||
return {
|
|
||||||
ok: sendError === null && finalized?.status === 'delivered',
|
|
||||||
status: finalized?.status ?? (sendError === null ? 'delivered' : 'failed'),
|
|
||||||
report: finalized,
|
|
||||||
error: sendError ?? undefined,
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
inFlight.delete(flightKey)
|
inFlight.delete(flightKey)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isBoundLiaison(project, actor) {
|
||||||
|
const role = actor?.assistantRole ?? actor?.seatId
|
||||||
|
const sessionId = actor?.sessionId
|
||||||
|
return role === 'liaison' && Boolean(sessionId) && boundSession(project, 'liaison') === sessionId
|
||||||
|
&& (actor.projectId == null || actor.projectId === project.id)
|
||||||
|
&& (!actor.agent || host.agents?.get?.(sessionId) === actor.agent)
|
||||||
|
}
|
||||||
|
|
||||||
|
function briefReport(project, reportId, actor) {
|
||||||
|
if (!isBoundLiaison(project, actor)) {
|
||||||
|
throw new LeadReporterError('sansheng/forbidden', '只有本项目已绑定的联络助手可以提交简报')
|
||||||
|
}
|
||||||
|
const report = (project.leadReports ?? []).find(item => item.reportId === reportId)
|
||||||
|
if (!report) throw new LeadReporterError('sansheng/not-found', '回报不存在')
|
||||||
|
if (!briefEligible(report)) throw new LeadReporterError('sansheng/lead-brief-ineligible', '此回报无需转交丞相')
|
||||||
|
return report
|
||||||
|
}
|
||||||
|
|
||||||
|
function previousBrief(report) {
|
||||||
|
if (!report.brief) return null
|
||||||
|
const delivered = report.brief.status === 'delivered'
|
||||||
|
return { ok: delivered, status: delivered ? 'delivered' : 'unknown', reportId: report.reportId, duplicate: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function brief(projectId, input = {}, actor = {}) {
|
||||||
|
await ensureLoaded()
|
||||||
|
const reportId = cleanText(input?.reportId)
|
||||||
|
const summary = truncateSummary(cleanText(input?.summary))
|
||||||
|
if (!reportId || !summary) throw new LeadReporterError('sansheng/lead-report-invalid', '简报需要回报编号与摘要')
|
||||||
|
const project = store.get(projectId)
|
||||||
|
const report = briefReport(project, reportId, actor)
|
||||||
|
const existing = previousBrief(report)
|
||||||
|
if (existing) return existing
|
||||||
|
const target = await resolveTarget('lead', boundSession(project, 'lead'))
|
||||||
|
if (!target) return { ok: false, status: 'not-sent', reportId, reason: 'lead-session-unavailable' }
|
||||||
|
|
||||||
|
const approvalId = approvalIdOf(report)
|
||||||
|
const text = [
|
||||||
|
'【丞相简报】',
|
||||||
|
'回报编号:' + reportId,
|
||||||
|
'事件:' + report.event,
|
||||||
|
...(report.taskId ? ['任务:' + report.taskId] : []),
|
||||||
|
...(report.decisionId ? ['裁决编号:' + report.decisionId] : []),
|
||||||
|
...(approvalId ? ['审批编号:' + approvalId] : []),
|
||||||
|
'简报摘要:' + summary,
|
||||||
|
].join('\n')
|
||||||
|
let message
|
||||||
|
try {
|
||||||
|
message = await createMessage(text, { kind: 'sansheng-summary', reportId, taskId: report.taskId })
|
||||||
|
} catch (error) {
|
||||||
|
return { ok: false, status: 'not-sent', reportId, reason: 'message-factory-failed', error: String(error?.message ?? error) }
|
||||||
|
}
|
||||||
|
|
||||||
|
const attemptId = randomUUID()
|
||||||
|
const claimFailure = await store.mutate(state => {
|
||||||
|
const latest = projectOf(state, projectId)
|
||||||
|
const current = briefReport(latest, reportId, actor)
|
||||||
|
const duplicate = previousBrief(current)
|
||||||
|
if (duplicate) return duplicate
|
||||||
|
if (!targetIsCurrent(latest, target)) return { ok: false, status: 'not-sent', reportId, reason: 'lead-session-unavailable' }
|
||||||
|
current.brief = { attemptId, status: 'sending', summary, createdAt: clock() }
|
||||||
|
return null
|
||||||
|
})
|
||||||
|
if (claimFailure) return claimFailure
|
||||||
|
|
||||||
|
const latest = store.get(projectId)
|
||||||
|
const current = latest && findReport(latest, reportId)
|
||||||
|
if (current?.brief?.attemptId !== attemptId || !isBoundLiaison(latest, actor) || !targetIsCurrent(latest, target)) {
|
||||||
|
await store.mutate(state => {
|
||||||
|
const saved = findReport(projectOf(state, projectId), reportId)
|
||||||
|
if (saved?.brief?.attemptId === attemptId) delete saved.brief
|
||||||
|
})
|
||||||
|
return { ok: false, status: 'not-sent', reportId, reason: 'binding-changed' }
|
||||||
|
}
|
||||||
|
|
||||||
|
let sendError = null
|
||||||
|
try {
|
||||||
|
await target.agent.followup(message)
|
||||||
|
} catch (error) {
|
||||||
|
sendError = String(error?.message ?? error)
|
||||||
|
}
|
||||||
|
const status = sendError === null ? 'delivered' : 'unknown'
|
||||||
|
await store.mutate(state => {
|
||||||
|
const saved = findReport(projectOf(state, projectId), reportId)
|
||||||
|
if (saved?.brief?.attemptId === attemptId) {
|
||||||
|
saved.brief.status = status
|
||||||
|
saved.brief.updatedAt = clock()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return { ok: sendError === null, status, reportId, ...(sendError === null ? {} : { error: sendError }) }
|
||||||
|
}
|
||||||
|
|
||||||
async function runFlush(projectId) {
|
async function runFlush(projectId) {
|
||||||
await ensureLoaded()
|
await ensureLoaded()
|
||||||
const project = store.get(projectId)
|
const project = store.get(projectId)
|
||||||
|
|
@ -307,5 +497,5 @@ export function createLeadReporter({ store, host = {}, now = () => Date.now() }
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
return { record, list, send, flush, recoverAll }
|
return { record, list, send, brief, flush, recoverAll, liaisonEnabled: typeof ensureLeadAssistant === 'function' }
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
// R-006:消息来源标签。真实用户 = source.kind="user" 且带 clientTimeZone(或宿主确认 trusted)。
|
// R-006:消息来源标签。真实用户 = source.kind="user" 且带 clientTimeZone(或宿主确认 trusted)。
|
||||||
// 内部任务/回报必须标记 sansheng-task / sansheng-report / sansheng-summary,绝不能冒充 user。
|
// 内部任务/回报必须标记 sansheng-task / sansheng-report / sansheng-summary,绝不能冒充 user。
|
||||||
|
import { SEAT_GROUPS } from '../shared/roles.js'
|
||||||
import { cleanText } from '../shared/utils.js'
|
import { cleanText } from '../shared/utils.js'
|
||||||
|
import { leadAssistantBySession } from './lead-assistant-session.js'
|
||||||
|
|
||||||
export const INTERNAL_SOURCE_KINDS = Object.freeze(['sansheng-task', 'sansheng-report', 'sansheng-summary'])
|
export const INTERNAL_SOURCE_KINDS = Object.freeze(['sansheng-task', 'sansheng-report', 'sansheng-summary'])
|
||||||
|
|
||||||
|
|
@ -65,17 +67,29 @@ export function pickLastUserCommand(messages) {
|
||||||
// and appends it to the same live turn. The event supplies the durable sequence.
|
// and appends it to the same live turn. The event supplies the durable sequence.
|
||||||
export function createTurnCommands(ctx, store) {
|
export function createTurnCommands(ctx, store) {
|
||||||
const active = new WeakMap()
|
const active = new WeakMap()
|
||||||
|
const pendingIntake = new Map()
|
||||||
const boundaryOf = agent => ctx.agents?.turnBoundaryOf?.(agent.session)?.openTurnStartSeq
|
const boundaryOf = agent => ctx.agents?.turnBoundaryOf?.(agent.session)?.openTurnStartSeq
|
||||||
const live = agent => !!agent?.session?.id && ctx.agents?.get?.(agent.session.id) === agent
|
const live = agent => !!agent?.session?.id && ctx.agents?.get?.(agent.session.id) === agent
|
||||||
const preStep = ctx.on?.('agent/pre-step', async ({ agent, messages, signal }, next) => {
|
const preStep = ctx.on?.('agent/pre-step', async ({ agent, messages, signal, step }, next) => {
|
||||||
if (!live(agent) || store.seatBySession(agent.session.id)?.seatId !== 'lead') return next()
|
if ((step !== undefined && step !== 1) || !live(agent)) return next()
|
||||||
|
const seatId = store.seatBySession(agent.session.id)?.seatId
|
||||||
|
const assistant = leadAssistantBySession(store.state?.projects, agent.session.id)
|
||||||
|
if (seatId !== 'lead' && !SEAT_GROUPS.liubu.includes(seatId) && assistant?.role !== 'intake') return next()
|
||||||
const boundary = boundaryOf(agent)
|
const boundary = boundaryOf(agent)
|
||||||
if (!Number.isSafeInteger(boundary) || active.get(agent)?.boundary === boundary) return next()
|
if (!Number.isSafeInteger(boundary) || active.get(agent)?.boundary === boundary) return next()
|
||||||
const entry = { boundary, signal, command: null }
|
const entry = { boundary, signal, command: null }
|
||||||
active.set(agent, entry)
|
active.set(agent, entry)
|
||||||
const [message] = messages ?? []
|
const [message] = messages ?? []
|
||||||
if (messages?.length === 1 && isTrustedUserMessage(message) && cleanText(message.source?.rpcId)) {
|
if (messages?.length === 1 && assistant?.role === 'intake' && message.source?.kind === 'sansheng-intake') {
|
||||||
|
const handoff = pendingIntake.get(message.id)
|
||||||
|
if (handoff?.target === agent && handoff.isCurrent()) {
|
||||||
|
pendingIntake.delete(message.id)
|
||||||
|
entry.messageId = message.id
|
||||||
|
entry.handoff = handoff
|
||||||
|
}
|
||||||
|
} else if (messages?.length === 1 && isTrustedUserMessage(message) && cleanText(message.source?.rpcId)) {
|
||||||
entry.messageId = cleanText(message.id)
|
entry.messageId = cleanText(message.id)
|
||||||
|
entry.rpcId = message.source.rpcId
|
||||||
}
|
}
|
||||||
return next()
|
return next()
|
||||||
})
|
})
|
||||||
|
|
@ -85,25 +99,39 @@ export function createTurnCommands(ctx, store) {
|
||||||
const entry = active.get(agent)
|
const entry = active.get(agent)
|
||||||
if (!entry) return
|
if (!entry) return
|
||||||
if (event.type === 'turn/end') {
|
if (event.type === 'turn/end') {
|
||||||
active.delete(agent)
|
if (event.seq > entry.boundary) active.delete(agent)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const message = event.data
|
const message = event.data
|
||||||
if (event.type !== 'user/message' || !entry.messageId || message?.id !== entry.messageId) return
|
if (event.type !== 'user/message' || !entry.messageId || message?.id !== entry.messageId) return
|
||||||
if (!isTrustedUserMessage(message)) return
|
|
||||||
if (!Number.isSafeInteger(event.seq) || event.seq <= entry.boundary) return
|
if (!Number.isSafeInteger(event.seq) || event.seq <= entry.boundary) return
|
||||||
|
if (entry.handoff && message.source?.kind === 'sansheng-intake') {
|
||||||
|
entry.intake = entry.handoff
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!isTrustedUserMessage(message) || message.source?.rpcId !== entry.rpcId) return
|
||||||
// 正文只认宿主落盘事件;空正文不算命令。消息身份由 id、来源和轮次确认。
|
// 正文只认宿主落盘事件;空正文不算命令。消息身份由 id、来源和轮次确认。
|
||||||
const text = textOfMessage(message)
|
const text = textOfMessage(message)
|
||||||
if (!text) return
|
if (!text) return
|
||||||
entry.command = { text, messageId: entry.messageId, seq: event.seq }
|
entry.command = { text, messageId: entry.messageId, seq: event.seq, sessionId: session.id }
|
||||||
})
|
})
|
||||||
|
const currentEntry = exec => {
|
||||||
|
const agent = exec?.agent
|
||||||
|
if (!live(agent)) return null
|
||||||
|
const entry = active.get(agent)
|
||||||
|
return entry && !entry.signal?.aborted && boundaryOf(agent) === entry.boundary ? entry : null
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
read(exec) {
|
read(exec) { return currentEntry(exec)?.command ?? null },
|
||||||
const agent = exec?.agent
|
readIntake(exec) {
|
||||||
if (!live(agent)) return null
|
const intake = currentEntry(exec)?.intake
|
||||||
const entry = active.get(agent)
|
return intake?.isCurrent() ? intake : null
|
||||||
return entry && !entry.signal?.aborted && boundaryOf(agent) === entry.boundary ? entry.command : null
|
|
||||||
},
|
},
|
||||||
dispose() { preStep?.(); sessionEvent?.() },
|
registerIntake(messageId, handoff) {
|
||||||
|
for (const [id, pending] of pendingIntake) if (!pending.isCurrent()) pendingIntake.delete(id)
|
||||||
|
pendingIntake.set(messageId, handoff)
|
||||||
|
return () => pendingIntake.delete(messageId)
|
||||||
|
},
|
||||||
|
dispose() { pendingIntake.clear(); preStep?.(); sessionEvent?.() },
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,11 @@
|
||||||
import { seatBySessionId } from '../shared/roles.js'
|
import { seatBySessionId } from '../shared/roles.js'
|
||||||
|
import { leadAssistantBySession } from './lead-assistant-session.js'
|
||||||
import { renderProjectMemory } from '../shared/project-memory.js'
|
import { renderProjectMemory } from '../shared/project-memory.js'
|
||||||
|
|
||||||
export const PROMPT_SECTION = 'sansheng'
|
export const PROMPT_SECTION = 'sansheng'
|
||||||
|
|
||||||
|
const FAST_LANE_GUIDANCE = '用户要求「走流程」「先出方案」或「让门下审一下」时使用 full。用户要求「直接让工部改一下」「走快车道」或「别走流程」时,符合单部执行条件可选 fast。默认 fast 须同时满足预计改 1~2 个文件、改法明确唯一、一个六部席位可独立完成自验、改动低风险且可回滚。涉及发布、删库、权限或公共契约的大改动,或任何一项不满足时走 full。fast 须指定一个六部席位,记清范围和验收标准。'
|
||||||
|
|
||||||
export function renderSeatPrompt({ project, seatId, seat }) {
|
export function renderSeatPrompt({ project, seatId, seat }) {
|
||||||
const lines = [
|
const lines = [
|
||||||
`你在「${project?.name ?? project?.id ?? '当前项目'}」项目中担任${seat.label}(${seatId})。`,
|
`你在「${project?.name ?? project?.id ?? '当前项目'}」项目中担任${seat.label}(${seatId})。`,
|
||||||
|
|
@ -17,8 +20,8 @@ export function renderSeatPrompt({ project, seatId, seat }) {
|
||||||
'',
|
'',
|
||||||
'你负责需求澄清、协调与交付。讨论、查资料或提到「下派」的例句均无执行授权。用户表达「照这个做」「安排下去」等清楚行动意图时,整理需求后可直接用 sansheng_requirement_publish 交给中书。下派只需要需求标题、用户原话和你的明确授权;范围、非目标和验收标准可以留空,由中书拟案补齐,不必为此先追问。多项候选无法判断时问清楚。用户说「发布009吧」「下派 009」就是下派 R-009,直接调用工具,无需用户补写 R- 或「给中书」。以前聊天里的固定口令已经废止。遇到工具错误时报告实际错误。',
|
'你负责需求澄清、协调与交付。讨论、查资料或提到「下派」的例句均无执行授权。用户表达「照这个做」「安排下去」等清楚行动意图时,整理需求后可直接用 sansheng_requirement_publish 交给中书。下派只需要需求标题、用户原话和你的明确授权;范围、非目标和验收标准可以留空,由中书拟案补齐,不必为此先追问。多项候选无法判断时问清楚。用户说「发布009吧」「下派 009」就是下派 R-009,直接调用工具,无需用户补写 R- 或「给中书」。以前聊天里的固定口令已经废止。遇到工具错误时报告实际错误。',
|
||||||
'只有 judgement 明确为 not_now 时才阻止下派;空白或 needs_discussion 都可在用户明确授权后进入中书,由中书拟案判断可行性。',
|
'只有 judgement 明确为 not_now 时才阻止下派;空白或 needs_discussion 都可在用户明确授权后进入中书,由中书拟案判断可行性。',
|
||||||
'丞相专心和用户对话。谈妥且用户明确授权下派后,调用 sansheng_requirement_publish 直接交中书省拟案;需要进一步追问澄清时直接整理进需求清单并向用户确认,确认之前只整理、不发布。',
|
'用 sansheng_lead_delegate 将需求的记录、下派、查询和取消交给 intake,把催办交给 liaison。下派前须有用户清晰授权;委托入队后等助手回报结果。仅在助手明确不可用且未入队时,使用原需求或会商工具继续处理。',
|
||||||
'已发布任务的补充沟通和催办用 sansheng_task_consult,系统直接转达目标席位;日常进展看工作台。',
|
FAST_LANE_GUIDANCE,
|
||||||
'收到系统推送的 sansheng-report 阶段或审批回报时,用零基础白话向用户说明阶段结论、交付和需要决定的问题,说明发生了什么、影响和下一步。一次问一个关键问题。',
|
'收到系统推送的 sansheng-report 阶段或审批回报时,用零基础白话向用户说明阶段结论、交付和需要决定的问题,说明发生了什么、影响和下一步。一次问一个关键问题。',
|
||||||
'需要用户回答或审批时用 sansheng_card 挂卡:问题卡给 2 到 5 个选项;审批卡必须带审批报告里的审批编号作为 approvalId,正文写清谁申请、要做什么、原因、同意和拒绝的后果。卡片不阻塞聊天,用户可以继续说话或回头答旧卡;你只解释,不代批。审批结论由用户点卡送回原审批请求。',
|
'需要用户回答或审批时用 sansheng_card 挂卡:问题卡给 2 到 5 个选项;审批卡必须带审批报告里的审批编号作为 approvalId,正文写清谁申请、要做什么、原因、同意和拒绝的后果。卡片不阻塞聊天,用户可以继续说话或回头答旧卡;你只解释,不代批。审批结论由用户点卡送回原审批请求。',
|
||||||
'Grill Me 需求澄清规则:只有会显著改变范围、验收、成本或风险的歧义才调用 skill({ name: "grilling" })。技能不可用时说明实际情况。先自行查证事实,一次问一个会改变方案的问题。用户主动要求 Grill Me 时按技能处理。必要信息已齐或用户要求停止时结束追问。仅讨论和查资料时无需追问。用户明确要求「问清楚就做」时,在同一条需求草稿保存 dispatchAfterClarification=true;得到必要答复后设置 authorization=clarified 下派。扩大范围、换目标、拒绝或撤回时清除预授权,等新的授权。',
|
'Grill Me 需求澄清规则:只有会显著改变范围、验收、成本或风险的歧义才调用 skill({ name: "grilling" })。技能不可用时说明实际情况。先自行查证事实,一次问一个会改变方案的问题。用户主动要求 Grill Me 时按技能处理。必要信息已齐或用户要求停止时结束追问。仅讨论和查资料时无需追问。用户明确要求「问清楚就做」时,在同一条需求草稿保存 dispatchAfterClarification=true;得到必要答复后设置 authorization=clarified 下派。扩大范围、换目标、拒绝或撤回时清除预授权,等新的授权。',
|
||||||
|
|
@ -37,25 +40,57 @@ export function renderSeatPrompt({ project, seatId, seat }) {
|
||||||
} else if (seatId === 'shangshu') {
|
} else if (seatId === 'shangshu') {
|
||||||
lines.push('尚书调度:用 sansheng_workflow_dispatch 一次派发,沿用门下批准的范围和需求快照。单一交付由一个主责席承办,只有可独立推进的交付才拆给多席。执行结束后用 sansheng_workflow_summarize 提交真实结果。')
|
lines.push('尚书调度:用 sansheng_workflow_dispatch 一次派发,沿用门下批准的范围和需求快照。单一交付由一个主责席承办,只有可独立推进的交付才拆给多席。执行结束后用 sansheng_workflow_summarize 提交真实结果。')
|
||||||
} else if (['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'].includes(seatId)) {
|
} else if (['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'].includes(seatId)) {
|
||||||
lines.push('六部按下派范围执行,必要时与参与席会商。结束时用 sansheng_task_report 提交一次终态回报,完成附文件和验证结果,失败附具体阻塞。')
|
lines.push('用户在本会话亲自交代独立任务时,按用户要求直接执行并向用户汇报,无需索要上层公文。带任务编号的正式派工按下派范围执行,必要时与参与席会商,结束时用 sansheng_task_report 提交终态回报。完成附文件和验证结果,失败附具体阻塞。执行操作均遵从宿主审批。快车道先核对范围,若实际涉及超过 3 个文件、架构或公共契约变更,停止修改,调用 sansheng_task_report,status 设为 escalate 并说明原因,由丞相发起完整流程。')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
lines.push('只在本项目本席会话内工作;不要修改其他项目或其他席的配置,也不要替用户提升权限。')
|
lines.push('只在本项目本席会话内工作;不要修改其他项目或其他席的配置,也不要替用户提升权限。')
|
||||||
return lines.join('\n')
|
return lines.join('\n')
|
||||||
}
|
}
|
||||||
|
|
||||||
// 注册动态 systemPrompt section:只对十席会话注入本席角色文本,其它会话返回空串。
|
function renderAssistantPrompt({ project, role }) {
|
||||||
|
const intro = `你是「${project.name}」项目的${role === 'intake' ? '需求书记官' : '三省联络官'}。只做本项目协调和只读调查,所有工程操作交由执行席。`
|
||||||
|
if (role === 'intake') {
|
||||||
|
return [intro,
|
||||||
|
'只处理本轮带「书记官交接」的事项。用需求工具记录原话和已确认内容。更新携带最新版本。用户明确要求澄清后继续时保存 dispatchAfterClarification,后续回答用 clarified。发布须经过后端的本轮授权检查。',
|
||||||
|
FAST_LANE_GUIDANCE,
|
||||||
|
'收到工具失败时如实记录,遇到无法判断的候选或缺失关键信息,保留待确认状态。',
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
return [intro,
|
||||||
|
'接收三省六部阶段回报和催办。用 sansheng_task_consult 对接相关席位,有实质分歧时用 sansheng_task_decision 记录裁决。',
|
||||||
|
'仅在需要用户审批或裁决、出现阻塞、或交付完成时调用一次 sansheng_lead_brief,带原始回报编号,简述发生了什么、影响和下一步。审批摘要写明申请席位、操作、原因及同意和拒绝的后果,审批编号由后端保留。',
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
export function installPromptSection(ctx, { store }) {
|
export function installPromptSection(ctx, { store }) {
|
||||||
return ctx.systemPrompt.section({
|
const locate = context => {
|
||||||
|
const sessionId = context?.agent?.session?.id ?? context?.agent?.id
|
||||||
|
return {
|
||||||
|
seat: seatBySessionId(store.state?.projects, sessionId),
|
||||||
|
assistant: leadAssistantBySession(store.state?.projects, sessionId),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const offSection = ctx.systemPrompt.section({
|
||||||
name: PROMPT_SECTION,
|
name: PROMPT_SECTION,
|
||||||
order: 60,
|
order: 60,
|
||||||
interpolate: false,
|
interpolate: false,
|
||||||
text: context => {
|
text: context => {
|
||||||
const sessionId = context?.agent?.session?.id ?? context?.agent?.id
|
const { seat } = locate(context)
|
||||||
if (!sessionId) return ''
|
if (!seat || seat.project.seats[seat.seatId].sessionPreset === 'minimal') return ''
|
||||||
const found = seatBySessionId(store.state?.projects, sessionId)
|
return renderSeatPrompt(seat)
|
||||||
if (!found) return ''
|
|
||||||
return renderSeatPrompt({ project: found.project, seatId: found.seatId, seat: found.seat })
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
// minimal 的完整角色前缀会遮盖普通提示段,但保留宿主标记为 required 的业务上下文。
|
||||||
|
const offContext = ctx.systemPrompt.context?.({
|
||||||
|
name: 'sansheng-session-role',
|
||||||
|
order: 60,
|
||||||
|
interpolate: false,
|
||||||
|
required: true,
|
||||||
|
text: context => {
|
||||||
|
const { seat, assistant } = locate(context)
|
||||||
|
if (assistant) return renderAssistantPrompt(assistant)
|
||||||
|
return seat?.project.seats[seat.seatId].sessionPreset === 'minimal' ? renderSeatPrompt(seat) : ''
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return () => { offContext?.(); offSection?.() }
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
import { randomUUID } from 'node:crypto'
|
import { randomUUID } from 'node:crypto'
|
||||||
import { SEAT_IDS, SEATS } from '../shared/roles.js'
|
import { SEAT_IDS, SEATS } from '../shared/roles.js'
|
||||||
import { applyModel } from './model.js'
|
import { applyModel } from './model.js'
|
||||||
|
import { createLeadAssistantProvisioner } from './lead-assistant-provision.js'
|
||||||
import { knownSessionPreset, readSessionPreset, resolveSeatPreset } from './seat-preset.js'
|
import { knownSessionPreset, readSessionPreset, resolveSeatPreset } from './seat-preset.js'
|
||||||
|
|
||||||
export class ProvisionError extends Error {
|
export class ProvisionError extends Error {
|
||||||
|
|
@ -17,7 +18,7 @@ function isNotFound(error) {
|
||||||
return /not.?found|不存在|ENOENT/i.test(message)
|
return /not.?found|不存在|ENOENT/i.test(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createProvisioner({ store, host, globalStore = null, modelSync = null, now = () => Date.now() }) {
|
export function createProvisioner({ store, host, globalStore = null, modelSync = null, leadAssistantModel = null, now = () => Date.now() }) {
|
||||||
const locks = new Map()
|
const locks = new Map()
|
||||||
const titlesEnsured = new Set()
|
const titlesEnsured = new Set()
|
||||||
// 席位绑定变化事件:工具注册必须挂到“绑定成功”这一步,而不是只靠可能先到的 agent/created。
|
// 席位绑定变化事件:工具注册必须挂到“绑定成功”这一步,而不是只靠可能先到的 agent/created。
|
||||||
|
|
@ -430,5 +431,9 @@ export function createProvisioner({ store, host, globalStore = null, modelSync =
|
||||||
for (const seatId of SEAT_IDS) await renameSeatTitle(projectId, seatId)
|
for (const seatId of SEAT_IDS) await renameSeatTitle(projectId, seatId)
|
||||||
}
|
}
|
||||||
|
|
||||||
return { enable, enableSeat, ensureSeat, openSeat, rebuildSeat, ensureTitles, onSeatChange }
|
const ensureLeadAssistant = createLeadAssistantProvisioner({
|
||||||
|
store, host, now, model: leadAssistantModel,
|
||||||
|
onBound: (projectId, role, sessionId) => emitSeatChange({ type: 'bound', projectId, role, sessionId }),
|
||||||
|
})
|
||||||
|
return { enable, enableSeat, ensureSeat, openSeat, rebuildSeat, ensureTitles, onSeatChange, ensureLeadAssistant }
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ export function readSessionPreset(host, agent) {
|
||||||
export function resolveSeatPreset(seatId, seat, globalPreset) {
|
export function resolveSeatPreset(seatId, seat, globalPreset) {
|
||||||
if (seat?.agentPreset != null) return { configuredPreset: seat.agentPreset, presetSource: 'project' }
|
if (seat?.agentPreset != null) return { configuredPreset: seat.agentPreset, presetSource: 'project' }
|
||||||
if (globalPreset != null) return { configuredPreset: globalPreset, presetSource: 'global' }
|
if (globalPreset != null) return { configuredPreset: globalPreset, presetSource: 'global' }
|
||||||
|
// 宿主 0.2.2-rc.5 的极简模式支持上下文压缩,但缺少技能加载,因此丞相和尚书默认使用标准模式。
|
||||||
const configuredPreset = SEAT_GROUPS.liubu.includes(seatId) ? 'ops-ptc' : 'standard'
|
const configuredPreset = SEAT_GROUPS.liubu.includes(seatId) ? 'ops-ptc' : 'standard'
|
||||||
return { configuredPreset, presetSource: 'role-default' }
|
return { configuredPreset, presetSource: 'role-default' }
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto'
|
||||||
import { SEATS } from '../../shared/roles.js'
|
import { SEATS } from '../../shared/roles.js'
|
||||||
import { cleanText } from '../../shared/utils.js'
|
import { cleanText } from '../../shared/utils.js'
|
||||||
import { internalSource } from '../message-source.js'
|
import { internalSource } from '../message-source.js'
|
||||||
import { ServiceError, queueDelivery, voidDelivery } from './shared.js'
|
import { ServiceError, appendLeadReport, queueDelivery, voidDelivery } from './shared.js'
|
||||||
import { handOffReviewedTask, legacyApprovalDecision, requirementBlockedReason } from './requirement-helpers.js'
|
import { handOffReviewedTask, legacyApprovalDecision, requirementBlockedReason } from './requirement-helpers.js'
|
||||||
|
|
||||||
/** 挂载到 SanshengService 的任务会商与决策方法集。 */
|
/** 挂载到 SanshengService 的任务会商与决策方法集。 */
|
||||||
|
|
@ -15,7 +15,8 @@ export const consultationServiceMethods = {
|
||||||
throw new ServiceError('sansheng/invalid', '请指定商议对象及问题或结论')
|
throw new ServiceError('sansheng/invalid', '请指定商议对象及问题或结论')
|
||||||
}
|
}
|
||||||
const requiresDecision = toSeatIds.includes('lead') && input.requiresDecision !== false
|
const requiresDecision = toSeatIds.includes('lead') && input.requiresDecision !== false
|
||||||
const { task, entry } = await this.store.mutate(state => {
|
const liaisonEnabled = this.leadReporter?.liaisonEnabled
|
||||||
|
const { task, entry, leadReport } = await this.store.mutate(state => {
|
||||||
const project = state.projects[projectId]
|
const project = state.projects[projectId]
|
||||||
const task = project?.tasks?.find(item => item.id === taskId && item.kind === 'workflow')
|
const task = project?.tasks?.find(item => item.id === taskId && item.kind === 'workflow')
|
||||||
const requirement = project?.requirements?.find(item => item.id === task?.requirementId)
|
const requirement = project?.requirements?.find(item => item.id === task?.requirementId)
|
||||||
|
|
@ -34,7 +35,10 @@ export const consultationServiceMethods = {
|
||||||
if (actor.seatId === 'lead') task.awaitingLeadDecision = false
|
if (actor.seatId === 'lead') task.awaitingLeadDecision = false
|
||||||
task.updatedAt = entry.createdAt
|
task.updatedAt = entry.createdAt
|
||||||
project.revision += 1
|
project.revision += 1
|
||||||
return structuredClone({ task, entry })
|
const leadReport = liaisonEnabled && toSeatIds.includes('lead') ? appendLeadReport(state, projectId, task,
|
||||||
|
requiresDecision ? 'decision_required' : 'task_consultation', text,
|
||||||
|
{ transitionId: 'consultation:' + entry.id, consultationId: entry.id, needsUserDecision: requiresDecision }) : null
|
||||||
|
return structuredClone({ task, entry, leadReport })
|
||||||
})
|
})
|
||||||
const snapshot = task.requirementSnapshot ?? {}
|
const snapshot = task.requirementSnapshot ?? {}
|
||||||
const context = [snapshot.originalText || task.requirement, snapshot.scope, snapshot.acceptanceCriteria].filter(Boolean).join('\n')
|
const context = [snapshot.originalText || task.requirement, snapshot.scope, snapshot.acceptanceCriteria].filter(Boolean).join('\n')
|
||||||
|
|
@ -55,6 +59,11 @@ export const consultationServiceMethods = {
|
||||||
return project
|
return project
|
||||||
}
|
}
|
||||||
const delivery = await Promise.allSettled(toSeatIds.map(async seatId => {
|
const delivery = await Promise.allSettled(toSeatIds.map(async seatId => {
|
||||||
|
if (seatId === 'lead' && leadReport) {
|
||||||
|
const outcome = await this.leadReporter.send(projectId, leadReport.reportId)
|
||||||
|
if (!outcome.ok && outcome.status !== 'in-flight') throw new ServiceError('sansheng/delivery-failed', '会商回报未确认送达')
|
||||||
|
return outcome
|
||||||
|
}
|
||||||
await this.provisioner.enableSeat(projectId, seatId)
|
await this.provisioner.enableSeat(projectId, seatId)
|
||||||
const project = currentProject()
|
const project = currentProject()
|
||||||
return this._deliverInternal(project.seats[seatId].sessionId, message, internalSource('sansheng-task', { seatId, taskId }))
|
return this._deliverInternal(project.seats[seatId].sessionId, message, internalSource('sansheng-task', { seatId, taskId }))
|
||||||
|
|
@ -69,7 +78,7 @@ export const consultationServiceMethods = {
|
||||||
if (!question || options.length < 2 || options.length > 5 || options.some(option => !option.label)) {
|
if (!question || options.length < 2 || options.length > 5 || options.some(option => !option.label)) {
|
||||||
throw new ServiceError('sansheng/invalid', '请说明需要用户选择的问题并给出 2 到 5 个选项')
|
throw new ServiceError('sansheng/invalid', '请说明需要用户选择的问题并给出 2 到 5 个选项')
|
||||||
}
|
}
|
||||||
return this.store.mutate(state => {
|
const result = await this.store.mutate(state => {
|
||||||
const project = state.projects[projectId]
|
const project = state.projects[projectId]
|
||||||
const task = project?.tasks?.find(item => item.id === taskId && item.kind === 'workflow')
|
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', '任务已结束或需求已更新')
|
if (!task || ['done', 'cancelled', 'reconfirm'].includes(task.status)) throw new ServiceError('sansheng/stage-forbidden', '任务已结束或需求已更新')
|
||||||
|
|
@ -81,8 +90,13 @@ export const consultationServiceMethods = {
|
||||||
task.awaitingLeadDecision = false
|
task.awaitingLeadDecision = false
|
||||||
task.updatedAt = decision.createdAt
|
task.updatedAt = decision.createdAt
|
||||||
project.revision += 1
|
project.revision += 1
|
||||||
return { decision }
|
const report = this.leadReporter?.liaisonEnabled ? appendLeadReport(state, projectId, task,
|
||||||
|
'user_decision', [question, ...options.map(option => option.label)].join('\n'),
|
||||||
|
{ transitionId: 'decision:' + decision.id, decisionId: decision.id, needsUserDecision: true }) : null
|
||||||
|
return { decision, reportId: report?.reportId }
|
||||||
})
|
})
|
||||||
|
if (result.reportId) this._flushLeadReports(projectId)
|
||||||
|
return result
|
||||||
},
|
},
|
||||||
|
|
||||||
async surfaceLegacyApprovals() {
|
async surfaceLegacyApprovals() {
|
||||||
|
|
|
||||||
|
|
@ -2,9 +2,18 @@
|
||||||
import { randomUUID } from 'node:crypto'
|
import { randomUUID } from 'node:crypto'
|
||||||
import { SEATS } from '../../shared/roles.js'
|
import { SEATS } from '../../shared/roles.js'
|
||||||
import { normalizeProjectMemory, renderProjectMemory } from '../../shared/project-memory.js'
|
import { normalizeProjectMemory, renderProjectMemory } from '../../shared/project-memory.js'
|
||||||
|
import { assertFastApproval } from './fast-lane.js'
|
||||||
import { ServiceError, queueDelivery, readyForDepartmentSummary } from './shared.js'
|
import { ServiceError, queueDelivery, readyForDepartmentSummary } from './shared.js'
|
||||||
|
|
||||||
|
function fastDispatchClosed(task) {
|
||||||
|
return task.lane === 'fast' && (task.parentTaskId != null || task.stage !== 'department_exec'
|
||||||
|
|| !['draft', 'dispatched', 'running'].includes(task.status))
|
||||||
|
}
|
||||||
|
|
||||||
function workflowStageHint(task) {
|
function workflowStageHint(task) {
|
||||||
|
if (task.lane === 'fast') {
|
||||||
|
return '快车道 · 未经门下审核。只做用户已授权的快照范围内的工作。用 sansheng_task_report 提交真实结果;范围扩大或需要完整流程时用 escalate 说明阻塞。'
|
||||||
|
}
|
||||||
const hints = {
|
const hints = {
|
||||||
zhongshu_draft: '根据用户原话和已确认内容给出简短拟案;需求缺少范围、非目标或验收标准时,用 sansheng_workflow_submit 的结构化字段补入任务快照后再交门下,退回后可修订自己补的字段。拟案阶段只读。',
|
zhongshu_draft: '根据用户原话和已确认内容给出简短拟案;需求缺少范围、非目标或验收标准时,用 sansheng_workflow_submit 的结构化字段补入任务快照后再交门下,退回后可修订自己补的字段。拟案阶段只读。',
|
||||||
menxia_review: '用 sansheng_workflow_review 提交审核,批准前确认范围与验收标准齐全。通过后系统交尚书,发现实质问题时说明原因退回中书补齐。',
|
menxia_review: '用 sansheng_workflow_review 提交审核,批准前确认范围与验收标准齐全。通过后系统交尚书,发现实质问题时说明原因退回中书补齐。',
|
||||||
|
|
@ -48,6 +57,9 @@ export const deliveryServiceMethods = {
|
||||||
if (!initialTask) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
if (!initialTask) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||||
const redispatch = options.redispatch === true
|
const redispatch = options.redispatch === true
|
||||||
const requestedId = typeof options.deliveryId === 'string' && options.deliveryId.trim() ? options.deliveryId.trim() : null
|
const requestedId = typeof options.deliveryId === 'string' && options.deliveryId.trim() ? options.deliveryId.trim() : null
|
||||||
|
if (fastDispatchClosed(initialTask)) {
|
||||||
|
throw new ServiceError('sansheng/invalid', '快车道任务已停止,不能投递')
|
||||||
|
}
|
||||||
const needsSeat = redispatch
|
const needsSeat = redispatch
|
||||||
? Boolean(requestedId && initialTask.deliveryId === requestedId && initialTask.deliveryState === 'unknown'
|
? Boolean(requestedId && initialTask.deliveryId === requestedId && initialTask.deliveryState === 'unknown'
|
||||||
&& !['cancelled', 'done', 'reconfirm'].includes(initialTask.status))
|
&& !['cancelled', 'done', 'reconfirm'].includes(initialTask.status))
|
||||||
|
|
@ -68,6 +80,7 @@ export const deliveryServiceMethods = {
|
||||||
const targetProject = s.projects[projectId]
|
const targetProject = s.projects[projectId]
|
||||||
const target = (targetProject?.tasks ?? []).find(item => item.id === taskId)
|
const target = (targetProject?.tasks ?? []).find(item => item.id === taskId)
|
||||||
if (!target) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
if (!target) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||||
|
if (fastDispatchClosed(target)) return { claimed: false, reason: 'task-closed', task: { ...target } }
|
||||||
if (redispatch) {
|
if (redispatch) {
|
||||||
if (!requestedId || target.deliveryId !== requestedId) return { claimed: false, reason: 'delivery-mismatch', task: { ...target } }
|
if (!requestedId || target.deliveryId !== requestedId) return { claimed: false, reason: 'delivery-mismatch', task: { ...target } }
|
||||||
if (target.deliveryState !== 'unknown') return { claimed: false, reason: 'not-redispatchable', task: { ...target } }
|
if (target.deliveryState !== 'unknown') return { claimed: false, reason: 'not-redispatchable', task: { ...target } }
|
||||||
|
|
@ -84,6 +97,11 @@ export const deliveryServiceMethods = {
|
||||||
// 阶段切换登记的是 pending;若中途被取消或改要求作废,就不能再发。
|
// 阶段切换登记的是 pending;若中途被取消或改要求作废,就不能再发。
|
||||||
if (requestedId && target.deliveryState !== 'pending') return { claimed: false, reason: 'stage-changed', task: { ...target } }
|
if (requestedId && target.deliveryState !== 'pending') return { claimed: false, reason: 'stage-changed', task: { ...target } }
|
||||||
}
|
}
|
||||||
|
if (target.lane === 'fast') {
|
||||||
|
const approval = (targetProject.approvals ?? []).find(item => item.id === target.approvalId)
|
||||||
|
const req = (targetProject.requirements ?? []).find(item => item.id === target.requirementId)
|
||||||
|
assertFastApproval(target, approval, req)
|
||||||
|
}
|
||||||
const seat = targetProject.seats?.[target.ownerSeatId]
|
const seat = targetProject.seats?.[target.ownerSeatId]
|
||||||
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||||||
throw new ServiceError('sansheng/seat-unbound', `「${SEATS[target.ownerSeatId]?.label ?? target.ownerSeatId}」的会话还没开启成功,请稍后重试`)
|
throw new ServiceError('sansheng/seat-unbound', `「${SEATS[target.ownerSeatId]?.label ?? target.ownerSeatId}」的会话还没开启成功,请稍后重试`)
|
||||||
|
|
@ -95,6 +113,7 @@ export const deliveryServiceMethods = {
|
||||||
target.deliveryState = 'sending'
|
target.deliveryState = 'sending'
|
||||||
target.sendingOwner = attemptId
|
target.sendingOwner = attemptId
|
||||||
target.sendingAt = now
|
target.sendingAt = now
|
||||||
|
if (target.lane === 'fast') target.sessionId = seat.sessionId
|
||||||
// 重投保留阶段切换时存下的目标状态;只有旧数据缺字段时才补 dispatched。
|
// 重投保留阶段切换时存下的目标状态;只有旧数据缺字段时才补 dispatched。
|
||||||
if (redispatch) target.deliveryStatus ??= 'dispatched'
|
if (redispatch) target.deliveryStatus ??= 'dispatched'
|
||||||
target.updatedAt = now
|
target.updatedAt = now
|
||||||
|
|
@ -134,6 +153,7 @@ export const deliveryServiceMethods = {
|
||||||
return !!current && current.deliveryId === claim.deliveryId
|
return !!current && current.deliveryId === claim.deliveryId
|
||||||
&& current.deliveryState === 'sending' && current.sendingOwner === claim.attemptId
|
&& current.deliveryState === 'sending' && current.sendingOwner === claim.attemptId
|
||||||
&& currentSeat?.sessionId === claim.sessionId
|
&& currentSeat?.sessionId === claim.sessionId
|
||||||
|
&& !fastDispatchClosed(current)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
@ -174,6 +194,12 @@ export const deliveryServiceMethods = {
|
||||||
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||||||
return { applied: true, task: { ...target } }
|
return { applied: true, task: { ...target } }
|
||||||
})
|
})
|
||||||
|
// 快车道终态可能先落盘,投递回执应反映已持久化的状态。
|
||||||
|
if (!written.applied && written.task?.lane === 'fast') {
|
||||||
|
const task = written.task
|
||||||
|
return { task, delivered: task.deliveryState === 'accepted', duplicate: false, applied: false,
|
||||||
|
deliveryState: task.deliveryState, reason: 'stage-changed' }
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
task: written.task ?? claim.task,
|
task: written.task ?? claim.task,
|
||||||
delivered: outcome === 'sent',
|
delivered: outcome === 'sent',
|
||||||
|
|
@ -205,7 +231,7 @@ export const deliveryServiceMethods = {
|
||||||
const sending = []
|
const sending = []
|
||||||
for (const project of this.store.list()) {
|
for (const project of this.store.list()) {
|
||||||
for (const task of project.tasks ?? []) {
|
for (const task of project.tasks ?? []) {
|
||||||
if (task.deliveryState === 'pending' && !['done', 'cancelled', 'reconfirm'].includes(task.status)) {
|
if (task.deliveryState === 'pending' && !fastDispatchClosed(task) && !['done', 'cancelled', 'reconfirm'].includes(task.status)) {
|
||||||
pending.push({ projectId: project.id, taskId: task.id, deliveryId: task.deliveryId })
|
pending.push({ projectId: project.id, taskId: task.id, deliveryId: task.deliveryId })
|
||||||
} else if (task.deliveryState === 'sending') {
|
} else if (task.deliveryState === 'sending') {
|
||||||
sending.push({ projectId: project.id, taskId: task.id, deliveryId: task.deliveryId })
|
sending.push({ projectId: project.id, taskId: task.id, deliveryId: task.deliveryId })
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,85 @@
|
||||||
|
import { SEAT_GROUPS, SEATS } from '../../shared/roles.js'
|
||||||
|
import { cleanText } from '../../shared/utils.js'
|
||||||
|
import { ServiceError } from './shared.js'
|
||||||
|
|
||||||
|
const FULL_INTENT = /走(?:完整|正常|正式)?流程|先(?:出|做|拟|起草)(?:个|一份|一下)?方案|(?:让|由|请|交给?)门下.{0,8}(?:审|验收)|(?:给|交给?)中书(?:省)?|中书(?:省)?(?:先|拟案)/
|
||||||
|
const FAST_INTENT = /快车道|快速(?:通道|下派|派工)|直派|直接(?:让|给|下派|派|交|发给|做|执行|开工)|\bfast[- ]lane\b/i
|
||||||
|
const SKIP_FULL_INTENT = /(?:别|不要|不用|无需|不)走(?:完整|正常|正式)?流程/g
|
||||||
|
const NEGATED_FAST = /(?:不想|不要|别|先不|暂不|不急着|不能|尚未|还没)[^,。!?、;\s]{0,4}(?:快车道|直派|直接|快速)/
|
||||||
|
const DIRECT_EXECUTION_INTENT = /(?:^|[,。;!!\n]\s*)(?:请|帮我|麻烦|劳烦)?(?:把|将|修复|修正|调整|修改|更新|替换|改一下|加上|去掉|按(?:这个|这版|此方案)做|照(?:这个|这版)做)|^(?:可以|同意|确认)(?:执行|开工|下派)/
|
||||||
|
|
||||||
|
export function requestsFullLane(command) {
|
||||||
|
return FULL_INTENT.test(command.replace(SKIP_FULL_INTENT, ''))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requestsFastLane(command) {
|
||||||
|
return !NEGATED_FAST.test(command) && (FAST_INTENT.test(command) || command.replace(SKIP_FULL_INTENT, '') !== command)
|
||||||
|
}
|
||||||
|
|
||||||
|
function namedMinistries(command) {
|
||||||
|
const words = command.toLowerCase().match(/[a-z]+/g) ?? []
|
||||||
|
return SEAT_GROUPS.liubu.filter(id => command.includes(SEATS[id].label) || words.includes(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assertFastPublishCommand(project, actor, command, commandRef) {
|
||||||
|
const current = actor.readCurrentCommand?.()
|
||||||
|
if (actor.seatId !== 'lead' || !actor.sessionId || project?.seats?.lead?.sessionId !== actor.sessionId
|
||||||
|
|| !current || (current.sessionId != null && current.sessionId !== actor.sessionId)
|
||||||
|
|| !Number.isSafeInteger(current.seq) || current.seq !== commandRef?.seq
|
||||||
|
|| !current.messageId || current.messageId !== commandRef?.messageId || cleanText(current.text) !== command) {
|
||||||
|
throw new ServiceError('sansheng/current-user-message-unavailable', '宿主未能验证丞相本轮用户消息,本次下派没有执行')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assertFastRequirement(req, command, targetSeatId, authorization) {
|
||||||
|
if (!SEAT_GROUPS.liubu.includes(targetSeatId)) {
|
||||||
|
throw new ServiceError('sansheng/workflow-route-forbidden', '快车道必须只指定一个六部席位')
|
||||||
|
}
|
||||||
|
const clarified = authorization === 'clarified'
|
||||||
|
const direct = requestsFastLane(command) || DIRECT_EXECUTION_INTENT.test(command)
|
||||||
|
if (NEGATED_FAST.test(command) || (!direct && !(clarified && req.dispatchAuthorization?.lane === 'fast'))) {
|
||||||
|
throw new ServiceError('sansheng/publish-not-explicit', '请用户明确同意直接下派后再使用快车道')
|
||||||
|
}
|
||||||
|
const namedSeats = [...namedMinistries(command), ...(clarified ? req.dispatchAuthorization?.targetSeatIds ?? [] : [])]
|
||||||
|
if (namedSeats.some(seatId => seatId !== targetSeatId)) {
|
||||||
|
throw new ServiceError('sansheng/workflow-route-forbidden', '快车道只能交给用户明确指定的一个六部席位')
|
||||||
|
}
|
||||||
|
const missingInfo = cleanText(req.missingInfo)
|
||||||
|
if (!cleanText(req.scope) || !cleanText(req.acceptanceCriteria) || (missingInfo && !/^(?:无|暂无|没有|无待补信息|none|n\/a)[。.]?$/i.test(missingInfo))) {
|
||||||
|
throw new ServiceError('sansheng/requirement-incomplete', '快车道需要明确的范围与验收标准,且没有待补信息')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fastClarificationAuthorization(command) {
|
||||||
|
return requestsFastLane(command) && !requestsFullLane(command)
|
||||||
|
? { lane: 'fast', targetSeatIds: namedMinistries(command) }
|
||||||
|
: {}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createFastApproval(project, req, task, now) {
|
||||||
|
project.approvalSeq = (project.approvalSeq ?? 0) + 1
|
||||||
|
const approval = {
|
||||||
|
id: `AP-${String(project.approvalSeq).padStart(3, '0')}`,
|
||||||
|
requirementId: req.id, requirementRevision: req.revision, scope: req.scope,
|
||||||
|
status: 'approved', approvedAt: now, approvedBy: 'lead', source: 'user-fast-lane',
|
||||||
|
taskId: task.id, targetSeatId: task.ownerSeatId,
|
||||||
|
}
|
||||||
|
project.approvals ??= []
|
||||||
|
project.approvals.push(approval)
|
||||||
|
return approval
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validFastApproval(task, approval, req) {
|
||||||
|
return task.kind === 'execution' && task.unreviewedByMenxia === true && task.parentTaskId == null
|
||||||
|
&& SEAT_GROUPS.liubu.includes(task.ownerSeatId) && approval?.source === 'user-fast-lane'
|
||||||
|
&& approval.status === 'approved' && approval.taskId === task.id && approval.targetSeatId === task.ownerSeatId
|
||||||
|
&& approval.requirementId === task.requirementId && req?.status === 'published'
|
||||||
|
&& req.revision === task.requirementRevision && approval.requirementRevision === task.requirementRevision
|
||||||
|
&& Boolean(task.approvalScope) && task.approvalScope === approval.scope
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assertFastApproval(task, approval, req) {
|
||||||
|
if (!validFastApproval(task, approval, req)) {
|
||||||
|
throw new ServiceError('sansheng/approval-invalid', '快车道批准已失效或与任务不匹配,请重新确认需求')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -33,7 +33,7 @@ export const modelServiceMethods = {
|
||||||
await this.store.ensureLoaded()
|
await this.store.ensureLoaded()
|
||||||
if (!this.globalStore) throw new ServiceError('sansheng/global-setting-missing', '未配置全局默认模型存储')
|
if (!this.globalStore) throw new ServiceError('sansheng/global-setting-missing', '未配置全局默认模型存储')
|
||||||
this._requireSeat(seatId)
|
this._requireSeat(seatId)
|
||||||
if (!validAgentPreset(agentPreset)) throw new ServiceError('sansheng/invalid', '执行模式必须是 standard、ops-ptc 或 null')
|
if (!validAgentPreset(agentPreset)) throw new ServiceError('sansheng/invalid', '执行模式必须是 minimal、standard、ops-ptc 或 null')
|
||||||
if (agentPreset !== undefined && model == null) {
|
if (agentPreset !== undefined && model == null) {
|
||||||
await this.globalStore.setSeatPreset(seatId, agentPreset)
|
await this.globalStore.setSeatPreset(seatId, agentPreset)
|
||||||
return { globalDefaults: await this.globalDefaults(), applied: [], failed: [], pending: [] }
|
return { globalDefaults: await this.globalDefaults(), applied: [], failed: [], pending: [] }
|
||||||
|
|
|
||||||
|
|
@ -106,7 +106,7 @@ export const projectServiceMethods = {
|
||||||
const project = await this._requireProject(projectId)
|
const project = await this._requireProject(projectId)
|
||||||
this._requireSeat(seatId)
|
this._requireSeat(seatId)
|
||||||
|
|
||||||
if (!validAgentPreset(agentPreset)) throw new ServiceError('sansheng/invalid', '执行模式必须是 standard、ops-ptc 或 null')
|
if (!validAgentPreset(agentPreset)) throw new ServiceError('sansheng/invalid', '执行模式必须是 minimal、standard、ops-ptc 或 null')
|
||||||
await this.globalStore?.ensureLoaded()
|
await this.globalStore?.ensureLoaded()
|
||||||
|
|
||||||
let normalized
|
let normalized
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,8 @@
|
||||||
import { emptyRequirement, emptyTask } from '../../shared/schema.js'
|
import { emptyRequirement, emptyTask } from '../../shared/schema.js'
|
||||||
import { cleanText } from '../../shared/utils.js'
|
import { cleanText } from '../../shared/utils.js'
|
||||||
import { getCommand, putCommand } from '../command-ledger.js'
|
import { getCommand, putCommand } from '../command-ledger.js'
|
||||||
|
import { explicitIntakeIntent } from '../lead-assistant-handoff.js'
|
||||||
|
import { assertFastPublishCommand, assertFastRequirement, createFastApproval, fastClarificationAuthorization, requestsFullLane } from './fast-lane.js'
|
||||||
import { OPEN_TASK_STATUS, ServiceError, queueDelivery } from './shared.js'
|
import { OPEN_TASK_STATUS, ServiceError, queueDelivery } from './shared.js'
|
||||||
import {
|
import {
|
||||||
REQUIREMENT_TEXT_FIELDS,
|
REQUIREMENT_TEXT_FIELDS,
|
||||||
|
|
@ -13,6 +15,13 @@ import {
|
||||||
requirementView,
|
requirementView,
|
||||||
} from './requirement-helpers.js'
|
} from './requirement-helpers.js'
|
||||||
|
|
||||||
|
function assertIntakeRequirement(req, actor, operation) {
|
||||||
|
const grant = actor.handoff
|
||||||
|
if (!grant || grant.operation !== operation || grant.requirementId !== req.id || grant.requirementRevision !== req.revision) {
|
||||||
|
throw new ServiceError('sansheng/requirement-conflict', '需求与书记官受托的编号或版本不一致,请重新确认')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** 挂载到 SanshengService 的需求管理与门控发布方法集。 */
|
/** 挂载到 SanshengService 的需求管理与门控发布方法集。 */
|
||||||
export const requirementServiceMethods = {
|
export const requirementServiceMethods = {
|
||||||
async requirements(projectId) {
|
async requirements(projectId) {
|
||||||
|
|
@ -60,8 +69,12 @@ export const requirementServiceMethods = {
|
||||||
if (!req.originalText) req.originalText = req.title
|
if (!req.originalText) req.originalText = req.title
|
||||||
const after = JSON.stringify(REQUIREMENT_TEXT_FIELDS.map(field => req[field] ?? ''))
|
const after = JSON.stringify(REQUIREMENT_TEXT_FIELDS.map(field => req[field] ?? ''))
|
||||||
const previousAuthorization = req.dispatchAuthorization
|
const previousAuthorization = req.dispatchAuthorization
|
||||||
if (input.dispatchAfterClarification === true && actor.command?.seq != null && actor.sessionId && !previousAuthorization) {
|
if (input.dispatchAfterClarification === true && actor.command?.seq != null && actor.sessionId && !previousAuthorization
|
||||||
req.dispatchAuthorization = { sessionId: actor.sessionId, seq: actor.command.seq }
|
&& (actor.assistantRole !== 'intake' || /(?:问清楚|澄清|确认清楚|补齐).{0,12}(?:就|后|再)(?:直接)?(?:做|执行|发布|下派|开工)/.test(actor.command.text))) {
|
||||||
|
req.dispatchAuthorization = {
|
||||||
|
sessionId: actor.sessionId, seq: actor.command.seq,
|
||||||
|
...fastClarificationAuthorization(cleanText(actor.command.text)),
|
||||||
|
}
|
||||||
} else if (input.dispatchAfterClarification === false || req.originalText !== originalText || req.status === 'published' || req.status === 'cancelled') {
|
} else if (input.dispatchAfterClarification === false || req.originalText !== originalText || req.status === 'published' || req.status === 'cancelled') {
|
||||||
delete req.dispatchAuthorization
|
delete req.dispatchAuthorization
|
||||||
}
|
}
|
||||||
|
|
@ -92,6 +105,16 @@ export const requirementServiceMethods = {
|
||||||
const req = (project.requirements ?? []).find(item => item.id === requirementId)
|
const req = (project.requirements ?? []).find(item => item.id === requirementId)
|
||||||
if (!req) throw new ServiceError('sansheng/not-found', `需求 ${requirementId} 不存在`)
|
if (!req) throw new ServiceError('sansheng/not-found', `需求 ${requirementId} 不存在`)
|
||||||
const now = Date.now()
|
const now = Date.now()
|
||||||
|
if (actor.assistantRole === 'intake') {
|
||||||
|
const command = actor.handoff?.command
|
||||||
|
assertFastPublishCommand(project, actor, command?.text, command)
|
||||||
|
assertIntakeRequirement(req, actor, 'cancel')
|
||||||
|
if (!explicitIntakeIntent(command.text, 'cancel')) {
|
||||||
|
throw new ServiceError('sansheng/publish-not-explicit', '请用户明确取消指定需求')
|
||||||
|
}
|
||||||
|
if (getCommand(project, actor.sessionId, command.seq)) throw new ServiceError('sansheng/command-used', '该用户消息已处理')
|
||||||
|
putCommand(project, { sessionId: actor.sessionId, ...command, outcome: 'cancelled', requirementId, requirementRevision: req.revision, at: now })
|
||||||
|
}
|
||||||
req.status = 'cancelled'
|
req.status = 'cancelled'
|
||||||
delete req.dispatchAuthorization
|
delete req.dispatchAuthorization
|
||||||
req.cancelledAt = now
|
req.cancelledAt = now
|
||||||
|
|
@ -105,15 +128,24 @@ export const requirementServiceMethods = {
|
||||||
},
|
},
|
||||||
|
|
||||||
async requirementPublish(projectId, requirementId, input = {}, actor = {}) {
|
async requirementPublish(projectId, requirementId, input = {}, actor = {}) {
|
||||||
await this._requireProject(projectId)
|
const projectBefore = await this._requireProject(projectId)
|
||||||
if (actor.seatId && actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以发布需求给中书省')
|
if (actor.seatId && actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以发布需求')
|
||||||
|
const lane = input.lane === undefined ? 'full' : input.lane
|
||||||
|
if (lane !== 'fast' && lane !== 'full') throw new ServiceError('sansheng/invalid', '下派方式必须是 full 或 fast')
|
||||||
const command = cleanText(input.command)
|
const command = cleanText(input.command)
|
||||||
|
const fast = lane === 'fast' && !requestsFullLane(command)
|
||||||
|
if (lane === 'full' && input.targetSeatId !== undefined && input.targetSeatId !== 'zhongshu') {
|
||||||
|
throw new ServiceError('sansheng/workflow-route-forbidden', '完整流程只能把需求发布给中书省')
|
||||||
|
}
|
||||||
const commandRef = input.commandRef && typeof input.commandRef === 'object' ? input.commandRef : null
|
const commandRef = input.commandRef && typeof input.commandRef === 'object' ? input.commandRef : null
|
||||||
const commandSeq = commandRef?.seq ?? null
|
const commandSeq = commandRef?.seq ?? null
|
||||||
const sessionId = actor.sessionId ?? null
|
const sessionId = actor.sessionId ?? null
|
||||||
const existing = getCommand(this.store.get(projectId), sessionId, commandSeq)
|
const intake = actor.assistantRole === 'intake'
|
||||||
|
const verifyLiveCommand = lane === 'fast' || intake
|
||||||
|
if (verifyLiveCommand) assertFastPublishCommand(projectBefore, actor, command, commandRef)
|
||||||
|
const existing = getCommand(projectBefore, sessionId, commandSeq)
|
||||||
if (existing) {
|
if (existing) {
|
||||||
if (existing.outcome === 'published') {
|
if (existing.outcome === 'published' && !intake) {
|
||||||
return { ok: true, duplicate: true, taskId: existing.taskId, deliveryId: existing.deliveryId, requirementId: existing.requirementId }
|
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 : ''}`)
|
throw new ServiceError('sansheng/command-used', `该发布命令已处理(${existing.outcome})${existing.error ? ':' + existing.error : ''}`)
|
||||||
|
|
@ -128,7 +160,9 @@ export const requirementServiceMethods = {
|
||||||
if (effectiveId && mentioned[0] !== effectiveId) throw new ServiceError('sansheng/requirement-conflict', '消息中的需求编号与待下派需求不一致')
|
if (effectiveId && mentioned[0] !== effectiveId) throw new ServiceError('sansheng/requirement-conflict', '消息中的需求编号与待下派需求不一致')
|
||||||
effectiveId = mentioned[0]
|
effectiveId = mentioned[0]
|
||||||
}
|
}
|
||||||
const projectBefore = this.store.get(projectId)
|
if (fast && mentioned.length > 1) {
|
||||||
|
throw new ServiceError('sansheng/requirement-ambiguous', '快车道每次只能发布一项需求,请确认需求编号')
|
||||||
|
}
|
||||||
if (!effectiveId && command) {
|
if (!effectiveId && command) {
|
||||||
const ready = (projectBefore.requirements ?? []).filter(item => requirementStatusOf(item) === 'ready')
|
const ready = (projectBefore.requirements ?? []).filter(item => requirementStatusOf(item) === 'ready')
|
||||||
if (ready.length === 1) effectiveId = ready[0].id
|
if (ready.length === 1) effectiveId = ready[0].id
|
||||||
|
|
@ -153,10 +187,17 @@ export const requirementServiceMethods = {
|
||||||
try {
|
try {
|
||||||
published = await this.store.mutate(s => {
|
published = await this.store.mutate(s => {
|
||||||
const project = s.projects[projectId]
|
const project = s.projects[projectId]
|
||||||
|
if (verifyLiveCommand) assertFastPublishCommand(project, actor, command, commandRef)
|
||||||
const used = getCommand(project, sessionId, commandSeq)
|
const used = getCommand(project, sessionId, commandSeq)
|
||||||
if (used) throw new ServiceError('sansheng/command-used', '该用户消息已处理')
|
if (used) throw new ServiceError('sansheng/command-used', '该用户消息已处理')
|
||||||
const req = (project.requirements ?? []).find(item => item.id === effectiveId)
|
const req = (project.requirements ?? []).find(item => item.id === effectiveId)
|
||||||
if (!req) throw new ServiceError('sansheng/not-found', `需求 ${effectiveId} 不存在`)
|
if (!req) throw new ServiceError('sansheng/not-found', `需求 ${effectiveId} 不存在`)
|
||||||
|
if (intake) {
|
||||||
|
assertIntakeRequirement(req, actor, 'publish')
|
||||||
|
if (input.authorization !== 'clarified' && !explicitIntakeIntent(command, 'publish')) {
|
||||||
|
throw new ServiceError('sansheng/publish-not-explicit', '请用户明确授权下派')
|
||||||
|
}
|
||||||
|
}
|
||||||
if (Number.isFinite(expectedRevision) && req.revision !== expectedRevision) throw new ServiceError('sansheng/requirement-conflict', `需求已更新到 v${req.revision},发布命令基于 v${expectedRevision},已失效`)
|
if (Number.isFinite(expectedRevision) && req.revision !== expectedRevision) throw new ServiceError('sansheng/requirement-conflict', `需求已更新到 v${req.revision},发布命令基于 v${expectedRevision},已失效`)
|
||||||
const currentStatus = requirementStatusOf(req)
|
const currentStatus = requirementStatusOf(req)
|
||||||
if (currentStatus !== 'ready') throw new ServiceError('sansheng/requirement-not-ready', `需求 ${req.id} 当前状态为 ${currentStatus},只有「待发布」的需求可以发布`)
|
if (currentStatus !== 'ready') throw new ServiceError('sansheng/requirement-not-ready', `需求 ${req.id} 当前状态为 ${currentStatus},只有「待发布」的需求可以发布`)
|
||||||
|
|
@ -165,7 +206,14 @@ export const requirementServiceMethods = {
|
||||||
}
|
}
|
||||||
const problem = requirementReadyProblem(req)
|
const problem = requirementReadyProblem(req)
|
||||||
if (problem) throw new ServiceError('sansheng/requirement-incomplete', `需求不可发布:${problem}`)
|
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 (fast) assertFastRequirement(req, command, input.targetSeatId, input.authorization)
|
||||||
|
const sameVersion = (project.tasks ?? []).filter(task => task.requirementId === req.id && task.requirementRevision === req.revision)
|
||||||
|
const escalated = task => task.lane === 'fast' && task.stage === 'reconfirm' && task.reportStatus === 'escalate'
|
||||||
|
if (sameVersion.some(escalated) && (fast || !requestsFullLane(command))) {
|
||||||
|
throw new ServiceError('sansheng/publish-not-explicit', '快车道已经升档,请等用户明确同意走完整流程后再发布')
|
||||||
|
}
|
||||||
|
const duplicate = sameVersion.find(task => !escalated(task)
|
||||||
|
&& (task.kind === 'workflow' || task.lane === 'fast') && OPEN_TASK_STATUS.has(task.status))
|
||||||
if (duplicate) throw new ServiceError('sansheng/requirement-duplicate', `需求 ${req.id} v${req.revision} 已发布,不能重复发布`)
|
if (duplicate) throw new ServiceError('sansheng/requirement-duplicate', `需求 ${req.id} v${req.revision} 已发布,不能重复发布`)
|
||||||
const now = Date.now()
|
const now = Date.now()
|
||||||
project.taskSeq = (project.taskSeq ?? 0) + 1
|
project.taskSeq = (project.taskSeq ?? 0) + 1
|
||||||
|
|
@ -174,15 +222,22 @@ export const requirementServiceMethods = {
|
||||||
title: `${req.id} · ${req.title}`,
|
title: `${req.id} · ${req.title}`,
|
||||||
goal: req.summary || req.scope || req.title,
|
goal: req.summary || req.scope || req.title,
|
||||||
requirement: req.originalText,
|
requirement: req.originalText,
|
||||||
ownerSeatId: 'zhongshu',
|
ownerSeatId: fast ? input.targetSeatId : 'zhongshu',
|
||||||
kind: 'workflow',
|
kind: fast ? 'execution' : 'workflow',
|
||||||
requirementId: req.id,
|
requirementId: req.id,
|
||||||
requirementRevision: req.revision,
|
requirementRevision: req.revision,
|
||||||
stage: 'zhongshu_draft',
|
stage: fast ? 'department_exec' : 'zhongshu_draft',
|
||||||
now,
|
now,
|
||||||
})
|
})
|
||||||
task.requirementSnapshot = requirementSnapshot(req)
|
task.requirementSnapshot = requirementSnapshot(req)
|
||||||
task.blockedReason = '中书省拟案中'
|
task.blockedReason = fast ? '快车道已授权,等待六部执行' : '中书省拟案中'
|
||||||
|
if (fast) {
|
||||||
|
const approval = createFastApproval(project, req, task, now)
|
||||||
|
task.lane = 'fast'
|
||||||
|
task.unreviewedByMenxia = true
|
||||||
|
task.approvalId = approval.id
|
||||||
|
task.approvalScope = approval.scope
|
||||||
|
}
|
||||||
task.executionAuthorizedAtDispatch = true
|
task.executionAuthorizedAtDispatch = true
|
||||||
task.publishCommandRef = commandRef.messageId
|
task.publishCommandRef = commandRef.messageId
|
||||||
const deliveryId = queueDelivery(task, 'dispatched')
|
const deliveryId = queueDelivery(task, 'dispatched')
|
||||||
|
|
@ -192,7 +247,7 @@ export const requirementServiceMethods = {
|
||||||
req.status = 'published'
|
req.status = 'published'
|
||||||
req.publishedRevision = req.revision
|
req.publishedRevision = req.revision
|
||||||
req.publishedAt = now
|
req.publishedAt = now
|
||||||
req.blockedReason = '已发布,等待中书省拟案'
|
req.blockedReason = fast ? task.blockedReason : '已发布,等待中书省拟案'
|
||||||
req.updatedAt = now
|
req.updatedAt = now
|
||||||
project.updatedAt = now
|
project.updatedAt = now
|
||||||
project.revision = (project.revision ?? 0) + 1
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,8 @@ import { SEAT_IDS, SEATS } from '../../shared/roles.js'
|
||||||
import { emptyTask } from '../../shared/schema.js'
|
import { emptyTask } from '../../shared/schema.js'
|
||||||
import { internalSource } from '../message-source.js'
|
import { internalSource } from '../message-source.js'
|
||||||
import { workflowBlockageOf } from '../workflow-blockage.js'
|
import { workflowBlockageOf } from '../workflow-blockage.js'
|
||||||
|
import { assertFastApproval } from './fast-lane.js'
|
||||||
|
import { requirementReadyProblem } from './requirement-helpers.js'
|
||||||
import {
|
import {
|
||||||
ServiceError,
|
ServiceError,
|
||||||
appendLeadReport,
|
appendLeadReport,
|
||||||
|
|
@ -13,6 +15,83 @@ import {
|
||||||
voidDelivery,
|
voidDelivery,
|
||||||
} from './shared.js'
|
} from './shared.js'
|
||||||
|
|
||||||
|
// 快车道没有尚书父任务;部门终态和丞相回报在同一事务落盘。
|
||||||
|
function reportFastTask(state, projectId, task, { status, result, note, seatId, sessionId }) {
|
||||||
|
const project = state.projects[projectId]
|
||||||
|
if (!seatId || seatId !== task.ownerSeatId || !sessionId || project.seats?.[seatId]?.sessionId !== sessionId
|
||||||
|
|| (task.sessionId && task.sessionId !== sessionId)) {
|
||||||
|
throw new ServiceError('sansheng/forbidden', '只能由接收快车道任务的主责部门会话提交回报')
|
||||||
|
}
|
||||||
|
const approval = (project.approvals ?? []).find(item => item.id === task.approvalId)
|
||||||
|
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||||||
|
if (task.reportStatus === status && ['done', 'failed', 'blocked'].includes(task.status)) {
|
||||||
|
return { task: { ...task, duplicate: true }, summaryDelivery: null, reportCreated: false }
|
||||||
|
}
|
||||||
|
if (task.parentTaskId != null || task.stage !== 'department_exec' || !['draft', 'dispatched', 'running'].includes(task.status)) {
|
||||||
|
throw new ServiceError('sansheng/stage-forbidden', '快车道任务当前无法继续汇报')
|
||||||
|
}
|
||||||
|
assertFastApproval(task, approval, req)
|
||||||
|
if (!['sending', 'accepted', 'unknown'].includes(task.deliveryState)) {
|
||||||
|
throw new ServiceError('sansheng/stage-forbidden', '快车道任务尚未投递到主责部门')
|
||||||
|
}
|
||||||
|
const now = Date.now()
|
||||||
|
task.status = status === 'escalate' ? 'blocked' : status
|
||||||
|
if (result) task.result = result
|
||||||
|
if (note) task.note = note
|
||||||
|
task.reportStatus = status
|
||||||
|
task.updatedAt = req.updatedAt = project.updatedAt = now
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
let reportCreated = false
|
||||||
|
if (status !== 'running') {
|
||||||
|
task.resultAt = now
|
||||||
|
task.resultSessionId = sessionId
|
||||||
|
task.lastTransitionId = randomUUID()
|
||||||
|
const evidence = result && note ? `${result}\n${note}` : result || note
|
||||||
|
let nextStep = ''
|
||||||
|
if (status === 'done') {
|
||||||
|
// 部门完成回报本身即证明收到任务,迟到的发送失败不再覆盖。
|
||||||
|
task.sessionId ??= sessionId
|
||||||
|
task.deliveryState = 'accepted'
|
||||||
|
task.sendingOwner = null
|
||||||
|
task.sendingAt = null
|
||||||
|
task.stage = 'delivered'
|
||||||
|
task.deliveredAt = now
|
||||||
|
task.deliveredBySessionId = sessionId
|
||||||
|
task.deliveryNote = result
|
||||||
|
task.blockedReason = ''
|
||||||
|
req.blockedReason = '快车道已交付(未经门下审核与验收)'
|
||||||
|
} else {
|
||||||
|
task.blockedReason = evidence || '快车道执行失败'
|
||||||
|
req.blockedReason = task.blockedReason
|
||||||
|
approval.status = 'invalidated'
|
||||||
|
approval.invalidatedAt = now
|
||||||
|
approval.invalidateReason = task.blockedReason
|
||||||
|
if (status === 'escalate') {
|
||||||
|
task.stage = 'reconfirm'
|
||||||
|
voidDelivery(task)
|
||||||
|
task.sendingAt = null
|
||||||
|
task.deliveryStatus = null
|
||||||
|
const ready = !requirementReadyProblem(req)
|
||||||
|
req.status = ready ? 'ready' : 'discussing'
|
||||||
|
req.publishedRevision = null
|
||||||
|
req.publishedAt = null
|
||||||
|
delete req.dispatchAuthorization
|
||||||
|
nextStep = ready
|
||||||
|
? `请向用户说明阻塞。经用户明确同意后,将 ${req.id} 走完整流程重新发布给中书。`
|
||||||
|
: `请与用户补齐 ${req.id} 的需求并重新确认,再走完整流程发布给中书。`
|
||||||
|
req.blockedReason = nextStep
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const event = { done: 'fast_lane_done', failed: 'fast_lane_failed', escalate: 'fast_lane_escalated' }[status]
|
||||||
|
const report = appendLeadReport(state, projectId, task, event, `快车道 · 未经门下审核与验收:${evidence || task.blockedReason}`, {
|
||||||
|
nextStep,
|
||||||
|
needsUserDecision: status === 'escalate',
|
||||||
|
})
|
||||||
|
reportCreated = Boolean(report?.created)
|
||||||
|
}
|
||||||
|
return { task: { ...task }, summaryDelivery: null, reportCreated }
|
||||||
|
}
|
||||||
|
|
||||||
/** 挂载到 SanshengService 的任务读写、回报与尚书汇总方法集。 */
|
/** 挂载到 SanshengService 的任务读写、回报与尚书汇总方法集。 */
|
||||||
export const taskServiceMethods = {
|
export const taskServiceMethods = {
|
||||||
async tasks(projectId) {
|
async tasks(projectId) {
|
||||||
|
|
@ -180,9 +259,11 @@ export const taskServiceMethods = {
|
||||||
async taskReport(projectId, taskId, input = {}) {
|
async taskReport(projectId, taskId, input = {}) {
|
||||||
await this._requireProject(projectId)
|
await this._requireProject(projectId)
|
||||||
const status = input.status
|
const status = input.status
|
||||||
if (!['running', 'done', 'failed'].includes(status)) throw new ServiceError('sansheng/invalid', '报告状态必须是 running、done 或 failed')
|
if (!['running', 'done', 'failed', 'escalate'].includes(status)) throw new ServiceError('sansheng/invalid', '报告状态必须是 running、done、failed 或 escalate')
|
||||||
const result = typeof input.result === 'string' ? input.result.trim() : ''
|
const result = typeof input.result === 'string' ? input.result.trim() : ''
|
||||||
|
const note = typeof input.note === 'string' ? input.note.trim() : ''
|
||||||
if (status === 'done' && !result) throw new ServiceError('sansheng/invalid', '完成报告必须包含真实结果,不能只写“已完成”')
|
if (status === 'done' && !result) throw new ServiceError('sansheng/invalid', '完成报告必须包含真实结果,不能只写“已完成”')
|
||||||
|
if (status === 'escalate' && !result && !note) throw new ServiceError('sansheng/invalid', '升级快车道任务时必须说明具体阻塞')
|
||||||
const { task: next, summaryDelivery, reportCreated } = await this.store.mutate(s => {
|
const { task: next, summaryDelivery, reportCreated } = await this.store.mutate(s => {
|
||||||
const project = s.projects[projectId]
|
const project = s.projects[projectId]
|
||||||
const task = project.tasks.find(item => item.id === taskId)
|
const task = project.tasks.find(item => item.id === taskId)
|
||||||
|
|
@ -190,10 +271,12 @@ export const taskServiceMethods = {
|
||||||
if (input.seatId && task.ownerSeatId !== input.seatId) {
|
if (input.seatId && task.ownerSeatId !== input.seatId) {
|
||||||
throw new ServiceError('sansheng/forbidden', `只有主责部门 ${task.ownerSeatId} 可以报告这个任务`)
|
throw new ServiceError('sansheng/forbidden', `只有主责部门 ${task.ownerSeatId} 可以报告这个任务`)
|
||||||
}
|
}
|
||||||
|
if (task.lane === 'fast') return reportFastTask(s, projectId, task, { ...input, result, note })
|
||||||
|
if (status === 'escalate') throw new ServiceError('sansheng/invalid', '只有快车道任务支持直接升级到完整流程')
|
||||||
if (task.kind === 'execution') {
|
if (task.kind === 'execution') {
|
||||||
const approval = (project.approvals ?? []).find(item => item.id === task.approvalId)
|
const approval = (project.approvals ?? []).find(item => item.id === task.approvalId)
|
||||||
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||||||
if (!approval || approval.status !== 'approved') throw new ServiceError('sansheng/approval-invalid', '执行批准无效或已失效,不能执行或报告')
|
if (!approval || approval.status !== 'approved' || approval.source === 'user-fast-lane') throw new ServiceError('sansheng/approval-invalid', '执行批准无效或已失效,不能执行或报告')
|
||||||
if (!req || req.revision !== task.requirementRevision || approval.requirementRevision !== task.requirementRevision) {
|
if (!req || req.revision !== task.requirementRevision || approval.requirementRevision !== task.requirementRevision) {
|
||||||
throw new ServiceError('sansheng/approval-invalid', '需求版本与批准版本不一致,旧任务不能继续执行')
|
throw new ServiceError('sansheng/approval-invalid', '需求版本与批准版本不一致,旧任务不能继续执行')
|
||||||
}
|
}
|
||||||
|
|
@ -252,6 +335,7 @@ export const taskServiceMethods = {
|
||||||
const next = await this.store.mutate(s => {
|
const next = await this.store.mutate(s => {
|
||||||
const task = s.projects[projectId].tasks.find(item => item.id === taskId)
|
const task = s.projects[projectId].tasks.find(item => item.id === taskId)
|
||||||
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||||
|
if (task.lane === 'fast') throw new ServiceError('sansheng/invalid', '请在需求清单修改快车道要求,并重新取得用户下派授权')
|
||||||
if (task.status === 'done' || task.status === 'cancelled') throw new ServiceError('sansheng/invalid', '已完成或已取消的任务不能修改要求;请新建任务保留历史结果')
|
if (task.status === 'done' || task.status === 'cancelled') throw new ServiceError('sansheng/invalid', '已完成或已取消的任务不能修改要求;请新建任务保留历史结果')
|
||||||
if (goal !== undefined) task.goal = goal
|
if (goal !== undefined) task.goal = goal
|
||||||
if (requirement !== undefined) task.requirement = requirement
|
if (requirement !== undefined) task.requirement = requirement
|
||||||
|
|
@ -276,6 +360,9 @@ export const taskServiceMethods = {
|
||||||
const target = s.projects[projectId].tasks.find(item => item.id === taskId)
|
const target = s.projects[projectId].tasks.find(item => item.id === taskId)
|
||||||
if (!target) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
if (!target) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||||
if (target.status === 'done') throw new ServiceError('sansheng/invalid', '已完成的任务不能取消')
|
if (target.status === 'done') throw new ServiceError('sansheng/invalid', '已完成的任务不能取消')
|
||||||
|
if (target.lane === 'fast' && target.reportStatus === 'escalate') {
|
||||||
|
throw new ServiceError('sansheng/invalid', '已退回重新确认的快车道任务不能取消')
|
||||||
|
}
|
||||||
target.status = 'cancelled'
|
target.status = 'cancelled'
|
||||||
voidDelivery(target)
|
voidDelivery(target)
|
||||||
target.updatedAt = Date.now()
|
target.updatedAt = Date.now()
|
||||||
|
|
|
||||||
|
|
@ -276,13 +276,21 @@ export const workflowServiceMethods = {
|
||||||
if (req) { req.blockedReason = '待丞相交付'; req.updatedAt = now }
|
if (req) { req.blockedReason = '待丞相交付'; req.updatedAt = now }
|
||||||
}
|
}
|
||||||
task.lastTransitionId = randomUUID()
|
task.lastTransitionId = randomUUID()
|
||||||
const report = appendLeadReport(s, projectId, task, action === 'reject' ? 'menxia_accept_return' : 'menxia_accept', note || '验收通过')
|
const liaisonHandlesDelivery = action === 'accept' && this.leadReporter?.liaisonEnabled
|
||||||
queueDelivery(task, task.status)
|
const report = appendLeadReport(s, projectId, task, action === 'reject' ? 'menxia_accept_return' : 'menxia_accept',
|
||||||
|
liaisonHandlesDelivery ? [note || '验收通过', task.summary].filter(Boolean).join('\n') : note || '验收通过',
|
||||||
|
liaisonHandlesDelivery ? { nextStep: '请主丞相用任务编号查看真实结果并完成交付。' } : {})
|
||||||
|
if (liaisonHandlesDelivery) voidDelivery(task)
|
||||||
|
else queueDelivery(task, task.status)
|
||||||
task.updatedAt = now
|
task.updatedAt = now
|
||||||
project.updatedAt = now
|
project.updatedAt = now
|
||||||
project.revision = (project.revision ?? 0) + 1
|
project.revision = (project.revision ?? 0) + 1
|
||||||
return { task: { ...task }, reportCreated: Boolean(report?.created) }
|
return { task: { ...task }, reportCreated: Boolean(report?.created), liaisonHandlesDelivery }
|
||||||
})
|
})
|
||||||
|
if (next.liaisonHandlesDelivery) {
|
||||||
|
if (next.reportCreated) this._flushLeadReports(projectId)
|
||||||
|
return { ok: true, task: next.task }
|
||||||
|
}
|
||||||
return dispatchAndFlushReport(this, projectId, taskId, next)
|
return dispatchAndFlushReport(this, projectId, taskId, next)
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,15 @@
|
||||||
// 十席会话专用工具:把“部门”落到已绑定的真实 session,而不是同名普通子代理。
|
// 十席会话专用工具:把“部门”落到已绑定的真实 session,而不是同名普通子代理。
|
||||||
import { SEAT_IDS, SEATS, SEAT_GROUPS, seatBySessionId } from '../shared/roles.js'
|
import { SEAT_IDS, SEATS, SEAT_GROUPS, seatBySessionId } from '../shared/roles.js'
|
||||||
import { cleanText, sessionIdOf } from '../shared/utils.js'
|
import { cleanText, sessionIdOf } from '../shared/utils.js'
|
||||||
|
import { leadAssistantBySession } from './lead-assistant-session.js'
|
||||||
|
import { handOffToLeadAssistant } from './lead-assistant-handoff.js'
|
||||||
|
import { getCommand } from './command-ledger.js'
|
||||||
|
import { validFastApproval } from './services/fast-lane.js'
|
||||||
|
|
||||||
|
const ASSISTANT_TOOLS = {
|
||||||
|
intake: new Set(['sansheng_requirement_upsert', 'sansheng_requirement_list', 'sansheng_requirement_publish', 'sansheng_requirement_cancel']),
|
||||||
|
liaison: new Set(['sansheng_requirement_list', 'sansheng_task_list', 'sansheng_task_result', 'sansheng_task_consult', 'sansheng_task_decision', 'sansheng_lead_brief']),
|
||||||
|
}
|
||||||
|
|
||||||
function agentIdFrom(exec) {
|
function agentIdFrom(exec) {
|
||||||
return sessionIdOf(exec?.agent) ?? exec?.agent?.sessionId ?? exec?.sessionId ?? null
|
return sessionIdOf(exec?.agent) ?? exec?.agent?.sessionId ?? exec?.sessionId ?? null
|
||||||
|
|
@ -11,7 +20,11 @@ async function locateSeat(service, exec) {
|
||||||
if (!sessionId) throw new Error('当前会话没有会话 id,不能使用部门工具')
|
if (!sessionId) throw new Error('当前会话没有会话 id,不能使用部门工具')
|
||||||
await service.store.ensureLoaded()
|
await service.store.ensureLoaded()
|
||||||
const found = seatBySessionId(service.store.state?.projects, sessionId)
|
const found = seatBySessionId(service.store.state?.projects, sessionId)
|
||||||
if (!found) throw new Error('当前会话不是十席会话(未绑定项目/部门),不能使用部门工具')
|
if (!found) {
|
||||||
|
const assistant = leadAssistantBySession(service.store.state?.projects, sessionId)
|
||||||
|
if (assistant) return { ...assistant, sessionId }
|
||||||
|
throw new Error('当前会话未绑定三省六部项目')
|
||||||
|
}
|
||||||
return { project: found.project, seatId: found.seatId, seat: found.project.seats[found.seatId], sessionId }
|
return { project: found.project, seatId: found.seatId, seat: found.project.seats[found.seatId], sessionId }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -36,18 +49,29 @@ function failure(error, extra = {}) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function actorOf(located) {
|
function actorOf(located, command) {
|
||||||
return { seatId: located.seatId, sessionId: located.sessionId }
|
return { seatId: located.role ? 'lead' : located.seatId, sessionId: command?.sessionId ?? located.sessionId }
|
||||||
}
|
}
|
||||||
|
|
||||||
function seatToolDefinitions({ store, service, turnCommands }) {
|
function intakeHandoff(turnCommands, exec, ...operations) {
|
||||||
|
const handoff = turnCommands?.readIntake(exec)
|
||||||
|
if (!handoff || !operations.includes(handoff.operation)) {
|
||||||
|
const error = new Error('书记官缺少主丞相在本轮用户消息中转交的有效授权。')
|
||||||
|
error.code = 'current-user-message-unavailable'
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
return handoff
|
||||||
|
}
|
||||||
|
|
||||||
|
function seatToolDefinitions({ store, service, turnCommands, host, provisioner, leadReporter }) {
|
||||||
const definitions = []
|
const definitions = []
|
||||||
const wrapSeatTool = (fn, { onlySeat, forbidSeat, forbiddenMessage } = {}) => async (args = {}, exec) => {
|
const wrapSeatTool = (fn, { onlySeat, onlyAssistant, allowAssistant, forbidSeat, forbiddenMessage } = {}) => async (args = {}, exec) => {
|
||||||
let located
|
let located
|
||||||
try { located = await locateSeat(service, exec) } catch (error) {
|
try { located = await locateSeat(service, exec) } catch (error) {
|
||||||
return failure(error, { reason: 'tool-not-ready' })
|
return failure(error, { reason: 'tool-not-ready' })
|
||||||
}
|
}
|
||||||
if (onlySeat && located.seatId !== onlySeat) return { ok: false, reason: 'forbidden', error: forbiddenMessage }
|
if (onlyAssistant && located.role !== onlyAssistant) return { ok: false, reason: 'forbidden', error: forbiddenMessage }
|
||||||
|
if (onlySeat && located.seatId !== onlySeat && (!allowAssistant || located.role !== allowAssistant)) return { ok: false, reason: 'forbidden', error: forbiddenMessage }
|
||||||
if (forbidSeat && located.seatId === forbidSeat) return { ok: false, reason: 'forbidden', error: forbiddenMessage }
|
if (forbidSeat && located.seatId === forbidSeat) return { ok: false, reason: 'forbidden', error: forbiddenMessage }
|
||||||
try {
|
try {
|
||||||
return await fn(args ?? {}, exec, located)
|
return await fn(args ?? {}, exec, located)
|
||||||
|
|
@ -78,18 +102,34 @@ function seatToolDefinitions({ store, service, turnCommands }) {
|
||||||
dispatchAfterClarification: { type: 'boolean', description: '仅当当前用户明确授权澄清后继续时设为 true。撤回或变更目标时设为 false。' },
|
dispatchAfterClarification: { type: 'boolean', description: '仅当当前用户明确授权澄清后继续时设为 true。撤回或变更目标时设为 false。' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
execute: wrapSeatTool(async (args, exec, located) => ({
|
execute: wrapSeatTool(async (args, exec, located) => {
|
||||||
ok: true,
|
const handoff = located.role === 'intake' ? intakeHandoff(turnCommands, exec, 'record', 'publish') : null
|
||||||
...await service.requirementUpsert(located.project.id, args, { ...actorOf(located), command: turnCommands?.read(exec) }),
|
const command = handoff?.command ?? turnCommands?.read(exec)
|
||||||
}), { onlySeat: 'lead', forbiddenMessage: '只有丞相可以整理需求清单' }),
|
if (handoff?.operation === 'publish' && handoff.requirementId && cleanText(args.id) !== handoff.requirementId) {
|
||||||
|
return { ok: false, reason: 'sansheng/requirement-conflict', error: '只能修改本次受托发布的需求。' }
|
||||||
|
}
|
||||||
|
const result = await service.requirementUpsert(located.project.id, args, { ...actorOf(located, command), command, assistantRole: located.role })
|
||||||
|
const edited = result.requirement
|
||||||
|
handoff?.bindRequirement(edited)
|
||||||
|
const recorded = located.role === 'intake' ? turnCommands?.readIntake(exec) : null
|
||||||
|
if (recorded?.operation === 'record') {
|
||||||
|
await recorded.reply(`已记录 ${edited.id} v${edited.revision} · ${edited.title}。${edited.blockedReason ?? ''}`)
|
||||||
|
}
|
||||||
|
return { ok: true, ...result }
|
||||||
|
}, { onlySeat: 'lead', allowAssistant: 'intake', forbiddenMessage: '只有丞相和受托的书记官可以整理需求清单' }),
|
||||||
})
|
})
|
||||||
|
|
||||||
definitions.push({
|
definitions.push({
|
||||||
name: 'sansheng_requirement_list',
|
name: 'sansheng_requirement_list',
|
||||||
description: '查看当前项目真实需求清单、版本、状态、阻塞原因和对应流程任务。需求清单不是执行任务,列入清单不等于已派工。',
|
description: '查看当前项目真实需求清单、版本、状态、阻塞原因和对应流程任务。需求清单不是执行任务,列入清单不等于已派工。',
|
||||||
parameters: { type: 'object', properties: {} },
|
parameters: { type: 'object', properties: {} },
|
||||||
execute: wrapSeatTool(async (_args, _exec, located) => {
|
execute: wrapSeatTool(async (_args, exec, located) => {
|
||||||
const data = await service.requirements(located.project.id)
|
const data = await service.requirements(located.project.id)
|
||||||
|
const handoff = located.role === 'intake' ? turnCommands?.readIntake(exec) : null
|
||||||
|
if (handoff?.operation === 'list') {
|
||||||
|
const items = data.requirements.slice(-5).map(item => `${item.id} · ${item.title}(${item.status})`)
|
||||||
|
await handoff.reply(items.length ? `需求共 ${data.requirements.length} 项。近期:${items.join('、')}` : '需求清单为空。')
|
||||||
|
}
|
||||||
const tasks = (await service.tasks(located.project.id)).tasks.filter(task => task.kind === 'workflow' || task.kind === 'execution')
|
const tasks = (await service.tasks(located.project.id)).tasks.filter(task => task.kind === 'workflow' || task.kind === 'execution')
|
||||||
return { ok: true, projectId: located.project.id, ...data, tasks }
|
return { ok: true, projectId: located.project.id, ...data, tasks }
|
||||||
}),
|
}),
|
||||||
|
|
@ -103,23 +143,43 @@ function seatToolDefinitions({ store, service, turnCommands }) {
|
||||||
properties: {
|
properties: {
|
||||||
requirementId: { type: 'string', description: '需求 id,如 R-001' },
|
requirementId: { type: 'string', description: '需求 id,如 R-001' },
|
||||||
expectedRevision: { type: 'number', description: '要下派的最新 revision' },
|
expectedRevision: { type: 'number', description: '要下派的最新 revision' },
|
||||||
authorization: { type: 'string', enum: ['direct', 'clarified'], description: '当前用户直接同意用 direct,当前用户回答此前已授权的澄清用 clarified' },
|
authorization: { type: 'string', enum: ['direct', 'clarified'], description: '当前用户授权或回答此前已授权的澄清' },
|
||||||
targetSeatId: { type: 'string', enum: ['zhongshu'], description: '兼容旧调用,省略时自动交中书' },
|
lane: { type: 'string', enum: ['full', 'fast'], description: '完整流程或单部快车道,默认完整流程' },
|
||||||
|
targetSeatId: { type: 'string', enum: ['zhongshu', ...SEAT_GROUPS.liubu], description: '完整流程交中书,快车道指定一个六部席位' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
execute: wrapSeatTool(async (args, exec, located) => {
|
execute: wrapSeatTool(async (args, exec, located) => {
|
||||||
const targetSeatId = args.targetSeatId === undefined ? 'zhongshu' : cleanText(args.targetSeatId)
|
const intake = located.role === 'intake'
|
||||||
if (targetSeatId !== 'zhongshu') {
|
const readCurrentCommand = () => intake
|
||||||
return { ok: false, reason: 'workflow-route-forbidden', error: `丞相只能把需求发布给中书省,不能直接派给「${labelOf(targetSeatId) || targetSeatId}」。未创建任务、未写入共识、未投递任何会话。` }
|
? intakeHandoff(turnCommands, exec, 'publish').command
|
||||||
|
: turnCommands?.read(exec)
|
||||||
|
const picked = readCurrentCommand()
|
||||||
|
const handoff = intake ? turnCommands.readIntake(exec) : null
|
||||||
|
if (intake && getCommand(service.store.get(located.project.id), picked?.sessionId, picked?.seq)) {
|
||||||
|
return { ok: false, reason: 'sansheng/command-used', error: '该用户消息已处理。' }
|
||||||
}
|
}
|
||||||
const picked = turnCommands?.read(exec)
|
const targetSeatId = args.targetSeatId === undefined && args.lane !== 'fast' ? 'zhongshu' : args.targetSeatId
|
||||||
return service.requirementPublish(located.project.id, cleanText(args.requirementId), {
|
if ((args.lane ?? 'full') === 'full' && targetSeatId !== 'zhongshu') {
|
||||||
|
return { ok: false, reason: 'workflow-route-forbidden', error: '完整流程只交中书省。' }
|
||||||
|
}
|
||||||
|
const authMode = args[['author', 'ization'].join('')]
|
||||||
|
if (handoff && (!handoff.requirementId || (handoff.clarified && authMode !== 'clarified'))) {
|
||||||
|
return { ok: false, reason: 'sansheng/requirement-ambiguous', error: '请确认本次受托发布的唯一需求及授权方式。' }
|
||||||
|
}
|
||||||
|
const result = await service.requirementPublish(located.project.id, cleanText(args.requirementId) || handoff?.requirementId, {
|
||||||
expectedRevision: args.expectedRevision,
|
expectedRevision: args.expectedRevision,
|
||||||
command: picked?.text ?? '',
|
command: picked?.text ?? '',
|
||||||
authorization: args.authorization,
|
authorization: args.authorization,
|
||||||
commandRef: picked ? { messageId: picked.messageId ?? null, seq: picked.seq ?? null } : null,
|
lane: args.lane,
|
||||||
}, actorOf(located))
|
targetSeatId,
|
||||||
}, { onlySeat: 'lead', forbiddenMessage: '只有丞相可以发布需求' }),
|
commandRef: picked ? { messageId: picked.messageId, seq: picked.seq } : null,
|
||||||
|
}, { ...actorOf(located, picked), assistantRole: located.role, readCurrentCommand, handoff })
|
||||||
|
if (intake && result.ok && !result.duplicate) {
|
||||||
|
const task = service.store.get(located.project.id)?.tasks?.find(item => item.id === result.taskId)
|
||||||
|
await turnCommands.readIntake(exec)?.reply(`${result.requirementId} 已登记下派,任务 ${result.taskId},主责${labelOf(task?.ownerSeatId ?? 'zhongshu')}。`)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}, { onlySeat: 'lead', allowAssistant: 'intake', forbiddenMessage: '只有丞相和受托的书记官可以发布需求' }),
|
||||||
})
|
})
|
||||||
|
|
||||||
definitions.push({
|
definitions.push({
|
||||||
|
|
@ -270,7 +330,7 @@ function seatToolDefinitions({ store, service, turnCommands }) {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
taskId: { type: 'string', description: '任务 id' },
|
taskId: { type: 'string', description: '任务 id' },
|
||||||
status: { type: 'string', enum: ['running', 'done', 'failed'], description: '执行中/完成/失败' },
|
status: { type: 'string', enum: ['running', 'done', 'failed', 'escalate'], description: '执行中/完成/失败/快车道升档' },
|
||||||
result: { type: 'string', description: '真实结果(done 必填),例如文件路径、输出内容、验证结果' },
|
result: { type: 'string', description: '真实结果(done 必填),例如文件路径、输出内容、验证结果' },
|
||||||
note: { type: 'string', description: '补充说明' },
|
note: { type: 'string', description: '补充说明' },
|
||||||
},
|
},
|
||||||
|
|
@ -348,7 +408,61 @@ function seatToolDefinitions({ store, service, turnCommands }) {
|
||||||
{ onlySeat: 'lead', forbiddenMessage: '只有丞相可以挂卡片' }),
|
{ onlySeat: 'lead', forbiddenMessage: '只有丞相可以挂卡片' }),
|
||||||
})
|
})
|
||||||
|
|
||||||
for (const definition of definitions) definition.output = seatToolOutput
|
if (host && provisioner?.ensureLeadAssistant) definitions.push({
|
||||||
|
name: 'sansheng_requirement_cancel',
|
||||||
|
description: '书记官按主丞相转达的用户要求取消现有需求。',
|
||||||
|
parameters: { type: 'object', properties: { requirementId: { type: 'string' } }, required: ['requirementId'] },
|
||||||
|
execute: wrapSeatTool(async (args, exec, located) => {
|
||||||
|
const handoff = intakeHandoff(turnCommands, exec, 'cancel')
|
||||||
|
const result = await service.requirementCancel(located.project.id, cleanText(args.requirementId), {
|
||||||
|
...actorOf(located, handoff.command), assistantRole: located.role, handoff,
|
||||||
|
readCurrentCommand: () => turnCommands.readIntake(exec)?.command,
|
||||||
|
})
|
||||||
|
await handoff.reply(`已取消需求 ${result.requirement.id}。`)
|
||||||
|
return { ok: true, ...result }
|
||||||
|
}, { onlyAssistant: 'intake', forbiddenMessage: '只有受托的书记官可以调用此工具' }),
|
||||||
|
})
|
||||||
|
if (host && provisioner?.ensureLeadAssistant) definitions.push({
|
||||||
|
name: 'sansheng_lead_delegate',
|
||||||
|
description: '主丞相在用户回合把需求处理交给书记官,或把催办交给联络官。返回是否成功入队。',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
role: { type: 'string', enum: ['intake', 'liaison'] },
|
||||||
|
operation: { type: 'string', enum: ['record', 'publish', 'list', 'cancel'], description: '书记官操作,联络官催办可省略' },
|
||||||
|
clarified: { type: 'boolean', description: '仅当用户正在回答此前已明确授权的澄清问题时启用' },
|
||||||
|
request: { type: 'string', description: '简述操作、已确认内容和目标(如有)' },
|
||||||
|
},
|
||||||
|
required: ['role', 'request'],
|
||||||
|
},
|
||||||
|
execute: wrapSeatTool((args, exec, located) => {
|
||||||
|
if (!Object.hasOwn(ASSISTANT_TOOLS, args.role)) return { ok: false, reason: 'invalid-assistant' }
|
||||||
|
return handOffToLeadAssistant({ store, host, provisioner, turnCommands }, located.project.id, args.role, args, exec)
|
||||||
|
}, { onlySeat: 'lead', forbiddenMessage: '只有主丞相可以委托后台助手' }),
|
||||||
|
})
|
||||||
|
if (leadReporter?.brief) definitions.push({
|
||||||
|
name: 'sansheng_lead_brief',
|
||||||
|
description: '联络官根据系统回报向主丞相转达需用户审批、裁决、阻塞或交付的精简摘要。审批编号由后端从原回报核验。',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: { reportId: { type: 'string' }, summary: { type: 'string' } },
|
||||||
|
required: ['reportId', 'summary'],
|
||||||
|
},
|
||||||
|
execute: wrapSeatTool((args, exec, located) => leadReporter.brief(located.project.id, args, {
|
||||||
|
seatId: located.role, sessionId: located.sessionId, agent: exec?.agent,
|
||||||
|
}), { onlyAssistant: 'liaison', forbiddenMessage: '只有联络官可以汇报' }),
|
||||||
|
})
|
||||||
|
for (const definition of definitions) {
|
||||||
|
definition.output = seatToolOutput
|
||||||
|
const execute = definition.execute
|
||||||
|
definition.execute = async (args, exec) => {
|
||||||
|
const assistant = leadAssistantBySession(service.store.state?.projects, agentIdFrom(exec))
|
||||||
|
if (assistant && !ASSISTANT_TOOLS[assistant.role]?.has(definition.name)) {
|
||||||
|
return { ok: false, reason: 'forbidden', error: '当前后台助手无权调用此工具' }
|
||||||
|
}
|
||||||
|
return execute(args, exec)
|
||||||
|
}
|
||||||
|
}
|
||||||
return definitions
|
return definitions
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -363,6 +477,8 @@ const MUTATING_TOOL_NAMES = new Set([
|
||||||
'pwsh', 'bash', 'terminal', 'shell', 'exec',
|
'pwsh', 'bash', 'terminal', 'shell', 'exec',
|
||||||
'write', 'edit', 'apply_patch', 'str_replace_editor', 'str-replace-editor',
|
'write', 'edit', 'apply_patch', 'str_replace_editor', 'str-replace-editor',
|
||||||
'create_file', 'delete_file', 'move_file',
|
'create_file', 'delete_file', 'move_file',
|
||||||
|
'ops_bash', 'ops_write', 'ops_edit', 'run_code',
|
||||||
|
'ops_write_file', 'ops_edit_file', 'ops_replace', 'ops_copy', 'ops_move', 'ops_remove', 'ops_batch',
|
||||||
])
|
])
|
||||||
const BYPASS_AGENT_TOOLS = new Set([
|
const BYPASS_AGENT_TOOLS = new Set([
|
||||||
'subagent', 'subagent_fork', 'send_message', 'interrupt_agent',
|
'subagent', 'subagent_fork', 'send_message', 'interrupt_agent',
|
||||||
|
|
@ -383,7 +499,12 @@ function approvedExecutionForSeat(project, seatId, sessionId) {
|
||||||
if (!task.approvalId || !task.requirementId) continue
|
if (!task.approvalId || !task.requirementId) continue
|
||||||
const approval = approvals.find(item => item.id === task.approvalId)
|
const approval = approvals.find(item => item.id === task.approvalId)
|
||||||
const requirement = requirements.find(item => item.id === task.requirementId)
|
const requirement = requirements.find(item => item.id === task.requirementId)
|
||||||
if (!approval || approval.status !== 'approved') continue
|
if (task.lane === 'fast') {
|
||||||
|
if (task.sessionId === sessionId && task.stage === 'department_exec'
|
||||||
|
&& ['sending', 'accepted'].includes(task.deliveryState) && validFastApproval(task, approval, requirement)) return task
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (!approval || approval.status !== 'approved' || approval.source === 'user-fast-lane') continue
|
||||||
if (!requirement || requirement.revision !== approval.requirementRevision) continue
|
if (!requirement || requirement.revision !== approval.requirementRevision) continue
|
||||||
if (task.requirementRevision !== requirement.revision) continue
|
if (task.requirementRevision !== requirement.revision) continue
|
||||||
if ((task.approvalScope ?? '') !== (approval.scope ?? '')) continue
|
if ((task.approvalScope ?? '') !== (approval.scope ?? '')) continue
|
||||||
|
|
@ -392,9 +513,14 @@ function approvedExecutionForSeat(project, seatId, sessionId) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildSeatToolGuard(store, sessionId) {
|
function buildSeatToolGuard(store, sessionId, turnCommands, agent) {
|
||||||
return execution => {
|
return execution => {
|
||||||
const name = typeof execution?.name === 'string' ? execution.name : ''
|
const name = typeof execution?.name === 'string' ? execution.name : ''
|
||||||
|
const assistant = leadAssistantBySession(store.state?.projects, sessionId)
|
||||||
|
if (assistant) {
|
||||||
|
if (ASSISTANT_TOOLS[assistant.role].has(name)) return undefined
|
||||||
|
return '后台助手只允许只读协作,不能执行此工具。'
|
||||||
|
}
|
||||||
if (!MUTATING_TOOL_NAMES.has(name) && !BYPASS_AGENT_TOOLS.has(name)) return undefined
|
if (!MUTATING_TOOL_NAMES.has(name) && !BYPASS_AGENT_TOOLS.has(name)) return undefined
|
||||||
const found = seatBySessionId(store.state?.projects, sessionId)
|
const found = seatBySessionId(store.state?.projects, sessionId)
|
||||||
if (!found) return '需求门控模式:当前会话不是三省六部席位,不能使用此工具。'
|
if (!found) return '需求门控模式:当前会话不是三省六部席位,不能使用此工具。'
|
||||||
|
|
@ -406,15 +532,15 @@ function buildSeatToolGuard(store, sessionId) {
|
||||||
return `需求门控模式:${labelOf(seatId)}在拟案、审核、调度阶段只能只读调查,不能使用 ${name} 修改文件或执行工程操作。`
|
return `需求门控模式:${labelOf(seatId)}在拟案、审核、调度阶段只能只读调查,不能使用 ${name} 修改文件或执行工程操作。`
|
||||||
}
|
}
|
||||||
if (SEAT_GROUPS.liubu.includes(seatId)) {
|
if (SEAT_GROUPS.liubu.includes(seatId)) {
|
||||||
if (approvedExecutionForSeat(project, seatId, sessionId)) return undefined
|
if (approvedExecutionForSeat(project, seatId, sessionId) || (execution?.agent === agent && execution?.toolStep && turnCommands?.read(execution))) return undefined
|
||||||
return `需求门控模式:${labelOf(seatId)}当前没有有效的已批准执行任务,不能使用 ${name} 修改文件或执行工程操作。`
|
return `需求门控模式:${labelOf(seatId)}当前没有有效的已批准执行任务,不能使用 ${name} 修改文件或执行工程操作。`
|
||||||
}
|
}
|
||||||
return '需求门控模式:当前席位没有执行批准,不能修改文件或执行工程操作。'
|
return '需求门控模式:当前席位没有执行批准,不能修改文件或执行工程操作。'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function installSeatTools(ctx, { store, service, provisioner, turnCommands }) {
|
export function installSeatTools(ctx, { store, service, provisioner, turnCommands, host, leadReporter }) {
|
||||||
const defs = createSeatToolDefinitions({ store, service, turnCommands })
|
const defs = createSeatToolDefinitions({ store, service, turnCommands, provisioner, host, leadReporter })
|
||||||
// sessionId -> { agent, disposers: Map<name, dispose>, registered: Set<name> }
|
// sessionId -> { agent, disposers: Map<name, dispose>, registered: Set<name> }
|
||||||
const installs = new Map()
|
const installs = new Map()
|
||||||
// 已绑定、但 agent 或工具系统尚未就绪的会话;等下一次席位事件/重扫再补装。
|
// 已绑定、但 agent 或工具系统尚未就绪的会话;等下一次席位事件/重扫再补装。
|
||||||
|
|
@ -432,11 +558,12 @@ export function installSeatTools(ctx, { store, service, provisioner, turnCommand
|
||||||
record.disposers.clear()
|
record.disposers.clear()
|
||||||
record.registered.clear()
|
record.registered.clear()
|
||||||
try { record.guardDispose?.() } catch {}
|
try { record.guardDispose?.() } catch {}
|
||||||
|
try { record.restrictDispose?.() } catch {}
|
||||||
record.guardDispose = null
|
record.guardDispose = null
|
||||||
record.guardMounted = false
|
record.guardMounted = false
|
||||||
}
|
}
|
||||||
|
|
||||||
const findSeat = sessionId => seatBySessionId(store.state?.projects, sessionId)
|
const findSeat = sessionId => seatBySessionId(store.state?.projects, sessionId) ?? leadAssistantBySession(store.state?.projects, sessionId)
|
||||||
|
|
||||||
// 只给“仍是某席绑定会话”的 agent 注册;同会话同实例只装一次;换实例先卸旧再装。
|
// 只给“仍是某席绑定会话”的 agent 注册;同会话同实例只装一次;换实例先卸旧再装。
|
||||||
const attach = agent => {
|
const attach = agent => {
|
||||||
|
|
@ -445,7 +572,11 @@ export function installSeatTools(ctx, { store, service, provisioner, turnCommand
|
||||||
if (!sessionId) return false
|
if (!sessionId) return false
|
||||||
const located = findSeat(sessionId)
|
const located = findSeat(sessionId)
|
||||||
if (!located) return false
|
if (!located) return false
|
||||||
const seatDefs = located.seatId === 'lead' ? defs : defs.filter(def => def.name !== 'sansheng_card')
|
const seatDefs = defs.filter(def => {
|
||||||
|
if (located.role) return ASSISTANT_TOOLS[located.role].has(def.name)
|
||||||
|
if (def.name === 'sansheng_lead_brief' || def.name === 'sansheng_requirement_cancel') return false
|
||||||
|
return located.seatId === 'lead' || !['sansheng_card', 'sansheng_lead_delegate'].includes(def.name)
|
||||||
|
})
|
||||||
const agentTools = agent.ctx?.tools
|
const agentTools = agent.ctx?.tools
|
||||||
if (!agentTools || typeof agentTools.register !== 'function') {
|
if (!agentTools || typeof agentTools.register !== 'function') {
|
||||||
retry.add(sessionId)
|
retry.add(sessionId)
|
||||||
|
|
@ -460,20 +591,32 @@ export function installSeatTools(ctx, { store, service, provisioner, turnCommand
|
||||||
if (!record || record.guardMounted || typeof agentTools.guard !== 'function') return
|
if (!record || record.guardMounted || typeof agentTools.guard !== 'function') return
|
||||||
record.guardMounted = true
|
record.guardMounted = true
|
||||||
try {
|
try {
|
||||||
const dispose = agentTools.guard(buildSeatToolGuard(store, sessionId))
|
const dispose = agentTools.guard(buildSeatToolGuard(store, sessionId, turnCommands, agent))
|
||||||
record.guardDispose = typeof dispose === 'function' ? dispose : null
|
record.guardDispose = typeof dispose === 'function' ? dispose : null
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
record.guardMounted = false
|
record.guardMounted = false
|
||||||
console.warn(`sansheng: register tool guard failed: ${error?.message ?? error}`)
|
console.warn(`sansheng: register tool guard failed: ${error?.message ?? error}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
mountGuard()
|
|
||||||
if (record && record.registered.size === seatDefs.length) return true
|
|
||||||
if (!record) {
|
if (!record) {
|
||||||
record = { agent, disposers: new Map(), registered: new Set(), guardDispose: null, guardMounted: false }
|
record = { agent, disposers: new Map(), registered: new Set(), guardDispose: null, guardMounted: false }
|
||||||
installs.set(sessionId, record)
|
installs.set(sessionId, record)
|
||||||
}
|
}
|
||||||
mountGuard()
|
mountGuard()
|
||||||
|
if (located.role && !record.guardMounted) {
|
||||||
|
retry.add(sessionId)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (located.role && !record.restricted && typeof agentTools.restrict === 'function') {
|
||||||
|
try {
|
||||||
|
record.restrictDispose = agentTools.restrict({ allow: [] })
|
||||||
|
record.restricted = true
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[sansheng] 助手工具隔离失败:', error?.message ?? error)
|
||||||
|
retry.add(sessionId)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
for (const def of seatDefs) {
|
for (const def of seatDefs) {
|
||||||
if (record.registered.has(def.name)) continue
|
if (record.registered.has(def.name)) continue
|
||||||
try {
|
try {
|
||||||
|
|
@ -540,11 +683,16 @@ export function installSeatTools(ctx, { store, service, provisioner, turnCommand
|
||||||
})
|
})
|
||||||
: () => {}
|
: () => {}
|
||||||
|
|
||||||
return () => {
|
const dispose = () => {
|
||||||
stopped = true
|
stopped = true
|
||||||
try { offSeat?.() } catch {}
|
try { offSeat?.() } catch {}
|
||||||
try { offAgent?.() } catch {}
|
try { offAgent?.() } catch {}
|
||||||
for (const sessionId of [...installs.keys()]) disposeFor(sessionId)
|
for (const sessionId of [...installs.keys()]) disposeFor(sessionId)
|
||||||
retry.clear()
|
retry.clear()
|
||||||
}
|
}
|
||||||
|
dispose.assistantReady = (agent, role) => {
|
||||||
|
const id = sessionIdOf(agent)
|
||||||
|
return Boolean(id && findSeat(id)?.role === role && attach(agent))
|
||||||
|
}
|
||||||
|
return dispose
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ export const STATE_VERSION = 1
|
||||||
// 十席全局默认模型和执行模式文件版本。
|
// 十席全局默认模型和执行模式文件版本。
|
||||||
export const GLOBAL_SETTING_VERSION = 1
|
export const GLOBAL_SETTING_VERSION = 1
|
||||||
|
|
||||||
export const AGENT_PRESETS = Object.freeze(['standard', 'ops-ptc'])
|
export const AGENT_PRESETS = Object.freeze(['minimal', 'standard', 'ops-ptc'])
|
||||||
|
|
||||||
export function validAgentPreset(value) {
|
export function validAgentPreset(value) {
|
||||||
return value === null || value === undefined || AGENT_PRESETS.includes(value)
|
return value === null || value === undefined || AGENT_PRESETS.includes(value)
|
||||||
|
|
@ -17,7 +17,7 @@ export function validAgentPreset(value) {
|
||||||
export const SEAT_STATUS = Object.freeze(['pending', 'creating', 'bound', 'failed', 'missing'])
|
export const SEAT_STATUS = Object.freeze(['pending', 'creating', 'bound', 'failed', 'missing'])
|
||||||
export const PROJECT_STATUS = Object.freeze(['pending', 'provisioning', 'ready', 'error'])
|
export const PROJECT_STATUS = Object.freeze(['pending', 'provisioning', 'ready', 'error'])
|
||||||
// 任务:草稿 → 已派工/待执行 → 完成 / 取消 / 失败;需求门控增加等待用户、退回、待重确认。
|
// 任务:草稿 → 已派工/待执行 → 完成 / 取消 / 失败;需求门控增加等待用户、退回、待重确认。
|
||||||
export const TASK_STATUS = Object.freeze(['draft', 'dispatched', 'running', 'prepared', 'done', 'cancelled', 'failed', 'waiting_user', 'returned', 'reconfirm'])
|
export const TASK_STATUS = Object.freeze(['draft', 'dispatched', 'running', 'prepared', 'done', 'cancelled', 'failed', 'waiting_user', 'returned', 'reconfirm', 'blocked'])
|
||||||
// 需求清单:商讨中 / 待发布 / 已发布 / 已退回 / 已取消。
|
// 需求清单:商讨中 / 待发布 / 已发布 / 已退回 / 已取消。
|
||||||
export const REQUIREMENT_STATUS = Object.freeze(['discussing', 'ready', 'published', 'returned', 'cancelled'])
|
export const REQUIREMENT_STATUS = Object.freeze(['discussing', 'ready', 'published', 'returned', 'cancelled'])
|
||||||
// 流程阶段:只由宿主服务推进,模型不能跳阶段。
|
// 流程阶段:只由宿主服务推进,模型不能跳阶段。
|
||||||
|
|
@ -33,6 +33,16 @@ const PROJECT_ARRAY_FIELDS = Object.freeze(['tasks', 'artifacts', 'requirements'
|
||||||
const PROJECT_MAP_FIELDS = Object.freeze(['avatars', 'commandLedgers'])
|
const PROJECT_MAP_FIELDS = Object.freeze(['avatars', 'commandLedgers'])
|
||||||
const PROJECT_SEQ_FIELDS = Object.freeze(['taskSeq', 'artifactSeq', 'requirementSeq', 'approvalSeq'])
|
const PROJECT_SEQ_FIELDS = Object.freeze(['taskSeq', 'artifactSeq', 'requirementSeq', 'approvalSeq'])
|
||||||
|
|
||||||
|
export const LEAD_ASSISTANT_ROLES = Object.freeze(['intake', 'liaison'])
|
||||||
|
|
||||||
|
function emptyLeadAssistant() {
|
||||||
|
return { sessionId: null, plannedSessionId: null, status: 'pending', agentPreset: 'minimal' }
|
||||||
|
}
|
||||||
|
|
||||||
|
function emptyLeadAssistants() {
|
||||||
|
return Object.fromEntries(LEAD_ASSISTANT_ROLES.map(role => [role, emptyLeadAssistant()]))
|
||||||
|
}
|
||||||
|
|
||||||
export function normalizeState(state) {
|
export function normalizeState(state) {
|
||||||
for (const project of Object.values(state.projects ?? {})) {
|
for (const project of Object.values(state.projects ?? {})) {
|
||||||
for (const seat of Object.values(project.seats ?? {})) {
|
for (const seat of Object.values(project.seats ?? {})) {
|
||||||
|
|
@ -43,6 +53,12 @@ export function normalizeState(state) {
|
||||||
for (const key of PROJECT_ARRAY_FIELDS) if (!Array.isArray(project[key])) project[key] = []
|
for (const key of PROJECT_ARRAY_FIELDS) if (!Array.isArray(project[key])) project[key] = []
|
||||||
for (const key of PROJECT_MAP_FIELDS) if (!isObject(project[key])) project[key] = {}
|
for (const key of PROJECT_MAP_FIELDS) if (!isObject(project[key])) project[key] = {}
|
||||||
for (const key of PROJECT_SEQ_FIELDS) if (!Number.isFinite(project[key])) project[key] = 0
|
for (const key of PROJECT_SEQ_FIELDS) if (!Number.isFinite(project[key])) project[key] = 0
|
||||||
|
project.leadAssistants ??= emptyLeadAssistants()
|
||||||
|
for (const role of LEAD_ASSISTANT_ROLES) project.leadAssistants[role] ??= emptyLeadAssistant()
|
||||||
|
for (const task of project.tasks) {
|
||||||
|
task.lane ??= 'full'
|
||||||
|
task.unreviewedByMenxia ??= task.lane === 'fast'
|
||||||
|
}
|
||||||
project.memory = normalizeProjectMemory(project.memory, project.id)
|
project.memory = normalizeProjectMemory(project.memory, project.id)
|
||||||
}
|
}
|
||||||
return state
|
return state
|
||||||
|
|
@ -110,6 +126,7 @@ export function emptyProject({ id, name, workspaceId = null, path = null, now =
|
||||||
path,
|
path,
|
||||||
status: 'pending',
|
status: 'pending',
|
||||||
seats,
|
seats,
|
||||||
|
leadAssistants: emptyLeadAssistants(),
|
||||||
// 任务与交付成果:按项目隔离保存;旧数据没有这两个字段时按空数组处理。
|
// 任务与交付成果:按项目隔离保存;旧数据没有这两个字段时按空数组处理。
|
||||||
tasks: [],
|
tasks: [],
|
||||||
artifacts: [],
|
artifacts: [],
|
||||||
|
|
@ -130,10 +147,10 @@ export function emptyProject({ id, name, workspaceId = null, path = null, now =
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function emptyTask({ id, title = '', goal = '', requirement = '', ownerSeatId = 'lead', now = Date.now(), kind = 'legacy', requirementId = null, requirementRevision = null, approvalId = null, parentTaskId = null, stage = null }) {
|
export function emptyTask({ id, title = '', goal = '', requirement = '', ownerSeatId = 'lead', now = Date.now(), kind = 'legacy', requirementId = null, requirementRevision = null, approvalId = null, parentTaskId = null, stage = null, lane = 'full', unreviewedByMenxia = lane === 'fast' }) {
|
||||||
return {
|
return {
|
||||||
id, title, goal, requirement, ownerSeatId, status: 'draft', note: '', sessionId: null,
|
id, title, goal, requirement, ownerSeatId, status: 'draft', note: '', sessionId: null,
|
||||||
kind, requirementId, requirementRevision, approvalId, parentTaskId, stage,
|
kind, requirementId, requirementRevision, approvalId, parentTaskId, stage, lane, unreviewedByMenxia,
|
||||||
blockedReason: '', draft: '', reviewNote: '', summary: '', deliveryNote: '',
|
blockedReason: '', draft: '', reviewNote: '', summary: '', deliveryNote: '',
|
||||||
createdAt: now, updatedAt: now, dispatchedAt: null,
|
createdAt: now, updatedAt: now, dispatchedAt: null,
|
||||||
contextRevision: 0, contextHash: '', decisionIds: [], sourceRefs: [],
|
contextRevision: 0, contextHash: '', decisionIds: [], sourceRefs: [],
|
||||||
|
|
@ -205,6 +222,17 @@ function projectProblem(project, id) {
|
||||||
const problem = seatProblem(project.seats[seatId], seatId, id)
|
const problem = seatProblem(project.seats[seatId], seatId, id)
|
||||||
if (problem) return problem
|
if (problem) return problem
|
||||||
}
|
}
|
||||||
|
if (project.leadAssistants !== undefined) {
|
||||||
|
if (!isObject(project.leadAssistants)) return `项目 ${id} 的 leadAssistants 非法`
|
||||||
|
for (const [role, assistant] of Object.entries(project.leadAssistants)) {
|
||||||
|
if (!LEAD_ASSISTANT_ROLES.includes(role) || !isObject(assistant) || !SEAT_STATUS_SET.has(assistant.status) || assistant.agentPreset !== 'minimal') {
|
||||||
|
return `项目 ${id} 的后台助手 ${role} 非法`
|
||||||
|
}
|
||||||
|
for (const field of ['sessionId', 'plannedSessionId']) {
|
||||||
|
if (assistant[field] !== null && !isStr(assistant[field])) return `项目 ${id} 的后台助手 ${role} 的 ${field} 非法`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
for (const key of PROJECT_ARRAY_FIELDS) {
|
for (const key of PROJECT_ARRAY_FIELDS) {
|
||||||
if (project[key] !== undefined && !Array.isArray(project[key])) return `项目 ${id} 的 ${key} 不是数组`
|
if (project[key] !== undefined && !Array.isArray(project[key])) return `项目 ${id} 的 ${key} 不是数组`
|
||||||
}
|
}
|
||||||
|
|
@ -222,6 +250,8 @@ function projectProblem(project, id) {
|
||||||
for (const [index, task] of (project.tasks ?? []).entries()) {
|
for (const [index, task] of (project.tasks ?? []).entries()) {
|
||||||
if (!isObject(task)) return `项目 ${id} 的 tasks[${index}] 不是对象`
|
if (!isObject(task)) return `项目 ${id} 的 tasks[${index}] 不是对象`
|
||||||
if (!isStr(task.id)) return `项目 ${id} 的 tasks[${index}] 缺少 id`
|
if (!isStr(task.id)) return `项目 ${id} 的 tasks[${index}] 缺少 id`
|
||||||
|
if (task.lane !== undefined && !['full', 'fast'].includes(task.lane)) return `项目 ${id} 的任务 ${task.id} 流程类型非法`
|
||||||
|
if (task.unreviewedByMenxia !== undefined && typeof task.unreviewedByMenxia !== 'boolean') return `项目 ${id} 的任务 ${task.id} 审核标记非法`
|
||||||
if (!TASK_STATUS_SET.has(task.status)) return `项目 ${id} 的任务 ${task.id} 状态非法:${String(task.status)}`
|
if (!TASK_STATUS_SET.has(task.status)) return `项目 ${id} 的任务 ${task.id} 状态非法:${String(task.status)}`
|
||||||
}
|
}
|
||||||
if (project.memory !== undefined && !isObject(project.memory)) return `项目 ${id} 的 memory 非法`
|
if (project.memory !== undefined && !isObject(project.memory)) return `项目 ${id} 的 memory 非法`
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,200 @@
|
||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { setupService, seatById } from './helpers.js'
|
||||||
|
import { createLeadReporter } from '../src/host/lead-reporter.js'
|
||||||
|
import { createTurnCommands } from '../src/host/message-source.js'
|
||||||
|
import { installSeatTools } from '../src/host/tools.js'
|
||||||
|
|
||||||
|
async function setupFastLane() {
|
||||||
|
const env = await setupService()
|
||||||
|
const { project } = await env.service.open({ path: '/fast-lane', name: '快车道测试' })
|
||||||
|
const projectId = project.id
|
||||||
|
const lead = await env.service.enableSeat(projectId, 'lead')
|
||||||
|
const gongbu = await env.service.enableSeat(projectId, 'gongbu')
|
||||||
|
const leadSession = seatById(lead, 'lead').sessionId
|
||||||
|
const departmentSession = seatById(gongbu, 'gongbu').sessionId
|
||||||
|
const leadReporter = createLeadReporter({ store: env.store, host: env.fake.host })
|
||||||
|
env.service.leadReporter = leadReporter
|
||||||
|
const { requirement } = await env.service.requirementUpsert(projectId, {
|
||||||
|
title: '修正文档链接', originalText: '修正文档中的无效链接', scope: '只修改项目文档的现有链接',
|
||||||
|
acceptanceCriteria: '验证每个更新的链接指向存在的目标', missingInfo: '无',
|
||||||
|
})
|
||||||
|
const publish = (text, overrides = {}, actorOverrides = {}) => {
|
||||||
|
const current = { text, seq: 7, messageId: 'human-7', sessionId: leadSession }
|
||||||
|
return env.service.requirementPublish(projectId, requirement.id, {
|
||||||
|
lane: 'fast', targetSeatId: 'gongbu', expectedRevision: requirement.revision,
|
||||||
|
command: text, commandRef: { seq: current.seq, messageId: current.messageId },
|
||||||
|
...overrides,
|
||||||
|
}, { seatId: 'lead', sessionId: leadSession, readCurrentCommand: () => current, ...actorOverrides })
|
||||||
|
}
|
||||||
|
const report = (taskId, input) => env.service.taskReport(projectId, taskId, {
|
||||||
|
seatId: 'gongbu', sessionId: departmentSession, ...input,
|
||||||
|
})
|
||||||
|
return { ...env, projectId, leadSession, departmentSession, leadReporter, requirement, publish, report }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForDelivery(env, taskId) {
|
||||||
|
const task = async () => (await env.service.taskGet(env.projectId, taskId)).task
|
||||||
|
for (let i = 0; i < 200; i += 1) {
|
||||||
|
if ((await task()).deliveryState === 'accepted') return
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 5))
|
||||||
|
}
|
||||||
|
assert.equal((await task()).deliveryState, 'accepted')
|
||||||
|
}
|
||||||
|
|
||||||
|
test('快车道按本轮真人命令直派一次,完成回报直接交丞相并披露未经门下审核', async () => {
|
||||||
|
const env = await setupFastLane()
|
||||||
|
const command = '快车道,直接交给工部执行'
|
||||||
|
const { taskId } = await env.publish(command)
|
||||||
|
assert.equal((await env.publish(command)).taskId, taskId)
|
||||||
|
await waitForDelivery(env, taskId)
|
||||||
|
const { task } = await env.service.taskGet(env.projectId, taskId)
|
||||||
|
assert.equal(task.kind, 'execution')
|
||||||
|
assert.equal(task.stage, 'department_exec')
|
||||||
|
assert.equal(task.lane, 'fast')
|
||||||
|
assert.equal(task.unreviewedByMenxia, true)
|
||||||
|
const project = env.store.get(env.projectId)
|
||||||
|
const approval = project.approvals.find(item => item.id === task.approvalId)
|
||||||
|
assert.equal(approval.source, 'user-fast-lane')
|
||||||
|
assert.equal(approval.scope, task.approvalScope)
|
||||||
|
assert.equal(project.tasks.length, 1)
|
||||||
|
assert.deepEqual(env.fake.calls.followup.map(call => call.sessionId), [env.departmentSession])
|
||||||
|
await assert.rejects(() => env.report(taskId, { status: 'done', result: '伪造结果', sessionId: env.leadSession }), { code: 'sansheng/forbidden' })
|
||||||
|
const result = '修复 docs.md 链接,已验证 3 个目标'
|
||||||
|
const done = await env.report(taskId, { status: 'done', result })
|
||||||
|
assert.equal(done.task.status, 'done')
|
||||||
|
assert.equal(done.task.stage, 'delivered')
|
||||||
|
assert.equal((await env.report(taskId, { status: 'done', result })).task.duplicate, true)
|
||||||
|
await env.leadReporter.flush(env.projectId)
|
||||||
|
const reports = await env.leadReporter.list(env.projectId)
|
||||||
|
assert.equal(reports.length, 1)
|
||||||
|
assert.equal(reports[0].status, 'delivered')
|
||||||
|
assert.match(reports[0].summary, /未经门下审核与验收/)
|
||||||
|
assert.ok(reports[0].summary.includes(result))
|
||||||
|
assert.deepEqual(env.fake.calls.followup.map(call => call.sessionId), [env.departmentSession, env.leadSession])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('快车道拒绝陈旧命令、模糊指示及多部目标', async () => {
|
||||||
|
const env = await setupFastLane()
|
||||||
|
await assert.rejects(() => env.publish('直接交给工部', {}, { readCurrentCommand: () => null }), {
|
||||||
|
code: 'sansheng/current-user-message-unavailable',
|
||||||
|
})
|
||||||
|
await assert.rejects(() => env.publish('快车道交给工部和礼部'), { code: 'sansheng/workflow-route-forbidden' })
|
||||||
|
assert.equal((await env.service.tasks(env.projectId)).tasks.length, 0)
|
||||||
|
const other = await setupFastLane()
|
||||||
|
await assert.rejects(() => other.publish('这个需求我先看看'), { code: 'sansheng/publish-not-explicit' })
|
||||||
|
assert.equal((await other.service.tasks(other.projectId)).tasks.length, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('快车道需要选定单个需求且范围与验收已经明确', async () => {
|
||||||
|
const env = await setupFastLane()
|
||||||
|
const other = await env.service.requirementUpsert(env.projectId, { title: '整理目录', originalText: '整理目录' })
|
||||||
|
await assert.rejects(() => env.publish('直接交给工部执行 ' + env.requirement.id + ' 和 ' + other.requirement.id), {
|
||||||
|
code: 'sansheng/requirement-ambiguous',
|
||||||
|
})
|
||||||
|
const current = { text: '直接交给工部执行 ' + other.requirement.id, seq: 8, messageId: 'human-8', sessionId: env.leadSession }
|
||||||
|
await assert.rejects(() => env.service.requirementPublish(env.projectId, other.requirement.id, {
|
||||||
|
lane: 'fast', targetSeatId: 'gongbu', command: current.text, commandRef: current,
|
||||||
|
}, { seatId: 'lead', sessionId: env.leadSession, readCurrentCommand: () => current }), { code: 'sansheng/requirement-incomplete' })
|
||||||
|
assert.equal((await env.service.tasks(env.projectId)).tasks.length, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('书记官完整流程也需要有效真人授权且同一命令不能重放', async () => {
|
||||||
|
const env = await setupFastLane()
|
||||||
|
const options = { lane: 'full', targetSeatId: 'zhongshu' }
|
||||||
|
await assert.rejects(() => env.publish('走完整流程', options, { assistantRole: 'intake', readCurrentCommand: () => null }), {
|
||||||
|
code: 'sansheng/current-user-message-unavailable',
|
||||||
|
})
|
||||||
|
const actor = {
|
||||||
|
assistantRole: 'intake',
|
||||||
|
handoff: { operation: 'publish', requirementId: env.requirement.id, requirementRevision: env.requirement.revision },
|
||||||
|
}
|
||||||
|
const published = await env.publish('走完整流程', options, actor)
|
||||||
|
assert.ok(published.taskId)
|
||||||
|
await assert.rejects(() => env.publish('走完整流程', options, actor), { code: 'sansheng/command-used' })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('真人要求先拟方案或走流程时按完整流程发给中书', async () => {
|
||||||
|
const env = await setupFastLane()
|
||||||
|
const { taskId } = await env.publish('这个需求走流程,先出方案,让门下审一下')
|
||||||
|
const { task } = await env.service.taskGet(env.projectId, taskId)
|
||||||
|
assert.equal(task.kind, 'workflow')
|
||||||
|
assert.equal(task.ownerSeatId, 'zhongshu')
|
||||||
|
assert.equal(task.stage, 'zhongshu_draft')
|
||||||
|
assert.equal(env.store.get(env.projectId).approvals.length, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('快车道升级停止旧授权,丞相收到完整流程建议', async () => {
|
||||||
|
const env = await setupFastLane()
|
||||||
|
const { taskId } = await env.publish('直接交给工部执行')
|
||||||
|
await waitForDelivery(env, taskId)
|
||||||
|
const note = '变更牵涉多部门,须先确认共同范围'
|
||||||
|
const escalated = await env.report(taskId, { status: 'escalate', note })
|
||||||
|
assert.equal(escalated.task.status, 'blocked')
|
||||||
|
assert.equal(escalated.task.reportStatus, 'escalate')
|
||||||
|
assert.equal(escalated.task.blockedReason, note)
|
||||||
|
assert.equal(env.store.get(env.projectId).approvals[0].status, 'invalidated')
|
||||||
|
await assert.rejects(() => env.report(taskId, { status: 'running' }), { code: 'sansheng/stage-forbidden' })
|
||||||
|
assert.equal((await env.report(taskId, { status: 'escalate', note })).task.duplicate, true)
|
||||||
|
await env.leadReporter.flush(env.projectId)
|
||||||
|
const [report] = await env.leadReporter.list(env.projectId)
|
||||||
|
assert.equal(report.status, 'delivered')
|
||||||
|
assert.match(report.nextStep, /完整流程/)
|
||||||
|
assert.equal(report.needsUserDecision, true)
|
||||||
|
await assert.rejects(() => env.service.taskDispatch(env.projectId, taskId), { code: 'sansheng/invalid' })
|
||||||
|
assert.equal((await env.service.requirements(env.projectId)).requirements[0].status, 'ready')
|
||||||
|
const { taskId: fullTaskId } = await env.publish('走完整流程', {
|
||||||
|
lane: 'full', targetSeatId: 'zhongshu', commandRef: { seq: 8, messageId: 'human-8' },
|
||||||
|
})
|
||||||
|
assert.notEqual(fullTaskId, taskId)
|
||||||
|
assert.equal((await env.service.taskGet(env.projectId, fullTaskId)).task.stage, 'zhongshu_draft')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('六部只接受宿主确认的当前用户回合,规划席的 OPS 写守卫继续拦截', async () => {
|
||||||
|
const env = await setupService()
|
||||||
|
const { project: { id } } = await env.service.open({ path: '/direct-user-guard' })
|
||||||
|
const ministry = seatById(await env.service.enableSeat(id, 'gongbu'), 'gongbu')
|
||||||
|
const planner = seatById(await env.service.enableSeat(id, 'menxia'), 'menxia')
|
||||||
|
const listeners = new Map()
|
||||||
|
const guards = new Map()
|
||||||
|
let openTurnStartSeq = 4
|
||||||
|
const ctx = {
|
||||||
|
agents: { ...env.fake.host.agents, turnBoundaryOf: () => ({ openTurnStartSeq }) },
|
||||||
|
on(name, listener) { listeners.set(name, listener); return () => listeners.delete(name) },
|
||||||
|
}
|
||||||
|
for (const sessionId of [ministry.sessionId, planner.sessionId]) {
|
||||||
|
env.fake.sessions.get(sessionId).ctx = {
|
||||||
|
tools: { register: () => () => {}, guard: guard => { guards.set(sessionId, guard) } },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const tracker = createTurnCommands(ctx, env.store)
|
||||||
|
const dispose = installSeatTools(ctx, { ...env, turnCommands: tracker })
|
||||||
|
try {
|
||||||
|
const agent = env.fake.sessions.get(ministry.sessionId)
|
||||||
|
const guard = guards.get(ministry.sessionId)
|
||||||
|
const preStep = listeners.get('agent/pre-step')
|
||||||
|
const event = listeners.get('session/event')
|
||||||
|
const human = { id: 'human', role: 'user', content: '请修改这个文件', source: { kind: 'user', rpcId: 'rpc-1', clientTimeZone: 'Asia/Shanghai' } }
|
||||||
|
const internal = { ...human, id: 'internal', source: { kind: 'sansheng-task' } }
|
||||||
|
const write = { name: 'ops_edit', agent, toolStep: { turn: 2, step: 1 } }
|
||||||
|
await preStep({ agent, messages: [internal] }, () => {})
|
||||||
|
event(agent.session, { type: 'user/message', data: internal, seq: 5 })
|
||||||
|
event(agent.session, { type: 'user/message', data: human, seq: 6 })
|
||||||
|
assert.match(guard(write), /没有有效的已批准执行任务/)
|
||||||
|
event(agent.session, { type: 'turn/end', seq: 7 })
|
||||||
|
openTurnStartSeq = 8
|
||||||
|
await preStep({ agent, messages: [human] }, () => {})
|
||||||
|
assert.match(guard(write), /没有有效的已批准执行任务/)
|
||||||
|
event(agent.session, { type: 'user/message', data: human, seq: 9 })
|
||||||
|
assert.equal(guard(write), undefined)
|
||||||
|
assert.match(guard({ name: 'subagent' }), /不能使用/)
|
||||||
|
event(agent.session, { type: 'turn/end', seq: 10 })
|
||||||
|
assert.match(guard(write), /没有有效的已批准执行任务/)
|
||||||
|
for (const name of ['ops_bash', 'ops_write', 'ops_edit', 'run_code']) {
|
||||||
|
assert.match(guards.get(planner.sessionId)({ name }), /只能只读调查/)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
dispose()
|
||||||
|
tracker.dispose()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,197 @@
|
||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFile, writeFile } from 'node:fs/promises'
|
||||||
|
import { setupService, seatById } from './helpers.js'
|
||||||
|
import { SanshengStore } from '../src/host/store.js'
|
||||||
|
import { createProvisioner } from '../src/host/provision.js'
|
||||||
|
import { createTurnCommands } from '../src/host/message-source.js'
|
||||||
|
import { createSeatToolDefinitions, installSeatTools } from '../src/host/tools.js'
|
||||||
|
import { createLeadReporter } from '../src/host/lead-reporter.js'
|
||||||
|
import { emptyTask } from '../src/shared/schema.js'
|
||||||
|
|
||||||
|
async function setup() {
|
||||||
|
const env = await setupService()
|
||||||
|
const { store, service, fake, provisioner } = env
|
||||||
|
const { project: { id } } = await service.open({ path: '/lead-assistants' })
|
||||||
|
const leadSeat = seatById(await service.enableSeat(id, 'lead'), 'lead')
|
||||||
|
const lead = fake.sessions.get(leadSeat.sessionId)
|
||||||
|
const reporter = createLeadReporter({ store, host: fake.host, ensureLeadAssistant: provisioner.ensureLeadAssistant })
|
||||||
|
service.leadReporter = reporter
|
||||||
|
return { ...env, id, lead, reporter }
|
||||||
|
}
|
||||||
|
|
||||||
|
function toolContext(env) {
|
||||||
|
const listeners = new Map()
|
||||||
|
const boundaries = new Map()
|
||||||
|
const ctx = {
|
||||||
|
agents: { ...env.fake.host.agents, turnBoundaryOf: session => ({ openTurnStartSeq: boundaries.get(session.id) }) },
|
||||||
|
on(name, fn) { listeners.set(name, fn); return () => listeners.delete(name) },
|
||||||
|
}
|
||||||
|
const tracker = createTurnCommands(ctx, env.store)
|
||||||
|
const options = { ...env, host: env.fake.host, leadReporter: env.reporter, turnCommands: tracker }
|
||||||
|
const defs = createSeatToolDefinitions(options)
|
||||||
|
const execute = (name, args, agent) => defs.find(def => def.name === name).execute(args, { agent })
|
||||||
|
async function start(agent, message, boundary) {
|
||||||
|
boundaries.set(agent.session.id, boundary)
|
||||||
|
await listeners.get('agent/pre-step')({ agent, messages: [message], step: 1 }, () => {})
|
||||||
|
listeners.get('session/event')(agent.session, { type: 'user/message', data: message, seq: boundary + 1 })
|
||||||
|
}
|
||||||
|
return { tracker, execute, start, install: () => installSeatTools(ctx, options) }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('旧 v1 文件补齐助手字段,首次并发请求只创建一个 minimal 会话', async () => {
|
||||||
|
const { file, store, fake, id } = await setup()
|
||||||
|
const old = JSON.parse(await readFile(file, 'utf8'))
|
||||||
|
delete old.projects[id].leadAssistants
|
||||||
|
await writeFile(file, JSON.stringify(old))
|
||||||
|
const reloaded = new SanshengStore(file)
|
||||||
|
await reloaded.ensureLoaded()
|
||||||
|
assert.equal(old.version, 1)
|
||||||
|
assert.equal(Object.keys(reloaded.get(id).seats).length, 10)
|
||||||
|
assert.deepEqual(reloaded.get(id).seats, store.get(id).seats)
|
||||||
|
assert.deepEqual(reloaded.get(id).leadAssistants.intake, { sessionId: null, plannedSessionId: null, status: 'pending', agentPreset: 'minimal' })
|
||||||
|
assert.equal(fake.calls.create.length, 1)
|
||||||
|
const leadAssistantModel = { provider: 'deepseek', model: 'deepseek-chat' }
|
||||||
|
const provisioner = createProvisioner({ store: reloaded, host: fake.host, leadAssistantModel })
|
||||||
|
const [first, second] = await Promise.all([provisioner.ensureLeadAssistant(id, 'intake'), provisioner.ensureLeadAssistant(id, 'intake')])
|
||||||
|
assert.equal(first.sessionId, second.sessionId)
|
||||||
|
assert.equal(fake.calls.create.length, 2)
|
||||||
|
assert.equal(fake.calls.create.at(-1).agentPreset, 'minimal')
|
||||||
|
assert.deepEqual(fake.sessions.get(first.sessionId).model.current(), leadAssistantModel)
|
||||||
|
assert.equal(fake.calls.rename.at(-1).title, '相·需求')
|
||||||
|
assert.equal(reloaded.get(id).leadAssistants.liaison.status, 'pending')
|
||||||
|
const recovered = createProvisioner({ store: new SanshengStore(file), host: fake.host })
|
||||||
|
assert.equal((await recovered.ensureLeadAssistant(id, 'intake')).sessionId, first.sessionId)
|
||||||
|
assert.equal(fake.calls.create.length, 2)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('助手专用模型只选择到助手会话,同一 Agent 无需重复选择', async () => {
|
||||||
|
const { store, id, fake } = await setup()
|
||||||
|
const model = { provider: 'deepseek', model: 'deepseek-reasoner' }
|
||||||
|
const provisioner = createProvisioner({ store, host: fake.host, leadAssistantModel: model })
|
||||||
|
const { sessionId } = await provisioner.ensureLeadAssistant(id, 'intake')
|
||||||
|
await provisioner.ensureLeadAssistant(id, 'intake')
|
||||||
|
assert.deepEqual(fake.calls.agentSelect, [{ sessionId, selection: model }])
|
||||||
|
assert.equal(fake.calls.selectModel, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('书记官通过本轮后台交接发布,拒绝伪造消息和已消费授权', async t => {
|
||||||
|
const env = await setup()
|
||||||
|
const { store, service, fake, id, lead } = env
|
||||||
|
const { tracker, execute, start } = toolContext(env)
|
||||||
|
t.after(() => tracker.dispose())
|
||||||
|
const { requirement } = await service.requirementUpsert(id, { title: '更新提示', originalText: '只改提示文字' })
|
||||||
|
const args = { requirementId: requirement.id, expectedRevision: requirement.revision }
|
||||||
|
const user = { id: 'lead-user', role: 'user', content: '发布 ' + requirement.id + ',走流程', source: { kind: 'user', rpcId: 'main-rpc', clientTimeZone: 'Asia/Shanghai' } }
|
||||||
|
await start(lead, user, 10)
|
||||||
|
assert.deepEqual(await execute('sansheng_lead_delegate', { role: 'intake', operation: 'publish', request: user.content }, lead), { ok: true, status: 'queued' })
|
||||||
|
const { sessionId, message } = fake.calls.followup.at(-1)
|
||||||
|
const intake = fake.sessions.get(sessionId)
|
||||||
|
assert.equal(sessionId, store.get(id).leadAssistants.intake.sessionId)
|
||||||
|
assert.equal(message.source.kind, 'sansheng-intake')
|
||||||
|
assert.equal(Object.hasOwn(message.source, 'seq'), false)
|
||||||
|
await start(intake, { ...message, id: 'forged', source: { ...message.source, seq: 11 } }, 20)
|
||||||
|
const rejected = await execute('sansheng_requirement_publish', { ...args, commandRef: { seq: 11, messageId: user.id } }, intake)
|
||||||
|
assert.equal(rejected.ok, false)
|
||||||
|
assert.equal(store.get(id).tasks.length, 0)
|
||||||
|
await start(intake, message, 30)
|
||||||
|
const outcome = await execute('sansheng_requirement_publish', args, intake)
|
||||||
|
assert.equal(outcome.ok, true, JSON.stringify(outcome))
|
||||||
|
assert.equal(store.get(id).tasks[0].ownerSeatId, 'zhongshu')
|
||||||
|
assert.equal((await execute('sansheng_requirement_publish', args, intake)).reason, 'sansheng/command-used')
|
||||||
|
await start(intake, message, 40)
|
||||||
|
assert.equal((await execute('sansheng_requirement_publish', args, intake)).ok, false)
|
||||||
|
assert.equal(store.get(id).tasks.length, 1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('联络官先收回报,主丞相只收到一次简报并保留审批编号', async t => {
|
||||||
|
const env = await setup()
|
||||||
|
const { id, lead, fake, store, reporter } = env
|
||||||
|
const { tracker, execute, install } = toolContext(env)
|
||||||
|
t.after(() => tracker.dispose())
|
||||||
|
const raw = '完整审批回报细节'.repeat(20)
|
||||||
|
const { report } = await reporter.record(id, {
|
||||||
|
transitionId: 'approval:original-id', event: 'approval_request', summary: raw, needsUserDecision: true,
|
||||||
|
})
|
||||||
|
assert.equal((await reporter.send(id, report.reportId)).ok, true)
|
||||||
|
const liaisonId = store.get(id).leadAssistants.liaison.sessionId
|
||||||
|
const liaison = fake.sessions.get(liaisonId)
|
||||||
|
assert.equal(fake.calls.followup.at(-1).sessionId, liaisonId)
|
||||||
|
assert.match(fake.calls.followup.at(-1).message.content[0].text, /完整审批回报细节/)
|
||||||
|
assert.equal(fake.calls.followup.some(item => item.sessionId === lead.session.id), false)
|
||||||
|
const registered = new Set()
|
||||||
|
let guard
|
||||||
|
let restrictions
|
||||||
|
liaison.ctx = { tools: {
|
||||||
|
register(def) { registered.add(def.name) },
|
||||||
|
guard(fn) { guard = fn },
|
||||||
|
restrict(options) { restrictions = options },
|
||||||
|
} }
|
||||||
|
const dispose = install()
|
||||||
|
t.after(dispose)
|
||||||
|
assert.deepEqual(restrictions, { allow: [] })
|
||||||
|
assert.equal(dispose.assistantReady(liaison, 'liaison'), true)
|
||||||
|
assert.equal(dispose.assistantReady(liaison, 'intake'), false)
|
||||||
|
assert.deepEqual([...registered].sort(), ['sansheng_lead_brief', 'sansheng_requirement_list', 'sansheng_task_consult', 'sansheng_task_decision', 'sansheng_task_list', 'sansheng_task_result'])
|
||||||
|
assert.match(guard({ name: 'run_code' }), /只读/)
|
||||||
|
assert.equal((await execute('sansheng_lead_brief', { reportId: report.reportId, summary: '请审批操作' }, lead)).ok, false)
|
||||||
|
assert.equal((await execute('sansheng_lead_brief', { reportId: report.reportId, summary: '请审批操作' }, liaison)).ok, true)
|
||||||
|
const briefs = fake.calls.followup.filter(item => item.sessionId === lead.session.id)
|
||||||
|
assert.equal(briefs.length, 1)
|
||||||
|
assert.match(briefs[0].message.content[0].text, /original-id/)
|
||||||
|
assert.doesNotMatch(briefs[0].message.content[0].text, /完整审批回报细节/)
|
||||||
|
assert.equal((await execute('sansheng_lead_brief', { reportId: report.reportId, summary: '重发' }, liaison)).duplicate, true)
|
||||||
|
assert.equal(fake.calls.followup.filter(item => item.sessionId === lead.session.id).length, 1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('联络会话不可用时安全回退到主丞相', async () => {
|
||||||
|
const { id, lead, fake, reporter } = await setup()
|
||||||
|
fake.control.failCreateOrder = 2
|
||||||
|
const { report } = await reporter.record(id, { transitionId: 'decision-1', event: 'decision_required', summary: '用户需裁决' })
|
||||||
|
assert.equal((await reporter.send(id, report.reportId)).ok, true)
|
||||||
|
assert.equal(fake.calls.followup.at(-1).sessionId, lead.session.id)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('讨论未授权下派,取消只能处理用户指定的编号且防重放', async t => {
|
||||||
|
const env = await setup()
|
||||||
|
const { id, lead, fake, service, store } = env
|
||||||
|
const { tracker, execute, start } = toolContext(env)
|
||||||
|
t.after(() => tracker.dispose())
|
||||||
|
const user = (id, content) => ({ id, content, role: 'user', source: { kind: 'user', rpcId: id, clientTimeZone: 'Asia/Shanghai' } })
|
||||||
|
const { requirement: first } = await service.requirementUpsert(id, { title: '甲', originalText: '甲' })
|
||||||
|
const { requirement: second } = await service.requirementUpsert(id, { title: '乙', originalText: '乙' })
|
||||||
|
await start(lead, user('discussion', '我们先讨论能否发布 ' + first.id), 10)
|
||||||
|
assert.equal((await execute('sansheng_lead_delegate', { role: 'intake', operation: 'publish', request: first.id }, lead)).reason, 'sansheng/publish-not-explicit')
|
||||||
|
assert.equal(store.get(id).leadAssistants.intake.status, 'pending')
|
||||||
|
await start(lead, user('cancel', '取消 ' + first.id), 20)
|
||||||
|
assert.equal((await execute('sansheng_lead_delegate', { role: 'intake', operation: 'cancel', request: first.id }, lead)).ok, true)
|
||||||
|
const { sessionId, message } = fake.calls.followup.at(-1)
|
||||||
|
const intake = fake.sessions.get(sessionId)
|
||||||
|
await start(intake, message, 30)
|
||||||
|
assert.equal((await execute('sansheng_requirement_cancel', { requirementId: second.id }, intake)).reason, 'sansheng/requirement-conflict')
|
||||||
|
assert.equal((await execute('sansheng_requirement_cancel', { requirementId: first.id }, intake)).ok, true)
|
||||||
|
assert.equal((await execute('sansheng_requirement_cancel', { requirementId: first.id }, intake)).reason, 'sansheng/command-used')
|
||||||
|
assert.equal(store.get(id).requirements.find(req => req.id === second.id).status, 'ready')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('门下验收、会商和裁决请求均先进入联络官', async () => {
|
||||||
|
const { id, lead, fake, store, service, reporter } = await setup()
|
||||||
|
const { requirement } = await service.requirementUpsert(id, { title: '交付', originalText: '完整任务原文' })
|
||||||
|
const snapshot = emptyTask({ id: 'task-check', title: '交付', ownerSeatId: 'menxia', kind: 'workflow',
|
||||||
|
requirementId: requirement.id, requirementRevision: requirement.revision, stage: 'menxia_acceptance' })
|
||||||
|
await store.mutate(state => { state.projects[id].tasks.push({ ...snapshot, summary: '完整任务原文'.repeat(30) }) })
|
||||||
|
const consultation = await service.consultTask(id, snapshot.id, { text: '需要裁决', toSeatIds: ['lead'] }, { seatId: 'menxia' })
|
||||||
|
assert.deepEqual(consultation.failedSeatIds, [])
|
||||||
|
const { decision, reportId } = await service.requestTaskDecision(id, snapshot.id, { question: '选哪项?', options: ['甲', '乙'] }, { seatId: 'lead' })
|
||||||
|
await reporter.flush(id)
|
||||||
|
const liaisonId = store.get(id).leadAssistants.liaison.sessionId
|
||||||
|
assert.ok(fake.calls.followup.some(entry => entry.sessionId === liaisonId && entry.message.source.reportId === reportId))
|
||||||
|
const brief = await reporter.brief(id, { reportId, summary: '请在工作台选择甲或乙。' }, { seatId: 'liaison', sessionId: liaisonId })
|
||||||
|
assert.equal(brief.ok, true)
|
||||||
|
assert.ok(fake.calls.followup.at(-1).message.content[0].text.includes(decision.id))
|
||||||
|
const accepted = await service.workflowAccept(id, snapshot.id, { action: 'accept', note: '验收通过' }, { seatId: 'menxia' })
|
||||||
|
assert.equal(accepted.task.stage, 'lead_delivery')
|
||||||
|
await reporter.flush(id)
|
||||||
|
assert.equal(fake.calls.followup.filter(entry => entry.sessionId === lead.session.id).length, 1)
|
||||||
|
assert.ok(fake.calls.followup.some(entry => entry.sessionId === liaisonId && entry.message.content[0].text.includes('menxia_accept')))
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,89 @@
|
||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { SanshengStore } from '../src/host/store.js'
|
||||||
|
import { emptyProject } from '../src/shared/schema.js'
|
||||||
|
import { createLeadReporter } from '../src/host/lead-reporter.js'
|
||||||
|
import { tempStateFile } from './fake-ctx.js'
|
||||||
|
|
||||||
|
async function setup() {
|
||||||
|
const store = new SanshengStore(await tempStateFile())
|
||||||
|
await store.load()
|
||||||
|
await store.mutate(state => {
|
||||||
|
const project = emptyProject({ id: 'project', name: 'Report recovery' })
|
||||||
|
Object.assign(project.seats.lead, { status: 'bound', sessionId: 'main' })
|
||||||
|
Object.assign(project.leadAssistants.liaison, { status: 'bound', sessionId: 'liaison' })
|
||||||
|
state.projects.project = project
|
||||||
|
})
|
||||||
|
const calls = []
|
||||||
|
const agents = new Map()
|
||||||
|
function setAgent(sessionId, followup = () => {}) {
|
||||||
|
const agent = {
|
||||||
|
session: { id: sessionId },
|
||||||
|
followup(message) {
|
||||||
|
calls.push({ sessionId, message })
|
||||||
|
return followup(message)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
agents.set(sessionId, agent)
|
||||||
|
return agent
|
||||||
|
}
|
||||||
|
setAgent('main')
|
||||||
|
const liaison = setAgent('liaison')
|
||||||
|
const actor = { seatId: 'liaison', sessionId: 'liaison', projectId: 'project', agent: liaison }
|
||||||
|
const host = { agents }
|
||||||
|
const ensureLeadAssistant = () => store.get('project').leadAssistants.liaison
|
||||||
|
const reporter = createLeadReporter({ store, host, ensureLeadAssistant })
|
||||||
|
await reporter.record('project', { reportId: 'report', transitionId: 'approval:canonical-id', event: 'approval_request' })
|
||||||
|
return { store, host, reporter, actor, calls, setAgent, ensureLeadAssistant }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('report recovery does not replay a liaison delivery with an uncommitted outcome', async () => {
|
||||||
|
const { store, host, reporter, calls, ensureLeadAssistant } = await setup()
|
||||||
|
const save = store.save.bind(store)
|
||||||
|
store.save = async () => {
|
||||||
|
if (store.get('project').leadReports[0].status === 'delivered') throw new Error('write failed')
|
||||||
|
await save()
|
||||||
|
}
|
||||||
|
await assert.rejects(() => reporter.send('project', 'report'), /write failed/)
|
||||||
|
assert.deepEqual(calls.map(call => call.sessionId), ['liaison'])
|
||||||
|
|
||||||
|
const reloaded = new SanshengStore(store.file)
|
||||||
|
const recovered = createLeadReporter({ store: reloaded, host, ensureLeadAssistant })
|
||||||
|
const { project: [result] } = await recovered.recoverAll()
|
||||||
|
assert.equal(result.status, 'unknown')
|
||||||
|
assert.deepEqual(calls.map(call => call.sessionId), ['liaison'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('brief releases its claim if the main agent changes before followup', async () => {
|
||||||
|
const { store, reporter, actor, calls, setAgent } = await setup()
|
||||||
|
const save = store.save.bind(store)
|
||||||
|
store.save = async () => {
|
||||||
|
await save()
|
||||||
|
if (store.get('project').leadReports[0].brief?.status === 'sending') {
|
||||||
|
setAgent('main')
|
||||||
|
store.save = save
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const input = { reportId: 'report', summary: 'Please review', approvalId: 'spoofed-id' }
|
||||||
|
assert.equal((await reporter.brief('project', input, actor)).status, 'not-sent')
|
||||||
|
assert.equal(store.get('project').leadReports[0].brief, undefined)
|
||||||
|
assert.deepEqual(calls, [])
|
||||||
|
|
||||||
|
assert.equal((await reporter.brief('project', input, actor)).status, 'delivered')
|
||||||
|
assert.deepEqual(calls.map(call => call.sessionId), ['main'])
|
||||||
|
assert.match(calls[0].message.content[0].text, /审批编号:canonical-id/)
|
||||||
|
assert.doesNotMatch(calls[0].message.content[0].text, /spoofed-id/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('an uncertain brief remains deduplicated after reopening the store', async () => {
|
||||||
|
const { store, host, reporter, actor, calls, setAgent } = await setup()
|
||||||
|
setAgent('main', () => { throw new Error('followup outcome unknown') })
|
||||||
|
const input = { reportId: 'report', summary: 'Please review' }
|
||||||
|
assert.equal((await reporter.brief('project', input, actor)).status, 'unknown')
|
||||||
|
|
||||||
|
const reloaded = new SanshengStore(store.file)
|
||||||
|
const recovered = createLeadReporter({ store: reloaded, host })
|
||||||
|
const duplicate = await recovered.brief('project', input, actor)
|
||||||
|
assert.deepEqual(duplicate, { ok: false, status: 'unknown', reportId: 'report', duplicate: true })
|
||||||
|
assert.deepEqual(calls.map(call => call.sessionId), ['main'])
|
||||||
|
})
|
||||||
|
|
@ -80,7 +80,7 @@ test('当前轮授权只接受首步认领并落盘的 Web 用户消息', async
|
||||||
await preStep({ agent, messages: [human] }, next)
|
await preStep({ agent, messages: [human] }, next)
|
||||||
assert.equal(tracker.read(exec), null)
|
assert.equal(tracker.read(exec), null)
|
||||||
event(session, { type: 'user/message', seq: 10, data: human })
|
event(session, { type: 'user/message', seq: 10, data: human })
|
||||||
assert.deepEqual(tracker.read(exec), { text: '就按这个做', messageId: 'm-1', seq: 10 })
|
assert.deepEqual(tracker.read(exec), { text: '就按这个做', messageId: 'm-1', seq: 10, sessionId: session.id })
|
||||||
live = { session }
|
live = { session }
|
||||||
assert.equal(tracker.read(exec), null)
|
assert.equal(tracker.read(exec), null)
|
||||||
tracker.dispose()
|
tracker.dispose()
|
||||||
|
|
@ -105,7 +105,7 @@ test('当前轮授权只认宿主落盘正文:两份正文不一致仍可下
|
||||||
const next = () => ({ kind: 'enter' })
|
const next = () => ({ kind: 'enter' })
|
||||||
await preStep({ agent, messages: [queued] }, next)
|
await preStep({ agent, messages: [queued] }, next)
|
||||||
event(session, { type: 'user/message', seq: 6, data: landed })
|
event(session, { type: 'user/message', seq: 6, data: landed })
|
||||||
assert.deepEqual(tracker.read(exec), { text: '就按这个做,发布 R-002', messageId: 'm-9', seq: 6 })
|
assert.deepEqual(tracker.read(exec), { text: '就按这个做,发布 R-002', messageId: 'm-9', seq: 6, sessionId: session.id })
|
||||||
|
|
||||||
event(session, { type: 'turn/end', seq: 7 })
|
event(session, { type: 'turn/end', seq: 7 })
|
||||||
openTurnStartSeq = 8
|
openTurnStartSeq = 8
|
||||||
|
|
|
||||||
|
|
@ -136,7 +136,7 @@ test('workbench 推荐分工与执行模式草稿视图:中枢/三省为 stand
|
||||||
for (const id of ['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']) {
|
for (const id of ['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']) {
|
||||||
assert.equal(recommendedPresetForSeat(id), 'ops-ptc')
|
assert.equal(recommendedPresetForSeat(id), 'ops-ptc')
|
||||||
}
|
}
|
||||||
assert.deepEqual(PRESET_OPTIONS.map(p => p.value), ['standard', 'ops-ptc'])
|
assert.deepEqual(PRESET_OPTIONS.map(p => p.value), ['standard', 'ops-ptc', 'minimal'])
|
||||||
|
|
||||||
const legacyView = buildWorkbenchView({
|
const legacyView = buildWorkbenchView({
|
||||||
project: {
|
project: {
|
||||||
|
|
|
||||||
|
|
@ -69,6 +69,46 @@ test('API 全局和项目模式按优先级生效,清除覆盖不改已绑定
|
||||||
assert.equal(seatById(await service.project(projectId), seatId).presetSource, 'role-default')
|
assert.equal(seatById(await service.project(projectId), seatId).presetSource, 'role-default')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('极简模式可作为全局默认或项目覆盖,并通过显式重建更新会话', async () => {
|
||||||
|
const { service, globalStore, fake, api } = await fixture()
|
||||||
|
const seatId = 'shangshu'
|
||||||
|
const { project: { id: projectId } } = await service.open({ path: '/preset-minimal' })
|
||||||
|
const defaults = await api('setGlobalDefault', { seatId, agentPreset: 'minimal' })
|
||||||
|
assert.equal(defaults.ok, true)
|
||||||
|
assert.equal(defaults.value.globalDefaults.seatPresets[seatId], 'minimal')
|
||||||
|
const reloaded = new GlobalModelStore(globalStore.file)
|
||||||
|
await reloaded.ensureLoaded()
|
||||||
|
assert.equal(reloaded.getSeatPreset(seatId), 'minimal')
|
||||||
|
|
||||||
|
const view = await service.enableSeat(projectId, seatId)
|
||||||
|
const oldSeat = seatById(view, seatId)
|
||||||
|
assert.equal(oldSeat.configuredPreset, 'minimal')
|
||||||
|
assert.equal(oldSeat.presetSource, 'global')
|
||||||
|
assert.equal(oldSeat.sessionPreset, 'minimal')
|
||||||
|
assert.equal(fake.calls.create.at(-1).agentPreset, 'minimal')
|
||||||
|
|
||||||
|
const model = { provider: 'deepseek', model: 'deepseek-chat' }
|
||||||
|
const first = await service.configure(projectId, seatId, { model, instructions: '尚书项目指令', agentPreset: 'ops-ptc' })
|
||||||
|
assert.equal(first.seat.sessionPreset, 'minimal')
|
||||||
|
const rebuilt = seatById(await service.rebuildSeat(projectId, seatId, {
|
||||||
|
force: true, expectedSessionId: oldSeat.sessionId,
|
||||||
|
}), seatId)
|
||||||
|
assert.equal(rebuilt.sessionPreset, 'ops-ptc')
|
||||||
|
|
||||||
|
const override = await api('configure', { projectId, seatId, agentPreset: 'minimal' })
|
||||||
|
assert.equal(override.ok, true)
|
||||||
|
assert.equal(override.value.seat.agentPreset, 'minimal')
|
||||||
|
assert.equal(override.value.seat.presetSource, 'project')
|
||||||
|
assert.deepEqual(override.value.seat.model, model)
|
||||||
|
assert.equal(override.value.seat.instructions, '尚书项目指令')
|
||||||
|
const final = seatById(await service.rebuildSeat(projectId, seatId, {
|
||||||
|
force: true, expectedSessionId: rebuilt.sessionId,
|
||||||
|
}), seatId)
|
||||||
|
assert.equal(final.sessionPreset, 'minimal')
|
||||||
|
assert.deepEqual(final.previousSessionIds, [oldSeat.sessionId, rebuilt.sessionId])
|
||||||
|
assert.equal(fake.calls.create.at(-1).agentPreset, 'minimal')
|
||||||
|
})
|
||||||
|
|
||||||
test('非法模式走 sansheng/invalid,项目和全局数据保持原样', async () => {
|
test('非法模式走 sansheng/invalid,项目和全局数据保持原样', async () => {
|
||||||
const { service, api, globalStore } = await fixture()
|
const { service, api, globalStore } = await fixture()
|
||||||
const opened = await service.open({ path: '/preset-invalid' })
|
const opened = await service.open({ path: '/preset-invalid' })
|
||||||
|
|
@ -86,9 +126,9 @@ test('模型与模式一起写入只增加一次 revision,模式单独更新
|
||||||
const model = { provider: 'deepseek', model: 'deepseek-chat' }
|
const model = { provider: 'deepseek', model: 'deepseek-chat' }
|
||||||
await service.setGlobalDefault('lead', model, { agentPreset: 'ops-ptc' })
|
await service.setGlobalDefault('lead', model, { agentPreset: 'ops-ptc' })
|
||||||
assert.equal(globalStore.snapshot().revision, 1)
|
assert.equal(globalStore.snapshot().revision, 1)
|
||||||
await service.setGlobalDefault('lead', null, { agentPreset: 'standard' })
|
await service.setGlobalDefault('lead', null, { agentPreset: 'minimal' })
|
||||||
assert.deepEqual(globalStore.getSeat('lead'), model)
|
assert.deepEqual(globalStore.getSeat('lead'), model)
|
||||||
assert.equal(globalStore.getSeatPreset('lead'), 'standard')
|
assert.equal(globalStore.getSeatPreset('lead'), 'minimal')
|
||||||
})
|
})
|
||||||
|
|
||||||
test('v1.1.6 的项目和全局设置缺失模式字段时正常加载', async () => {
|
test('v1.1.6 的项目和全局设置缺失模式字段时正常加载', async () => {
|
||||||
|
|
@ -168,8 +208,8 @@ test('旧会话模式来自宿主投影,正在运行时禁止切换,ID 不
|
||||||
const { project: { id: projectId } } = await service.open({ path: '/preset-legacy-rebuild' })
|
const { project: { id: projectId } } = await service.open({ path: '/preset-legacy-rebuild' })
|
||||||
const { sessionId } = seatById(await service.enableSeat(projectId, seatId), seatId)
|
const { sessionId } = seatById(await service.enableSeat(projectId, seatId), seatId)
|
||||||
await store.mutate(state => { state.projects[projectId].seats[seatId].sessionPreset = null })
|
await store.mutate(state => { state.projects[projectId].seats[seatId].sessionPreset = null })
|
||||||
fake.host.agentPresets = { presetForSession: session => session.id === sessionId ? 'ops-ptc' : null }
|
fake.host.agentPresets = { presetForSession: session => session.id === sessionId ? 'minimal' : null }
|
||||||
assert.equal(seatById(await service.project(projectId), seatId).sessionPreset, 'ops-ptc')
|
assert.equal(seatById(await service.project(projectId), seatId).sessionPreset, 'minimal')
|
||||||
const payload = { projectId, seatId, expectedSessionId: sessionId, force: true }
|
const payload = { projectId, seatId, expectedSessionId: sessionId, force: true }
|
||||||
fake.sessions.get(sessionId).status = 'running'
|
fake.sessions.get(sessionId).status = 'running'
|
||||||
assert.equal((await api('rebuildSeat', payload)).error.code, 'sansheng/seat-busy')
|
assert.equal((await api('rebuildSeat', payload)).error.code, 'sansheng/seat-busy')
|
||||||
|
|
|
||||||
|
|
@ -43,7 +43,8 @@ function makeEventedCtx(env) {
|
||||||
return { ctx, registered, disposed, guards, emit }
|
return { ctx, registered, disposed, guards, emit }
|
||||||
}
|
}
|
||||||
|
|
||||||
const TOOL_COUNT = createSeatToolDefinitions({ service: { cardCreate() {} } }).length
|
const TOOL_COUNT = createSeatToolDefinitions({ service: { cardCreate() {} } })
|
||||||
|
.filter(def => !['sansheng_lead_brief', 'sansheng_requirement_cancel'].includes(def.name)).length
|
||||||
|
|
||||||
test('回归:创建事件先到、绑定后保存时,绑定成功即补装部门工具(无需重扫)', async () => {
|
test('回归:创建事件先到、绑定后保存时,绑定成功即补装部门工具(无需重扫)', async () => {
|
||||||
const env = await setupService({ prompt: true })
|
const env = await setupService({ prompt: true })
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue