@surfishs/dsh-prompt-enhance 0.0.8 → 0.1.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.
@@ -3,16 +3,75 @@
3
3
  *
4
4
  * The host renders conversation.input.dock entries full-width, while the
5
5
  * composer card is narrower and may be centered or offset. This hook measures
6
- * the nearest editor below the dock, walks up to the composer's rounded
7
- * surface, and copies its width and left margin onto the returned wrapper.
8
- * When no editor is found, the host's full width is left untouched.
6
+ * the composer THIS entry belongs to and copies its width and left margin onto
7
+ * the returned wrapper.
8
+ *
9
+ * The slot exposes no layout or geometry prop — its standard props are hooks,
10
+ * `inputActions` and `sessionId` — so the DOM is the only source, and it is read
11
+ * in three tiers, most specific first:
12
+ * 1. the composer button this plugin renders for the SAME session (it carries
13
+ * {@link SESSION_ANCHOR_ATTRIBUTE}), then the rounded surface above it;
14
+ * 2. any editor inside the entry's own parent — dock entries and the composer
15
+ * card usually share that container, which keeps a multi-session layout from
16
+ * measuring a neighbour's composer;
17
+ * 3. any editor in the document (the original heuristic, kept as the last
18
+ * resort for a host whose DOM matches neither of the above).
19
+ * When nothing is found, the host's full width is left untouched.
9
20
  * @module dsh-prompt-enhance/client/useDockAlignment
10
21
  */
11
22
 
12
23
  import { useEffect, useRef, type RefObject } from 'react'
13
24
 
