@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.
@@ -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()