release: dsh-sansheng-liubu v1.1.4:议政与省级子 Agent、非阻塞回执与叫停、Better Sidebar 子插件拆分
This commit is contained in:
parent
a4334bfba0
commit
2499dc44cc
|
|
@ -1,3 +1,4 @@
|
||||||
|
docs/
|
||||||
ds-bot/
|
ds-bot/
|
||||||
node_modules/
|
node_modules/
|
||||||
.dsh-test-*/
|
.dsh-test-*/
|
||||||
|
|
|
||||||
|
|
@ -89,3 +89,16 @@ HTTP 处理器端到端;systemPrompt 只注入十席;Web 纯视图模型(
|
||||||
- 左侧入口从 `sidebar.session.action` 移到 `sidebar.panellist`(order 32,记忆系统与“更多”之间),点击只开右侧工作台,中央聊天不被接管。
|
- 左侧入口从 `sidebar.session.action` 移到 `sidebar.panellist`(order 32,记忆系统与“更多”之间),点击只开右侧工作台,中央聊天不被接管。
|
||||||
- 测试 41 项全通过;`client.js` 已重建。
|
- 测试 41 项全通过;`client.js` 已重建。
|
||||||
- 未完成:隔离环境真实界面截图、v0.1.2 发布与市场索引、用户本地安装。
|
- 未完成:隔离环境真实界面截图、v0.1.2 发布与市场索引、用户本地安装。
|
||||||
|
|
||||||
|
## v1.2(2026-11-26):R-001~R-007 批次(fake ctx 完成;真实宿主 POC 待补)
|
||||||
|
|
||||||
|
- R-001 全局默认模型:`global-store.js`(setting.json 原子写/严格校验/revision)、`model-sync.js`(项目覆盖→全局默认→部署默认,projectId:seatId 队列与 generation、身份复核、current 回读)、service/api/provision/index 接线、工作台来源/同步状态与「设为全局默认」入口。
|
||||||
|
- R-002 发布口令:`command-ledger.js` 以 sessionId+seq 记录命令结果;唯一 ready 支持裸「发布」,多条返回候选拒绝;同 seq 拒绝重放。
|
||||||
|
- R-003 自动回报:`lead-reporter.js`(leadReports + 30s 条件领取 + createUserMessage/followup 单一发送路径,不重送 unknown)。
|
||||||
|
- R-004 集中审批:`approval-center.js`(approval/request prepend、双通道 linked AbortController、精确身份 answer、degraded 状态)。
|
||||||
|
- R-005 运行状态:`seat-activity.js`(只认 live Agent.status;turn/end 仅记录 runtimeFailure;tool/call 映射;5s reconcile 缓存)。
|
||||||
|
- R-006 可信来源:`message-source.js`(source.kind=user + clientTimeZone 才可作命令;内部来源 sansheng-task/report/summary)。
|
||||||
|
- R-007 冷会话派工:`seat-delivery.js`(先 resolveAgent、身份复核后 createUserMessage+followup+flush;flush 失败记 unknown)。
|
||||||
|
- 测试:`node --test test/*.test.js` 134 项通过;`client.js` 已重建并通过 `--check`。
|
||||||
|
- R-002 恢复链已完成:taskDispatch 的 pending→sending 条件领取/持有者复核、sending 遗留 unknown 不盲发、启动 recoverPendingDeliveries 恢复 pending、redispatchTask 仅按 expectedDeliveryId + blocked/unknown 条件重投;已由 fake-ctx 单测覆盖。
|
||||||
|
- 真实宿主 POC 边界(如实记录):R-001 启动屏障受宿主无 pre-first-turn 钩子限制;R-004 approval/request 事件、R-005 live Agent.status、R-007 resolveAgent/followup/flush 四路径目前仅有 fake-ctx 单测与类型契约核对,尚未在真实 DSH 桌面进程做端到端 POC。真机验收需安装插件后用 `scripts/verify-model-sync.mjs` 及真实会话补充证据。
|
||||||
|
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 73 KiB After Width: | Height: | Size: 73 KiB |
|
|
@ -0,0 +1,10 @@
|
||||||
|
# 三省六部 Better Sidebar 子插件
|
||||||
|
|
||||||
|
并行的浏览器子插件:把三省六部工作台注册为 Better Sidebar 右栏标签。
|
||||||
|
|
||||||
|
- 主插件 `dsh-sansheng-liubu` 负责左侧导航、工作台正文和宿主原生右栏回退,并通过 `sanshengWorkbench` 服务暴露工作台组件和右栏接管口。
|
||||||
|
- 本插件声明 `inject = ['betterSidebar', 'sanshengWorkbench']`,注册 `sansheng-workbench` 标签(`single: true`)。
|
||||||
|
- 未安装 Better Sidebar 或本插件、或注册失败时,主插件继续使用原生 `sidebarRight` 回退。
|
||||||
|
- 卸载时先撤销本插件注册,再恢复主插件原生右栏。
|
||||||
|
|
||||||
|
发布顺序:先更新主插件,再启用本子插件。
|
||||||
|
|
@ -0,0 +1,130 @@
|
||||||
|
// Generated from src/client by `npm run build` (scripts/build-client.mjs). Do not edit by hand.
|
||||||
|
window.__ModuleLoader__.load({
|
||||||
|
id: "dsh-sansheng-liubu-better-sidebar",
|
||||||
|
factory: (require) => {
|
||||||
|
const module = { exports: {} }
|
||||||
|
var __defProp = Object.defineProperty;
|
||||||
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||||
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||||
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||||
|
var __export = (target, all) => {
|
||||||
|
for (var name in all)
|
||||||
|
__defProp(target, name, { get: all[name], enumerable: true });
|
||||||
|
};
|
||||||
|
var __copyProps = (to, from, except, desc) => {
|
||||||
|
if (from && typeof from === "object" || typeof from === "function") {
|
||||||
|
for (let key of __getOwnPropNames(from))
|
||||||
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||||
|
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||||
|
}
|
||||||
|
return to;
|
||||||
|
};
|
||||||
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||||
|
|
||||||
|
// src/client/index.js
|
||||||
|
var index_exports = {};
|
||||||
|
__export(index_exports, {
|
||||||
|
apply: () => apply,
|
||||||
|
inject: () => inject
|
||||||
|
});
|
||||||
|
module.exports = __toCommonJS(index_exports);
|
||||||
|
var import_react = require("react");
|
||||||
|
var TAB_KIND = "sansheng-workbench";
|
||||||
|
var PLUGIN_LABEL = "sansheng-better-sidebar";
|
||||||
|
function isFn(value) {
|
||||||
|
return typeof value === "function";
|
||||||
|
}
|
||||||
|
var inject = ["betterSidebar", "sanshengWorkbench"];
|
||||||
|
function apply(ctx) {
|
||||||
|
const bs = ctx.get("betterSidebar");
|
||||||
|
const workbench = ctx.get("sanshengWorkbench");
|
||||||
|
if (!bs || !workbench) {
|
||||||
|
console.warn("[" + PLUGIN_LABEL + "] 缺少 betterSidebar 或 sanshengWorkbench,右栏增强不启用");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let disposeTab = null;
|
||||||
|
let detachOpener = null;
|
||||||
|
let takenOver = false;
|
||||||
|
function restoreNativeFallback() {
|
||||||
|
if (isFn(workbench.restoreNativeRightTab)) {
|
||||||
|
try {
|
||||||
|
workbench.restoreNativeRightTab();
|
||||||
|
} catch (error) {
|
||||||
|
console.warn("[" + PLUGIN_LABEL + "] 恢复主插件原生右栏失败:", error?.message ?? error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function register() {
|
||||||
|
if (isFn(workbench.releaseNativeRightTab)) {
|
||||||
|
try {
|
||||||
|
workbench.releaseNativeRightTab();
|
||||||
|
} catch (error) {
|
||||||
|
console.warn("[" + PLUGIN_LABEL + "] 释放主插件原生右栏失败:", error?.message ?? error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
takenOver = true;
|
||||||
|
try {
|
||||||
|
disposeTab = bs.registerTab({
|
||||||
|
id: TAB_KIND,
|
||||||
|
title: () => workbench.title || "三省六部",
|
||||||
|
description: workbench.description,
|
||||||
|
icon: workbench.icon,
|
||||||
|
order: 32,
|
||||||
|
single: true,
|
||||||
|
component: (props) => {
|
||||||
|
const scope = props && props.scope ? props.scope : null;
|
||||||
|
const sessionId = scope && scope.sessionId;
|
||||||
|
return (0, import_react.createElement)("div", {
|
||||||
|
className: "ssw-tab-body",
|
||||||
|
"data-session-id": sessionId || void 0,
|
||||||
|
"data-sansheng-right-tab": "better-sidebar"
|
||||||
|
}, (0, import_react.createElement)(workbench.Workbench, { sessionId }));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.warn("[" + PLUGIN_LABEL + "] 注册 Better Sidebar 标签失败,恢复主插件原生右栏:", error?.message ?? error);
|
||||||
|
takenOver = false;
|
||||||
|
restoreNativeFallback();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
detachOpener = workbench.attachRightTabOpener((sessionId) => {
|
||||||
|
if (!sessionId) return false;
|
||||||
|
const scope = { sessionId };
|
||||||
|
try {
|
||||||
|
const summary = workbench.sessionSummary?.(sessionId);
|
||||||
|
if (summary && typeof summary.cwd === "string" && summary.cwd) scope.cwd = summary.cwd;
|
||||||
|
} catch {
|
||||||
|
}
|
||||||
|
bs.openTab({ type: TAB_KIND, title: workbench.title || "三省六部" }, scope);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
function unregister() {
|
||||||
|
if (isFn(detachOpener)) {
|
||||||
|
try {
|
||||||
|
detachOpener();
|
||||||
|
} catch {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
detachOpener = null;
|
||||||
|
if (isFn(disposeTab)) {
|
||||||
|
try {
|
||||||
|
disposeTab();
|
||||||
|
} catch {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
disposeTab = null;
|
||||||
|
if (takenOver) {
|
||||||
|
takenOver = false;
|
||||||
|
restoreNativeFallback();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
register();
|
||||||
|
if (isFn(ctx.effect)) ctx.effect(() => () => {
|
||||||
|
unregister();
|
||||||
|
}, "dsh-sansheng-liubu-better-sidebar: right tab");
|
||||||
|
}
|
||||||
|
return Object.defineProperty({ ...module.exports }, Symbol.toStringTag, { value: 'Module' })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
# 三省六部 Better Sidebar 子插件:只在浏览器右栏注册工作台标签,服务端为空。
|
||||||
|
- insert:
|
||||||
|
- id: sansheng-better-sidebar
|
||||||
|
name: 'dsh-sansheng-liubu-better-sidebar'
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
// 三省六部 Better Sidebar 子插件的服务端入口:不需要任何宿主服务,只启用浏览器半。
|
||||||
|
export const inject = []
|
||||||
|
|
||||||
|
export function apply() {}
|
||||||
|
|
@ -0,0 +1,66 @@
|
||||||
|
{
|
||||||
|
"name": "dsh-sansheng-liubu-better-sidebar",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "三省六部 Better Sidebar 右栏子插件:把工作台注册为 Better Sidebar 标签,没装或注册失败时由主插件原生右栏回退。",
|
||||||
|
"keywords": [
|
||||||
|
"dsh-plugin",
|
||||||
|
"deepseek-harness",
|
||||||
|
"dsh",
|
||||||
|
"sansheng",
|
||||||
|
"better-sidebar"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"type": "module",
|
||||||
|
"main": "index.js",
|
||||||
|
"exports": {
|
||||||
|
".": "./index.js",
|
||||||
|
"./client": "./client.js",
|
||||||
|
"./package.json": "./package.json"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"index.js",
|
||||||
|
"client.js",
|
||||||
|
"src/",
|
||||||
|
"cordis.patch.yml",
|
||||||
|
"README.md"
|
||||||
|
],
|
||||||
|
"scripts": {
|
||||||
|
"build": "node scripts/build-client.mjs",
|
||||||
|
"build:check": "node scripts/build-client.mjs --check"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@deepseek-ai/cordis": "*",
|
||||||
|
"dsh-better-sidebar": ">=0.17.0",
|
||||||
|
"dsh-sansheng-liubu": ">=1.1.3",
|
||||||
|
"react": "^18.2.0",
|
||||||
|
"react-dom": "^18.2.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"dsh-better-sidebar": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"dsh-sansheng-liubu": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"dsh": {
|
||||||
|
"client": {
|
||||||
|
"platform": "web",
|
||||||
|
"inject": [
|
||||||
|
"dsh-sansheng-liubu"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"bundle": {
|
||||||
|
"patch": "./cordis.patch.yml"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"esbuild": "0.28.2"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,64 @@
|
||||||
|
// Builds client.js (browser half) from src/client.
|
||||||
|
// node scripts/build-client.mjs writes client.js
|
||||||
|
// node scripts/build-client.mjs --check exit 1 if client.js differs from a fresh build
|
||||||
|
import { readFileSync, writeFileSync } from 'node:fs'
|
||||||
|
import { createRequire } from 'node:module'
|
||||||
|
import { dirname, join } from 'node:path'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const PLUGIN = dirname(dirname(fileURLToPath(import.meta.url)))
|
||||||
|
const OUTPUT = join(PLUGIN, 'client.js')
|
||||||
|
const PLATFORM_MODULES = ['react', 'react-dom', '@deepseek-ai/dsh-client-ui-primitives']
|
||||||
|
const BUNDLE_ID = 'dsh-sansheng-liubu-better-sidebar'
|
||||||
|
|
||||||
|
async function loadEsbuild() {
|
||||||
|
try { return await import('esbuild') } catch { /* 本地开发时尝试复用主插件依赖 */ }
|
||||||
|
try {
|
||||||
|
const require = createRequire(new URL('../../sansheng/package.json', import.meta.url))
|
||||||
|
return require('esbuild')
|
||||||
|
} catch { /* 继续给统一错误 */ }
|
||||||
|
throw new Error('缺少 esbuild:请先在包内安装 devDependencies(pnpm/npm i),再构建 client.js。')
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function bundleClient() {
|
||||||
|
const esbuild = await loadEsbuild()
|
||||||
|
const result = await esbuild.build({
|
||||||
|
absWorkingDir: PLUGIN,
|
||||||
|
entryPoints: ['src/client/index.js'],
|
||||||
|
bundle: true,
|
||||||
|
format: 'cjs',
|
||||||
|
platform: 'browser',
|
||||||
|
target: 'es2022',
|
||||||
|
external: PLATFORM_MODULES,
|
||||||
|
treeShaking: false,
|
||||||
|
charset: 'utf8',
|
||||||
|
write: false,
|
||||||
|
logLevel: 'silent',
|
||||||
|
})
|
||||||
|
if (result.warnings.length > 0) throw new Error('esbuild warnings:\n' + result.warnings.map(w => w.text).join('\n'))
|
||||||
|
return [
|
||||||
|
'// Generated from src/client by `npm run build` (scripts/build-client.mjs). Do not edit by hand.',
|
||||||
|
'window.__ModuleLoader__.load({',
|
||||||
|
' id: ' + JSON.stringify(BUNDLE_ID) + ',',
|
||||||
|
' factory: (require) => {',
|
||||||
|
'const module = { exports: {} }',
|
||||||
|
result.outputFiles[0].text.trimEnd(),
|
||||||
|
"return Object.defineProperty({ ...module.exports }, Symbol.toStringTag, { value: 'Module' })",
|
||||||
|
' },',
|
||||||
|
'})',
|
||||||
|
'',
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||||
|
const next = await bundleClient()
|
||||||
|
if (process.argv.includes('--check')) {
|
||||||
|
let current = ''
|
||||||
|
try { current = readFileSync(OUTPUT, 'utf8') } catch {}
|
||||||
|
if (current !== next) { console.error('client.js 与 src/client 不一致,请运行 npm run build'); process.exit(1) }
|
||||||
|
console.log('client.js 是最新的')
|
||||||
|
} else {
|
||||||
|
writeFileSync(OUTPUT, next)
|
||||||
|
console.log('已写出 client.js')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,100 @@
|
||||||
|
// 三省六部 Better Sidebar 子插件:把主插件的工作台注册为 Better Sidebar 标签。
|
||||||
|
// 主插件通过 sanshengWorkbench 服务提供工作台组件、会话摘要和原生右栏接管口;
|
||||||
|
// 本插件只负责向 Better Sidebar 注册标签、打开标签,并在卸载或失败时恢复主插件原生右栏。
|
||||||
|
|
||||||
|
import { createElement as h } from 'react'
|
||||||
|
|
||||||
|
const TAB_KIND = 'sansheng-workbench'
|
||||||
|
const PLUGIN_LABEL = 'sansheng-better-sidebar'
|
||||||
|
|
||||||
|
function isFn(value) {
|
||||||
|
return typeof value === 'function'
|
||||||
|
}
|
||||||
|
|
||||||
|
export const inject = ['betterSidebar', 'sanshengWorkbench']
|
||||||
|
|
||||||
|
export function apply(ctx) {
|
||||||
|
const bs = ctx.get('betterSidebar')
|
||||||
|
const workbench = ctx.get('sanshengWorkbench')
|
||||||
|
if (!bs || !workbench) {
|
||||||
|
console.warn('[' + PLUGIN_LABEL + '] 缺少 betterSidebar 或 sanshengWorkbench,右栏增强不启用')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let disposeTab = null
|
||||||
|
let detachOpener = null
|
||||||
|
let takenOver = false
|
||||||
|
|
||||||
|
function restoreNativeFallback() {
|
||||||
|
if (isFn(workbench.restoreNativeRightTab)) {
|
||||||
|
try { workbench.restoreNativeRightTab() } catch (error) {
|
||||||
|
console.warn('[' + PLUGIN_LABEL + '] 恢复主插件原生右栏失败:', error?.message ?? error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function register() {
|
||||||
|
// 接管顺序:先释放主插件原生类型和两个槽位,再注册 Better Sidebar 描述符。
|
||||||
|
// 同一 kind 只能有一份右栏入口,注册失败则立刻恢复原生回退。
|
||||||
|
if (isFn(workbench.releaseNativeRightTab)) {
|
||||||
|
try { workbench.releaseNativeRightTab() } catch (error) {
|
||||||
|
console.warn('[' + PLUGIN_LABEL + '] 释放主插件原生右栏失败:', error?.message ?? error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
takenOver = true
|
||||||
|
try {
|
||||||
|
disposeTab = bs.registerTab({
|
||||||
|
id: TAB_KIND,
|
||||||
|
title: () => workbench.title || '三省六部',
|
||||||
|
description: workbench.description,
|
||||||
|
icon: workbench.icon,
|
||||||
|
order: 32,
|
||||||
|
single: true,
|
||||||
|
component: (props) => {
|
||||||
|
const scope = props && props.scope ? props.scope : null
|
||||||
|
const sessionId = scope && scope.sessionId
|
||||||
|
return h('div', {
|
||||||
|
className: 'ssw-tab-body',
|
||||||
|
'data-session-id': sessionId || undefined,
|
||||||
|
'data-sansheng-right-tab': 'better-sidebar',
|
||||||
|
}, h(workbench.Workbench, { sessionId }))
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[' + PLUGIN_LABEL + '] 注册 Better Sidebar 标签失败,恢复主插件原生右栏:', error?.message ?? error)
|
||||||
|
takenOver = false
|
||||||
|
restoreNativeFallback()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
detachOpener = workbench.attachRightTabOpener((sessionId) => {
|
||||||
|
if (!sessionId) return false
|
||||||
|
const scope = { sessionId }
|
||||||
|
try {
|
||||||
|
const summary = workbench.sessionSummary?.(sessionId)
|
||||||
|
if (summary && typeof summary.cwd === 'string' && summary.cwd) scope.cwd = summary.cwd
|
||||||
|
} catch { /* 忽略摘要探测失败,sessionId 足够打开 */ }
|
||||||
|
bs.openTab({ type: TAB_KIND, title: workbench.title || '三省六部' }, scope)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
function unregister() {
|
||||||
|
if (isFn(detachOpener)) {
|
||||||
|
try { detachOpener() } catch { /* 忽略 */ }
|
||||||
|
}
|
||||||
|
detachOpener = null
|
||||||
|
if (isFn(disposeTab)) {
|
||||||
|
try { disposeTab() } catch { /* 忽略 */ }
|
||||||
|
}
|
||||||
|
disposeTab = null
|
||||||
|
// 子插件卸载:先撤自己的注册,再恢复主插件原生回退。
|
||||||
|
if (takenOver) {
|
||||||
|
takenOver = false
|
||||||
|
restoreNativeFallback()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
register()
|
||||||
|
if (isFn(ctx.effect)) ctx.effect(() => () => { unregister() }, 'dsh-sansheng-liubu-better-sidebar: right tab')
|
||||||
|
}
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
# 三省六部(dsh-sansheng)· v1.1.3
|
# 三省六部(dsh-sansheng)· v1.1.4
|
||||||
|
|
||||||
在 DSH 里为每个项目提供固定的十席角色(丞相、中书、门下、尚书、吏部、户部、礼部、兵部、刑部、工部),
|
在 DSH 里为每个项目提供固定的十席角色(丞相、中书、门下、尚书、吏部、户部、礼部、兵部、刑部、工部),
|
||||||
每席绑定一个独立的原生 root Session,模型与补充说明按项目独立保存。中间复用宿主原生会话,不替换聊天引擎。
|
每席绑定一个独立的原生 root Session,模型与补充说明按项目独立保存。中间复用宿主原生会话,不替换聊天引擎。
|
||||||
|
|
|
||||||
1200
sansheng/client.js
1200
sansheng/client.js
File diff suppressed because it is too large
Load Diff
|
|
@ -15,6 +15,9 @@ import { installPromptSection } from './src/host/prompt.js'
|
||||||
import { installSeatTools } from './src/host/tools.js'
|
import { installSeatTools } from './src/host/tools.js'
|
||||||
import { createTurnCommands } from './src/host/message-source.js'
|
import { createTurnCommands } from './src/host/message-source.js'
|
||||||
import { createLeadBackground } from './src/host/lead-background.js'
|
import { createLeadBackground } from './src/host/lead-background.js'
|
||||||
|
import { createLeadSecretaries } from './src/host/lead-secretaries.js'
|
||||||
|
import { createProvinceAgents } from './src/host/province-agents.js'
|
||||||
|
import { SEATS } from './src/shared/roles.js'
|
||||||
import { sanshengStatePath, sanshengGlobalSettingPath } from './src/host/paths.js'
|
import { sanshengStatePath, sanshengGlobalSettingPath } from './src/host/paths.js'
|
||||||
import { ROUTE } from './src/host/constants.js'
|
import { ROUTE } from './src/host/constants.js'
|
||||||
|
|
||||||
|
|
@ -52,11 +55,34 @@ export function apply(ctx, config = {}) {
|
||||||
const found = store.seatBySession(sessionId)
|
const found = store.seatBySession(sessionId)
|
||||||
return found ? { projectId: found.project.id, seatId: found.seatId } : null
|
return found ? { projectId: found.project.id, seatId: found.seatId } : null
|
||||||
},
|
},
|
||||||
|
// 有新的原生审批时,先把“谁申请、要做什么、原因”作为正式回报推给丞相;
|
||||||
|
// 丞相再用 sansheng_card 挂审批卡,用户点卡后仍回到这个原生请求。
|
||||||
|
onPending: entry => {
|
||||||
|
const label = SEATS[entry.seatId]?.label ?? entry.seatId
|
||||||
|
const summary = `待你审批:${label}申请${entry.tool ? '「' + entry.tool + '」' : '一次操作'}${entry.reason ? ',原因:' + entry.reason : ''}。审批编号:${entry.id}`
|
||||||
|
void leadReporter.record(entry.projectId, {
|
||||||
|
taskId: null,
|
||||||
|
transitionId: 'approval:' + entry.id,
|
||||||
|
event: 'approval_request',
|
||||||
|
stage: null,
|
||||||
|
ownerSeatId: entry.seatId,
|
||||||
|
summary,
|
||||||
|
textSnapshot: summary,
|
||||||
|
needsUserDecision: true,
|
||||||
|
sourceKind: 'sansheng-report',
|
||||||
|
}).then(() => leadReporter.flush(entry.projectId)).catch(error => {
|
||||||
|
console.warn('[sansheng] 审批待办回报失败:', error?.message ?? error)
|
||||||
|
})
|
||||||
|
},
|
||||||
})
|
})
|
||||||
const seatActivity = createSeatActivity({ store, host, approvalCenter })
|
const seatActivity = createSeatActivity({ store, host, approvalCenter })
|
||||||
const provisioner = createProvisioner({ store, host, modelSync })
|
const provisioner = createProvisioner({ store, host, modelSync })
|
||||||
const seatDelivery = createSeatDelivery({ host })
|
const seatDelivery = createSeatDelivery({ host })
|
||||||
const service = new SanshengService({ store, host, provisioner, globalStore, modelSync, seatActivity, leadReporter, approvalCenter, seatDelivery })
|
const serviceRef = { service: null }
|
||||||
|
const leadSecretaries = createLeadSecretaries({ ctx, store })
|
||||||
|
const provinceAgents = createProvinceAgents({ ctx, store, serviceRef, host })
|
||||||
|
const service = new SanshengService({ store, host, provisioner, globalStore, modelSync, seatActivity, leadReporter, approvalCenter, seatDelivery, provinceAgents, leadSecretaries })
|
||||||
|
serviceRef.service = service
|
||||||
const handle = createApiHandler(service)
|
const handle = createApiHandler(service)
|
||||||
|
|
||||||
ctx.effect(() => seatActivity.install(ctx), 'sansheng: seat activity')
|
ctx.effect(() => seatActivity.install(ctx), 'sansheng: seat activity')
|
||||||
|
|
@ -82,9 +108,11 @@ export function apply(ctx, config = {}) {
|
||||||
ctx.effect(() => installPromptSection(ctx, { store }), 'sansheng: prompt section')
|
ctx.effect(() => installPromptSection(ctx, { store }), 'sansheng: prompt section')
|
||||||
const leadBackground = createLeadBackground({ ctx, store })
|
const leadBackground = createLeadBackground({ ctx, store })
|
||||||
ctx.effect(() => leadBackground.install(), 'sansheng: lead background')
|
ctx.effect(() => leadBackground.install(), 'sansheng: lead background')
|
||||||
|
ctx.effect(() => leadSecretaries.install(), 'sansheng: lead secretaries')
|
||||||
|
ctx.effect(() => provinceAgents.install(), 'sansheng: province agents')
|
||||||
ctx.effect(() => {
|
ctx.effect(() => {
|
||||||
const turnCommands = createTurnCommands(ctx, store)
|
const turnCommands = createTurnCommands(ctx, store)
|
||||||
const disposeTools = installSeatTools(ctx, { store, service, provisioner, turnCommands, leadBackground })
|
const disposeTools = installSeatTools(ctx, { store, service, provisioner, turnCommands, leadBackground, leadSecretaries, provinceAgents })
|
||||||
return () => { disposeTools(); turnCommands.dispose() }
|
return () => { disposeTools(); turnCommands.dispose() }
|
||||||
}, 'sansheng: seat tools')
|
}, 'sansheng: seat tools')
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "dsh-sansheng-liubu",
|
"name": "dsh-sansheng-liubu",
|
||||||
"version": "1.1.3",
|
"version": "1.1.4",
|
||||||
"description": "三省六部:每个项目固定十席角色与独立会话的 DSH 插件(第一版)。",
|
"description": "三省六部:每个项目固定十席角色与独立会话的 DSH 插件(第一版)。",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"dsh-plugin",
|
"dsh-plugin",
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import { WorkbenchV2 } from './workbench-v2.js'
|
||||||
import { workspaceForSession, workspaceItemsFromSnapshot, sessionSummaryFromSnapshot } from './workspace.js'
|
import { workspaceForSession, workspaceItemsFromSnapshot, sessionSummaryFromSnapshot } from './workspace.js'
|
||||||
import { request } from './transport.js'
|
import { request } from './transport.js'
|
||||||
import { CSS as WORKBENCH_CSS } from './styles.js'
|
import { CSS as WORKBENCH_CSS } from './styles.js'
|
||||||
|
import { SanshengCardRow } from './cards.js'
|
||||||
import { install as installNativePanel } from '../native/index.js'
|
import { install as installNativePanel } from '../native/index.js'
|
||||||
|
|
||||||
export const inject = ['sessions', 'workspaces', 'uiWorkspace', 'uiConversation', 'slots', 'theme', 'layout', 'sidebarRightTabs', 'sidebarRight']
|
export const inject = ['sessions', 'workspaces', 'uiWorkspace', 'uiConversation', 'slots', 'theme', 'layout', 'sidebarRightTabs', 'sidebarRight']
|
||||||
|
|
@ -110,6 +111,9 @@ export function apply(ctx) {
|
||||||
|
|
||||||
const get = (name) => { try { return ctx.get(name) } catch { return undefined } }
|
const get = (name) => { try { return ctx.get(name) } catch { return undefined } }
|
||||||
|
|
||||||
|
// 子插件(sansheng-better-sidebar)挂进来的右栏打开方法;为空时走宿主原生右栏。
|
||||||
|
let rightTabOpener = null
|
||||||
|
|
||||||
// ---------- 当前项目 / 工作区(特性探测,拿不到就提示用户先选项目) ----------
|
// ---------- 当前项目 / 工作区(特性探测,拿不到就提示用户先选项目) ----------
|
||||||
function sessionsSnapshot() {
|
function sessionsSnapshot() {
|
||||||
return snapshotOf(get('sessions')?.list) ?? snapshotOf(get('sessions'))
|
return snapshotOf(get('sessions')?.list) ?? snapshotOf(get('sessions'))
|
||||||
|
|
@ -358,26 +362,27 @@ export function apply(ctx) {
|
||||||
const targetSessionId = (typeof sessionId === 'string' && sessionId) ? sessionId : rightMountedSessionId()
|
const targetSessionId = (typeof sessionId === 'string' && sessionId) ? sessionId : rightMountedSessionId()
|
||||||
const existing = findRightWorkbenchTab(targetSessionId)
|
const existing = findRightWorkbenchTab(targetSessionId)
|
||||||
if (existing) return revealRightTab(targetSessionId)
|
if (existing) return revealRightTab(targetSessionId)
|
||||||
// 桌面版右栏由 dsh-better-sidebar 接管:它自己的 openTab 会排队等待会话面板挂载,
|
// 右栏增强交给并行的子插件:它注册 Better Sidebar 标签后,把打开方法挂回这里。
|
||||||
// 主区正被切走时也不会丢;直接调宿主 sidebarRight 反而会因“没有挂载的会话面板”失败。
|
// 只要子插件在,打开失败就交回调用方走浮层/内嵌,不再注册原生类型,避免和 Better Sidebar 的 kind 冲突。
|
||||||
// 显式传 scope:新会话刚建立时 bs 的 active snapshot 可能还停在旧会话,不能靠猜。
|
if (isFn(rightTabOpener)) {
|
||||||
const bs = get('betterSidebar')
|
|
||||||
if (bs && isFn(bs.openTab)) {
|
|
||||||
try {
|
try {
|
||||||
if (!targetSessionId) return false
|
if (rightTabOpener(targetSessionId)) {
|
||||||
const summary = sessionSummary(targetSessionId)
|
scheduleRevealRightTab(targetSessionId)
|
||||||
const scope = { sessionId: targetSessionId }
|
return true
|
||||||
if (summary && typeof summary.cwd === 'string' && summary.cwd) scope.cwd = summary.cwd
|
}
|
||||||
bs.openTab({ type: TAB_KIND, title: '三省六部' }, scope)
|
|
||||||
scheduleRevealRightTab(targetSessionId)
|
|
||||||
return true
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('[sansheng] better-sidebar 打开失败,改用宿主接口:', error && error.message ? error.message : error)
|
console.warn('[sansheng] 子插件打开右栏失败:', error && error.message ? error.message : error)
|
||||||
}
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
const right = get('sidebarRight')
|
const right = get('sidebarRight')
|
||||||
if (!right || !isFn(right.openTab)) return false
|
if (!right || !isFn(right.openTab)) return false
|
||||||
if (!ensureRightTab()) return false
|
if (!ensureRightTab()) {
|
||||||
|
// 原生回退按需注册:有子插件时它已在 apply 时接管,这里不会注册;
|
||||||
|
// 没有子插件时第一次点导航再把原生类型和两个槽位挂上,避免和 Better Sidebar 的 kind 冲突。
|
||||||
|
registerRightTabType()
|
||||||
|
if (!ensureRightTab()) return false
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
// 原生接口的 openTab 只能作用于 on-screen 会话;目标会话尚未 adopt 时,
|
// 原生接口的 openTab 只能作用于 on-screen 会话;目标会话尚未 adopt 时,
|
||||||
// 如果宿主暴露了 openTabIn(跨会话目标通道)就用它,否则退回 openTab 并靠退避重试。
|
// 如果宿主暴露了 openTabIn(跨会话目标通道)就用它,否则退回 openTab 并靠退避重试。
|
||||||
|
|
@ -394,72 +399,83 @@ export function apply(ctx) {
|
||||||
}
|
}
|
||||||
function SanshengTabBody(props) {
|
function SanshengTabBody(props) {
|
||||||
const sessionId = props && props.sessionId
|
const sessionId = props && props.sessionId
|
||||||
return h('div', { className: 'ssw-tab-body', 'data-session-id': sessionId || undefined }, h(SanshengWorkbench, { sessionId }))
|
return h('div', {
|
||||||
|
className: 'ssw-tab-body',
|
||||||
|
'data-session-id': sessionId || undefined,
|
||||||
|
'data-sansheng-right-tab': 'native',
|
||||||
|
}, h(SanshengWorkbench, { sessionId }))
|
||||||
}
|
}
|
||||||
function SanshengTabTitle() {
|
function SanshengTabTitle() {
|
||||||
return h('span', { className: 'ssw-tab-title' }, '三省六部')
|
return h('span', { className: 'ssw-tab-title' }, '三省六部')
|
||||||
}
|
}
|
||||||
// 宿主按 definition.id 选 slot(TabSlot: entryKey=definition.id),因此 slot key 必须等于类型 id。
|
// 宿主按 definition.id 选 slot(TabSlot: entryKey=definition.id),因此 slot key 必须等于类型 id。
|
||||||
function registerRightTabType() {
|
// 原生右栏是主插件自带的回退;子插件接管时先 release,失败或卸载时 restore。
|
||||||
// 桌面版:向 better-sidebar 注册一个原生右侧标签(它自己负责正文/标题与落位)。
|
let nativeRightTabWanted = true
|
||||||
try {
|
let nativeRightTabStop = null
|
||||||
const bs = get('betterSidebar')
|
function uninstallNativeRightTab() {
|
||||||
if (bs && isFn(bs.registerTab)) {
|
const stop = nativeRightTabStop
|
||||||
const dispose = bs.registerTab({
|
nativeRightTabStop = null
|
||||||
id: TAB_KIND,
|
if (isFn(stop)) {
|
||||||
title: '三省六部',
|
try { stop() } catch { /* 忽略 */ }
|
||||||
description: '十席角色与独立会话的当前项目工作台',
|
|
||||||
icon: (size) => h(TreeIcon, { width: size, height: size }),
|
|
||||||
order: 32,
|
|
||||||
single: true,
|
|
||||||
component: (tabProps) => {
|
|
||||||
const scope = tabProps && tabProps.scope ? tabProps.scope : null
|
|
||||||
const sessionId = scope && scope.sessionId
|
|
||||||
return h('div', { className: 'ssw-tab-body', 'data-session-id': sessionId || undefined }, h(SanshengWorkbench, { sessionId }))
|
|
||||||
},
|
|
||||||
})
|
|
||||||
return () => { try { if (isFn(dispose)) dispose() } catch { /* 忽略 */ } }
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[sansheng] 注册 better-sidebar 标签失败:', error && error.message ? error.message : error)
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
function registerRightTabType() {
|
||||||
|
if (!nativeRightTabWanted || nativeRightTabStop || isFn(rightTabOpener)) return
|
||||||
|
if (!isFn(ctx.inject)) return
|
||||||
try {
|
try {
|
||||||
if (!isFn(ctx.inject)) return
|
nativeRightTabStop = ctx.inject(['sidebarRightTabs'], (injected) => {
|
||||||
ctx.inject(['sidebarRightTabs'], (injected) => {
|
if (!nativeRightTabWanted || isFn(rightTabOpener)) return
|
||||||
const tabs = injected.get('sidebarRightTabs')
|
const tabs = injected.get('sidebarRightTabs')
|
||||||
if (!tabs || !isFn(tabs.register)) return
|
if (!tabs || !isFn(tabs.register)) return
|
||||||
let disposeType = null, disposeBody = null, disposeTitle = null
|
injected.effect(() => {
|
||||||
try {
|
let disposeType = null, disposeBody = null, disposeTitle = null
|
||||||
disposeType = tabs.register({
|
const cleanup = () => {
|
||||||
id: TAB_TYPE_ID, kind: TAB_KIND, keepMounted: true, priority: 'extension', title: () => '三省六部',
|
try { disposeBody && disposeBody() } catch { /* 忽略 */ }
|
||||||
guide: [{
|
try { disposeTitle && disposeTitle() } catch { /* 忽略 */ }
|
||||||
id: `${TAB_TYPE_ID}:guide`, order: 32, title: () => '三省六部',
|
try { disposeType && disposeType() } catch { /* 忽略 */ }
|
||||||
description: () => '十席角色与独立会话的当前项目工作台', icon: TreeIcon,
|
}
|
||||||
}],
|
try {
|
||||||
})
|
disposeType = tabs.register({
|
||||||
disposeBody = ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
|
id: TAB_TYPE_ID, kind: TAB_KIND, keepMounted: true, priority: 'extension', title: () => '三省六部',
|
||||||
name: 'sidebar.right.pane.tab', key: TAB_TYPE_ID, inject: (sessionId) => ({ sessionId }),
|
guide: [{
|
||||||
}, SanshengTabBody))
|
id: `${TAB_TYPE_ID}:guide`, order: 32, title: () => '三省六部',
|
||||||
disposeTitle = ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
|
description: () => '十席角色与独立会话的当前项目工作台', icon: TreeIcon,
|
||||||
name: 'sidebar.right.pane.tab.title', key: TAB_TYPE_ID, inject: (sessionId) => ({ sessionId }),
|
}],
|
||||||
}, SanshengTabTitle))
|
})
|
||||||
} catch (error) {
|
// 正文和标题槽位要在类型注册后再注入:sidebar.right.pane.tab 是随类型声明的子槽位。
|
||||||
console.warn('[sansheng] 注册右侧标签失败:', error && error.message ? error.message : error)
|
disposeBody = ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
|
||||||
try { disposeBody && disposeBody() } catch { /* 忽略 */ }
|
name: 'sidebar.right.pane.tab', key: TAB_TYPE_ID, inject: (sessionId) => ({ sessionId }),
|
||||||
try { disposeTitle && disposeTitle() } catch { /* 忽略 */ }
|
}, SanshengTabBody))
|
||||||
try { disposeType && disposeType() } catch { /* 忽略 */ }
|
disposeTitle = ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
|
||||||
return
|
name: 'sidebar.right.pane.tab.title', key: TAB_TYPE_ID, inject: (sessionId) => ({ sessionId }),
|
||||||
}
|
}, SanshengTabTitle))
|
||||||
return () => {
|
} catch (error) {
|
||||||
try { disposeBody && disposeBody() } catch { /* 忽略 */ }
|
const message = error && error.message ? error.message : error
|
||||||
try { disposeTitle && disposeTitle() } catch { /* 忽略 */ }
|
if (!/inactive context/.test(String(message))) {
|
||||||
try { disposeType && disposeType() } catch { /* 忽略 */ }
|
console.warn('[sansheng] 注册右侧标签失败:', message)
|
||||||
}
|
}
|
||||||
|
cleanup()
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
return cleanup
|
||||||
|
}, 'sansheng: native right tab fallback')
|
||||||
})
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('[sansheng] 注册右侧标签失败:', error && error.message ? error.message : error)
|
nativeRightTabStop = null
|
||||||
|
const message = error && error.message ? error.message : error
|
||||||
|
if (!/inactive context/.test(String(message))) {
|
||||||
|
console.warn('[sansheng] 注册右侧标签失败:', message)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
function releaseNativeRightTab() {
|
||||||
|
nativeRightTabWanted = false
|
||||||
|
uninstallNativeRightTab()
|
||||||
|
}
|
||||||
|
function restoreNativeRightTab() {
|
||||||
|
nativeRightTabWanted = true
|
||||||
|
registerRightTabType()
|
||||||
|
}
|
||||||
|
|
||||||
// 工作台会随宿主会话切换而重挂载;按项目记住选中的部门,避免又跳回丞相。
|
// 工作台会随宿主会话切换而重挂载;按项目记住选中的部门,避免又跳回丞相。
|
||||||
const selectedSeatCache = new Map()
|
const selectedSeatCache = new Map()
|
||||||
|
|
@ -483,6 +499,26 @@ export function apply(ctx) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 并行子插件 sansheng-better-sidebar 通过这个服务拿工作台和右栏接管口。
|
||||||
|
// 主插件仍是工作台正文、导航和宿主原生右栏回退的所有者;子插件只负责 Better Sidebar 注册。
|
||||||
|
const workbenchService = {
|
||||||
|
version: 1,
|
||||||
|
Workbench: SanshengWorkbench,
|
||||||
|
tabKind: TAB_KIND,
|
||||||
|
tabTypeId: TAB_TYPE_ID,
|
||||||
|
title: '三省六部',
|
||||||
|
description: '十席角色与独立会话的当前项目工作台',
|
||||||
|
icon: (size) => h(TreeIcon, { width: size, height: size }),
|
||||||
|
sessionSummary,
|
||||||
|
attachRightTabOpener(fn) {
|
||||||
|
rightTabOpener = isFn(fn) ? fn : null
|
||||||
|
return () => { if (rightTabOpener === fn) rightTabOpener = null }
|
||||||
|
},
|
||||||
|
releaseNativeRightTab,
|
||||||
|
restoreNativeRightTab,
|
||||||
|
}
|
||||||
|
ctx.provide('sanshengWorkbench', workbenchService)
|
||||||
|
|
||||||
// ---------- 左侧导航入口 ----------
|
// ---------- 左侧导航入口 ----------
|
||||||
// 宿主正式扩展点是 sidebar.panellist:一行导航 + 一个同名 keyed main 页(插件/任务看板/记忆系统同机制)。
|
// 宿主正式扩展点是 sidebar.panellist:一行导航 + 一个同名 keyed main 页(插件/任务看板/记忆系统同机制)。
|
||||||
// 位置钉在记忆系统(order 30)与技能管理(31)之后、宿主「更多」之前。
|
// 位置钉在记忆系统(order 30)与技能管理(31)之后、宿主「更多」之前。
|
||||||
|
|
@ -519,7 +555,7 @@ export function apply(ctx) {
|
||||||
function installRightDockPinning() {
|
function installRightDockPinning() {
|
||||||
const right = get('sidebarRight')
|
const right = get('sidebarRight')
|
||||||
if (!right || !isFn(right.mounted?.subscribe)) return
|
if (!right || !isFn(right.mounted?.subscribe)) return
|
||||||
const delays = [60, 140, 280, 560, 1000, 1800, 3000]
|
const delays = [400, 800, 1200, 1800, 2600, 3600, 5000]
|
||||||
let timer = null
|
let timer = null
|
||||||
let attempt = 0
|
let attempt = 0
|
||||||
const clear = () => {
|
const clear = () => {
|
||||||
|
|
@ -611,9 +647,7 @@ export function apply(ctx) {
|
||||||
}
|
}
|
||||||
function SanshengNavFallback() {
|
function SanshengNavFallback() {
|
||||||
// 点击左侧「三省六部」整行时,优先把工作台停靠到右侧;打不开就在主区内嵌显示。
|
// 点击左侧「三省六部」整行时,优先把工作台停靠到右侧;打不开就在主区内嵌显示。
|
||||||
// 关键:openRightWorkbench 必须在组件仍挂载时同步尝试。旧逻辑先 backToChat,
|
// openRightWorkbench 必须在组件仍挂载时同步尝试,避免切走主区后定时器落在卸载实例上。
|
||||||
// 组件随即卸载,定时器里的 setMode('inline') 落在已卸载实例上,主区就永远空白。
|
|
||||||
const hasBetterSidebar = !!get('betterSidebar')
|
|
||||||
const [mode, setMode] = useState('pending')
|
const [mode, setMode] = useState('pending')
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let opened = false
|
let opened = false
|
||||||
|
|
@ -623,20 +657,7 @@ export function apply(ctx) {
|
||||||
backToChat()
|
backToChat()
|
||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
if (!hasBetterSidebar) {
|
setMode('inline')
|
||||||
setMode('inline')
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
// 桌面右栏宿主:先切回会话,再等会话重新挂载后重试打开右栏。
|
|
||||||
// 这些定时器不随本组件卸载取消,否则切回会话就把自己“清理”掉了。
|
|
||||||
backToChat()
|
|
||||||
let openedLater = false
|
|
||||||
for (const delay of [200, 600, 1200, 2000]) {
|
|
||||||
setTimeout(() => {
|
|
||||||
try { if (!openedLater && openRightWorkbench(currentSessionId())) { openedLater = true; backToChat() } } catch { /* 忽略 */ }
|
|
||||||
}, delay)
|
|
||||||
}
|
|
||||||
setTimeout(() => { if (!openedLater) setMode('inline') }, 2600)
|
|
||||||
return undefined
|
return undefined
|
||||||
}, [])
|
}, [])
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
@ -682,11 +703,27 @@ export function apply(ctx) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 丞相会话里的卡片行:宿主公开的按工具名分发 slot,不需要自定义 session 事件。
|
||||||
|
function registerCardToolview() {
|
||||||
|
if (!ctx.slots || !isFn(ctx.slots.inject) || !isFn(ctx.slots.register)) return
|
||||||
|
try {
|
||||||
|
ctx.slots.inject('tool.call.toolview', () => ctx.slots.register({
|
||||||
|
name: 'tool.call.toolview',
|
||||||
|
key: 'sansheng_card',
|
||||||
|
}, SanshengCardRow))
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[sansheng] 注册卡片视图失败:', error && error.message ? error.message : error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 左侧导航行(宿主正式槽位,位置在记忆系统之后、更多之前)。
|
// 左侧导航行(宿主正式槽位,位置在记忆系统之后、更多之前)。
|
||||||
registerNavEntry()
|
registerNavEntry()
|
||||||
|
registerCardToolview()
|
||||||
|
|
||||||
// 右侧工作台标签类型:需在 apply 时就注册(宿主按类型 id 选正文 slot)。
|
// 原生右栏先等一个短窗口:若并行子插件已接管,rightTabOpener 会在 apply 时挂上,这里就跳过;
|
||||||
registerRightTabType()
|
// 没有子插件时才注册原生类型,保证只装主插件时首次点击即可打开。
|
||||||
|
const nativeRightTabTimer = setTimeout(() => { try { registerRightTabType() } catch { /* 忽略 */ } }, 500)
|
||||||
|
if (isFn(ctx.effect)) ctx.effect(() => () => clearTimeout(nativeRightTabTimer), 'sansheng: native right tab timer')
|
||||||
installRightDockPinning()
|
installRightDockPinning()
|
||||||
|
|
||||||
// dsh-go 原生面板:浏览器(无 dshGo 服务)或桥未就绪时,install 内部安静退出。
|
// dsh-go 原生面板:浏览器(无 dshGo 服务)或桥未就绪时,install 内部安静退出。
|
||||||
|
|
|
||||||
|
|
@ -243,9 +243,62 @@ function fmtModel(rec, options) {
|
||||||
return described.modelLabel
|
return described.modelLabel
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const DELIB_SEATS = ['zhongshu', 'menxia', 'shangshu']
|
||||||
|
const AVATAR_MIME = ['image/png', 'image/jpeg', 'image/webp']
|
||||||
|
const AVATAR_MAX_BYTES = 120 * 1024
|
||||||
|
|
||||||
|
function seatTone(seatId) {
|
||||||
|
return seatId === 'zhongshu' ? '#4c6ef5' : seatId === 'menxia' ? '#12b886' : seatId === 'shangshu' ? '#e8590c' : '#868e96'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 默认头像用席位名的第一个字;自定义字符或缩放后的图片优先。
|
||||||
|
function avatarNode(seatId, avatars, size = 34, highlight = false) {
|
||||||
|
const custom = avatars?.[seatId]
|
||||||
|
const ring = highlight ? { boxShadow: '0 0 0 2px ' + seatTone(seatId), borderRadius: '50%' } : {}
|
||||||
|
if (custom?.type === 'image') {
|
||||||
|
return h('img', {
|
||||||
|
src: custom.dataUrl, alt: (SEATS[seatId]?.name ?? seatId) + '头像', width: size, height: size,
|
||||||
|
style: { width: size, height: size, borderRadius: '50%', objectFit: 'cover', flex: '0 0 auto', ...ring },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const text = custom?.type === 'char' ? custom.char : (SEATS[seatId]?.name ?? seatId).slice(0, 1)
|
||||||
|
return h('span', {
|
||||||
|
'aria-hidden': 'true',
|
||||||
|
style: {
|
||||||
|
width: size, height: size, borderRadius: '50%', background: seatTone(seatId), color: '#fff',
|
||||||
|
display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto',
|
||||||
|
fontSize: Math.max(12, Math.round(size * 0.42)), fontWeight: 600, ...ring,
|
||||||
|
},
|
||||||
|
}, text)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 上传图先缩到 256×256 再入库;循环降质量保证 ≤120KB,绝不上传原图。
|
||||||
|
async function shrinkAvatar(file) {
|
||||||
|
if (!file || !AVATAR_MIME.includes(file.type)) throw new Error('头像只支持 PNG、JPEG 或 WebP 图片')
|
||||||
|
const bitmap = await createImageBitmap(file)
|
||||||
|
try {
|
||||||
|
const side = 256
|
||||||
|
const canvas = document.createElement('canvas')
|
||||||
|
canvas.width = side; canvas.height = side
|
||||||
|
const ctx2d = canvas.getContext('2d')
|
||||||
|
const scale = Math.max(side / bitmap.width, side / bitmap.height)
|
||||||
|
const width = Math.max(1, Math.round(bitmap.width * scale))
|
||||||
|
const height = Math.max(1, Math.round(bitmap.height * scale))
|
||||||
|
ctx2d.drawImage(bitmap, Math.round((side - width) / 2), Math.round((side - height) / 2), width, height)
|
||||||
|
for (const quality of [0.9, 0.8, 0.7, 0.6, 0.5]) {
|
||||||
|
const dataUrl = canvas.toDataURL('image/jpeg', quality)
|
||||||
|
if (Math.floor((dataUrl.length - dataUrl.indexOf(',') - 1) * 3 / 4) <= AVATAR_MAX_BYTES) return dataUrl
|
||||||
|
}
|
||||||
|
throw new Error('图片压缩后仍超过 120KB,请换一张更简单的图片')
|
||||||
|
} finally {
|
||||||
|
bitmap.close?.()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function WorkbenchV2(props) {
|
export function WorkbenchV2(props) {
|
||||||
const {
|
const {
|
||||||
onClose,
|
onClose,
|
||||||
|
sessionId,
|
||||||
resolveWorkspace,
|
resolveWorkspace,
|
||||||
navigateToSession,
|
navigateToSession,
|
||||||
openRightTab,
|
openRightTab,
|
||||||
|
|
@ -281,6 +334,16 @@ export function WorkbenchV2(props) {
|
||||||
const [approvals, setApprovals] = useState([])
|
const [approvals, setApprovals] = useState([])
|
||||||
const [pendingApprovals, setPendingApprovals] = useState([])
|
const [pendingApprovals, setPendingApprovals] = useState([])
|
||||||
const [approvalStatus, setApprovalStatus] = useState(null)
|
const [approvalStatus, setApprovalStatus] = useState(null)
|
||||||
|
const [deliberations, setDeliberations] = useState([])
|
||||||
|
const [deliberation, setDeliberation] = useState(null)
|
||||||
|
const [delibSelectedId, setDelibSelectedId] = useState(null)
|
||||||
|
const [delibDraft, setDelibDraft] = useState({ topic: '', taskId: '', requirementId: '', maxRounds: '3' })
|
||||||
|
const [delibEndNote, setDelibEndNote] = useState('')
|
||||||
|
const [delibBusy, setDelibBusy] = useState(false)
|
||||||
|
const [page, setPage] = useState('overview')
|
||||||
|
const [delibSettingsOpen, setDelibSettingsOpen] = useState(false)
|
||||||
|
const [avatarEdit, setAvatarEdit] = useState(null)
|
||||||
|
const [agentRuns, setAgentRuns] = useState([])
|
||||||
const [reqView, setReqView] = useState('requirements')
|
const [reqView, setReqView] = useState('requirements')
|
||||||
const [artifacts, setArtifacts] = useState([])
|
const [artifacts, setArtifacts] = useState([])
|
||||||
const [artifactDraft, setArtifactDraft] = useState({ title: '', path: '', summary: '' })
|
const [artifactDraft, setArtifactDraft] = useState({ title: '', path: '', summary: '' })
|
||||||
|
|
@ -322,7 +385,12 @@ export function WorkbenchV2(props) {
|
||||||
loadedProjectId.current = nextProjectId
|
loadedProjectId.current = nextProjectId
|
||||||
setView(projectView); setModels(modelCatalog); setMemory(memoryData)
|
setView(projectView); setModels(modelCatalog); setMemory(memoryData)
|
||||||
setMemoryDraft({ goal: memoryData?.goal ?? '', constraints: (memoryData?.constraints ?? []).join('\n'), acceptance: (memoryData?.acceptance ?? []).join('\n'), decisions: '' })
|
setMemoryDraft({ goal: memoryData?.goal ?? '', constraints: (memoryData?.constraints ?? []).join('\n'), acceptance: (memoryData?.acceptance ?? []).join('\n'), decisions: '' })
|
||||||
if (projectChanged) setSelectedTask(null)
|
if (projectChanged) {
|
||||||
|
setSelectedTask(null)
|
||||||
|
setDelibSelectedId(null)
|
||||||
|
setDeliberation(null)
|
||||||
|
setDeliberations([])
|
||||||
|
}
|
||||||
if (projectChanged || taskAnswerVersion.current === answerVersion) setTasks(previous => refreshList(taskRes.value?.tasks, previous, projectChanged))
|
if (projectChanged || taskAnswerVersion.current === answerVersion) setTasks(previous => refreshList(taskRes.value?.tasks, previous, projectChanged))
|
||||||
setArtifacts(previous => refreshList(artifactRes.value?.artifacts, previous, projectChanged))
|
setArtifacts(previous => refreshList(artifactRes.value?.artifacts, previous, projectChanged))
|
||||||
setRequirements(previous => refreshList(requirementData.value?.requirements, previous, projectChanged))
|
setRequirements(previous => refreshList(requirementData.value?.requirements, previous, projectChanged))
|
||||||
|
|
@ -384,6 +452,155 @@ export function WorkbenchV2(props) {
|
||||||
}
|
}
|
||||||
}, [projectId])
|
}, [projectId])
|
||||||
|
|
||||||
|
async function refreshDeliberations() {
|
||||||
|
if (!projectId) return
|
||||||
|
const [data, agentsData] = await Promise.allSettled([
|
||||||
|
request('deliberations', { projectId }),
|
||||||
|
request('agents', { projectId }),
|
||||||
|
])
|
||||||
|
if (!alive.current || loadedProjectId.current !== projectId) return
|
||||||
|
if (agentsData.status === 'fulfilled') setAgentRuns(Array.isArray(agentsData.value?.runs) ? agentsData.value.runs : [])
|
||||||
|
const list = Array.isArray(data.value?.deliberations) ? data.value.deliberations : []
|
||||||
|
setDeliberations(list)
|
||||||
|
const target = delibSelectedId || list.find(item => item.status === 'running')?.id || list[0]?.id || null
|
||||||
|
if (!target) { setDeliberation(null); return }
|
||||||
|
const full = await request('deliberation', { projectId, deliberationId: target })
|
||||||
|
if (!alive.current || loadedProjectId.current !== projectId) return
|
||||||
|
setDeliberation(full?.deliberation ?? null)
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (page !== 'deliberations' || !projectId) return undefined
|
||||||
|
let disposed = false
|
||||||
|
let running = false
|
||||||
|
let timer = null
|
||||||
|
const tick = async () => {
|
||||||
|
if (disposed || running) return
|
||||||
|
running = true
|
||||||
|
try { await refreshDeliberations() } catch (error) {
|
||||||
|
if (!disposed && alive.current) console.warn('[sansheng] 议政刷新失败:', error?.message ?? error)
|
||||||
|
} finally { running = false }
|
||||||
|
}
|
||||||
|
timer = setInterval(tick, 1500)
|
||||||
|
void tick()
|
||||||
|
return () => { disposed = true; if (timer !== null) clearInterval(timer) }
|
||||||
|
}, [page, projectId, delibSelectedId])
|
||||||
|
|
||||||
|
async function startDeliberation() {
|
||||||
|
if (!projectId || delibBusy) return
|
||||||
|
const topic = String(delibDraft.topic || '').trim()
|
||||||
|
if (!topic) { setError('请先填写议政议题'); return }
|
||||||
|
setDelibBusy(true); setError(null)
|
||||||
|
try {
|
||||||
|
const maxRounds = delibDraft.maxRounds === '' ? 3 : Number(delibDraft.maxRounds)
|
||||||
|
const data = await request('deliberationStart', {
|
||||||
|
projectId,
|
||||||
|
topic,
|
||||||
|
taskId: delibDraft.taskId || undefined,
|
||||||
|
requirementId: delibDraft.requirementId || undefined,
|
||||||
|
maxRounds,
|
||||||
|
originSessionId: sessionId || undefined,
|
||||||
|
})
|
||||||
|
if (!alive.current || loadedProjectId.current !== projectId) return
|
||||||
|
setDelibSelectedId(data.deliberation.id)
|
||||||
|
setDeliberation(data.deliberation)
|
||||||
|
setDelibDraft(previous => ({ ...previous, topic: '' }))
|
||||||
|
setNotice(data.receipt?.text || '议政已发起,已叫中书。')
|
||||||
|
} catch (error) {
|
||||||
|
if (alive.current) setError(error && error.message ? error.message : '议政发起失败')
|
||||||
|
} finally { if (alive.current) setDelibBusy(false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function endDeliberation() {
|
||||||
|
const deliberationId = delibSelectedId || deliberations.find(item => item.status === 'running')?.id
|
||||||
|
if (!projectId || !deliberationId || delibBusy) return
|
||||||
|
setDelibBusy(true); setError(null)
|
||||||
|
try {
|
||||||
|
await request('deliberationEnd', { projectId, deliberationId, note: delibEndNote.trim() || undefined })
|
||||||
|
if (!alive.current || loadedProjectId.current !== projectId) return
|
||||||
|
setDelibEndNote('')
|
||||||
|
setNotice('议政已结束,结论已记录。')
|
||||||
|
await refreshDeliberations()
|
||||||
|
} catch (error) {
|
||||||
|
if (alive.current) setError(error && error.message ? error.message : '结束议政失败')
|
||||||
|
} finally { if (alive.current) setDelibBusy(false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function stopDeliberation() {
|
||||||
|
const deliberationId = delibSelectedId || deliberations.find(item => item.status === 'running')?.id
|
||||||
|
if (!projectId || !deliberationId || delibBusy) return
|
||||||
|
setDelibBusy(true); setError(null)
|
||||||
|
try {
|
||||||
|
const data = await request('deliberationStop', { projectId, deliberationId, note: delibEndNote.trim() || undefined })
|
||||||
|
if (!alive.current || loadedProjectId.current !== projectId) return
|
||||||
|
setDelibEndNote('')
|
||||||
|
setNotice(data.receipt?.text || '议政已停止。')
|
||||||
|
setDeliberation(data.deliberation)
|
||||||
|
await refreshDeliberations()
|
||||||
|
} catch (error) {
|
||||||
|
if (alive.current) setError(error && error.message ? error.message : '停止议政失败')
|
||||||
|
} finally { if (alive.current) setDelibBusy(false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function retryDeliberation() {
|
||||||
|
const deliberationId = delibSelectedId || deliberations.find(item => item.status === 'running')?.id
|
||||||
|
if (!projectId || !deliberationId || delibBusy) return
|
||||||
|
setDelibBusy(true); setError(null)
|
||||||
|
try {
|
||||||
|
const data = await request('deliberationRetry', { projectId, deliberationId })
|
||||||
|
if (!alive.current || loadedProjectId.current !== projectId) return
|
||||||
|
setDeliberation(data.deliberation)
|
||||||
|
setNotice(data.delivery?.ok ? '已重试当前席位。' : '重试没有成功,页面会保留当前状态。')
|
||||||
|
await refreshDeliberations()
|
||||||
|
} catch (error) {
|
||||||
|
if (alive.current) setError(error && error.message ? error.message : '重试议政失败')
|
||||||
|
} finally { if (alive.current) setDelibBusy(false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveAvatar(seatId, payload = {}) {
|
||||||
|
if (!projectId) return
|
||||||
|
setDelibBusy(true); setError(null)
|
||||||
|
try {
|
||||||
|
const data = payload.clear
|
||||||
|
? await request('clearAvatar', { projectId, seatId })
|
||||||
|
: await request('setAvatar', { projectId, seatId, ...payload })
|
||||||
|
if (!alive.current || loadedProjectId.current !== projectId) return
|
||||||
|
setView(previous => {
|
||||||
|
if (!previous?.project) return previous
|
||||||
|
const avatars = { ...(previous.project.avatars ?? {}) }
|
||||||
|
if (data.avatar) avatars[seatId] = data.avatar
|
||||||
|
else delete avatars[seatId]
|
||||||
|
return { ...previous, project: { ...previous.project, avatars } }
|
||||||
|
})
|
||||||
|
setAvatarEdit(null)
|
||||||
|
setNotice(data.avatar ? '头像已更新。' : '头像已恢复默认。')
|
||||||
|
} catch (error) {
|
||||||
|
if (alive.current) setError(error && error.message ? error.message : '保存头像失败')
|
||||||
|
} finally { if (alive.current) setDelibBusy(false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pickAvatarFile(seatId, file) {
|
||||||
|
try {
|
||||||
|
const dataUrl = await shrinkAvatar(file)
|
||||||
|
await saveAvatar(seatId, { dataUrl })
|
||||||
|
} catch (error) {
|
||||||
|
if (alive.current) setError(error && error.message ? error.message : '图片处理失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function stopAgentRun(run) {
|
||||||
|
if (!projectId || delibBusy) return
|
||||||
|
setDelibBusy(true); setError(null)
|
||||||
|
try {
|
||||||
|
await request('agentStop', { projectId, runId: run.id, kind: run.kind })
|
||||||
|
if (!alive.current || loadedProjectId.current !== projectId) return
|
||||||
|
setNotice('已停止「' + (run.label || run.seatId || '后台子 Agent') + '」,不会再产生新动作。')
|
||||||
|
await refreshDeliberations()
|
||||||
|
} catch (error) {
|
||||||
|
if (alive.current) setError(error && error.message ? error.message : '停止失败')
|
||||||
|
} finally { if (alive.current) setDelibBusy(false) }
|
||||||
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!projectId || !selectionCache) return
|
if (!projectId || !selectionCache) return
|
||||||
const saved = selectionCache.get(projectId)
|
const saved = selectionCache.get(projectId)
|
||||||
|
|
@ -653,12 +870,14 @@ export function WorkbenchV2(props) {
|
||||||
: (notice ? h('p', { className: 'ssv-banner is-notice', role: 'status' }, notice) : null)
|
: (notice ? h('p', { className: 'ssv-banner is-notice', role: 'status' }, notice) : null)
|
||||||
|
|
||||||
function renderTopbar(title, extra) {
|
function renderTopbar(title, extra) {
|
||||||
const shortcuts = tab === 'overview'
|
const shortcuts = [
|
||||||
? [
|
...(tab === 'overview'
|
||||||
h('button', { type: 'button', key: 'memory', className: 'icon-btn', title: '记忆', 'aria-label': '记忆', onClick: () => setTab('memory') }, h(BookIcon)),
|
? [
|
||||||
h('button', { type: 'button', key: 'settings', className: 'icon-btn', title: '设置', 'aria-label': '设置', onClick: () => setTab('settings') }, h(SlidersIcon)),
|
h('button', { type: 'button', key: 'memory', className: 'icon-btn', title: '记忆', 'aria-label': '记忆', onClick: () => setTab('memory') }, h(BookIcon)),
|
||||||
]
|
h('button', { type: 'button', key: 'settings', className: 'icon-btn', title: '设置', 'aria-label': '设置', onClick: () => setTab('settings') }, h(SlidersIcon)),
|
||||||
: []
|
]
|
||||||
|
: []),
|
||||||
|
]
|
||||||
return h('header', { className: 'topbar' },
|
return h('header', { className: 'topbar' },
|
||||||
h('div', { className: 'topbar-title' },
|
h('div', { className: 'topbar-title' },
|
||||||
h('h1', null, title),
|
h('h1', null, title),
|
||||||
|
|
@ -1233,10 +1452,357 @@ export function WorkbenchV2(props) {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function renderDeliberations() {
|
||||||
|
const active = deliberations.find(item => item.status === 'running') || null
|
||||||
|
const shownId = delibSelectedId || active?.id || deliberations[0]?.id || null
|
||||||
|
const summary = deliberations.find(item => item.id === shownId) || null
|
||||||
|
const full = deliberation && deliberation.id === shownId ? deliberation : null
|
||||||
|
const shown = full || summary || null
|
||||||
|
const isActive = Boolean(shown && shown.status === 'running')
|
||||||
|
const seatLabel = id => (SEATS[id] && SEATS[id].label) || id || '—'
|
||||||
|
const stanceLabel = stance => stance === 'agree' ? '同意' : (stance === 'dissent' ? '有分歧' : '未表态')
|
||||||
|
const turnLabel = status => ({
|
||||||
|
waiting: '待叫席', delivering: '投递中', delivered: '已叫席', failed: '叫席失败', timeout: '未回',
|
||||||
|
}[status] || '待发言')
|
||||||
|
const taskOptions = tasks.filter(task => task.kind === 'workflow' || task.kind === 'execution')
|
||||||
|
const maxText = shown && shown.maxRounds > 0 ? String(shown.maxRounds) + ' 轮' : '不限'
|
||||||
|
const missingText = shown && Array.isArray(shown.missing) && shown.missing.length
|
||||||
|
? '未回:' + shown.missing.map(item => seatLabel(item.seatId) + '(第 ' + item.round + ' 轮 '
|
||||||
|
+ (item.reason === 'unknown' ? '发送结果未知' : item.reason === 'timeout' ? '超时' : '失败') + ')').join(';')
|
||||||
|
: ''
|
||||||
|
|
||||||
|
const startForm = h('section', { className: 'card', 'aria-label': '发起议政' },
|
||||||
|
h('h3', null, '发起议政'),
|
||||||
|
h('p', { className: 'foot-note' }, '三省各派代表,按中书 → 门下 → 尚书轮流发言;后发言者能看到前文。'),
|
||||||
|
h('label', { className: 'cfg-row', style: { display: 'block', marginTop: '10px' } }, '议题',
|
||||||
|
h('textarea', {
|
||||||
|
rows: 3, className: 'ssv-textarea', value: delibDraft.topic,
|
||||||
|
placeholder: '例如:多语言页面首版先做哪些语言?',
|
||||||
|
onChange: event => setDelibDraft(previous => ({ ...previous, topic: event.target.value })),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
h('div', { className: 'cfg-grid', style: { marginTop: '8px' } },
|
||||||
|
h('label', { className: 'cfg-row' }, '关联任务(可选)',
|
||||||
|
h('select', {
|
||||||
|
value: delibDraft.taskId,
|
||||||
|
onChange: event => setDelibDraft(previous => ({ ...previous, taskId: event.target.value })),
|
||||||
|
},
|
||||||
|
h('option', { value: '' }, '不关联任务'),
|
||||||
|
taskOptions.map(task => h('option', { key: task.id, value: task.id }, task.id + ' · ' + task.title)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
h('label', { className: 'cfg-row' }, '关联需求(可选)',
|
||||||
|
h('select', {
|
||||||
|
value: delibDraft.requirementId,
|
||||||
|
onChange: event => setDelibDraft(previous => ({ ...previous, requirementId: event.target.value })),
|
||||||
|
},
|
||||||
|
h('option', { value: '' }, '不关联需求'),
|
||||||
|
requirements.map(req => h('option', { key: req.id, value: req.id }, req.id + ' v' + req.revision + ' · ' + req.title)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
h('label', { className: 'cfg-row' }, '轮次上限',
|
||||||
|
h('input', {
|
||||||
|
type: 'number', min: 0, max: 20, value: delibDraft.maxRounds,
|
||||||
|
onChange: event => setDelibDraft(previous => ({ ...previous, maxRounds: event.target.value })),
|
||||||
|
}),
|
||||||
|
h('span', { className: 'foot-note' }, '默认 3;填 0 表示不限。'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
h('div', { className: 'ws-actions' },
|
||||||
|
h('button', { type: 'button', className: 'btn primary', disabled: delibBusy || Boolean(active), onClick: startDeliberation },
|
||||||
|
delibBusy ? '发起中…' : (active ? '已有进行中的议政' : '发起议政')),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
const activeHead = isActive
|
||||||
|
? h('section', { className: 'card', 'aria-label': '当前议政' },
|
||||||
|
h('div', { className: 'rc-head' },
|
||||||
|
h('h3', null, shown.topic),
|
||||||
|
h('span', { className: 'rc-status run' }, h('i'), '进行中'),
|
||||||
|
),
|
||||||
|
h('div', { className: 'req-meta' },
|
||||||
|
h('span', null, '第 ' + shown.round + ' 轮 / 上限 ' + maxText),
|
||||||
|
h('span', null, '当前当值:' + (shown.currentSeatLabel || seatLabel(shown.currentSeatId))),
|
||||||
|
h('span', null, '叫席:' + turnLabel(shown.turn && shown.turn.status)),
|
||||||
|
shown.turn && shown.turn.attempts ? h('span', null, '第 ' + shown.turn.attempts + ' 次投递') : null,
|
||||||
|
),
|
||||||
|
shown.turn && shown.turn.error ? h('p', { className: 'ssv-banner is-error' }, shown.turn.error) : null,
|
||||||
|
missingText ? h('p', { className: 'foot-note' }, missingText) : null,
|
||||||
|
shown.originSessionId ? h('p', { className: 'foot-note' }, '发起会话:' + shown.originSessionId.slice(0, 8)) : null,
|
||||||
|
shown.turn && ['failed', 'timeout'].includes(shown.turn.status)
|
||||||
|
? h('div', { className: 'ws-actions' },
|
||||||
|
h('button', { type: 'button', className: 'btn', disabled: delibBusy, onClick: retryDeliberation }, '重试当前席位'),
|
||||||
|
)
|
||||||
|
: null,
|
||||||
|
h('div', { className: 'ws-actions', style: { marginTop: '10px' } },
|
||||||
|
h('input', {
|
||||||
|
type: 'text', value: delibEndNote, placeholder: '结束或停止说明(可选)',
|
||||||
|
onChange: event => setDelibEndNote(event.target.value),
|
||||||
|
style: { flex: '1 1 180px' },
|
||||||
|
}),
|
||||||
|
h('button', { type: 'button', className: 'btn', disabled: delibBusy, onClick: endDeliberation }, '结束并收束'),
|
||||||
|
h('button', {
|
||||||
|
type: 'button', className: 'btn', disabled: delibBusy, onClick: stopDeliberation,
|
||||||
|
title: '立刻中断当前席位,不再叫下一位',
|
||||||
|
}, '立即停止'),
|
||||||
|
),
|
||||||
|
h('p', { className: 'foot-note' }, '「结束并收束」按正常流程生成结论;「立即停止」会立刻落状态、中断当前席位,之后不再叫下一位。'),
|
||||||
|
)
|
||||||
|
: null
|
||||||
|
|
||||||
|
const stoppedHead = shown && shown.status === 'stopped'
|
||||||
|
? h('section', { className: 'card', 'aria-label': '已停止的议政' },
|
||||||
|
h('div', { className: 'rc-head' },
|
||||||
|
h('h3', null, shown.topic),
|
||||||
|
h('span', { className: 'rc-status fail' }, h('i'), '已停止'),
|
||||||
|
),
|
||||||
|
h('div', { className: 'req-meta' },
|
||||||
|
h('span', null, '停在第 ' + (shown.stoppedTurn?.round ?? shown.round) + ' 轮'),
|
||||||
|
h('span', null, '停在:' + (shown.stoppedTurn?.seatLabel || seatLabel(shown.stoppedTurn?.seatId))),
|
||||||
|
shown.stoppedAt ? h('span', null, '停止时间:' + new Date(shown.stoppedAt).toLocaleString()) : null,
|
||||||
|
),
|
||||||
|
shown.stoppedNote ? h('p', { className: 'foot-note' }, '停止说明:' + shown.stoppedNote) : null,
|
||||||
|
h('p', { className: 'foot-note' }, '停止后不会再叫下一位;已有发言保留在下方转写。'),
|
||||||
|
)
|
||||||
|
: null
|
||||||
|
|
||||||
|
const transcript = shown && Array.isArray(shown.speeches) ? shown.speeches : []
|
||||||
|
const transcriptBlock = h('section', { className: 'card', 'aria-label': '议政转写' },
|
||||||
|
h('h3', null, '议政转写'),
|
||||||
|
transcript.length === 0
|
||||||
|
? h('p', { className: 'empty-note' }, '还没有发言。')
|
||||||
|
: h('div', { className: 'review-list' }, transcript.map(speech => h('article', { className: 'review-card', key: speech.id },
|
||||||
|
h('div', { className: 'rc-head' },
|
||||||
|
h('div', { className: 'rc-title' }, seatLabel(speech.seatId) + ' · 第 ' + speech.round + ' 轮'),
|
||||||
|
h('span', { className: 'rc-status ' + (speech.stance === 'agree' ? 'done' : speech.stance === 'dissent' ? 'fail' : 'review') },
|
||||||
|
h('i'), stanceLabel(speech.stance)),
|
||||||
|
),
|
||||||
|
h('p', { className: 'card-summary-text', style: { whiteSpace: 'pre-wrap' } }, speech.text),
|
||||||
|
speech.openIssues ? h('p', { className: 'foot-note' }, '未决:' + speech.openIssues) : null,
|
||||||
|
speech.pending ? h('p', { className: 'foot-note' }, '本席仍有待决问题。') : null,
|
||||||
|
))),
|
||||||
|
)
|
||||||
|
|
||||||
|
const conclusionBlock = shown && shown.conclusion
|
||||||
|
? h('section', { className: 'card', 'aria-label': '议政结论' },
|
||||||
|
h('h3', null, '结论'),
|
||||||
|
h('p', { className: 'card-summary-text', style: { whiteSpace: 'pre-wrap' } }, shown.conclusion.text),
|
||||||
|
h('p', { className: 'foot-note' }, shown.conclusion.needsUserDecision ? '有分歧或未回席位,需要用户决定。' : '三省已一致。'),
|
||||||
|
)
|
||||||
|
: null
|
||||||
|
|
||||||
|
const history = deliberations.filter(item => item.status !== 'running')
|
||||||
|
const historyBlock = h('section', { className: 'card', 'aria-label': '历史议政' },
|
||||||
|
h('h3', null, '历史议政'),
|
||||||
|
history.length === 0
|
||||||
|
? h('p', { className: 'empty-note' }, '还没有已收束的议政。')
|
||||||
|
: h('div', { className: 'review-list' }, history.map(item => h('article', {
|
||||||
|
className: 'review-card', key: item.id, style: { cursor: 'pointer' },
|
||||||
|
onClick: () => setDelibSelectedId(item.id),
|
||||||
|
},
|
||||||
|
h('div', { className: 'rc-head' },
|
||||||
|
h('div', { className: 'rc-title' }, item.topic),
|
||||||
|
h('span', { className: 'rc-status ' + (item.status === 'stopped' ? 'fail' : 'done') }, h('i'), item.status === 'stopped' ? '已停止' : '已收束'),
|
||||||
|
),
|
||||||
|
h('p', { className: 'foot-note' }, item.id + ' · 第 ' + item.round + ' 轮 · 发言 ' + item.speechCount + ' 条'
|
||||||
|
+ (item.status === 'stopped' && item.stoppedTurn ? ' · 停在第 ' + item.stoppedTurn.round + ' 轮 ' + (item.stoppedTurn.seatLabel || seatLabel(item.stoppedTurn.seatId)) : '')),
|
||||||
|
item.conclusion ? h('p', { className: 'card-summary-text' }, shortText(item.conclusion.text, 140)) : null,
|
||||||
|
))),
|
||||||
|
)
|
||||||
|
|
||||||
|
return h('div', { className: 'page' },
|
||||||
|
renderTopbar('三省议政', [
|
||||||
|
h('button', { type: 'button', className: 'btn', disabled: delibBusy, onClick: () => { void refreshDeliberations().catch(() => {}) } }, '刷新'),
|
||||||
|
active && shown && shown.id !== active.id
|
||||||
|
? h('button', { type: 'button', className: 'btn primary', onClick: () => setDelibSelectedId(active.id) }, '回到进行中')
|
||||||
|
: null,
|
||||||
|
]),
|
||||||
|
startForm,
|
||||||
|
activeHead,
|
||||||
|
stoppedHead,
|
||||||
|
transcriptBlock,
|
||||||
|
conclusionBlock,
|
||||||
|
historyBlock,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderChatDeliberations() {
|
||||||
|
const avatars = view?.project?.avatars ?? {}
|
||||||
|
const active = deliberations.find(item => item.status === 'running') || null
|
||||||
|
const shownId = delibSelectedId || active?.id || deliberations[0]?.id || null
|
||||||
|
const summary = deliberations.find(item => item.id === shownId) || null
|
||||||
|
const full = deliberation && deliberation.id === shownId ? deliberation : null
|
||||||
|
const shown = full || summary || null
|
||||||
|
const isActive = Boolean(shown && shown.status === 'running')
|
||||||
|
const currentSeat = isActive ? (shown.currentSeatId || shown.turn?.seatId || null) : null
|
||||||
|
const seatLabel = id => (SEATS[id] && (SEATS[id].name || SEATS[id].label)) || id || '—'
|
||||||
|
const statusText = !shown ? '还没有议政' : isActive
|
||||||
|
? '第 ' + shown.round + ' 轮 · ' + (currentSeat ? seatLabel(currentSeat) + '正在说' : '等待叫席')
|
||||||
|
: shown.status === 'stopped'
|
||||||
|
? '停在第 ' + (shown.stoppedTurn?.round ?? shown.round) + ' 轮 · ' + (shown.stoppedTurn?.seatLabel || seatLabel(shown.stoppedTurn?.seatId))
|
||||||
|
: '已收束 · 第 ' + shown.round + ' 轮'
|
||||||
|
const statusTone = isActive ? 'run' : shown?.status === 'stopped' ? 'fail' : 'done'
|
||||||
|
|
||||||
|
const statusBar = h('div', { className: 'card', style: { display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', marginBottom: 6 } },
|
||||||
|
h('span', { className: 'rc-status ' + statusTone }, h('i'), isActive ? '进行中' : shown?.status === 'stopped' ? '已停止' : '已收束'),
|
||||||
|
h('span', { style: { fontSize: 13 } }, statusText),
|
||||||
|
h('span', { style: { flex: 1 } }),
|
||||||
|
shown?.id ? h('span', { className: 'foot-note' }, shown.id) : null,
|
||||||
|
isActive ? h('button', {
|
||||||
|
type: 'button', className: 'btn', title: '立刻中断当前席位,不再叫下一位',
|
||||||
|
style: { height: 24, padding: '0 8px', fontSize: 12 }, disabled: delibBusy, onClick: stopDeliberation,
|
||||||
|
}, '停止') : null,
|
||||||
|
)
|
||||||
|
|
||||||
|
const seatRow = h('div', { style: { display: 'flex', gap: 10, alignItems: 'center', margin: '2px 0 8px' } },
|
||||||
|
DELIB_SEATS.map(seatId => h('button', {
|
||||||
|
key: seatId, type: 'button', title: '换' + seatLabel(seatId) + '头像',
|
||||||
|
style: {
|
||||||
|
display: 'flex', alignItems: 'center', gap: 6, background: 'none', border: 'none', cursor: 'pointer', padding: 2,
|
||||||
|
opacity: !isActive || currentSeat === seatId ? 1 : 0.5,
|
||||||
|
},
|
||||||
|
onClick: () => setAvatarEdit(previous => previous?.seatId === seatId ? null : { seatId, char: '' }),
|
||||||
|
}, avatarNode(seatId, avatars, 30, isActive && currentSeat === seatId), h('span', { style: { fontSize: 12 } }, seatLabel(seatId)))),
|
||||||
|
h('span', { style: { flex: 1 } }),
|
||||||
|
h('button', {
|
||||||
|
type: 'button', className: 'btn', style: { height: 24, padding: '0 8px', fontSize: 12 },
|
||||||
|
onClick: () => setDelibSettingsOpen(value => !value),
|
||||||
|
}, '设置'),
|
||||||
|
)
|
||||||
|
|
||||||
|
const settings = delibSettingsOpen ? h('div', { className: 'card', style: { padding: 10, marginBottom: 6, display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'end' } },
|
||||||
|
h('label', { className: 'cfg-row' }, '轮次上限',
|
||||||
|
h('input', {
|
||||||
|
type: 'number', min: 0, max: 20, value: delibDraft.maxRounds, style: { width: 64 },
|
||||||
|
onChange: event => setDelibDraft(prev => ({ ...prev, maxRounds: event.target.value })),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
h('label', { className: 'cfg-row' }, '关联任务',
|
||||||
|
h('select', { value: delibDraft.taskId, onChange: event => setDelibDraft(prev => ({ ...prev, taskId: event.target.value })) },
|
||||||
|
h('option', { value: '' }, '不关联'),
|
||||||
|
tasks.filter(task => task.kind === 'workflow' || task.kind === 'execution').map(task => h('option', { key: task.id, value: task.id }, task.id + ' ' + task.title)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
h('label', { className: 'cfg-row' }, '关联需求',
|
||||||
|
h('select', { value: delibDraft.requirementId, onChange: event => setDelibDraft(prev => ({ ...prev, requirementId: event.target.value })) },
|
||||||
|
h('option', { value: '' }, '不关联'),
|
||||||
|
requirements.map(req => h('option', { key: req.id, value: req.id }, req.id + ' v' + req.revision + ' ' + req.title)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
h('span', { className: 'foot-note' }, '默认 3 轮,填 0 表示不限'),
|
||||||
|
) : null
|
||||||
|
|
||||||
|
const avatarEditor = avatarEdit ? h('div', { className: 'card', style: { padding: 10, marginBottom: 6 } },
|
||||||
|
h('div', { style: { display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' } },
|
||||||
|
avatarNode(avatarEdit.seatId, avatars, 40),
|
||||||
|
h('label', { className: 'btn', style: { cursor: 'pointer' } }, '选图片',
|
||||||
|
h('input', {
|
||||||
|
type: 'file', accept: 'image/png,image/jpeg,image/webp', style: { display: 'none' },
|
||||||
|
onChange: event => { const file = event.target.files?.[0]; if (file) void pickAvatarFile(avatarEdit.seatId, file); event.target.value = '' },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
h('input', {
|
||||||
|
type: 'text', maxLength: 8, placeholder: '或填一个字/emoji', value: avatarEdit.char, style: { width: 130 },
|
||||||
|
onChange: event => setAvatarEdit(prev => ({ ...prev, char: event.target.value })),
|
||||||
|
}),
|
||||||
|
h('button', { type: 'button', className: 'btn primary', disabled: delibBusy || !avatarEdit.char.trim(), onClick: () => void saveAvatar(avatarEdit.seatId, { char: avatarEdit.char.trim() }) }, '保存字符'),
|
||||||
|
h('button', { type: 'button', className: 'btn', disabled: delibBusy, onClick: () => void saveAvatar(avatarEdit.seatId, { clear: true }) }, '恢复默认'),
|
||||||
|
h('span', { style: { flex: 1 } }),
|
||||||
|
h('button', { type: 'button', className: 'btn', onClick: () => setAvatarEdit(null) }, '关闭'),
|
||||||
|
),
|
||||||
|
h('p', { className: 'foot-note' }, '图片缩到 256×256 后保存,限 120KB;默认头像沿用席位名。'),
|
||||||
|
) : null
|
||||||
|
|
||||||
|
const transcript = shown?.speeches ?? []
|
||||||
|
const bubbles = transcript.length === 0
|
||||||
|
? h('p', { className: 'empty-note', style: { textAlign: 'center', padding: '34px 0' } }, '还没开始议政,说一句就能开。')
|
||||||
|
: h('div', { style: { display: 'flex', flexDirection: 'column', gap: 12, padding: '6px 2px 10px' } },
|
||||||
|
transcript.map(speech => h('div', { key: speech.id, style: { display: 'flex', gap: 10, alignItems: 'flex-start' } },
|
||||||
|
avatarNode(speech.seatId, avatars, 32, isActive && currentSeat === speech.seatId),
|
||||||
|
h('div', { style: { maxWidth: '78%' } },
|
||||||
|
h('div', { style: { fontSize: 12, color: '#6b7280', marginBottom: 3 } },
|
||||||
|
seatLabel(speech.seatId) + ' · 第 ' + speech.round + ' 轮'
|
||||||
|
+ (speech.stance === 'dissent' ? ' · 有分歧' : speech.pending ? ' · 仍有待决' : '')),
|
||||||
|
h('div', {
|
||||||
|
style: {
|
||||||
|
background: speech.seatId === 'zhongshu' ? '#eef2ff' : speech.seatId === 'menxia' ? '#e6fcf5' : '#fff4e6',
|
||||||
|
borderRadius: 12, padding: '9px 12px', fontSize: 14, lineHeight: 1.65, whiteSpace: 'pre-wrap',
|
||||||
|
},
|
||||||
|
}, speech.text),
|
||||||
|
speech.openIssues ? h('div', { className: 'foot-note', style: { marginTop: 4 } }, '未决:' + speech.openIssues) : null,
|
||||||
|
),
|
||||||
|
)),
|
||||||
|
)
|
||||||
|
const stoppedNote = shown?.status === 'stopped'
|
||||||
|
? h('p', { className: 'foot-note', style: { textAlign: 'center', padding: '5px 0 8px' } },
|
||||||
|
'停在第 ' + (shown.stoppedTurn?.round ?? shown.round) + ' 轮 · ' + (shown.stoppedTurn?.seatLabel || seatLabel(shown.stoppedTurn?.seatId))
|
||||||
|
+ ',不会再叫下一位。' + (shown.stoppedNote ? ' 说明:' + shown.stoppedNote : ''))
|
||||||
|
: null
|
||||||
|
const conclusion = shown?.conclusion && !isActive
|
||||||
|
? h('section', { className: 'card', style: { marginTop: 8 } },
|
||||||
|
h('h3', null, '结论'),
|
||||||
|
h('p', { className: 'card-summary-text', style: { whiteSpace: 'pre-wrap' } }, shown.conclusion.text),
|
||||||
|
)
|
||||||
|
: null
|
||||||
|
|
||||||
|
const composer = h('div', { className: 'card', style: { display: 'flex', gap: 8, alignItems: 'center', marginTop: 8, padding: 8 } },
|
||||||
|
h('input', {
|
||||||
|
type: 'text', value: delibDraft.topic, placeholder: isActive ? '这一场还在进行,先看他们说完' : '说一句要三省议的事…',
|
||||||
|
disabled: Boolean(active), style: { flex: 1, minWidth: 0 },
|
||||||
|
onChange: event => setDelibDraft(prev => ({ ...prev, topic: event.target.value })),
|
||||||
|
onKeyDown: event => { if (event.key === 'Enter' && !active) void startDeliberation() },
|
||||||
|
}),
|
||||||
|
h('button', { type: 'button', className: 'btn primary', disabled: delibBusy || Boolean(active) || !delibDraft.topic.trim(), onClick: startDeliberation },
|
||||||
|
delibBusy ? '发起中…' : '发起'),
|
||||||
|
)
|
||||||
|
|
||||||
|
const runsBlock = agentRuns.length
|
||||||
|
? h('section', { className: 'card', style: { marginTop: 8 } },
|
||||||
|
h('h3', null, '后台子 Agent'),
|
||||||
|
h('div', { className: 'review-list' }, agentRuns.map(run => h('div', { key: run.id, className: 'review-card', style: { display: 'flex', alignItems: 'center', gap: 8 } },
|
||||||
|
h('span', { className: 'rc-title', style: { flex: 1, fontSize: 13 } },
|
||||||
|
(run.label || run.seatId) + (run.deliberationId ? ' · ' + run.deliberationId + ' 第 ' + run.round + ' 轮' : '')
|
||||||
|
+ (run.kind === 'order' && run.brief ? ' · ' + shortText(run.brief, 36) : '')),
|
||||||
|
h('button', { type: 'button', className: 'btn', disabled: delibBusy, onClick: () => void stopAgentRun(run) }, '停止'),
|
||||||
|
))),
|
||||||
|
)
|
||||||
|
: null
|
||||||
|
|
||||||
|
const history = deliberations.filter(item => item.status !== 'running')
|
||||||
|
const historyBlock = history.length
|
||||||
|
? h('section', { className: 'card', style: { marginTop: 8 } },
|
||||||
|
h('h3', null, '历史议政'),
|
||||||
|
h('div', { className: 'review-list' }, history.slice(0, 6).map(item => h('button', {
|
||||||
|
key: item.id, type: 'button', className: 'review-card', style: { textAlign: 'left', cursor: 'pointer' },
|
||||||
|
onClick: () => setDelibSelectedId(item.id),
|
||||||
|
},
|
||||||
|
h('span', { className: 'rc-title' }, item.topic),
|
||||||
|
h('span', { className: 'foot-note' }, item.id + ' · ' + (item.status === 'stopped' ? '已停止' : '已收束') + ' · 发言 ' + item.speechCount + ' 条'),
|
||||||
|
))),
|
||||||
|
)
|
||||||
|
: null
|
||||||
|
|
||||||
|
return h('div', { className: 'page' },
|
||||||
|
renderTopbar('三省议政', [
|
||||||
|
h('button', { type: 'button', className: 'btn', disabled: delibBusy, onClick: () => { void refreshDeliberations().catch(() => {}) } }, '刷新'),
|
||||||
|
]),
|
||||||
|
statusBar,
|
||||||
|
seatRow,
|
||||||
|
settings,
|
||||||
|
avatarEditor,
|
||||||
|
h('div', { className: 'card', style: { padding: '2px 10px' } }, bubbles, stoppedNote),
|
||||||
|
composer,
|
||||||
|
runsBlock,
|
||||||
|
conclusion,
|
||||||
|
historyBlock,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function renderPage() {
|
function renderPage() {
|
||||||
if (phase === 'loading') return h('div', { className: 'page' }, h('p', { className: 'empty-note' }, '正在载入工作台…'))
|
if (phase === 'loading') return h('div', { className: 'page' }, h('p', { className: 'empty-note' }, '正在载入工作台…'))
|
||||||
if (phase === 'no-workspace') return h('div', { className: 'page' }, h('p', { className: 'empty-note' }, '请先在宿主中选择或建立一个项目工作区,再打开三省六部工作台。'))
|
if (phase === 'no-workspace') return h('div', { className: 'page' }, h('p', { className: 'empty-note' }, '请先在宿主中选择或建立一个项目工作区,再打开三省六部工作台。'))
|
||||||
if (phase === 'error' && !view) return h('div', { className: 'page' }, h('p', { className: 'ssv-banner is-error', role: 'alert' }, error || '工作台加载失败'), errorRetryable ? h('div', { className: 'ws-actions' }, h('button', { type: 'button', className: 'btn primary', onClick: loadProject }, '重试')) : null)
|
if (phase === 'error' && !view) return h('div', { className: 'page' }, h('p', { className: 'ssv-banner is-error', role: 'alert' }, error || '工作台加载失败'), errorRetryable ? h('div', { className: 'ws-actions' }, h('button', { type: 'button', className: 'btn primary', onClick: loadProject }, '重试')) : null)
|
||||||
|
if (page === 'deliberations') return renderChatDeliberations()
|
||||||
if (tab === 'memory') return renderMemory()
|
if (tab === 'memory') return renderMemory()
|
||||||
if (tab === 'settings') return renderSettings()
|
if (tab === 'settings') return renderSettings()
|
||||||
return renderOverview()
|
return renderOverview()
|
||||||
|
|
@ -1246,9 +1812,14 @@ export function WorkbenchV2(props) {
|
||||||
h('div', { className: 'main' },
|
h('div', { className: 'main' },
|
||||||
h('div', { className: 'panel-top' },
|
h('div', { className: 'panel-top' },
|
||||||
h('div', { className: 'brand' }, h('span', { className: 'seal' }, '三省六部'), h('span', { className: 'sub' }, 'DSH 工作台')),
|
h('div', { className: 'brand' }, h('span', { className: 'seal' }, '三省六部'), h('span', { className: 'sub' }, 'DSH 工作台')),
|
||||||
tab !== 'overview' ? h('div', { className: 'panel-actions' },
|
tab !== 'overview' || page !== 'overview' ? h('div', { className: 'panel-actions' },
|
||||||
h('button', { type: 'button', className: 'btn', onClick: () => setTab('overview') }, '← 总览'),
|
h('button', { type: 'button', className: 'btn' + (page === 'overview' && tab === 'overview' ? ' primary' : ''), onClick: () => { setPage('overview'); setTab('overview') } }, '概览'),
|
||||||
) : null,
|
h('button', { type: 'button', className: 'btn' + (page === 'deliberations' ? ' primary' : ''), onClick: () => setPage('deliberations') }, '议政'),
|
||||||
|
tab !== 'overview' ? h('button', { type: 'button', className: 'btn', onClick: () => setTab('overview') }, '← 总览') : null,
|
||||||
|
) : h('div', { className: 'panel-actions' },
|
||||||
|
h('button', { type: 'button', className: 'btn primary', onClick: () => { setPage('overview'); setTab('overview') } }, '概览'),
|
||||||
|
h('button', { type: 'button', className: 'btn', onClick: () => setPage('deliberations') }, '议政'),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
statusBanner,
|
statusBanner,
|
||||||
renderPage(),
|
renderPage(),
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,11 @@ function requireTaskId(payload) {
|
||||||
if (typeof id !== 'string' || id.trim() === '') throw bad('缺少 taskId')
|
if (typeof id !== 'string' || id.trim() === '') throw bad('缺少 taskId')
|
||||||
return id
|
return id
|
||||||
}
|
}
|
||||||
|
function requireDeliberationId(payload) {
|
||||||
|
const id = payload?.deliberationId
|
||||||
|
if (typeof id !== 'string' || id.trim() === '') throw bad('缺少 deliberationId')
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
// 生成 POST /api/sansheng 的处理函数:{endpoint,payload} -> {ok,value}|{ok,error}
|
// 生成 POST /api/sansheng 的处理函数:{endpoint,payload} -> {ok,value}|{ok,error}
|
||||||
export function createApiHandler(service) {
|
export function createApiHandler(service) {
|
||||||
|
|
@ -88,6 +93,40 @@ export function createApiHandler(service) {
|
||||||
return { ok: true, value: await service.approvals(requireProjectId(payload)) }
|
return { ok: true, value: await service.approvals(requireProjectId(payload)) }
|
||||||
case 'leadReports':
|
case 'leadReports':
|
||||||
return { ok: true, value: await service.leadReports(requireProjectId(payload)) }
|
return { ok: true, value: await service.leadReports(requireProjectId(payload)) }
|
||||||
|
case 'cardGet':
|
||||||
|
return { ok: true, value: await service.cardGet(payload?.cardId) }
|
||||||
|
case 'cardAnswer':
|
||||||
|
return { ok: true, value: await service.cardAnswer(payload?.cardId, payload?.choice) }
|
||||||
|
case 'cards':
|
||||||
|
return { ok: true, value: await service.cards(requireProjectId(payload)) }
|
||||||
|
case 'deliberations':
|
||||||
|
return { ok: true, value: await service.deliberations(requireProjectId(payload)) }
|
||||||
|
case 'deliberation':
|
||||||
|
return { ok: true, value: await service.deliberation(requireProjectId(payload), requireDeliberationId(payload)) }
|
||||||
|
case 'deliberationStart':
|
||||||
|
return { ok: true, value: await service.startDeliberation(requireProjectId(payload), payload ?? {}) }
|
||||||
|
case 'deliberationEnd':
|
||||||
|
return { ok: true, value: await service.endDeliberation(requireProjectId(payload), requireDeliberationId(payload), payload ?? {}) }
|
||||||
|
case 'deliberationStop':
|
||||||
|
return { ok: true, value: await service.stopDeliberation(requireProjectId(payload), requireDeliberationId(payload), payload ?? {}) }
|
||||||
|
case 'order':
|
||||||
|
return { ok: true, value: await service.startOrder(requireProjectId(payload), payload ?? {}, {}) }
|
||||||
|
case 'agents':
|
||||||
|
return { ok: true, value: await service.agentRuns(requireProjectId(payload)) }
|
||||||
|
case 'agentStop':
|
||||||
|
return { ok: true, value: await service.stopAgentRun(requireProjectId(payload), payload?.runId, payload?.kind) }
|
||||||
|
case 'setAvatar': {
|
||||||
|
const seatId = payload?.seatId
|
||||||
|
if (!SEAT_IDS.includes(seatId)) throw bad('未知席位')
|
||||||
|
return { ok: true, value: await service.setAvatar(requireProjectId(payload), seatId, payload ?? {}) }
|
||||||
|
}
|
||||||
|
case 'clearAvatar': {
|
||||||
|
const seatId = payload?.seatId
|
||||||
|
if (!SEAT_IDS.includes(seatId)) throw bad('未知席位')
|
||||||
|
return { ok: true, value: await service.clearAvatar(requireProjectId(payload), seatId) }
|
||||||
|
}
|
||||||
|
case 'deliberationRetry':
|
||||||
|
return { ok: true, value: await service.retryDeliberation(requireProjectId(payload), requireDeliberationId(payload)) }
|
||||||
case 'seatStatus':
|
case 'seatStatus':
|
||||||
return { ok: true, value: await service.statusSnapshot(payload?.projectId) }
|
return { ok: true, value: await service.statusSnapshot(payload?.projectId) }
|
||||||
case 'approvalAnswer': {
|
case 'approvalAnswer': {
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ export function redactApprovalDetail(detail) {
|
||||||
return { text: text.slice(0, 500), code: code.slice(0, 200) }
|
return { text: text.slice(0, 500), code: code.slice(0, 200) }
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createApprovalCenter({ ctx = {}, resolveSeatBySessionId, now = () => Date.now(), idFactory = randomUUID } = {}) {
|
export function createApprovalCenter({ ctx = {}, resolveSeatBySessionId, now = () => Date.now(), idFactory = randomUUID, onPending = null } = {}) {
|
||||||
if (typeof resolveSeatBySessionId !== 'function') throw new ApprovalCenterError('sansheng/approval-config', '需要 resolveSeatBySessionId')
|
if (typeof resolveSeatBySessionId !== 'function') throw new ApprovalCenterError('sansheng/approval-config', '需要 resolveSeatBySessionId')
|
||||||
const clock = typeof now === 'function' ? now : () => Number(now)
|
const clock = typeof now === 'function' ? now : () => Number(now)
|
||||||
const pending = new Map()
|
const pending = new Map()
|
||||||
|
|
@ -87,6 +87,9 @@ export function createApprovalCenter({ ctx = {}, resolveSeatBySessionId, now = (
|
||||||
}
|
}
|
||||||
pending.set(id, entry)
|
pending.set(id, entry)
|
||||||
emit({ type: 'open', entry: publicEntry(entry) })
|
emit({ type: 'open', entry: publicEntry(entry) })
|
||||||
|
if (typeof onPending === 'function') {
|
||||||
|
try { onPending(publicEntry(entry)) } catch { /* 通知失败不影响原生审批 */ }
|
||||||
|
}
|
||||||
|
|
||||||
// 工作台与原生卡共用一个结果。原生卡的应答按 DSH 的结果码透传。
|
// 工作台与原生卡共用一个结果。原生卡的应答按 DSH 的结果码透传。
|
||||||
void Promise.resolve().then(async () => {
|
void Promise.resolve().then(async () => {
|
||||||
|
|
@ -113,7 +116,12 @@ export function createApprovalCenter({ ctx = {}, resolveSeatBySessionId, now = (
|
||||||
if (!OUTCOME_BY_CHOICE.has(choice)) throw new ApprovalCenterError('sansheng/approval-invalid', 'choice 必须是 allow 或 reject')
|
if (!OUTCOME_BY_CHOICE.has(choice)) throw new ApprovalCenterError('sansheng/approval-invalid', 'choice 必须是 allow 或 reject')
|
||||||
const entry = pending.get(cleanText(id))
|
const entry = pending.get(cleanText(id))
|
||||||
if (!entry) throw new ApprovalCenterError('sansheng/approval-stale', '审批已处理或不存在')
|
if (!entry) throw new ApprovalCenterError('sansheng/approval-stale', '审批已处理或不存在')
|
||||||
if (identity.projectId !== entry.projectId || identity.seatId !== entry.seatId || identity.sessionId !== entry.sessionId) {
|
if (identity.projectId !== entry.projectId) {
|
||||||
|
throw new ApprovalCenterError('sansheng/approval-forbidden', '审批归属不匹配')
|
||||||
|
}
|
||||||
|
// 丞相可以代表本项目回答任一席的审批;其他席位仍必须精确匹配自己的申请。
|
||||||
|
const leadAnswer = identity.seatId === 'lead'
|
||||||
|
if (!leadAnswer && (identity.seatId !== entry.seatId || identity.sessionId !== entry.sessionId)) {
|
||||||
throw new ApprovalCenterError('sansheng/approval-forbidden', '审批归属不匹配')
|
throw new ApprovalCenterError('sansheng/approval-forbidden', '审批归属不匹配')
|
||||||
}
|
}
|
||||||
const ok = finalize(entry, OUTCOME_BY_CHOICE.get(choice))
|
const ok = finalize(entry, OUTCOME_BY_CHOICE.get(choice))
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
// 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。
|
||||||
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', 'sansheng-deliberation'])
|
||||||
|
|
||||||
function cleanText(value) { return typeof value === 'string' ? value.trim() : '' }
|
function cleanText(value) { return typeof value === 'string' ? value.trim() : '' }
|
||||||
|
|
||||||
|
|
@ -11,12 +11,13 @@ export function userMessageSource({ clientTimeZone, trusted = false } = {}) {
|
||||||
return source
|
return source
|
||||||
}
|
}
|
||||||
|
|
||||||
export function internalSource(kind, { seatId, taskId, reportId, at } = {}) {
|
export function internalSource(kind, { seatId, taskId, reportId, deliberationId, at } = {}) {
|
||||||
if (!INTERNAL_SOURCE_KINDS.includes(kind)) throw new Error('内部消息来源非法:' + String(kind))
|
if (!INTERNAL_SOURCE_KINDS.includes(kind)) throw new Error('内部消息来源非法:' + String(kind))
|
||||||
const source = { kind }
|
const source = { kind }
|
||||||
if (cleanText(seatId)) source.seatId = seatId
|
if (cleanText(seatId)) source.seatId = seatId
|
||||||
if (cleanText(taskId)) source.taskId = taskId
|
if (cleanText(taskId)) source.taskId = taskId
|
||||||
if (cleanText(reportId)) source.reportId = reportId
|
if (cleanText(reportId)) source.reportId = reportId
|
||||||
|
if (cleanText(deliberationId)) source.deliberationId = deliberationId
|
||||||
if (Number.isFinite(at)) source.at = at
|
if (Number.isFinite(at)) source.at = at
|
||||||
return source
|
return source
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -47,9 +47,10 @@ export function createModelSync({ store, globalStore, host, normalizeCatalog, no
|
||||||
function setStatus(projectId, seatId, patch) {
|
function setStatus(projectId, seatId, patch) {
|
||||||
const key = keyOf(projectId, seatId)
|
const key = keyOf(projectId, seatId)
|
||||||
const previous = statuses.get(key) ?? {}
|
const previous = statuses.get(key) ?? {}
|
||||||
|
// agentRef 是活 Agent,不能深拷贝;状态对外只通过 publicStatus 去掉它。
|
||||||
const next = { ...previous, ...patch, updatedAt: clock() }
|
const next = { ...previous, ...patch, updatedAt: clock() }
|
||||||
statuses.set(key, next)
|
statuses.set(key, next)
|
||||||
return copy(next)
|
return publicStatus(next)
|
||||||
}
|
}
|
||||||
function publicStatus(record) {
|
function publicStatus(record) {
|
||||||
if (!record) return null
|
if (!record) return null
|
||||||
|
|
|
||||||
|
|
@ -17,6 +17,10 @@ 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_lead_secretary 按 role 启动——zhongshu 对接中书,menxia 对接门下,shangshu 对接尚书,requirement 是记室、记录用户需求;启动记室时把用户原话放进 brief。主簿与记室在后台只读调查和记录,不阻塞你和用户聊天,也不得代办发布、批准或派工。',
|
||||||
|
'向中书下达具体指令、需要留回执时,用 sansheng_order:工具先返回回执(谁下的、关联任务或需求版本),中书接令子 Agent 核对后把用户原话和要点交给中书主席。不要用普通聊天消息替代接令回执。',
|
||||||
|
'收到来源为 sansheng-report 的省级正式回报,或后台主簿或记室交回的结果时,立即用零基础白话向用户说明:发生了什么、对当前任务的影响、是否需要用户决定、下一步;不要等其它省或后台主簿或记室。向用户提问也只用零基础白话,一次问一个关键问题。',
|
||||||
|
'需要用户回答或审批时用 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 下派。扩大范围、换目标、拒绝或撤回时清除预授权,等新的授权。',
|
||||||
'需求清单保存用户原话和已确认内容。用户已确认的范围、非目标和验收标准保持原样;未确认的可留空交中书补齐。需求改变时更新同一条需求并携带 expectedRevision。新需求涉及已知偏好时可按已知偏好处理,避免重复问。',
|
'需求清单保存用户原话和已确认内容。用户已确认的范围、非目标和验收标准保持原样;未确认的可留空交中书补齐。需求改变时更新同一条需求并携带 expectedRevision。新需求涉及已知偏好时可按已知偏好处理,避免重复问。',
|
||||||
'工作独立且会占用用户等待时间时,用 sansheng_lead_background 分出需求整理、派工准备、跟踪或反馈。可同时安排互不依赖的工作,收到启动回执后继续当前对话。助手回报是建议,检查任务和需求版本后再正式办理。',
|
'工作独立且会占用用户等待时间时,用 sansheng_lead_background 分出需求整理、派工准备、跟踪或反馈。可同时安排互不依赖的工作,收到启动回执后继续当前对话。助手回报是建议,检查任务和需求版本后再正式办理。',
|
||||||
|
|
|
||||||
|
|
@ -43,6 +43,7 @@ export function projectView(project, seatExtras = {}) {
|
||||||
workspaceId: project.workspaceId ?? null,
|
workspaceId: project.workspaceId ?? null,
|
||||||
path: project.path ?? null,
|
path: project.path ?? null,
|
||||||
status: project.status,
|
status: project.status,
|
||||||
|
avatars: { ...(project.avatars ?? {}) },
|
||||||
seats: SEAT_IDS.map(id => seatView(id, project.seats[id], seatExtras[id] ?? {})),
|
seats: SEAT_IDS.map(id => seatView(id, project.seats[id], seatExtras[id] ?? {})),
|
||||||
groups: {
|
groups: {
|
||||||
lead: [...SEAT_GROUPS.lead],
|
lead: [...SEAT_GROUPS.lead],
|
||||||
|
|
@ -60,6 +61,180 @@ const REQUIREMENT_TEXT_FIELDS = [
|
||||||
// 中书拟案时只能补这些空缺字段;标题、用户原话和判断仍由丞相维护。
|
// 中书拟案时只能补这些空缺字段;标题、用户原话和判断仍由丞相维护。
|
||||||
const REQUIREMENT_FILL_FIELDS = ['scope', 'nonGoals', 'acceptanceCriteria', 'risks', 'dependencies', 'missingInfo']
|
const REQUIREMENT_FILL_FIELDS = ['scope', 'nonGoals', 'acceptanceCriteria', 'risks', 'dependencies', 'missingInfo']
|
||||||
const OPEN_TASK_STATUS = new Set(['draft', 'dispatched', 'running', 'prepared', 'waiting_user', 'returned', 'reconfirm'])
|
const OPEN_TASK_STATUS = new Set(['draft', 'dispatched', 'running', 'prepared', 'waiting_user', 'returned', 'reconfirm'])
|
||||||
|
const CARD_LIMIT = 200
|
||||||
|
const CARD_KINDS = new Set(['question', 'approval'])
|
||||||
|
// 议政:三省代表按固定顺序轮转;上限可配,0 表示不设上限。
|
||||||
|
const DELIBERATION_SEATS = Object.freeze(['zhongshu', 'menxia', 'shangshu'])
|
||||||
|
const DELIBERATION_STANCES = new Set(['agree', 'dissent', 'neutral'])
|
||||||
|
const DELIBERATION_LIMIT = 60
|
||||||
|
const DELIBERATION_TIMEOUT_MS = 180000
|
||||||
|
const DELIBERATION_MAX_ROUNDS = 20
|
||||||
|
const DELIBERATION_DEFAULT_ROUNDS = 3
|
||||||
|
const AVATAR_MAX_BYTES = 120 * 1024
|
||||||
|
const AVATAR_CHAR_MAX = 8
|
||||||
|
|
||||||
|
function normalizeCardOptions(raw, kind) {
|
||||||
|
const options = (Array.isArray(raw) ? raw : []).map(item => ({
|
||||||
|
label: cleanText(item?.label),
|
||||||
|
value: cleanText(item?.value),
|
||||||
|
description: cleanText(item?.description),
|
||||||
|
})).filter(item => item.label && item.value)
|
||||||
|
if (kind === 'approval') {
|
||||||
|
if (options.length === 0) {
|
||||||
|
return [
|
||||||
|
{ label: '同意', value: 'allow', description: '允许这次操作' },
|
||||||
|
{ label: '拒绝', value: 'reject', description: '拒绝这次操作' },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
if (options.length !== 2 || options.some(item => !['allow', 'reject'].includes(item.value))
|
||||||
|
|| new Set(options.map(item => item.value)).size !== 2) {
|
||||||
|
throw new ServiceError('sansheng/card-invalid', '审批卡必须提供 allow 和 reject 两个选项')
|
||||||
|
}
|
||||||
|
return options
|
||||||
|
}
|
||||||
|
if (options.length < 2 || options.length > 5 || new Set(options.map(item => item.value)).size !== options.length) {
|
||||||
|
throw new ServiceError('sansheng/card-invalid', '问题卡需要 2 到 5 个不重复选项')
|
||||||
|
}
|
||||||
|
return options
|
||||||
|
}
|
||||||
|
|
||||||
|
function capCards(list) {
|
||||||
|
if (list.length > CARD_LIMIT) list.splice(0, list.length - CARD_LIMIT)
|
||||||
|
}
|
||||||
|
|
||||||
|
function deliberationSeatLabel(seatId) {
|
||||||
|
return SEATS[seatId]?.label ?? seatId
|
||||||
|
}
|
||||||
|
|
||||||
|
function deliberationStanceLabel(stance) {
|
||||||
|
if (stance === 'agree') return '同意'
|
||||||
|
if (stance === 'dissent') return '有分歧'
|
||||||
|
return '未表态'
|
||||||
|
}
|
||||||
|
|
||||||
|
function deliberationSummary(record) {
|
||||||
|
return {
|
||||||
|
id: record.id,
|
||||||
|
topic: record.topic,
|
||||||
|
status: record.status,
|
||||||
|
round: record.round,
|
||||||
|
maxRounds: record.maxRounds,
|
||||||
|
currentSeatId: record.currentSeatId ?? null,
|
||||||
|
currentSeatLabel: record.currentSeatId ? deliberationSeatLabel(record.currentSeatId) : null,
|
||||||
|
turn: record.turn ? {
|
||||||
|
round: record.turn.round,
|
||||||
|
seatId: record.turn.seatId,
|
||||||
|
status: record.turn.status,
|
||||||
|
attempts: record.turn.attempts ?? 0,
|
||||||
|
startedAt: record.turn.startedAt ?? null,
|
||||||
|
error: record.turn.error ?? null,
|
||||||
|
} : null,
|
||||||
|
speechCount: (record.speeches ?? []).length,
|
||||||
|
missing: (record.missing ?? []).map(item => ({ ...item })),
|
||||||
|
stoppedTurn: record.stoppedTurn ? { ...record.stoppedTurn, seatLabel: deliberationSeatLabel(record.stoppedTurn.seatId) } : null,
|
||||||
|
stoppedAt: record.stoppedAt ?? null,
|
||||||
|
stoppedBy: record.stoppedBy ?? null,
|
||||||
|
stoppedNote: record.stoppedNote ?? null,
|
||||||
|
conclusion: record.conclusion ? { ...record.conclusion } : null,
|
||||||
|
linked: {
|
||||||
|
taskId: record.taskId ?? null,
|
||||||
|
requirementId: record.requirementId ?? null,
|
||||||
|
requirementRevision: record.requirementRevision ?? null,
|
||||||
|
},
|
||||||
|
originSessionId: record.originSessionId ?? null,
|
||||||
|
startedBy: record.startedBy ?? 'user',
|
||||||
|
createdAt: record.createdAt ?? null,
|
||||||
|
updatedAt: record.updatedAt ?? null,
|
||||||
|
concludedAt: record.concludedAt ?? null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function deliberationTranscript(record) {
|
||||||
|
const speeches = record.speeches ?? []
|
||||||
|
if (speeches.length === 0) return '(尚无发言)'
|
||||||
|
const rounds = [...new Set(speeches.map(item => item.round))].sort((a, b) => a - b)
|
||||||
|
return rounds.map(round => {
|
||||||
|
const lines = speeches.filter(item => item.round === round).map(item => {
|
||||||
|
const tags = [deliberationStanceLabel(item.stance)]
|
||||||
|
if (item.pending) tags.push('仍有待决问题')
|
||||||
|
const head = '- ' + deliberationSeatLabel(item.seatId) + '(' + tags.join(',') + '):' + item.text
|
||||||
|
return item.openIssues ? head + '\n 未决:' + item.openIssues : head
|
||||||
|
})
|
||||||
|
return '第 ' + round + ' 轮\n' + lines.join('\n')
|
||||||
|
}).join('\n\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
function deliberationLinkText(project, record) {
|
||||||
|
const task = record.taskId ? (project.tasks ?? []).find(item => item.id === record.taskId) : null
|
||||||
|
const requirement = record.requirementId ? (project.requirements ?? []).find(item => item.id === record.requirementId) : null
|
||||||
|
if (!task && !requirement) return '本次议政不关联任务或需求。'
|
||||||
|
const lines = []
|
||||||
|
if (task) lines.push('关联任务:' + task.id + ' · ' + task.title + '(' + task.status + ')')
|
||||||
|
if (requirement) lines.push('关联需求:' + requirement.id + ' v' + requirement.revision + ' · ' + requirement.title)
|
||||||
|
const snapshot = task?.requirementSnapshot ?? {}
|
||||||
|
const originalText = requirement?.originalText || snapshot.originalText || task?.requirement || ''
|
||||||
|
const scope = requirement?.scope || snapshot.scope || ''
|
||||||
|
const acceptance = requirement?.acceptanceCriteria || snapshot.acceptanceCriteria || ''
|
||||||
|
if (originalText) lines.push('用户原话/要求:' + String(originalText).slice(0, 1200))
|
||||||
|
if (scope) lines.push('已确认范围:' + String(scope).slice(0, 1200))
|
||||||
|
if (acceptance) lines.push('已确认验收:' + String(acceptance).slice(0, 1200))
|
||||||
|
return lines.join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
function deliberationMessage(project, record, seatId, round) {
|
||||||
|
const maxText = record.maxRounds > 0 ? String(record.maxRounds) : '不限'
|
||||||
|
return [
|
||||||
|
'【三省议政】' + record.id + ' · ' + record.topic,
|
||||||
|
deliberationLinkText(project, record),
|
||||||
|
'轮次:第 ' + round + ' 轮,上限 ' + maxText + ' 轮。当前当值:' + deliberationSeatLabel(seatId) + '。',
|
||||||
|
'已登记发言:',
|
||||||
|
deliberationTranscript(record),
|
||||||
|
round === 1
|
||||||
|
? '这是第一轮,请先说明本省判断:同意、反对,或还有待决问题。'
|
||||||
|
: '请只回应尚未解决的分歧,不要重复已经达成的内容;如果已经没有待决问题,明确说同意。',
|
||||||
|
'提交方式:调用 sansheng_deliberation_speak,参数 deliberationId=' + record.id + ',round=' + round
|
||||||
|
+ ',text=你的发言,stance=agree|dissent|neutral,pending=是否仍有待决问题(true/false),openIssues=未决点(没有就留空)。',
|
||||||
|
'只有当前当值代表能提交本轮,提交一次即可;不要发布、批准、派工或修改任务。',
|
||||||
|
].join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
function deliberationConclusion(record, reason, note = '') {
|
||||||
|
const latestBySeat = new Map()
|
||||||
|
for (const speech of record.speeches ?? []) latestBySeat.set(speech.seatId, speech)
|
||||||
|
const lines = []
|
||||||
|
for (const seatId of DELIBERATION_SEATS) {
|
||||||
|
const speech = latestBySeat.get(seatId)
|
||||||
|
if (!speech) continue
|
||||||
|
const tags = [deliberationStanceLabel(speech.stance)]
|
||||||
|
if (speech.pending) tags.push('仍有待决问题')
|
||||||
|
lines.push(deliberationSeatLabel(seatId) + ':' + speech.text + '(' + tags.join(',') + ')')
|
||||||
|
if (speech.openIssues) lines.push(' ' + deliberationSeatLabel(seatId) + '未决:' + speech.openIssues)
|
||||||
|
}
|
||||||
|
const missing = record.missing ?? []
|
||||||
|
if (missing.length) {
|
||||||
|
lines.push('未回:' + missing.map(item => deliberationSeatLabel(item.seatId) + '(第 ' + item.round + ' 轮 '
|
||||||
|
+ (item.reason === 'timeout' ? '超时' : '失败') + ')').join(';'))
|
||||||
|
}
|
||||||
|
const hasObjection = [...latestBySeat.values()].some(speech => speech.stance !== 'agree' || speech.pending || speech.openIssues)
|
||||||
|
const needsUserDecision = hasObjection || missing.length > 0
|
||||||
|
let head
|
||||||
|
if (reason === 'consensus') head = '三省一致,议政收束。'
|
||||||
|
else if (reason === 'max-rounds') head = '已达到配置的 ' + record.maxRounds + ' 轮上限,仍未完全一致。'
|
||||||
|
else if (reason === 'stopped') {
|
||||||
|
const at = record.stoppedTurn
|
||||||
|
? '停在第 ' + record.stoppedTurn.round + ' 轮 · ' + deliberationSeatLabel(record.stoppedTurn.seatId) + ',本轮不再叫下一位。'
|
||||||
|
: '已停止,本轮不再叫下一位。'
|
||||||
|
head = note ? '用户叫停议政:' + note + '(' + at + ')' : '用户叫停议政。' + at
|
||||||
|
} else head = note ? '发起人结束议政:' + note : '发起人结束议政。'
|
||||||
|
return {
|
||||||
|
text: [head, lines.join('\n')].filter(Boolean).join('\n'),
|
||||||
|
at: Date.now(),
|
||||||
|
by: reason === 'ended' ? 'initiator' : (reason === 'stopped' ? 'user' : 'system'),
|
||||||
|
needsUserDecision,
|
||||||
|
missing: missing.map(item => ({ ...item })),
|
||||||
|
stopped: reason === 'stopped' ? (record.stoppedTurn ?? null) : null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function cleanText(value) { return typeof value === 'string' ? value.trim() : '' }
|
function cleanText(value) { return typeof value === 'string' ? value.trim() : '' }
|
||||||
|
|
||||||
|
|
@ -318,7 +493,7 @@ export function normalizeCatalog(catalog) {
|
||||||
}
|
}
|
||||||
|
|
||||||
export class SanshengService {
|
export class SanshengService {
|
||||||
constructor({ store, host, provisioner, globalStore = null, modelSync = null, seatActivity = null, approvalCenter = null, leadReporter = null, seatDelivery = null }) {
|
constructor({ store, host, provisioner, globalStore = null, modelSync = null, seatActivity = null, approvalCenter = null, leadReporter = null, seatDelivery = null, provinceAgents = null, leadSecretaries = null }) {
|
||||||
this.store = store
|
this.store = store
|
||||||
this.host = host
|
this.host = host
|
||||||
this.provisioner = provisioner
|
this.provisioner = provisioner
|
||||||
|
|
@ -328,7 +503,33 @@ export class SanshengService {
|
||||||
this.approvalCenter = approvalCenter
|
this.approvalCenter = approvalCenter
|
||||||
this.leadReporter = leadReporter
|
this.leadReporter = leadReporter
|
||||||
this.seatDelivery = seatDelivery
|
this.seatDelivery = seatDelivery
|
||||||
|
this.provinceAgents = provinceAgents
|
||||||
|
this.leadSecretaries = leadSecretaries
|
||||||
this._seedStatus = { status: 'unknown', candidates: [] }
|
this._seedStatus = { status: 'unknown', candidates: [] }
|
||||||
|
// 每个项目一条议政后台队列:发起和发言只落盘并回执,叫下一位在队列里跑,不挡住调用方。
|
||||||
|
this._deliberationJobs = new Map()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 把叫席、收束通知排进后台队列。同一个项目的议政动作按顺序执行,避免两次点击交错。
|
||||||
|
_scheduleDeliberation(projectId, label, run) {
|
||||||
|
const previous = this._deliberationJobs.get(projectId) ?? Promise.resolve()
|
||||||
|
const next = previous
|
||||||
|
.then(() => run())
|
||||||
|
.catch(error => {
|
||||||
|
console.warn('[sansheng] 议政后台任务失败(' + label + '):', error?.message ?? error)
|
||||||
|
})
|
||||||
|
this._deliberationJobs.set(projectId, next)
|
||||||
|
void next.finally(() => {
|
||||||
|
if (this._deliberationJobs.get(projectId) === next) this._deliberationJobs.delete(projectId)
|
||||||
|
})
|
||||||
|
return next
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试与停止操作用:等这个项目已排队的议政后台动作全部跑完。
|
||||||
|
async waitForDeliberation(projectId) {
|
||||||
|
while (this._deliberationJobs.has(projectId)) {
|
||||||
|
await this._deliberationJobs.get(projectId)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 组合每席的配置来源、实际会话模型、同步状态与运行状态。
|
// 组合每席的配置来源、实际会话模型、同步状态与运行状态。
|
||||||
|
|
@ -1032,6 +1233,604 @@ export class SanshengService {
|
||||||
return { entry, failedSeatIds: toSeatIds.filter((_id, i) => delivery[i].status === 'rejected') }
|
return { entry, failedSeatIds: toSeatIds.filter((_id, i) => delivery[i].status === 'rejected') }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async deliberations(projectId) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
await this._expireDeliberation(projectId)
|
||||||
|
const project = this.store.get(projectId)
|
||||||
|
return { deliberations: (project.deliberations ?? []).slice().reverse().map(deliberationSummary) }
|
||||||
|
}
|
||||||
|
|
||||||
|
async deliberation(projectId, deliberationId) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
await this._expireDeliberation(projectId)
|
||||||
|
const record = (this.store.get(projectId)?.deliberations ?? []).find(item => item.id === deliberationId)
|
||||||
|
if (!record) throw new ServiceError('sansheng/deliberation-not-found', '议政不存在')
|
||||||
|
return { deliberation: structuredClone(record) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 读取时把已超时的当值回合标出来,不自动推进,交给用户重试或带缺失收束。
|
||||||
|
async _expireDeliberation(projectId) {
|
||||||
|
const project = this.store.get(projectId)
|
||||||
|
const running = (project?.deliberations ?? []).find(item => item.status === 'running'
|
||||||
|
&& item.turn && ['waiting', 'delivering', 'delivered'].includes(item.turn.status))
|
||||||
|
if (!running) return
|
||||||
|
const startedAt = Number(running.turn.startedAt ?? 0)
|
||||||
|
if (!startedAt || Date.now() - startedAt < DELIBERATION_TIMEOUT_MS) return
|
||||||
|
await this.store.mutate(state => {
|
||||||
|
const current = state.projects[projectId]
|
||||||
|
const record = (current?.deliberations ?? []).find(item => item.id === running.id)
|
||||||
|
if (!record || record.status !== 'running' || !record.turn
|
||||||
|
|| !['waiting', 'delivering', 'delivered'].includes(record.turn.status)) return
|
||||||
|
const now = Date.now()
|
||||||
|
if (!Number(record.turn.startedAt) || now - Number(record.turn.startedAt) < DELIBERATION_TIMEOUT_MS) return
|
||||||
|
const delivery = (record.deliveries ?? []).find(item => item.id === record.turn.deliveryId)
|
||||||
|
const unknown = delivery?.status === 'sending'
|
||||||
|
if (unknown) delivery.status = 'unknown'
|
||||||
|
record.turn.status = 'timeout'
|
||||||
|
record.turn.error = unknown ? '发送结果未知,等待回执超时' : '等待发言超时'
|
||||||
|
record.updatedAt = now
|
||||||
|
record.missing ??= []
|
||||||
|
if (!record.missing.some(item => item.round === record.turn.round && item.seatId === record.turn.seatId)) {
|
||||||
|
record.missing.push({
|
||||||
|
round: record.turn.round, seatId: record.turn.seatId,
|
||||||
|
reason: unknown ? 'unknown' : 'timeout', at: now,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
current.revision = (current.revision ?? 0) + 1
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async startDeliberation(projectId, input = {}, actor = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
const topic = cleanText(input.topic).slice(0, 2000)
|
||||||
|
if (!topic) throw new ServiceError('sansheng/deliberation-invalid', '请填写议政议题')
|
||||||
|
const rawRounds = input.maxRounds === undefined || input.maxRounds === null || input.maxRounds === ''
|
||||||
|
? DELIBERATION_DEFAULT_ROUNDS : Number(input.maxRounds)
|
||||||
|
if (!Number.isInteger(rawRounds) || rawRounds < 0 || rawRounds > DELIBERATION_MAX_ROUNDS) {
|
||||||
|
throw new ServiceError('sansheng/deliberation-invalid', '轮次上限必须是 0 到 ' + DELIBERATION_MAX_ROUNDS + ' 的整数,0 表示不限')
|
||||||
|
}
|
||||||
|
const taskId = cleanText(input.taskId)
|
||||||
|
const requirementId = cleanText(input.requirementId)
|
||||||
|
const created = await this.store.mutate(state => {
|
||||||
|
const project = state.projects[projectId]
|
||||||
|
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
if ((project.deliberations ?? []).some(item => item.status === 'running')) {
|
||||||
|
throw new ServiceError('sansheng/deliberation-busy', '当前项目已有一场进行中的议政,请先结束或等它收束')
|
||||||
|
}
|
||||||
|
let task = null
|
||||||
|
let requirement = null
|
||||||
|
if (taskId) {
|
||||||
|
task = (project.tasks ?? []).find(item => item.id === taskId) ?? null
|
||||||
|
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||||
|
}
|
||||||
|
if (requirementId) {
|
||||||
|
requirement = (project.requirements ?? []).find(item => item.id === requirementId) ?? null
|
||||||
|
if (!requirement) throw new ServiceError('sansheng/not-found', `需求 ${requirementId} 不存在`)
|
||||||
|
} else if (task?.requirementId) {
|
||||||
|
requirement = (project.requirements ?? []).find(item => item.id === task.requirementId) ?? null
|
||||||
|
}
|
||||||
|
const now = Date.now()
|
||||||
|
const seq = (project.deliberationSeq ?? 0) + 1
|
||||||
|
project.deliberationSeq = seq
|
||||||
|
const record = {
|
||||||
|
id: 'D-' + String(seq).padStart(3, '0'),
|
||||||
|
topic,
|
||||||
|
status: 'running',
|
||||||
|
maxRounds: rawRounds,
|
||||||
|
round: 1,
|
||||||
|
currentSeatId: 'zhongshu',
|
||||||
|
turn: { round: 1, seatId: 'zhongshu', startedAt: now, attempts: 0, status: 'waiting', error: null },
|
||||||
|
speeches: [],
|
||||||
|
missing: [],
|
||||||
|
taskId: task?.id ?? null,
|
||||||
|
requirementId: requirement?.id ?? null,
|
||||||
|
requirementRevision: requirement?.revision ?? null,
|
||||||
|
originSessionId: cleanText(input.originSessionId) || cleanText(actor.sessionId) || null,
|
||||||
|
startedBy: cleanText(actor.seatId) || 'user',
|
||||||
|
deliveries: [],
|
||||||
|
conclusion: null,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
concludedAt: null,
|
||||||
|
}
|
||||||
|
project.deliberations ??= []
|
||||||
|
project.deliberations.push(record)
|
||||||
|
if (project.deliberations.length > DELIBERATION_LIMIT) {
|
||||||
|
project.deliberations.splice(0, project.deliberations.length - DELIBERATION_LIMIT)
|
||||||
|
}
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
return structuredClone(record)
|
||||||
|
})
|
||||||
|
// 先回执、后叫席:叫席(含新建席位会话)在后台队列里跑,工具调用和页面请求都不被它占住。
|
||||||
|
this._scheduleDeliberation(projectId, 'start ' + created.id, () => this._deliverDeliberationTurn(projectId, created.id))
|
||||||
|
return {
|
||||||
|
deliberation: created,
|
||||||
|
receipt: {
|
||||||
|
text: '议政 ' + created.id + ' 已发起,已叫' + deliberationSeatLabel(created.currentSeatId) + '。发言回来会显示在议政页。',
|
||||||
|
round: created.round,
|
||||||
|
seatId: created.currentSeatId,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async _deliverDeliberationTurn(projectId, deliberationId) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
let project = this.store.get(projectId)
|
||||||
|
let record = (project?.deliberations ?? []).find(item => item.id === deliberationId)
|
||||||
|
if (!record || record.status !== 'running' || !record.currentSeatId) {
|
||||||
|
return { ok: false, error: '议政已结束或没有当值代表' }
|
||||||
|
}
|
||||||
|
const seatId = record.currentSeatId
|
||||||
|
const round = record.round
|
||||||
|
try {
|
||||||
|
await this.provisioner.enableSeat(projectId, seatId)
|
||||||
|
} catch (error) {
|
||||||
|
const message = String(error?.message ?? error).slice(0, 900)
|
||||||
|
await this.store.mutate(state => {
|
||||||
|
const current = state.projects[projectId]
|
||||||
|
const latest = (current?.deliberations ?? []).find(item => item.id === deliberationId)
|
||||||
|
if (!latest || latest.status !== 'running' || latest.currentSeatId !== seatId || latest.round !== round) return
|
||||||
|
const now = Date.now()
|
||||||
|
latest.turn = { round, seatId, startedAt: now, attempts: Number(latest.turn?.attempts ?? 0) + 1, status: 'failed', error: message, deliveryId: null }
|
||||||
|
latest.missing ??= []
|
||||||
|
if (!latest.missing.some(item => item.round === round && item.seatId === seatId)) {
|
||||||
|
latest.missing.push({ round, seatId, reason: 'failed', at: now })
|
||||||
|
}
|
||||||
|
latest.updatedAt = now
|
||||||
|
current.revision = (current.revision ?? 0) + 1
|
||||||
|
}).catch(() => {})
|
||||||
|
return { ok: false, error: message }
|
||||||
|
}
|
||||||
|
project = this.store.get(projectId)
|
||||||
|
record = (project?.deliberations ?? []).find(item => item.id === deliberationId)
|
||||||
|
if (!record || record.status !== 'running' || record.currentSeatId !== seatId || record.round !== round) {
|
||||||
|
return { ok: false, error: '议政轮次已变化' }
|
||||||
|
}
|
||||||
|
const seat = project.seats?.[seatId]
|
||||||
|
if (!seat || seat.status !== 'bound' || !seat.sessionId) return { ok: false, error: '席位尚未绑定会话' }
|
||||||
|
|
||||||
|
// 先把本次发送落成 sending 记录,再真正投递;崩溃后据此识别已发/未知,不自动重发。
|
||||||
|
const deliveryId = randomUUID()
|
||||||
|
const preparedAt = Date.now()
|
||||||
|
const prepared = await this.store.mutate(state => {
|
||||||
|
const current = state.projects[projectId]
|
||||||
|
const latest = (current?.deliberations ?? []).find(item => item.id === deliberationId)
|
||||||
|
if (!latest || latest.status !== 'running' || latest.currentSeatId !== seatId || latest.round !== round) return false
|
||||||
|
latest.deliveries ??= []
|
||||||
|
const attempt = latest.deliveries.filter(item => item.round === round && item.seatId === seatId).length + 1
|
||||||
|
latest.deliveries.push({ id: deliveryId, round, seatId, status: 'sending', attempt, at: preparedAt, confirmedAt: null, error: null })
|
||||||
|
if (latest.deliveries.length > 200) latest.deliveries.splice(0, latest.deliveries.length - 200)
|
||||||
|
latest.turn = {
|
||||||
|
round, seatId, startedAt: preparedAt, attempts: attempt,
|
||||||
|
status: 'delivering', error: null, deliveryId,
|
||||||
|
}
|
||||||
|
latest.updatedAt = preparedAt
|
||||||
|
current.revision = (current.revision ?? 0) + 1
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if (!prepared) return { ok: false, error: '议政轮次已变化' }
|
||||||
|
|
||||||
|
// 落完 sending 之后、真正发送之前再看一眼:用户可能刚点了停止。
|
||||||
|
const beforeSend = this.store.get(projectId)?.deliberations?.find(item => item.id === deliberationId)
|
||||||
|
if (!beforeSend || beforeSend.status !== 'running' || beforeSend.currentSeatId !== seatId || beforeSend.round !== round) {
|
||||||
|
await this.store.mutate(state => {
|
||||||
|
const latest = (state.projects[projectId]?.deliberations ?? []).find(item => item.id === deliberationId)
|
||||||
|
const delivery = (latest?.deliveries ?? []).find(item => item.id === deliveryId)
|
||||||
|
if (delivery && delivery.status === 'sending') {
|
||||||
|
delivery.status = 'cancelled'
|
||||||
|
delivery.error = '议政已停止,不再叫下一位'
|
||||||
|
}
|
||||||
|
}).catch(() => {})
|
||||||
|
return { ok: false, error: '议政已停止或轮次已变化' }
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 省级子 Agent 可用时由它们当议政代表;否则退回席位会话本人(单测和旧项目仍走这条路)。
|
||||||
|
let delegate = null
|
||||||
|
const message = deliberationMessage(project, record, seatId, round)
|
||||||
|
if (this.provinceAgents) {
|
||||||
|
delegate = await this.provinceAgents.startDeliberationTurn({ projectId, seatId, deliberationId, round, prompt: message })
|
||||||
|
} else {
|
||||||
|
await this._deliverInternal(seat.sessionId, message, internalSource('sansheng-deliberation', { seatId, deliberationId }))
|
||||||
|
}
|
||||||
|
await this.store.mutate(state => {
|
||||||
|
const current = state.projects[projectId]
|
||||||
|
const latest = (current?.deliberations ?? []).find(item => item.id === deliberationId)
|
||||||
|
if (!latest) return
|
||||||
|
const delivery = (latest.deliveries ?? []).find(item => item.id === deliveryId)
|
||||||
|
if (latest.status !== 'running' || latest.currentSeatId !== seatId || latest.round !== round) {
|
||||||
|
if (delivery && delivery.status === 'sending') {
|
||||||
|
delivery.status = 'cancelled'
|
||||||
|
delivery.error = '议政已停止,不再叫下一位'
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const now = Date.now()
|
||||||
|
if (delivery) { delivery.status = 'sent'; delivery.confirmedAt = now }
|
||||||
|
latest.turn = {
|
||||||
|
round, seatId, startedAt: now, attempts: Number(latest.turn?.attempts ?? 0),
|
||||||
|
status: 'delivered', error: null, deliveryId,
|
||||||
|
delegateRunId: delegate?.runId ?? null, delegateChildId: delegate?.childId ?? null,
|
||||||
|
}
|
||||||
|
latest.missing = (latest.missing ?? []).filter(item => !(item.round === round && item.seatId === seatId))
|
||||||
|
latest.updatedAt = now
|
||||||
|
current.revision = (current.revision ?? 0) + 1
|
||||||
|
})
|
||||||
|
return { ok: true, sessionId: delegate?.childId ?? seat.sessionId, deliveryId, delegate }
|
||||||
|
} catch (error) {
|
||||||
|
const message = String(error?.message ?? error).slice(0, 900)
|
||||||
|
await this.store.mutate(state => {
|
||||||
|
const current = state.projects[projectId]
|
||||||
|
const latest = (current?.deliberations ?? []).find(item => item.id === deliberationId)
|
||||||
|
if (!latest) return
|
||||||
|
const delivery = (latest.deliveries ?? []).find(item => item.id === deliveryId)
|
||||||
|
if (latest.status !== 'running' || latest.currentSeatId !== seatId || latest.round !== round) {
|
||||||
|
if (delivery && delivery.status === 'sending') {
|
||||||
|
delivery.status = 'cancelled'
|
||||||
|
delivery.error = '议政已停止,不再叫下一位'
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const now = Date.now()
|
||||||
|
if (delivery) { delivery.status = 'failed'; delivery.error = message }
|
||||||
|
latest.turn = {
|
||||||
|
round, seatId, startedAt: now, attempts: Number(latest.turn?.attempts ?? 0),
|
||||||
|
status: 'failed', error: message, deliveryId,
|
||||||
|
}
|
||||||
|
latest.missing ??= []
|
||||||
|
if (!latest.missing.some(item => item.round === round && item.seatId === seatId)) {
|
||||||
|
latest.missing.push({ round, seatId, reason: 'failed', at: now })
|
||||||
|
}
|
||||||
|
latest.updatedAt = now
|
||||||
|
current.revision = (current.revision ?? 0) + 1
|
||||||
|
}).catch(() => {})
|
||||||
|
return { ok: false, error: message, deliveryId }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async deliberationSpeak(projectId, deliberationId, input = {}, actor = {}, callId = null) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!DELIBERATION_SEATS.includes(actor.seatId)) {
|
||||||
|
throw new ServiceError('sansheng/forbidden', '只有中书、门下、尚书的当值代表可以发言')
|
||||||
|
}
|
||||||
|
await this._expireDeliberation(projectId)
|
||||||
|
const result = await this.store.mutate(state => {
|
||||||
|
const project = state.projects[projectId]
|
||||||
|
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
const record = (project.deliberations ?? []).find(item => item.id === deliberationId)
|
||||||
|
if (!record) throw new ServiceError('sansheng/deliberation-not-found', '议政不存在')
|
||||||
|
const delegate = actor.delegate ?? null
|
||||||
|
if (delegate) {
|
||||||
|
if (delegate.deliberationId !== deliberationId || delegate.seatId !== actor.seatId
|
||||||
|
|| delegate.runId !== record.turn?.delegateRunId) {
|
||||||
|
throw new ServiceError('sansheng/forbidden', '当前省级子 Agent 不是本轮当值代表')
|
||||||
|
}
|
||||||
|
const located = this.provinceAgents?.locateBySession(actor.sessionId)
|
||||||
|
if (!located || located.run.id !== delegate.runId) {
|
||||||
|
throw new ServiceError('sansheng/forbidden', '省级子 Agent 运行记录已失效')
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const seat = project.seats?.[actor.seatId]
|
||||||
|
if (!seat || seat.sessionId !== actor.sessionId) {
|
||||||
|
throw new ServiceError('sansheng/forbidden', '当前会话不是该席绑定的会话')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const round = Number(input.round)
|
||||||
|
const existing = (record.speeches ?? []).find(item => item.round === round && item.seatId === actor.seatId)
|
||||||
|
if (existing) {
|
||||||
|
return { speech: existing, record: structuredClone(record), duplicate: true, nextSeatId: null, concluded: false }
|
||||||
|
}
|
||||||
|
if (record.status !== 'running') throw new ServiceError('sansheng/deliberation-ended', '议政已结束')
|
||||||
|
if (!Number.isInteger(round) || round !== record.round) {
|
||||||
|
throw new ServiceError('sansheng/deliberation-turn', '不是当前轮次')
|
||||||
|
}
|
||||||
|
if (record.currentSeatId !== actor.seatId || !record.turn || record.turn.round !== round) {
|
||||||
|
throw new ServiceError('sansheng/deliberation-turn', '还没轮到你发言')
|
||||||
|
}
|
||||||
|
const text = cleanText(input.text).slice(0, 6000)
|
||||||
|
if (!text) throw new ServiceError('sansheng/deliberation-invalid', '发言不能为空')
|
||||||
|
const stance = cleanText(input.stance) || 'neutral'
|
||||||
|
if (!DELIBERATION_STANCES.has(stance)) {
|
||||||
|
throw new ServiceError('sansheng/deliberation-invalid', 'stance 必须是 agree、dissent 或 neutral')
|
||||||
|
}
|
||||||
|
const now = Date.now()
|
||||||
|
const speech = {
|
||||||
|
id: randomUUID(), round, seatId: actor.seatId, text, stance,
|
||||||
|
pending: input.pending === true,
|
||||||
|
openIssues: cleanText(input.openIssues).slice(0, 1200),
|
||||||
|
callId: cleanText(callId) || null,
|
||||||
|
via: actor.delegate ? 'subagent' : 'seat',
|
||||||
|
runId: actor.delegate?.runId ?? null,
|
||||||
|
at: now,
|
||||||
|
}
|
||||||
|
record.speeches ??= []
|
||||||
|
record.speeches.push(speech)
|
||||||
|
record.missing = (record.missing ?? []).filter(item => !(item.round === round && item.seatId === actor.seatId))
|
||||||
|
record.turn = null
|
||||||
|
record.currentSeatId = null
|
||||||
|
record.updatedAt = now
|
||||||
|
const roundSpeeches = record.speeches.filter(item => item.round === round)
|
||||||
|
let nextSeatId = null
|
||||||
|
let concluded = false
|
||||||
|
if (roundSpeeches.length < DELIBERATION_SEATS.length) {
|
||||||
|
nextSeatId = DELIBERATION_SEATS.find(id => !roundSpeeches.some(item => item.seatId === id))
|
||||||
|
record.currentSeatId = nextSeatId
|
||||||
|
record.turn = { round, seatId: nextSeatId, startedAt: now, attempts: 0, status: 'waiting', error: null }
|
||||||
|
} else {
|
||||||
|
const consensus = roundSpeeches.every(item => item.stance === 'agree' && !item.pending && !item.openIssues)
|
||||||
|
const maxed = record.maxRounds > 0 && round >= record.maxRounds
|
||||||
|
if (consensus || maxed) {
|
||||||
|
concluded = true
|
||||||
|
record.status = 'concluded'
|
||||||
|
record.concludedAt = now
|
||||||
|
record.conclusion = deliberationConclusion(record, consensus ? 'consensus' : 'max-rounds')
|
||||||
|
} else {
|
||||||
|
record.round = round + 1
|
||||||
|
nextSeatId = 'zhongshu'
|
||||||
|
record.currentSeatId = nextSeatId
|
||||||
|
record.turn = { round: record.round, seatId: nextSeatId, startedAt: now, attempts: 0, status: 'waiting', error: null }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
return { speech, record: structuredClone(record), duplicate: false, nextSeatId, concluded }
|
||||||
|
})
|
||||||
|
if (result.duplicate) {
|
||||||
|
return { ok: true, duplicate: true, speech: result.speech, deliberation: result.record }
|
||||||
|
}
|
||||||
|
if (actor.delegate && typeof this.provinceAgents?.finishRun === 'function') {
|
||||||
|
await this.provinceAgents.finishRun(projectId, actor.delegate.runId, '发言已提交')
|
||||||
|
}
|
||||||
|
// 发言只落盘并回执;叫下一位、收束通知都排进后台队列,当前席位不再被下一席的启动拖住。
|
||||||
|
if (result.nextSeatId) {
|
||||||
|
this._scheduleDeliberation(projectId, 'turn ' + deliberationId, () => this._deliverDeliberationTurn(projectId, deliberationId))
|
||||||
|
}
|
||||||
|
if (result.concluded) {
|
||||||
|
this._scheduleDeliberation(projectId, 'notify ' + deliberationId, () => this._notifyDeliberationConclusion(projectId, deliberationId))
|
||||||
|
}
|
||||||
|
const receipt = result.concluded
|
||||||
|
? { text: '发言已记录,议政已收束,结论会回到发起会话。', concluded: true }
|
||||||
|
: { text: '发言已记录,已叫' + deliberationSeatLabel(result.nextSeatId) + '。', round: result.record.round, seatId: result.nextSeatId }
|
||||||
|
return { ok: true, duplicate: false, speech: result.speech, deliberation: result.record, delivery: null, receipt, concluded: result.concluded }
|
||||||
|
}
|
||||||
|
|
||||||
|
async endDeliberation(projectId, deliberationId, input = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
await this._expireDeliberation(projectId)
|
||||||
|
const record = await this.store.mutate(state => {
|
||||||
|
const project = state.projects[projectId]
|
||||||
|
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
const current = (project.deliberations ?? []).find(item => item.id === deliberationId)
|
||||||
|
if (!current) throw new ServiceError('sansheng/deliberation-not-found', '议政不存在')
|
||||||
|
if (current.status !== 'running') throw new ServiceError('sansheng/deliberation-ended', '议政已结束')
|
||||||
|
const now = Date.now()
|
||||||
|
current.status = 'concluded'
|
||||||
|
current.concludedAt = now
|
||||||
|
current.currentSeatId = null
|
||||||
|
current.turn = null
|
||||||
|
current.conclusion = deliberationConclusion(current, 'ended', cleanText(input.note).slice(0, 1200))
|
||||||
|
current.updatedAt = now
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
return structuredClone(current)
|
||||||
|
})
|
||||||
|
this._scheduleDeliberation(projectId, 'notify ' + deliberationId, () => this._notifyDeliberationConclusion(projectId, deliberationId))
|
||||||
|
return { deliberation: record }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 用户叫停:先落“已停止”并清空当值,再真正取消当前席位的回合;
|
||||||
|
// 后台队列在每次叫席前后都会看状态,停止后不会再投递下一位。
|
||||||
|
async stopDeliberation(projectId, deliberationId, input = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
await this._expireDeliberation(projectId)
|
||||||
|
let delegateRunId = null
|
||||||
|
const stopped = await this.store.mutate(state => {
|
||||||
|
const project = state.projects[projectId]
|
||||||
|
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
const record = (project.deliberations ?? []).find(item => item.id === deliberationId)
|
||||||
|
if (!record) throw new ServiceError('sansheng/deliberation-not-found', '议政不存在')
|
||||||
|
if (record.status !== 'running') throw new ServiceError('sansheng/deliberation-ended', '议政已结束')
|
||||||
|
const now = Date.now()
|
||||||
|
const turn = record.turn ?? null
|
||||||
|
delegateRunId = turn?.delegateRunId ?? null
|
||||||
|
record.status = 'stopped'
|
||||||
|
record.stoppedAt = now
|
||||||
|
record.stoppedBy = cleanText(input.by) || 'user'
|
||||||
|
record.stoppedNote = cleanText(input.note).slice(0, 600) || null
|
||||||
|
record.stoppedTurn = turn
|
||||||
|
? { round: turn.round, seatId: turn.seatId, status: 'stopped', attempts: turn.attempts ?? 0, startedAt: turn.startedAt ?? now }
|
||||||
|
: (record.currentSeatId
|
||||||
|
? { round: record.round, seatId: record.currentSeatId, status: 'stopped', attempts: 0, startedAt: now }
|
||||||
|
: null)
|
||||||
|
for (const delivery of record.deliveries ?? []) {
|
||||||
|
if (delivery.status === 'sending') {
|
||||||
|
delivery.status = 'cancelled'
|
||||||
|
delivery.error = '议政已停止,不再叫下一位'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
record.currentSeatId = null
|
||||||
|
record.turn = null
|
||||||
|
record.concludedAt = now
|
||||||
|
record.conclusion = deliberationConclusion(record, 'stopped', record.stoppedNote ?? '')
|
||||||
|
record.updatedAt = now
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
return structuredClone(record)
|
||||||
|
})
|
||||||
|
let cancelled = false
|
||||||
|
if (delegateRunId && this.provinceAgents) {
|
||||||
|
try {
|
||||||
|
const result = await this.provinceAgents.stopRun(projectId, delegateRunId, '议政已停止')
|
||||||
|
cancelled = Boolean(result?.cancelled)
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
if (!cancelled) {
|
||||||
|
cancelled = this._cancelSeatTurn(this.store.get(projectId)?.seats?.[stopped.stoppedTurn?.seatId]?.sessionId)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
deliberation: stopped,
|
||||||
|
cancelled,
|
||||||
|
receipt: {
|
||||||
|
text: stopped.stoppedTurn
|
||||||
|
? '已停止,停在第 ' + stopped.stoppedTurn.round + ' 轮 · ' + deliberationSeatLabel(stopped.stoppedTurn.seatId) + ',不会再叫下一位。'
|
||||||
|
: '已停止,不会再叫下一位。',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 真中断:宿主公开的 agent.cancel 就是用户点“停止”时走的那条路;拿不到就只保证不再投递。
|
||||||
|
_cancelSeatTurn(sessionId) {
|
||||||
|
if (!sessionId) return false
|
||||||
|
try {
|
||||||
|
const agent = this.host.agents?.get?.(sessionId)
|
||||||
|
if (!agent || typeof agent.cancel !== 'function') return false
|
||||||
|
agent.cancel({ kind: 'user' })
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async retryDeliberation(projectId, deliberationId) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
await this._expireDeliberation(projectId)
|
||||||
|
const record = (this.store.get(projectId)?.deliberations ?? []).find(item => item.id === deliberationId)
|
||||||
|
if (!record) throw new ServiceError('sansheng/deliberation-not-found', '议政不存在')
|
||||||
|
if (record.status !== 'running') throw new ServiceError('sansheng/deliberation-ended', '议政已结束')
|
||||||
|
if (!record.turn || !['failed', 'timeout'].includes(record.turn.status)) {
|
||||||
|
throw new ServiceError('sansheng/deliberation-turn', '当前回合没有失败或超时,无需重试')
|
||||||
|
}
|
||||||
|
await this.store.mutate(state => {
|
||||||
|
const current = state.projects[projectId]
|
||||||
|
const latest = (current?.deliberations ?? []).find(item => item.id === deliberationId)
|
||||||
|
if (!latest || latest.status !== 'running') return
|
||||||
|
const old = (latest.deliveries ?? []).find(item => item.id === latest.turn?.deliveryId)
|
||||||
|
if (old?.status === 'sending') {
|
||||||
|
old.status = 'unknown'
|
||||||
|
old.error = '重试前未确认原投递结果'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const delivery = await this._deliverDeliberationTurn(projectId, deliberationId)
|
||||||
|
const fresh = await this.deliberation(projectId, deliberationId)
|
||||||
|
return { deliberation: fresh.deliberation, delivery }
|
||||||
|
}
|
||||||
|
|
||||||
|
async _notifyDeliberationConclusion(projectId, deliberationId) {
|
||||||
|
try {
|
||||||
|
const project = this.store.get(projectId)
|
||||||
|
const record = (project?.deliberations ?? []).find(item => item.id === deliberationId)
|
||||||
|
if (!record) return
|
||||||
|
const seats = Object.values(project?.seats ?? {})
|
||||||
|
const originSeat = record.originSessionId
|
||||||
|
? seats.find(seat => seat.sessionId === record.originSessionId)
|
||||||
|
: null
|
||||||
|
const lead = project?.seats?.lead
|
||||||
|
const target = originSeat?.sessionId ? originSeat.sessionId : (lead?.status === 'bound' ? lead.sessionId : null)
|
||||||
|
if (!target) return
|
||||||
|
const conclusion = record.conclusion ?? { text: '议政已结束。', needsUserDecision: false }
|
||||||
|
const text = [
|
||||||
|
'【三省议政结束】' + record.id + ' · ' + record.topic,
|
||||||
|
'结论:' + conclusion.text,
|
||||||
|
'是否需要用户决定:' + (conclusion.needsUserDecision ? '是' : '否'),
|
||||||
|
'请用零基础白话向用户说明:达成了什么、还差什么、是否需要用户拍板。',
|
||||||
|
conclusion.needsUserDecision
|
||||||
|
? '有分歧时用 sansheng_card 挂问题卡,把可选做法写进选项;不要代用户决定。'
|
||||||
|
: '纯共识不要挂需要点选的卡,直接说明结论和议政入口。',
|
||||||
|
].join('\n')
|
||||||
|
await this._deliverInternal(target, text, internalSource('sansheng-deliberation', { seatId: 'lead', deliberationId }))
|
||||||
|
} catch {
|
||||||
|
// 通知失败不影响议政落盘;用户仍可在工作台查看转写和结论。
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 丞相把指令交给中书接令子 Agent:先回执,接令再把原话和要点交回中书主席。
|
||||||
|
async startOrder(projectId, input = {}, actor = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
if (!this.provinceAgents) throw new ServiceError('sansheng/province-unavailable', '宿主未提供省级子 Agent,无法启动中书接令')
|
||||||
|
const instruction = cleanText(input.instruction)
|
||||||
|
if (!instruction) throw new ServiceError('sansheng/order-invalid', '请说明要下达给中书的指令')
|
||||||
|
return this.provinceAgents.startOrder({
|
||||||
|
projectId,
|
||||||
|
instruction,
|
||||||
|
taskId: cleanText(input.taskId) || null,
|
||||||
|
requirementId: cleanText(input.requirementId) || null,
|
||||||
|
sourceSessionId: cleanText(input.originSessionId) || cleanText(actor.sessionId) || null,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 统一列出后台能停的运行:主簿、记室、省级接令与议政代表。
|
||||||
|
async agentRuns(projectId) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
const secretaries = typeof this.leadSecretaries?.list === 'function' ? await this.leadSecretaries.list(projectId) : []
|
||||||
|
const province = this.provinceAgents ? await this.provinceAgents.list(projectId) : []
|
||||||
|
return { runs: [...secretaries, ...province] }
|
||||||
|
}
|
||||||
|
|
||||||
|
async stopAgentRun(projectId, runId, kind = '') {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
const id = cleanText(runId)
|
||||||
|
if (!id) throw new ServiceError('sansheng/agent-run-not-found', '缺少运行编号')
|
||||||
|
if (kind === 'secretary' || (kind !== 'province' && typeof this.leadSecretaries?.hasRun === 'function'
|
||||||
|
&& await this.leadSecretaries.hasRun(projectId, id))) {
|
||||||
|
if (!this.leadSecretaries) throw new ServiceError('sansheng/agent-run-not-found', '主簿与记室未启用')
|
||||||
|
return this.leadSecretaries.stop(projectId, id)
|
||||||
|
}
|
||||||
|
if (this.provinceAgents) return this.provinceAgents.stopRun(projectId, id)
|
||||||
|
throw new ServiceError('sansheng/agent-run-not-found', '后台子 Agent 运行不存在')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 头像:字符或已缩放图片;图片超出上限直接拒绝,客户端负责缩放到 256×256。
|
||||||
|
async setAvatar(projectId, seatId, input = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/avatar-invalid', '未知席位')
|
||||||
|
const char = cleanText(input.char)
|
||||||
|
const dataUrl = cleanText(input.dataUrl)
|
||||||
|
let avatar
|
||||||
|
if (char) {
|
||||||
|
if ([...char].length > AVATAR_CHAR_MAX) {
|
||||||
|
throw new ServiceError('sansheng/avatar-invalid', '头像字符最多 8 个,emoji 也算一个')
|
||||||
|
}
|
||||||
|
avatar = { type: 'char', char }
|
||||||
|
} else if (dataUrl) {
|
||||||
|
const match = /^data:(image\/(?:png|jpeg|webp));base64,([A-Za-z0-9+/=]+)$/.exec(dataUrl)
|
||||||
|
if (!match) throw new ServiceError('sansheng/avatar-invalid', '头像只支持 PNG、JPEG 或 WebP 图片')
|
||||||
|
const bytes = Buffer.from(match[2], 'base64').length
|
||||||
|
if (bytes === 0) throw new ServiceError('sansheng/avatar-invalid', '图片内容为空')
|
||||||
|
if (bytes > AVATAR_MAX_BYTES) {
|
||||||
|
throw new ServiceError('sansheng/avatar-invalid', '图片超过 120KB,请换一张小一点的图片')
|
||||||
|
}
|
||||||
|
avatar = { type: 'image', mime: match[1], dataUrl, bytes }
|
||||||
|
} else {
|
||||||
|
throw new ServiceError('sansheng/avatar-invalid', '请提供图片或字符头像')
|
||||||
|
}
|
||||||
|
await this.store.mutate(state => {
|
||||||
|
const project = state.projects[projectId]
|
||||||
|
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
project.avatars ??= {}
|
||||||
|
project.avatars[seatId] = avatar
|
||||||
|
project.updatedAt = Date.now()
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
})
|
||||||
|
return { seatId, avatar }
|
||||||
|
}
|
||||||
|
|
||||||
|
async clearAvatar(projectId, seatId) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/avatar-invalid', '未知席位')
|
||||||
|
await this.store.mutate(state => {
|
||||||
|
const project = state.projects[projectId]
|
||||||
|
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
if (project.avatars?.[seatId]) {
|
||||||
|
delete project.avatars[seatId]
|
||||||
|
project.updatedAt = Date.now()
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return { seatId, avatar: null }
|
||||||
|
}
|
||||||
|
|
||||||
async requestTaskDecision(projectId, taskId, input, actor) {
|
async requestTaskDecision(projectId, taskId, input, actor) {
|
||||||
if (actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '请先把分歧交给丞相')
|
if (actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '请先把分歧交给丞相')
|
||||||
const question = cleanText(input.question)
|
const question = cleanText(input.question)
|
||||||
|
|
@ -1808,6 +2607,128 @@ export class SanshengService {
|
||||||
return { projects: await this.seatActivity.reconcileAll(), available: true }
|
return { projects: await this.seatActivity.reconcileAll(), available: true }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async cards(projectId) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
const project = this.store.get(projectId)
|
||||||
|
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
return { cards: structuredClone(project.cards ?? []) }
|
||||||
|
}
|
||||||
|
|
||||||
|
async cardGet(cardId) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
const id = cleanText(cardId)
|
||||||
|
if (!id) throw new ServiceError('sansheng/card-invalid', '缺少 cardId')
|
||||||
|
for (const project of this.store.list()) {
|
||||||
|
const card = (project.cards ?? []).find(item => item.id === id)
|
||||||
|
if (card) return { ok: true, card: structuredClone(card) }
|
||||||
|
}
|
||||||
|
throw new ServiceError('sansheng/card-not-found', `卡片 ${id} 不存在`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 丞相只能为当前项目挂卡;审批卡的结论仍回到 approval-center 的同一个原生请求。
|
||||||
|
async cardCreate(projectId, input = {}, actor = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
const project = this.store.get(projectId)
|
||||||
|
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
if (actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以挂卡片')
|
||||||
|
const lead = project.seats?.lead
|
||||||
|
if (lead?.status !== 'bound' || !lead.sessionId) throw new ServiceError('sansheng/seat-unbound', '丞相会话未就绪,不能挂卡片')
|
||||||
|
if (actor.sessionId && actor.sessionId !== lead.sessionId) throw new ServiceError('sansheng/forbidden', '丞相会话已变化')
|
||||||
|
const kind = cleanText(input.kind)
|
||||||
|
if (!CARD_KINDS.has(kind)) throw new ServiceError('sansheng/card-invalid', '卡片类型必须是 question 或 approval')
|
||||||
|
const title = cleanText(input.title)
|
||||||
|
const body = cleanText(input.body)
|
||||||
|
if (!title || title.length > 200) throw new ServiceError('sansheng/card-invalid', '卡片标题必须为 1 至 200 字符')
|
||||||
|
if (!body || body.length > 4000) throw new ServiceError('sansheng/card-invalid', '卡片正文必须为 1 至 4000 字符')
|
||||||
|
const options = normalizeCardOptions(input.options, kind)
|
||||||
|
const now = Date.now()
|
||||||
|
let approval = null
|
||||||
|
if (kind === 'approval') {
|
||||||
|
if (!this.approvalCenter) throw new ServiceError('sansheng/approval-degraded', '审批中心不可用,不能挂审批卡')
|
||||||
|
const approvalId = cleanText(input.approvalId)
|
||||||
|
if (!approvalId) throw new ServiceError('sansheng/card-invalid', '审批卡需要 approvalId')
|
||||||
|
approval = this.approvalCenter.list(projectId).find(item => item.id === approvalId) ?? null
|
||||||
|
if (!approval) throw new ServiceError('sansheng/approval-stale', '审批已处理或不存在,不能挂卡')
|
||||||
|
}
|
||||||
|
const card = {
|
||||||
|
id: cleanText(input.callId) || randomUUID(),
|
||||||
|
kind, title, body,
|
||||||
|
options,
|
||||||
|
approvalId: approval?.id ?? null,
|
||||||
|
seatId: approval?.seatId ?? null,
|
||||||
|
seatLabel: approval?.seatId ? (SEATS[approval.seatId]?.label ?? approval.seatId) : null,
|
||||||
|
tool: approval?.tool ?? null,
|
||||||
|
reason: approval?.reason ?? null,
|
||||||
|
detail: approval?.detail ?? null,
|
||||||
|
projectId,
|
||||||
|
sessionId: lead.sessionId,
|
||||||
|
status: 'pending',
|
||||||
|
answer: null,
|
||||||
|
answerLabel: null,
|
||||||
|
createdAt: now,
|
||||||
|
answeredAt: null,
|
||||||
|
}
|
||||||
|
await this.store.mutate(state => {
|
||||||
|
const current = state.projects[projectId]
|
||||||
|
if (!current) return
|
||||||
|
current.cards ??= []
|
||||||
|
current.cards.push(card)
|
||||||
|
capCards(current.cards)
|
||||||
|
current.updatedAt = now
|
||||||
|
current.revision = (current.revision ?? 0) + 1
|
||||||
|
})
|
||||||
|
return { ok: true, card: structuredClone(card) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 答题是普通用户消息(会唤醒丞相);审题结论只走 approval-center,不另造第二套决定。
|
||||||
|
async cardAnswer(cardId, choice, actor = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
const id = cleanText(cardId)
|
||||||
|
const value = cleanText(choice)
|
||||||
|
if (!id || !value) throw new ServiceError('sansheng/card-invalid', '缺少 cardId 或选择')
|
||||||
|
let project = null
|
||||||
|
let card = null
|
||||||
|
for (const candidate of this.store.list()) {
|
||||||
|
const found = (candidate.cards ?? []).find(item => item.id === id)
|
||||||
|
if (found) { project = candidate; card = found; break }
|
||||||
|
}
|
||||||
|
if (!project || !card) throw new ServiceError('sansheng/card-not-found', `卡片 ${id} 不存在`)
|
||||||
|
if (card.status === 'answered') return { ok: true, duplicate: true, card: structuredClone(card) }
|
||||||
|
const option = card.options.find(item => item.value === value)
|
||||||
|
if (!option) throw new ServiceError('sansheng/card-invalid', '卡片没有这个选项')
|
||||||
|
const lead = project.seats?.lead
|
||||||
|
if (lead?.status !== 'bound' || !lead.sessionId) throw new ServiceError('sansheng/seat-unbound', '丞相会话未就绪,不能回答卡片')
|
||||||
|
if (actor.seatId && actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以回答卡片')
|
||||||
|
if (actor.sessionId && actor.sessionId !== lead.sessionId) throw new ServiceError('sansheng/forbidden', '丞相会话已变化')
|
||||||
|
if (card.kind === 'approval') {
|
||||||
|
if (!this.approvalCenter) throw new ServiceError('sansheng/approval-degraded', '审批中心不可用')
|
||||||
|
await this.approvalCenter.answer(card.approvalId, { projectId: project.id, seatId: 'lead', sessionId: lead.sessionId }, value)
|
||||||
|
} else {
|
||||||
|
const agent = this.host?.agents?.get?.(lead.sessionId)
|
||||||
|
if (!agent || typeof agent.followup !== 'function') throw new ServiceError('sansheng/card-session-unavailable', '丞相会话不可用,回答未送达')
|
||||||
|
const message = this.host?.createUserMessage
|
||||||
|
? await Promise.resolve(this.host.createUserMessage({
|
||||||
|
content: [{ type: 'text', text: `[卡片回答] ${card.title}\n用户选择:${option.label}` }],
|
||||||
|
source: { kind: 'sansheng-card-answer', cardId: card.id, choice: value },
|
||||||
|
}))
|
||||||
|
: { role: 'user', content: [{ type: 'text', text: `[卡片回答] ${card.title}\n用户选择:${option.label}` }], source: { kind: 'sansheng-card-answer', cardId: card.id, choice: value } }
|
||||||
|
await agent.followup(message)
|
||||||
|
}
|
||||||
|
const answered = await this.store.mutate(state => {
|
||||||
|
const current = state.projects[project.id]
|
||||||
|
const target = (current.cards ?? []).find(item => item.id === id)
|
||||||
|
if (!target) throw new ServiceError('sansheng/card-not-found', `卡片 ${id} 不存在`)
|
||||||
|
target.status = 'answered'
|
||||||
|
target.answer = value
|
||||||
|
target.answerLabel = option.label
|
||||||
|
target.answeredAt = Date.now()
|
||||||
|
current.updatedAt = target.answeredAt
|
||||||
|
current.revision = (current.revision ?? 0) + 1
|
||||||
|
return structuredClone(target)
|
||||||
|
})
|
||||||
|
return { ok: true, card: answered }
|
||||||
|
}
|
||||||
|
|
||||||
async leadReports(projectId) {
|
async leadReports(projectId) {
|
||||||
await this.store.ensureLoaded()
|
await this.store.ensureLoaded()
|
||||||
const project = this.store.get(projectId)
|
const project = this.store.get(projectId)
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,17 @@ function normalizeProjects(state) {
|
||||||
if (!Array.isArray(project.artifacts)) project.artifacts = []
|
if (!Array.isArray(project.artifacts)) project.artifacts = []
|
||||||
if (!Array.isArray(project.requirements)) project.requirements = []
|
if (!Array.isArray(project.requirements)) project.requirements = []
|
||||||
if (!Array.isArray(project.approvals)) project.approvals = []
|
if (!Array.isArray(project.approvals)) project.approvals = []
|
||||||
|
if (!Array.isArray(project.cards)) project.cards = []
|
||||||
|
if (!Array.isArray(project.deliberations)) project.deliberations = []
|
||||||
|
if (!Number.isFinite(project.deliberationSeq)) project.deliberationSeq = 0
|
||||||
|
if (!Array.isArray(project.provinceRuns)) project.provinceRuns = []
|
||||||
|
if (project.avatars === null || typeof project.avatars !== 'object' || Array.isArray(project.avatars)) project.avatars = {}
|
||||||
if (!Array.isArray(project.leadReports)) project.leadReports = []
|
if (!Array.isArray(project.leadReports)) project.leadReports = []
|
||||||
|
if (!Array.isArray(project.secretaryRuns)) project.secretaryRuns = []
|
||||||
|
if (!Array.isArray(project.secretaryReports)) project.secretaryReports = []
|
||||||
|
if (!Array.isArray(project.requirementLog)) project.requirementLog = []
|
||||||
|
if (typeof project.secretarySessionId !== 'string' && project.secretarySessionId !== null && project.secretarySessionId !== undefined) project.secretarySessionId = null
|
||||||
|
if (typeof project.secretaryAgentId !== 'string' && project.secretaryAgentId !== null && project.secretaryAgentId !== undefined) project.secretaryAgentId = null
|
||||||
if (project.commandLedgers === null || typeof project.commandLedgers !== 'object' || Array.isArray(project.commandLedgers)) project.commandLedgers = {}
|
if (project.commandLedgers === null || typeof project.commandLedgers !== 'object' || Array.isArray(project.commandLedgers)) project.commandLedgers = {}
|
||||||
if (!Number.isFinite(project.taskSeq)) project.taskSeq = 0
|
if (!Number.isFinite(project.taskSeq)) project.taskSeq = 0
|
||||||
if (!Number.isFinite(project.artifactSeq)) project.artifactSeq = 0
|
if (!Number.isFinite(project.artifactSeq)) project.artifactSeq = 0
|
||||||
|
|
@ -143,7 +153,16 @@ export class SanshengStore {
|
||||||
await mkdir(dirname(this.file), { recursive: true })
|
await mkdir(dirname(this.file), { recursive: true })
|
||||||
const tmp = `${this.file}.${process.pid}.${Date.now()}.tmp`
|
const tmp = `${this.file}.${process.pid}.${Date.now()}.tmp`
|
||||||
await writeFile(tmp, JSON.stringify(this.state, null, 2), 'utf8')
|
await writeFile(tmp, JSON.stringify(this.state, null, 2), 'utf8')
|
||||||
await rename(tmp, this.file)
|
// Windows 上杀毒/索引可能短暂占用刚写完的临时文件,rename 会 EPERM;短重试后仍失败才报错。
|
||||||
|
for (let attempt = 0; ; attempt += 1) {
|
||||||
|
try {
|
||||||
|
await rename(tmp, this.file)
|
||||||
|
return
|
||||||
|
} catch (error) {
|
||||||
|
if (attempt >= 4) throw error
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 15 * (attempt + 1)))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 确保项目记录存在;已存在则只补空字段,不覆盖既有会话/配置。
|
// 确保项目记录存在;已存在则只补空字段,不覆盖既有会话/配置。
|
||||||
|
|
|
||||||
|
|
@ -65,7 +65,7 @@ function actorOf(located) {
|
||||||
return { seatId: located.seatId, sessionId: located.sessionId }
|
return { seatId: located.seatId, sessionId: located.sessionId }
|
||||||
}
|
}
|
||||||
|
|
||||||
function seatToolDefinitions({ store, service, turnCommands, leadBackground }) {
|
function seatToolDefinitions({ store, service, turnCommands, leadBackground, leadSecretaries, provinceAgents }) {
|
||||||
const definitions = []
|
const definitions = []
|
||||||
|
|
||||||
definitions.push({
|
definitions.push({
|
||||||
|
|
@ -379,6 +379,32 @@ function seatToolDefinitions({ store, service, turnCommands, leadBackground }) {
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if (typeof service?.deliberationSpeak === 'function') definitions.push({
|
||||||
|
name: 'sansheng_deliberation_speak',
|
||||||
|
description: '三省议政专用:只在当前议政轮到本席时提交本轮发言。发言会自动落进议政转录;不要在这里发布、批准或派工。',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
deliberationId: { type: 'string', description: '议政编号,如 D-001' },
|
||||||
|
round: { type: 'number', description: '当前轮次' },
|
||||||
|
text: { type: 'string', description: '本轮发言,白话说明本省判断和理由' },
|
||||||
|
stance: { type: 'string', enum: ['agree', 'dissent', 'neutral'], description: '同意 / 有分歧 / 未表态' },
|
||||||
|
pending: { type: 'boolean', description: '是否仍有待决问题' },
|
||||||
|
openIssues: { type: 'string', description: '未决点;没有就留空' },
|
||||||
|
},
|
||||||
|
required: ['deliberationId', 'round', 'text'],
|
||||||
|
},
|
||||||
|
async execute(args, exec) {
|
||||||
|
try {
|
||||||
|
const located = await locateSeat(service, exec)
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
...await service.deliberationSpeak(located.project.id, text(args.deliberationId), args, actorOf(located), exec?.callId),
|
||||||
|
}
|
||||||
|
} catch (error) { return failure(error) }
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
definitions.push({
|
definitions.push({
|
||||||
name: 'sansheng_task_decision',
|
name: 'sansheng_task_decision',
|
||||||
description: '丞相专用:无法按用户已知偏好解决实质分歧时,将问题及选项放入「待你处理」。',
|
description: '丞相专用:无法按用户已知偏好解决实质分歧时,将问题及选项放入「待你处理」。',
|
||||||
|
|
@ -411,6 +437,78 @@ function seatToolDefinitions({ store, service, turnCommands, leadBackground }) {
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if (leadSecretaries) definitions.push({
|
||||||
|
name: 'sansheng_lead_secretary',
|
||||||
|
description: '丞相专用。启动一位项目主簿或记室在后台工作:zhongshu、menxia、shangshu 分别对接中书/门下/尚书,requirement 是记室,负责记录用户需求。工具只等待宿主接收,不阻塞当前聊天;主簿或记室结束后回报。主簿与记室只读和记录,不发布、不批准、不派工。',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
role: { type: 'string', enum: ['zhongshu', 'menxia', 'shangshu', 'requirement'], description: '主簿或记室角色' },
|
||||||
|
brief: { type: 'string', description: '交给主簿或记室的后台工作说明,附上用户原话更佳' },
|
||||||
|
},
|
||||||
|
required: ['role', 'brief'],
|
||||||
|
},
|
||||||
|
async execute(args, exec) {
|
||||||
|
try { return await leadSecretaries.start(exec, args) } catch (error) { return failure(error) }
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (provinceAgents) definitions.push({
|
||||||
|
name: 'sansheng_order',
|
||||||
|
description: '丞相专用。把一条指令交给中书接令子 Agent:工具先返回回执(谁下的、关联任务或需求版本),接令核对后把用户原话和要点交回中书主席。不阻塞当前对话,不直接派工。',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
instruction: { type: 'string', description: '要下达给中书的指令,尽量保留用户原话和关键要求' },
|
||||||
|
taskId: { type: 'string', description: '关联任务 id,可选' },
|
||||||
|
requirementId: { type: 'string', description: '关联需求 id,可选' },
|
||||||
|
},
|
||||||
|
required: ['instruction'],
|
||||||
|
},
|
||||||
|
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 {
|
||||||
|
return { ok: true, ...await service.startOrder(located.project.id, args, actorOf(located)) }
|
||||||
|
} catch (error) { return failure(error) }
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (typeof service?.cardCreate === 'function') definitions.push({
|
||||||
|
name: 'sansheng_card',
|
||||||
|
description: '丞相专用。在当前丞相会话的消息流里挂一张非阻塞卡片,用户可以在聊天继续时点选,也可以回头答较早的卡;回答会回到本轮。问题卡提供 2 到 5 个选项;审批卡必须带 approvalId,选项只能是 allow/reject,模型只解释不代批,用户点选后仍回到原审批请求。',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
kind: { type: 'string', enum: ['question', 'approval'], description: '问题卡或审批卡' },
|
||||||
|
title: { type: 'string', description: '卡片标题,零基础白话' },
|
||||||
|
body: { type: 'string', description: '卡片正文:发生了什么、影响、为什么需要决定;审批卡还要写同意/拒绝的后果' },
|
||||||
|
options: {
|
||||||
|
type: 'array',
|
||||||
|
description: '用户可选项;问题卡 2 到 5 个,审批卡可省略(默认同意/拒绝)',
|
||||||
|
items: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
label: { type: 'string' }, value: { type: 'string' }, description: { type: 'string' },
|
||||||
|
},
|
||||||
|
required: ['label', 'value'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
approvalId: { type: 'string', description: '审批卡的原始审批 id' },
|
||||||
|
},
|
||||||
|
required: ['kind', 'title', 'body'],
|
||||||
|
},
|
||||||
|
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 {
|
||||||
|
return await service.cardCreate(located.project.id, { ...args, callId: exec?.callId }, actorOf(located))
|
||||||
|
} catch (error) { return failure(error) }
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
for (const definition of definitions) definition.output = seatToolOutput
|
for (const definition of definitions) definition.output = seatToolOutput
|
||||||
return definitions
|
return definitions
|
||||||
}
|
}
|
||||||
|
|
@ -489,8 +587,8 @@ function buildSeatToolGuard(store, sessionId) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function installSeatTools(ctx, { store, service, provisioner, turnCommands, leadBackground }) {
|
export function installSeatTools(ctx, { store, service, provisioner, turnCommands, leadBackground, leadSecretaries, provinceAgents }) {
|
||||||
const defs = createSeatToolDefinitions({ store, service, turnCommands, leadBackground })
|
const defs = createSeatToolDefinitions({ store, service, turnCommands, leadBackground, leadSecretaries, provinceAgents })
|
||||||
// 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 或工具系统尚未就绪的会话;等下一次席位事件/重扫再补装。
|
||||||
|
|
@ -531,7 +629,13 @@ 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_lead_background')
|
const sanshengSeat = SEAT_GROUPS.sansheng.includes(located.seatId)
|
||||||
|
const seatDefs = defs.filter(def => {
|
||||||
|
// 议政发言只给三省代表,丞相和六部都不挂。
|
||||||
|
if (def.name === 'sansheng_deliberation_speak') return sanshengSeat
|
||||||
|
if (located.seatId === 'lead') return true
|
||||||
|
return def.name !== 'sansheng_lead_background' && def.name !== 'sansheng_lead_secretary' && def.name !== 'sansheng_card' && def.name !== 'sansheng_order'
|
||||||
|
})
|
||||||
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)
|
||||||
|
|
|
||||||
|
|
@ -13,12 +13,14 @@ export const PROJECT_STATUS = Object.freeze(['pending', 'provisioning', 'ready',
|
||||||
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'])
|
||||||
// 需求清单:商讨中 / 待发布 / 已发布 / 已退回 / 已取消。
|
// 需求清单:商讨中 / 待发布 / 已发布 / 已退回 / 已取消。
|
||||||
export const REQUIREMENT_STATUS = Object.freeze(['discussing', 'ready', 'published', 'returned', 'cancelled'])
|
export const REQUIREMENT_STATUS = Object.freeze(['discussing', 'ready', 'published', 'returned', 'cancelled'])
|
||||||
|
export const DELIBERATION_STATUS = Object.freeze(['running', 'concluded', 'stopped'])
|
||||||
// 流程阶段:只由宿主服务推进,模型不能跳阶段。
|
// 流程阶段:只由宿主服务推进,模型不能跳阶段。
|
||||||
export const WORKFLOW_STAGE = Object.freeze(['zhongshu_draft', 'menxia_review', 'awaiting_execution_approval', 'shangshu_dispatch', 'department_exec', 'shangshu_summary', 'menxia_acceptance', 'lead_delivery', 'delivered', 'reconfirm'])
|
export const WORKFLOW_STAGE = Object.freeze(['zhongshu_draft', 'menxia_review', 'awaiting_execution_approval', 'shangshu_dispatch', 'department_exec', 'shangshu_summary', 'menxia_acceptance', 'lead_delivery', 'delivered', 'reconfirm'])
|
||||||
|
|
||||||
const SEAT_STATUS_SET = new Set(SEAT_STATUS)
|
const SEAT_STATUS_SET = new Set(SEAT_STATUS)
|
||||||
const PROJECT_STATUS_SET = new Set(PROJECT_STATUS)
|
const PROJECT_STATUS_SET = new Set(PROJECT_STATUS)
|
||||||
const TASK_STATUS_SET = new Set(TASK_STATUS)
|
const TASK_STATUS_SET = new Set(TASK_STATUS)
|
||||||
|
const DELIBERATION_STATUS_SET = new Set(DELIBERATION_STATUS)
|
||||||
|
|
||||||
function isObject(v) { return v !== null && typeof v === 'object' && !Array.isArray(v) }
|
function isObject(v) { return v !== null && typeof v === 'object' && !Array.isArray(v) }
|
||||||
function isStr(v) { return typeof v === 'string' && v.trim() !== '' }
|
function isStr(v) { return typeof v === 'string' && v.trim() !== '' }
|
||||||
|
|
@ -78,6 +80,17 @@ export function emptyProject({ id, name, workspaceId = null, path = null, now =
|
||||||
artifacts: [],
|
artifacts: [],
|
||||||
requirements: [],
|
requirements: [],
|
||||||
approvals: [],
|
approvals: [],
|
||||||
|
cards: [],
|
||||||
|
// 议政:项目级独立转录,不写进任务会商;旧数据没有时按空数组处理。
|
||||||
|
deliberations: [],
|
||||||
|
deliberationSeq: 0,
|
||||||
|
provinceRuns: [],
|
||||||
|
avatars: {},
|
||||||
|
secretaryRuns: [],
|
||||||
|
secretaryReports: [],
|
||||||
|
requirementLog: [],
|
||||||
|
secretarySessionId: null,
|
||||||
|
secretaryAgentId: null,
|
||||||
taskSeq: 0,
|
taskSeq: 0,
|
||||||
artifactSeq: 0,
|
artifactSeq: 0,
|
||||||
requirementSeq: 0,
|
requirementSeq: 0,
|
||||||
|
|
@ -175,6 +188,16 @@ function projectProblem(project, id) {
|
||||||
if (!isStr(approval.id)) return `项目 ${id} 的 approvals[${index}] 缺少 id`
|
if (!isStr(approval.id)) return `项目 ${id} 的 approvals[${index}] 缺少 id`
|
||||||
if (!['approved', 'invalidated'].includes(approval.status)) return `项目 ${id} 的批准 ${approval.id} 状态非法`
|
if (!['approved', 'invalidated'].includes(approval.status)) return `项目 ${id} 的批准 ${approval.id} 状态非法`
|
||||||
}
|
}
|
||||||
|
if (project.cards !== undefined && !Array.isArray(project.cards)) return `项目 ${id} 的 cards 不是数组`
|
||||||
|
if (project.deliberations !== undefined && !Array.isArray(project.deliberations)) return `项目 ${id} 的 deliberations 不是数组`
|
||||||
|
for (const [index, record] of (project.deliberations ?? []).entries()) {
|
||||||
|
if (!isObject(record)) return `项目 ${id} 的 deliberations[${index}] 不是对象`
|
||||||
|
if (!isStr(record.id)) return `项目 ${id} 的 deliberations[${index}] 缺少 id`
|
||||||
|
if (!DELIBERATION_STATUS_SET.has(record.status)) return `项目 ${id} 的议政 ${record.id} 状态非法:${String(record.status)}`
|
||||||
|
if (!Number.isFinite(record.round)) return `项目 ${id} 的议政 ${record.id} 轮次非法`
|
||||||
|
if (record.speeches !== undefined && !Array.isArray(record.speeches)) return `项目 ${id} 的议政 ${record.id} 发言不是数组`
|
||||||
|
}
|
||||||
|
if (project.deliberationSeq !== undefined && !Number.isFinite(project.deliberationSeq)) return `项目 ${id} 的 deliberationSeq 非法`
|
||||||
if (project.tasks !== undefined && !Array.isArray(project.tasks)) return `项目 ${id} 的 tasks 不是数组`
|
if (project.tasks !== undefined && !Array.isArray(project.tasks)) return `项目 ${id} 的 tasks 不是数组`
|
||||||
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}] 不是对象`
|
||||||
|
|
@ -183,6 +206,13 @@ function projectProblem(project, id) {
|
||||||
}
|
}
|
||||||
if (project.memory !== undefined && (project.memory === null || typeof project.memory !== 'object' || Array.isArray(project.memory))) return `项目 ${id} 的 memory 非法`
|
if (project.memory !== undefined && (project.memory === null || typeof project.memory !== 'object' || Array.isArray(project.memory))) return `项目 ${id} 的 memory 非法`
|
||||||
if (project.leadReports !== undefined && !Array.isArray(project.leadReports)) return `项目 ${id} 的 leadReports 不是数组`
|
if (project.leadReports !== undefined && !Array.isArray(project.leadReports)) return `项目 ${id} 的 leadReports 不是数组`
|
||||||
|
for (const key of ['secretaryRuns', 'secretaryReports', 'requirementLog', 'provinceRuns']) {
|
||||||
|
if (project[key] !== undefined && !Array.isArray(project[key])) return `项目 ${id} 的 ${key} 不是数组`
|
||||||
|
}
|
||||||
|
if (project.avatars !== undefined && (project.avatars === null || typeof project.avatars !== 'object' || Array.isArray(project.avatars))) return `项目 ${id} 的 avatars 非法`
|
||||||
|
for (const key of ['secretarySessionId', 'secretaryAgentId']) {
|
||||||
|
if (project[key] !== undefined && project[key] !== null && typeof project[key] !== 'string') return `项目 ${id} 的 ${key} 非法`
|
||||||
|
}
|
||||||
if (project.commandLedgers !== undefined && (project.commandLedgers === null || typeof project.commandLedgers !== 'object' || Array.isArray(project.commandLedgers))) return `项目 ${id} 的 commandLedgers 非法`
|
if (project.commandLedgers !== undefined && (project.commandLedgers === null || typeof project.commandLedgers !== 'object' || Array.isArray(project.commandLedgers))) return `项目 ${id} 的 commandLedgers 非法`
|
||||||
if (project.artifacts !== undefined && !Array.isArray(project.artifacts)) return `项目 ${id} 的 artifacts 不是数组`
|
if (project.artifacts !== undefined && !Array.isArray(project.artifacts)) return `项目 ${id} 的 artifacts 不是数组`
|
||||||
for (const [index, artifact] of (project.artifacts ?? []).entries()) {
|
for (const [index, artifact] of (project.artifacts ?? []).entries()) {
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
// 只测纯视图模型:绝不 import 会拉起 React 的 index.js。
|
// 只测纯视图模型:绝不 import 会拉起 React 的 index.js。
|
||||||
import test from 'node:test'
|
import test from 'node:test'
|
||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFile } from 'node:fs/promises'
|
||||||
import {
|
import {
|
||||||
buildWorkbenchView,
|
buildWorkbenchView,
|
||||||
collectModelOptions,
|
collectModelOptions,
|
||||||
|
|
@ -8,7 +9,16 @@ import {
|
||||||
UNCHOSEN_MODEL_LABEL,
|
UNCHOSEN_MODEL_LABEL,
|
||||||
} from '../src/client/workbench.js'
|
} from '../src/client/workbench.js'
|
||||||
|
|
||||||
// 与 CONTRACT.md 一致:十席固定编制、两字显示名。
|
// 丞相会话卡片:只注册宿主公开的 tool.call.toolview,不碰底部输入框。
|
||||||
|
test('丞相会话卡片按工具名注册,并从项目 store 读取/回答', async () => {
|
||||||
|
const index = await readFile(new URL('../src/client/index.js', import.meta.url), 'utf8')
|
||||||
|
assert.match(index, /tool\.call\.toolview/)
|
||||||
|
assert.match(index, /key: 'sansheng_card'/)
|
||||||
|
const cards = await readFile(new URL('../src/client/cards.js', import.meta.url), 'utf8')
|
||||||
|
assert.match(cards, /cardGet/)
|
||||||
|
assert.match(cards, /cardAnswer/)
|
||||||
|
assert.doesNotMatch(cards, /<textarea|<input|textarea\(|input\(/)
|
||||||
|
})
|
||||||
const SEAT_ROWS = [
|
const SEAT_ROWS = [
|
||||||
['lead', '丞相'],
|
['lead', '丞相'],
|
||||||
['zhongshu', '中书'],
|
['zhongshu', '中书'],
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ export async function tempStateFile() {
|
||||||
export function createFakeHost(opts = {}) {
|
export function createFakeHost(opts = {}) {
|
||||||
const sessions = new Map() // sessionId -> agent
|
const sessions = new Map() // sessionId -> agent
|
||||||
const workspaces = new Map() // id -> { id, name, path }
|
const workspaces = new Map() // id -> { id, name, path }
|
||||||
const calls = { create: [], resolve: [], selectModel: 0, agentSelect: [], createAt: [], prompt: [], followup: [], createUserMessage: [], flush: [], rename: [] }
|
const calls = { create: [], resolve: [], selectModel: 0, agentSelect: [], createAt: [], prompt: [], followup: [], createUserMessage: [], flush: [], rename: [], cancel: [] }
|
||||||
const control = {
|
const control = {
|
||||||
failCreateOrder: null, // 第 N 次 create 抛错(1 起)
|
failCreateOrder: null, // 第 N 次 create 抛错(1 起)
|
||||||
mismatchCreateOrder: null, // 第 N 次 create 返回另一个 ID
|
mismatchCreateOrder: null, // 第 N 次 create 返回另一个 ID
|
||||||
|
|
@ -49,6 +49,9 @@ export function createFakeHost(opts = {}) {
|
||||||
calls.followup.push({ sessionId, message })
|
calls.followup.push({ sessionId, message })
|
||||||
if (typeof control.followupHook === 'function') await control.followupHook(sessionId, message)
|
if (typeof control.followupHook === 'function') await control.followupHook(sessionId, message)
|
||||||
},
|
},
|
||||||
|
cancel(reason) {
|
||||||
|
calls.cancel.push({ sessionId, reason })
|
||||||
|
},
|
||||||
}
|
}
|
||||||
sessions.set(sessionId, agent)
|
sessions.set(sessionId, agent)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -51,6 +51,9 @@ test('丞相提示包含 Grill Me 规则,其他九席不注入', async () => {
|
||||||
assert.match(leadText, /expectedRevision/)
|
assert.match(leadText, /expectedRevision/)
|
||||||
assert.match(leadText, /dispatchAfterClarification=true/)
|
assert.match(leadText, /dispatchAfterClarification=true/)
|
||||||
assert.match(leadText, /authorization=clarified/)
|
assert.match(leadText, /authorization=clarified/)
|
||||||
|
assert.match(leadText, /sansheng_lead_secretary/)
|
||||||
|
assert.match(leadText, /零基础白话/)
|
||||||
|
assert.match(leadText, /sansheng-report/)
|
||||||
assert.doesNotMatch(leadText, /发布 R-xxx 给中书/)
|
assert.doesNotMatch(leadText, /发布 R-xxx 给中书/)
|
||||||
|
|
||||||
for (const seatId of ['zhongshu', 'menxia', 'shangshu', 'libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']) {
|
for (const seatId of ['zhongshu', 'menxia', 'shangshu', 'libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']) {
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,7 @@ async function makeService() {
|
||||||
const service = new SanshengService({ store, host: fake.host, provisioner, globalStore, modelSync })
|
const service = new SanshengService({ store, host: fake.host, provisioner, globalStore, modelSync })
|
||||||
const opened = await service.open({ path: '/model-service', name: '模型服务项目' })
|
const opened = await service.open({ path: '/model-service', name: '模型服务项目' })
|
||||||
await service.enableSeat(opened.project.id, 'gongbu')
|
await service.enableSeat(opened.project.id, 'gongbu')
|
||||||
return { service, projectId: opened.project.id, globalStore, fake }
|
return { service, projectId: opened.project.id, globalStore, fake, modelSync }
|
||||||
}
|
}
|
||||||
|
|
||||||
test('service:全局默认继承、项目覆盖优先、清除覆盖回全局', async () => {
|
test('service:全局默认继承、项目覆盖优先、清除覆盖回全局', async () => {
|
||||||
|
|
@ -45,3 +45,16 @@ test('service:全局默认继承、项目覆盖优先、清除覆盖回全局'
|
||||||
assert.equal(seat.modelSource, 'global')
|
assert.equal(seat.modelSource, 'global')
|
||||||
assert.equal(seat.configuredModel.model, 'deepseek-reasoner')
|
assert.equal(seat.configuredModel.model, 'deepseek-reasoner')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('model sync:活 agentRef 不参与状态深拷贝', async () => {
|
||||||
|
const { service, projectId, fake, modelSync } = await makeService()
|
||||||
|
const view = await service.project(projectId)
|
||||||
|
const seat = view.project.seats.find(item => item.id === 'gongbu')
|
||||||
|
const agent = fake.sessions.get(seat.sessionId)
|
||||||
|
Object.defineProperty(agent, 'toJSON', {
|
||||||
|
enumerable: false,
|
||||||
|
value() { throw new Error('cannot get property "toJSON" without inject') },
|
||||||
|
})
|
||||||
|
const status = await modelSync.syncSeat(projectId, 'gongbu', 'test')
|
||||||
|
assert.equal(status.status, 'synced')
|
||||||
|
})
|
||||||
|
|
|
||||||
|
|
@ -43,7 +43,7 @@ function makeEventedCtx(env) {
|
||||||
return { ctx, registered, disposed, guards, emit }
|
return { ctx, registered, disposed, guards, emit }
|
||||||
}
|
}
|
||||||
|
|
||||||
const TOOL_COUNT = createSeatToolDefinitions({}).length
|
const TOOL_COUNT = createSeatToolDefinitions({ service: { cardCreate() {} } }).length
|
||||||
|
|
||||||
test('回归:创建事件先到、绑定后保存时,绑定成功即补装部门工具(无需重扫)', async () => {
|
test('回归:创建事件先到、绑定后保存时,绑定成功即补装部门工具(无需重扫)', async () => {
|
||||||
const env = await setupService({ prompt: true })
|
const env = await setupService({ prompt: true })
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue