@surfishs/dsh-prompt-enhance 0.0.9 → 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.
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
  }
@@ -3,22 +3,45 @@
3
3
  *
4
4
  * The browser origin changes whenever the desktop app restarts on another port,
5
5
  * so a `localStorage` cache cannot be the durable tier memory the user asked
6
- * for. This cache lives in the DeepSeek Harness home directory instead, keyed
7
- * by provider/model, with no TTL: an entry is replaced only by a manual refresh
8
- * or by a different pair.
6
+ * for. This cache lives in the DeepSeek Harness home directory instead, with one
7
+ * file per provider/model pair.
8
+ *
9
+ * One file per pair, not one shared document: the old layout rewrote the whole
10
+ * document on every write, so two processes writing DIFFERENT pairs raced on
11
+ * that document and the later write silently dropped the earlier pair. Per-pair
12
+ * files remove that cross-key race; the only contention left is two processes
13
+ * writing the SAME pair, which carries the same answer.
14
+ *
15
+ * Entries expire after {@link CACHE_TTL_MS}: a model's declared tiers change
16
+ * when the adapter does, and a stale negative answer ("declares no tiers") would
17
+ * otherwise keep suppressing the user's configured effort forever, with no error
18
+ * to point at it. The previous single-document file
19
+ * (`reasoning-efforts.json`) is ignored rather than migrated — it is only a
20
+ * cache, so the first enhancement after the upgrade pays one extra probe.
9
21
  * @module dsh-prompt-enhance/reasoning-cache
10
22
  */
11
23
 
12
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
24
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
13
25
  import { homedir } from 'node:os'
14
26
  import { dirname, join } from 'node:path'
15
27
  import type { ReasoningEffortInfo } from './shared/reasoning'
16
28
 
17
- /** Cache document version; a mismatch is treated as an empty cache. */
29
+ /** On-disk format version of one cache file; a mismatch is treated as absent. */
18
30
  const CACHE_VERSION = 1
19
31
 