14
- /** Measure the composer below the dock and align the returned wrapper to it. */
15
- export function useDockAlignment(active: boolean): RefObject<HTMLDivElement> {
25
+ /** Everything the composer has been seen to use as its editable surface. */
26
+ const EDITOR_SELECTOR = 'textarea, [contenteditable="true"], [role="textbox"]'
27
+
28
+ /**
29
+ * Attribute the composer button carries, keyed by the session UI key. The dock
30
+ * entries read it to find the composer of the session they render for.
31
+ */
32
+ export const SESSION_ANCHOR_ATTRIBUTE = 'data-dsh-pe-key'
33
+
34
+ /** Geometry that makes an element plausible as the composer's card. */
35
+ const CARD_MIN_WIDTH = 360
36
+ const CARD_MIN_HEIGHT = 48
37
+ const CARD_MIN_RADIUS = 4
38
+ const CARD_MAX_DEPTH = 12
39
+ const CARD_MAX_VIEWPORT_SHARE = 0.8
40
+ const CARD_CENTER_TOLERANCE = 40
41
+ const EDITOR_BELOW_SLACK = 4
42
+
43
+ /** Whether one element looks like the composer's rounded, opaque surface. */
44
+ function isCardSurface(node: HTMLElement, minWidth: number): boolean {
45
+ const rect = node.getBoundingClientRect()
46
+ if (rect.width < minWidth || rect.width <= CARD_MIN_WIDTH || rect.height <= CARD_MIN_HEIGHT) return false
47
+ const style = getComputedStyle(node)
48
+ return (parseFloat(style.borderTopLeftRadius) || 0) >= CARD_MIN_RADIUS && style.backgroundColor !== 'rgba(0, 0, 0, 0)'
49
+ }
50
+
51
+ /** The nearest card surface above one element (the session-anchor path). */
52
+ function cardAround(start: HTMLElement): DOMRect | undefined {
53
+ let node: HTMLElement | null = start.parentElement
54
+ for (let depth = 0; depth < CARD_MAX_DEPTH && node !== null; depth++) {
55
+ if (isCardSurface(node, 0)) return node.getBoundingClientRect()
56
+ node = node.parentElement
57
+ }
58
+ return undefined
59
+ }
60
+
61
+ /** Every editor inside one scope. */
62
+ function editorsIn(scope: ParentNode): HTMLElement[] {
63
+ return Array.from(scope.querySelectorAll<HTMLElement>(EDITOR_SELECTOR))
64
+ }
65
+
66
+ /**
67
+ * Measure the composer of this dock entry and align the returned wrapper to it.
68
+ * @param active - whether this entry is currently rendered.
69
+ * @param uiKey - session UI key of the entry; the button anchor is looked up by
70
+ * it. Omitted when the host gave this composer no id (legacy hosts), in which
71
+ * case only tiers 2 and 3 apply.
72
+ * @returns the wrapper ref the caller must attach.
73
+ */
74
+ export function useDockAlignment(active: boolean, uiKey?: string): RefObject<HTMLDivElement> {
16
75
  const rootRef = useRef<HTMLDivElement>(null)
17
76
 
18
77
  useEffect(() => {
@@ -20,50 +79,66 @@ export function useDockAlignment(active: boolean): RefObject<HTMLDivElement> {
20
79
  const root = rootRef.current
21
80
  if (root === null) return
22
81
  let frame = 0
23
- const align = (): void => {
24
- const parent = root.parentElement
25
- if (parent === null) return
26
- // A transform-only offset is applied to the wrong base when the host
27
- // already centers this entry, and a translated box can be clipped by its
28
- // parent; use a layout margin instead. The previous margin is subtracted
29
- // from the measured left so repeated runs do not accumulate drift.
30
- root.style.transform = ''
31
- const rootRect = root.getBoundingClientRect()
32
- const editors = Array.from(document.querySelectorAll<HTMLElement>('textarea, [contenteditable="true"], [role="textbox"]'))
33
- const editor = editors.find((node) => {
82
+
83
+ /**
84
+ * The composer card measured from an editor. Collects every rounded, opaque
85
+ * ancestor of the editor, then takes the widest one that is still plausibly
86
+ * the card: the first match is often an inner wrapper a few pixels narrower
87
+ * than the card, while the conversation pane above it is too wide. Center
88
+ * proximity rejects the pane when the composer is off-center, and the width
89
+ * cap rejects it when both are centered.
90
+ * @param editor - the composer's editable surface.
91
+ * @returns the card rect, or undefined when no ancestor qualifies.
92
+ */
93
+ const cardFromEditor = (editor: HTMLElement): DOMRect | undefined => {
94
+ const editorRect = editor.getBoundingClientRect()
95
+ const candidates: DOMRect[] = []
96
+ let node: HTMLElement | null = editor
97
+ for (let depth = 0; depth < CARD_MAX_DEPTH && node !== null; depth++) {
98
+ if (isCardSurface(node, editorRect.width)) candidates.push(node.getBoundingClientRect())
99
+ node = node.parentElement
100
+ }
101
+ const widest = (list: DOMRect[]): DOMRect | undefined => list.sort((a, b) => b.width - a.width)[0]
102
+ if (candidates.length === 0) return undefined
103
+ const editorCenter = editorRect.left + editorRect.width / 2
104
+ const centered = candidates.filter((rect) => rect.width <= window.innerWidth * CARD_MAX_VIEWPORT_SHARE && Math.abs(rect.left + rect.width / 2 - editorCenter) < CARD_CENTER_TOLERANCE)
105
+ return widest(centered) ?? widest(candidates)
106
+ }
107
+
108
+ /** The first editor below the dock inside one scope. */
109
+ const editorBelow = (scope: ParentNode, rootRect: DOMRect): HTMLElement | undefined =>
110
+ editorsIn(scope).find((node) => {
34
111
  const rect = node.getBoundingClientRect()
35
- return rect.width > 0 && rect.height > 0 && rect.top >= rootRect.bottom - 4
112
+ return rect.width > 0 && rect.height > 0 && rect.top >= rootRect.bottom - EDITOR_BELOW_SLACK
36
113
  })
37
- if (editor === undefined) {
114
+
115
+ /** The composer card of THIS entry, most specific anchor first. */
116
+ const cardForThisEntry = (): DOMRect | undefined => {
117
+ if (uiKey !== undefined) {
118
+ const anchor = Array.from(document.querySelectorAll<HTMLElement>(`[${SESSION_ANCHOR_ATTRIBUTE}]`)).find((node) => node.getAttribute(SESSION_ANCHOR_ATTRIBUTE) === uiKey)
119
+ if (anchor !== undefined) {
120
+ const anchored = cardAround(anchor)
121
+ if (anchored !== undefined) return anchored
122
+ }
123
+ }
124
+ const rootRect = root.getBoundingClientRect()
125
+ const parent = root.parentElement
126
+ const scoped = parent === null ? undefined : editorBelow(parent, rootRect)
127
+ if (scoped !== undefined) {
128
+ const rect = cardFromEditor(scoped)
129
+ if (rect !== undefined) return rect
130
+ }
131
+ const anywhere = editorBelow(document, rootRect)
132
+ return anywhere === undefined ? undefined : cardFromEditor(anywhere)
133
+ }
134
+
135
+ /** Copy one card rect onto the wrapper; undefined restores the host width. */
136
+ const apply = (cardRect: DOMRect | undefined): void => {
137
+ if (cardRect === undefined) {
38
138
  root.style.width = ''
39
139
  root.style.marginLeft = ''
40
- root.style.transform = ''
41
140
  return
42
141
  }
43
- const editorRect = editor.getBoundingClientRect()
44
- // Collect every rounded, opaque ancestor of the editor, then take the
45
- // widest one that is still plausibly the composer card. The first match
46
- // is often an inner wrapper a few pixels narrower than the card; the
47
- // conversation pane above it is too wide. Center proximity rejects the
48
- // pane when the composer is off-center, and the width cap rejects it
49
- // when both are centered.
50
- const candidates: { node: HTMLElement; rect: DOMRect }[] = []
51
- let node: HTMLElement | null = editor
52
- for (let depth = 0; depth < 12 && node !== null; depth++) {
53
- const rect = node.getBoundingClientRect()
54
- const style = getComputedStyle(node)
55
- if (rect.width >= editorRect.width && rect.width > 360 && rect.height > 48 && (parseFloat(style.borderTopLeftRadius) || 0) >= 4 && style.backgroundColor !== 'rgba(0, 0, 0, 0)') {
56
- candidates.push({ node, rect })
57
- }
58
- node = node.parentElement
59
- }
60
- const editorCenter = editorRect.left + editorRect.width / 2
61
- const cardEntry =
62
- candidates
63
- .filter((candidate) => candidate.rect.width <= window.innerWidth * 0.8 && Math.abs(candidate.rect.left + candidate.rect.width / 2 - editorCenter) < 40)
64
- .sort((a, b) => b.rect.width - a.rect.width)[0] ?? candidates.sort((a, b) => b.rect.width - a.rect.width)[0]
65
- if (cardEntry === undefined) return
66
- const cardRect = cardEntry.rect
67
142
  const width = `${cardRect.width}px`
68
143
  if (root.style.width !== width) root.style.width = width
69
144
  // Width can shift a centered entry; measure again before deriving the
@@ -73,6 +148,15 @@ export function useDockAlignment(active: boolean): RefObject<HTMLDivElement> {
73
148
  const marginLeft = `${cardRect.left - (afterWidth.left - currentMargin)}px`
74
149
  if (root.style.marginLeft !== marginLeft) root.style.marginLeft = marginLeft
75
150
  }
151
+
152
+ const align = (): void => {
153
+ // A transform-only offset is applied to the wrong base when the host
154
+ // already centers this entry, and a translated box can be clipped by its
155
+ // parent; use a layout margin instead. The previous margin is subtracted
156
+ // from the measured left so repeated runs do not accumulate drift.
157
+ root.style.transform = ''
158
+ apply(cardForThisEntry())
159
+ }
76
160
  const schedule = (): void => {
77
161
  cancelAnimationFrame(frame)
78
162
  frame = requestAnimationFrame(align)
@@ -87,7 +171,7 @@ export function useDockAlignment(active: boolean): RefObject<HTMLDivElement> {
87
171
  window.removeEventListener('resize', schedule)
88
172
  observer?.disconnect()
89
173
  }
90
- }, [active])
174
+ }, [active, uiKey])
91
175
 
92
176
  return rootRef
93
177
  }
package/src/config.ts CHANGED
@@ -229,10 +229,14 @@ function resolveReasoningEffort(value: unknown): ReasoningEffortChoice {
229
229
  /**
230
230
  * Validate and detach one resolved config. Unknown keys (leftovers from older
231
231
  * versions) are stripped — only the schema-known fields survive. The loader
232
- * fills schema defaults before apply; this re-checks the invariants the
233
- * schema cannot express (provider/model pairing, non-empty route strings) so
234
- * a bad stored section fails loud at the boundary instead of inside a model
235
- * call.
232
+ * fills schema defaults before apply; this re-checks the invariants the schema
233
+ * cannot express (boolean types, numeric ranges) so a bad stored section fails
234
+ * loud at the boundary instead of inside a model call.
235
+ *
236
+ * The provider/model pair is the one deliberate exception: an incomplete
237
+ * override is not corruption but the state the settings page creates on every
238
+ * visit (each field saves as it changes), so it resolves to "no override" —
239
+ * the documented follow-session fallback — rather than throwing.
236
240
  * @param config - untrusted resolved section.
237
241
  * @returns the validated config, unknown keys removed.
238
242
  * @throws Error describing the first violated invariant.
@@ -240,28 +244,30 @@ function resolveReasoningEffort(value: unknown): ReasoningEffortChoice {
240
244
  export function resolveConfig(config: Config): Config {
241
245
  if (config === null || typeof config !== 'object') throw new Error('dsh-prompt-enhance: configuration is required')
242
246
  if (typeof config.enabled !== 'boolean') throw new Error('dsh-prompt-enhance: enabled 必须是布尔值')
243
- const hasProvider = config.provider !== undefined && config.provider !== ''
244
- const hasModel = config.model !== undefined && config.model !== ''
245
- if (hasProvider !== hasModel) {
246
- throw new Error('dsh-prompt-enhance: provider 与 model 必须成对填写(要么都填,要么都留空以跟随当前会话模型)')
247
- }
248
- const provider = hasProvider ? (config.provider ?? '').trim() : config.provider
249
- const model = hasModel ? (config.model ?? '').trim() : config.model
250
- if ((hasProvider && provider === '') || (hasModel && model === '')) {
251
- throw new Error('dsh-prompt-enhance: provider/model 覆盖必须是非空字符串')
252
- }
253
- const temperature = config.temperature
254
- if (typeof temperature !== 'number' || !Number.isFinite(temperature) || temperature < TEMPERATURE.min || temperature > TEMPERATURE.max) {
255
- throw new Error(`dsh-prompt-enhance: temperature 必须是 ${TEMPERATURE.min}–${TEMPERATURE.max} 之间的有限数字`)
256
- }
257
247
  // Whitespace-only is "absent", not "set": the explicit pair is definitionally
258
248
  // non-empty, so a blank override strips away as `undefined` rather than
259
249
  // surviving as `''` and reading as "an override exists" downstream.
260
- const pairOrUndefined = (value: string | undefined): string | undefined => {
261
- if (value === undefined) return undefined
250
+ const pairOrUndefined = (value: unknown): string | undefined => {
251
+ if (typeof value !== 'string') return undefined
262
252
  const trimmed = value.trim()
263
253
  return trimmed === '' ? undefined : trimmed
264
254
  }
255
+ const provider = pairOrUndefined(config.provider)
256
+ const model = pairOrUndefined(config.model)
257
+ // An incomplete pair is a NORMAL state, not a corrupt section: the settings
258
+ // page persists each field the moment it changes, so picking a provider
259
+ // stores `provider` alone until a model is chosen. Both READMEs and the row's
260
+ // own hint promise that state falls back to follow-session, so it resolves to
261
+ // NO override here. Throwing instead answered every enhance request with 500
262
+ // during that window — a config error for one optional preference.
263
+ //
264
+ // Only a COMPLETE pair pins the route; a half pair must never survive to read
265
+ // as an override downstream (see `resolveRoute`).
266
+ const override: { provider?: string; model?: string } = provider !== undefined && model !== undefined ? { provider, model } : {}
267
+ const temperature = config.temperature
268
+ if (typeof temperature !== 'number' || !Number.isFinite(temperature) || temperature < TEMPERATURE.min || temperature > TEMPERATURE.max) {
269
+ throw new Error(`dsh-prompt-enhance: temperature 必须是 ${TEMPERATURE.min}–${TEMPERATURE.max} 之间的有限数字`)
270
+ }
265
271
  const intInRange = (value: unknown, name: string, range: NumericRange): number => {
266
272
  if (typeof value !== 'number' || !Number.isInteger(value) || value < range.min || value > range.max) {
267
273
  throw new Error(`dsh-prompt-enhance: ${name} 必须是 ${range.min}–${range.max} 之间的整数`)
@@ -270,8 +276,8 @@ export function resolveConfig(config: Config): Config {
270
276
  }
271
277
  return {
272
278
  enabled: config.enabled,
273
- provider: pairOrUndefined(provider),
274
- model: pairOrUndefined(model),
279
+ provider: override.provider,
280
+ model: override.model,
275
281
  temperature,
276
282
  // Ids are adapter-owned, so the stored string is kept as-is; a blank or
277
283
  // absent value degrades to the cheapest shipped default. An id the route
@@ -9,6 +9,7 @@
9
9
 
10
10
  import type { Context } from '@deepseek-ai/cordis'
11
11
  import type { CommandDefinition, CommandInvocation } from '@deepseek-ai/dsh-commands'
12
+ import { breakerOutcome, type AdmissionGate, type AdmissionOutcome } from './admission'
12
13
  import { checkInputText, formatInputCheckZh } from './shared/validate'
13
14
  import { type Config } from './config'
14
15
  import { formatEnhanceError, toEnhanceError } from './enhancer'
@@ -24,8 +25,10 @@ interface CommandsFace {
24
25
  * service is a silent no-op so the plugin still loads in UI-less spines.
25
26
  * @param ctx - registrant context.
26
27
  * @param readConfig - per-call config reader.
28
+ * @param gate - the admission gate shared with the composer route, so the
29
+ * command plane is capped by the same window, concurrency cap and breaker.
27
30
  */
28
- export function registerEnhanceCommand(ctx: Context, readConfig: () => Config): void {
31
+ export function registerEnhanceCommand(ctx: Context, readConfig: () => Config, gate: AdmissionGate): void {
29
32
  const commands = ctx.get('commands') as unknown as CommandsFace | undefined
30
33
  if (commands === undefined) return
31
34
  const definition: CommandDefinition = {
@@ -39,8 +42,8 @@ export function registerEnhanceCommand(ctx: Context, readConfig: () => Config):
39
42
  return { kind: 'error', text: '用法:/enhance <文本>。要增强输入框里的草稿,请用输入框右侧的「增强」按钮或快捷键。' }
40
43
  }
41
44
  // Everything below reads config, and `resolveConfig` throws on the
42
- // invariants the schema cannot express (provider without model, an
43
- // out-of-range value left by hand-editing). Reading it outside the try
45
+ // invariants the schema cannot express (an out-of-range value or a
46
+ // non-boolean switch left by hand-editing). Reading it outside the try
44
47
  // turned those into an uncaught handler throw — the user got a raw
45
48
  // exception instead of the bilingual message the route already shows.
46
49
  try {
@@ -52,13 +55,32 @@ export function registerEnhanceCommand(ctx: Context, readConfig: () => Config):
52
55
  if (!check.ok) {
53
56
  return { kind: 'error', text: formatInputCheckZh(check) }
54
57
  }
55
- const value = await runEnhance(ctx, config, {
56
- text: raw,
57
- sessionRoute: sessionRouteOf(ctx, invocation.agent.session.id),
58
- signal: invocation.signal,
59
- sessionId: invocation.agent.session.id,
60
- })
61
- return { kind: 'success', text: value.text }
58
+ // The command spends the same model budget as the composer button, so it
59
+ // asks the same gate. Admission follows validation: a rejected draft must
60
+ // not consume a window slot.
61
+ const decision = gate.admit(Date.now(), { rateLimitPerMinute: config.rateLimitPerMinute, maxConcurrent: config.maxConcurrent })
62
+ if (!decision.ok) {
63
+ return { kind: 'error', text: formatEnhanceError(decision.error) }
64
+ }
65
+ let outcome: AdmissionOutcome = 'aborted'
66
+ try {
67
+ const value = await runEnhance(ctx, config, {
68
+ text: raw,
69
+ sessionRoute: sessionRouteOf(ctx, invocation.agent.session.id),
70
+ signal: invocation.signal,
71
+ sessionId: invocation.agent.session.id,
72
+ })
73
+ outcome = 'success'
74
+ return { kind: 'success', text: value.text }
75
+ } catch (error) {
76
+ // Classified exactly like the composer route, through the same helper:
77
+ // a cancelled command and a failure the route cannot fix (missing
78
+ // configuration, refused effort) must not feed the breaker.
79
+ outcome = breakerOutcome(invocation.signal.aborted, toEnhanceError(error).code)
80
+ throw error
81
+ } finally {
82
+ gate.settle(outcome, Date.now())
83
+ }
62
84
  } catch (error) {
63
85
  return { kind: 'error', text: formatEnhanceError(toEnhanceError(error)) }
64
86
  }
@@ -8,6 +8,7 @@
8
8
 
9
9
  import type { IncomingMessage, ServerResponse } from 'node:http'
10
10
  import type { Context } from '@deepseek-ai/cordis'
11
+ import { breakerOutcome, type AdmissionGate, type AdmissionOutcome } from './admission'
11
12
  import { ENHANCE_ENDPOINT, ENHANCE_PREFIX, ENHANCE_STREAM_ENDPOINT } from './shared/protocol'
12
13
  import { createStreamNormalizer } from './shared/stream-text'
13
14
  import { createSseWriter } from './sse'
@@ -16,7 +17,7 @@ import { type Config } from './config'
16
17
  import { toEnhanceError } from './enhancer'
17
18
  import { runEnhance, sessionRouteOf } from './orchestrate'
18
19
  import { isTrustedRequest } from './loopback'
19
- import { readBoundedJson, writeJson, endResponse } from './http'
20
+ import { BodyTooLargeError, readBoundedJson, writeJson, endResponse } from './http'
20
21
  import { REASONING_EFFORTS_ENDPOINT } from './shared/reasoning'
21
22
  import { serveReasoningEfforts } from './reasoning-route'
22
23
  import { LLM_MODELS_ENDPOINT, LLM_PROVIDERS_ENDPOINT, LLM_ROUTE_CHECK_ENDPOINT } from './shared/catalog'
@@ -25,36 +26,11 @@ import { serveCatalog } from './catalog-route'
25
26
  /** Envelope slack over the UTF-8 text cap: JSON quoting can inflate ~2-6x in the worst case. */
26
27
  const bodyCapOf = (maxInputChars: number): number => maxInputChars * 6 + 4096
27
28
 
28
- /**
29
- * Consecutive FAILED calls that trip the cool-down, and how long it lasts.
30
- *
31
- * The sliding window below counts successful calls only, so a run of timeouts
32
- * never burns the user's quota (see the gate note in serveEnhance). That
33
- * leaves one hole: a deterministic upstream failure — a wrong API key, a
34
- * mistyped provider, a model the account cannot reach — fails in
35
- * milliseconds, and a retry loop against such a failure is bounded only by
36
- * the concurrency cap, i.e. barely at all. Three consecutive failures are
37
- * enough to tell "the model is flaky" from "this route cannot work", so the
38
- * route pauses instead of hammering the provider.
39
- */
40
- const FAILURE_STREAK_LIMIT = 3
41
- const FAILURE_COOLDOWN_MS = 30_000
42
-
43
- /** Per-mount admission state: sliding-window rate stamps, active-call count, failure breaker. */
44
- interface AdmissionGate {
45
- stamps: number[]
46
- active: number
47
- /** Consecutive failed calls since the last success. */
48
- failures: number
49
- /** Epoch millis until which every call is refused with `cooldown`. */
50
- cooldownUntil: number
51
- }
52
-
53
29
  /**
54
30
  * Serve one enhance POST against the request envelope.
55
31
  * @param ctx - registrant context (llm, optional sessions/settings).
56
32
  * @param readConfig - per-request config reader.
57
- * @param gate - per-mount admission state.
33
+ * @param gate - the shared admission gate (window, concurrency, breaker).
58
34
  * @param pathname - the request path, already parsed by the prefix handler.
59
35
  * @param req - the incoming request.
60
36
  * @param res - the outgoing response.
@@ -100,14 +76,16 @@ async function serveEnhance(ctx: Context, readConfig: () => Config, gate: Admiss
100
76
  // reading a single byte. The streamed cap inside readBoundedJson stays as the
101
77
  // backstop for chunked bodies, which carry no Content-Length at all. A caller
102
78
  // that declares megabytes and dribbles them (or never sends them) must not
103
- // hold the connection open, so the socket is destroyed once the 413 lands.
79
+ // hold the connection open, so the connection is closed once the 413 lands.
104
80
  const cap = bodyCapOf(config.maxInputChars)
105
81
  const declaredLength = Number(req.headers['content-length'])
106
82
  if (Number.isFinite(declaredLength) && declaredLength > cap) {
107
83
  // `connection: close` instead of destroying the socket: the 413 still has
108
84
  // to reach the caller, and a blunt destroy also kills whatever else rides
109
- // this keep-alive connection. Declaring the connection non-reusable lets
110
- // Node discard the unread body and close on its own schedule.
85
+ // this keep-alive connection. Declaring the connection non-reusable is
86
+ // enough: Node flushes the 413, ends the socket right behind it, and never
87
+ // accepts the unread remainder — the caller's later body bytes fail with
88
+ // EPIPE — so nothing here has to be torn down by hand.
111
89
  res.setHeader('connection', 'close')
112
90
  writeJson(res, 413, { ok: false, error: { code: 'rejected', message: '请求体超过大小上限。' } })
113
91
  return
@@ -116,7 +94,14 @@ async function serveEnhance(ctx: Context, readConfig: () => Config, gate: Admiss
116
94
  try {
117
95
  body = await readBoundedJson(req, cap)
118
96
  } catch (error) {
119
- const tooLarge = error instanceof Error && error.message === 'body too large'
97
+ const tooLarge = error instanceof BodyTooLargeError
98
+ // The overflow case left the body unread, so this connection can never carry
99
+ // another request — and measured on node v24.21.0, Node keeps it open with
100
+ // no FIN unless the response says otherwise. Declare it non-reusable exactly
101
+ // like the declared-length fast reject above: the 413 still has to travel,
102
+ // but the socket must not linger after it.
103
+ // Only the 413 closes: the 422 path consumed the body, so it stays reusable.
104
+ if (tooLarge) res.setHeader('connection', 'close')
120
105
  writeJson(res, tooLarge ? 413 : 422, {
121
106
  ok: false,
122
107
  error: { code: 'rejected', message: tooLarge ? '请求体超过大小上限。' : '请求体不是有效的 JSON。' },
@@ -128,6 +113,16 @@ async function serveEnhance(ctx: Context, readConfig: () => Config, gate: Admiss
128
113
  writeJson(res, 422, { ok: false, error: { code: 'rejected', message: '请求体必须是 { sessionId?, text } JSON。' } })
129
114
  return
130
115
  }
116
+ // The session id arrives from the request body and is used as-is for the route
117
+ // hint, the conversation context and GenerateOptions.sessionId. The route is
118
+ // bound to this app's origin (loopback.ts pins the port), but a LOCAL process
119
+ // can still name any EXISTING session and have its recent history sent to the
120
+ // model. Accepted, not fixed: that process already holds the harness
121
+ // credentials and can read the same session from disk, so an ownership check
122
+ // here would only remove an implicit guarantee, not a capability — and an
123
+ // unknown id already degrades to "no route hint, no context" inside
124
+ // orchestrate. Revisit if the browser ever gains a per-session handle the host
125
+ // can verify.
131
126
  const sessionId = typeof record.sessionId === 'string' && record.sessionId !== '' ? record.sessionId : undefined
132
127
  const check = checkInputText(record.text, config.maxInputChars)
133
128
  if (!check.ok) {
@@ -140,60 +135,16 @@ async function serveEnhance(ctx: Context, readConfig: () => Config, gate: Admiss
140
135
  })
141
136
  return
142
137
  }
143
- // Admission gate (after validation, so only real calls consume budget):
144
- // sliding-window rate cap, then concurrency cap. Rejected calls answer 429
145
- // with the configured limits so the user can act.
146
- //
147
- // The rate window counts SUCCESSFUL calls only — a stamp lands after the
148
- // 200 has been written, never on failure. Counting attempts instead would
149
- // burn the user's window on a run of timeouts/upstream errors and lock
150
- // them out right when the model recovers. The concurrency cap below still
151
- // bounds in-flight calls regardless of outcome, so failed calls cannot be
152
- // used to hammer the upstream either.
153
- const now = Date.now()
154
- // Failure breaker first: a host stuck on a broken route must refuse before
155
- // it reads a body or spends a window slot, and the wait is advertised so the
156
- // panel can say when to try again.
157
- if (now < gate.cooldownUntil) {
158
- const retryAfterSeconds = Math.max(1, Math.ceil((gate.cooldownUntil - now) / 1000))
159
- res.setHeader('Retry-After', String(retryAfterSeconds))
160
- writeJson(res, 429, {
161
- ok: false,
162
- error: { code: 'cooldown', params: { retryAfterSeconds, failures: FAILURE_STREAK_LIMIT } },
163
- })
164
- return
165
- }
166
- // Trim the window in one splice instead of a `while (shift)` loop: with the
167
- // configured cap at 600 the worst case drops from O(N²) array shifts to a
168
- // single O(N) relocation. The cap is bounded, so this stays cheap in
169
- // absolute terms; the point is to avoid the quadratic shape on every call.
170
- const stamps = gate.stamps
171
- const cut = now - 60000
172
- let validFrom = 0
173
- while (validFrom < stamps.length && (stamps[validFrom] ?? cut) < cut) validFrom++
174
- if (validFrom > 0) stamps.splice(0, validFrom)
175
- if (stamps.length >= config.rateLimitPerMinute) {
176
- // The window is bounded, so the oldest surviving stamp tells exactly when
177
- // a slot frees up — advertise it instead of making the user guess.
178
- const oldest = stamps[0] ?? now
179
- const retryAfterSeconds = Math.max(1, Math.ceil((60000 - (now - oldest)) / 1000))
180
- res.setHeader('Retry-After', String(retryAfterSeconds))
181
- writeJson(res, 429, {
182
- ok: false,
183
- error: { code: 'rate-limit', params: { limit: config.rateLimitPerMinute, retryAfterSeconds } },
184
- })
138
+ // Admission gate (after validation, so only real calls consume budget). The
139
+ // gate instance is shared with the /enhance command plane — see ./admission.
140
+ const decision = gate.admit(Date.now(), { rateLimitPerMinute: config.rateLimitPerMinute, maxConcurrent: config.maxConcurrent })
141
+ if (!decision.ok) {
142
+ // Advertise the wait only when the gate can predict one (cool-down or rate
143
+ // window); a busy concurrency slot frees whenever some call settles.
144
+ if (decision.retryAfterSeconds !== undefined) res.setHeader('Retry-After', String(decision.retryAfterSeconds))
145
+ writeJson(res, 429, { ok: false, error: decision.error })
185
146
  return
186
147
  }
187
- // No Retry-After here: a busy slot frees whenever some in-flight call
188
- // settles, which is not a delay this route can predict.
189
- if (gate.active >= config.maxConcurrent) {
190
- writeJson(res, 429, {
191
- ok: false,
192
- error: { code: 'concurrency-limit', params: { max: config.maxConcurrent } },
193
- })
194
- return
195
- }
196
- gate.active += 1
197
148
  // Cancel the model call when the browser goes away mid-flight. `res.close`
198
149
  // also fires after a normal response completes, so guard with
199
150
  // `writableEnded` — only a premature close aborts the call.
@@ -202,6 +153,8 @@ async function serveEnhance(ctx: Context, readConfig: () => Config, gate: Admiss
202
153
  if (!res.writableEnded) callerAbort.abort()
203
154
  }
204
155
  res.on('close', onConnectionClosed)
156
+ /** How the admitted call ended; the gate is settled from `finally`. */
157
+ let outcome: AdmissionOutcome = 'aborted'
205
158
  try {
206
159
  const runOptions = {
207
160
  text: record.text,
@@ -254,19 +207,14 @@ async function serveEnhance(ctx: Context, readConfig: () => Config, gate: Admiss
254
207
  // Count only on success: failed calls must not consume the sliding window
255
208
  // (see the gate note above). `Date.now()` at completion, not admission,
256
209
  // keeps the window honest — a slow success still counts as one call.
257
- stamps.push(Date.now())
258
- gate.failures = 0
210
+ outcome = 'success'
259
211
  } catch (error) {
260
- // A caller that walked away is not a failing route: aborting mid-flight
261
- // must never move the breaker toward its cool-down.
262
- if (!callerAbort.signal.aborted) {
263
- gate.failures += 1
264
- if (gate.failures >= FAILURE_STREAK_LIMIT) {
265
- gate.cooldownUntil = Date.now() + FAILURE_COOLDOWN_MS
266
- gate.failures = 0
267
- }
268
- }
269
212
  const wire = toEnhanceError(error)
213
+ // A caller that walked away is not a failing route, and neither is a failure
214
+ // the route itself cannot fix (missing model configuration, a refused
215
+ // effort): `breakerOutcome` decides that once for both entries, so the panel
216
+ // and the command cannot classify the same error differently.
217
+ outcome = breakerOutcome(callerAbort.signal.aborted, wire.code)
270
218
  if (stream && res.headersSent) {
271
219
  // Headers are already out: the failure has to ride the same stream, and
272
220
  // the stream has to be closed the same way the success path closes it.
@@ -286,15 +234,17 @@ async function serveEnhance(ctx: Context, readConfig: () => Config, gate: Admiss
286
234
  }
287
235
  } finally {
288
236
  res.off('close', onConnectionClosed)
289
- gate.active -= 1
237
+ // Release the slot and record how the call ended: a success lands a window
238
+ // stamp, a failure feeds the breaker, a cancellation does neither.
239
+ gate.settle(outcome, Date.now())
290
240
  }
291
241
  }
292
242
 
293
243
  /**
294
- * Contexts that already own the route. The admission gate is created per
295
- * registration, so mounting twice on one context would silently double the
296
- * effective limits — exactly the drift a re-applied plugin (reload, re-link)
297
- * must not introduce.
244
+ * Contexts that already own the route. A second registration on one context
245
+ * would answer the same path twice, and it would spend the shared admission
246
+ * gate twice per request — exactly the drift a re-applied plugin (reload,
247
+ * re-link) must not introduce.
298
248
  *
299
249
  * The recorded mount carries the webserver it was registered on: if the host
300
250
  * ever rebuilds that service while reusing the same context, a bare "already
@@ -329,8 +279,10 @@ const mounts = new WeakMap<Context, RouteMount>()
329
279
  *
330
280
  * @param ctx - registrant context.
331
281
  * @param readConfig - per-request config reader so settings changes apply immediately.
282
+ * @param gate - the admission gate shared with the /enhance command plane, so
283
+ * both entries are capped by the same window, concurrency cap and breaker.
332
284
  */
333
- export function registerEnhanceRoute(ctx: Context, readConfig: () => Config): void {
285
+ export function registerEnhanceRoute(ctx: Context, readConfig: () => Config, gate: AdmissionGate): void {
334
286
  ctx.inject(['webServer'], (routeCtx: Context) => {
335
287
  const webserver = routeCtx.get('webServer') as unknown as
336
288
  | {
@@ -353,7 +305,6 @@ export function registerEnhanceRoute(ctx: Context, readConfig: () => Config): vo
353
305
  }
354
306
  mounts.delete(ctx)
355
307
  }
356
- const gate: AdmissionGate = { stamps: [], active: 0, failures: 0, cooldownUntil: 0 }
357
308
  routeCtx.effect(() => {
358
309
  const dispose = webserver.register({
359
310
  kind: 'prefix',