dsh-tool-manager 1.5.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +27 -1
  2. package/DESIGN.md +25 -18
  3. package/README.md +70 -28
  4. package/dist/catalog.d.ts +9 -2
  5. package/dist/catalog.d.ts.map +1 -1
  6. package/dist/catalog.js +15 -7
  7. package/dist/catalog.js.map +1 -1
  8. package/dist/client.js +847 -94
  9. package/dist/config.d.ts +10 -1
  10. package/dist/config.d.ts.map +1 -1
  11. package/dist/config.js +20 -0
  12. package/dist/config.js.map +1 -1
  13. package/dist/dsh.d.ts +36 -0
  14. package/dist/dsh.d.ts.map +1 -1
  15. package/dist/dsh.js.map +1 -1
  16. package/dist/exposure-history.d.ts +35 -2
  17. package/dist/exposure-history.d.ts.map +1 -1
  18. package/dist/exposure-history.js +168 -46
  19. package/dist/exposure-history.js.map +1 -1
  20. package/dist/index.d.ts +15 -3
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +186 -14
  23. package/dist/index.js.map +1 -1
  24. package/dist/policy.d.ts +35 -2
  25. package/dist/policy.d.ts.map +1 -1
  26. package/dist/policy.js +156 -29
  27. package/dist/policy.js.map +1 -1
  28. package/dist/runtime.d.ts +36 -0
  29. package/dist/runtime.d.ts.map +1 -1
  30. package/dist/runtime.js +160 -23
  31. package/dist/runtime.js.map +1 -1
  32. package/dist/snapshot.d.ts.map +1 -1
  33. package/dist/snapshot.js +4 -1
  34. package/dist/snapshot.js.map +1 -1
  35. package/dist/stats.d.ts +2 -0
  36. package/dist/stats.d.ts.map +1 -1
  37. package/dist/stats.js +48 -23
  38. package/dist/stats.js.map +1 -1
  39. package/dist/suggest.d.ts +50 -1
  40. package/dist/suggest.d.ts.map +1 -1
  41. package/dist/suggest.js +113 -2
  42. package/dist/suggest.js.map +1 -1
  43. package/dist/types.d.ts +84 -0
  44. package/dist/types.d.ts.map +1 -1
  45. package/docs/images/tool-manager.png +0 -0
  46. package/package.json +1 -1
