diff --git a/README.md b/README.md index 0e9ec55..d1745d4 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ -# 三省六部(dsh-sansheng)· 第一版 +# 三省六部(dsh-sansheng)· v0.5.0 在 DSH 里为每个项目提供固定的十席角色(丞相、中书、门下、尚书、吏部、户部、礼部、兵部、刑部、工部), -每席绑定一个独立的原生命 root Session,模型与补充说明按项目独立保存。中间复用宿主原生会话,不替换聊天引擎。 +每席绑定一个独立的原生 root Session,模型与补充说明按项目独立保存。中间复用宿主原生会话,不替换聊天引擎。 -当前进度(对应 `docs/v1-plan.md` §7 实施顺序): +当前版本能力: -- ✅ 第 2 步:项目内身份与十席会话绑定(宿主服务 + 严格创建/恢复/失败重试/跨项目隔离,`npm test` 用 fake ctx 验证)。 -- ✅ 第 3 步:Web 入口与右侧工作台(已在隔离测试 DSH 真机验证:入口、十席工作台、真实建十个会话、重启幂等)。 -- 🟡 第 4 步:dsh-go 原生面板(源代码就位,触摸/返回/会话跳转需真机核验)。 -- ⬜ 第 5 步:双项目联调后打包发布。 +- 固定十席会话、项目隔离、重启幂等,模型与补充说明按项目/席位独立保存。 +- 项目共识:目标、硬约束、验收标准、决定与来源按版本保存,并注入部门提示词和派工上下文。 +- 部门工具:丞相用 `sansheng_dispatch_task` 派工到目标部门已绑定的真实会话;部门用 `sansheng_task_report` 回报执行中/完成/失败,结果关联真实部门会话;丞相可查询真实任务与结果,不能用同名子代理或普通 agent 冒充部门。 +- 任务记录区分待执行/已派工/执行中/已完成/已取消/失败,支持重复投递去重、取消后迟到结果留档(不改回取消状态)。 **本包尚未安装到任何 DSH profile,也未改动用户的日常 DSH 配置。** diff --git a/client.js b/client.js index a97cc62..4d5e215 100644 --- a/client.js +++ b/client.js @@ -466,10 +466,12 @@ body[data-ds-dark-theme] .ssw-float,html[data-theme=dark] .ssw-float{background: .ssw-row-title{font-size:13px} .ssw-row-meta{margin:4px 0 0;font-size:11px;color:var(--ssw-muted)} .ssw-row-note{margin:4px 0 0;font-size:10px;color:var(--ssw-faint)} +.ssw-row-result{margin:4px 0 0;font-size:11px;color:var(--ssw-ok);word-break:break-word} .ssw-row-actions{display:flex;gap:10px;margin-top:6px} .ssw-link{color:var(--ssw-blue);font-size:12px;padding:2px 2px} .ssw-link-muted{color:var(--ssw-muted)} .ssw-badge{font-size:10px;padding:2px 6px;border-radius:999px;background:var(--ssw-wash);color:var(--ssw-blue)} +.ssw-badge[data-status=running]{background:rgba(37,99,235,.12);color:var(--ssw-blue)} .ssw-badge[data-status=done]{background:rgba(22,163,74,.12);color:var(--ssw-ok)} .ssw-badge[data-status=cancelled]{background:rgba(107,114,128,.14);color:var(--ssw-muted)} .ssw-badge[data-status=failed]{background:rgba(220,38,38,.12);color:var(--ssw-danger)} @@ -1739,9 +1741,9 @@ function apply(ctx) { onClick: () => setTab(id) }, (0, import_react.createElement)("span", null, label), (0, import_react.createElement)("span", { className: "ssw-tab-count" }, String(tabCounts[id] ?? 0)))) ); - const TASK_STATUS_LABEL = { draft: "草稿", prepared: "待执行", dispatched: "已派工", done: "已完成", cancelled: "已取消", failed: "失败" }; + const TASK_STATUS_LABEL = { draft: "草稿", prepared: "待执行", dispatched: "已派工", running: "执行中", done: "已完成", cancelled: "已取消", failed: "失败" }; const taskRows = tasks.length === 0 ? (0, import_react.createElement)("p", { className: "ssw-empty-line" }, "这个项目还没有任务。点「新建任务」先存一张草稿。") : tasks.map((task) => { - const stale = (memory?.revision ?? 0) > (task.contextRevision ?? 0) && (task.status === "dispatched" || task.status === "prepared"); + const stale = (memory?.revision ?? 0) > (task.contextRevision ?? 0) && (task.status === "dispatched" || task.status === "prepared" || task.status === "running"); return (0, import_react.createElement)( "article", { key: task.id, className: "ssw-row", "data-task": task.id }, @@ -1754,6 +1756,7 @@ function apply(ctx) { ), (0, import_react.createElement)("p", { className: "ssw-row-meta" }, (SEATS[task.ownerSeatId]?.label ?? task.ownerSeatId) + (task.goal ? " · " + task.goal : "") + (task.contextRevision !== void 0 ? " · 共识 v" + task.contextRevision : "")), task.note ? (0, import_react.createElement)("p", { className: "ssw-row-note" }, task.note) : null, + task.result ? (0, import_react.createElement)("p", { className: "ssw-row-result" }, "结果:" + task.result) : null, (0, import_react.createElement)( "div", { className: "ssw-row-actions" }, diff --git a/index.js b/index.js index e1aa966..943dcd1 100644 --- a/index.js +++ b/index.js @@ -4,6 +4,7 @@ import { createProvisioner } from './src/host/provision.js' import { SanshengService } from './src/host/service.js' import { createApiHandler } from './src/host/api.js' import { installPromptSection } from './src/host/prompt.js' +import { installSeatTools } from './src/host/tools.js' import { sanshengStatePath } from './src/host/paths.js' import { ROUTE } from './src/host/constants.js' @@ -30,6 +31,7 @@ export function apply(ctx, config = {}) { const handle = createApiHandler(service) ctx.effect(() => installPromptSection(ctx, { store }), 'sansheng: prompt section') + ctx.effect(() => installSeatTools(ctx, { store, service }), 'sansheng: seat tools') // 复用宿主共享 /api 通道;浏览器带会话 Cookie 认证。 ctx.effect(() => ctx.connection.fetch.register({ diff --git a/package.json b/package.json index 24aa6b0..9325aab 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-sansheng-liubu", - "version": "0.4.1", + "version": "0.5.0", "description": "三省六部:每个项目固定十席角色与独立会话的 DSH 插件(第一版)。", "keywords": [ "dsh-plugin", diff --git a/src/client/index.js b/src/client/index.js index fc9daff..9c3fc25 100644 --- a/src/client/index.js +++ b/src/client/index.js @@ -790,11 +790,11 @@ export function apply(ctx) { className: 'ssw-tab' + (tab === id ? ' is-active' : ''), onClick: () => setTab(id), }, h('span', null, label), h('span', { className: 'ssw-tab-count' }, String(tabCounts[id] ?? 0))))) - const TASK_STATUS_LABEL = { draft: '草稿', prepared: '待执行', dispatched: '已派工', done: '已完成', cancelled: '已取消', failed: '失败' } + const TASK_STATUS_LABEL = { draft: '草稿', prepared: '待执行', dispatched: '已派工', running: '执行中', done: '已完成', cancelled: '已取消', failed: '失败' } const taskRows = tasks.length === 0 ? h('p', { className: 'ssw-empty-line' }, '这个项目还没有任务。点「新建任务」先存一张草稿。') : tasks.map(task => { - const stale = (memory?.revision ?? 0) > (task.contextRevision ?? 0) && (task.status === 'dispatched' || task.status === 'prepared') + const stale = (memory?.revision ?? 0) > (task.contextRevision ?? 0) && (task.status === 'dispatched' || task.status === 'prepared' || task.status === 'running') return h('article', { key: task.id, className: 'ssw-row', 'data-task': task.id }, h('div', { className: 'ssw-row-top' }, h('strong', { className: 'ssw-row-title' }, task.title), @@ -802,6 +802,7 @@ export function apply(ctx) { stale ? h('span', { className: 'ssw-badge', 'data-status': 'stale' }, '要求有更新') : null), h('p', { className: 'ssw-row-meta' }, (SEATS[task.ownerSeatId]?.label ?? task.ownerSeatId) + (task.goal ? ' · ' + task.goal : '') + (task.contextRevision !== undefined ? ' · 共识 v' + task.contextRevision : '')), task.note ? h('p', { className: 'ssw-row-note' }, task.note) : null, + task.result ? h('p', { className: 'ssw-row-result' }, '结果:' + task.result) : null, h('div', { className: 'ssw-row-actions' }, (task.status === 'draft' || task.status === 'prepared' || task.status === 'failed') ? h('button', { type: 'button', className: 'ssw-link', disabled: busy, onClick: () => dispatchTask(task.id) }, task.status === 'prepared' ? '重试派工' : '派工') diff --git a/src/client/styles.js b/src/client/styles.js index cd0f246..87c277a 100644 --- a/src/client/styles.js +++ b/src/client/styles.js @@ -98,10 +98,12 @@ body[data-ds-dark-theme] .ssw-float,html[data-theme=dark] .ssw-float{background: .ssw-row-title{font-size:13px} .ssw-row-meta{margin:4px 0 0;font-size:11px;color:var(--ssw-muted)} .ssw-row-note{margin:4px 0 0;font-size:10px;color:var(--ssw-faint)} +.ssw-row-result{margin:4px 0 0;font-size:11px;color:var(--ssw-ok);word-break:break-word} .ssw-row-actions{display:flex;gap:10px;margin-top:6px} .ssw-link{color:var(--ssw-blue);font-size:12px;padding:2px 2px} .ssw-link-muted{color:var(--ssw-muted)} .ssw-badge{font-size:10px;padding:2px 6px;border-radius:999px;background:var(--ssw-wash);color:var(--ssw-blue)} +.ssw-badge[data-status=running]{background:rgba(37,99,235,.12);color:var(--ssw-blue)} .ssw-badge[data-status=done]{background:rgba(22,163,74,.12);color:var(--ssw-ok)} .ssw-badge[data-status=cancelled]{background:rgba(107,114,128,.14);color:var(--ssw-muted)} .ssw-badge[data-status=failed]{background:rgba(220,38,38,.12);color:var(--ssw-danger)} diff --git a/src/host/prompt.js b/src/host/prompt.js index f3b2057..2177c17 100644 --- a/src/host/prompt.js +++ b/src/host/prompt.js @@ -12,6 +12,17 @@ export function renderSeatPrompt({ project, seatId, seat }) { if (typeof note === 'string' && note.trim() !== '') lines.push(`补充说明:${note.trim()}`) const consensus = renderProjectMemory(project?.memory, { maxDecisionChars: 2400 }) if (consensus) lines.push('', consensus) + if (seatId === 'lead') { + lines.push( + '', + '派工硬性规则:你必须使用 sansheng_dispatch_task 工具把任务派给目标部门已绑定的真实会话,并把用户原话和最新项目共识一起带上;禁止用同名子代理、普通 agent、自己代写、页面“派工成功”或口头通知来冒充部门执行。工具返回 ok:false / delivered:false 时必须明确告诉用户投递失败,不能降级、不能声称已完成。', + ) + } else { + lines.push( + '', + '回报硬性规则:你必须使用 sansheng_task_report 工具回报真实状态(running 执行中、done 完成、failed 失败);done 必须附真实结果(文件路径、输出或验证结果),不得虚报。丞相不能代替部门报告。', + ) + } lines.push('只在本项目本席会话内工作;不要修改其他项目或其他席的配置,也不要替用户提升权限。') return lines.join('\n') } @@ -23,7 +34,7 @@ export function installPromptSection(ctx, { store }) { order: 60, interpolate: false, text: context => { - const sessionId = context?.agent?.id + const sessionId = context?.agent?.session?.id ?? context?.agent?.id if (!sessionId) return '' const found = seatBySessionId(store.state?.projects, sessionId) if (!found) return '' diff --git a/src/host/service.js b/src/host/service.js index 37d2d3c..cef7efb 100644 --- a/src/host/service.js +++ b/src/host/service.js @@ -208,10 +208,11 @@ export class SanshengService { if (!title) throw new ServiceError('sansheng/invalid', '任务标题不能为空') if (!SEAT_IDS.includes(input.ownerSeatId)) throw new ServiceError('sansheng/invalid', `未知主责席 ${String(input.ownerSeatId)}`) const goal = typeof input.goal === 'string' ? input.goal : '' + const requirement = typeof input.requirement === 'string' ? input.requirement : '' const task = await this.store.mutate(s => { const project = s.projects[projectId] project.taskSeq = (project.taskSeq ?? 0) + 1 - const next = emptyTask({ id: `task-${project.taskSeq}`, title, goal, ownerSeatId: input.ownerSeatId }) + const next = emptyTask({ id: `task-${project.taskSeq}`, title, goal, requirement, ownerSeatId: input.ownerSeatId }) if (!Array.isArray(project.tasks)) project.tasks = [] project.tasks.push(next) project.updatedAt = Date.now() @@ -221,13 +222,17 @@ export class SanshengService { return { task } } - async taskDispatch(projectId, taskId) { + async taskDispatch(projectId, taskId, options = {}) { await this.store.ensureLoaded() const project = this.store.get(projectId) if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`) const task = (project.tasks ?? []).find(item => item.id === taskId) if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`) - if (task.status === 'done' || task.status === 'cancelled') throw new ServiceError('sansheng/invalid', '已完成或已取消的任务不能再次派工') + if (task.status === 'done' || task.status === 'cancelled') throw new ServiceError('sansheng/invalid', '已完成或已取消的任务不能再次派工;请新建任务保留历史结果') + // 同一任务已成功投递时不重复刷屏;修改要求后由 taskRevise 显式 force 重发。 + if (task.deliveryState === 'accepted' && task.status === 'dispatched' && !options.force) { + return { task: { ...task }, delivered: true, duplicate: true } + } let seat = project.seats[task.ownerSeatId] if (!seat || seat.status !== 'bound' || !seat.sessionId) { // 按需开启:丞相派工时只给出主责部门,由系统用该部门预配置的模型开启会话;丞相不选模型。 @@ -239,7 +244,12 @@ export class SanshengService { } const memory = normalizeProjectMemory(project.memory, projectId) const memoryText = renderProjectMemory(memory) - const text = [memoryText, `【任务】${task.title}${task.goal ? '\n' + task.goal : ''}`].filter(Boolean).join('\n\n') + const detail = [ + `【任务】${task.title}`, + task.goal ? `任务说明:${task.goal}` : '', + task.requirement ? `用户原话:${task.requirement}` : '', + ].filter(Boolean).join('\n') + const text = [memoryText, detail].filter(Boolean).join('\n\n') const deliveryId = randomUUID() let delivered = false let note = '' @@ -278,7 +288,76 @@ export class SanshengService { s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1 return { ...target } }) - return { task: next, delivered } + return { task: next, delivered, duplicate: false } + } + + async taskGet(projectId, taskId) { + await this.store.ensureLoaded() + const project = this.store.get(projectId) + if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`) + const task = (project.tasks ?? []).find(item => item.id === taskId) + if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`) + return { task: { ...task } } + } + + async taskReport(projectId, taskId, input = {}) { + await this.store.ensureLoaded() + if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`) + const status = input.status + if (!['running', 'done', 'failed'].includes(status)) throw new ServiceError('sansheng/invalid', '报告状态必须是 running、done 或 failed') + const result = typeof input.result === 'string' ? input.result.trim() : '' + if (status === 'done' && !result) throw new ServiceError('sansheng/invalid', '完成报告必须包含真实结果,不能只写“已完成”') + const next = await this.store.mutate(s => { + const task = s.projects[projectId].tasks.find(item => item.id === taskId) + if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`) + if (input.seatId && task.ownerSeatId !== input.seatId) { + throw new ServiceError('sansheng/forbidden', `只有主责部门 ${task.ownerSeatId} 可以报告这个任务`) + } + if (task.status === 'done' && status !== 'done') throw new ServiceError('sansheng/invalid', '已完成的任务不能回退状态') + // 已取消任务的结果迟到:保留取消状态,但把真实结果留档,不假装没发生。 + const late = task.status === 'cancelled' + if (!late) task.status = status + if (result) task.result = result + if (late || status === 'done' || status === 'failed') { + task.resultAt = Date.now() + task.resultSessionId = input.sessionId ?? null + task.reportStatus = late ? 'late' : status + } else { + task.reportStatus = 'running' + } + if (typeof input.note === 'string' && input.note.trim()) task.note = input.note.trim() + task.updatedAt = Date.now() + s.projects[projectId].updatedAt = Date.now() + s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1 + return { ...task, late } + }) + return { task: next, late: Boolean(next.late) } + } + + async taskRevise(projectId, taskId, input = {}) { + await this.store.ensureLoaded() + if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`) + const goal = typeof input.goal === 'string' ? input.goal.trim() : undefined + const requirement = typeof input.requirement === 'string' ? input.requirement.trim() : undefined + if (goal === undefined && requirement === undefined) throw new ServiceError('sansheng/invalid', '修改要求需要提供 goal 或 requirement') + const next = await this.store.mutate(s => { + const task = s.projects[projectId].tasks.find(item => item.id === taskId) + if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`) + if (task.status === 'done' || task.status === 'cancelled') throw new ServiceError('sansheng/invalid', '已完成或已取消的任务不能修改要求;请新建任务保留历史结果') + if (goal !== undefined) task.goal = goal + if (requirement !== undefined) task.requirement = requirement + task.status = 'draft' + task.result = null + task.resultAt = null + task.resultSessionId = null + task.reportStatus = 'none' + task.deliveryState = 'none' + task.updatedAt = Date.now() + s.projects[projectId].updatedAt = Date.now() + s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1 + return { ...task } + }) + return { task: next } } async taskCancel(projectId, taskId) { diff --git a/src/host/tools.js b/src/host/tools.js new file mode 100644 index 0000000..bf670ea --- /dev/null +++ b/src/host/tools.js @@ -0,0 +1,282 @@ +// 十席会话专用工具:把“部门”落到已绑定的真实 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) { + const { project, seatId } = await locateSeat(service, exec) + 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, + }) + const dispatched = await service.taskDispatch(project.id, created.task.id, { force: true }) + const result = okTask(dispatched.task) + if (!dispatched.delivered) { + return { ...result, ok: false, delivered: false, taskId: created.task.id, 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 }) { + const installed = new Map() + const defs = createSeatToolDefinitions({ store, service }) + let stopped = false + + const disposeFor = sessionId => { + const list = installed.get(sessionId) + if (!list) return + installed.delete(sessionId) + for (const dispose of list) { + try { dispose?.() } catch {} + } + } + + 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 + } + + const attach = agent => { + if (stopped || !agent) return + const sessionId = agent.session?.id ?? agent.id + if (!sessionId) return + if (installed.has(sessionId)) return + if (!findSeat(sessionId)) return + const agentTools = agent.ctx?.tools + if (!agentTools || typeof agentTools.register !== 'function') return + const disposers = [] + for (const def of defs) { + try { + const dispose = agentTools.register(def) + if (typeof dispose === 'function') disposers.push(dispose) + } catch (error) { + console.warn(`sansheng: register ${def.name} failed: ${error?.message ?? error}`) + } + } + installed.set(sessionId, disposers) + } + + const scan = () => { + let agents = [] + try { agents = ctx.agents?.list?.() ?? [] } catch {} + for (const agent of agents) void attach(agent) + } + + scan() + void store.ensureLoaded().then(scan).catch(() => {}) + const off = typeof ctx.on === 'function' ? ctx.on('agent/created', payload => { + const agent = payload?.agent ?? payload + attach(agent) + }) : () => {} + + return () => { + stopped = true + try { off?.() } catch {} + for (const sessionId of [...installed.keys()]) disposeFor(sessionId) + } +} diff --git a/src/shared/schema.js b/src/shared/schema.js index eaa8c67..2074927 100644 --- a/src/shared/schema.js +++ b/src/shared/schema.js @@ -8,7 +8,7 @@ export const STATE_VERSION = 1 export const SEAT_STATUS = Object.freeze(['pending', 'creating', 'bound', 'failed', 'missing']) export const PROJECT_STATUS = Object.freeze(['pending', 'provisioning', 'ready', 'error']) // 任务:草稿 → 已派工/待执行 → 完成 / 取消 / 失败 -export const TASK_STATUS = Object.freeze(['draft', 'dispatched', 'prepared', 'done', 'cancelled', 'failed']) +export const TASK_STATUS = Object.freeze(['draft', 'dispatched', 'running', 'prepared', 'done', 'cancelled', 'failed']) const SEAT_STATUS_SET = new Set(SEAT_STATUS) const PROJECT_STATUS_SET = new Set(PROJECT_STATUS) @@ -57,12 +57,13 @@ export function emptyProject({ id, name, workspaceId = null, path = null, now = } } -export function emptyTask({ id, title = '', goal = '', ownerSeatId = 'lead', now = Date.now() }) { +export function emptyTask({ id, title = '', goal = '', requirement = '', ownerSeatId = 'lead', now = Date.now() }) { return { - id, title, goal, ownerSeatId, status: 'draft', note: '', sessionId: null, + id, title, goal, requirement, ownerSeatId, status: 'draft', note: '', sessionId: null, createdAt: now, updatedAt: now, dispatchedAt: null, contextRevision: 0, contextHash: '', decisionIds: [], sourceRefs: [], deliveryId: null, deliveryState: 'none', contextSyncState: 'none', + result: null, resultAt: null, resultSessionId: null, reportStatus: 'none', } } diff --git a/test/prompt.test.js b/test/prompt.test.js index 611d933..4351c23 100644 --- a/test/prompt.test.js +++ b/test/prompt.test.js @@ -19,6 +19,9 @@ test('只对十席会话注入角色提示', async () => { assert.match(text, /工部/) assert.match(text, /代码实现与工程产出/) + const bySession = section.text({ agent: { id: 'runtime-agent-id', session: { id: seat.sessionId } } }) + assert.match(bySession, /工部/) + assert.equal(section.text({ agent: { id: 'other-session' } }), '') assert.equal(section.text({}), '') }) diff --git a/test/tools.test.js b/test/tools.test.js new file mode 100644 index 0000000..e988653 --- /dev/null +++ b/test/tools.test.js @@ -0,0 +1,277 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { setupService, seatById } from './helpers.js' +import { createSeatToolDefinitions, installSeatTools } from '../src/host/tools.js' + +async function setupToolProject(opts = {}) { + const env = await setupService({ prompt: true, ...opts }) + const opened = await env.service.open({ path: opts.path ?? '/tools', name: opts.name ?? '工具项目' }) + const projectId = opened.project.id + await env.service.memoryUpdate(projectId, { + goal: '完成可验收交付', + constraints: ['不能改动生产数据'], + acceptance: ['测试通过'], + }) + const leadView = await env.service.enableSeat(projectId, 'lead') + const gongView = await env.service.enableSeat(projectId, 'gongbu') + const leadSessionId = seatById(leadView, 'lead').sessionId + const gongSessionId = seatById(gongView, 'gongbu').sessionId + const defs = createSeatToolDefinitions({ store: env.store, service: env.service }) + const byName = Object.fromEntries(defs.map(def => [def.name, def])) + return { + ...env, + projectId, + leadSessionId, + gongSessionId, + leadExec: { agent: env.fake.sessions.get(leadSessionId) }, + gongExec: { agent: env.fake.sessions.get(gongSessionId) }, + tool: name => { + const def = byName[name] + if (!def) throw new Error('missing tool ' + name) + return def + }, + } +} + +test('部门工具:丞相派工落到真实工部会话,原话与共识一起送达', async () => { + const env = await setupToolProject({ path: '/tools-dispatch', name: '派工工具项目' }) + const beforePrompts = env.fake.calls.prompt.length + const result = await env.tool('sansheng_dispatch_task').execute({ + targetSeatId: 'gongbu', + title: '生成 Hello World', + goal: '创建一个可验证的 Hello World 文件', + requirement: '以后称呼我为陛下;工部生成 Hello World,并回真实文件路径', + sourceText: '用户原话:以后称呼我为陛下;工部生成 Hello World,并回真实文件路径', + }, env.leadExec) + + assert.equal(result.ok, true) + assert.equal(result.delivered, true) + assert.equal(result.status, 'dispatched') + assert.equal(result.sessionId, env.gongSessionId) + assert.equal(result.targetLabel, '工部') + + const memory = (await env.service.memory(env.projectId)).memory + assert.equal(memory.revision, 2) + assert.match(memory.decisions.at(-1).text, /陛下/) + assert.equal(memory.decisions.at(-1).type, 'user') + assert.ok(memory.sources.some(source => /陛下/.test(source.excerpt))) + + const task = (await env.service.taskGet(env.projectId, result.taskId)).task + assert.equal(task.ownerSeatId, 'gongbu') + assert.match(task.requirement, /陛下/) + assert.equal(task.contextRevision, 2) + + assert.equal(env.fake.calls.prompt.length, beforePrompts + 1) + const delivery = env.fake.calls.prompt.at(-1) + assert.equal(delivery.sessionId, env.gongSessionId) + const text = delivery.content[0].text + assert.match(text, /项目共识 v2/) + assert.match(text, /不能改动生产数据/) + assert.match(text, /用户原话:以后称呼我为陛下/) + assert.match(text, /生成 Hello World/) +}) + +test('部门工具:真实回报 running/done 可见,丞相不能代替部门报告', async () => { + const env = await setupToolProject({ path: '/tools-report', name: '回报工具项目' }) + const dispatched = await env.tool('sansheng_dispatch_task').execute({ + targetSeatId: 'gongbu', + title: '写 Hello World', + goal: '输出文件并验证', + requirement: '写一个 Hello World 文件', + }, env.leadExec) + + await assert.rejects( + () => env.tool('sansheng_task_report').execute({ taskId: dispatched.taskId, status: 'done', result: '丞相代写' }, env.leadExec), + /丞相不能代替部门/, + ) + + const running = await env.tool('sansheng_task_report').execute({ taskId: dispatched.taskId, status: 'running', note: '开始执行' }, env.gongExec) + assert.equal(running.ok, true) + assert.equal(running.task.status, 'running') + assert.equal(running.task.reportStatus, 'running') + + const done = await env.tool('sansheng_task_report').execute({ + taskId: dispatched.taskId, + status: 'done', + result: '已生成 D:/out/hello.txt,内容为 Hello World', + }, env.gongExec) + assert.equal(done.task.status, 'done') + assert.match(done.task.result, /D:\/out\/hello\.txt/) + assert.equal(done.task.resultSessionId, env.gongSessionId) + + const leadRead = await env.tool('sansheng_task_result').execute({ taskId: dispatched.taskId }, env.leadExec) + assert.equal(leadRead.task.status, 'done') + assert.match(leadRead.task.result, /Hello World/) + assert.equal(leadRead.task.resultSessionId, env.gongSessionId) +}) + +test('部门工具:修改要求会写入最新共识并重新投递到原部门会话', async () => { + const env = await setupToolProject({ path: '/tools-revise', name: '改要求项目' }) + const dispatched = await env.tool('sansheng_dispatch_task').execute({ + targetSeatId: 'gongbu', + title: '生成报告', + goal: '第一版', + requirement: '叫工部生成第一版报告', + }, env.leadExec) + + await env.service.memoryUpdate(env.projectId, { constraints: ['不能改动生产数据', '必须使用新模板'] }) + const revised = await env.tool('sansheng_task_revise').execute({ + taskId: dispatched.taskId, + goal: '第二版,按新模板', + requirement: '不要叫工部了,称呼我为殿下;按新模板重做报告', + sourceText: '用户改口:称呼我为殿下;按新模板重做报告', + }, env.leadExec) + + assert.equal(revised.ok, true) + assert.equal(revised.delivered, true) + assert.equal(revised.sessionId, env.gongSessionId) + assert.equal(revised.contextRevision, 4) + assert.match(revised.requirement, /殿下/) + const memory = (await env.service.memory(env.projectId)).memory + assert.equal(memory.revision, 4) + assert.match(memory.decisions.at(-1).text, /殿下/) + + const delivery = env.fake.calls.prompt.at(-1) + assert.equal(delivery.sessionId, env.gongSessionId) + assert.match(delivery.content[0].text, /项目共识 v4/) + assert.match(delivery.content[0].text, /必须使用新模板/) + assert.match(delivery.content[0].text, /称呼我为殿下/) +}) + +test('部门工具:严格项目隔离,普通会话不能使用', async () => { + const a = await setupToolProject({ path: '/tools-a', name: 'A 项目' }) + const b = await setupToolProject({ path: '/tools-b', name: 'B 项目' }) + const dispatched = await a.tool('sansheng_dispatch_task').execute({ + targetSeatId: 'gongbu', + title: 'A 项目机密任务', + requirement: 'A 项目的要求,不能出现在 B 项目', + }, a.leadExec) + + const bList = await b.tool('sansheng_task_list').execute({}, b.leadExec) + assert.equal(bList.tasks.length, 0) + const bMemory = (await b.service.memory(b.projectId)).memory + assert.equal(bMemory.decisions.length, 0) + assert.ok(!bMemory.constraints.some(item => /A 项目/.test(item))) + + await assert.rejects( + () => b.tool('sansheng_task_result').execute({ taskId: dispatched.taskId }, b.leadExec), + /不存在/, + ) + const aList = await a.tool('sansheng_task_list').execute({}, a.leadExec) + assert.equal(aList.tasks.length, 1) + + const ordinary = { agent: { id: 'ordinary-session' } } + await assert.rejects( + () => a.tool('sansheng_task_list').execute({}, ordinary), + /十席会话/, + ) +}) + +test('部门工具:取消后的迟到结果保留为 late,不篡改取消状态', async () => { + const env = await setupToolProject({ path: '/tools-late', name: '迟到项目' }) + const dispatched = await env.tool('sansheng_dispatch_task').execute({ + targetSeatId: 'gongbu', + title: '可能迟到的任务', + requirement: '做一件事', + }, env.leadExec) + await env.service.taskCancel(env.projectId, dispatched.taskId) + const lateRunning = await env.tool('sansheng_task_report').execute({ + taskId: dispatched.taskId, + status: 'running', + note: '取消后还在跑', + }, env.gongExec) + assert.equal(lateRunning.task.status, 'cancelled') + assert.equal(lateRunning.task.reportStatus, 'late') + const late = await env.tool('sansheng_task_report').execute({ + taskId: dispatched.taskId, + status: 'done', + result: '取消后仍完成了,结果保留', + }, env.gongExec) + assert.equal(late.late, true) + assert.equal(late.task.status, 'cancelled') + assert.equal(late.task.reportStatus, 'late') + assert.match(late.task.result, /取消后仍完成/) + const leadRead = await env.tool('sansheng_task_result').execute({ taskId: dispatched.taskId }, env.leadExec) + assert.equal(leadRead.task.reportStatus, 'late') +}) + +test('部门工具:只注册到已绑定席位,新席创建后按需补装', async () => { + const env = await setupToolProject({ path: '/tools-register', name: '注册项目' }) + const registered = [] + const listeners = {} + const attach = agent => { + if (!agent) return + agent.ctx = { tools: { register(def) { registered.push({ sessionId: agent.id, name: def.name }); return () => {} } } } + } + attach(env.fake.sessions.get(env.leadSessionId)) + attach(env.fake.sessions.get(env.gongSessionId)) + const ordinary = env.fake.addSession('ordinary-register') + attach(ordinary) + const ctx = { + agents: { list: () => [...env.fake.sessions.values()] }, + on(event, fn) { listeners[event] = fn; return () => {} }, + } + installSeatTools(ctx, { store: env.store, service: env.service }) + assert.equal(registered.filter(item => item.sessionId === env.leadSessionId).length, 5) + assert.equal(registered.filter(item => item.sessionId === env.gongSessionId).length, 5) + assert.equal(registered.filter(item => item.sessionId === 'ordinary-register').length, 0) + + const libuView = await env.service.enableSeat(env.projectId, 'libu') + const libuSessionId = seatById(libuView, 'libu').sessionId + const libuAgent = env.fake.sessions.get(libuSessionId) + attach(libuAgent) + listeners['agent/created']({ agent: libuAgent }) + assert.equal(registered.filter(item => item.sessionId === libuSessionId).length, 5) +}) + +test('部门工具:按 agent.session.id 匹配席位,不按 agent.id 误判', async () => { + const env = await setupToolProject({ path: '/tools-session-id', name: '会话标识项目' }) + const registered = [] + const runtimeAgent = { + id: 'agent-runtime-lead', + session: { id: env.leadSessionId }, + ctx: { + tools: { + register(def) { + registered.push(def.name) + return () => {} + }, + }, + }, + } + const ctx = { agents: { list: () => [runtimeAgent] }, on() { return () => {} } } + installSeatTools(ctx, { store: env.store, service: env.service }) + assert.equal(registered.length, 5) +}) + +test('部门工具:执行时优先用 agent.session.id 定位席位', async () => { + const env = await setupToolProject({ path: '/tools-exec-session', name: '执行标识项目' }) + const exec = { agent: { id: 'runtime-agent-lead', session: { id: env.leadSessionId } } } + const list = await env.tool('sansheng_task_list').execute({}, exec) + assert.equal(list.ok, true) + assert.equal(list.tasks.length, 0) +}) + +test('部门工具:已完成任务不能原地改要求,应新建任务', async () => { + const env = await setupToolProject({ path: '/tools-revise-done', name: '完成改要求项目' }) + const dispatched = await env.tool('sansheng_dispatch_task').execute({ + targetSeatId: 'gongbu', + title: '已完成的交付', + requirement: '第一版要求', + }, env.leadExec) + await env.tool('sansheng_task_report').execute({ + taskId: dispatched.taskId, + status: 'done', + result: '真实结果:文件已生成', + }, env.gongExec) + const before = (await env.service.memory(env.projectId)).memory.revision + await assert.rejects( + () => env.tool('sansheng_task_revise').execute({ taskId: dispatched.taskId, requirement: '第二版要求', sourceText: '用户改口:第二版要求' }, env.leadExec), + /新建任务/, + ) + const after = (await env.service.memory(env.projectId)).memory.revision + assert.equal(after, before) + const task = (await env.service.taskGet(env.projectId, dispatched.taskId)).task + assert.equal(task.status, 'done') + assert.match(task.result, /真实结果/) +})