@y1x1n/dsh-prompt-optimizer 0.3.16 → 0.6.4

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/lib/controller.js CHANGED
@@ -1,3 +1,13 @@
1
+ // src/client/host-faces.ts
2
+ function legacyQueryFace(connection) {
3
+ return connection?.api;
4
+ }
5
+ function sessionEventEntries(sessions, sessionId) {
6
+ const binding = sessions?.binding?.(sessionId);
7
+ const window = binding?.eventSource?.getSnapshot();
8
+ return window?.entries;
9
+ }
10
+
1
11
  // src/prompt.ts
2
12
  var MARKERS = {
3
13
  analysis: "<<<ANALYSIS>>>",
@@ -5,18 +15,18 @@ var MARKERS = {
5
15
  end: "<<<END>>>"
6
16
  };
7
17
  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
18
  ${MARKERS.optimized}
11
19
  \u8F93\u51FA\u4F18\u5316\u540E\u7684\u5B8C\u6574\u63D0\u793A\u8BCD\u5168\u6587
20
+ ${MARKERS.analysis}
21
+ \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
12
22
  ${MARKERS.end}
13
23
 
14
24
  \u9664\u4E0A\u8FF0\u6807\u8BB0\u5305\u88F9\u7684\u5185\u5BB9\u5916,\u4E0D\u8981\u8F93\u51FA\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002`;
15
25
  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
26
  ${MARKERS.optimized}
19
27
  The full optimized prompt text
28
+ ${MARKERS.analysis}
29
+ One finding per line: "dimension | issue | suggestion". If a dimension is fine: "dimension | no issue | -".
20
30
  ${MARKERS.end}
21
31
 
22
32
  Do not output anything outside these markers.`;
@@ -35,23 +45,44 @@ Do not output anything outside these markers.`;
35
45
  var CONTEXT_MAX_TURNS = 8;
36
46
  var CONTEXT_MAX_CHARS = 1600;
37
47
  var CONTEXT_TURN_MAX_CHARS = 600;
48
+ var CONTEXT_MIN_USER_TURNS = 1;
49
+ var CONTEXT_USER_BUDGET = 800;
38
50
  function capConversationContext(turns) {
39
51
  const recent = turns.filter((t) => t.text.trim()).slice(-CONTEXT_MAX_TURNS).map((t) => ({
40
52
  role: t.role,
41
53
  text: t.text.trim().length > CONTEXT_TURN_MAX_CHARS ? `${t.text.trim().slice(0, CONTEXT_TURN_MAX_CHARS)}\u2026` : t.text.trim()
42
54
  }));
55
+ if (recent.length === 0) return [];
56
+ const indexed = recent.map((turn, index) => ({ turn, index }));
57
+ const kept = /* @__PURE__ */ new Map();
43
58
  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;
59
+ const users = indexed.filter((x) => x.turn.role === "user");
60
+ let userBudget = Math.min(CONTEXT_USER_BUDGET, budget);
61
+ for (let i = users.length - 1; i >= 0; i--) {
62
+ const { turn, index } = users[i];
63
+ const keptUsers = users.length - i;
64
+ const mustKeep = keptUsers <= CONTEXT_MIN_USER_TURNS && ![...kept.values()].some((t) => t.role === "user");
65
+ if (turn.text.length <= userBudget) {
66
+ kept.set(index, turn);
67
+ userBudget -= turn.text.length;
68
+ budget -= turn.text.length;
69
+ } else if (mustKeep) {
70
+ const slice = userBudget > 16 ? userBudget : Math.min(16, budget);
71
+ if (slice > 0) {
72
+ kept.set(index, { role: turn.role, text: `${turn.text.slice(0, slice)}\u2026` });
73
+ userBudget -= slice;
74
+ budget -= slice;
75
+ }
50
76
  }
51
- kept.unshift(turn);
77
+ }
78
+ const assistants = indexed.filter((x) => x.turn.role === "assistant");
79
+ for (let i = assistants.length - 1; i >= 0; i--) {
80
+ const { turn, index } = assistants[i];
81
+ if (turn.text.length > budget) continue;
82
+ kept.set(index, turn);
52
83
  budget -= turn.text.length;
53
84
  }
54
- return kept;
85
+ return [...kept.entries()].sort(([a], [b]) => a - b).map(([, turn]) => turn);
55
86
  }
56
87
  function findMarker(text, word, fromIndex = 0) {
57
88
  const re = new RegExp(`<<<\\s*${word}\\s*>>>`, "g");
@@ -59,27 +90,70 @@ function findMarker(text, word, fromIndex = 0) {
59
90
  const match = re.exec(text);
60
91
  return match ? { index: match.index, length: match[0].length } : null;
61
92
  }
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();
93
+ function findLastMarker(text, word, beforeIndex = text.length) {
94
+ const re = new RegExp(`<<<\\s*${word}\\s*>>>`, "g");
95
+ let last = null;
96
+ for (const match of text.matchAll(re)) {
97
+ if (match.index >= beforeIndex) break;
98
+ last = { index: match.index, length: match[0].length };
69
99
  }
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();
100
+ return last;
101
+ }
102
+ function findNextMarker(text, fromIndex) {
103
+ const re = /<<<\s*(?:ANALYSIS|OPTIMIZED|END)\s*>>>/g;
104
+ re.lastIndex = fromIndex;
105
+ const match = re.exec(text);
106
+ return match ? { index: match.index, length: match[0].length } : null;
107
+ }
108
+ function segmentAfter(text, marker) {
109
+ const firstEnd = findMarker(text, "END");
110
+ if (firstEnd && marker.index > firstEnd.index) return "";
111
+ const start = marker.index + marker.length;
112
+ const next = findNextMarker(text, start);
113
+ let end = next ? next.index : text.length;
114
+ if (firstEnd && firstEnd.index > start && firstEnd.index < end) end = firstEnd.index;
115
+ return text.slice(start, end).trim();
116
+ }
117
+ var THINK_OPEN = "<think>";
118
+ var THINK_CLOSE = "</think>";
119
+ function stripThinkBlocks(text) {
120
+ let out = "";
121
+ let rest = text;
122
+ for (; ; ) {
123
+ const open = rest.indexOf(THINK_OPEN);
124
+ if (open === -1) return out + rest;
125
+ out += rest.slice(0, open);
126
+ const close = rest.indexOf(THINK_CLOSE, open + THINK_OPEN.length);
127
+ if (close === -1) return out;
128
+ rest = rest.slice(close + THINK_CLOSE.length);
73
129
  }
74
- return { analysis, optimized };
130
+ }
131
+ function parsePartialOptimizerOutput(raw) {
132
+ const text = stripThinkBlocks(raw);
133
+ const o = findLastMarker(text, "OPTIMIZED");
134
+ const a = findLastMarker(text, "ANALYSIS");
135
+ return {
136
+ analysis: a ? segmentAfter(text, a) : "",
137
+ optimized: o ? segmentAfter(text, o) : ""
138
+ };
75
139
  }
76
140
  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 };
141
+ const o = findLastMarker(raw, "OPTIMIZED");
142
+ const a = findLastMarker(raw, "ANALYSIS");
143
+ if (o && a && o.index < a.index) {
144
+ return {
145
+ compacted: `${MARKERS.analysis}
146
+ ${raw.slice(a.index + a.length)}`,
147
+ analysis: "",
148
+ optimized: raw.slice(o.index + o.length, a.index).trim()
149
+ };
150
+ }
151
+ if (o) {
152
+ const analysis = a && a.index < o.index ? raw.slice(a.index + a.length, o.index).trim() : "";
153
+ return { compacted: `${MARKERS.optimized}
154
+ ${raw.slice(o.index + o.length)}`, analysis, optimized: "" };
155
+ }
156
+ return { compacted: null, analysis: "", optimized: "" };
83
157
  }
84
158
 
85
159
  // src/client/controller.ts
@@ -92,9 +166,12 @@ function splitCommandPrefix(text) {
92
166
  if (!match[2] || !match[2].trim()) return { body: trimmed, commandOnly: true };
93
167
  return { prefix: match[1], body: match[2].trim() };
94
168
  }
169
+ function joinLast(last) {
170
+ return last.prefix ? `${last.prefix} ${last.text}` : last.text;
171
+ }
95
172
  function shouldAutoClose(input) {
96
173
  if (!input.open || input.status === "loading") return false;
97
- return !input.draft.trim() || !input.prevRunning && input.running || input.queued > input.prevQueued;
174
+ return input.phase === "sending" || !input.draft.trim() || !input.prevRunning && input.running || input.queued > input.prevQueued;
98
175
  }
99
176
  function flattenText(content) {
100
177
  if (!Array.isArray(content)) return "";
@@ -132,6 +209,7 @@ function createOptimizerController(ctx, opts = {}) {
132
209
  let abort = null;
133
210
  let liveRaw = "";
134
211
  let frozenAnalysis = "";
212
+ let frozenOptimized = "";
135
213
  let liveTimer = null;
136
214
  const clearLiveTimer = () => {
137
215
  if (liveTimer) {
@@ -162,6 +240,7 @@ function createOptimizerController(ctx, opts = {}) {
162
240
  clearLiveTimer();
163
241
  liveRaw = "";
164
242
  frozenAnalysis = "";
243
+ frozenOptimized = "";
165
244
  const controller = new AbortController();
166
245
  abort = controller;
167
246
  const watchdogMs = Math.max(1e3, opts.getWatchdogMs?.() ?? 125e3);
@@ -176,7 +255,7 @@ function createOptimizerController(ctx, opts = {}) {
176
255
  set({
177
256
  status: "error",
178
257
  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`
258
+ error: `\u8BF7\u6C42\u8D85\u65F6(\u5BA2\u6237\u7AEF ${seconds} \u79D2\u65E0\u54CD\u5E94,Host \u53EF\u80FD\u672A\u8FD0\u884C)\u3002\u53EF\u5728 \u8BBE\u7F6E\u7684\u63D2\u4EF6\u9875\u300C\u63D0\u793A\u8BCD\u4F18\u5316\u300D \u4E2D\u8C03\u9AD8\u300C\u8D85\u65F6\u65F6\u95F4\u300D\u3002`
180
259
  });
