624 lines
27 KiB
JavaScript
624 lines
27 KiB
JavaScript
// 十席会话专用工具:把“部门”落到已绑定的真实 session,而不是同名普通子代理。
|
||
import { SEAT_IDS, SEATS, SEAT_GROUPS } 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 failure(error, extra = {}) {
|
||
return {
|
||
ok: false,
|
||
reason: error?.code ?? 'error',
|
||
error: error?.message ?? String(error),
|
||
...extra,
|
||
}
|
||
}
|
||
|
||
function actorOf(located) {
|
||
return { seatId: located.seatId, sessionId: located.sessionId }
|
||
}
|
||
|
||
function seatToolDefinitions({ store, service, turnCommands, leadBackground }) {
|
||
const definitions = []
|
||
|
||
definitions.push({
|
||
name: 'sansheng_requirement_upsert',
|
||
description: '丞相专用:把与用户商讨出的需求整理进需求清单。新增或更新同一个需求条目都不会创建任务、不会派工;用户同意下派后才会进入中书省。条目包含判断、范围、非目标、验收标准、风险/依赖/待补信息。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: {
|
||
id: { type: 'string', description: '已有需求 id(如 R-001);省略表示新建' },
|
||
expectedRevision: { type: 'number', description: '更新时必填:当前 revision,用于防止并发覆盖' },
|
||
title: { type: 'string', description: '需求标题' },
|
||
summary: { type: 'string', description: '一句话摘要' },
|
||
originalText: { type: 'string', description: '用户原始要求,尽量保留原话' },
|
||
judgement: { type: 'string', enum: ['can_do', 'needs_discussion', 'not_now'], description: '丞相判断:可立项 / 需商讨 / 暂不可做' },
|
||
judgementReason: { type: 'string', description: '判断理由' },
|
||
scope: { type: 'string', description: '范围(可发布必填)' },
|
||
nonGoals: { type: 'string', description: '非目标' },
|
||
acceptanceCriteria: { type: 'string', description: '验收标准(可发布必填)' },
|
||
risks: { type: 'string', description: '风险' },
|
||
dependencies: { type: 'string', description: '依赖' },
|
||
missingInfo: { type: 'string', description: '待补信息' },
|
||
dispatchAfterClarification: { type: 'boolean', description: '仅当当前用户明确授权澄清后继续时设为 true。撤回或变更目标时设为 false。' },
|
||
},
|
||
},
|
||
async execute(args = {}, exec) {
|
||
let located
|
||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||
if (located.seatId !== 'lead') return { ok: false, reason: 'forbidden', error: '只有丞相可以整理需求清单' }
|
||
try {
|
||
const result = await service.requirementUpsert(located.project.id, args, { ...actorOf(located), command: turnCommands?.read(exec) })
|
||
return { ok: true, ...result }
|
||
} catch (error) { return failure(error) }
|
||
},
|
||
})
|
||
|
||
definitions.push({
|
||
name: 'sansheng_requirement_list',
|
||
description: '查看当前项目真实需求清单、版本、状态、阻塞原因和对应流程任务。需求清单不是执行任务,列入清单不等于已派工。',
|
||
parameters: { type: 'object', properties: {} },
|
||
async execute(_args = {}, exec) {
|
||
let located
|
||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||
const data = await service.requirements(located.project.id)
|
||
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 }
|
||
},
|
||
})
|
||
|
||
definitions.push({
|
||
name: 'sansheng_requirement_publish',
|
||
description: '丞相专用:用户明确同意下派,或回答已授权下派的需求的澄清问题时使用。保存后在后台交中书。讨论中不得调用。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: {
|
||
requirementId: { type: 'string', description: '需求 id,如 R-001' },
|
||
expectedRevision: { type: 'number', description: '要下派的最新 revision' },
|
||
authorization: { type: 'string', enum: ['direct', 'clarified'], description: '当前用户直接同意用 direct,当前用户回答此前已授权的澄清用 clarified' },
|
||
targetSeatId: { type: 'string', enum: ['zhongshu'], description: '只能发布给中书省' },
|
||
},
|
||
required: ['targetSeatId'],
|
||
},
|
||
async execute(args = {}, exec) {
|
||
let located
|
||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||
if (located.seatId !== 'lead') return { ok: false, reason: 'forbidden', error: '只有丞相可以发布需求' }
|
||
const targetSeatId = text(args.targetSeatId)
|
||
if (targetSeatId !== 'zhongshu') {
|
||
return { ok: false, reason: 'workflow-route-forbidden', error: `丞相只能把需求发布给中书省,不能直接派给「${labelOf(targetSeatId) || targetSeatId}」。未创建任务、未写入共识、未投递任何会话。` }
|
||
}
|
||
try {
|
||
const picked = turnCommands?.read(exec)
|
||
const result = await service.requirementPublish(located.project.id, text(args.requirementId), {
|
||
expectedRevision: args.expectedRevision,
|
||
command: picked?.text ?? '',
|
||
authorization: args.authorization,
|
||
commandRef: picked ? { messageId: picked.messageId ?? null, seq: picked.seq ?? null } : null,
|
||
}, actorOf(located))
|
||
return result
|
||
} catch (error) { return failure(error) }
|
||
},
|
||
})
|
||
|
||
|
||
|
||
definitions.push({
|
||
name: 'sansheng_workflow_submit',
|
||
description: '中书省专用:把拟案提交门下省审核。拟案阶段只能只读调查,不能修改工程、不能向六部派工。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: {
|
||
taskId: { type: 'string', description: '流程任务 id' },
|
||
draft: { type: 'string', description: '完整拟案:目标、范围、非目标、验收标准、风险、执行步骤' },
|
||
},
|
||
required: ['taskId', 'draft'],
|
||
},
|
||
async execute(args = {}, exec) {
|
||
let located
|
||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||
try {
|
||
return await service.workflowSubmitDraft(located.project.id, text(args.taskId), { draft: text(args.draft) }, actorOf(located))
|
||
} catch (error) { return failure(error) }
|
||
},
|
||
})
|
||
|
||
definitions.push({
|
||
name: 'sansheng_workflow_review',
|
||
description: '门下审核中书拟案。通过直接交尚书。允许一次带明确原因的退回,仍有实质分歧时会商或交丞相。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: {
|
||
taskId: { type: 'string', description: '流程任务 id' },
|
||
action: { type: 'string', enum: ['approve', 'return'], description: '通过或退回' },
|
||
note: { type: 'string', description: '审核意见;退回必填' },
|
||
},
|
||
required: ['taskId', 'action'],
|
||
},
|
||
async execute(args = {}, exec) {
|
||
let located
|
||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||
try {
|
||
return await service.workflowReview(located.project.id, text(args.taskId), { action: text(args.action), note: text(args.note) }, actorOf(located))
|
||
} catch (error) { return failure(error) }
|
||
},
|
||
})
|
||
|
||
definitions.push({
|
||
name: 'sansheng_workflow_dispatch',
|
||
description: '尚书把门下审过的当前版本任务并行分派给六部。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: {
|
||
taskId: { type: 'string', description: '流程任务 id' },
|
||
assignments: {
|
||
type: 'array',
|
||
description: '六部任务列表',
|
||
items: {
|
||
type: 'object',
|
||
properties: {
|
||
seatId: { type: 'string', enum: ['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'] },
|
||
title: { type: 'string', description: '任务标题' },
|
||
goal: { type: 'string', description: '任务说明/验收目标' },
|
||
},
|
||
required: ['seatId', 'title'],
|
||
},
|
||
},
|
||
},
|
||
required: ['taskId', 'assignments'],
|
||
},
|
||
async execute(args = {}, exec) {
|
||
let located
|
||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||
try {
|
||
return await service.workflowDispatch(located.project.id, text(args.taskId), { assignments: args.assignments }, actorOf(located))
|
||
} catch (error) { return failure(error) }
|
||
},
|
||
})
|
||
|
||
definitions.push({
|
||
name: 'sansheng_workflow_summarize',
|
||
description: '尚书省专用:所有六部执行任务结束后,汇总真实结果并提交门下验收。必须区分完成、失败与未完成,不能把已派工当成完成。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: {
|
||
taskId: { type: 'string', description: '流程任务 id' },
|
||
summary: { type: 'string', description: '汇总内容;省略时由宿主根据六部真实结果生成' },
|
||
},
|
||
required: ['taskId'],
|
||
},
|
||
async execute(args = {}, exec) {
|
||
let located
|
||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||
try {
|
||
return await service.workflowSummarize(located.project.id, text(args.taskId), { summary: text(args.summary) }, actorOf(located))
|
||
} catch (error) { return failure(error) }
|
||
},
|
||
})
|
||
|
||
definitions.push({
|
||
name: 'sansheng_workflow_accept',
|
||
description: '门下省专用:验收尚书汇总。accept 后交丞相交付;reject 退回尚书省重新调度。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: {
|
||
taskId: { type: 'string', description: '流程任务 id' },
|
||
action: { type: 'string', enum: ['accept', 'reject'], description: '通过或退回' },
|
||
note: { type: 'string', description: '验收意见;退回必填' },
|
||
},
|
||
required: ['taskId', 'action'],
|
||
},
|
||
async execute(args = {}, exec) {
|
||
let located
|
||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||
try {
|
||
return await service.workflowAccept(located.project.id, text(args.taskId), { action: text(args.action), note: text(args.note) }, actorOf(located))
|
||
} catch (error) { return failure(error) }
|
||
},
|
||
})
|
||
|
||
definitions.push({
|
||
name: 'sansheng_workflow_deliver',
|
||
description: '丞相专用:向用户交付已通过门下验收的真实结果。不得代替六部伪造或改写执行结果。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: {
|
||
taskId: { type: 'string', description: '流程任务 id' },
|
||
delivery: { type: 'string', description: '给用户的交付说明,必须引用真实执行结果和结果会话' },
|
||
},
|
||
required: ['taskId', 'delivery'],
|
||
},
|
||
async execute(args = {}, exec) {
|
||
let located
|
||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||
try {
|
||
return await service.workflowDeliver(located.project.id, text(args.taskId), { delivery: text(args.delivery) }, actorOf(located))
|
||
} catch (error) { return failure(error) }
|
||
},
|
||
})
|
||
|
||
|
||
|
||
definitions.push({
|
||
name: 'sansheng_task_list',
|
||
description: '查看当前项目真实任务列表,包含状态、主责部门、流程阶段、是否已投递、结果和结果来源会话。',
|
||
parameters: { type: 'object', properties: {} },
|
||
async execute(_args = {}, exec) {
|
||
let located
|
||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||
const { project } = located
|
||
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) {
|
||
let located
|
||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||
try {
|
||
const task = (await service.taskGet(located.project.id, text(args.taskId))).task
|
||
return { ok: true, task: { ...task, targetLabel: labelOf(task.ownerSeatId) } }
|
||
} catch (error) { return failure(error) }
|
||
},
|
||
})
|
||
|
||
|
||
|
||
definitions.push({
|
||
name: 'sansheng_task_report',
|
||
description: '部门专用:向当前项目的任务回报 running(执行中)、done(完成,必须附真实结果)或 failed(失败)。六部执行任务必须带有效 approvalId、需求 revision 和批准范围;丞相不能代替部门报告。',
|
||
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) {
|
||
let located
|
||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||
const { project, seatId, sessionId } = located
|
||
if (seatId === 'lead') return { ok: false, reason: 'forbidden', error: '丞相不能代替部门报告,必须由实际执行部门回报' }
|
||
try {
|
||
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) }
|
||
} catch (error) { return failure(error) }
|
||
},
|
||
})
|
||
|
||
definitions.push({
|
||
name: 'sansheng_task_consult',
|
||
description: '在同一流程任务内与三省或参与执行的部门会商。仍有分歧时把选项和影响交丞相。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: { taskId: { type: 'string' }, toSeatIds: { type: 'array', items: { type: 'string', enum: SEAT_IDS } }, text: { type: 'string' } },
|
||
required: ['taskId', 'toSeatIds', 'text'],
|
||
},
|
||
async execute(args, exec) {
|
||
try {
|
||
const located = await locateSeat(service, exec)
|
||
return { ok: true, ...await service.consultTask(located.project.id, text(args.taskId), args, actorOf(located)) }
|
||
} catch (error) { return failure(error) }
|
||
},
|
||
})
|
||
|
||
definitions.push({
|
||
name: 'sansheng_task_decision',
|
||
description: '丞相专用:无法按用户已知偏好解决实质分歧时,将问题及选项放入「待你处理」。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: { taskId: { type: 'string' }, question: { type: 'string' }, options: { type: 'array', items: { type: 'string' } } },
|
||
required: ['taskId', 'question', 'options'],
|
||
},
|
||
async execute(args, exec) {
|
||
try {
|
||
const located = await locateSeat(service, exec)
|
||
return { ok: true, ...await service.requestTaskDecision(located.project.id, text(args.taskId), args, actorOf(located)) }
|
||
} catch (error) { return failure(error) }
|
||
},
|
||
})
|
||
|
||
if (leadBackground) definitions.push({
|
||
name: 'sansheng_lead_background',
|
||
description: '丞相专用。启动原生后台助手整理需求、准备协调派工、跟踪进度或汇总反馈。工具只等待宿主接收,助手结束时会回报。',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: {
|
||
kind: { type: 'string', enum: ['requirement', 'coordination', 'tracking', 'feedback'] },
|
||
brief: { type: 'string' }, requirementId: { type: 'string' }, taskId: { type: 'string' },
|
||
},
|
||
required: ['kind', 'brief'],
|
||
},
|
||
async execute(args, exec) {
|
||
try { return await leadBackground.start(exec, args) } catch (error) { return failure(error) }
|
||
},
|
||
})
|
||
|
||
for (const definition of definitions) definition.output = seatToolOutput
|
||
return definitions
|
||
}
|
||
|
||
export function createSeatToolDefinitions(options) {
|
||
return seatToolDefinitions(options)
|
||
}
|
||
|
||
|
||
// 通用工具守卫:需求门控不能只拦 sansheng_* 工具,还要拦住各席位的通用文件/命令工具与子代理旁路。
|
||
// 这是宿主 ctx.tools.guard 的系统级 deny,不依赖模型是否遵守提示词。
|
||
const MUTATING_TOOL_NAMES = new Set([
|
||
'pwsh', 'bash', 'terminal', 'shell', 'exec',
|
||
'write', 'edit', 'apply_patch', 'str_replace_editor', 'str-replace-editor',
|
||
'create_file', 'delete_file', 'move_file',
|
||
])
|
||
const BYPASS_AGENT_TOOLS = new Set([
|
||
'subagent', 'subagent_fork', 'send_message', 'interrupt_agent',
|
||
'task_board_create', 'task_board_run', 'schedule_create',
|
||
])
|
||
const PLANNING_SEATS = new Set(['lead', 'zhongshu', 'shangshu', 'menxia'])
|
||
|
||
function labelOfSeat(seatId) {
|
||
return SEATS[seatId]?.label ?? seatId
|
||
}
|
||
|
||
// 六部只有在“真实已批准、revision/范围一致、且派给了本会话”的执行子任务里才允许写。
|
||
function approvedExecutionForSeat(project, seatId, sessionId) {
|
||
const tasks = Array.isArray(project?.tasks) ? project.tasks : []
|
||
const requirements = Array.isArray(project?.requirements) ? project.requirements : []
|
||
const approvals = Array.isArray(project?.approvals) ? project.approvals : []
|
||
for (const task of tasks) {
|
||
if (task?.kind !== 'execution') continue
|
||
if (task.ownerSeatId !== seatId) continue
|
||
if (task.sessionId && task.sessionId !== sessionId) continue
|
||
if (!['draft', 'prepared', 'dispatched', 'running'].includes(task.status)) continue
|
||
if (!task.approvalId || !task.requirementId) continue
|
||
const approval = approvals.find(item => item.id === task.approvalId)
|
||
const requirement = requirements.find(item => item.id === task.requirementId)
|
||
if (!approval || approval.status !== 'approved') continue
|
||
if (!requirement || requirement.revision !== approval.requirementRevision) continue
|
||
if (task.requirementRevision !== requirement.revision) continue
|
||
if ((task.approvalScope ?? '') !== (approval.scope ?? '')) continue
|
||
return task
|
||
}
|
||
return null
|
||
}
|
||
|
||
function seatProject(store, sessionId) {
|
||
for (const project of Object.values(store.state?.projects ?? {})) {
|
||
for (const seatId of SEAT_IDS) {
|
||
if (project?.seats?.[seatId]?.sessionId === sessionId) return { project, seatId }
|
||
}
|
||
}
|
||
return null
|
||
}
|
||
|
||
function buildSeatToolGuard(store, sessionId) {
|
||
return execution => {
|
||
const name = typeof execution?.name === 'string' ? execution.name : ''
|
||
if (!MUTATING_TOOL_NAMES.has(name) && !BYPASS_AGENT_TOOLS.has(name)) return undefined
|
||
const found = seatProject(store, sessionId)
|
||
if (!found) return '需求门控模式:当前会话不是三省六部席位,不能使用此工具。'
|
||
const { project, seatId } = found
|
||
if (BYPASS_AGENT_TOOLS.has(name)) {
|
||
return `需求门控模式:${labelOfSeat(seatId)}不能使用 ${name} 绕过席位派工或审批流程。`
|
||
}
|
||
if (PLANNING_SEATS.has(seatId)) {
|
||
return `需求门控模式:${labelOfSeat(seatId)}在拟案、审核、调度阶段只能只读调查,不能使用 ${name} 修改文件或执行工程操作。`
|
||
}
|
||
if (SEAT_GROUPS.liubu.includes(seatId)) {
|
||
if (approvedExecutionForSeat(project, seatId, sessionId)) return undefined
|
||
return `需求门控模式:${labelOfSeat(seatId)}当前没有有效的已批准执行任务,不能使用 ${name} 修改文件或执行工程操作。`
|
||
}
|
||
return '需求门控模式:当前席位没有执行批准,不能修改文件或执行工程操作。'
|
||
}
|
||
}
|
||
|
||
export function installSeatTools(ctx, { store, service, provisioner, turnCommands, leadBackground }) {
|
||
const defs = createSeatToolDefinitions({ store, service, turnCommands, leadBackground })
|
||
// 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()
|
||
try { record.guardDispose?.() } catch {}
|
||
record.guardDispose = null
|
||
record.guardMounted = false
|
||
}
|
||
|
||
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
|
||
const located = findSeat(sessionId)
|
||
if (!located) return false
|
||
const seatDefs = located.seatId === 'lead' ? defs : defs.filter(def => def.name !== 'sansheng_lead_background')
|
||
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
|
||
}
|
||
const mountGuard = () => {
|
||
if (!record || record.guardMounted || typeof agentTools.guard !== 'function') return
|
||
record.guardMounted = true
|
||
try {
|
||
const dispose = agentTools.guard(buildSeatToolGuard(store, sessionId))
|
||
record.guardDispose = typeof dispose === 'function' ? dispose : null
|
||
} catch (error) {
|
||
record.guardMounted = false
|
||
console.warn(`sansheng: register tool guard failed: ${error?.message ?? error}`)
|
||
}
|
||
}
|
||
mountGuard()
|
||
if (record && record.registered.size === seatDefs.length) return true
|
||
if (!record) {
|
||
record = { agent, disposers: new Map(), registered: new Set(), guardDispose: null, guardMounted: false }
|
||
installs.set(sessionId, record)
|
||
}
|
||
mountGuard()
|
||
for (const def of seatDefs) {
|
||
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 === seatDefs.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()
|
||
}
|
||
}
|