@surfishs/dsh-prompt-enhance 0.1.2 → 0.1.4

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.
@@ -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)
@@ -16,6 +16,22 @@ export type Translate = TranslateNS<typeof LOCALE_NS>
16
16
  /** The shipped Chinese dictionary, used when a host projects no `t` seat. */
17
17
  export const ZH_COPY: Readonly<Record<string, string>> = zh
18
18
 
19
+ /**
20
+ * Fill `{name}` placeholders from `params`, then hand the result to the seat.
21
+ * The seat's own parameter support is host-dependent; doing the substitution
22
+ * locally keeps a parameterized row message working on every host (and in the
23
+ * test double, whose `t` takes the key only).
24
+ * @param t - the locale-bound translate seat.
25
+ * @param key - the dictionary key.
26
+ * @param params - placeholder values.
27
+ * @returns the interpolated copy.
28
+ */
29
+ function interpolate(t: Translate, key: PromptEnhanceKey, params: Record<string, string>): string {
30
+ let text = t(key)
31
+ for (const [name, value] of Object.entries(params)) text = text.split(`{${name}}`).join(value)
32
+ return text
33
+ }
34
+
19
35
  /**
20
36
  * Resolve the Plugins-page copy reader: the injected `t` when present, the
21
37
  * shipped Chinese dictionary otherwise. Falling back keeps an older host (or a
@@ -84,7 +100,7 @@ export function sectionCopy(t: Translate, chinese: boolean): RowCopy {
84
100
  hint: (row) => t(row.hint),
85
101
  placeholder: (row) => (row.placeholder === undefined ? undefined : t(row.placeholder)),
86
102
  choice: (key) => t(key),
87
- interpolate: (key, params) => t(key, params),
103
+ interpolate: (key, params) => interpolate(t, key, params),
88
104
  }
89
105
  }
90
106
 
@@ -117,6 +133,6 @@ export function pageCopy(t: Translate): RowCopy {
117
133
  hint: (row) => t(row.hint),
118
134
  placeholder: (row) => (row.placeholder === undefined ? undefined : t(row.placeholder)),
119
135
  choice: (key) => t(key),
120
- interpolate: (key, params) => t(key, params),
136
+ interpolate: (key, params) => interpolate(t, key, params),
121
137
  }
122
138
  }
@@ -12,6 +12,7 @@
12
12
  import { SettingsFormModel, settingsNumberField, settingsTextField } from '@deepseek-ai/dsh-client-ui-primitives'
13
13
  import type { SettingsFieldDescriptor } from '@deepseek-ai/dsh-client-ui-primitives'
14
14
  import { DEFAULT_VALUES } from '../shared/defaults'
15
+ import { FIELD_LIMITS, TEMPERATURE, type NumericRange } from '../shared/limits'
15
16
  import { parseShortcut } from './shortcut'
16
17
  import type { PromptEnhanceKey } from './locales'
17
18
  import type { RowCopy, Translate } from './settings-page-copy'
@@ -130,10 +131,35 @@ export interface Row {
130
131
  * Absent means "anything the descriptor stages is writable".
131
132
  */
132
133
  readonly validate?: (text: string) => boolean
134
+ /** Inclusive bounds a number row enforces; `integer` defaults to true. */
135
+ readonly range?: NumericRange & { readonly integer?: boolean }
133
136
  /** Offer the press-a-combination recorder next to the input (the shortcut row). */
134
137
  readonly recordable?: boolean
135
138
  }
136
139
 
