dsh-prompt-customizer 0.2.7 → 0.3.1

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.
@@ -1,5 +1,5 @@
1
- /** Pure preset / section helpers shared by the client UI and the node tests. */
2
- import type { Config, Inventory, Preset, PresetData } from './types.ts'
1
+ /** 纯函数的预设 / 段操作助手,同时被客户端 UI 与 Node 测试复用(不触碰 IO 与 React)。 */
2
+ import type { Config, Inventory, OverrideData, Phase, PhaseViewKey, Preset, PresetData, ToolsConfig } from './types.ts'
3
3
 
4
4
  export interface Section {
5
5
  name: string
@@ -7,26 +7,80 @@ export interface Section {
7
7
  text?: string
8
8
  active: boolean
9
9
  replaced: boolean
10
- /** `system` = read from the host prompt inventory (not deletable); `custom` = added by this plugin (deletable). */
10
+ /** `system` = 读自宿主提示词清单(不可删除);`custom` = 本插件注入(可删除)。 */
11
11
  source?: 'system' | 'custom'
12
12
  }
13
13
 
14
- /** The config fields a preset apply must write back to the settings scope. */
14
+ /** 应用预设后需要回写到设置作用域的那部分配置字段。
15
+ * 阶段名单为可选:旧快照不带 → 应用时保留当前值,绝不抹掉。 */
15
16
  export interface ConfigPatch {
16
17
  sections: string[]
18
+ sectionsBootstrap?: string[]
19
+ sectionsCompaction?: string[]
17
20
  replace: Record<string, string>
18
- inject: Array<{ name: string; order: number; text: string }>
19
- tools: { exclude: string[]; include: string[] }
21
+ inject: ResolvedInject[]
22
+ tools: ToolsConfig
23
+ }
24
+
25
+ /** 快照捕获的阶段 order 空间(always 之外的三个阶段)。 */
26
+ const CAPTURE_PHASES: Array<'bootstrap' | 'active' | 'compaction'> = ['bootstrap', 'active', 'compaction']
27
+
28
+ /** 把一条有序名字转成相对链(每段记住它的前一段),text / custom 只给 custom 段。 */
29
+ function toChain(names: string[], textOf: (name: string) => string, customOf: (name: string) => boolean, phase?: Phase): NonNullable<PresetData['order']> {
30
+ return names.map((name, i) => ({
31
+ name,
32
+ after: i > 0 ? names[i - 1] : undefined,
33
+ text: customOf(name) ? (textOf(name) ?? '') : '',
34
+ custom: customOf(name),
35
+ ...(phase !== undefined ? { phase } : {}),
36
+ }))
37
+ }
38
+
39
+ /**
40
+ * 从当前配置构建预设快照(完整捕获,含每阶段独立设定)。
41
+ *
42
+ * 全局相对链派生自合并后的完整段列表(而不仅是 `cfg.inject`),这样即使保存前
43
+ * 只是屏蔽了几个段(没有重排),预设仍会携带完整的有序集合,应用时才能得到一个
44
+ * 有意义的「激活列表」。在此之上,bootstrap / active / compaction 各再带一条自己
45
+ * 的相对链 —— 数据源就是 UI 逐阶段持久化的注入条目(每阶段独立的 order 空间),
46
+ * 否则阶段化的名单与排序在「导出 → 导入 → 应用」后就丢了。
47
+ */
48
+ export function buildPresetData(cfg: Config, merged: Section[]): PresetData {
49
+ const globalNames = merged.map((sec) => sec.name)
50
+ const textOf = new Map(merged.map((sec) => [sec.name, sec.text ?? ''] as const))
51
+ const customOf = new Map(merged.map((sec) => [sec.name, sec.source === 'custom'] as const))
52
+ const order = toChain(globalNames, (n) => textOf.get(n) ?? '', (n) => customOf.get(n) === true)
53
+ for (const phase of CAPTURE_PHASES) {
54
+ const items = (cfg.inject ?? [])
55
+ .filter((item) => item.phase === phase)
56
+ .sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
57
+ if (items.length === 0) continue
58
+ order.push(...toChain(
59
+ items.map((item) => item.name),
60
+ (n) => items.find((item) => item.name === n)?.text ?? '',
61
+ (n) => items.find((item) => item.name === n)?.custom === true,
62
+ phase,
63
+ ))
64
+ }
65
+ const data: PresetData = {
66
+ sections: cfg.sections,
67
+ replace: cfg.replace,
68
+ order,
69
+ tools: cfg.tools,
70
+ }
71
+ // 非空才捕获:没有阶段名单的配置导出的快照与改动前逐键一致。
72
+ if ((cfg.sectionsBootstrap ?? []).length > 0) data.sectionsBootstrap = cfg.sectionsBootstrap
73
+ if ((cfg.sectionsCompaction ?? []).length > 0) data.sectionsCompaction = cfg.sectionsCompaction
74
+ return data
20
75
  }
21
76
 
22
77
  /**
23
- * Merge the inventory sections with the user's inject list, sorted by order.
24
- * Sections read from the inventory (other plugins) are `system`; sections this
25
- * plugin generated carry a hidden `custom` marker and are `custom`. The source
26
- * is decided by the hidden marker — never by name collisions — so a custom
27
- * section keeps its identity (and its deletability) even when its name happens
28
- * to match an inventory section, and across preset switches. Custom sections
29
- * always render their own text; they can never be "<动态生成>".
78
+ * 把宿主清单段与用户注入列表按 order 合并、排序。
79
+ * 读自清单(其他插件产出)的段标记为 `system`;本插件生成的段带隐藏的
80
+ * `custom` 标记,标记为 `custom`。来源只由隐藏标记决定——绝不靠名字碰撞
81
+ * 判断——因此即使自定义段恰好与某个清单段重名,它也能保住自己的身份
82
+ * (以及可删除性),并在切换预设后依然成立。自定义段始终渲染自己的文本,
83
+ * 永远不会显示为「<动态生成>」。
30
84
  */
31
85
  export function mergeSections(inv: Inventory | null, cfg: Config, blockedNames: ReadonlySet<string>): Section[] {
32
86
  const map = new Map<string, Section>()
@@ -49,25 +103,26 @@ export function mergeSections(inv: Inventory | null, cfg: Config, blockedNames:
49
103
  })
50
104
  }
