@yfwu2020/dsh-selection-explain 0.7.1 → 0.8.3

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.
@@ -0,0 +1,310 @@
1
+ /**
2
+ * 划词解读 · 设置面板的**单一事实来源**。
3
+ *
4
+ * 为什么单独成模块:
5
+ * · 小窗设置页要渲染 20+ 个字段,字段的标题 / 说明 / 单位 / 边界**必须**与 host 的
6
+ * 校验规则是同一份数据 —— 分两处写迟早会漂(UI 说 1~600,host 却按 1~200 截断)。
7
+ * 所以 GET /settings 直接把这份 spec 发给客户端,客户端只负责画,不做业务判断。
8
+ * · 纯数据 + 纯函数,不 import cordis / node,单测可以直接跑(见 scripts/test-settings.mjs)。
9
+ *
10
+ * 分组是**导航结构**,不是装饰:20+ 项平铺会淹没用户,按"用户想去哪类事"分 6 组。
11
+ */
12
+
13
+ /** 字段控件类型。 */
14
+ export type SettingKind = 'switch' | 'number' | 'text' | 'seg' | 'model'
15
+
16
+ /** 一个设置项的声明。 */
17
+ export interface SettingSpec {
18
+ /** 对应 Config 的字段名(也是 POST body 里的键)。 */
19
+ key: string
20
+ kind: SettingKind
21
+ /** 行标题。 */
22
+ label: string
23
+ /** 一行说明:说清"改了会怎样",包括代价。 */
24
+ hint: string
25
+ /** 关闭此开关时禁用当前字段,但保留其配置值。 */
26
+ enabledBy?: string
27
+ /** number 的单位(显示在输入框右侧)。 */
28
+ unit?: string
29
+ /** number 的边界(与 host 侧 clamp 用同一组值)。 */
30
+ min?: number
31
+ max?: number
32
+ /** number 的步进。 */
33
+ step?: number
34
+ /** seg 的候选项。 */
35
+ options?: string[]
36
+ /** 留空时的语义说明(text 用,放进 placeholder)。 */
37
+ placeholder?: string
38
+ /**
39
+ * **复合字段**:一个控件写多个 Config 字段(当前只有模型选择 —— 一个下拉同时定 provider 与 model)。
40
+ * 有它就说明 `key` 是个**虚拟键**、本身不写进配置,真正写的是这里列出的字段。
41
+ */
42
+ keys?: string[]
43
+ /**
44
+ * 显示单位与配置单位的**倍率**:显示值 = 配置值 / scale。
45
+ *
46
+ * 配置里时间一律是毫秒(schema 与 yml 的历史值都是毫秒,不动它),
47
+ * 但界面上"秒"更好读(用户提的要求)。所以 min/max 仍然按**配置单位**声明,
48
+ * 由客户端换算出显示用的边界 —— 边界的唯一事实来源始终是 Config schema。
49
+ */
50
+ scale?: number
51
+ }
52
+
53
+ /** 一个分组。 */
54
+ export interface SettingGroup {
55
+ id: string
56
+ /** 左栏分类名。 */
57
+ label: string
58
+ items: SettingSpec[]
59
+ sections: Array<{ label: string; keys: string[]; hint?: string; note?: string }>
60
+ }
61
+
62
+ /**
63
+ * 分组顺序 = 左栏从上到下的顺序。
64
+ * 「模型」放第一:27 项里唯一大多数人有理由改的一类。
65
+ */
66
+ export const SETTINGS_GROUPS: SettingGroup[] = [
67
+ {
68
+ id: 'model', label: '模型',
69
+ sections: [
70
+ {"label": "模型", "keys": ["modelChoice"]},
71
+ {"label": "思考强度", "keys": ["translationReasoningEffort", "reasoningEffort", "chatReasoningEffort"], "note": "关闭思考仍会生成回答。"},
72
+ ],
73
+ items: [
74
+ {"key": "modelChoice", "kind": "model", "label": "模型", "hint": "", "keys": ["provider", "model"]},
75
+ {"key": "translationReasoningEffort", "kind": "seg", "label": "首轮", "hint": "翻译 / 解读 / 注释", "options": ["off", "low", "high", "max"]},
76
+ {"key": "reasoningEffort", "kind": "seg", "label": "次轮", "hint": "点击「展开详解」", "options": ["off", "low", "high", "max"]},
77
+ {"key": "chatReasoningEffort", "kind": "seg", "label": "追问", "hint": "在小窗中继续提问", "options": ["off", "low", "high", "max"]},
78
+ ],
79
+ },
80
+ {
81
+ id: 'read', label: '解读',
82
+ sections: [
83
+ {"label": "文本范围", "keys": ["maxSelectionChars", "maxContextChars"]},
84
+ {"label": "频率与时限", "keys": ["maxRequestsPerMinute", "timeoutMs"]},
85
+ ],
86
+ items: [
87
+ {"key": "maxSelectionChars", "kind": "number", "label": "选中文字上限", "hint": "超出此长度时,不进行解读。", "unit": "字符", "min": 20, "max": 20000, "step": 1},
88
+ {"key": "maxContextChars", "kind": "number", "label": "局部前后文上限", "hint": "不含会话背景,超出部分截断。", "unit": "字符", "min": 200, "max": 60000, "step": 1},
89
+ {"key": "maxRequestsPerMinute", "kind": "number", "label": "每分钟请求上限", "hint": "所有阶段合计,超限需稍后重试。", "unit": "次", "min": 1, "max": 600, "step": 1},
90
+ {"key": "timeoutMs", "kind": "number", "label": "生成时限", "hint": "含检索耗时,超时后停止生成。", "unit": "秒", "min": 5000, "max": 600000, "step": 1000, "scale": 1000},
91
+ ],
92
+ },
93
+ {
94
+ id: 'ctx', label: '背景',
95
+ sections: [
96
+ {"label": "解读", "keys": ["sessionContext", "sessionContextFastMessages", "sessionContextMaxMessages", "sessionContextMaxChars"]},
97
+ {"label": "引用", "keys": ["quoteContextRounds", "quoteContextMaxCharsPerTurn", "quoteContextMaxChars"], "hint": "将引用所在轮及其上下文随提问一起发给模型。", "note": "一轮包含一次提问及其回答。"},
98
+ ],
99
+ items: [
100
+ {"key": "sessionContext", "kind": "switch", "label": "附带会话消息", "hint": "将选中文字所在消息及之前的消息一并发给模型。"},
101
+ {"key": "sessionContextFastMessages", "kind": "number", "label": "首轮上下文消息数", "hint": "每条提问或回答计一条。", "unit": "条", "min": 1, "max": 200, "step": 1, "enabledBy": "sessionContext"},
102
+ {"key": "sessionContextMaxMessages", "kind": "number", "label": "次轮与追问上下文消息数", "hint": "", "unit": "条", "min": 1, "max": 200, "step": 1, "enabledBy": "sessionContext"},
103
+ {"key": "sessionContextMaxChars", "kind": "number", "label": "上下文总字符上限", "hint": "0 为不限;超出时优先保留近期消息。", "unit": "字符", "min": 0, "max": 2000000, "step": 1000, "enabledBy": "sessionContext"},
104
+ {"key": "quoteContextRounds", "kind": "number", "label": "上下文轮数", "hint": "引用前后各取指定轮数;0 仅取所在轮。", "unit": "轮", "min": 0, "max": 10, "step": 1},
105
+ {"key": "quoteContextMaxCharsPerTurn", "kind": "number", "label": "单条消息字符上限", "hint": "长消息优先保留引用附近内容。", "unit": "字符", "min": 200, "max": 20000, "step": 100},
106
+ {"key": "quoteContextMaxChars", "kind": "number", "label": "上下文总字符上限", "hint": "超出时减少上下文,保留引用所在消息。", "unit": "字符", "min": 400, "max": 100000, "step": 100},
107
+ ],
108
+ },
109
+ {
110
+ id: 'tools', label: '联网',
111
+ sections: [
112
+ {"label": "工具调用", "keys": ["tools", "maxToolRounds", "toolResultMaxChars"]},
113
+ {"label": "工具范围", "keys": ["toolNames", "fallbackToolNames", "toolReadRoot"]},
114
+ ],
115
+ items: [
116
+ {"key": "tools", "kind": "switch", "label": "允许调用工具", "hint": "模型可按需调用下方指定的工具。"},
117
+ {"key": "maxToolRounds", "kind": "number", "label": "调用轮数", "hint": "0 为不调用工具;同一轮可调用多个工具。", "unit": "轮", "min": 0, "max": 8, "step": 1, "enabledBy": "tools"},
118
+ {"key": "toolResultMaxChars", "kind": "number", "label": "单次结果字符上限", "hint": "工具返回的文本超出时截断。", "unit": "字符", "min": 200, "max": 20000, "step": 100, "enabledBy": "tools"},
119
+ {"key": "toolNames", "kind": "text", "label": "允许的工具", "hint": "工具名以逗号分隔。", "placeholder": "advanced_search,platform_search,read,grep,glob", "enabledBy": "tools"},
120
+ {"key": "fallbackToolNames", "kind": "text", "label": "备用搜索工具", "hint": "找不到允许列表中的搜索工具时补充。", "placeholder": "web_search", "enabledBy": "tools"},
121
+ {"key": "toolReadRoot", "kind": "text", "label": "文件读取目录", "hint": "留空取会话工作目录;* 为不限。", "placeholder": "会话工作目录", "enabledBy": "tools"},
122
+ ],
123
+ },
124
+ {
125
+ id: 'ui', label: '界面',
126
+ sections: [
127
+ {"label": "划词入口", "keys": ["bridgeSidebarPreview"]},
128
+ {"label": "悬浮入口", "keys": ["pillEnabled", "pillIdleMs"], "note": "费用胶囊显示时保持展开。"},
129
+ ],
130
+ items: [
131
+ {"key": "bridgeSidebarPreview", "kind": "switch", "label": "侧边栏网页划词", "hint": "选中文字后显示「解读」按钮。"},
132
+ {"key": "pillEnabled", "kind": "switch", "label": "显示状态胶囊", "hint": "显示最近一次解读状态,点击打开或收起小窗。"},
133
+ {"key": "pillIdleMs", "kind": "number", "label": "自动收起时间", "hint": "空闲达到此时长后缩成小球。", "unit": "秒", "min": 2000, "max": 600000, "step": 1000, "scale": 1000, "enabledBy": "pillEnabled"},
134
+ ],
135
+ },
136
+ {
137
+ id: 'data', label: '数据',
138
+ sections: [
139
+ {"label": "历史记录", "keys": ["historyMaxEntries"], "note": "0 为不保存,已有对话保留。超出时移除最久未更新的对话,已升格的保留。"},
140
+ ],
141
+ items: [
142
+ {"key": "historyMaxEntries", "kind": "number", "label": "保留最近对话数量", "hint": "每条包含所选文字、模型回答及后续追问。", "unit": "条", "min": 0, "max": 500, "step": 1},
143
+ ],
144
+ },
145
+ ]
146
+
147
+ /** spec 里的全部条目(含虚拟键)。 */
148
+ export const SETTINGS_ITEMS: SettingSpec[] = SETTINGS_GROUPS.flatMap((group) => group.items)
149
+
150
+ /** key → spec 的索引(渲染与校验按 key 找规则)。 */
151
+ export const SETTINGS_BY_KEY: Map<string, SettingSpec> = new Map(
152
+ SETTINGS_ITEMS.map((item) => [item.key, item] as const),
153
+ )
154
+
155
+ /**
156
+ * 真正会写进配置的字段全集。
157
+ *
158
+ * 与「spec 的 key 集合」**不是一回事**:模型下拉的 key 是虚拟的 `modelChoice`,
159
+ * 它写的是 `provider` + `model` 两个真实字段(见 SettingSpec.keys)。
160
+ * 校验、应用覆盖、组装当前值,全都用这一份。
161
+ */
162
+ export const SETTINGS_KEYS: string[] = SETTINGS_ITEMS.flatMap((item) => item.keys ?? [item.key])
163
+
164
+ /** 只读的虚拟键(客户端可以渲染,但不能直接 POST 写它)。 */
165
+ export const SETTINGS_VIRTUAL_KEYS: string[] = SETTINGS_ITEMS
166
+ .filter((item) => Array.isArray(item.keys))
167
+ .map((item) => item.key)
168
+
169
+ /**
170
+ * **配置键** → 声明它的 spec(复合字段按 keys 展开)。
171
+ *
172
+ * 校验走这一份而不是 SETTINGS_BY_KEY:POST 上来的是配置键(`provider` / `model`),
173
+ * 而 spec 里那条的 key 是虚拟的 `modelChoice` —— 只有展开过才找得到规则。
174
+ */
175
+ export const SETTINGS_WRITABLE_BY_KEY: Map<string, SettingSpec> = new Map(
176
+ SETTINGS_ITEMS.flatMap((item) =>
177
+ (item.keys ?? [item.key]).map((key) => [key, item] as const),
178
+ ),
179
+ )
180
+
181
+ /** 校验结果:通过则 values 是**只含合法键**的补丁。 */
182
+ export interface NormalizeResult {
183
+ ok: boolean
184
+ /** 被接受的键值对(已按 spec 归一)。 */
185
+ values: Record<string, unknown>
186
+ /** 被拒绝的键及原因(给客户端提示用,不阻断其它键)。 */
187
+ rejected: Array<{ key: string; reason: string }>
188
+ }
189
+
190
+ /**
191
+ * 把一个客户端补丁归一成"可直接写进配置"的对象。
192
+ *
193
+ * 规则:
194
+ * · 不认识的 key 一律拒绝(不能靠 POST 往配置里塞任意字段);
195
+ * · number 做 clamp(超界不报错,夹到边界 —— 用户拖滑块时不该看到红色报错);
196
+ * · seg 只接受 options 里的值;
197
+ * · switch 只接受真正的布尔(字符串 'true' 之类的也别猜,直接拒);
198
+ * · text 去掉首尾空白,长到离谱的直接拒(防止把配置文件写爆)。
199
+ *
200
+ * 有意**不抛异常**:一个键写错不该让整次保存失败。
201
+ */
202
+ export function normalizeSettingsPatch(input: unknown): NormalizeResult {
203
+ const values: Record<string, unknown> = {}
204
+ const rejected: Array<{ key: string; reason: string }> = []
205
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
206
+ return { ok: false, values, rejected: [{ key: '', reason: '请求体不是对象' }] }
207
+ }
208
+ for (const [key, raw] of Object.entries(input as Record<string, unknown>)) {
209
+ const spec = SETTINGS_WRITABLE_BY_KEY.get(key)
210
+ if (!spec) {
211
+ // 虚拟键(如 modelChoice)不直接写配置:客户端要把它展开成 provider + model 再发上来。
212
+ // 单独认一下是为了给一句能照着做的错误,而不是笼统的"未知设置项"。
213
+ const virtual = SETTINGS_BY_KEY.get(key)
214
+ rejected.push({
215
+ key,
216
+ reason: virtual && Array.isArray(virtual.keys)
217
+ ? `该字段由 ${virtual.keys.join(' + ')} 组成,请分别提交`
218
+ : '未知的设置项',
219
+ })
220
+ continue
221
+ }
222
+ // 复合字段的子键一律按文本校验:目前唯一的复合字段是模型选择,
223
+ // provider 与 model 都是字符串(新增复合字段时在这里补类型判断)。
224
+ if (Array.isArray(spec.keys)) {
225
+ if (typeof raw !== 'string') {
226
+ rejected.push({ key, reason: '需要字符串' })
227
+ continue
228
+ }
229
+ if (raw.trim().length > 500) {
230
+ rejected.push({ key, reason: '太长(上限 500 字符)' })
231
+ continue
232
+ }
233
+ values[key] = raw.trim()
234
+ continue
235
+ }
236
+ if (spec.kind === 'switch') {
237
+ if (typeof raw !== 'boolean') {
238
+ rejected.push({ key, reason: '需要布尔值' })
239
+ continue
240
+ }
241
+ values[key] = raw
242
+ continue
243
+ }
244
+ if (spec.kind === 'number') {
245
+ const num = typeof raw === 'number' ? raw : Number(raw)
246
+ if (!Number.isFinite(num)) {
247
+ rejected.push({ key, reason: '需要数字' })
248
+ continue
249
+ }
250
+ const min = spec.min ?? -Infinity
251
+ const max = spec.max ?? Infinity
252
+ values[key] = Math.min(max, Math.max(min, num))
253
+ continue
254
+ }
255
+ if (spec.kind === 'seg') {
256
+ if (typeof raw !== 'string' || !(spec.options ?? []).includes(raw)) {
257
+ rejected.push({ key, reason: `可选:${(spec.options ?? []).join(' / ')}` })
258
+ continue
259
+ }
260
+ values[key] = raw
261
+ continue
262
+ }
263
+ // text
264
+ if (typeof raw !== 'string') {
265
+ rejected.push({ key, reason: '需要字符串' })
266
+ continue
267
+ }
268
+ const text = raw.trim()
269
+ if (text.length > 2000) {
270
+ rejected.push({ key, reason: '太长(上限 2000 字符)' })
271
+ continue
272
+ }
273
+ values[key] = text
274
+ }
275
+ return { ok: rejected.length === 0, values, rejected }
276
+ }
277
+
278
+ /** 设置页需要的完整载荷。 */
279
+ export interface SettingsPayload {
280
+ groups: SettingGroup[]
281
+ /** 当前生效值。 */
282
+ values: Record<string, unknown>
283
+ /** 出厂默认值(「恢复默认」和"是否改过"的判断都靠它)。 */
284
+ defaults: Record<string, unknown>
285
+ }
286
+
287
+ /** 组装 GET /settings 的响应体。 */
288
+ export function buildSettingsPayload(
289
+ values: Record<string, unknown>,
290
+ defaults: Record<string, unknown>,
291
+ ): SettingsPayload {
292
+ return { groups: SETTINGS_GROUPS, values, defaults }
293
+ }
294
+
295
+ /** 旧设置文件的底层配置继续生效,但不再暴露为设置控件或接受 UI 写入。 */
296
+ export const PERSISTED_SETTING_KEYS = ['maxTokens', 'temperature', 'resultCacheTtlMs']
297
+ export function normalizeStoredSettings(input: unknown): Record<string, unknown> {
298
+ const values = normalizeSettingsPatch(input).values
299
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return values
300
+ const raw = input as Record<string, unknown>
301
+ const bounds: Record<string, [number, number]> = { maxTokens: [0, 32000], temperature: [-1, 2], resultCacheTtlMs: [0, 86400000] }
302
+ for (const key of PERSISTED_SETTING_KEYS) {
303
+ const value = raw[key]
304
+ if (typeof value !== 'number' || !Number.isFinite(value)) continue
305
+ const [min, max] = bounds[key]!
306
+ values[key] = Math.min(max, Math.max(min, value))
307
+ }
308
+ // chatProvider/chatModel 已退役,不迁入统一的 provider/model。
309
+ return values
310
+ }