@infinity_cheng/dsh-prompt-editor 0.4.0 → 0.5.0

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/README.md CHANGED
@@ -48,14 +48,14 @@ Client 可以热更新,但 Host 的 JavaScript 模块换代必须**完全退
48
48
 
49
49
  1. 在输入框里输入草稿,或选中其中一段。
50
50
  2. 点输入框右侧的「增强」,或在输入框里按 `⌘E` / `Ctrl+E`(`⌘⇧E` / `Ctrl+Shift+E` 也兼容)。
51
- 3. 预览弹窗默认显示 inline diff(删除划线、新增高亮),可切到「对照」看左右原文/改写;下面是确定性检查。
51
+ 3. 预览弹窗默认显示「对照」左右两栏,可切到「差异」看 inline diff(删除划线、新增高亮);下面是确定性检查。
52
52
  4. 弹窗里可以复制结果、停止生成;替换后 8 秒内可以点「撤销」恢复原文。
53
- 4. 选 `替换选中` / `替换全文` 才写回草稿;`重试` 可换规则重跑,`取消` 不改任何内容。
54
- 5. 有选区时只替换选区;没有选区时替换全文。替换后仍可用输入框自己的 `Ctrl+Z` 撤销。
53
+ 5. 选 `替换选中` / `替换全文` 才写回草稿;`重试` 可换规则重跑,`取消` 不改任何内容。
54
+ 6. 有选区时只替换选区;没有选区时替换全文。替换后仍可用输入框自己的 `Ctrl+Z` 撤销。
55
55
 
56
56
  设置入口:**设置 → 提示词增强**。默认规则和增强模型都写入当前 DSH profile 的插件配置,输入框按钮和 Agent 工具共用同一个值。
57
57
 
58
- 默认规则下面可以开启 **使用增强专用模型**:关闭时跟随当前会话模型;开启后固定使用从 DSH 模型目录里选择的 provider/model。
58
+ 默认规则下面可以开启 **使用增强专用模型**:关闭时跟随当前会话模型,并提示「已保存:…(当前未启用)」;开启后固定使用从 DSH 模型目录里选择的 provider/model。
59
59
 
60
60
  含 `@文件`/链接引用块时,**先选中一段不含引用块的文字**再点增强:只替换选区,引用块原样保留。没有选区或选区包含引用块时,会提示重新选择;全文替换含引用块的草稿仍不支持。
61
61
 
@@ -75,6 +75,8 @@ Client 可以热更新,但 Host 的 JavaScript 模块换代必须**完全退
75
75
  | `language` | 否 | `auto` / `zh` / `en` |
76
76
  | `context` | 否 | 可选的对话或项目上下文,按数据处理 |
77
77
  | `contextPath` | 否 | 可选文件,读入作为上下文 |
78
+ | `provider` | 否 | 高级:单次调用覆盖 provider,需同时给 `model` |
79
+ | `model` | 否 | 高级:单次调用覆盖模型,不影响设置里的默认模型 |
78
80
 
79
81
  返回:
80
82
 
@@ -173,7 +175,7 @@ Safari 验证结果。
173
175
  | 向用户提问 | 0 | 0 |
174
176
  | 占位符 | 1(未检出) | 0 |
175
177
 
176
- 第二轮唯一剩下的 `too_long` 是 React 升级任务(737 字符);strict 模式对“把…改清楚”仍偏短。这两项是质量打磨,不是正确性问题。
178
+ 这是 Flash 的历史基线(0.1.x 规则)。后续的 Pro 自适应提示词、strict「最小但完整」和日志 `CODE_CHANGE` 约束见下方 changelog,以及 `tests/live-eval-pro-01.md`、`tests/blind-eval-pro-vs-flash-01.md`(未随 npm 包发布)。
177
179
 
178
180
  评测方法与完整评分表在源码的 `tests/live-eval-01.md` 和 `tests/live-eval-02.md`(未随 npm 包发布)。
179
181
 
@@ -210,6 +212,15 @@ Safari 验证结果。
210
212
  llmTimeoutMs: 120000
211
213
  maxLengthRatio: 5.5
212
214
  maxPromptChars: 3000
