@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.
- package/README.en.md +33 -19
- package/README.md +33 -19
- package/docs/images/panel-en-915.png +0 -0
- package/docs/images/panel.png +0 -0
- package/icon.svg +14 -0
- package/lib/client.js +123 -68
- package/lib/index.js +208 -131
- package/lib/index.js.map +3 -3
- package/package.json +5 -2
- package/src/admission.ts +146 -0
- package/src/client/EnhanceButton.tsx +34 -15
- package/src/client/ResultDock.tsx +1 -1
- package/src/client/SparkleFishIcon.tsx +22 -7
- package/src/client/UndoBar.tsx +1 -1
- package/src/client/enhance-client.ts +6 -0
- package/src/client/globals.d.ts +3 -0
- package/src/client/locales.ts +5 -4
- package/src/client/settings-page-spec.ts +9 -1
- package/src/client/styles.ts +34 -30
- package/src/client/useDockAlignment.ts +128 -44
- package/src/config.ts +28 -22
- package/src/enhance-command.ts +32 -10
- package/src/enhance-routes.ts +52 -101
- package/src/enhancer.ts +64 -15
- package/src/http.ts +37 -6
- package/src/index.ts +6 -2
- package/src/reasoning-cache.ts +153 -63
- package/src/shared/normalize.ts +26 -14
- package/src/client/SparkleIcon.tsx +0 -23
package/src/enhancer.ts
CHANGED
|
@@ -6,8 +6,7 @@
|
|
|
6
6
|
* @module dsh-prompt-enhance/enhancer
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import { BlockAssembler,
|
|
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
|
|
99
|
-
*
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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.
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
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
|
|
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
|
-
|
|
87
|
-
|
|
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
|
}
|
package/src/reasoning-cache.ts
CHANGED
|
@@ -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,
|
|
7
|
-
*
|
|
8
|
-
*
|
|
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
|
-
/**
|
|
29
|
+
/** On-disk format version of one cache file; a mismatch is treated as absent. */
|
|
18
30
|
const CACHE_VERSION = 1
|
|
19
31
|
|
|
20
|
-
/**
|
|
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
|
-
/**
|
|
52
|
-
export function
|
|
53
|
-
return join(harnessHome(), 'dsh-prompt-enhance', 'reasoning-efforts
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
74
|
-
|
|
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
|
-
|
|
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
|
-
|
|
145
|
+
// A cache directory we cannot write is not a reason to fail the read.
|
|
86
146
|
}
|
|
87
147
|
}
|
|
88
148
|
|
|
89
|
-
/**
|
|
90
|
-
|
|
91
|
-
|
|
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
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
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
|
-
|
|
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
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
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
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
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
|
-
|
|
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
|
-
|
|
151
|
-
|
|
152
|
-
|
|
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
|
}
|
package/src/shared/normalize.ts
CHANGED
|
@@ -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.
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
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 (
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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()
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The two-star sparkle used for the enhance action: one large four-point star
|
|
3
|
-
* at the upper left and a smaller companion at the lower right. The path is
|
|
4
|
-
* taken from the icon the user supplied from sharednai5.pro, which matches the
|
|
5
|
-
* mark NovelAI's image toolbar uses for its enhance action.
|
|
6
|
-
* @module dsh-prompt-enhance/client/SparkleIcon
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
import type { ReactElement } from 'react'
|
|
10
|
-
|
|
11
|
-
/** A sparkle sized to its container, painted with the current text color. */
|
|
12
|
-
export function SparkleIcon(props: { size?: number; spinning?: boolean }): ReactElement {
|
|
13
|
-
const size = props.size ?? 15
|
|
14
|
-
return (
|
|
15
|
-
<svg width={size} height={size} viewBox="0 0 16 16" fill="none" aria-hidden="true" focusable="false" style={{ display: 'block', flexShrink: 0 }}>
|
|
16
|
-
<path
|
|
17
|
-
d="M5.02692 11.2125C5.22842 11.3544 5.46898 11.4303 5.71542 11.4297C5.96186 11.429 6.20204 11.352 6.40284 11.2091C6.60626 11.0605 6.76053 10.8547 6.8451 10.617L7.35593 9.0477C7.4867 8.65418 7.70731 8.29654 8.00029 8.00312C8.29327 7.7097 8.65056 7.48856 9.04383 7.35724L10.6335 6.8429C10.8685 6.7578 11.0709 6.60108 11.2121 6.39484C11.3534 6.1886 11.4264 5.94323 11.4208 5.6933C11.4153 5.44337 11.3315 5.20148 11.1812 5.00172C11.0309 4.80196 10.8217 4.65439 10.5832 4.57981L9.01183 4.06776C8.61813 3.9372 8.26027 3.71665 7.96668 3.4236C7.67308 3.13056 7.45184 2.77309 7.3205 2.37959L6.80396 0.793139C6.72078 0.559416 6.56684 0.357433 6.36355 0.215288C6.16025 0.0731435 5.91772 -0.0020932 5.66968 4.43152e-05C5.42164 0.00218183 5.18044 0.0815873 4.97962 0.227214C4.77881 0.372841 4.62837 0.577448 4.54923 0.81257L4.02697 2.41273C3.89617 2.79564 3.68006 3.1438 3.39497 3.43091C3.10989 3.71803 2.76329 3.93657 2.38135 4.07005L0.792873 4.58096C0.559281 4.66432 0.357437 4.81836 0.215361 5.02168C0.0732858 5.225 -0.00197096 5.46752 3.92466e-05 5.71557C0.00204945 5.96362 0.0812268 6.20489 0.226579 6.40588C0.371931 6.60687 0.576246 6.75762 0.811157 6.83719L2.38135 7.34581C2.77671 7.47731 3.13575 7.69966 3.42967 7.99502C3.72359 8.29038 3.94421 8.65052 4.07383 9.04656L4.59037 10.6364C4.67265 10.8696 4.82579 11.0708 5.02692 11.2125ZM12.0402 15.8324C12.1571 15.9146 12.2915 15.9685 12.4328 15.9897C12.5742 16.011 12.7185 15.9991 12.8544 15.955C12.9903 15.9109 13.1141 15.8357 13.2159 15.7355C13.3178 15.6352 13.395 15.5127 13.4413 15.3775L13.7247 14.5065C13.7857 14.3259 13.8874 14.1617 14.0218 14.0265C14.1567 13.8893 14.3212 13.7888 14.5018 13.7293L15.384 13.4413C15.5661 13.3784 15.7237 13.2597 15.8342 13.102C15.9448 12.9443 16.0028 12.7557 16.0099 12.5631C15.997 12.3705 15.9333 12.1838 15.818 12.0295C15.7027 11.8752 15.5416 11.7613 15.3578 11.704L14.4847 11.4182C14.3039 11.3581 14.1397 11.2569 14.0048 11.1224C13.8699 10.9879 13.7682 10.8239 13.7076 10.6433L13.4196 9.75977C13.3577 9.57805 13.2403 9.42041 13.0839 9.30918C12.9275 9.19795 12.74 9.13877 12.5481 9.14003C12.3562 9.1413 12.1695 9.20294 12.0146 9.31622C11.8596 9.42951 11.7443 9.58869 11.6848 9.7712L11.4026 10.6421C11.3444 10.8214 11.2455 10.9847 11.1136 11.1194C10.9818 11.254 10.8206 11.3563 10.6426 11.4182L9.75922 11.7063C9.57745 11.7679 9.41968 11.8851 9.30827 12.0414C9.19685 12.1977 9.13744 12.3851 9.13845 12.5771C9.13946 12.769 9.20085 12.9558 9.3139 13.1109C9.42696 13.266 9.58596 13.3816 9.76836 13.4413L10.6403 13.7236C10.8232 13.7853 10.9877 13.8871 11.1226 14.0219C11.2586 14.1579 11.3591 14.3225 11.4174 14.5043L11.7065 15.3889C11.7691 15.5678 11.8857 15.7227 12.0402 15.8324Z"
|
|
18
|
-
fill="currentColor"
|
|
19
|
-
/>
|
|
20
|
-
{props.spinning === true ? <animate attributeName="opacity" values="1;0.35;1" dur="1.1s" repeatCount="indefinite" /> : null}
|
|
21
|
-
</svg>
|
|
22
|
-
)
|
|
23
|
-
}
|