298 lines
15 KiB
JavaScript
298 lines
15 KiB
JavaScript
import test from 'node:test'
|
||
import assert from 'node:assert/strict'
|
||
import { SanshengStore } from '../src/host/store.js'
|
||
import { createFakeHost, tempStateFile } from './fake-ctx.js'
|
||
import { createProvisioner } from '../src/host/provision.js'
|
||
import { createProvinceAgents } from '../src/host/province-agents.js'
|
||
import { SanshengService } from '../src/host/service.js'
|
||
|
||
function fakeSubagentRig(fake, beforeActivationReturns) {
|
||
const handlers = new Map()
|
||
const emit = (type, ...args) => handlers.get(type)?.(...args)
|
||
const presets = []
|
||
const restrictions = []
|
||
const specs = []
|
||
const children = new Map()
|
||
const cancelled = []
|
||
const disposed = []
|
||
const registry = {
|
||
register: async preset => { presets.push(preset); return () => {} },
|
||
presetForSession: () => null,
|
||
}
|
||
const subagents = {
|
||
getProvider: () => ({ inheritsParentContext: false, capabilities: { agentPreset: true } }),
|
||
async startActivation(spec) {
|
||
specs.push(spec)
|
||
const childId = spec.childId
|
||
const agent = {
|
||
id: childId,
|
||
session: {
|
||
id: childId,
|
||
header: { agentPreset: spec.agentPreset },
|
||
append: (type, data) => restrictions.push({ childId, type, data }),
|
||
},
|
||
ctx: { get: name => ({
|
||
tools: { restrict: data => restrictions.push({ childId, type: 'tools', data }) },
|
||
sandboxPolicy: { overrideOf: () => null },
|
||
approval: { setPolicy: (_agent, data) => restrictions.push({ childId, type: 'approval', data }) },
|
||
})[name] },
|
||
cancel(reason) { cancelled.push({ childId, reason }) },
|
||
}
|
||
children.set(childId, agent)
|
||
emit('agent/created', { agent })
|
||
await beforeActivationReturns?.(spec, emit)
|
||
return { childId, name: 'child', dispose: async () => { disposed.push(childId) }, result: Promise.resolve({}) }
|
||
},
|
||
}
|
||
const ctx = {
|
||
agents: { get: id => children.get(id) ?? fake.host.agents.get(id) },
|
||
get: name => name === 'subagents' ? subagents : (name === 'agentPresets' ? registry : null),
|
||
on(type, handler) {
|
||
handlers.set(type, handler)
|
||
return () => handlers.delete(type)
|
||
},
|
||
}
|
||
return { ctx, specs, children, cancelled, disposed, emit, presets, restrictions }
|
||
}
|
||
|
||
async function setup({ onOrderSettled, beforeActivationReturns } = {}) {
|
||
const file = await tempStateFile()
|
||
const store = new SanshengStore(file)
|
||
await store.load()
|
||
const fake = createFakeHost({ prompt: true })
|
||
const provisioner = createProvisioner({ store, host: fake.host })
|
||
const rig = fakeSubagentRig(fake, beforeActivationReturns)
|
||
const serviceRef = { service: null }
|
||
const provinceAgents = createProvinceAgents({ ctx: rig.ctx, store, serviceRef, host: fake.host, onOrderSettled })
|
||
provinceAgents.install()
|
||
const service = new SanshengService({ store, host: fake.host, provisioner, provinceAgents })
|
||
serviceRef.service = service
|
||
const opened = await service.open({ path: '/province', name: '省级子 Agent 项目' })
|
||
const projectId = opened.project.id
|
||
await service.enableSeat(projectId, 'zhongshu')
|
||
await service.enableSeat(projectId, 'menxia')
|
||
await service.enableSeat(projectId, 'shangshu')
|
||
return { file, store, fake, service, provinceAgents, projectId, ...rig }
|
||
}
|
||
|
||
test('中书接令:丞相指令交给中书接令子 Agent,先回执再转主席', async () => {
|
||
const env = await setup()
|
||
const order = await env.service.startOrder(env.projectId, {
|
||
instruction: '把登录页改成邮箱登录,保留手机号登录。',
|
||
}, { sessionId: 'province-lead-session' })
|
||
assert.equal(order.ok, true)
|
||
assert.match(order.receipt.text, /已叫中书接令/)
|
||
assert.match(order.receipt.text, /来源:丞相会话 province/)
|
||
const spec = env.specs.at(-1)
|
||
assert.equal(spec.agentPreset, 'sansheng-province-zhongshu-order')
|
||
assert.equal(spec.delivery, 'parent', '接令结果交回中书主席')
|
||
assert.equal(spec.maxDepth, 1)
|
||
assert.equal(spec.parent.session.id, env.store.get(env.projectId).seats.zhongshu.sessionId)
|
||
const prompt = spec.prompt[0].text
|
||
assert.match(prompt, /邮箱登录/)
|
||
assert.match(prompt, /丞相会话/)
|
||
const runs = await env.service.agentRuns(env.projectId)
|
||
assert.equal(runs.runs.length, 1)
|
||
assert.equal(runs.runs[0].kind, 'order')
|
||
assert.equal(runs.runs[0].seatId, 'zhongshu')
|
||
})
|
||
|
||
test('门下和尚书接令使用固定预设、席位主席和只读策略,并记录属官来源', async () => {
|
||
const env = await setup()
|
||
await env.store.mutate(state => {
|
||
state.projects[env.projectId].secretaryRuns = [{ childId: 'secretary-child-session' }]
|
||
})
|
||
for (const [seatId, province] of [['menxia', '门下'], ['shangshu', '尚书']]) {
|
||
const order = await env.provinceAgents.startOrder({
|
||
projectId: env.projectId, instruction: '核对验收条件', seatId,
|
||
sourceSessionId: 'secretary-child-session',
|
||
})
|
||
const spec = env.specs.at(-1)
|
||
const parentSessionId = env.store.get(env.projectId).seats[seatId].sessionId
|
||
assert.equal(spec.parent.session.id, parentSessionId)
|
||
assert.equal(spec.delivery, 'parent')
|
||
assert.equal(spec.agentPreset, 'sansheng-province-' + seatId + '-order')
|
||
assert.deepEqual(env.presets.find(preset => preset.id === spec.agentPreset)?.plugins, [])
|
||
assert.match(spec.prompt[0].text, new RegExp(province + '主席'))
|
||
assert.match(order.receipt.text, new RegExp('已叫' + province + '接令'))
|
||
assert.match(order.receipt.text, /丞相属官会话/)
|
||
const run = env.store.get(env.projectId).provinceRuns.at(-1)
|
||
assert.equal(run.sourceSessionId, 'secretary-child-session')
|
||
assert.equal(run.parentSessionId, parentSessionId)
|
||
assert.deepEqual(env.restrictions.filter(entry => entry.childId === order.childId), [
|
||
{ childId: order.childId, type: 'tools', data: { allow: [] } },
|
||
{ childId: order.childId, type: 'sandbox/mode', data: { mode: 'read-only' } },
|
||
{ childId: order.childId, type: 'approval', data: 'never' },
|
||
])
|
||
}
|
||
await assert.rejects(env.provinceAgents.startOrder({
|
||
projectId: env.projectId, instruction: '核对验收条件', seatId: 'bingbu',
|
||
}), { code: 'sansheng/province-invalid' })
|
||
assert.equal(env.specs.length, 2)
|
||
})
|
||
|
||
test('显式需求版本必须匹配任务和需求,并在记录接令时复核', async () => {
|
||
const env = await setup()
|
||
await env.store.mutate(state => {
|
||
const project = state.projects[env.projectId]
|
||
project.requirements = [{ id: 'R-001', revision: 2 }]
|
||
project.tasks = [{ id: 'task-1', requirementId: 'R-001', requirementRevision: 2 }]
|
||
})
|
||
const input = { projectId: env.projectId, instruction: '核对范围', seatId: 'menxia', requirementId: 'R-001' }
|
||
await assert.rejects(env.provinceAgents.startOrder({ ...input, expectedRevision: 1 }), { code: 'sansheng/requirement-conflict' })
|
||
const order = await env.provinceAgents.startOrder({ ...input, taskId: 'task-1', expectedRevision: 2 })
|
||
assert.equal(order.receipt.source.requirementRevision, 2)
|
||
|
||
const pending = env.provinceAgents.startOrder({ ...input, expectedRevision: 2 })
|
||
const changed = env.store.mutate(state => { state.projects[env.projectId].requirements[0].revision++ })
|
||
await Promise.all([changed, assert.rejects(pending, { code: 'sansheng/requirement-conflict' })])
|
||
await assert.rejects(env.provinceAgents.startOrder({
|
||
...input, requirementId: null, taskId: 'task-1', expectedRevision: 2,
|
||
}), { code: 'sansheng/requirement-conflict' })
|
||
assert.equal(env.specs.length, 1)
|
||
assert.equal(env.store.get(env.projectId).provinceRuns.length, 1)
|
||
})
|
||
|
||
function orderSettlement(childId, text) {
|
||
return {
|
||
type: 'user/message',
|
||
data: { source: { kind: 'subagent-settled', senderSessionId: childId }, content: [{ type: 'text', text }] },
|
||
}
|
||
}
|
||
|
||
test('接令回调只在主席收到结果且落盘后调用一次', async () => {
|
||
const callbacks = []
|
||
const env = await setup({
|
||
async onOrderSettled(payload) {
|
||
const readPersistedRun = async () => {
|
||
const persistedStore = new SanshengStore(env.file)
|
||
await persistedStore.load()
|
||
const persistedRun = persistedStore.get(env.projectId).provinceRuns.find(run => run.id === payload.run.id)
|
||
return { payload, persistedRun }
|
||
}
|
||
const callback = readPersistedRun()
|
||
callbacks.push(callback)
|
||
await callback
|
||
},
|
||
})
|
||
const { projectId } = env
|
||
const order = await env.provinceAgents.startOrder({ projectId, instruction: '核对范围', seatId: 'shangshu' })
|
||
const spec = env.specs.at(-1)
|
||
const event = orderSettlement(order.childId, '已核对范围')
|
||
env.emit('session/event', { id: 'other-session' }, event)
|
||
await env.store._queue
|
||
assert.equal(env.store.get(projectId).provinceRuns[0].status, 'running')
|
||
assert.equal(callbacks.length, 0)
|
||
env.emit('session/event', spec.parent.session, event)
|
||
env.emit('session/event', spec.parent.session, event)
|
||
await env.store._queue
|
||
const run = env.store.get(projectId).provinceRuns[0]
|
||
assert.equal(run.status, 'settled')
|
||
assert.deepEqual(await Promise.all(callbacks), [{ payload: { projectId, run, result: '已核对范围' }, persistedRun: run }])
|
||
assert.equal(env.provinceAgents._internal.live.has(run.id), false)
|
||
})
|
||
|
||
test('接令在 spawn 返回前回执也保留已落盘结果', async () => {
|
||
const callbacks = []
|
||
const env = await setup({
|
||
onOrderSettled: async payload => { callbacks.push(payload) },
|
||
beforeActivationReturns: (spec, emit) => emit('session/event', spec.parent.session, orderSettlement(spec.childId, '已收到')),
|
||
})
|
||
const order = await env.provinceAgents.startOrder({ projectId: env.projectId, instruction: '核对范围' })
|
||
const run = env.store.get(env.projectId).provinceRuns[0]
|
||
assert.equal(run.status, 'settled')
|
||
assert.equal(run.sessionId, order.childId)
|
||
assert.deepEqual(callbacks, [{ projectId: env.projectId, run, result: '已收到' }])
|
||
assert.equal(env.provinceAgents._internal.live.has(run.id), false)
|
||
})
|
||
|
||
test('议政代表由省级子 Agent 担任,发言落盘标记 subagent,前文照旧带走', async () => {
|
||
const env = await setup()
|
||
const started = await env.service.startDeliberation(env.projectId, { topic: '省级代表议政' })
|
||
await env.service.waitForDeliberation(env.projectId)
|
||
const id = started.deliberation.id
|
||
const spec = env.specs.at(-1)
|
||
assert.equal(spec.agentPreset, 'sansheng-province-zhongshu-deliberation')
|
||
assert.equal(spec.delivery, 'caller')
|
||
assert.match(spec.prompt[0].text, /省级代表议政/)
|
||
|
||
const record = (await env.service.deliberation(env.projectId, id)).deliberation
|
||
const runId = record.turn.delegateRunId
|
||
assert.ok(runId)
|
||
const childId = record.turn.delegateChildId
|
||
const speech = await env.service.deliberationSpeak(env.projectId, id, {
|
||
round: 1, text: '中书代表同意', stance: 'agree',
|
||
}, {
|
||
seatId: 'zhongshu', sessionId: childId,
|
||
delegate: { runId, deliberationId: id, round: 1, seatId: 'zhongshu' },
|
||
})
|
||
assert.equal(speech.speech.via, 'subagent')
|
||
assert.equal(speech.speech.runId, runId)
|
||
|
||
await env.service.waitForDeliberation(env.projectId)
|
||
const next = env.specs.at(-1)
|
||
assert.equal(next.agentPreset, 'sansheng-province-menxia-deliberation')
|
||
assert.match(next.prompt[0].text, /中书代表同意/, '门下子 Agent 的提示里带前文')
|
||
})
|
||
|
||
test('停止议政会真打断省级子 Agent,之后不再叫下一位', async () => {
|
||
const env = await setup()
|
||
const started = await env.service.startDeliberation(env.projectId, { topic: '停止省级代表' })
|
||
await env.service.waitForDeliberation(env.projectId)
|
||
const id = started.deliberation.id
|
||
const record = (await env.service.deliberation(env.projectId, id)).deliberation
|
||
const speech = await env.service.deliberationSpeak(env.projectId, id, {
|
||
round: 1, text: '中书说完了', stance: 'agree',
|
||
}, {
|
||
seatId: 'zhongshu', sessionId: record.turn.delegateChildId,
|
||
delegate: { runId: record.turn.delegateRunId, deliberationId: id, round: 1, seatId: 'zhongshu' },
|
||
})
|
||
assert.equal(speech.ok, true)
|
||
await env.service.waitForDeliberation(env.projectId)
|
||
const menxiaRun = env.specs.at(-1)
|
||
assert.equal(menxiaRun.agentPreset, 'sansheng-province-menxia-deliberation')
|
||
|
||
const stopped = await env.service.stopDeliberation(env.projectId, id, { note: '用户点停' })
|
||
assert.equal(stopped.deliberation.status, 'stopped')
|
||
assert.equal(stopped.deliberation.stoppedTurn.seatId, 'menxia')
|
||
assert.equal(stopped.cancelled, true)
|
||
assert.ok(env.cancelled.some(item => item.childId === menxiaRun.childId))
|
||
const runs = await env.service.agentRuns(env.projectId)
|
||
assert.equal(runs.runs.length, 0, '被停的代表不再出现在运行列表')
|
||
const project = env.store.get(env.projectId)
|
||
const run = project.provinceRuns.find(item => item.childId === menxiaRun.childId)
|
||
assert.equal(run.status, 'stopped')
|
||
})
|
||
|
||
test('统一停止入口能停掉省级接令运行', async () => {
|
||
const env = await setup()
|
||
const order = await env.service.startOrder(env.projectId, { instruction: '把按钮颜色改成蓝色' }, { sessionId: 'lead-session-2' })
|
||
const runs = await env.service.agentRuns(env.projectId)
|
||
assert.equal(runs.runs.length, 1)
|
||
const stopped = await env.service.stopAgentRun(env.projectId, runs.runs[0].id, 'province')
|
||
assert.equal(stopped.ok, true)
|
||
assert.equal(stopped.cancelled, true)
|
||
assert.ok(env.cancelled.some(item => item.childId === order.childId))
|
||
assert.equal((await env.service.agentRuns(env.projectId)).runs.length, 0)
|
||
})
|
||
|
||
test('头像:字符与缩放图片入项目状态,超限与坏格式拒绝,清空恢复默认', async () => {
|
||
const env = await setup()
|
||
const char = await env.service.setAvatar(env.projectId, 'zhongshu', { char: '中' })
|
||
assert.equal(char.avatar.type, 'char')
|
||
assert.equal(env.store.get(env.projectId).avatars.zhongshu.char, '中')
|
||
|
||
const tiny = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
|
||
const image = await env.service.setAvatar(env.projectId, 'menxia', { dataUrl: tiny })
|
||
assert.equal(image.avatar.type, 'image')
|
||
assert.equal(env.store.get(env.projectId).avatars.menxia.mime, 'image/png')
|
||
|
||
await assert.rejects(env.service.setAvatar(env.projectId, 'shangshu', { dataUrl: 'data:text/plain;base64,aGVsbG8=' }), { code: 'sansheng/avatar-invalid' })
|
||
const huge = 'data:image/png;base64,' + Buffer.alloc(130 * 1024).toString('base64')
|
||
await assert.rejects(env.service.setAvatar(env.projectId, 'shangshu', { dataUrl: huge }), { code: 'sansheng/avatar-invalid' })
|
||
await assert.rejects(env.service.setAvatar(env.projectId, 'zhongshu', { char: '一二三四五六七八九' }), { code: 'sansheng/avatar-invalid' })
|
||
|
||
await env.service.clearAvatar(env.projectId, 'zhongshu')
|
||
assert.equal(env.store.get(env.projectId).avatars.zhongshu, undefined)
|
||
assert.equal((await env.service.project(env.projectId)).project.avatars.menxia.type, 'image')
|
||
}) |