@surfishs/dsh-prompt-enhance 0.0.6 → 0.0.8

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.
Files changed (57) hide show
  1. package/README.en.md +3 -0
  2. package/README.md +3 -0
  3. package/cordis.patch.yml +1 -1
  4. package/lib/client.js +454 -397
  5. package/lib/index.js +67 -56
  6. package/lib/index.js.map +3 -3
  7. package/package.json +23 -15
  8. package/src/client/ActionIcons.tsx +4 -17
  9. package/src/client/EnhanceButton.tsx +52 -48
  10. package/src/client/ResultDock.tsx +22 -9
  11. package/src/client/ResultPanel.tsx +83 -52
  12. package/src/client/SparkleFishIcon.tsx +3 -13
  13. package/src/client/SparkleIcon.tsx +2 -12
  14. package/src/client/UndoBar.tsx +11 -6
  15. package/src/client/enhance-client.ts +44 -40
  16. package/src/client/index.tsx +3 -12
  17. package/src/client/llm-catalog.ts +14 -16
  18. package/src/client/locales.ts +20 -4
  19. package/src/client/reasoning-options.ts +7 -15
  20. package/src/client/settings-page-controls.tsx +449 -0
  21. package/src/client/settings-page-copy.ts +112 -0
  22. package/src/client/settings-page-spec.ts +330 -0
  23. package/src/client/settings-page-styles.ts +161 -0
  24. package/src/client/settings-page.tsx +166 -1109
  25. package/src/client/settings-source.ts +41 -31
  26. package/src/client/settings.ts +17 -12
  27. package/src/client/shortcut.ts +7 -6
  28. package/src/client/styles.ts +52 -0
  29. package/src/client/useDockAlignment.ts +5 -15
  30. package/src/config.ts +84 -27
  31. package/src/context.ts +1 -5
  32. package/src/enhance-routes.ts +8 -8
  33. package/src/enhancer.ts +43 -34
  34. package/src/orchestrate.ts +19 -23
  35. package/src/prompts.ts +4 -4
  36. package/src/provider-catalog.ts +1 -1
  37. package/src/reasoning-cache.ts +4 -4
  38. package/src/reasoning-efforts.ts +4 -9
  39. package/src/settings-source.ts +37 -23
  40. package/src/shared/limits.ts +38 -0
  41. package/src/shared/normalize.ts +4 -1
  42. package/src/shared/protocol.ts +27 -23
  43. package/src/shared/reasoning.ts +1 -7
  44. package/src/shared/stream-text.ts +0 -6
  45. package/src/shared/validate.ts +3 -9
  46. package/docs/code-review-2026-09.md +0 -211
  47. package/docs/handoff-settings-page.md +0 -195
  48. package/docs/release-0.2.3.md +0 -47
  49. package/docs/release-0.2.4.md +0 -20
  50. package/docs/release-0.2.5.md +0 -28
  51. package/docs/release-0.2.6.md +0 -33
  52. package/docs/release-0.2.7.md +0 -22
  53. package/docs/release-0.3.0.md +0 -36
  54. package/docs/release-0.3.1.md +0 -50
  55. package/docs/release-0.3.2.md +0 -41
  56. package/docs/release-0.3.3.md +0 -53
  57. package/docs/release-0.3.4.md +0 -43
@@ -140,9 +140,7 @@ export function installClientSettingsSource(ctx: ClientContext, options: ClientS
140
140
  */
141
141
  const resolveEntryId = (): string | undefined => {
142
142
  const served = servedNamespaces(forms)
143
- return options.rowIds.find((id) => served.includes(id))
144
- ?? served.find((ns) => ns.includes('dsh-prompt-enhance'))
145
- ?? options.rowIds[0]
143
+ return options.rowIds.find((id) => served.includes(id)) ?? served.find((ns) => ns.includes('dsh-prompt-enhance')) ?? options.rowIds[0]
146
144
  }
147
145
 
148
146
  /** Bind (or rebind) the form of the entry the host currently serves. */
@@ -183,23 +181,29 @@ export function installClientSettingsSource(ctx: ClientContext, options: ClientS
183
181
  // list is what names the row: follow it so a late load (or a rename the
184
182
  // first pass could not see) still lands on the plugin's section instead of
185
183
  // leaving the mirror on its bundled defaults.
186
- ctx.effect(() => () => {
187
- try {
188
- unsubscribeForm?.()
189
- } catch {
190
- // Service already gone.
191
- }
192
- }, 'dsh-prompt-enhance: settings form mirror')
184
+ ctx.effect(
185
+ () => () => {
186
+ try {
187
+ unsubscribeForm?.()
188
+ } catch {
189
+ // Service already gone.
190
+ }
191
+ },
192
+ 'dsh-prompt-enhance: settings form mirror',
193
+ )
193
194
  try {
194
195
  const watch = forms.describe?.()?.subscribe?.(() => bind())
195
196
  if (typeof watch === 'function') {
196
- ctx.effect(() => () => {
197
- try {
198
- watch()
199
- } catch {
200
- // Service already gone.
201
- }
202
- }, 'dsh-prompt-enhance: settings namespace watch')
197
+ ctx.effect(
198
+ () => () => {
199
+ try {
200
+ watch()
201
+ } catch {
202
+ // Service already gone.
203
+ }
204
+ },
205
+ 'dsh-prompt-enhance: settings namespace watch',
206
+ )
203
207
  }
204
208
  } catch {
205
209
  // A describe face without a subscription still leaves the first bind.
@@ -227,13 +231,16 @@ export function installClientSettingsSource(ctx: ClientContext, options: ClientS
227
231
  } catch {
228
232
  unsubscribe = undefined
229
233
  }
230
- ctx.effect(() => () => {
231
- try {
232
- unsubscribe?.()
233
- } catch {
234
- // Service already gone.
235
- }
236
- }, 'dsh-prompt-enhance: settings binder mirror')
234
+ ctx.effect(
235
+ () => () => {
236
+ try {
237
+ unsubscribe?.()
238
+ } catch {
239
+ // Service already gone.
240
+ }
241
+ },
242
+ 'dsh-prompt-enhance: settings binder mirror',
243
+ )
237
244
  })
238
245
 
239
246
  // 3. 0.1.1-rc: the element-level settings scope.
@@ -258,12 +265,15 @@ export function installClientSettingsSource(ctx: ClientContext, options: ClientS
258
265
  } catch {
259
266
  unsubscribe = undefined
260
267
  }
261
- ctx.effect(() => () => {
262
- try {
263
- unsubscribe?.()
264
- } catch {
265
- // Service already gone.
266
- }
267
- }, 'dsh-prompt-enhance: settings scope mirror')
268
+ ctx.effect(
269
+ () => () => {
270
+ try {
271
+ unsubscribe?.()
272
+ } catch {
273
+ // Service already gone.
274
+ }
275
+ },
276
+ 'dsh-prompt-enhance: settings scope mirror',
277
+ )
268
278
  })