package/dist/client.js CHANGED
@@ -14,23 +14,24 @@ window.__ModuleLoader__.load({
14
14
  ".tm_head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px}",
15
15
  ".tm_head h2{font-size:18px;margin:0 0 5px}.tm_muted{color:var(--dsw-alias-label-secondary,#9097a4);font-size:12px;line-height:1.5}",
16
16
  ".tm_preset_picker{display:flex;align-items:center;gap:9px;flex-wrap:wrap}.tm_preset_picker label{font-size:12px;color:var(--dsw-alias-label-secondary,#9097a4)}.tm_select_wrap{position:relative;display:inline-flex;max-width:100%}.tm_select_wrap:after{content:'';position:absolute;right:12px;top:50%;width:7px;height:7px;border-right:2px solid currentColor;border-bottom:2px solid currentColor;transform:translateY(-70%) rotate(45deg);pointer-events:none;opacity:.9}.tm_preset_select,.tm_btn{appearance:none;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.28));border-radius:8px;background:var(--dsw-alias-bg-layer-1,rgba(128,128,128,.08));color:inherit;padding:7px 10px;font:inherit;font-size:12px}.tm_preset_select{min-width:min(360px,100%);cursor:pointer;padding-right:34px}.tm_preset_select option{background:var(--dsw-alias-bg-base,#17191d);color:inherit}.tm_btn{cursor:pointer}.tm_btn.primary{background:#5367e8;border-color:#5367e8;color:#fff}.tm_btn:disabled{opacity:.5;cursor:not-allowed}",
17
+ ".tm_model_block{display:flex;flex-direction:column;gap:6px;min-width:0}.tm_model_row{display:flex;align-items:center;gap:8px;flex-wrap:wrap;min-width:0}.tm_model_row .tm_model_label{flex:0 0 auto;font-size:12px;color:var(--dsw-alias-label-secondary,#9097a4);cursor:help;white-space:nowrap}.tm_model_row .tm_select_wrap{min-width:0}.tm_model_row .tm_model_pick{flex:1 1 auto}.tm_model_row .tm_preset_select{min-width:0;width:100%}.tm_model_row .tm_effort_pick{flex:0 0 auto}.tm_model_row .tm_effort_pick .tm_preset_select{width:auto;min-width:96px}.tm_model_hints{display:flex;align-items:center;gap:8px;flex-wrap:wrap}",
17
18
  ".tm_panel{border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.24));border-radius:12px;background:var(--dsw-alias-bg-layer-1,rgba(128,128,128,.06));overflow:hidden}",
18
19
  ".tm_panel_head{padding:13px 14px;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.2));display:flex;justify-content:space-between;gap:12px;align-items:center;flex-wrap:wrap;position:relative}.tm_panel_head b{font-size:14px}",
19
- ".tm_tools{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:0}.tm_tool{display:flex;gap:10px;align-items:flex-start;padding:11px 14px;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.13))}.tm_tool_name{font:600 12px ui-monospace,SFMono-Regular,Consolas,monospace}.tm_tool_desc{font-size:11px;color:var(--dsw-alias-label-secondary,#9097a4);line-height:1.4;margin-top:3px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}",
20
+ ".tm_tools{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:0}.tm_tool{display:flex;gap:10px;align-items:flex-start;padding:11px 14px;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.13))}.tm_tool_name{font:600 12px ui-monospace,SFMono-Regular,Consolas,monospace}.tm_group_ref{display:inline-block;margin-left:6px;padding:1px 6px;border-radius:6px;background:rgba(128,128,128,.12);color:var(--dsw-alias-label-secondary,#9097a4);font:400 10px/1.5 ui-sans-serif,system-ui,sans-serif;vertical-align:middle}.tm_group_name{display:inline-block;margin-left:4px;color:var(--dsw-alias-label-secondary,#9097a4);font:400 10px/1.5 ui-sans-serif,system-ui,sans-serif;vertical-align:middle}.tm_tool_desc{font-size:11px;color:var(--dsw-alias-label-secondary,#9097a4);line-height:1.4;margin-top:3px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}",
20
21
  ".tm_row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.tm_input{box-sizing:border-box;min-width:130px;flex:1;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3));border-radius:7px;background:var(--dsw-alias-bg-base,#17191d);color:inherit;padding:7px 9px;font:inherit;font-size:12px}.tm_code{font:11px ui-monospace,SFMono-Regular,Consolas,monospace;color:#9da8ff}.tm_notice{padding:12px;border-radius:9px;background:color-mix(in srgb,#f59e0b 12%,transparent);font-size:12px}.tm_error{padding:12px;border-radius:9px;background:color-mix(in srgb,#ef4444 12%,transparent);color:#fca5a5;font-size:12px}",
21
22
  ".tm_filters{display:flex;gap:6px;flex-wrap:wrap;align-items:center}.tm_chip{appearance:none;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.28));border-radius:999px;background:transparent;color:inherit;padding:4px 9px;cursor:pointer;font:inherit;font-size:11px}.tm_chip.active{border-color:#7c8cff;background:color-mix(in srgb,#7c8cff 16%,transparent)}",
22
23
  ".tm_stats{display:flex;flex-wrap:nowrap;gap:6px;padding:8px 12px;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.13))}.tm_stat{flex:1 1 0;min-width:0;padding:6px 7px;border-radius:7px;background:var(--dsw-alias-bg-layer-1,rgba(128,128,128,.07));border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.15))}.tm_stat_value{font-size:15px;font-weight:700;line-height:1.15;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.tm_stat_label{margin-top:2px;font-size:10px;line-height:1.3;color:var(--dsw-alias-label-secondary,#9097a4);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}@media(max-width:560px){.tm_stats{flex-wrap:wrap}.tm_stat{flex:1 1 30%}}",
23
24
  ".tm_token{display:inline-flex;align-items:center;margin-left:6px;padding:1px 6px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.22));border-radius:999px;background:var(--dsw-alias-bg-layer-1,rgba(128,128,128,.09));font:600 10px/1.45 ui-monospace,SFMono-Regular,Consolas,monospace;color:var(--dsw-alias-label-secondary,#9097a4);white-space:nowrap;vertical-align:middle}.tm_tool>.tm_token{margin-left:auto;flex:0 0 auto}.tm_stat_extra{margin-top:1px;font-size:9.5px;line-height:1.3;color:var(--dsw-alias-label-secondary,#9097a4);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}",
24
- ".tm_help{display:inline-flex;align-items:center;justify-content:center;width:15px;height:15px;margin-left:6px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.28));border-radius:50%;background:var(--dsw-alias-bg-layer-1,rgba(128,128,128,.08));color:var(--dsw-alias-label-secondary,#9097a4);font:700 10px/1 ui-sans-serif,system-ui,sans-serif;cursor:help;vertical-align:middle;outline:none}.tm_help:hover,.tm_help:focus-visible{border-color:#7c8cff;color:#9da8ff}.tm_help::after{content:attr(data-tip);position:absolute;left:0;top:calc(100% + 6px);width:min(520px,calc(100vw - 48px));max-width:100%;padding:10px 12px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.28));border-radius:9px;background:var(--dsw-alias-bg-base,#17191d);box-shadow:0 14px 40px rgba(0,0,0,.35);color:var(--dsw-alias-label-primary,#e7e9ed);font:400 12px/1.65 ui-sans-serif,system-ui,sans-serif;white-space:pre-line;text-align:left;opacity:0;visibility:hidden;pointer-events:none;z-index:30;transition:opacity .12s ease}.tm_help:hover::after,.tm_help:focus-visible::after{opacity:1;visibility:visible}",
25
+ ".tm_help{display:inline-flex;align-items:center;justify-content:center;width:15px;height:15px;margin-left:6px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.28));border-radius:50%;background:var(--dsw-alias-bg-layer-1,rgba(128,128,128,.08));color:var(--dsw-alias-label-secondary,#9097a4);font:700 10px/1 ui-sans-serif,system-ui,sans-serif;cursor:help;vertical-align:middle;outline:none}.tm_help:hover,.tm_help:focus-visible{border-color:#7c8cff;color:#9da8ff}.tm_help::after{content:attr(data-tip);position:absolute;left:0;top:calc(100% + 6px);width:min(520px,calc(100vw - 48px));max-width:none;padding:10px 12px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.28));border-radius:9px;background:var(--dsw-alias-bg-base,#17191d);box-shadow:0 14px 40px rgba(0,0,0,.35);color:var(--dsw-alias-label-primary,#e7e9ed);font:400 12px/1.65 ui-sans-serif,system-ui,sans-serif;white-space:pre-line;text-align:left;opacity:0;visibility:hidden;pointer-events:none;z-index:30;transition:opacity .12s ease}.tm_help:hover::after,.tm_help:focus-visible::after{opacity:1;visibility:visible}",
25
26
  ".tm_badge{display:inline-block;margin-left:6px;padding:2px 7px;border:1px solid transparent;border-radius:999px;font-size:10px;font-weight:700;line-height:1.35;letter-spacing:.02em;vertical-align:middle;color:#fff}.tm_badge.off{background:#b42318;border-color:#d92d20;color:#fff}.tm_badge.cold{background:#4338ca;border-color:#6366f1;color:#fff}.tm_badge.live{background:#15803d;border-color:#22c55e;color:#fff}.tm_badge.ptc{background:#6d28d9;border-color:#a78bfa;color:#fff}.tm_badge.native{background:#334155;border-color:#64748b;color:#fff}",
26
27
  ".tm_group{border-bottom:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.13))}.tm_group:last-child{border-bottom:0}",
27
- ".tm_group_bar{display:flex;align-items:center;gap:8px;padding:11px 14px}",
28
+ ".tm_group_bar{display:flex;align-items:center;gap:8px;padding:11px 14px}.tm_group_mode{border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.28));border-radius:999px;background:var(--dsw-alias-bg-layer-1,rgba(128,128,128,.08));color:inherit;padding:3px 8px;font:inherit;font-size:11px;cursor:pointer}.tm_group_mode.always{color:#22c55e;border-color:#22c55e;background:rgba(34,197,94,.12)}.tm_group_mode.ondemand{color:#818cf8;border-color:#6366f1;background:rgba(99,102,241,.12)}.tm_group_mode.off{color:#f87171;border-color:#ef4444;background:rgba(239,68,68,.12)}.tm_group_mode option{background:var(--dsw-alias-bg-base,#17191d);color:var(--dsw-alias-label-primary,#e7e9ed)}.tm_group_mode option[value=always]{color:#22c55e}.tm_group_mode option[value=ondemand]{color:#818cf8}.tm_group_mode option[value=off]{color:#f87171}",
28
29
  ".tm_chevron{appearance:none;border:0;background:transparent;color:inherit;width:28px;height:28px;border-radius:7px;cursor:pointer;font:16px/1 inherit;flex:0 0 auto}.tm_chevron:hover{background:var(--dsw-alias-bg-layer-1,rgba(128,128,128,.1))}",
29
30
  ".tm_group_main{appearance:none;border:0;background:transparent;color:inherit;text-align:left;flex:1;min-width:0;cursor:pointer;padding:0}",
30
31
  ".tm_group_title{font-size:13px;font-weight:600;line-height:1.3}.tm_group_sub{font-size:11px;color:var(--dsw-alias-label-secondary,#9097a4);margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}",
31
32
  ".tm_group_count{flex:0 0 auto;font-size:12px;color:var(--dsw-alias-label-secondary,#9097a4)}",
32
33
  ".tm_group_body{padding:0 14px 12px 50px}",
33
- ".tm_member{padding:7px 0;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.08))}.tm_member:last-child{border-bottom:0}",
34
+ ".tm_member{display:flex;gap:8px;align-items:flex-start;padding:7px 0;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.08))}.tm_member:last-child{border-bottom:0}",
34
35
  ".tm_modal{position:fixed;inset:0;z-index:10000;display:flex;align-items:center;justify-content:center;padding:24px}",
35
36
  ".tm_modal_mask{position:absolute;inset:0;background:rgba(0,0,0,.55)}",
36
37
  ".tm_modal_card{position:relative;z-index:1;width:min(720px,100%);max-height:min(84vh,760px);display:flex;flex-direction:column;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.28));border-radius:14px;background:var(--dsw-alias-bg-base,#17191d);box-shadow:0 24px 80px rgba(0,0,0,.45)}",
@@ -88,17 +89,27 @@ window.__ModuleLoader__.load({
88
89
  function policyPayload(policy) {
89
90
  const payload = {
90
91
  disabled: [...(policy.disabled || [])],
91
- groups: (policy.groups || []).map((group) => ({
92
- name: group.name,
93
- ...(group.description ? { description: group.description } : {}),
94
- patterns: [...(group.patterns || [])],
95
- })),
92
+ groups: (policy.groups || []).map((group) => {
93
+ const loading = group.loading === "always" || group.loading === "off" ? group.loading : undefined;
94
+ const groupDisabled = Array.isArray(group.disabled) ? [...group.disabled] : [];
95
+ return {
96
+ name: group.name,
97
+ ...(group.description ? { description: group.description } : {}),
98
+ patterns: [...(group.patterns || [])],
99
+ ...(loading === undefined ? {} : { loading }),
100
+ ...(groupDisabled.length === 0 ? {} : { disabled: groupDisabled }),
101
+ };
102
+ }),
96
103
  };
97
104
  if (policy.mode === "mcp") payload.mode = "mcp";
105
+ if (typeof policy.keepAfterCompaction === "number") {
106
+ payload.keepAfterCompaction = policy.keepAfterCompaction;
107
+ }
98
108
  return payload;
99
109
  }
100
110
  /**
101
- * Project one Preset's whole policy onto another Preset.
111
+ * Copy one Preset's groups (including each group's loading mode and
112
+ * group-level disables) and disabled names onto another.
102
113
  *
103
114
  * The target is meant to be overwritten, so its current groups and
104
115
  * disabled names are ignored. Copy only what the target can actually
@@ -106,6 +117,13 @@ window.__ModuleLoader__.load({
106
117
  * Presets, and a group whose members all disappear is skipped instead
107
118
  * of becoming an invalid empty group. Old wildcard patterns are
108
119
  * expanded to exact names, matching what the group editor shows.
120
+ *
121
+ * Loading mode is not part of the copy: it says how a Preset reads the
122
+ * groups it owns (tool_list in default mode, tool_find in mcp mode), so
123
+ * it belongs to the target. Rebuilding the policy used to omit `mode`,
124
+ * which silently turned an MCP 按需 target back into default mode after
125
+ * a copy. The compaction keep limit is policy rather than loading
126
+ * semantics, so it follows the groups: the target is overwritten whole.
109
127
  */
110
128
  function copyPresetPolicy(sourcePreset, targetPreset) {
111
129
  const sourceTools = sourcePreset.tools || [];
@@ -118,29 +136,183 @@ window.__ModuleLoader__.load({
118
136
  const groups = [];
119
137
  const skippedGroups = [];
120
138
  for (const group of sourcePolicy.groups || []) {
139
+ const sourceMembers = new Set(matchingTools(sourceTools, group.patterns || []).map((tool) => tool.name));
140
+ const groupDisabled = new Set(
141
+ (group.disabled || []).filter((name) => sourceMembers.has(name) && targetNames.has(name)),
142
+ );
121
143
  const members = [];
122
144
  for (const tool of matchingTools(sourceTools, group.patterns || [])) {
123
145
  if (!targetNames.has(tool.name) || claimed.has(tool.name)) continue;
124
146
  claimed.add(tool.name);
125
147
  members.push(tool.name);
126
148
  }
127
- if (members.length === 0) {
149
+ if (!members.some((name) => !groupDisabled.has(name))) {
128
150
  skippedGroups.push(group.name || "未命名分组");
129
151
  continue;
130
152
  }
153
+ const loading = group.loading === "always" || group.loading === "off" ? group.loading : undefined;
154
+ const disabledMembers = [...groupDisabled];
131
155
  groups.push({
132
156
  name: group.name,
133
157
  ...(group.description ? { description: group.description } : {}),
134
158
  patterns: members,
159
+ ...(loading === undefined ? {} : { loading }),
160
+ ...(disabledMembers.length === 0 ? {} : { disabled: disabledMembers }),
135
161
  });
136
162
  }
137
- return { disabled, groups, skippedGroups };
163
+ const mode = targetPreset.policy && targetPreset.policy.mode === "mcp" ? "mcp" : undefined;
164
+ const keep = typeof sourcePolicy.keepAfterCompaction === "number"
165
+ ? sourcePolicy.keepAfterCompaction
166
+ : undefined;
167
+ return {
168
+ disabled,
169
+ groups,
170
+ ...(mode ? { mode } : {}),
171
+ ...(keep === undefined ? {} : { keepAfterCompaction: keep }),
172
+ skippedGroups,
173
+ };
174
+ }
175
+ /**
176
+ * The empty policy a Preset resets to.
177
+ *
178
+ * Loading mode survives a reset for the same reason it survives a copy:
179
+ * it is a Preset-level choice, not one of the groups being cleared.
180
+ * The compaction keep limit is the same kind of choice — it says how
181
+ * opened groups age, not which groups exist — so reset keeps it too.
182
+ * Dropping it flipped an MCP 按需 Preset back to default mode and
183
+ * re-registered the discovery tool the Preset had switched away from.
184
+ */
185
+ function resetPresetPolicy(policy) {
186
+ const mode = policy && policy.mode === "mcp" ? "mcp" : undefined;
187
+ const keep = policy && typeof policy.keepAfterCompaction === "number"
188
+ ? policy.keepAfterCompaction
189
+ : undefined;
190
+ return {
191
+ disabled: [],
192
+ groups: [],
193
+ ...(mode ? { mode } : {}),
194
+ ...(keep === undefined ? {} : { keepAfterCompaction: keep }),
195
+ };
138
196
  }
139
197
  function settingsPayload(value) {
140
198
  const settings = { presets: {} };
141
199
  for (const item of value && value.presets || []) settings.presets[item.id] = policyPayload(item.policy);
200
+ // `null` is an explicit "follow the default model again". A MISSING key
201
+ // is what a page loaded before this setting existed sends, and the Host
202
+ // reads that as "leave the stored choice alone".
203
+ settings.generation = generationPayload(value);
142
204
  return settings;
143
205
  }
206
+ /**
207
+ * The shared AI generation model, normalized for persistence.
208
+ *
209
+ * Auto-naming and auto-grouping only classify tools and print JSON, so both
210
+ * may run a fast model instead of a slow default one. A pinned route is
211
+ * stored as `{provider, model}`; an effort chosen while still running the
212
+ * default model is stored on its own, so the plugin keeps picking whatever
213
+ * the deployment default is and only overrides its reasoning effort.
214
+ */
215
+ function generationPayload(value) {
216
+ const choice = value && value.generation;
217
+ if (!choice || typeof choice !== "object") return null;
218
+ const provider = typeof choice.provider === "string" ? choice.provider.trim() : "";
219
+ const model = typeof choice.model === "string" ? choice.model.trim() : "";
220
+ const reasoningEffort = typeof choice.reasoningEffort === "string" ? choice.reasoningEffort.trim() : "";
221
+ if (provider && model) return { provider, model, ...(reasoningEffort ? { reasoningEffort } : {}) };
222
+ if (reasoningEffort) return { reasoningEffort };
223
+ return null;
224
+ }
225
+ /**
226
+ * The selection a generation request will run.
227
+ *
228
+ * A stored choice either pins a route or only overrides the effort of the
229
+ * default model; both end up here as one concrete provider/model/effort,
230
+ * which is what the picker shows and what the dialogs name.
231
+ */
232
+ function effectiveGenerationModel(choice, fallback) {
233
+ const pinned = choice && choice.provider && choice.model ? choice : null;
234
+ const base = pinned || fallback;
235
+ if (!base || !base.provider || !base.model) return null;
236
+ const effort = pinned
237
+ ? (choice.reasoningEffort || "")
238
+ : ((choice && choice.reasoningEffort) || (fallback && fallback.reasoningEffort) || "");
239
+ return { provider: base.provider, model: base.model, ...(effort ? { reasoningEffort: effort } : {}) };
240
+ }
241
+ /** Whether a selection is exactly the deployment default route. */
242
+ function isDefaultSelection(selection, fallback) {
243
+ return !!(selection && fallback && selection.provider === fallback.provider && selection.model === fallback.model);
244
+ }
245
+ /**
246
+ * The level a switched-to model should run, given the one in use before.
247
+ *
248
+ * Dropping the level whenever the new model does not declare it is what made
249
+ * switching models silently fall back to the deployment default's own level
250
+ * (Max here), which is the slowest possible outcome for a run the reader had
251
+ * just set to Off. The declared levels are ordered least to greatest, so the
252
+ * same relative position is carried over: Off on a four-step model lands on
253
+ * the cheapest step of a three-step one, Max still lands on Max.
254
+ */
255
+ function carryReasoningEffort(previous, previousEfforts, nextEfforts, nextDefault) {
256
+ if (!previous) return "";
257
+ const ids = (list) => (list || []).map((effort) => effort.id);
258
+ const next = ids(nextEfforts);
259
+ if (next.length === 0) return "";
260
+ if (next.includes(previous)) return previous;
261
+ if (nextDefault && next.includes(nextDefault)) return nextDefault;
262
+ const from = ids(previousEfforts);
263
+ const index = from.indexOf(previous);
264
+ if (index < 0 || from.length < 2) return next[0];
265
+ const position = Math.round((index / (from.length - 1)) * (next.length - 1));
266
+ return next[Math.min(Math.max(position, 0), next.length - 1)];
267
+ }
268
+ /** One model picker value: JSON so provider/model ids may contain anything. */
269
+ function generationModelValue(choice) {
270
+ if (!choice || !choice.provider || !choice.model) return "";
271
+ return JSON.stringify([choice.provider, choice.model]);
272
+ }
273
+ /** Read a model picker value back; `""` means "follow the default model". */
274
+ function parseGenerationModelValue(value) {
275
+ if (typeof value !== "string" || !value) return null;
276
+ let parsed;
277
+ try {
278
+ parsed = JSON.parse(value);
279
+ } catch {
280
+ return null;
281
+ }
282
+ if (!Array.isArray(parsed) || parsed.length !== 2) return null;
283
+ const [provider, model] = parsed;
284
+ if (typeof provider !== "string" || typeof model !== "string" || !provider || !model) return null;
285
+ return { provider, model };
286
+ }
287
+ /**
288
+ * Which model a generation request will run, named for the reader.
289
+ *
290
+ * The dialogs used to say "当前默认模型" unconditionally, which became wrong
291
+ * as soon as the generation model could be set separately. The name and the
292
+ * level come from the catalog when it lists them, so the sentence and the
293
+ * picker read the same: the sentence prints a level exactly when the picker
294
+ * has one selected.
295
+ */
296
+ function generationTargetLabel(choice, fallback, catalog) {
297
+ const effective = effectiveGenerationModel(choice, fallback);
298
+ if (!effective) return "未配置的模型";
299
+ const entry = findModelEntry(catalog, effective);
300
+ const name = entry && entry.name ? entry.name : effective.provider + "/" + effective.model;
301
+ const chosen = effective.reasoningEffort || "";
302
+ const effort = chosen
303
+ ? ((entry && entry.reasoning ? (entry.reasoning.efforts || []).find((item) => item.id === chosen) : null) || { name: chosen })
304
+ : null;
305
+ return "「" + name + (effort ? " · 推理 " + effort.name : "") + "」";
306
+ }
307
+ /** The catalog entry for a choice, or null when the catalog does not list it. */
308
+ function findModelEntry(catalog, choice) {
309
+ if (!catalog || !choice) return null;
310
+ for (const group of catalog.groups || []) {
311
+ if (group.id !== choice.provider) continue;
312
+ return (group.models || []).find((model) => model.id === choice.model) || null;
313
+ }
314
+ return null;
315
+ }
144
316
  function settingsSignature(value) {
145
317
  return JSON.stringify(settingsPayload(value));
146
318
  }
@@ -203,8 +375,11 @@ window.__ModuleLoader__.load({
203
375
  const empty = [];
204
376
  const disabledMembers = [];
205
377
  for (const group of preset.policy.groups || []) {
378
+ const groupDisabled = new Set(group.disabled || []);
206
379
  const members = matchingTools(preset.tools, group.patterns);
207
- if (!members.some((tool) => !disabled.has(tool.name))) empty.push(group.name || "未命名分组");
380
+ if (!members.some((tool) => !disabled.has(tool.name) && !groupDisabled.has(tool.name))) {
381
+ empty.push(group.name || "未命名分组");
382
+ }
208
383
  for (const tool of members) {
209
384
  if (disabled.has(tool.name)) disabledMembers.push({ tool: tool.name, group: group.name || "未命名分组" });
210
385
  const groups = owners.get(tool.name) || [];
@@ -217,16 +392,27 @@ window.__ModuleLoader__.load({
217
392
  }
218
393
  function catalogStats(preset) {
219
394
  const disabled = new Set(preset.policy.disabled || []);
220
- const grouped = groupedNames(preset);
395
+ const groups = preset.policy.groups || [];
221
396
  let ungroupedTools = 0;
222
397
  let onDemandTools = 0;
223
398
  let disabledTools = 0;
224
399
  for (const tool of preset.tools || []) {
225
- if (disabled.has(tool.name)) disabledTools += 1;
226
- else if (grouped.has(tool.name)) onDemandTools += 1;
400
+ if (disabled.has(tool.name)) {
401
+ disabledTools += 1;
402
+ continue;
403
+ }
404
+ const owner = groups.find((group) => matchingTools([tool], group.patterns).length > 0);
405
+ if (!owner) {
406
+ ungroupedTools += 1;
407
+ continue;
408
+ }
409
+ const groupDisabled = Array.isArray(owner.disabled) ? owner.disabled : [];
410
+ const loading = owner.loading === "always" || owner.loading === "off" ? owner.loading : "ondemand";
411
+ if (loading === "off" || groupDisabled.includes(tool.name)) disabledTools += 1;
412
+ else if (loading === "ondemand") onDemandTools += 1;
227
413
  else ungroupedTools += 1;
228
414
  }
229
- return { totalTools: (preset.tools || []).length, groupCount: (preset.policy.groups || []).length, ungroupedTools, onDemandTools, disabledTools };
415
+ return { totalTools: (preset.tools || []).length, groupCount: groups.length, ungroupedTools, onDemandTools, disabledTools };
230
416
  }
231
417
  // Token estimates mirror the Host's `@deepseek-ai/dsh-token-meter/estimate`
232
418
  // (4 characters per token) so the editor updates live while groups are
@@ -270,38 +456,82 @@ window.__ModuleLoader__.load({
270
456
  return estimateToolTokens(tool);
271
457
  }
272
458
  function estimateGroupTokens(group, members) {
273
- if (members.length === 0) return { schema: 0, catalog: 0, net: 0 };
459
+ if (members.length === 0 || groupLoading(group) === "off") return { schema: 0, catalog: 0, net: 0 };
274
460
  let schema = 0;
275
461
  for (const tool of members) {
276
462
  const tokens = toolTokens(tool);
277
463
  if (tokens === null) return null;
278
464
  schema += tokens;
279
465
  }
466
+ if (groupLoading(group) === "always") return { schema, catalog: 0, net: schema };
280
467
  const catalog = Math.ceil(renderCatalogLine(group, members).length / 4);
281
468
  return { schema, catalog, net: schema - catalog };
282
469
  }
470
+ function groupLoading(group) {
471
+ return group.loading === "always" || group.loading === "off" ? group.loading : "ondemand";
472
+ }
473
+ function groupDisabled(group) {
474
+ return Array.isArray(group.disabled) ? group.disabled : [];
475
+ }
476
+ function groupOwners(preset) {
477
+ const owners = new Map();
478
+ for (const group of preset.policy.groups || []) {
479
+ for (const tool of matchingTools(preset.tools, group.patterns)) {
480
+ if (!owners.has(tool.name)) owners.set(tool.name, group);
481
+ }
482
+ }
483
+ return owners;
484
+ }
485
+ function groupOfTool(preset, toolName) {
486
+ const tool = (preset.tools || []).find((item) => item.name === toolName);
487
+ if (!tool) return undefined;
488
+ return (preset.policy.groups || []).find((group) => matchingTools([tool], group.patterns).length > 0);
489
+ }
490
+ function toolDisabled(preset, toolName) {
491
+ if ((preset.policy.disabled || []).includes(toolName)) return true;
492
+ const group = groupOfTool(preset, toolName);
493
+ return group !== undefined
494
+ && (groupLoading(group) === "off" || groupDisabled(group).includes(toolName));
495
+ }
496
+ function activeGroupMembers(group, preset) {
497
+ const disabled = new Set(preset.policy.disabled || []);
498
+ const groupDisabledSet = new Set(groupDisabled(group));
499
+ return matchingTools(preset.tools, group.patterns)
500
+ .filter((tool) => !disabled.has(tool.name) && !groupDisabledSet.has(tool.name));
501
+ }
283
502
  function activeGroupViews(preset) {
284
503
  const disabled = new Set(preset.policy.disabled || []);
285
504
  const claimed = new Set();
286
505
  const active = [];
287
506
  for (const group of preset.policy.groups || []) {
288
- const members = matchingTools(preset.tools, group.patterns)
289
- .filter((tool) => !disabled.has(tool.name) && !claimed.has(tool.name));
507
+ const allMembers = matchingTools(preset.tools, group.patterns);
508
+ const members = activeGroupMembers(group, preset).filter((tool) => !claimed.has(tool.name));
509
+ // Claim disabled members too: first-match ownership must not let a
510
+ // later group resurrect a group-disabled tool in the draft view.
511
+ for (const tool of allMembers) claimed.add(tool.name);
290
512
  if (members.length === 0) continue;
291
- for (const tool of members) claimed.add(tool.name);
292
513
  active.push({ group, members });
293
514
  }
294
515
  return { active, claimed, disabled };
295
516
  }
296
517
  function presetTokenStats(preset) {
297
- const { active, claimed, disabled } = activeGroupViews(preset);
518
+ const { active, disabled } = activeGroupViews(preset);
519
+ const onDemandActive = active.filter((item) => groupLoading(item.group) === "ondemand");
520
+ const owners = groupOwners(preset);
298
521
  const allTools = preset.tools || [];
299
- const alwaysOn = allTools.filter((tool) => !disabled.has(tool.name) && !claimed.has(tool.name));
300
- const onDemand = allTools.filter((tool) => claimed.has(tool.name));
301
- const disabledTools = allTools.filter((tool) => disabled.has(tool.name));
522
+ const alwaysOn = [];
523
+ const onDemand = [];
524
+ const disabledTools = [];
525
+ for (const tool of allTools) {
526
+ const owner = owners.get(tool.name);
527
+ const groupOff = owner !== undefined && (groupLoading(owner) === "off" || groupDisabled(owner).includes(tool.name));
528
+ if (disabled.has(tool.name) || groupOff) disabledTools.push(tool);
529
+ else if (owner !== undefined && groupLoading(owner) === "ondemand") onDemand.push(tool);
530
+ else alwaysOn.push(tool);
531
+ }
302
532
  let onDemandTokens = 0;
303
533
  let onDemandSavings = 0;
304
- for (const item of active) {
534
+ for (const item of onDemandActive) {
305
535
  const tokens = estimateGroupTokens(item.group, item.members);
306
536
  if (tokens) {
307
537
  onDemandTokens += tokens.schema;
@@ -322,7 +552,7 @@ window.__ModuleLoader__.load({
322
552
  alwaysOnTokens: additive ? resident(alwaysOn) : estimateToolsTokens(alwaysOn),
323
553
  onDemandTools: onDemand.length,
324
554
  onDemandTokens,
325
- onDemandGroups: active.length,
555
+ onDemandGroups: onDemandActive.length,
326
556
  onDemandSavings,
327
557
  disabledTools: disabledTools.length,
328
558
  disabledTokens: additive ? resident(disabledTools) : estimateToolsTokens(disabledTools),
@@ -330,8 +560,14 @@ window.__ModuleLoader__.load({
330
560
  }
331
561
  function groupTokenEstimates(preset) {
332
562
  const map = new Map();
333
- for (const item of activeGroupViews(preset).active) {
334
- map.set(item.group._key || item.group.name, estimateGroupTokens(item.group, item.members));
563
+ for (const group of preset.policy.groups || []) {
564
+ if (groupLoading(group) === "off") {
565
+ map.set(group._key || group.name, null);
566
+ continue;
567
+ }
568
+ const members = activeGroupMembers(group, preset);
569
+ const tokens = estimateGroupTokens(group, members);
570
+ map.set(group._key || group.name, tokens);
335
571
  }
336
572
  return map;
337
573
  }
@@ -445,7 +681,7 @@ window.__ModuleLoader__.load({
445
681
  }
446
682
 
447
683
  const TOOL_CATALOG_HELP = [
448
- "关掉后立刻对模型隐藏。按需组默认隐藏,模型要先调用 tool_list 打开所在组才能使用。",
684
+ "关掉后立刻对模型隐藏。分组可设为常驻、按需或关闭:常驻组直接声明,按需组默认隐藏、模型要先调用 tool_list 打开所在组才能使用,关闭组整组不声明;组内成员还可以单独禁用。",
449
685
  "",
450
686
  "tool_list 只在当前 Preset 有有效按需组时才出现(保存后从下一个模型步骤生效),没有有效按需组时模型看不到它;它由插件自动管理,不出现在本页工具目录中,也不能在这里开关或分组。",
451
687
  ].join("\n");
@@ -454,20 +690,57 @@ window.__ModuleLoader__.load({
454
690
  // paragraphs have to name the other tool. The header keeps one help
455
691
  // entry point and picks the wording from the preset loading mode.
456
692
  const TOOL_CATALOG_HELP_MCP = [
457
- "关掉后立刻对模型隐藏。按需组只声明组名与描述,组内工具不单独声明;模型用 tool_find 读取整组用法后可直接按名调用,不需要开组。",
693
+ "关掉后立刻对模型隐藏。分组可设为常驻、按需或关闭:常驻组直接声明,按需组只声明组名与描述、组内工具不单独声明,模型用 tool_find 读取整组用法后可直接按名调用;关闭组整组不声明,组内成员还可以单独禁用。",
458
694
  "",
459
695
  "tool_find 由插件自动注册,不出现在本页目录中,也不能在这里开关或分组;它只在当前 Preset 有有效按需组时出现。",
696
+ "",
697
+ "注意:部分供应商会限制工具调用名,此时 MCP 按需模式无法正常调用组内工具,请改用「默认」加载模式。",
460
698
  ].join("\n");
461
699
 
462
700
  function toolCatalogHelp(mcpMode) {
463
701
  return mcpMode ? TOOL_CATALOG_HELP_MCP : TOOL_CATALOG_HELP;
464
702
  }
465
703
 
466
- // One short hover line per mode. The chips carry the explanation now:
467
- // the row used to print a paragraph beside them, which pushed the chips
468
- // around and repeated what the tool catalog help already says.
469
- const GROUP_CHIP_TITLE = "组内工具平时不声明;模型用 tool_list({ group }) 打开一组后,这组工具才进入工具表。";
470
- const MCP_CHIP_TITLE = "组内工具始终不进工具表;模型用 tool_find({ group }) 看整组参数,随时能按名字直接调用。";
704
+ // One help entry next to the mode label. Both mode explanations live
705
+ // there instead of on the chips, so the warning below covers the whole
706
+ // choice instead of looking like a property of one hovered button.
707
+ const LOADING_MODE_HELP = [
708
+ "默认:组内工具平时不声明;模型用 tool_list({ group }) 打开一组后,这组工具才进入工具表。",
709
+ "",
710
+ "MCP 按需:组内工具始终不进工具表;模型用 tool_find({ group }) 看整组参数,随时能按名字直接调用。",
711
+ "",
712
+ "注意:MCP 按需依赖模型能够直接发出未声明的工具名。部分供应商会限制工具调用名(例如 OpenCode Go),模型只能反复调用 tool_find,无法真正调用组内工具;遇到这种情况请改用「默认」加载模式。",
713
+ ].join("\n");
714
+
715
+ // How a completed compaction treats the groups this Session opened. The
716
+ // default is deliberately "keep everything": compaction must not surprise
717
+ // a reader who never configured this, and only the default mode has an
718
+ // open state to begin with.
719
+ const KEEP_AFTER_COMPACTION_HELP = [
720
+ "默认全部保留:会话压缩不会改变已经打开的按需组。",
721
+ "",
722
+ "填一个数字后,每次会话压缩成功结束(自动压缩或 /compact)时,只保留最近使用的 N 个已打开的按需组,其余重新收起;模型可以再用 tool_list 打开。",
723
+ "",
724
+ "「最近使用」只看上一次压缩之后到这一次压缩之间的区间:组内工具有过成功调用,或组在此期间被打开/重新打开;只是闲置跨过压缩的组会被关闭,若这一区间没有任何组被打开/使用,压缩后可以一个组都不保留。压缩之后才打开的组不受这一次裁剪影响。",
725
+ "",
726
+ "0 表示压缩后全部关闭;留空表示不限制。",
727
+ "",
728
+ "只在「默认」加载模式下生效:MCP 按需模式没有打开状态。随页面「保存」写入。",
729
+ ].join("\n");
730
+
731
+ // The generation model is a global choice, not a Preset one: auto-naming
732
+ // and auto-grouping classify tools and print JSON, so a fast model is
733
+ // usually enough even when the conversation runs a slow reasoning one.
734
+ // It is offered inside both dialogs that spend a request — 「自动分组」
735
+ // and the group editor's 「自动生成名称和描述」.
736
+ const GENERATION_MODEL_HELP = [
737
+ "「自动分组」和「手动分组」里生成名称、描述时共用的模型,对所有 Preset 生效。",
738
+ "",
739
+ "默认就是 DSH 当前的默认模型及其推理强度;也可以换成任意已注册的 Provider + 模型,并单独选推理强度,「模型默认」表示不额外指定。",
740
+ "",
741
+ "所选模型已不可用(被删除或未配置)时,生成会回退到默认模型并明确提示,不会静默失败。",
742
+ "改动立即写入配置文件,不需要再点「保存」。",
743
+ ].join("\n");
471
744
 
472
745
  function ToolManagerSection() {
473
746
  const [snapshot, setSnapshot] = react.useState(null);
@@ -487,6 +760,10 @@ window.__ModuleLoader__.load({
487
760
  const [aiConfirm, setAiConfirm] = react.useState(null);
488
761
  const [suggestionTimeoutSeconds, setSuggestionTimeoutSeconds] = react.useState("60");
489
762
  const [autoGroupTimeoutSeconds, setAutoGroupTimeoutSeconds] = react.useState("120");
763
+ const [models, setModels] = react.useState(null);
764
+ const [modelsError, setModelsError] = react.useState("");
765
+ const [generationSaveError, setGenerationSaveError] = react.useState("");
766
+ const [aiNotice, setAiNotice] = react.useState("");
490
767
 
491
768
  const load = react.useCallback((attempt) => {
492
769
  const tries = attempt || 0;
@@ -507,6 +784,15 @@ window.__ModuleLoader__.load({
507
784
  }).finally(() => setBusy(false));
508
785
  }, []);
509
786
  react.useEffect(() => { load(); }, [load]);
787
+ // The picker is the only consumer of the model catalog, so a failure
788
+ // here leaves "跟随默认模型" usable instead of blocking the whole page.
789
+ react.useEffect(() => {
790
+ let live = true;
791
+ api("/models")
792
+ .then((value) => { if (live) { setModels(value); setModelsError(""); } })
793
+ .catch((e) => { if (live) setModelsError(String(e.message || e)); });
794
+ return () => { live = false; };
795
+ }, []);
510
796
  const dirty = !!(snapshot && draft && settingsSignature(snapshot) !== settingsSignature(draft));
511
797
  react.useEffect(() => {
512
798
  if (!dirty) return undefined;
@@ -563,6 +849,128 @@ window.__ModuleLoader__.load({
563
849
  });
564
850
  }
565
851
 
852
+ /**
853
+ * Set how many opened groups survive a completed compaction.
854
+ *
855
+ * A controlled text input rather than `type=number`: the latter
856
+ * reports an empty value for half-typed text ("1e"), which would
857
+ * silently clear the setting while the reader is still typing. Only
858
+ * digits are accepted, and an empty field means the unlimited
859
+ * default.
860
+ */
861
+ function setCompactionKeep(value) {
862
+ const text = String(value || "").trim();
863
+ if (text === "") {
864
+ mutatePreset((target) => {
865
+ delete target.policy.keepAfterCompaction;
866
+ });
867
+ return;
868
+ }
869
+ if (!/^\d+$/.test(text)) return;
870
+ const count = Number(text);
871
+ if (!Number.isSafeInteger(count) || count > 999) return;
872
+ mutatePreset((target) => {
873
+ target.policy.keepAfterCompaction = count;
874
+ });
875
+ }
876
+
877
+ /**
878
+ * Choose the shared generation model, or `null` to let the plugin pick.
879
+ *
880
+ * The choice is persisted right away — this setting belongs to no
881
+ * Preset, so waiting for 「保存」 would only ask the reader to save a page
882
+ * they did not change. The draft still moves first, so the picker and the
883
+ * next request see the choice even while the write is in flight.
884
+ */
885
+ function setGenerationChoice(choice) {
886
+ setDraft((current) => {
887
+ if (!current) return current;
888
+ const next = clone(current);
889
+ if (choice) next.generation = { ...choice };
890
+ else delete next.generation;
891
+ return next;
892
+ });
893
+ setMessage("");
894
+ setAiNotice("");
895
+ persistGeneration(choice);
896
+ }
897
+
898
+ /**
899
+ * Write the generation model to the config file.
900
+ *
901
+ * It goes through its own route instead of the page save so it needs no
902
+ * page revision: the Preset policies a page may be drafting are untouched,
903
+ * and the store serializes this write with the next 「保存」.
904
+ */
905
+ function persistGeneration(choice) {
906
+ setGenerationSaveError("");
907
+ api("/generation", {
908
+ method: "POST",
909
+ body: JSON.stringify({ generation: generationPayload({ generation: choice }) }),
910
+ }).then((result) => {
911
+ if (!result) return;
912
+ // The Host answered with the revision it ended up at. Adopt it so the
913
+ // next 「保存」 sends a revision the store still accepts; take the
914
+ // larger one when two writes of ours raced.
915
+ setSnapshot((current) => {
916
+ if (!current) return current;
917
+ const next = { ...current, revision: Math.max(current.revision || 0, result.revision || 0) };
918
+ if (result.generation) next.generation = { ...result.generation };
919
+ else delete next.generation;
920
+ return next;
921
+ });
922
+ setGenerationSaveError("");
923
+ }).catch((error) => {
924
+ setGenerationSaveError(String(error.message || error));
925
+ });
926
+ }
927
+
928
+ /**
929
+ * Pick a model for both generation tasks.
930
+ *
931
+ * The chosen level travels with the switch whenever the new model can
932
+ * express it, because it describes how hard the classification should
933
+ * think, not which route runs it. Choosing the deployment default route
934
+ * stores no route at all: that keeps the plugin on whatever the default
935
+ * model becomes. Any other route is persisted.
936
+ */
937
+ function chooseGenerationModel(value) {
938
+ const picked = parseGenerationModelValue(value);
939
+ if (!picked) return;
940
+ const entry = findModelEntry(models, picked);
941
+ const targetEfforts = entry && entry.reasoning ? entry.reasoning.efforts || [] : [];
942
+ const keep = carryReasoningEffort(
943
+ generationEffortValue,
944
+ generationEntry && generationEntry.reasoning ? generationEntry.reasoning.efforts || [] : [],
945
+ targetEfforts,
946
+ entry && entry.reasoning ? entry.reasoning.defaultEffort : undefined,
947
+ );
948
+ setGenerationChoice(isDefaultSelection(picked, defaultSelection)
949
+ ? (keep ? { reasoningEffort: keep } : null)
950
+ : { provider: picked.provider, model: picked.model, ...(keep ? { reasoningEffort: keep } : {}) });
951
+ }
952
+
953
+ /**
954
+ * Pick the reasoning level of whichever model the picker currently shows.
955
+ *
956
+ * The level is stored even while the model stays the default one, so the
957
+ * picker never has to be locked just because the route was not pinned.
958
+ * "默认" stores nothing, which keeps following whatever level the model
959
+ * or the deployment default already uses.
960
+ */
961
+ function chooseGenerationEffort(reasoningEffort) {
962
+ if (!generationModel) return;
963
+ if (!isDefaultSelection(generationModel, defaultSelection)) {
964
+ setGenerationChoice({
965
+ provider: generationModel.provider,
966
+ model: generationModel.model,
967
+ ...(reasoningEffort ? { reasoningEffort } : {}),
968
+ });
969
+ return;
970
+ }
971
+ setGenerationChoice(reasoningEffort ? { reasoningEffort } : null);
972
+ }
973
+
566
974
  function openCreate() {
567
975
  setModal({
568
976
  mode: "create",
@@ -570,6 +978,8 @@ window.__ModuleLoader__.load({
570
978
  name: nextGroupName(preset.policy.groups),
571
979
  description: "",
572
980
  patterns: [],
981
+ loading: "ondemand",
982
+ disabled: [],
573
983
  query: "",
574
984
  generating: false,
575
985
  generateError: "",
@@ -578,9 +988,9 @@ window.__ModuleLoader__.load({
578
988
 
579
989
  function resetPresetConfig() {
580
990
  if (!hasPresetConfig) return;
581
- if (!window.confirm("确定重置当前 Preset 的配置吗?这会清空它的全部按需组和已关闭工具;只修改页面草稿,保存后生效。")) return;
991
+ if (!window.confirm("确定重置当前 Preset 的配置吗?这会清空它的全部组和已关闭工具,加载模式与「压缩后保留」保持不变;只修改页面草稿,保存后生效。")) return;
582
992
  mutatePreset((target) => {
583
- target.policy = { disabled: [], groups: [] };
993
+ target.policy = resetPresetPolicy(target.policy);
584
994
  });
585
995
  setQuery("");
586
996
  setFilter("all");
@@ -620,7 +1030,7 @@ window.__ModuleLoader__.load({
620
1030
  if (target.id === source.id || !selected.has(target.id) || target.broken) continue;
621
1031
  const copied = copyPresetPolicy(source, target);
622
1032
  const before = JSON.stringify(policyPayload(target.policy));
623
- const after = JSON.stringify(policyPayload({ disabled: copied.disabled, groups: copied.groups }));
1033
+ const after = JSON.stringify(policyPayload(copied));
624
1034
  plans.push({ targetId: target.id, label: target.name || target.id, copied, changed: before !== after });
625
1035
  }
626
1036
  if (!plans.length) { setCopyDialog(null); return; }
@@ -632,6 +1042,7 @@ window.__ModuleLoader__.load({
632
1042
  target.policy = {
633
1043
  disabled: [...plan.copied.disabled],
634
1044
  groups: plan.copied.groups.map((group) => ({ ...group, _key: newKey() })),
1045
+ ...(plan.copied.mode ? { mode: plan.copied.mode } : {}),
635
1046
  };
636
1047
  }
637
1048
  return next;
@@ -660,12 +1071,35 @@ window.__ModuleLoader__.load({
660
1071
  name: group.name || "",
661
1072
  description: group.description || "",
662
1073
  patterns: members,
1074
+ loading: groupLoading(group),
1075
+ disabled: [...groupDisabled(group)],
663
1076
  query: "",
664
1077
  generating: false,
665
1078
  generateError: "",
666
1079
  });
667
1080
  }
668
1081
 
1082
+ function setGroupLoading(key, value) {
1083
+ mutatePreset((target) => {
1084
+ const group = (target.policy.groups || []).find((item) => item._key === key);
1085
+ if (!group) return;
1086
+ if (value === "always" || value === "off") group.loading = value;
1087
+ else delete group.loading;
1088
+ });
1089
+ }
1090
+
1091
+ function setGroupMemberDisabled(key, toolName, disabled) {
1092
+ mutatePreset((target) => {
1093
+ const group = (target.policy.groups || []).find((item) => item._key === key);
1094
+ if (!group) return;
1095
+ const next = new Set(group.disabled || []);
1096
+ if (disabled) next.add(toolName);
1097
+ else next.delete(toolName);
1098
+ if (next.size === 0) delete group.disabled;
1099
+ else group.disabled = [...next];
1100
+ });
1101
+ }
1102
+
669
1103
  function deleteGroup(key) {
670
1104
  mutatePreset((target) => {
671
1105
  target.policy.groups = (target.policy.groups || []).filter((group) => group._key !== key);
@@ -678,6 +1112,16 @@ window.__ModuleLoader__.load({
678
1112
  setModal((current) => current ? { ...current, ...patch } : current);
679
1113
  }
680
1114
 
1115
+ function toggleModalDisabled(toolName) {
1116
+ setModal((current) => {
1117
+ if (!current) return current;
1118
+ const next = new Set(current.disabled || []);
1119
+ if (next.has(toolName)) next.delete(toolName);
1120
+ else next.add(toolName);
1121
+ return { ...current, disabled: [...next], generateError: "" };
1122
+ });
1123
+ }
1124
+
681
1125
  function patchAiConfirm(patch) {
682
1126
  setAiConfirm((current) => current ? { ...current, ...patch } : current);
683
1127
  }
@@ -701,7 +1145,6 @@ window.__ModuleLoader__.load({
701
1145
  setAiConfirm({
702
1146
  kind: "suggest",
703
1147
  title: "确认自动生成名称和描述",
704
- message: "将所选工具的名称和描述发送给当前默认模型,并产生一次模型请求。",
705
1148
  timeoutSeconds: suggestionTimeoutSeconds,
706
1149
  prompt: initialPrompt,
707
1150
  promptCustom: false,
@@ -709,13 +1152,16 @@ window.__ModuleLoader__.load({
709
1152
  error: "",
710
1153
  run: (timeoutMs, _tools, prompt) => {
711
1154
  setSuggestionTimeoutSeconds(String(timeoutMs / 1000));
712
- patchModal({ generating: true, generateError: "" });
1155
+ setAiNotice("");
1156
+ patchModal({ generating: true, generateError: "", generateNotice: "" });
713
1157
  api("/suggest-group", {
714
1158
  method: "POST",
715
- body: JSON.stringify({ presetId: preset.id, toolNames, otherGroupNames, timeoutMs, prompt }),
1159
+ body: JSON.stringify({ presetId: preset.id, toolNames, otherGroupNames, timeoutMs, prompt, generation: generationPayload(draft) }),
716
1160
  }).then((suggestion) => {
1161
+ const notice = suggestion.modelNotice ? String(suggestion.modelNotice) : "";
1162
+ if (notice) setAiNotice(notice);
717
1163
  setModal((current) => current && current.key === key
718
- ? { ...current, name: suggestion.name || current.name, description: suggestion.description || current.description, generating: false, generateError: "" }
1164
+ ? { ...current, name: suggestion.name || current.name, description: suggestion.description || current.description, generating: false, generateError: "", generateNotice: notice }
719
1165
  : current);
720
1166
  }).catch((e) => {
721
1167
  setModal((current) => current && current.key === key
@@ -732,7 +1178,11 @@ window.__ModuleLoader__.load({
732
1178
  const description = String(modal.description || "").trim();
733
1179
  const eligible = new Set(eligibleGroupTools(preset, modal.key).map((tool) => tool.name));
734
1180
  const patterns = [...new Set(modal.patterns || [])].filter((toolName) => eligible.has(toolName));
1181
+ const selected = new Set(patterns);
1182
+ const groupDisabled = [...new Set(modal.disabled || [])].filter((toolName) => selected.has(toolName));
1183
+ const loading = modal.loading === "always" || modal.loading === "off" ? modal.loading : undefined;
735
1184
  if (!name || patterns.length === 0) return;
1185
+ if (patterns.every((toolName) => groupDisabled.includes(toolName))) return;
736
1186
  const created = modal.mode === "create";
737
1187
  const key = modal.key;
738
1188
  mutatePreset((target) => {
@@ -740,7 +1190,14 @@ window.__ModuleLoader__.load({
740
1190
  const clash = target.policy.groups.some((item) => item._key !== key && String(item.name || "").toLowerCase() === name.toLowerCase());
741
1191
  if (clash) return;
742
1192
  if (created) {
743
- target.policy.groups.push({ _key: key, name, description, patterns });
1193
+ target.policy.groups.push({
1194
+ _key: key,
1195
+ name,
1196
+ description,
1197
+ patterns,
1198
+ ...(loading === undefined ? {} : { loading }),
1199
+ ...(groupDisabled.length === 0 ? {} : { disabled: groupDisabled }),
1200
+ });
744
1201
  return;
745
1202
  }
746
1203
  const group = target.policy.groups.find((item) => item._key === key);
@@ -748,6 +1205,10 @@ window.__ModuleLoader__.load({
748
1205
  group.name = name;
749
1206
  group.description = description;
750
1207
  group.patterns = patterns;
1208
+ if (loading === undefined) delete group.loading;
1209
+ else group.loading = loading;
1210
+ if (groupDisabled.length === 0) delete group.disabled;
1211
+ else group.disabled = groupDisabled;
751
1212
  });
752
1213
  setModal(null);
753
1214
  if (created) setExpanded((current) => ({ ...current, [key]: true }));
@@ -772,7 +1233,6 @@ window.__ModuleLoader__.load({
772
1233
  setAiConfirm({
773
1234
  kind: "auto-group",
774
1235
  title: "确认自动分组",
775
- message: "筛选并勾选需要分组的工具,发送给当前默认模型进行聚类。",
776
1236
  timeoutSeconds: autoGroupTimeoutSeconds,
777
1237
  query: "",
778
1238
  selected: allCandidateNames,
@@ -782,13 +1242,15 @@ window.__ModuleLoader__.load({
782
1242
  error: "",
783
1243
  run: (timeoutMs, selectedToolNames, prompt) => {
784
1244
  setAutoGroupTimeoutSeconds(String(timeoutMs / 1000));
785
- setAutoGrouping(true); setAutoGroupError(""); setAutoPreview(null);
1245
+ setAutoGrouping(true); setAutoGroupError(""); setAutoPreview(null); setAiNotice("");
786
1246
  const signature = autoGroupSignature(selectedToolNames, otherGroupNames);
787
1247
  api("/auto-group", {
788
1248
  method: "POST",
789
- body: JSON.stringify({ presetId: preset.id, toolNames: selectedToolNames, otherGroupNames, timeoutMs, prompt }),
1249
+ body: JSON.stringify({ presetId: preset.id, toolNames: selectedToolNames, otherGroupNames, timeoutMs, prompt, generation: generationPayload(draft) }),
790
1250
  }).then((result) => {
791
- setAutoPreview({ presetId: preset.id, signature, selectedTools: selectedToolNames, groups: result.groups || [], ungrouped: result.ungrouped || [] });
1251
+ const notice = result.modelNotice ? String(result.modelNotice) : "";
1252
+ if (notice) setAiNotice(notice);
1253
+ setAutoPreview({ presetId: preset.id, signature, selectedTools: selectedToolNames, groups: result.groups || [], ungrouped: result.ungrouped || [], notice });
792
1254
  }).catch((e) => setAutoGroupError(String(e.message || e))).finally(() => setAutoGrouping(false));
793
1255
  },
794
1256
  });
@@ -855,13 +1317,19 @@ window.__ModuleLoader__.load({
855
1317
  function save() {
856
1318
  for (const item of draft.presets || []) {
857
1319
  if (item.broken) continue;
858
- // Groups are inert in mcp mode, so a stale/empty group must not
859
- // block saving the mode switch.
860
- if (item.policy.mode === "mcp") continue;
861
- const issues = groupDraftIssues(item);
1320
+ // MCP mode keeps groups for tool_find; stale default/ondemand
1321
+ // groups should not block saving, but explicit always/off groups
1322
+ // still carry loading semantics and must be valid.
1323
+ let checkItem = item;
1324
+ if (item.policy.mode === "mcp") {
1325
+ const groups = (item.policy.groups || []).filter((group) => group.loading === "always" || group.loading === "off");
1326
+ if (groups.length === 0) continue;
1327
+ checkItem = { ...item, policy: { ...item.policy, groups } };
1328
+ }
1329
+ const issues = groupDraftIssues(checkItem);
862
1330
  if (issues.disabledMembers.length) {
863
1331
  const issue = issues.disabledMembers[0];
864
- setError("Preset “" + item.id + "”中的已关闭工具“" + issue.tool + "”不能加入分组“" + issue.group + "”。请从分组移除或重新开启该工具。");
1332
+ setError("Preset “" + item.id + "”中的已关闭工具“" + issue.tool + "”落在分组“" + issue.group + "”的匹配范围内。Preset 级已关闭工具不能与分组重叠,请从分组移除该工具或取消它的关闭状态。");
865
1333
  setMessage("");
866
1334
  return;
867
1335
  }
@@ -882,7 +1350,7 @@ window.__ModuleLoader__.load({
882
1350
  api("/save", { method: "POST", body: JSON.stringify({ expectedRevision: snapshot.revision, settings }) })
883
1351
  .then((value) => {
884
1352
  const next = withGroupKeys(value);
885
- setSnapshot(value); setDraft(next); setModal(null); setCopyDialog(null);
1353
+ setSnapshot(value); setDraft(next); setModal(null); setCopyDialog(null); setAiNotice("");
886
1354
  setMessage("已保存;运行中 Agent 将从下一个模型步骤应用新策略。");
887
1355
  })
888
1356
  .catch((e) => setError(String(e.message || e)))
@@ -892,6 +1360,28 @@ window.__ModuleLoader__.load({
892
1360
  const disabled = new Set(preset.policy.disabled || []);
893
1361
  const grouped = groupedNames(preset);
894
1362
  const mcpMode = preset.policy.mode === "mcp";
1363
+ const generationChoice = draft.generation || null;
1364
+ const defaultSelection = draft.defaultSelection || null;
1365
+ // What the next request will actually run: a pinned model, else the
1366
+ // deployment default one. The picker always shows a concrete model, so
1367
+ // there is no "follow the default" row to read.
1368
+ const generationModel = effectiveGenerationModel(generationChoice, defaultSelection);
1369
+ const generationEntry = findModelEntry(models, generationModel);
1370
+ // A provider whose own catalog failed tells us nothing about its models,
1371
+ // so only a readable catalog that simply lacks the model is proof.
1372
+ const generationCatalogFailed = !!(models && generationModel
1373
+ && (models.failures || []).some((item) => item.id === generationModel.provider));
1374
+ const generationUnavailable = !!(generationModel && models && !generationEntry && !generationCatalogFailed);
1375
+ const generationEfforts = generationEntry && generationEntry.reasoning
1376
+ ? generationEntry.reasoning.efforts || []
1377
+ : [];
1378
+ // The dropdown shows the level in effect, so "默认" is only shown while no
1379
+ // level is in effect at all. Following the deployment default model means
1380
+ // running ITS level, so the select reads Max there rather than "默认".
1381
+ const generationEffortValue = generationModel && generationModel.reasoningEffort
1382
+ ? generationModel.reasoningEffort
1383
+ : "";
1384
+ const generationLabel = generationTargetLabel(generationChoice, defaultSelection, models);
895
1385
  const saveBlocked = saveBlockReason({ busy, autoGrouping, writable: draft.writable, dirty });
896
1386
  const errorPreset = errorPresetId(error, (draft.presets || []).map((item) => item.id));
897
1387
  const autoGroupCandidates = (preset.tools || []).filter((tool) => !disabled.has(tool.name) && !grouped.has(tool.name));
@@ -912,28 +1402,48 @@ window.__ModuleLoader__.load({
912
1402
  const title = String(group.name || "").toLowerCase();
913
1403
  const description = String(group.description || "").toLowerCase();
914
1404
  const members = matchingTools(preset.tools, group.patterns);
1405
+ const loading = groupLoading(group);
1406
+ if (filter === "cold" && loading !== "ondemand") return false;
1407
+ if (filter === "live" && loading !== "always") return false;
1408
+ if (filter === "disabled" && loading !== "off") return false;
915
1409
  if (!needle) return true;
916
1410
  return title.includes(needle) || description.includes(needle) || members.some((tool) => matchesQuery(tool, needle));
917
1411
  });
918
- const showGroups = filter === "all" || filter === "cold";
1412
+ const showGroups = filter === "all" || filter === "cold" || filter === "live" || filter === "disabled";
919
1413
  const visibleTools = (preset.tools || []).filter((tool) => {
920
1414
  if (!matchesQuery(tool, needle)) return false;
921
1415
  if (filter === "cold") return false;
922
- if (filter === "disabled") return disabled.has(tool.name);
923
- if (filter === "live") return !disabled.has(tool.name) && !grouped.has(tool.name);
1416
+ if (filter === "disabled") {
1417
+ const owner = groupOfTool(preset, tool.name);
1418
+ // A closed group is already represented by its group card and
1419
+ // its “已关闭 N 个工具” summary; don't repeat every member here.
1420
+ if (owner && groupLoading(owner) === "off") return false;
1421
+ return toolDisabled(preset, tool.name);
1422
+ }
1423
+ if (filter === "live") return !toolDisabled(preset, tool.name) && !grouped.has(tool.name);
924
1424
  return !grouped.has(tool.name);
925
1425
  });
926
1426
  const orphans = (preset.policy.disabled || []).filter((name) => !(preset.tools || []).some((tool) => tool.name === name));
927
1427
  const modalNeedle = String(modal && modal.query || "").trim().toLowerCase();
928
1428
  const modalSelected = new Set(modal ? modal.patterns || [] : []);
1429
+ const modalGroupDisabled = new Set(modal ? modal.disabled || [] : []);
1430
+ const modalLoading = modal && (modal.loading === "always" || modal.loading === "off") ? modal.loading : "ondemand";
1431
+ const modalHint = modalLoading === "always"
1432
+ ? "勾选要常驻的工具;取消勾选或点「禁用」都不会向模型声明。"
1433
+ : modalLoading === "off"
1434
+ ? "整组关闭时不声明;切回「常驻 / 按需」后按这里的勾选恢复。"
1435
+ : "筛选后勾选要收进该组的工具。确定后会显示在按需里。";
929
1436
  const modalEligibleTools = modal ? eligibleGroupTools(preset, modal.key) : [];
930
1437
  const modalEligibleNames = new Set(modalEligibleTools.map((tool) => tool.name));
931
1438
  const pickerTools = modal ? (preset.tools || []).filter((tool) =>
932
1439
  (modalEligibleNames.has(tool.name) || modalSelected.has(tool.name)) && matchesQuery(tool, modalNeedle)) : [];
933
1440
  const visibleSelected = pickerTools.filter((tool) => modalSelected.has(tool.name)).map((tool) => tool.name);
934
1441
  const modalMatchedTools = modal ? matchingTools(preset.tools, modal.patterns || []).filter((tool) => modalEligibleNames.has(tool.name)) : [];
1442
+ const modalEnabledCount = modalMatchedTools.filter((tool) => (
1443
+ !disabled.has(tool.name) && !modalGroupDisabled.has(tool.name)
1444
+ )).length;
935
1445
  const modalInvalidSelected = modal ? [...modalSelected].filter((name) => !modalEligibleNames.has(name)) : [];
936
- const canConfirm = !!(modal && String(modal.name || "").trim() && modalMatchedTools.length > 0 && modalInvalidSelected.length === 0);
1446
+ const canConfirm = !!(modal && String(modal.name || "").trim() && modalEnabledCount > 0 && modalInvalidSelected.length === 0);
937
1447
  const listedGroups = showGroups ? visibleGroups : [];
938
1448
  const aiIsAutoGroup = !!(aiConfirm && aiConfirm.kind === "auto-group");
939
1449
  const aiNeedle = String(aiConfirm && aiConfirm.query || "").trim().toLowerCase();
@@ -965,31 +1475,69 @@ window.__ModuleLoader__.load({
965
1475
  patchAiConfirm(patch);
966
1476
  }
967
1477
 
1478
+ function groupModeOptions() {
1479
+ return [
1480
+ h("option", { value: "always", style: { color: "#22c55e" } }, "常驻"),
1481
+ h("option", { value: "ondemand", style: { color: "#818cf8" } }, "按需"),
1482
+ h("option", { value: "off", style: { color: "#f87171" } }, "关闭"),
1483
+ ];
1484
+ }
1485
+
968
1486
  function renderGroup(group) {
969
1487
  const key = group._key;
970
1488
  const open = !!expanded[key];
971
1489
  const members = matchingTools(preset.tools, group.patterns);
972
1490
  const estimate = groupTokens.get(key) || null;
973
1491
  const title = (group.name || "").trim() || "未命名分组";
1492
+ const loading = groupLoading(group);
1493
+ const groupDisabledSet = new Set(groupDisabled(group));
1494
+ const memberStatus = (tool) => {
1495
+ if (disabled.has(tool.name) || loading === "off" || groupDisabledSet.has(tool.name)) return { label: "关闭", className: "off" };
1496
+ return loading === "always" ? { label: "常驻", className: "live" } : { label: "按需", className: "cold" };
1497
+ };
974
1498
  return h("div", { className: "tm_group", key: key },
975
1499
  h("div", { className: "tm_group_bar" },
976
1500
  h("button", { className: "tm_chevron", title: open ? "收起" : "展开", onClick: () => setExpanded((current) => ({ ...current, [key]: !current[key] })) }, open ? "▾" : "▸"),
977
1501
  h("button", { className: "tm_group_main", onClick: () => setExpanded((current) => ({ ...current, [key]: !current[key] })) },
978
- h("div", { className: "tm_group_title" }, title, h("span", { className: "tm_badge cold" }, "按需")),
1502
+ h("div", { className: "tm_group_title" }, title),
979
1503
  h("div", { className: "tm_group_sub" }, group.description || "没有描述"),
980
1504
  ),
981
- estimate && estimate.schema > 0 ? tokenBadge(estimate.net, "估算(" + unitNote + "):组内工具 " + formatTokenAmount(estimate.schema) + " tok · 关闭时目录行 " + formatTokenAmount(estimate.catalog) + " tok · 收起净省 " + formatTokenAmount(estimate.net) + " tok/轮") : null,
982
- h("span", { className: "tm_group_count" }, members.length + " 个工具"),
1505
+ h("select", {
1506
+ className: "tm_group_mode " + loading,
1507
+ value: loading,
1508
+ title: preset.policy.mode === "mcp"
1509
+ ? "常驻=直接声明;按需=tool_find 读取后按名调用;关闭=整组不声明"
1510
+ : "常驻=直接声明;按需=tool_list 打开后使用;关闭=整组不声明",
1511
+ onChange: (event) => setGroupLoading(key, event.target.value),
1512
+ }, groupModeOptions()),
1513
+ loading === "off"
1514
+ ? h("span", { className: "tm_muted" }, "已关闭 " + members.length + " 个工具")
1515
+ : estimate && estimate.schema > 0
1516
+ ? tokenBadge(estimate.net, loading === "always"
1517
+ ? "估算(" + unitNote + "):组内工具常驻 " + formatTokenAmount(estimate.schema) + " tok/轮"
1518
+ : "估算(" + unitNote + "):组内工具 " + formatTokenAmount(estimate.schema) + " tok · 关闭时目录行 " + formatTokenAmount(estimate.catalog) + " tok · 收起净省 " + formatTokenAmount(estimate.net) + " tok/轮")
1519
+ : null,
1520
+ loading === "off" ? null : h("span", { className: "tm_group_count" }, members.length + " 个工具"),
983
1521
  h("button", { className: "tm_btn", onClick: () => openEdit(group) }, "编辑"),
984
1522
  h("button", { className: "tm_btn", onClick: () => deleteGroup(key) }, "删除"),
985
1523
  ),
986
1524
  open ? h("div", { className: "tm_group_body" }, members.length
987
1525
  ? members.map((tool) => {
988
1526
  const tokens = toolTokens(tool);
989
- const isDisabled = disabled.has(tool.name);
990
- return h("div", { className: "tm_member", key: tool.name },
991
- h("div", { className: "tm_tool_name" }, tool.name, isDisabled ? h("span", { className: "tm_badge off" }, "关闭") : null, tokenBadge(tokens, "估算(" + unitNote + "):" + (isDisabled ? "已关闭,开启后常驻 " : "单工具常驻 ") + formatTokenAmount(tokens) + " tok/轮")),
992
- h("div", { className: "tm_tool_desc", title: tool.description }, tool.description),
1527
+ const status = memberStatus(tool);
1528
+ const memberTag = loading === "off" ? "div" : "label";
1529
+ return h(memberTag, { className: "tm_member", key: tool.name },
1530
+ loading === "off" ? null : h("input", {
1531
+ type: "checkbox",
1532
+ checked: !groupDisabledSet.has(tool.name) && !disabled.has(tool.name),
1533
+ disabled: disabled.has(tool.name),
1534
+ title: disabled.has(tool.name) ? "该工具由 Preset 级设置关闭" : "取消勾选=在本组内禁用此工具",
1535
+ onChange: (event) => setGroupMemberDisabled(key, tool.name, !event.target.checked),
1536
+ }),
1537
+ h("span", null,
1538
+ h("div", { className: "tm_tool_name" }, tool.name, h("span", { className: "tm_badge " + status.className }, status.label), tokenBadge(tokens, "估算(" + unitNote + "):" + formatTokenAmount(tokens) + " tok/轮")),
1539
+ h("div", { className: "tm_tool_desc", title: tool.description }, tool.description),
1540
+ ),
993
1541
  );
994
1542
  })
995
1543
  : h("div", { className: "tm_error" }, "无效空组:请编辑并选择至少一个可用工具,或删除该组。"),
@@ -998,13 +1546,29 @@ window.__ModuleLoader__.load({
998
1546
  }
999
1547
 
1000
1548
  function renderTool(tool) {
1001
- const enabled = !disabled.has(tool.name);
1549
+ const owner = groupOfTool(preset, tool.name);
1550
+ const enabled = !toolDisabled(preset, tool.name);
1002
1551
  const tokens = toolTokens(tool);
1552
+ const groupName = owner ? (String(owner.name || "").trim() || "未命名分组") : "";
1553
+ const ownerLoading = owner ? groupLoading(owner) : "ondemand";
1003
1554
  return h("label", { className: "tm_tool", key: tool.name },
1004
- h("input", { type: "checkbox", checked: enabled, onChange: () => toggleTool(tool.name) }),
1555
+ h("input", {
1556
+ type: "checkbox",
1557
+ checked: enabled,
1558
+ disabled: !!owner,
1559
+ title: owner ? "该工具由分组「" + groupName + "」控制,请在分组中调整" : undefined,
1560
+ onChange: () => { if (!owner) toggleTool(tool.name); },
1561
+ }),
1005
1562
  h("span", null,
1006
1563
  h("div", { className: "tm_tool_name" }, tool.name,
1007
- !enabled ? h("span", { className: "tm_badge off" }, "关闭") : h("span", { className: "tm_badge live" }, "常开"),
1564
+ enabled ? h("span", { className: "tm_badge live" }, "常驻") : h("span", { className: "tm_badge off" }, "关闭"),
1565
+ owner && filter === "disabled"
1566
+ ? h("span", null,
1567
+ h("span", { className: "tm_group_ref" }, "所属组:"),
1568
+ h("span", { className: "tm_badge " + (ownerLoading === "always" ? "live" : "cold") }, ownerLoading === "always" ? "常驻" : "按需"),
1569
+ h("span", { className: "tm_group_name" }, groupName),
1570
+ )
1571
+ : null,
1008
1572
  ),
1009
1573
  h("div", { className: "tm_tool_desc", title: tool.description }, tool.description),
1010
1574
  ),
@@ -1012,12 +1576,129 @@ window.__ModuleLoader__.load({
1012
1576
  );
1013
1577
  }
1014
1578
 
1579
+ /**
1580
+ * The confirm text, derived at render time so it follows the picker.
1581
+ *
1582
+ * It used to be frozen when the dialog opened, which made the headline
1583
+ * lie as soon as the model was changed in the dialog it describes.
1584
+ */
1585
+ function aiConfirmMessage() {
1586
+ if (!aiConfirm) return "";
1587
+ return aiConfirm.kind === "auto-group"
1588
+ ? "筛选并勾选需要分组的工具,发送给" + generationLabel + "进行聚类。"
1589
+ : "将所选工具的名称和描述发送给" + generationLabel + ",并产生一次模型请求。";
1590
+ }
1591
+
1592
+ /**
1593
+ * The shared generation model control, rendered inside a dialog.
1594
+ *
1595
+ * It belongs to whichever dialog is about to spend a model request —
1596
+ * 「自动分组」 and 「手动分组」 — so the reader can shrink the model right
1597
+ * where the cost is about to happen. Both dialogs edit one value. The
1598
+ * model and its reasoning effort share one line: the effort only matters
1599
+ * for the model next to it.
1600
+ */
1601
+ function renderGenerationPicker() {
1602
+ const pinned = !!(generationChoice && generationChoice.provider && generationChoice.model);
1603
+ const listed = !!generationEntry;
1604
+ // A reader recognises the provider's own display name, not a route, so
1605
+ // the option text is just that name. The provider is appended only when
1606
+ // two routes would read identically; the route itself is the tooltip.
1607
+ const catalogGroups = models ? models.groups || [] : [];
1608
+ const displayName = (model) => (model.name && model.name !== model.id ? model.name : model.id);
1609
+ const nameCounts = new Map();
1610
+ for (const group of catalogGroups) {
1611
+ for (const model of group.models || []) {
1612
+ const name = displayName(model);
1613
+ nameCounts.set(name, (nameCounts.get(name) || 0) + 1);
1614
+ }
1615
+ }
1616
+ const modelOptions = catalogGroups.map((group) => h("optgroup", {
1617
+ key: group.id,
1618
+ label: group.name || group.id,
1619
+ }, (group.models || []).map((model) => {
1620
+ const name = displayName(model);
1621
+ const unique = nameCounts.get(name) === 1;
1622
+ return h("option", {
1623
+ key: model.id,
1624
+ value: generationModelValue({ provider: group.id, model: model.id }),
1625
+ title: group.id + "/" + model.id,
1626
+ }, unique || !group.name ? name : name + " · " + group.name);
1627
+ })));
1628
+ // The effective model may not be in the catalog: the default route can
1629
+ // be unlisted, a saved route can be gone, and the catalog can still be
1630
+ // loading. Keep it selectable so the row never shows a wrong model.
1631
+ const unlistedLabel = generationModel
1632
+ ? generationModel.provider + "/" + generationModel.model + (pinned ? "(当前不可用)" : "")
1633
+ : "";
1634
+ // An effort the catalog does not list for this route still has to be
1635
+ // readable, otherwise the closed select would show a different level.
1636
+ const undeclaredLevel = listed && generationEffortValue
1637
+ && !generationEfforts.some((effort) => effort.id === generationEffortValue)
1638
+ ? generationEffortValue
1639
+ : "";
1640
+ return h("div", { className: "tm_model_block", key: "generation" },
1641
+ h("div", { className: "tm_model_row" },
1642
+ h("span", { className: "tm_model_label", title: GENERATION_MODEL_HELP, key: "modelLabel" }, "生成模型"),
1643
+ h("span", { className: "tm_select_wrap tm_model_pick", key: "modelPick" },
1644
+ h("select", {
1645
+ className: "tm_preset_select",
1646
+ value: generationModelValue(generationModel),
1647
+ disabled: busy || !generationModel,
1648
+ title: "自动命名与自动分组共用的模型,默认是 DSH 当前的默认模型。选一个快速模型可以明显缩短生成时间。",
1649
+ onChange: (event) => chooseGenerationModel(event.target.value),
1650
+ },
1651
+ !generationModel ? h("option", { value: "" }, "没有可用的默认模型") : null,
1652
+ modelOptions,
1653
+ generationModel && !listed ? h("option", { value: generationModelValue(generationModel) }, unlistedLabel) : null,
1654
+ ),
1655
+ ),
1656
+ listed
1657
+ ? [
1658
+ h("span", {
1659
+ className: "tm_model_label",
1660
+ key: "effortLabel",
1661
+ title: "该模型的推理强度,这里显示的就是本次请求会发送的档位。",
1662
+ }, "推理强度"),
1663
+ h("span", { className: "tm_select_wrap tm_effort_pick", key: "effortPick" },
1664
+ h("select", {
1665
+ className: "tm_preset_select",
1666
+ value: generationEffortValue,
1667
+ disabled: busy || !generationModel,
1668
+ title: "该模型的推理强度。「默认」表示不额外指定,用模型(或 DSH 默认模型)本来的档位。",
1669
+ onChange: (event) => chooseGenerationEffort(event.target.value),
1670
+ },
1671
+ h("option", { value: "" }, "默认"),
1672
+ generationEfforts.map((effort) => h("option", { key: effort.id, value: effort.id }, effort.name)),
1673
+ undeclaredLevel ? h("option", { value: undeclaredLevel }, undeclaredLevel) : null,
1674
+ ),
1675
+ ),
1676
+ ]
1677
+ : h("span", { className: "tm_muted", key: "effortMissing", title: "读不到这个模型的推理强度列表,暂时不能指定。" }, "读不到该模型的推理强度"),
1678
+ ),
1679
+ generationSaveError ? h("div", { className: "tm_error" }, "保存失败:" + generationSaveError) : null,
1680
+ generationUnavailable
1681
+ ? h("div", { className: "tm_model_hints" },
1682
+ h("span", { className: "tm_badge off", title: "生成时会自动回退到默认模型,并提示原因" }, "该模型当前不可用"),
1683
+ h("span", { className: "tm_muted" }, "生成时会改用默认模型,并提示原因。"),
1684
+ )
1685
+ : null,
1686
+ modelsError
1687
+ ? h("div", { className: "tm_muted" }, "模型列表读取失败:" + modelsError)
1688
+ : (models && (models.failures || []).length
1689
+ ? h("div", {
1690
+ className: "tm_muted",
1691
+ title: models.failures.map((item) => item.name + ":" + item.message).join("\n"),
1692
+ }, "有 " + models.failures.length + " 个 Provider 的模型列表读取失败,未列出其模型。")
1693
+ : null),
1694
+ );
1695
+ }
1015
1696
  const aiConfirmDialog = aiConfirm && typeof document !== "undefined" ? reactDom.createPortal(
1016
1697
  h("div", { className: "tm_modal", role: "dialog", "aria-modal": "true", "aria-label": aiConfirm.title },
1017
1698
  h("div", { className: "tm_modal_mask", onMouseDown: () => setAiConfirm(null) }),
1018
1699
  h("div", { className: "tm_modal_card" },
1019
1700
  h("div", { className: "tm_modal_head" },
1020
- h("div", null, h("h3", null, aiConfirm.title), h("div", { className: "tm_muted" }, aiConfirm.message)),
1701
+ h("div", null, h("h3", null, aiConfirm.title), h("div", { className: "tm_muted" }, aiConfirmMessage())),
1021
1702
  h("button", { className: "tm_btn", onClick: () => setAiConfirm(null) }, "关闭"),
1022
1703
  ),
1023
1704
  h("div", { className: "tm_modal_body" },
@@ -1042,7 +1723,7 @@ window.__ModuleLoader__.load({
1042
1723
  ),
1043
1724
  aiSelected.size === 0
1044
1725
  ? h("div", { className: "tm_error", key: "status" }, "请至少勾选一个工具进行分组。")
1045
- : h("div", { className: "tm_muted", key: "status" }, "已勾选 " + aiSelected.size + " / " + aiCandidates.length + " 个候选工具。自动分组会调用当前默认模型,结果仍可手动修改。"),
1726
+ : h("div", { className: "tm_muted", key: "status" }, "已勾选 " + aiSelected.size + " / " + aiCandidates.length + " 个候选工具。自动分组会调用" + generationLabel + ",结果仍可手动修改。"),
1046
1727
  aiVisibleCandidates.length
1047
1728
  ? h("div", { className: "tm_picker", key: "picker" }, aiVisibleCandidates.map((tool) => h("label", { className: "tm_pick", key: tool.name },
1048
1729
  h("input", {
@@ -1060,6 +1741,7 @@ window.__ModuleLoader__.load({
1060
1741
  ),
1061
1742
  )))
1062
1743
  : h("div", { className: "tm_muted", key: "empty", style: { padding: "12px" } }, aiCandidates.length ? "没有符合筛选的工具。" : "当前没有可分组的工具。"),
1744
+ renderGenerationPicker(),
1063
1745
  ] : null,
1064
1746
  h("div", {
1065
1747
  style: {
@@ -1170,13 +1852,13 @@ window.__ModuleLoader__.load({
1170
1852
  ) : null;
1171
1853
 
1172
1854
  const dialog = modal && typeof document !== "undefined" ? reactDom.createPortal(
1173
- h("div", { className: "tm_modal", role: "dialog", "aria-modal": "true", "aria-label": modal.mode === "create" ? "新建按需组" : "编辑按需组" },
1855
+ h("div", { className: "tm_modal", role: "dialog", "aria-modal": "true", "aria-label": modal.mode === "create" ? "新建分组" : "编辑分组" },
1174
1856
  h("div", { className: "tm_modal_mask", onMouseDown: () => setModal(null) }),
1175
1857
  h("div", { className: "tm_modal_card" },
1176
1858
  h("div", { className: "tm_modal_head" },
1177
1859
  h("div", null,
1178
- h("h3", null, modal.mode === "create" ? "新建按需组" : "编辑按需组"),
1179
- h("div", { className: "tm_muted" }, "筛选后勾选要收进该组的工具。确定后会显示在按需里。"),
1860
+ h("h3", null, modal.mode === "create" ? "新建分组" : "编辑分组"),
1861
+ h("div", { className: "tm_muted" }, modalHint),
1180
1862
  ),
1181
1863
  h("button", { className: "tm_btn", onClick: () => setModal(null) }, "关闭"),
1182
1864
  ),
@@ -1185,7 +1867,17 @@ window.__ModuleLoader__.load({
1185
1867
  h("input", { className: "tm_input", value: modal.name, placeholder: "名称(模型用这个打开)", onChange: (e) => patchModal({ name: e.target.value, generateError: "" }) }),
1186
1868
  h("button", { className: "tm_btn", disabled: modal.generating || modalMatchedTools.length === 0 || modalInvalidSelected.length > 0, onClick: generateGroupDetails }, modal.generating ? "生成中…" : "自动生成名称和描述"),
1187
1869
  ),
1870
+ h("div", { className: "tm_row" },
1871
+ h("span", { className: "tm_muted" }, "加载"),
1872
+ h("select", {
1873
+ className: "tm_group_mode " + modalLoading,
1874
+ value: modalLoading,
1875
+ onChange: (e) => patchModal({ loading: e.target.value }),
1876
+ }, groupModeOptions()),
1877
+ ),
1878
+ renderGenerationPicker(),
1188
1879
  modal.generateError ? h("div", { className: "tm_error" }, modal.generateError) : null,
1880
+ modal.generateNotice ? h("div", { className: "tm_notice" }, modal.generateNotice) : null,
1189
1881
  h("textarea", { className: "tm_input", style: { width: "100%", minHeight: "72px", resize: "vertical" }, value: modal.description, placeholder: "描述(可选)", onChange: (e) => patchModal({ description: e.target.value, generateError: "" }) }),
1190
1882
  h("div", { className: "tm_row" },
1191
1883
  h("input", { className: "tm_input", value: modal.query, placeholder: "筛选工具名或描述", onChange: (e) => patchModal({ query: e.target.value }) }),
@@ -1194,9 +1886,11 @@ window.__ModuleLoader__.load({
1194
1886
  ),
1195
1887
  modalInvalidSelected.length
1196
1888
  ? h("div", { className: "tm_error" }, "以下工具已关闭或属于其他分组,不能加入当前组:" + modalInvalidSelected.join(", ") + "。请取消选择。")
1197
- : h("div", { className: modalMatchedTools.length ? "tm_muted" : "tm_error" }, modalMatchedTools.length
1198
- ? "已选 " + modalMatchedTools.length + " 个工具。自动生成会调用当前默认模型,结果仍可手动修改。"
1199
- : "每个按需组至少需要一个未关闭且未被其他组占用的工具。"),
1889
+ : h("div", { className: modalEnabledCount > 0 ? "tm_muted" : "tm_error" }, modalMatchedTools.length
1890
+ ? modalLoading === "off"
1891
+ ? "已选 " + modalMatchedTools.length + " 个工具。自动生成会调用" + generationLabel + ",结果仍可手动修改。"
1892
+ : "已选 " + modalMatchedTools.length + " 个工具,其中 " + (modalMatchedTools.length - modalEnabledCount) + " 个禁用。自动生成会调用" + generationLabel + ",结果仍可手动修改。"
1893
+ : "每组至少需要一个未禁用的工具。"),
1200
1894
  pickerTools.length
1201
1895
  ? h("div", { className: "tm_picker" }, pickerTools.map((tool) => h("label", { className: "tm_pick", key: tool.name },
1202
1896
  h("input", {
@@ -1205,16 +1899,33 @@ window.__ModuleLoader__.load({
1205
1899
  disabled: !modalEligibleNames.has(tool.name) && !modalSelected.has(tool.name),
1206
1900
  onChange: (e) => {
1207
1901
  const next = new Set(modal.patterns || []);
1208
- if (e.target.checked && modalEligibleNames.has(tool.name)) next.add(tool.name); else next.delete(tool.name);
1902
+ if (e.target.checked && modalEligibleNames.has(tool.name)) next.add(tool.name);
1903
+ else {
1904
+ next.delete(tool.name);
1905
+ const disabledNext = new Set(modal.disabled || []);
1906
+ disabledNext.delete(tool.name);
1907
+ patchModal({ patterns: [...next], disabled: [...disabledNext], generateError: "" });
1908
+ return;
1909
+ }
1209
1910
  patchModal({ patterns: [...next], generateError: "" });
1210
1911
  },
1211
1912
  }),
1212
1913
  h("span", null,
1213
1914
  h("div", { className: "tm_tool_name" }, tool.name,
1214
1915
  disabled.has(tool.name) ? h("span", { className: "tm_badge off" }, "已关闭")
1916
+ : modalGroupDisabled.has(tool.name) ? h("span", { className: "tm_badge off" }, "禁用")
1215
1917
  : (!modalEligibleNames.has(tool.name) ? h("span", { className: "tm_badge off" }, "其他组") : null)),
1216
1918
  h("div", { className: "tm_tool_desc", title: tool.description }, tool.description),
1217
1919
  ),
1920
+ modalSelected.has(tool.name) && modalLoading !== "off"
1921
+ ? h("button", {
1922
+ type: "button",
1923
+ className: "tm_btn",
1924
+ style: { marginLeft: "auto", flex: "0 0 auto", fontSize: "11px", padding: "3px 7px" },
1925
+ disabled: disabled.has(tool.name),
1926
+ onClick: (e) => { e.preventDefault(); toggleModalDisabled(tool.name); },
1927
+ }, modalGroupDisabled.has(tool.name) ? "取消禁用" : "禁用")
1928
+ : null,
1218
1929
  )))
1219
1930
  : h("div", { className: "tm_muted" }, preset.tools.length ? "没有符合筛选的工具。" : "这个 Preset 当前没有可见工具。"),
1220
1931
  ),
@@ -1240,7 +1951,8 @@ window.__ModuleLoader__.load({
1240
1951
  h("div", { className: "tm_panel_head" }, h("div", { className: "tm_preview_meta" }, h("b", null, group.name), h("div", { className: "tm_preview_desc" }, group.description)), h("span", { className: "tm_group_count" }, group.tools.length + " 个工具")),
1241
1952
  h("div", { style: { padding: "10px 14px" } }, group.tools.map((name) => h("div", { className: "tm_member tm_tool_name", key: name }, name))),
1242
1953
  )),
1243
- autoPreview.ungrouped.length ? h("div", { className: "tm_notice" }, "保持常开、未归组:", h("span", { className: "tm_code" }, autoPreview.ungrouped.join(", "))) : null,
1954
+ autoPreview.notice ? h("div", { className: "tm_notice" }, autoPreview.notice) : null,
1955
+ autoPreview.ungrouped.length ? h("div", { className: "tm_notice" }, "保持常驻、未归组:", h("span", { className: "tm_code" }, autoPreview.ungrouped.join(", "))) : null,
1244
1956
  ),
1245
1957
  h("div", { className: "tm_modal_foot" },
1246
1958
  h("button", { className: "tm_btn", onClick: () => setAutoPreview(null) }, "取消"),
@@ -1258,16 +1970,17 @@ window.__ModuleLoader__.load({
1258
1970
  h("div", { className: "tm_modal_head" },
1259
1971
  h("div", null,
1260
1972
  h("h3", null, "复制当前 Preset 配置"),
1261
- h("div", { className: "tm_muted" }, "将当前 Preset 的全部按需组和已关闭工具复制到勾选的 Preset;只改页面草稿,保存后生效。"),
1973
+ h("div", { className: "tm_muted" }, "将当前 Preset 的全部组和已关闭工具复制到勾选的 Preset;每组加载方式与组内禁用会随组一起复制,加载模式不跟随复制,「压缩后保留最近使用的按需组」会随分组一起复制;只改页面草稿,保存后生效。"),
1262
1974
  ),
1263
1975
  h("button", { className: "tm_btn", onClick: () => setCopyDialog(null) }, "关闭"),
1264
1976
  ),
1265
1977
  h("div", { className: "tm_modal_body" },
1266
1978
  h("div", { className: "tm_notice" },
1267
- "源 Preset「" + (copySource.name || copySource.id) + "」:"
1268
- + (copySource.policy.groups || []).length + " 个按需组、"
1979
+ "源 Preset「" + (copySource.name || copySource.id) + "」(加载模式:"
1980
+ + (copySource.policy.mode === "mcp" ? "MCP 按需" : "默认") + "):"
1981
+ + (copySource.policy.groups || []).length + " 个组、"
1269
1982
  + (copySource.policy.disabled || []).length + " 个已关闭工具。"
1270
- + "勾选的目标 Preset 现有分组和关闭项将被整份覆盖。",
1983
+ + "勾选的目标 Preset 现有分组和关闭项将被整份覆盖,加载模式不变,「压缩后保留」跟随源 Preset。",
1271
1984
  ),
1272
1985
  h("div", { className: "tm_row" },
1273
1986
  h("button", {
@@ -1282,6 +1995,7 @@ window.__ModuleLoader__.load({
1282
1995
  ? h("div", { className: "tm_picker" }, copyPreviewRows.map(({ target, preview }) => {
1283
1996
  const currentGroups = (target.policy.groups || []).length;
1284
1997
  const currentDisabled = (target.policy.disabled || []).length;
1998
+ const targetMode = target.policy.mode === "mcp" ? "MCP 按需" : "默认";
1285
1999
  const meta = target.broken
1286
2000
  ? "工具目录读取失败,暂不能复制"
1287
2001
  : "现有 " + currentGroups + " 个组 / " + currentDisabled + " 个关闭项 → 将复制 "
@@ -1289,6 +2003,10 @@ window.__ModuleLoader__.load({
1289
2003
  + (preview.skippedGroups.length
1290
2004
  ? ";跳过 " + preview.skippedGroups.length + " 个组:" + preview.skippedGroups.join("、")
1291
2005
  : "")
2006
+ + ";加载模式保持「" + targetMode + "」"
2007
+ + ";压缩后保留 " + (typeof preview.keepAfterCompaction === "number"
2008
+ ? preview.keepAfterCompaction + " 个"
2009
+ : "全部")
1292
2010
  + ((target.tools || []).length === 0 ? ";目标没有可见工具,复制后配置为空" : "");
1293
2011
  return h("label", { className: "tm_pick", key: target.id },
1294
2012
  h("input", {
@@ -1326,7 +2044,7 @@ window.__ModuleLoader__.load({
1326
2044
 
1327
2045
  return h("div", { className: "tm_root" },
1328
2046
  h("div", { className: "tm_head" },
1329
- h("div", null, h("h2", null, "Agent 工具管理"), h("div", { className: "tm_muted" }, "按每个 Agent 预设开关工具。点「手动分组」把不常用的收进按需组:平时模型看不到,需要时先查目录再打开。")),
2047
+ h("div", null, h("h2", null, "Agent 工具管理"), h("div", { className: "tm_muted" }, "按每个 Agent 预设开关工具。点「手动分组」把工具整理成常驻、按需或关闭组:常驻组直接可用,按需组平时模型看不到、需要时先查目录再打开,关闭组整组不声明。")),
1330
2048
  h("div", { className: "tm_row" },
1331
2049
  h("button", { className: "tm_btn", onClick: reload, disabled: busy || autoGrouping }, "刷新"),
1332
2050
  h("button", {
@@ -1357,7 +2075,7 @@ window.__ModuleLoader__.load({
1357
2075
  className: "tm_preset_select",
1358
2076
  value: preset.id,
1359
2077
  disabled: autoGrouping,
1360
- onChange: (event) => { setActive(event.target.value); setQuery(""); setFilter("all"); setModal(null); setAutoPreview(null); setCopyDialog(null); setAutoGroupError(""); setExpanded({}); },
2078
+ onChange: (event) => { setActive(event.target.value); setQuery(""); setFilter("all"); setModal(null); setAutoPreview(null); setCopyDialog(null); setAutoGroupError(""); setAiNotice(""); setExpanded({}); },
1361
2079
  }, draft.presets.map((item) => h("option", { key: item.id, value: item.id }, (item.name || item.id) + " · " + (item.tools || []).length + " 个工具" + (item.isDefault ? " · 默认" : "") + (item.trust === "user" ? " · 用户" : "") + (item.id === errorPreset ? " · 保存失败" : "")))),
1362
2080
  ),
1363
2081
  preset.broken ? null
@@ -1365,27 +2083,49 @@ window.__ModuleLoader__.load({
1365
2083
  ? h("span", { className: "tm_badge ptc", title: "本 Preset 走 PTC:工具以一份生成的 TypeScript SDK 注入系统提示词,token 按该文本 ÷4 估算(含 run_code 调用声明、PTC 指令段与 SDK 脚手架)" }, "PTC")
1366
2084
  : h("span", { className: "tm_badge native", title: "本 Preset 走原生 tool-calling:工具以 JSON schema 随请求发送,token 按 JSON ÷4 估算" }, "原生"),
1367
2085
  ),
1368
- h("div", { className: "tm_row", style: { padding: "0 14px 10px" } },
1369
- h("span", { className: "tm_muted" }, "加载模式"),
1370
- h("button", { className: "tm_chip" + (mcpMode ? "" : " active"), onClick: () => setMode("groups"), title: GROUP_CHIP_TITLE }, "默认"),
1371
- h("button", { className: "tm_chip" + (mcpMode ? " active" : ""), onClick: () => setMode("mcp"), title: MCP_CHIP_TITLE }, "MCP 按需"),
2086
+ h("div", { className: "tm_row", style: { padding: "0 14px" } },
2087
+ h("span", { className: "tm_muted", style: { position: "relative" } }, "加载模式", h("span", { className: "tm_help", tabIndex: 0, "aria-label": "加载模式说明", "data-tip": LOADING_MODE_HELP }, "?")),
2088
+ h("button", { className: "tm_chip" + (mcpMode ? "" : " active"), onClick: () => setMode("groups") }, "默认"),
2089
+ h("button", { className: "tm_chip" + (mcpMode ? " active" : ""), onClick: () => setMode("mcp") }, "MCP 按需"),
2090
+ ),
2091
+ mcpMode ? null : h("div", { className: "tm_row", style: { padding: "0 14px" } },
2092
+ h("span", { className: "tm_muted", style: { position: "relative" } },
2093
+ "压缩后保留最近使用的按需组",
2094
+ h("span", { className: "tm_help", tabIndex: 0, "aria-label": "压缩后保留说明", "data-tip": KEEP_AFTER_COMPACTION_HELP }, "?"),
2095
+ ),
2096
+ h("input", {
2097
+ className: "tm_input",
2098
+ style: { maxWidth: "120px", flex: "0 0 120px" },
2099
+ type: "text",
2100
+ inputMode: "numeric",
2101
+ "aria-label": "压缩后保留最近使用的按需组数量",
2102
+ value: typeof preset.policy.keepAfterCompaction === "number"
2103
+ ? String(preset.policy.keepAfterCompaction)
2104
+ : "",
2105
+ placeholder: "全部",
2106
+ disabled: autoGrouping,
2107
+ title: "留空=全部保留;0=压缩后全部关闭;N=只保留最近使用的 N 个",
2108
+ onChange: (event) => setCompactionKeep(event.target.value),
2109
+ }),
2110
+ h("span", { className: "tm_muted" }, "留空=全部保留"),
1372
2111
  ),
1373
2112
  preset.broken ? h("div", { className: "tm_error" }, preset.broken) : null,
1374
2113
  autoGroupError ? h("div", { className: "tm_error" }, autoGroupError) : null,
2114
+ aiNotice ? h("div", { className: "tm_notice" }, aiNotice) : null,
1375
2115
  h("section", { className: "tm_panel" },
1376
2116
  h("div", { className: "tm_panel_head" },
1377
2117
  h("div", null,
1378
2118
  h("b", null, "工具目录", h("span", { className: "tm_help", tabIndex: 0, "aria-label": "工具目录说明", "data-tip": toolCatalogHelp(mcpMode) }, "?")),
1379
2119
  ),
1380
2120
  h("div", { className: "tm_row" },
1381
- h("button", { className: "tm_btn", onClick: startAutoGroup, disabled: autoGrouping || autoGroupCandidates.length === 0, title: autoGroupCandidates.length ? "用默认模型对未分组且未关闭的工具进行聚类" : "没有可自动分组的工具" }, autoGrouping ? "自动分组中…" : "自动分组"),
2121
+ h("button", { className: "tm_btn", onClick: startAutoGroup, disabled: autoGrouping || autoGroupCandidates.length === 0, title: autoGroupCandidates.length ? "用" + generationLabel + "对未分组且未关闭的工具进行聚类" : "没有可自动分组的工具" }, autoGrouping ? "自动分组中…" : "自动分组"),
1382
2122
  h("button", { className: "tm_btn", onClick: openCreate, disabled: autoGrouping }, "手动分组"),
1383
2123
  h("button", {
1384
2124
  className: "tm_btn",
1385
2125
  onClick: resetPresetConfig,
1386
2126
  disabled: autoGrouping || busy || !draft.writable || !hasPresetConfig,
1387
2127
  title: hasPresetConfig
1388
- ? "清空当前 Preset 的全部按需组和已关闭工具"
2128
+ ? "清空当前 Preset 的全部组和已关闭工具(加载模式与压缩后保留保持不变)"
1389
2129
  : "当前 Preset 没有可重置的配置",
1390
2130
  }, "重置配置"),
1391
2131
  h("button", {
@@ -1393,7 +2133,7 @@ window.__ModuleLoader__.load({
1393
2133
  onClick: openCopyDialog,
1394
2134
  disabled: autoGrouping || busy || !draft.writable || !hasPresetConfig || copyTargetCount === 0,
1395
2135
  title: hasPresetConfig
1396
- ? "把当前 Preset 的分组和已关闭工具复制到其他 Preset"
2136
+ ? "把当前 Preset 的分组和已关闭工具复制到其他 Preset(加载模式不复制;压缩后保留会复制)"
1397
2137
  : "当前 Preset 没有可复制的分组或已关闭工具",
1398
2138
  }, "复制配置"),
1399
2139
  ),
@@ -1401,8 +2141,8 @@ window.__ModuleLoader__.load({
1401
2141
  h("div", { className: "tm_stats" },
1402
2142
  [
1403
2143
  ["工具总量", stats.totalTools, formatTokenAmount(tokenStats.totalTokens) + " tok", "全部 " + stats.totalTools + " 个工具合计 " + formatTokenAmount(tokenStats.totalTokens) + " tok/轮(" + unitNote + (isPtc ? ",含平台常数 " + formatTokenAmount(constantTokens) + " tok" : "") + ";全部常驻时)"],
1404
- ["分组数量", stats.groupCount, "省 " + formatTokenAmount(tokenStats.onDemandSavings) + " tok", "全部 " + tokenStats.onDemandGroups + " 个按需组收起:组内工具合计 " + formatTokenAmount(tokenStats.onDemandTokens) + " tok − 关闭态目录行 " + formatTokenAmount(onDemandCatalogTokens) + " tok = 净省 " + formatTokenAmount(tokenStats.onDemandSavings) + " tok/轮"],
1405
- ["未分组工具", stats.ungroupedTools, formatTokenAmount(tokenStats.alwaysOnTokens) + " tok", "未分组且未关闭的 " + tokenStats.alwaysOnTools + " 个工具每轮常驻 " + formatTokenAmount(tokenStats.alwaysOnTokens) + " tok"],
2144
+ ["分组数量", stats.groupCount, "省 " + formatTokenAmount(tokenStats.onDemandSavings) + " tok", "其中 " + tokenStats.onDemandGroups + " 个按需组收起:组内工具合计 " + formatTokenAmount(tokenStats.onDemandTokens) + " tok − 关闭态目录行 " + formatTokenAmount(onDemandCatalogTokens) + " tok = 净省 " + formatTokenAmount(tokenStats.onDemandSavings) + " tok/轮"],
2145
+ ["常驻工具", stats.ungroupedTools, formatTokenAmount(tokenStats.alwaysOnTokens) + " tok", "未分组或常驻组内且未关闭的 " + tokenStats.alwaysOnTools + " 个工具每轮常驻 " + formatTokenAmount(tokenStats.alwaysOnTokens) + " tok"],
1406
2146
  ["按需工具", stats.onDemandTools, formatTokenAmount(tokenStats.onDemandTokens) + " tok", "按需组内 " + tokenStats.onDemandTools + " 个工具合计 " + formatTokenAmount(tokenStats.onDemandTokens) + " tok;收起后仍会注入目录行 " + formatTokenAmount(onDemandCatalogTokens) + " tok,实际净省见「分组数量」卡"],
1407
2147
  ["已关闭工具", stats.disabledTools, formatTokenAmount(tokenStats.disabledTokens) + " tok", "已关闭的 " + tokenStats.disabledTools + " 个工具关闭可省 " + formatTokenAmount(tokenStats.disabledTokens) + " tok/轮"],
1408
2148
  ...(isPtc
@@ -1415,7 +2155,7 @@ window.__ModuleLoader__.load({
1415
2155
  h("div", { className: "tm_row", style: { padding: "10px 14px" } },
1416
2156
  h("input", { className: "tm_input", value: query, placeholder: "搜索工具名、描述或组名", onChange: (e) => setQuery(e.target.value) }),
1417
2157
  h("div", { className: "tm_filters" },
1418
- [["all", "全部"], ["live", "常开"], ["cold", "按需"], ["disabled", "已关闭"]].map(([id, label]) =>
2158
+ [["all", "全部"], ["live", "常驻"], ["cold", "按需"], ["disabled", "已关闭"]].map(([id, label]) =>
1419
2159
  h("button", { key: id, className: "tm_chip" + (filter === id ? " active" : ""), onClick: () => setFilter(id) }, label),
1420
2160
  ),
1421
2161
  ),
@@ -1458,6 +2198,19 @@ window.__ModuleLoader__.load({
1458
2198
  // Pure policy projection, exported for unit tests. DSH only consumes
1459
2199
  // apply/inject, so this does not widen the client plugin contract.
1460
2200
  exports.copyPresetPolicy = copyPresetPolicy;
2201
+ exports.resetPresetPolicy = resetPresetPolicy;
2202
+ // Generation-model projections, exported for unit tests: the persisted
2203
+ // payload, the picker's value codec, the effective selection the picker
2204
+ // shows, and the label the dialogs print.
2205
+ exports.settingsPayload = settingsPayload;
2206
+ exports.generationPayload = generationPayload;
2207
+ exports.effectiveGenerationModel = effectiveGenerationModel;
2208
+ exports.isDefaultSelection = isDefaultSelection;
2209
+ exports.carryReasoningEffort = carryReasoningEffort;
2210
+ exports.generationModelValue = generationModelValue;
2211
+ exports.parseGenerationModelValue = parseGenerationModelValue;
2212
+ exports.generationTargetLabel = generationTargetLabel;
2213
+ exports.findModelEntry = findModelEntry;
1461
2214
  // Save-guard projections, exported for unit tests. The button's disabled
1462
2215
  // state and the error banner both used to hide which Preset or which
1463
2216
  // condition was involved; these make that answerable without a DOM.