20
- /** One cached answer. */
32
+ /**
33
+ * How long one answer stays usable.
34
+ *
35
+ * Tier metadata is model capability data, so it changes only when the adapter
36
+ * changes — slowly, hence a generous window. Without an expiry, the negative
37
+ * answer ("this route declares no tiers") would keep overriding the user's
38
+ * configured effort even after the model gained tiers.
39
+ */
40
+ export const CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000
41
+
42
+ /** One cached answer as stored on disk. */
21
43
  interface CacheEntry {
44
+ version: number
22
45
  provider: string
23
46
  model: string
24
47
  efforts: ReasoningEffortInfo[]
@@ -28,12 +51,6 @@ interface CacheEntry {
28
51
  savedAt: number
29
52
  }
30
53
 
31
- /** The whole cache document. */
32
- interface CacheDocument {
33
- version: number
34
- entries: Record<string, CacheEntry>
35
- }
36
-
37
54
  /** One cached answer without the bookkeeping fields. */
38
55
  export interface CachedReasoningEfforts {
39
56
  efforts: ReasoningEffortInfo[]
@@ -48,12 +65,26 @@ function harnessHome(): string {
48
65
  return configured === '' ? join(homedir(), '.dsh') : configured
49
66
  }
50
67
 
51
- /** Absolute path of the cache document. */
52
- export function cacheFilePath(): string {
53
- return join(harnessHome(), 'dsh-prompt-enhance', 'reasoning-efforts.json')
68
+ /** Directory holding one file per provider/model pair. */
69
+ export function cacheDirectory(): string {
70
+ return join(harnessHome(), 'dsh-prompt-enhance', 'reasoning-efforts')
54
71
  }
55
72
 
56
- /** Stable key of one pair. */
73
+ /**
74
+ * Absolute path of one pair's cache file.
75
+ *
76
+ * Both halves are percent-encoded and kept as separate path segments: provider
77
+ * and model ids routinely carry `/`, `:` and spaces (e.g. `anthropic/claude-3`),
78
+ * which are illegal in a Windows file name.
79
+ * @param provider - provider id.
80
+ * @param model - model id.
81
+ * @returns the file path.
82
+ */
83
+ export function cacheFilePath(provider: string, model: string): string {
84
+ return join(cacheDirectory(), encodeURIComponent(provider), `${encodeURIComponent(model)}.json`)
85
+ }
86
+
87
+ /** Stable key of one pair (memo key and log identity). */
57
88
  function entryKey(provider: string, model: string): string {
58
89
  return `${provider}/${model}`
59
90
  }
@@ -70,75 +101,131 @@ function effortOf(value: unknown): ReasoningEffortInfo | undefined {
70
101
  }
71
102
  }
72
103
 
73
- /** Read the document, treating any unreadable/corrupt file as empty. */
74
- async function readDocument(): Promise<CacheDocument> {
104
+ /**
105
+ * In-process memo of resolved answers, one per provider/model pair.
106
+ *
107
+ * `effectiveReasoningEffort` runs on every enhancement, on the critical path
108
+ * before the model call, and used to read + parse a cache file each time. The
109
+ * cache only changes through this module, so once a process has seen an answer it
110
+ * can serve from memory; a write primes the memo and a manual refresh drops it.
111
+ * A miss is deliberately NOT memoized: an entry written by another process would
112
+ * otherwise stay invisible for this process's lifetime.
113
+ */
114
+ const memo = new Map<string, CachedReasoningEfforts>()
115
+
116
+ /**
117
+ * Harness home the memo's answers belong to. A different home means different
118
+ * cache files, so the memo must start empty instead of answering for a
119
+ * deployment it never read. (Tests point DSH_HOME at a fresh directory per case;
120
+ * this is what keeps them from seeing each other's answers.)
121
+ */
122
+ let memoHome: string | undefined
123
+
124
+ /**
125
+ * The memo for the CURRENT cache directory, dropped when the home moves.
126
+ * @returns the live memo map.
127
+ */
128
+ function memoFor(): Map<string, CachedReasoningEfforts> {
129
+ const home = harnessHome()
130
+ if (memoHome !== home) {
131
+ memo.clear()
132
+ memoHome = home
133
+ }
134
+ return memo
135
+ }
136
+
137
+ /**
138
+ * Drop one expired file without letting the cleanup decide the read's outcome.
139
+ * @param path - the file to remove.
140
+ */
141
+ async function dropExpired(path: string): Promise<void> {
75
142
  try {
76
- const raw = await readFile(cacheFilePath(), 'utf8')
77
- const parsed: unknown = JSON.parse(raw)
78
- if (parsed === null || typeof parsed !== 'object') return { version: CACHE_VERSION, entries: {} }
79
- const record = parsed as { version?: unknown; entries?: unknown }
80
- if (record.version !== CACHE_VERSION || record.entries === null || typeof record.entries !== 'object') {
81
- return { version: CACHE_VERSION, entries: {} }
82
- }
83
- return { version: CACHE_VERSION, entries: record.entries as Record<string, CacheEntry> }
143
+ await rm(path, { force: true })
84
144
  } catch {
85
- return { version: CACHE_VERSION, entries: {} }
145
+ // A cache directory we cannot write is not a reason to fail the read.
86
146
  }
87
147
  }
88
148
 
89
- /** Atomically replace the document (temp file in the same directory + rename). */
90
- async function writeDocument(document: CacheDocument): Promise<void> {
91
- const path = cacheFilePath()
149
+ /**
150
+ * Read one pair's file, honouring the TTL and the on-disk version.
151
+ * @param provider - provider id.
152
+ * @param model - model id.
153
+ * @returns the cached efforts, or undefined when absent/expired/malformed.
154
+ */
155
+ async function readEntryFile(provider: string, model: string): Promise<CachedReasoningEfforts | undefined> {
156
+ const path = cacheFilePath(provider, model)
92
157
  try {
93
- await mkdir(dirname(path), { recursive: true })
94
- const temporary = `${path}.${process.pid}.tmp`
95
- await writeFile(temporary, JSON.stringify(document), 'utf8')
96
- await rename(temporary, path)
158
+ const entry = JSON.parse(await readFile(path, 'utf8')) as Partial<CacheEntry> | null
159
+ if (entry === null || typeof entry !== 'object') return undefined
160
+ if (entry.version !== CACHE_VERSION || entry.provider !== provider || entry.model !== model) return undefined
161
+ if (typeof entry.savedAt !== 'number' || Date.now() - entry.savedAt > CACHE_TTL_MS) {
162
+ // Expired (or undated): answer as absent and drop the file so the next
163
+ // read does not pay for it again.
164
+ await dropExpired(path)
165
+ return undefined
166
+ }
167
+ // A negative answer is cached too: routes that declare no reasoning would
168
+ // otherwise pay a capability lookup on every enhancement call.
169
+ if (entry.noEfforts === true) return { efforts: [], noEfforts: true }
170
+ if (!Array.isArray(entry.efforts) || entry.efforts.length === 0) return undefined
171
+ const efforts = entry.efforts.map(effortOf).filter((effort): effort is ReasoningEffortInfo => effort !== undefined)
172
+ if (efforts.length !== entry.efforts.length) return undefined
173
+ return {
174
+ efforts,
175
+ ...(typeof entry.defaultEffort === 'string' && entry.defaultEffort !== '' ? { defaultEffort: entry.defaultEffort } : {}),
176
+ }
97
177
  } catch {
98
- // The cache is an optimization; a read-only home must not fail the route.
178
+ return undefined
99
179
  }
100
180
  }
101
181
 
102
182
  /**
103
- * Read one cached answer.
183
+ * Read one cached answer, from the in-process memo when this process already
184
+ * resolved it, from its own file otherwise.
104
185
  * @param provider - provider id.
105
186
  * @param model - model id.
106
- * @returns the cached efforts, or undefined when absent/malformed.
187
+ * @returns the cached efforts, or undefined when absent/expired/malformed.
107
188
  */
108
189
  export async function readCachedCapabilities(provider: string, model: string): Promise<CachedReasoningEfforts | undefined> {
109
- const document = await readDocument()
110
- const entry = document.entries[entryKey(provider, model)]
111
- if (entry === undefined || entry.provider !== provider || entry.model !== model) return undefined
112
- // A negative answer is cached too: routes that declare no reasoning would
113
- // otherwise pay a capability lookup on every enhancement call.
114
- if (entry.noEfforts === true) return { efforts: [], noEfforts: true }
115
- if (!Array.isArray(entry.efforts) || entry.efforts.length === 0) return undefined
116
- const efforts = entry.efforts.map(effortOf).filter((effort): effort is ReasoningEffortInfo => effort !== undefined)
117
- if (efforts.length !== entry.efforts.length) return undefined
118
- return {
119
- efforts,
120
- ...(typeof entry.defaultEffort === 'string' && entry.defaultEffort !== '' ? { defaultEffort: entry.defaultEffort } : {}),
121
- }
190
+ const known = memoFor().get(entryKey(provider, model))
191
+ if (known !== undefined) return known
192
+ const answer = await readEntryFile(provider, model)
193
+ if (answer !== undefined) memoFor().set(entryKey(provider, model), answer)
194
+ return answer
122
195
  }
123
196
 
124
197
  /**
125
- * Persist one resolved answer.
198
+ * Persist one resolved answer, one file per pair.
126
199
  * @param provider - provider id.
127
200
  * @param model - model id.
128
201
  * @param efforts - the adapter-declared efforts.
129
202
  * @param defaultEffort - the adapter's default, when declared.
203
+ * @param noEfforts - true when the route declares no reasoning at all.
130
204
  */
131
205
  export async function writeCachedCapabilities(provider: string, model: string, efforts: ReasoningEffortInfo[], defaultEffort?: string, noEfforts = false): Promise<void> {
132
- const document = await readDocument()
133
- document.entries[entryKey(provider, model)] = {
134
- provider,
135
- model,
136
- efforts,
137
- ...(defaultEffort === undefined ? {} : { defaultEffort }),
138
- ...(noEfforts ? { noEfforts: true } : {}),
139
- savedAt: Date.now(),
206
+ const path = cacheFilePath(provider, model)
207
+ try {
208
+ await mkdir(dirname(path), { recursive: true })
209
+ const entry: CacheEntry = {
210
+ version: CACHE_VERSION,
211
+ provider,
212
+ model,
213
+ efforts,
214
+ ...(defaultEffort === undefined ? {} : { defaultEffort }),
215
+ ...(noEfforts ? { noEfforts: true } : {}),
216
+ savedAt: Date.now(),
217
+ }
218
+ // Temp file in the same directory + rename: a reader never sees a partial
219
+ // write, and two writers of the same pair cannot interleave their bytes.
220
+ const temporary = `${path}.${process.pid}.tmp`
221
+ await writeFile(temporary, JSON.stringify(entry), 'utf8')
222
+ await rename(temporary, path)
223
+ } catch {
224
+ // The cache is an optimization; a read-only home must not fail the route.
140
225
  }
141
- await writeDocument(document)
226
+ // Prime the memo with exactly what a read would return, so the next
227
+ // enhancement answers from memory instead of re-reading the file.
228
+ memoFor().set(entryKey(provider, model), noEfforts ? { efforts: [], noEfforts: true } : { efforts, ...(defaultEffort === undefined ? {} : { defaultEffort }) })
142
229
  }
143
230
 
144
231
  /**
@@ -147,7 +234,10 @@ export async function writeCachedCapabilities(provider: string, model: string, e
147
234
  * @param model - model id.
148
235
  */
149
236
  export async function clearCachedCapabilities(provider: string, model: string): Promise<void> {
150
- const document = await readDocument()
151
- delete document.entries[entryKey(provider, model)]
152
- await writeDocument(document)
237
+ try {
238
+ await rm(cacheFilePath(provider, model), { force: true })
239
+ } catch {
240
+ // Nothing to clear.
241
+ }
242
+ memoFor().delete(entryKey(provider, model))
153
243
  }
@@ -8,27 +8,39 @@
8
8
  /** Three or more consecutive newlines collapse to one blank line. */
9
9
  const EXCESS_BLANK_LINES = /\n{3,}/g
10
10
 
11
+ /** One code-fence mark. */
12
+ const FENCE = '```'
13
+
11
14
  /**
12
- * Normalize one model output into the final enhanced prompt body. A wrapping
13
- * code fence is stripped when the text starts with one, ends with one, and
14
- * contains exactly two fence marks (open + close) — this also covers
15
- * single-line fences like `` ```角色:翻译``` ``. Fences anywhere else are part
16
- * of the content (e.g. multiple code blocks) and must survive untouched.
15
+ * Normalize one model output into the final enhanced prompt body.
16
+ *
17
+ * A single fence PAIR that ends the answer is a wrapper and is stripped, even
18
+ * when the model prefixed it with a lead-in line ("以下是改写后的提示词:") —
19
+ * that lead-in used to stay glued to the fence, so the raw ``` reached the
20
+ * composer. This also covers single-line fences like `` ```角色:翻译``` ``.
21
+ *
22
+ * Two boundaries keep the lenient rule from corrupting real content:
23
+ * - the pair must be the ONLY one in the text (a rewritten prompt that shows
24
+ * several code blocks keeps all of them);
25
+ * - nothing but whitespace may follow the closing fence. Text after the block
26
+ * means the block is the model's content, not a wrapper around the answer.
17
27
  * @param raw - the assembled text output of the model.
18
28
  * @returns the normalized body; empty string when nothing usable remains.
19
29
  */
20
30
  export function normalizeOutput(raw: string): string {
21
31
  let text = raw.trim()
22
32
  const fenceMarkCount = (text.match(/```/g) ?? []).length
23
- if (text.startsWith('```') && /```[\s]*$/.test(text) && fenceMarkCount === 2) {
24
- if (text.includes('\n')) {
25
- text = text
26
- .slice(text.indexOf('\n') + 1)
27
- .replace(/```[\s]*$/, '')
28
- .trim()
29
- } else {
30
- text = text.slice(3, -3).trim()
31
- }
33
+ if (fenceMarkCount === 2 && /```[\s]*$/.test(text)) {
34
+ const open = text.indexOf(FENCE)
35
+ const close = text.indexOf(FENCE, open + FENCE.length)
36
+ // Everything before the opening fence is the lead-in, if the model wrote
37
+ // one; everything between the newline after the fence and the closing mark
38
+ // is the body (the tail of the opening line is its language tag).
39
+ const lead = text.slice(0, open).trim()
40
+ const afterFence = text.slice(open + FENCE.length, close)
41
+ const firstNewline = afterFence.indexOf('\n')
42
+ const body = (firstNewline === -1 ? afterFence : afterFence.slice(firstNewline + 1)).trim()
43
+ text = lead === '' ? body : `${lead}\n${body}`
32
44
  }
33
45
  text = text.replace(EXCESS_BLANK_LINES, '\n\n')
34
46
  return text.trim()