181
260
  };
182
261
  const startedAt = Date.now();
@@ -186,12 +265,17 @@ function createOptimizerController(ctx, opts = {}) {
186
265
  (async () => {
187
266
  if (opts.isModelPinned?.()) return void 0;
188
267
  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;
268
+ const directories = opts.getSessionModelDirectories?.();
269
+ if (!directories) {
270
+ console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u6A21\u578B\u76EE\u5F55\u670D\u52A1\u5728\u5F53\u524D dsh \u7248\u672C\u7F3A\u5E2D,\u6539\u7528 Host \u56DE\u9000");
271
+ return void 0;
272
+ }
273
+ const state2 = await directories.directoryFor(sessionId).load();
274
+ const current = state2.current;
275
+ if (current?.provider && current.model) {
192
276
  return { provider: current.provider, model: current.model, reasoningEffort: current.reasoningEffort };
193
277
  }
194
- console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u6A21\u578B\u67E5\u8BE2\u88AB\u62D2\u7EDD,\u6539\u7528 Host \u56DE\u9000:", resp2.result.error);
278
+ console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u9009\u62E9,\u6539\u7528 Host \u56DE\u9000:", state2.error ?? current);
195
279
  } catch (cause) {
196
280
  console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u6A21\u578B\u67E5\u8BE2\u5931\u8D25,\u6539\u7528 Host \u56DE\u9000:", cause);
197
281
  }
@@ -200,12 +284,29 @@ function createOptimizerController(ctx, opts = {}) {
200
284
  (async () => {
201
285
  if (!(opts.isContextEnabled?.() ?? true)) return void 0;
202
286
  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);
287
+ const entries = sessionEventEntries(opts.getSessions?.(), sessionId);
288
+ if (entries?.length) {
289
+ const turns = extractContextTurns(entries);
290
+ if (turns.length) return turns;
291
+ console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u4E8B\u4EF6\u7A97\u53E3\u91CC\u6CA1\u6709\u53EF\u7528\u7684\u5BF9\u8BDD,\u5C1D\u8BD5\u65E7\u67E5\u8BE2\u9762");
292
+ } else {
293
+ console.warn("[dsh-prompt-optimizer] \u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u53EF\u8BFB\u7684\u4E8B\u4EF6\u7A97\u53E3,\u5C1D\u8BD5\u65E7\u67E5\u8BE2\u9762");
294
+ }
295
+ } catch (cause) {
296
+ console.warn("[dsh-prompt-optimizer] \u8BFB\u53D6\u4F1A\u8BDD\u4E8B\u4EF6\u7A97\u53E3\u5931\u8D25,\u5C1D\u8BD5\u65E7\u67E5\u8BE2\u9762:", cause);
297
+ }
298
+ try {
299
+ const history = legacyQueryFace(ctx.connection)?.sessions?.history;
300
+ if (!history) {
301
+ console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u5386\u53F2\u67E5\u8BE2\u9762\u5728\u5F53\u524D dsh \u7248\u672C\u7F3A\u5E2D,\u6309\u65E0\u4E0A\u4E0B\u6587\u4F18\u5316");
302
+ return void 0;
303
+ }
304
+ const result = await history({ sessionId, maxMessages: 24 }, controller.signal);
305
+ if (result.ok) {
306
+ const turns = extractContextTurns(result.value.events ?? []);
206
307
  return turns.length ? turns : void 0;
207
308
  }
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);
309
+ console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u5386\u53F2\u67E5\u8BE2\u88AB\u62D2\u7EDD,\u6309\u65E0\u4E0A\u4E0B\u6587\u4F18\u5316:", result.error);
209
310
  } catch (cause) {
210
311
  console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u5386\u53F2\u67E5\u8BE2\u5931\u8D25,\u6309\u65E0\u4E0A\u4E0B\u6587\u4F18\u5316:", cause);
211
312
  }
@@ -215,7 +316,10 @@ function createOptimizerController(ctx, opts = {}) {
215
316
  const resp = await fetch(ROUTE, {
216
317
  method: "POST",
217
318
  headers: { "content-type": "application/json" },
218
- body: JSON.stringify({ text: draft, provider: selection?.provider, model: selection?.model, reasoningEffort: selection?.reasoningEffort, context, previous }),
319
+ // sessionId 随请求带给 Host:Host 把它标注到 llm 调用上,要求会话头
320
+ // 的提供方(如 opencode 的 x-opencode-session)才能路由成功,同时
321
+ // 会话级计量会把这次调用归属到当前会话。
322
+ body: JSON.stringify({ text: draft, sessionId, provider: selection?.provider, model: selection?.model, reasoningEffort: selection?.reasoningEffort, context, previous }),
219
323
  signal: controller.signal
220
324
  });
221
325
  if (!resp.ok || !(resp.headers.get("content-type") ?? "").includes("text/event-stream")) {
@@ -240,7 +344,13 @@ function createOptimizerController(ctx, opts = {}) {
240
344
  buffer = buffer.slice(sep + 2);
241
345
  const line = frame.split("\n").find((l) => l.startsWith("data:"));
242
346
  if (!line) continue;
243
- const event = JSON.parse(line.slice(5).trim());
347
+ let event;
348
+ try {
349
+ event = JSON.parse(line.slice(5).trim());
350
+ } catch {
351
+ console.warn("[dsh-prompt-optimizer] \u8DF3\u8FC7\u65E0\u6CD5\u89E3\u6790\u7684 SSE \u5E27:", line.slice(0, 120));
352
+ continue;
353
+ }
244
354
  if (event.type === "delta") {
245
355
  liveRaw += String(event.text ?? "");
246
356
  if (!liveTimer) {
@@ -249,11 +359,12 @@ function createOptimizerController(ctx, opts = {}) {
249
359
  if (state.status === "loading" && abort === controller) {
250
360
  const comp = compactPartialBuffer(liveRaw);
251
361
  if (comp.compacted !== null) {
252
- frozenAnalysis = comp.analysis;
362
+ if (comp.analysis) frozenAnalysis = comp.analysis;
363
+ if (comp.optimized) frozenOptimized = comp.optimized;
253
364
  liveRaw = comp.compacted;
254
365
  }
255
366
  const partial = parsePartialOptimizerOutput(liveRaw);
256
- const live = { analysis: partial.analysis || frozenAnalysis, optimized: partial.optimized };
367
+ const live = { analysis: partial.analysis || frozenAnalysis, optimized: partial.optimized || frozenOptimized };
257
368
  if (opts.isFastMode?.() && !live.analysis && !live.optimized && liveRaw.trim() && !liveRaw.includes("<<<")) {
258
369
  live.optimized = liveRaw.trim();
259
370
  }
@@ -312,7 +423,7 @@ function createOptimizerController(ctx, opts = {}) {
312
423
  getSnapshot: () => state,
313
424
  optimize,
314
425
  retry() {
315
- if (state.last) void optimize(state.last.text, state.last.sessionId);
426
+ if (state.last) void optimize(joinLast(state.last), state.last.sessionId);
316
427
  },
317
428
  markApplied(applied) {
318
429
  set({ applied });
@@ -343,6 +454,7 @@ function createOptimizerController(ctx, opts = {}) {
343
454
  export {
344
455
  createOptimizerController,
345
456
  extractContextTurns,
457
+ joinLast,
346
458
  shouldAutoClose,
347
459
  splitCommandPrefix
348
460
  };