140
+ /** Whether one staged numeric text is writable: empty clears, otherwise an in-range number. */
141
+ function validateNumber(text: string, range: NumericRange, integer: boolean): boolean {
142
+ const trimmed = text.trim()
143
+ // Empty means "clear" in the form model, so it is valid for every row.
144
+ if (trimmed === '') return true
145
+ const value = Number(trimmed)
146
+ if (!Number.isFinite(value)) return false
147
+ if (integer && !Number.isInteger(value)) return false
148
+ return value >= range.min && value <= range.max
149
+ }
150
+
151
+ /** One numeric row: its real bounds plus the staged-text validation the red-box path reads. */
152
+ function numberRow(key: string, label: PromptEnhanceKey, hint: PromptEnhanceKey, range: NumericRange, integer = true): Row {
153
+ return {
154
+ key,
155
+ kind: 'number',
156
+ label,
157
+ hint,
158
+ range: { ...range, integer },
159
+ validate: (text: string) => validateNumber(text, range, integer),
160
+ }
161
+ }
162
+
137
163
  /**
138
164
  * Every row both pages edit, in display order: the master switch and the two
139
165
  * display/context switches first, then routing and generation, then the
@@ -144,7 +170,7 @@ export const BASIC_ROWS: readonly Row[] = [
144
170
  { key: 'provider', kind: 'provider', label: 'settings.row.provider.label', hint: 'settings.row.provider.hint' },
145
171
  { key: 'model', kind: 'model', label: 'settings.row.model.label', hint: 'settings.row.model.hint' },
146
172
  { key: 'reasoningEffort', kind: 'reasoning', label: 'settings.row.reasoningEffort.label', hint: 'settings.row.reasoningEffort.hint' },
147
- { key: 'temperature', kind: 'number', label: 'settings.row.temperature.label', hint: 'settings.row.temperature.hint' },
173
+ numberRow('temperature', 'settings.row.temperature.label', 'settings.row.temperature.hint', TEMPERATURE, false),
148
174
  { key: 'contextAware', kind: 'boolean', label: 'settings.row.contextAware.label', hint: 'settings.row.contextAware.hint' },
149
175
  { key: 'streaming', kind: 'boolean', label: 'settings.row.streaming.label', hint: 'settings.row.streaming.hint' },
150
176
  { key: 'systemPrompt', kind: 'text', label: 'settings.row.systemPrompt.label', hint: 'settings.row.systemPrompt.hint', placeholder: 'settings.row.systemPrompt.placeholder' },
@@ -165,13 +191,13 @@ export const ADVANCED_ROWS: readonly Row[] = [
165
191
  { key: 'foldAnimation', kind: 'boolean', label: 'settings.row.foldAnimation.label', hint: 'settings.row.foldAnimation.hint' },
166
192
  { key: 'autoFold', kind: 'boolean', label: 'settings.row.autoFold.label', hint: 'settings.row.autoFold.hint' },
167
193
  { key: 'strategyMode', kind: 'strategy', label: 'settings.row.strategyMode.label', hint: 'settings.row.strategyMode.hint' },
168
- { key: 'maxInputChars', kind: 'number', label: 'settings.row.maxInputChars.label', hint: 'settings.row.maxInputChars.hint' },
169
- { key: 'maxOutputTokens', kind: 'number', label: 'settings.row.maxOutputTokens.label', hint: 'settings.row.maxOutputTokens.hint' },
170
- { key: 'timeoutMs', kind: 'number', label: 'settings.row.timeoutMs.label', hint: 'settings.row.timeoutMs.hint' },
171
- { key: 'contextMaxMessages', kind: 'number', label: 'settings.row.contextMaxMessages.label', hint: 'settings.row.contextMaxMessages.hint' },
172
- { key: 'contextMaxChars', kind: 'number', label: 'settings.row.contextMaxChars.label', hint: 'settings.row.contextMaxChars.hint' },
173
- { key: 'maxConcurrent', kind: 'number', label: 'settings.row.maxConcurrent.label', hint: 'settings.row.maxConcurrent.hint' },
174
- { key: 'rateLimitPerMinute', kind: 'number', label: 'settings.row.rateLimitPerMinute.label', hint: 'settings.row.rateLimitPerMinute.hint' },
194
+ numberRow('maxInputChars', 'settings.row.maxInputChars.label', 'settings.row.maxInputChars.hint', FIELD_LIMITS.maxInputChars),
195
+ numberRow('maxOutputTokens', 'settings.row.maxOutputTokens.label', 'settings.row.maxOutputTokens.hint', FIELD_LIMITS.maxOutputTokens),
196
+ numberRow('timeoutMs', 'settings.row.timeoutMs.label', 'settings.row.timeoutMs.hint', FIELD_LIMITS.timeoutMs),
197
+ numberRow('contextMaxMessages', 'settings.row.contextMaxMessages.label', 'settings.row.contextMaxMessages.hint', FIELD_LIMITS.contextMaxMessages),
198
+ numberRow('contextMaxChars', 'settings.row.contextMaxChars.label', 'settings.row.contextMaxChars.hint', FIELD_LIMITS.contextMaxChars),
199
+ numberRow('maxConcurrent', 'settings.row.maxConcurrent.label', 'settings.row.maxConcurrent.hint', FIELD_LIMITS.maxConcurrent),
200
+ numberRow('rateLimitPerMinute', 'settings.row.rateLimitPerMinute.label', 'settings.row.rateLimitPerMinute.hint', FIELD_LIMITS.rateLimitPerMinute),
175
201
  ]
176
202
 
177
203
  /** Every row both pages edit; the renderer splits it at the Advanced boundary. */