269
279
  }
@@ -1,12 +1,18 @@
1
1
  /**
2
2
  * Browser-side mirror of the plugin settings. The client bundle never
3
3
  * imports the host config module (it pulls schemastery into the browser),
4
- * so this module re-declares the three fields the UI reads, with the same
5
- * defaults, and re-exports them as a subscribable store fed by the bound
6
- * settings scope.
4
+ * so this module narrows the four fields the UI reads to a local interface and
5
+ * re-exports them as a subscribable store fed by the bound settings scope.
6
+ *
7
+ * The DEFAULTS, unlike the shape, are not re-declared: they come from
8
+ * `shared/defaults`, the same module `DEFAULT_CONFIG` is built from. A `.ts`
9
+ * file there is dependency-free, so it costs the browser bundle nothing and
10
+ * keeps one shipped default from being spelled twice.
7
11
  * @module dsh-prompt-enhance/client/settings
8
12
  */
9
13
 
14
+ import { DEFAULT_VALUES } from '../shared/defaults'
15
+
10
16
  /** The settings subset the browser UI consumes (mirror of the host defaults). */
11
17
  export interface ClientSettings {
12
18
  enabled: boolean
@@ -18,16 +24,16 @@ export interface ClientSettings {
18
24
 
19
25
  // Compile-time guarantee: the mirror only tracks keys that exist in the host
20
26
  // config — a host-side rename fails this file's typecheck instead of
21
- // silently desyncing the two defaults.
27
+ // silently desyncing the two shapes.
22
28
  type AssertMirror = keyof ClientSettings extends keyof import('../config').Config ? true : never
23
29
  const _assertMirror: AssertMirror = true
24
30
  void _assertMirror
25
- /** Defaults mirroring the host `DEFAULT_CONFIG`. */
31
+ /** Defaults taken from the host's own default table, so they cannot drift. */
26
32
  export const DEFAULT_CLIENT_SETTINGS: ClientSettings = {
27
- enabled: true,
28
- maxInputChars: 12000,
29
- shortcut: '',
30
- streaming: true,
33
+ enabled: DEFAULT_VALUES.enabled,
34
+ maxInputChars: DEFAULT_VALUES.maxInputChars,
35
+ shortcut: DEFAULT_VALUES.shortcut,
36
+ streaming: DEFAULT_VALUES.streaming,
31
37
  }
32
38
 
33
39
  const listeners = new Set<() => void>()
@@ -70,9 +76,8 @@ export function decodeClientSettings(section: unknown): ClientSettings {
70
76
  if (record === null || typeof record !== 'object') return DEFAULT_CLIENT_SETTINGS
71
77
  return {
72
78
  enabled: typeof record.enabled === 'boolean' ? record.enabled : DEFAULT_CLIENT_SETTINGS.enabled,
73
- maxInputChars: typeof record.maxInputChars === 'number' && Number.isFinite(record.maxInputChars) && record.maxInputChars > 0
74
- ? Math.floor(record.maxInputChars)
75
- : DEFAULT_CLIENT_SETTINGS.maxInputChars,
79
+ maxInputChars:
80
+ typeof record.maxInputChars === 'number' && Number.isFinite(record.maxInputChars) && record.maxInputChars > 0 ? Math.floor(record.maxInputChars) : DEFAULT_CLIENT_SETTINGS.maxInputChars,
76
81
  shortcut: typeof record.shortcut === 'string' ? record.shortcut : DEFAULT_CLIENT_SETTINGS.shortcut,
77
82
  streaming: typeof record.streaming === 'boolean' ? record.streaming : DEFAULT_CLIENT_SETTINGS.streaming,
78
83
  }
@@ -60,7 +60,12 @@ type ModifierFlags = Record<'ctrl' | 'alt' | 'shift' | 'meta', boolean>
60
60
  */
61
61
  export function parseShortcut(spec: string | undefined): ShortcutCombo | null {
62
62
  if (spec === undefined) return null
63
- const tokens = spec.trim().toLowerCase().split('+').map((token) => token.trim()).filter((token) => token !== '')
63
+ const tokens = spec
64
+ .trim()
65
+ .toLowerCase()
66
+ .split('+')
67
+ .map((token) => token.trim())
68
+ .filter((token) => token !== '')
64
69
  if (tokens.length === 0 || tokens.length > 5) return null
65
70
  const modifiers: ModifierFlags = { ctrl: false, alt: false, shift: false, meta: false }
66
71
  const last = tokens[tokens.length - 1] ?? ''
@@ -86,10 +91,6 @@ export function parseShortcut(spec: string | undefined): ShortcutCombo | null {
86
91
  export function matchesShortcut(event: KeyboardEvent, combo: ShortcutCombo | null): boolean {
87
92
  if (combo === null) return false
88
93
  return (
89
- event.ctrlKey === combo.ctrl
90
- && event.altKey === combo.alt
91
- && event.shiftKey === combo.shift
92
- && event.metaKey === combo.meta
93
- && (event.code === combo.code || event.key.toLowerCase() === combo.key)
94
+ event.ctrlKey === combo.ctrl && event.altKey === combo.alt && event.shiftKey === combo.shift && event.metaKey === combo.meta && (event.code === combo.code || event.key.toLowerCase() === combo.key)
94
95
  )
95
96
  }
@@ -271,6 +271,58 @@ export const CSS = `
271
271
  text-align: center;
272
272
  white-space: nowrap;
273
273
  }
274
+ .dsh-pe-advanced {
275
+ margin-top: 12px;
276
+ border-top: 1px solid var(--dsw-alias-border-l3, rgba(128, 128, 128, 0.22));
277
+ }
278
+ .dsh-pe-advanced > summary {
279
+ display: flex;
280
+ align-items: center;
281
+ gap: 8px;
282
+ min-height: 40px;
283
+ padding: 0 4px;
284
+ list-style: none;
285
+ font-size: 13px;
286
+ font-weight: 500;
287
+ color: var(--dsw-alias-label-secondary, inherit);
288
+ cursor: pointer;
289
+ user-select: none;
290
+ }
291
+ .dsh-pe-advanced > summary::-webkit-details-marker { display: none; }
292
+ .dsh-pe-advanced > summary::marker { content: ''; }
293
+ .dsh-pe-advanced > summary::before {
294
+ content: '';
295
+ flex: none;
296
+ width: 0;
297
+ height: 0;
298
+ border-top: 4px solid transparent;
299
+ border-bottom: 4px solid transparent;
300
+ border-left: 5px solid currentColor;
301
+ transition: transform 120ms ease;
302
+ }
303
+ .dsh-pe-advanced[open] > summary::before { transform: rotate(90deg); }
304
+ .dsh-pe-advanced > summary:hover {
305
+ color: var(--dsw-alias-label-primary, inherit);
306
+ background: rgba(127, 127, 127, 0.08);
307
+ border-radius: 6px;
308
+ }
309
+ .dsh-pe-advanced > summary:focus-visible {
310
+ outline: 2px solid var(--dsw-alias-state-business-primary, #4f8cff);
311
+ outline-offset: -2px;
312
+ border-radius: 6px;
313
+ }
314
+ .dsh-pe-advanced[open] > summary { margin-bottom: 4px; }
315
+ .dsh-pe-advanced + .dsh-pe-form-footer { margin-top: 0; }
316
+ .dsh-pe-chip-reset:hover:not(:disabled),
317
+ .dsh-pe-chip-refresh:hover:not(:disabled) {
318
+ --pe-chip-bg: var(--dsw-alias-interactive-bg-hover, rgba(127, 127, 127, 0.18));
319
+ --pe-chip-color: var(--dsw-alias-label-primary, inherit);
320
+ }
321
+ .dsh-pe-chip-reset:focus-visible,
322
+ .dsh-pe-chip-refresh:focus-visible {
323
+ outline: 2px solid var(--dsw-alias-state-business-primary, #4f8cff);
324
+ outline-offset: 2px;
325
+ }
274
326
  .dsh-pe-form-footer {
275
327
  display: flex;
276
328
  justify-content: flex-end;
@@ -28,7 +28,6 @@ export function useDockAlignment(active: boolean): RefObject<HTMLDivElement> {
28
28
  // parent; use a layout margin instead. The previous margin is subtracted
29
29
  // from the measured left so repeated runs do not accumulate drift.
30
30
  root.style.transform = ''
31
- const previousMargin = parseFloat(root.style.marginLeft) || 0
32
31
  const rootRect = root.getBoundingClientRect()
33
32
  const editors = Array.from(document.querySelectorAll<HTMLElement>('textarea, [contenteditable="true"], [role="textbox"]'))
34
33
  const editor = editors.find((node) => {
@@ -53,25 +52,16 @@ export function useDockAlignment(active: boolean): RefObject<HTMLDivElement> {
53
52
  for (let depth = 0; depth < 12 && node !== null; depth++) {
54
53
  const rect = node.getBoundingClientRect()
55
54
  const style = getComputedStyle(node)
56
- if (
57
- rect.width >= editorRect.width
58
- && rect.width > 360
59
- && rect.height > 48
60
- && (parseFloat(style.borderTopLeftRadius) || 0) >= 4
61
- && style.backgroundColor !== 'rgba(0, 0, 0, 0)'
62
- ) {
55
+ if (rect.width >= editorRect.width && rect.width > 360 && rect.height > 48 && (parseFloat(style.borderTopLeftRadius) || 0) >= 4 && style.backgroundColor !== 'rgba(0, 0, 0, 0)') {
63
56
  candidates.push({ node, rect })
64
57
  }
65
58
  node = node.parentElement
66
59
  }
67
60
  const editorCenter = editorRect.left + editorRect.width / 2
68
- const cardEntry = candidates
69
- .filter((candidate) => (
70
- candidate.rect.width <= window.innerWidth * 0.8
71
- && Math.abs(candidate.rect.left + candidate.rect.width / 2 - editorCenter) < 40
72
- ))
73
- .sort((a, b) => b.rect.width - a.rect.width)[0]
74
- ?? candidates.sort((a, b) => b.rect.width - a.rect.width)[0]
61
+ const cardEntry =
62
+ candidates
63
+ .filter((candidate) => candidate.rect.width <= window.innerWidth * 0.8 && Math.abs(candidate.rect.left + candidate.rect.width / 2 - editorCenter) < 40)
64
+ .sort((a, b) => b.rect.width - a.rect.width)[0] ?? candidates.sort((a, b) => b.rect.width - a.rect.width)[0]
75
65
  if (cardEntry === undefined) return
76
66
  const cardRect = cardEntry.rect
77
67
  const width = `${cardRect.width}px`
package/src/config.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  import z from '@deepseek-ai/schemastery'
9
9
  import { INVARIANT_CONTRACT } from './prompts'
10
10
  import { DEFAULT_VALUES } from './shared/defaults'
11
+ import { FIELD_LIMITS, TEMPERATURE, type NumericRange } from './shared/limits'
11
12
 
12
13
  /** Settings namespace of the plugin section. */
13
14
  export const PROMPT_ENHANCE_NAMESPACE = 'dsh-prompt-enhance'
@@ -133,20 +134,78 @@ export const Config = z.object({
133
134
  enabled: z.boolean().default(DEFAULT_CONFIG.enabled).description('总开关:关闭后隐藏输入框增强按钮并停用所有触发方式').volatile(),
134
135
  provider: z.string().description('覆盖模型路由的 provider(与「模型」必须成对填写;留空跟随当前会话模型)').volatile(),
135
136
  model: z.string().description('覆盖模型路由的 model(与「provider」必须成对填写;留空跟随当前会话模型)').volatile(),
136
- temperature: z.number().min(0).max(1).step(0.05).default(DEFAULT_CONFIG.temperature).description('采样温度;低温改写更忠实于原意').volatile(),
137
- reasoningEffort: z.string().default(DEFAULT_CONFIG.reasoningEffort).description('推理档位:填写当前 provider/model 声明的档位 id(如 DeepSeek 的 off/low/high/max);inherit 表示不传该字段、跟随提供方默认档').volatile(),
138
- maxOutputTokens: z.number().step(1).min(256).max(32768).default(DEFAULT_CONFIG.maxOutputTokens).description('单次增强的输出 token 上限').volatile(),
139
- maxInputChars: z.number().step(1).min(200).max(200000).default(DEFAULT_CONFIG.maxInputChars).description('输入字数上限;超限拒绝而不截断,避免改变原意').volatile(),
140
- timeoutMs: z.number().step(1).min(5000).max(600000).default(DEFAULT_CONFIG.timeoutMs).description('单次增强的超时(毫秒)').volatile(),
137
+ temperature: z.number().min(TEMPERATURE.min).max(TEMPERATURE.max).step(TEMPERATURE.step).default(DEFAULT_CONFIG.temperature).description('采样温度;低温改写更忠实于原意').volatile(),
138
+ reasoningEffort: z
139
+ .string()
140
+ .default(DEFAULT_CONFIG.reasoningEffort)
141
+ .description('推理档位:填写当前 provider/model 声明的档位 id(如 DeepSeek 的 off/low/high/max);inherit 表示不传该字段、跟随提供方默认档')
142
+ .volatile(),
143
+ maxOutputTokens: z
144
+ .number()
145
+ .step(1)
146
+ .min(FIELD_LIMITS.maxOutputTokens.min)
147
+ .max(FIELD_LIMITS.maxOutputTokens.max)
148
+ .default(DEFAULT_CONFIG.maxOutputTokens)
149
+ .description('单次增强的输出 token 上限')
150
+ .volatile(),
151
+ maxInputChars: z
152
+ .number()
153
+ .step(1)
154
+ .min(FIELD_LIMITS.maxInputChars.min)
155
+ .max(FIELD_LIMITS.maxInputChars.max)
156
+ .default(DEFAULT_CONFIG.maxInputChars)
157
+ .description('输入字数上限;超限拒绝而不截断,避免改变原意')
158
+ .volatile(),
159
+ timeoutMs: z.number().step(1).min(FIELD_LIMITS.timeoutMs.min).max(FIELD_LIMITS.timeoutMs.max).default(DEFAULT_CONFIG.timeoutMs).description('单次增强的超时(毫秒)').volatile(),
141
160
  systemPrompt: z.string().role('textarea').default(DEFAULT_CONFIG.systemPrompt).description('系统提示词;留空使用内置增强策略').volatile(),
142
- strategyMode: z.union(['replace-default', 'extend-default']).default(DEFAULT_CONFIG.strategyMode).description('自定义系统提示词的组合方式:整体替换内置策略(默认;仅保留插件始终追加的最小输出契约:输入是数据、只输出改写结果),或把自定义文本追加在内置策略之后(内置规则继续生效)').volatile(),
143
- shortcut: z.string().default(DEFAULT_CONFIG.shortcut).description('触发快捷键,默认留空即禁用;如需启用,填如 ctrl+alt+e(须包含 ctrl/alt/meta 中至少一个修饰键,shift 仅可作附加,纯字母/数字或 shift+字母会被忽略)').volatile(),
144
- maxConcurrent: z.number().step(1).min(1).max(16).default(DEFAULT_CONFIG.maxConcurrent).description('宿主侧并发上限:同时进行的增强调用数,超出的请求返回 429').volatile(),
145
- rateLimitPerMinute: z.number().step(1).min(1).max(600).default(DEFAULT_CONFIG.rateLimitPerMinute).description('每分钟增强次数上限(滑动窗口),超出返回 429').volatile(),
161
+ strategyMode: z
162
+ .union(['replace-default', 'extend-default'])
163
+ .default(DEFAULT_CONFIG.strategyMode)
164
+ .description('自定义系统提示词的组合方式:整体替换内置策略(默认;仅保留插件始终追加的最小输出契约:输入是数据、只输出改写结果),或把自定义文本追加在内置策略之后(内置规则继续生效)')
165
+ .volatile(),
166
+ shortcut: z
167
+ .string()
168
+ .default(DEFAULT_CONFIG.shortcut)
169
+ .description('触发快捷键,默认留空即禁用;如需启用,填如 ctrl+alt+e(须包含 ctrl/alt/meta 中至少一个修饰键,shift 仅可作附加,纯字母/数字或 shift+字母会被忽略)')
170
+ .volatile(),
171
+ maxConcurrent: z
172
+ .number()
173
+ .step(1)
174
+ .min(FIELD_LIMITS.maxConcurrent.min)
175
+ .max(FIELD_LIMITS.maxConcurrent.max)
176
+ .default(DEFAULT_CONFIG.maxConcurrent)
177
+ .description('宿主侧并发上限:同时进行的增强调用数,超出的请求返回 429')
178
+ .volatile(),
179
+ rateLimitPerMinute: z
180
+ .number()
181
+ .step(1)
182
+ .min(FIELD_LIMITS.rateLimitPerMinute.min)
183
+ .max(FIELD_LIMITS.rateLimitPerMinute.max)
184
+ .default(DEFAULT_CONFIG.rateLimitPerMinute)
185
+ .description('每分钟增强次数上限(滑动窗口),超出返回 429')
186
+ .volatile(),
146
187
  streaming: z.boolean().default(DEFAULT_CONFIG.streaming).description('增量展示:模型边写边在面板显示(仅影响显示节奏,最终结果不变;宿主或网络不支持时自动回退为一次性返回)').volatile(),
147
- contextAware: z.boolean().default(DEFAULT_CONFIG.contextAware).description('上下文感知:读取当前会话近期对话,用于消解指代、补全省略与术语约束;无历史或历史不足时自动回退为单条增强,不臆造信息').volatile(),
148
- contextMaxMessages: z.number().step(1).min(0).max(50).default(DEFAULT_CONFIG.contextMaxMessages).description('上下文窗口(条数):最多参考最近多少条 user/assistant 轮次;0 表示不参考').volatile(),
149
- contextMaxChars: z.number().step(1).min(0).max(100000).default(DEFAULT_CONFIG.contextMaxChars).description('上下文窗口(字数):历史片段的字符预算,从最新一条向前装配;0 表示不参考').volatile(),
188
+ contextAware: z
189
+ .boolean()
190
+ .default(DEFAULT_CONFIG.contextAware)
191
+ .description('上下文感知:读取当前会话近期对话,用于消解指代、补全省略与术语约束;无历史或历史不足时自动回退为单条增强,不臆造信息')
192
+ .volatile(),
193
+ contextMaxMessages: z
194
+ .number()
195
+ .step(1)
196
+ .min(FIELD_LIMITS.contextMaxMessages.min)
197
+ .max(FIELD_LIMITS.contextMaxMessages.max)
198
+ .default(DEFAULT_CONFIG.contextMaxMessages)
199
+ .description('上下文窗口(条数):最多参考最近多少条 user/assistant 轮次;0 表示不参考')
200
+ .volatile(),
201
+ contextMaxChars: z
202
+ .number()
203
+ .step(1)
204
+ .min(FIELD_LIMITS.contextMaxChars.min)
205
+ .max(FIELD_LIMITS.contextMaxChars.max)
206
+ .default(DEFAULT_CONFIG.contextMaxChars)
207
+ .description('上下文窗口(字数):历史片段的字符预算,从最新一条向前装配;0 表示不参考')
208
+ .volatile(),
150
209
  })
151
210
 
152
211
  /**
@@ -192,8 +251,8 @@ export function resolveConfig(config: Config): Config {
192
251
  throw new Error('dsh-prompt-enhance: provider/model 覆盖必须是非空字符串')
193
252
  }
194
253
  const temperature = config.temperature
195
- if (typeof temperature !== 'number' || !Number.isFinite(temperature) || temperature < 0 || temperature > 1) {
196
- throw new Error('dsh-prompt-enhance: temperature 必须是 0–1 之间的有限数字')
254
+ if (typeof temperature !== 'number' || !Number.isFinite(temperature) || temperature < TEMPERATURE.min || temperature > TEMPERATURE.max) {
255
+ throw new Error(`dsh-prompt-enhance: temperature 必须是 ${TEMPERATURE.min}–${TEMPERATURE.max} 之间的有限数字`)
197
256
  }
198
257
  // Whitespace-only is "absent", not "set": the explicit pair is definitionally
199
258
  // non-empty, so a blank override strips away as `undefined` rather than
@@ -203,9 +262,9 @@ export function resolveConfig(config: Config): Config {
203
262
  const trimmed = value.trim()
204
263
  return trimmed === '' ? undefined : trimmed
205
264
  }
206
- const intInRange = (value: unknown, name: string, min: number, max: number): number => {
207
- if (typeof value !== 'number' || !Number.isInteger(value) || value < min || value > max) {
208
- throw new Error(`dsh-prompt-enhance: ${name} 必须是 ${min}–${max} 之间的整数`)
265
+ const intInRange = (value: unknown, name: string, range: NumericRange): number => {
266
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < range.min || value > range.max) {
267
+ throw new Error(`dsh-prompt-enhance: ${name} 必须是 ${range.min}–${range.max} 之间的整数`)
209
268
  }
210
269
  return value
211
270
  }
@@ -219,21 +278,21 @@ export function resolveConfig(config: Config): Config {
219
278
  // does not declare is rejected by the adapter with a clear error rather
220
279
  // than silently replaced.
221
280
  reasoningEffort: resolveReasoningEffort(config.reasoningEffort),
222
- maxOutputTokens: intInRange(config.maxOutputTokens, 'maxOutputTokens', 256, 32768),
223
- maxInputChars: intInRange(config.maxInputChars, 'maxInputChars', 200, 200000),
224
- timeoutMs: intInRange(config.timeoutMs, 'timeoutMs', 5000, 600000),
281
+ maxOutputTokens: intInRange(config.maxOutputTokens, 'maxOutputTokens', FIELD_LIMITS.maxOutputTokens),
282
+ maxInputChars: intInRange(config.maxInputChars, 'maxInputChars', FIELD_LIMITS.maxInputChars),
283
+ timeoutMs: intInRange(config.timeoutMs, 'timeoutMs', FIELD_LIMITS.timeoutMs),
225
284
  systemPrompt: typeof config.systemPrompt === 'string' ? config.systemPrompt : '',
226
285
  // Tolerate absent or hand-edited values: anything but the extend literal
227
286
  // means replace, so stored sections from earlier versions keep exactly
228
287
  // the behavior they were saved under.
229
288
  strategyMode: config.strategyMode === 'extend-default' ? 'extend-default' : 'replace-default',
230
289
  shortcut: typeof config.shortcut === 'string' ? config.shortcut : '',
231
- maxConcurrent: intInRange(config.maxConcurrent, 'maxConcurrent', 1, 16),
232
- rateLimitPerMinute: intInRange(config.rateLimitPerMinute, 'rateLimitPerMinute', 1, 600),
290
+ maxConcurrent: intInRange(config.maxConcurrent, 'maxConcurrent', FIELD_LIMITS.maxConcurrent),
291
+ rateLimitPerMinute: intInRange(config.rateLimitPerMinute, 'rateLimitPerMinute', FIELD_LIMITS.rateLimitPerMinute),
233
292
  streaming: typeof config.streaming === 'boolean' ? config.streaming : DEFAULT_CONFIG.streaming,
234
293
  contextAware: typeof config.contextAware === 'boolean' ? config.contextAware : DEFAULT_CONFIG.contextAware,
235
- contextMaxMessages: intInRange(config.contextMaxMessages, 'contextMaxMessages', 0, 50),
236
- contextMaxChars: intInRange(config.contextMaxChars, 'contextMaxChars', 0, 100000),
294
+ contextMaxMessages: intInRange(config.contextMaxMessages, 'contextMaxMessages', FIELD_LIMITS.contextMaxMessages),
295
+ contextMaxChars: intInRange(config.contextMaxChars, 'contextMaxChars', FIELD_LIMITS.contextMaxChars),
237
296
  }
238
297
  }
239
298
 
@@ -253,8 +312,6 @@ export function resolveConfig(config: Config): Config {
253
312
  export function effectiveSystemPrompt(config: Config, builtin: string): string {
254
313
  const custom = (config.systemPrompt ?? '').trim()
255
314
  if (custom === '') return builtin
256
- const strategy = config.strategyMode === 'extend-default'
257
- ? `${builtin}\n\nOperator additions (follow them where they do not conflict with the rules above):\n${custom}`
258
- : custom
315
+ const strategy = config.strategyMode === 'extend-default' ? `${builtin}\n\nOperator additions (follow them where they do not conflict with the rules above):\n${custom}` : custom
259
316
  return `${strategy}\n\n${INVARIANT_CONTRACT}`
260
317
  }
package/src/context.ts CHANGED
@@ -180,11 +180,7 @@ export function formatContextBlock(turns: readonly ContextTurn[]): string {
180
180
  * @returns the framed snippet, or `undefined` when there is no usable history
181
181
  * — the caller then runs the original single-prompt enhancement.
182
182
  */
183
- export function buildConversationContext(
184
- messages: readonly unknown[] | undefined,
185
- options: ContextWindowOptions,
186
- draft?: string,
187
- ): string | undefined {
183
+ export function buildConversationContext(messages: readonly unknown[] | undefined, options: ContextWindowOptions, draft?: string): string | undefined {
188
184
  if (messages === undefined) return undefined
189
185
  const turns = selectTurns(messages, options, draft)
190
186
  if (turns.length === 0) return undefined
@@ -136,9 +136,7 @@ async function serveEnhance(ctx: Context, readConfig: () => Config, gate: Admiss
136
136
  // empty text (server-side only — the client guards it first) stays generic.
137
137
  writeJson(res, 422, {
138
138
  ok: false,
139
- error: check.code === 'too-long'
140
- ? { code: 'rejected', params: { count: check.count, max: check.max } }
141
- : { code: 'rejected' },
139
+ error: check.code === 'too-long' ? { code: 'rejected', params: { count: check.count, max: check.max } } : { code: 'rejected' },
142
140
  })
143
141
  return
144
142
  }
@@ -209,7 +207,7 @@ async function serveEnhance(ctx: Context, readConfig: () => Config, gate: Admiss
209
207
  text: record.text,
210
208
  sessionRoute: sessionRouteOf(ctx, sessionId),
211
209
  signal: callerAbort.signal,
212
- ...sessionId !== undefined ? { sessionId } : {},
210
+ ...(sessionId !== undefined ? { sessionId } : {}),
213
211
  }
214
212
  if (stream) {
215
213
  // The stream already opens before the model call, so the client sees
@@ -334,9 +332,11 @@ const mounts = new WeakMap<Context, RouteMount>()
334
332
  */
335
333
  export function registerEnhanceRoute(ctx: Context, readConfig: () => Config): void {
336
334
  ctx.inject(['webServer'], (routeCtx: Context) => {
337
- const webserver = routeCtx.get('webServer') as unknown as {
338
- register(route: unknown): unknown
339
- } | undefined
335
+ const webserver = routeCtx.get('webServer') as unknown as
336
+ | {
337
+ register(route: unknown): unknown
338
+ }
339
+ | undefined
340
340
  if (webserver === undefined) return
341
341
  const existing = mounts.get(ctx)
342
342
  // Already mounted on this very service (a second apply on a live fiber, or
@@ -370,7 +370,7 @@ export function registerEnhanceRoute(ctx: Context, readConfig: () => Config): vo
370
370
  return serveEnhance(ctx, readConfig, gate, pathname, req, res, pathname === ENHANCE_STREAM_ENDPOINT)
371
371
  },
372
372
  })
373
- const disposed = typeof dispose === 'function' ? dispose as () => void : (): void => {}
373
+ const disposed = typeof dispose === 'function' ? (dispose as () => void) : (): void => {}
374
374
  mounts.set(ctx, { webserver, dispose: disposed })
375
375
  return (): void => {
376
376
  // Only the owner clears the record: after a service swap a newer mount
package/src/enhancer.ts CHANGED
@@ -163,8 +163,8 @@ export async function enhanceText(llm: LlmStreamFace, options: EnhanceCallOption
163
163
  // `inherit` deliberately leaves the field unset, for a route that
164
164
  // rejects an explicit effort; `ReasoningEffortId` is a brand over the
165
165
  // effort id, hence the cast.
166
- ...effort === 'inherit' ? {} : { reasoningEffort: effort as NonNullable<GenerateOptions['reasoningEffort']> },
167
- ...options.sessionId !== undefined ? { sessionId: options.sessionId as GenerateOptions['sessionId'] } : {},
166
+ ...(effort === 'inherit' ? {} : { reasoningEffort: effort as NonNullable<GenerateOptions['reasoningEffort']> }),
167
+ ...(options.sessionId !== undefined ? { sessionId: options.sessionId as GenerateOptions['sessionId'] } : {}),
168
168
  }
169
169
  const assembler = new BlockAssembler()
170
170
  const iterator = llm.stream(generate)[Symbol.asyncIterator]()
@@ -221,9 +221,7 @@ export async function enhanceText(llm: LlmStreamFace, options: EnhanceCallOption
221
221
  // One model call per attempt; the loop exists only for the single effort
222
222
  // downgrade below, so it can never spin more than twice.
223
223
  let retriedWithoutEffort = false
224
- const readAttempt = async (): Promise<
225
- { ok: true; blocks: ReturnType<BlockAssembler['blocks']>; usage: BlockAssembler['usage']; truncated: boolean } | { ok: false; detail: EnhanceError }
226
- > => {
224
+ const readAttempt = async (): Promise<{ ok: true; blocks: ReturnType<BlockAssembler['blocks']>; usage: BlockAssembler['usage']; truncated: boolean } | { ok: false; detail: EnhanceError }> => {
227
225
  while (true) {
228
226
  let attempt: { assembler: BlockAssembler; exhausted: boolean }
229
227
  try {
@@ -292,28 +290,32 @@ export async function enhanceText(llm: LlmStreamFace, options: EnhanceCallOption
292
290
  if (blocks.some((block) => block.type === 'tool-call')) {
293
291
  fail({ code: 'upstream', params: { reason: 'tool-call' } })
294
292
  }
295
- const joined = blocks.filter((block) => block.type === 'text').map((block) => block.text).join('\n')
293
+ const joined = blocks
294
+ .filter((block) => block.type === 'text')
295
+ .map((block) => block.text)
296
+ .join('\n')
296
297
  const text = normalizeOutput(joined)
297
298
  if (text === '') {
298
299
  fail({ code: 'upstream', params: { reason: 'empty' } })
299
300
  }
300
301
  const usage = outcome.usage
301
- const reportedUsage = usage === undefined
302
- ? undefined
303
- : {
304
- inputTokens: usage.inputTokens,
305
- outputTokens: usage.outputTokens,
306
- ...usage.totalTokens === undefined ? {} : { totalTokens: usage.totalTokens },
307
- ...usage.cacheReadTokens === undefined ? {} : { cacheReadTokens: usage.cacheReadTokens },
308
- ...usage.cacheWriteTokens === undefined ? {} : { cacheWriteTokens: usage.cacheWriteTokens },
309
- }
302
+ const reportedUsage =
303
+ usage === undefined
304
+ ? undefined
305
+ : {
306
+ inputTokens: usage.inputTokens,
307
+ outputTokens: usage.outputTokens,
308
+ ...(usage.totalTokens === undefined ? {} : { totalTokens: usage.totalTokens }),
309
+ ...(usage.cacheReadTokens === undefined ? {} : { cacheReadTokens: usage.cacheReadTokens }),
310
+ ...(usage.cacheWriteTokens === undefined ? {} : { cacheWriteTokens: usage.cacheWriteTokens }),
311
+ }
310
312
  return {
311
313
  text,
312
314
  provider: options.route.provider,
313
315
  model: options.route.model,
314
316
  elapsedMs: Date.now() - started,
315
- ...reportedUsage === undefined ? {} : { usage: reportedUsage },
316
- ...outcome.truncated ? { truncated: true } : {},
317
+ ...(reportedUsage === undefined ? {} : { usage: reportedUsage }),
318
+ ...(outcome.truncated ? { truncated: true } : {}),
317
319
  }
318
320
  } catch (error) {
319
321
  if (error instanceof EnhanceFailure) throw error
@@ -353,15 +355,7 @@ function finishToDetail(reason: FinishReason): EnhanceError | undefined {
353
355
  }
354
356
 
355
357
  /** Stable upstream reasons the dictionaries and formatEnhanceError both know. */
356
- export type UpstreamReason =
357
- | 'auth'
358
- | 'invalid-credential'
359
- | 'rate-limit'
360
- | 'quota'
361
- | 'empty'
362
- | 'context-window'
363
- | 'tool-call'
364
- | 'max-tokens'
358
+ export type UpstreamReason = 'auth' | 'invalid-credential' | 'rate-limit' | 'quota' | 'empty' | 'context-window' | 'tool-call' | 'max-tokens'
365
359
 
366
360
  /** Known provider failure codes with a dedicated fix hint; others stay generic. */
367
361
  const REASON_CODES: Record<string, UpstreamReason> = {
@@ -406,14 +400,29 @@ export function formatEnhanceError(error: EnhanceError): string {
406
400
  const params = error.params ?? {}
407
401
  let text: string
408
402
  switch (error.code) {
409
- case 'rejected': text = '增强请求被拒绝。'; break
410
- case 'rate-limit': text = `请求过于频繁:每分钟最多 ${params.limit ?? '?'} 次增强,请 ${params.retryAfterSeconds ?? '稍候'} 秒后再试。`; break
411
- case 'concurrency-limit': text = `已有 ${params.max ?? '?'} 个增强在进行中,请等待其中一个完成后再试。`; break
412
- case 'cooldown': text = `连续 ${params.failures ?? '?'} 次增强失败,已暂停调用以避免持续冲击模型服务;请 ${params.retryAfterSeconds ?? '?'} 秒后重试,或先检查插件设置中的模型配置。`; break
413
- case 'timeout': text = `增强超时(${params.seconds ?? '?'} 秒),可重试;原输入未改动。`; break
414
- case 'unconfigured': text = '尚未确定增强用的模型:请在插件设置中成对填写 provider/model,或先在当前会话发送一条消息(将跟随会话模型)。'; break
415
- case 'upstream': text = typeof params.reason === 'string' ? (REASON_HINTS[params.reason as UpstreamReason] ?? '模型服务返回错误,请重试;原输入未改动。') : '模型服务返回错误,请重试;原输入未改动。'; break
416
- default: text = '增强失败,请重试;原输入未改动。'
403
+ case 'rejected':
404
+ text = '增强请求被拒绝。'
405
+ break
406
+ case 'rate-limit':
407
+ text = `请求过于频繁:每分钟最多 ${params.limit ?? '?'} 次增强,请 ${params.retryAfterSeconds ?? '稍候'} 秒后再试。`
408
+ break
409
+ case 'concurrency-limit':
410
+ text = `已有 ${params.max ?? '?'} 个增强在进行中,请等待其中一个完成后再试。`
411
+ break
412
+ case 'cooldown':
413
+ text = `连续 ${params.failures ?? '?'} 次增强失败,已暂停调用以避免持续冲击模型服务;请 ${params.retryAfterSeconds ?? '?'} 秒后重试,或先检查插件设置中的模型配置。`
414
+ break
415
+ case 'timeout':
416
+ text = `增强超时(${params.seconds ?? '?'} 秒),可重试;原输入未改动。`
417
+ break
418
+ case 'unconfigured':
419
+ text = '尚未确定增强用的模型:请在插件设置中成对填写 provider/model,或先在当前会话发送一条消息(将跟随会话模型)。'
420
+ break
421
+ case 'upstream':
422
+ text = typeof params.reason === 'string' ? (REASON_HINTS[params.reason as UpstreamReason] ?? '模型服务返回错误,请重试;原输入未改动。') : '模型服务返回错误,请重试;原输入未改动。'
423
+ break
424
+ default:
425
+ text = '增强失败,请重试;原输入未改动。'
417
426
  }
418
427
  const detail = error.message
419
428
  if (detail !== undefined && detail !== '') return `${text}\n${detail}`