@y1x1n/dsh-prompt-optimizer 0.3.13
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 +178 -0
- package/README.md +180 -0
- package/cordis.patch.yml +5 -0
- package/lib/client.js +1494 -0
- package/lib/controller.js +348 -0
- package/lib/index.js +648 -0
- package/lib/prompt.js +254 -0
- package/package.json +54 -0
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
// src/prompt.ts
|
|
2
|
+
var MARKERS = {
|
|
3
|
+
analysis: "<<<ANALYSIS>>>",
|
|
4
|
+
optimized: "<<<OPTIMIZED>>>",
|
|
5
|
+
end: "<<<END>>>"
|
|
6
|
+
};
|
|
7
|
+
var FORMAT_FULL_ZH = `# \u8F93\u51FA\u683C\u5F0F(\u4E25\u683C\u9075\u5B88,\u6807\u8BB0\u884C\u5355\u72EC\u6210\u884C)
|
|
8
|
+
${MARKERS.analysis}
|
|
9
|
+
\u6309\u7EF4\u5EA6\u9010\u6761\u8F93\u51FA\u8BCA\u65AD,\u6BCF\u6761\u4E00\u884C,\u683C\u5F0F:\u300C\u7EF4\u5EA6 | \u95EE\u9898 | \u5EFA\u8BAE\u300D\u3002\u67D0\u7EF4\u5EA6\u65E0\u660E\u663E\u95EE\u9898\u65F6\u5199:\u300C\u7EF4\u5EA6 | \u65E0\u660E\u663E\u95EE\u9898 | -\u300D\u3002
|
|
10
|
+
${MARKERS.optimized}
|
|
11
|
+
\u8F93\u51FA\u4F18\u5316\u540E\u7684\u5B8C\u6574\u63D0\u793A\u8BCD\u5168\u6587
|
|
12
|
+
${MARKERS.end}
|
|
13
|
+
|
|
14
|
+
\u9664\u4E0A\u8FF0\u6807\u8BB0\u5305\u88F9\u7684\u5185\u5BB9\u5916,\u4E0D\u8981\u8F93\u51FA\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002`;
|
|
15
|
+
var FORMAT_FULL_EN = `# Output format (strictly follow; markers on their own lines)
|
|
16
|
+
${MARKERS.analysis}
|
|
17
|
+
One finding per line: "dimension | issue | suggestion". If a dimension is fine: "dimension | no issue | -".
|
|
18
|
+
${MARKERS.optimized}
|
|
19
|
+
The full optimized prompt text
|
|
20
|
+
${MARKERS.end}
|
|
21
|
+
|
|
22
|
+
Do not output anything outside these markers.`;
|
|
23
|
+
var FORMAT_FAST_ZH = `# \u8F93\u51FA\u683C\u5F0F(\u4E25\u683C\u9075\u5B88,\u6807\u8BB0\u884C\u5355\u72EC\u6210\u884C)
|
|
24
|
+
${MARKERS.optimized}
|
|
25
|
+
\u8F93\u51FA\u4F18\u5316\u540E\u7684\u5B8C\u6574\u63D0\u793A\u8BCD\u5168\u6587
|
|
26
|
+
${MARKERS.end}
|
|
27
|
+
|
|
28
|
+
\u9664\u4E0A\u8FF0\u6807\u8BB0\u5305\u88F9\u7684\u5185\u5BB9\u5916,\u4E0D\u8981\u8F93\u51FA\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002`;
|
|
29
|
+
var FORMAT_FAST_EN = `# Output format (strictly follow; markers on their own lines)
|
|
30
|
+
${MARKERS.optimized}
|
|
31
|
+
The full optimized prompt text
|
|
32
|
+
${MARKERS.end}
|
|
33
|
+
|
|
34
|
+
Do not output anything outside these markers.`;
|
|
35
|
+
var CONTEXT_MAX_TURNS = 8;
|
|
36
|
+
var CONTEXT_MAX_CHARS = 1600;
|
|
37
|
+
var CONTEXT_TURN_MAX_CHARS = 600;
|
|
38
|
+
function capConversationContext(turns) {
|
|
39
|
+
const recent = turns.filter((t) => t.text.trim()).slice(-CONTEXT_MAX_TURNS).map((t) => ({
|
|
40
|
+
role: t.role,
|
|
41
|
+
text: t.text.trim().length > CONTEXT_TURN_MAX_CHARS ? `${t.text.trim().slice(0, CONTEXT_TURN_MAX_CHARS)}\u2026` : t.text.trim()
|
|
42
|
+
}));
|
|
43
|
+
let budget = CONTEXT_MAX_CHARS;
|
|
44
|
+
const kept = [];
|
|
45
|
+
for (let i = recent.length - 1; i >= 0; i--) {
|
|
46
|
+
const turn = recent[i];
|
|
47
|
+
if (turn.text.length > budget) {
|
|
48
|
+
if (kept.length === 0) kept.push({ role: turn.role, text: `${turn.text.slice(0, budget)}\u2026` });
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
kept.unshift(turn);
|
|
52
|
+
budget -= turn.text.length;
|
|
53
|
+
}
|
|
54
|
+
return kept;
|
|
55
|
+
}
|
|
56
|
+
function findMarker(text, word, fromIndex = 0) {
|
|
57
|
+
const re = new RegExp(`<<<\\s*${word}\\s*>>>`, "g");
|
|
58
|
+
re.lastIndex = fromIndex;
|
|
59
|
+
const match = re.exec(text);
|
|
60
|
+
return match ? { index: match.index, length: match[0].length } : null;
|
|
61
|
+
}
|
|
62
|
+
function parsePartialOptimizerOutput(raw) {
|
|
63
|
+
const a = findMarker(raw, "ANALYSIS");
|
|
64
|
+
const o = findMarker(raw, "OPTIMIZED");
|
|
65
|
+
let analysis = "";
|
|
66
|
+
let optimized = "";
|
|
67
|
+
if (a && (!o || a.index < o.index)) {
|
|
68
|
+
analysis = raw.slice(a.index + a.length, o ? o.index : raw.length).trim();
|
|
69
|
+
}
|
|
70
|
+
if (o) {
|
|
71
|
+
const e = findMarker(raw, "END", o.index + o.length);
|
|
72
|
+
optimized = raw.slice(o.index + o.length, e ? e.index : raw.length).trim();
|
|
73
|
+
}
|
|
74
|
+
return { analysis, optimized };
|
|
75
|
+
}
|
|
76
|
+
function compactPartialBuffer(raw) {
|
|
77
|
+
const o = findMarker(raw, "OPTIMIZED");
|
|
78
|
+
if (!o) return { compacted: null, analysis: "" };
|
|
79
|
+
const a = findMarker(raw, "ANALYSIS");
|
|
80
|
+
const analysis = a && a.index < o.index ? raw.slice(a.index + a.length, o.index).trim() : "";
|
|
81
|
+
return { compacted: `${MARKERS.optimized}
|
|
82
|
+
${raw.slice(o.index + o.length)}`, analysis };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// src/client/controller.ts
|
|
86
|
+
var ROUTE = "/dsh-prompt-optimizer/optimize";
|
|
87
|
+
var INITIAL = { open: false, status: "idle", error: null, result: null, live: null, last: null, applied: null };
|
|
88
|
+
function splitCommandPrefix(text) {
|
|
89
|
+
const trimmed = text.trim();
|
|
90
|
+
const match = /^(\/[A-Za-z][\w-]*)(?:\s+([\s\S]+))?$/.exec(trimmed);
|
|
91
|
+
if (!match) return { body: trimmed };
|
|
92
|
+
if (!match[2] || !match[2].trim()) return { body: trimmed, commandOnly: true };
|
|
93
|
+
return { prefix: match[1], body: match[2].trim() };
|
|
94
|
+
}
|
|
95
|
+
function shouldAutoClose(input) {
|
|
96
|
+
if (!input.open || input.status === "loading") return false;
|
|
97
|
+
return !input.draft.trim() || !input.prevRunning && input.running || input.queued > input.prevQueued;
|
|
98
|
+
}
|
|
99
|
+
function flattenText(content) {
|
|
100
|
+
if (!Array.isArray(content)) return "";
|
|
101
|
+
return content.map(
|
|
102
|
+
(block) => block && typeof block === "object" && block.type === "text" ? String(block.text ?? "") : ""
|
|
103
|
+
).filter(Boolean).join("\n").trim();
|
|
104
|
+
}
|
|
105
|
+
function sampleContextTurns(turns) {
|
|
106
|
+
const users = turns.map((t, i) => ({ t, i })).filter((x) => x.t.role === "user").slice(-4);
|
|
107
|
+
const assistants = turns.map((t, i) => ({ t, i })).filter((x) => x.t.role === "assistant").slice(-4);
|
|
108
|
+
const merged = [...users, ...assistants].sort((a, b) => a.i - b.i).map((x) => x.t);
|
|
109
|
+
return capConversationContext(merged);
|
|
110
|
+
}
|
|
111
|
+
function extractContextTurns(entries) {
|
|
112
|
+
const turns = [];
|
|
113
|
+
for (const entry of entries) {
|
|
114
|
+
const event = entry?.event;
|
|
115
|
+
if (!event || typeof event !== "object") continue;
|
|
116
|
+
if (event.type === "user/message") {
|
|
117
|
+
const data = event.data;
|
|
118
|
+
if (data?.source?.kind !== "user") continue;
|
|
119
|
+
const text = flattenText(data.content);
|
|
120
|
+
if (text) turns.push({ role: "user", text });
|
|
121
|
+
} else if (event.type === "assistant/message") {
|
|
122
|
+
const data = event.data;
|
|
123
|
+
const text = flattenText(data?.message?.content);
|
|
124
|
+
if (text) turns.push({ role: "assistant", text });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return sampleContextTurns(turns);
|
|
128
|
+
}
|
|
129
|
+
function createOptimizerController(ctx, opts = {}) {
|
|
130
|
+
let state = INITIAL;
|
|
131
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
132
|
+
let abort = null;
|
|
133
|
+
let liveRaw = "";
|
|
134
|
+
let frozenAnalysis = "";
|
|
135
|
+
let liveTimer = null;
|
|
136
|
+
const clearLiveTimer = () => {
|
|
137
|
+
if (liveTimer) {
|
|
138
|
+
clearTimeout(liveTimer);
|
|
139
|
+
liveTimer = null;
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
const set = (patch) => {
|
|
143
|
+
state = { ...state, ...patch };
|
|
144
|
+
for (const listener of listeners) listener();
|
|
145
|
+
};
|
|
146
|
+
async function optimize(text, sessionId) {
|
|
147
|
+
const split = splitCommandPrefix(text);
|
|
148
|
+
const { prefix, body: draft } = split;
|
|
149
|
+
if (!draft || state.status === "loading") return;
|
|
150
|
+
if (split.commandOnly) {
|
|
151
|
+
set({
|
|
152
|
+
open: true,
|
|
153
|
+
status: "error",
|
|
154
|
+
error: "\u68C0\u6D4B\u5230\u659C\u6760\u547D\u4EE4\u4F46\u6CA1\u6709\u6B63\u6587:\u8BF7\u5148\u8F93\u5165\u8981\u4F18\u5316\u7684\u5185\u5BB9\u3002",
|
|
155
|
+
live: null,
|
|
156
|
+
last: { text: draft, sessionId }
|
|
157
|
+
});
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
const previous = state.result && state.result.wellFormed && state.last?.sessionId === sessionId && state.last.text !== draft && (opts.isContextEnabled?.() ?? true) ? state.result.optimized : void 0;
|
|
161
|
+
abort?.abort();
|
|
162
|
+
clearLiveTimer();
|
|
163
|
+
liveRaw = "";
|
|
164
|
+
frozenAnalysis = "";
|
|
165
|
+
const controller = new AbortController();
|
|
166
|
+
abort = controller;
|
|
167
|
+
const watchdogMs = Math.max(1e3, opts.getWatchdogMs?.() ?? 125e3);
|
|
168
|
+
let clientTimedOut = false;
|
|
169
|
+
const watchdog = setTimeout(() => {
|
|
170
|
+
clientTimedOut = true;
|
|
171
|
+
controller.abort();
|
|
172
|
+
}, watchdogMs);
|
|
173
|
+
const failTimeout = () => {
|
|
174
|
+
clearLiveTimer();
|
|
175
|
+
const seconds = Math.round(watchdogMs / 1e3);
|
|
176
|
+
set({
|
|
177
|
+
status: "error",
|
|
178
|
+
live: null,
|
|
179
|
+
error: `\u8BF7\u6C42\u8D85\u65F6(\u5BA2\u6237\u7AEF ${seconds} \u79D2\u65E0\u54CD\u5E94,Host \u53EF\u80FD\u672A\u8FD0\u884C)\u3002\u53EF\u5728 \u8BBE\u7F6E \u2192 \u63D2\u4EF6\u914D\u7F6E \u2192 \u63D0\u793A\u8BCD\u4F18\u5316 \u4E2D\u8C03\u9AD8\u300C\u8D85\u65F6\u65F6\u95F4\u300D\u3002`
|
|
180
|
+
});
|
|
181
|
+
};
|
|
182
|
+
const startedAt = Date.now();
|
|
183
|
+
set({ open: true, status: "loading", error: null, live: { analysis: "", optimized: "" }, last: { text: draft, sessionId, prefix }, applied: null });
|
|
184
|
+
try {
|
|
185
|
+
const [selection, context] = await Promise.all([
|
|
186
|
+
(async () => {
|
|
187
|
+
if (opts.isModelPinned?.()) return void 0;
|
|
188
|
+
try {
|
|
189
|
+
const resp2 = await ctx.connection.api.sessions.models({ sessionId }, controller.signal);
|
|
190
|
+
if (resp2.result.ok) {
|
|
191
|
+
const current = resp2.result.value.current;
|
|
192
|
+
return { provider: current.provider, model: current.model, reasoningEffort: current.reasoningEffort };
|
|
193
|
+
}
|
|
194
|
+
console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u6A21\u578B\u67E5\u8BE2\u88AB\u62D2\u7EDD,\u6539\u7528 Host \u56DE\u9000:", resp2.result.error);
|
|
195
|
+
} catch (cause) {
|
|
196
|
+
console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u6A21\u578B\u67E5\u8BE2\u5931\u8D25,\u6539\u7528 Host \u56DE\u9000:", cause);
|
|
197
|
+
}
|
|
198
|
+
return void 0;
|
|
199
|
+
})(),
|
|
200
|
+
(async () => {
|
|
201
|
+
if (!(opts.isContextEnabled?.() ?? true)) return void 0;
|
|
202
|
+
try {
|
|
203
|
+
const resp2 = await ctx.connection.api.sessions.history({ sessionId, maxMessages: 24 }, controller.signal);
|
|
204
|
+
if (resp2.result.ok) {
|
|
205
|
+
const turns = extractContextTurns(resp2.result.value.events);
|
|
206
|
+
return turns.length ? turns : void 0;
|
|
207
|
+
}
|
|
208
|
+
console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u5386\u53F2\u67E5\u8BE2\u88AB\u62D2\u7EDD,\u6309\u65E0\u4E0A\u4E0B\u6587\u4F18\u5316:", resp2.result.error);
|
|
209
|
+
} catch (cause) {
|
|
210
|
+
console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u5386\u53F2\u67E5\u8BE2\u5931\u8D25,\u6309\u65E0\u4E0A\u4E0B\u6587\u4F18\u5316:", cause);
|
|
211
|
+
}
|
|
212
|
+
return void 0;
|
|
213
|
+
})()
|
|
214
|
+
]);
|
|
215
|
+
const resp = await fetch(ROUTE, {
|
|
216
|
+
method: "POST",
|
|
217
|
+
headers: { "content-type": "application/json" },
|
|
218
|
+
body: JSON.stringify({ text: draft, provider: selection?.provider, model: selection?.model, reasoningEffort: selection?.reasoningEffort, context, previous }),
|
|
219
|
+
signal: controller.signal
|
|
220
|
+
});
|
|
221
|
+
if (!resp.ok || !(resp.headers.get("content-type") ?? "").includes("text/event-stream")) {
|
|
222
|
+
const data = await resp.json().catch(() => null);
|
|
223
|
+
if (!controller.signal.aborted) {
|
|
224
|
+
set({ status: "error", live: null, error: String(data?.error ?? `\u8BF7\u6C42\u5931\u8D25(HTTP ${resp.status})`) });
|
|
225
|
+
}
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
const reader = resp.body?.getReader();
|
|
229
|
+
if (!reader) throw new Error("\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301\u6D41\u5F0F\u54CD\u5E94");
|
|
230
|
+
const decoder = new TextDecoder();
|
|
231
|
+
let buffer = "";
|
|
232
|
+
let terminal = false;
|
|
233
|
+
for (; ; ) {
|
|
234
|
+
const { done, value } = await reader.read();
|
|
235
|
+
if (done) break;
|
|
236
|
+
buffer += decoder.decode(value, { stream: true });
|
|
237
|
+
let sep;
|
|
238
|
+
while ((sep = buffer.indexOf("\n\n")) !== -1) {
|
|
239
|
+
const frame = buffer.slice(0, sep);
|
|
240
|
+
buffer = buffer.slice(sep + 2);
|
|
241
|
+
const line = frame.split("\n").find((l) => l.startsWith("data:"));
|
|
242
|
+
if (!line) continue;
|
|
243
|
+
const event = JSON.parse(line.slice(5).trim());
|
|
244
|
+
if (event.type === "delta") {
|
|
245
|
+
liveRaw += String(event.text ?? "");
|
|
246
|
+
if (!liveTimer) {
|
|
247
|
+
liveTimer = setTimeout(() => {
|
|
248
|
+
liveTimer = null;
|
|
249
|
+
if (state.status === "loading" && abort === controller) {
|
|
250
|
+
const comp = compactPartialBuffer(liveRaw);
|
|
251
|
+
if (comp.compacted !== null) {
|
|
252
|
+
frozenAnalysis = comp.analysis;
|
|
253
|
+
liveRaw = comp.compacted;
|
|
254
|
+
}
|
|
255
|
+
const partial = parsePartialOptimizerOutput(liveRaw);
|
|
256
|
+
const live = { analysis: partial.analysis || frozenAnalysis, optimized: partial.optimized };
|
|
257
|
+
if (opts.isFastMode?.() && !live.analysis && !live.optimized && liveRaw.trim() && !liveRaw.includes("<<<")) {
|
|
258
|
+
live.optimized = liveRaw.trim();
|
|
259
|
+
}
|
|
260
|
+
set({ live });
|
|
261
|
+
}
|
|
262
|
+
}, 50);
|
|
263
|
+
}
|
|
264
|
+
} else if (event.type === "done") {
|
|
265
|
+
terminal = true;
|
|
266
|
+
clearLiveTimer();
|
|
267
|
+
set({
|
|
268
|
+
status: "done",
|
|
269
|
+
live: null,
|
|
270
|
+
result: {
|
|
271
|
+
analysis: String(event.analysis ?? ""),
|
|
272
|
+
optimized: String(event.optimized ?? ""),
|
|
273
|
+
wellFormed: event.wellFormed !== false,
|
|
274
|
+
truncated: event.truncated === true,
|
|
275
|
+
provider: String(event.provider ?? ""),
|
|
276
|
+
model: String(event.model ?? ""),
|
|
277
|
+
fallbackUsed: event.fallbackUsed === true,
|
|
278
|
+
fallbackReason: typeof event.fallbackReason === "string" && event.fallbackReason ? event.fallbackReason : void 0,
|
|
279
|
+
durationMs: Date.now() - startedAt
|
|
280
|
+
}
|
|
281
|
+
});
|
|
282
|
+
} else if (event.type === "error") {
|
|
283
|
+
terminal = true;
|
|
284
|
+
clearLiveTimer();
|
|
285
|
+
set({ status: "error", live: null, error: String(event.error ?? "\u672A\u77E5\u9519\u8BEF") });
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (!terminal) {
|
|
290
|
+
if (!controller.signal.aborted) {
|
|
291
|
+
clearLiveTimer();
|
|
292
|
+
set({ status: "error", live: null, error: "\u8FDE\u63A5\u4E2D\u65AD:\u54CD\u5E94\u6D41\u63D0\u524D\u7ED3\u675F" });
|
|
293
|
+
} else if (clientTimedOut && abort === controller) {
|
|
294
|
+
failTimeout();
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
} catch (cause) {
|
|
298
|
+
if (controller.signal.aborted) {
|
|
299
|
+
if (clientTimedOut && abort === controller) failTimeout();
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
set({ status: "error", live: null, error: cause instanceof Error ? cause.message : String(cause) });
|
|
303
|
+
} finally {
|
|
304
|
+
clearTimeout(watchdog);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return {
|
|
308
|
+
subscribe(listener) {
|
|
309
|
+
listeners.add(listener);
|
|
310
|
+
return () => listeners.delete(listener);
|
|
311
|
+
},
|
|
312
|
+
getSnapshot: () => state,
|
|
313
|
+
optimize,
|
|
314
|
+
retry() {
|
|
315
|
+
if (state.last) void optimize(state.last.text, state.last.sessionId);
|
|
316
|
+
},
|
|
317
|
+
markApplied(applied) {
|
|
318
|
+
set({ applied });
|
|
319
|
+
},
|
|
320
|
+
clearApplied() {
|
|
321
|
+
if (state.applied) set({ applied: null });
|
|
322
|
+
},
|
|
323
|
+
close() {
|
|
324
|
+
abort?.abort();
|
|
325
|
+
abort = null;
|
|
326
|
+
clearLiveTimer();
|
|
327
|
+
set({ ...INITIAL });
|
|
328
|
+
},
|
|
329
|
+
/**
|
|
330
|
+
* O2:loading 中取消(Esc)。与 close 不同:中止请求但不清空状态,
|
|
331
|
+
* 面板定格展示已生成的部分——用户等了几十秒的内容不应一键蒸发。
|
|
332
|
+
* 后续可「重新优化」续跑或「关闭」彻底收起。
|
|
333
|
+
*/
|
|
334
|
+
cancel() {
|
|
335
|
+
if (state.status !== "loading") return;
|
|
336
|
+
abort?.abort();
|
|
337
|
+
abort = null;
|
|
338
|
+
clearLiveTimer();
|
|
339
|
+
set({ status: "cancelled" });
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
export {
|
|
344
|
+
createOptimizerController,
|
|
345
|
+
extractContextTurns,
|
|
346
|
+
shouldAutoClose,
|
|
347
|
+
splitCommandPrefix
|
|
348
|
+
};
|