@@ -104,6 +104,37 @@ function PageHeader(props: { title: string; description: string; version: string
104
104
  )
105
105
  }
106
106
 
107
+ /**
108
+ * The red-box reason for a staged row, or undefined when the text is writable.
109
+ * @param row - the row being rendered.
110
+ * @param text - its staged text.
111
+ * @param copy - the page copy, for the row-specific message.
112
+ * @returns the message to show inline, or undefined.
113
+ */
114
+ function invalidMessageOf(row: Row, text: string, copy: RowCopy): string | undefined {
115
+ if (row.validate === undefined || row.validate(text)) return undefined
116
+ if (row.range !== undefined) {
117
+ const key = row.range.integer === false ? 'settings.row.invalidNumber' : 'settings.row.invalidInteger'
118
+ return copy.interpolate(key, { min: String(row.range.min), max: String(row.range.max) })
119
+ }
120
+ return copy.labels.invalidShortcut
121
+ }
122
+
123
+ /**
124
+ * The input placeholder for one row. A numeric row that is empty shows the
125
+ * effective default, so "blank" visibly means "use the default" instead of
126
+ * looking like a silent clear.
127
+ * @param row - the row being rendered.
128
+ * @param view - its staged state.
129
+ * @param copy - the page copy, for the placeholder text.
130
+ * @returns the placeholder, or undefined.
131
+ */
132
+ function placeholderOf(row: Row, view: FieldView, copy: RowCopy): string | undefined {
133
+ if (row.kind !== 'number' || view.text.trim() !== '') return copy.placeholder(row)
134
+ const fallback = defaultTextOf(row.key)
135
+ return fallback === '' ? copy.placeholder(row) : copy.interpolate('settings.row.blankDefault', { value: fallback })
136
+ }
137
+
107
138
  /**
108
139
  * One row, rendered as the control its kind asks for.
109
140
  * @param props - the row, its copy, its state, its actions, and the pinned pair.
@@ -148,8 +179,8 @@ function SettingsRow(props: {
148
179
  <ValueRow
149
180
  {...shared}
150
181
  numeric={props.row.kind === 'number'}
151
- placeholder={props.copy.placeholder(props.row)}
152
- invalidMessage={props.row.validate !== undefined && !props.row.validate(props.view.text) ? props.copy.labels.invalidShortcut : undefined}
182
+ placeholder={placeholderOf(props.row, props.view, props.copy)}
183
+ invalidMessage={invalidMessageOf(props.row, props.view.text, props.copy)}
153
184
  recordable={props.row.recordable === true}
154
185
  />
155
186
  )
@@ -40,6 +40,9 @@ export const CSS = `
40
40
  from the other scheme. */
