@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/lib/client.js ADDED
@@ -0,0 +1,1494 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-prompt-optimizer",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ "use strict";
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __export = (target, all) => {
12
+ for (var name2 in all)
13
+ __defProp(target, name2, { get: all[name2], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
+
25
+ // src/client/index.tsx
26
+ var index_exports = {};
27
+ __export(index_exports, {
28
+ BUTTON_CLASS: () => BUTTON_CLASS,
29
+ apply: () => apply,
30
+ inject: () => inject,
31
+ name: () => name
32
+ });
33
+ module.exports = __toCommonJS(index_exports);
34
+
35
+ // src/client/OptimizeButton.tsx
36
+ var import_react2 = require("react");
37
+
38
+ // src/client/SparkleIcon.tsx
39
+ var import_jsx_runtime = require("react/jsx-runtime");
40
+ function SparkleIcon(props) {
41
+ const size = props.size ?? 14;
42
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
43
+ "svg",
44
+ {
45
+ width: size,
46
+ height: size,
47
+ viewBox: "0 0 24 24",
48
+ fill: "none",
49
+ "aria-hidden": "true",
50
+ style: { display: "block", flexShrink: 0 },
51
+ children: [
52
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
53
+ "path",
54
+ {
55
+ d: "M10 2 L11.6 8.4 L18 10 L11.6 11.6 L10 18 L8.4 11.6 L2 10 L8.4 8.4 Z",
56
+ fill: "currentColor"
57
+ }
58
+ ),
59
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
60
+ "path",
61
+ {
62
+ d: "M17.5 14 L18.3 16.7 L21 17.5 L18.3 18.3 L17.5 21 L16.7 18.3 L14 17.5 L16.7 16.7 Z",
63
+ fill: "currentColor"
64
+ }
65
+ ),
66
+ props.spinning && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("animate", { attributeName: "opacity", values: "1;0.35;1", dur: "1.1s", repeatCount: "indefinite" })
67
+ ]
68
+ }
69
+ );
70
+ }
71
+
72
+ // src/client/i18n.ts
73
+ var import_react = require("react");
74
+ var face = null;
75
+ function installLocaleFace(next) {
76
+ face = next;
77
+ }
78
+ var dict = {
79
+ zh: {
80
+ "button.optimize": "\u4F18\u5316",
81
+ "button.optimizing": "\u4F18\u5316\u4E2D\u2026",
82
+ "button.title": "\u5206\u6790\u5E76\u4F18\u5316\u5F53\u524D\u8F93\u5165\u7684\u63D0\u793A\u8BCD",
83
+ "button.titleEmpty": "\u5148\u5728\u8F93\u5165\u6846\u8F93\u5165\u63D0\u793A\u8BCD",
84
+ "panel.aria": "\u63D0\u793A\u8BCD\u4F18\u5316",
85
+ "panel.title": "\u63D0\u793A\u8BCD\u4F18\u5316",
86
+ "panel.closeTitle": "\u5173\u95ED (Esc)",
87
+ "panel.close": "\u5173\u95ED",
88
+ "panel.stage.waiting": "\u7B49\u5F85\u6A21\u578B\u54CD\u5E94",
89
+ "panel.stage.analyzing": "\u6B63\u5728\u5206\u6790\u8BCA\u65AD",
90
+ "panel.stage.writing": "\u6B63\u5728\u8F93\u51FA\u4F18\u5316\u7A3F",
91
+ "panel.escCancel": "Esc \u53D6\u6D88",
92
+ "panel.analysis": "\u5206\u6790\u8BCA\u65AD",
93
+ "panel.optimized": "\u4F18\u5316\u7ED3\u679C",
94
+ "panel.error": "\u51FA\u9519\u4E86",
95
+ "panel.cancelled": "\u5DF2\u53D6\u6D88\u4F18\u5316,\u4EE5\u4E0B\u4E3A\u5DF2\u751F\u6210\u7684\u90E8\u5206\u5185\u5BB9\u3002",
96
+ "panel.retry": "\u91CD\u8BD5",
97
+ "panel.replace": "\u66FF\u6362\u8F93\u5165\u6846",
98
+ "panel.copy": "\u590D\u5236",
99
+ "panel.copied": "\u5DF2\u590D\u5236 \u2713",
100
+ "panel.reoptimize": "\u91CD\u65B0\u4F18\u5316",
101
+ "panel.reoptimizeTitle": "\u91CD\u65B0\u8FD0\u884C\u4F18\u5316:\u82E5\u8349\u7A3F\u76F8\u5BF9\u4E0A\u4E00\u8F6E\u7ED3\u679C\u6709\u6539\u52A8,\u4F1A\u643A\u5E26\u4E0A\u8F6E\u7ED3\u679C\u7EED\u6539;\u5426\u5219\u5168\u65B0\u751F\u6210",
102
+ "panel.undo": "\u64A4\u56DE",
103
+ "panel.applied": "\u5DF2\u66FF\u6362\u5230\u8F93\u5165\u6846 \u2713",
104
+ "panel.appliedShort": "\u5DF2\u66FF\u6362 \u2713",
105
+ "panel.undoneShort": "\u5DF2\u64A4\u56DE \u2713",
106
+ "panel.fallback": "\u5DF2\u56DE\u9000",
107
+ "panel.duration": "\u7528\u65F6",
108
+ "panel.truncated": "\u8F93\u51FA\u8FBE\u5230 Token \u4E0A\u9650\u88AB\u622A\u65AD\u3002\u53EF\u5728 \u8BBE\u7F6E \u2192 \u63D2\u4EF6\u914D\u7F6E \u2192 \u63D0\u793A\u8BCD\u4F18\u5316 \u4E2D\u8C03\u9AD8\u300C\u6700\u5927\u8F93\u51FA Token\u300D\u3002",
109
+ "panel.notWellFormed": "\u6A21\u578B\u672A\u5B8C\u5168\u9075\u5B88\u8F93\u51FA\u683C\u5F0F,\u4EE5\u4E0A\u5185\u5BB9\u53EF\u80FD\u6DF7\u5165\u591A\u4F59\u6587\u5B57,\u66FF\u6362\u524D\u8BF7\u626B\u4E00\u773C\u3002",
110
+ "settings.desc": "\u53D1\u9001\u680F\u300C\u4F18\u5316\u300D\u6309\u94AE(\u2728 \u56FE\u6807)\u7684\u884C\u4E3A\u914D\u7F6E",
111
+ "settings.loading": "\u8BBE\u7F6E\u52A0\u8F7D\u4E2D\u2026",
112
+ "settings.unavailable": "\u5F53\u524D\u8FDE\u63A5\u4E0D\u53EF\u5199\u8BBE\u7F6E(\u8FDC\u7A0B\u9875\u9762\u4E3A\u5185\u5B58\u6A21\u5F0F),\u6539\u52A8\u4EC5\u5728\u672C\u6B21\u4F1A\u8BDD\u751F\u6548\u3002",
113
+ "settings.memoryOnly": "\u5F53\u524D\u4E3A\u5185\u5B58\u6A21\u5F0F:\u8BBE\u7F6E\u4E0D\u4F1A\u6301\u4E45\u5316\u3002",
114
+ "settings.undo": "\u64A4\u9500\u4E0A\u4E00\u6B21\u4FEE\u6539",
115
+ "settings.undoTitle": "\u6062\u590D\u8FD9\u6B21\u4FEE\u6539\u524D\u7684\u5168\u90E8\u8BBE\u7F6E(\u4EC5\u672C\u6B21\u9875\u9762\u4F1A\u8BDD\u5185\u53EF\u64A4\u9500)",
116
+ "settings.group.model": "\u6A21\u578B",
117
+ "settings.group.params": "\u8C03\u7528\u53C2\u6570",
118
+ "settings.group.context": "\u4E0A\u4E0B\u6587",
119
+ "settings.summary.model": "\u6A21\u578B",
120
+ "settings.summary.mode": "\u6A21\u5F0F",
121
+ "settings.model": "\u4F18\u5316\u7528\u6A21\u578B",
122
+ "settings.model.follow": "\u8DDF\u968F\u5F53\u524D\u4F1A\u8BDD(\u9ED8\u8BA4)",
123
+ "settings.catalog.loading": "\u6A21\u578B\u76EE\u5F55\u52A0\u8F7D\u4E2D\u2026",
124
+ "settings.catalog.error": "\u6A21\u578B\u76EE\u5F55\u52A0\u8F7D\u5931\u8D25,\u70B9\u53F3\u4FA7\u6309\u94AE\u91CD\u8BD5\u3002",
125
+ "settings.refresh": "\u21BB \u5237\u65B0",
126
+ "settings.refreshTitle": "\u91CD\u65B0\u62C9\u53D6\u6A21\u578B\u76EE\u5F55(\u65B0\u589E\u63D0\u4F9B\u65B9/\u6A21\u578B\u540E\u4F7F\u7528)",
127
+ "settings.fallbackModel": "\u56DE\u9000\u6A21\u578B",
128
+ "settings.fallbackModel.none": "\u65E0(\u9ED8\u8BA4)",
129
+ "settings.test": "\u6A21\u578B\u8FDE\u901A\u6027",
130
+ "settings.test.run": "\u6D4B\u8BD5\u8FDE\u63A5",
131
+ "settings.test.running": "\u6D4B\u8BD5\u4E2D\u2026",
132
+ "settings.test.ok": "\u8FDE\u63A5\u6B63\u5E38:{provider} / {model}({latencyMs}ms)",
133
+ "settings.language": "\u8F93\u51FA\u8BED\u8A00",
134
+ "settings.mode": "\u4F18\u5316\u6A21\u5F0F",
135
+ "settings.mode.full": "\u5B8C\u6574(\u5206\u6790\u8BCA\u65AD + \u4F18\u5316)",
136
+ "settings.mode.fast": "\u5FEB\u901F(\u4EC5\u4F18\u5316,\u7B49\u5F85\u7EA6\u51CF\u534A)",
137
+ "settings.mode.full.short": "\u5B8C\u6574",
138
+ "settings.mode.fast.short": "\u5FEB\u901F",
139
+ "settings.effort": "\u63A8\u7406\u5F3A\u5EA6",
140
+ "settings.effort.lowest": "\u964D\u5230\u6700\u4F4E\u6863(\u9ED8\u8BA4,\u63A8\u7406\u6A21\u578B\u66F4\u5FEB)",
141
+ "settings.effort.session": "\u8DDF\u968F\u5F53\u524D\u4F1A\u8BDD",
142
+ "settings.maxTokens": "\u6700\u5927\u8F93\u51FA Token",
143
+ "settings.timeout": "\u8D85\u65F6\u65F6\u95F4(\u79D2)",
144
+ "settings.temperature": "\u91C7\u6837\u6E29\u5EA6",
145
+ "settings.temperatureTitle": "\u4F18\u5316\u662F\u683C\u5F0F\u5316\u4EFB\u52A1,\u4F4E\u6E29\u8F93\u51FA\u66F4\u7A33\u5B9A;\u9ED8\u8BA4 0.2,\u4E00\u822C\u65E0\u9700\u8C03\u6574",
146
+ "settings.autoMaxTokens": "\u8F93\u51FA\u4E0A\u9650\u81EA\u9002\u5E94",
147
+ "settings.autoMaxTokens.on": "\u5F00:\u957F\u8349\u7A3F\u81EA\u52A8\u63D0\u9AD8\u8F93\u51FA\u4E0A\u9650(\u9ED8\u8BA4)",
148
+ "settings.autoMaxTokens.off": "\u5173:\u56FA\u5B9A\u7528\u4E0A\u9762\u7684\u6700\u5927\u8F93\u51FA Token",
149
+ "settings.includeContext": "\u643A\u5E26\u4E0A\u4E0B\u6587",
150
+ "settings.includeContext.on": "\u5F00:\u53C2\u8003\u6700\u8FD1\u5BF9\u8BDD,\u4F18\u5316\u65B9\u5411\u66F4\u8D34\u5408(\u9ED8\u8BA4)",
151
+ "settings.includeContext.off": "\u5173:\u4EC5\u770B\u8349\u7A3F\u672C\u8EAB",
152
+ "settings.validate.maxTokens": "\u8BF7\u8F93\u5165 1024\u201332768 \u4E4B\u95F4\u7684\u6570\u5B57",
153
+ "settings.validate.timeout": "\u8BF7\u8F93\u5165 10\u2013600 \u4E4B\u95F4\u7684\u6570\u5B57",
154
+ "settings.validate.temperature": "\u8BF7\u8F93\u5165 0\u20132 \u4E4B\u95F4\u7684\u6570\u5B57",
155
+ "settings.repoTitle": "\u5728 GitHub \u4E0A\u67E5\u770B\u6E90\u7801 / \u53CD\u9988\u95EE\u9898"
156
+ },
157
+ en: {
158
+ "button.optimize": "Optimize",
159
+ "button.optimizing": "Optimizing\u2026",
160
+ "button.title": "Analyze and optimize the prompt in the input box",
161
+ "button.titleEmpty": "Type a prompt in the input box first",
162
+ "panel.aria": "Prompt optimizer",
163
+ "panel.title": "Prompt Optimizer",
164
+ "panel.closeTitle": "Close (Esc)",
165
+ "panel.close": "Close",
166
+ "panel.stage.waiting": "Waiting for the model",
167
+ "panel.stage.analyzing": "Analyzing",
168
+ "panel.stage.writing": "Writing the optimized prompt",
169
+ "panel.escCancel": "Esc to cancel",
170
+ "panel.analysis": "Analysis",
171
+ "panel.optimized": "Optimized Prompt",
172
+ "panel.error": "Something went wrong",
173
+ "panel.cancelled": "Optimization cancelled; below is the partial output generated so far.",
174
+ "panel.retry": "Retry",
175
+ "panel.replace": "Replace Input",
176
+ "panel.copy": "Copy",
177
+ "panel.copied": "Copied \u2713",
178
+ "panel.reoptimize": "Re-optimize",
179
+ "panel.reoptimizeTitle": "Re-runs optimization: carries the previous result only if the draft changed since then; otherwise regenerates fresh",
180
+ "panel.undo": "Undo",
181
+ "panel.applied": "Replaced into the input box \u2713",
182
+ "panel.appliedShort": "Applied \u2713",
183
+ "panel.undoneShort": "Undone \u2713",
184
+ "panel.fallback": "fallback",
185
+ "panel.duration": "took",
186
+ "panel.truncated": 'Output hit the token cap and was truncated. Raise "Max output tokens" under Settings \u2192 Plugins \u2192 Prompt Optimizer.',
187
+ "panel.notWellFormed": "The model did not fully follow the output format; the content above may contain extra text \u2014 review before replacing.",
188
+ "settings.desc": "Behavior of the composer \u2728 Optimize button",
189
+ "settings.loading": "Loading settings\u2026",
190
+ "settings.unavailable": "This connection cannot write settings (remote page is in-memory); changes apply to this session only.",
191
+ "settings.memoryOnly": "In-memory mode: settings will not persist.",
192
+ "settings.undo": "Undo last change",
193
+ "settings.undoTitle": "Restore all settings to before this change (undo is session-only)",
194
+ "settings.group.model": "Model",
195
+ "settings.group.params": "Generation parameters",
196
+ "settings.group.context": "Context",
197
+ "settings.summary.model": "Model",
198
+ "settings.summary.mode": "Mode",
199
+ "settings.model": "Optimizer model",
200
+ "settings.model.follow": "Follow current session (default)",
201
+ "settings.catalog.loading": "Loading model catalog\u2026",
202
+ "settings.catalog.error": "Failed to load the model catalog \u2014 use the button to retry.",
203
+ "settings.refresh": "\u21BB Refresh",
204
+ "settings.refreshTitle": "Reload the model catalog (after adding providers/models)",
205
+ "settings.fallbackModel": "Fallback model",
206
+ "settings.fallbackModel.none": "None (default)",
207
+ "settings.test": "Connectivity",
208
+ "settings.test.run": "Test connection",
209
+ "settings.test.running": "Testing\u2026",
210
+ "settings.test.ok": "Connected: {provider} / {model} ({latencyMs}ms)",
211
+ "settings.language": "Output language",
212
+ "settings.mode": "Mode",
213
+ "settings.mode.full": "Full (analysis + rewrite)",
214
+ "settings.mode.fast": "Fast (rewrite only, ~half the wait)",
215
+ "settings.mode.full.short": "Full",
216
+ "settings.mode.fast.short": "Fast",
217
+ "settings.effort": "Reasoning effort",
218
+ "settings.effort.lowest": "Clamp to lowest tier (default, faster on reasoning models)",
219
+ "settings.effort.session": "Follow current session",
220
+ "settings.maxTokens": "Max output tokens",
221
+ "settings.timeout": "Timeout (seconds)",
222
+ "settings.temperature": "Temperature",
223
+ "settings.temperatureTitle": "Optimization is a formatting task \u2014 low temperature gives stabler output; default 0.2, usually no need to change",
224
+ "settings.autoMaxTokens": "Adaptive output cap",
225
+ "settings.autoMaxTokens.on": "On: long drafts raise the output cap (default)",
226
+ "settings.autoMaxTokens.off": "Off: always use the max output tokens above",
227
+ "settings.includeContext": "Include context",
228
+ "settings.includeContext.on": "On: read recent conversation for a better-aligned rewrite (default)",
229
+ "settings.includeContext.off": "Off: only look at the draft itself",
230
+ "settings.validate.maxTokens": "Enter a number between 1024 and 32768",
231
+ "settings.validate.timeout": "Enter a number between 10 and 600",
232
+ "settings.validate.temperature": "Enter a number between 0 and 2",
233
+ "settings.repoTitle": "View source / report issues on GitHub"
234
+ }
235
+ };
236
+ function interpolate(text, params) {
237
+ if (!params) return text;
238
+ return text.replace(/\{(\w+)\}/g, (m, name2) => params[name2] !== void 0 ? String(params[name2]) : m);
239
+ }
240
+ function useT() {
241
+ const active = (0, import_react.useSyncExternalStore)(
242
+ (callback) => face?.subscribe(callback) ?? (() => {
243
+ }),
244
+ () => face?.getSnapshot().active === "en" ? "en" : "zh"
245
+ );
246
+ return (key, params) => interpolate(dict[active][key] ?? dict.zh[key], params);
247
+ }
248
+
249
+ // src/client/OptimizeButton.tsx
250
+ var import_jsx_runtime2 = require("react/jsx-runtime");
251
+ var buttonStyle = {
252
+ display: "inline-flex",
253
+ alignItems: "center",
254
+ gap: 4,
255
+ padding: "4px 10px",
256
+ fontSize: 12,
257
+ lineHeight: "18px",
258
+ borderRadius: 6,
259
+ border: "1px solid var(--dsw-alias-border-l2, rgba(128, 128, 128, 0.35))",
260
+ background: "var(--dsw-alias-button-tool-bar-fill, transparent)",
261
+ color: "var(--dsw-alias-label-primary, inherit)",
262
+ cursor: "pointer",
263
+ whiteSpace: "nowrap",
264
+ // U4:预留最宽文案(「优化中…」/「Optimizing…」)的宽度,状态切换不引起工具栏抖动。
265
+ minWidth: 92
266
+ };
267
+ function createOptimizeButton(controller) {
268
+ return function OptimizeButton(props) {
269
+ const state = (0, import_react2.useSyncExternalStore)(controller.subscribe, controller.getSnapshot);
270
+ const t = useT();
271
+ const draft = props.input.draft;
272
+ const empty = !draft.trim();
273
+ const loading = state.status === "loading";
274
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: { display: "inline-flex" }, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
275
+ "button",
276
+ {
277
+ className: "dsh-po-btn",
278
+ type: "button",
279
+ style: { ...buttonStyle, ...empty || loading ? { opacity: 0.45, cursor: "not-allowed" } : {} },
280
+ disabled: empty || loading,
281
+ title: empty ? t("button.titleEmpty") : t("button.title"),
282
+ onClick: () => void controller.optimize(draft, props.sessionId),
283
+ children: [
284
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(SparkleIcon, { spinning: loading }),
285
+ loading ? t("button.optimizing") : t("button.optimize")
286
+ ]
287
+ }
288
+ ) });
289
+ };
290
+ }
291
+
292
+ // src/client/ResultDock.tsx
293
+ var import_react3 = require("react");
294
+
295
+ // src/prompt.ts
296
+ var MARKERS = {
297
+ analysis: "<<<ANALYSIS>>>",
298
+ optimized: "<<<OPTIMIZED>>>",
299
+ end: "<<<END>>>"
300
+ };
301
+ var FORMAT_FULL_ZH = `# \u8F93\u51FA\u683C\u5F0F(\u4E25\u683C\u9075\u5B88,\u6807\u8BB0\u884C\u5355\u72EC\u6210\u884C)
302
+ ${MARKERS.analysis}
303
+ \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
304
+ ${MARKERS.optimized}
305
+ \u8F93\u51FA\u4F18\u5316\u540E\u7684\u5B8C\u6574\u63D0\u793A\u8BCD\u5168\u6587
306
+ ${MARKERS.end}
307
+
308
+ \u9664\u4E0A\u8FF0\u6807\u8BB0\u5305\u88F9\u7684\u5185\u5BB9\u5916,\u4E0D\u8981\u8F93\u51FA\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002`;
309
+ var FORMAT_FULL_EN = `# Output format (strictly follow; markers on their own lines)
310
+ ${MARKERS.analysis}
311
+ One finding per line: "dimension | issue | suggestion". If a dimension is fine: "dimension | no issue | -".
312
+ ${MARKERS.optimized}
313
+ The full optimized prompt text
314
+ ${MARKERS.end}
315
+
316
+ Do not output anything outside these markers.`;
317
+ var FORMAT_FAST_ZH = `# \u8F93\u51FA\u683C\u5F0F(\u4E25\u683C\u9075\u5B88,\u6807\u8BB0\u884C\u5355\u72EC\u6210\u884C)
318
+ ${MARKERS.optimized}
319
+ \u8F93\u51FA\u4F18\u5316\u540E\u7684\u5B8C\u6574\u63D0\u793A\u8BCD\u5168\u6587
320
+ ${MARKERS.end}
321
+
322
+ \u9664\u4E0A\u8FF0\u6807\u8BB0\u5305\u88F9\u7684\u5185\u5BB9\u5916,\u4E0D\u8981\u8F93\u51FA\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002`;
323
+ var FORMAT_FAST_EN = `# Output format (strictly follow; markers on their own lines)
324
+ ${MARKERS.optimized}
325
+ The full optimized prompt text
326
+ ${MARKERS.end}
327
+
328
+ Do not output anything outside these markers.`;
329
+ var CONTEXT_MAX_TURNS = 8;
330
+ var CONTEXT_MAX_CHARS = 1600;
331
+ var CONTEXT_TURN_MAX_CHARS = 600;
332
+ function capConversationContext(turns) {
333
+ const recent = turns.filter((t) => t.text.trim()).slice(-CONTEXT_MAX_TURNS).map((t) => ({
334
+ role: t.role,
335
+ text: t.text.trim().length > CONTEXT_TURN_MAX_CHARS ? `${t.text.trim().slice(0, CONTEXT_TURN_MAX_CHARS)}\u2026` : t.text.trim()
336
+ }));
337
+ let budget = CONTEXT_MAX_CHARS;
338
+ const kept = [];
339
+ for (let i = recent.length - 1; i >= 0; i--) {
340
+ const turn = recent[i];
341
+ if (turn.text.length > budget) {
342
+ if (kept.length === 0) kept.push({ role: turn.role, text: `${turn.text.slice(0, budget)}\u2026` });
343
+ break;
344
+ }
345
+ kept.unshift(turn);
346
+ budget -= turn.text.length;
347
+ }
348
+ return kept;
349
+ }
350
+ function findMarker(text, word, fromIndex = 0) {
351
+ const re = new RegExp(`<<<\\s*${word}\\s*>>>`, "g");
352
+ re.lastIndex = fromIndex;
353
+ const match = re.exec(text);
354
+ return match ? { index: match.index, length: match[0].length } : null;
355
+ }
356
+ function parsePartialOptimizerOutput(raw) {
357
+ const a = findMarker(raw, "ANALYSIS");
358
+ const o = findMarker(raw, "OPTIMIZED");
359
+ let analysis = "";
360
+ let optimized = "";
361
+ if (a && (!o || a.index < o.index)) {
362
+ analysis = raw.slice(a.index + a.length, o ? o.index : raw.length).trim();
363
+ }
364
+ if (o) {
365
+ const e = findMarker(raw, "END", o.index + o.length);
366
+ optimized = raw.slice(o.index + o.length, e ? e.index : raw.length).trim();
367
+ }
368
+ return { analysis, optimized };
369
+ }
370
+ function compactPartialBuffer(raw) {
371
+ const o = findMarker(raw, "OPTIMIZED");
372
+ if (!o) return { compacted: null, analysis: "" };
373
+ const a = findMarker(raw, "ANALYSIS");
374
+ const analysis = a && a.index < o.index ? raw.slice(a.index + a.length, o.index).trim() : "";
375
+ return { compacted: `${MARKERS.optimized}
376
+ ${raw.slice(o.index + o.length)}`, analysis };
377
+ }
378
+
379
+ // src/client/controller.ts
380
+ var ROUTE = "/dsh-prompt-optimizer/optimize";
381
+ var INITIAL = { open: false, status: "idle", error: null, result: null, live: null, last: null, applied: null };
382
+ function splitCommandPrefix(text) {
383
+ const trimmed = text.trim();
384
+ const match = /^(\/[A-Za-z][\w-]*)(?:\s+([\s\S]+))?$/.exec(trimmed);
385
+ if (!match) return { body: trimmed };
386
+ if (!match[2] || !match[2].trim()) return { body: trimmed, commandOnly: true };
387
+ return { prefix: match[1], body: match[2].trim() };
388
+ }
389
+ function shouldAutoClose(input) {
390
+ if (!input.open || input.status === "loading") return false;
391
+ return !input.draft.trim() || !input.prevRunning && input.running || input.queued > input.prevQueued;
392
+ }
393
+ function flattenText(content) {
394
+ if (!Array.isArray(content)) return "";
395
+ return content.map(
396
+ (block) => block && typeof block === "object" && block.type === "text" ? String(block.text ?? "") : ""
397
+ ).filter(Boolean).join("\n").trim();
398
+ }
399
+ function sampleContextTurns(turns) {
400
+ const users = turns.map((t, i) => ({ t, i })).filter((x) => x.t.role === "user").slice(-4);
401
+ const assistants = turns.map((t, i) => ({ t, i })).filter((x) => x.t.role === "assistant").slice(-4);
402
+ const merged = [...users, ...assistants].sort((a, b) => a.i - b.i).map((x) => x.t);
403
+ return capConversationContext(merged);
404
+ }
405
+ function extractContextTurns(entries) {
406
+ const turns = [];
407
+ for (const entry of entries) {
408
+ const event = entry?.event;
409
+ if (!event || typeof event !== "object") continue;
410
+ if (event.type === "user/message") {
411
+ const data = event.data;
412
+ if (data?.source?.kind !== "user") continue;
413
+ const text = flattenText(data.content);
414
+ if (text) turns.push({ role: "user", text });
415
+ } else if (event.type === "assistant/message") {
416
+ const data = event.data;
417
+ const text = flattenText(data?.message?.content);
418
+ if (text) turns.push({ role: "assistant", text });
419
+ }
420
+ }
421
+ return sampleContextTurns(turns);
422
+ }
423
+ function createOptimizerController(ctx, opts = {}) {
424
+ let state = INITIAL;
425
+ const listeners = /* @__PURE__ */ new Set();
426
+ let abort = null;
427
+ let liveRaw = "";
428
+ let frozenAnalysis = "";
429
+ let liveTimer = null;
430
+ const clearLiveTimer = () => {
431
+ if (liveTimer) {
432
+ clearTimeout(liveTimer);
433
+ liveTimer = null;
434
+ }
435
+ };
436
+ const set = (patch) => {
437
+ state = { ...state, ...patch };
438
+ for (const listener of listeners) listener();
439
+ };
440
+ async function optimize(text, sessionId) {
441
+ const split = splitCommandPrefix(text);
442
+ const { prefix, body: draft } = split;
443
+ if (!draft || state.status === "loading") return;
444
+ if (split.commandOnly) {
445
+ set({
446
+ open: true,
447
+ status: "error",
448
+ error: "\u68C0\u6D4B\u5230\u659C\u6760\u547D\u4EE4\u4F46\u6CA1\u6709\u6B63\u6587:\u8BF7\u5148\u8F93\u5165\u8981\u4F18\u5316\u7684\u5185\u5BB9\u3002",
449
+ live: null,
450
+ last: { text: draft, sessionId }
451
+ });
452
+ return;
453
+ }
454
+ const previous = state.result && state.result.wellFormed && state.last?.sessionId === sessionId && state.last.text !== draft && (opts.isContextEnabled?.() ?? true) ? state.result.optimized : void 0;
455
+ abort?.abort();
456
+ clearLiveTimer();
457
+ liveRaw = "";
458
+ frozenAnalysis = "";
459
+ const controller = new AbortController();
460
+ abort = controller;
461
+ const watchdogMs = Math.max(1e3, opts.getWatchdogMs?.() ?? 125e3);
462
+ let clientTimedOut = false;
463
+ const watchdog = setTimeout(() => {
464
+ clientTimedOut = true;
465
+ controller.abort();
466
+ }, watchdogMs);
467
+ const failTimeout = () => {
468
+ clearLiveTimer();
469
+ const seconds = Math.round(watchdogMs / 1e3);
470
+ set({
471
+ status: "error",
472
+ live: null,
473
+ 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`
474
+ });
475
+ };
476
+ const startedAt = Date.now();
477
+ set({ open: true, status: "loading", error: null, live: { analysis: "", optimized: "" }, last: { text: draft, sessionId, prefix }, applied: null });
478
+ try {
479
+ const [selection, context] = await Promise.all([
480
+ (async () => {
481
+ if (opts.isModelPinned?.()) return void 0;
482
+ try {
483
+ const resp2 = await ctx.connection.api.sessions.models({ sessionId }, controller.signal);
484
+ if (resp2.result.ok) {
485
+ const current = resp2.result.value.current;
486
+ return { provider: current.provider, model: current.model, reasoningEffort: current.reasoningEffort };
487
+ }
488
+ console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u6A21\u578B\u67E5\u8BE2\u88AB\u62D2\u7EDD,\u6539\u7528 Host \u56DE\u9000:", resp2.result.error);
489
+ } catch (cause) {
490
+ console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u6A21\u578B\u67E5\u8BE2\u5931\u8D25,\u6539\u7528 Host \u56DE\u9000:", cause);
491
+ }
492
+ return void 0;
493
+ })(),
494
+ (async () => {
495
+ if (!(opts.isContextEnabled?.() ?? true)) return void 0;
496
+ try {
497
+ const resp2 = await ctx.connection.api.sessions.history({ sessionId, maxMessages: 24 }, controller.signal);
498
+ if (resp2.result.ok) {
499
+ const turns = extractContextTurns(resp2.result.value.events);
500
+ return turns.length ? turns : void 0;
501
+ }
502
+ console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u5386\u53F2\u67E5\u8BE2\u88AB\u62D2\u7EDD,\u6309\u65E0\u4E0A\u4E0B\u6587\u4F18\u5316:", resp2.result.error);
503
+ } catch (cause) {
504
+ console.warn("[dsh-prompt-optimizer] \u4F1A\u8BDD\u5386\u53F2\u67E5\u8BE2\u5931\u8D25,\u6309\u65E0\u4E0A\u4E0B\u6587\u4F18\u5316:", cause);
505
+ }
506
+ return void 0;
507
+ })()
508
+ ]);
509
+ const resp = await fetch(ROUTE, {
510
+ method: "POST",
511
+ headers: { "content-type": "application/json" },
512
+ body: JSON.stringify({ text: draft, provider: selection?.provider, model: selection?.model, reasoningEffort: selection?.reasoningEffort, context, previous }),
513
+ signal: controller.signal
514
+ });
515
+ if (!resp.ok || !(resp.headers.get("content-type") ?? "").includes("text/event-stream")) {
516
+ const data = await resp.json().catch(() => null);
517
+ if (!controller.signal.aborted) {
518
+ set({ status: "error", live: null, error: String(data?.error ?? `\u8BF7\u6C42\u5931\u8D25(HTTP ${resp.status})`) });
519
+ }
520
+ return;
521
+ }
522
+ const reader = resp.body?.getReader();
523
+ if (!reader) throw new Error("\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301\u6D41\u5F0F\u54CD\u5E94");
524
+ const decoder = new TextDecoder();
525
+ let buffer = "";
526
+ let terminal = false;
527
+ for (; ; ) {
528
+ const { done, value } = await reader.read();
529
+ if (done) break;
530
+ buffer += decoder.decode(value, { stream: true });
531
+ let sep;
532
+ while ((sep = buffer.indexOf("\n\n")) !== -1) {
533
+ const frame = buffer.slice(0, sep);
534
+ buffer = buffer.slice(sep + 2);
535
+ const line = frame.split("\n").find((l) => l.startsWith("data:"));
536
+ if (!line) continue;
537
+ const event = JSON.parse(line.slice(5).trim());
538
+ if (event.type === "delta") {
539
+ liveRaw += String(event.text ?? "");
540
+ if (!liveTimer) {
541
+ liveTimer = setTimeout(() => {
542
+ liveTimer = null;
543
+ if (state.status === "loading" && abort === controller) {
544
+ const comp = compactPartialBuffer(liveRaw);
545
+ if (comp.compacted !== null) {
546
+ frozenAnalysis = comp.analysis;
547
+ liveRaw = comp.compacted;
548
+ }
549
+ const partial = parsePartialOptimizerOutput(liveRaw);
550
+ const live = { analysis: partial.analysis || frozenAnalysis, optimized: partial.optimized };
551
+ if (opts.isFastMode?.() && !live.analysis && !live.optimized && liveRaw.trim() && !liveRaw.includes("<<<")) {
552
+ live.optimized = liveRaw.trim();
553
+ }
554
+ set({ live });
555
+ }
556
+ }, 50);
557
+ }
558
+ } else if (event.type === "done") {
559
+ terminal = true;
560
+ clearLiveTimer();
561
+ set({
562
+ status: "done",
563
+ live: null,
564
+ result: {
565
+ analysis: String(event.analysis ?? ""),
566
+ optimized: String(event.optimized ?? ""),
567
+ wellFormed: event.wellFormed !== false,
568
+ truncated: event.truncated === true,
569
+ provider: String(event.provider ?? ""),
570
+ model: String(event.model ?? ""),
571
+ fallbackUsed: event.fallbackUsed === true,
572
+ fallbackReason: typeof event.fallbackReason === "string" && event.fallbackReason ? event.fallbackReason : void 0,
573
+ durationMs: Date.now() - startedAt
574
+ }
575
+ });
576
+ } else if (event.type === "error") {
577
+ terminal = true;
578
+ clearLiveTimer();
579
+ set({ status: "error", live: null, error: String(event.error ?? "\u672A\u77E5\u9519\u8BEF") });
580
+ }
581
+ }
582
+ }
583
+ if (!terminal) {
584
+ if (!controller.signal.aborted) {
585
+ clearLiveTimer();
586
+ set({ status: "error", live: null, error: "\u8FDE\u63A5\u4E2D\u65AD:\u54CD\u5E94\u6D41\u63D0\u524D\u7ED3\u675F" });
587
+ } else if (clientTimedOut && abort === controller) {
588
+ failTimeout();
589
+ }
590
+ }
591
+ } catch (cause) {
592
+ if (controller.signal.aborted) {
593
+ if (clientTimedOut && abort === controller) failTimeout();
594
+ return;
595
+ }
596
+ set({ status: "error", live: null, error: cause instanceof Error ? cause.message : String(cause) });
597
+ } finally {
598
+ clearTimeout(watchdog);
599
+ }
600
+ }
601
+ return {
602
+ subscribe(listener) {
603
+ listeners.add(listener);
604
+ return () => listeners.delete(listener);
605
+ },
606
+ getSnapshot: () => state,
607
+ optimize,
608
+ retry() {
609
+ if (state.last) void optimize(state.last.text, state.last.sessionId);
610
+ },
611
+ markApplied(applied) {
612
+ set({ applied });
613
+ },
614
+ clearApplied() {
615
+ if (state.applied) set({ applied: null });
616
+ },
617
+ close() {
618
+ abort?.abort();
619
+ abort = null;
620
+ clearLiveTimer();
621
+ set({ ...INITIAL });
622
+ },
623
+ /**
624
+ * O2:loading 中取消(Esc)。与 close 不同:中止请求但不清空状态,
625
+ * 面板定格展示已生成的部分——用户等了几十秒的内容不应一键蒸发。
626
+ * 后续可「重新优化」续跑或「关闭」彻底收起。
627
+ */
628
+ cancel() {
629
+ if (state.status !== "loading") return;
630
+ abort?.abort();
631
+ abort = null;
632
+ clearLiveTimer();
633
+ set({ status: "cancelled" });
634
+ }
635
+ };
636
+ }
637
+
638
+ // src/client/ResultDock.tsx
639
+ var import_jsx_runtime3 = require("react/jsx-runtime");
640
+ async function copyText(text) {
641
+ try {
642
+ await navigator.clipboard.writeText(text);
643
+ return true;
644
+ } catch {
645
+ try {
646
+ const ta = document.createElement("textarea");
647
+ ta.value = text;
648
+ ta.style.position = "fixed";
649
+ ta.style.opacity = "0";
650
+ document.body.appendChild(ta);
651
+ ta.select();
652
+ const ok = document.execCommand("copy");
653
+ ta.remove();
654
+ return ok;
655
+ } catch {
656
+ return false;
657
+ }
658
+ }
659
+ }
660
+ var styles = {
661
+ panel: {
662
+ marginBottom: 6,
663
+ borderRadius: 10,
664
+ border: "1px solid var(--dsw-alias-border-l2, rgba(128, 128, 128, 0.3))",
665
+ background: "var(--dsw-alias-bg-layer-2, #202226)",
666
+ color: "var(--dsw-alias-label-primary, inherit)",
667
+ boxShadow: "0 4px 16px rgba(0, 0, 0, 0.12)",
668
+ padding: "10px 12px",
669
+ fontSize: 12.5,
670
+ lineHeight: 1.5,
671
+ fontFamily: "var(--dsw-font-family, inherit)"
672
+ },
673
+ header: { display: "flex", alignItems: "center", gap: 6, marginBottom: 2 },
674
+ title: { fontWeight: 600, flex: 1 },
675
+ modelBadge: {
676
+ fontSize: 11,
677
+ color: "var(--dsw-alias-label-primary-dimmed, rgba(128,128,128,0.9))",
678
+ border: "1px solid var(--dsw-alias-border-l3, rgba(128,128,128,0.25))",
679
+ borderRadius: 999,
680
+ padding: "0 8px"
681
+ },
682
+ close: {
683
+ border: "none",
684
+ background: "transparent",
685
+ color: "var(--dsw-alias-label-primary-dimmed, inherit)",
686
+ cursor: "pointer",
687
+ fontSize: 14,
688
+ padding: "0 4px"
689
+ },
690
+ // U5:分析与优化各自独立滚动区(原先单容器 maxHeight 嵌套出现双滚动条),
691
+ // 长内容不再互相挤压;外层 body 不限高,滚动归属到各段内部。
692
+ body: { paddingRight: 4 },
693
+ analysisBody: { maxHeight: "16vh", overflowY: "auto", marginTop: 2 },
694
+ optimizedBox: {
695
+ background: "var(--dsw-alias-bg-layer-3, rgba(128,128,128,0.08))",
696
+ borderRadius: 6,
697
+ padding: "6px 8px",
698
+ maxHeight: "26vh",
699
+ overflowY: "auto",
700
+ marginTop: 2
701
+ },
702
+ sectionTitle: {
703
+ // U5:段落标题可点击折叠;去掉默认按钮外观。
704
+ display: "inline-flex",
705
+ alignItems: "center",
706
+ gap: 4,
707
+ fontSize: 11,
708
+ fontWeight: 600,
709
+ color: "var(--dsw-alias-label-primary-dimmed, rgba(128,128,128,0.9))",
710
+ margin: "6px 0 2px",
711
+ padding: 0,
712
+ border: "none",
713
+ background: "none",
714
+ font: "inherit",
715
+ cursor: "pointer",
716
+ textAlign: "left"
717
+ },
718
+ chevron: { fontSize: 9, transition: "transform 0.15s ease" },
719
+ pre: { margin: 0, whiteSpace: "pre-wrap", wordBreak: "break-word", fontFamily: "inherit" },
720
+ actions: { display: "flex", gap: 8, marginTop: 8 },
721
+ actionBtn: {
722
+ display: "inline-flex",
723
+ alignItems: "center",
724
+ padding: "4px 12px",
725
+ fontSize: 12,
726
+ borderRadius: 6,
727
+ border: "1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.4))",
728
+ background: "var(--dsw-alias-button-tool-bar-fill, transparent)",
729
+ color: "var(--dsw-alias-label-primary, inherit)",
730
+ cursor: "pointer"
731
+ },
732
+ primaryBtn: {
733
+ background: "var(--dsw-alias-button-primary-fill, #3b6ef6)",
734
+ borderColor: "transparent",
735
+ color: "var(--dsw-alias-label-primary-inverted, #fff)"
736
+ },
737
+ errorText: { color: "var(--dsw-alias-state-error-primary, #e5534b)", whiteSpace: "pre-wrap" },
738
+ // U7/O6:头部状态条(绿色描边小徽章)。
739
+ statusChip: {
740
+ fontSize: 11,
741
+ color: "var(--dsw-alias-state-success-primary, #2da44e)",
742
+ border: "1px solid currentColor",
743
+ borderRadius: 999,
744
+ padding: "0 8px",
745
+ whiteSpace: "nowrap"
746
+ },
747
+ // U10/R5:质量警示(truncated / notWellFormed)从灰色小字升级为描边警示框,
748
+ // 让「替换前请检查」被真正看到;notWellFormed 横幅置于内容区顶部(R5)。
749
+ warnBanner: {
750
+ display: "flex",
751
+ alignItems: "flex-start",
752
+ gap: 6,
753
+ marginTop: 8,
754
+ padding: "6px 8px",
755
+ fontSize: 12,
756
+ lineHeight: 1.5,
757
+ borderRadius: 6,
758
+ border: "1px solid var(--dsw-alias-state-warn-primary, #d4a72c)",
759
+ background: "var(--dsw-alias-state-warn-bg, rgba(212, 167, 44, 0.12))",
760
+ color: "var(--dsw-alias-state-warn-primary, #d4a72c)"
761
+ },
762
+ cancelledHint: {
763
+ fontSize: 12,
764
+ color: "var(--dsw-alias-state-warn-primary, #d4a72c)",
765
+ padding: "4px 0 2px"
766
+ },
767
+ loading: {
768
+ display: "flex",
769
+ alignItems: "center",
770
+ gap: 8,
771
+ color: "var(--dsw-alias-label-primary-dimmed, inherit)",
772
+ padding: "8px 0"
773
+ }
774
+ };
775
+ function createResultDock(controller) {
776
+ return function OptimizerResultDock(props) {
777
+ const state = (0, import_react3.useSyncExternalStore)(controller.subscribe, controller.getSnapshot);
778
+ const t = useT();
779
+ const [copied, setCopied] = (0, import_react3.useState)(false);
780
+ const [analysisOpen, setAnalysisOpen] = (0, import_react3.useState)(true);
781
+ const [undoneFlash, setUndoneFlash] = (0, import_react3.useState)(false);
782
+ const owns = state.open && state.last?.sessionId === props.sessionId;
783
+ (0, import_react3.useEffect)(() => {
784
+ if (!owns) return;
785
+ const onKey = (event) => {
786
+ if (event.key !== "Escape") return;
787
+ if (controller.getSnapshot().status === "loading") controller.cancel();
788
+ else controller.close();
789
+ };
790
+ document.addEventListener("keydown", onKey);
791
+ return () => document.removeEventListener("keydown", onKey);
792
+ }, [owns]);
793
+ const applied = state.applied;
794
+ const draft = props.input.draft;
795
+ const running = Boolean(props.session?.running);
796
+ const queued = props.session?.queue?.length ?? 0;
797
+ const prevRef = (0, import_react3.useRef)({ running, queued });
798
+ (0, import_react3.useEffect)(() => {
799
+ const prev = prevRef.current;
800
+ prevRef.current = { running, queued };
801
+ if (!owns) return;
802
+ if (shouldAutoClose({ open: true, status: state.status, draft, prevRunning: prev.running, running, prevQueued: prev.queued, queued })) {
803
+ controller.close();
804
+ return;
805
+ }
806
+ if (applied && draft !== applied.text) controller.clearApplied();
807
+ }, [draft, applied, owns, state.status, running, queued]);
808
+ const [elapsed, setElapsed] = (0, import_react3.useState)(0);
809
+ (0, import_react3.useEffect)(() => {
810
+ if (state.status !== "loading") return;
811
+ const started = Date.now();
812
+ setElapsed(0);
813
+ const timer = setInterval(() => setElapsed(Math.floor((Date.now() - started) / 1e3)), 1e3);
814
+ return () => clearInterval(timer);
815
+ }, [state.status]);
816
+ (0, import_react3.useEffect)(() => {
817
+ if (!undoneFlash) return;
818
+ const timer = setTimeout(() => setUndoneFlash(false), 2500);
819
+ return () => clearTimeout(timer);
820
+ }, [undoneFlash]);
821
+ const liveBoxRef = (0, import_react3.useRef)(null);
822
+ const stickRef = (0, import_react3.useRef)(true);
823
+ (0, import_react3.useEffect)(() => {
824
+ if (state.status === "loading") stickRef.current = true;
825
+ }, [state.status]);
826
+ (0, import_react3.useEffect)(() => {
827
+ const el = liveBoxRef.current;
828
+ if (!el || state.status !== "loading") return;
829
+ if (stickRef.current) el.scrollTop = el.scrollHeight;
830
+ }, [state.live, state.status]);
831
+ const onLiveScroll = () => {
832
+ const el = liveBoxRef.current;
833
+ if (!el) return;
834
+ stickRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 28;
835
+ };
836
+ if (!owns) return null;
837
+ const { result } = state;
838
+ const stage = state.live?.optimized ? t("panel.stage.writing") : state.live?.analysis ? t("panel.stage.analyzing") : t("panel.stage.waiting");
839
+ const liveBody = state.live && (state.live.analysis || state.live.optimized) ? /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { ref: liveBoxRef, onScroll: onLiveScroll, style: { ...styles.body, maxHeight: "34vh", overflowY: "auto", marginTop: 2 }, children: [
840
+ state.live.analysis && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
841
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: styles.sectionTitle, children: t("panel.analysis") }),
842
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("pre", { style: styles.pre, children: state.live.analysis })
843
+ ] }),
844
+ state.live.optimized && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
845
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: styles.sectionTitle, children: t("panel.optimized") }),
846
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: styles.optimizedBox, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("pre", { style: styles.pre, children: state.live.optimized }) })
847
+ ] })
848
+ ] }) : null;
849
+ const onCopy = async () => {
850
+ if (!result) return;
851
+ setCopied(await copyText(result.optimized));
852
+ setTimeout(() => setCopied(false), 1500);
853
+ };
854
+ const onReplace = () => {
855
+ if (!result) return;
856
+ const nextDraft = state.last?.prefix ? `${state.last.prefix} ${result.optimized}` : result.optimized;
857
+ controller.markApplied({ backup: props.input.draft, text: nextDraft });
858
+ props.inputActions.setDraft(nextDraft);
859
+ };
860
+ const onUndo = () => {
861
+ if (!applied) return;
862
+ props.inputActions.setDraft(applied.backup);
863
+ controller.clearApplied();
864
+ setUndoneFlash(true);
865
+ };
866
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: styles.panel, role: "dialog", "aria-label": t("panel.aria"), children: [
867
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: styles.header, children: [
868
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(SparkleIcon, { size: 15 }),
869
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: styles.title, children: t("panel.title") }),
870
+ result && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
871
+ "span",
872
+ {
873
+ style: styles.modelBadge,
874
+ title: result.fallbackUsed && result.fallbackReason ? `${t("panel.fallback")}: ${result.fallbackReason}` : void 0,
875
+ children: [
876
+ result.provider,
877
+ " / ",
878
+ result.model,
879
+ result.fallbackUsed ? ` \xB7 ${t("panel.fallback")}` : "",
880
+ typeof result.durationMs === "number" ? ` \xB7 ${t("panel.duration")} ${(result.durationMs / 1e3).toFixed(1)}s` : ""
881
+ ]
882
+ }
883
+ ),
884
+ applied && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: styles.statusChip, children: t("panel.appliedShort") }),
885
+ !applied && undoneFlash && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: styles.statusChip, children: t("panel.undoneShort") }),
886
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { className: "dsh-po-btn", type: "button", style: styles.close, title: t("panel.closeTitle"), onClick: () => controller.close(), children: "\u2715" })
887
+ ] }),
888
+ state.status === "loading" && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
889
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: styles.loading, children: [
890
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(SparkleIcon, { spinning: true }),
891
+ stage,
892
+ "\u2026(",
893
+ elapsed,
894
+ "s,",
895
+ t("panel.escCancel"),
896
+ ")"
897
+ ] }),
898
+ liveBody
899
+ ] }),
900
+ state.status === "cancelled" && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
901
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: styles.cancelledHint, children: t("panel.cancelled") }),
902
+ liveBody,
903
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: styles.actions, children: [
904
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { className: "dsh-po-btn", type: "button", style: { ...styles.actionBtn, ...styles.primaryBtn }, title: t("panel.reoptimizeTitle"), onClick: () => controller.retry(), children: t("panel.reoptimize") }),
905
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { className: "dsh-po-btn", type: "button", style: styles.actionBtn, onClick: () => controller.close(), children: t("panel.close") })
906
+ ] })
907
+ ] }),
908
+ state.status === "error" && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
909
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: styles.sectionTitle, children: t("panel.error") }),
910
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: styles.errorText, children: state.error }),
911
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: styles.actions, children: [
912
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { className: "dsh-po-btn", type: "button", style: styles.actionBtn, title: t("panel.reoptimizeTitle"), onClick: () => controller.retry(), children: t("panel.retry") }),
913
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { className: "dsh-po-btn", type: "button", style: styles.actionBtn, onClick: () => controller.close(), children: t("panel.close") })
914
+ ] })
915
+ ] }),
916
+ state.status === "done" && result && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
917
+ !result.wellFormed && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: { ...styles.warnBanner, marginTop: 0, marginBottom: 8 }, children: [
918
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { "aria-hidden": true, children: "\u26A0" }),
919
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { children: t("panel.notWellFormed") })
920
+ ] }),
921
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: styles.body, children: [
922
+ result.analysis && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
923
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("button", { className: "dsh-po-btn", type: "button", style: styles.sectionTitle, onClick: () => setAnalysisOpen((v) => !v), "aria-expanded": analysisOpen, children: [
924
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { ...styles.chevron, transform: analysisOpen ? "rotate(90deg)" : "none" }, children: "\u25B8" }),
925
+ t("panel.analysis")
926
+ ] }),
927
+ analysisOpen && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: styles.analysisBody, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("pre", { style: styles.pre, children: result.analysis }) })
928
+ ] }),
929
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: { ...styles.sectionTitle, cursor: "default" }, children: t("panel.optimized") }),
930
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: styles.optimizedBox, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("pre", { style: styles.pre, children: result.optimized }) }),
931
+ result.truncated && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: styles.warnBanner, children: [
932
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { "aria-hidden": true, children: "\u26A0" }),
933
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { children: t("panel.truncated") })
934
+ ] })
935
+ ] }),
936
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: styles.actions, children: applied ? /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
937
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { className: "dsh-po-btn", type: "button", style: { ...styles.actionBtn, ...styles.primaryBtn }, onClick: onUndo, children: t("panel.undo") }),
938
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { className: "dsh-po-btn", type: "button", style: styles.actionBtn, title: t("panel.reoptimizeTitle"), onClick: () => controller.retry(), children: t("panel.reoptimize") }),
939
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { className: "dsh-po-btn", type: "button", style: styles.actionBtn, onClick: () => controller.close(), children: t("panel.close") })
940
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
941
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { className: "dsh-po-btn", type: "button", style: { ...styles.actionBtn, ...styles.primaryBtn }, onClick: onReplace, children: t("panel.replace") }),
942
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { className: "dsh-po-btn", type: "button", style: styles.actionBtn, onClick: onCopy, children: copied ? t("panel.copied") : t("panel.copy") }),
943
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { className: "dsh-po-btn", type: "button", style: styles.actionBtn, title: t("panel.reoptimizeTitle"), onClick: () => controller.retry(), children: t("panel.reoptimize") }),
944
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { className: "dsh-po-btn", type: "button", style: styles.actionBtn, onClick: () => controller.close(), children: t("panel.close") })
945
+ ] }) })
946
+ ] })
947
+ ] });
948
+ };
949
+ }
950
+
951
+ // src/client/SettingsCard.tsx
952
+ var import_react4 = require("react");
953
+
954
+ // src/client/GitHubIcon.tsx
955
+ var import_jsx_runtime4 = require("react/jsx-runtime");
956
+ function GitHubIcon(props) {
957
+ const size = props.size ?? 16;
958
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
959
+ "svg",
960
+ {
961
+ width: size,
962
+ height: size,
963
+ viewBox: "0 0 16 16",
964
+ "aria-hidden": "true",
965
+ fill: "currentColor",
966
+ style: { display: "block", flexShrink: 0 },
967
+ children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("path", { d: "M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z" })
968
+ }
969
+ );
970
+ }
971
+
972
+ // src/client/SettingsCard.tsx
973
+ var import_jsx_runtime5 = require("react/jsx-runtime");
974
+ var REPO_URL = "https://github.com/Y1X1n/dsh-prompt-optimizer";
975
+ var FOLLOW_SESSION = "";
976
+ var styles2 = {
977
+ card: {
978
+ border: "1px solid var(--dsw-alias-border-l2, rgba(128, 128, 128, 0.3))",
979
+ borderRadius: 10,
980
+ padding: "14px 16px",
981
+ fontSize: 13,
982
+ lineHeight: 1.6,
983
+ color: "var(--dsw-alias-label-primary, inherit)",
984
+ fontFamily: "var(--dsw-font-family, inherit)"
985
+ },
986
+ title: { fontSize: 14, fontWeight: 600 },
987
+ desc: { color: "var(--dsw-alias-label-primary-dimmed, rgba(128,128,128,0.9))", marginBottom: 12 },
988
+ headerBtn: {
989
+ display: "flex",
990
+ alignItems: "center",
991
+ gap: 6,
992
+ width: "100%",
993
+ padding: 0,
994
+ border: "none",
995
+ background: "none",
996
+ color: "inherit",
997
+ font: "inherit",
998
+ cursor: "pointer",
999
+ textAlign: "left"
1000
+ },
1001
+ chevron: {
1002
+ fontSize: 11,
1003
+ color: "var(--dsw-alias-label-primary-dimmed, rgba(128,128,128,0.9))",
1004
+ transition: "transform 0.15s ease"
1005
+ },
1006
+ headerDesc: {
1007
+ marginLeft: "auto",
1008
+ fontSize: 12,
1009
+ fontWeight: 400,
1010
+ color: "var(--dsw-alias-label-primary-dimmed, rgba(128,128,128,0.9))"
1011
+ },
1012
+ body: { marginTop: 12 },
1013
+ row: { display: "flex", alignItems: "center", gap: 10, marginBottom: 10 },
1014
+ label: { width: 110, flexShrink: 0, color: "var(--dsw-alias-label-primary, inherit)" },
1015
+ input: {
1016
+ flex: 1,
1017
+ maxWidth: 320,
1018
+ padding: "4px 8px",
1019
+ fontSize: 13,
1020
+ borderRadius: 6,
1021
+ border: "1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.4))",
1022
+ background: "var(--dsw-alias-bg-layer-1, transparent)",
1023
+ color: "var(--dsw-alias-label-primary, inherit)"
1024
+ },
1025
+ hint: { color: "var(--dsw-alias-label-primary-dimmed, rgba(128,128,128,0.9))", fontSize: 12 },
1026
+ // U13:分组小标题(模型 / 调用参数 / 上下文),带浅分隔线。
1027
+ groupTitle: {
1028
+ margin: "14px 0 8px",
1029
+ paddingTop: 8,
1030
+ borderTop: "1px solid var(--dsw-alias-border-l3, rgba(128,128,128,0.18))",
1031
+ fontSize: 11,
1032
+ fontWeight: 600,
1033
+ color: "var(--dsw-alias-label-primary-dimmed, rgba(128,128,128,0.9))"
1034
+ },
1035
+ fieldError: { color: "var(--dsw-alias-state-error-primary, #e5534b)", fontSize: 12 },
1036
+ refreshBtn: {
1037
+ flexShrink: 0,
1038
+ padding: "4px 10px",
1039
+ fontSize: 12,
1040
+ borderRadius: 6,
1041
+ border: "1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.4))",
1042
+ background: "var(--dsw-alias-button-tool-bar-fill, transparent)",
1043
+ color: "var(--dsw-alias-label-primary, inherit)",
1044
+ cursor: "pointer"
1045
+ },
1046
+ // 标题右侧的 GitHub 仓库入口:点击在新标签打开仓库主页。
1047
+ repoLink: {
1048
+ display: "inline-flex",
1049
+ alignItems: "center",
1050
+ marginLeft: 8,
1051
+ padding: 4,
1052
+ color: "var(--dsw-alias-label-primary-dimmed, rgba(128,128,128,0.9))",
1053
+ background: "none",
1054
+ border: "none",
1055
+ borderRadius: 6,
1056
+ cursor: "pointer",
1057
+ textDecoration: "none"
1058
+ }
1059
+ };
1060
+ function TextField(props) {
1061
+ const [text, setText] = (0, import_react4.useState)(props.value);
1062
+ const [error, setError] = (0, import_react4.useState)(null);
1063
+ (0, import_react4.useEffect)(() => setText(props.value), [props.value]);
1064
+ const commit = () => {
1065
+ if (text === props.value) {
1066
+ setError(null);
1067
+ return;
1068
+ }
1069
+ const problem = props.validate?.(text) ?? null;
1070
+ if (problem) {
1071
+ setError(problem);
1072
+ return;
1073
+ }
1074
+ setError(null);
1075
+ props.onCommit(text);
1076
+ };
1077
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles2.row, children: [
1078
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: styles2.label, title: props.labelTitle, children: props.label }),
1079
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1080
+ "input",
1081
+ {
1082
+ className: "dsh-po-btn",
1083
+ style: { ...styles2.input, ...error ? { borderColor: "var(--dsw-alias-state-error-primary, #e5534b)" } : {} },
1084
+ value: text,
1085
+ placeholder: props.placeholder,
1086
+ onChange: (e) => {
1087
+ setText(e.target.value);
1088
+ setError(null);
1089
+ },
1090
+ onBlur: commit,
1091
+ onKeyDown: (e) => {
1092
+ if (e.key === "Enter") commit();
1093
+ }
1094
+ }
1095
+ ),
1096
+ error && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: styles2.fieldError, children: error })
1097
+ ] });
1098
+ }
1099
+ function createSettingsCard(ctx, scope) {
1100
+ return function PromptOptimizerSettingsCard() {
1101
+ const snap = (0, import_react4.useSyncExternalStore)(
1102
+ (callback) => scope.subscribe(callback),
1103
+ () => scope.getSnapshot()
1104
+ );
1105
+ const t = useT();
1106
+ const value = snap.value ?? {};
1107
+ const SETTING_KEYS = [
1108
+ "language",
1109
+ "model",
1110
+ "fallbackModel",
1111
+ "maxTokens",
1112
+ "timeoutSeconds",
1113
+ "mode",
1114
+ "reasoningEffort",
1115
+ "temperature",
1116
+ "autoMaxTokens",
1117
+ "includeContext"
1118
+ ];
1119
+ const SETTING_DEFAULTS = {
1120
+ language: "zh",
1121
+ model: "",
1122
+ fallbackModel: "",
1123
+ maxTokens: 8192,
1124
+ timeoutSeconds: 120,
1125
+ mode: "full",
1126
+ reasoningEffort: "lowest",
1127
+ temperature: 0.2,
1128
+ autoMaxTokens: true,
1129
+ includeContext: true
1130
+ };
1131
+ const undoStack = (0, import_react4.useRef)([]);
1132
+ const [canUndo, setCanUndo] = (0, import_react4.useState)(false);
1133
+ const applyingUndo = (0, import_react4.useRef)(false);
1134
+ const setValue = (key, v) => {
1135
+ if (!applyingUndo.current) {
1136
+ undoStack.current.push({ ...value });
1137
+ if (undoStack.current.length > 20) undoStack.current.shift();
1138
+ setCanUndo(true);
1139
+ }
1140
+ void scope.set(key, v);
1141
+ };
1142
+ const undoLastChange = () => {
1143
+ const prev = undoStack.current.pop();
1144
+ setCanUndo(undoStack.current.length > 0);
1145
+ if (!prev) return;
1146
+ applyingUndo.current = true;
1147
+ try {
1148
+ for (const k of SETTING_KEYS) {
1149
+ const target = prev[k] ?? SETTING_DEFAULTS[k];
1150
+ if (value[k] !== target) {
1151
+ void scope.set(k, target);
1152
+ }
1153
+ }
1154
+ } finally {
1155
+ applyingUndo.current = false;
1156
+ }
1157
+ };
1158
+ const [groups, setGroups] = (0, import_react4.useState)(null);
1159
+ const [catalogState, setCatalogState] = (0, import_react4.useState)("loading");
1160
+ const loadCatalog = async () => {
1161
+ setCatalogState("loading");
1162
+ try {
1163
+ const resp = await ctx.connection.api.llm.models({});
1164
+ if (resp.result.ok) {
1165
+ setGroups(resp.result.value.groups);
1166
+ setCatalogState("ready");
1167
+ } else {
1168
+ setCatalogState("error");
1169
+ }
1170
+ } catch {
1171
+ setCatalogState("error");
1172
+ }
1173
+ };
1174
+ (0, import_react4.useEffect)(() => {
1175
+ void loadCatalog();
1176
+ }, []);
1177
+ const [test, setTest] = (0, import_react4.useState)({ status: "idle" });
1178
+ const runTest = async () => {
1179
+ setTest({ status: "testing" });
1180
+ try {
1181
+ const resp = await fetch("/dsh-prompt-optimizer/test-model", {
1182
+ method: "POST",
1183
+ headers: { "content-type": "application/json" },
1184
+ body: "{}"
1185
+ });
1186
+ const data = await resp.json().catch(() => null);
1187
+ if (data?.ok) {
1188
+ setTest({ status: "ok", message: t("settings.test.ok", { provider: data.provider, model: data.model, latencyMs: data.latencyMs }) });
1189
+ } else {
1190
+ setTest({ status: "fail", message: String(data?.error ?? `HTTP ${resp.status}`) });
1191
+ }
1192
+ } catch (cause) {
1193
+ setTest({ status: "fail", message: cause instanceof Error ? cause.message : String(cause) });
1194
+ }
1195
+ };
1196
+ const EXPAND_KEY = "dsh-prompt-optimizer.settings-expanded";
1197
+ const [expanded, setExpanded] = (0, import_react4.useState)(() => {
1198
+ try {
1199
+ return localStorage.getItem(EXPAND_KEY) === "1";
1200
+ } catch {
1201
+ return false;
1202
+ }
1203
+ });
1204
+ const toggle = () => setExpanded((v) => {
1205
+ const next = !v;
1206
+ try {
1207
+ localStorage.setItem(EXPAND_KEY, next ? "1" : "0");
1208
+ } catch {
1209
+ }
1210
+ return next;
1211
+ });
1212
+ const pinnedModel = value.model?.trim();
1213
+ let modelShort = pinnedModel;
1214
+ if (!pinnedModel) {
1215
+ modelShort = t("settings.model.follow");
1216
+ } else if (groups) {
1217
+ const slash = pinnedModel.indexOf("/");
1218
+ const g = slash > 0 ? groups.find((x) => x.id === pinnedModel.slice(0, slash)) : void 0;
1219
+ const m = g?.models.find((mm) => mm.id === pinnedModel.slice(slash + 1));
1220
+ if (m) modelShort = m.name;
1221
+ }
1222
+ const summaryText = `${t("settings.summary.model")}: ${modelShort} \xB7 ${t("settings.summary.mode")}: ${value.mode === "fast" ? t("settings.mode.fast.short") : t("settings.mode.full.short")}`;
1223
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("section", { style: styles2.card, children: [
1224
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: { display: "flex", alignItems: "center" }, children: [
1225
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("button", { className: "dsh-po-btn", type: "button", style: { ...styles2.headerBtn, flex: 1 }, onClick: toggle, "aria-expanded": expanded, children: [
1226
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: { ...styles2.chevron, transform: expanded ? "rotate(90deg)" : "none" }, children: "\u25B8" }),
1227
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: styles2.title, children: t("panel.title") }),
1228
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: styles2.headerDesc, children: expanded ? t("settings.desc") : summaryText })
1229
+ ] }),
1230
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1231
+ "a",
1232
+ {
1233
+ className: "dsh-po-btn",
1234
+ href: REPO_URL,
1235
+ target: "_blank",
1236
+ rel: "noopener noreferrer",
1237
+ style: styles2.repoLink,
1238
+ title: t("settings.repoTitle"),
1239
+ "aria-label": t("settings.repoTitle"),
1240
+ onClick: (e) => e.stopPropagation(),
1241
+ children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(GitHubIcon, { size: 16 })
1242
+ }
1243
+ )
1244
+ ] }),
1245
+ expanded && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles2.body, children: [
1246
+ snap.status === "loading" && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: styles2.hint, children: t("settings.loading") }),
1247
+ snap.status === "unavailable" && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: styles2.hint, children: t("settings.unavailable") }),
1248
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: styles2.groupTitle, children: t("settings.group.model") }),
1249
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles2.row, children: [
1250
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: styles2.label, children: t("settings.model") }),
1251
+ groups === null ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: styles2.hint, children: catalogState === "error" ? t("settings.catalog.error") : t("settings.catalog.loading") }) : /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
1252
+ "select",
1253
+ {
1254
+ style: styles2.input,
1255
+ value: value.model ?? FOLLOW_SESSION,
1256
+ onChange: (e) => void setValue("model", e.target.value),
1257
+ children: [
1258
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: FOLLOW_SESSION, children: t("settings.model.follow") }),
1259
+ groups.map((g) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("optgroup", { label: g.name, children: g.models.map((m) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: `${g.id}/${m.id}`, children: m.name }, m.id)) }, g.id))
1260
+ ]
1261
+ }
1262
+ ),
1263
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1264
+ "button",
1265
+ {
1266
+ className: "dsh-po-btn",
1267
+ type: "button",
1268
+ style: { ...styles2.refreshBtn, ...catalogState === "loading" ? { opacity: 0.45, cursor: "default" } : {} },
1269
+ disabled: catalogState === "loading",
1270
+ title: t("settings.refreshTitle"),
1271
+ onClick: () => void loadCatalog(),
1272
+ children: t("settings.refresh")
1273
+ }
1274
+ )
1275
+ ] }),
1276
+ groups !== null && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles2.row, children: [
1277
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: styles2.label, children: t("settings.fallbackModel") }),
1278
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
1279
+ "select",
1280
+ {
1281
+ style: styles2.input,
1282
+ value: value.fallbackModel ?? "",
1283
+ onChange: (e) => void setValue("fallbackModel", e.target.value),
1284
+ children: [
1285
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "", children: t("settings.fallbackModel.none") }),
1286
+ groups.map((g) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("optgroup", { label: g.name, children: g.models.map((m) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: `${g.id}/${m.id}`, children: m.name }, m.id)) }, g.id))
1287
+ ]
1288
+ }
1289
+ )
1290
+ ] }),
1291
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles2.row, children: [
1292
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: styles2.label, children: t("settings.test") }),
1293
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1294
+ "button",
1295
+ {
1296
+ className: "dsh-po-btn",
1297
+ type: "button",
1298
+ style: { ...styles2.refreshBtn, ...test.status === "testing" ? { opacity: 0.45, cursor: "default" } : {} },
1299
+ disabled: test.status === "testing",
1300
+ onClick: () => void runTest(),
1301
+ children: test.status === "testing" ? t("settings.test.running") : t("settings.test.run")
1302
+ }
1303
+ ),
1304
+ test.message && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: test.status === "fail" ? styles2.fieldError : styles2.hint, children: test.message })
1305
+ ] }),
1306
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: styles2.groupTitle, children: t("settings.group.params") }),
1307
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles2.row, children: [
1308
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: styles2.label, children: t("settings.language") }),
1309
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
1310
+ "select",
1311
+ {
1312
+ style: { ...styles2.input, maxWidth: 160 },
1313
+ value: value.language ?? "zh",
1314
+ onChange: (e) => void setValue("language", e.target.value),
1315
+ children: [
1316
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "zh", children: "\u4E2D\u6587" }),
1317
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "en", children: "English" })
1318
+ ]
1319
+ }
1320
+ )
1321
+ ] }),
1322
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles2.row, children: [
1323
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: styles2.label, children: t("settings.mode") }),
1324
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
1325
+ "select",
1326
+ {
1327
+ style: { ...styles2.input, maxWidth: 260 },
1328
+ value: value.mode ?? "full",
1329
+ onChange: (e) => void setValue("mode", e.target.value),
1330
+ children: [
1331
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "full", children: t("settings.mode.full") }),
1332
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "fast", children: t("settings.mode.fast") })
1333
+ ]
1334
+ }
1335
+ )
1336
+ ] }),
1337
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles2.row, children: [
1338
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: styles2.label, children: t("settings.effort") }),
1339
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
1340
+ "select",
1341
+ {
1342
+ style: { ...styles2.input, maxWidth: 260 },
1343
+ value: value.reasoningEffort ?? "lowest",
1344
+ onChange: (e) => void setValue("reasoningEffort", e.target.value),
1345
+ children: [
1346
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "lowest", children: t("settings.effort.lowest") }),
1347
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "session", children: t("settings.effort.session") })
1348
+ ]
1349
+ }
1350
+ )
1351
+ ] }),
1352
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: styles2.groupTitle, children: t("settings.group.context") }),
1353
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles2.row, children: [
1354
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: styles2.label, children: t("settings.includeContext") }),
1355
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
1356
+ "select",
1357
+ {
1358
+ style: { ...styles2.input, maxWidth: 260 },
1359
+ value: value.includeContext === false ? "off" : "on",
1360
+ onChange: (e) => void setValue("includeContext", e.target.value === "on"),
1361
+ children: [
1362
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "on", children: t("settings.includeContext.on") }),
1363
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "off", children: t("settings.includeContext.off") })
1364
+ ]
1365
+ }
1366
+ )
1367
+ ] }),
1368
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1369
+ TextField,
1370
+ {
1371
+ label: t("settings.maxTokens"),
1372
+ value: String(value.maxTokens ?? 8192),
1373
+ placeholder: "8192",
1374
+ validate: (v) => {
1375
+ const n = Number.parseInt(v, 10);
1376
+ return Number.isFinite(n) && n >= 1024 && n <= 32768 ? null : t("settings.validate.maxTokens");
1377
+ },
1378
+ onCommit: (v) => void setValue("maxTokens", Number.parseInt(v, 10))
1379
+ }
1380
+ ),
1381
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1382
+ TextField,
1383
+ {
1384
+ label: t("settings.timeout"),
1385
+ value: String(value.timeoutSeconds ?? 120),
1386
+ placeholder: "120",
1387
+ validate: (v) => {
1388
+ const n = Number.parseInt(v, 10);
1389
+ return Number.isFinite(n) && n >= 10 && n <= 600 ? null : t("settings.validate.timeout");
1390
+ },
1391
+ onCommit: (v) => void setValue("timeoutSeconds", Number.parseInt(v, 10))
1392
+ }
1393
+ ),
1394
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1395
+ TextField,
1396
+ {
1397
+ label: t("settings.temperature"),
1398
+ labelTitle: t("settings.temperatureTitle"),
1399
+ value: String(value.temperature ?? 0.2),
1400
+ placeholder: "0.2",
1401
+ validate: (v) => {
1402
+ const n = Number.parseFloat(v);
1403
+ return Number.isFinite(n) && n >= 0 && n <= 2 ? null : t("settings.validate.temperature");
1404
+ },
1405
+ onCommit: (v) => void setValue("temperature", Number.parseFloat(v))
1406
+ }
1407
+ ),
1408
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: styles2.row, children: [
1409
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: styles2.label, children: t("settings.autoMaxTokens") }),
1410
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
1411
+ "select",
1412
+ {
1413
+ style: { ...styles2.input, maxWidth: 260 },
1414
+ value: value.autoMaxTokens === false ? "off" : "on",
1415
+ onChange: (e) => void setValue("autoMaxTokens", e.target.value === "on"),
1416
+ children: [
1417
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "on", children: t("settings.autoMaxTokens.on") }),
1418
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "off", children: t("settings.autoMaxTokens.off") })
1419
+ ]
1420
+ }
1421
+ )
1422
+ ] }),
1423
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: styles2.row, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1424
+ "button",
1425
+ {
1426
+ className: "dsh-po-btn",
1427
+ type: "button",
1428
+ style: { ...styles2.refreshBtn, ...!canUndo ? { opacity: 0.45, cursor: "default" } : {} },
1429
+ disabled: !canUndo,
1430
+ title: t("settings.undoTitle"),
1431
+ onClick: undoLastChange,
1432
+ children: t("settings.undo")
1433
+ }
1434
+ ) }),
1435
+ !snap.writable && snap.status === "ready" && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { style: styles2.hint, children: t("settings.memoryOnly") })
1436
+ ] })
1437
+ ] });
1438
+ };
1439
+ }
1440
+
1441
+ // src/client/index.tsx
1442
+ var name = "dsh-prompt-optimizer-client";
1443
+ var inject = ["slots", "connection", "remote", "settingsScope"];
1444
+ var BUTTON_CLASS = "dsh-po-btn";
1445
+ function ensureFocusStyles() {
1446
+ if (typeof document === "undefined") return;
1447
+ const ID = "dsh-prompt-optimizer-focus-styles";
1448
+ if (document.getElementById(ID)) return;
1449
+ const style = document.createElement("style");
1450
+ style.id = ID;
1451
+ style.textContent = ".dsh-po-btn:focus-visible{outline:2px solid var(--dsw-alias-state-focus-ring, #4f7cf7);outline-offset:2px;border-radius:4px;}";
1452
+ document.head.appendChild(style);
1453
+ }
1454
+ function apply(ctx) {
1455
+ ensureFocusStyles();
1456
+ ctx.inject(["locale"], (lctx) => {
1457
+ installLocaleFace(lctx.locale ?? null);
1458
+ });
1459
+ const scope = ctx.settingsScope.bind({ namespace: "prompt-optimizer" });
1460
+ const controller = createOptimizerController(ctx, {
1461
+ // 与 Host 侧「空字符串视为未设置」的口径一致。
1462
+ isModelPinned: () => Boolean(scope.getSnapshot().value?.model?.trim()),
1463
+ // 与 Host 侧「includeContext 缺省视为开」的口径一致(R28)。
1464
+ isContextEnabled: () => scope.getSnapshot().value?.includeContext ?? true,
1465
+ // 与 Host 侧「仅 mode==='fast' 为快速」的归一化口径一致。
1466
+ isFastMode: () => scope.getSnapshot().value?.mode === "fast",
1467
+ // R21:看门狗 = 设置超时秒数 + 5s 余量(正常时 Host 的超时错误先到达,文案更友好)。
1468
+ getWatchdogMs: () => ((scope.getSnapshot().value?.timeoutSeconds ?? 120) + 5) * 1e3
1469
+ });
1470
+ ctx.slots.inject(
1471
+ "conversation.input.right",
1472
+ () => ctx.slots.register(
1473
+ { name: "conversation.input.right", id: "prompt-optimizer", order: 30 },
1474
+ createOptimizeButton(controller)
1475
+ )
1476
+ );
1477
+ ctx.slots.inject(
1478
+ "conversation.input.dock",
1479
+ () => ctx.slots.register(
1480
+ { name: "conversation.input.dock", id: "prompt-optimizer", order: 30 },
1481
+ createResultDock(controller)
1482
+ )
1483
+ );
1484
+ ctx.slots.inject(
1485
+ "settings.plugin.item",
1486
+ () => ctx.slots.register(
1487
+ { name: "settings.plugin.item", key: "prompt-optimizer" },
1488
+ createSettingsCard(ctx, scope)
1489
+ )
1490
+ );
1491
+ }
1492
+ return module.exports;
1493
+ }
1494
+ });