215
+ # 可选:按 provider/model 覆盖提示词与调用参数;未配置时使用内置 Pro 档案
216
+ modelProfiles:
217
+ "deepseek-official/deepseek-v4-pro":
218
+ promptVariant: auto # auto | concise | balanced | normal
219
+ temperature: 0.12
220
+ maxLengthRatio: 4
221
+ maxPromptChars: 1800
222
+ retryOnLength: true
223
+ maxTokens: 0 # 0 = 不在插件层限制
213
224
  ```
214
225
 
215
226
  ## 兼容性
@@ -220,6 +231,21 @@ Safari 验证结果。
220
231
  - Host + Client 两半;Client 是 lazy-CJS bundle,无独立构建步骤
221
232
  - Client 槽位:`conversation.input.right`、`settings.section`
222
233
 
234
+ ### 0.5.0 Pro 调优与盲评
235
+
236
+ - 内置 `deepseek-official/deepseek-v4-pro` 自适应档案:temperature 0.12、4x/1800 字符上限、超长重试。
237
+ - 提示词按草稿复杂度自动选择:简单草稿用 concise(2–4x),拆服务/监控/升级/并发/日志脱敏等复杂草稿用 balanced(2–5x,保留必要的范围、方法、验收)。
238
+ - 关闭专用模型开关时,下拉显示「跟随当前会话模型」,下方提示已保存的模型;重新开启自动恢复。
239
+ - 不限制 Pro 的 `maxTokens`,避免 reasoning 预算耗尽后没有文本。
240
+ - 代码型日志/数据草稿注入 `task_kind_hint`;仍写成“处理现成样本”时判 `wrong_task_kind`,重试或回退。
241
+ - 新增 `tests/live-eval-pro-01.md` 基线:20/20 完成,0 error,0 warning,0 fallback,2 UNCHANGED。
242
+ - strict 改为“最小但完整”:补动作、输入证据、验收,仍禁止章节/清单/示例。
243
+ - 新增 `tests/blind-eval-pro-vs-flash-01.md`:4 组匿名盲评,Pro 4 胜 0 负;总均分 Pro 4.81 / Flash 4.06。
244
+ - `enhance_prompt` 支持可选 `provider` / `model` 单次覆盖,便于模型对比,不影响设置里的默认模型。
245
+ - 日志/脱敏类草稿的 CODE_CHANGE 约束补充固定占位符、字段结构、全量日志覆盖和验收。
246
+ - 弹窗增加不透明静态底色再叠加主题色,修复半透明主题下底层文字穿透。
247
+ - 关闭专用模型开关时显示「跟随当前会话模型」和已保存模型提示。
248
+
223
249
  ### 0.4.0
224
250
 
225
251
  合并发布自 0.3.2 之后的所有本地改动:
@@ -272,7 +298,7 @@ Safari 验证结果。
272
298
 
273
299
  - **Phase 1(已完成)**:输入框按钮 + 流式预览 + 选区感知 + 设置页
274
300
  - **Phase 2(进行中)**:快捷键、引用块选区增强、设置持久化、增强专用模型、inline diff、复制/撤销/停止已完成;多 chip 边界测试、i18n/深色/窄屏、客户端自动化测试待做
275
- - **0.1.x**:收紧 React 升级类任务的长度;让 strict 模式在保持简短的同时补上验收信息
301
+ - **0.5.0(本次)**:Pro 自适应提示词、strict 最小但完整、CODE_CHANGE 防漂移、Pro vs Flash 盲评基线
276
302
  - **后续**:规则集切换、A/B、团队词汇表、与提示词库插件联动
277
303
 
278
304
  ## 开发
@@ -292,7 +318,7 @@ node ~/.dsh/skills/dsh-plugin-development/scripts/check-plugin.mjs .
292
318
  npm pack --dry-run --json
293
319
  ```
294
320
 
295
- 当前结构测试 15 项通过:fixtures、规则契约、解析器、校验器、`UNCHANGED`、事实丢失回退、提问回退、占位符/附件回退、完整性提示、工具注册等。
321
+ 当前结构测试 21 项通过:fixtures、规则契约、解析器、校验器、`UNCHANGED`、事实丢失回退、提问回退、占位符/附件回退、完整性提示、Pro 档案、超长重试、单次模型覆盖、工具注册等。
296
322
 
297
323
  ## 许可证
298
324
 
