@surfishs/dsh-prompt-enhance 0.0.9 → 0.1.1

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.
@@ -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',
package/src/enhancer.ts CHANGED
@@ -6,8 +6,7 @@
6
6
  * @module dsh-prompt-enhance/enhancer
7
7
  */
8
8
 
9
- import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'
10
- import type { GenerateOptions, FinishReason, StreamChunk } from '@deepseek-ai/dsh-llm'
9
+ import type { BlockAssembler, FinishReason, GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
11
10
  import type { EnhanceError, EnhanceResult } from './shared/protocol'
12
11
  import { normalizeOutput } from './shared/normalize'
13
12
  import { frameUserPrompt } from './prompts'
@@ -29,6 +28,30 @@ declare module '@deepseek-ai/dsh-llm' {
29
28
  }
30
29
  }
31
30
 
31
+ /** The host's LLM module namespace, imported lazily (see {@link loadLlmRuntime}). */
32
+ type LlmRuntimeModule = typeof import('@deepseek-ai/dsh-llm')
33
+
34
+ /** Cached lazy import, so the module is resolved once per process. */
35
+ let llmRuntimePromise: Promise<LlmRuntimeModule> | undefined
36
+
37
+ /**
38
+ * Load the harness LLM module on first use.
39
+ *
40
+ * `@deepseek-ai/dsh-llm` is a HOST-supplied module, declared as an OPTIONAL
41
+ * peer on purpose: npm must not install it into the profile, because the host
42
+ * resolves it from its own tree and a profile copy would be a different
43
+ * instance than the adapter that produces the stream chunks. A top-level value
44
+ * import broke that contract in the other direction — a host without the module
45
+ * failed to LOAD this plugin instead of failing one call, which is exactly what
46
+ * "optional peer" says must not happen. Imported lazily, the absence surfaces
47
+ * as an ordinary enhancement error and every other surface keeps working.
48
+ * @returns the module namespace, cached for the process lifetime.
49
+ */
50
+ function loadLlmRuntime(): Promise<LlmRuntimeModule> {
51
+ llmRuntimePromise ??= import('@deepseek-ai/dsh-llm')
52
+ return llmRuntimePromise
53
+ }
54
+
32
55
  /** Structural LLM face so tests stub the stream without a Cordis runtime. */