51
105
  }
52
- return [...map.values()].sort((a, b) => a.order - b.order)
106
+ return [...map.values()].sort((a, b) => a.order - b.order).map((sec, i) => ({ ...sec, order: i }))
107
+ }
108
+
109
+ /** ConfigPatch 里对外的注入条目(always 组刻意不带 phase 键)。 */
110
+ export interface ResolvedInject {
111
+ name: string
112
+ order: number
113
+ text: string
114
+ custom?: boolean
115
+ phase?: Phase
53
116
  }
54
117
 
55
118
  /**
56
- * Resolve a preset's relative order into an absolute ordered list (0..n-1).
57
- * Sections with no anchor (or whose anchor is absent) come first in preset
58
- * order; each anchored section is inserted right after its anchor; any
59
- * remaining sections (cycles) are appended.
119
+ * 把一条相对链解析为绝对有序名字(0..n-1)。
120
+ * 没有锚点(或锚点不在本组内)的名字按原始顺序排在最前;每个带锚点的名字
121
+ * 插到其锚点之后;剩余的名字(存在环)追加到末尾。
60
122
  */
61
- export function resolveOrder(presetOrder: PresetData['order']): Array<{ name: string; order: number; text: string; custom?: boolean }> {
62
- const list = presetOrder ?? []
123
+ function resolveChain(list: Array<{ name: string; after?: string }>): string[] {
63
124
  const afterMap = new Map<string, string | undefined>()
64
- const textMap = new Map<string, string>()
65
- const customMap = new Map<string, boolean>()
66
- for (const sec of list) {
67
- afterMap.set(sec.name, sec.after)
68
- textMap.set(sec.name, sec.text)
69
- customMap.set(sec.name, sec.custom === true)
70
- }
125
+ for (const sec of list) afterMap.set(sec.name, sec.after)
71
126
 
72
127
  const result: string[] = []
73
128
  const placed = new Set<string>()
@@ -94,59 +149,60 @@ export function resolveOrder(presetOrder: PresetData['order']): Array<{ name: st
94
149
  for (const sec of list) {
95
150
  if (!placed.has(sec.name)) { result.push(sec.name); placed.add(sec.name) }
96
151
  }
97
-
98
- return result.map((name, i) => ({ name, order: i, text: textMap.get(name) ?? '', custom: customMap.get(name) }))
152
+ return result
99
153
  }
100
154
 
101
155
  /**
102
- * Build a preset snapshot from the current config. The order list is derived
103
- * from the MERGED section list (not just `cfg.inject`) so that a preset saved
104
- * after only blocking sections (without reordering) still carries the full
105
- * ordered set, and thus a meaningful "active list" when applied.
156
+ * 把快照里的相对顺序解析为注入条目列表。
157
+ *
158
+ * order 条目可以带 `phase`:同名而不同 phase 的多条 = 该段在多个阶段各有自己的
159
+ * 位置(每阶段有独立的 order 空间,与 UI 的 phaseInjectEntries 一致)。无 phase
160
+ * 的条目属于 always 组 —— 也就是旧快照的单一全局序,输出形状与旧实现逐键一致
161
+ * (刻意不写 phase 键,「保存 → 应用 = 不动点」的不变量依赖键形状完全相同)。
106
162
  */
107
- export function buildPresetData(cfg: Config, merged: Section[]): PresetData {
108
- // Only custom (plugin-added) sections carry their own text into the preset's
109
- // order list. System sections keep an empty text so applying the preset only
110
- // reorders them and never freezes their dynamically generated content.
111
- const order = merged.map((sec, i) => ({
112
- name: sec.name,
113
- after: i > 0 ? merged[i - 1].name : undefined,
114
- text: sec.source === 'custom' ? (sec.text ?? '') : '',
115
- custom: sec.source === 'custom',
116
- }))
117
- return {
118
- sections: cfg.sections,
119
- replace: cfg.replace,
120
- order,
121
- tools: cfg.tools,
163
+ export function resolveOrder(presetOrder: PresetData['order']): ResolvedInject[] {
164
+ const list = presetOrder ?? []
165
+ const groups = new Map<Phase, NonNullable<PresetData['order']>>([['always', []]])
166
+ for (const sec of list) {
167
+ const phase = sec.phase ?? 'always'
168
+ const group = groups.get(phase)
169
+ if (group) group.push(sec)
170
+ else groups.set(phase, [sec])
122
171
  }
172
+ const out: ResolvedInject[] = []
173
+ for (const [phase, members] of groups) {
174
+ const textMap = new Map(members.map((x) => [x.name, x.text ?? '']))
175
+ const customMap = new Map(members.map((x) => [x.name, x.custom === true]))
176
+ const names = resolveChain(members)
177
+ out.push(...names.map((name, i) => (phase === 'always'
178
+ ? { name, order: i, text: textMap.get(name) ?? '', custom: customMap.get(name) }
179
+ : { name, order: i, text: textMap.get(name) ?? '', custom: customMap.get(name), phase })))
180
+ }
181
+ return out
123
182
  }
124
183
 
125
184
  /**
126
- * Compute the config patch when applying a preset:
127
- * - same-name sections are overridden (the order list drives this at runtime)
128
- * - preset sections missing from the current prompt are added
129
- * - current sections NOT in the preset's ordered list are disabled by default
130
- * - only the preset's ACTIVE sections (in the order list but not in its block
131
- * list) are unblocked; the preset's own blocked sections stay blocked.
185
+ * 计算应用预设时的配置补丁:
186
+ * - 同名段被覆盖(顺序列表在运行时驱动这一行为)
187
+ * - 预设中有、当前提示词中没有的段被添加
188
+ * - 当前有、但不在预设有序列表中的段默认被屏蔽
189
+ * - 只有预设的「激活段」(在 order 列表且不在其屏蔽名单中)被解除屏蔽;
190
+ * 预设自己屏蔽的段保持屏蔽。
132
191
  *
133
- * Custom injected sections that exist in the current config but are NOT in the
134
- * preset's ordered list are preserved in the resulting inject list (so they
135
- * stay visible) and disabled (added to the blocked set), rather than silently
136
- * dropped — a preset must not make the user's own injected sections vanish.
192
+ * 当前配置里存在、但不在预设有序列表中的自定义注入段会被保留到结果的
193
+ * inject 列表中(因此仍然可见)并置为禁用(加入屏蔽集合),而不是被静默
194
+ * 丢弃——预设不能让用户自己注入的凭空消失。
137
195
  */
138
196
  export function applyPresetData(data: PresetData, cfg: Config, currentNames: ReadonlySet<string>): ConfigPatch {
139
197
  const presetOrder = data.order ?? []
140
198
  const presetNames = new Set(presetOrder.map((x) => x.name))
141
199
  const blocked = new Set(data.sections ?? [])
142
200
 
143
- // Inject list = the preset's resolved order, then any custom injected
144
- // sections present in the current config but absent from the preset list.
145
- // Keeping them in `inject` makes them visible; they are disabled below.
146
- // Kept customs continue after the preset's own indexes; if the preset covers
147
- // only a small subset they may tie with the inventory's native orders — the
148
- // merge view sorts stably (inventory first), so ordering stays deterministic,
149
- // and the next reorder/persist re-indexes everything contiguously anyway.
201
+ // 注入列表 = 预设解析出的顺序,再追加当前配置中存在、但预设列表没有的
202
+ // 自定义注入段。让它们留在 `inject` 里才能保持可见;随后统一置为禁用。
203
+ // 被保留的自定义段接在预设自身的下标之后;若预设只覆盖一小部分段,它们
204
+ // 可能与清单原生 order 并列——合并视图按稳定排序(清单在前),顺序仍是
205
+ // 确定性的,且下一次重排/持久化会把所有下标重新连续化。
150
206
  const inject = resolveOrder(presetOrder)
151
207
  const kept = new Set(inject.map((x) => x.name))
152
208
  let order = inject.length
@@ -156,30 +212,42 @@ export function applyPresetData(data: PresetData, cfg: Config, currentNames: Rea
156
212
  inject.push({ name: item.name, order: order++, text: item.text ?? '', custom: item.custom === true })
157
213
  }
158
214
 
159
- // Only enforce the "active set" when the preset actually defines an order.
160
- // An empty order (e.g. a hand-authored / imported preset that only blocks a
161
- // few sections) must not default-disable every current section.
215
+ // 仅当预设确实定义了 order 列表时才强制执行「激活集合」。
216
+ // 空的 order(例如手工编写 / 只屏蔽了几个段的导入预设)绝不能把当前所有
217
+ // 段默认禁用。
162
218
  if (presetOrder.length > 0) {
163
219
  const activeNames = new Set([...presetNames].filter((n) => !blocked.has(n)))
164
220
  for (const name of currentNames) if (!presetNames.has(name)) blocked.add(name)
165
221
  for (const name of activeNames) blocked.delete(name)
166
222
  }
167
223
 
168
- return {
224
+ // 阶段化字段一律「快照有则覆盖,缺省则保留当前值」:旧快照(没有这些键)
225
+ // 应用后仍只换静态过滤,绝不把用户已有的阶段目录与阶段名单抹平。
226
+ // 缺席时不留下显式 undefined 键 —— 「保存→应用 = 不动点」的不变量依赖键形状。
227
+ const keptCatalogs: ToolsConfig = {}
228
+ const bootstrap = data.tools?.bootstrap !== undefined ? data.tools.bootstrap : cfg.tools?.bootstrap
229
+ const compaction = data.tools?.compaction !== undefined ? data.tools.compaction : cfg.tools?.compaction
230
+ if (bootstrap !== undefined) keptCatalogs.bootstrap = bootstrap
231
+ if (compaction !== undefined) keptCatalogs.compaction = compaction
232
+ const patch: ConfigPatch = {
169
233
  sections: [...blocked],
170
234
  replace: { ...(cfg.replace ?? {}), ...(data.replace ?? {}) },
171
235
  inject,
172
- tools: { exclude: data.tools?.exclude ?? [], include: data.tools?.include ?? [] },
236
+ tools: {
237
+ exclude: data.tools?.exclude ?? [],
238
+ ...keptCatalogs,
239
+ },
173
240
  }
241
+ if (Array.isArray(data.sectionsBootstrap)) patch.sectionsBootstrap = data.sectionsBootstrap
242
+ if (Array.isArray(data.sectionsCompaction)) patch.sectionsCompaction = data.sectionsCompaction
243
+ return patch
174
244
  }
175
245
 
176
246
  /**
177
- * Remove a custom (plugin-added) section from the config: it disappears from
178
- * the inject list, is no longer forced into the blocked set, and any replace
179
- * text for it is cleared. The remaining inject entries are re-indexed to a
180
- * contiguous 0..n-1 order (the virtual index model), so removal never leaves
181
- * holes. System sections read from the host inventory cannot be removed this
182
- * way (they would just come back on the next inventory read).
247
+ * 从配置中移除一个 custom(本插件注入)段:它从 inject 列表消失,不再被
248
+ * 强制加入屏蔽集合,相关的替换文本也被清除。剩余的 inject 条目会被重新
249
+ * 编号为连续的 0..n-1(虚拟下标模型),删除不会留下空洞。读自宿主清单的
250
+ * system 段无法这样移除(下次读取清单时它们又会回来)。
183
251
  */
184
252
  export function removeSection(name: string, cfg: Config): Pick<Config, 'sections' | 'inject' | 'replace'> {
185
253
  const sections = (cfg.sections ?? []).filter((n) => n !== name)
@@ -191,64 +259,131 @@ export function removeSection(name: string, cfg: Config): Pick<Config, 'sections
191
259
  return { sections, inject, replace }
192
260
  }
193
261
 
194
- // ── Tool filtering ──────────────────────────────────────────────────────────
262
+ // ── 工具过滤 ─────────────────────────────────────────────────────────────
263
+
264
+ export type ToolsCfg = { exclude?: string[] }
265
+
266
+ /** 三个阶段部分的固定展示顺序:引导期 → 常驻期 → 压缩受控期。
267
+ * 恒定全部渲染 —— 预设没有某个阶段时该部分只是空的,绝不隐藏。 */
268
+ export const PART_ORDER: PhaseViewKey[] = ['bootstrap', 'active', 'compaction']
269
+
270
+ /**
271
+ * 一个阶段部分写回哪一份过滤配置:引导期 → `tools.bootstrap`、压缩受控期 →
272
+ * `tools.compaction`、常驻期 → 静态 `tools.exclude`。三份名单互不继承。
273
+ */
274
+ export function phaseConfigKey(key: PhaseViewKey): 'bootstrap' | 'compaction' | 'static' {
275
+ return key === 'active' ? 'static' : key
276
+ }
277
+
278
+ /**
279
+ * 把一个阶段的 exclude 名单写回整份工具配置,返回新对象(其余阶段原样保留)。
280
+ * 一次拖放可能要同时改两个阶段的名单(搬移 = 源阶段隐藏 + 目标阶段显示),必须
281
+ * 在同一个对象上连续套完再落一次写入 —— 分两次写会各自基于旧 cfg 计算而互相覆盖。
282
+ */
283
+ export function withPhaseExclude(tools: ToolsConfig | undefined, key: PhaseViewKey, exclude: string[]): ToolsConfig {
284
+ const base = tools ?? {}
285
+ const target = phaseConfigKey(key)
286
+ if (target === 'bootstrap') return { ...base, bootstrap: { ...(base.bootstrap ?? {}), exclude } }
287
+ if (target === 'compaction') return { ...base, compaction: { ...(base.compaction ?? {}), exclude } }
288
+ return { ...base, exclude }
289
+ }
195
290
 
196
- export type ToolsCfg = { exclude?: string[]; include?: string[] }
291
+ /**
292
+ * 把一个阶段的 add 名单(要加回该阶段的工具)写回整份工具配置,返回新对象。
293
+ * 与 withPhaseExclude 对称:常驻期写静态 `tools.add`,引导期写 `tools.bootstrap.add`,
294
+ * 压缩受控期写 `tools.compaction.add`,其余阶段原样保留。
295
+ */
296
+ export function withPhaseAdd(tools: ToolsConfig | undefined, key: PhaseViewKey, add: string[]): ToolsConfig {
297
+ const base = tools ?? {}
298
+ const target = phaseConfigKey(key)
299
+ if (target === 'bootstrap') return { ...base, bootstrap: { ...(base.bootstrap ?? {}), add } }
300
+ if (target === 'compaction') return { ...base, compaction: { ...(base.compaction ?? {}), add } }
301
+ return { ...base, add }
302
+ }
197
303
 
198
- /** Whether a tool is hidden under the current include/exclude config. */
304
+ /** 某个工具在当前黑名单配置下是否被隐藏。 */
199
305
  export function isToolHidden(name: string, toolsCfg: ToolsCfg | undefined): boolean {
200
- const include = toolsCfg?.include ?? []
201
- const exclude = toolsCfg?.exclude ?? []
202
- return include.length > 0 ? !include.includes(name) : exclude.includes(name)
306
+ return (toolsCfg?.exclude ?? []).includes(name)
203
307
  }
204
308
 
205
- /** Toggle a tool's hidden state, returning a new tools config. */
309
+ /** 切换某个工具的隐藏状态,返回新的工具配置(不改原对象)。 */
206
310
  export function toggleTool(name: string, currentlyHidden: boolean, toolsCfg: ToolsCfg | undefined): ToolsCfg {
207
- const include = toolsCfg?.include ?? []
208
- const exclude = toolsCfg?.exclude ?? []
209
- if (include.length > 0) {
210
- const next = include.slice()
211
- if (currentlyHidden) {
212
- next.push(name)
213
- // Re-showing a tool in whitelist mode must also clear any stale blacklist
214
- // entry, otherwise the name lingers in both lists and reappears as hidden
215
- // if the user later switches back to blacklist mode.
216
- const nextExclude = exclude.filter((n) => n !== name)
217
- return { exclude: nextExclude, include: next }
218
- }
219
- const i = next.indexOf(name)
220
- if (i >= 0) next.splice(i, 1)
221
- return { exclude, include: next }
311
+ const exclude = (toolsCfg?.exclude ?? []).slice()
312
+ if (currentlyHidden) { const i = exclude.indexOf(name); if (i >= 0) exclude.splice(i, 1) }
313
+ else if (!exclude.includes(name)) exclude.push(name)
314
+ return { exclude }
315
+ }
316
+
317
+ // ── 按 agent 预设的覆盖编辑 ─────────────────────────────────────────────
318
+
319
+ /**
320
+ * 编辑目标的「显示视图」:全局目标返回原配置;agent 预设目标把该预设
321
+ * override 的字段叠在全局值之上展示(空缺字段显示全局继承值)。`presets`
322
+ * 与 `activePreset` 永远来自全局 —— 预设快照库本身不分作用域。
323
+ */
324
+ export function editView(cfg: Config, target: string | undefined): Config {
325
+ if (!target) return cfg
326
+ const ovr = cfg.overrides?.[target] ?? {}
327
+ return {
328
+ sections: ovr.sections ?? cfg.sections,
329
+ sectionsBootstrap: ovr.sectionsBootstrap ?? cfg.sectionsBootstrap,
330
+ sectionsCompaction: ovr.sectionsCompaction ?? cfg.sectionsCompaction,
331
+ replace: ovr.replace ?? cfg.replace,
332
+ inject: ovr.inject ?? cfg.inject,
333
+ tools: {
334
+ exclude: ovr.tools?.exclude ?? cfg.tools?.exclude,
335
+ add: ovr.tools?.add ?? cfg.tools?.add,
336
+ bootstrap: ovr.tools?.bootstrap ?? cfg.tools?.bootstrap,
337
+ compaction: ovr.tools?.compaction ?? cfg.tools?.compaction,
338
+ },
339
+ presets: cfg.presets,
340
+ activePreset: cfg.activePreset,
222
341
  }
223
- const next = exclude.slice()
224
- if (currentlyHidden) { const i = next.indexOf(name); if (i >= 0) next.splice(i, 1) }
225
- else next.push(name)
226
- return { exclude: next, include }
227
342
  }
228
343
 
229
344
  /**
230
- * Switch between include (whitelist) and exclude (blacklist) modes. Turning
231
- * include mode on discards names unknown to the current tool set and seeds the
232
- * include list from the currently non-excluded tools; turning it off clears the
233
- * include list (keep only known exclude names).
345
+ * 往某个 agent 预设的 override 里写入一个字段,返回新的 overrides 记录
346
+ * (不改原对象)。与 editView 配对:编辑视图里看到的继承值一旦被修改,
347
+ * 就整体落成该预设自己的字段(字段级接管语义)。
234
348
  */
235
- export function setToolMode(on: boolean, toolsCfg: ToolsCfg | undefined, toolNames: string[]): ToolsCfg {
236
- const known = new Set(toolNames)
237
- const exclude = (toolsCfg?.exclude ?? []).filter((n) => known.has(n))
238
- if (on) return { exclude, include: toolNames.filter((n) => !exclude.includes(n)) }
239
- return { exclude, include: [] }
349
+ export function setOverrideField(
350
+ cfg: Config,
351
+ target: string,
352
+ field: 'sections' | 'replace' | 'inject' | 'tools',
353
+ value: unknown,
354
+ ): Record<string, OverrideData> {
355
+ return {
356
+ ...(cfg.overrides ?? {}),
357
+ [target]: { ...(cfg.overrides?.[target] ?? {}), [field]: value },
358
+ }
240
359
  }
241
360
 
242
- // ── Preset list operations ──────────────────────────────────────────────────
361
+ // ── 预设列表操作 ──────────────────────────────────────────────────────────
243
362
 
244
- /** Serialize a preset for export (JSON-safe full snapshot). */
363
+ /** 序列化预设用于导出(JSON 安全的完整快照)。 */
245
364
  export function serializePreset(preset: Preset): { name: string; data: PresetData } {
246
365
  return { name: preset.name, data: preset.data }
247
366
  }
248
367
 
249
368
  /**
250
- * Import preset(s): same-name presets are skipped, only distinct names are
251
- * added. Returns a new presets list (or the original if nothing changed).
369
+ * Derive a safe default filename for a preset export. User-entered preset
370
+ * names may contain characters that are illegal in filenames (`/\:*?"<>|`,
371
+ * control chars) — those are replaced; a trailing dot/space is trimmed
372
+ * (invalid on Windows); an empty or all-illegal result falls back to
373
+ * `preset`.
374
+ */
375
+ export function presetExportFilename(name: string): string {
376
+ const sanitized = String(name)
377
+ .replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_')
378
+ .trim()
379
+ .replace(/[. ]+$/, '')
380
+ const base = sanitized === '' ? 'preset' : sanitized
381
+ return `${base}.json`
382
+ }
383
+
384
+ /**
385
+ * 导入预设:同名的会被跳过,只追加名字不同的预设。返回新的预设列表
386
+ * (若没有任何变更则返回原列表)。
252
387
  */
253
388
  export function addImportedPresets(existing: Preset[], parsed: unknown, makeId: () => string): Preset[] {
254
389
  const incoming = Array.isArray(parsed) ? parsed : [parsed]
@@ -259,10 +394,15 @@ export function addImportedPresets(existing: Preset[], parsed: unknown, makeId:
259
394
  return added.length > 0 ? [...existing, ...added] : existing
260
395
  }
261
396
 
262
- /** Delete a preset, clearing the active id if it pointed at the removed one. */
397
+ /** 删除某个预设;若它正是当前激活的预设,则同时清除 activeId。 */
263
398
  export function removePreset(presets: Preset[], id: string, activeId?: string): { presets: Preset[]; activeId?: string } {
264
399
  return {
265
400
  presets: presets.filter((p) => p.id !== id),
266
401
  activeId: activeId === id ? undefined : activeId,
267
402
  }
268
403
  }
404
+
405
+ /** 生成预设 id:时间戳 + 随机段(base36),够用且无需额外依赖。 */
406
+ export function genId(): string {
407
+ return 'p_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 7)
408
+ }
@@ -1,4 +1,4 @@
1
- /** Inline styles shared by the prompt-customizer panel components. */
1
+ /** 提示词定制面板各组件共享的内联样式(颜色走半透明灰,随宿主主题自然适配)。 */
2
2
  export const s = (() => {
3
3
  const flex = { display: 'flex', alignItems: 'center' }
4
4
  return {
@@ -35,7 +35,15 @@ export const s = (() => {
35
35
  editBox: { display: 'flex', flexDirection: 'column', gap: 6, marginTop: 4 },
36
36
  editInput: { padding: '6px', border: '1px solid rgba(128,128,128,.35)', borderRadius: 6, background: 'transparent', color: 'inherit', fontFamily: 'inherit', fontSize: 12, resize: 'vertical', width: '100%', boxSizing: 'border-box' },
37
37
  input: { padding: '4px 6px', border: '1px solid rgba(128,128,128,.35)', borderRadius: 6, background: 'transparent', color: 'inherit' },
38
+ // 原生下拉的弹出列表不吃继承色(浅色底 + 继承的浅色字会看不见):
39
+ // 用系统色对(Canvas/CanvasText)跟随宿主 color-scheme,深浅主题下都可读。
40
+ option: { backgroundColor: 'Canvas', color: 'CanvasText' },
38
41
  muted: { color: 'rgba(128,128,128,.75)', fontSize: 12 },
39
42
  error: { color: '#f85149', fontSize: 12, marginBottom: 6 },
43
+ noticeOk: { color: '#3fb950', fontSize: 12, marginBottom: 6 },
44
+ noticeWarn: { color: '#d29922', fontSize: 12, marginBottom: 6 },
45
+ groupTitle: { display: 'flex', gap: 8, alignItems: 'baseline', marginTop: 8, marginBottom: 2, color: 'rgba(128,128,128,.9)', fontSize: 12 },
46
+ saveBtn: { padding: '4px 12px', border: '1px solid rgba(128,128,128,.35)', borderRadius: 6, background: 'transparent', cursor: 'pointer', color: 'inherit' },
47
+ saveBtnDirty: { padding: '4px 12px', border: '1px solid #d29922', borderRadius: 6, background: 'rgba(210,153,34,.15)', cursor: 'pointer', color: 'inherit' },
40
48
  }
41
49
  })()