package/client.js CHANGED
@@ -89,6 +89,7 @@ window.__ModuleLoader__.load({
89
89
  'settings.modelLoadError': '模型目录读取失败',
90
90
  'settings.modelPlaceholder': '跟随当前会话模型',
91
91
  'settings.modelChoose': '请选择模型',
92
+ 'settings.savedModel': '已保存:{model}(当前未启用)',
92
93
  }
93
94
 
94
95
  function makeText(t) {
@@ -227,7 +228,8 @@ window.__ModuleLoader__.load({
227
228
  .dsh-prompt-editor-trigger:disabled{opacity:.45;cursor:default}
228
229
  .dsh-prompt-editor-trigger svg{display:block;flex:0 0 auto}
229
230
  .dsh-prompt-editor-overlay{position:fixed;inset:0;z-index:10000;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(0,0,0,.38)}
230
- .dsh-prompt-editor-dialog{display:flex;flex-direction:column;width:min(920px,100%);max-height:min(760px,88vh);overflow:hidden;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);border:1px solid var(--dsw-alias-border-l1);border-radius:14px;box-shadow:0 18px 60px rgba(0,0,0,.28)}
231
+ .dsh-prompt-editor-dialog{display:flex;flex-direction:column;width:min(920px,100%);max-height:min(760px,88vh);overflow:hidden;background-color:var(--dsw-static-neutral-bluish-00,#fff);background-image:linear-gradient(var(--dsw-alias-bg-base),var(--dsw-alias-bg-base));color:var(--dsw-alias-label-primary);border:1px solid var(--dsw-alias-border-l1);border-radius:14px;box-shadow:0 18px 60px rgba(0,0,0,.28)}
232
+ body[data-ds-dark-theme] .dsh-prompt-editor-dialog{background-color:var(--dsw-static-neutral-bluish-950,#16171b)}
231
233
  .dsh-prompt-editor-head{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 16px;border-bottom:1px solid var(--dsw-alias-border-l1)}
232
234
  .dsh-prompt-editor-titleWrap{display:flex;align-items:center;gap:10px;min-width:0}
233
235
  .dsh-prompt-editor-title{font-size:14px;line-height:20px;font-weight:600;color:var(--dsw-alias-label-primary)}
@@ -277,6 +279,7 @@ window.__ModuleLoader__.load({
277
279
  .dsh-prompt-editor-settingsModel{max-width:300px}
278
280
  .dsh-prompt-editor-checkbox{width:16px;height:16px;margin:0;accent-color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#2f6fed);cursor:pointer}
279
281
  .dsh-prompt-editor-toggle{display:inline-flex;align-items:center;gap:7px;color:var(--dsw-alias-label-primary);font-size:12px;cursor:pointer;user-select:none}
282
+ .dsh-prompt-editor-savedModel{margin:0!important;color:var(--dsw-alias-label-secondary)!important;font-size:11px!important}
280
283
  .dsh-prompt-editor-settingsRow{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:12px 14px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1)}
281
284
  .dsh-prompt-editor-settingsCopy{display:flex;flex-direction:column;gap:2px;min-width:0}
282
285
  .dsh-prompt-editor-settingsTitle{color:var(--dsw-alias-label-primary);font-size:13px;line-height:20px;font-weight:500}
@@ -482,7 +485,7 @@ window.__ModuleLoader__.load({
482
485
  : state.error !== null && result === null && enhanced === ''
483
486
  ? h('pre', { className: 'dsh-prompt-editor-pre', tabIndex: 0 }, text('dialog.failed'))
484
487
  : enhanced === '' && stopped
485
- ? h('pre', { className: 'dsh-prompt-editor-pre', tabIndex: 0 }, text('dialog.stopped'))
488
+ ? h('pre', { className: 'dsh-prompt-editor-pre', tabIndex: 0 }, text('dialog.failed'))
486
489
  : h(InlineDiff, { before: state.source, after: enhanced }))
487
490
 
488
491
  const sidePanes = [
@@ -499,7 +502,7 @@ window.__ModuleLoader__.load({
499
502
  : state.error !== null
500
503
  ? text('dialog.failed')
501
504
  : stopped
502
- ? text('dialog.stopped')
505
+ ? text('dialog.failed')
503
506
  : (unchanged ? text('dialog.unchanged') : text('dialog.loading')))),
504
507
  ]
505
508
 
@@ -1057,9 +1060,18 @@ window.__ModuleLoader__.load({
1057
1060
 
1058
1061
  const mode = values?.defaultMode ?? 'intent-first'
1059
1062
  const useCustomModel = values?.useCustomModel === true
1060
- const modelValue = values?.enhanceProvider && values?.enhanceModel
1063
+ const storedModelValue = values?.enhanceProvider && values?.enhanceModel
1061
1064
  ? `${values.enhanceProvider}\u0000${values.enhanceModel}`
1062
1065
  : ''
1066
+ const modelValue = useCustomModel ? storedModelValue : ''
1067
+ const savedModelName = (() => {
1068
+ if (!values?.enhanceProvider || !values?.enhanceModel) return ''
1069
+ const group = catalog.groups.find((item) => item.id === values.enhanceProvider)
1070
+ const found = group?.models.find((item) => item.id === values.enhanceModel)
1071
+ return found !== undefined
1072
+ ? `${group.label} / ${found.name}`
1073
+ : `${values.enhanceProvider} / ${values.enhanceModel}`
1074
+ })()
1063
1075
  const modelOptions = [
1064
1076
  h('option', { key: '', value: '' }, catalog.status === 'loading'
1065
1077
  ? text('settings.modelLoading')
@@ -1104,7 +1116,10 @@ window.__ModuleLoader__.load({
1104
1116
  disabled: saving || values === null,
1105
1117
  onChange: (event) => save({ useCustomModel: event.target.checked }),
1106
1118
  }),
1107
- text('settings.useCustomModel'))),
1119
+ text('settings.useCustomModel')),
1120
+ !useCustomModel && savedModelName !== ''
1121
+ ? h('p', { className: 'dsh-prompt-editor-savedModel' }, text('settings.savedModel', { model: savedModelName }))
1122
+ : null),
1108
1123
  h('div', { className: 'dsh-prompt-editor-settingsControl' },
1109
1124
  h('select', {
1110
1125
  className: 'dsh-prompt-editor-select dsh-prompt-editor-settingsModel',
package/index.js CHANGED
@@ -22,6 +22,38 @@ export const Config = Schema.object({
22
22
  llmTimeoutMs: Schema.number().default(120000),
23
23
  maxLengthRatio: Schema.number().default(5.5),
24
24
  maxPromptChars: Schema.number().default(3000),
25
+ /**
26
+ * Optional per-model overrides, keyed by `provider/model`. Ordinary config:
27
+ * edit the profile patch and restart; settings-page preferences stay volatile.
28
+ */
29
+ modelProfiles: Schema.dict(Schema.object({
30
+ temperature: Schema.number().default(0.2),
31
+ maxTokens: Schema.number().default(0),
32
+ maxLengthRatio: Schema.number().default(4),
33
+ maxPromptChars: Schema.number().default(1800),
34
+ promptVariant: Schema.string().default('auto'),
35
+ retryOnLength: Schema.boolean().default(true),
36
+ reasoningEffort: Schema.string().default(''),
37
+ })).default({}),
38
+ })
39
+
40
+ /**
41
+ * A shipped profile for the Pro route. It is deliberately conservative: the
42
+ * normal intent-first prompt over-expands on this model, so use the concise
43
+ * variant and retry once if the result is still too long.
44
+ */
45
+ const BUILTIN_MODEL_PROFILES = Object.freeze({
46
+ 'deepseek-official/deepseek-v4-pro': Object.freeze({
47
+ temperature: 0.12,
48
+ // 0 means "use the provider default": Pro spends part of this budget on
49
+ // reasoning, so a small cap can end the stream before any text arrives.
50
+ maxTokens: 0,
51
+ maxLengthRatio: 4,
52
+ maxPromptChars: 1800,
53
+ promptVariant: 'auto',
54
+ retryOnLength: true,
55
+ reasoningEffort: '',
56
+ }),
25
57
  })
26
58
 
27
59
  /**
@@ -78,6 +110,14 @@ export function apply(ctx, config) {
78
110
  type: 'string',
79
111
  description: 'Optional file whose contents are used as context.',
80
112
  },
113
+ provider: {
114
+ type: 'string',
115
+ description: 'Advanced: provider override for this call only. Requires model; omit to use the configured enhancement model.',
116
+ },
117
+ model: {
118
+ type: 'string',
119
+ description: 'Advanced: model override for this call only. Requires provider; used for model comparisons and diagnostics.',
120
+ },
81
121
  },
82
122
  output: {
83
123
  schema: {
@@ -120,6 +160,8 @@ export function apply(ctx, config) {
120
160
  mode: args.mode,
121
161
  language: args.language,
122
162
  context: [args.context, contextPathText].filter((part) => typeof part === 'string' && part.trim() !== '').join('\n\n'),
163
+ provider: args.provider,
164
+ model: args.model,
123
165
  signal: exec.signal,
124
166
  })
125
167
  },
@@ -189,15 +231,65 @@ function readSettings(ctx, config) {
189
231
  }
190
232
  }
191
233
 
234
+ /**
235
+ * A rough complexity classifier. Complex drafts get the balanced prompt;
236
+ * short/simple drafts keep the concise one. This is deterministic and local,
237
+ * so it costs no extra model call.
238
+ * @param {string} draft
239
+ * @param {string | undefined} context
240
+ */
241
+ export function isComplexDraft(draft, context) {
242
+ if (typeof context === 'string' && context.trim() !== '') return true
243
+ const text = String(draft)
244
+ const high = /(重构|拆|迁移|升级|并发|监控|告警|鉴权|权限|性能|安全|接口|导出|批量|多步|工作流|重试|超时|日志|脱敏|打码)/i.test(text)
245
+ const code = /```|src\/|\.(?:ts|tsx|js|jsx|json|yaml|yml)|https?:\/\/|npm |package\.json/i.test(text)
246
+ const constraints = /(不要|只改|保持|不得|必须|至少|最多|以内|超过|兼容|回归|测试)/i.test(text)
247
+ const clauses = (text.match(/[,,;;。]/g) ?? []).length >= 2
248
+ let score = 0
249
+ if (text.trim().length >= 120) score += 1
250
+ if (high) score += 1
251
+ if (code) score += 1
252
+ if (constraints) score += 1
253
+ if (clauses) score += 1
254
+ return high || code || text.trim().length >= 120 || score >= 2
255
+ }
256
+
257
+ function promptVariantFor(profile, draft, context) {
258
+ if (profile === null || profile === undefined) return undefined
259
+ if (profile.promptVariant === 'concise' || profile.promptVariant === 'balanced' || profile.promptVariant === 'normal') {
260
+ return profile.promptVariant
261
+ }
262
+ if (profile.promptVariant !== 'auto') return undefined
263
+ return isComplexDraft(draft, context) ? 'balanced' : 'concise'
264
+ }
265
+
192
266
  function liveDefaultMode(ctx, config) {
193
267
  return readSettings(ctx, config).defaultMode
194
268
  }
195
269
 
196
270
  /**
197
- * A custom enhancement model applies only when the switch is on and a full
198
- * provider/model pair is stored; otherwise the session default is used.
271
+ * Resolve the optional profile for the currently selected custom model.
272
+ * @param {any} ctx
273
+ * @param {any} config
274
+ */
275
+ function resolveModelProfile(config, selection) {
276
+ if (selection?.provider === undefined || selection?.model === undefined) return null
277
+ const key = `${selection.provider}/${selection.model}`
278
+ const configured = config.modelProfiles?.[key]
279
+ const builtin = BUILTIN_MODEL_PROFILES[key]
280
+ if (configured === undefined && builtin === undefined) return null
281
+ return { ...builtin, ...configured, key }
282
+ }
283
+
284
+ /**
285
+ * A per-call override wins; otherwise the stored custom model applies when the
286
+ * switch is on; otherwise the session default is used.
199
287
  */
200
- function resolveModelSelection(ctx, config) {
288
+ function resolveModelSelection(ctx, config, override) {
289
+ if (override?.provider !== undefined && override.provider !== ''
290
+ && override?.model !== undefined && override.model !== '') {
291
+ return { provider: override.provider, model: override.model }
292
+ }
201
293
  const settings = readSettings(ctx, config)
202
294
  if (settings.useCustomModel && settings.enhanceProvider !== '' && settings.enhanceModel !== '') {
203
295
  return { provider: settings.enhanceProvider, model: settings.enhanceModel }
@@ -361,22 +453,36 @@ async function handleEnhanceRoute(ctx, config, request) {
361
453
 
362
454
  /**
363
455
  * Enhance a draft end to end.
364
- * @param {{ ctx: any, config: any, draft: string, mode?: string, language?: string, context?: string, signal?: AbortSignal, onDelta?: (text: string) => void, onReset?: () => void }} request
456
+ * @param {{ ctx: any, config: any, draft: string, mode?: string, language?: string, context?: string, provider?: string, model?: string, signal?: AbortSignal, onDelta?: (text: string) => void, onReset?: () => void }} request
365
457
  */
366
458
  export async function enhance(request) {
367
459
  const { ctx, config, signal, onDelta, onReset } = request
368
460
  const draft = normalizeDraft(request.draft, config.maxDraftChars)
369
- const mode = resolveMode(request.mode ?? liveDefaultMode(ctx, config))
461
+ const selection = resolveModelSelection(ctx, config, {
462
+ provider: request.provider,
463
+ model: request.model,
464
+ })
465
+ const profile = resolveModelProfile(config, selection)
466
+ const variant = promptVariantFor(profile, draft, request.context)
467
+ const mode = resolveMode(request.mode ?? liveDefaultMode(ctx, config), variant)
370
468
  const language = normalizeLanguage(request.language)
371
469
  const context = (request.context ?? '').trim().slice(0, config.maxContextChars)
372
- const baseUser = buildUserMessage({ draft, context, language }) + completenessHint(draft)
470
+ const kindHint = taskKindHint(draft)
471
+ const codeTask = isCodeChangeDraft(draft)
472
+ const effectiveMode = codeTask
473
+ ? {
474
+ ...mode,
475
+ system: `${mode.system}\n\n<task_kind>CODE_CHANGE</task_kind>\nThis draft is a code/config change to logging or telemetry, not a request to process a supplied sample. Do not ask for logs; do not output a redacted sample. Rewrite it as an instruction to modify the producer code.${isRedactionDraft(draft) ? ' The rewritten prompt must require a fixed placeholder, preserve field names and log structure, cover every log level and output path, and define acceptance as no plaintext values of the named sensitive fields while request id remains.' : ''}`,
476
+ }
477
+ : mode
478
+ const baseUser = (kindHint === '' ? '' : `${kindHint}\n\n`) + buildUserMessage({ draft, context, language }) + completenessHint(draft)
373
479
 
374
480
  let userMessage = baseUser
375
481
  let lastWarnings = []
376
482
 
377
483
  for (let attempt = 0; attempt < 2; attempt += 1) {
378
484
  if (attempt > 0) onReset?.()
379
- const raw = await callModel({ ctx, config, mode, userMessage, signal, onDelta })
485
+ const raw = await callModel({ ctx, config, mode: effectiveMode, profile, selection, userMessage, signal, onDelta })
380
486
  const parsed = parseModelOutput(raw)
381
487
 
382
488
  if (parsed.kind === 'unchanged') {
@@ -390,12 +496,16 @@ export async function enhance(request) {
390
496
  mode: mode.id,
391
497
  tagged: parsed.tagged,
392
498
  language,
393
- maxLengthRatio: config.maxLengthRatio,
394
- maxPromptChars: config.maxPromptChars,
499
+ maxLengthRatio: profile?.maxLengthRatio ?? config.maxLengthRatio,
500
+ maxPromptChars: profile?.maxPromptChars ?? config.maxPromptChars,
395
501
  })
396
502
  const hard = warnings.filter(isHardWarning)
503
+ const lengthWarnings = profile?.retryOnLength === true
504
+ ? warnings.filter((warning) => warning.startsWith('too_long'))
505
+ : []
506
+ const retryWarnings = [...hard, ...lengthWarnings]
397
507
 
398
- if (hard.length === 0) {
508
+ if (retryWarnings.length === 0) {
399
509
  return {
400
510
  prompt: parsed.prompt,
401
511
  changed: parsed.prompt.trim() !== draft.trim(),
@@ -406,6 +516,17 @@ export async function enhance(request) {
406
516
  }
407
517
 
408
518
  if (attempt === 1) {
519
+ // A still-too-long result is usable; preserve it with the warning rather
520
+ // than discarding a valid rewrite. Hard semantic failures still fallback.
521
+ if (hard.length === 0) {
522
+ return {
523
+ prompt: parsed.prompt,
524
+ changed: parsed.prompt.trim() !== draft.trim(),
525
+ mode: mode.id,
526
+ warnings,
527
+ status: parsed.prompt.trim() !== draft.trim() ? 'changed' : 'unchanged',
528
+ }
529
+ }
409
530
  return {
410
531
  prompt: draft,
411
532
  changed: false,
@@ -416,7 +537,7 @@ export async function enhance(request) {
416
537
  }
417
538
 
418
539
  lastWarnings = warnings
419
- userMessage = withCorrection(baseUser, warnings, parsed.prompt)
540
+ userMessage = withCorrection(baseUser, retryWarnings, parsed.prompt)
420
541
  continue
421
542
  }
422
543
 
@@ -433,8 +554,8 @@ export async function enhance(request) {
433
554
  * @param {{ ctx: any, config: any, mode: any, userMessage: string, signal?: AbortSignal, onDelta?: (text: string) => void }} request
434
555
  */
435
556
  async function callModel(request) {
436
- const { ctx, config, mode, userMessage, signal, onDelta } = request
437
- const selection = resolveModelSelection(ctx, config)
557
+ const { ctx, config, mode, profile, userMessage, signal, onDelta } = request
558
+ const selection = request.selection ?? resolveModelSelection(ctx, config)
438
559
  if (selection?.provider === undefined || selection?.model === undefined) {
439
560
  throw new Error('no default model selection is available')
440
561
  }
@@ -443,7 +564,7 @@ async function callModel(request) {
443
564
  const timeout = AbortSignal.timeout(config.llmTimeoutMs)
444
565
  const llmSignal = signal === undefined ? timeout : AbortSignal.any([signal, timeout])
445
566
 
446
- for await (const chunk of ctx.llm.stream({
567
+ const options = {
447
568
  provider: selection.provider,
448
569
  model: selection.model,
449
570
  sessionId: 'dsh-prompt-editor',
@@ -452,9 +573,15 @@ async function callModel(request) {
452
573
  content: [{ type: 'text', text: userMessage }],
453
574
  source: { kind: 'user' },
454
575
  })],
455
- temperature: mode.temperature,
576
+ temperature: profile?.temperature ?? mode.temperature,
456
577
  signal: llmSignal,
457
- })) {
578
+ }
579
+ if (typeof profile?.maxTokens === 'number' && profile.maxTokens > 0) options.maxTokens = profile.maxTokens
580
+ if (typeof profile?.reasoningEffort === 'string' && profile.reasoningEffort !== '') {
581
+ options.reasoningEffort = profile.reasoningEffort
582
+ }
583
+
584
+ for await (const chunk of ctx.llm.stream(options)) {
458
585
  assembler.push(chunk)
459
586
  if (chunk.type === 'text-delta' && typeof chunk.text === 'string' && onDelta !== undefined) {
460
587
  onDelta(chunk.text)
@@ -533,6 +660,7 @@ export function validatePrompt(input) {
533
660
 
534
661
  const lost = lostFacts(draft, prompt)
535
662
  if (lost.length > 0) warnings.push(`lost_facts: ${lost.join(', ')}`)
663
+ if (isCodeChangeDraft(draft) && isSampleProcessing(prompt)) warnings.push('wrong_task_kind')
536
664
 
537
665
  if (!tagged) warnings.push('missing_tags')
538
666
 
@@ -563,6 +691,7 @@ function isHardWarning(warning) {
563
691
  return warning.startsWith('refusal') ||
564
692
  warning.startsWith('asks_user') ||
565
693
  warning.startsWith('lost_facts') ||
694
+ warning.startsWith('wrong_task_kind') ||
566
695
  warning.startsWith('placeholder') ||
567
696
  warning.startsWith('empty_output')
568
697
  }
@@ -582,6 +711,12 @@ function withCorrection(baseUser, warnings, previous) {
582
711
  'Your previous answer was rejected because:',
583
712
  reasons,
584
713
  'Rewrite the draft again. Preserve all facts verbatim, do not ask the user anything, and follow the output contract exactly.',
714
+ ...(warnings.some((warning) => warning.startsWith('too_long'))
715
+ ? ['The previous answer was too long. Compress it and remove any section, example, or acceptance criterion the draft did not ask for.']
716
+ : []),
717
+ ...(warnings.includes('wrong_task_kind')
718
+ ? ['This draft is a code/config change. Do not process a supplied log or data sample; rewrite it as an instruction to change the code that produces them.']
719
+ : []),
585
720
  `The rejected answer began with: ${String(previous).slice(0, 500)}`,
586
721
  '</correction>',
587
722
  ].join('\n')
@@ -604,6 +739,31 @@ function asksUser(text) {
604
739
  return /(?:你|您)(?:希望|想要|需要|是否|要不要|更倾向|倾向于)|(?:需要|要)我(?:来|帮|先)|(?:请|能否|可以)(?:确认|告诉我|选择)|(?:would you like|do you want me|should i|can you confirm|please confirm|let me know which)/i.test(text)
605
740
  }
606
741
 
742
+ /**
743
+ * Keep code-shaped log/data work from being reinterpreted as processing a
744
+ * supplied sample. This is a hint, not a validator; the model still decides.
745
+ * @param {string} draft
746
+ */
747
+ function isCodeChangeDraft(draft) {
748
+ const domain = /(日志|log|数据|data|请求|request)/i.test(draft)
749
+ const mutation = /(字段|field|打码|脱敏|掩码|mask|redact|过滤|filter|格式化|format)/i.test(draft)
750
+ const sample = /(这段|这份|如下|以下|附件|attached|provided|上面的).{0,16}(日志|数据|文本|log|data|text)|\[附件/i.test(draft)
751
+ return domain && mutation && !sample
752
+ }
753
+
754
+ function isRedactionDraft(draft) {
755
+ return isCodeChangeDraft(draft) && /(打码|脱敏|掩码|mask|redact)/i.test(draft)
756
+ }
757
+
758
+ function taskKindHint(draft) {
759
+ if (!isCodeChangeDraft(draft)) return ''
760
+ return '<task_kind_hint>This draft is a CODE CHANGE to logging/telemetry code, not a request to process a supplied sample. Rewrite it as an instruction to modify the code that produces the logs. Do not write "provided logs", do not ask for a log sample, and do not output a redacted log.</task_kind_hint>'
761
+ }
762
+
763
+ function isSampleProcessing(prompt) {
764
+ return /(?:随请求提供的|提供的|这段|这份)(?:日志|数据|文本)|输出(?:脱敏|打码|处理)后的(?:完整)?(?:日志|数据|文本)|处理(?:随请求提供的)?(?:日志|数据|文本)/i.test(prompt)
765
+ }
766
+
607
767
  /**
608
768
  * Suggest UNCHANGED when a long draft already looks like a complete brief.
609
769
  * This is a hint, not a hard rule; the model still decides.
package/locale/en.json CHANGED
@@ -58,7 +58,8 @@
58
58
  "modelLoading": "Loading models…",
59
59
  "modelLoadError": "Could not load the model catalog",
60
60
  "modelPlaceholder": "Follow the session model",
61
- "modelChoose": "Choose a model"
61
+ "modelChoose": "Choose a model",
62
+ "savedModel": "Saved: {model} (currently disabled)"
62
63
  },
63
64
  "undo": {
64
65
  "done": "Replaced",
package/locale/zh.json CHANGED
@@ -58,7 +58,8 @@
58
58
  "modelLoading": "正在读取模型…",
59
59
  "modelLoadError": "模型目录读取失败",
60
60
  "modelPlaceholder": "跟随当前会话模型",
61
- "modelChoose": "请选择模型"
61
+ "modelChoose": "请选择模型",
62
+ "savedModel": "已保存:{model}(当前未启用)"
62
63
  },
63
64
  "undo": {
64
65
  "done": "已替换",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infinity_cheng/dsh-prompt-editor",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Rewrite a rough prompt draft into a clear, executable prompt in DeepSeek Harness: streaming preview, selection-aware replace, and fact-preservation checks.",
5
5
  "icon": "icon.svg",
6
6
  "type": "module",
package/rules.mjs CHANGED
@@ -48,6 +48,8 @@ const INTENT_FIRST = [
48
48
  'If the draft is already precise and self-consistent, or is not a task at all, return UNCHANGED.',
49
49
  '',
50
50
  'If the draft refers to “this text”, “this data”, “this log” or similar, and that content is not present in the supplied context, instruct the executor to use the text/data supplied with the request. Never claim it is present and never invent it.',
51
+ 'If the draft asks to change code or configuration that handles logs, data, or requests, keep it a code-change task; do not reinterpret it as a request to process supplied content.',
52
+ 'If the draft asks to mask, redact, filter, or format fields in logs/data/requests, treat it as a change to the code or pipeline that produces them, not as a request to process a sample. Only process a sample when the draft explicitly names one (这段/这份/附件/如下).',
51
53
  '',
52
54
  'Before returning, check:',
53
55
  '- Could a competent assistant finish the job from this text alone, without a follow-up question?',
@@ -56,20 +58,94 @@ const INTENT_FIRST = [
56
58
  '- Is every sentence task-specific rather than generic prompt advice?',
57
59
  ].join('\n')
58
60
 
61
+ const INTENT_FIRST_CONCISE = [
62
+ 'You are a prompt editor, not an assistant. The user typed a rough draft into a chat box.',
63
+ 'Rewrite it into a clear, executable prompt while staying close to the draft.',
64
+ 'A thin draft may grow to roughly two to four times its length; never exceed four times.',
65
+ '',
66
+ 'Cover only the dimensions the executor cannot infer:',
67
+ '- GOAL: the outcome to produce.',
68
+ '- INPUTS: what to work from, where it lives, and how it is identified.',
69
+ '- OUTPUT: format, length, and language of the deliverable.',
70
+ '- ACCEPTANCE: what makes the result acceptable.',
71
+ 'Omit any dimension the executor can infer. Do not add procedures, checklists, examples, background, or acceptance criteria the draft did not ask for.',
72
+ '',
73
+ 'Preserve every fact the user typed, character for character: names, numbers, ranges, units, dates, paths, URLs, commands, code spans, version numbers, @references and attachment markers.',
74
+ 'Attachment markers such as [附件1: report.md] must be kept exactly as written, including the brackets and the label.',
75
+ 'You may add detail and structure, but you may not translate, reformat, contradict, narrow, or drop what is written.',
76
+ 'Never leave a placeholder such as 【待补】, TODO, TBD, or a blank slot for a human to fill. If a fact is unknown, delegate the decision to the executor in plain words.',
77
+ '',
78
+ 'Write in the same language as the draft, unless the user explicitly requested another language. Address the executing assistant in the imperative.',
79
+ 'Never ask the user a question, never offer a choice, never request confirmation, and never wait for the user.',
80
+ '',
81
+ 'If the draft already states the goal, the inputs, the expected output and an acceptance criterion, return UNCHANGED.',
82
+ 'If the draft is already precise and self-consistent, or is not a task at all, return UNCHANGED.',
83
+ '',
84
+ 'If the draft refers to text/data that is not present, instruct the executor to use what was supplied; never claim it is present.',
85
+ 'If the draft asks to change code or configuration that handles logs, data, or requests, keep it a code-change task; do not reinterpret it as a request to process supplied content.',
86
+ 'If the draft asks to mask, redact, filter, or format fields in logs/data/requests, treat it as a change to the code or pipeline that produces them, not as a request to process a sample. Only process a sample when the draft explicitly names one (这段/这份/附件/如下).',
87
+ '',
88
+ 'Before returning, check:',
89
+ '- Could a competent assistant finish the job from this text alone?',
90
+ '- Are all the user\'s facts preserved exactly?',
91
+ '- Did you add anything the draft did not ask for? If yes, remove it.',
92
+ '- Does the rewrite ask the user anything or wait for confirmation? It must not.',
93
+ ].join('\n')
94
+
95
+ const INTENT_FIRST_BALANCED = [
96
+ 'You are a prompt editor, not an assistant. The user typed a rough draft into a chat box.',
97
+ 'Rewrite it into a clear, executable prompt. Keep the result proportional: a thin draft may grow to two to five times its length, never more.',
98
+ '',
99
+ 'For a complex task (multiple steps, constraints, files, migration, monitoring, or verification), cover the minimum needed for:',
100
+ '- GOAL: the outcome to produce.',
101
+ '- INPUTS: what to work from and how it is identified.',
102
+ '- SCOPE: what is included and the non-goals that would otherwise waste effort.',
103
+ '- METHOD: the steps or constraints that decide how the work gets done.',
104
+ '- OUTPUT: format, length, and language of the deliverable.',
105
+ '- ACCEPTANCE: what makes the result acceptable.',
106
+ 'For a simple task, omit the dimensions the executor can infer.',
107
+ 'Do not add generic checklists, background, examples, or acceptance criteria the draft did not ask for.',
108
+ '',
109
+ 'Preserve every fact the user typed, character for character: names, numbers, ranges, units, dates, paths, URLs, commands, code spans, version numbers, @references and attachment markers.',
110
+ 'Attachment markers such as [附件1: report.md] must be kept exactly as written, including the brackets and the label.',
111
+ 'You may add detail and structure, but you may not translate, reformat, contradict, narrow, or drop what is written.',
112
+ 'Never leave a placeholder such as 【待补】, TODO, TBD, or a blank slot for a human to fill. If a fact is unknown, delegate the decision to the executor in plain words.',
113
+ '',
114
+ 'Write in the same language as the draft, unless the user explicitly requested another language. Address the executing assistant in the imperative.',
115
+ 'Never ask the user a question, never offer a choice, never request confirmation, and never wait for the user.',
116
+ '',
117
+ 'If the draft already states the goal, the inputs, the expected output and an acceptance criterion, return UNCHANGED.',
118
+ 'If the draft is already precise and self-consistent, or is not a task at all, return UNCHANGED.',
119
+ '',
120
+ 'If the draft refers to text/data that is not present, instruct the executor to use what was supplied; never claim it is present.',
121
+ 'If the draft asks to change code or configuration that handles logs, data, or requests, keep it a code-change task; do not reinterpret it as a request to process supplied content.',
122
+ 'If the draft asks to mask, redact, filter, or format fields in logs/data/requests, treat it as a code change to their producer, not as processing a sample.',
123
+ '',
124
+ 'Before returning, check:',
125
+ '- Could a competent assistant finish the job from this text alone?',
126
+ '- Are all the user\'s facts preserved exactly?',
127
+ '- Does the rewrite add anything the draft did not ask for? If yes, remove it.',
128
+ '- Does the rewrite ask the user anything or wait for confirmation? It must not.',
129
+ ].join('\n')
130
+
59
131
  const STRICT = [
60
132
  'You are a prompt editor, not an assistant. The user typed a rough draft into a chat box.',
61
133
  'Make the smallest edit that removes ambiguity or a missing instruction. Keep the user\'s wording, structure, tone, and approximate length.',
62
134
  'Do not add new requirements, sections, examples, context, or best practices. Do not turn a short request into a long brief.',
135
+ 'Minimal does not mean vague. When the draft leaves any of these unclear, the result must state the concrete action, the input or evidence to inspect, and the acceptance condition. Add at most one short clause for each; do not add a plan, checklist, examples, or sections.',
63
136
  'Never answer, execute, evaluate, or discuss the draft itself. Never ask the user anything.',
64
137
  '',
65
138
  'Preserve every fact the user typed, character for character: names, numbers, ranges, units, dates, paths, URLs, commands, code spans, version numbers, @references and attachment markers.',
66
139
  'Attachment markers such as [附件1: report.md] must be kept exactly as written, including the brackets and the label.',
67
140
  'If the draft asks you to rewrite a quoted phrase (for example 把“处理一下这个报错”改清楚), rewrite the quoted phrase into a clear task. Write the clarified task directly; do not open with 把…改写成/这句话/上述说法, and do not describe the act of rewriting.',
68
141
  'If the draft refers to text/data that is not present, instruct the executor to use what was supplied; never claim it is present.',
142
+ 'If the draft asks to change code or configuration that handles logs, data, or requests, keep it a code-change task; do not reinterpret it as a request to process supplied content.',
143
+ 'If the draft asks to mask, redact, filter, or format fields in logs/data/requests, treat it as a code change to their producer, not as processing a sample.',
69
144
  'Never leave a placeholder such as 【待补】, TODO, TBD, or a blank slot for a human to fill.',
70
145
  'Write in the same language as the draft. Address the executing assistant in the imperative.',
71
146
  'Never ask the user a question, offer a choice, request confirmation, or leave a placeholder.',
72
147
  'If the draft is already clear enough to execute, return UNCHANGED. A small clarification is allowed; expansion is not.',
148
+ 'Before returning: would the executor still have to ask what to do or what counts as done? If yes, add the missing clause; if no, return the minimal edit.',
73
149
  ].join('\n')
74
150
 
75
151
  /** Built-in modes. */
@@ -92,8 +168,15 @@ export const MODES = {
92
168
  * Resolve a mode or fall back to intent-first.
93
169
  * @param {string | undefined} id
94
170
  */
95
- export function resolveMode(id) {
96
- return MODES[id] ?? MODES['intent-first']
171
+ export function resolveMode(id, variant) {
172
+ const base = MODES[id] ?? MODES['intent-first']
173
+ if (base.id === 'intent-first' && variant === 'concise') {
174
+ return { ...base, system: `${INTENT_FIRST_CONCISE}\n\n${OUTPUT_CONTRACT}` }
175
+ }
176
+ if (base.id === 'intent-first' && variant === 'balanced') {
177
+ return { ...base, system: `${INTENT_FIRST_BALANCED}\n\n${OUTPUT_CONTRACT}` }
178
+ }
179
+ return base
97
180
  }
98
181
 
99
182
  /**