33
56
  export interface LlmStreamFace {
34
57
  stream(options: GenerateOptions): AsyncIterable<StreamChunk>
@@ -95,8 +118,10 @@ export interface EnhanceCallOptions {
95
118
  context?: string
96
119
  /**
97
120
  * Receives each text delta as the model produces it (display only). May be
98
- * async — the streaming route's sink awaits socket backpressure. A throw, or
99
- * a rejected promise, is swallowed: a broken display path must never fail
121
+ * async — the streaming route's sink awaits socket backpressure, and this
122
+ * call AWAITS the returned promise before pulling the next delta, so a slow
123
+ * reader slows the model stream instead of letting frames queue up. A throw,
124
+ * or a rejected promise, is swallowed: a broken display path must never fail
100
125
  * the enhancement itself.
101
126
  */
102
127
  onDelta?: (delta: string) => void | Promise<void>
@@ -135,8 +160,18 @@ export async function enhanceText(llm: LlmStreamFace, options: EnhanceCallOption
135
160
  }
136
161
  try {
137
162
  signal.throwIfAborted()
163
+ let runtime: LlmRuntimeModule
164
+ try {
165
+ runtime = await loadLlmRuntime()
166
+ } catch (error) {
167
+ // The optional peer is absent on this host: fail THIS call with a
168
+ // readable detail, instead of having failed to load the plugin at all.
169
+ return fail({ code: 'internal', message: `harness LLM module unavailable: ${describe(error)}` })
170
+ }
171
+ const createMessage = runtime.createUserMessage
172
+ const BlockAssemblerClass = runtime.BlockAssembler
138
173
  const messages = [
139
- createUserMessage({
174
+ createMessage({
140
175
  content: [{ type: 'text', text: frameUserPrompt(options.text, options.context) }],
141
176
  source: { kind: 'dsh-prompt-enhance' },
142
177
  }),
@@ -166,7 +201,7 @@ export async function enhanceText(llm: LlmStreamFace, options: EnhanceCallOption
166
201
  ...(effort === 'inherit' ? {} : { reasoningEffort: effort as NonNullable<GenerateOptions['reasoningEffort']> }),
167
202
  ...(options.sessionId !== undefined ? { sessionId: options.sessionId as GenerateOptions['sessionId'] } : {}),
168
203
  }
169
- const assembler = new BlockAssembler()
204
+ const assembler = new BlockAssemblerClass()
170
205
  const iterator = llm.stream(generate)[Symbol.asyncIterator]()
171
206
  // Race the iteration against the deadline: an adapter that stalls without
172
207
  // yielding must still hit the timeout (per-chunk checks alone would hang).
@@ -193,15 +228,29 @@ export async function enhanceText(llm: LlmStreamFace, options: EnhanceCallOption
193
228
  // Display-only tap: the stream already arrives incrementally, so the
194
229
  // panel can show the rewrite as it is written instead of waiting for
195
230
  // the final normalization.
196
- if (next.value.type === 'text-delta' && options.onDelta !== undefined) {
197
- try {
198
- // The sink may be async (the SSE route awaits socket drain), so a
199
- // rejected promise is attached here too — an unhandled rejection
200
- // from a display-only path must not surface as a process warning.
201
- void Promise.resolve(options.onDelta(next.value.text)).catch(() => {})
202
- } catch {
203
- // Never let a broken display path fail the enhancement.
204
- }
231
+ const onDelta = options.onDelta
232
+ if (next.value.type === 'text-delta' && onDelta !== undefined) {
233
+ // Narrowed here, outside the promise callback below: the union
234
+ // narrowing from this `if` does not survive into a closure.
235
+ const delta = next.value.text
236
+ // AWAITED, not fire-and-forget — this is the backpressure link.
237
+ // The SSE route's sink resolves only once the frame has been handed
238
+ // to the socket with buffer room left (see createSseWriter), so
239
+ // awaiting it parks this loop: the model is not asked for the next
240
+ // delta while the reader is still draining. Dropping the promise
241
+ // made that guarantee true only on paper; frames simply queued in
242
+ // the socket buffer instead.
243
+ //
244
+ // The race keeps the deadline honest. This await sits outside the
245
+ // `iterator.next()` race above, so a reader that neither drains nor
246
+ // closes would otherwise pin the call past `timeoutMs`; `aborted`
247
+ // rejects on timeout/cancel and ends the attempt with the mapped
248
+ // error, exactly as it does for a stalled stream.
249
+ const sink = Promise.resolve()
250
+ .then(() => onDelta(delta))
251
+ // A broken display path must never fail the enhancement.
252
+ .catch(() => {})
253
+ await Promise.race([sink, aborted])
205
254
  }
206
255
  }
207
256
  } finally {
package/src/http.ts CHANGED
@@ -8,11 +8,42 @@
8
8
  import type { IncomingMessage, ServerResponse } from 'node:http'
9
9
 
10
10
  /**
11
- * Read a request body of at most `maxBytes` and parse it as JSON. On overflow
12
- * the reader stops consuming and throws WITHOUT destroying the request — the
13
- * route still owes the client a deliverable 413 response. Node discards the
14
- * unread remainder and closes the connection after the response ends.
15
- * @throws 'body too large' past the cap, or the JSON.parse error otherwise.
11
+ * Read a request body of at most `maxBytes` and parse it as JSON.
12
+ *
13
+ * On overflow the throw leaves the `for await` loop, and closing that loop
14
+ * closes the async iterator — which a Node Readable does by destroying itself.
15
+ * The request is therefore destroyed and marked `aborted`, and the unread
16
+ * remainder is never consumed. The response socket outlives it (measured on node
17
+ * v24.21.0), so the caller can still be answered, but nothing ends the half-read
18
+ * request on the connection's behalf: the 413 path has to declare
19
+ * `connection: close` itself, or the socket stays open with no FIN until Node's
20
+ * request timeout reaps it.
21
+ * @throws {@link BodyTooLargeError} past the cap, or the JSON.parse error otherwise.
22
+ */
23
+
24
+ /**
25
+ * The request body exceeded the route's cap.
26
+ *
27
+ * A class, not a message: callers must be able to tell this apart from a parse
28
+ * error without matching text, so re-wording the message here cannot silently
29
+ * turn a 413 into a 422.
30
+ */
31
+ export class BodyTooLargeError extends Error {
32
+ /** Stable discriminant for `instanceof`-free checks across realms. */
33
+ readonly code = 'body-too-large'
34
+
35
+ constructor() {
36
+ super('body too large')
37
+ this.name = 'BodyTooLargeError'
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Read a JSON request body, refusing anything past `maxBytes`.
43
+ * @param req - the incoming request.
44
+ * @param maxBytes - the cap in bytes.
45
+ * @returns the parsed JSON body.
46
+ * @throws {@link BodyTooLargeError} past the cap, or the JSON.parse error otherwise.
16
47
  */
17
48
  export async function readBoundedJson(req: IncomingMessage, maxBytes: number): Promise<unknown> {
18
49
  const chunks: Buffer[] = []
@@ -20,7 +51,7 @@ export async function readBoundedJson(req: IncomingMessage, maxBytes: number): P
20
51
  for await (const chunk of req) {
21
52
  const buffer = chunk as Buffer
22
53
  size += buffer.length
23
- if (size > maxBytes) throw new Error('body too large')
54
+ if (size > maxBytes) throw new BodyTooLargeError()
24
55
  chunks.push(buffer)
25
56
  }
26
57
  return JSON.parse(Buffer.concat(chunks).toString('utf8'))
package/src/index.ts CHANGED
@@ -10,6 +10,7 @@
10
10
 
11
11
  import type { Context } from '@deepseek-ai/cordis'
12
12
  import { Config, DEFAULT_CONFIG, PROMPT_ENHANCE_NAMESPACE, resolveConfig, type Config as PluginConfig } from './config'
13
+ import { AdmissionGate } from './admission'
13
14
  import { installSettingsSource } from './settings-source'
14
15
  import { PROMPT_ENHANCE_ROW_IDS } from './shared/protocol'
15
16
  import { registerEnhanceRoute } from './enhance-routes'
@@ -83,6 +84,9 @@ export function apply(ctx: Context, config: PluginConfig = { ...DEFAULT_CONFIG }
83
84
  // normalized form (trimmed provider/model, stripped legacy keys, validated
84
85
  // ranges) — the validate hook only refuses bad values, it never transforms.
85
86
  const readConfig = (): PluginConfig => resolveConfig(source.read() as PluginConfig)
86
- registerEnhanceRoute(ctx, readConfig)
87
- registerEnhanceCommand(ctx, readConfig)
87
+ // One admission gate per plugin instance, shared by both entries that can
88
+ // spend a model call: the composer route and the /enhance command plane.
89
+ const gate = new AdmissionGate()
90
+ registerEnhanceRoute(ctx, readConfig, gate)
91
+ registerEnhanceCommand(ctx, readConfig, gate)
88
92
  }