dsh-preset-enhance 0.3.1-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +47 -0
- package/agent-mode/agent.cordis.yml +12 -0
- package/agent-mode/preset.yml +3 -0
- package/client.js +29 -0
- package/cordis.patch.yml +3 -0
- package/index.mjs +503 -0
- package/lib/deepseek-beta.mjs +154 -0
- package/lib/macros.mjs +109 -0
- package/lib/preset.mjs +100 -0
- package/lib/store.mjs +73 -0
- package/mode.mjs +6 -0
- package/package.json +19 -0
- package/web/editor.css +6 -0
- package/web/editor.js +477 -0
- package/web/index.html +27 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 bychv
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# DSH Preset Enhance
|
|
2
|
+
|
|
3
|
+
为 DeepSeek Harness 加载和编辑 SillyTavern 预设,在请求发送给模型前按顺序表注入消息,并按 DSH 模式或当前会话控制工具。
|
|
4
|
+
|
|
5
|
+
## 安装
|
|
6
|
+
|
|
7
|
+
~~~powershell
|
|
8
|
+
dsh plugin --profile web add github:bychv/dsh-preset-enhance
|
|
9
|
+
~~~
|
|
10
|
+
|
|
11
|
+
重新启动 `dsh web` 后,左侧栏会出现“预设工作台”,新建对话的模式列表中会出现“预设模式”。
|
|
12
|
+
|
|
13
|
+
## 预设注入
|
|
14
|
+
|
|
15
|
+
工作台可以导入、编辑、预览和导出 SillyTavern 预设。导入后会立即保存到全局预设库并成为当前默认;在预设库中切换选择也会立即更新当前默认。最后选择保存在 DSH 状态目录中,重启后继续使用。当前默认预设会用于自动注入;可以在“新会话自动启用预设注入”中选择任意 DSH 模式。保存模式列表只影响之后新建的会话;已有会话保持原状态。专用的“预设模式”始终自动启用。
|
|
16
|
+
|
|
17
|
+
当前会话可以使用原生命令即时切换,命令由 DSH 本地处理,不会作为聊天消息发给模型:
|
|
18
|
+
|
|
19
|
+
~~~text
|
|
20
|
+
/preset on
|
|
21
|
+
/preset off
|
|
22
|
+
/preset status
|
|
23
|
+
~~~
|
|
24
|
+
|
|
25
|
+
直接输入 `/preset` 会在开启和关闭之间切换。
|
|
26
|
+
|
|
27
|
+
“预设模式”从当前安装的 `standard` 模式生成,因此拥有标准模式的工具集。它会移除 DSH 的身份 system prompt 和运行环境快照,使发送给模型的提示词完全由预设和真实聊天记录组成。其他模式保留各自原有提示词,同时可以叠加预设注入。
|
|
28
|
+
|
|
29
|
+
提示词条目分为两个区域:
|
|
30
|
+
|
|
31
|
+
- **顺序表内**:条目已经参与当前顺序表;复选框只控制是否启用,未勾选的条目仍属于顺序表。
|
|
32
|
+
- **闲置条目**:条目没有加入当前顺序表,不参与注入;点击“加入”后才会移动到使用区。
|
|
33
|
+
|
|
34
|
+
支持顺序表中 `chatHistory` 前后的 system、user、assistant/model 消息,以及按聊天深度注入。支持常用 SillyTavern 变量宏,包括 `setvar`、`getvar`、global 变量、数值修改、随机选择与骰子。`extensions` 会原样保留在预设 JSON 中,当前版本不执行其中的扩展行为。
|
|
35
|
+
|
|
36
|
+
当编译后的最后一条预设消息是 assistant 时(包括顶层 `assistant_prefill`,以及预设顺序表在 `chatHistory` 后安排的 assistant/model 条目),工作台会显示预填充续写提醒,消息预览也会标出 `Assistant Prefix`。这类预设必须使用支持 assistant prefix 的接口。
|
|
37
|
+
|
|
38
|
+
使用 DSH 的 `deepseek-official` 提供方时,可以在“Assistant 预填充接口”面板开启“DeepSeek 官方 Beta 前缀续写”。开启后,插件只对当前请求中匹配到的末条预填充自动执行两项转换:将官方 Chat Completion 地址切到 `https://api.deepseek.com/beta`,并为最后一条 assistant 消息发送 `prefix: true`。在思考模式下,开放的 `<think>` 前缀会映射到 `reasoning_content`,其他 assistant 消息也会补齐接口要求的思考字段。由于官方 Prefix 接口不接受函数调用,该次预填充请求会自动移除 `tools`、`tool_choice` 和 `parallel_tool_calls`;之后的普通请求、非预填充请求和其他提供方不受影响。接口要求见 [DeepSeek 对话前缀续写文档](https://api-docs.deepseek.com/zh-cn/guides/chat_prefix_completion)。
|
|
39
|
+
|
|
40
|
+
## 工具预设
|
|
41
|
+
|
|
42
|
+
工具面板支持两层配置:
|
|
43
|
+
|
|
44
|
+
- **模式默认**:可以为每个可用的 DSH 模式分别开启或关闭工具。没有独立覆盖的会话会继承该策略,保存后从下一次模型请求开始生效。
|
|
45
|
+
- **当前会话覆盖**:在同一会话中随时改动工具开关,下一次请求立即使用新策略;“恢复继承”会重新采用当前模式的默认策略。
|
|
46
|
+
|
|
47
|
+
关闭的工具会从发给模型的工具 schema 中移除,执行守卫也会拒绝该工具,避免已有或手写工具调用绕过开关。工具目录通过 DSH 的模式注册表和 standing scope 实时解析;内置模式和其他插件引入的模式都会自动列出,各模式的每个实际工具都能独立开关。若第三方模式本身无法装载,工作台会显示该模式的解析错误。
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Shadow the deployment persona with an empty complete prompt and suppress the
|
|
2
|
+
# runtime-context snapshot. The host interceptor also removes the empty prompt
|
|
3
|
+
# node at the final request boundary before assembling the SillyTavern preset.
|
|
4
|
+
- id: persona
|
|
5
|
+
name: '@deepseek-ai/dsh-persona'
|
|
6
|
+
config:
|
|
7
|
+
prefix: ''
|
|
8
|
+
complete: true
|
|
9
|
+
includeRuntimeContext: false
|
|
10
|
+
|
|
11
|
+
- id: preset-enhance-mode
|
|
12
|
+
name: dsh-preset-enhance/mode
|
package/client.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
id: 'dsh-preset-enhance',
|
|
3
|
+
factory: require => {
|
|
4
|
+
const React = require('react');
|
|
5
|
+
const Frame = props => React.createElement('iframe', {
|
|
6
|
+
title: '预设查看与编辑',
|
|
7
|
+
src: `/preset-enhance?sessionId=${encodeURIComponent(props.sessionId ?? props.injected?.sessionId ?? '')}`,
|
|
8
|
+
style: { width: '100%', height: '100%', minHeight: '640px', border: 0 },
|
|
9
|
+
});
|
|
10
|
+
const PresetIcon = ({ size = 18 }) => React.createElement('svg', {
|
|
11
|
+
width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8,
|
|
12
|
+
strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true,
|
|
13
|
+
}, React.createElement('path', { d: 'M5 4h14v16H5z' }),
|
|
14
|
+
React.createElement('path', { d: 'M8 8h8M8 12h5M8 16h8' }),
|
|
15
|
+
React.createElement('path', { d: 'M16 11v4M14 13h4' }));
|
|
16
|
+
return { inject: ['slots', 'conversation'], apply(ctx) {
|
|
17
|
+
ctx.slots.inject('conversation.view', () => ctx.slots.register({
|
|
18
|
+
name: 'conversation.view', id: 'preset-enhance-editor', order: 25,
|
|
19
|
+
label: '预设', inject: sessionId => ({ sessionId }),
|
|
20
|
+
}, Frame));
|
|
21
|
+
ctx.slots.inject('main', () => ctx.slots.register({
|
|
22
|
+
name: 'main', key: 'preset-enhance-editor',
|
|
23
|
+
}, Frame));
|
|
24
|
+
ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
|
|
25
|
+
name: 'sidebar.panellist', id: 'preset-enhance-editor', order: 30, label: '预设工作台',
|
|
26
|
+
}, PresetIcon));
|
|
27
|
+
} };
|
|
28
|
+
},
|
|
29
|
+
});
|
package/cordis.patch.yml
ADDED
package/index.mjs
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { resolve, join } from 'node:path';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
5
|
+
import { PresetStore } from './lib/store.mjs';
|
|
6
|
+
import { compilePreset, validatePreset, getOrder } from './lib/preset.mjs';
|
|
7
|
+
import { DEEPSEEK_OFFICIAL_PROVIDER, installDeepSeekBetaBridge } from './lib/deepseek-beta.mjs';
|
|
8
|
+
|
|
9
|
+
export const name = 'preset-enhance';
|
|
10
|
+
export const inject = ['llm', 'sessions', 'webServer', 'commands', 'tools', 'agentPresets', 'agents'];
|
|
11
|
+
export const AGENT_PRESET_ID = 'st-preset';
|
|
12
|
+
const BASE = '/preset-enhance';
|
|
13
|
+
const DSH_SYSTEM_PROMPT = '@deepseek-ai/dsh-system-prompt';
|
|
14
|
+
const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
15
|
+
const PRESET_COMPILER_VERSION = 2;
|
|
16
|
+
const ownGet = (object, key) => Object.hasOwn(object, key) ? object[key] : undefined;
|
|
17
|
+
const assign = (object, key, value) => Object.defineProperty(object, key, { value, writable: true, enumerable: true, configurable: true });
|
|
18
|
+
const isRecord = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
19
|
+
|
|
20
|
+
export async function apply(ctx, config = {}) {
|
|
21
|
+
const home = process.env.DSH_HOME?.trim() || join(homedir(), '.dsh');
|
|
22
|
+
const store = new PresetStore(resolve(config.dataFile ?? join(home, 'preset-enhance', 'state.json')));
|
|
23
|
+
const routed = new WeakSet();
|
|
24
|
+
const deepSeekBeta = installDeepSeekBetaBridge(ctx);
|
|
25
|
+
const standard = config.standardComposition ??
|
|
26
|
+
(ctx.agentPresets ? (await ctx.agentPresets.readDocument('standard')).content : undefined);
|
|
27
|
+
await ensurePresetAgentMode(resolve(config.agentPresetRoot ?? join(home, '.agent-presets')), standard);
|
|
28
|
+
|
|
29
|
+
let policySnapshot = toolPolicySnapshot(await store.read());
|
|
30
|
+
const refreshPolicies = state => { policySnapshot = toolPolicySnapshot(state); };
|
|
31
|
+
if (ctx.tools?.guard) ctx.effect(() => ctx.tools.guard(exec => {
|
|
32
|
+
const session = exec.agent?.session;
|
|
33
|
+
if (!session) return;
|
|
34
|
+
const policy = effectiveToolPolicy(policySnapshot, session.id, sessionModeId(session));
|
|
35
|
+
if (policy[exec.name] === false) return `工具 ${exec.name} 已在预设工作台中关闭`;
|
|
36
|
+
}), 'preset-enhance: tool policy guard');
|
|
37
|
+
if (ctx.commands?.register) ctx.effect(() => ctx.commands.register(presetCommand(store)), 'preset-enhance: /preset');
|
|
38
|
+
|
|
39
|
+
ctx.on('llm/stream', async function* (options, next) {
|
|
40
|
+
const session = options.sessionId ? ctx.sessions.get(options.sessionId) : undefined;
|
|
41
|
+
if (routed.has(options) || options.purpose || !session) { yield* next(); return; }
|
|
42
|
+
|
|
43
|
+
const modeId = sessionModeId(session);
|
|
44
|
+
const exclusive = modeId === AGENT_PRESET_ID;
|
|
45
|
+
const history = exclusive ? presetModeHistory(options.messages) : options.messages;
|
|
46
|
+
const observed = catalogFromTools(options.tools);
|
|
47
|
+
const initial = await store.read();
|
|
48
|
+
refreshPolicies(initial);
|
|
49
|
+
const explicit = ownGet(initial.bindings, options.sessionId);
|
|
50
|
+
const wantsPreset = explicit?.enabled ||
|
|
51
|
+
(!explicit && shouldAutoEnable(initial, session) && defaultRecord(initial));
|
|
52
|
+
const catalogChanged = observed.length > 0 && !sameCatalog(initial.toolCatalogs[modeId] ?? [], observed);
|
|
53
|
+
let compiled = null;
|
|
54
|
+
|
|
55
|
+
if (wantsPreset || catalogChanged) {
|
|
56
|
+
compiled = await store.transaction(current => {
|
|
57
|
+
let changed = false;
|
|
58
|
+
if (observed.length > 0 && syncToolCatalog(current, modeId, observed)) changed = true;
|
|
59
|
+
let binding = ownGet(current.bindings, options.sessionId);
|
|
60
|
+
if (!binding && shouldAutoEnable(current, session)) {
|
|
61
|
+
const record = defaultRecord(current);
|
|
62
|
+
if (record) {
|
|
63
|
+
binding = { enabled: true, presetId: record.id, characterId: null, values: {}, markers: {} };
|
|
64
|
+
assign(current.bindings, options.sessionId, binding);
|
|
65
|
+
changed = true;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (changed) current.revision++;
|
|
69
|
+
refreshPolicies(current);
|
|
70
|
+
if (!binding?.enabled) return null;
|
|
71
|
+
const record = current.presets.find(p => p.id === binding.presetId);
|
|
72
|
+
if (!record) throw new Error('当前会话启用的预设不存在');
|
|
73
|
+
const key = digest({ compiler: PRESET_COMPILER_VERSION, messages: history, preset: record, binding });
|
|
74
|
+
const prior = ownGet(current.sessions, options.sessionId);
|
|
75
|
+
if (prior?.key === key) return prior.result;
|
|
76
|
+
const result = compilePreset(record.preset, history, {
|
|
77
|
+
...binding, seed: key, local: prior?.result.local, global: current.global,
|
|
78
|
+
});
|
|
79
|
+
options.signal?.throwIfAborted();
|
|
80
|
+
current.global = result.global;
|
|
81
|
+
assign(current.sessions, options.sessionId, {
|
|
82
|
+
key, at: new Date().toISOString(), presetId: record.id, result,
|
|
83
|
+
});
|
|
84
|
+
return result;
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const policy = effectiveToolPolicy(policySnapshot, options.sessionId, modeId);
|
|
89
|
+
const filteredTools = filterTools(options.tools, policy);
|
|
90
|
+
const toolsChanged = (options.tools?.length ?? 0) !== filteredTools.length;
|
|
91
|
+
const messages = compiled?.messages ?? history;
|
|
92
|
+
const messagesChanged = compiled !== null || messages !== options.messages;
|
|
93
|
+
if (!toolsChanged && !messagesChanged) { yield* next(); return; }
|
|
94
|
+
|
|
95
|
+
const request = routedRequest(options, messages, filteredTools);
|
|
96
|
+
const betaPrefix = initial.deepseekBetaPrefix === true && options.provider === DEEPSEEK_OFFICIAL_PROVIDER &&
|
|
97
|
+
compiled?.assistantPrefix?.active === true;
|
|
98
|
+
const releaseBeta = betaPrefix ? deepSeekBeta.activate(options.sessionId, messageText(messages.at(-1))) : () => {};
|
|
99
|
+
routed.add(request);
|
|
100
|
+
try { yield* ctx.llm.stream(request); } finally { releaseBeta(); routed.delete(request); }
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
const assets = new Map([
|
|
104
|
+
[BASE, ['web/index.html', 'text/html']],
|
|
105
|
+
[`${BASE}/editor.js`, ['web/editor.js', 'text/javascript']],
|
|
106
|
+
[`${BASE}/editor.css`, ['web/editor.css', 'text/css']],
|
|
107
|
+
]);
|
|
108
|
+
for (const [path, [file, mime]] of assets) ctx.effect(() => ctx.webServer.register({
|
|
109
|
+
kind: 'exact', path,
|
|
110
|
+
handler: async (req, res) => {
|
|
111
|
+
if (req.method !== 'GET') return respond(res, 405, { error: 'Method not allowed' });
|
|
112
|
+
res.writeHead(200, {
|
|
113
|
+
'content-type': `${mime}; charset=utf-8`,
|
|
114
|
+
'cache-control': 'no-store',
|
|
115
|
+
'content-security-policy': "default-src 'self'; script-src 'self'; style-src 'self'; frame-ancestors 'self'; object-src 'none'; base-uri 'none'",
|
|
116
|
+
});
|
|
117
|
+
res.end(await readFile(new URL(file, import.meta.url)));
|
|
118
|
+
},
|
|
119
|
+
}), `preset-enhance: ${path}`);
|
|
120
|
+
|
|
121
|
+
ctx.effect(() => ctx.webServer.register({
|
|
122
|
+
kind: 'exact', path: `${BASE}/api`, handler: async (req, res) => {
|
|
123
|
+
try {
|
|
124
|
+
const url = new URL(req.url, 'http://preset.local');
|
|
125
|
+
if (req.method === 'GET') {
|
|
126
|
+
const state = await store.read();
|
|
127
|
+
refreshPolicies(state);
|
|
128
|
+
const sessionId = url.searchParams.get('sessionId') ?? '';
|
|
129
|
+
const session = sessionId ? ctx.sessions.get(sessionId) : undefined;
|
|
130
|
+
const fallback = !ownGet(state.bindings, sessionId) && shouldAutoEnable(state, session) ?
|
|
131
|
+
defaultBinding(state) : undefined;
|
|
132
|
+
const modeDefault = defaultRecord(state);
|
|
133
|
+
const modes = await agentModeRows(ctx);
|
|
134
|
+
const discovered = await discoverModeToolCatalogs(ctx, modes);
|
|
135
|
+
const catalogs = { ...state.toolCatalogs, ...discovered.catalogs };
|
|
136
|
+
const live = liveToolCatalog(ctx, sessionId);
|
|
137
|
+
const liveMode = sessionModeId(session);
|
|
138
|
+
if (live.length > 0 && liveMode) catalogs[liveMode] = live;
|
|
139
|
+
return respond(res, 200, {
|
|
140
|
+
revision: state.revision,
|
|
141
|
+
presets: state.presets,
|
|
142
|
+
binding: ownGet(state.bindings, sessionId) ?? fallback ?? { enabled: false },
|
|
143
|
+
selectedPresetId: state.selectedPresetId ?? modeDefault?.id ?? null,
|
|
144
|
+
deepseekBetaPrefix: state.deepseekBetaPrefix === true,
|
|
145
|
+
modeDefaultPresetId: modeDefault?.id ?? null,
|
|
146
|
+
modeDefaultName: modeDefault?.name ?? null,
|
|
147
|
+
presetMode: liveMode === AGENT_PRESET_ID,
|
|
148
|
+
sessionMode: liveMode,
|
|
149
|
+
agentModes: modes,
|
|
150
|
+
autoEnableModes: state.autoEnableModes,
|
|
151
|
+
toolCatalogs: catalogs,
|
|
152
|
+
toolCatalogErrors: discovered.errors,
|
|
153
|
+
modeToolPolicies: state.modeToolPolicies,
|
|
154
|
+
sessionToolPolicy: sessionId ? ownGet(state.sessionToolPolicies, sessionId) ?? null : null,
|
|
155
|
+
last: ownGet(state.sessions, sessionId) ?? null,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
if (req.method !== 'POST') return respond(res, 405, { error: 'Method not allowed' });
|
|
159
|
+
if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) throw new Error('需要 application/json');
|
|
160
|
+
if (req.headers.origin && new URL(req.headers.origin).host !== req.headers.host) throw new Error('拒绝跨来源写入');
|
|
161
|
+
const body = await readJson(req);
|
|
162
|
+
if (body.action === 'preview') {
|
|
163
|
+
return respond(res, 200, compilePreset(body.preset, previewHistory(ctx, body), {
|
|
164
|
+
...body.options, seed: 'preview',
|
|
165
|
+
}));
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const needsModes = ['save-auto-modes', 'save-mode-tools', 'save-session-tools'].includes(body.action);
|
|
169
|
+
const modeRows = needsModes ? await agentModeRows(ctx) : [];
|
|
170
|
+
const knownModes = needsModes ? new Set(modeRows.map(mode => mode.id)) : null;
|
|
171
|
+
const discovered = ['save-mode-tools', 'save-session-tools'].includes(body.action) ?
|
|
172
|
+
await discoverModeToolCatalogs(ctx, modeRows) : null;
|
|
173
|
+
const result = await store.transaction(state => {
|
|
174
|
+
if (body.revision !== state.revision) throw new Error('预设已被其他窗口更新,请重新加载后再保存');
|
|
175
|
+
if (body.action === 'save') {
|
|
176
|
+
validatePreset(body.preset);
|
|
177
|
+
const old = state.presets.find(p => p.id === body.id);
|
|
178
|
+
const record = {
|
|
179
|
+
id: old?.id ?? randomUUID(),
|
|
180
|
+
name: String(body.name || '未命名预设').slice(0, 200),
|
|
181
|
+
preset: body.preset,
|
|
182
|
+
};
|
|
183
|
+
if (old) state.presets[state.presets.indexOf(old)] = record;
|
|
184
|
+
else state.presets.push(record);
|
|
185
|
+
state.selectedPresetId = record.id;
|
|
186
|
+
state.defaultPresetId = record.id;
|
|
187
|
+
state.revision++;
|
|
188
|
+
return { id: record.id };
|
|
189
|
+
}
|
|
190
|
+
if (body.action === 'set-default') {
|
|
191
|
+
const record = state.presets.find(p => p.id === body.id);
|
|
192
|
+
if (!record) throw new Error('请先保存并选择预设');
|
|
193
|
+
state.selectedPresetId = record.id;
|
|
194
|
+
state.defaultPresetId = record.id;
|
|
195
|
+
state.revision++;
|
|
196
|
+
return { id: record.id };
|
|
197
|
+
}
|
|
198
|
+
if (body.action === 'select-preset') {
|
|
199
|
+
const record = state.presets.find(p => p.id === body.id);
|
|
200
|
+
if (!record) throw new Error('请选择有效的预设');
|
|
201
|
+
state.selectedPresetId = record.id;
|
|
202
|
+
state.defaultPresetId = record.id;
|
|
203
|
+
state.revision++;
|
|
204
|
+
return { id: record.id };
|
|
205
|
+
}
|
|
206
|
+
if (body.action === 'save-deepseek-beta') {
|
|
207
|
+
if (typeof body.enabled !== 'boolean') throw new Error('DeepSeek Beta 开关值无效');
|
|
208
|
+
state.deepseekBetaPrefix = body.enabled;
|
|
209
|
+
state.revision++;
|
|
210
|
+
return { enabled: state.deepseekBetaPrefix };
|
|
211
|
+
}
|
|
212
|
+
if (body.action === 'save-auto-modes') {
|
|
213
|
+
if (!Array.isArray(body.modes) || body.modes.some(id => typeof id !== 'string' || !knownModes.has(id))) {
|
|
214
|
+
throw new Error('自动启用模式列表包含未知模式');
|
|
215
|
+
}
|
|
216
|
+
const previous = new Set(state.autoEnableModes);
|
|
217
|
+
const selected = [...new Set([AGENT_PRESET_ID, ...body.modes])];
|
|
218
|
+
const now = Date.now();
|
|
219
|
+
for (const id of selected) if (!previous.has(id)) state.autoEnableSince[id] = now;
|
|
220
|
+
for (const id of Object.keys(state.autoEnableSince)) if (!selected.includes(id)) delete state.autoEnableSince[id];
|
|
221
|
+
state.autoEnableSince[AGENT_PRESET_ID] = 0;
|
|
222
|
+
state.autoEnableModes = selected;
|
|
223
|
+
state.revision++;
|
|
224
|
+
return { modes: selected };
|
|
225
|
+
}
|
|
226
|
+
if (body.action === 'save-mode-tools') {
|
|
227
|
+
if (typeof body.modeId !== 'string' || !knownModes.has(body.modeId)) throw new Error('请选择有效的 DSH 模式');
|
|
228
|
+
const policy = validateToolPolicy(body.policy, discovered.catalogs[body.modeId]);
|
|
229
|
+
assign(state.modeToolPolicies, body.modeId, policy);
|
|
230
|
+
state.revision++;
|
|
231
|
+
refreshPolicies(state);
|
|
232
|
+
return { modeId: body.modeId };
|
|
233
|
+
}
|
|
234
|
+
if (body.action === 'save-session-tools') {
|
|
235
|
+
const session = typeof body.sessionId === 'string' ? ctx.sessions.get(body.sessionId) : undefined;
|
|
236
|
+
if (!session) throw new Error('缺少有效的会话 ID');
|
|
237
|
+
const modeId = sessionModeId(session);
|
|
238
|
+
if (!knownModes.has(modeId)) throw new Error('当前会话没有可识别的 DSH 模式');
|
|
239
|
+
if (body.inherit === true) delete state.sessionToolPolicies[body.sessionId];
|
|
240
|
+
else assign(state.sessionToolPolicies, body.sessionId,
|
|
241
|
+
validateToolPolicy(body.policy, discovered.catalogs[modeId]));
|
|
242
|
+
state.revision++;
|
|
243
|
+
refreshPolicies(state);
|
|
244
|
+
return { inherited: body.inherit === true };
|
|
245
|
+
}
|
|
246
|
+
if (body.action === 'bind') {
|
|
247
|
+
validateBinding(state, body);
|
|
248
|
+
state.revision++;
|
|
249
|
+
return { ok: true };
|
|
250
|
+
}
|
|
251
|
+
throw new Error('未知操作');
|
|
252
|
+
});
|
|
253
|
+
respond(res, 200, result);
|
|
254
|
+
} catch (error) {
|
|
255
|
+
respond(res, 400, { error: error.message });
|
|
256
|
+
}
|
|
257
|
+
},
|
|
258
|
+
}), 'preset-enhance: API');
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function messageText(message) {
|
|
262
|
+
return message?.content?.filter(block => block.type === 'text').map(block => block.text).join('') ?? '';
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function validateBinding(state, body) {
|
|
266
|
+
if (typeof body.sessionId !== 'string' || !body.sessionId || body.sessionId.length > 200) {
|
|
267
|
+
throw new Error('缺少有效的会话 ID');
|
|
268
|
+
}
|
|
269
|
+
const record = state.presets.find(p => p.id === body.binding?.presetId);
|
|
270
|
+
if (body.binding?.enabled && !record) throw new Error('请先保存并选择预设');
|
|
271
|
+
if (record) getOrder(record.preset, body.binding.characterId);
|
|
272
|
+
const values = body.binding?.values ?? {};
|
|
273
|
+
const markers = body.binding?.markers ?? {};
|
|
274
|
+
for (const map of [values, markers]) {
|
|
275
|
+
if (!isRecord(map) || Object.values(map).some(value => typeof value !== 'string')) {
|
|
276
|
+
throw new Error('角色变量和标记内容必须是文本映射');
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
assign(state.bindings, body.sessionId, {
|
|
280
|
+
enabled: body.binding.enabled === true,
|
|
281
|
+
presetId: record?.id ?? '',
|
|
282
|
+
characterId: body.binding.characterId ?? null,
|
|
283
|
+
values,
|
|
284
|
+
markers,
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function presetCommand(store) {
|
|
289
|
+
return {
|
|
290
|
+
name: 'preset',
|
|
291
|
+
description: '切换当前会话的预设注入(/preset [on|off|status])',
|
|
292
|
+
input: { hint: '[on|off|status]' },
|
|
293
|
+
handler: async invocation => {
|
|
294
|
+
const input = invocation.rawInput.trim().toLowerCase();
|
|
295
|
+
if (!['', 'on', 'off', 'status'].includes(input)) {
|
|
296
|
+
return { kind: 'error', text: '用法:/preset [on|off|status]' };
|
|
297
|
+
}
|
|
298
|
+
const session = invocation.agent.session;
|
|
299
|
+
const before = await store.read();
|
|
300
|
+
const explicit = ownGet(before.bindings, session.id);
|
|
301
|
+
const enabled = explicit?.enabled ?? (shouldAutoEnable(before, session) && !!defaultRecord(before));
|
|
302
|
+
if (input === 'status') {
|
|
303
|
+
const record = explicit?.presetId ? before.presets.find(p => p.id === explicit.presetId) : defaultRecord(before);
|
|
304
|
+
return { kind: 'success', text: `预设注入:${enabled ? '已开启' : '已关闭'}${record ? `(${record.name})` : ''}` };
|
|
305
|
+
}
|
|
306
|
+
const target = input === 'on' ? true : input === 'off' ? false : !enabled;
|
|
307
|
+
return await store.transaction(state => {
|
|
308
|
+
const current = ownGet(state.bindings, session.id);
|
|
309
|
+
const record = current?.presetId ? state.presets.find(p => p.id === current.presetId) : defaultRecord(state);
|
|
310
|
+
if (target && !record) return { kind: 'error', text: '尚未保存模式默认预设,请先在预设工作台中设置。' };
|
|
311
|
+
assign(state.bindings, session.id, {
|
|
312
|
+
enabled: target,
|
|
313
|
+
presetId: record?.id ?? '',
|
|
314
|
+
characterId: current?.characterId ?? null,
|
|
315
|
+
values: current?.values ?? {},
|
|
316
|
+
markers: current?.markers ?? {},
|
|
317
|
+
});
|
|
318
|
+
state.revision++;
|
|
319
|
+
return { kind: 'success', text: `预设注入已${target ? '开启' : '关闭'}${record ? `:${record.name}` : ''}` };
|
|
320
|
+
});
|
|
321
|
+
},
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function defaultRecord(state) {
|
|
326
|
+
return state.presets.find(p => p.id === state.selectedPresetId) ??
|
|
327
|
+
state.presets.find(p => p.id === state.defaultPresetId) ?? state.presets[0];
|
|
328
|
+
}
|
|
329
|
+
function defaultBinding(state) {
|
|
330
|
+
const record = defaultRecord(state);
|
|
331
|
+
return record ? {
|
|
332
|
+
enabled: true,
|
|
333
|
+
presetId: record.id,
|
|
334
|
+
characterId: null,
|
|
335
|
+
values: {},
|
|
336
|
+
markers: {},
|
|
337
|
+
inherited: true,
|
|
338
|
+
} : undefined;
|
|
339
|
+
}
|
|
340
|
+
function sessionModeId(session) {
|
|
341
|
+
if (!session) return '';
|
|
342
|
+
let selected = session.header?.agentPreset ?? '';
|
|
343
|
+
for (const event of session.snapshotEvents?.() ?? []) {
|
|
344
|
+
if (event.type === 'agent-preset/selected') selected = event.data?.agentPreset ?? '';
|
|
345
|
+
}
|
|
346
|
+
return selected;
|
|
347
|
+
}
|
|
348
|
+
function shouldAutoEnable(state, session) {
|
|
349
|
+
if (!session) return false;
|
|
350
|
+
const modeId = sessionModeId(session);
|
|
351
|
+
if (!state.autoEnableModes.includes(modeId)) return false;
|
|
352
|
+
const since = Number(state.autoEnableSince[modeId] ?? 0);
|
|
353
|
+
const createdAt = Number(session.header?.createdAt ?? Number.POSITIVE_INFINITY);
|
|
354
|
+
return createdAt >= since;
|
|
355
|
+
}
|
|
356
|
+
function presetModeHistory(messages) {
|
|
357
|
+
return messages.filter(message => message.role !== 'system' &&
|
|
358
|
+
!(message.source?.kind === 'plugin' && message.source.plugin === DSH_SYSTEM_PROMPT));
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function toolPolicySnapshot(state) {
|
|
362
|
+
return {
|
|
363
|
+
modes: structuredClone(state.modeToolPolicies ?? {}),
|
|
364
|
+
sessions: structuredClone(state.sessionToolPolicies ?? {}),
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
function effectiveToolPolicy(snapshot, sessionId, modeId) {
|
|
368
|
+
return ownGet(snapshot.sessions, sessionId) ?? ownGet(snapshot.modes, modeId) ?? {};
|
|
369
|
+
}
|
|
370
|
+
function validateToolPolicy(value, catalog) {
|
|
371
|
+
if (!isRecord(value)) throw new Error('工具开关必须是对象');
|
|
372
|
+
if (!Array.isArray(catalog)) throw new Error('无法读取该模式的工具目录');
|
|
373
|
+
const allowed = new Set(catalog.map(tool => tool.name));
|
|
374
|
+
const policy = {};
|
|
375
|
+
for (const [tool, enabled] of Object.entries(value)) {
|
|
376
|
+
if (typeof enabled !== 'boolean') throw new Error('工具开关值必须是布尔值');
|
|
377
|
+
if (!allowed.has(tool)) throw new Error('工具不属于当前模式或已被移除');
|
|
378
|
+
assign(policy, tool, enabled);
|
|
379
|
+
}
|
|
380
|
+
return policy;
|
|
381
|
+
}
|
|
382
|
+
function catalogFromTools(tools) {
|
|
383
|
+
if (!Array.isArray(tools)) return [];
|
|
384
|
+
return tools.map(tool => ({
|
|
385
|
+
name: String(tool.name),
|
|
386
|
+
description: String(tool.description ?? '').slice(0, 500),
|
|
387
|
+
})).filter(tool => tool.name.length > 0).sort((a, b) => a.name.localeCompare(b.name));
|
|
388
|
+
}
|
|
389
|
+
function sameCatalog(left, right) {
|
|
390
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
391
|
+
}
|
|
392
|
+
function syncToolCatalog(state, modeId, observed) {
|
|
393
|
+
if (!modeId || sameCatalog(state.toolCatalogs[modeId] ?? [], observed)) return false;
|
|
394
|
+
assign(state.toolCatalogs, modeId, observed);
|
|
395
|
+
return true;
|
|
396
|
+
}
|
|
397
|
+
function filterTools(tools, policy) {
|
|
398
|
+
return Array.isArray(tools) ? tools.filter(tool => policy[tool.name] !== false) : [];
|
|
399
|
+
}
|
|
400
|
+
function routedRequest(options, messages, tools) {
|
|
401
|
+
const { tools: _tools, ...request } = options;
|
|
402
|
+
return Object.freeze({ ...request, messages, ...(tools.length > 0 ? { tools } : {}) });
|
|
403
|
+
}
|
|
404
|
+
export async function discoverModeToolCatalogs(ctx, modes) {
|
|
405
|
+
const catalogs = {};
|
|
406
|
+
const errors = {};
|
|
407
|
+
for (const mode of modes) {
|
|
408
|
+
if (mode.broken) {
|
|
409
|
+
assign(errors, mode.id, String(mode.broken));
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
try {
|
|
413
|
+
if (!ctx.agentPresets?.standingKeyFor || !ctx.tools?.schemas) {
|
|
414
|
+
throw new Error('当前 DSH 未提供模式工具枚举服务');
|
|
415
|
+
}
|
|
416
|
+
const scope = await ctx.agentPresets.standingKeyFor(mode.id);
|
|
417
|
+
assign(catalogs, mode.id, catalogFromTools(ctx.tools.schemas(scope)));
|
|
418
|
+
} catch (error) {
|
|
419
|
+
assign(errors, mode.id, error instanceof Error ? error.message : String(error));
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return { catalogs, errors };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function liveToolCatalog(ctx, sessionId) {
|
|
426
|
+
if (!sessionId) return [];
|
|
427
|
+
try {
|
|
428
|
+
const agent = ctx.agents?.get?.(sessionId);
|
|
429
|
+
return agent?.ctx?.tools?.schemas ? catalogFromTools(agent.ctx.tools.schemas(agent)) : [];
|
|
430
|
+
} catch {
|
|
431
|
+
return [];
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
async function agentModeRows(ctx) {
|
|
435
|
+
if (!ctx.agentPresets?.list) return [{ id: AGENT_PRESET_ID, name: '预设模式' }];
|
|
436
|
+
return (await ctx.agentPresets.list()).map(mode => ({
|
|
437
|
+
id: mode.id,
|
|
438
|
+
name: mode.name ?? mode.id,
|
|
439
|
+
description: mode.description ?? '',
|
|
440
|
+
trust: mode.trust,
|
|
441
|
+
broken: mode.broken ?? null,
|
|
442
|
+
}));
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
export function buildPresetModeComposition(standard) {
|
|
446
|
+
const persona = `- id: persona
|
|
447
|
+
name: '@deepseek-ai/dsh-persona'
|
|
448
|
+
config:
|
|
449
|
+
prefix: ''
|
|
450
|
+
complete: true
|
|
451
|
+
includeRuntimeContext: false
|
|
452
|
+
|
|
453
|
+
`;
|
|
454
|
+
const pattern = /^- id: persona\r?\n[\s\S]*?(?=^- id: )/m;
|
|
455
|
+
if (!pattern.test(standard)) throw new Error('standard 模式组成中找不到 persona 条目');
|
|
456
|
+
const transformed = standard.replace(pattern, persona).trimEnd();
|
|
457
|
+
if (transformed.includes('dsh-preset-enhance/mode')) return `${transformed}\n`;
|
|
458
|
+
return `${transformed}
|
|
459
|
+
|
|
460
|
+
- id: preset-enhance-mode
|
|
461
|
+
name: dsh-preset-enhance/mode
|
|
462
|
+
`;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
export async function ensurePresetAgentMode(root, standard) {
|
|
466
|
+
const destination = join(root, AGENT_PRESET_ID);
|
|
467
|
+
await mkdir(destination, { recursive: true });
|
|
468
|
+
const composition = standard ? buildPresetModeComposition(standard) :
|
|
469
|
+
await readFile(new URL('agent-mode/agent.cordis.yml', import.meta.url), 'utf8');
|
|
470
|
+
await writeFile(join(destination, 'preset.yml'), await readFile(new URL('agent-mode/preset.yml', import.meta.url)));
|
|
471
|
+
await writeFile(join(destination, 'agent.cordis.yml'), composition);
|
|
472
|
+
return destination;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
function previewHistory(ctx, body) {
|
|
476
|
+
const session = ctx.sessions.get(body.sessionId);
|
|
477
|
+
const derived = session?.deriveMessages() ?? [];
|
|
478
|
+
const history = sessionModeId(session) === AGENT_PRESET_ID ? presetModeHistory(derived) : derived;
|
|
479
|
+
return body.input ? [...history, {
|
|
480
|
+
id: 'preview-user',
|
|
481
|
+
role: 'user',
|
|
482
|
+
content: [{ type: 'text', text: String(body.input) }],
|
|
483
|
+
source: { kind: 'user' },
|
|
484
|
+
}] : history;
|
|
485
|
+
}
|
|
486
|
+
async function readJson(req) {
|
|
487
|
+
const parts = [];
|
|
488
|
+
let size = 0;
|
|
489
|
+
for await (const part of req) {
|
|
490
|
+
const bytes = Buffer.from(part);
|
|
491
|
+
size += bytes.length;
|
|
492
|
+
if (size > 8_000_000) throw new Error('预设文件不能超过 8 MB');
|
|
493
|
+
parts.push(bytes);
|
|
494
|
+
}
|
|
495
|
+
return JSON.parse(Buffer.concat(parts).toString('utf8'));
|
|
496
|
+
}
|
|
497
|
+
function respond(res, status, value) {
|
|
498
|
+
res.writeHead(status, {
|
|
499
|
+
'content-type': 'application/json; charset=utf-8',
|
|
500
|
+
'cache-control': 'no-store',
|
|
501
|
+
});
|
|
502
|
+
res.end(JSON.stringify(value));
|
|
503
|
+
}
|