392 lines
15 KiB
JavaScript
392 lines
15 KiB
JavaScript
// 十席会话专用工具:把“部门”落到已绑定的真实 session,而不是同名普通子代理。
|
||
import { SEAT_IDS, SEATS } from '../shared/roles.js'
|
||
|
||
function text(value) {
|
||
return typeof value === 'string' ? value.trim() : ''
|
||
}
|
||
|
||
function agentIdFrom(exec) {
|
||
return exec?.agent?.session?.id ?? exec?.agent?.id ?? exec?.agent?.sessionId ?? exec?.sessionId ?? null
|
||
}
|
||
|
||
async function locateSeat(service, exec) {
|
||
const sessionId = agentIdFrom(exec)
|
||
if (!sessionId) throw new Error('当前会话没有会话 id,不能使用部门工具')
|
||
await service.store.ensureLoaded()
|
||
for (const project of service.store.list()) {
|
||
for (const seatId of SEAT_IDS) {
|
||
const seat = project.seats?.[seatId]
|
||
if (seat?.sessionId === sessionId) return { project, seatId, seat, sessionId }
|
||
}
|
||
}
|
||
throw new Error('当前会话不是十席会话(未绑定项目/部门),不能使用部门工具')
|
||
}
|
||
|
||
function labelOf(seatId) {
|
||
return SEATS[seatId]?.label ?? seatId
|
||
}
|
||
|
||
function okTask(task) {
|
||
return {
|
||
ok: true,
|
||
taskId: task.id,
|
||
status: task.status,
|
||
ownerSeatId: task.ownerSeatId,
|
||
targetLabel: labelOf(task.ownerSeatId),
|
||
requirement: task.requirement ?? '',
|
||
result: task.result ?? '',
|
||
resultSessionId: task.resultSessionId ?? null,
|
||
reportStatus: task.reportStatus ?? 'none',
|
||
contextRevision: task.contextRevision ?? null,
|
||
deliveryState: task.deliveryState ?? 'none',
|
||
note: task.note ?? '',
|
||
}
|
||
}
|
||
|
||
const seatToolOutput = {
|
||
// DSH 要求每个工具声明模型可见的输出契约;这里统一用 JSON 对象文本。
|
||
schema: { type: 'object', additionalProperties: true },
|
||
render(_args, value) {
|
||
return [{ type: 'text', text: JSON.stringify(value, null, 2) }]
|
||
},
|
||
}
|
||
|
||
function seatToolDefinitions({ store, service }) {
|
||
const definitions = []
|
||
|
||
definitions.push({
|
||
name: 'sansheng_dispatch_task',
|
||
description: '丞相专用:把任务正式派给当前项目已绑定的部门会话(工部/吏部等),使用该部门原有会话和模型。禁止用同名子代理、普通 agent 或自己代写来冒充部门。派工前会把用户原话与最新项目共识写入共识,并把共识和原话一起投递。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: {
|
||
targetSeatId: { type: 'string', description: '目标部门 id,例如 gongbu(工部)、libu(吏部)' },
|
||
title: { type: 'string', description: '任务标题' },
|
||
goal: { type: 'string', description: '任务说明/验收目标' },
|
||
requirement: { type: 'string', description: '用户对部门提出的具体要求(尽量保留原话)' },
|
||
sourceText: { type: 'string', description: '用户原话或讨论原文,用于写入项目共识来源' },
|
||
},
|
||
required: ['targetSeatId', 'title'],
|
||
},
|
||
async execute(args = {}, exec) {
|
||
// 区分三种失败:本席工具未就绪 / 目标部门未开启 / 任务投递失败;成功才回 ok:true。
|
||
let located
|
||
try {
|
||
located = await locateSeat(service, exec)
|
||
} catch (error) {
|
||
return {
|
||
ok: false,
|
||
delivered: false,
|
||
reason: 'tool-not-ready',
|
||
error: `本席派工工具未就绪:${error?.message ?? error}`,
|
||
hint: '当前会话没有有效的席位绑定,不能派工;请从已绑定的丞相会话发起。',
|
||
}
|
||
}
|
||
const { project, seatId } = located
|
||
if (seatId !== 'lead') throw new Error('只有丞相可以派工,部门不能自行派工')
|
||
const targetSeatId = text(args.targetSeatId)
|
||
if (!SEAT_IDS.includes(targetSeatId) || targetSeatId === 'lead') throw new Error('目标必须是丞相以外的十席部门')
|
||
const title = text(args.title)
|
||
if (!title) throw new Error('任务标题不能为空')
|
||
const goal = text(args.goal)
|
||
const requirement = text(args.requirement)
|
||
const sourceText = text(args.sourceText)
|
||
const source = sourceText || requirement || title
|
||
// 先写共识:派工必须带最新共识和用户原话,不能只发一句“让工部做”。
|
||
if (requirement || sourceText) {
|
||
await service.memoryUpdate(project.id, {
|
||
decisions: [{ type: 'user', status: 'active', text: sourceText || requirement }],
|
||
sources: [{ type: 'user', excerpt: source, at: Date.now() }],
|
||
})
|
||
}
|
||
const created = await service.taskCreate(project.id, {
|
||
title,
|
||
goal,
|
||
requirement,
|
||
ownerSeatId: targetSeatId,
|
||
})
|
||
let dispatched
|
||
try {
|
||
dispatched = await service.taskDispatch(project.id, created.task.id, { force: true })
|
||
} catch (error) {
|
||
const code = String(error?.code ?? '')
|
||
const message = String(error?.message ?? error)
|
||
if (code === 'sansheng/seat-unbound' || /会话还没开启|seat-unbound|未开启/.test(message)) {
|
||
return {
|
||
ok: false,
|
||
delivered: false,
|
||
reason: 'target-seat-unavailable',
|
||
taskId: created.task.id,
|
||
targetLabel: labelOf(targetSeatId),
|
||
error: `目标部门「${labelOf(targetSeatId)}」未开启,无法派工:${message}`,
|
||
}
|
||
}
|
||
return {
|
||
ok: false,
|
||
delivered: false,
|
||
reason: 'delivery-failed',
|
||
taskId: created.task.id,
|
||
targetLabel: labelOf(targetSeatId),
|
||
error: `任务投递失败:${message}`,
|
||
}
|
||
}
|
||
const result = okTask(dispatched.task)
|
||
if (!dispatched.delivered) {
|
||
return {
|
||
...result,
|
||
ok: false,
|
||
delivered: false,
|
||
reason: 'delivery-failed',
|
||
taskId: created.task.id,
|
||
targetLabel: labelOf(targetSeatId),
|
||
error: dispatched.task.note || '任务投递失败,未送达部门会话',
|
||
}
|
||
}
|
||
return {
|
||
...result,
|
||
ok: true,
|
||
delivered: true,
|
||
taskId: created.task.id,
|
||
sessionId: dispatched.task.sessionId,
|
||
targetLabel: labelOf(targetSeatId),
|
||
}
|
||
},
|
||
})
|
||
|
||
definitions.push({
|
||
name: 'sansheng_task_list',
|
||
description: '查看当前项目真实任务列表,包含状态、主责部门、是否已投递、结果和结果来源会话。',
|
||
parameters: { type: 'object', properties: {} },
|
||
async execute(_args = {}, exec) {
|
||
const { project } = await locateSeat(service, exec)
|
||
const tasks = (project.tasks ?? []).map(task => ({ ...task, targetLabel: labelOf(task.ownerSeatId) }))
|
||
return { ok: true, projectId: project.id, tasks }
|
||
},
|
||
})
|
||
|
||
definitions.push({
|
||
name: 'sansheng_task_result',
|
||
description: '查询一个任务的真实结果。结果必须带部门回报的真实内容和 resultSessionId,不能由丞相代写。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: { taskId: { type: 'string', description: '任务 id' } },
|
||
required: ['taskId'],
|
||
},
|
||
async execute(args = {}, exec) {
|
||
const { project } = await locateSeat(service, exec)
|
||
const task = (await service.taskGet(project.id, text(args.taskId))).task
|
||
return { ok: true, task: { ...task, targetLabel: labelOf(task.ownerSeatId) } }
|
||
},
|
||
})
|
||
|
||
definitions.push({
|
||
name: 'sansheng_task_revise',
|
||
description: '丞相专用:用户改口或补充要求时,先更新项目共识,再按新要求重新投递到原部门会话。不能只口头说“已通知”。已完成或已取消的任务不能改历史结果,需用 sansheng_dispatch_task 新建任务。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: {
|
||
taskId: { type: 'string', description: '任务 id' },
|
||
goal: { type: 'string', description: '新的任务说明' },
|
||
requirement: { type: 'string', description: '新的用户要求(尽量保留原话)' },
|
||
sourceText: { type: 'string', description: '用户改口原文,用于写入项目共识来源' },
|
||
},
|
||
required: ['taskId'],
|
||
},
|
||
async execute(args = {}, exec) {
|
||
const { project, seatId } = await locateSeat(service, exec)
|
||
if (seatId !== 'lead') throw new Error('只有丞相可以修改要求并重投')
|
||
const taskId = text(args.taskId)
|
||
const goal = text(args.goal)
|
||
const requirement = text(args.requirement)
|
||
const sourceText = text(args.sourceText)
|
||
if (!goal && !requirement) throw new Error('修改要求需要提供新的 goal 或 requirement')
|
||
const existing = (await service.taskGet(project.id, taskId)).task
|
||
if (existing.status === 'done' || existing.status === 'cancelled') {
|
||
throw new Error('任务已完成或已取消,不能原地修改;请用 sansheng_dispatch_task 新建任务,保留历史结果')
|
||
}
|
||
if (requirement || sourceText) {
|
||
await service.memoryUpdate(project.id, {
|
||
decisions: [{ type: 'user', status: 'active', text: sourceText || requirement }],
|
||
sources: [{ type: 'user', excerpt: sourceText || requirement, at: Date.now() }],
|
||
})
|
||
}
|
||
await service.taskRevise(project.id, taskId, { goal: goal || undefined, requirement: requirement || undefined })
|
||
const dispatched = await service.taskDispatch(project.id, taskId, { force: true })
|
||
const result = okTask(dispatched.task)
|
||
if (!dispatched.delivered) {
|
||
return { ...result, ok: false, delivered: false, error: dispatched.task.note || '改要求后投递失败,未送达部门会话' }
|
||
}
|
||
return {
|
||
...result,
|
||
ok: true,
|
||
delivered: true,
|
||
sessionId: dispatched.task.sessionId,
|
||
requirement: dispatched.task.requirement ?? '',
|
||
contextRevision: dispatched.task.contextRevision ?? null,
|
||
}
|
||
},
|
||
})
|
||
|
||
definitions.push({
|
||
name: 'sansheng_task_report',
|
||
description: '部门专用:向当前项目的任务回报 running(执行中)、done(完成,必须附真实结果)或 failed(失败)。丞相不能代替部门报告,结果会关联真实部门 session。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: {
|
||
taskId: { type: 'string', description: '任务 id' },
|
||
status: { type: 'string', enum: ['running', 'done', 'failed'], description: '执行中/完成/失败' },
|
||
result: { type: 'string', description: '真实结果(done 必填),例如文件路径、输出内容、验证结果' },
|
||
note: { type: 'string', description: '补充说明' },
|
||
},
|
||
required: ['taskId', 'status'],
|
||
},
|
||
async execute(args = {}, exec) {
|
||
const { project, seatId, sessionId } = await locateSeat(service, exec)
|
||
if (seatId === 'lead') throw new Error('丞相不能代替部门报告,必须由实际执行部门回报')
|
||
const reported = await service.taskReport(project.id, text(args.taskId), {
|
||
status: text(args.status),
|
||
result: text(args.result),
|
||
note: text(args.note),
|
||
seatId,
|
||
sessionId,
|
||
})
|
||
return { ok: true, task: reported.task, late: Boolean(reported.late) }
|
||
},
|
||
})
|
||
|
||
for (const definition of definitions) definition.output = seatToolOutput
|
||
return definitions
|
||
}
|
||
|
||
export function createSeatToolDefinitions(options) {
|
||
return seatToolDefinitions(options)
|
||
}
|
||
|
||
export function installSeatTools(ctx, { store, service, provisioner }) {
|
||
const defs = createSeatToolDefinitions({ store, service })
|
||
// sessionId -> { agent, disposers: Map<name, dispose>, registered: Set<name> }
|
||
const installs = new Map()
|
||
// 已绑定、但 agent 或工具系统尚未就绪的会话;等下一次席位事件/重扫再补装。
|
||
const retry = new Set()
|
||
let stopped = false
|
||
|
||
const sessionIdOf = agent => agent?.session?.id ?? agent?.id ?? null
|
||
|
||
const disposeFor = sessionId => {
|
||
const record = installs.get(sessionId)
|
||
if (!record) return
|
||
installs.delete(sessionId)
|
||
retry.delete(sessionId)
|
||
for (const dispose of record.disposers.values()) {
|
||
try { dispose?.() } catch {}
|
||
}
|
||
record.disposers.clear()
|
||
record.registered.clear()
|
||
}
|
||
|
||
const findSeat = sessionId => {
|
||
for (const project of Object.values(store.state?.projects ?? {})) {
|
||
for (const seatId of SEAT_IDS) {
|
||
const seat = project?.seats?.[seatId]
|
||
if (seat?.sessionId === sessionId) return { project, seatId, seat }
|
||
}
|
||
}
|
||
return null
|
||
}
|
||
|
||
// 只给“仍是某席绑定会话”的 agent 注册;同会话同实例只装一次;换实例先卸旧再装。
|
||
const attach = agent => {
|
||
if (stopped || !agent) return false
|
||
const sessionId = sessionIdOf(agent)
|
||
if (!sessionId) return false
|
||
if (!findSeat(sessionId)) return false
|
||
const agentTools = agent.ctx?.tools
|
||
if (!agentTools || typeof agentTools.register !== 'function') {
|
||
retry.add(sessionId)
|
||
return false
|
||
}
|
||
let record = installs.get(sessionId)
|
||
if (record && record.agent !== agent) {
|
||
disposeFor(sessionId)
|
||
record = undefined
|
||
}
|
||
if (record && record.registered.size === defs.length) return true
|
||
if (!record) {
|
||
record = { agent, disposers: new Map(), registered: new Set() }
|
||
installs.set(sessionId, record)
|
||
}
|
||
for (const def of defs) {
|
||
if (record.registered.has(def.name)) continue
|
||
try {
|
||
const dispose = agentTools.register(def)
|
||
record.disposers.set(def.name, typeof dispose === 'function' ? dispose : null)
|
||
record.registered.add(def.name)
|
||
} catch (error) {
|
||
console.warn(`sansheng: register ${def.name} failed: ${error?.message ?? error}`)
|
||
}
|
||
}
|
||
const complete = record.registered.size === defs.length
|
||
if (complete) retry.delete(sessionId)
|
||
else retry.add(sessionId)
|
||
return complete
|
||
}
|
||
|
||
const agentById = sessionId => {
|
||
try {
|
||
const direct = ctx.agents?.get?.(sessionId)
|
||
if (direct) return direct
|
||
} catch {}
|
||
try {
|
||
const list = ctx.agents?.list?.() ?? []
|
||
return list.find(agent => sessionIdOf(agent) === sessionId) ?? null
|
||
} catch { return null }
|
||
}
|
||
|
||
const attachBySessionId = sessionId => {
|
||
if (!sessionId) return false
|
||
if (!findSeat(sessionId)) { retry.delete(sessionId); return false }
|
||
const agent = agentById(sessionId)
|
||
if (!agent) { retry.add(sessionId); return false }
|
||
return attach(agent)
|
||
}
|
||
|
||
const scan = () => {
|
||
let agents = []
|
||
try { agents = ctx.agents?.list?.() ?? [] } catch {}
|
||
for (const agent of agents) attach(agent)
|
||
for (const sessionId of [...retry]) attachBySessionId(sessionId)
|
||
}
|
||
|
||
scan()
|
||
void store.ensureLoaded().then(scan).catch(() => {})
|
||
|
||
// 主入口:席位绑定成功(新建/恢复/重建)后立即安装工具,不再依赖 agent/created 先于绑定保存的顺序。
|
||
const offSeat = typeof provisioner?.onSeatChange === 'function'
|
||
? provisioner.onSeatChange(event => {
|
||
if (stopped || !event) return
|
||
// 重绑到新会话:旧会话立刻失去该席位的工具权限。
|
||
if (event.previousSessionId && event.previousSessionId !== event.sessionId) {
|
||
disposeFor(event.previousSessionId)
|
||
}
|
||
if (event.type === 'missing' || !event.sessionId) return
|
||
attachBySessionId(event.sessionId)
|
||
})
|
||
: () => {}
|
||
|
||
// 绑定已存在、会话稍后加载的顺序:agent/created 时再补装。
|
||
const offAgent = typeof ctx.on === 'function'
|
||
? ctx.on('agent/created', payload => {
|
||
const agent = payload?.agent ?? payload
|
||
attach(agent)
|
||
})
|
||
: () => {}
|
||
|
||
return () => {
|
||
stopped = true
|
||
try { offSeat?.() } catch {}
|
||
try { offAgent?.() } catch {}
|
||
for (const sessionId of [...installs.keys()]) disposeFor(sessionId)
|
||
retry.clear()
|
||
}
|
||
}
|