0.7.0:每个部门都能单独固定模型(面板下发 /dept-model,模式插件按角色生效)
This commit is contained in:
parent
a1a40df16c
commit
cfd4b0957a
10
CHANGELOG.md
10
CHANGELOG.md
|
|
@ -1,6 +1,14 @@
|
|||
# Changelog
|
||||
|
||||
> 版本号以 `package.json` 为准(当前 0.6.0)。更早的 0.6.x 条目沿用旧编号,保留作历史。
|
||||
> 版本号以 `package.json` 为准(当前 0.7.0)。更早的 0.6.x 条目沿用旧编号,保留作历史。
|
||||
|
||||
## 0.7.0 — 每个部门可以单独固定模型
|
||||
|
||||
- 部门是子会话(`origin: "subagent"`),宿主的 `session.selectModel` 对它们一律拒绝(`session/agent-busy`,建议走 subagent delivery),所以「在这里选好就生效」原来根本做不到。现在面板改为下发 `/dept-model <部门> <provider> <model> [推理等级]` 指令,由模式插件按角色把模型写进运行时路由表并落盘 `routes.json`,`agent/request` 钩子在下一轮开工时生效。
|
||||
- 模式插件新增 `parseDeptModelCommand` / `describeDeptRoutes` / `readStoredRoutes` / `writeStoredRoutes`:支持 set、`list`、`clear [部门]`,未知部门与参数不足各自给出可读原因;路由文件按 `DSH_HOME`(缺省 `~/.dsh`)下的 `sansheng-liubu/routes.json` 读写,读不到就当没固定过。
|
||||
- 面板「模型设置」对部门显示「按部门固定」,选好保存即固定,脚注显示「该部门固定使用此模型」;每个部门的固定值用 `localStorage` 记在面板侧(`sansheng-liubu.route.<角色>`),用于显示当前模型。
|
||||
- 预览脚本新增 `--seat=<角色>`,可以直接截某个部门的详情;演示数据补了 `localStorage` 与部门子会话地址,工部示例固定为 DeepSeek V4。
|
||||
- 测试:客户端新增「改模型改由丞相会话下发 /dept-model」「固定路由从面板记录读出来当当前模型」两项;策略侧新增指令解析与路由文件往返用例。`node --test` 48 项全过。
|
||||
|
||||
## 0.6.0 — 模型选择真的能用了
|
||||
|
||||
|
|
|
|||
111
index.js
111
index.js
|
|
@ -1,3 +1,7 @@
|
|||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
|
||||
const PRESET_ID = 'sansheng-liubu'
|
||||
export const POLICY_VERSION = '0.4.0'
|
||||
|
||||
|
|
@ -189,18 +193,120 @@ function normalizeRoutes(routes = {}) {
|
|||
return merged
|
||||
}
|
||||
|
||||
/**
|
||||
* 面板上的「部门模型」走这条指令:宿主的 session.selectModel 会拒绝子会话
|
||||
* (`session.header.origin === "subagent"` → session/agent-busy),所以部门模型
|
||||
* 只能由本插件在 agent/request 时改,面板则用 /dept-model 把选择下发过来。
|
||||
*/
|
||||
export const DEPT_MODEL_COMMAND = 'dept-model'
|
||||
export const DEPT_MODEL_USAGE = '<部门> <provider> <model> [推理等级] | list | clear [部门]'
|
||||
|
||||
export function routesFilePath(env = process.env) {
|
||||
const home = typeof env.DSH_HOME === 'string' && env.DSH_HOME.trim() ? env.DSH_HOME.trim() : path.join(os.homedir(), '.dsh')
|
||||
return path.join(home, 'sansheng-liubu', 'routes.json')
|
||||
}
|
||||
|
||||
export function readStoredRoutes(file) {
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
|
||||
return normalizeRoutes(parsed && typeof parsed === 'object' ? parsed : {})
|
||||
} catch (error) { return {} }
|
||||
}
|
||||
|
||||
export function writeStoredRoutes(file, routes) {
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true })
|
||||
fs.writeFileSync(file, JSON.stringify(routes, null, 2) + '\n', 'utf8')
|
||||
return true
|
||||
} catch (error) { return false }
|
||||
}
|
||||
|
||||
export function parseDeptModelCommand(rawInput) {
|
||||
const tokens = String(rawInput === undefined || rawInput === null ? '' : rawInput).trim().split(/\s+/).filter(Boolean)
|
||||
if (tokens.length === 0 || tokens[0].toLowerCase() === 'list') return { action: 'list' }
|
||||
const head = tokens[0].toLowerCase()
|
||||
if (head === 'clear' || head === 'reset') {
|
||||
const role = (tokens[1] || '').toLowerCase()
|
||||
if (role && !COURT_ROLES.includes(role)) return { action: 'error', reason: `未知部门:${tokens[1]}` }
|
||||
return { action: 'clear', role: role || undefined }
|
||||
}
|
||||
if (!COURT_ROLES.includes(head)) return { action: 'error', reason: `未知部门:${tokens[0]}(可用:${COURT_ROLES.join('、')})` }
|
||||
if (tokens.length < 3) return { action: 'error', reason: `用法:/${DEPT_MODEL_COMMAND} ${DEPT_MODEL_USAGE}` }
|
||||
const reasoningEffort = tokens[3]
|
||||
return {
|
||||
action: 'set',
|
||||
role: head,
|
||||
route: { provider: tokens[1], model: tokens[2], ...(reasoningEffort ? { reasoningEffort } : {}) },
|
||||
}
|
||||
}
|
||||
|
||||
export function describeDeptRoutes(routes = {}) {
|
||||
const entries = Object.entries(routes).filter(([, route]) => route && route.provider && route.model)
|
||||
if (entries.length === 0) return `十席目前都跟随宿主默认模型;用 /${DEPT_MODEL_COMMAND} ${DEPT_MODEL_USAGE} 逐个固定。`
|
||||
return '部门固定模型:' + entries
|
||||
.map(([role, route]) => `${role}=${route.provider}/${route.model}${route.reasoningEffort ? '·' + route.reasoningEffort : ''}`)
|
||||
.join(';')
|
||||
}
|
||||
|
||||
function registerDeptModelCommand(ctx, handler) {
|
||||
if (!ctx.commands || typeof ctx.commands.register !== 'function') return () => {}
|
||||
try {
|
||||
const dispose = ctx.effect(function* () {
|
||||
yield ctx.commands.register({
|
||||
name: DEPT_MODEL_COMMAND,
|
||||
description: '固定某个部门的模型(面板「模型设置」用)',
|
||||
input: { hint: DEPT_MODEL_USAGE },
|
||||
handler: invocation => handler(invocation && invocation.rawInput),
|
||||
})
|
||||
}, `sansheng-liubu: /${DEPT_MODEL_COMMAND}`)
|
||||
return typeof dispose === 'function' ? dispose : () => {}
|
||||
} catch (error) {
|
||||
ctx.logger?.warn?.(`[sansheng-liubu] 注册 /${DEPT_MODEL_COMMAND} 失败:${error && error.message ? error.message : error}`)
|
||||
return () => {}
|
||||
}
|
||||
}
|
||||
|
||||
const INSTALLATIONS = globalThis[Symbol.for('dsh.sansheng-liubu.installations')] ??=
|
||||
new WeakMap()
|
||||
|
||||
export const name = 'sansheng-liubu-mode'
|
||||
export const inject = ['agents', 'agentTeams', 'agentPresets', 'systemPrompt', 'tools']
|
||||
export const inject = ['agents', 'agentTeams', 'agentPresets', 'systemPrompt', 'tools', 'commands']
|
||||
|
||||
export function apply(ctx, config = {}) {
|
||||
const presetId = typeof config.presetId === 'string' ? config.presetId : PRESET_ID
|
||||
const routes = normalizeRoutes(config.routes)
|
||||
const routeFile = routesFilePath()
|
||||
const routes = normalizeRoutes({ ...readStoredRoutes(routeFile), ...(config.routes || {}) })
|
||||
const owned = new Map()
|
||||
const audit = entry => ctx.logger?.info?.(`[sansheng-liubu:audit] ${JSON.stringify({ at: new Date().toISOString(), ...entry })}`)
|
||||
|
||||
const persist = () => {
|
||||
if (writeStoredRoutes(routeFile, routes)) return
|
||||
ctx.logger?.warn?.(`[sansheng-liubu] 路由表写入失败:${routeFile}`)
|
||||
}
|
||||
|
||||
const runDeptModel = rawInput => {
|
||||
const parsed = parseDeptModelCommand(rawInput)
|
||||
if (parsed.action === 'error') return { kind: 'error', text: parsed.reason }
|
||||
if (parsed.action === 'list') return { kind: 'success', text: describeDeptRoutes(routes) }
|
||||
if (parsed.action === 'clear') {
|
||||
if (parsed.role) delete routes[parsed.role]
|
||||
else for (const role of Object.keys(routes)) delete routes[role]
|
||||
persist()
|
||||
return {
|
||||
kind: 'success',
|
||||
text: parsed.role ? `${parsed.role} 已恢复跟随宿主默认模型。` : '十席都已恢复跟随宿主默认模型。',
|
||||
}
|
||||
}
|
||||
routes[parsed.role] = parsed.route
|
||||
persist()
|
||||
const effort = parsed.route.reasoningEffort ? `(推理等级 ${parsed.route.reasoningEffort})` : ''
|
||||
return {
|
||||
kind: 'success',
|
||||
text: `${parsed.role} 已固定为 ${parsed.route.provider}/${parsed.route.model}${effort},该部门下一轮开工即生效。`,
|
||||
}
|
||||
}
|
||||
const disposeCommand = registerDeptModelCommand(ctx, runDeptModel)
|
||||
|
||||
const uninstall = agent => {
|
||||
const release = owned.get(agent)
|
||||
if (!release) return
|
||||
|
|
@ -269,6 +375,7 @@ export function apply(ctx, config = {}) {
|
|||
const disposeDisposed = ctx.on('agent/disposed', ({ agent }) => uninstall(agent))
|
||||
|
||||
return () => {
|
||||
disposeCommand()
|
||||
disposeCreated()
|
||||
disposeDisposed()
|
||||
for (const agent of [...owned.keys()]) uninstall(agent)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "dsh-sansheng-liubu-mode",
|
||||
"version": "0.6.0",
|
||||
"version": "0.7.0",
|
||||
"private": true,
|
||||
"description": "上朝:丞相统筹的三省六部多 Agent 模式",
|
||||
"type": "module",
|
||||
|
|
|
|||
|
|
@ -221,10 +221,38 @@ window.__ModuleLoader__.load({
|
|||
return options.find((option) => option.provider === current.provider && option.model === current.model);
|
||||
}
|
||||
|
||||
/** 部门模型指令:宿主拒绝给子会话直接改模型,改由丞相会话下发到模式插件。 */
|
||||
const DEPT_MODEL_COMMAND = "dept-model";
|
||||
|
||||
function seatRouteKey(role) {
|
||||
return "sansheng-liubu.route." + role;
|
||||
}
|
||||
|
||||
/** 面板记住每个部门的固定模型(宿主插件另存一份在 routes.json)。 */
|
||||
function readSeatRoute(role) {
|
||||
try {
|
||||
const store = globalThis.localStorage;
|
||||
if (!store || typeof store.getItem !== "function") return undefined;
|
||||
const raw = store.getItem(seatRouteKey(role));
|
||||
if (!raw) return undefined;
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!parsed || typeof parsed.provider !== "string" || typeof parsed.model !== "string") return undefined;
|
||||
return {
|
||||
provider: parsed.provider,
|
||||
model: parsed.model,
|
||||
...(typeof parsed.reasoningEffort === "string" && parsed.reasoningEffort ? { reasoningEffort: parsed.reasoningEffort } : {}),
|
||||
};
|
||||
} catch (error) { return undefined; }
|
||||
}
|
||||
|
||||
function writeSeatRoute(role, route) {
|
||||
try {
|
||||
const store = globalThis.localStorage;
|
||||
if (store && typeof store.setItem === "function") store.setItem(seatRouteKey(role), JSON.stringify(route));
|
||||
} catch (error) { /* 记不住就只影响下次刷新,不报错 */ }
|
||||
}
|
||||
|
||||
function modelSwitchPlan(current, next, addressesSubagent) {
|
||||
if (addressesSubagent === true) {
|
||||
return { ok: false, reason: "子会话不能单独更换模型;请在丞相会话中设置,或新建会话时选择" };
|
||||
}
|
||||
if (!next || !next.provider || !next.model) return { ok: false, reason: "未选择模型" };
|
||||
const effort = next.reasoningEffort === undefined ? undefined : next.reasoningEffort;
|
||||
if (current && current.provider === next.provider && current.model === next.model && (current.reasoningEffort || undefined) === effort) {
|
||||
|
|
@ -232,7 +260,8 @@ window.__ModuleLoader__.load({
|
|||
}
|
||||
const payload = { provider: next.provider, model: next.model };
|
||||
if (effort !== undefined) payload.reasoningEffort = effort;
|
||||
return { ok: true, payload };
|
||||
// 部门是子会话:宿主不给它们单独改模型,改走模式插件的 /dept-model 路由。
|
||||
return { ok: true, payload, via: addressesSubagent === true ? "command" : "session" };
|
||||
}
|
||||
|
||||
function decreeText(role, text, team) {
|
||||
|
|
@ -673,16 +702,16 @@ button.sl-stat-members:focus-visible{outline:2px solid color-mix(in srgb,var(--s
|
|||
if (!targetId) { setCatalog({ status: "idle", options: [], error: null, current: undefined, subagent: false }); return undefined; }
|
||||
let alive = true;
|
||||
setCatalog((prev) => ({ ...prev, status: "loading", error: null }));
|
||||
host.loadCatalog(targetId).then((result) => {
|
||||
host.loadCatalog(targetId, seat && seat.role).then((result) => {
|
||||
if (!alive) return;
|
||||
setCatalog({ status: "ready", options: result.options, current: result.current, error: result.error, subagent: result.subagent, unresolved: result.unresolved === true, inherited: result.inherited === true });
|
||||
setCatalog({ status: "ready", options: result.options, current: result.current, error: result.error, subagent: result.subagent, fixed: result.fixed === true, unresolved: result.unresolved === true, inherited: result.inherited === true });
|
||||
setDraftModel(result.current ? result.current.provider + "/" + result.current.model : "");
|
||||
setDraftEffort((result.current && result.current.reasoningEffort) || "");
|
||||
}, (error) => {
|
||||
if (alive) setCatalog({ status: "error", options: [], error: String(error && error.message || error), current: undefined, subagent: false });
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, [targetId, catalogRetry]);
|
||||
}, [targetId, seat && seat.role, catalogRetry]);
|
||||
|
||||
const presetForSeat = seat && seat.id && sessions.byId[seat.id] && sessions.byId[seat.id].projectionValues
|
||||
? sessions.byId[seat.id].projectionValues.agentPreset
|
||||
|
|
@ -692,7 +721,7 @@ button.sl-stat-members:focus-visible{outline:2px solid color-mix(in srgb,var(--s
|
|||
const currentModelValue = catalog.current ? catalog.current.provider + "/" + catalog.current.model : "";
|
||||
const currentEffortValue = (catalog.current && catalog.current.reasoningEffort) || "";
|
||||
const modelDirty = draftModel !== currentModelValue || draftEffort !== currentEffortValue;
|
||||
const canSaveModel = Boolean(chosenOption && seat && seat.id && modelDirty && !catalog.subagent && !busy);
|
||||
const canSaveModel = Boolean(chosenOption && seat && seat.id && modelDirty && !busy);
|
||||
|
||||
const applyModel = () => {
|
||||
if (!chosenOption || !seat || !seat.id) return;
|
||||
|
|
@ -703,11 +732,15 @@ button.sl-stat-members:focus-visible{outline:2px solid color-mix(in srgb,var(--s
|
|||
}, catalog.subagent);
|
||||
if (!plan.ok) { setNotice({ kind: "error", text: plan.reason }); return; }
|
||||
setBusy(true);
|
||||
host.selectModel(seat.id, plan.payload).then((result) => {
|
||||
const request = plan.via === "command"
|
||||
? host.routeModel(seat.role, plan.payload)
|
||||
: host.selectModel(seat.id, plan.payload);
|
||||
request.then((result) => {
|
||||
setBusy(false);
|
||||
if (result.ok) {
|
||||
setNotice({ kind: "ok", text: "已切换到 " + chosenOption.label });
|
||||
setCatalog((prev) => ({ ...prev, current: plan.payload }));
|
||||
if (plan.via === "command") writeSeatRoute(seat.role, plan.payload);
|
||||
setNotice({ kind: "ok", text: (plan.via === "command" ? "已把 " + seat.label + " 固定为 " : "已切换到 ") + chosenOption.label });
|
||||
setCatalog((prev) => ({ ...prev, current: plan.payload, fixed: plan.via === "command" ? true : prev.fixed }));
|
||||
} else {
|
||||
setNotice({ kind: "error", text: result.error });
|
||||
}
|
||||
|
|
@ -896,9 +929,10 @@ button.sl-stat-members:focus-visible{outline:2px solid color-mix(in srgb,var(--s
|
|||
seat && seat.present ? h("div", { className: "sl-setting-block" }, [
|
||||
h("div", { className: "sl-setting-head" }, [
|
||||
h("h3", { children: "模型设置" }),
|
||||
h("small", { children: catalog.subagent ? "子会话跟随丞相" : "只影响该部门" }),
|
||||
h("small", { children: catalog.subagent ? "按部门固定" : "只影响该部门" }),
|
||||
]),
|
||||
catalog.subagent ? h("div", { className: "sl-hint", children: "子会话沿用丞相模型,不能在这里单独切换。" }) : h(React.Fragment, null, [
|
||||
catalog.subagent ? h("div", { className: "sl-hint", children: "部门是子会话,宿主不允许事后单独改;这里选好后由模式把它固定下来,下一轮开工即用。" }) : null,
|
||||
h(React.Fragment, null, [
|
||||
h("div", { className: "sl-model-grid" }, [
|
||||
h("label", { className: "sl-control" }, [
|
||||
h("span", { children: "模型" }),
|
||||
|
|
@ -939,10 +973,10 @@ button.sl-stat-members:focus-visible{outline:2px solid color-mix(in srgb,var(--s
|
|||
onClick: applyModel,
|
||||
children: busy ? "保存中…" : "保存模型设置",
|
||||
}),
|
||||
h("small", { className: modelDirty ? "is-dirty" : "", children: catalog.subagent
|
||||
? "子会话沿用丞相模型"
|
||||
: modelDirty
|
||||
? "有未保存的更改"
|
||||
h("small", { className: modelDirty ? "is-dirty" : "", children: modelDirty
|
||||
? "有未保存的更改"
|
||||
: catalog.fixed
|
||||
? "该部门固定使用此模型"
|
||||
: catalog.inherited
|
||||
? (catalog.unresolved ? "该部门会话未在本页打开,选好保存后直接生效" : "当前:跟随默认(" + modelLabel(catalog.current) + ")")
|
||||
: "当前:" + (catalog.current ? modelLabel(catalog.current) : "未设置") }),
|
||||
|
|
@ -955,7 +989,7 @@ button.sl-stat-members:focus-visible{outline:2px solid color-mix(in srgb,var(--s
|
|||
onClick: () => setCatalogRetry((value) => value + 1),
|
||||
children: "重试读取模型",
|
||||
}) : null,
|
||||
]) : null,
|
||||
]) : null,
|
||||
h("div", { className: "sl-conversation-block" }, [
|
||||
h("button", {
|
||||
type: "button",
|
||||
|
|
@ -1347,8 +1381,10 @@ button.sl-stat-members:focus-visible{outline:2px solid color-mix(in srgb,var(--s
|
|||
error: error ? "读取预设失败:" + String(error && error.message || error) : "读取预设超时:宿主 6 秒没有响应",
|
||||
}));
|
||||
},
|
||||
loadCatalog(sessionId) {
|
||||
loadCatalog(sessionId, role) {
|
||||
const subagentOf = (id) => (typeof sessions.subagentAddress === "function" ? sessions.subagentAddress(id) !== undefined : false);
|
||||
const isSubagent = subagentOf(sessionId);
|
||||
const fixed = isSubagent ? readSeatRoute(role) : undefined;
|
||||
// 模型清单是全局的:宿主同时只维护一份,任何会话都能读到;会话只决定「当前选的是哪个」。
|
||||
const global = modelCatalogOf();
|
||||
if (global.service === false) {
|
||||
|
|
@ -1379,10 +1415,11 @@ button.sl-stat-members:focus-visible{outline:2px solid color-mix(in srgb,var(--s
|
|||
const fallback = value && value.default ? value.default : undefined;
|
||||
return {
|
||||
options: modelOptions(value),
|
||||
current: own || fallback,
|
||||
inherited: own ? false : Boolean(fallback),
|
||||
current: fixed || own || fallback,
|
||||
inherited: fixed ? false : own ? false : Boolean(fallback),
|
||||
fixed: Boolean(fixed),
|
||||
error: (extra && extra.error) || directoryError() || null,
|
||||
subagent: subagentOf(sessionId),
|
||||
subagent: isSubagent,
|
||||
unresolved: Boolean(extra && extra.unresolved),
|
||||
};
|
||||
};
|
||||
|
|
@ -1422,6 +1459,17 @@ button.sl-stat-members:focus-visible{outline:2px solid color-mix(in srgb,var(--s
|
|||
return { ok: false, error: detail };
|
||||
}, (error) => ({ ok: false, error: String((error && error.message) || error) }));
|
||||
},
|
||||
/** 子会话不能直接改模型,改由丞相会话把指令下发给模式插件。 */
|
||||
routeModel(role, payload) {
|
||||
const lead = currentSession();
|
||||
if (!lead) return Promise.resolve({ ok: false, error: "没有可下发指令的丞相会话" });
|
||||
const text = "/" + DEPT_MODEL_COMMAND + " " + role + " " + payload.provider + " " + payload.model +
|
||||
(payload.reasoningEffort ? " " + payload.reasoningEffort : "");
|
||||
return deliverPrompt(lead, text).then((result) => {
|
||||
if (result.ok) return { ok: true, text: text };
|
||||
return { ok: false, error: result.error || "下发部门模型失败" };
|
||||
});
|
||||
},
|
||||
selectPreset(sessionId, presetId) {
|
||||
const remote = presetsRemote();
|
||||
if (!remote || typeof remote.select !== "function") return Promise.resolve({ ok: false, error: "当前宿主未提供 Agent 预设接口" });
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "dsh-sansheng-liubu-panel",
|
||||
"version": "0.6.0",
|
||||
"version": "0.7.0",
|
||||
"private": true,
|
||||
"description": "三省六部 Agent 面板:在 DSH Web GUI 中常驻显示并切换团队 Agent",
|
||||
"type": "module",
|
||||
|
|
|
|||
|
|
@ -57,8 +57,14 @@ function loadPlugin() {
|
|||
},
|
||||
},
|
||||
}
|
||||
vm.runInNewContext(source, { window, document, console, URL, Map, Set, WeakMap, Promise, setTimeout, clearTimeout }, { filename: 'client.js' })
|
||||
return { loaded, exports: loaded.exports, styleCount: () => styleCount, css: () => cssText }
|
||||
const storage = new Map()
|
||||
const localStorage = {
|
||||
getItem: (key) => (storage.has(key) ? storage.get(key) : null),
|
||||
setItem: (key, value) => { storage.set(key, String(value)) },
|
||||
removeItem: (key) => { storage.delete(key) },
|
||||
}
|
||||
vm.runInNewContext(source, { window, document, console, URL, Map, Set, WeakMap, Promise, setTimeout, clearTimeout, localStorage }, { filename: 'client.js' })
|
||||
return { loaded, exports: loaded.exports, styleCount: () => styleCount, css: () => cssText, storage }
|
||||
}
|
||||
|
||||
/** 全局模型清单的样板值:宿主一代只给一份,任何会话读到的都是它。 */
|
||||
|
|
@ -398,7 +404,10 @@ test('builds model options with reasoning efforts', () => {
|
|||
assert.equal(plan.ok, true)
|
||||
assert.equal(plan.payload.provider, 'moonshotai-cn')
|
||||
assert.equal(plan.payload.reasoningEffort, 'high')
|
||||
assert.equal(modelSwitchPlan(undefined, { provider: 'a', model: 'b' }, true).ok, false, '子会话不能单独换模型')
|
||||
const subagentPlan = modelSwitchPlan(undefined, { provider: 'a', model: 'b' }, true)
|
||||
assert.equal(subagentPlan.ok, true, '子会话改模型走模式插件的部门路由')
|
||||
assert.equal(subagentPlan.via, 'command')
|
||||
assert.equal(modelSwitchPlan({ provider: 'a', model: 'b' }, { provider: 'a', model: 'b' }, true).ok, false, '同样的选择不必再保存')
|
||||
})
|
||||
|
||||
test('formats a decree with the target department', () => {
|
||||
|
|
@ -921,3 +930,35 @@ test('正常路径给出全局清单与该会话自己的当前选择', async ()
|
|||
assert.equal(result.options.length, 2)
|
||||
assert.deepEqual(result.current, { provider: 'p', model: 'm' })
|
||||
})
|
||||
|
||||
test('部门是子会话时,改模型改由丞相会话下发 /dept-model', async () => {
|
||||
const prompts = []
|
||||
const { host } = catalogHost({
|
||||
sessions: {
|
||||
list: () => [],
|
||||
binding: (sessionId) => ({
|
||||
session: { prompt: async (parts, mode) => { prompts.push({ sessionId, parts, mode }); return { ok: true } } },
|
||||
}),
|
||||
subagentAddress: () => ({ parentSessionId: 'lead-1', childSessionId: 'gongbu-1' }),
|
||||
refreshProjections: async () => {},
|
||||
},
|
||||
})
|
||||
const result = await host.routeModel('gongbu', { provider: 'deepseek', model: 'deepseek-chat', reasoningEffort: 'high' })
|
||||
assert.equal(result.ok, true)
|
||||
assert.equal(prompts.length, 1)
|
||||
assert.equal(prompts[0].sessionId, 'lead-1', '指令投给丞相会话')
|
||||
assert.equal(prompts[0].parts[0].text, '/dept-model gongbu deepseek deepseek-chat high')
|
||||
})
|
||||
|
||||
test('子会话的固定路由从面板记录里读出来当「当前模型」', async () => {
|
||||
const { exports, storage } = loadPlugin()
|
||||
storage.set('sansheng-liubu.route.gongbu', JSON.stringify({ provider: 'deepseek', model: 'deepseek-reasoner', reasoningEffort: 'high' }))
|
||||
const context = mockContext()
|
||||
context.ctx.sessions.subagentAddress = () => ({ parentSessionId: 'lead-1', childSessionId: 'gongbu-1' })
|
||||
exports.apply(context.ctx)
|
||||
const host = exports.createHost(context.ctx)
|
||||
const result = await host.loadCatalog('gongbu-1', 'gongbu')
|
||||
assert.equal(result.fixed, true, '有固定路由时不算继承')
|
||||
assert.equal(result.current.model, 'deepseek-reasoner')
|
||||
assert.equal(result.current.reasoningEffort, 'high')
|
||||
})
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ const DEFAULTS = {
|
|||
out: 'dsh-image-gen',
|
||||
width: 440,
|
||||
view: 'court',
|
||||
seat: 'lead',
|
||||
theme: 'light',
|
||||
name: 'panel-preview-sidebar',
|
||||
source: 'panel/lib/client.js',
|
||||
|
|
@ -65,6 +66,7 @@ function printHelp() {
|
|||
--out=<目录> PNG 输出目录(默认 ${DEFAULTS.out})
|
||||
--width=<像素> 侧栏容器宽度 320-900(默认 ${DEFAULTS.width})
|
||||
--view=<court|tasks> 渲染页签(默认 ${DEFAULTS.view})
|
||||
--seat=<角色> 选中哪个席位,如 gongbu(默认 ${DEFAULTS.seat})
|
||||
--theme=<light|dark> 主题(默认 ${DEFAULTS.theme})
|
||||
--name=<文件名> 输出文件名,不含扩展名(默认 ${DEFAULTS.name})
|
||||
--source=<路径> 要渲染的 client.js(默认 ${DEFAULTS.source},A/B 对比用)
|
||||
|
|
@ -111,6 +113,7 @@ function parseArgs(argv) {
|
|||
options.viewport = toInt(options.viewport, '--viewport', 0, 4000)
|
||||
if (!VIEWS.includes(options.view)) fail(`--view 只能是 ${VIEWS.join(' / ')},收到:${options.view}`)
|
||||
if (!THEMES.includes(options.theme)) fail(`--theme 只能是 ${THEMES.join(' / ')},收到:${options.theme}`)
|
||||
if (!DEMO_ROLES.includes(options.seat)) fail(`--seat 只能是 ${DEMO_ROLES.join(' / ')},收到:${options.seat}`)
|
||||
if (!options.name || /[\\/:*?"<>|]/.test(options.name)) fail(`--name 不能为空或包含路径字符:${options.name}`)
|
||||
|
||||
options.out = resolve(ROOT, options.out)
|
||||
|
|
@ -351,6 +354,7 @@ function loadBundle(sourcePath, hooks) {
|
|||
clearTimeout,
|
||||
setImmediate,
|
||||
queueMicrotask,
|
||||
localStorage: createDemoStorage(),
|
||||
}
|
||||
|
||||
try {
|
||||
|
|
@ -619,6 +623,19 @@ function findNode(node, predicate) {
|
|||
|
||||
const LEAD_SESSION = 'sess-lead'
|
||||
const DEMO_ROLES = ['lead', 'zhongshu', 'menxia', 'shangshu', 'libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']
|
||||
|
||||
/** 预览里的 localStorage:预置一条部门固定路由,让「按部门固定」这个状态看得见。 */
|
||||
function createDemoStorage() {
|
||||
const store = new Map([
|
||||
['sansheng-liubu.route.gongbu', JSON.stringify({ provider: 'deepseek', model: 'deepseek-v4', reasoningEffort: 'high' })],
|
||||
])
|
||||
return {
|
||||
getItem: (key) => (store.has(key) ? store.get(key) : null),
|
||||
setItem: (key, value) => { store.set(key, String(value)) },
|
||||
removeItem: (key) => { store.delete(key) },
|
||||
}
|
||||
}
|
||||
|
||||
const DEMO_LABELS = {
|
||||
lead: '丞相', zhongshu: '中书省', menxia: '门下省', shangshu: '尚书省',
|
||||
libu: '吏部', hubu: '户部', lipu: '礼部', bingbu: '兵部', xingbu: '刑部', gongbu: '工部',
|
||||
|
|
@ -753,7 +770,7 @@ function createDemoContext() {
|
|||
list: sessionList,
|
||||
statuses: statusStore,
|
||||
binding: () => binding,
|
||||
subagentAddress: () => undefined,
|
||||
subagentAddress: (sessionId) => (sessionId === LEAD_SESSION ? undefined : { parentSessionId: LEAD_SESSION, childSessionId: sessionId }),
|
||||
refreshProjections: async () => {},
|
||||
},
|
||||
uiWorkspace: {
|
||||
|
|
@ -1010,6 +1027,19 @@ async function main() {
|
|||
}
|
||||
}
|
||||
|
||||
if (options.view === 'court' && options.seat !== 'lead') {
|
||||
const card = findNode(tree, (node) => node.props && node.props['data-role'] === options.seat)
|
||||
if (!card || typeof card.props.onClick !== 'function') {
|
||||
fail(`找不到「${options.seat}」席位,无法切到该部门详情。`)
|
||||
}
|
||||
card.props.onClick()
|
||||
tree = await settle(hooks, rootVNode)
|
||||
const selected = findNode(tree, (node) => node.props && node.props['data-role'] === options.seat)
|
||||
if (!selected || selected.props['aria-pressed'] !== 'true') {
|
||||
fail(`点击「${options.seat}」席位后没有切换到该部门详情。`)
|
||||
}
|
||||
}
|
||||
|
||||
const panelHtml = serializeNode(tree)
|
||||
if (!panelHtml.trim()) fail('序列化后的面板 HTML 为空。')
|
||||
if (panelHtml.length < 2000) fail(`面板 HTML 过短(${panelHtml.length} 字符),可能渲染不完整。`)
|
||||
|
|
|
|||
|
|
@ -136,3 +136,29 @@ test('keeps management tool audit and approval rules', () => {
|
|||
assert.equal(audit[0].authority, 'chancellor')
|
||||
assert.match(evaluateToolPolicy('bingbu', 'automation_create', [approvedTask('bingbu')]), /门下省准奏记录/)
|
||||
})
|
||||
|
||||
test('parses the department model command the panel sends', async () => {
|
||||
const { parseDeptModelCommand, describeDeptRoutes, readStoredRoutes, writeStoredRoutes } = await import('../index.js')
|
||||
assert.deepEqual(parseDeptModelCommand('gongbu deepseek deepseek-chat high'), {
|
||||
action: 'set',
|
||||
role: 'gongbu',
|
||||
route: { provider: 'deepseek', model: 'deepseek-chat', reasoningEffort: 'high' },
|
||||
})
|
||||
assert.equal(parseDeptModelCommand('gongbu deepseek deepseek-chat').route.reasoningEffort, undefined)
|
||||
assert.equal(parseDeptModelCommand('').action, 'list')
|
||||
assert.equal(parseDeptModelCommand('list').action, 'list')
|
||||
assert.deepEqual(parseDeptModelCommand('clear gongbu'), { action: 'clear', role: 'gongbu' })
|
||||
assert.match(parseDeptModelCommand('hufu a b').reason, /未知部门/)
|
||||
assert.match(parseDeptModelCommand('gongbu deepseek').reason, /用法/)
|
||||
assert.match(describeDeptRoutes({ gongbu: { provider: 'p', model: 'm', reasoningEffort: 'high' } }), /gongbu=p\/m·high/)
|
||||
|
||||
const { mkdtempSync, rmSync } = await import('node:fs')
|
||||
const { tmpdir } = await import('node:os')
|
||||
const { join } = await import('node:path')
|
||||
const dir = mkdtempSync(join(tmpdir(), 'sansheng-routes-'))
|
||||
const file = join(dir, 'nested', 'routes.json')
|
||||
assert.equal(writeStoredRoutes(file, { bingbu: { provider: 'p', model: 'm' } }), true)
|
||||
assert.deepEqual(readStoredRoutes(file).bingbu, { provider: 'p', model: 'm' })
|
||||
assert.deepEqual(readStoredRoutes(join(dir, 'missing.json')), {}, '读不到就当没有固定过')
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
|
|
|||
Loading…
Reference in New Issue