41
41
  --pe-warn-border: color-mix(in srgb, var(--dsw-alias-state-warn-primary, #e8c07d) 35%, transparent);
42
42
  --pe-warn-bg: color-mix(in srgb, var(--dsw-alias-state-warn-primary, #e8c07d) 12%, transparent);
43
+ /* Same tint recipe for the truncation banner: red is a state, not a theme. */
44
+ --pe-danger-border: color-mix(in srgb, var(--dsw-alias-state-error-primary, #ffb4a8) 35%, transparent);
45
+ --pe-danger-bg: color-mix(in srgb, var(--dsw-alias-state-error-primary, #ffb4a8) 12%, transparent);
43
46
  }
44
47
  /* Quick-settings menu, copied from the shell's own menu primitives:
45
48
  - the card surface is MenuSurface.module.css (radius-lg, elevation stroke,
@@ -362,6 +365,7 @@ html[data-platform='darwin'] .dsh-pe-menu {
362
365
  /* Collapsed, the warning banners live in the hidden body; this marker stands in
363
366
  for them so a stale or truncated result never folds away silently. */
364
367
  .dsh-pe-warn-dot { font-size: 15px; line-height: 1; color: var(--pe-warn-fg); }
368
+ .dsh-pe-warn-dot.is-danger { color: var(--pe-danger); }
365
369
  .dsh-pe-result { padding: 2px 10px 6px; }
366
370
  .dsh-pe-result-text {
367
371
  margin: 0;
@@ -429,6 +433,114 @@ html[data-platform='darwin'] .dsh-pe-menu {
429
433
  border-top: 1px solid var(--pe-separator);
430
434
  }
431
435
  .dsh-pe-foot .dsh-pe-grow { flex: 1; }
436
+
437
+ /* The context-usage button sits at the quiet end of the footer, opposite the
438
+ actions. Its tooltip opens upward into the card body, so no portal is needed
439
+ and the card's own overflow clipping stays out of the way. */
440
+ .dsh-pe-context-wrap {
441
+ position: relative;
442
+ display: inline-flex;
443
+ }
444
+ .dsh-pe-context {
445
+ box-sizing: border-box;
446
+ display: inline-flex;
447
+ flex: none;
448
+ align-items: center;
449
+ justify-content: center;
450
+ width: 28px;
451
+ height: 28px;
452
+ padding: 0;
453
+ border: 0;
454
+ border-radius: 8px;
455
+ background: transparent;
456
+ /* The glyph carries the state on its own: grey when the window is healthy,
457
+ amber when it had to cut something. The precise counts stay in the
458
+ tooltip. */
459
+ --pe-context-accent: var(--dsw-alias-label-tertiary, #8a8a8a);
460
+ color: var(--pe-context-accent);
461
+ cursor: default;
462
+ }
463
+ .dsh-pe-context:hover { background: var(--pe-hover); }
464
+ .dsh-pe-context.is-limited {
465
+ --pe-context-accent: #b45309;
466
+ color: var(--pe-context-accent);
467
+ }
468
+ /* The warning lives in the glyph alone by default; the amber tint appears on
469
+ hover or keyboard focus, matching the plain state's on-demand background. */
470
+ .dsh-pe-context.is-limited:hover,
471
+ .dsh-pe-context.is-limited:focus-visible {
472
+ background: rgba(180, 83, 9, 0.1);
473
+ }
474
+ .dsh-pe-context-icon {
475
+ position: relative;
476
+ z-index: 1;
477
+ display: block;
478
+ width: 20px;
479
+ height: 20px;
480
+ color: var(--pe-context-accent);
481
+ }
482
+ .dsh-pe-context-tip {
483
+ position: absolute;
484
+ left: 0;
485
+ bottom: calc(100% + 8px);
486
+ z-index: 5;
487
+ display: flex;
488
+ flex-direction: column;
489
+ gap: 2px;
490
+ box-sizing: border-box;
491
+ width: max-content;
492
+ max-width: min(340px, calc(100vw - 40px));
493
+ padding: 6px 10px;
494
+ border-radius: var(--dsw-radius-sm, 6px);
495
+ background: var(--dsw-alias-tooltip-bg, #2f2f2f);
496
+ color: var(--dsw-alias-tooltip-label, #ffffff);
497
+ font-size: 13px;
498
+ line-height: 20px;
499
+ font-variant-numeric: tabular-nums;
500
+ white-space: normal;
501
+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.18);
502
+ pointer-events: none;
503
+ animation: dsh-pe-context-tip-in 140ms ease-out;
504
+ }
505
+ /* The bubble needs an anchor: it floats above the icon and would otherwise
506
+ read as disconnected from the footer. */
507
+ .dsh-pe-context-tip::after {
508
+ content: '';
509
+ position: absolute;
510
+ left: 12px;
511
+ bottom: -5px;
512
+ width: 0;
513
+ height: 0;
514
+ border-left: 5px solid transparent;
515
+ border-right: 5px solid transparent;
516
+ border-top: 5px solid var(--dsw-alias-tooltip-bg, #2f2f2f);
517
+ }
518
+ @keyframes dsh-pe-context-tip-in {
519
+ from {
520
+ opacity: 0;
521
+ transform: translateY(2px);
522
+ }
523
+ }
524
+ @media (prefers-reduced-motion: reduce) {
525
+ .dsh-pe-context-tip { animation: none; }
526
+ }
527
+ /* The stats line is one unit: a wrap that leaves the percentage alone reads
528
+ as a layout bug. The reason line may wrap freely. */
529
+ .dsh-pe-context-tip .dsh-pe-context-stats { white-space: nowrap; }
530
+ .dsh-pe-context-tip .dsh-pe-context-reason { color: #f2c185; }
531
+ /* Attachment count is metadata, not a warning: same tooltip body color. */
532
+ .dsh-pe-context-tip .dsh-pe-context-attachments { white-space: nowrap; }
533
+ /* Narrow viewports: the card itself is close to the viewport width, so the
534
+ fixed tooltip width would clip. Give it a viewport-relative cap and let the
535
+ stats line wrap instead of overflowing. */
536
+ @media (max-width: 560px) {
537
+ .dsh-pe-context-tip {
538
+ min-width: 0;
539
+ width: 230px;
540
+ max-width: calc(100vw - 40px);
541
+ }
542
+ .dsh-pe-context-tip .dsh-pe-context-stats { white-space: normal; }
543
+ }
432
544
  .dsh-pe-btn-action {
433
545
  box-sizing: border-box;
434
546
  display: inline-flex;
@@ -472,6 +584,10 @@ html[data-platform='darwin'] .dsh-pe-menu {
472
584
  (retry, cancel) the same size as the rest. */
473
585
  .dsh-pe-btn-floor { min-width: 96px; }
474
586
  .dsh-pe-btn-action:disabled { opacity: 0.45; cursor: default; }
587
+ /* aria-disabled, not the native attribute: the button keeps focus and its
588
+ click handler so the reason stays reachable (the handler refuses to run). */
589
+ .dsh-pe-btn-action[aria-disabled='true'] { opacity: 0.45; cursor: not-allowed; }
590
+ .dsh-pe-btn-action[aria-disabled='true']:hover { background: transparent; }
475
591
 
476
592
  /* Both labels of the regenerate button share one cell, so the button is as wide
477
593
  as the longer label of the active language and a label swap can never move
@@ -489,6 +605,13 @@ html[data-platform='darwin'] .dsh-pe-menu {
489
605
  background: var(--pe-warn-bg);
490
606
  color: var(--pe-warn-fg);
491
607
  }
608
+ /* Truncation is a result-quality problem, not a stale-draft warning: red says
609
+ the result itself is incomplete, while the stale banner keeps the amber. */
610
+ .dsh-pe-stale.dsh-pe-truncated {
611
+ border-top-color: var(--pe-danger-border);
612
+ background: var(--pe-danger-bg);
613
+ color: var(--pe-danger);
614
+ }
492
615
 
493
616
  .dsh-pe-btn {
494
617
  display: inline-flex;
@@ -17,6 +17,11 @@ export interface PanelState {
17
17
  readonly phase: 'loading' | 'result' | 'error'
18
18
  /** The draft as it was when the request started (never mutated). */
19
19
  readonly original: string
20
+ /**
21
+ * Draft attachments the request announced to the model. Count only — the
22
+ * contents are never sent — and a snapshot of the request-time composer.
23
+ */
24
+ readonly attachments?: { readonly count: number }
20
25
  readonly result?: EnhanceResult
21
26
  readonly error?: EnhanceError
22
27
  /** True while the card body is collapsed: the header and the footer stay, the body hides. */
@@ -164,7 +169,13 @@ export function openLoading(state: Omit<PanelState, 'phase' | 'result' | 'error'
164
169
  /** Settle the open panel with a result. Ignored when the panel moved on. */
165
170
  export function settleResult(sessionId: string, result: EnhanceResult): void {
166
171
  if (panelState?.sessionId !== sessionId || panelState.phase !== 'loading') return
167
- panelState = { sessionId, phase: 'result', original: panelState.original, result }
172
+ panelState = {
173
+ sessionId,
174
+ phase: 'result',
175
+ original: panelState.original,
176
+ result,
177
+ ...(panelState.attachments === undefined ? {} : { attachments: panelState.attachments }),
178
+ }
168
179
  notify()
169
180
  }
170
181
 
package/src/config.ts CHANGED
@@ -318,14 +318,21 @@ export function resolveConfig(config: Config): Config {
318
318
  * {@link INVARIANT_CONTRACT} — the framed draft is data, the output is the
319
319
  * rewrite alone, context is evidence — so a one-line custom strategy still
320
320
  * behaves like an enhancement instead of derailing into a conversation.
321
- * Tolerates an absent field (older stored sections predate the schema default).
321
+ *
322
+ * Context rules are passed separately (not pre-merged into `builtin`) so a
323
+ * `replace-default` strategy cannot silently drop them; they apply in every
324
+ * mode. Tolerates an absent field (older stored sections predate the schema
325
+ * default).
322
326
  * @param config - the resolved config.
323
327
  * @param builtin - the built-in strategy prompt.
328
+ * @param contextRules - the context-rules block, or an empty string.
324
329
  * @returns the system prompt of the next call.
325
330
  */
326
- export function effectiveSystemPrompt(config: Config, builtin: string): string {
331
+ export function effectiveSystemPrompt(config: Config, builtin: string, contextRules = ''): string {
327
332
  const custom = (config.systemPrompt ?? '').trim()
328
- if (custom === '') return builtin
329
- const strategy = config.strategyMode === 'extend-default' ? `${builtin}\n\nOperator additions (follow them where they do not conflict with the rules above):\n${custom}` : custom
333
+ const context = contextRules.trim() === '' ? '' : `\n${contextRules}`
334
+ if (custom === '') return `${builtin}${context}`
335
+ const strategy =
336
+ config.strategyMode === 'extend-default' ? `${builtin}${context}\n\nOperator additions (follow them where they do not conflict with the rules above):\n${custom}` : `${custom}${context}`
330
337
  return `${strategy}\n\n${INVARIANT_CONTRACT}`
331
338
  }
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
  }
@@ -26,6 +26,25 @@ import { serveCatalog } from './catalog-route'
26
26
  /** Envelope slack over the UTF-8 text cap: JSON quoting can inflate ~2-6x in the worst case. */
27
27
  const bodyCapOf = (maxInputChars: number): number => maxInputChars * 6 + 4096
28
28
 
29
+ /**
30
+ * Sanity bound on the announced attachment count. This is not a product limit
31
+ * (the composer decides what may be added); it only keeps a malformed or
32
+ * hostile body from writing an absurd number into the prompt.
33
+ */
34
+ const MAX_ATTACHMENT_COUNT = 100
35
+
36
+ /**
37
+ * Validate the optional `attachments` field of one request body.
38
+ * @param value - the untrusted field.
39
+ * @returns the count (0 for absent), or undefined when the shape is invalid.
40
+ */
41
+ function attachmentCountOf(value: unknown): number | undefined {
42
+ if (value === undefined) return 0
43
+ if (value === null || typeof value !== 'object') return undefined
44
+ const count = (value as { count?: unknown }).count
45
+ return typeof count === 'number' && Number.isSafeInteger(count) && count >= 0 && count <= MAX_ATTACHMENT_COUNT ? count : undefined
46
+ }
47
+
29
48
  /**
30
49
  * Serve one enhance POST against the request envelope.
31
50
  * @param ctx - registrant context (llm, optional sessions/settings).
@@ -108,9 +127,17 @@ async function serveEnhance(ctx: Context, readConfig: () => Config, gate: Admiss
108
127
  })
109
128
  return
110
129
  }
111
- const record = body as { sessionId?: unknown; text?: unknown } | null
130
+ const record = body as { sessionId?: unknown; text?: unknown; attachments?: unknown } | null
112
131
  if (record === null || typeof record !== 'object' || typeof record.text !== 'string') {
113
- writeJson(res, 422, { ok: false, error: { code: 'rejected', message: '请求体必须是 { sessionId?, text } JSON。' } })
132
+ writeJson(res, 422, { ok: false, error: { code: 'rejected', message: '请求体必须是 { sessionId?, text, attachments? } JSON。' } })
133
+ return
134
+ }
135
+ // The attachment count is metadata the browser snapshots from the composer:
136
+ // it is forwarded into the prompt (never the contents), so it must be a
137
+ // bounded integer before it can reach the model.
138
+ const attachmentCount = attachmentCountOf(record.attachments)
139
+ if (attachmentCount === undefined) {
140
+ writeJson(res, 422, { ok: false, error: { code: 'rejected', message: 'attachments 必须是 { count: 0–100 的整数 }。' } })
114
141
  return
115
142
  }
116
143
  // The session id arrives from the request body and is used as-is for the route
@@ -161,6 +188,7 @@ async function serveEnhance(ctx: Context, readConfig: () => Config, gate: Admiss
161
188
  sessionRoute: sessionRouteOf(ctx, sessionId),
162
189
  signal: callerAbort.signal,
163
190
  ...(sessionId !== undefined ? { sessionId } : {}),
191
+ ...(attachmentCount > 0 ? { attachments: { count: attachmentCount } } : {}),
164
192
  }
165
193
  if (stream) {
166
194
  // The stream already opens before the model call, so the client sees
package/src/enhancer.ts CHANGED
@@ -116,6 +116,8 @@ export interface EnhanceCallOptions {
116
116
  sessionId?: string
117
117
  /** The framed conversation-context snippet, when the call carries one. */
118
118
  context?: string
119
+ /** Draft attachment count the prompt only announces; contents are never sent. */
120
+ attachmentCount?: number
119
121
  /**
120
122
  * Receives each text delta as the model produces it (display only). May be
121
123
  * async — the streaming route's sink awaits socket backpressure, and this
@@ -172,7 +174,7 @@ export async function enhanceText(llm: LlmStreamFace, options: EnhanceCallOption
172
174
  const BlockAssemblerClass = runtime.BlockAssembler
173
175
  const messages = [
174
176
  createMessage({
175
- content: [{ type: 'text', text: frameUserPrompt(options.text, options.context) }],
177
+ content: [{ type: 'text', text: frameUserPrompt(options.text, options.context, options.attachmentCount) }],
176
178
  source: { kind: 'dsh-prompt-enhance' },
177
179
  }),
178
180
  ]