@surfishs/dsh-prompt-enhance 0.1.2 → 0.1.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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@surfishs/dsh-prompt-enhance",
3
3
  "description": "Prompt enhancement for the dsh web GUI: rewrite the composer draft into a well-structured prompt through the harness LLM service, preview the before/after, then fill back, copy, or undo. Original draft is always preserved.",
4
- "version": "0.1.2",
4
+ "version": "0.1.3",
5
5
  "author": "surfishs",
6
6
  "type": "module",
7
7
  "engines": {
@@ -8,7 +8,7 @@
8
8
 
9
9
  import { useCallback, useRef, useState, type ReactNode } from 'react'
10
10
  import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
11
- import type { EnhanceError, EnhanceUsage, ClientFailureReason } from '../shared/protocol'
11
+ import type { ContextUsage, EnhanceError, EnhanceUsage, ClientFailureReason } from '../shared/protocol'
12
12
  import type { PromptEnhanceKey } from './locales'
13
13
  import type { PanelState } from './ui-state'
14
14
  import { ChevronIcon, CopyIcon, FillIcon, RegenerateIcon, UndoIcon, XIcon } from './ActionIcons'
@@ -177,6 +177,62 @@ function totalTokensOf(usage: EnhanceUsage): number {
177
177
  return usage.totalTokens ?? usage.inputTokens + usage.outputTokens + (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0)
178
178
  }
179
179
 
180
+ /**
181
+ * Footer info button: the call's context usage, on hover/focus (and a tap on
182
+ * touch devices, where there is no hover). The card has no room for this in
183
+ * its header, and the footer keeps the action row intact.
184
+ * @param props - the usage numbers and the locale seat.
185
+ * @returns the info button and its tooltip.
186
+ */
187
+ function ContextUsageInfo(props: { usage?: ContextUsage; t: TranslateNS<'dsh-prompt-enhance'> }): ReactNode {
188
+ const { usage, t } = props
189
+ const [open, setOpen] = useState(false)
190
+ // Reaching the turn cap is the normal shape of the window, not a warning;
191
+ // only a character squeeze or a cut turn needs the amber treatment.
192
+ const limited = usage !== undefined && (usage.cutTurn || usage.limitedBy === 'chars')
193
+ const percent = usage !== undefined && usage.maxChars > 0 ? Math.round((usage.usedChars / usage.maxChars) * 100) : 0
194
+ const stats =
195
+ usage === undefined
196
+ ? t('panel.contextUnused')
197
+ : t('panel.contextStats', {
198
+ turns: usage.usedTurns,
199
+ maxTurns: usage.maxTurns,
200
+ chars: formatTokens(usage.usedChars),
201
+ maxChars: formatTokens(usage.maxChars),
202
+ percent,
203
+ })
204
+ const reason = usage === undefined ? '' : usage.cutTurn ? t('panel.contextCut') : usage.limitedBy === 'chars' ? t('panel.contextCharsLimited') : ''
205
+ return (
206
+ <span className="dsh-pe-context-wrap">
207
+ <button
208
+ type="button"
209
+ className={`dsh-pe-context${limited ? ' is-limited' : ''}`}
210
+ aria-label={t('panel.contextUsage')}
211
+ aria-expanded={open}
212
+ onMouseEnter={() => setOpen(true)}
213
+ onMouseLeave={() => setOpen(false)}
214
+ onFocus={() => setOpen(true)}
215
+ onBlur={() => setOpen(false)}
216
+ onClick={() => setOpen((value) => !value)}
217
+ onKeyDown={(event) => {
218
+ if (event.key === 'Escape') setOpen(false)
219
+ }}
220
+ >
221
+ <svg className="dsh-pe-context-icon" viewBox="0 0 16 16" aria-hidden="true" focusable="false">
222
+ <rect x="2.2" y="3.4" width="11.6" height="9.2" rx="2.2" fill="none" stroke="currentColor" strokeWidth="1.2" />
223
+ <path d="M5.2 6.6h5.6M5.2 9.2h3.8" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" />
224
+ </svg>
225
+ </button>
226
+ {open && (
227
+ <span role="tooltip" className="dsh-pe-context-tip">
228
+ <span className="dsh-pe-context-stats">{stats}</span>
229
+ {reason !== '' && <span className="dsh-pe-context-reason">{reason}</span>}
230
+ </span>
231
+ )}
232
+ </span>
233
+ )
234
+ }
235
+
180
236
  /** One enhancement result card. */
181
237
  export function ResultPanel(props: ResultPanelProps): ReactNode {
182
238
  const { state, t, onApply, onCancel, onRetry, applied = false, onUndo, onRegenerate, regenerated = false, collapsed = false, onToggleCollapsed, foldAnimation = true } = props
@@ -338,6 +394,7 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
338
394
  </div>
339
395
 
340
396
  <footer className="dsh-pe-foot">
397
+ {state.phase === 'result' && <ContextUsageInfo usage={state.result?.context} t={t} />}
341
398
  <span className="dsh-pe-grow" />
342
399
  {state.phase === 'result' && (
343
400
  <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-floor" onClick={onRegenerate} disabled={onRegenerate === undefined}>
@@ -11,6 +11,7 @@ import {
11
11
  type EnhanceError,
12
12
  type EnhanceErrorCode,
13
13
  type EnhanceRequestBody,
14
+ type ContextUsage,
14
15
  type EnhanceResult,
15
16
  type EnhanceStreamEvent,
16
17
  type EnhanceUsage,
@@ -82,6 +83,41 @@ function parseUsage(value: unknown): EnhanceUsage | undefined {
82
83
  }
83
84
 
84
85
  /** Strictly narrow one success value; anything malformed is a client-visible error. */
86
+ /**
87
+ * Validate the optional context-usage block the host sends with a result.
88
+ *
89
+ * The panel relies on the numbers being integers (malformed fractions would
90
+ * format oddly) and on `limitedBy` being one of the two caps; anything else
91
+ * is treated as "no usage" rather than surfacing a broken tooltip.
92
+ * @param value - the untrusted wire value.
93
+ * @returns the usage, or undefined when absent/malformed.
94
+ */
95
+ function parseContextUsage(value: unknown): ContextUsage | undefined {
96
+ const record = value as Partial<ContextUsage> | null
97
+ if (record === null || typeof record !== 'object') return undefined
98
+ const integer = (field: unknown): field is number => typeof field === 'number' && Number.isInteger(field) && field >= 0
99
+ if (
100
+ !integer(record.usedTurns) ||
101
+ !integer(record.maxTurns) ||
102
+ !integer(record.usedChars) ||
103
+ !integer(record.maxChars) ||
104
+ !integer(record.droppedTurns) ||
105
+ (record.limitedBy !== null && record.limitedBy !== 'turns' && record.limitedBy !== 'chars') ||
106
+ typeof record.cutTurn !== 'boolean'
107
+ ) {
108
+ return undefined
109
+ }
110
+ return {
111
+ usedTurns: record.usedTurns,
112
+ maxTurns: record.maxTurns,
113
+ usedChars: record.usedChars,
114
+ maxChars: record.maxChars,
115
+ droppedTurns: record.droppedTurns,
116
+ limitedBy: record.limitedBy,
117
+ cutTurn: record.cutTurn,
118
+ }
119
+ }
120
+
85
121
  function parseResult(value: unknown): EnhanceResult {
86
122
  const record = value as Partial<EnhanceResult> | null
87
123
  if (
@@ -97,6 +133,7 @@ function parseResult(value: unknown): EnhanceResult {
97
133
  Number.isFinite(record.elapsedMs)
98
134
  ) {
99
135
  const usage = parseUsage((record as { usage?: unknown }).usage)
136
+ const context = parseContextUsage((record as { context?: unknown }).context)
100
137
  return {
101
138
  text: record.text,
102
139
  provider: record.provider,
@@ -113,6 +150,7 @@ function parseResult(value: unknown): EnhanceResult {
113
150
  // drops anything not listed here, so a new result field has to be added
114
151
  // in this exact place or the UI silently never sees it.
115
152
  ...(typeof record.reasoningEffort === 'string' ? { reasoningEffort: record.reasoningEffort } : {}),
153
+ ...(context === undefined ? {} : { context }),
116
154
  }
117
155
  }
118
156
  throw new EnhanceClientError({ code: 'internal', params: { reason: 'malformed' } })
@@ -18,7 +18,7 @@ export const zh = {
18
18
  'menu.effortsNone': '该模型未声明推理档位',
19
19
  'menu.effortsFailed': '无法读取该模型的档位',
20
20
  'menu.effort': '推理等级',
21
- 'menu.effortDefault': '不指定',
21
+ 'menu.effortDefault': '模型默认',
22
22
  'menu.context': '上下文感知',
23
23
  'menu.contextOn': '开',
24
24
  'menu.contextOff': '关',
@@ -42,10 +42,15 @@ export const zh = {
42
42
  'panel.retry': '重试',
43
43
  'panel.stale.warn': '草稿已改动,当前结果基于旧文本。「重新生成」会按当前文本重跑;回填仍会覆盖当前输入(可撤销)。',
44
44
  'panel.truncated': '输出被截断(达到输出上限),结果可能不完整。可在设置里调高「输出 token 上限」后重新生成。',
45
+ 'panel.contextUsage': '上下文用量',
46
+ 'panel.contextStats': '上下文 {turns}/{maxTurns} 条 · {chars}/{maxChars} 字({percent}%)',
47
+ 'panel.contextCharsLimited': '已达字数上限,较早内容未发送',
48
+ 'panel.contextCut': '已达字数上限,最新一条仅发送了开头',
49
+ 'panel.contextUnused': '本次未使用上下文',
45
50
  'panel.model': '模型:{provider} / {model}',
46
51
  'panel.elapsed': '耗时 {ms}',
47
52
  'panel.tokens': '{total} tokens',
48
- 'panel.effortDefault': '不指定',
53
+ 'panel.effortDefault': '模型默认',
49
54
  'panel.tokens.input': '输入 {count}',
50
55
  'panel.tokens.output': '输出 {count}',
51
56
  'panel.tokens.cacheRead': '缓存读取 {count}',
@@ -62,7 +67,7 @@ export const zh = {
62
67
  'error.rejected': '增强请求被拒绝。请稍后重试;若持续出现,请检查插件设置。',
63
68
  'error.timeout': '增强超时({seconds} 秒)。可直接重试,或到设置里调高「超时(毫秒)」;原输入未改动。',
64
69
  'error.unconfigured': '还没确定用哪个模型:请在插件设置里填写 provider 和 model(两项都要填),或在当前会话先发一条消息以跟随会话模型。',
65
- 'error.effortUnsupported': '该模型不支持所选推理档位「{effort}」,请改选其它档位,或改用「不指定」。',
70
+ 'error.effortUnsupported': '该模型不支持所选推理档位「{effort}」,请改选其它档位,或改用「模型默认」。',
66
71
  'error.upstream': '模型服务返回错误;若下方有详情,请按详情处理,否则可直接重试。原输入未改动。',
67
72
  'error.internal': '增强失败,请重试;若反复失败,请查看 dsh 运行日志。原输入未改动。',
68
73
  'error.client.unreachable': '无法连接宿主服务,请确认 dsh web 正在运行后重试。',
@@ -136,7 +141,7 @@ export const zh = {
136
141
  'settings.row.temperature.label': '温度',
137
142
  'settings.row.temperature.hint': '采样温度(0~1,步进 0.05),越低越忠实原文;默认 0.3。',
138
143
  'settings.row.reasoningEffort.label': '推理预算',
139
- 'settings.row.reasoningEffort.hint': '档位选项来自当前 provider/model 的声明;自定义模型时按需读取。「不指定」表示不传该字段。',
144
+ 'settings.row.reasoningEffort.hint': '档位选项来自当前 provider/model 的声明;自定义模型时按需读取。「模型默认」表示不发送该字段,由提供方使用默认档。',
140
145
  'settings.row.maxOutputTokens.label': '输出 token 上限',
141
146
  'settings.row.maxOutputTokens.hint': '单次增强的输出预算;默认 8192。',
142
147
  'settings.row.maxInputChars.label': '输入字符上限',
@@ -161,7 +166,7 @@ export const zh = {
161
166
  'settings.row.shortcut.placeholder': '例:ctrl+alt+shift+e',
162
167
  'settings.strategy.replace': '替换内置策略',
163
168
  'settings.strategy.extend': '追加在内置策略后',
164
- 'settings.reasoning.inherit': '不指定',
169
+ 'settings.reasoning.inherit': '模型默认',
165
170
  'settings.reasoning.loading': '正在读取该模型的档位…',
166
171
  'settings.reasoning.unavailable': '无法读取该模型的档位列表;已保存的档位仍会照常发送。',
167
172
  'settings.reasoning.noTiers': '该模型未声明推理档位;调用时不发送档位,由提供方决定。',
@@ -191,7 +196,7 @@ export const en: Record<PromptEnhanceKey, string> = {
191
196
  'menu.effortsNone': 'This model declares no reasoning tiers',
192
197
  'menu.effortsFailed': 'Could not read this model tiers',
193
198
  'menu.effort': 'Reasoning effort',
194
- 'menu.effortDefault': 'Not specified',
199
+ 'menu.effortDefault': 'Model default',
195
200
  'menu.context': 'Context awareness',
196
201
  'menu.contextOn': 'on',
197
202
  'menu.contextOff': 'off',
@@ -215,10 +220,15 @@ export const en: Record<PromptEnhanceKey, string> = {
215
220
  'panel.retry': 'Retry',
216
221
  'panel.stale.warn': 'Draft changed — this result uses the earlier text. Regenerate re-runs on the current draft; Apply still overwrites the input (undoable).',
217
222
  'panel.truncated': 'Output was cut at the output limit, so the result may be incomplete. Raise "Output token budget" in the settings, then regenerate.',
223
+ 'panel.contextUsage': 'Context usage',
224
+ 'panel.contextStats': 'Context {turns}/{maxTurns} turns · {chars}/{maxChars} chars ({percent}%)',
225
+ 'panel.contextCharsLimited': 'Character cap reached; earlier turns were not sent',
226
+ 'panel.contextCut': 'Character limit reached; only the opening of the latest turn was sent',
227
+ 'panel.contextUnused': 'No conversation context was used for this call',
218
228
  'panel.model': 'Model: {provider} / {model}',
219
229
  'panel.elapsed': '{ms} elapsed',
220
230
  'panel.tokens': '{total} tokens',
221
- 'panel.effortDefault': 'Not specified',
231
+ 'panel.effortDefault': 'Model default',
222
232
  'panel.tokens.input': 'Input {count}',
223
233
  'panel.tokens.output': 'Output {count}',
224
234
  'panel.tokens.cacheRead': 'Cache read {count}',
@@ -236,7 +246,7 @@ export const en: Record<PromptEnhanceKey, string> = {
236
246
  'error.timeout': 'The enhancement timed out ({seconds}s). Retry, or raise "Timeout (ms)" in the settings; your draft is untouched.',
237
247
  'error.unconfigured':
238
248
  'No model is configured for the enhancement: fill in both provider and model in the plugin settings, or send a message in the current session first to follow the session model.',
239
- 'error.effortUnsupported': 'This model does not support the selected reasoning effort "{effort}". Choose another tier, or use "Not specified".',
249
+ 'error.effortUnsupported': 'This model does not support the selected reasoning effort "{effort}". Choose another tier, or use "Model default".',
240
250
  'error.upstream': 'The model provider returned an error. If there is detail below, act on it; otherwise retry. Your draft is untouched.',
241
251
  'error.internal': 'Enhancement failed. Retry; if it keeps failing, check the dsh logs. Your draft is untouched.',
242
252
  'error.client.unreachable': 'Cannot reach the host service — make sure dsh web is running, then retry.',
@@ -312,7 +322,8 @@ export const en: Record<PromptEnhanceKey, string> = {
312
322
  'settings.row.temperature.label': 'Temperature',
313
323
  'settings.row.temperature.hint': 'Sampling temperature (0–1, step 0.05); lower stays closer to the original. Default 0.3.',
314
324
  'settings.row.reasoningEffort.label': 'Reasoning effort',
315
- 'settings.row.reasoningEffort.hint': 'Tier choices come from what the configured provider/model declares; custom models are read on demand. "Not specified" omits the field.',
325
+ 'settings.row.reasoningEffort.hint':
326
+ 'Tier choices come from what the configured provider/model declares; custom models are read on demand. "Model default" means the field is omitted and the provider applies its default.',
316
327
  'settings.row.maxOutputTokens.label': 'Output token budget',
317
328
  'settings.row.maxOutputTokens.hint': 'Output budget for one enhancement call. Default 8192.',
318
329
  'settings.row.maxInputChars.label': 'Input character cap',
@@ -338,7 +349,7 @@ export const en: Record<PromptEnhanceKey, string> = {
338
349
  'settings.row.shortcut.placeholder': 'e.g. ctrl+alt+shift+e',
339
350
  'settings.strategy.replace': 'Replace the built-in strategy',
340
351
  'settings.strategy.extend': 'Append after the built-in strategy',
341
- 'settings.reasoning.inherit': 'Not specified',
352
+ 'settings.reasoning.inherit': 'Model default',
342
353
  'settings.reasoning.loading': 'Reading this model’s tiers…',
343
354
  'settings.reasoning.unavailable': 'Could not read this model’s tier list; your saved tier is still sent.',
344
355
  'settings.reasoning.noTiers': 'This model declares no reasoning tiers; calls omit the field and let the provider decide.',
@@ -185,7 +185,7 @@ export function ReasoningRow(props: RowProps & { provider: string; model: string
185
185
  }, [cacheKey, pair, refreshToken])
186
186
 
187
187
  // Every provider — DeepSeek included — shows the adapter's own tier names;
188
- // only the "not specified" sentinel is plugin copy. It leads the control: the
188
+ // only the "model default" sentinel is plugin copy. It leads the control: the
189
189
  // stored value can point at it, and it must not trail the concrete tiers.
190
190
  const current = props.view.text
191
191
  const realTierKnown = phase === 'ready' && capabilities !== undefined && capabilities.source !== 'unavailable' && capabilities.efforts.some((effort) => effort.id === current)
@@ -429,6 +429,112 @@ html[data-platform='darwin'] .dsh-pe-menu {
429
429
  border-top: 1px solid var(--pe-separator);
430
430
  }
431
431
  .dsh-pe-foot .dsh-pe-grow { flex: 1; }
432
+
433
+ /* The context-usage button sits at the quiet end of the footer, opposite the
434
+ actions. Its tooltip opens upward into the card body, so no portal is needed
435
+ and the card's own overflow clipping stays out of the way. */
436
+ .dsh-pe-context-wrap {
437
+ position: relative;
438
+ display: inline-flex;
439
+ }
440
+ .dsh-pe-context {
441
+ box-sizing: border-box;
442
+ display: inline-flex;
443
+ flex: none;
444
+ align-items: center;
445
+ justify-content: center;
446
+ width: 28px;
447
+ height: 28px;
448
+ padding: 0;
449
+ border: 0;
450
+ border-radius: 8px;
451
+ background: transparent;
452
+ /* The glyph carries the state on its own: grey when the window is healthy,
453
+ amber when it had to cut something. The precise counts stay in the
454
+ tooltip. */
455
+ --pe-context-accent: var(--dsw-alias-label-tertiary, #8a8a8a);
456
+ color: var(--pe-context-accent);
457
+ cursor: default;
458
+ }
459
+ .dsh-pe-context:hover { background: var(--pe-hover); }
460
+ .dsh-pe-context.is-limited {
461
+ --pe-context-accent: #b45309;
462
+ color: var(--pe-context-accent);
463
+ }
464
+ /* The warning lives in the glyph alone by default; the amber tint appears on
465
+ hover or keyboard focus, matching the plain state's on-demand background. */
466
+ .dsh-pe-context.is-limited:hover,
467
+ .dsh-pe-context.is-limited:focus-visible {
468
+ background: rgba(180, 83, 9, 0.1);
469
+ }
470
+ .dsh-pe-context-icon {
471
+ position: relative;
472
+ z-index: 1;
473
+ display: block;
474
+ width: 20px;
475
+ height: 20px;
476
+ color: var(--pe-context-accent);
477
+ }
478
+ .dsh-pe-context-tip {
479
+ position: absolute;
480
+ left: 0;
481
+ bottom: calc(100% + 8px);
482
+ z-index: 5;
483
+ display: flex;
484
+ flex-direction: column;
485
+ gap: 2px;
486
+ box-sizing: border-box;
487
+ width: max-content;
488
+ max-width: min(340px, calc(100vw - 40px));
489
+ padding: 6px 10px;
490
+ border-radius: var(--dsw-radius-sm, 6px);
491
+ background: var(--dsw-alias-tooltip-bg, #2f2f2f);
492
+ color: var(--dsw-alias-tooltip-label, #ffffff);
493
+ font-size: 13px;
494
+ line-height: 20px;
495
+ font-variant-numeric: tabular-nums;
496
+ white-space: normal;
497
+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.18);
498
+ pointer-events: none;
499
+ animation: dsh-pe-context-tip-in 140ms ease-out;
500
+ }
501
+ /* The bubble needs an anchor: it floats above the icon and would otherwise
502
+ read as disconnected from the footer. */
503
+ .dsh-pe-context-tip::after {
504
+ content: '';
505
+ position: absolute;
506
+ left: 12px;
507
+ bottom: -5px;
508
+ width: 0;
509
+ height: 0;
510
+ border-left: 5px solid transparent;
511
+ border-right: 5px solid transparent;
512
+ border-top: 5px solid var(--dsw-alias-tooltip-bg, #2f2f2f);
513
+ }
514
+ @keyframes dsh-pe-context-tip-in {
515
+ from {
516
+ opacity: 0;
517
+ transform: translateY(2px);
518
+ }
519
+ }
520
+ @media (prefers-reduced-motion: reduce) {
521
+ .dsh-pe-context-tip { animation: none; }
522
+ }
523
+ /* The stats line is one unit: a wrap that leaves the percentage alone reads
524
+ as a layout bug. The reason line may wrap freely. */
525
+ .dsh-pe-context-tip .dsh-pe-context-stats { white-space: nowrap; }
526
+ .dsh-pe-context-tip .dsh-pe-context-reason { color: #f2c185; }
527
+ /* Narrow viewports: the card itself is close to the viewport width, so the
528
+ fixed tooltip width would clip. Give it a viewport-relative cap and let the
529
+ stats line wrap instead of overflowing. */
530
+ @media (max-width: 560px) {
531
+ .dsh-pe-context-tip {
532
+ min-width: 0;
533
+ width: 230px;
534
+ max-width: calc(100vw - 40px);
535
+ }
536
+ .dsh-pe-context-tip .dsh-pe-context-stats { white-space: normal; }
537
+ }
432
538
  .dsh-pe-btn-action {
433
539
  box-sizing: border-box;
434
540
  display: inline-flex;
package/src/context.ts CHANGED
@@ -14,6 +14,7 @@
14
14
  */
15
15
 
16
16
  import { countText } from './shared/validate'
17
+ import type { ContextUsage } from './shared/protocol'
17
18
 
18
19
  /** One turn of conversation history admitted into the context window. */
19
20
  export interface ContextTurn {
@@ -35,6 +36,25 @@ export interface ContextWindowOptions {
35
36
  interface HistoryMessageLike {
36
37
  role?: unknown
37
38
  content?: unknown
39
+ source?: unknown
40
+ }
41
+
42
+ /**
43
+ * Whether a user-role message was injected by the harness rather than typed
44
+ * by the user. DSH represents environment, skill and time context as
45
+ * `user/message` events whose `source.kind` is not `user` (e.g.
46
+ * `runtime-context`, `skill-catalog`, `time-context`); they are visible to the
47
+ * model but not to the user, so they must not spend the conversation-context
48
+ * budget or show up as "your recent turns".
49
+ * @param message - one derived history message (untrusted).
50
+ * @returns true for non-user producer kinds; false when the source is absent
51
+ * (older hosts) or is the user's own message.
52
+ */
53
+ function isInjectedUserContext(message: HistoryMessageLike): boolean {
54
+ const source = message.source
55
+ if (source === null || typeof source !== 'object') return false
56
+ const kind = (source as { kind?: unknown }).kind
57
+ return typeof kind === 'string' && kind !== 'user'
38
58
  }
39
59
 
40
60
  /** Marker appended to a turn that was cut to fit the character budget. */
@@ -82,6 +102,14 @@ function turnTextOf(message: HistoryMessageLike): string {
82
102
  return parts.join('\n')
83
103
  }
84
104
 
105
+ /** One selection plus the usage numbers the result card reports. */
106
+ export interface ContextSelection {
107
+ /** Admitted turns, chronological. */
108
+ turns: ContextTurn[]
109
+ /** How much of the configured window was used, and why it stopped. */
110
+ usage: ContextUsage
111
+ }
112
+
85
113
  /**
86
114
  * Pick the turns that fit the configured window, newest last.
87
115
  *
@@ -95,15 +123,34 @@ function turnTextOf(message: HistoryMessageLike): string {
95
123
  * @returns the admitted turns in chronological order; empty when none fit.
96
124
  */
97
125
  export function selectTurns(messages: readonly unknown[], options: ContextWindowOptions, draft?: string): ContextTurn[] {
126
+ return selectTurnsWithUsage(messages, options, draft).turns
127
+ }
128
+
129
+ /**
130
+ * The same selection as {@link selectTurns}, plus what the result card shows.
131
+ *
132
+ * `usedChars` counts the admitted turn text only — the same gauge the budget
133
+ * spends — so the reported fraction always matches the configured cap.
134
+ * @param messages - the session's derived history (untrusted).
135
+ * @param options - the configured window.
136
+ * @param draft - the raw draft being enhanced.
137
+ * @returns the admitted turns and their usage.
138
+ */
139
+ export function selectTurnsWithUsage(messages: readonly unknown[], options: ContextWindowOptions, draft?: string): ContextSelection {
98
140
  const maxMessages = Number.isInteger(options.maxMessages) ? Math.max(0, options.maxMessages) : 0
99
141
  const maxChars = Number.isInteger(options.maxChars) ? Math.max(0, options.maxChars) : 0
100
- if (maxMessages === 0 || maxChars === 0) return []
142
+ const empty = (): ContextSelection => ({
143
+ turns: [],
144
+ usage: { usedTurns: 0, maxTurns: maxMessages, usedChars: 0, maxChars, droppedTurns: 0, limitedBy: null, cutTurn: false },
145
+ })
146
+ if (maxMessages === 0 || maxChars === 0) return empty()
101
147
 
102
148
  const turns: ContextTurn[] = []
103
149
  for (const message of messages) {
104
150
  if (message === null || typeof message !== 'object') continue
105
151
  const record = message as HistoryMessageLike
106
152
  if (record.role !== 'user' && record.role !== 'assistant') continue
153
+ if (record.role === 'user' && isInjectedUserContext(record)) continue
107
154
  const text = turnTextOf(record)
108
155
  if (text === '') continue
109
156
  turns.push({ role: record.role, text })
@@ -125,9 +172,13 @@ export function selectTurns(messages: readonly unknown[], options: ContextWindow
125
172
  }
126
173
  }
127
174
 
175
+ const total = turns.length
128
176
  const windowed = turns.slice(-maxMessages)
177
+ const droppedByMessages = total - windowed.length
129
178
  const kept: ContextTurn[] = []
130
179
  let used = 0
180
+ let limitedBy: ContextUsage['limitedBy'] = null
181
+ let cutTurn = false
131
182
  for (let index = windowed.length - 1; index >= 0; index--) {
132
183
  const turn = windowed[index]!
133
184
  // Same gauge as `shared/validate.countText`, the input cap, and the host
@@ -141,14 +192,31 @@ export function selectTurns(messages: readonly unknown[], options: ContextWindow
141
192
  // marked as cut. The head is what names the task, the stack, and the
142
193
  // constraints the draft is shorthand for.
143
194
  if (kept.length === 0 && room > TRUNCATION_MARK.length + 40) {
144
- kept.unshift({ role: turn.role, text: `${cutToCodePoints(turn.text, room - TRUNCATION_MARK.length).trimEnd()}${TRUNCATION_MARK}` })
195
+ const cut = `${cutToCodePoints(turn.text, room - TRUNCATION_MARK.length).trimEnd()}${TRUNCATION_MARK}`
196
+ kept.unshift({ role: turn.role, text: cut })
197
+ cutTurn = true
198
+ } else {
199
+ limitedBy = 'chars'
145
200
  }
146
201
  break
147
202
  }
148
203
  used += length
149
204
  kept.unshift(turn)
150
205
  }
151
- return kept
206
+ if (!cutTurn && limitedBy === null && droppedByMessages > 0) limitedBy = 'turns'
207
+ const usedChars = kept.reduce((sum, turn) => sum + countText(turn.text), 0)
208
+ return {
209
+ turns: kept,
210
+ usage: {
211
+ usedTurns: kept.length,
212
+ maxTurns: maxMessages,
213
+ usedChars,
214
+ maxChars,
215
+ droppedTurns: total - kept.length,
216
+ limitedBy,
217
+ cutTurn,
218
+ },
219
+ }
152
220
  }
153
221
 
154
222
  /**
@@ -180,9 +248,21 @@ export function formatContextBlock(turns: readonly ContextTurn[]): string {
180
248
  * @returns the framed snippet, or `undefined` when there is no usable history
181
249
  * — the caller then runs the original single-prompt enhancement.
182
250
  */
183
- export function buildConversationContext(messages: readonly unknown[] | undefined, options: ContextWindowOptions, draft?: string): string | undefined {
251
+ export function buildConversationContextWithUsage(messages: readonly unknown[] | undefined, options: ContextWindowOptions, draft?: string): { text: string; usage: ContextUsage } | undefined {
184
252
  if (messages === undefined) return undefined
185
- const turns = selectTurns(messages, options, draft)
186
- if (turns.length === 0) return undefined
187
- return formatContextBlock(turns)
253
+ const selection = selectTurnsWithUsage(messages, options, draft)
254
+ if (selection.turns.length === 0) return undefined
255
+ return { text: formatContextBlock(selection.turns), usage: selection.usage }
256
+ }
257
+
258
+ /**
259
+ * Build the grounding snippet for one enhancement, or nothing at all.
260
+ * @param messages - the session's derived history (untrusted, may be undefined).
261
+ * @param options - the configured window.
262
+ * @param draft - the raw draft being enhanced.
263
+ * @returns the framed snippet, or `undefined` when there is no usable history
264
+ * — the caller then runs the original single-prompt enhancement.
265
+ */
266
+ export function buildConversationContext(messages: readonly unknown[] | undefined, options: ContextWindowOptions, draft?: string): string | undefined {
267
+ return buildConversationContextWithUsage(messages, options, draft)?.text
188
268
  }
@@ -10,9 +10,9 @@ import type { Context } from '@deepseek-ai/cordis'
10
10
  import { randomUUID } from 'node:crypto'
11
11
  import { effectiveSystemPrompt, type Config } from './config'
12
12
  import { DEFAULT_SYSTEM_PROMPT, withContextRules } from './prompts'
13
- import { buildConversationContext } from './context'
13
+ import { buildConversationContextWithUsage } from './context'
14
14
  import { EnhanceFailure, enhanceText, resolveRoute, toEnhanceError, type RoutePair } from './enhancer'
15
- import type { EnhanceResult } from './shared/protocol'
15
+ import type { ContextUsage, EnhanceResult } from './shared/protocol'
16
16
  import { countText } from './shared/validate'
17
17
  import type { LlmResolvedModelInfo } from '@deepseek-ai/dsh-llm'
18
18
  import { readCachedCapabilities, writeCachedCapabilities } from './reasoning-cache'
@@ -180,6 +180,22 @@ export function defaultRouteOf(ctx: Context): RoutePair | undefined {
180
180
  * @returns the framed snippet, or undefined to run unconstrained.
181
181
  */
182
182
  export function conversationContextOf(ctx: Context, sessionId: string | undefined, config: Config, draft: string): string | undefined {
183
+ return conversationContextWithUsage(ctx, sessionId, config, draft)?.text
184
+ }
185
+
186
+ /**
187
+ * The conversation-context snippet plus its usage numbers, or nothing at all.
188
+ *
189
+ * Same fail-open rules as {@link conversationContextOf}; the only addition is
190
+ * the {@link ContextUsage} the result card displays. Callers that only need
191
+ * the text keep using the wrapper above.
192
+ * @param ctx - registrant context (optional `sessions`).
193
+ * @param sessionId - the session the draft belongs to, when known.
194
+ * @param config - the resolved config (switch + window).
195
+ * @param draft - the raw draft being enhanced.
196
+ * @returns the framed snippet and its usage, or undefined.
197
+ */
198
+ export function conversationContextWithUsage(ctx: Context, sessionId: string | undefined, config: Config, draft: string): { text: string; usage: ContextUsage } | undefined {
183
199
  if (!config.contextAware) return undefined
184
200
  if (sessionId === undefined || sessionId === '') return undefined
185
201
  const session = serviceEntry(ctx, 'sessions', sessionId) as ReturnType<SessionsFace['get']> | undefined
@@ -193,7 +209,7 @@ export function conversationContextOf(ctx: Context, sessionId: string | undefine
193
209
  // A session-layer hiccup must not turn one enhance request into a 502.
194
210
  return undefined
195
211
  }
196
- return buildConversationContext(messages, { maxMessages: config.contextMaxMessages, maxChars: config.contextMaxChars }, draft)
212
+ return buildConversationContextWithUsage(messages, { maxMessages: config.contextMaxMessages, maxChars: config.contextMaxChars }, draft)
197
213
  }
198
214
 
199
215
  /** One orchestration request. */
@@ -287,7 +303,8 @@ export async function runEnhance(ctx: Context, config: Config, options: RunEnhan
287
303
  if (llm === undefined) {
288
304
  throw new EnhanceFailure({ code: 'internal' })
289
305
  }
290
- const context = options.context !== undefined ? options.context : conversationContextOf(ctx, options.sessionId, config, options.text)
306
+ const derivedContext = options.context === undefined ? conversationContextWithUsage(ctx, options.sessionId, config, options.text) : undefined
307
+ const context = options.context !== undefined ? options.context : derivedContext?.text
291
308
  const effort = await effectiveReasoningEffort(llm, route.provider, route.model, config.reasoningEffort)
292
309
  const result = await enhanceText(llm, {
293
310
  route,
@@ -305,7 +322,9 @@ export async function runEnhance(ctx: Context, config: Config, options: RunEnhan
305
322
  ...(options.sessionId !== undefined ? { sessionId: options.sessionId } : {}),
306
323
  })
307
324
  console.info(`[dsh-prompt-enhance] ${requestId} in=${countText(options.text)} out=${countText(result.text)} ctx=${context === undefined ? 0 : 1} ${result.elapsedMs}ms ok`)
308
- return result
325
+ // The card reports what the context window actually held; a caller that
326
+ // supplied its own snippet has no usage to report, so the field stays out.
327
+ return derivedContext === undefined ? result : { ...result, context: derivedContext.usage }
309
328
  } catch (error) {
310
329
  const wire = toEnhanceError(error)
311
330
  console.info(`[dsh-prompt-enhance] ${requestId} in=${countText(options.text)} error=${wire.code} ${Date.now() - started}ms`)
@@ -65,6 +65,24 @@ export interface EnhanceUsage {
65
65
  }
66
66
 
67
67
  /** One successful enhancement. */
68
+ /** How much conversation history one enhancement actually sent. */
69
+ export interface ContextUsage {
70
+ /** Turns admitted into the snippet. */
71
+ usedTurns: number
72
+ /** Configured turn cap (`contextMaxMessages`). */
73
+ maxTurns: number
74
+ /** Unicode code points admitted (turn text only, matching the context budget). */
75
+ usedChars: number
76
+ /** Configured character cap (`contextMaxChars`). */
77
+ maxChars: number
78
+ /** Qualifying turns that did not fit. */
79
+ droppedTurns: number
80
+ /** Which cap stopped the selection; null when everything qualified fit. */
81
+ limitedBy: 'turns' | 'chars' | null
82
+ /** True when the newest turn was cut to its head and marked as truncated. */
83
+ cutTurn: boolean
84
+ }
85
+
68
86
  export interface EnhanceResult {
69
87
  /** The rewritten prompt body (already normalized: no fences, trimmed). */
70
88
  text: string
@@ -84,6 +102,8 @@ export interface EnhanceResult {
84
102
  * field, so the UI must treat it as optional.
85
103
  */
86
104
  reasoningEffort?: string
105
+ /** Conversation-history usage of this call; absent when no context was sent. */
106
+ context?: ContextUsage
87
107
  }
88
108
 
89
109
  /**